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(agents): reopen sessions as variants
Darren Kattan33951a7f8d86
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a2b7c1196..b8d9ff0b6 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -143,6 +143,7 @@ import {type AddHandlers} from '../lib/addMenuSpec'import { transferConversationItems } from '../lib/transferItems'+import { reopenVariants } from '../lib/reopenVariants'import { viewportAtZoom1 } from '../lib/zoomReset'import { isSpaceRelease, spacePanKeydown } from '../lib/spacePan'import { UpdateCard } from '../components/UpdateCard'@@ -557,7 +558,7 @@ const minimapNodeColor = (n: Node): string =>* restart on the strength of the wider one would get a row whose closure refuses every click.* Anything that is not a terminal (a sticky, an editor) is undefined, which `restartEligibility`* reads as `not-resumable`. */-const restartAgentIdOf = (n: Node | undefined): string | undefined =>+const restartAgentIdOf = (n: Node | undefined): AgentId | undefined =>!n || n.type !== 'terminal' ? undefined : createdAgentId(n.data)/** One canvas node as a board card, or null when this kind is not a card at all (a group frame, an@@ -4640,12 +4641,13 @@ export function Canvas() {// time, so a stale menu cannot force a restart onto a session that just went busy); all that is// left here is telling the user how it went. Up to ~6s of exit polling plus the echo-verified// resume line, hence the await before the notice.- const restartAgentNode = useCallback(async (nodeId: string) => {+ const restartAgentNode = useCallback(async (nodeId: string, targetAgentId?: AgentId) => {const fn = agentRestartFn(nodeId)if (!fn) return // node unmounted between opening the menu and clicking+ const action = targetAgentId ? 'Reopen' : 'Restart'let outcome: RestartOutcometry {- outcome = await fn()+ outcome = await fn(targetAgentId)} catch {// The transport under the restart threw (a relay socket still CONNECTING rejects the very// first write). Unhandled, this rejection made the action a silent no-op — the user clicked@@ -4653,15 +4655,39 @@ export function Canvas() {// the message sends them to look rather than claiming either.setNotice({kind: 'error',- text: 'Restart failed: this session could not be reached. Check the pane before retrying.'+ text: `${action} failed: this session could not be reached. Check the pane before retrying.`})return}+ if (outcome === 'restarted' && targetAgentId) {+ // The pane now runs the target variant. Persist that identity so its icon/capabilities and+ // every later plain Restart describe what is actually in the pane. The provider session id+ // stays unchanged, so choosing the original variant later reverses this cleanly.+ setNodes((ns) =>+ ns.map((n) =>+ n.id === nodeId && n.type === 'terminal'+ ? { ...n, data: { ...n.data, agentId: targetAgentId } }+ : n+ )+ )+ markDirty()+ }+ const targetLabel =+ targetAgentId == null+ ? undefined+ : (agentConfig(targetAgentId)?.label ??+ useSettings.getState().settings.customAgents.find((c) => c.id === targetAgentId)?.label ??+ targetAgentId)// 'info' fades itself out; anything that did NOT restart is left on screen to be read and// dismissed — the pane is untouched either way (nothing is ever killed).setNotice(outcome === 'restarted'- ? { kind: 'info', text: 'Agent restarted — conversation resumed.' }+ ? {+ kind: 'info',+ text: targetLabel+ ? `Session reopened as ${targetLabel} — conversation resumed.`+ : 'Agent restarted — conversation resumed.'+ }: outcome === 'exit-timeout'? {kind: 'error',@@ -4670,7 +4696,7 @@ export function Canvas() {// Nothing is ever force-killed, so the pane is exactly as the CLI left it — which is// what the user has to go and look at.text:- 'Restart failed: the pane did not return to a shell in time, so the CLI was not ' ++ `${action} failed: the pane did not return to a shell in time, so the CLI was not ` +'relaunched. Nothing was killed — check the pane.'}: {@@ -4682,12 +4708,12 @@ export function Canvas() {// know when the CLI has quit), or a restart of this node was already in flight (the// per-node action and the bulk one can reach the same node).text:- 'Restart skipped: this session is busy, already restarting, not attached ' ++ `${action} skipped: this session is busy, already restarting, not attached ` +'(closed, ended, or nothing to resume), or its pane cannot be watched without ' +'persistent tmux sessions. Nothing was written to the pane.'})- }, [])+ }, [setNodes, markDirty])// Who the bulk restart would act on, right now: the ACTIVE project's canvas (nodesRef holds// exactly that). Read fresh at every call — agent state and session ids arrive asynchronously.@@ -5297,7 +5323,12 @@ export function Canvas() {? (() => {const n = nodesRef.current.find((x) => x.id === ids[0])const st = useAgentStatus.getState().byId[ids[0]]- const gate = restartEligibility(restartAgentIdOf(n), st?.state, st?.sessionId)+ const sourceAgentId = restartAgentIdOf(n)+ const gate = restartEligibility(sourceAgentId, st?.state, st?.sessionId)+ const settings = useSettings.getState().settings+ const variants = sourceAgentId+ ? reopenVariants(sourceAgentId, settings.customAgents, settings.disabledAgents)+ : []// 'not-resumable' is permanent (a plain shell, opencode, a custom CLI with no exit// command) — no row at all. The other two are temporary, so the row stays and says// what to wait for instead of disappearing and teaching nothing.@@ -5324,7 +5355,27 @@ export function Canvas() {disabled: !!why,hint: why ?? 'Quits the CLI and relaunches it with --resume (same conversation).',onClick: () => void restartAgentNode(ids[0])- }+ },+ ...(variants.length+ ? ([+ {+ type: 'submenu',+ label: 'Reopen session as',+ icon: <IconSwitch />,+ children: variants.map(+ (variant): MenuItem => ({+ label: variant.label,+ icon: <AgentIcon agentId={variant.id} />,+ disabled: !!why,+ hint:+ why ??+ `Quits this CLI and resumes the same session as ${variant.label}.`,+ onClick: () => void restartAgentNode(ids[0], variant.id)+ })+ )+ }+ ] as MenuItem[])+ : [])] as MenuItem[]})(): []),diff --git a/src/renderer/lib/agentIcons.test.tsx b/src/renderer/lib/agentIcons.test.tsxnew file mode 100644index 000000000..54bd1a838--- /dev/null+++ b/src/renderer/lib/agentIcons.test.tsx@@ -0,0 +1,41 @@+import { afterEach, describe, expect, it } from 'vitest'+import { renderToStaticMarkup } from 'react-dom/server'+import {+ setCustomAgentBaseResolver,+ type AgentId,+ type BuiltinAgentId+} from '@shared/agents/config'+import { AgentIcon } from './agentIcons'++const renderIcon = (agentId: AgentId, size = 18): string =>+ renderToStaticMarkup(<AgentIcon agentId={agentId} size={size} />)++afterEach(() => setCustomAgentBaseResolver(null))++describe('AgentIcon custom-agent inheritance', () => {+ it('renders the exact base harness icon for inheriting custom agents', () => {+ const bases: BuiltinAgentId[] = ['claude', 'codex', 'gemini', 'opencode', 'grok']+ setCustomAgentBaseResolver((id) => {+ const base = id.startsWith('custom:') ? id.slice('custom:'.length) : ''+ return bases.includes(base as BuiltinAgentId) ? (base as BuiltinAgentId) : undefined+ })++ for (const base of bases) {+ expect(renderIcon(`custom:${base}`), base).toBe(renderIcon(base))+ }+ })++ it('keeps the terminal fallback for baseless custom agents', () => {+ setCustomAgentBaseResolver(() => undefined)++ const custom = renderIcon('custom:plain')+ expect(custom).not.toBe(renderIcon('claude'))+ expect(custom).not.toBe(renderIcon('grok'))+ expect(custom).toContain('<svg')+ })++ it('preserves the requested size after resolving the base icon', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:claude' ? 'claude' : undefined))+ expect(renderIcon('custom:claude', 23)).toBe(renderIcon('claude', 23))+ })+})diff --git a/src/renderer/lib/agentIcons.tsx b/src/renderer/lib/agentIcons.tsxindex 8ac1ec302..ceb00a014 100644--- a/src/renderer/lib/agentIcons.tsx+++ b/src/renderer/lib/agentIcons.tsx@@ -1,4 +1,4 @@-import type { AgentId } from '@shared/agents/config'+import { capabilityAgentId, type AgentId } from '@shared/agents/config'import { IconTerminal } from '../components/icons'import { BRAND_PULSE_CLASS, brandLogoSrc, brandPulsePlan } from './brandPulse'import { GROK_MARK_PATH, GROK_MARK_VIEWBOX } from './grokMark'@@ -59,10 +59,15 @@ export function BrandPulse({ agentId, size }: { agentId?: AgentId; size: number}export function AgentIcon({ agentId, size = 16 }: { agentId: AgentId; size?: number }): React.JSX.Element {- if (agentId === 'grok') return <GrokMark size={size} />- // `brandLogoSrc`, not `AGENT_LOGO[agentId]`: the id can be anything a hand-edited project.json- // says, and a prototype key ('constructor') would hand back a Function as the image source.- const src = brandLogoSrc(agentId)+ // A custom agent with `baseAgent` speaks that harness's protocol and should carry its visual+ // identity too. The renderer registers a live custom-id resolver at boot, so settings edits are+ // reflected on the next render without duplicating custom-agent lookup logic in every menu.+ const iconAgentId = capabilityAgentId(agentId)+ if (iconAgentId === 'grok') return <GrokMark size={size} />+ // `brandLogoSrc`, not `AGENT_LOGO[iconAgentId]`: the id can be anything a hand-edited+ // project.json says, and a prototype key ('constructor') would hand back a Function as the image+ // source.+ const src = brandLogoSrc(iconAgentId)if (src) {return <img src={src} width={size} height={size} alt="" style={{ display: 'block' }} />}diff --git a/src/renderer/lib/reopenVariants.test.ts b/src/renderer/lib/reopenVariants.test.tsnew file mode 100644index 000000000..8c14af63f--- /dev/null+++ b/src/renderer/lib/reopenVariants.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import type { AgentId } from "@shared/agents/config";+import type { CustomAgent } from "@shared/types";+import { reopenVariants } from "./reopenVariants";++const customs: CustomAgent[] = [+ {+ id: "custom:claude-a",+ label: "Claude A",+ launchCmd: "claude-a",+ baseAgent: "claude",+ },+ {+ id: "custom:claude-b",+ label: "Claude B",+ launchCmd: "claude-b",+ baseAgent: "claude",+ },+ {+ id: "custom:codex",+ label: "Codex Proxy",+ launchCmd: "codex-proxy",+ baseAgent: "codex",+ },+ { id: "custom:plain", label: "Plain Custom", launchCmd: "plain" },+];++describe("reopenVariants", () => {+ it("lists enabled custom variants that share a builtin source base", () => {+ expect(reopenVariants("claude", customs, [])).toEqual([+ { id: "custom:claude-a", label: "Claude A", base: "claude" },+ { id: "custom:claude-b", label: "Claude B", base: "claude" },+ ]);+ });++ it("offers the base and sibling customs for a custom source", () => {+ expect(reopenVariants("custom:claude-a" as AgentId, customs, [])).toEqual([+ { id: "claude", label: "Claude Code", base: "claude" },+ { id: "custom:claude-b", label: "Claude B", base: "claude" },+ ]);+ });++ it("excludes disabled targets without hiding other same-base variants", () => {+ expect(+ reopenVariants("custom:claude-a" as AgentId, customs, [+ "claude",+ "custom:claude-b",+ ]),+ ).toEqual([]);+ expect(reopenVariants("claude", customs, ["custom:claude-a"])).toEqual([+ { id: "custom:claude-b", label: "Claude B", base: "claude" },+ ]);+ });++ it("returns no variants for baseless or unknown custom sources", () => {+ expect(reopenVariants("custom:plain" as AgentId, customs, [])).toEqual([]);+ expect(reopenVariants("custom:missing" as AgentId, customs, [])).toEqual(+ [],+ );+ });++ it("never crosses provider session-id namespaces", () => {+ expect(reopenVariants("codex", customs, []).map((v) => v.id)).toEqual([+ "custom:codex",+ ]);+ expect(+ reopenVariants("claude", customs, []).map((v) => v.id),+ ).not.toContain("custom:codex");+ });+});diff --git a/src/renderer/lib/reopenVariants.ts b/src/renderer/lib/reopenVariants.tsnew file mode 100644index 000000000..e1e76be7e--- /dev/null+++ b/src/renderer/lib/reopenVariants.ts@@ -0,0 +1,65 @@+import {+ AGENT_CONFIG,+ BUILTIN_AGENT_IDS,+ canResume,+ type AgentId,+ type BuiltinAgentId,+} from "@shared/agents/config";+import type { CustomAgent } from "@shared/types";++/**+ * One agent a node could reopen its current session id AS, in place, by swapping the CLI that+ * resumes it. All variants share the source's base harness (`capabilityAgentId`), because a+ * provider session id is resumable only by a binary of the harness that minted it — a claude id+ * resumes under plain `claude` OR a custom `baseAgent: 'claude'` agent's binary, never under+ * `codex`. The list is the base harness itself plus every enabled custom agent inheriting it,+ * minus the node's own current agent (no "reopen as yourself").+ */+export interface ReopenVariant {+ id: AgentId;+ label: string;+ base: BuiltinAgentId;+}++/**+ * The same-base variants a node running `sourceAgentId` could reopen its session id as. Returns+ * `[]` when the source's base is not resumable (`canResume` resolves through+ * `capabilityAgentId`, so a claude-base custom passes; a baseless custom or a plain shell does+ * not) — only a resumable base offers reopen-by-id. Mirrors the Dock's `inheritingByBase`+ * grouping (`Dock.tsx`): the base builtin, then its inheriting enabled customs, with the source+ * and any disabled agent filtered out.+ *+ * Pure + unit-tested; Canvas wraps it in setState.+ */+export function reopenVariants(+ sourceAgentId: AgentId,+ customAgents: readonly CustomAgent[],+ disabledAgents: readonly AgentId[],+): ReopenVariant[] {+ // Resolve from the records passed in rather than the runtime's injected capability resolver.+ // This keeps the helper deterministic in tests and, more importantly, makes a deleted/unknown+ // custom source ineligible instead of guessing that its id is a harness.+ const base = BUILTIN_AGENT_IDS.includes(sourceAgentId as BuiltinAgentId)+ ? (sourceAgentId as BuiltinAgentId)+ : customAgents.find((c) => c.id === sourceAgentId)?.baseAgent;+ if (!base || !canResume(base)) return [];++ const disabled = new Set(disabledAgents);+ const out: ReopenVariant[] = [];++ // The base harness itself is a variant (reopen a custom-agent session as the plain harness, or+ // vice versa), unless the source IS the base builtin.+ if (sourceAgentId !== base && !disabled.has(base)) {+ out.push({ id: base, label: AGENT_CONFIG[base].label, base });+ }++ // Every enabled custom agent that inherits this base, minus the source itself.+ for (const c of customAgents) {+ if (c.id === sourceAgentId) continue;+ if (disabled.has(c.id)) continue;+ if (c.baseAgent !== base) continue;+ out.push({ id: c.id, label: c.label, base });+ }++ return out;+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 3eb8b564d..67c6a4c27 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -141,7 +141,21 @@ import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'import { useSession, useActiveSessionPresence } from '../session/session'import { accountChipLabel, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'-import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, canReadTitle, createdAgentId, reportsOwnCopy, agentConfig } from '@shared/agents/config'+import {+ hasHooks,+ canRecur,+ canContextLink,+ hasUsage,+ canChat,+ canResume,+ canRename,+ canReadTitle,+ createdAgentId,+ reportsOwnCopy,+ agentConfig,+ capabilityAgentId,+ type AgentId+} from '@shared/agents/config'import { withPermissionMode } from '@shared/agents/approval-mode'import { assembleResumeCommand } from '@shared/agents/launch'import { ensureActivePermissionMode } from '../state/permissionMode'@@ -2832,11 +2846,30 @@ export function TerminalNode({}const unregisterRestart = registerAgentRestart(id,- guardConcurrentRestart(id, async () => {+ guardConcurrentRestart(id, async (targetAgentId?: AgentId) => {const st = useAgentStatus.getState().byId[id]const agentSessionId = st?.sessionId- const gate = restartEligibility(agentId, st?.state, agentSessionId)- if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'+ // `data.agentId` can change after a successful same-base swap while this deliberately+ // long-lived terminal effect stays mounted. Read the node NOW instead of trusting the+ // value captured when the pane attached, or a later plain Restart would silently reopen+ // the old agent again.+ const sourceAgentId = createdAgentId(getNode(id)?.data)+ const gate = restartEligibility(sourceAgentId, st?.state, agentSessionId)+ if (!gate.ok || !sourceAgentId || !agentSessionId || !restartTarget())+ return 'not-eligible'+ const target = targetAgentId ?? sourceAgentId+ const settings = useSettings.getState().settings+ const builtinTarget = agentConfig(target)+ const customTarget = builtinTarget+ ? undefined+ : settings.customAgents.find((c) => c.id === target)+ // Session ids are provider-specific. A stale context menu (or settings edit while it is+ // open) must never feed a Claude id to Codex, nor launch a custom agent that was deleted.+ if (+ (!builtinTarget && !customTarget) ||+ capabilityAgentId(target) !== capabilityAgentId(sourceAgentId)+ )+ return 'not-eligible'// Built HERE, not inside the choreography: the shared assembly builder is the single funnel// for every CLI launch path (shared/agents/launch.ts) and the mode is a renderer-side, async// read — exactly as the cold-restore relaunch above does it. Without it a canvas running@@ -2844,20 +2877,28 @@ export function TerminalNode({// Re-resolved at call time for the same reason as there: the mode is a property of how a// session is launched, not of the node. Inheritance-aware: a custom agent's baseAgent/args// are re-applied so a restart of a claude-base proxy resumes correctly.- const customAgent = agentConfig(agentId)- ? undefined- : useSettings.getState().settings.customAgents.find((c) => c.id === agentId)- const { command } = assembleResumeCommand(+ // Launch-command / args substitutions must use the host that owns this pane. `api` is+ // session-scoped, so a relay tab asks its host rather than expanding against this Mac.+ const launchEnv = customTarget+ ? await api.agent.envSnapshot().catch(() => ({}))+ : {}+ const { command, missingEnv } = assembleResumeCommand({- agentId,- customAgent,+ agentId: target,+ customAgent: customTarget,sessionId: agentSessionId,- permissionMode: await ensureActivePermissionMode(agentId)+ permissionMode: await ensureActivePermissionMode(target)},- {}+ launchEnv)+ // Never type a knowingly mangled launch line (for example `--token ''`) into the pane.+ // Settings already surfaces these missing names in its preview; a stale menu after an env+ // change degrades to the ordinary not-eligible notice and leaves the shell untouched.+ if (missingEnv.length) return 'not-eligible'return performRestartResume({- agentId,+ // Source and target were proven to share one capability base above, so this resolves to+ // the same exit + resume grammar while the explicit command selects the target binary.+ agentId: target,sessionId: agentSessionId,io: restartIo,// An unusable session id leaves this undefined and performRestartResume refuses thediff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 8b6f51b72..9d9cd01a1 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -958,6 +958,18 @@ describe('guardConcurrentRestart', () => {await expect(guarded()).rejects.toThrow('ipc died')expect(runs).toBe(2)})++ it('forwards arguments while keeping the same per-node lock', async () => {+ const seen: string[] = []+ const guarded = guardConcurrentRestart('n-args', async (target?: string) => {+ seen.push(target ?? 'same')+ return 'restarted' as const+ })++ expect(await guarded('custom:claude')).toBe('restarted')+ expect(await guarded()).toBe('restarted')+ expect(seen).toEqual(['custom:claude', 'same'])+ })})describe('agent restart registry', () => {@@ -978,6 +990,17 @@ describe('agent restart registry', () => {registerAgentRestart('n2', fn)()expect(agentRestartFn('n2')).toBeUndefined()})++ it('forwards an optional target agent to the registered restart', async () => {+ let seen: string | undefined+ registerAgentRestart('n3', async (targetAgentId) => {+ seen = targetAgentId+ return 'restarted'+ })++ expect(await agentRestartFn('n3')?.('custom:claude')).toBe('restarted')+ expect(seen).toBe('custom:claude')+ })})describe('agent hibernate registry', () => {diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex bf83a4413..a8a1b7745 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -4,7 +4,13 @@* model list without losing the conversation. Kept free of DOM/IPC so the node menu, the bulk* filter and the restart choreography can all share exactly one set of rules.*/-import { canResume, canResumeWith, capabilityAgentId, resumeCommand } from '../../shared/agents/config'+import {+ canResume,+ canResumeWith,+ capabilityAgentId,+ resumeCommand,+ type AgentId+} from '../../shared/agents/config'import { isShellCommand } from '@shared/agents/pane'import {DELIVERY_ATTEMPTS,@@ -385,15 +391,15 @@ const inFlight = new Set<string>()* does not count — so a doubled request is neither counted twice as restarted nor reported as a* failure the user could act on. (The alternative, a fifth outcome, would break that frozen line.)*/-export function guardConcurrentRestart<T extends string>(+export function guardConcurrentRestart<T extends string, Args extends unknown[]>(nodeId: string,- fn: () => Promise<T>-): () => Promise<T | 'not-eligible'> {- return async () => {+ fn: (...args: Args) => Promise<T>+): (...args: Args) => Promise<T | 'not-eligible'> {+ return async (...args: Args) => {if (inFlight.has(nodeId)) return 'not-eligible'inFlight.add(nodeId)try {- return await fn()+ return await fn(...args)} finally {// Released on rejection too: a transport that threw once must not leave the node// permanently un-restartable for the rest of the app's run.@@ -403,17 +409,19 @@ export function guardConcurrentRestart<T extends string>(}// ── Node registry (same park-surviving pattern as TerminalNode's restartSubs) ────────────-const restartFns = new Map<string, () => Promise<RestartOutcome>>()+export type AgentRestartFn = (targetAgentId?: AgentId) => Promise<RestartOutcome>++const restartFns = new Map<string, AgentRestartFn>()/** Register a node's restart closure; returns an unregister that is inert if superseded. */-export function registerAgentRestart(nodeId: string, fn: () => Promise<RestartOutcome>): () => void {+export function registerAgentRestart(nodeId: string, fn: AgentRestartFn): () => void {restartFns.set(nodeId, fn)return () => {if (restartFns.get(nodeId) === fn) restartFns.delete(nodeId)}}-export function agentRestartFn(nodeId: string): (() => Promise<RestartOutcome>) | undefined {+export function agentRestartFn(nodeId: string): AgentRestartFn | undefined {return restartFns.get(nodeId)}