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.

fix(accounts): persist Codex scope before opening login terminal

enes9532134fc343
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0223794bd..1217e6e4e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -690,3 +690,7 @@ Two files, two audiences:
**If you change or discover something other contributors must know, update this file too.** An
invariant that only lives in a commit message is one refactor away from being violated by someone
who never saw it.
+
+Managed Codex login terminals are agent-less: core identifies their provider from the saved
+account list. Before opening one, await `useSettings.getState().flush()` after adding the account.
+The normal 300 ms coalesced save is too late: an unknown id can launch against the system home.
diff --git a/src/core/pty-claude-account-spawn.test.ts b/src/core/pty-claude-account-spawn.test.ts
index f28ef7761..2e68556c7 100644
--- a/src/core/pty-claude-account-spawn.test.ts
+++ b/src/core/pty-claude-account-spawn.test.ts
@@ -13,7 +13,8 @@
* refusal and the spawn count.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
-import { mkdirSync, mkdtempSync, rmSync } from 'fs'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { execFileSync } from 'child_process'
import os from 'os'
import path from 'path'
import { initPlatform, resetPlatformForTests } from './platform'
@@ -65,6 +66,7 @@ describe('a managed Claude account is not a Codex account (#345)', () => {
mgr.registerIpc()
})
afterEach(() => {
+ vi.unstubAllEnvs()
resetPlatformForTests()
rmSync(userDataDir, { recursive: true, force: true })
})
@@ -83,14 +85,14 @@ describe('a managed Claude account is not a Codex account (#345)', () => {
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()
+ expect(spawned[0].env.CODEX_HOME).toBe(process.env.CODEX_HOME)
})
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()
+ expect(spawned[0].env.CODEX_HOME).toBe(process.env.CODEX_HOME)
})
it('the agent-less `codex login` terminal STILL gets the managed Codex scope', async () => {
@@ -107,4 +109,31 @@ describe('a managed Claude account is not a Codex account (#345)', () => {
expect(res.unavailable).toBe('codex-account')
expect(spawned).toHaveLength(0)
})
+
+ it('login writes only the managed credential and strips inherited API keys (#683)', async () => {
+ const systemHome = path.join(userDataDir, 'system-codex')
+ mkdirSync(systemHome)
+ writeFileSync(path.join(systemHome, 'auth.json'), 'system-fixture-unchanged')
+ vi.stubEnv('CODEX_HOME', systemHome)
+ vi.stubEnv('OPENAI_API_KEY', 'fixture-openai-key')
+ vi.stubEnv('CODEX_API_KEY', 'fixture-codex-key')
+ const home = codexAccountHome(userDataDir, CODEX_ACCT)
+ mkdirSync(home, { recursive: true })
+ try {
+ const res = await create({ accountId: CODEX_ACCT, persistKey: 'fixture-login' })
+ expect(res.unavailable).toBeUndefined()
+ const env = spawned[0].env
+ expect(env.CODEX_HOME).toBe(home)
+ expect(env.OPENAI_API_KEY).toBeUndefined()
+ expect(env.CODEX_API_KEY).toBeUndefined()
+ // A disposable fake CLI consumes the actual spawn environment. No Codex login/network.
+ execFileSync(process.execPath, ['-e',
+ "require('fs').writeFileSync(require('path').join(process.env.CODEX_HOME, 'auth.json'), 'managed-fixture')"
+ ], { env })
+ expect(readFileSync(path.join(home, 'auth.json'), 'utf8')).toBe('managed-fixture')
+ expect(readFileSync(path.join(systemHome, 'auth.json'), 'utf8')).toBe('system-fixture-unchanged')
+ } finally {
+ rmSync(home, { recursive: true, force: true })
+ }
+ })
})
diff --git a/src/renderer/components/settings/sections/AccountsSection.codex-login.test.tsx b/src/renderer/components/settings/sections/AccountsSection.codex-login.test.tsx
new file mode 100644
index 000000000..dccc18905
--- /dev/null
+++ b/src/renderer/components/settings/sections/AccountsSection.codex-login.test.tsx
@@ -0,0 +1,94 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { AccountsSection } from './AccountsSection'
+import { useSettings } from '../../../state/settings'
+import { DEFAULT_SETTINGS, type Settings } from '@shared/types'
+
+let root: Root
+let host: HTMLDivElement
+let acknowledge: () => void
+let rejectSave: (error: Error) => void
+let published: Settings
+let launched: string[]
+let listener: EventListener
+const waitLogin = vi.fn()
+const save = vi.fn()
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ published = { ...DEFAULT_SETTINGS }
+ launched = []
+ waitLogin.mockReset().mockResolvedValue({ email: '[email protected]' })
+ save.mockReset().mockImplementation((settings: Settings) => new Promise<void>((resolve, reject) => {
+ acknowledge = () => { published = settings; resolve() }
+ rejectSave = reject
+ }))
+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS }, hydrated: true })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ usage: { fetch: async () => null },
+ ssh: { list: async () => [] },
+ settings: { save },
+ codexAccounts: {
+ add: async () => ({ id: 'fixture-codex', home: '/fixture/managed' }),
+ systemIdentity: async () => null,
+ identity: async () => null,
+ waitLogin
+ }
+ }
+ listener = ((event: CustomEvent<{ accountId: string }>) => {
+ // The agent-less PTY resolves its provider from MAIN's list, not the renderer's store.
+ const id = event.detail.accountId
+ launched.push(published.codexAccounts.some((a) => a.id === id) ? id : 'SYSTEM')
+ }) as EventListener
+ window.addEventListener('nodeterm:add-codex-account-login', listener)
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<AccountsSection isActive />))
+})
+
+afterEach(async () => {
+ act(() => root.unmount())
+ window.removeEventListener('nodeterm:add-codex-account-login', listener)
+ host.remove()
+ // Drain the pending identity update's ordinary coalesced save before leaving jsdom.
+ save.mockResolvedValue(undefined)
+ await useSettings.getState().flush()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+})
+
+async function add(): Promise<void> {
+ const button = [...host.querySelectorAll('button')].find((b) => b.textContent === 'Add Codex account')!
+ expect(button).toBeTruthy()
+ await act(async () => button.click())
+}
+
+describe('managed Codex login settings barrier (#683)', () => {
+ it('waits for main to know the account before launching, then clears pending after identity capture', async () => {
+ await add()
+ expect(launched).toEqual([])
+ expect(save).toHaveBeenCalledTimes(1)
+ expect(waitLogin).not.toHaveBeenCalled()
+ await act(async () => { await vi.advanceTimersByTimeAsync(300) })
+ expect(save).toHaveBeenCalledTimes(1)
+ expect(launched).toEqual([])
+ await act(async () => { acknowledge() })
+ expect(launched).toEqual(['fixture-codex'])
+ expect(waitLogin).toHaveBeenCalledWith('fixture-codex')
+ expect(useSettings.getState().settings.codexAccounts[0]).toMatchObject({
+ id: 'fixture-codex', email: '[email protected]', pending: false
+ })
+ })
+
+ it('does not launch or poll when publishing the account fails', async () => {
+ await add()
+ await act(async () => rejectSave(new Error('fixture write failure')))
+ expect(launched).toEqual([])
+ expect(waitLogin).not.toHaveBeenCalled()
+ expect(host.textContent).toContain('Could not set up the Codex account.')
+ })
+})
diff --git a/src/renderer/components/settings/sections/AccountsSection.tsx b/src/renderer/components/settings/sections/AccountsSection.tsx
index 077005dad..6957e1524 100644
--- a/src/renderer/components/settings/sections/AccountsSection.tsx
+++ b/src/renderer/components/settings/sections/AccountsSection.tsx
@@ -437,6 +437,9 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
const added = await window.nodeTerminal.codexAccounts.add()
const account: CodexAccount = { id: added.id, label: 'New Codex account', pending: true }
applyCodexAccounts((accs) => [...accs, account])
+ // PTY scoping identifies this agent-less login by the core's account list. The ordinary
+ // settings save is coalesced for 300 ms; launching before it lands uses the system home.
+ await useSettings.getState().flush()
window.dispatchEvent(
new CustomEvent('nodeterm:add-codex-account-login', { detail: { accountId: added.id } })
)
diff --git a/src/renderer/state/settings.ts b/src/renderer/state/settings.ts
index cb885d773..fd8b7ae90 100644
--- a/src/renderer/state/settings.ts
+++ b/src/renderer/state/settings.ts
@@ -7,6 +7,8 @@ interface SettingsState {
hydrated: boolean
hydrate(): Promise<void>
update(patch: Partial<Settings>): void
+ /** Publish current settings before an operation whose core-side decision depends on them. */
+ flush(): Promise<void>
}
// Coalesce disk writes: the settings inputs fire update() per keystroke/step-click, and each
@@ -41,6 +43,15 @@ export const useSettings = create<SettingsState>((set, get) => ({
settings: DEFAULT_SETTINGS,
hydrated: false,
+ async flush() {
+ if (saveTimer) clearTimeout(saveTimer)
+ saveTimer = null
+ pendingSave = null
+ // Always send the current snapshot, even if the timer already dispatched an older save.
+ // Core's FIFO writer makes this acknowledgement a barrier for that earlier write too.
+ await window.nodeTerminal.settings.save(get().settings)
+ },
+
async hydrate() {
const s = await window.nodeTerminal.settings.load()
set({ settings: { ...DEFAULT_SETTINGS, ...s }, hydrated: true })