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(codex-accounts): real SSH lifecycle, and scope remote spawns by provider
review3886f9a9426f
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 6fa504e85..238ca41ff 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -97,6 +97,7 @@ import {resolveCodexSessionScope} from './codex-accounts-core'import { NODE_ID_MAX, isSafeNodeId } from './remote-safety'+import { remoteAccountScopeEnvArgs } from './remote-account-env'import { presenceHub } from './presence/hub'import {codexLauncherDir,@@ -3066,10 +3067,14 @@ export class PtyManager {// ABSOLUTE — tmux copies `-e` values verbatim (no `$HOME`/`~` expansion) — so we build it from// the connection's resolved remote $HOME. Fail-open: an unknown remoteHome (home resolution// failed on connect) skips the account env and the session runs under the remote `~/.claude`.- const remoteAccountEnv =- options.accountId && options.sshRemote.remoteHome- ? accountTmuxEnvArgs(remoteAccountConfigDirAbs(options.sshRemote.remoteHome, options.accountId))- : []+ // Routed by PROVIDER (`remoteAccountScopeEnvArgs`): a managed Codex account gets its+ // CODEX_HOME + NODETERM_CODEX_ACCOUNT_ID, a Claude one its CLAUDE_CONFIG_DIR.+ const remoteAccountEnv = remoteAccountScopeEnvArgs({+ agentId: options.agentId,+ accountId: options.accountId,+ remoteHome: options.sshRemote.remoteHome,+ isCodexAccount: (id) => this.isCodexAccount(id)+ })// Custom-agent env for a REMOTE node: expand ${env:VAR} against the LOCAL process env (the// key stays local; only the resolved VALUE travels over SSH). PATH is skipped — the local// machine can't see the remote box's PATH, so a locally-resolved PATH would break CLIdiff --git a/src/core/remote-account-env.test.ts b/src/core/remote-account-env.test.tsnew file mode 100644index 000000000..c1deb3c11--- /dev/null+++ b/src/core/remote-account-env.test.ts@@ -0,0 +1,41 @@+// MUTATION: route every accountId to Claude again (the pre-fix behavior) → the Codex case gets+// CLAUDE_CONFIG_DIR and reddens.+import { describe, expect, it } from 'vitest'+import { remoteAccountScopeEnvArgs } from './remote-account-env'+import { remoteCodexHome } from './codex-accounts-core'++const HOME = '/home/u'+const codexIds = new Set(['cx1'])+const isCodexAccount = (id: string): boolean => codexIds.has(id)+const env = (+ agentId: string | undefined,+ accountId: string | undefined,+ remoteHome: string | undefined | null = HOME+) => remoteAccountScopeEnvArgs({ agentId, accountId, remoteHome: remoteHome ?? undefined, isCodexAccount })++describe('remoteAccountScopeEnvArgs', () => {+ it('scopes a managed Codex account to its private home on the host — not a Claude dir', () => {+ expect(env('codex', 'cx1')).toEqual([+ '-e',+ `CODEX_HOME=${remoteCodexHome(HOME, 'cx1')}`,+ '-e',+ 'NODETERM_CODEX_ACCOUNT_ID=cx1'+ ])+ })++ it('scopes the agent-less `codex login` terminal of a Codex account too', () => {+ expect(env(undefined, 'cx1')).toContain(`CODEX_HOME=${remoteCodexHome(HOME, 'cx1')}`)+ })++ it('keeps a managed Claude account on CLAUDE_CONFIG_DIR, byte-identical to before', () => {+ expect(env('claude', 'cl1')).toEqual(['-e', `CLAUDE_CONFIG_DIR=${HOME}/.nodeterm/claude-accounts/cl1`])+ expect(env(undefined, 'cl1')).toEqual(['-e', `CLAUDE_CONFIG_DIR=${HOME}/.nodeterm/claude-accounts/cl1`])+ })++ it('leaves the host defaults alone for a system account or an unresolved/unsafe $HOME', () => {+ expect(env('codex', undefined)).toEqual([])+ expect(env('claude', undefined)).toEqual([])+ expect(env('codex', 'cx1', null)).toEqual([])+ expect(env('codex', 'cx1', '/home/u\ntouch /tmp/x')).toEqual([])+ })+})diff --git a/src/core/remote-account-env.ts b/src/core/remote-account-env.tsnew file mode 100644index 000000000..b9cd920cc--- /dev/null+++ b/src/core/remote-account-env.ts@@ -0,0 +1,33 @@+// Which account scope a REMOTE (SSH) tmux session is spawned under — the `-e` pairs for the remote+// `tmux new-session`. The local leg answers the same question inline in `buildPtyEnv`; the remote+// leg used to hand EVERY `accountId` to Claude's `CLAUDE_CONFIG_DIR`, so a node bound to a managed+// Codex account on an SSH host got a Claude config dir that does not exist and NO `CODEX_HOME` — and+// its codex silently ran as the host's SYSTEM login. The Codex remote env builder existed and had no+// caller.+//+// The provider is decided exactly as locally: `needsCodexAccountScope` with the caller's+// `isCodexAccount` (the two account lists share an id alphabet, so the id alone cannot say).+import { accountTmuxEnvArgs, remoteAccountConfigDirAbs } from './claude-accounts-core'+import { needsCodexAccountScope, remoteCodexTmuxEnvArgs } from './codex-accounts-core'+import { isSafeRemoteHome } from './remote-safety'++export function remoteAccountScopeEnvArgs(opts: {+ agentId: string | undefined+ accountId: string | undefined+ /** The connection's resolved `$HOME` (tmux copies `-e` values verbatim, so paths are absolute). */+ remoteHome: string | undefined+ isCodexAccount: (id: string) => boolean+}): string[] {+ const { agentId, accountId, remoteHome, isCodexAccount } = opts+ if (!remoteHome) return [] // fail-open, as before: the session runs under the host's defaults+ if (needsCodexAccountScope(agentId, accountId, isCodexAccount)) {+ // The SYSTEM Codex account (no id) is left to the host's own environment: a remote user may+ // point CODEX_HOME elsewhere themselves (a snap install remaps it), and overriding that with+ // `~/.codex` would break them. A managed account gets its private home; a `$HOME` that could+ // smuggle a newline into the `-e` value gets nothing.+ if (!accountId || !isSafeRemoteHome(remoteHome)) return []+ return remoteCodexTmuxEnvArgs(remoteHome, accountId)+ }+ if (!accountId) return []+ return accountTmuxEnvArgs(remoteAccountConfigDirAbs(remoteHome, accountId))+}diff --git a/src/main/codex-accounts.remote.test.ts b/src/main/codex-accounts.remote.test.tsnew file mode 100644index 000000000..78a2df005--- /dev/null+++ b/src/main/codex-accounts.remote.test.ts@@ -0,0 +1,106 @@+/**+ * The SSH leg of the Codex account verbs (Settings → Accounts, a remote machine's panel). With a+ * `{ projectId }` ctx every verb acts ON that host through the SSH manager — and a ctx it cannot+ * resolve is an error, never a quiet fall-back to THIS machine's managed homes.+ *+ * MUTATION: drop `remoteFor(ctx)` from `add` (mint locally regardless) ⇒ the add test finds a new+ * LOCAL home and no remote call ⇒ red. Let the remote waitLogin accept any truthy answer from the+ * auth probe as "logged in" before it is `true` ⇒ the null-probe test resolves early ⇒ red.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { existsSync, mkdtempSync, readdirSync, rmSync } from 'fs'+import os from 'os'+import path from 'path'++const h: { handlers: Record<string, (...a: any[]) => unknown> } = { handlers: {} }+vi.mock('electron', () => ({+ ipcMain: { handle: (ch: string, fn: (...a: any[]) => unknown) => (h.handlers[ch] = fn) }+}))+vi.mock('../core/codex-session-name', () => ({+ readCodexThreadAt: vi.fn(),+ readCodexAccountAt: vi.fn(async () => ({ email: '[email protected]' }))+}))+vi.mock('../core/pty-manager', () => ({ findInLoginPath: vi.fn(async () => null) }))+vi.mock('./codex-relay-daemon', () => ({ ensureCodexRelayRoot: vi.fn() }))++import { IPC } from '../shared/ipc'+import { fakePlatform } from '../core/platform-fake'++let userDataDir = ''+const mgr = {+ remoteCodexAccountAdd: vi.fn(async (_p: string, id: string) => ({ home: `/home/u/.nodeterm/cx/${id}` })),+ remoteCodexAuthPresent: vi.fn(async (): Promise<boolean | null> => true),+ remoteCodexAccountIdentity: vi.fn(async (): Promise<{ email: string | null } | null> => ({+ email: '[email protected]'+ })),+ remoteCodexAccountRemove: vi.fn(async () => true)+}+const sender = { id: 1, isDestroyed: () => false, once: () => {}, removeListener: () => {} }+const call = (channel: string, ...args: any[]) => h.handlers[channel]({ sender }, ...args)+const CTX = { projectId: 'p1' }++beforeEach(async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ h.handlers = {}+ for (const f of Object.values(mgr)) f.mockClear()+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-remote-'))+ vi.resetModules()+ const { initPlatform } = await import('../core/platform')+ initPlatform(fakePlatform({ userDataDir }))+ const { initCodexAccounts } = await import('./codex-accounts')+ initCodexAccounts(() => mgr as any)+})+afterEach(async () => {+ vi.useRealTimers()+ const { resetPlatformForTests } = await import('../core/platform')+ resetPlatformForTests()+ rmSync(userDataDir, { recursive: true, force: true })+})++const localHomes = (): string[] => {+ const root = path.join(userDataDir, 'codex-accounts')+ return existsSync(root) ? readdirSync(root) : []+}++describe('Codex account verbs over SSH', () => {+ it('add mints the home ON the host and creates nothing locally', async () => {+ const res = (await call(IPC.codexAccountsAdd, CTX)) as { id: string; home: string }+ expect(mgr.remoteCodexAccountAdd).toHaveBeenCalledWith('p1', res.id)+ expect(res.home).toBe(`/home/u/.nodeterm/cx/${res.id}`)+ expect(localHomes()).toEqual([])+ })++ it('add refuses when the host is not connected', async () => {+ mgr.remoteCodexAccountAdd.mockResolvedValueOnce(null as never)+ await expect(call(IPC.codexAccountsAdd, CTX)).rejects.toThrow(/not connected/)+ })++ it('waitLogin polls the host and reads the email there', async () => {+ expect(await call(IPC.codexAccountsWaitLogin, 'acct1', CTX)).toEqual({ email: '[email protected]' })+ expect(mgr.remoteCodexAuthPresent).toHaveBeenCalledWith('p1', 'acct1')+ })++ it('waitLogin keeps waiting while the host cannot be asked, and completes without an email', async () => {+ mgr.remoteCodexAuthPresent.mockResolvedValueOnce(null).mockResolvedValueOnce(false)+ mgr.remoteCodexAccountIdentity.mockResolvedValueOnce(null)+ const done = call(IPC.codexAccountsWaitLogin, 'acct1', CTX) as Promise<unknown>+ await vi.advanceTimersByTimeAsync(2000)+ await vi.advanceTimersByTimeAsync(2000)+ expect(await done).toEqual({ email: null })+ expect(mgr.remoteCodexAuthPresent).toHaveBeenCalledTimes(3)+ })++ it('systemIdentity and identity ask the host', async () => {+ await call(IPC.codexAccountsSystemIdentity, CTX)+ expect(mgr.remoteCodexAccountIdentity).toHaveBeenLastCalledWith('p1', undefined)+ await call(IPC.codexAccountsIdentity, 'acct1', CTX)+ expect(mgr.remoteCodexAccountIdentity).toHaveBeenLastCalledWith('p1', 'acct1')+ })++ it('remove deletes the home ON the host, and throws when it could not', async () => {+ await call(IPC.codexAccountsRemove, 'acct1', CTX)+ expect(mgr.remoteCodexAccountRemove).toHaveBeenCalledWith('p1', 'acct1')+ mgr.remoteCodexAccountRemove.mockResolvedValueOnce(false)+ await expect(call(IPC.codexAccountsRemove, 'acct1', CTX)).rejects.toThrow(/SSH host/)+ })+})diff --git a/src/main/codex-accounts.test.ts b/src/main/codex-accounts.test.tsindex ae082aa7b..04b309b6e 100644--- a/src/main/codex-accounts.test.ts+++ b/src/main/codex-accounts.test.ts@@ -119,8 +119,9 @@ describe('Codex local account lifecycle (Task 5.1)', () => {it('systemIdentity reads THIS Mac by default but fails closed for a remote projectId', async () => {// No ctx ⇒ this Mac's system login (the mocked app-server reader).await expect(call(IPC.codexAccountsSystemIdentity)).resolves.toEqual({ email: '[email protected]' })- // A remote `{ projectId }` request cannot be resolved by this build, so it MUST resolve null —- // never THIS Mac's identity (§5 "system-account discovery must not fabricate an account"; a+ // A remote `{ projectId }` request with no SSH manager to ask cannot be resolved, so it MUST+ // resolve null — never THIS Mac's identity (with a manager it asks the host: see+ // codex-accounts.remote.test.ts) (§5 "system-account discovery must not fabricate an account"; a// remote machine panel never borrows the local login).// MUTATION PIN: change the handler to return `accountIdentity()` for a remote projectId// (fail-OPEN) and this assertion reds.diff --git a/src/main/codex-accounts.ts b/src/main/codex-accounts.tsindex 4b052fbfc..773eee55e 100644--- a/src/main/codex-accounts.ts+++ b/src/main/codex-accounts.ts@@ -203,19 +203,56 @@ export function initCodexAccounts(getSshManager?: () => SshProjectManager | unde// very first spawn.migrateLegacyCodexAccountHomes(platform().userDataDir)- ipcMain.handle(IPC.codexAccountsAdd, async () => {+ /**+ * The SSH leg of every account verb: a `{ projectId }` ctx names a CONNECTED SSH project, and the+ * account's home lives on that host. Resolved here, once, so each handler either takes the remote+ * path or the local one — never both, and never the local one for a ctx it could not resolve+ * (that would mint, poll or delete a home on the wrong machine).+ */+ const remoteFor = (ctx?: { projectId?: string }): { mgr: SshProjectManager; projectId: string } | null => {+ const projectId = typeof ctx?.projectId === 'string' && ctx.projectId ? ctx.projectId : undefined+ if (!projectId) return null+ const mgr = getSshManager?.()+ if (!mgr) throw new Error('SSH is not available in this build')+ return { mgr, projectId }+ }++ ipcMain.handle(IPC.codexAccountsAdd, async (_event, ctx?: { projectId?: string }) => {const id = randomUUID()+ const remote = remoteFor(ctx)+ if (remote) {+ // Creates the isolated home ON the host (umask 077, shared non-secret assets symlinked in).+ // The credential is written there by the device login the renderer opens next — it never+ // travels. Throws with the failed phase, which the Settings row shows.+ const res = await remote.mgr.remoteCodexAccountAdd(remote.projectId, id)+ if (!res) throw new Error('The SSH project is not connected')+ return { id, home: res.home }+ }return { id, home: await initializeAccountHome(id) }})- ipcMain.handle(IPC.codexAccountsWaitLogin, async (_event, id: string) => {+ ipcMain.handle(IPC.codexAccountsWaitLogin, async (_event, id: string, ctx?: { projectId?: string }) => {assertCodexAccountId(id)+ const remote = remoteFor(ctx)const home = localCodexAccountHome(id)const waiter = { cancelled: false }waiters.set(id, waiter)const deadline = Date.now() + LOGIN_TIMEOUT_MStry {while (!waiter.cancelled && Date.now() < deadline) {+ if (remote) {+ // Same gate as locally (a real, non-symlink auth.json), asked ON the host. The email comes+ // from the account's own app-server; a host that cannot run one (no node/curl for the+ // relay) still completes the login, just without an email to name the row by.+ if (await remote.mgr.remoteCodexAuthPresent(remote.projectId, id)) {+ const identity = await remote.mgr+ .remoteCodexAccountIdentity(remote.projectId, id)+ .catch(() => null)+ return identity ?? { email: null }+ }+ await new Promise((resolve) => setTimeout(resolve, LOGIN_POLL_MS))+ continue+ }try {// The login gate: a REAL file, never a symlink. A device login writes auth.json into the// managed home; a symlink here would mean the account is riding the system credential.@@ -240,20 +277,47 @@ export function initCodexAccounts(getSshManager?: () => SshProjectManager | undeif (waiter) waiter.cancelled = true})- ipcMain.handle(IPC.codexAccountsIdentity, (_event, id: string) => existingManagedIdentity(id))+ // The two READS fail closed to `null` when a remote ctx cannot be served (no SSH manager): an+ // unknown identity is an answer, and it must never be THIS Mac's.+ const remoteForRead = (ctx?: { projectId?: string }): ReturnType<typeof remoteFor> | 'unservable' => {+ try {+ return remoteFor(ctx)+ } catch {+ return 'unservable'+ }+ }- // No ctx ⇒ this Mac's system identity. A `{ projectId }` ctx asks for a remote HOST's system- // identity, which this build does not yet resolve — fail closed to `null` rather than returning- // THIS Mac's login, so a remote machine panel never fabricates/borrows a local identity- // (§5 "system-account discovery must not fabricate an account"). Remote resolution is a follow-up.- ipcMain.handle(- IPC.codexAccountsSystemIdentity,- (_event, ctx?: { projectId?: string }) =>- ctx?.projectId ? Promise.resolve(null) : accountIdentity()- )+ ipcMain.handle(IPC.codexAccountsIdentity, async (_event, id: string, ctx?: { projectId?: string }) => {+ const remote = remoteForRead(ctx)+ if (remote === 'unservable') return null+ if (!remote) return existingManagedIdentity(id)+ // `remoteCodexAccountIdentity` refuses (null) a home with no REAL auth.json of its own, so a+ // not-yet-logged-in remote account never reports the host's system identity.+ return remote.mgr.remoteCodexAccountIdentity(remote.projectId, id).catch(() => null)+ })++ // No ctx ⇒ this Mac's system identity. A `{ projectId }` ctx asks the connected HOST's own+ // `~/.codex`, through its app-server. Every failure is `null` — a remote machine panel shows no+ // email rather than borrowing this Mac's login (§5 "system-account discovery must not fabricate").+ ipcMain.handle(IPC.codexAccountsSystemIdentity, async (_event, ctx?: { projectId?: string }) => {+ const remote = remoteForRead(ctx)+ if (remote === 'unservable') return null+ if (!remote) return accountIdentity()+ return remote.mgr.remoteCodexAccountIdentity(remote.projectId, undefined).catch(() => null)+ })- ipcMain.handle(IPC.codexAccountsRemove, async (_event, id: string) => {+ ipcMain.handle(IPC.codexAccountsRemove, async (_event, id: string, ctx?: { projectId?: string }) => {assertCodexAccountId(id)+ const remote = remoteFor(ctx)+ if (remote) {+ const waiter = waiters.get(id)+ if (waiter) waiter.cancelled = true+ // Stops the account's app-server and deletes its home ON the host (credential included).+ if (!(await remote.mgr.remoteCodexAccountRemove(remote.projectId, id))) {+ throw new Error('Could not remove the Codex account on the SSH host — is it connected?')+ }+ return+ }// Property 10 — race/use-safe removal. Refuse while a switch reservation holds this account, or// while a concurrent removal is already in flight.if (diff --git a/src/main/remote-ssh/ssh-project.codex-auth.test.ts b/src/main/remote-ssh/ssh-project.codex-auth.test.tsnew file mode 100644index 000000000..9e576d20f--- /dev/null+++ b/src/main/remote-ssh/ssh-project.codex-auth.test.ts@@ -0,0 +1,51 @@+// `remoteCodexAuthPresent` — the remote Codex login gate: a REAL auth.json on the host, never a+// symlink, and "could not ask" (null) kept apart from "no" so a poll never reads a dead master as a+// finished login.+import { describe, expect, it, vi } from 'vitest'+import { SshProjectManager } from './ssh-project'+import type { SshConnection } from '@shared/ssh'+import { remoteCodexHome } from '../../core/codex-accounts-core'++const conn: SshConnection = { host: 'h', user: 'u' }++function makeMgr(reply: { code: number; stdout: string }) {+ const probes: string[] = []+ const run = vi.fn(async (args: string[]) => {+ const cmd = args.at(-1) ?? ''+ if (cmd.includes('auth.json')) {+ probes.push(cmd)+ return reply+ }+ return args.join(' ').includes('printf %s') ? { code: 0, stdout: '/home/u' } : { code: 0, stdout: '' }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),+ run,+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: vi.fn()+ })+ return { mgr, probes }+}++describe('SshProjectManager.remoteCodexAuthPresent', () => {+ it('checks for a real, non-symlink auth.json in the account home on the host', async () => {+ const { mgr, probes } = makeMgr({ code: 0, stdout: 'motd\nyes\n' })+ await mgr.connect('p1', conn, '/srv')+ expect(await mgr.remoteCodexAuthPresent('p1', 'acct1')).toBe(true)+ const auth = `${remoteCodexHome('/home/u', 'acct1')}/auth.json`+ expect(probes[0]).toContain(`test -f '${auth}'`)+ expect(probes[0]).toContain(`test ! -L '${auth}'`)+ })++ it('answers false for "no", and null when it could not ask', async () => {+ const no = makeMgr({ code: 0, stdout: 'no\n' })+ await no.mgr.connect('p1', conn, '/srv')+ expect(await no.mgr.remoteCodexAuthPresent('p1', 'acct1')).toBe(false)+ const dead = makeMgr({ code: 255, stdout: '' })+ await dead.mgr.connect('p1', conn, '/srv')+ expect(await dead.mgr.remoteCodexAuthPresent('p1', 'acct1')).toBeNull()+ expect(await makeMgr({ code: 0, stdout: 'yes' }).mgr.remoteCodexAuthPresent('p1', 'acct1')).toBeNull()+ })+})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 952aa10ec..90106d796 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -1888,6 +1888,33 @@ export class SshProjectManager {}}+ /**+ * Has this managed remote account completed its device login? The same gate the local waitLogin+ * uses — a REAL `auth.json`, never a symlink (shared assets are symlinked in from the system home;+ * a credential riding the system login is not this account's). `null` = could not ask (not+ * connected, unsafe `$HOME`, failed ssh), which a poll treats as "not yet", never as "yes".+ */+ async remoteCodexAuthPresent(projectId: string, accountId: string): Promise<boolean | null> {+ assertCodexAccountId(accountId)+ const c = this.conns.get(projectId)+ if (!c || !isSafeRemoteHome(c.remoteHome)) return null+ const auth = `${remoteCodexHome(c.remoteHome as string, accountId)}/auth.json`+ try {+ const { code, stdout } = await this.r.run(+ childArgs(+ c.conn,+ c.controlPath,+ `if test -f ${posixQuote(auth)} && test ! -L ${posixQuote(auth)}; then echo yes; else echo no; fi`+ )+ )+ if (code !== 0) return null+ const answer = stdout.trim().split('\n').pop()+ return answer === 'yes' ? true : answer === 'no' ? false : null+ } catch {+ return null+ }+ }+/** Stop the account's app-server and delete its home (credential jar included). Runs entirely on* the host — the credential never travels. No-op false when not connected. */async remoteCodexAccountRemove(projectId: string, accountId: string): Promise<boolean> {diff --git a/src/preload/index.ts b/src/preload/index.tsindex dccb9f93f..6ded394a6 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -565,12 +565,12 @@ const api: NodeTerminalApi = {ipcRenderer.invoke(IPC.claudeAccountsCopySession, sessionId, sourceAccountId, targetAccountId)},codexAccounts: {- add: () => ipcRenderer.invoke(IPC.codexAccountsAdd),- waitLogin: (id) => ipcRenderer.invoke(IPC.codexAccountsWaitLogin, id),+ add: (ctx) => ipcRenderer.invoke(IPC.codexAccountsAdd, ctx),+ waitLogin: (id, ctx) => ipcRenderer.invoke(IPC.codexAccountsWaitLogin, id, ctx),cancelWaitLogin: (id) => ipcRenderer.invoke(IPC.codexAccountsCancelWait, id),- identity: (id) => ipcRenderer.invoke(IPC.codexAccountsIdentity, id),+ identity: (id, ctx) => ipcRenderer.invoke(IPC.codexAccountsIdentity, id, ctx),systemIdentity: (ctx) => ipcRenderer.invoke(IPC.codexAccountsSystemIdentity, ctx),- remove: (id) => ipcRenderer.invoke(IPC.codexAccountsRemove, id),+ remove: (id, ctx) => ipcRenderer.invoke(IPC.codexAccountsRemove, id, ctx),switchThread: (threadId, cwd, sourceAccountId, targetAccountId) =>ipcRenderer.invoke(IPC.codexAccountsSwitchThread,diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex fbfd8d141..600edaca1 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -937,6 +937,16 @@ describe('createCodexAccountLoginNode', () => {)expect(createCodexAccountLoginNode('acct-2', 0).data.cwd).toBeUndefined()})++ it('logs a REMOTE account in on its host with the device flow (the browser callback cannot reach it)', () => {+ const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' } as never+ const node = createCodexAccountLoginNode('acct-2', 0, undefined, '/local/repo', ssh)+ expect(node.data.initialCommand).toBe('codex login --device-auth')+ expect(node.data.accountId).toBe('acct-2')+ expect(node.data.ssh).toBeTruthy()+ expect(node.data.cwd).toBe('/srv/app')+ expect(createCodexAccountLoginNode('acct-2', 0).data.initialCommand).toBe('codex login')+ })})describe('createSystemLoginNode (issue #420)', () => {diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 414845aff..d5feae820 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -833,24 +833,30 @@ export function createAccountLoginNode(** 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.* `cwd` carries the same weight as it does on the Claude sibling above (issue #553): a login node* with none starts in `$HOME`, and a CLI whose trust check is keyed on the cwd then asks about the- * whole home directory. Being local-only, the caller must pass a LOCAL directory — the active- * project's cwd, which an SSH project does not have.+ * whole home directory. For a LOCAL account the caller passes the active project's local cwd.+ *+ * `ssh` makes it a REMOTE login, for an account whose home was created on that host+ * (`codexAccounts.add({ projectId })`): the node runs in the host's tmux, where the remote spawn+ * scopes it to the account's `CODEX_HOME`, and `createTerminalNode` roots it at `ssh.remoteCwd`.+ * The command is `codex login --device-auth` there: the default flow opens a browser and waits for+ * a callback on the HOST's localhost, which the user's browser cannot reach. The device flow prints+ * a URL + code to finish anywhere. Trailing param, so every local call stays byte-identical.*/export function createCodexAccountLoginNode(accountId: string,index: number,center?: { x: number; y: number },- cwd?: string+ cwd?: string,+ ssh?: Project['ssh']): CanvasNode {- const node = createTerminalNode(index, cwd, center)+ const node = createTerminalNode(index, cwd, center, undefined, ssh)node.data = {...node.data,title: 'Codex login',accountId,- initialCommand: 'codex login'+ initialCommand: ssh ? 'codex login --device-auth' : 'codex login'}return node}diff --git a/src/shared/types.ts b/src/shared/types.tsindex f9a45f8fe..12a1dde8c 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2833,22 +2833,26 @@ export interface ClaudeSkillShareResult {*/export interface CodexAccountsApi {/** Mint a new managed account: create its private CODEX_HOME (0700) and symlink the shared,- * non-secret runtime assets in. Returns the new id + its home. */- add(): Promise<{ id: string; home: string }>+ * non-secret runtime assets in. Returns the new id + its home. With an SSH `ctx` the home is+ * created ON that connected host (no credential ever travels); throws when it cannot be. */+ add(ctx?: AccountSshCtx): Promise<{ id: string; home: string }>/** Poll the account's `auth.json` (a real file, never a symlink) every 2s up to 5min for a- * completed device login, then read its email; null on timeout/cancel. */- waitLogin(id: string): Promise<{ email: string | null } | null>+ * completed device login, then read its email; null on timeout/cancel. With an SSH `ctx` the poll+ * runs on the host, and a login whose email cannot be read there resolves `{ email: null }`. */+ waitLogin(id: string, ctx?: AccountSshCtx): Promise<{ email: string | null } | null>/** Cancel an in-flight `waitLogin` for this account. */cancelWaitLogin(id: string): Promise<void>- /** Read a managed account's already-logged-in identity (email), or null if not logged in. */- identity(id: string): Promise<{ email: string | null } | null>+ /** Read a managed account's already-logged-in identity (email), or null if not logged in. With an+ * SSH `ctx`, asked of the account's home on that host. */+ identity(id: string, ctx?: AccountSshCtx): Promise<{ email: string | null } | null>/** Read a machine's system (`~/.codex`) account identity. No arg ⇒ this Mac. `{ projectId }` ⇒* the connected SSH host behind that project; a host whose system identity cannot be resolved* resolves `null` (fail-closed — a remote machine panel never borrows this Mac's login). */systemIdentity(ctx?: { projectId?: string }): Promise<{ email: string | null } | null>/** Remove a managed account: stop its daemon and delete its home. Refused while a switch- * reservation holds it or a concurrent removal is in flight (Property 10). */- remove(id: string): Promise<void>+ * reservation holds it or a concurrent removal is in flight (Property 10). With an SSH `ctx`,+ * the home is deleted on that host; throws when it could not be. */+ remove(id: string, ctx?: AccountSshCtx): Promise<void>/** Phase 1 of the owner-authorized same-machine switch: plan + reserve the rollout exposure of a* conversation from one account to another under a `rollbackToken` (TTL 60s, owner = caller). */switchThread(