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
fix(accounts): a managed Claude account is not a Codex one; wire the Codex login node
enes91a76a95291a
diff --git a/CLAUDE.md b/CLAUDE.mdindex f6b628a52..a0938a8c1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1245,7 +1245,17 @@ else, and its context links must keep classifying across restarts).**login node** that runs `claude /login` under the account dir. Main polls the dir's`.claude.json` (`LOGIN_POLL_MS` 2 s, up to `LOGIN_TIMEOUT_MS` 5 min) for `oauthAccount.email`;on capture the account flips out of `pending` with its email as the default label. Account- removal cancels any pending wait + `markDirty`.+ removal cancels any pending wait + `markDirty`. **Codex accounts have the same two halves** —+ `createCodexAccountLoginNode` (`codex login`, title "Codex login") behind the+ `nodeterm:add-codex-account-login` listener, with `codexAccounts.waitLogin` polling the managed+ home's `auth.json`. Both flows mint an **agent-less terminal** carrying only `accountId`, and+ that shape is why `needsCodexAccountScope` takes an `isCodexAccount` resolver rather than+ reading `!!accountId`: the two account lists share an id alphabet, so the id alone cannot say+ which provider it belongs to. Guessing "codex" refused every managed **Claude** node (#345);+ guessing "not codex" would let `codex login` write into the system `~/.codex`. A dispatch with+ no listener is a silent no-op, which is how the Codex half shipped inert (#346) — pinned now by+ `renderer/lib/nodeterm-events.test.ts`, which fails on any `nodeterm:*` event that is sent but+ never heard.- **Hook install** — the managed hook is merged into **each account dir's** `settings.json` atadd-account **and** at app launch (local, shared `install-helper.ts`) / via`RemoteHooks.installIntoAccountDir` (remote), so every identity reports agent status.diff --git a/src/core/codex-accounts-core.test.ts b/src/core/codex-accounts-core.test.tsindex 19fc79cbd..4940829dc 100644--- a/src/core/codex-accounts-core.test.ts+++ b/src/core/codex-accounts-core.test.ts@@ -145,11 +145,18 @@ describe('per-session Codex env', () => {])})- it('scopes Codex agents and managed-id login terminals, nothing else', () => {- expect(needsCodexAccountScope('codex')).toBe(true)- expect(needsCodexAccountScope(undefined, 'account-a')).toBe(true)- expect(needsCodexAccountScope(undefined, undefined)).toBe(false)- expect(needsCodexAccountScope('bash')).toBe(false)+ it('scopes Codex agents and managed-CODEX-id login terminals, nothing else', () => {+ const isCodex = (id: string): boolean => id === 'codex-a'+ // A Codex agent always needs a scope — system account included, so the id may be absent.+ expect(needsCodexAccountScope('codex', undefined, isCodex)).toBe(true)+ // The agent-less `codex login` terminal: no agent, but a managed CODEX id.+ expect(needsCodexAccountScope(undefined, 'codex-a', isCodex)).toBe(true)+ // …and the `claude /login` terminal right beside it must NOT be caught (#345): same shape,+ // an id from the OTHER list. Answering by id shape instead of by list is what broke it.+ expect(needsCodexAccountScope(undefined, 'claude-a', isCodex)).toBe(false)+ expect(needsCodexAccountScope('claude', 'claude-a', isCodex)).toBe(false)+ expect(needsCodexAccountScope(undefined, undefined, isCodex)).toBe(false)+ expect(needsCodexAccountScope('bash', undefined, isCodex)).toBe(false)})})diff --git a/src/core/codex-accounts-core.ts b/src/core/codex-accounts-core.tsindex dd69cc5eb..0c8d53c1d 100644--- a/src/core/codex-accounts-core.ts+++ b/src/core/codex-accounts-core.ts@@ -224,10 +224,25 @@ export function resolveCodexSessionScope(/*** Codex agents need an explicit system-or-managed scope; a plain login terminal needs it when it- * carries a managed account id. Sharing this predicate keeps tmux and plain PTYs aligned.+ * carries a managed CODEX account id. Sharing this predicate keeps tmux and plain PTYs aligned.+ *+ * `isCodexAccount` is REQUIRED, and deliberately has no default, because neither guess is safe.+ * Managed Claude and Codex accounts are separate lists that share one id alphabet, so the id alone+ * cannot say which provider it belongs to. Answering "yes" for any id — which this predicate used+ * to do via `!!accountId` — sends every managed CLAUDE node into the fail-closed Codex gate, where+ * it looks for a `~/.nodeterm/cx/<digest>` home that a Claude account never populates and REFUSES+ * (issue #345: agent nodes and the `claude /login` terminal alike spawned nothing). Answering "no"+ * by default would be worse in the other direction: the `codex login` terminal would spawn without+ * a scope and write its credential into the user's SYSTEM `~/.codex`. So the caller must say.*/-export function needsCodexAccountScope(agentId?: string, accountId?: string): boolean {- return agentId === 'codex' || !!accountId+export function needsCodexAccountScope(+ agentId: string | undefined,+ accountId: string | undefined,+ isCodexAccount: (id: string) => boolean+): boolean {+ if (agentId === 'codex') return true+ if (!accountId) return false+ return isCodexAccount(accountId)}/**diff --git a/src/core/pty-claude-account-spawn.test.ts b/src/core/pty-claude-account-spawn.test.tsnew file mode 100644index 000000000..f28ef7761--- /dev/null+++ b/src/core/pty-claude-account-spawn.test.ts@@ -0,0 +1,110 @@+/**+ * Issue #345 — a managed CLAUDE account must not be mistaken for a Codex one.+ *+ * `needsCodexAccountScope` used to answer `agentId === 'codex' || !!accountId`. The two account+ * lists share an id alphabet, so that `!!accountId` proxy also matched every managed CLAUDE id:+ * the spawn entered the fail-closed Codex gate, looked for `~/.nodeterm/cx/<digest>` (a namespace a+ * Claude account never populates), found nothing and REFUSED. Every node bound to a managed Claude+ * account — agent node and `claude /login` terminal alike — returned `unavailable: 'codex-account'`+ * and spawned nothing.+ *+ * MUTATION: make the resolver in pty-manager's two call sites answer `() => true` (i.e. restore the+ * old "any account id is a Codex one" proxy) → the two Claude cases below redden on both the+ * refusal and the spawn count.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { mkdirSync, mkdtempSync, rmSync } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'+import { DEFAULT_SETTINGS } from '../shared/types'+import type { PtyCreateOptions, PtyCreateResult, Settings } from '../shared/types'+import { codexAccountHome } from './codex-accounts-core'+import { accountConfigDir } from './claude-accounts-core'++const spawned: Array<{ file: string; args: string[]; env: Record<string, string> }> = []++vi.mock('node-pty', () => ({+ spawn: (file: string, args: string[], options: { env: Record<string, string> }) => {+ spawned.push({ file, args, env: options?.env ?? {} })+ return {+ onData: () => {}, onExit: () => {}, write: () => {}, resize: () => {},+ pause: () => {}, resume: () => {}, kill: () => {}, pid: 4321+ }+ }+}))+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++const ALICE = 1+const CODEX_ACCT = 'codexacct1'+const CLAUDE_ACCT = 'claudeacct1'++describe('a managed Claude account is not a Codex account (#345)', () => {+ let fake: FakePlatform+ let userDataDir: string++ beforeEach(async () => {+ spawned.length = 0+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-claude-acct-'))+ fake = fakePlatform({ userDataDir })+ initPlatform(fake)+ const { PtyManager } = await import('./pty-manager')+ // Only the CODEX account is in codexAccounts — the Claude id is deliberately absent, which is+ // exactly what tells the two apart.+ const settings: Settings = {+ ...DEFAULT_SETTINGS,+ codexAccounts: [{ id: CODEX_ACCT, label: 'work' }]+ }+ const mgr = new PtyManager()+ mgr.init(() => settings)+ mgr.registerIpc()+ })+ afterEach(() => {+ resetPlatformForTests()+ rmSync(userDataDir, { recursive: true, force: true })+ })++ const create = (options: Partial<PtyCreateOptions>) =>+ fake.handlers[IPC.ptyCreate](ALICE, {+ cols: 80, rows: 24, persistKey: 'node-1', cwd: '/srv/app', ...options+ }) as Promise<PtyCreateResult>++ it('a Claude AGENT node bound to a managed Claude account SPAWNS', async () => {+ // The Claude account's config dir exists — the Claude path falls back with a warning chip+ // when it does not, which would hide the refusal this test is about.+ mkdirSync(accountConfigDir(userDataDir, CLAUDE_ACCT), { recursive: true })+ const res = await create({ agentId: 'claude', accountId: CLAUDE_ACCT })+ expect(res.unavailable).toBeUndefined()+ expect(spawned).toHaveLength(1)+ // It is a Claude scope, not a Codex one.+ expect(spawned[0].env.CLAUDE_CONFIG_DIR).toContain(CLAUDE_ACCT)+ expect(spawned[0].env.CODEX_HOME).toBeUndefined()+ })++ it('the agent-less `claude /login` terminal SPAWNS', async () => {+ const res = await create({ accountId: CLAUDE_ACCT, persistKey: 'node-2' })+ expect(res.unavailable).toBeUndefined()+ expect(spawned).toHaveLength(1)+ expect(spawned[0].env.CODEX_HOME).toBeUndefined()+ })++ it('the agent-less `codex login` terminal STILL gets the managed Codex scope', async () => {+ mkdirSync(codexAccountHome(userDataDir, CODEX_ACCT), { recursive: true })+ const res = await create({ accountId: CODEX_ACCT, persistKey: 'node-3' })+ expect(res.unavailable).toBeUndefined()+ expect(spawned).toHaveLength(1)+ expect(spawned[0].env.CODEX_HOME).toBe(codexAccountHome(userDataDir, CODEX_ACCT))+ expect(spawned[0].env.NODETERM_CODEX_ACCOUNT_ID).toBe(CODEX_ACCT)+ })++ it('a Codex AGENT node still fails closed on a missing managed home', async () => {+ const res = await create({ agentId: 'codex', accountId: CODEX_ACCT, persistKey: 'node-4' })+ expect(res.unavailable).toBe('codex-account')+ expect(spawned).toHaveLength(0)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 38309f828..26dbc76ea 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -706,6 +706,15 @@ export class PtyManager {private tmuxPath: string | null = nullprivate confPath = ''private getSettings: () => Settings = () => DEFAULT_SETTINGS++ /**+ * Is this account id one of the managed CODEX accounts? Asked instead of guessing from the id's+ * shape: `codexAccounts` and `claudeAccounts` share an id alphabet, so only the list can tell+ * them apart (issue #345). Reads LIVE settings, so an account added after init is seen.+ */+ private isCodexAccount(accountId: string): boolean {+ return this.getSettings().codexAccounts.some((a) => a.id === accountId)+ }/** Literal model-gateway key loaded by the shell's secret service during startup. */private getModelGatewaySecret: () => string | null = () => null/**@@ -1795,7 +1804,7 @@ export class PtyManager {// chip. `resolveCodexSessionScope` returns `{ unavailable: 'codex-account' }` for exactly that// case; we map it straight through to a real refusal and spawn NOTHING. The system account (no// id) always resolves. Remote (ssh) Codex sessions carry their account env via tmux `-e`.- if (needsCodexAccountScope(options.agentId, options.accountId) && !options.sshRemote) {+ if (needsCodexAccountScope(options.agentId, options.accountId, (id) => this.isCodexAccount(id)) && !options.sshRemote) {const scope = resolveCodexSessionScope(platform().userDataDir, options.accountId)if (isCodexScopeRefusal(scope)) {return { sessionId: '', fresh: false, unavailable: 'codex-account' }@@ -2209,7 +2218,7 @@ export class PtyManager {// property 4), so `codexSessionEnv` here never resolves an explicit id to the system home. Also// strip env vars that would shadow the account's OAuth login with API-key auth. Remote (ssh)// Codex sessions get this via the remote tmux `-e` list, not the local ssh client env.- if (needsCodexAccountScope(options.agentId, options.accountId) && !options.sshRemote) {+ if (needsCodexAccountScope(options.agentId, options.accountId, (id) => this.isCodexAccount(id)) && !options.sshRemote) {const codexScope = codexSessionEnv(platform().userDataDir, options.accountId)env.CODEX_HOME = codexScope.CODEX_HOMEenv.NODETERM_CODEX_ACCOUNT_ID = codexScope.NODETERM_CODEX_ACCOUNT_IDdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 73f73d619..afa98ab85 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -391,6 +391,7 @@ import {commonParentId,fitGroupToChildren,createAccountLoginNode,+ createCodexAccountLoginNode,isAccountLoginNode,systemAccountDisplay,createAgentNode,@@ -3667,6 +3668,30 @@ export function Canvas() {// Resolves the ssh binding by host at fire time (reads stores directly), so no project dep.}, [setNodes, markDirty, viewCenter])+ // The Codex sibling of the block above: Settings → Accounts "Add Codex account" dispatches+ // 'nodeterm:add-codex-account-login' and then polls `codexAccounts.waitLogin` for the account+ // home's auth.json. Nothing was listening, so no `codex login` ever ran and the poll waited out+ // its timeout on a credential nothing was writing (issue #346). Local only: `codexAccounts.add()`+ // mints on THIS machine, so there is no remote/host leg to resolve — the remote account+ // lifecycle lands with the host relay.+ useEffect(() => {+ const onAddCodexAccountLogin = (ev: Event): void => {+ const accountId = (ev as CustomEvent<{ accountId?: string }>).detail?.accountId+ if (!accountId) return+ setNodes((ns) => [+ ...ns.map((n) => ({ ...n, selected: false })),+ { ...createCodexAccountLoginNode(accountId, ns.length, viewCenter()), selected: true }+ ])+ markDirty()+ // Same reason as the Claude branch: the event fires from the full-screen Settings overlay,+ // which would otherwise hide the login node the user has to interact with.+ setSettingsOpen(false)+ }+ window.addEventListener('nodeterm:add-codex-account-login', onAddCodexAccountLogin)+ return () =>+ window.removeEventListener('nodeterm:add-codex-account-login', onAddCodexAccountLogin)+ }, [setNodes, markDirty, viewCenter])+// Resolve the system account's email once, so context menus (built via getState) can label// the "System account" entry with it.useEffect(() => useSystemAccount.getState().ensure(), [])diff --git a/src/renderer/lib/nodeterm-events.test.ts b/src/renderer/lib/nodeterm-events.test.tsnew file mode 100644index 000000000..26cfa5a4a--- /dev/null+++ b/src/renderer/lib/nodeterm-events.test.ts@@ -0,0 +1,61 @@+/**+ * Issue #346 — a `nodeterm:*` CustomEvent dispatched with nothing listening for it.+ *+ * "Add Codex account" dispatched `nodeterm:add-codex-account-login` to open the device-login node,+ * then awaited `codexAccounts.waitLogin` for the `auth.json` that node's `codex login` would write.+ * No listener was ever registered, so no node opened, nothing wrote the credential, and the add+ * flow waited out its five-minute timeout. Nothing could see it: the dispatch compiles, typechecks+ * and runs — a CustomEvent with no listener is a silent no-op by design.+ *+ * So the guard is the pairing itself, for every event rather than that one: these are the app's+ * only fire-and-forget channel between the Settings overlay and the canvas, and each new one is a+ * fresh chance to wire just one end. Names are read from source because the sender and the+ * receiver never share a symbol — that string literal IS the coupling.+ *+ * MUTATION: delete the `nodeterm:add-codex-account-login` listener in Canvas.tsx → red, naming the+ * event. (Deleting a DISPATCH is not a failure: a listener with no sender is inert, and one exists+ * for events the desktop shell fires from outside this tree.)+ */+import { describe, expect, it } from 'vitest'+import fs from 'fs'+import path from 'path'++const RENDERER = path.join(__dirname, '..')++function walk(dir: string, out: string[] = []): string[] {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name)+ if (entry.isDirectory()) walk(full, out)+ else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) out.push(full)+ }+ return out+}++function names(re: RegExp): Map<string, string[]> {+ const found = new Map<string, string[]>()+ for (const file of walk(RENDERER)) {+ const src = fs.readFileSync(file, 'utf8')+ for (const m of src.matchAll(re)) {+ const name = m[1]+ found.set(name, [...(found.get(name) ?? []), path.relative(RENDERER, file)])+ }+ }+ return found+}++describe('every nodeterm CustomEvent the renderer dispatches has a listener', () => {+ const dispatched = names(/new CustomEvent\(\s*['"](nodeterm:[a-z-]+)['"]/g)+ const listened = names(/addEventListener\(\s*['"](nodeterm:[a-z-]+)['"]/g)++ it('finds the channel at all — a regex that matches nothing would pass vacuously', () => {+ expect(dispatched.size).toBeGreaterThan(5)+ expect(listened.size).toBeGreaterThan(5)+ })++ it('has no dispatch without a listener', () => {+ const orphans = [...dispatched.entries()]+ .filter(([name]) => !listened.has(name))+ .map(([name, files]) => `${name} (dispatched in ${files.join(', ')})`)+ expect(orphans).toEqual([])+ })+})diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex f3aabed7e..c3fdbcd4a 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -5,6 +5,7 @@ import {arrangeNodes,commonParentId,createAccountLoginNode,+ createCodexAccountLoginNode,createAgentNode,createDinoNode,fitGroupToChildren,@@ -707,6 +708,22 @@ describe('createAccountLoginNode', () => {})})+describe('createCodexAccountLoginNode', () => {+ it('produces a terminal node that logs the given Codex account in', () => {+ const node = createCodexAccountLoginNode('acct-2', 0)+ expect(node.type).toBe('terminal')+ expect(node.data.title).toBe('Codex login')+ expect(node.data.accountId).toBe('acct-2')+ expect(node.data.initialCommand).toBe('codex login')+ })++ it('carries NO agentId — the agent-less shape is what the Codex scope gate keys on', () => {+ // With an agentId of 'codex' this would be an agent node and take the agent paths; the login+ // terminal is scoped purely because its account id is a managed CODEX one (see #345/#346).+ expect(createCodexAccountLoginNode('acct-2', 0).data.agentId).toBeUndefined()+ })+})+describe('dino node serialization', () => {it('round-trips a dino node and its highScore', () => {const dino = {diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 421cc9eb3..228f2a6da 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -707,6 +707,33 @@ export function createAccountLoginNode(return node}+/**+ * Terminal node used to log a new managed CODEX account in — the sibling of+ * `createAccountLoginNode`. The session runs under that account's `CODEX_HOME` (S6 §2.1 env+ * injection, gated by `needsCodexAccountScope` asking whether the id is a managed Codex one), so+ * `codex login` writes `auth.json` into the managed home rather than the user's system `~/.codex`.+ * That file is exactly what `codexAccounts.waitLogin` polls for, so without this node the add flow+ * waits on a credential nothing is writing (issue #346).+ *+ * A plain terminal (not an agent node), like the Claude one: no session-name tracking, and the+ * agent-less shape is what keeps the node out of the Codex AGENT paths while still being scoped.+ * Local only — `codexAccounts.add()` mints on THIS machine, so there is no ssh binding to pass.+ */+export function createCodexAccountLoginNode(+ accountId: string,+ index: number,+ center?: { x: number; y: number }+): CanvasNode {+ const node = createTerminalNode(index, undefined, center)+ node.data = {+ ...node.data,+ title: 'Codex login',+ accountId,+ initialCommand: 'codex login'+ }+ return node+}+/*** True when node data is (or started as) an account-login terminal (`claude /login`).* `initialCommand` is one-shot and never persisted, so the factory title is the only durable