Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(project-settings): per-project launchCmd + defaultAgentId at every launch site
enes441222e0f2b8
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex b86446ee0..b4f0e573c 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -309,7 +309,6 @@ import { pushSessionRename } from '../lib/sessionRename'import { oneLine } from '@shared/one-line'import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'import { useSettings } from '../state/settings'-import { launchableDefaultAgent } from '../state/agentAvailability'import { activePermissionMode } from '../state/permissionMode'import { useContextWindow } from '../state/contextWindow'import { useSessionNaming } from '../state/sessionNaming'@@ -390,6 +389,7 @@ import {reparentNode,selectedRootIds,resolveNewNodeAccount,+ resolveNewNodeAgent,accountsForProject,sshAccountsHint,ungroupNodes,@@ -3502,7 +3502,10 @@ export function Canvas() {prompt,undefined,account,- activePermissionMode()+ activePermissionMode(),+ // The owning project, for its own `.nodeterm/settings.json` launch command — the same+ // project the account/cwd above are resolved from.+ activeProjectId)])markDirty()@@ -3702,7 +3705,10 @@ export function Canvas() {initialPrompt,project?.ssh,account,- activePermissionMode(agentId)+ activePermissionMode(agentId),+ // Same funnel as the account above: the active project owns the node, so its own+ // `.nodeterm/settings.json` launch command layers over the global one.+ activeProjectId)return [...ns, groupId ? parentInto(node, groupId) : node]})@@ -3722,7 +3728,13 @@ export function Canvas() {const at = spawnTeamDialog?.atsetSpawnTeamDialog(null)addAgentNode(- useSettings.getState().settings.defaultAgent ?? 'claude',+ // No explicit pick here — the conductor opens on whatever this project calls its default+ // agent (`.nodeterm/settings.json` → agents.defaultAgentId), else the global one.+ resolveNewNodeAgent(+ undefined,+ useProjects.getState().activeProjectId,+ useSettings.getState().settings+ ),at,undefined,undefined,@@ -3774,9 +3786,16 @@ export function Canvas() {addTerminal()} else if (k === 'c' && e.shiftKey) {e.preventDefault()- // launchableDefaultAgent, not the raw setting: a default naming a since-removed custom- // agent would otherwise type its bare `custom:<uuid>` id into the new node's shell.- addAgentNode(launchableDefaultAgent(useSettings.getState().settings))+ // resolveNewNodeAgent, not the raw setting: this project's own default agent wins, and a+ // default naming a since-removed custom agent would otherwise type its bare+ // `custom:<uuid>` id into the new node's shell (it guards that, like launchableDefaultAgent).+ addAgentNode(+ resolveNewNodeAgent(+ undefined,+ useProjects.getState().activeProjectId,+ useSettings.getState().settings+ )+ )}}window.addEventListener('keydown', onKey)@@ -5154,7 +5173,9 @@ export function Canvas() {...copy.data,// Built fresh here (never re-wrapping a persisted command), so it is flagged exactly once.initialCommand: withPermissionMode(- `${claudeLaunchCommand()} -r ${originalId}`,+ // The branched copy stays in the project it was branched from, so it comes back through+ // that project's wrapper exactly like the source node did.+ `${claudeLaunchCommand(useProjects.getState().activeProjectId)} -r ${originalId}`,'claude',activePermissionMode()),@@ -5233,7 +5254,10 @@ export function Canvas() {source.data.accountId,// The mode belongs to the node being OPENED, so it is gated on the TARGET agent — a// handoff into grok must not inherit claude's version gate.- activePermissionMode(targetAgentId)+ activePermissionMode(targetAgentId),+ // The transfer target lands in the active project's canvas, so that project's launch+ // command applies to it — the same project `projectSsh` was just resolved from.+ activeProjectId)node.selected = trueconst placed = placeSpawned(node, at ?? besideNode(source))@@ -6418,7 +6442,9 @@ export function Canvas() {project,useSettings.getState().settings.claudeAccounts),- activePermissionMode(choice.agentId)+ activePermissionMode(choice.agentId),+ // Board-created nodes belong to the active project like any other.+ activeProjectId)setNodes((ns) => [...ns, node])const board = project?.kanban ?? seedBoard@@ -6536,10 +6562,22 @@ export function Canvas() {focusNodeById(boundNodeId)return}- // No live node — open a resume node in the active project, using the transcript's cwd.- const cmd = resumeCommand('claude', hit.sessionId, false, agentLaunchOverride('claude'))+ // No live node — open a resume node in the active project, using the transcript's cwd. The+ // resume line goes through that project's launch command, like every other launch it owns.+ const activeId = useProjects.getState().activeProjectId+ const cmd = resumeCommand('claude', hit.sessionId, false, agentLaunchOverride('claude', activeId))if (!cmd) return- const node = createAgentNode('claude', nodesRef.current.length, hit.cwd, viewCenter())+ const node = createAgentNode(+ 'claude',+ nodesRef.current.length,+ hit.cwd,+ viewCenter(),+ undefined,+ undefined,+ undefined,+ undefined,+ activeId+ )// The resume command replaces (never wraps) the factory's command, so it is flagged once.node.data = {...node.data,@@ -7149,7 +7187,10 @@ export function Canvas() {args.prompt,sshFor(agentCwd),account,- activePermissionMode(agentId)+ activePermissionMode(agentId),+ // Same project the account funnel above resolves from: the canvas the verb runs+ // on, whose `.nodeterm/settings.json` launch command applies to what it opens.+ projStore.activeProjectId),after ?? [],undefined,@@ -7494,7 +7535,8 @@ export function Canvas() {}),sshFor(targetCwd),vAccount,- vMode+ vMode,+ vStore.activeProjectId)return armAfter({ ...node, data: { ...node.data, title: `Verify: ${lens}`, titleAuto: false } },@@ -7518,7 +7560,8 @@ export function Canvas() {}),sshFor(targetCwd),vAccount,- vMode+ vMode,+ vStore.activeProjectId)return { ...j, data: { ...j.data, title: 'Verify: verdict', titleAuto: false } }})(),@@ -7606,7 +7649,8 @@ export function Canvas() {r.prompt,sshFor(srcCwd),teamAccount,- activePermissionMode(memberAgent)+ activePermissionMode(memberAgent),+ teamStore.activeProjectId)return r.title ? { ...node, data: { ...node.data, title: r.title, titleAuto: false } } : node})diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 32bee2790..4510537b8 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -190,6 +190,21 @@ export function sshConnectionScope(conn: SshConnection): string {return sshConnectionIdForProject(activeProjectId, conn, getProject(activeProjectId)?.ssh?.server)}+/**+ * The project whose per-project settings apply to a node in THIS canvas — for the launch-command+ * layer (`agentLaunchOverride`) on relaunch, restart and wake.+ *+ * The active project, deliberately, and NOT `sshConnectionScope`'s answer: that scope is a+ * CONNECTION identity, which for a remote node attached to a foreign host is a synthetic+ * project×host attachment id (`sshAttachmentId`) rather than a project id at all — passing it here+ * would silently resolve to "no project settings" for exactly those nodes. A node only ever exists+ * in the active project's React Flow (same reasoning `sshConnectionScope` states), so the active+ * project is its owner; an SSH project's own nodes answer the same id either way.+ */+function owningProjectId(): string {+ return useProjects.getState().activeProjectId+}+/** The live ControlMaster path a remote node would run over, if any. Lets the caller tell "we will* resolve in a microtask" from "we are about to sit in the wait below" without duplicating the* lookup. Without a `conn` it answers for the active project's own connection. */@@ -2878,9 +2893,11 @@ export function TerminalNode({permissionMode: mode,model: data.agentModel,sharedIdentity: shared,- // The user's launch-command override rides the relaunch too, so a wrapper user's node- // comes back through its wrapper after a reboot — the moment env/account setup matters.- launchCmdOverride: agentLaunchOverride(agentId)+ // The launch-command override rides the relaunch too, so a wrapper user's node comes+ // back through its wrapper after a reboot — the moment env/account setup matters.+ // Scoped to the OWNING project (`owningProjectId`) so a project-level wrapper does+ // not vanish on cold restore, which is exactly where it is most needed.+ launchCmdOverride: agentLaunchOverride(agentId, owningProjectId())},// The boot-time desktop env snapshot — the same object fresh launch and the Settings// preview expand against, so a ${env:…}-referencing custom agent cold-restores with@@ -3039,9 +3056,10 @@ export function TerminalNode({sessionId: agentSessionId,permissionMode: await ensureActivePermissionMode(target),model: selectedModel ?? undefined,- // The per-builtin launch-command override rides the restart too (undefined for a custom- // target, which already owns its launchCmd) — it is a property of how the agent launches.- launchCmdOverride: agentLaunchOverride(target)+ // The launch-command override rides the restart too (the global layer is undefined for+ // a custom target, which already owns its launchCmd) — it is a property of how the+ // agent launches, so the owning project's own value applies here as well.+ launchCmdOverride: agentLaunchOverride(target, owningProjectId())},launchEnv)@@ -3157,9 +3175,9 @@ export function TerminalNode({sessionId: agentSessionId,permissionMode: await ensureActivePermissionMode(agentId),sharedIdentity: false,- // The USER's launch-command override lives on their own PATH (or is an absolute path),- // not in a generated launcher dir, so it rides the wake too.- launchCmdOverride: agentLaunchOverride(agentId)+ // The launch-command override lives on the user's own PATH (or is an absolute path),+ // not in a generated launcher dir, so it rides the wake too — project layer included.+ launchCmdOverride: agentLaunchOverride(agentId, owningProjectId())},// Same boot-time env snapshot as fresh launch / cold restore, so a wake types the same// line the node launched with (empty on browser/relay by design).diff --git a/src/renderer/state/workspace.project-launch.test.ts b/src/renderer/state/workspace.project-launch.test.tsnew file mode 100644index 000000000..c9371f442--- /dev/null+++ b/src/renderer/state/workspace.project-launch.test.ts@@ -0,0 +1,246 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import type { ProjectLaunchInfo } from '@shared/project-settings'+import {+ agentLaunchOverride,+ claudeLaunchCommand,+ createAgentNode,+ resolveNewNodeAgent,+ resetLaunchTrustAsksForTests+} from './workspace'+import { ensureProjectLaunchInfo, resetProjectLaunchInfoForTests } from './projectLaunchInfo'+import { useSettings } from './settings'+import { DEFAULT_SETTINGS, type Settings } from '@shared/types'++/**+ * The PER-PROJECT half of the launch layering (`.nodeterm/settings.json` → `agents`):+ * - `launchCmd` — this project's local doc, then its git-SHARED doc but ONLY once that family is+ * trusted, then the user's global Settings → Agents override. Scoped to the agent the project+ * names as its default, because that is exactly what the panel promises ("Overrides how the+ * default agent is launched").+ * - `defaultAgentId` — what a NON-explicit new node launches, above the global default.+ * A launch never blocks and never fails closed: no warm snapshot ⇒ byte-identical to before.+ */++const requestTrust = vi.fn(() => Promise.resolve(false))++/** Seeds the module-level launch-info cache the way Canvas warms it (one wire round trip). */+async function warmProject(projectId: string, info: ProjectLaunchInfo | null): Promise<void> {+ ;(globalThis as { window?: unknown }).window = {+ nodeTerminal: {+ projectSettings: { launchInfo: () => Promise.resolve(info) },+ projectSetup: { requestTrust }+ }+ }+ await ensureProjectLaunchInfo(projectId)+}++const info = (+ agents: ProjectLaunchInfo['resolved']['agents'],+ trustedAgents: boolean+): ProjectLaunchInfo => ({+ resolved: { setup: {}, worktree: {}, agents, terminal: {} },+ trusted: { agents: trustedAgents, shell: true }+})++const settingsWith = (patch: Partial<Settings>): void => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, ...patch } })+}++beforeEach(() => {+ resetProjectLaunchInfoForTests()+ resetLaunchTrustAsksForTests()+ requestTrust.mockClear()+ requestTrust.mockImplementation(() => Promise.resolve(false))+})++afterEach(() => {+ useSettings.setState({ settings: DEFAULT_SETTINGS })+ delete (globalThis as { window?: unknown }).window+})++describe('agentLaunchOverride — per-project launchCmd', () => {+ it('is the global override when no project is named', async () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject('p1', info({ launchCmd: { value: 'proj-wrap', source: 'local' } }, true))+ expect(agentLaunchOverride('claude')).toBe('global-wrap')+ })++ it('is the global override when the project has no warm snapshot', () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ expect(agentLaunchOverride('claude', 'p1')).toBe('global-wrap')+ })++ it('lets a project LOCAL launchCmd win over the global override', async () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject('p1', info({ launchCmd: { value: 'local-wrap', source: 'local' } }, false))+ expect(agentLaunchOverride('claude', 'p1')).toBe('local-wrap')+ // A local value is the user's own typing — never gated, so nothing is ever asked.+ expect(requestTrust).not.toHaveBeenCalled()+ })++ it('lets a TRUSTED shared launchCmd win over the global override', async () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject('p1', info({ launchCmd: { value: 'shared-wrap', source: 'shared' } }, true))+ expect(agentLaunchOverride('claude', 'p1')).toBe('shared-wrap')+ expect(requestTrust).not.toHaveBeenCalled()+ })++ it('falls PAST an untrusted shared launchCmd to the global override', async () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject('p1', info({ launchCmd: { value: 'shared-wrap', source: 'shared' } }, false))+ expect(agentLaunchOverride('claude', 'p1')).toBe('global-wrap')+ })++ it('falls through to the bare command when there is no global override either', async () => {+ await warmProject('p1', info({ launchCmd: { value: 'shared-wrap', source: 'shared' } }, false))+ expect(agentLaunchOverride('claude', 'p1')).toBeUndefined()+ expect(claudeLaunchCommand('p1')).toBe('claude')+ })++ it('asks for trust exactly ONCE per project per session, however many launches ask', async () => {+ await warmProject('p1', info({ launchCmd: { value: 'shared-wrap', source: 'shared' } }, false))+ agentLaunchOverride('claude', 'p1')+ agentLaunchOverride('claude', 'p1')+ agentLaunchOverride('claude', 'p1')+ expect(requestTrust).toHaveBeenCalledTimes(1)+ expect(requestTrust).toHaveBeenCalledWith('p1', 'agents')+ })++ it('survives a requestTrust that REJECTS — the launch line is still resolved', async () => {+ requestTrust.mockImplementation(() => Promise.reject(new Error('no handler')))+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject('p1', info({ launchCmd: { value: 'shared-wrap', source: 'shared' } }, false))+ expect(agentLaunchOverride('claude', 'p1')).toBe('global-wrap')+ await Promise.resolve()+ })++ it('never asks for trust when the project sets no shared launchCmd at all', async () => {+ await warmProject('p1', info({}, false))+ expect(agentLaunchOverride('claude', 'p1')).toBeUndefined()+ expect(requestTrust).not.toHaveBeenCalled()+ })++ it('applies only to the agent the project targets — another agent keeps the global path', async () => {+ settingsWith({ agentLaunchCommands: { codex: 'global-codex' }, defaultAgent: 'claude' })+ await warmProject('p1', info({ launchCmd: { value: 'proj-wrap', source: 'local' } }, true))+ expect(agentLaunchOverride('claude', 'p1')).toBe('proj-wrap')+ expect(agentLaunchOverride('codex', 'p1')).toBe('global-codex')+ })++ it('follows the project’s own defaultAgentId when deciding which agent it targets', async () => {+ settingsWith({ defaultAgent: 'claude' })+ await warmProject(+ 'p1',+ info(+ {+ defaultAgentId: { value: 'codex', source: 'local' },+ launchCmd: { value: 'proj-wrap', source: 'local' }+ },+ true+ )+ )+ expect(agentLaunchOverride('codex', 'p1')).toBe('proj-wrap')+ expect(agentLaunchOverride('claude', 'p1')).toBeUndefined()+ })++ it('does not ask for trust when the shared launchCmd targets another agent', async () => {+ settingsWith({ defaultAgent: 'claude' })+ await warmProject('p1', info({ launchCmd: { value: 'shared-wrap', source: 'shared' } }, false))+ expect(agentLaunchOverride('codex', 'p1')).toBeUndefined()+ expect(requestTrust).not.toHaveBeenCalled()+ })++ it('ignores a blank project launchCmd (and asks nothing for it)', async () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject('p1', info({ launchCmd: { value: ' ', source: 'shared' } }, false))+ expect(agentLaunchOverride('claude', 'p1')).toBe('global-wrap')+ expect(requestTrust).not.toHaveBeenCalled()+ })++ it('ignores a non-string launchCmd from a hostile shared document', async () => {+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })+ await warmProject(+ 'p1',+ info({ launchCmd: { value: 42 as unknown as string, source: 'shared' } }, true)+ )+ expect(agentLaunchOverride('claude', 'p1')).toBe('global-wrap')+ })+})++describe('createAgentNode — the project launch command reaches the typed line', () => {+ it('launches the project’s default agent through the project wrapper', async () => {+ await warmProject('p1', info({ launchCmd: { value: 'proj-wrap', source: 'local' } }, true))+ const node = createAgentNode(+ 'claude',+ 0,+ undefined,+ undefined,+ 'fix the bug',+ undefined,+ undefined,+ undefined,+ 'p1'+ )+ expect(node.data.initialCommand).toBe("proj-wrap 'fix the bug'")+ })++ it('stays byte-identical to today when no project id is threaded', () => {+ const node = createAgentNode('claude', 0, undefined, undefined, 'fix the bug')+ expect(node.data.initialCommand).toBe("claude 'fix the bug'")+ })+})++describe('resolveNewNodeAgent', () => {+ const settings = (patch: Partial<Settings>): Settings => ({ ...DEFAULT_SETTINGS, ...patch })++ it('never overrules an explicit pick', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: 'codex', source: 'local' } }, true))+ expect(resolveNewNodeAgent('gemini', 'p1', settings({ defaultAgent: 'claude' }))).toBe('gemini')+ })++ it('uses the project default above the global one', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: 'codex', source: 'local' } }, true))+ expect(resolveNewNodeAgent(undefined, 'p1', settings({ defaultAgent: 'claude' }))).toBe('codex')+ })++ it('accepts a shared project default without a trust grant (naming is not executing)', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: 'codex', source: 'shared' } }, false))+ expect(resolveNewNodeAgent(undefined, 'p1', settings({ defaultAgent: 'claude' }))).toBe('codex')+ })++ it('accepts a custom agent the user actually has', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: 'custom:x', source: 'local' } }, true))+ const s = settings({+ defaultAgent: 'claude',+ customAgents: [{ id: 'custom:x', label: 'X', launchCmd: 'x-cli' }] as Settings['customAgents']+ })+ expect(resolveNewNodeAgent(undefined, 'p1', s)).toBe('custom:x')+ })++ it('falls through when the project names an agent that does not exist', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: 'custom:gone', source: 'local' } }, true))+ expect(resolveNewNodeAgent(undefined, 'p1', settings({ defaultAgent: 'claude' }))).toBe('claude')+ })++ it('falls through when the project names an agent the user has DISABLED', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: 'codex', source: 'shared' } }, true))+ const s = settings({ defaultAgent: 'claude', disabledAgents: ['codex'] })+ expect(resolveNewNodeAgent(undefined, 'p1', s)).toBe('claude')+ })++ it('falls through on a non-string / blank id from a hostile document', async () => {+ await warmProject('p1', info({ defaultAgentId: { value: ' ', source: 'shared' } }, true))+ expect(resolveNewNodeAgent(undefined, 'p1', settings({ defaultAgent: 'claude' }))).toBe('claude')+ })++ it('is the global default when there is no project (or no snapshot)', () => {+ expect(resolveNewNodeAgent(undefined, undefined, settings({ defaultAgent: 'gemini' }))).toBe('gemini')+ expect(resolveNewNodeAgent(undefined, 'cold', settings({ defaultAgent: 'gemini' }))).toBe('gemini')+ })++ it('guards a global default whose custom agent was since removed', () => {+ expect(+ resolveNewNodeAgent(undefined, undefined, settings({ defaultAgent: 'custom:gone' }))+ ).toBe('claude')+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex bdc748dac..1f3af96f1 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1,11 +1,21 @@import type { Node } from '@xyflow/react'-import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, PendingLaunch, Project } from '@shared/types'+import type {+ CanvasMutation,+ CanvasNodeState,+ ClaudeAccount,+ NodeKind,+ PendingLaunch,+ Project,+ Settings+} from '@shared/types'import type { AgentId, AgentPermissionMode, BuiltinAgentId } from '@shared/agents/config'import { agentConfig, supportsSessionIdFlag } from '@shared/agents/config'import { assembleLaunchCommand } from '@shared/agents/launch'import { agentEnvSnapshot } from '../lib/agentEnv'import { uuid } from '@renderer/lib/uuid'import { claudeCliCapsNow } from './permissionMode'+import { projectLaunchInfoNow } from './projectLaunchInfo'+import { isAgentEnabled, launchableDefaultAgent } from './agentAvailability'import { codexSharedIdentity } from './codexIdentity'import { sshHostKey } from '@shared/ssh'import { useSettings } from './settings'@@ -293,32 +303,134 @@ export function createSshTerminalNode(}}-/**- * The user's launch-command override for a builtin agent (Settings → Agents → Launch commands),- * or undefined when unset/blank. This is the ONE place the setting is read; every launch site- * (new node, cold restore, in-place restart, hibernation wake, transcript resume) either calls- * this or receives its result — shared/agents/config.ts cannot read settings (layering), so the- * renderer resolves the override and passes it down (`resumeCommand`'s `base` param).- *- * Trusted verbatim, like a custom agent's `launchCmd`: it comes from the local user's own- * settings.json and is typed into their own pane. Custom agents index past the builtin-keyed map- * to undefined — they already own their launchCmd.- */-export function agentLaunchOverride(agentId: AgentId): string | undefined {+/** The user's OWN global launch-command override, with no project layered over it. */+function globalLaunchOverride(agentId: AgentId): string | undefined {const raw = useSettings.getState().settings.agentLaunchCommands?.[agentId as BuiltinAgentId]const cmd = typeof raw === 'string' ? raw.trim() : ''return cmd || undefined}+/**+ * Projects whose SHARED `agents` family we have already asked the human to trust this session.+ * The ask is fire-and-forget from a synchronous launch path (a launch is never blocked on it), so+ * without this every single launch in an untrusted project would re-raise the dialog. Once per+ * project is enough: an approval makes main fire `projectSettings.onTrustChanged`, Canvas+ * invalidates that project's launch-info cache, and the NEXT launch reads the fresh verdict and+ * picks the shared launchCmd up on its own.+ */+const agentsTrustAsked = new Set<string>()++/** Test seam: forget which projects have already been asked (see `agentsTrustAsked`). */+export function resetLaunchTrustAsksForTests(): void {+ agentsTrustAsked.clear()+}++/** Raise the `agents` trust prompt for a project, at most once per project per session. Never+ * awaited and never allowed to throw: this runs inside a synchronous launch resolution, and the+ * answer (if any) arrives via the trust-changed invalidation, not via this call. */+function askAgentsTrustOnce(projectId: string): void {+ if (agentsTrustAsked.has(projectId)) return+ agentsTrustAsked.add(projectId)+ try {+ // The preload leg REJECTS when the main handler throws (the ws-bridge leg maps that to false),+ // so the `.catch` is load-bearing — an unhandled rejection here would surface as a renderer+ // error on a path whose whole contract is "the launch does not care about the answer".+ void window.nodeTerminal?.projectSetup?.requestTrust(projectId, 'agents').catch(() => {})+ } catch {+ // No bridge leg at all (older relay host, a stub) — the launch proceeds on the global value.+ }+}++/**+ * The launch-command override for an agent, or undefined when nothing overrides the bare CLI.+ * This is the ONE place launch commands are read; every launch site (new node, cold restore,+ * in-place restart, hibernation wake, transcript resume) either calls this or receives its result+ * — shared/agents/config.ts cannot read settings (layering), so the renderer resolves the override+ * and passes it down (`resumeCommand`'s `base` param).+ *+ * Three layers, most specific first, with `projectId` naming the project that OWNS the node:+ * 1. the project's LOCAL `.nodeterm/settings.json` `agents.launchCmd` — this machine's own file,+ * the user's own typing, never gated;+ * 2. the project's git-SHARED `agents.launchCmd`, but ONLY while that family is trusted at this+ * location. Falling PAST an untrusted one raises the trust prompt (once per project, see+ * `askAgentsTrustOnce`) and resolves on the layer below meanwhile — a launch is never blocked,+ * never delayed, and never runs a shared command the human has not seen;+ * 3. the user's global Settings → Agents → Launch commands entry (builtin-keyed: custom agents+ * index past it to undefined — they already own their launchCmd).+ *+ * SCOPE: the project's launchCmd applies to the agent that project TARGETS — the panel's own copy+ * is "Overrides how the default agent is launched", and the family holds one launchCmd, not one+ * per agent id. So it is used only when `agentId` is the project's effective default+ * (`resolveNewNodeAgent`); every other agent resolves on the global layer, exactly as before.+ *+ * Fails OPEN in the ordinary sense: no project id, or no warm snapshot for it+ * (`projectLaunchInfoNow` is synchronous by design — see its module doc), resolves layer 3 alone,+ * byte-identical to the behavior before per-project settings existed.+ */+export function agentLaunchOverride(agentId: AgentId, projectId?: string): string | undefined {+ const global = globalLaunchOverride(agentId)+ if (!projectId) return global+ const info = projectLaunchInfoNow(projectId)+ if (!info) return global+ const entry = info.resolved.agents.launchCmd+ if (!entry) return global+ // Scope check BEFORE anything else: an agent this project does not target consumes nothing here,+ // so it must not even raise a trust prompt about a value it would never use.+ if (agentId !== resolveNewNodeAgent(undefined, projectId, useSettings.getState().settings)) {+ return global+ }+ // `.nodeterm/settings.json` is hand-editable, git-shared, hostile input (see @shared/project-settings):+ // a non-string that slipped through is simply not a launch command.+ const cmd = typeof entry.value === 'string' ? entry.value.trim() : ''+ if (!cmd) return global+ if (entry.source === 'local') return cmd+ // NOTE (carried from Task 2's review): the trust-changed invalidation this ask relies on is+ // keyed by projectId while the grant itself is keyed by LOCATION — two projects pointing at the+ // same folder each keep their own cached verdict, so the sibling stays cold until its own+ // refresh. Known and deliberate; the cost is one extra prompt, never a wrong grant.+ if (info.trusted.agents) return cmd+ askAgentsTrustOnce(projectId)+ return global+}+/*** Command that launches Claude Code. Detection works via hooks installed globally in* ~/.claude/settings.json (gated by NODETERM_* env that the PTY manager sets), so a plain* `claude` is enough — which is also why an override wrapper (account switchers etc.) is safe* here: hooks identify the session whatever the launch line was, as long as the wrapper ends up* exec-ing the real CLI. Append `-r <id>` to resume a specific session (used by Branch).+ * `projectId` layers that project's own launchCmd over the global one (`agentLaunchOverride`).+ */+export function claudeLaunchCommand(projectId?: string): string {+ return agentLaunchOverride('claude', projectId) ?? 'claude'+}++/**+ * The agent a NEW node launches: an explicit pick always wins, then the project's own+ * `agents.defaultAgentId`, then the global default.+ *+ * The project value is VALIDATED against what this machine can actually launch — a known builtin,+ * or a custom agent the user still has — and against `disabledAgents`: `.nodeterm/settings.json`+ * is git-shared and hand-editable, so it may name an agent that was removed, never existed, or+ * that this user deliberately switched off, and none of those may become the id typed into a+ * shell (`resolveAgent`'s unknown-id fallback launches the id itself — the same failure+ * `launchableDefaultAgent` exists to prevent for the global setting).+ *+ * Deliberately NOT trust-gated: naming which of the user's own installed agents to open is not+ * executable content (`projectTrustContent('agents', …)` hashes launchCmd + env, not this), and+ * every id it can select resolves to a command the user already configured themselves.*/-export function claudeLaunchCommand(): string {- return agentLaunchOverride('claude') ?? 'claude'+export function resolveNewNodeAgent(+ explicit: AgentId | undefined,+ projectId: string | undefined,+ settings: Settings+): AgentId {+ if (explicit) return explicit+ const raw = projectId ? projectLaunchInfoNow(projectId)?.resolved.agents.defaultAgentId : undefined+ const id = typeof raw?.value === 'string' ? raw.value.trim() : ''+ const known = !!id && (!!agentConfig(id) || settings.customAgents.some((c) => c.id === id))+ if (known && isAgentEnabled(settings, id)) return id+ return launchableDefaultAgent(settings)}/** Fallback color for custom / unknown agents that have no config-provided color. */@@ -393,14 +505,16 @@ export function createAgentNode(initialPrompt?: string,ssh?: Project['ssh'],accountId?: string,- permissionMode?: AgentPermissionMode+ permissionMode?: AgentPermissionMode,+ projectId?: string): CanvasNode {const { label, color } = resolveAgent(agentId)- // A per-builtin launch-command override (Settings -> Agents -> Launch commands) replaces the bare- // CLI in the assembled command. Threaded into the shared assembler below as `launchCmdOverride`- // so fresh launch, cold-restore resume and in-place restart all pick it up identically. Custom- // agents already own their `launchCmd`, so the helper returns undefined for them.- const launchCmdOverride = agentLaunchOverride(agentId)+ // The launch-command override (this project's `.nodeterm/settings.json` first, then Settings →+ // Agents → Launch commands — see `agentLaunchOverride`) replaces the bare CLI in the assembled+ // command. Threaded into the shared assembler below as `launchCmdOverride` so fresh launch,+ // cold-restore resume and in-place restart all pick it up identically. Custom agents already own+ // their `launchCmd`, so the global layer returns undefined for them.+ const launchCmdOverride = agentLaunchOverride(agentId, projectId)// The session id is DECIDED here rather than learned from a hook later, so this node always has// something to resume with — see SESSION_ID_CAPABLE for the failure this closes. `uuid()` (not// crypto.randomUUID) because the Server Edition serves plain HTTP on a LAN, where randomUUID is