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): local accounts, device login, and the three-phase account switch

Claude Code451142d000ae
diff --git a/src/core/codex-accounts-core.test.ts b/src/core/codex-accounts-core.test.ts
index f19ea3bbb..19fc79cbd 100644
--- a/src/core/codex-accounts-core.test.ts
+++ b/src/core/codex-accounts-core.test.ts
@@ -23,6 +23,7 @@ import {
codexSocketForAccount,
codexTmuxEnvArgs,
codexUsageAccounts,
+ ensureSharedCodexDaemon,
legacyCodexAccountHome,
migrateLegacyCodexAccountHome,
migrateLegacyCodexAccountHomes,
@@ -541,3 +542,27 @@ describe('cross-account rollout exposure (atomic, never-overwrite)', () => {
expect(plan.sourceIno).toBe(stat.ino)
})
})
+
+describe('ensureSharedCodexDaemon: reuse-if-reachable-else-start-once (§2.2)', () => {
+ it('does NOT start when the app-server is already reachable', async () => {
+ let started = 0
+ await ensureSharedCodexDaemon(
+ async () => true,
+ async () => {
+ started++
+ }
+ )
+ expect(started).toBe(0)
+ })
+
+ it('starts exactly once when the app-server is not reachable', async () => {
+ let started = 0
+ await ensureSharedCodexDaemon(
+ async () => false,
+ async () => {
+ started++
+ }
+ )
+ expect(started).toBe(1)
+ })
+})
diff --git a/src/core/codex-accounts-core.ts b/src/core/codex-accounts-core.ts
index 62ec305ea..dd69cc5eb 100644
--- a/src/core/codex-accounts-core.ts
+++ b/src/core/codex-accounts-core.ts
@@ -155,6 +155,22 @@ export function remoteCodexTmuxEnvArgs(remoteHome: string, accountId?: string):
])
}
+/**
+ * One shared Codex `app-server` per (machine, account): reuse it if it is already reachable, else
+ * start it exactly once (§2.2, the RAM-saver — not one app-server per node). `probe` answers "is a
+ * live app-server already listening on this account's control socket?"; `start` boots one. Kept in
+ * core (pure control flow over two injected effects) so the same primitive arms on desktop and on
+ * headless Server Edition, and so a test drives it with fakes rather than a real Codex CLI.
+ * Based on @Corvin's `ensureSharedCodexDaemon` in PR #112.
+ */
+export async function ensureSharedCodexDaemon(
+ probe: () => Promise<boolean>,
+ start: () => Promise<void>
+): Promise<void> {
+ if (await probe()) return
+ await start()
+}
+
/**
* Explicit per-session env. An EMPTY account id means the system account and is written
* explicitly, so it OVERWRITES any managed `NODETERM_CODEX_ACCOUNT_ID` inherited from a parent
diff --git a/src/main/codex-accounts.switch.test.ts b/src/main/codex-accounts.switch.test.ts
new file mode 100644
index 000000000..0fe73610d
--- /dev/null
+++ b/src/main/codex-accounts.switch.test.ts
@@ -0,0 +1,192 @@
+/**
+ * The three-phase, owner-authorized, TTL-bounded same-machine Codex account switch (S6 §4.1 /
+ * Properties 5 & 10). Driven against the REAL rollout primitives on a REAL temp filesystem
+ * (planCodexRolloutExposure / commitCodexRolloutExposure — constraint 8: no re-implementation); only
+ * the electron shell boundary, the app-server readers, and the relay-root effect are faked.
+ *
+ * MUTATIONS (recorded in the PR body):
+ * - drop `pending.owner.id === event.sender.id` in commit ⇒ a non-owner WebContents commits ⇒ red.
+ * - drop the `pendingSwitchExposures` guard in remove ⇒ removal succeeds while a switch holds the
+ * account ⇒ red.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } 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
+ }
+ }
+}))
+
+// The app-server client + relay root are runtime effects (probe U4/U6, unrunnable headless). Fake
+// them; the rollout copy under test is the real fs primitive.
+const readThread = vi.fn()
+const readAccount = vi.fn(async () => ({ email: '[email protected]' }))
+vi.mock('../core/codex-session-name', () => ({
+ readCodexThreadAt: (..._a: any[]) => readThread(),
+ readCodexAccountAt: (..._a: any[]) => readAccount()
+}))
+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'
+import { codexAccountHome } from '../core/codex-accounts-core'
+
+const SOURCE = 'acctsource1'
+const TARGET = 'accttarget1'
+const THREAD = 'thread-abc123'
+
+let userDataDir = ''
+let sourceRollout = ''
+
+/** A WebContents-shaped fake: `.id` + the listener surface the switch protocol drives. */
+const makeSender = (id: number) => {
+ const listeners: Array<() => void> = []
+ return {
+ id,
+ isDestroyed: () => false,
+ once: (_ev: string, cb: () => void) => listeners.push(cb),
+ removeListener: () => {},
+ fireDestroyed: () => listeners.forEach((cb) => cb())
+ }
+}
+const call = (channel: string, sender: any, ...args: any[]) =>
+ h.handlers[channel]({ sender }, ...args)
+
+beforeEach(async () => {
+ h.handlers = {}
+ readThread.mockReset()
+ readAccount.mockReset().mockResolvedValue({ email: '[email protected]' })
+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-switch-'))
+ // Real homes at the exact paths the module computes, with a real rollout under source/sessions.
+ const sourceHome = codexAccountHome(userDataDir, SOURCE)
+ const targetHome = codexAccountHome(userDataDir, TARGET)
+ const sessionsDir = path.join(sourceHome, 'sessions', '2026', '08')
+ mkdirSync(sessionsDir, { recursive: true })
+ mkdirSync(path.join(targetHome, 'sessions'), { recursive: true })
+ sourceRollout = path.join(sessionsDir, `rollout-${THREAD}.jsonl`)
+ writeFileSync(sourceRollout, '{"id":"' + THREAD + '"}\n')
+ readThread.mockResolvedValue({ id: THREAD, name: null, path: sourceRollout })
+ // Fresh module state per test (the reservation maps live at module scope). resetModules resets the
+ // platform module too, so init it on the freshly-imported instance codex-accounts will bind to.
+ vi.resetModules()
+ const { initPlatform } = await import('../core/platform')
+ initPlatform(fakePlatform({ userDataDir }))
+ const { initCodexAccounts } = await import('./codex-accounts')
+ initCodexAccounts()
+})
+afterEach(async () => {
+ const { resetPlatformForTests } = await import('../core/platform')
+ resetPlatformForTests()
+ rmSync(userDataDir, { recursive: true, force: true })
+ vi.clearAllTimers()
+})
+
+describe('Codex same-machine switch — three-phase, owner-authorized (Properties 5, 10)', () => {
+ it('reserves, commits an atomic hardlink into the target, and preserves the conversation id', async () => {
+ const owner = makeSender(1)
+ const res = (await call(
+ IPC.codexAccountsSwitchThread,
+ owner,
+ THREAD,
+ '/work',
+ SOURCE,
+ TARGET
+ )) as { threadId: string; rollbackToken?: string }
+ expect(res.threadId).toBe(THREAD)
+ expect(res.rollbackToken).toBeTruthy()
+
+ await call(IPC.codexAccountsCommitSwitch, owner, res.rollbackToken)
+
+ // The target now holds the SAME inode (byte-identical conversation id survives the copy).
+ const targetPath = path.join(
+ codexAccountHome(userDataDir, TARGET),
+ 'sessions',
+ '2026',
+ '08',
+ `rollout-${THREAD}.jsonl`
+ )
+ const src = statSync(sourceRollout)
+ const tgt = statSync(targetPath)
+ expect(tgt.ino).toBe(src.ino)
+ expect(tgt.dev).toBe(src.dev)
+
+ // Finishing releases the reservation, so the account is removable again.
+ await call(IPC.codexAccountsFinishSwitch, owner, res.rollbackToken)
+ expect(readThread).toHaveBeenCalled()
+ })
+
+ it('a non-owner WebContents cannot commit or finish the switch', async () => {
+ const owner = makeSender(1)
+ const attacker = makeSender(2)
+ const res = (await call(IPC.codexAccountsSwitchThread, owner, THREAD, '/work', SOURCE, TARGET)) as {
+ rollbackToken?: string
+ }
+ // commit/finish/rollback are synchronous handlers, so a refusal throws synchronously.
+ expect(() => call(IPC.codexAccountsCommitSwitch, attacker, res.rollbackToken)).toThrow(
+ /preparation expired/
+ )
+ // The owner can still commit — the attacker's attempt did not consume the reservation.
+ expect(call(IPC.codexAccountsCommitSwitch, owner, res.rollbackToken)).toBeUndefined()
+ // A non-owner cannot finish the (now committed) switch either.
+ expect(() => call(IPC.codexAccountsFinishSwitch, attacker, res.rollbackToken)).toThrow(
+ /was not committed/
+ )
+ })
+
+ it('removal refuses while a switch reservation holds either account (Property 10)', async () => {
+ const owner = makeSender(1)
+ await call(IPC.codexAccountsSwitchThread, owner, THREAD, '/work', SOURCE, TARGET)
+ await expect(call(IPC.codexAccountsRemove, owner, SOURCE)).rejects.toThrow(
+ /reserved by an account switch/
+ )
+ await expect(call(IPC.codexAccountsRemove, owner, TARGET)).rejects.toThrow(
+ /reserved by an account switch/
+ )
+ })
+
+ it('the TTL releases the reservation, unblocking removal and voiding a late commit', async () => {
+ vi.useFakeTimers()
+ try {
+ const owner = makeSender(1)
+ const res = (await call(IPC.codexAccountsSwitchThread, owner, THREAD, '/work', SOURCE, TARGET)) as {
+ rollbackToken?: string
+ }
+ vi.advanceTimersByTime(60_000)
+ // The reservation is gone: a late (synchronous) commit is refused.
+ expect(() => call(IPC.codexAccountsCommitSwitch, owner, res.rollbackToken)).toThrow(
+ /preparation expired/
+ )
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('owner destroyed auto-releases the reservation', async () => {
+ const owner = makeSender(1)
+ const res = (await call(IPC.codexAccountsSwitchThread, owner, THREAD, '/work', SOURCE, TARGET)) as {
+ rollbackToken?: string
+ }
+ owner.fireDestroyed()
+ expect(() => call(IPC.codexAccountsCommitSwitch, owner, res.rollbackToken)).toThrow(
+ /preparation expired/
+ )
+ })
+
+ it('a no-op switch to the same account short-circuits without reserving', async () => {
+ const owner = makeSender(1)
+ const res = (await call(IPC.codexAccountsSwitchThread, owner, THREAD, '/work', SOURCE, SOURCE)) as {
+ rollbackToken?: string
+ }
+ expect(res.rollbackToken).toBeUndefined()
+ // Nothing reserved ⇒ removal is not blocked.
+ await expect(call(IPC.codexAccountsRemove, owner, SOURCE)).resolves.toBeUndefined()
+ })
+})
diff --git a/src/main/codex-accounts.test.ts b/src/main/codex-accounts.test.ts
new file mode 100644
index 000000000..8857f2811
--- /dev/null
+++ b/src/main/codex-accounts.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Task 5.1 — local managed Codex account lifecycle: add (private 0700 home + shared-asset symlinks),
+ * the device-login gate (a REAL non-symlink auth.json), and race/use-safe removal (Property 10).
+ * Real filesystem under mkdtemp; only the electron shell, the app-server readers, the CLI lookup,
+ * and the relay-root effect are faked.
+ *
+ * MUTATIONS (recorded in the PR body):
+ * - switch the login gate's `fs.lstat` to `fs.stat` (follows the symlink) ⇒ a symlinked credential
+ * pointed at the system jar counts as logged in ⇒ the symlink test reddens. (lstat is the
+ * load-bearing guard: under lstat a symlink's `isFile()` is already false; the explicit
+ * `!isSymbolicLink()` is belt-and-braces on top.)
+ * - drop the `removingCodexAccounts` in-progress guard ⇒ a concurrent removal is admitted ⇒ red.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { lstatSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } 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) }
+}))
+const readAccount = vi.fn(async () => ({ email: '[email protected]' }))
+vi.mock('../core/codex-session-name', () => ({
+ readCodexThreadAt: vi.fn(async () => null),
+ readCodexAccountAt: (..._a: any[]) => readAccount()
+}))
+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'
+import { codexAccountHome } from '../core/codex-accounts-core'
+
+let userDataDir = ''
+let systemHome = ''
+const sender = { id: 1, isDestroyed: () => false, once: () => {}, removeListener: () => {} }
+const call = (channel: string, ...args: any[]) => h.handlers[channel]({ sender }, ...args)
+
+beforeEach(async () => {
+ h.handlers = {}
+ readAccount.mockReset().mockResolvedValue({ email: '[email protected]' })
+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-acct-'))
+ systemHome = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-sys-'))
+ // A system home with a shared, non-secret asset + directory to be symlinked into managed homes.
+ writeFileSync(path.join(systemHome, 'config.toml'), 'model = "gpt"\n')
+ mkdirSync(path.join(systemHome, 'skills'))
+ process.env.CODEX_HOME = systemHome
+ vi.resetModules()
+ const { initPlatform } = await import('../core/platform')
+ initPlatform(fakePlatform({ userDataDir }))
+ const { initCodexAccounts } = await import('./codex-accounts')
+ initCodexAccounts()
+})
+afterEach(async () => {
+ const { resetPlatformForTests } = await import('../core/platform')
+ resetPlatformForTests()
+ delete process.env.CODEX_HOME
+ rmSync(userDataDir, { recursive: true, force: true })
+ rmSync(systemHome, { recursive: true, force: true })
+})
+
+describe('Codex local account lifecycle (Task 5.1)', () => {
+ it('add mints a 0700 home and symlinks the shared, non-secret runtime assets', async () => {
+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }
+ expect(id).toMatch(/^[0-9a-f-]{36}$/)
+ expect(home).toBe(codexAccountHome(userDataDir, id))
+ if (process.platform !== 'win32') expect(lstatSync(home).mode & 0o777).toBe(0o700)
+ // config.toml + skills are symlinks INTO the system home (installation shared, creds are not).
+ expect(lstatSync(path.join(home, 'config.toml')).isSymbolicLink()).toBe(true)
+ expect(lstatSync(path.join(home, 'skills')).isSymbolicLink()).toBe(true)
+ // auth.json is NEVER symlinked in — a managed account acts only as its own login.
+ expect(() => lstatSync(path.join(home, 'auth.json'))).toThrow()
+ })
+
+ it('the login gate returns the identity for a REAL non-symlink auth.json', async () => {
+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }
+ writeFileSync(path.join(home, 'auth.json'), '{"tokens":{}}')
+ expect(await call(IPC.codexAccountsWaitLogin, id)).toEqual({ email: '[email protected]' })
+ })
+
+ it('the login gate REFUSES a symlinked auth.json (Property 10 / §2.1)', async () => {
+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }
+ // A credential that is a SYMLINK (e.g. pointed at the system jar) is not "logged in".
+ const realCred = path.join(systemHome, 'auth.json')
+ writeFileSync(realCred, '{"tokens":{}}')
+ symlinkSync(realCred, path.join(home, 'auth.json'))
+ const pending = call(IPC.codexAccountsWaitLogin, id) as Promise<unknown>
+ // The first gate check SKIPS the symlink; cancelling makes the loop return null after its single
+ // 2s poll sleep (real timers — deterministic, well under the test timeout) instead of the 5min
+ // deadline. A gate that (wrongly) accepted the symlink would return the identity here.
+ call(IPC.codexAccountsCancelWait, id)
+ expect(await pending).toBeNull()
+ }, 15_000)
+
+ it('refuses a concurrent removal of the same account (Property 10)', async () => {
+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }
+ expect(home).toBeTruthy()
+ // Two removals launched back-to-back: the first synchronously claims the in-progress lock before
+ // its first await, so the second is refused.
+ const first = call(IPC.codexAccountsRemove, id) as Promise<void>
+ await expect(call(IPC.codexAccountsRemove, id)).rejects.toThrow(/already in progress/)
+ await expect(first).resolves.toBeUndefined()
+ })
+
+ it('rejects an unsafe account id before it becomes a path (supply-chain guard)', async () => {
+ await expect(call(IPC.codexAccountsWaitLogin, '../escape')).rejects.toThrow(/Invalid Codex account id/)
+ await expect(call(IPC.codexAccountsRemove, '../escape')).rejects.toThrow(/Invalid Codex account id/)
+ })
+})
diff --git a/src/main/codex-accounts.transfer.test.ts b/src/main/codex-accounts.transfer.test.ts
new file mode 100644
index 000000000..e9ecd330a
--- /dev/null
+++ b/src/main/codex-accounts.transfer.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Task 5.3 — the SOURCE side of moving an idle local conversation to an SSH account. The remote
+ * landing is PR 6; this leg validates STRICT source containment (a regular file under
+ * `<sourceHome>/sessions/`, basename `<threadId>.jsonl`, no symlinked segment — reusing PR 3's
+ * `planCodexRolloutExposure` guards) and only THEN hands the upload to the remote importer, with the
+ * local rollout left untouched.
+ *
+ * MUTATION (recorded in the PR body): let the handler skip `planCodexRolloutExposure` and call the
+ * importer with the raw source path ⇒ the escaping-source test admits the upload ⇒ red. The pin
+ * below asserts the importer is NEVER called when the source escapes `sessions/`.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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) }
+}))
+const readThread = vi.fn()
+vi.mock('../core/codex-session-name', () => ({
+ readCodexThreadAt: (..._a: any[]) => readThread(),
+ 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'
+import { codexAccountHome } from '../core/codex-accounts-core'
+
+const SOURCE = 'acctsource1'
+const TARGET = 'accttarget1'
+const THREAD = 'thread-abc123'
+const PROJECT = 'proj-1'
+
+let userDataDir = ''
+let sourceHome = ''
+const remoteCodexImportThread = vi.fn(async () => ({ imported: true }))
+const sender = { id: 1, isDestroyed: () => false, once: () => {}, removeListener: () => {} }
+const call = (channel: string, ...args: any[]) => h.handlers[channel]({ sender }, ...args)
+
+beforeEach(async () => {
+ h.handlers = {}
+ readThread.mockReset()
+ remoteCodexImportThread.mockClear()
+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-xfer-'))
+ sourceHome = codexAccountHome(userDataDir, SOURCE)
+ mkdirSync(path.join(sourceHome, 'sessions', '2026'), { recursive: true })
+ mkdirSync(codexAccountHome(userDataDir, TARGET), { recursive: true })
+ vi.resetModules()
+ const { initPlatform } = await import('../core/platform')
+ initPlatform(fakePlatform({ userDataDir }))
+ const { initCodexAccounts } = await import('./codex-accounts')
+ // A live SSH manager carrying PR 6's importer.
+ initCodexAccounts(() => ({ remoteCodexImportThread }) as any)
+})
+afterEach(async () => {
+ const { resetPlatformForTests } = await import('../core/platform')
+ resetPlatformForTests()
+ rmSync(userDataDir, { recursive: true, force: true })
+})
+
+describe('Codex local→SSH transfer source leg (Task 5.3)', () => {
+ it('hands a contained source rollout to the remote importer with the sessions-relative path', async () => {
+ const rollout = path.join(sourceHome, 'sessions', '2026', `rollout-${THREAD}.jsonl`)
+ writeFileSync(rollout, '{}\n')
+ readThread.mockResolvedValue({ id: THREAD, name: null, path: rollout })
+
+ const res = (await call(
+ IPC.codexAccountsTransferThreadToSsh,
+ THREAD,
+ '/work',
+ PROJECT,
+ TARGET,
+ SOURCE
+ )) as { threadId: string; imported: boolean }
+
+ expect(res).toEqual({ threadId: THREAD, imported: true })
+ expect(remoteCodexImportThread).toHaveBeenCalledTimes(1)
+ const [projectId, targetAccountId, threadId, sessionsRelativePath, localPath] =
+ remoteCodexImportThread.mock.calls[0] as unknown[]
+ expect(projectId).toBe(PROJECT)
+ expect(targetAccountId).toBe(TARGET)
+ expect(threadId).toBe(THREAD)
+ expect(sessionsRelativePath).toBe(`sessions/2026/rollout-${THREAD}.jsonl`)
+ // The LOCAL rollout is handed by path, never moved.
+ expect(localPath).toBe(rollout)
+ })
+
+ it('refuses a source path escaping sessions/ BEFORE any upload', async () => {
+ // A rollout the app-server reports OUTSIDE the source account's sessions/ (e.g. a crafted
+ // absolute path). Containment must refuse it before the importer is ever reached.
+ const escaping = path.join(userDataDir, `rollout-${THREAD}.jsonl`)
+ writeFileSync(escaping, '{}\n')
+ readThread.mockResolvedValue({ id: THREAD, name: null, path: escaping })
+
+ await expect(
+ call(IPC.codexAccountsTransferThreadToSsh, THREAD, '/work', PROJECT, TARGET, SOURCE)
+ ).rejects.toThrow()
+ expect(remoteCodexImportThread).not.toHaveBeenCalled()
+ })
+
+ it('refuses a basename whose thread id does not match, before any upload', async () => {
+ const wrong = path.join(sourceHome, 'sessions', '2026', 'rollout-someone-else.jsonl')
+ writeFileSync(wrong, '{}\n')
+ readThread.mockResolvedValue({ id: THREAD, name: null, path: wrong })
+ await expect(
+ call(IPC.codexAccountsTransferThreadToSsh, THREAD, '/work', PROJECT, TARGET, SOURCE)
+ ).rejects.toThrow()
+ expect(remoteCodexImportThread).not.toHaveBeenCalled()
+ })
+
+ it('rejects an unsafe thread id at the door', async () => {
+ await expect(
+ call(IPC.codexAccountsTransferThreadToSsh, '../escape', '/work', PROJECT, TARGET, SOURCE)
+ ).rejects.toThrow(/Invalid Codex transfer request/)
+ expect(remoteCodexImportThread).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/codex-accounts.ts b/src/main/codex-accounts.ts
new file mode 100644
index 000000000..1345bf223
--- /dev/null
+++ b/src/main/codex-accounts.ts
@@ -0,0 +1,390 @@
+// Impure lifecycle for machine-scoped managed Codex accounts (S6 PR 5) — the leg that makes
+// account-scoping REACHABLE for LOCAL accounts. Mirrors `claude-accounts.ts` (add / device-login /
+// cancel / remove) and adds the three-phase, owner-authorized SAME-MACHINE switch (resume the same
+// conversation id, never fork) plus the SOURCE side of moving an idle conversation to an SSH
+// account. The account LIST is renderer-owned in `settings.json` (`codexAccounts`); this module owns
+// only the filesystem, the per-account app-server daemon, and the switch reservation state.
+//
+// The copy primitives are NOT re-implemented here: `planCodexRolloutExposure` /
+// `commitCodexRolloutExposure` (src/core/codex-accounts-core.ts, PR 3) are the atomic, never-
+// overwrite hardlink. Based on @Corvin's `codex-accounts.ts` in PR #112, re-sliced onto the PR 3/4
+// primitives with the SSH transfer source leg (its remote landing is PR 6).
+import { randomUUID } from 'crypto'
+import { execFile } from 'child_process'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import { promisify } from 'util'
+import { ipcMain, type WebContents } from 'electron'
+import { IPC } from '../shared/ipc'
+import {
+ assertCodexAccountId,
+ commitCodexRolloutExposure,
+ codexAccountHome,
+ codexHomeForAccount,
+ codexSessionEnv,
+ codexSocketForAccount,
+ ensureSharedCodexDaemon,
+ legacyCodexAccountHome,
+ migrateLegacyCodexAccountHome,
+ migrateLegacyCodexAccountHomes,
+ planCodexRolloutExposure,
+ type CodexRolloutExposurePlan
+} from '../core/codex-accounts-core'
+import { readCodexAccountAt, readCodexThreadAt } from '../core/codex-session-name'
+import { ensureCodexRelayRoot } from './codex-relay-daemon'
+import { platform } from '../core/platform'
+import { findInLoginPath } from '../core/pty-manager'
+import type { SshProjectManager } from './remote-ssh/ssh-project'
+
+const execFileP = promisify(execFile)
+const LOGIN_POLL_MS = 2000
+const LOGIN_TIMEOUT_MS = 5 * 60 * 1000
+/** Non-secret runtime assets symlinked from the system home into each managed home: shared
+ * installation, never a credential or the thread SQLite DB. */
+const SHARED_ENTRIES = ['config.toml', 'AGENTS.md', 'skills', 'plugins', 'packages', 'rules', 'hooks.json']
+const SWITCH_RESERVATION_TTL_MS = 60_000
+/** A threadId that could reach the filesystem as a path component. Same shape as ACCOUNT_ID_RE. */
+const SAFE_THREAD_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
+
+/** PR 6 provides this on the SSH manager. Typed structurally here so PR 5 can hand the source leg
+ * off without depending on PR 6's implementation. */
+type CodexSshImporter = {
+ remoteCodexImportThread?(
+ projectId: string,
+ accountId: string | undefined,
+ threadId: string,
+ sessionsRelativePath: string,
+ localRolloutPath: string
+ ): Promise<{ imported: boolean }>
+}
+
+const waiters = new Map<string, { cancelled: boolean }>()
+
+/**
+ * One in-flight switch reservation. Holds the planned (but maybe not yet committed) exposure, the
+ * two account ids it pins (so removal refuses while it holds them — Property 10), the owning
+ * WebContents (every phase must be driven by the SAME renderer — Property owner-authorized), and
+ * the auto-release wiring (owner `destroyed` or the TTL).
+ */
+type PendingSwitchExposure = {
+ exposure?: CodexRolloutExposurePlan
+ sourceAccountId?: string
+ targetAccountId?: string
+ committed: boolean
+ owner: WebContents
+ ownerDestroyed: () => void
+ timer: ReturnType<typeof setTimeout>
+}
+const pendingSwitchExposures = new Map<string, PendingSwitchExposure>()
+const removingCodexAccounts = new Set<string>()
+
+function releasePendingSwitch(token: string): void {
+ const pending = pendingSwitchExposures.get(token)
+ if (!pending) return
+ pendingSwitchExposures.delete(token)
+ clearTimeout(pending.timer)
+ if (!pending.owner.isDestroyed()) pending.owner.removeListener('destroyed', pending.ownerDestroyed)
+}
+
+export function localCodexAccountHome(accountId: string): string {
+ return codexAccountHome(platform().userDataDir, accountId)
+}
+
+export function localCodexSocket(accountId?: string): string {
+ return codexSocketForAccount(platform().userDataDir, accountId)
+}
+
+/**
+ * Reuse the account's shared app-server if it is already answering on its control socket, else boot
+ * one exactly once (§2.2). The managed home is migrated to its short form first so the app-server
+ * Unix socket stays under `SUN_LEN`. UNVERIFIED against a real Codex CLI headless (probe U4/U6) —
+ * device-verification owed; the control flow (probe → start-once) is pure and tested via injection.
+ */
+export async function ensureCodexAccountDaemon(accountId?: string): Promise<void> {
+ if (accountId) migrateLegacyCodexAccountHome(platform().userDataDir, accountId)
+ const socket = localCodexSocket(accountId)
+ await ensureSharedCodexDaemon(
+ async () => (await readCodexAccountAt(socket, 1000)) !== null,
+ async () => {
+ const codex = await findInLoginPath('codex')
+ if (!codex) throw new Error('Codex CLI unavailable')
+ await execFileP(codex, ['app-server', 'daemon', 'start'], {
+ cwd: os.homedir(),
+ env: { ...process.env, ...codexSessionEnv(platform().userDataDir, accountId) },
+ timeout: 15_000,
+ maxBuffer: 1024 * 1024
+ })
+ }
+ )
+}
+
+/**
+ * Create a managed account's private home (0700) and symlink the shared, NON-secret runtime assets
+ * from the system home in. Credentials (`auth.json`) and the thread DB are never shared — only
+ * installation assets. A missing source asset is skipped; an existing target link is left as-is.
+ */
+async function initializeAccountHome(id: string): Promise<string> {
+ migrateLegacyCodexAccountHome(platform().userDataDir, id)
+ const home = localCodexAccountHome(id)
+ await fs.mkdir(home, { recursive: true, mode: 0o700 })
+ await fs.chmod(home, 0o700)
+ const sourceHome = process.env.CODEX_HOME?.trim() || path.join(os.homedir(), '.codex')
+ for (const name of SHARED_ENTRIES) {
+ const source = path.join(sourceHome, name)
+ const target = path.join(home, name)
+ try {
+ await fs.lstat(source)
+ await fs.symlink(source, target)
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code
+ if (code !== 'ENOENT' && code !== 'EEXIST') throw error
+ }
+ }
+ return home
+}
+
+async function accountIdentity(accountId?: string): Promise<{ email: string | null } | null> {
+ await ensureCodexAccountDaemon(accountId)
+ return readCodexAccountAt(localCodexSocket(accountId), 5000)
+}
+
+/**
+ * Read an already-logged-in managed account's identity. The login GATE is a REAL non-symlink
+ * `auth.json`: a symlinked or absent credential is "not logged in" and returns null (Property 10 /
+ * §2.1 — a managed account acts only as its OWN login, never a symlink into the system jar).
+ */
+async function existingManagedIdentity(id: string): Promise<{ email: string | null } | null> {
+ assertCodexAccountId(id)
+ try {
+ migrateLegacyCodexAccountHome(platform().userDataDir, id)
+ const auth = await fs.lstat(path.join(localCodexAccountHome(id), 'auth.json'))
+ if (!auth.isFile() || auth.isSymbolicLink()) return null
+ return await accountIdentity(id)
+ } catch {
+ return null
+ }
+}
+
+/**
+ * @param getSshManager Lazily resolves the SSH project manager (created after this init in
+ * index.ts). Only the local→SSH transfer SOURCE leg uses it today; local account ops never do.
+ */
+export function initCodexAccounts(getSshManager?: () => SshProjectManager | undefined): void {
+ // Ensure `~/.nodeterm` exists before any relay/daemon reach (carried PR-4 obligation: only the
+ // relay's detached serve() created it before, so a first reach from this process could race a
+ // missing root).
+ ensureCodexRelayRoot()
+ // Synchronous, BEFORE renderer hydration / PTY restore: a legacy long CODEX_HOME cannot host the
+ // app-server Unix socket, and an already-persisted managed node must see its migrated home on its
+ // very first spawn.
+ migrateLegacyCodexAccountHomes(platform().userDataDir)
+
+ ipcMain.handle(IPC.codexAccountsAdd, async () => {
+ const id = randomUUID()
+ return { id, home: await initializeAccountHome(id) }
+ })
+
+ ipcMain.handle(IPC.codexAccountsWaitLogin, async (_event, id: string) => {
+ assertCodexAccountId(id)
+ const home = localCodexAccountHome(id)
+ const waiter = { cancelled: false }
+ waiters.set(id, waiter)
+ const deadline = Date.now() + LOGIN_TIMEOUT_MS
+ try {
+ while (!waiter.cancelled && Date.now() < deadline) {
+ 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.
+ const auth = await fs.lstat(path.join(home, 'auth.json'))
+ if (auth.isFile() && !auth.isSymbolicLink()) {
+ const identity = await accountIdentity(id)
+ if (identity) return identity
+ }
+ } catch {
+ // No credential file yet, or its daemon is not ready — keep polling.
+ }
+ await new Promise((resolve) => setTimeout(resolve, LOGIN_POLL_MS))
+ }
+ return null
+ } finally {
+ waiters.delete(id)
+ }
+ })
+
+ ipcMain.handle(IPC.codexAccountsCancelWait, (_event, id: string) => {
+ const waiter = waiters.get(id)
+ if (waiter) waiter.cancelled = true
+ })
+
+ ipcMain.handle(IPC.codexAccountsIdentity, (_event, id: string) => existingManagedIdentity(id))
+
+ ipcMain.handle(IPC.codexAccountsSystemIdentity, () => accountIdentity())
+
+ ipcMain.handle(IPC.codexAccountsRemove, async (_event, id: string) => {
+ assertCodexAccountId(id)
+ // Property 10 — race/use-safe removal. Refuse while a switch reservation holds this account, or
+ // while a concurrent removal is already in flight.
+ if (
+ [...pendingSwitchExposures.values()].some(
+ (pending) => pending.sourceAccountId === id || pending.targetAccountId === id
+ )
+ ) {
+ throw new Error('Codex account is reserved by an account switch')
+ }
+ if (removingCodexAccounts.has(id)) throw new Error('Codex account removal is already in progress')
+ removingCodexAccounts.add(id)
+ try {
+ const waiter = waiters.get(id)
+ if (waiter) waiter.cancelled = true
+ try {
+ const codex = await findInLoginPath('codex')
+ if (codex) {
+ await execFileP(codex, ['app-server', 'daemon', 'stop'], {
+ cwd: os.homedir(),
+ env: { ...process.env, CODEX_HOME: localCodexAccountHome(id) },
+ timeout: 10_000,
+ maxBuffer: 1024 * 1024
+ })
+ }
+ } catch {
+ // A stopped/missing daemon is already the desired state.
+ }
+ const home = localCodexAccountHome(id)
+ const legacy = legacyCodexAccountHome(platform().userDataDir, id)
+ await fs.rm(home, { recursive: true, force: true })
+ if (legacy !== home) await fs.rm(legacy, { recursive: true, force: true })
+ } finally {
+ removingCodexAccounts.delete(id)
+ }
+ })
+
+ // ---- The three-phase, owner-authorized, TTL-bounded switch (§4.1 / Properties 5, 10) ----------
+
+ ipcMain.handle(
+ IPC.codexAccountsSwitchThread,
+ async (
+ event,
+ threadId: string,
+ cwd: string,
+ sourceAccountId?: string,
+ targetAccountId?: string
+ ) => {
+ if (!SAFE_THREAD_ID.test(threadId) || !path.isAbsolute(cwd)) {
+ throw new Error('Invalid Codex account switch request')
+ }
+ if (sourceAccountId) assertCodexAccountId(sourceAccountId)
+ if (targetAccountId) assertCodexAccountId(targetAccountId)
+ if (sourceAccountId === targetAccountId) return { threadId }
+ if (
+ (sourceAccountId && removingCodexAccounts.has(sourceAccountId)) ||
+ (targetAccountId && removingCodexAccounts.has(targetAccountId))
+ ) {
+ throw new Error('Codex account removal is in progress')
+ }
+ const rollbackToken = randomUUID()
+ const ownerDestroyed = (): void => releasePendingSwitch(rollbackToken)
+ const timer = setTimeout(() => releasePendingSwitch(rollbackToken), SWITCH_RESERVATION_TTL_MS)
+ timer.unref?.()
+ event.sender.once('destroyed', ownerDestroyed)
+ // Reserve BEFORE planning so a concurrent removal of either account is already blocked while
+ // we read the app-server and plan the exposure.
+ pendingSwitchExposures.set(rollbackToken, {
+ sourceAccountId,
+ targetAccountId,
+ committed: false,
+ owner: event.sender,
+ ownerDestroyed,
+ timer
+ })
+ try {
+ await ensureCodexAccountDaemon(sourceAccountId)
+ await ensureCodexAccountDaemon(targetAccountId)
+ const source = await readCodexThreadAt(localCodexSocket(sourceAccountId), threadId, 5000)
+ if (!source?.path) throw new Error('Source Codex conversation is unavailable')
+ const exposure = planCodexRolloutExposure(
+ codexHomeForAccount(platform().userDataDir, sourceAccountId),
+ codexHomeForAccount(platform().userDataDir, targetAccountId),
+ source.path,
+ threadId
+ )
+ const pending = pendingSwitchExposures.get(rollbackToken)
+ if (!pending) throw new Error('Codex account switch preparation expired')
+ pending.exposure = exposure
+ return { threadId, rollbackToken }
+ } catch (error) {
+ releasePendingSwitch(rollbackToken)
+ throw error
+ }
+ }
+ )
+
+ ipcMain.handle(IPC.codexAccountsCommitSwitch, (event, token: string) => {
+ const pending = pendingSwitchExposures.get(token)
+ // Owner-authorized: only the WebContents that reserved the switch may commit it.
+ if (!pending?.exposure || pending.owner.id !== event.sender.id) {
+ throw new Error('Codex account switch preparation expired')
+ }
+ commitCodexRolloutExposure(pending.exposure)
+ pending.committed = true
+ })
+
+ ipcMain.handle(IPC.codexAccountsFinishSwitch, (event, token: string) => {
+ const pending = pendingSwitchExposures.get(token)
+ if (!pending?.committed || pending.owner.id !== event.sender.id) {
+ throw new Error('Codex account switch was not committed')
+ }
+ releasePendingSwitch(token)
+ })
+
+ ipcMain.handle(IPC.codexAccountsRollbackSwitch, (event, token: string) => {
+ const pending = pendingSwitchExposures.get(token)
+ if (pending?.owner.id === event.sender.id) releasePendingSwitch(token)
+ })
+
+ // ---- Local → SSH transfer SOURCE leg (§4.2b, Task 5.3). The remote landing is PR 6 ------------
+
+ ipcMain.handle(
+ IPC.codexAccountsTransferThreadToSsh,
+ async (
+ _event,
+ threadId: string,
+ cwd: string,
+ projectId: string,
+ targetAccountId?: string,
+ sourceAccountId?: string
+ ) => {
+ if (!SAFE_THREAD_ID.test(threadId) || !path.isAbsolute(cwd) || !projectId) {
+ throw new Error('Invalid Codex transfer request')
+ }
+ if (sourceAccountId) assertCodexAccountId(sourceAccountId)
+ if (targetAccountId) assertCodexAccountId(targetAccountId)
+ await ensureCodexAccountDaemon(sourceAccountId)
+ const source = await readCodexThreadAt(localCodexSocket(sourceAccountId), threadId, 5000)
+ if (!source?.path) throw new Error('Source Codex conversation is unavailable')
+ // STRICT SOURCE CONTAINMENT before any upload: reuse PR 3's `planCodexRolloutExposure`
+ // (source-side half) rather than re-implementing the guards. It refuses a source that is not a
+ // regular file, whose basename does not end `<threadId>.jsonl`, or that escapes
+ // `<sourceHome>/sessions/` (realpath + containment + no symlinked segment). Passing the source
+ // home as the target home is safe: only the SOURCE fields are read here, the local rollout is
+ // never linked/moved (it stays fully usable — §4.2 step 6).
+ const sourceHome = codexHomeForAccount(platform().userDataDir, sourceAccountId)
+ const plan = planCodexRolloutExposure(sourceHome, sourceHome, source.path, threadId)
+ const sessionsRelativePath = path.posix.join('sessions', plan.targetRelativePath.split(path.sep).join('/'))
+ // Hand the actual upload + atomic remote install to PR 6's importer. Absent (not yet wired /
+ // no live SSH manager) fails closed with a named error rather than silently succeeding.
+ const importer = getSshManager?.() as (SshProjectManager & CodexSshImporter) | undefined
+ if (!importer?.remoteCodexImportThread) {
+ throw new Error('Remote Codex import is unavailable')
+ }
+ const result = await importer.remoteCodexImportThread(
+ projectId,
+ targetAccountId,
+ threadId,
+ sessionsRelativePath,
+ plan.sourcePath
+ )
+ return { threadId, imported: result.imported }
+ }
+ )
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 816a98e1f..c52392d0f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -188,6 +188,7 @@ import { WhisperModelStore } from '../core/speech/whisper-models'
import { SpeechService } from '../core/speech/speech-service'
import { registerSpeechIpc } from '../core/speech/register-ipc'
import { initClaudeAccounts } from './claude-accounts'
+import { initCodexAccounts } from './codex-accounts'
import { claudeCliCaps, registerClaudeCliIpc, type ClaudeCliCaps } from '../core/claude-cli'
import { refreshCodexIdentityCaps, registerCodexIdentityIpc } from '../core/codex-identity-caps'
import {
@@ -2789,6 +2790,11 @@ app.whenReady().then(async () => {
// Lazy getter: sshProjectManager is created just below, so a remote account op (which only runs
// after the user has connected an SSH project) always sees the live manager.
initClaudeAccounts(() => sshProjectManager)
+ // Machine-scoped managed Codex accounts (S6). Its synchronous boot migration of legacy long
+ // CODEX_HOMEs runs here, before the renderer restores its PTYs — an already-persisted managed
+ // Codex node must see its migrated (SUN_LEN-safe) home on its very first spawn. Same lazy SSH
+ // getter for the local→SSH transfer source leg.
+ initCodexAccounts(() => sshProjectManager)
// The jailed core bridge both phone hosts serve: typed git verbs against the real GitService
// (cwd-jailed to the shared canvas roots inside the handlers) and phone node registration
// through the workspace store (written as an outside edit, so the watcher broadcasts it and
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 9d1d9f1e5..e951faed0 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -468,6 +468,34 @@ const api: NodeTerminalApi = {
cancelWaitLogin: (id) => ipcRenderer.invoke(IPC.claudeAccountsCancelWait, id),
remove: (id, ctx) => ipcRenderer.invoke(IPC.claudeAccountsRemove, id, ctx)
},
+ codexAccounts: {
+ add: () => ipcRenderer.invoke(IPC.codexAccountsAdd),
+ waitLogin: (id) => ipcRenderer.invoke(IPC.codexAccountsWaitLogin, id),
+ cancelWaitLogin: (id) => ipcRenderer.invoke(IPC.codexAccountsCancelWait, id),
+ identity: (id) => ipcRenderer.invoke(IPC.codexAccountsIdentity, id),
+ systemIdentity: () => ipcRenderer.invoke(IPC.codexAccountsSystemIdentity),
+ remove: (id) => ipcRenderer.invoke(IPC.codexAccountsRemove, id),
+ switchThread: (threadId, cwd, sourceAccountId, targetAccountId) =>
+ ipcRenderer.invoke(
+ IPC.codexAccountsSwitchThread,
+ threadId,
+ cwd,
+ sourceAccountId,
+ targetAccountId
+ ),
+ commitSwitch: (token) => ipcRenderer.invoke(IPC.codexAccountsCommitSwitch, token),
+ finishSwitch: (token) => ipcRenderer.invoke(IPC.codexAccountsFinishSwitch, token),
+ rollbackSwitch: (token) => ipcRenderer.invoke(IPC.codexAccountsRollbackSwitch, token),
+ transferThreadToSsh: (threadId, cwd, projectId, targetAccountId, sourceAccountId) =>
+ ipcRenderer.invoke(
+ IPC.codexAccountsTransferThreadToSsh,
+ threadId,
+ cwd,
+ projectId,
+ targetAccountId,
+ sourceAccountId
+ )
+ },
transcripts: {
search: (query: string) => ipcRenderer.invoke(IPC.transcriptSearch, query)
},
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 54099284d..7874d3555 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -303,6 +303,19 @@ export function buildStubApi(): Omit<
cancelWaitLogin: U('claudeAccounts.cancelWaitLogin'),
remove: U('claudeAccounts.remove')
},
+ codexAccounts: {
+ add: U('codexAccounts.add'),
+ waitLogin: U('codexAccounts.waitLogin'),
+ cancelWaitLogin: U('codexAccounts.cancelWaitLogin'),
+ identity: U('codexAccounts.identity'),
+ systemIdentity: U('codexAccounts.systemIdentity'),
+ remove: U('codexAccounts.remove'),
+ switchThread: U('codexAccounts.switchThread'),
+ commitSwitch: U('codexAccounts.commitSwitch'),
+ finishSwitch: U('codexAccounts.finishSwitch'),
+ rollbackSwitch: U('codexAccounts.rollbackSwitch'),
+ transferThreadToSsh: U('codexAccounts.transferThreadToSsh')
+ },
transcripts: {
search: U('transcripts.search')
},
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 09cf5ac14..3d7b92e76 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -41,6 +41,20 @@ export const IPC = {
claudeAccountsWaitLogin: 'claude-accounts:wait-login',
claudeAccountsCancelWait: 'claude-accounts:cancel-wait',
claudeAccountsRemove: 'claude-accounts:remove',
+ // Machine-scoped managed Codex accounts (S6). Add/device-login/removal, plus the three-phase,
+ // owner-authorized account switch (resume the SAME conversation id, never fork) and the
+ // source-side leg of moving an idle conversation to an SSH account. See main/codex-accounts.ts.
+ codexAccountsAdd: 'codex-accounts:add',
+ codexAccountsWaitLogin: 'codex-accounts:wait-login',
+ codexAccountsCancelWait: 'codex-accounts:cancel-wait',
+ codexAccountsIdentity: 'codex-accounts:identity',
+ codexAccountsSystemIdentity: 'codex-accounts:system-identity',
+ codexAccountsRemove: 'codex-accounts:remove',
+ codexAccountsSwitchThread: 'codex-accounts:switch-thread',
+ codexAccountsCommitSwitch: 'codex-accounts:commit-switch',
+ codexAccountsFinishSwitch: 'codex-accounts:finish-switch',
+ codexAccountsRollbackSwitch: 'codex-accounts:rollback-switch',
+ codexAccountsTransferThreadToSsh: 'codex-accounts:transfer-thread-to-ssh',
claudeCliCaps: 'claude-cli:caps',
/** Can a node on this machine get a managed Codex identity? See core/codex-identity-caps.ts. */
codexIdentityCaps: 'codex-identity:caps',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 3b025c0a4..655032a73 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2052,6 +2052,53 @@ export interface ClaudeAccountsApi {
remove(id: string, ctx?: AccountSshCtx): Promise<void>
}
+/**
+ * Machine-scoped managed Codex accounts (S6). LOCAL accounts on this Mac are reachable through
+ * PR 5; SSH remote accounts land in PR 6. The account LIST is renderer-owned in `settings.json`
+ * (`codexAccounts`), exactly like `claudeAccounts`; main owns only the fs + daemon lifecycle and
+ * the switch protocol.
+ */
+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 }>
+ /** 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>
+ /** 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 the system (`~/.codex`) account's identity. */
+ systemIdentity(): 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>
+ /** 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(
+ threadId: string,
+ cwd: string,
+ sourceAccountId?: string,
+ targetAccountId?: string
+ ): Promise<{ threadId: string; rollbackToken?: string }>
+ /** Phase 2: commit the reserved exposure (atomic hardlink into the target account). */
+ commitSwitch(rollbackToken: string): Promise<void>
+ /** Phase 3a: finish a committed switch, releasing the reservation. */
+ finishSwitch(rollbackToken: string): Promise<void>
+ /** Phase 3b: roll back a reservation (releases it; a committed link is left for cleanup). */
+ rollbackSwitch(rollbackToken: string): Promise<void>
+ /** Source-side leg of moving an idle LOCAL conversation to an SSH account: validate strict source
+ * containment then hand the upload to the remote import path (PR 6). Local rollout untouched. */
+ transferThreadToSsh(
+ threadId: string,
+ cwd: string,
+ projectId: string,
+ targetAccountId?: string,
+ sourceAccountId?: string
+ ): Promise<{ threadId: string; imported: boolean }>
+}
+
/** One ranked search hit across all on-disk Claude session transcripts. */
export interface TranscriptHit {
sessionId: string
@@ -2525,6 +2572,7 @@ export interface NodeTerminalApi {
agent: AgentApi
chat: ChatApi
claudeAccounts: ClaudeAccountsApi
+ codexAccounts: CodexAccountsApi
transcripts: TranscriptsApi
remoteHost: RemoteHostApi
relayHost: RelayHostApi