Files
openchamber/packages/ui/src/components/layout/ProjectActionsButton.tsx
T
Bohdan Triapitsyn 85c4320825 Settings storage with scopes, and project setup that can live in the repository (#3413)
* refactor(settings): settings registry and intent-gated writes

Problem: every setting lived in a flat document with ten hand-maintained
key lists that had drifted (three keys the server silently dropped, five
it kept that nothing read), and three code paths wrote to the server
without a person changing anything: the theme persist effect on mount,
bootstrap seeding of server-missing keys, and the auto-save echoing
values just adopted from the server.

Approach: one registry (packages/ui/src/lib/settings/registry.ts) names
every key with its scope (instance / profile / device), a boundary parser
and its store binding; DesktopSettings, the sanitizer, the mirror, the
apply step and the auto-save derive from it. A generated JSON snapshot
carries the key list to the server and the VS Code bridge. Writes carry
intent: the theme context writes only from its user-facing setters, a
missing server key leaves the local store alone instead of resetting it,
updateDesktopSettings drops values the server already holds, and the
auto-savers treat values applied from the server as a new baseline.

Testing: bun test packages/ui (registry + persistence suites cover zero
writes on load, dedup, toggle-back cancellation, failed-save retry, and
snapshot freshness); tsc for every workspace.

* refactor(ui): read and write settings through the shared path only

Problem: fourteen pages and stores fetched /api/config/settings on their
own and re-parsed the raw document by hand, so the registry could not
guard them and two of them treated a failed load as an empty list.

Approach: loadDesktopSettings() and updateDesktopSettings() (which now
resolves { ok }) replace every direct call; SkillsCatalogPage and
AddCatalogDialog refuse to write the catalog list until it is known.

Testing: bun test packages/ui (403 files), eslint on the changed files.

* refactor(server): validate settings writes against the registry snapshot

Problem: the server whitelist was the only guard on PUT /api/config/settings
and had drifted from the client; dead keys were still persisted.

Approach: settings-helpers.js drops any key the generated registry
snapshot does not list as persistable and strips secret keys from
responses; the dead keys (markdownDisplayMode, toolCallExpansion,
typographySizes, expandedEditorToolbar, gitProviderId/gitModelId) are
gone; the profile keys that were client-only now round-trip. A drift
test requires a valid sample for every persistable registry key.

Testing: vitest run in packages/web (182 files), including the packed
tarball import.

* refactor(vscode): gate bridge settings writes by the registry

Problem: the extension host wrote any key the webview sent straight into
settings.json, and commit-message generation read the dead
gitProviderId/gitModelId pair instead of the small-model setting.

Approach: filterPersistableSettingsChanges applies the registry snapshot
before the file write; chooseBridgeGitGenerationModel honours
smallModelUseDefault/smallModelOverride ahead of the zen fallback.

Testing: bun test packages/vscode (37 files), tsc, build:extension.

* feat(settings): split the user's profile into preferences.json

Problem: one flat settings.json held instance facts, the user's
preferences and device state together, so device state travelled between
installs and the profile had no document of its own to sync from.

Approach: the server keeps one merged document for clients but routes
each key by registry scope on disk (settings-files.js): profile keys go to
preferences.json as { value, updatedAt } entries stamped when the value
changes, everything else stays in settings.json, device keys are dropped
from writes. A missing preferences.json is seeded once from settings.json,
which is left intact; an unreadable one is a failure that pauses profile
writes and never gets overwritten. Server modules that read a profile key
off the disk use the merged sync read. Electron main reads the theme mode
from both files and now owns the splash colours, handed over the
window-theme IPC instead of the settings document. Clients stop sending
device keys, seed them once from a pre-split document, and persist
inputBarOffset locally. The PWA manifest keys are instance facts.

Testing: vitest in packages/web (seed, split write, timestamp retention,
unreadable file), bun test in packages/ui and packages/electron, tsc for
every workspace.

* feat(vscode): write the profile to preferences.json from the extension host

Problem: the extension host writes the shared settings files directly and
had to follow the server's split, and its file writes reported success on
failure.

Approach: settings-files.ts mirrors the server's format and split rules
(seed once, unreadable preferences.json is a failure); persistSettings
routes profile keys to preferences.json and the rest to settings.json,
and the atomic writers now throw so a failed save reaches the webview.
Clearing a key now actually removes it from the owning file.

Testing: bun test packages/vscode (38 files), tsc, build:extension.

* feat(settings): store the per-surface profile fields by surface kind

Problem: theme, chat-layout switches and typography sizes are one value
for every client of an instance, so the phone and the desktop cannot
disagree without a hard-coded runtime branch.

Approach: every settings request carries the client's surface kind in the
x-openchamber-surface header (web, desktop, vscode, mobile — the phone app
and the hosted mobile shell are one kind). For the registry's perSurface
keys the store writes a changed value under fields[key].surfaces[kind] in
preferences.json and never touches the base from a surface; reads resolve
the kind's own value, then the base, then nothing. Writes without a
surface (migrations, the seed) set the base. The VS Code host is always
vscode; Electron main resolves desktop for the native window theme. The
Settings UI is unchanged.

Testing: vitest in packages/web (surface write/read, no base copy, unknown
surface falls back to base), bun test in packages/vscode and packages/ui,
tsc for every workspace, build:extension.

* fix(settings): keep a legacy copy of the profile in settings.json

The first write after the split rewrote settings.json with the instance
part only, and that write happens on startup (relay reconcile). A build
from before the split reads only settings.json, so rolling back would
have lost every preference: theme, default model, all of it.

Every write now stores the profile's base values in settings.json next
to the instance part (`legacySettingsDocumentOf`), on the server and in
the VS Code extension host alike. Current builds ignore the copy because
preferences.json wins in the merged read. When preferences.json is
unreadable the copy already on disk is kept rather than dropped.

Testing: settings-runtime tests updated for the copy; full web suite
(182 files), VS Code tests and extension build, tsc clean. Verified live
on a scratch OPENCHAMBER_DATA_DIR: all 136 keys survive startup, theme
changes land per surface, plain keys land in the base.

* feat(settings): make the UI password and tunnel preset tokens write-only

GET /api/config/settings returned desktopUiPassword and the managed
remote tunnel preset tokens to every authenticated client, including
paired phones and the VS Code webview that never need them.

Both keys are now `secret` in the registry: accepted on write, withheld
from reads. The server answers with a hasDesktopUiPassword flag; the
desktop network page shows "Password set" and sends a value only when
the user types a new one or presses "Remove password" (an empty string
clears it and turns LAN access off). The tunnel page already learned
token presence from the status endpoint. The VS Code bridge strips
secret keys from what it hands the webview while still merging them
from disk on write.

Testing: registry, i18n parity, server settings, VS Code gate tests and
tsc; workspace type-check. Verified against a scratch server: GET
carries the flag and no password, PUT with '' clears, PUT with a value
sets. The desktop-only page itself awaits the owner's run.

* fix(settings): send the surface kind as a query parameter, not a header

The packaged desktop shell (openchamber-ui://app) and the phone app are
cross-origin to the OpenChamber server, so the x-openchamber-surface
header turned every settings request into a CORS preflight the server
did not allow. Settings looked reset and every save reported "Save
failed" without reaching persistSettings. An older remote instance would
refuse the header the same way even with the allow-list fixed.

The client now sends ?surface=<kind>, which keeps the request
CORS-simple on every server version; the server reads the query
parameter and still honours the header. The header is also in the CORS
allow-list for completeness.

Testing: workspace type-check, persistence and registry tests, server
opencode tests. On a scratch server: PUT with ?surface=vscode lands
under surfaces.vscode, GET without or with an unknown surface serves the
base, the header fallback resolves. Confirmed in the owner's rebuilt
desktop and on the phone.

* refactor(settings): drop the show-password toggle from the desktop network page

With the password write-only, the field only ever holds a value the user
is typing right now; the reveal toggle and its strings are gone from
every locale.

* refactor(projects): serve project setup through the server, drop the legacy migration

The shared UI read and wrote ~/.config/openchamber/projects/<id>.json
itself: it resolved the home directory, composed the path, and used the
Files API, which only desktop and VS Code have natively and which cannot
see a remote instance's file at all. It also still carried the months-old
migration from <repo>/.openchamber/openchamber.json, which deleted files in
the folder the upcoming shared project config will use.

The client-owned keys (worktree setup commands, project actions, draft
starters) now live behind GET/PUT /api/projects/:projectId/config.
project-setup.js sanitizes and builds the view; the project-config runtime
merges a patch under the same cross-process lock the scheduled-task writers
hold, so unknown and server-owned keys survive. A wrongly shaped key is a
400, not a silent drop. openchamberConfig.ts keeps its exported functions
and is now an HTTP client. The VS Code webview handles the route locally
and bridges to the extension host, which owns the file with a TS mirror of
the sanitizers.

Testing: server tests for sanitizers, round trip, lock, and invalid patch;
client tests against a mocked route; VS Code sanitizer and bridge tests;
workspace type-check, both VS Code builds, UI isolated suite (409 files),
server projects and project-context suites. Live GET/PUT against a
running server with the owner's real project config.

* feat(projects): read the team's shared config and merge it with the personal one

A project can now carry <repo>/.openchamber/project.json (version 1:
setupWorktree, setupWorktreeWait, projectActions, draftStarters,
plansDir). The server finds the checkout from the path-derived project
id, parses the file, and answers GET /api/projects/:id/config with one
merged view: what runs at the top level, plus shared and personal blocks
so a page can edit the personal file without copying a teammate's entry
into it.

Merge rules: shared setup commands run first (a personal
setupWorktreeMode of "replace" uses the personal list only); the
personal wait flag wins when set; actions union by id with a personal
action replacing the shared one and personal hiddenSharedActionIds
dropping shared ones; starters union by type:name; the primary action is
personal only. A shared file that exists but cannot be parsed, or that
names a plansDir outside the repo, is reported as invalid with a reason
and never treated as "no shared setup". Nothing writes the repo file yet.

Client: getProjectSetup exposes the view; the existing helpers return
effective values, while the Projects page sections and the draft
starters hook edit the personal block only. Shared entries show a quiet
"shared" mark in the actions dropdown and read-only lists above the
editable ones on the Projects page; shared starter chips have no remove
handle. The VS Code extension host mirrors the parser and merge.

Testing: server tests for the parser, plansDir guard, merge table, id
round trip, and a runtime test against a temp checkout; client tests
against a mocked route; VS Code sanitizer, merge, and bridge tests; the
section test covers the shared row; locale parity; workspace type-check;
UI isolated suite (409 files). Live: GET against a temp repo with a
shared file and with a broken one.

* feat(projects): ask before the team's shared commands run, once per set of commands

Shared setup commands and shared actions come from a file a git pull can
change, and they run on the machine of whoever pulls. The first time one
would run, a dialog now shows exactly what would run and asks: "Trust and
run" or "Not this time". A "trust" answer is recorded in the personal
config against a SHA-256 of the executable parts (setup commands and each
action's id, command, and runIn; renames and icons do not count), so a
pull that changes a command brings the prompt back. Nothing asks when the
shared file has nothing that executes.

Worktree creation (session creator, new-worktree dialog, session store,
multi-run launcher, agent-manager empty state) resolves its commands
through the prompt; "not this time" runs only the user's own commands.
The actions dropdown asks before a shared action runs. The Projects page
shows "Trusted on this instance" with a "Reset trust" button next to the
shared actions. The dialog is mounted beside the app-link confirmation on
every shell. The VS Code extension host mirrors the hash and the record.

Testing: server tests for hash stability, ordering, and the trusted flag,
plus a runtime test that changes the shared file and sees trust drop;
client tests for the confirmation store (ask, trust, skip, replace mode,
newer request, failed record, reset); VS Code mirror tests; the actions
button, new-worktree dialog, and issue-2039 tests updated for the trust
path; locale parity; workspace type-check; UI isolated suite (410 files).

* feat(projects): share and unshare setup with the team from the Projects page

The repo file <repo>/.openchamber/project.json is now written by the app,
and only when the user shares something: nothing appears in a repository
until then. PUT /api/projects/:id/config/shared replaces the keys it
names over the current file, writes it pretty-printed with version first
and only the keys that carry something, removes the file (and an empty
.openchamber folder) when nothing is left, refuses a missing checkout or
a plansDir outside the repo, and records trust for the writer, who has
seen what they shared.

On the Projects page, actions and setup commands get "Share with team"
and "Make personal"; shared actions can be hidden for this user; a
checkbox switches to "Use only my setup commands". Project starter chips
get share and make-personal hover buttons. A new "Shared config" block
shows the file's path and status, the shared plans folder, and the trust
status with "Reset trust". A share is a repo write followed by a personal
write; a failure after the first leaves the item visible once, as
personal. The VS Code extension host mirrors the writer.

Testing: server tests for the patch, serialization, emptiness, the write
and removal round trip, the writer's trust record, and the refusals;
client test for the shared route; VS Code bridge test for write and
removal; locale parity; workspace type-check; UI isolated suite (410
files). Live on a scratch server: share, invalid plansDir (400), unshare
to removal of file and folder.

* feat(projects): list, edit, and move plans in the team's shared plans folder

When the shared config names a plansDir, every markdown file in that
folder is a plan on the Plans tab: listed after the user's own plans,
marked shared, addressed as shared:<file>, read and edited in place
(the raw document is written verbatim, so a plan another tool wrote
keeps its shape), and deletable. Share moves one of the user's plans
into the folder; make personal moves it back under a new id; a name
collision gets a numeric suffix. Sharing is refused, with a hint in the
panel, until a shared plans folder is set in Project settings. This
answers the request to read plans from an existing folder such as
docs/plans.

Server: the project-context runtime takes resolveSharedPlansDir from the
project-config runtime; readContext reports sharedPlansDir; POST
.../plans/:id/share and /unshare. Client: movePlan in the context store,
a shared badge and a share / make-personal button per plan row. Session
attachments reference plan ids, so an attached plan that moves has to be
attached again.

Testing: runtime tests for listing, foreign markdown titles, id
traversal, in-place update and delete, share and unshare with a
collision, and the refusal without a folder; HTTP route tests; store and
locale parity tests; workspace type-check; full web suite (183 files);
UI isolated suite (410 files). Live on a scratch server against a temp
repo: list, share, read, unshare.

* fix(server): make OPENCHAMBER_DATA_DIR move every folder, not just the flat files

The variable is documented as the OpenChamber data directory, but only
settings, preferences, auth, and push files followed it; projects,
themes, speech models, and the chats default stayed under
~/.config/openchamber. A second instance started with a custom
directory therefore read and wrote the default instance's project
configs.

Every folder now hangs off the one root. An instance that already used
a custom directory gets projects, themes, and speech-models copied in
once at startup; copied, not moved, so a second instance beside the
default one cannot strip it, and nothing is merged into a folder that
already exists. Existing managed chats are not copied, as with
OPENCHAMBER_CHATS_DIR.

Testing: migration tests for copy-once, no-merge, and same-root no-op;
full web suite; a scratch server with an empty data dir copied the real
project configs and kept its writes in the copy.

* fix(projects): keep a plan's id when it moves into or out of the repository folder

A plan moved into the repository plans folder used to be listed under a
new shared:<file> id, so a session that had attached it lost the
attachment. The manifest entry now stays with a `shared` flag that says
which folder holds the file; the id survives both directions. Only a
plan that never had an entry (one written by another tool) gets an id
when it is brought in. A personal file and a repository file may share
a name because they live in different folders.

Testing: runtime tests for share and unshare with a stable id, reading
and editing the moved plan, the suffix on a name collision, and the
adoption of a foreign file.

* feat(projects): default repository plans folder, "move to repository" wording, tooltips

Plans now have a repository folder without any setup: .openchamber/plans
by default. A custom plansDir replaces the default outright (only that
folder is read and written; moving files between the two is the user's
job), and the field's placeholder and hint say so. The move buttons on
plans are therefore always available.

The word "share" is gone from the UI: it read like publishing, while
the action stores an item in the repository so everyone who pulls it
gets it. Labels are "Move to repository" / "Move to my settings", the
badge is "In repo", the block is "Repository config", and every button
on the Projects page carries a tooltip that says what happens (the
"Move to repository" button explains that edits save first while the
form is dirty). The trust status with "reset trust" moved from the
repository block into the Worktree section next to the commands it
guards; the plan row's badge sits beside the title.

Testing: locale parity, section test, workspace type-check, UI isolated
suite (410 files), full web suite.

* fix(projects): leave the icon key out of the repository file when an action has none

Actions without an icon were written as "icon": null into
.openchamber/project.json. The key is now omitted; readers already fall
back to the play icon. Server and VS Code serializers, tests updated.

* docs: describe the repository config file and how items move into it

A new page in every locale: what stays personal and what can move into
the repository, the .openchamber/project.json format with an example
and every key explained (setup commands, actions with the supported icon
names, starters, plansDir), the merge rules, the trust prompt, and plans
in the repository. Linked from the sidebar and from Project Actions.
Translations written by hand.
2026-09-07 17:50:55 +03:00

1330 lines
60 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 type { IconName } from '@/components/icon/icons';
import { cn } from '@/lib/utils';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { useEffectiveDirectory } from '@/hooks/useEffectiveDirectory';
import { useDeviceInfo } from '@/lib/device';
import { isDesktopShell } from '@/lib/desktop';
import { useUIStore } from '@/stores/useUIStore';
import { useTerminalStore } from '@/stores/useTerminalStore';
import { terminalSnapshotSize } from '@/lib/terminalApi';
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,
getProjectSetup,
type OpenChamberProjectAction,
type ProjectSetup,
type ProjectRef,
} from '@/lib/openchamberConfig';
import { ensureSharedSetupTrusted } from '@/lib/sharedTrustConfirmation';
import {
normalizeProjectActionDirectory,
PROJECT_ACTION_ICONS,
PROJECT_ACTIONS_UPDATED_EVENT,
resolveProjectActionDesktopForwardUrl,
toProjectActionRunKey,
} from '@/lib/projectActions';
import { detectDevServerCommand, readPackageJsonScripts } from '@/lib/detectDevServer';
import {
createProjectActionTerminalSession,
normalizeProjectActionCommand,
reconcileTerminalSessionAuthority,
stopProjectActionTerminalSession,
} from '@/lib/projectActionTerminal';
import { observeTerminalSessions } from '@/lib/terminalSessionObserver';
import type { TerminalTab } from '@/stores/useTerminalStore';
type UrlWatchEntry = {
hostDirectory: string;
directory: string;
tabId: string;
actionId: string;
executionId: string;
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 resolveProjectActionIconName = (action: Pick<OpenChamberProjectAction, 'id' | 'icon'>): IconName => {
if (action.id === AUTO_DISCOVER_ACTION_ID) {
return 'scan-2';
}
const matchedIcon = PROJECT_ACTION_ICONS.find((entry) => entry.key === action.icon);
return matchedIcon?.Icon ?? 'play';
};
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 effectiveDirectory = useEffectiveDirectory();
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 reconcileServerSessions = useTerminalStore((state) => state.reconcileServerSessions);
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 setTabPurpose = useTerminalStore((state) => state.setTabPurpose);
const allocateActionExecution = useTerminalStore((state) => state.allocateActionExecution);
const setTabLifecycle = useTerminalStore((state) => state.setTabLifecycle);
const setTabPreviewUrl = useTerminalStore((state) => state.setTabPreviewUrl);
const matchesActionExecution = useTerminalStore((state) => state.matchesActionExecution);
const captureStartedActionMutationRevisions = useTerminalStore((state) => state.captureStartedActionMutationRevisions);
const [actions, setActions] = React.useState<OpenChamberProjectAction[]>([]);
// The last merged setup, for the trust check before a shared action runs.
const setupRef = React.useRef<ProjectSetup | null>(null);
const [selectedActionId, setSelectedActionId] = React.useState<string | null>(null);
const [isLoading, setIsLoading] = React.useState(false);
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 [waitingForPreviewByExecution, setWaitingForPreviewByExecution] = React.useState<Record<string, true>>({});
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 setup = await getProjectSetup(stableProjectRef);
if (loadRequestIdRef.current !== requestId) {
return;
}
setupRef.current = setup;
const filtered = setup.projectActions;
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 normalizedProjectDirectory = React.useMemo(() => {
return normalizeProjectActionDirectory(stableProjectRef?.path || '');
}, [stableProjectRef?.path]);
const contextHostDirectory = React.useMemo(() => {
return normalizeProjectActionDirectory(effectiveDirectory || '') || normalizedDirectory;
}, [effectiveDirectory, normalizedDirectory]);
const contextHostDirectoryRef = React.useRef(contextHostDirectory);
React.useEffect(() => {
contextHostDirectoryRef.current = contextHostDirectory;
}, [contextHostDirectory]);
// The store owns its directory key form; reading `sessions` directly with a
// project-action-normalized path misses the entry whenever the two spellings
// differ (Windows drive letters and separators).
const directoryTerminalState = useTerminalStore((state) => (
normalizedDirectory ? state.getDirectoryState(normalizedDirectory) : undefined
));
const projectTerminalState = useTerminalStore((state) => (
normalizedProjectDirectory && normalizedProjectDirectory !== normalizedDirectory
? state.getDirectoryState(normalizedProjectDirectory)
: undefined
));
const watchedTerminalStates = React.useMemo(() => {
const states = normalizedDirectory
? [{ directory: normalizedDirectory, state: directoryTerminalState }]
: [];
if (normalizedProjectDirectory && normalizedProjectDirectory !== normalizedDirectory) {
states.push({ directory: normalizedProjectDirectory, state: projectTerminalState });
}
return states;
}, [directoryTerminalState, normalizedDirectory, normalizedProjectDirectory, projectTerminalState]);
const watchedTerminalDirectories = React.useMemo(() => {
const directories = normalizedDirectory ? [normalizedDirectory] : [];
if (normalizedProjectDirectory && normalizedProjectDirectory !== normalizedDirectory) {
directories.push(normalizedProjectDirectory);
}
return directories;
}, [normalizedDirectory, normalizedProjectDirectory]);
const executionDirectoryFor = React.useCallback((action: OpenChamberProjectAction): string => {
if (action.id !== AUTO_DISCOVER_ACTION_ID && action.runIn === 'parent') {
return normalizedProjectDirectory || normalizedDirectory;
}
return normalizedDirectory;
}, [normalizedDirectory, normalizedProjectDirectory]);
const executionKey = React.useCallback((executionDirectory: string, actionId: string, executionId: string) => (
`${executionDirectory}::${actionId}::${executionId}`
), []);
const getActionTab = React.useCallback((executionDirectory: string, actionId: string, state = useTerminalStore.getState()): TerminalTab | null => {
if (!executionDirectory) return null;
return state.getDirectoryState(executionDirectory)?.tabs.find((tab) => (
tab.purpose.type === 'project-action' && tab.purpose.actionId === actionId
)) ?? null;
}, []);
const projectActionRuns = React.useMemo(() => {
const runs: Record<string, { directory: string; actionId: string; tabId: string; sessionId: string; executionId: string; status: 'running' | 'waiting-for-preview' | 'stopping' }> = {};
for (const { directory: tabDirectory, state } of watchedTerminalStates) {
for (const tab of state?.tabs ?? []) {
if (tab.purpose.type !== 'project-action' || !tab.purpose.executionId || !tab.terminalSessionId) continue;
if (tab.lifecycle === 'idle' || tab.lifecycle === 'exited') continue;
const runKey = toProjectActionRunKey(tabDirectory, tab.purpose.actionId);
const execKey = executionKey(tabDirectory, tab.purpose.actionId, tab.purpose.executionId);
runs[runKey] = {
directory: tabDirectory,
actionId: tab.purpose.actionId,
tabId: tab.id,
sessionId: tab.terminalSessionId,
executionId: tab.purpose.executionId,
status: tab.lifecycle === 'stopping'
? 'stopping'
: waitingForPreviewByExecution[execKey]
? 'waiting-for-preview'
: 'running',
};
}
}
return runs;
}, [executionKey, waitingForPreviewByExecution, watchedTerminalStates]);
const clearExecutionUi = React.useCallback((executionDirectory: string, actionId: string, executionId: string) => {
const actionRunKey = toProjectActionRunKey(executionDirectory, actionId);
const executionStateKey = executionKey(executionDirectory, actionId, executionId);
const watch = urlWatchByRunKeyRef.current[actionRunKey];
const ownsActionScopedUi = watch?.executionId === executionId;
const browserWindow = globalThis.window;
const clearPreviewWaitTimeout = (key: string) => {
browserWindow?.clearTimeout(previewWaitTimeoutByRunKeyRef.current[key]);
delete previewWaitTimeoutByRunKeyRef.current[key];
};
if (ownsActionScopedUi) {
delete urlWatchByRunKeyRef.current[actionRunKey];
clearPreviewWaitTimeout(actionRunKey);
}
streamCleanupByRunKeyRef.current[executionStateKey]?.();
delete streamCleanupByRunKeyRef.current[executionStateKey];
clearPreviewWaitTimeout(executionStateKey);
setWaitingForPreviewByExecution((current) => {
if (!current[executionStateKey]) return current;
const next = { ...current };
delete next[executionStateKey];
return next;
});
}, [executionKey]);
const closeTrackedSubscription = React.useCallback((executionStateKey: string) => {
streamCleanupByRunKeyRef.current[executionStateKey]?.();
delete streamCleanupByRunKeyRef.current[executionStateKey];
}, []);
const clearTrackedPreviewTimeout = React.useCallback((executionStateKey: string) => {
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[executionStateKey]);
delete previewWaitTimeoutByRunKeyRef.current[executionStateKey];
}, []);
React.useEffect(() => {
// The refs hold mutable maps whose identity never changes; reading the
// container once inside the effect keeps the latest entries visible to
// the unmount cleanup without re-reading `.current` there.
const trackedStreams = streamCleanupByRunKeyRef.current;
const trackedTimeouts = previewWaitTimeoutByRunKeyRef.current;
return () => {
for (const executionStateKey of Object.keys(trackedStreams)) {
closeTrackedSubscription(executionStateKey);
}
for (const executionStateKey of Object.keys(trackedTimeouts)) {
clearTrackedPreviewTimeout(executionStateKey);
}
};
}, [clearTrackedPreviewTimeout, closeTrackedSubscription]);
React.useEffect(() => {
const watchedDirectories = new Set(watchedTerminalDirectories);
for (const watch of Object.values(urlWatchByRunKeyRef.current)) {
if (!watchedDirectories.has(watch.directory)) clearExecutionUi(watch.directory, watch.actionId, watch.executionId);
}
for (const executionStateKey of Object.keys(streamCleanupByRunKeyRef.current)) {
const executionDirectory = executionStateKey.split('::', 1)[0] ?? '';
if (!watchedDirectories.has(executionDirectory)) {
closeTrackedSubscription(executionStateKey);
}
}
}, [clearExecutionUi, closeTrackedSubscription, watchedTerminalDirectories]);
const revealProjectActionTerminal = React.useCallback((hostDirectory: string, executionDirectory: string) => {
useUIStore.getState().openContextPanelTab(hostDirectory, {
mode: 'terminal',
targetDirectory: executionDirectory === hostDirectory ? null : executionDirectory,
});
}, []);
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(() => {
const cleanups = watchedTerminalDirectories.map(executionDirectory => observeTerminalSessions(
terminal, executionDirectory, captureStartedActionMutationRevisions,
result => reconcileServerSessions(executionDirectory, result.sessions, {
startedActionMutationRevisions: result.startedActionMutationRevisions,
}),
));
return () => { for (const close of cleanups) close(); };
}, [captureStartedActionMutationRevisions, reconcileServerSessions, terminal, watchedTerminalDirectories]);
React.useEffect(() => {
for (const { directory: tabDirectory, state } of watchedTerminalStates) {
if (!tabDirectory) {
continue;
}
for (const tab of state?.tabs ?? []) {
if (tab.purpose.type !== 'project-action') continue;
const actionId = tab.purpose.actionId;
const action = displayActions.find((entry) => entry.id === actionId);
const nextLabel = action?.name ?? actionId;
const nextIcon = action?.icon || 'play';
if (tab.label !== nextLabel) {
setTabLabel(tabDirectory, tab.id, nextLabel);
}
if (tab.iconKey !== nextIcon) {
setTabIconKey(tabDirectory, tab.id, nextIcon);
}
}
}
}, [displayActions, setTabIconKey, setTabLabel, watchedTerminalStates]);
React.useEffect(() => {
const browserWindow = globalThis.window;
if (!browserWindow) {
return;
}
const handler = (event: Event) => {
// SAFETY: this event name is only dispatched by our own project-actions update helper with this detail payload.
const detail = (event as CustomEvent<{ projectId?: string }>).detail;
if (!projectId) {
return;
}
if (detail?.projectId && detail.projectId !== projectId) {
return;
}
void loadActions();
};
browserWindow.addEventListener(PROJECT_ACTIONS_UPDATED_EVENT, handler);
return () => {
browserWindow.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 executionStateKey = executionKey(watch.directory, watch.actionId, watch.executionId);
const candidates = watch.announced;
if (candidates.length === 0) return;
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[executionStateKey]);
delete previewWaitTimeoutByRunKeyRef.current[executionStateKey];
watch.openedUrl = true;
setWaitingForPreviewByExecution((current) => {
if (!current[executionStateKey]) return current;
const next = { ...current };
delete next[executionStateKey];
return next;
});
if (candidates.length === 1) {
setAnnouncedDevServers(watch.directory, []);
setTabPreviewUrl(watch.directory, watch.tabId, candidates[0], { locked: false, autoOpened: true });
openContextPreview(watch.directory, candidates[0]);
return;
}
watch.offering = true;
setAnnouncedDevServers(watch.directory, candidates);
useUIStore.getState().openContextSurface(watch.directory, 'browser');
toast.info(t('projectActions.toast.multipleServers'));
};
const monitorRuns = () => {
const terminalStore = useTerminalStore.getState();
const terminalSessions = terminalStore.sessions;
const currentRuns = 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) {
clearExecutionUi(entry.directory, entry.actionId, entry.executionId);
continue;
}
const existingWatch = urlWatchByRunKeyRef.current[runKey];
const watch = existingWatch?.executionId === entry.executionId
? existingWatch
: {
hostDirectory: contextHostDirectoryRef.current || entry.directory,
directory: entry.directory,
tabId: entry.tabId,
actionId: entry.actionId,
executionId: entry.executionId,
lastSeenChunkId: null,
openedUrl: true,
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, expectedExecutionId: run.executionId });
if (run.status === 'waiting-for-preview') {
setWaitingForPreviewByExecution((current) => {
const executionStateKey = executionKey(run.directory, run.actionId, run.executionId);
if (!current[executionStateKey]) return current;
const next = { ...current };
delete next[executionStateKey];
return next;
});
}
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]) {
const watch = urlWatchByRunKeyRef.current[runKey];
const currentTab = watch
? terminalSessions.get(watch.directory)?.tabs.find((tab) => tab.id === watch.tabId)
: undefined;
const watchStillOwnedByActiveExecution = currentTab?.purpose.type === 'project-action'
&& currentTab.purpose.executionId === watch?.executionId
&& Boolean(currentTab.terminalSessionId)
&& currentTab.lifecycle !== 'idle'
&& currentTab.lifecycle !== 'exited';
if (watchStillOwnedByActiveExecution) {
continue;
}
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();
});
}, [clearExecutionUi, contextHostDirectoryRef, displayActions, executionKey, openContextPreview, openExternal, projectActionRuns, setTabPreviewUrl, t]);
React.useEffect(() => {
for (const { directory: tabDirectory, state } of watchedTerminalStates) {
for (const tab of state?.tabs ?? []) {
if (tab.purpose.type !== 'project-action' || !tab.purpose.executionId || !tab.terminalSessionId) continue;
if (tab.lifecycle !== 'running') continue;
const actionId = tab.purpose.actionId;
const currentExecutionId = tab.purpose.executionId;
const streamKey = executionKey(tabDirectory, actionId, currentExecutionId);
if (streamCleanupByRunKeyRef.current[streamKey]) continue;
const subscription = terminal.connect(tab.terminalSessionId, {
onEvent: (event) => {
if (!matchesActionExecution(tabDirectory, tab.id, currentExecutionId)) return;
if (event.type === 'snapshot') {
useTerminalStore.getState().replaceBuffer(tabDirectory, tab.id, event.data ?? '', event.sequence ?? 0, terminalSnapshotSize(event));
if (event.status === 'running') {
useTerminalStore.getState().setTabLifecycle(tabDirectory, tab.id, 'running', { expectedExecutionId: currentExecutionId });
}
if (event.status === 'exited') {
useTerminalStore.getState().setTabLifecycle(tabDirectory, tab.id, 'exited', { expectedExecutionId: currentExecutionId });
useTerminalStore.getState().setTabPurpose(tabDirectory, tab.id, { type: 'project-action', actionId, executionId: null });
clearExecutionUi(tabDirectory, actionId, currentExecutionId);
}
}
const output = event.type === 'data' ? (event.data ?? '') : '';
if (output) {
useTerminalStore.getState().appendToBuffer(tabDirectory, tab.id, output, event.sequence, event.replayData);
}
if (event.type === 'exit') {
useTerminalStore.getState().setTabLifecycle(tabDirectory, tab.id, 'exited', { expectedExecutionId: currentExecutionId });
useTerminalStore.getState().setTabPurpose(tabDirectory, tab.id, { type: 'project-action', actionId, executionId: null });
clearExecutionUi(tabDirectory, actionId, currentExecutionId);
}
},
onError: (_error, fatal) => {
if (!fatal || !matchesActionExecution(tabDirectory, tab.id, currentExecutionId)) return;
useTerminalStore.getState().setTabLifecycle(tabDirectory, tab.id, 'exited', { expectedExecutionId: currentExecutionId });
useTerminalStore.getState().setTabSessionId(tabDirectory, tab.id, null, { expectedExecutionId: currentExecutionId });
useTerminalStore.getState().setTabPurpose(tabDirectory, tab.id, { type: 'project-action', actionId, executionId: null });
clearExecutionUi(tabDirectory, actionId, currentExecutionId);
},
});
streamCleanupByRunKeyRef.current[streamKey] = subscription.close;
}
}
}, [clearExecutionUi, executionKey, matchesActionExecution, terminal, watchedTerminalStates]);
const getOrCreateActionTab = React.useCallback(async (action: OpenChamberProjectAction) => {
const executionDirectory = executionDirectoryFor(action);
if (!executionDirectory) {
throw new Error(t('projectActions.error.noActiveDirectory'));
}
const key = toProjectActionRunKey(executionDirectory, action.id);
ensureDirectory(executionDirectory);
const currentStore = useTerminalStore.getState();
const existingTab = getActionTab(executionDirectory, action.id, currentStore);
const tabId = existingTab?.id ?? currentStore.createTab(executionDirectory);
setTabLabel(executionDirectory, tabId, action.name);
setTabIconKey(executionDirectory, tabId, action.icon || 'play');
if (!existingTab) {
setTabPurpose(executionDirectory, tabId, { type: 'project-action', actionId: action.id, executionId: null });
}
setActiveTab(executionDirectory, tabId);
const stateAfterTab = useTerminalStore.getState().getDirectoryState(executionDirectory);
const tab = stateAfterTab?.tabs.find((entry) => entry.id === tabId);
return {
executionDirectory,
key,
tabId,
sessionId: tab?.terminalSessionId ?? null,
executionId: tab?.purpose.type === 'project-action' ? tab.purpose.executionId : null,
};
}, [
ensureDirectory,
executionDirectoryFor,
getActionTab,
setActiveTab,
setTabIconKey,
setTabLabel,
setTabPurpose,
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(executionDirectoryFor(action), action.id);
const existingRun = projectActionRuns[runKey];
if (existingRun && existingRun.status === 'running') {
return;
}
if (startingRunKeysRef.current.has(runKey)) return;
startingRunKeysRef.current.add(runKey);
let requestedExecution: { directory: string; tabId: string; id: string } | null = null;
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 launchContextHostDirectory = contextHostDirectoryRef.current || normalizedDirectory;
const { executionDirectory, key, tabId } = await getOrCreateActionTab(discovered);
const normalizedCommand = normalizeProjectActionCommand(discovered.command);
if (!normalizedCommand) {
throw new Error(t('projectActions.error.failedToRunAction'));
}
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;
if (terminal.listSessions) {
const currentTab = getActionTab(executionDirectory, discovered.id);
if (currentTab?.purpose.type === 'project-action' && currentTab.purpose.executionId === null) {
const result = await reconcileTerminalSessionAuthority(terminal, executionDirectory, {
captureStartedActionMutationRevisions,
});
if (result) {
reconcileServerSessions(executionDirectory, result.sessions, {
startedActionMutationRevisions: result.startedActionMutationRevisions,
});
}
}
}
const priorTab = getActionTab(executionDirectory, discovered.id);
let activeSessionId: string;
let adoptedExecutionId: string;
if (priorTab?.lifecycle === 'running' && priorTab.terminalSessionId
&& priorTab.purpose.type === 'project-action' && priorTab.purpose.executionId) {
activeSessionId = priorTab.terminalSessionId;
adoptedExecutionId = priorTab.purpose.executionId;
} else {
const priorExecutionId = priorTab?.purpose.type === 'project-action' ? priorTab.purpose.executionId : null;
if (priorExecutionId) clearExecutionUi(executionDirectory, discovered.id, priorExecutionId);
const requestedExecutionId = allocateActionExecution(executionDirectory, tabId, discovered.id);
if (!requestedExecutionId) throw new Error(t('projectActions.error.failedToCreateTerminalSession'));
requestedExecution = { directory: executionDirectory, tabId, id: requestedExecutionId };
setConnecting(executionDirectory, tabId, true, { expectedExecutionId: requestedExecutionId });
const created = await createProjectActionTerminalSession({
terminal,
createOptions: {
cwd: executionDirectory,
shell: terminalShell,
loginShell: terminalLoginShell,
themeMode: currentTheme.metadata.variant === 'light' ? 'light' : 'dark',
terminalBackground: currentTheme.colors.surface.background,
terminalForeground: currentTheme.colors.syntax.base.foreground,
},
command: normalizedCommand,
isRunStillExpected: () => matchesActionExecution(executionDirectory, tabId, requestedExecutionId),
purpose: { type: 'project-action', actionId: discovered.id, executionId: requestedExecutionId },
});
if (!matchesActionExecution(executionDirectory, tabId, requestedExecutionId)) {
if (created.sessionId === requestedExecutionId) await terminal.close(created.sessionId).catch(() => undefined);
return;
}
adoptedExecutionId = created.purpose?.type === 'project-action' ? created.purpose.executionId : requestedExecutionId;
activeSessionId = created.sessionId;
setTabPurpose(executionDirectory, tabId, { type: 'project-action', actionId: discovered.id, executionId: adoptedExecutionId });
setTabSessionId(executionDirectory, tabId, activeSessionId, { expectedExecutionId: adoptedExecutionId });
setConnecting(executionDirectory, tabId, false, { expectedExecutionId: adoptedExecutionId });
}
if (revealTerminal && launchContextHostDirectory) {
revealProjectActionTerminal(launchContextHostDirectory, executionDirectory);
}
urlWatchByRunKeyRef.current[key] = {
hostDirectory: launchContextHostDirectory,
directory: executionDirectory,
tabId,
actionId: discovered.id,
executionId: adoptedExecutionId,
lastSeenChunkId: null,
openedUrl: Boolean(desktopForwardUrl) || Boolean(manualOpenUrl) || hasCustomOpenUrl,
tail: '',
openInPreview: discovered.id === AUTO_DISCOVER_ACTION_ID,
announced: [],
offering: false,
};
const executionStateKey = executionKey(executionDirectory, discovered.id, adoptedExecutionId);
setConnecting(executionDirectory, tabId, true, { expectedExecutionId: adoptedExecutionId });
const subscription = terminal.connect(
activeSessionId,
{ onEvent: (event) => {
if (!matchesActionExecution(executionDirectory, tabId, adoptedExecutionId)) return;
if (event.purpose?.type === 'project-action' && event.purpose.executionId !== adoptedExecutionId) return;
if (event.type === 'snapshot') {
useTerminalStore.getState().replaceBuffer(executionDirectory, tabId, event.data ?? '', event.sequence ?? 0, terminalSnapshotSize(event));
useTerminalStore.getState().setConnecting(executionDirectory, tabId, false, { expectedExecutionId: adoptedExecutionId });
if (event.purpose?.type === 'project-action') {
useTerminalStore.getState().setTabPurpose(executionDirectory, tabId, { type: 'project-action', actionId: event.purpose.actionId, executionId: event.purpose.executionId });
}
if (event.status === 'running') {
useTerminalStore.getState().setTabLifecycle(executionDirectory, tabId, 'running', { expectedExecutionId: adoptedExecutionId });
}
if (event.status === 'exited') {
useTerminalStore.getState().setTabLifecycle(executionDirectory, tabId, 'exited', { expectedExecutionId: adoptedExecutionId });
useTerminalStore.getState().setTabPurpose(executionDirectory, tabId, { type: 'project-action', actionId: discovered.id, executionId: null });
clearExecutionUi(executionDirectory, discovered.id, adoptedExecutionId);
}
}
const output = event.type === 'data' ? (event.data ?? '') : '';
if (output) {
useTerminalStore.getState().appendToBuffer(executionDirectory, tabId, output, event.sequence, event.replayData);
}
if (event.type === 'exit') {
useTerminalStore.getState().setTabLifecycle(executionDirectory, tabId, 'exited', { expectedExecutionId: adoptedExecutionId });
useTerminalStore.getState().setConnecting(executionDirectory, tabId, false, { expectedExecutionId: adoptedExecutionId });
useTerminalStore.getState().setTabPurpose(executionDirectory, tabId, { type: 'project-action', actionId: discovered.id, executionId: null });
clearExecutionUi(executionDirectory, discovered.id, adoptedExecutionId);
}
}, onError: (_error, fatal) => {
if (!matchesActionExecution(executionDirectory, tabId, adoptedExecutionId)) return;
useTerminalStore.getState().setConnecting(executionDirectory, tabId, false, { expectedExecutionId: adoptedExecutionId });
if (fatal) {
useTerminalStore.getState().setTabLifecycle(executionDirectory, tabId, 'exited', { expectedExecutionId: adoptedExecutionId });
useTerminalStore.getState().setTabSessionId(executionDirectory, tabId, null, { expectedExecutionId: adoptedExecutionId });
useTerminalStore.getState().setTabPurpose(executionDirectory, tabId, { type: 'project-action', actionId: discovered.id, executionId: null });
clearExecutionUi(executionDirectory, discovered.id, adoptedExecutionId);
}
} },
);
if (!matchesActionExecution(executionDirectory, tabId, adoptedExecutionId)) {
subscription.close();
return;
}
streamCleanupByRunKeyRef.current[executionStateKey]?.();
streamCleanupByRunKeyRef.current[executionStateKey] = subscription.close;
window.clearTimeout(previewWaitTimeoutByRunKeyRef.current[executionStateKey]);
delete previewWaitTimeoutByRunKeyRef.current[executionStateKey];
if (discovered.id === AUTO_DISCOVER_ACTION_ID && !manualOpenUrl) {
setWaitingForPreviewByExecution((current) => ({ ...current, [executionStateKey]: true }));
previewWaitTimeoutByRunKeyRef.current[executionStateKey] = window.setTimeout(() => {
delete previewWaitTimeoutByRunKeyRef.current[executionStateKey];
const watch = urlWatchByRunKeyRef.current[key];
if (!watch || watch.executionId !== adoptedExecutionId || watch.openedUrl || watch.offering) {
return;
}
if (!matchesActionExecution(executionDirectory, tabId, adoptedExecutionId)) {
return;
}
setWaitingForPreviewByExecution((current) => {
if (!current[executionStateKey]) return current;
const next = { ...current };
delete next[executionStateKey];
return next;
});
useTerminalStore.getState().setActiveTab(executionDirectory, tabId);
revealProjectActionTerminal(watch.hostDirectory, executionDirectory);
}, AUTO_DISCOVER_PREVIEW_WAIT_TIMEOUT_MS);
}
if (desktopForwardUrl) {
setTabPreviewUrl(executionDirectory, tabId, null, { locked: true, expectedExecutionId: adoptedExecutionId });
void openExternal(desktopForwardUrl);
toast.success(t('projectActions.toast.openedForwardedUrl'));
} else if (manualOpenUrl) {
setTabPreviewUrl(executionDirectory, tabId, manualOpenUrl, { locked: true, autoOpened: true, expectedExecutionId: adoptedExecutionId });
openContextPreview(launchContextHostDirectory, manualOpenUrl);
toast.success(t('projectActions.toast.openedActionUrl'));
} else if (hasCustomOpenUrl) {
setTabPreviewUrl(executionDirectory, tabId, null, { locked: true, expectedExecutionId: adoptedExecutionId });
toast.error(t('projectActions.error.invalidCustomUrlFormat'));
} else if (hasDesktopForwardSelection) {
setTabPreviewUrl(executionDirectory, tabId, null, { locked: true, expectedExecutionId: adoptedExecutionId });
toast.error(t('projectActions.error.selectedDesktopSshForwardUnavailable'));
} else {
setTabPreviewUrl(executionDirectory, tabId, null, { locked: false, autoOpened: false, expectedExecutionId: adoptedExecutionId });
}
} catch (error) {
if (requestedExecution && matchesActionExecution(requestedExecution.directory, requestedExecution.tabId, requestedExecution.id)) {
const { directory: failedDirectory, tabId: failedTabId, id } = requestedExecution;
clearExecutionUi(failedDirectory, action.id, id);
setTabLifecycle(failedDirectory, failedTabId, 'exited', { expectedExecutionId: id });
setTabPurpose(failedDirectory, failedTabId, { type: 'project-action', actionId: action.id, executionId: null });
}
if (error instanceof Error && error.message === 'PROJECT_ACTION_RUN_CANCELLED') {
return;
}
if (error instanceof Error && (error.message === 'COMMAND_MODE_UNSUPPORTED' || error.message === 'PROJECT_ACTION_PURPOSE_UNSUPPORTED')) {
toast.error(t('projectActions.error.failedToCreateTerminalSession'));
return;
}
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,
contextHostDirectoryRef,
desktopSshInstances,
getOrCreateActionTab,
allowMobile,
isMobile,
isDesktopShellApp,
normalizedDirectory,
terminalLoginShell,
terminalShell,
openExternal,
openContextPreview,
projectActionRuns,
revealProjectActionTerminal,
runtime.isVSCode,
executionDirectoryFor,
matchesActionExecution,
clearExecutionUi,
executionKey,
getActionTab,
reconcileServerSessions,
allocateActionExecution,
captureStartedActionMutationRevisions,
setConnecting,
setTabLifecycle,
setTabPurpose,
setTabPreviewUrl,
setTabSessionId,
stableProjectRef?.id,
t,
terminal,
]);
const stopAction = React.useCallback(async (action: OpenChamberProjectAction) => {
const runKey = toProjectActionRunKey(executionDirectoryFor(action), action.id);
const activeRun = projectActionRuns[runKey];
if (!activeRun) {
return;
}
await stopProjectActionTerminalSession({
terminal,
sessionId: activeRun.sessionId,
isExecutionStillCurrent: () => matchesActionExecution(activeRun.directory, activeRun.tabId, activeRun.executionId),
markStopping: () => {
setTabLifecycle(activeRun.directory, activeRun.tabId, 'stopping', { expectedExecutionId: activeRun.executionId });
},
restoreRunning: () => {
setTabLifecycle(activeRun.directory, activeRun.tabId, 'running', { expectedExecutionId: activeRun.executionId });
},
clearSession: () => {
setTabSessionId(activeRun.directory, activeRun.tabId, null, { expectedExecutionId: activeRun.executionId });
},
finalizeExit: () => {
setTabLifecycle(activeRun.directory, activeRun.tabId, 'exited', { expectedExecutionId: activeRun.executionId });
setTabPurpose(activeRun.directory, activeRun.tabId, { type: 'project-action', actionId: activeRun.actionId, executionId: null });
clearExecutionUi(activeRun.directory, activeRun.actionId, activeRun.executionId);
},
});
}, [clearExecutionUi, executionDirectoryFor, matchesActionExecution, projectActionRuns, setTabLifecycle, setTabPurpose, setTabSessionId, terminal]);
const handlePrimaryClick = React.useCallback(() => {
const action = selectedAction ?? displayActions[0];
if (!action) {
return;
}
const runKey = toProjectActionRunKey(executionDirectoryFor(action), action.id);
const runningEntry = projectActionRuns[runKey];
if (runningEntry?.status === 'stopping') {
return;
}
if (runningEntry) {
void stopAction(action);
return;
}
void runAction(action);
}, [displayActions, executionDirectoryFor, runAction, projectActionRuns, selectedAction, stopAction]);
// A shared action comes from the repo: the first time one would run, the
// trust prompt shows the team's commands; "not this time" runs nothing.
const runActionWithTrust = React.useCallback(async (action: OpenChamberProjectAction) => {
if (action.source === 'shared' && stableProjectRef) {
const setup = setupRef.current?.trust.trusted ? setupRef.current : await getProjectSetup(stableProjectRef);
setupRef.current = setup;
if (!(await ensureSharedSetupTrusted(stableProjectRef, setup))) {
return;
}
setupRef.current = { ...setup, trust: { ...setup.trust, trusted: true } };
}
await runAction(action);
}, [runAction, stableProjectRef]);
const handleSelectAction = React.useCallback((action: OpenChamberProjectAction, toggleStopIfRunning = false) => {
setSelectedActionId(action.id);
if (!toggleStopIfRunning) {
void runActionWithTrust(action);
return;
}
const runKey = toProjectActionRunKey(executionDirectoryFor(action), action.id);
const runningEntry = projectActionRuns[runKey];
if (runningEntry?.status === 'stopping') {
return;
}
if (runningEntry) {
void stopAction(action);
return;
}
void runActionWithTrust(action);
}, [executionDirectoryFor, runActionWithTrust, 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(executionDirectoryFor(previewAction), previewAction.id)] : null;
const selectedRunPreviewUrl = useTerminalStore((state) => {
if (!previewRun) return null;
return state.getDirectoryState(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 selectedIconName = resolveProjectActionIconName(resolvedSelected);
const selectedRunKey = toProjectActionRunKey(executionDirectoryFor(resolvedSelected), 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 iconName = resolveProjectActionIconName(entry);
const runKey = toProjectActionRunKey(executionDirectoryFor(entry), 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>
{entry.source === 'shared' ? (
<span className="shrink-0 typography-micro px-1 rounded leading-none pb-px text-muted-foreground bg-[var(--surface-subtle)]">
{t('projectActions.menu.sharedBadge')}
</span>
) : null}
{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 iconName = resolveProjectActionIconName(entry);
const runKey = toProjectActionRunKey(executionDirectoryFor(entry), 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>
{entry.source === 'shared' ? (
<span className="shrink-0 typography-micro px-1 rounded leading-none pb-px text-muted-foreground bg-[var(--surface-subtle)]">
{t('projectActions.menu.sharedBadge')}
</span>
) : null}
{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>
);
};