Skip to content

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.

feat(codex): the account-switch menu on a running Codex node

Claude Code7382147f2752
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 4947404f4..5aab17744 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -405,8 +405,8 @@ import {
ungroupNodes,
type CanvasNode
} from '../state/workspace'
-import { codexAccountSelectable } from './codex-account-switch'
-import { resolveNewCodexNodeAccount } from './codex-account-ops'
+import { codexAccountSelectable, codexAccountSwitchStillEligible } from './codex-account-switch'
+import { resolveNewCodexNodeAccount, planCodexAccountSwitch } from './codex-account-ops'
import type { CodexAccount } from '@shared/codex-account'
import { useSystemCodexAccount } from '../state/systemCodexAccount'
import { toKanbanSession } from './toKanbanSession'
@@ -4836,6 +4836,117 @@ export function Canvas() {
)
}, [setNodes, markDirty])
+ // S6 §3.5 — originate an owner-authorized Codex account SWITCH for a running node, then recycle
+ // its pane onto the target account. The renderer is NOT the security boundary: PR 5's three-phase
+ // handler is owner-authorized (only the WebContents that reserved may commit/finish) and refuses a
+ // missing/hostile id; here we fail closed BEFORE originating (planCodexAccountSwitch routes the
+ // target through codexAccountSelectable) and re-check `codexAccountSwitchStillEligible` before the
+ // recycle so a diverged/forked pane is never bound onto the switched account — the conversation id
+ // passed to switchThread is the node's own, so the switch RESUMES it, never forks.
+ const switchCodexAccountNode = useCallback(
+ async (nodeId: string, targetAccountId: string | undefined) => {
+ const codexApi = window.nodeTerminal.codexAccounts
+ const snapshot = (): {
+ agentId?: string
+ cwd?: string
+ accountId?: string
+ ssh?: boolean
+ sessionId?: string
+ state?: string
+ } => {
+ const n = nodesRef.current.find((x) => x.id === nodeId)
+ const st = useAgentStatus.getState().byId[nodeId]
+ return {
+ agentId: n?.data.agentId as string | undefined,
+ cwd: n?.data.cwd as string | undefined,
+ accountId: (n?.data.accountId as string | undefined) || undefined,
+ ssh: !!n?.data.ssh,
+ sessionId: restartSessionId(st?.sessionId, n?.data.agentSessionId),
+ state: st?.state
+ }
+ }
+ const decision = planCodexAccountSwitch(
+ snapshot(),
+ targetAccountId,
+ useSettings.getState().settings.codexAccounts,
+ connectedProjectIdForHost
+ )
+ if (!decision.ok) {
+ if (decision.reason === 'same-account') return // no-op: already on this account
+ setNotice({
+ kind: 'error',
+ text:
+ decision.reason === 'no-connection'
+ ? 'That Codex account lives on a host that is not connected — connect its SSH project first.'
+ : decision.reason === 'no-session'
+ ? 'This session has no resumable conversation id yet — nothing to switch.'
+ : 'That Codex account is no longer available. Nothing was changed.'
+ })
+ return
+ }
+ const { plan } = decision
+ let token: string | undefined
+ try {
+ const res = await codexApi.switchThread(
+ plan.sessionId,
+ plan.cwd,
+ plan.sourceAccountId,
+ plan.targetAccountId
+ )
+ token = res.rollbackToken
+ // A no-op or unreserved answer (no token) means main-side did not stage an exposure — done.
+ if (!token) return
+ // The fork took seconds — refuse to recycle unless the pane is STILL the exact idle
+ // conversation the user chose (Corvin's #112 recycle guard). Else roll the reservation back.
+ if (!codexAccountSwitchStillEligible(plan.expected, snapshot())) {
+ await codexApi.rollbackSwitch(token)
+ setNotice({
+ kind: 'error',
+ text: 'This session changed while the switch was preparing — nothing was changed.'
+ })
+ return
+ }
+ await codexApi.commitSwitch(token)
+ // Bind the node to the target account, THEN recycle its shell so codex relaunches under the
+ // target CODEX_HOME and `--resume <sessionId>` resumes the SAME conversation from it.
+ setNodes((ns) =>
+ ns.map((x) =>
+ x.id === nodeId && x.type === 'terminal'
+ ? { ...x, data: { ...x.data, accountId: plan.targetAccountId } }
+ : x
+ )
+ )
+ markDirty()
+ const fn = agentRestartFn(nodeId)
+ const outcome = fn ? await settleRestart(() => fn(undefined, undefined, true)) : 'not-eligible'
+ await codexApi.finishSwitch(token)
+ setNotice(
+ outcome === 'restarted'
+ ? { kind: 'info', text: 'Codex account switched — conversation resumed.' }
+ : {
+ kind: 'error',
+ text:
+ 'Codex account switched, but the pane could not be relaunched — restart the ' +
+ 'agent to resume on the new account.'
+ }
+ )
+ } catch {
+ if (token) {
+ try {
+ await codexApi.rollbackSwitch(token)
+ } catch {
+ // Best-effort rollback; the reservation also releases on its TTL / owner destruction.
+ }
+ }
+ setNotice({
+ kind: 'error',
+ text: 'The Codex account switch failed and was rolled back. Nothing was changed.'
+ })
+ }
+ },
+ [setNodes, markDirty, connectedProjectIdForHost]
+ )
+
// 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.
const bulkRestartPlan = useCallback((): BulkRestartPlan => {
@@ -5701,6 +5812,57 @@ export function Canvas() {
'Configure a URL and API key in Settings → Model gateway.'
}
] as MenuItem[])
+ : []),
+ // Switch this running Codex node onto another machine-scoped account (S6 §3.5). Shown
+ // only for a Codex node with managed accounts on its machine. Each row is gated through
+ // `codexAccountSelectable`; the actual switch is owner-authorized MAIN-SIDE and resumes
+ // the SAME conversation id (`switchCodexAccountNode`) — the UI is not the boundary.
+ ...(sourceAgentId === 'codex'
+ ? (() => {
+ const codexAll = useSettings.getState().settings.codexAccounts
+ const hostKey = n?.data.ssh ? sshHostKey(n.data.ssh as SshServer) : undefined
+ const onMachine = codexAll.filter(
+ (a) => !a.pending && (hostKey ? a.host === hostKey : !a.host)
+ )
+ if (onMachine.length === 0) return []
+ const currentAccountId = (n?.data.accountId as string | undefined) || undefined
+ const systemCodexLabel = systemAccountDisplay(
+ undefined,
+ useSystemCodexAccount.getState().email
+ )
+ const row = (
+ id: string | undefined,
+ label: string
+ ): MenuItem => {
+ const isCurrent = (id || undefined) === currentAccountId
+ const sel = codexAccountSelectable(id, onMachine, connectedProjectIdForHost)
+ return {
+ label: `${isCurrent ? '✓ ' : ''}${label}`,
+ icon: <AgentIcon agentId="codex" />,
+ disabled: !!why || isCurrent || !sel.ok,
+ hint: isCurrent
+ ? 'This node already runs on this account.'
+ : !sel.ok
+ ? sel.reason === 'no-connection'
+ ? 'This account lives on a host that is not connected.'
+ : 'This account is no longer available.'
+ : (why ??
+ 'Moves this conversation to the account and resumes it there (same conversation).'),
+ onClick: () => void switchCodexAccountNode(ids[0], id)
+ }
+ }
+ return [
+ {
+ type: 'submenu',
+ label: 'Switch Codex account',
+ icon: <IconSwitch />,
+ children: [
+ row(undefined, systemCodexLabel),
+ ...onMachine.map((a) => row(a.id, a.label))
+ ]
+ }
+ ] as MenuItem[]
+ })()
: [])
] as MenuItem[]
})()
@@ -5721,6 +5883,8 @@ export function Canvas() {
toggleMarkdown,
reloadTerminals,
restartAgentNode,
+ switchCodexAccountNode,
+ connectedProjectIdForHost,
deleteNodes,
gatewayModels,
gatewayStatus,
diff --git a/src/renderer/canvas/codex-account-ops.test.ts b/src/renderer/canvas/codex-account-ops.test.ts
index dcdced996..2348b1224 100644
--- a/src/renderer/canvas/codex-account-ops.test.ts
+++ b/src/renderer/canvas/codex-account-ops.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { CodexAccount } from '@shared/codex-account'
-import { resolveNewCodexNodeAccount } from './codex-account-ops'
+import { resolveNewCodexNodeAccount, planCodexAccountSwitch } from './codex-account-ops'
const local: CodexAccount = { id: 'account-a', label: 'Work' }
const remote: CodexAccount = { id: 'account-r', label: 'Box', host: 'u@box' }
@@ -52,3 +52,73 @@ describe('resolveNewCodexNodeAccount (fail-closed New Codex picker — §3.4 / P
})
})
})
+
+describe('planCodexAccountSwitch (fail-closed switch origination — §3.5)', () => {
+ const codexNode = {
+ agentId: 'codex',
+ cwd: '/repo',
+ accountId: 'account-a',
+ ssh: false,
+ sessionId: 'thread-a'
+ }
+
+ it('plans a switch to a present account, preserving the conversation id', () => {
+ const d = planCodexAccountSwitch(codexNode, 'account-r', accounts, connected)
+ expect(d.ok).toBe(true)
+ if (!d.ok) return
+ expect(d.plan.sourceAccountId).toBe('account-a')
+ expect(d.plan.targetAccountId).toBe('account-r')
+ // MUTATION PIN: the switch must resume the SAME conversation id, never fork. If the plan carried
+ // any id other than the node's own `sessionId` here (or in `expected.sessionId`), a UI switch
+ // could recycle a diverged pane. Both must equal 'thread-a'. Must stay red on any divergence.
+ expect(d.plan.sessionId).toBe('thread-a')
+ expect(d.plan.expected.sessionId).toBe('thread-a')
+ // The eligibility snapshot pins the SOURCE account (the pane still runs it pre-recycle).
+ expect(d.plan.expected.accountId).toBe('account-a')
+ expect(d.plan.expected.agentId).toBe('codex')
+ })
+
+ it('plans a switch to the system account (target undefined) from a managed one', () => {
+ const d = planCodexAccountSwitch(codexNode, undefined, accounts, connected)
+ expect(d).toMatchObject({ ok: true, plan: { targetAccountId: undefined } })
+ })
+
+ it('refuses a non-Codex node', () => {
+ expect(planCodexAccountSwitch({ ...codexNode, agentId: 'claude' }, 'account-r', accounts, connected)).toEqual({
+ ok: false,
+ reason: 'not-codex'
+ })
+ })
+
+ it('refuses a node with no resumable conversation id', () => {
+ expect(planCodexAccountSwitch({ ...codexNode, sessionId: undefined }, 'account-r', accounts, connected)).toEqual({
+ ok: false,
+ reason: 'no-session'
+ })
+ })
+
+ it('refuses a no-op switch to the account the node already runs', () => {
+ // MUTATION PIN: drop the `source === target` short-circuit → a same-account switch would be
+ // ORIGINATED (reserving + recycling for nothing). Must stay red.
+ expect(planCodexAccountSwitch(codexNode, 'account-a', accounts, connected)).toEqual({
+ ok: false,
+ reason: 'same-account'
+ })
+ })
+
+ it('REFUSES a MISSING target account — no silent substitution', () => {
+ // MUTATION PIN: if a refused target fell through to `{ ok: true }`, the UI would originate a
+ // switch that main-side then binds/refuses. The renderer must fail closed first. Must stay red.
+ expect(planCodexAccountSwitch(codexNode, 'account-gone', accounts, connected)).toEqual({
+ ok: false,
+ reason: 'unavailable'
+ })
+ })
+
+ it('REFUSES a remote target whose host is not connected', () => {
+ expect(planCodexAccountSwitch(codexNode, 'account-r', accounts, noConnection)).toEqual({
+ ok: false,
+ reason: 'no-connection'
+ })
+ })
+})
diff --git a/src/renderer/canvas/codex-account-ops.ts b/src/renderer/canvas/codex-account-ops.ts
index 2d7da9e73..870f0e3f7 100644
--- a/src/renderer/canvas/codex-account-ops.ts
+++ b/src/renderer/canvas/codex-account-ops.ts
@@ -6,9 +6,14 @@
// 1. `resolveNewCodexNodeAccount` — the "New Codex node" account picker (§3.4). An explicitly
// picked account that is MISSING / hostile / unconnected is REFUSED, never silently swapped for
// the system login.
+// 2. `planCodexAccountSwitch` — the running-node account-SWITCH menu (§3.5). Refuses a non-Codex
+// node, a node with no resumable conversation id, a no-op same-account switch, and (through
+// `codexAccountSelectable`) a missing/hostile/unconnected target. The `expected` snapshot it
+// returns is exactly what `codexAccountSwitchStillEligible` re-checks before the pane is
+// recycled, so a UI-originated switch always resumes the SAME conversation id — never a fork.
import type { CodexAccount } from '@shared/codex-account'
-import { codexAccountSelectable } from './codex-account-switch'
+import { codexAccountSelectable, type CodexAccountSwitchState } from './codex-account-switch'
/** The picker's verdict for a NEW Codex node. `create: false` carries the same fail-closed reason
* `codexAccountSelectable` produced — the node is NOT created, and never with another account. */
@@ -35,3 +40,64 @@ export function resolveNewCodexNodeAccount(
if (!selectable.ok) return { create: false, reason: selectable.reason }
return { create: true, accountId: explicit }
}
+
+/** What the imperative orchestrator needs to drive PR 5's three-phase switch for a node. */
+export interface CodexSwitchPlan {
+ /** The node's current account (undefined = system) — the switch source. */
+ sourceAccountId: string | undefined
+ /** The chosen account (undefined = system) — the switch target. */
+ targetAccountId: string | undefined
+ /** The node's conversation id. Passed verbatim to `switchThread`; the switch resumes THIS id. */
+ sessionId: string
+ cwd: string
+ /** Snapshot re-checked by `codexAccountSwitchStillEligible` before the pane is recycled. Its
+ * `sessionId` is the node's current id, so a diverged/forked pane is refused recycling. */
+ expected: Required<Pick<CodexAccountSwitchState, 'agentId' | 'cwd' | 'sessionId'>> &
+ Pick<CodexAccountSwitchState, 'accountId' | 'ssh'>
+}
+
+export type CodexSwitchDecision =
+ | { ok: true; plan: CodexSwitchPlan }
+ | { ok: false; reason: 'not-codex' | 'no-session' | 'same-account' | 'unavailable' | 'no-connection' }
+
+/**
+ * Decide whether a UI-originated account SWITCH may be ORIGINATED for a node (surface §3.5).
+ * Fail-closed — proceeds only on `{ ok: true }`:
+ * - the node must be a Codex node (`agentId === 'codex'`);
+ * - it must have a resumable conversation id (`sessionId`) and an absolute-ish cwd;
+ * - the target must differ from the source (a no-op switch is refused, not run);
+ * - the target must pass `codexAccountSelectable` (missing/hostile/unconnected ⇒ refused).
+ * The returned `plan.expected.sessionId` and `plan.sessionId` are BOTH the node's current id, so the
+ * orchestration can never fork the conversation onto the switched account.
+ */
+export function planCodexAccountSwitch(
+ node: { agentId?: string; cwd?: string; accountId?: string; ssh?: boolean; sessionId?: string },
+ targetAccountId: string | undefined,
+ accounts: readonly CodexAccount[],
+ connectedProjectIdForHost: (host: string) => string | undefined
+): CodexSwitchDecision {
+ if (node.agentId !== 'codex') return { ok: false, reason: 'not-codex' }
+ if (!node.sessionId || !node.cwd) return { ok: false, reason: 'no-session' }
+ const source = node.accountId || undefined
+ const target = targetAccountId || undefined
+ // A switch to the account the node already runs is a no-op — refuse rather than reserve/recycle.
+ if (source === target) return { ok: false, reason: 'same-account' }
+ const selectable = codexAccountSelectable(target, accounts, connectedProjectIdForHost)
+ if (!selectable.ok) return { ok: false, reason: selectable.reason }
+ return {
+ ok: true,
+ plan: {
+ sourceAccountId: source,
+ targetAccountId: target,
+ sessionId: node.sessionId,
+ cwd: node.cwd,
+ expected: {
+ agentId: 'codex',
+ cwd: node.cwd,
+ sessionId: node.sessionId,
+ accountId: source,
+ ssh: !!node.ssh
+ }
+ }
+ }
+}