Files
openchamber/packages/ui/src/components/layout/ProjectActionsButton.tsx
T
Bohdan Triapitsyn a5aa32446d feat(browser): replace the preview proxy with a real browser panel and an agent web tool (#2883)
The preview panel worked by proxying a dev server through OpenChamber's own
origin and rewriting the HTML that came back. Anything the rewriter did not
anticipate broke, and pages that refuse to be embedded never loaded at all.
This deletes the proxy (-1604 lines and its tests) and merges the preview and
browser panels into one surface backed by a real Chromium view.

What the panel is now

- A `<webview>` in its own session partition: logins and cookies persist, hot
  reload works because nothing is rewritten, DevTools are one click away.
- Annotation: pick one element, drag a region, or draw freehand, write a note,
  and it reaches chat with a screenshot of the visible page with the marks on it.
- Toolbar: hard reload, page zoom, device sizes, a light/dark switch that
  applies to the page rather than the app, and cookie/cache clearing scoped to
  the panel alone.
- Several pages at once, each tab showing the page's own favicon, and an address
  bar that suggests pages already visited in this project.
- Dev servers are listed from what is actually listening on the machine, checked
  against what a project announced, so a server is offered no matter how it was
  started. One that is still starting is waited for instead of failing.

Remote dev servers

The desktop app binds a local port and pipes raw bytes to the OpenChamber host
over the existing authenticated connection, so the page keeps its own origin at
the root of its own host. The reachable set is exactly what discovery reports
and is re-checked per connection, so an authenticated client cannot dial
arbitrary local services on the host. Links and redirects to another loopback
port stay on the machine that served the page. A tunnel that cannot be opened is
reported; it is never replaced by the plain loopback URL, which would answer
from the user's own machine under a remote address.

Agent control

Browser actions are a separate `openchamber_web` tool: open, snapshot, click,
type, scroll, inspect computed styles, resize between mobile/tablet/desktop, and
capture a screenshot into `.openchamber/screenshots/` in the project. The
existing `openchamber` tool keeps sessions, worktrees and scheduled tasks. Each
has its own setting in the new Settings -> General -> OpenChamber Tools section,
and the plugin is not injected at all when both are off.

Capability belongs to the connected client, not to configuration: a client
declares on its event stream that it can drive a page, which only a Chromium
host does. Exactly one client performs each request — it claims the request
before acting, and the first claim wins — because deciding by whose result
arrives first would be too late for a click that already happened. No client
listening is answered immediately with an explanation rather than a timeout.

Runtime boundaries

Web tabs get a plain iframe that can display a page but not inspect one. The
VS Code extension no longer offers the surface at all, since nothing that makes
the panel worth having works there. Mobile is unaffected.

Native boundary

Camera, microphone, location and device-picker requests from panel pages are
denied — Electron grants them by default when no handler is set, and the panel
loads whatever address the user types. Page capture, appearance emulation and
storage clearing verify that their target belongs to the panel's own session
instead of trusting a web-contents id from the renderer.

Persisted state

Stored `preview` tabs migrate to `browser` (v13 -> v14). Context panel tab
limits are now per surface, so filling one surface no longer evicts another's
tabs. Address history is stored per project and per runtime.

Documentation

`preview.mdx` and `desktop-browser.mdx` rewritten across all locales, the agent
tool settings path corrected, new `DOCUMENTATION.md` for the browser-control
broker and the dev tunnel, and the `ui-api-decoupling` skill updated where it
still described the deleted proxy.
2026-08-13 22:44:13 +03:00

970 lines
39 KiB
TypeScript

import React from 'react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { toast } from '@/components/ui';
import { Icon } from "@/components/icon/Icon";
import { cn } from '@/lib/utils';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { useDeviceInfo } from '@/lib/device';
import { isDesktopShell } from '@/lib/desktop';
import { useUIStore } from '@/stores/useUIStore';
import { useTerminalStore } from '@/stores/useTerminalStore';
import { extractAnnouncedUrls, extractProjectActionUrl } from '@/lib/terminalPreview';
import { setAnnouncedDevServers } from '@/lib/browser/announcedServers';
import { useThemeSystem } from '@/contexts/useThemeSystem';
import { useDesktopSshStore } from '@/stores/useDesktopSshStore';
import { openExternalUrl } from '@/lib/url';
import { useI18n } from '@/lib/i18n';
import {
getProjectActionsState,
type OpenChamberProjectAction,
type ProjectRef,
} from '@/lib/openchamberConfig';
import {
normalizeProjectActionDirectory,
PROJECT_ACTIONS_UPDATED_EVENT,
PROJECT_ACTION_ICON_MAP,
resolveProjectActionDesktopForwardUrl,
toProjectActionRunKey,
} from '@/lib/projectActions';
import { detectDevServerCommand, readPackageJsonScripts } from '@/lib/detectDevServer';
import { waitForTerminalExit } from '@/lib/projectActionTerminal';
type UrlWatchEntry = {
lastSeenChunkId: number | null;
openedUrl: boolean;
tail: string;
openInPreview: boolean;
/** Addresses announced so far by an auto-discovery run, in announcement order. */
announced: string[];
/** Set once the panel is showing these candidates and wants later ones too. */
offering: boolean;
};
interface ProjectActionsButtonProps {
projectRef: ProjectRef | null;
directory: string;
className?: string;
compact?: boolean;
allowMobile?: boolean;
}
const AUTO_DISCOVER_ACTION_ID = '__openchamber_auto_discover_preview__';
const AUTO_DISCOVER_PREVIEW_WAIT_TIMEOUT_MS = 15_000;
/**
* How long to keep listening after the first server announces itself. A project
* that starts several at once staggers them by a second or two, and opening the
* first to speak would just be a race.
*/
const AUTO_DISCOVER_SETTLE_MS = 3_000;
const stripControlChars = (value: string): string => {
let next = '';
for (let index = 0; index < value.length; index += 1) {
const code = value.charCodeAt(index);
const isControl = (code >= 0 && code <= 8)
|| code === 11
|| code === 12
|| (code >= 14 && code <= 31)
|| code === 127;
if (!isControl) {
next += value[index];
}
}
return next;
};
const normalizeManualOpenUrl = (value: string | undefined): string | null => {
const raw = (value || '').trim();
if (!raw) {
return null;
}
const candidate = /^https?:\/\//i.test(raw) ? raw : `http://${raw}`;
try {
const parsed = new URL(candidate);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return null;
}
return parsed.toString();
} catch {
return null;
}
};
export const ProjectActionsButton = ({
projectRef,
directory,
className,
compact = false,
allowMobile = false,
}: ProjectActionsButtonProps) => {
const { t } = useI18n();
const { currentTheme } = useThemeSystem();
const { terminal, runtime } = useRuntimeAPIs();
const { isMobile } = useDeviceInfo();
const isDesktopShellApp = React.useMemo(() => isDesktopShell(), []);
const desktopSshInstances = useDesktopSshStore((state) => state.instances);
const loadDesktopSsh = useDesktopSshStore((state) => state.load);
const terminalShell = useUIStore((state) => state.terminalShell);
const terminalLoginShell = useUIStore((state) => state.terminalLoginShells.includes(state.terminalShell));
const setSettingsPage = useUIStore((state) => state.setSettingsPage);
const setSettingsDialogOpen = useUIStore((state) => state.setSettingsDialogOpen);
const setSettingsProjectsSelectedId = useUIStore((state) => state.setSettingsProjectsSelectedId);
const openContextPreview = useUIStore((state) => state.openContextPreview);
const ensureDirectory = useTerminalStore((state) => state.ensureDirectory);
const setTabLabel = useTerminalStore((state) => state.setTabLabel);
const setTabIconKey = useTerminalStore((state) => state.setTabIconKey);
const setActiveTab = useTerminalStore((state) => state.setActiveTab);
const setConnecting = useTerminalStore((state) => state.setConnecting);
const setTabSessionId = useTerminalStore((state) => state.setTabSessionId);
const setTabPreviewUrl = useTerminalStore((state) => state.setTabPreviewUrl);
const projectActionRuns = useTerminalStore((state) => state.projectActionRuns);
const setProjectActionRun = useTerminalStore((state) => state.setProjectActionRun);
const updateProjectActionRunStatus = useTerminalStore((state) => state.updateProjectActionRunStatus);
const removeProjectActionRun = useTerminalStore((state) => state.removeProjectActionRun);
const [actions, setActions] = React.useState<OpenChamberProjectAction[]>([]);
const [selectedActionId, setSelectedActionId] = React.useState<string | null>(null);
const [isLoading, setIsLoading] = React.useState(false);
const tabByKeyRef = React.useRef<Record<string, string>>({});
const urlWatchByRunKeyRef = React.useRef<Record<string, UrlWatchEntry>>({});
const streamCleanupByRunKeyRef = React.useRef<Record<string, () => void>>({});
const previewWaitTimeoutByRunKeyRef = React.useRef<Record<string, number>>({});
const startingRunKeysRef = React.useRef<Set<string>>(new Set());
const loadRequestIdRef = React.useRef(0);
const projectId = projectRef?.id ?? null;
const projectPath = projectRef?.path ?? '';
const stableProjectRef = React.useMemo(() => {
if (!projectId) {
return null;
}
return { id: projectId, path: projectPath };
}, [projectId, projectPath]);
React.useEffect(() => {
if (!isDesktopShellApp) {
return;
}
void loadDesktopSsh().catch(() => undefined);
}, [isDesktopShellApp, loadDesktopSsh]);
const openExternal = React.useCallback(async (url: string) => {
await openExternalUrl(url);
}, []);
const loadActions = React.useCallback(async () => {
if (!stableProjectRef) {
return;
}
const requestId = loadRequestIdRef.current + 1;
loadRequestIdRef.current = requestId;
setIsLoading(true);
try {
const state = await getProjectActionsState(stableProjectRef);
if (loadRequestIdRef.current !== requestId) {
return;
}
const filtered = state.actions;
setActions(filtered);
setSelectedActionId((current) => {
if (current === AUTO_DISCOVER_ACTION_ID) {
return current;
}
if (current && filtered.some((entry) => entry.id === current)) {
return current;
}
return null;
});
} catch {
if (loadRequestIdRef.current !== requestId) {
return;
}
// Keep last known actions while next project loads or transient fetch fails.
} finally {
if (loadRequestIdRef.current === requestId) {
setIsLoading(false);
}
}
}, [stableProjectRef]);
const normalizedDirectory = React.useMemo(() => {
return normalizeProjectActionDirectory(directory || stableProjectRef?.path || '');
}, [directory, stableProjectRef?.path]);
const selectedAction = React.useMemo(() => {
if (!selectedActionId) {
return null;
}
return actions.find((entry) => entry.id === selectedActionId) ?? null;
}, [actions, selectedActionId]);
const autoDiscoverAction = React.useMemo<OpenChamberProjectAction>(() => ({
id: AUTO_DISCOVER_ACTION_ID,
name: t('projectActions.actions.autoDiscover'),
command: '',
icon: 'scan-2',
autoOpenUrl: true,
}), [t]);
const canUseAutoDiscover = !isMobile;
const displayActions = React.useMemo(
() => canUseAutoDiscover ? [autoDiscoverAction, ...actions] : actions,
[actions, autoDiscoverAction, canUseAutoDiscover]
);
React.useEffect(() => {
void loadActions();
}, [loadActions]);
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const handler = (event: Event) => {
const detail = (event as CustomEvent<{ projectId?: string }>).detail;
if (!projectId) {
return;
}
if (detail?.projectId && detail.projectId !== projectId) {
return;
}
void loadActions();
};
window.addEventListener(PROJECT_ACTIONS_UPDATED_EVENT, handler);
return () => {
window.removeEventListener(PROJECT_ACTIONS_UPDATED_EVENT, handler);
};
}, [loadActions, projectId]);
React.useEffect(() => {
if (!selectedActionId) {
return;
}
if (selectedActionId === AUTO_DISCOVER_ACTION_ID && canUseAutoDiscover) {
return;
}
if (!actions.some((entry) => entry.id === selectedActionId)) {
setSelectedActionId(null);
}
}, [actions, canUseAutoDiscover, selectedActionId]);
React.useEffect(() => {
/**
* Decides what an auto-discovery run found, once its servers have had a
* moment to announce themselves. One address is opened; several are offered
* in the browser panel, because choosing between them would be a guess
* dressed up as a feature.
*/
const settleAutoDiscovery = (runKey: string) => {
delete previewWaitTimeoutByRunKeyRef.current[runKey];
const watch = urlWatchByRunKeyRef.current[runKey];
if (!watch || watch.openedUrl) return;
const store = useTerminalStore.getState();
const run = store.projectActionRuns[runKey];
if (!run) return;
const candidates = watch.announced;
if (candidates.length === 0) return;
watch.openedUrl = true;
store.updateProjectActionRunStatus(runKey, 'running');
if (candidates.length === 1) {
setAnnouncedDevServers(run.directory, []);
setTabPreviewUrl(run.directory, run.tabId, candidates[0], { locked: false, autoOpened: true });
openContextPreview(run.directory, candidates[0]);
return;
}
watch.offering = true;
setAnnouncedDevServers(run.directory, candidates);
useUIStore.getState().openContextSurface(run.directory, 'browser');
toast.info(t('projectActions.toast.multipleServers'));
};
const monitorRuns = () => {
const terminalStore = useTerminalStore.getState();
const terminalSessions = terminalStore.sessions;
const currentRuns = terminalStore.projectActionRuns;
for (const [runKey, entry] of Object.entries(currentRuns)) {
const directoryState = terminalSessions.get(entry.directory);
const tab = directoryState?.tabs.find((item) => item.id === entry.tabId);
if (!tab || tab.terminalSessionId !== entry.sessionId) {
removeProjectActionRun(runKey);
continue;
}
const watch = urlWatchByRunKeyRef.current[runKey] ?? { lastSeenChunkId: null, openedUrl: false, tail: '', openInPreview: false, announced: [], offering: false };
urlWatchByRunKeyRef.current[runKey] = watch;
const action = displayActions.find((item) => item.id === entry.actionId);
const bufferChunks = terminalStore.getBuffer(entry.directory, entry.tabId).chunks;
if (!action || bufferChunks.length === 0) continue;
const nextChunks = bufferChunks.filter((chunk) => watch.lastSeenChunkId === null || chunk.id > watch.lastSeenChunkId);
if (nextChunks.length === 0) continue;
const combined = nextChunks.map((chunk) => chunk.data).join('');
const textForScan = `${watch.tail}${combined}`;
// Auto-discovery inferred the command; it must not also infer the
// address. It collects what the servers announce and decides once they
// have had a moment to all speak up.
// Keep listening after the panel starts offering candidates: servers in
// one project can be seconds apart, and a list that froze at whoever was
// ready first would quietly omit the rest.
if (watch.openInPreview && (!watch.openedUrl || watch.offering)) {
const announced = extractAnnouncedUrls(textForScan);
const before = watch.announced.length;
for (const url of announced) {
if (!watch.announced.includes(url)) watch.announced.push(url);
}
const added = watch.announced.length - before;
if (watch.offering && added > 0) {
setAnnouncedDevServers(entry.directory, watch.announced);
} else if (!watch.openedUrl && before === 0 && watch.announced.length > 0) {
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[runKey]);
previewWaitTimeoutByRunKeyRef.current[runKey] = window.setTimeout(
() => settleAutoDiscovery(runKey),
AUTO_DISCOVER_SETTLE_MS,
);
}
}
const maybeUrl = !watch.openedUrl && action.autoOpenUrl === true && !watch.openInPreview
? extractProjectActionUrl(textForScan)
: null;
const lastChunkId = nextChunks[nextChunks.length - 1]?.id ?? watch.lastSeenChunkId;
watch.lastSeenChunkId = lastChunkId;
watch.tail = textForScan.slice(-512);
if (maybeUrl) {
watch.openedUrl = true;
if (watch.openInPreview) {
const run = currentRuns[runKey];
if (run) {
setTabPreviewUrl(run.directory, run.tabId, maybeUrl, { locked: false, autoOpened: false });
if (run.status === 'waiting-for-preview') updateProjectActionRunStatus(runKey, 'running');
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[runKey]);
delete previewWaitTimeoutByRunKeyRef.current[runKey];
openContextPreview(run.directory, maybeUrl);
}
} else {
void openExternal(maybeUrl);
toast.success(t('projectActions.toast.openedUrlFromOutput'));
}
}
urlWatchByRunKeyRef.current[runKey] = watch;
}
for (const runKey of Object.keys(urlWatchByRunKeyRef.current)) {
if (!currentRuns[runKey]) {
delete urlWatchByRunKeyRef.current[runKey];
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[runKey]);
delete previewWaitTimeoutByRunKeyRef.current[runKey];
}
}
};
monitorRuns();
return useTerminalStore.subscribe((state, previousState) => {
if (state.sessions !== previousState.sessions || state.buffers !== previousState.buffers) monitorRuns();
});
}, [displayActions, openContextPreview, openExternal, projectActionRuns, removeProjectActionRun, setTabPreviewUrl, t, updateProjectActionRunStatus]);
const getOrCreateActionTab = React.useCallback(async (action: OpenChamberProjectAction, options: { revealTerminal?: boolean } = {}) => {
if (!normalizedDirectory) {
throw new Error(t('projectActions.error.noActiveDirectory'));
}
const key = toProjectActionRunKey(normalizedDirectory, action.id);
ensureDirectory(normalizedDirectory);
const currentStore = useTerminalStore.getState();
const existingDirectoryState = currentStore.getDirectoryState(normalizedDirectory);
let tabId = tabByKeyRef.current[key] || null;
const hasTab = tabId
? Boolean(existingDirectoryState?.tabs.some((entry) => entry.id === tabId))
: false;
if (!tabId || !hasTab) {
tabId = currentStore.createTab(normalizedDirectory);
tabByKeyRef.current[key] = tabId;
}
setTabLabel(normalizedDirectory, tabId, `Action: ${action.name}`);
setTabIconKey(normalizedDirectory, tabId, action.icon || 'play');
setActiveTab(normalizedDirectory, tabId);
if (options.revealTerminal !== false) {
useUIStore.getState().openContextPanelTab(normalizedDirectory, { mode: 'terminal' });
}
const stateAfterTab = useTerminalStore.getState().getDirectoryState(normalizedDirectory);
const tab = stateAfterTab?.tabs.find((entry) => entry.id === tabId);
return {
key,
tabId,
sessionId: tab?.terminalSessionId ?? null,
};
}, [
ensureDirectory,
normalizedDirectory,
setActiveTab,
setTabIconKey,
setTabLabel,
t,
]);
const runAction = React.useCallback(async (action: OpenChamberProjectAction) => {
if (runtime.isVSCode || (!allowMobile && isMobile)) {
return;
}
if (!normalizedDirectory) {
toast.error(t('projectActions.error.noActiveDirectoryForAction'));
return;
}
const runKey = toProjectActionRunKey(normalizedDirectory, action.id);
const existingRun = projectActionRuns[runKey];
if (existingRun && existingRun.status === 'running') {
return;
}
if (startingRunKeysRef.current.has(runKey)) return;
startingRunKeysRef.current.add(runKey);
try {
const discovered = action.id === AUTO_DISCOVER_ACTION_ID
? await (async (): Promise<OpenChamberProjectAction> => {
const [actionsState, scripts] = await Promise.all([
getProjectActionsState({ id: stableProjectRef?.id ?? '', path: normalizedDirectory }),
readPackageJsonScripts(normalizedDirectory),
]);
const devServer = await detectDevServerCommand(normalizedDirectory, actionsState.actions, scripts);
if (!devServer) {
throw new Error(t('contextPanel.preview.noDevServer'));
}
return {
id: AUTO_DISCOVER_ACTION_ID,
name: t('projectActions.actions.autoDiscover'),
command: devServer.command,
icon: 'scan-2',
autoOpenUrl: true,
openUrl: devServer.previewUrlHint || '',
};
})()
: action;
const hasCustomOpenUrl = discovered.autoOpenUrl === true && (discovered.openUrl || '').trim().length > 0;
const revealTerminal = !hasCustomOpenUrl && action.id !== AUTO_DISCOVER_ACTION_ID;
const { key, tabId, sessionId } = await getOrCreateActionTab(discovered, { revealTerminal });
let activeSessionId = sessionId;
if (!activeSessionId) {
setConnecting(normalizedDirectory, tabId, true);
try {
const created = await terminal.createSession({
cwd: normalizedDirectory,
sessionId: tabId,
shell: terminalShell,
loginShell: terminalLoginShell,
themeMode: currentTheme.metadata.variant === 'light' ? 'light' : 'dark',
terminalBackground: currentTheme.colors.surface.background,
terminalForeground: currentTheme.colors.syntax.base.foreground,
});
activeSessionId = created.sessionId;
setTabSessionId(normalizedDirectory, tabId, activeSessionId);
} finally {
setConnecting(normalizedDirectory, tabId, false);
}
}
if (!activeSessionId) {
throw new Error(t('projectActions.error.failedToCreateTerminalSession'));
}
streamCleanupByRunKeyRef.current[key]?.();
setConnecting(normalizedDirectory, tabId, true);
const subscription = terminal.connect(
activeSessionId,
{ onEvent: (event) => {
if (event.type === 'snapshot') {
useTerminalStore.getState().replaceBuffer(normalizedDirectory, tabId, event.data ?? '', event.sequence ?? 0);
useTerminalStore.getState().setConnecting(normalizedDirectory, tabId, false);
}
if (event.type === 'data' && typeof event.data === 'string' && event.data.length > 0) {
useTerminalStore.getState().appendToBuffer(normalizedDirectory, tabId, event.data, event.sequence, event.replayData);
}
if (event.type === 'exit') {
useTerminalStore.getState().setTabLifecycle(normalizedDirectory, tabId, 'exited');
useTerminalStore.getState().setConnecting(normalizedDirectory, tabId, false);
useTerminalStore.getState().removeProjectActionRun(key);
delete urlWatchByRunKeyRef.current[key];
streamCleanupByRunKeyRef.current[key]?.();
delete streamCleanupByRunKeyRef.current[key];
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[key]);
delete previewWaitTimeoutByRunKeyRef.current[key];
}
}, onError: (_error, fatal) => {
useTerminalStore.getState().setConnecting(normalizedDirectory, tabId, false);
if (fatal) {
useTerminalStore.getState().setTabLifecycle(normalizedDirectory, tabId, 'exited');
useTerminalStore.getState().setTabSessionId(normalizedDirectory, tabId, null);
useTerminalStore.getState().removeProjectActionRun(key);
}
} },
);
streamCleanupByRunKeyRef.current[key] = subscription.close;
const hasDesktopForwardSelection = discovered.autoOpenUrl === true
&& isDesktopShellApp
&& (discovered.desktopOpenSshForward || '').trim().length > 0;
const manualOpenUrl = discovered.autoOpenUrl ? normalizeManualOpenUrl(discovered.openUrl) : null;
const desktopForwardUrl = discovered.autoOpenUrl && isDesktopShellApp
? resolveProjectActionDesktopForwardUrl(discovered.desktopOpenSshForward, desktopSshInstances)
: null;
setProjectActionRun({
key,
directory: normalizedDirectory,
actionId: discovered.id,
tabId,
sessionId: activeSessionId,
status: discovered.id === AUTO_DISCOVER_ACTION_ID && !manualOpenUrl ? 'waiting-for-preview' : 'running',
});
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[key]);
delete previewWaitTimeoutByRunKeyRef.current[key];
if (discovered.id === AUTO_DISCOVER_ACTION_ID && !manualOpenUrl) {
previewWaitTimeoutByRunKeyRef.current[key] = window.setTimeout(() => {
const store = useTerminalStore.getState();
const run = store.projectActionRuns[key];
store.updateProjectActionRunStatus(key, 'running');
if (run) {
store.setActiveTab(run.directory, run.tabId);
useUIStore.getState().openContextPanelTab(run.directory, { mode: 'terminal' });
}
delete previewWaitTimeoutByRunKeyRef.current[key];
}, AUTO_DISCOVER_PREVIEW_WAIT_TIMEOUT_MS);
}
urlWatchByRunKeyRef.current[key] = {
lastSeenChunkId: null,
openedUrl: Boolean(desktopForwardUrl) || Boolean(manualOpenUrl) || hasCustomOpenUrl,
tail: '',
openInPreview: discovered.id === AUTO_DISCOVER_ACTION_ID,
announced: [],
offering: false,
};
const normalizedCommand = stripControlChars(discovered.command.trim().replace(/\r\n|\r/g, '\n'));
await terminal.sendInput(activeSessionId, `${normalizedCommand}\r`);
if (desktopForwardUrl) {
setTabPreviewUrl(normalizedDirectory, tabId, null, { locked: true });
void openExternal(desktopForwardUrl);
toast.success(t('projectActions.toast.openedForwardedUrl'));
} else if (manualOpenUrl) {
setTabPreviewUrl(normalizedDirectory, tabId, manualOpenUrl, { locked: true, autoOpened: true });
openContextPreview(normalizedDirectory, manualOpenUrl);
toast.success(t('projectActions.toast.openedActionUrl'));
} else if (hasCustomOpenUrl) {
setTabPreviewUrl(normalizedDirectory, tabId, null, { locked: true });
toast.error(t('projectActions.error.invalidCustomUrlFormat'));
} else if (hasDesktopForwardSelection) {
setTabPreviewUrl(normalizedDirectory, tabId, null, { locked: true });
toast.error(t('projectActions.error.selectedDesktopSshForwardUnavailable'));
} else {
setTabPreviewUrl(normalizedDirectory, tabId, null, { locked: false, autoOpened: false });
}
} catch (error) {
removeProjectActionRun(runKey);
delete urlWatchByRunKeyRef.current[runKey];
streamCleanupByRunKeyRef.current[runKey]?.();
delete streamCleanupByRunKeyRef.current[runKey];
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[runKey]);
delete previewWaitTimeoutByRunKeyRef.current[runKey];
toast.error(error instanceof Error ? error.message : t('projectActions.error.failedToRunAction'));
} finally {
startingRunKeysRef.current.delete(runKey);
}
}, [
currentTheme.colors.surface.background,
currentTheme.colors.syntax.base.foreground,
currentTheme.metadata.variant,
desktopSshInstances,
getOrCreateActionTab,
allowMobile,
isMobile,
isDesktopShellApp,
normalizedDirectory,
terminalLoginShell,
terminalShell,
openExternal,
openContextPreview,
projectActionRuns,
runtime.isVSCode,
removeProjectActionRun,
setConnecting,
setProjectActionRun,
setTabPreviewUrl,
setTabSessionId,
stableProjectRef?.id,
t,
terminal,
]);
const stopAction = React.useCallback(async (action: OpenChamberProjectAction) => {
const runKey = toProjectActionRunKey(normalizedDirectory, action.id);
const activeRun = projectActionRuns[runKey];
if (!activeRun) {
return;
}
updateProjectActionRunStatus(runKey, 'stopping');
const exitPromise = waitForTerminalExit(terminal, activeRun.sessionId, 1000);
try {
await terminal.sendInput(activeRun.sessionId, '\x03');
} catch {
// noop
}
const exitObserved = await exitPromise;
const afterTab = useTerminalStore.getState().getDirectoryState(activeRun.directory)?.tabs
.find((entry) => entry.id === activeRun.tabId);
const sessionStillSame = afterTab?.terminalSessionId === activeRun.sessionId;
if (sessionStillSame && !exitObserved) {
if (typeof terminal.forceKill === 'function') {
try {
await terminal.forceKill({ sessionId: activeRun.sessionId });
} catch {
// noop
}
} else {
try {
await terminal.close(activeRun.sessionId);
} catch {
// noop
}
}
setTabSessionId(activeRun.directory, activeRun.tabId, null);
}
removeProjectActionRun(runKey);
delete urlWatchByRunKeyRef.current[runKey];
streamCleanupByRunKeyRef.current[runKey]?.();
delete streamCleanupByRunKeyRef.current[runKey];
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[runKey]);
delete previewWaitTimeoutByRunKeyRef.current[runKey];
}, [normalizedDirectory, projectActionRuns, removeProjectActionRun, setTabSessionId, terminal, updateProjectActionRunStatus]);
const handlePrimaryClick = React.useCallback(() => {
const action = selectedAction ?? displayActions[0];
if (!action) {
return;
}
const runKey = toProjectActionRunKey(normalizedDirectory, action.id);
const runningEntry = projectActionRuns[runKey];
if (runningEntry?.status === 'stopping') {
return;
}
if (runningEntry) {
void stopAction(action);
return;
}
void runAction(action);
}, [displayActions, normalizedDirectory, runAction, projectActionRuns, selectedAction, stopAction]);
const handleSelectAction = React.useCallback((action: OpenChamberProjectAction, toggleStopIfRunning = false) => {
setSelectedActionId(action.id);
if (!toggleStopIfRunning) {
void runAction(action);
return;
}
const runKey = toProjectActionRunKey(normalizedDirectory, action.id);
const runningEntry = projectActionRuns[runKey];
if (runningEntry?.status === 'stopping') {
return;
}
if (runningEntry) {
void stopAction(action);
return;
}
void runAction(action);
}, [normalizedDirectory, runAction, projectActionRuns, stopAction]);
const openProjectActionsSettings = React.useCallback(() => {
if (!stableProjectRef?.id) {
return;
}
setSettingsProjectsSelectedId(stableProjectRef.id);
setSettingsPage('projects');
setSettingsDialogOpen(true);
}, [setSettingsDialogOpen, setSettingsPage, setSettingsProjectsSelectedId, stableProjectRef?.id]);
const previewAction = selectedAction ?? displayActions[0] ?? null;
const previewRun = previewAction ? projectActionRuns[toProjectActionRunKey(normalizedDirectory, previewAction.id)] : null;
const selectedRunPreviewUrl = useTerminalStore((state) => {
if (!previewRun) return null;
return state.sessions.get(previewRun.directory)?.tabs.find((tab) => tab.id === previewRun.tabId)?.previewUrl ?? null;
});
if (runtime.isVSCode || (!allowMobile && isMobile) || !stableProjectRef || !normalizedDirectory) {
return null;
}
const resolvedSelected = selectedAction ?? displayActions[0] ?? null;
if (!resolvedSelected) {
return null;
}
const selectedIconKey = (resolvedSelected.icon || 'play') as keyof typeof PROJECT_ACTION_ICON_MAP;
const selectedIconName = resolvedSelected.id === AUTO_DISCOVER_ACTION_ID
? 'scan-2'
: PROJECT_ACTION_ICON_MAP[selectedIconKey] || 'play';
const selectedRunKey = toProjectActionRunKey(normalizedDirectory, resolvedSelected.id);
const selectedRunning = projectActionRuns[selectedRunKey];
const isStoppingSelected = selectedRunning?.status === 'stopping';
const isWaitingForSelectedPreview = selectedRunning?.status === 'waiting-for-preview';
const showSelectedPreviewButton = Boolean(selectedRunning && selectedRunPreviewUrl);
const handleOpenSelectedPreview = () => {
if (!selectedRunning || !selectedRunPreviewUrl) {
return;
}
openContextPreview(selectedRunning.directory, selectedRunPreviewUrl);
};
const isAutoDiscoverSelected = resolvedSelected.id === AUTO_DISCOVER_ACTION_ID;
if (compact) {
return (
<div className="inline-flex items-center">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
disabled={isLoading || isStoppingSelected}
className={cn(
'app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2',
'typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary',
'disabled:cursor-not-allowed',
className
)}
onClick={handlePrimaryClick}
aria-label={selectedRunning
? t('projectActions.actions.stopNamedAria', { name: resolvedSelected.name })
: t('projectActions.actions.runNamedAria', { name: resolvedSelected.name })}
>
{isStoppingSelected || isWaitingForSelectedPreview
? <Icon name="loader-4" className="h-5 w-5 animate-spin text-[var(--status-warning)]" />
: selectedRunning
? <Icon name="stop" className="h-5 w-5 text-[var(--status-warning)]" />
: <Icon name={selectedIconName} className="h-5 w-5" />}
</button>
</TooltipTrigger>
{isAutoDiscoverSelected ? (
<TooltipContent sideOffset={6}>{t('projectActions.actions.autoDiscoverTooltip')}</TooltipContent>
) : null}
</Tooltip>
{showSelectedPreviewButton ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
aria-label={t('projectActions.actions.openPreview')}
onClick={handleOpenSelectedPreview}
>
<Icon name="global" className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent sideOffset={6}>{t('projectActions.actions.openPreview')}</TooltipContent>
</Tooltip>
) : null}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
aria-label={t('projectActions.actions.chooseActionAria')}
>
<Icon name="arrow-down-s" className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52 max-h-[70vh] overflow-y-auto">
<DropdownMenuItem className="flex items-center gap-2" onClick={openProjectActionsSettings}>
<Icon name="add" className="h-4 w-4" />
<span className="typography-ui-label text-foreground">{t('projectActions.actions.addNewAction')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
{displayActions.map((entry) => {
const iconKey = (entry.icon || 'play') as keyof typeof PROJECT_ACTION_ICON_MAP;
const iconName = entry.id === AUTO_DISCOVER_ACTION_ID
? 'scan-2'
: PROJECT_ACTION_ICON_MAP[iconKey] || 'play';
const runKey = toProjectActionRunKey(normalizedDirectory, entry.id);
const runState = projectActionRuns[runKey];
const isRunning = Boolean(runState);
const isStopping = runState?.status === 'stopping';
return (
<DropdownMenuItem
key={entry.id}
className="flex items-center gap-2"
onClick={() => {
handleSelectAction(entry, true);
}}
>
<Icon name={iconName} className="h-4 w-4" />
<span className="typography-ui-label text-foreground truncate">{entry.name}</span>
{isStopping || runState?.status === 'waiting-for-preview'
? <Icon name="loader-4" className="ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]" />
: isRunning
? <Icon name="stop" className="ml-auto h-4 w-4 text-[var(--status-warning)]" />
: null}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
);
}
return (
<div
className={cn(
'app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]',
'bg-[var(--surface-elevated)] overflow-hidden',
'border border-border/60',
compact ? 'h-9' : 'h-7',
className
)}
>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={handlePrimaryClick}
disabled={isLoading || isStoppingSelected}
className={cn(
'inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover',
compact ? 'w-9 px-0' : 'px-2.5',
'transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed'
)}
aria-label={selectedRunning
? t('projectActions.actions.stopNamedAria', { name: resolvedSelected.name })
: t('projectActions.actions.runNamedAria', { name: resolvedSelected.name })}
>
<span className="inline-flex h-4 w-4 shrink-0 items-center justify-center">
{isStoppingSelected || isWaitingForSelectedPreview
? <Icon name="loader-4" className="h-4 w-4 animate-spin text-[var(--status-warning)]" />
: selectedRunning
? <Icon name="stop" className="h-4 w-4 text-[var(--status-warning)]" />
: <Icon name={selectedIconName} className="h-4 w-4" />}
</span>
</button>
</TooltipTrigger>
{isAutoDiscoverSelected ? (
<TooltipContent sideOffset={6}>{t('projectActions.actions.autoDiscoverTooltip')}</TooltipContent>
) : null}
</Tooltip>
{showSelectedPreviewButton ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={handleOpenSelectedPreview}
className={cn(
compact ? 'inline-flex h-full w-8 items-center justify-center' : 'inline-flex h-full w-7 items-center justify-center',
'border-l border-[var(--interactive-border)] text-foreground',
'hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary'
)}
aria-label={t('projectActions.actions.openPreview')}
>
<Icon name="global" className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent sideOffset={6}>{t('projectActions.actions.openPreview')}</TooltipContent>
</Tooltip>
) : null}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className={cn(
compact ? 'inline-flex h-full w-8 items-center justify-center' : 'inline-flex h-full w-7 items-center justify-center',
'border-l border-[var(--interactive-border)] text-muted-foreground',
'hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary'
)}
aria-label={t('projectActions.actions.chooseActionAria')}
>
<Icon name="arrow-down-s" className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-52 max-h-[70vh] overflow-y-auto">
<DropdownMenuItem className="flex items-center gap-2" onClick={openProjectActionsSettings}>
<Icon name="add" className="h-4 w-4" />
<span className="typography-ui-label text-foreground">{t('projectActions.actions.addNewAction')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
{displayActions.map((entry) => {
const iconKey = (entry.icon || 'play') as keyof typeof PROJECT_ACTION_ICON_MAP;
const iconName = entry.id === AUTO_DISCOVER_ACTION_ID
? 'scan-2'
: PROJECT_ACTION_ICON_MAP[iconKey] || 'play';
const runKey = toProjectActionRunKey(normalizedDirectory, entry.id);
const runState = projectActionRuns[runKey];
const isRunning = Boolean(runState);
const isStopping = runState?.status === 'stopping';
return (
<DropdownMenuItem
key={entry.id}
className="flex items-center gap-2"
onClick={() => {
handleSelectAction(entry, true);
}}
>
<Icon name={iconName} className="h-4 w-4" />
<span className="typography-ui-label text-foreground truncate">{entry.name}</span>
{isStopping || runState?.status === 'waiting-for-preview'
? <Icon name="loader-4" className="ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]" />
: isRunning
? <Icon name="stop" className="ml-auto h-4 w-4 text-[var(--status-warning)]" />
: null}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
);
};