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(windows): managed Codex login + identity without the unix-socket app-server
review2c00bd36d3cf
diff --git a/src/core/codex-accounts-core.test.ts b/src/core/codex-accounts-core.test.tsindex 4940829dc..6caaf5d84 100644--- a/src/core/codex-accounts-core.test.ts+++ b/src/core/codex-accounts-core.test.ts@@ -573,3 +573,42 @@ describe('ensureSharedCodexDaemon: reuse-if-reachable-else-start-once (§2.2)',expect(started).toBe(1)})})++describe('readCodexAuthEmail / codexAppServerReachable (Windows identity leg)', () => {+ const jwt = (payload: unknown): string =>+ ['eyJhbGciOiJSUzI1NiJ9', Buffer.from(JSON.stringify(payload)).toString('base64url'), 'sig'].join('.')+ const auth = (idToken: unknown): string => JSON.stringify({ tokens: { id_token: idToken } })++ it('reads the email claim from the id_token payload (signature not verified — display only)', async () => {+ const { readCodexAuthEmail } = await import('./codex-accounts-core')+ expect(readCodexAuthEmail(auth(jwt({ email: ' [email protected] ' })))).toBe('[email protected]')+ })++ it('falls back to the OpenAI profile claim', async () => {+ const { readCodexAuthEmail } = await import('./codex-accounts-core')+ expect(+ readCodexAuthEmail(auth(jwt({ 'https://api.openai.com/profile': { email: '[email protected]' } })))+ ).toBe('[email protected]')+ })++ it('is null — never a throw — for anything unreadable', async () => {+ const { readCodexAuthEmail } = await import('./codex-accounts-core')+ expect(readCodexAuthEmail('not json')).toBeNull()+ expect(readCodexAuthEmail('null')).toBeNull()+ expect(readCodexAuthEmail('{}')).toBeNull()+ expect(readCodexAuthEmail(JSON.stringify({ tokens: {} }))).toBeNull()+ expect(readCodexAuthEmail(auth(42))).toBeNull()+ expect(readCodexAuthEmail(auth('only-one-part'))).toBeNull()+ expect(readCodexAuthEmail(auth('a.!!not base64!!.c'))).toBeNull()+ expect(readCodexAuthEmail(auth(`a.${Buffer.from('not json').toString('base64url')}.c`))).toBeNull()+ expect(readCodexAuthEmail(auth(jwt({ sub: 'x' })))).toBeNull()+ expect(readCodexAuthEmail(auth(jwt({ email: ' ' })))).toBeNull()+ })++ it('the app-server socket is unreachable on win32 only', async () => {+ const { codexAppServerReachable } = await import('./codex-accounts-core')+ expect(codexAppServerReachable('win32')).toBe(false)+ expect(codexAppServerReachable('darwin')).toBe(true)+ expect(codexAppServerReachable('linux')).toBe(true)+ })+})diff --git a/src/core/codex-accounts-core.ts b/src/core/codex-accounts-core.tsindex cf3df999d..270ad6972 100644--- a/src/core/codex-accounts-core.ts+++ b/src/core/codex-accounts-core.ts@@ -107,6 +107,47 @@ export function systemCodexHome(): string {return configured && path.isAbsolute(configured) ? configured : path.join(os.homedir(), '.codex')}+/**+ * Whether this host can reach a Codex app-server over its `ws+unix://` control socket. Not on+ * Windows: libuv cannot dial an AF_UNIX path through `ws+unix`, and `codexUnixWebSocketUrl` refuses+ * a drive-letter path (its `:`) anyway — so every identity / title read there would fail after a+ * daemon start that can only time out. Callers degrade to the on-disk sources instead+ * (`readCodexAuthEmail`, the relayed title). A named-pipe endpoint is the follow-up once one is+ * confirmed on a device.+ */+export function codexAppServerReachable(hostPlatform: NodeJS.Platform): boolean {+ return hostPlatform !== 'win32'+}++/**+ * The login email from a Codex `auth.json`, read from the `tokens.id_token` JWT's payload (the+ * `email` claim, else the `https://api.openai.com/profile` claim's `email`). The signature is NOT+ * verified and does not need to be: the result is a DISPLAY LABEL for the account row only — the+ * login gate stays the real, non-symlink `auth.json` check. Never throws; anything unreadable is+ * `null`.+ */+export function readCodexAuthEmail(authJson: string): string | null {+ try {+ const token = (JSON.parse(authJson) as { tokens?: { id_token?: unknown } } | null)?.tokens?.id_token+ if (typeof token !== 'string') return null+ const parts = token.split('.')+ if (parts.length < 2 || !/^[A-Za-z0-9_-]+={0,2}$/.test(parts[1])) return null+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as Record<+ string,+ unknown+ > | null+ if (!payload || typeof payload !== 'object') return null+ const pick = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v.trim() : null)+ const profile = payload['https://api.openai.com/profile']+ return (+ pick(payload.email) ??+ (profile && typeof profile === 'object' ? pick((profile as Record<string, unknown>).email) : null)+ )+ } catch {+ return null+ }+}+/** System vs managed is presence/absence of an id: no id ⇒ `~/.codex`; a valid id ⇒ its short home. */export function codexHomeForAccount(userDataDir: string, accountId?: string): string {return accountId ? codexAccountHome(userDataDir, accountId) : systemCodexHome()diff --git a/src/core/codex-session-name.test.ts b/src/core/codex-session-name.test.tsindex 4e097b34c..ac0e7d7a8 100644--- a/src/core/codex-session-name.test.ts+++ b/src/core/codex-session-name.test.ts@@ -295,3 +295,30 @@ describe('readCodexThreadAt / readCodexAccountAt', () => {expect(await readCodexAccountAt(s)).toEqual({ email: '[email protected]' })})})++describe('readCodexSessionName on a host with no reachable app-server (Windows)', () => {+ it('serves the relayed copy without dialing the socket', async () => {+ const savedHome = process.env.HOME+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-name-win-'))+ process.env.HOME = home+ forgetCodexSessionNames()+ try {+ // `thread-known` has a real server name; on win32 the socket is never asked, so the relayed+ // copy is the answer — proof that no WebSocket was dialed.+ const scope = createHash('sha256').update(sock).digest('hex').slice(0, 16)+ const nameDir = path.join(home, '.nodeterm', 'codex-thread-names', scope)+ fs.mkdirSync(nameDir, { recursive: true })+ fs.writeFileSync(path.join(nameDir, 'thread-known'), 'Relayed only')+ expect(await readCodexSessionName('thread-known', sock, 'win32')).toBe('Relayed only')+ expect(await readCodexSessionName('thread-absent', sock, 'win32')).toBeNull()+ // A seeded cache still wins first.+ rememberCodexSessionName('thread-seeded-win', 'Seeded', sock)+ expect(await readCodexSessionName('thread-seeded-win', sock, 'win32')).toBe('Seeded')+ } finally {+ forgetCodexSessionNames()+ if (savedHome === undefined) delete process.env.HOME+ else process.env.HOME = savedHome+ fs.rmSync(home, { recursive: true, force: true })+ }+ })+})diff --git a/src/core/codex-session-name.ts b/src/core/codex-session-name.tsindex 4503c7a01..2de6bd066 100644--- a/src/core/codex-session-name.ts+++ b/src/core/codex-session-name.ts@@ -25,6 +25,7 @@ import { WebSocket } from 'ws'// copy of the bare charset, which accepted `.` and `..` — harmless over the RPC wire here, but the// ids it validates (a thread the app-server just minted, one a node persisted) are handed straight// to the record store, where they ARE path segments. One rule, so the two cannot drift apart.+import { codexAppServerReachable } from './codex-accounts-core'import { CODEX_THREAD_START_TIMEOUT_MS, isSafeThreadId } from './codex-identity-proxy'/**@@ -668,15 +669,23 @@ export function forgetCodexSessionNames(): void {** When the shared app-server reports no name, fall back to the relay's on-disk copy* (`relayedCodexSessionName`) so a conversation forked in the TUI still shows its title.+ *+ * On a host that cannot reach the app-server at all (Windows — see `codexAppServerReachable`) the+ * relayed copy IS the read: no socket connect that can only fail, on every sweep. A named-pipe+ * app-server endpoint is the follow-up once one is confirmed on a device.*/export function readCodexSessionName(threadId: string,- socketPath = defaultCodexAppServerSocket()+ socketPath = defaultCodexAppServerSocket(),+ hostPlatform: NodeJS.Platform = process.platform): Promise<string | null> {if (!isSafeThreadId(threadId)) return Promise.resolve(null)const key = `${socketPath}\0${threadId}`const cached = names.get(key)if (cached && Date.now() - cached.at < CACHE_MS) return Promise.resolve(cached.name)+ if (!codexAppServerReachable(hostPlatform)) {+ return Promise.resolve(relayedCodexSessionName(socketPath, threadId))+ }const running = inflight.get(key)if (running) return runningconst request = readCodexSessionNameAt(socketPath, threadId).then(diff --git a/src/main/codex-accounts.test.ts b/src/main/codex-accounts.test.tsindex 04b309b6e..c72dac9a9 100644--- a/src/main/codex-accounts.test.ts+++ b/src/main/codex-accounts.test.ts@@ -25,7 +25,8 @@ 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) }))+const findInLoginPath = vi.fn(async () => null)+vi.mock('../core/pty-manager', () => ({ findInLoginPath: (..._a: any[]) => findInLoginPath() }))const ensureRelayRoot = vi.fn()vi.mock('./codex-relay-daemon', () => ({ ensureCodexRelayRoot: ensureRelayRoot }))@@ -41,6 +42,7 @@ const call = (channel: string, ...args: any[]) => h.handlers[channel]({ sender }beforeEach(async () => {h.handlers = {}ensureRelayRoot.mockClear()+ findInLoginPath.mockClear()readAccount.mockReset().mockResolvedValue({ email: '[email protected]' })userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-acct-'))systemHome = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-sys-'))@@ -128,3 +130,60 @@ describe('Codex local account lifecycle (Task 5.1)', () => {await expect(call(IPC.codexAccountsSystemIdentity, { projectId: 'proj-1' })).resolves.toBeNull()})})++describe('Codex identity on a host with no reachable app-server (Windows)', () => {+ const jwt = (email: string): string =>+ ['h', Buffer.from(JSON.stringify({ email })).toString('base64url'), 's'].join('.')+ const authJson = (email: string): string => JSON.stringify({ tokens: { id_token: jwt(email) } })++ beforeEach(async () => {+ const { setCodexAccountsHostPlatformForTests } = await import('./codex-accounts')+ setCodexAccountsHostPlatformForTests('win32')+ })+ afterEach(async () => {+ const { setCodexAccountsHostPlatformForTests } = await import('./codex-accounts')+ setCodexAccountsHostPlatformForTests(null)+ })++ it('waitLogin resolves the auth.json JWT email with NO daemon start and NO socket read', async () => {+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }+ writeFileSync(path.join(home, 'auth.json'), authJson('[email protected]'))+ expect(await call(IPC.codexAccountsWaitLogin, id)).toEqual({ email: '[email protected]' })+ expect(await call(IPC.codexAccountsIdentity, id)).toEqual({ email: '[email protected]' })+ expect(findInLoginPath).not.toHaveBeenCalled()+ expect(readAccount).not.toHaveBeenCalled()+ })++ it('a credential with no readable email still completes the login (email: null)', 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: null })+ })++ it.skipIf(process.platform === 'win32')('still REFUSES a symlinked auth.json', async () => {+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }+ const realCred = path.join(systemHome, 'auth.json')+ writeFileSync(realCred, authJson('[email protected]'))+ symlinkSync(realCred, path.join(home, 'auth.json'))+ expect(await call(IPC.codexAccountsIdentity, id)).toBeNull()+ const pending = call(IPC.codexAccountsWaitLogin, id) as Promise<unknown>+ call(IPC.codexAccountsCancelWait, id)+ expect(await pending).toBeNull()+ }, 15_000)++ it('the system identity reads the SYSTEM home\'s auth.json, and is null without one', async () => {+ expect(await call(IPC.codexAccountsSystemIdentity)).toBeNull()+ writeFileSync(path.join(systemHome, 'auth.json'), authJson('[email protected]'))+ expect(await call(IPC.codexAccountsSystemIdentity)).toEqual({ email: '[email protected]' })+ expect(readAccount).not.toHaveBeenCalled()+ })++ it('POSIX keeps the app-server path (regression pin)', async () => {+ const { setCodexAccountsHostPlatformForTests } = await import('./codex-accounts')+ setCodexAccountsHostPlatformForTests('linux')+ const { id, home } = (await call(IPC.codexAccountsAdd)) as { id: string; home: string }+ writeFileSync(path.join(home, 'auth.json'), authJson('[email protected]'))+ expect(await call(IPC.codexAccountsWaitLogin, id)).toEqual({ email: '[email protected]' })+ expect(readAccount).toHaveBeenCalled()+ })+})diff --git a/src/main/codex-accounts.ts b/src/main/codex-accounts.tsindex e28724648..7a77a4865 100644--- a/src/main/codex-accounts.ts+++ b/src/main/codex-accounts.ts@@ -19,6 +19,7 @@ import { ipcMain, type WebContents } from 'electron'import { IPC } from '../shared/ipc'import {assertCodexAccountId,+ codexAppServerReachable,commitCodexRolloutExposure,codexAccountHome,codexHomeForAccount,@@ -29,10 +30,13 @@ import {migrateLegacyCodexAccountHome,migrateLegacyCodexAccountHomes,planCodexRolloutExposure,+ readCodexAuthEmail,+ systemCodexHome,type CodexRolloutExposurePlan} from '../core/codex-accounts-core'import { readCodexAccountAt, readCodexThreadAt } from '../core/codex-session-name'import { directExecutableInvocation } from '../core/exec-path'+import { linkSharedEntry } from '../core/shared-entry-link'import { ensureCodexRelayRoot } from './codex-relay-daemon'import { platform } from '../core/platform'import { findInLoginPath } from '../core/pty-manager'@@ -124,9 +128,10 @@ export async function ensureCodexAccountDaemon(accountId?: string): Promise<void}/**- * 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.+ * Create a managed account's private home (0700) and link the shared, NON-secret runtime assets+ * from the system home in (`linkSharedEntry` — symlinks on POSIX). 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)@@ -136,23 +141,42 @@ async function initializeAccountHome(id: string): Promise<string> {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- }+ // POSIX: a plain symlink. Windows: junction / hardlink / copy, never a blocking EPERM.+ await linkSharedEntry(source, path.join(home, name))}return home}+/** The host OS the identity read branches on — a seam so the Windows leg is testable on Linux. */+let hostPlatform = (): NodeJS.Platform => process.platform+export function setCodexAccountsHostPlatformForTests(p: NodeJS.Platform | null): void {+ hostPlatform = p ? () => p : () => process.platform+}+async function accountIdentity(accountId?: string): Promise<{ email: string | null } | null> {+ if (!codexAppServerReachable(hostPlatform())) return authFileIdentity(accountId)await ensureCodexAccountDaemon(accountId)return readCodexAccountAt(localCodexSocket(accountId), 5000)}+/**+ * The identity on a host with no reachable app-server (Windows): NO daemon start — it could only+ * time out on every poll — just the account's own `auth.json`, under the same gate as the login+ * wait (a REAL file, never a symlink; absent ⇒ `null`). The email is the id_token's claim, a display+ * label only (`readCodexAuthEmail`); a credential with no readable email is still a login.+ */+async function authFileIdentity(accountId?: string): Promise<{ email: string | null } | null> {+ const home = accountId ? localCodexAccountHome(accountId) : systemCodexHome()+ const file = path.join(home, 'auth.json')+ try {+ const auth = await fs.lstat(file)+ if (!auth.isFile() || auth.isSymbolicLink()) return null+ return { email: readCodexAuthEmail(await fs.readFile(file, 'utf8')) }+ } catch {+ return null+ }+}+/*** 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 /