Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cli): follow moved engine homes in remaining readers (#915)

Dee3db20a708f45
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.ts
index e888e49d9..c7950b16b 100644
--- a/cli/e2e/enginehomes.e2e.ts
+++ b/cli/e2e/enginehomes.e2e.ts
@@ -9,9 +9,11 @@
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
-import { IsolatedDaemon, until } from './harness/daemon.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { sharedCodex } from './harness/sharedCodex.js'
type Engine = 'claude' | 'codex'
type Row = Record<string, any>
@@ -52,6 +54,175 @@ describe('the person\'s engines keeping their data elsewhere', () => {
let daemon: IsolatedDaemon | undefined
afterEach(async () => { await daemon?.close(); daemon = undefined })
+ it.each(['claude', 'codex'] as const)('%s model picker follows the login shell home', async engine => {
+ const d = await IsolatedDaemon.create(); daemon = d
+ d.env.NODE_OPTIONS = `--import=${pathToFileURL(join(CLI_ROOT, 'e2e/harness/hiddenProcessEnv.mjs')).href}`
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
+ const home = join(d.root, `${engine}-models`)
+ mkdirSync(home)
+ const variable = engine === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME'
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export ${variable}=${JSON.stringify(home)}\n`)
+ if (engine === 'claude') {
+ writeFileSync(join(d.engineConfig.claudeProjectsDir, '..', 'settings.json'), JSON.stringify({ availableModels: ['haiku'] }))
+ writeFileSync(join(home, 'settings.json'), JSON.stringify({ availableModels: ['sonnet'] }))
+ } else {
+ const cache = (slug: string) => JSON.stringify({ models: [{ slug, display_name: slug, visibility: 'list', supported_reasoning_levels: [{ effort: 'high' }] }] })
+ writeFileSync(join(d.env.CODEX_HOME!, 'models_cache.json'), cache('wrong-login-model'))
+ writeFileSync(join(home, 'models_cache.json'), cache('gpt-6-luna'))
+ }
+ await d.start()
+ await until('the core to read the login shell', () => /\[env\] read \d+ variables/.test(d.log()))
+ const client = await LocalClient.connect(d)
+ const created = await client.request('agent_create', { engine, cwd: d.projectsDir, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('the model-picker agent to bind', async () => {
+ const now = await row(client, created.agent.id); return now?.sessionId ? now : null
+ }, 30_000)
+ if (engine === 'codex') expect(agent.codexHome).toBeNull()
+ const answer = await client.request('models_list', { agentId: agent.id }, 30_000)
+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()
+ const ids = answer.models.map((model: Row) => model.id)
+ expect(ids).toContain(`runtime-v1:${agent.id}:${engine}:${engine === 'claude' ? 'sonnet' : 'gpt-6-luna'}@auto`)
+ expect(ids.some((id: string) => id.includes(engine === 'claude' ? ':haiku@' : ':wrong-login-model@'))).toBe(false)
+ client.close()
+ })
+
+ it.each(['activity', 'resources', 'close'] as const)('a moved shared Codex server supplies %s when process environment discovery is unavailable', async operation => {
+ const d = await IsolatedDaemon.create(); daemon = d
+ d.env.NODE_OPTIONS = `--import=${pathToFileURL(join(CLI_ROOT, 'e2e/harness/hiddenProcessEnv.mjs')).href}`
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
+ const home = join(d.root, 'codex-shared')
+ mkdirSync(home)
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export CODEX_HOME=${JSON.stringify(home)}\n`)
+ // Older Codex releases have a shared server and no --no-daemon flag. Keep the actual CLI probe.
+ writeFileSync(join(d.root, 'bin', 'codex'), `#!${process.execPath}\nimport(${JSON.stringify(pathToFileURL(join(CLI_ROOT, 'e2e/harness/fakeEngine.mjs')).href)}).then(m => m.run('codex', ${JSON.stringify({ ...d.engineConfig, without: ['--no-daemon'] })}))\n`, { mode: 0o755 })
+ const server = await sharedCodex(home)
+ try {
+ await d.start()
+ await until('the core to read the login shell', () => /\[env\] read \d+ variables/.test(d.log()))
+ const client = await LocalClient.connect(d)
+ const created = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('the shared conversation to bind', async () => {
+ const now = await row(client, created.agent.id); return now?.sessionId ? now : null
+ }, 30_000)
+ expect(agent.codexHome).toBeNull()
+ server.state.threadId = agent.sessionId
+ const started = client.next(isTurn('turn_started', agent.id), 30_000)
+ client.send('message', { agentId: agent.id, content: '!hold' })
+ await started
+ if (operation === 'activity') {
+ await until('the activity read at the moved server', () => server.state.requests.some(frame => frame.method === 'thread/read'), 45_000)
+ await until('the app to show verified working activity', async () => (await row(client, agent.id))?.activity?.state === 'working')
+ } else if (operation === 'resources') {
+ await until('the moved server in Harness Monitor', async () => {
+ const answer = await client.request('machine_resources', { harnesses: true })
+ expect(answer.harnesses?.shared, JSON.stringify(answer)).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: 'codex', agentIds: expect.arrayContaining([agent.id]), memoryBytes: expect.any(Number) }),
+ ]))
+ return answer.harnesses.shared.some((value: Row) => value.kind === 'codex' && value.agentIds.includes(agent.id) && value.memoryBytes > 0)
+ }, 20_000)
+ } else {
+ const result = await client.request('agent_close', { agentId: agent.id, sessionId: agent.sessionId, createdAt: agent.createdAt, mode: 'now' }, 90_000)
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ expect(server.state.requests.map(frame => frame.method)).toEqual(expect.arrayContaining(['thread/goal/set', 'turn/interrupt', 'thread/archive', 'thread/unarchive']))
+ expect(server.state.loaded).toBe(false)
+ }
+ client.close()
+ } finally { await server.close() }
+ })
+
+ it('a moved Codex home supplies the thread name shown on its agent', async () => {
+ const d = await IsolatedDaemon.create(); daemon = d
+ d.env.NODE_OPTIONS = `--import=${pathToFileURL(join(CLI_ROOT, 'e2e/harness/hiddenProcessEnv.mjs')).href}`
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
+ const home = join(d.root, 'codex-names')
+ mkdirSync(home)
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export CODEX_HOME=${JSON.stringify(home)}\n`)
+ await d.start()
+ await until('the daemon to read the login shell', () => /\[env\] read \d+ variables/.test(d.log()))
+ const client = await LocalClient.connect(d)
+ const created = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('the named agent to bind', async () => {
+ const now = await row(client, created.agent.id); return now?.sessionId ? now : null
+ }, 30_000)
+ // Codex can rename a thread from another client; the index changes without this pane's title changing.
+ for (const [folder, thread_name] of [[d.env.CODEX_HOME!, 'Wrong login name'], [home, 'Moved home conversation']]) {
+ writeFileSync(join(folder, 'session_index.jsonl'), JSON.stringify({ id: agent.sessionId, thread_name }) + '\n')
+ }
+ expect(agent.codexHome).toBeNull()
+ await until('the moved-home name on the agent', async () => (await row(client, agent.id))?.name === 'Moved home conversation', 20_000)
+ client.close()
+ })
+
+ it('a moved Codex home repairs a parent overwritten by its child when the daemon restarts', async () => {
+ const d = await IsolatedDaemon.create(); daemon = d
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
+ const home = join(d.root, 'codex-parent')
+ mkdirSync(home)
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export CODEX_HOME=${JSON.stringify(home)}\n`)
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const created = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, bypassPermission: true }, 90_000)
+ const agent = await until('the parent to bind', async () => {
+ const now = await row(client, created.agent.id); return now?.sessionId ? now : null
+ }, 30_000)
+ await turn(client, agent.id, '!spawn scout')
+ client.close()
+ await d.stop()
+ const registryFile = join(d.dataDir, 'registry.json')
+ const saved = JSON.parse(readFileSync(registryFile, 'utf8')) as Row[]
+ const parent = saved.find(record => record.sessionId === agent.sessionId)!
+ const parentPath = parent.transcriptPath
+ const folder = join(home, 'sessions', '2026', '10', '03')
+ const child = readdirSync(folder).find(file => file.endsWith('.jsonl') && !file.includes(agent.sessionId))!
+ // Reproduce the on-disk damage an older hook left; current hooks already reject child bindings.
+ parent.transcriptPath = join(folder, child)
+ parent.codexHome = null // A legacy row from before successful process-environment discovery.
+ writeFileSync(registryFile, JSON.stringify(saved), { mode: 0o600 })
+ await d.start()
+ expect(d.log()).toContain(`[registry] repaired Codex parent ${agent.sessionId.slice(0, 8)}`)
+ const repaired = (JSON.parse(readFileSync(registryFile, 'utf8')) as Row[]).find(record => record.sessionId === agent.sessionId)
+ expect(repaired?.transcriptPath).toBe(parentPath)
+ const again = await LocalClient.connect(d)
+ await turn(again, agent.id, 'the parent keeps its own conversation')
+ again.close()
+ })
+
+ it.each(['claude', 'codex'] as const)('search finds external %s conversations in the moved home after startup', async engine => {
+ const d = await IsolatedDaemon.create(); daemon = d
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
+ const home = join(d.root, `${engine}-search`)
+ mkdirSync(home)
+ const variable = engine === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME'
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export ${variable}=${JSON.stringify(home)}\n`)
+ await d.start()
+ await until('the core to adopt the moved home', () => /\[env\] read \d+ variables/.test(d.log()))
+ const sessionId = '11111111-1111-4111-8111-111111111111', at = new Date().toISOString()
+ const folder = join(home, engine === 'claude' ? 'projects/project' : 'sessions/2026/10/06')
+ mkdirSync(folder, { recursive: true })
+ // Native records from a separate terminal, never registered as a Harness agent.
+ const records = engine === 'claude' ? [{ type: 'user', entrypoint: 'cli', sessionId, cwd: d.projectsDir,
+ timestamp: at, uuid: 'question', message: { role: 'user', content: 'movedhomepangolin' } }] : [
+ { type: 'session_meta', timestamp: at, payload: { id: sessionId, cwd: d.projectsDir, source: 'cli' } },
+ { type: 'event_msg', timestamp: at, payload: { type: 'task_started', turn_id: 'external-turn' } },
+ { type: 'event_msg', timestamp: at, payload: { type: 'item_completed', turn_id: 'external-turn', item: { type: 'UserMessage', content: [{ type: 'text', text: 'movedhomepangolin' }] } } },
+ { type: 'event_msg', timestamp: at, payload: { type: 'task_complete', turn_id: 'external-turn' } },
+ ]
+ writeFileSync(join(folder, engine === 'claude' ? `${sessionId}.jsonl` : `rollout-${sessionId}.jsonl`), records.map(record => JSON.stringify(record)).join('\n') + '\n')
+ const client = await LocalClient.connect(d)
+ await until('the search process to connect', () => d.log().includes('[service search] connected to the core'))
+ expect(await client.request('session_search', { query: 'movedhomepangolin' })).not.toHaveProperty('error')
+ await until('search to return the external moved-home conversation', async () => {
+ const answer = await client.request('session_search', { query: 'movedhomepangolin' }, 30_000)
+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()
+ return JSON.stringify(answer).includes(sessionId)
+ }, 45_000, 1000)
+ expect(await rows(client)).toEqual([])
+ client.close()
+ })
+
it.each([
['claude', 'CLAUDE_CONFIG_DIR', 'claude-work'],
['codex', 'CODEX_HOME', 'codex-work'],
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 326e5701d..9c93d8aa1 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -111,6 +111,20 @@ async function codexWrapper(config) {
export async function run(engine, config = {}, { native = false } = {}) {
if (engine === 'codex' && !native) return codexWrapper(config)
const args = process.argv.slice(2)
+ if (engine === 'codex' && args[0] === 'app-server' && args[1] === 'proxy') {
+ // Found by QA on a quiet machine: moved-home close/activity must reach that home's shared server.
+ // Real Codex proxy carries raw WebSocket bytes and fails when the profile has no server; it starts none.
+ const home = process.env.CODEX_HOME || config.codexHome
+ if (!within(config.root, home)) throw new Error('fake Codex proxy outside its throwaway home')
+ const { port } = JSON.parse(readFileSync(join(home, 'app-server-daemon', 'fake-proxy.json'), 'utf8'))
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('invalid fixture server port')
+ const { createConnection } = await import('node:net')
+ const socket = createConnection({ host: '127.0.0.1', port })
+ process.stdin.pipe(socket).pipe(process.stdout)
+ socket.on('error', () => process.exit(1))
+ socket.on('close', () => process.exit(0))
+ return
+ }
const version = config.version ?? (engine === 'claude' ? '2.1.270' : '0.160.0')
const versionLine = engine === 'claude' ? `${version} (Claude Code)` : `codex-cli ${version}`
const without = new Set(config.without ?? [])
diff --git a/cli/e2e/harness/hiddenProcessEnv.mjs b/cli/e2e/harness/hiddenProcessEnv.mjs
new file mode 100644
index 000000000..e5a6bbca6
--- /dev/null
+++ b/cli/e2e/harness/hiddenProcessEnv.mjs
@@ -0,0 +1,30 @@
+// Found by QA on a quiet machine: a failed process-environment probe leaves a valid agent without
+// codexHome. Keep process identity and every other filesystem/process observation real.
+import childProcess from 'node:child_process'
+import { EventEmitter } from 'node:events'
+import fs from 'node:fs/promises'
+import { syncBuiltinESMExports } from 'node:module'
+import { promisify } from 'node:util'
+
+const denied = () => Object.assign(new Error('fixture: process environment is unreadable'), { code: 'EACCES' })
+const execFile = childProcess.execFile
+const execAsync = promisify(execFile)
+childProcess.execFile = function (file, args, ...rest) {
+ if (file === 'ps' && args?.[0] === 'eww') {
+ const child = new EventEmitter()
+ const callback = rest.find(value => typeof value === 'function')
+ queueMicrotask(() => { callback?.(denied(), '', ''); child.emit('close', 1) })
+ return child
+ }
+ return execFile.call(this, file, args, ...rest)
+}
+// Preserve Node's {stdout, stderr} promise result. Dropping its custom promisifier made Monitor's
+// unrelated process-table read fail in this fixture, instead of isolating only the environment probe.
+childProcess.execFile[promisify.custom] = (file, args, ...rest) =>
+ file === 'ps' && args?.[0] === 'eww' ? Promise.reject(denied()) : execAsync(file, args, ...rest)
+const readFile = fs.readFile
+fs.readFile = async function (path, ...rest) {
+ if (/^\/proc\/\d+\/environ$/.test(String(path))) throw denied()
+ return readFile.call(this, path, ...rest)
+}
+syncBuiltinESMExports()
diff --git a/cli/e2e/harness/sharedCodex.ts b/cli/e2e/harness/sharedCodex.ts
new file mode 100644
index 000000000..94b2b4f2d
--- /dev/null
+++ b/cli/e2e/harness/sharedCodex.ts
@@ -0,0 +1,36 @@
+/** The local app-server protocol of an older shared Codex session, without a model or credentials.
+ * Its real loopback WebSocket is reached through the fake CLI's raw-byte `app-server proxy` command. */
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { WebSocketServer } from 'ws'
+
+export async function sharedCodex(home: string) {
+ const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
+ await new Promise<void>((resolve, reject) => { server.once('listening', resolve); server.once('error', reject) })
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('missing fixture server port')
+ const start = execFileSync('ps', ['-o', 'lstart=', '-p', String(process.pid)], { encoding: 'utf8' }).trim()
+ mkdirSync(join(home, 'app-server-daemon'), { recursive: true })
+ writeFileSync(join(home, 'app-server-daemon', 'daemon.pid'), JSON.stringify({ pid: process.pid, processStartTime: start }))
+ writeFileSync(join(home, 'app-server-daemon', 'fake-proxy.json'), JSON.stringify({ port: address.port }))
+ const state = { threadId: '', loaded: true, requests: [] as Array<{ method: string; params?: Record<string, unknown> }> }
+ server.on('connection', socket => socket.on('message', bytes => {
+ const frame = JSON.parse(String(bytes)) as { id?: number; method: string; params?: Record<string, unknown> }
+ state.requests.push(frame)
+ if (frame.id === undefined) return
+ let result: Record<string, unknown> = {}
+ if (frame.method === 'initialize') result = { codexHome: home }
+ else if (frame.params?.threadId !== state.threadId) {
+ socket.send(JSON.stringify({ id: frame.id, error: { message: 'unknown fixture thread' } })); return
+ } else if (frame.method === 'thread/read') result = { thread: { id: state.threadId, status: { type: state.loaded ? 'active' : 'notLoaded' } } }
+ else if (frame.method === 'thread/goal/get') result = { goal: { status: 'active' } }
+ else if (frame.method === 'thread/turns/list') result = { data: [{ id: 'held-turn', status: 'inProgress' }] }
+ else if (frame.method === 'thread/archive') state.loaded = false
+ socket.send(JSON.stringify({ id: frame.id, result }))
+ }))
+ return { state, async close() {
+ for (const socket of server.clients) socket.terminate()
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ } }
+}
diff --git a/cli/src/lib/codexSessionLifecycle.ts b/cli/src/lib/codexSessionLifecycle.ts
index 3ffeef78d..fedf67e86 100644
--- a/cli/src/lib/codexSessionLifecycle.ts
+++ b/cli/src/lib/codexSessionLifecycle.ts
@@ -7,7 +7,7 @@ import { Duplex } from 'node:stream'
import { readFile, realpath } from 'node:fs/promises'
import { basename, join } from 'node:path'
import WebSocket from 'ws'
-import { env } from '../config/env.js'
+import { sessionCodexHome } from './engineHomes.js'
import { engineBin } from './engineBin.js'
import { argvTokens, processRows, type ProcessRow } from './tmux.js'
import type { RegisteredSession } from './registry.js'
@@ -94,7 +94,7 @@ export async function stopSharedCodexSession(session: RegisteredSession, current
deps: CodexStopDeps = { daemonIdentity, rows: processRows, connect: connectCodexControl },
confirmUnusedConversation?: (session: RegisteredSession) => Promise<boolean>): Promise<void> {
if (session.engine !== 'codex') return
- const home = session.codexHome || env.CODEX_HOME
+ const home = sessionCodexHome(session)
const rows = await deps.rows()
if (!rows) throw new Error('Could not verify the Codex server before stopping')
const guard = () => { if (!current()) throw new Error('The close request was cancelled or the session changed') }
diff --git a/cli/src/lib/engineHomeReaders.spec.ts b/cli/src/lib/engineHomeReaders.spec.ts
new file mode 100644
index 000000000..f64047c20
--- /dev/null
+++ b/cli/src/lib/engineHomeReaders.spec.ts
@@ -0,0 +1,70 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { CodexActivityReader } from './runtimeActivity.js'
+import { stopSharedCodexSession } from './codexSessionLifecycle.js'
+import { createHarnessResourcesReader } from './harnessResources.js'
+import type { RegisteredSession } from './registry.js'
+
+const shell = vi.hoisted(() => ({ environment: {} as NodeJS.ProcessEnv }))
+vi.mock('./loginShellEnv.js', () => ({ loginShellEnvironment: () => shell.environment }))
+const roots: string[] = []
+const start = 'Tue Oct 6 10:00:00 2026'
+const session = (codexHome: string | null = null) => ({
+ agentId: 'agent', sessionId: 'conversation', engine: 'codex', codexHome,
+ processIdentity: { pid: 78, startMarker: start, executable: 'codex' },
+} as RegisteredSession)
+function movedHome(): string {
+ const root = mkdtempSync(join(tmpdir(), 'engine-readers-')); roots.push(root)
+ shell.environment = { CODEX_HOME: root }
+ return root
+}
+afterEach(() => {
+ shell.environment = {}
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+})
+
+it('reads live activity from the login shell Codex server, keeping an explicit agent profile', async () => {
+ const home = movedHome()
+ const connect = vi.fn(async (_home: string) => ({ request: async () => ({ thread: { id: 'conversation', status: { type: 'active' } } }), close: () => {} }))
+ const reader = new CodexActivityReader({ connect, now: () => 1000,
+ rows: async () => [{ ...session().processIdentity!, parentPid: 1, args: 'codex resume conversation' }],
+ })
+ try {
+ expect(await reader.read(session())).toBe('working')
+ expect(connect).toHaveBeenLastCalledWith(home)
+ await reader.read(session(join(home, 'agent-profile')))
+ expect(connect).toHaveBeenLastCalledWith(join(home, 'agent-profile'))
+ } finally { reader.close() }
+})
+
+it('stops the shared conversation in the login shell Codex home instead of overlooking its server', async () => {
+ // Found by QA on a quiet machine: the wrong home can make close report success with work still running.
+ const home = movedHome()
+ const request = vi.fn(async () => ({ thread: { id: 'conversation', status: { type: 'notLoaded' } } }))
+ const connect = vi.fn(async (_home: string) => ({ request, close: () => {} }))
+ await stopSharedCodexSession(session(), () => true, {
+ daemonIdentity: async path => path === home ? { pid: 90, processStartTime: start } : null,
+ rows: async () => [{ pid: 90, parentPid: 1, executable: 'codex', args: 'codex app-server', startMarker: start }],
+ connect,
+ })
+ expect(connect).toHaveBeenCalledWith(home)
+ expect(request).toHaveBeenCalledWith('thread/read', { threadId: 'conversation' })
+})
+
+it('counts the moved-home shared Codex server in Harness Monitor', async () => {
+ const home = movedHome()
+ mkdirSync(join(home, 'app-server-daemon'))
+ writeFileSync(join(home, 'app-server-daemon', 'daemon.pid'), JSON.stringify({ pid: 90, processStartTime: start }))
+ const read = createHarnessResourcesReader(() => [session()], {
+ now: () => 1000,
+ sample: async () => [
+ { pid: 78, parent: 1, memoryBytes: 100, cpuMs: 0, start },
+ { pid: 90, parent: 1, memoryBytes: 700, cpuMs: 0, start },
+ ],
+ })
+ expect((await read()).shared).toEqual([
+ { kind: 'codex', agentIds: ['agent'], memoryBytes: 700, processCount: 1, cpuPercent: null },
+ ])
+})
diff --git a/cli/src/lib/engineHomes.spec.ts b/cli/src/lib/engineHomes.spec.ts
index 898f1c0cc..754f41505 100644
--- a/cli/src/lib/engineHomes.spec.ts
+++ b/cli/src/lib/engineHomes.spec.ts
@@ -1,9 +1,9 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { env } from '../config/env.js'
-import { adoptEngineHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, movedEngineHomes, resetEngineHomes } from './engineHomes.js'
+import { adoptEngineHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, movedEngineHomes, resetEngineHomes, sessionClaudeHome, sessionCodexHome } from './engineHomes.js'
// The login shell's environment, as the daemon captured it at start-up: none, unless a test says so.
const shell = vi.hoisted(() => ({ env: {} as NodeJS.ProcessEnv }))
@@ -65,6 +65,15 @@ describe('the homes the person moved', () => {
expect(movedEngineHomes()).toEqual({ claude: [], codex: [] })
})
+ it('refreshes a previously read home list when another process adopts a new login', () => {
+ writeFileSync(saved(), JSON.stringify({ codex: [join(root, 'previous')] }))
+ expect(codexHomeRoots('/default')).toEqual(['/default', join(root, 'previous')])
+ writeFileSync(saved(), JSON.stringify({ codex: [join(root, 'previous'), join(root, 'new-login')] }))
+ expect(codexHomeRoots('/default')).toEqual(['/default', join(root, 'previous'), join(root, 'new-login')])
+ rmSync(saved())
+ expect(codexHomeRoots('/default')).toEqual(['/default', join(root, 'previous'), join(root, 'new-login')])
+ })
+
it('still adopts when the data folder cannot be written; the next boot adopts again', () => {
const blocked = join(root, 'blocked')
writeFileSync(blocked, 'a file where the folder should be')
@@ -79,6 +88,38 @@ describe('the homes the person moved', () => {
}
mkdirSync(root, { recursive: true })
})
+
+ it('a bound conversation stays in its known home even when the current shell changes or a service has no shell cache', () => {
+ const home = join(root, 'previous-login'), current = join(root, 'current-login')
+ adoptEngineHomes({ CODEX_HOME: home }, defaults)
+ shell.env = { CODEX_HOME: current }
+ try {
+ for (const folder of ['sessions', 'archived_sessions']) {
+ const transcriptPath = join(home, folder, 'thread.jsonl')
+ expect(sessionCodexHome({ transcriptPath })).toBe(home)
+ expect(sessionCodexHome({ transcriptPath, codexHome: '/explicit-profile' })).toBe('/explicit-profile')
+ }
+ expect(sessionCodexHome({ transcriptPath: join(home, 'sessions-other', 'thread.jsonl') })).toBe(current)
+ expect(sessionCodexHome({ transcriptPath: join(home, '..', 'elsewhere', 'thread.jsonl') })).toBe(current)
+ shell.env = {}
+ expect(sessionCodexHome({ transcriptPath: join(home, 'sessions', 'thread.jsonl') })).toBe(home)
+ } finally { shell.env = {} }
+ })
+
+ it('Claude settings follow the bound home or current shell, with the settings default separate from folder trust', () => {
+ const previous = join(root, 'previous-claude'), current = join(root, 'current-claude')
+ adoptEngineHomes({ CLAUDE_CONFIG_DIR: previous }, defaults)
+ shell.env = { CLAUDE_CONFIG_DIR: current }
+ try {
+ expect(sessionClaudeHome({})).toBe(current)
+ expect(sessionClaudeHome({ transcriptPath: join(previous, 'projects', 'workspace', 'thread.jsonl') })).toBe(previous)
+ expect(sessionClaudeHome({ transcriptPath: join(previous, 'projects-other', 'thread.jsonl') })).toBe(current)
+ expect(sessionClaudeHome({ transcriptPath: join(previous, 'projects', '..', '..', 'thread.jsonl') })).toBe(current)
+ shell.env = {}
+ expect(sessionClaudeHome({ transcriptPath: join(previous, 'projects', 'workspace', 'thread.jsonl') })).toBe(previous)
+ expect(sessionClaudeHome({})).toBe(dirname(env.CLAUDE_PROJECTS_DIR))
+ } finally { shell.env = {} }
+ })
})
// The home an agent launched now writes in, for what has to be in that engine's own config before it
diff --git a/cli/src/lib/engineHomes.ts b/cli/src/lib/engineHomes.ts
index f3713d9d8..9f88b3902 100644
--- a/cli/src/lib/engineHomes.ts
+++ b/cli/src/lib/engineHomes.ts
@@ -18,24 +18,27 @@
* agent's transcript as it loads: a home known only from this boot's shell was unknown at that check,
* and every agent bound in it lost its binding at each restart (measured, the same test).
*/
-import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
-import { dirname, isAbsolute, join, resolve } from 'node:path'
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
import { env } from '../config/env.js'
import { loginShellEnvironment } from './loginShellEnv.js'
const claudeHomes: string[] = []
const codexHomes: string[] = []
-let loaded = false
+let loadedStamp = ''
const savedFile = (): string => join(env.ADAPTER_DATA_DIR, 'engine-homes.json')
-/** The homes adopted on earlier boots, once per process, before anything asks for a root. */
+/** Found by QA on a quiet machine: search starts before the core adopts its shell's homes. Read again when that process
+ * replaces the small saved file, retaining in-memory homes if a write or read is unavailable. */
function load(): void {
- if (loaded) return
- loaded = true
try {
- const saved = JSON.parse(readFileSync(savedFile(), 'utf8')) as { claude?: unknown; codex?: unknown }
+ const file = savedFile(), stat = statSync(file)
+ const stamp = `${file}:${stat.ino}:${stat.mtimeMs}:${stat.size}`
+ if (stamp === loadedStamp) return
+ loadedStamp = stamp
+ const saved = JSON.parse(readFileSync(file, 'utf8')) as { claude?: unknown; codex?: unknown }
const take = (list: unknown, into: string[]): void => {
for (const home of Array.isArray(list) ? list : []) {
if (typeof home === 'string' && isAbsolute(home) && !into.includes(home)) into.push(home)
@@ -127,6 +130,29 @@ export function launchCodexHome(codexHome: string | null | undefined, environmen
return codexHome || movedHome(environment.CODEX_HOME) || env.CODEX_HOME
}
+/** Found by QA on a quiet machine: activity, close and Monitor looked at another server when the process's
+ * environment was unreadable. A bound transcript identifies its adopted home even in a service
+ * without the core's shell cache. An explicit profile remains authoritative. */
+export function sessionCodexHome(session: { codexHome?: string | null; transcriptPath?: string | null }): string {
+ if (session.codexHome) return session.codexHome
+ const home = session.transcriptPath && codexHomeRoots(env.CODEX_HOME).find(root => {
+ const path = relative(root, session.transcriptPath!)
+ return path.startsWith(`sessions${sep}`) || path.startsWith(`archived_sessions${sep}`)
+ })
+ return home || launchCodexHome(null)
+}
+
+/** Found by QA on a quiet machine: Claude's picker and effort read another login's settings.
+ * A known transcript keeps its home after the shell changes. Settings default to .claude, unlike
+ * the folder-trust .claude.json below, which defaults to the user's home itself. */
+export function sessionClaudeHome(session: { transcriptPath?: string | null }): string {
+ const projects = session.transcriptPath && claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR).find(root => {
+ const path = relative(root, session.transcriptPath!)
+ return !!path && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path)
+ })
+ return projects ? dirname(projects) : movedHome(launchEnvironment().CLAUDE_CONFIG_DIR) || dirname(env.CLAUDE_PROJECTS_DIR)
+}
+
/**
* The folder Claude Code keeps `.claude.json` in for an agent launched now: the CLAUDE_CONFIG_DIR the
* person's shell sets, else the home folder. Claude Code's own rule (2.1.290:
@@ -141,5 +167,5 @@ export function launchClaudeConfigDir(environment: NodeJS.ProcessEnv = launchEnv
export function resetEngineHomes(): void {
claudeHomes.length = 0
codexHomes.length = 0
- loaded = false
+ loadedStamp = ''
}
diff --git a/cli/src/lib/harnessResources.ts b/cli/src/lib/harnessResources.ts
index cc1103680..777ac5023 100644
--- a/cli/src/lib/harnessResources.ts
+++ b/cli/src/lib/harnessResources.ts
@@ -1,14 +1,14 @@
import { execFile } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
-import { env } from '../config/env.js'
+import { sessionCodexHome } from './engineHomes.js'
import { promisify } from 'node:util'
import type { ProcessIdentity } from './terminalTypes.js'
import { readProcessTelemetry, type ProcessTelemetry } from './harnessTelemetry.js'
import { macProcessGpuPercent } from './macosProcessGpu.js'
const exec = promisify(execFile)
-type Agent = { agentId: string; processIdentity?: ProcessIdentity | null; engine?: string; codexHome?: string | null }
+type Agent = { agentId: string; processIdentity?: ProcessIdentity | null; engine?: string; codexHome?: string | null; transcriptPath?: string | null }
export type SharedResourceRoot = { pid: number; start: string; agentIds: string[] }
export interface ResourceProcess {
pid: number
@@ -69,7 +69,7 @@ async function sharedCodexRoots(agents: readonly Agent[]): Promise<SharedResourc
const profiles = new Map<string, string[]>()
for (const agent of agents) {
if (agent.engine !== 'codex' || !agent.processIdentity) continue
- const home = agent.codexHome || env.CODEX_HOME
+ const home = sessionCodexHome(agent)
profiles.set(home, [...profiles.get(home) ?? [], agent.agentId])
}
const roots: SharedResourceRoot[] = []
diff --git a/cli/src/lib/registry.homes.spec.ts b/cli/src/lib/registry.homes.spec.ts
new file mode 100644
index 000000000..d561831d9
--- /dev/null
+++ b/cli/src/lib/registry.homes.spec.ts
@@ -0,0 +1,35 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+
+let root: string | undefined
+afterEach(() => { vi.unstubAllEnvs(); vi.resetModules(); if (root) rmSync(root, { recursive: true, force: true }) })
+
+it('repairs a child-overwritten parent from an adopted Codex home before the login shell is read', async () => {
+ // Found by QA on a quiet machine: restart searched only the default home and discarded this parent binding.
+ root = mkdtempSync(join(tmpdir(), 'registry-homes-'))
+ vi.stubEnv('ADAPTER_DATA_DIR', root)
+ vi.stubEnv('CODEX_HOME', join(root, 'daemon-codex'))
+ const moved = join(root, 'moved-codex')
+ const sessions = join(moved, 'sessions', '2026', '10', '06')
+ mkdirSync(sessions, { recursive: true })
+ const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
+ const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
+ const parent = join(sessions, `rollout-${parentId}.jsonl`), child = join(sessions, `rollout-${childId}.jsonl`)
+ writeFileSync(parent, JSON.stringify({ type: 'session_meta', payload: { id: parentId, source: 'cli' } }) + '\n')
+ writeFileSync(child, JSON.stringify({ type: 'session_meta', payload: { id: childId,
+ source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
+ } }) + '\n')
+ writeFileSync(join(root, 'engine-homes.json'), JSON.stringify({ claude: [], codex: [moved] }))
+ writeFileSync(join(root, 'registry.json'), JSON.stringify([{
+ launcherId: 'agent', sessionId: parentId, engine: 'codex', transcriptPath: child,
+ projectDir: 'project', cwd: root, tmuxPane: '%8', processIdentity: null,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }]), { mode: 0o600 })
+ vi.resetModules()
+ const { registry } = await import('./registry.js')
+ registry.load()
+ expect(registry.get(parentId)?.transcriptPath).toBe(parent)
+ expect(JSON.parse(readFileSync(join(root, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parent)
+})
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 8050ac679..de2eb9698 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -40,7 +40,7 @@ import { join, basename, dirname, relative, isAbsolute } from 'path'
import { machineNames } from './machineNames.js'
import { cursorDataDir } from '../engines/cursor/home.js'
import { env } from '../config/env.js'
-import { claudeProjectsRoots, codexHomeRoots } from './engineHomes.js'
+import { claudeProjectsRoots, codexHomeRoots, sessionCodexHome } from './engineHomes.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { GridAssignment } from './gridAssignment.js'
@@ -997,7 +997,7 @@ class Registry {
const meta = readCodexRolloutMeta(transcriptPath)
if (meta?.isSubagent) {
const repaired = meta.parentThreadId === rawSessionId
- ? resolveCodexRollout(rawSessionId, join(rawCodexHome || env.CODEX_HOME, 'sessions'))
+ ? resolveCodexRollout(rawSessionId, join(sessionCodexHome({ codexHome: rawCodexHome, transcriptPath }), 'sessions'))
: null
if (!repaired || !validTranscriptPath('codex', repaired, rawCodexHome) || readCodexRolloutMeta(repaired)?.isSubagent) {
changed = true
diff --git a/cli/src/lib/runtimeActivity.ts b/cli/src/lib/runtimeActivity.ts
index 88be5ebc1..f5135d56c 100644
--- a/cli/src/lib/runtimeActivity.ts
+++ b/cli/src/lib/runtimeActivity.ts
@@ -1,5 +1,5 @@
import { basename } from 'node:path'
-import { env } from '../config/env.js'
+import { sessionCodexHome } from './engineHomes.js'
import { terminalActivityReading } from '../cable/terminalActivity.js'
import { connectCodexControl, type CodexControl } from './codexSessionLifecycle.js'
import { codexStoppedGoal } from './codexTurnRecovery.js'
@@ -21,7 +21,7 @@ export class CodexActivityReader {
constructor(private readonly deps = { connect: connectCodexControl, rows: processRows, now: () => performance.now() }) {}
async read(session: RegisteredSession): Promise<ActivityState> {
if (session.engine !== 'codex' || !session.processIdentity) return 'unknown'
- const home = session.codexHome || env.CODEX_HOME
+ const home = sessionCodexHome(session)
if ((this.retryAt.get(home) ?? 0) > this.deps.now()) return 'unknown'
if (!this.rows || this.deps.now() - this.rowsAt > 2_000) {
this.rowsAt = this.deps.now(); this.rows = this.deps.rows()
diff --git a/cli/src/lib/runtimeProfile.homes.spec.ts b/cli/src/lib/runtimeProfile.homes.spec.ts
new file mode 100644
index 000000000..b508c3bc5
--- /dev/null
+++ b/cli/src/lib/runtimeProfile.homes.spec.ts
@@ -0,0 +1,83 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { env } from '../config/env.js'
+import type { RegisteredSession } from './registry.js'
+import { adoptEngineHomes, resetEngineHomes } from './engineHomes.js'
+import { parseRuntimeProfile, RuntimeProfileManager } from './runtimeProfile.js'
+
+const shell = vi.hoisted(() => ({ environment: {} as NodeJS.ProcessEnv }))
+vi.mock('./loginShellEnv.js', () => ({ loginShellEnvironment: () => shell.environment }))
+let root: string
+const defaults = { codex: env.CODEX_HOME, claude: env.CLAUDE_PROJECTS_DIR, data: env.ADAPTER_DATA_DIR }
+const write = (folder: string, file: string, value: unknown): void => {
+ mkdirSync(folder, { recursive: true })
+ writeFileSync(join(folder, file), JSON.stringify(value))
+}
+const session = (engine: 'claude' | 'codex') => ({
+ agentId: 'agent', sessionId: 'conversation', engine, codexHome: null, transcriptPath: null,
+ cwd: join(root, 'project'), cliVersion: engine === 'codex' ? '0.160.0' : '2.1.280',
+} as RegisteredSession)
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'profile-homes-'))
+ env.CODEX_HOME = join(root, 'daemon-codex')
+ env.CLAUDE_PROJECTS_DIR = join(root, 'daemon-claude', 'projects')
+ env.ADAPTER_DATA_DIR = join(root, 'data')
+ resetEngineHomes()
+ shell.environment = { CODEX_HOME: join(root, 'shell-codex'), CLAUDE_CONFIG_DIR: join(root, 'shell-claude') }
+})
+afterEach(() => {
+ shell.environment = {}
+ env.CODEX_HOME = defaults.codex
+ env.CLAUDE_PROJECTS_DIR = defaults.claude
+ env.ADAPTER_DATA_DIR = defaults.data
+ resetEngineHomes()
+ rmSync(root, { recursive: true, force: true })
+})
+
+it('offers the model catalog of the shell login, with an explicit Codex profile taking precedence', async () => {
+ for (const [home, slug] of [[env.CODEX_HOME, 'daemon-model'], [shell.environment.CODEX_HOME!, 'shell-model'], [join(root, 'profile'), 'profile-model']]) {
+ write(home, 'models_cache.json', { models: [{ slug, display_name: slug, visibility: 'list', supported_reasoning_levels: [{ effort: 'high' }] }] })
+ }
+ const manager = new RuntimeProfileManager(), agent = session('codex')
+ expect((await manager.codexCatalog(agent)).map(model => model.slug)).toEqual(['shell-model'])
+ expect((await manager.modelsForSession(agent)).map(model => parseRuntimeProfile(model.id)?.model)).toEqual(['shell-model', 'shell-model'])
+ expect((await manager.codexCatalog({ ...agent, codexHome: join(root, 'profile') })).map(model => model.slug)).toEqual(['profile-model'])
+})
+
+it('offers the Claude model families allowed by the settings in its moved home', async () => {
+ write(join(root, 'daemon-claude'), 'settings.json', { availableModels: ['haiku'] })
+ write(shell.environment.CLAUDE_CONFIG_DIR!, 'settings.json', { availableModels: ['sonnet'] })
+ const models = (await new RuntimeProfileManager().modelsForSession(session('claude'))).map(model => parseRuntimeProfile(model.id)?.model)
+ expect(models).toContain('sonnet')
+ expect(models).not.toContain('haiku')
+})
+
+it('reads Claude effort from its moved settings, keeping the project override last', async () => {
+ write(join(root, 'daemon-claude'), 'settings.json', { effortLevel: 'low' })
+ write(shell.environment.CLAUDE_CONFIG_DIR!, 'settings.json', { effortLevel: 'high' })
+ const manager = new RuntimeProfileManager(), agent = session('claude')
+ await manager.ingestConfig(agent, true)
+ expect(manager.getState(agent.sessionId).effort).toBe('high')
+ write(join(agent.cwd!, '.claude'), 'settings.local.json', { effortLevel: 'medium' })
+ await manager.ingestConfig(agent, true)
+ expect(manager.getState(agent.sessionId).effort).toBe('medium')
+})
+
+it.each(['claude', 'codex'] as const)('a bound %s conversation keeps its original settings after the shell changes homes', async engine => {
+ const previous = join(root, 'previous-login'), agent = session(engine)
+ adoptEngineHomes(engine === 'claude' ? { CLAUDE_CONFIG_DIR: previous } : { CODEX_HOME: previous },
+ { claudeHome: join(root, 'daemon-claude'), codexHome: env.CODEX_HOME })
+ agent.transcriptPath = join(previous, engine === 'claude' ? 'projects/workspace' : 'sessions', 'conversation.jsonl')
+ if (engine === 'claude') {
+ write(previous, 'settings.json', { availableModels: ['sonnet'] })
+ write(shell.environment.CLAUDE_CONFIG_DIR!, 'settings.json', { availableModels: ['haiku'] })
+ } else {
+ write(previous, 'models_cache.json', { models: [{ slug: 'previous-model', visibility: 'list' }] })
+ write(shell.environment.CODEX_HOME!, 'models_cache.json', { models: [{ slug: 'current-model', visibility: 'list' }] })
+ }
+ const models = (await new RuntimeProfileManager().modelsForSession(agent)).map(model => parseRuntimeProfile(model.id)?.model)
+ expect(models).toContain(engine === 'claude' ? 'sonnet' : 'previous-model')
+ expect(models).not.toContain(engine === 'claude' ? 'haiku' : 'current-model')
+})
diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.ts
index 694fe02d7..3be519b02 100644
--- a/cli/src/lib/runtimeProfile.ts
+++ b/cli/src/lib/runtimeProfile.ts
@@ -1,8 +1,9 @@
import { readFile } from 'fs/promises'
-import { dirname, join } from 'path'
+import { join } from 'path'
import { execFile } from 'child_process'
import { promisify } from 'util'
import { env } from '../config/env.js'
+import { sessionClaudeHome, sessionCodexHome } from './engineHomes.js'
import { parseMuseSettings } from '../engines/muse/runtimeProfile.js'
import { parseAmpSession } from '../engines/amp/runtimeProfile.js'
import type { AgentEngine } from '../engines/types.js'
@@ -568,7 +569,7 @@ async function readText(file: string): Promise<string> {
}
function claudeSettingsFiles(session: RegisteredSession): string[] {
- const root = dirname(env.CLAUDE_PROJECTS_DIR)
+ const root = sessionClaudeHome(session)
const files = [join(root, 'settings.json')]
if (session.cwd) {
files.push(join(session.cwd, '.claude', 'settings.json'))
@@ -1336,13 +1337,12 @@ export class RuntimeProfileManager {
}
/**
- * `models_cache.json` in this agent's own CODEX_HOME profile, when it has one other than the default
- * (see RegisteredSession.codexHome) — otherwise the picker would show the default profile's cached
- * models for an agent that is not actually running on it.
+ * Found by QA on a quiet machine: the picker read the daemon's login instead of the agent's.
+ * Use the bound conversation's home, or the launch shell's, with an explicit Codex profile first.
*/
private async readCodexCache(session: RegisteredSession): Promise<CodexCache> {
try {
- const cache: unknown = JSON.parse(await readFile(join(session.codexHome || env.CODEX_HOME, 'models_cache.json'), 'utf8'))
+ const cache: unknown = JSON.parse(await readFile(join(sessionCodexHome(session), 'models_cache.json'), 'utf8'))
return record(cache) ?? {}
} catch {
return {}
diff --git a/cli/src/lib/sessionSearch/externals/claude.ts b/cli/src/lib/sessionSearch/externals/claude.ts
index 80665cbd4..d66910e22 100644
--- a/cli/src/lib/sessionSearch/externals/claude.ts
+++ b/cli/src/lib/sessionSearch/externals/claude.ts
@@ -53,48 +53,52 @@ export async function readClaudeHead(path: string, windows: readonly number[] =
return null
}
-export function claudeProvider(options: { projectsDir: string; home: string }): ExternalProvider {
+export function claudeProvider(options: { projectsDir: string; home: string; roots?: () => string[] }): ExternalProvider {
return {
engine: 'claude',
async scan(ctx: ScanContext): Promise<ExternalSession[]> {
const found: ExternalSession[] = []
- for (const project of await entries(options.projectsDir)) {
- if (!project.isDirectory()) continue
- const folder = join(options.projectsDir, project.name)
- // Only the project's own files: a sub-agent's are in a folder beneath it.
- for (const file of await entries(folder)) {
- if (!file.name.endsWith('.jsonl')) continue
- const path = join(folder, file.name)
- // A file, or a link to one; not a folder, not a broken link.
- const stamp = await fileStamp(path)
- if (!stamp) continue
- // A transcript's first lines never change: its head is read once, however it grows.
- const head = await ctx.head(`claude:${path}`, stamp.stamp, () => readClaudeHead(path))
- await ctx.pace()
- if (!head || ctx.excluded(head.cwd)) continue
- found.push({ ...head, engine: 'claude', title: '', mtime: stamp.mtime, transcriptPath: path })
+ for (const projectsDir of options.roots?.() ?? [options.projectsDir]) {
+ for (const project of await entries(projectsDir)) {
+ if (!project.isDirectory()) continue
+ const folder = join(projectsDir, project.name)
+ // Only the project's own files: a sub-agent's are in a folder beneath it.
+ for (const file of await entries(folder)) {
+ if (!file.name.endsWith('.jsonl')) continue
+ const path = join(folder, file.name)
+ // A file, or a link to one; not a folder, not a broken link.
+ const stamp = await fileStamp(path)
+ if (!stamp) continue
+ // A transcript's first lines never change: its head is read once, however it grows.
+ const head = await ctx.head(`claude:${path}`, stamp.stamp, () => readClaudeHead(path))
+ await ctx.pace()
+ if (!head || ctx.excluded(head.cwd)) continue
+ found.push({ ...head, engine: 'claude', title: '', mtime: stamp.mtime, transcriptPath: path })
+ }
}
}
return found
},
async owners(view: ProcessView): Promise<OwnerClaim[]> {
- const dir = join(options.home, 'sessions')
const claims: OwnerClaim[] = []
- const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith('.json'))
- if (!records.length) return claims
- const processes = new Map((await view.list()).map((process): [number, RunningProcess] => [process.pid, process]))
- const ownership = agentCommandOwnershipSnapshot()
- for (const file of records) {
- const path = join(dir, file.name)
- const row = record(await readJson(path))
- const pid = row?.pid
- if (typeof pid !== 'number' || !text(row?.sessionId) || !view.alive(pid)) continue
- // A record outlives a crash, and its pid can be handed to anything after — a shell in another
- // tab. Only a Claude process already running when the record says Claude started still has it.
- const process = processes.get(pid)
- if (!process || engineProcessMatch(process, 'claude', ownership).score <= 0) continue
- if (process.started !== undefined && typeof row?.startedAt === 'number' && process.started > row.startedAt + START_SLACK_MS) continue
- claims.push({ sessionId: text(row?.sessionId), pid, record: path })
+ const dirs = options.roots?.().map(root => join(root, '..', 'sessions')) ?? [join(options.home, 'sessions')]
+ for (const dir of dirs) {
+ const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith('.json'))
+ if (!records.length) continue
+ const processes = new Map((await view.list()).map((process): [number, RunningProcess] => [process.pid, process]))
+ const ownership = agentCommandOwnershipSnapshot()
+ for (const file of records) {
+ const path = join(dir, file.name)
+ const row = record(await readJson(path))
+ const pid = row?.pid
+ if (typeof pid !== 'number' || !text(row?.sessionId) || !view.alive(pid)) continue
+ // A record outlives a crash, and its pid can be handed to anything after — a shell in another
+ // tab. Only a Claude process already running when the record says Claude started still has it.
+ const process = processes.get(pid)
+ if (!process || engineProcessMatch(process, 'claude', ownership).score <= 0) continue
+ if (process.started !== undefined && typeof row?.startedAt === 'number' && process.started > row.startedAt + START_SLACK_MS) continue
+ claims.push({ sessionId: text(row?.sessionId), pid, record: path })
+ }
}
return claims
},
diff --git a/cli/src/lib/sessionSearch/externals/codex.ts b/cli/src/lib/sessionSearch/externals/codex.ts
index 275eb275d..e4f89109d 100644
--- a/cli/src/lib/sessionSearch/externals/codex.ts
+++ b/cli/src/lib/sessionSearch/externals/codex.ts
@@ -109,24 +109,26 @@ export async function codexTurnOpen(path: string, unknown: boolean | null = true
return unknown
}
-export function codexProvider(options: { home: string }): ExternalProvider {
+export function codexProvider(options: { home: string; roots?: () => string[] }): ExternalProvider {
return {
engine: 'codex',
async scan(ctx: ScanContext): Promise<ExternalSession[]> {
- const titles = await codexTitles(join(options.home, 'session_index.jsonl'), ctx)
const found: ExternalSession[] = []
- const archived = new Set(await rollouts(join(options.home, 'archived_sessions')))
- for (const path of [...await rollouts(join(options.home, 'sessions')), ...archived]) {
- const stamp = await fileStamp(path)
- if (!stamp) continue
- // A rollout's first line never changes: read once, however the file grows.
- const head = await ctx.head(`codex:${path}`, stamp.stamp, () => readCodexHead(path))
- await ctx.pace()
- if (!head || ctx.excluded(head.cwd)) continue
- found.push({
- ...head, engine: 'codex', title: titles.get(head.sessionId) ?? '', mtime: stamp.mtime, transcriptPath: path,
- ...(archived.has(path) ? { archived: true as const } : {}),
- })
+ for (const home of options.roots?.() ?? [options.home]) {
+ const titles = await codexTitles(join(home, 'session_index.jsonl'), ctx)
+ const archived = new Set(await rollouts(join(home, 'archived_sessions')))
+ for (const path of [...await rollouts(join(home, 'sessions')), ...archived]) {
+ const stamp = await fileStamp(path)
+ if (!stamp) continue
+ // A rollout's first line never changes: read once, however the file grows.
+ const head = await ctx.head(`codex:${path}`, stamp.stamp, () => readCodexHead(path))
+ await ctx.pace()
+ if (!head || ctx.excluded(head.cwd)) continue
+ found.push({
+ ...head, engine: 'codex', title: titles.get(head.sessionId) ?? '', mtime: stamp.mtime, transcriptPath: path,
+ ...(archived.has(path) ? { archived: true as const } : {}),
+ })
+ }
}
return found
},
diff --git a/cli/src/lib/sessionSearch/externals/homes.spec.ts b/cli/src/lib/sessionSearch/externals/homes.spec.ts
new file mode 100644
index 000000000..d0fca1c74
--- /dev/null
+++ b/cli/src/lib/sessionSearch/externals/homes.spec.ts
@@ -0,0 +1,58 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it } from 'vitest'
+import { env } from '../../../config/env.js'
+import { claudeProjectsRoots, resetEngineHomes } from '../../engineHomes.js'
+import { externalProviders } from './index.js'
+import { scanMemo } from './support.js'
+
+let root: string | undefined
+afterEach(() => {
+ rmSync(join(env.ADAPTER_DATA_DIR, 'engine-homes.json'), { force: true })
+ resetEngineHomes()
+ if (root) rmSync(root, { recursive: true, force: true })
+})
+
+it.each(['claude', 'codex'] as const)('search discovers %s homes adopted by the core after its separate process has started', async engine => {
+ root = mkdtempSync(join(tmpdir(), 'external-homes-'))
+ resetEngineHomes()
+ // Search starts before the core reads the login shell; its first root lookup may find no saved file.
+ claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR)
+ const providers = externalProviders()
+ const claudeHome = join(root, 'claude'), codexHome = join(root, 'codex')
+ const claudeId = '11111111-1111-4111-8111-111111111111', codexId = '22222222-2222-4222-8222-222222222222'
+ const write = (path: string, value: unknown) => {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, JSON.stringify(value) + '\n')
+ }
+ write(join(claudeHome, 'projects', 'project', `${claudeId}.jsonl`), {
+ type: 'user', entrypoint: 'cli', sessionId: claudeId, cwd: root, message: { role: 'user', content: 'find the moved Claude conversation' },
+ })
+ write(join(codexHome, 'sessions', '2026', '10', '06', `rollout-${codexId}.jsonl`), {
+ type: 'session_meta', payload: { id: codexId, cwd: root, source: 'cli' },
+ })
+ write(join(codexHome, 'session_index.jsonl'), { id: codexId, thread_name: 'Moved Codex thread' })
+ write(join(env.ADAPTER_DATA_DIR, 'engine-homes.json'), { claude: [claudeHome], codex: [codexHome] })
+ const ctx = scanMemo().context()
+ expect(await providers.find(p => p.engine === engine)!.scan(ctx)).toEqual(expect.arrayContaining([
+ expect.objectContaining(engine === 'claude' ? { sessionId: claudeId } : { sessionId: codexId, title: 'Moved Codex thread' }),
+ ]))
+})
+
+it('search recognizes a moved Claude conversation that is still busy in another terminal', async () => {
+ root = mkdtempSync(join(tmpdir(), 'external-homes-'))
+ const home = join(root, 'claude')
+ const record = join(home, 'sessions', '123.json')
+ mkdirSync(join(home, 'sessions'), { recursive: true })
+ writeFileSync(record, JSON.stringify({ pid: 123, sessionId: 'external-conversation', status: 'busy', startedAt: 1000 }))
+ writeFileSync(join(env.ADAPTER_DATA_DIR, 'engine-homes.json'), JSON.stringify({ claude: [home] }))
+ const provider = externalProviders().find(p => p.engine === 'claude')!
+ const claims = await provider.owners!({
+ alive: pid => pid === 123,
+ list: async () => [{ pid: 123, ppid: 1, executable: 'claude', args: 'claude', started: 1000 }],
+ openFiles: async () => new Map(), openFilesOf: async () => new Map(),
+ })
+ expect(claims).toContainEqual({ sessionId: 'external-conversation', pid: 123, record })
+ expect(await provider.busy!(claims[0])).toBe(true)
+})
diff --git a/cli/src/lib/sessionSearch/externals/index.ts b/cli/src/lib/sessionSearch/externals/index.ts
index 4b4136538..7f00c1d61 100644
--- a/cli/src/lib/sessionSearch/externals/index.ts
+++ b/cli/src/lib/sessionSearch/externals/index.ts
@@ -7,6 +7,7 @@ import { isAbsolute, join } from 'node:path'
import { cursorConfigDir, cursorDataDir } from '../../../engines/cursor/home.js'
import { env } from '../../../config/env.js'
+import { claudeProjectsRoots, codexHomeRoots } from '../../engineHomes.js'
import { agyProvider } from './agy.js'
import { claudeProvider } from './claude.js'
import { codexProvider } from './codex.js'
@@ -72,8 +73,10 @@ export function externalPaths(vars: NodeJS.ProcessEnv = process.env): ExternalPa
/** One provider per engine that keeps its conversations on this machine's disk. */
export function externalProviders(paths: ExternalPaths = externalPaths()): ExternalProvider[] {
return [
- claudeProvider({ projectsDir: paths.claudeProjectsDir, home: join(paths.claudeProjectsDir, '..') }),
- codexProvider({ home: paths.codexHome }),
+ // QA found search's separate process started before the core adopted the shell's homes.
+ // Resolve roots on each scan, retaining the default and previously adopted conversations.
+ claudeProvider({ projectsDir: paths.claudeProjectsDir, home: join(paths.claudeProjectsDir, '..'), roots: () => claudeProjectsRoots(paths.claudeProjectsDir) }),
+ codexProvider({ home: paths.codexHome, roots: () => codexHomeRoots(paths.codexHome) }),
cursorProvider({ configDir: paths.cursorConfigDir, dataDir: paths.cursorDataDir }),
grokProvider({ home: paths.grokHome }),
copilotProvider({ home: paths.copilotHome }),
diff --git a/cli/src/lib/sessionTitle.homes.spec.ts b/cli/src/lib/sessionTitle.homes.spec.ts
new file mode 100644
index 000000000..a3d5d4698
--- /dev/null
+++ b/cli/src/lib/sessionTitle.homes.spec.ts
@@ -0,0 +1,31 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { codexThreadName, resetCodexThreadNames } from './sessionTitle.js'
+
+const shell = vi.hoisted(() => ({ environment: {} as NodeJS.ProcessEnv }))
+vi.mock('./loginShellEnv.js', () => ({ loginShellEnvironment: () => shell.environment }))
+const roots: string[] = []
+afterEach(() => {
+ shell.environment = {}
+ vi.unstubAllEnvs()
+ resetCodexThreadNames()
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+})
+
+it('names a Codex thread from the login shell home before the daemon home, unless the agent has its own profile', () => {
+ // Found by QA on a quiet machine: moved-home agents kept the title from the daemon's other login.
+ const root = mkdtempSync(join(tmpdir(), 'session-title-homes-')); roots.push(root)
+ const home = (name: string) => {
+ const path = join(root, name)
+ mkdirSync(path)
+ writeFileSync(join(path, 'session_index.jsonl'), JSON.stringify({ id: 'conversation', thread_name: name }) + '\n')
+ return path
+ }
+ vi.stubEnv('CODEX_HOME', home('daemon-login'))
+ shell.environment = { CODEX_HOME: home('shell-login') }
+ const profile = home('agent-profile')
+ expect(codexThreadName('conversation')).toBe('shell-login')
+ expect(codexThreadName('conversation', profile)).toBe('agent-profile')
+})
diff --git a/cli/src/lib/sessionTitle.spec.ts b/cli/src/lib/sessionTitle.spec.ts
index 37da4b2c4..2785c4b8d 100644
--- a/cli/src/lib/sessionTitle.spec.ts
+++ b/cli/src/lib/sessionTitle.spec.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { appendFileSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -119,14 +119,17 @@ describe('codexThreadName: Codex’s own name for a thread', () => {
expect(codexThreadName('t1', home)).toBeNull()
})
- it('falls back to ~/.codex when neither the agent nor the environment names a Codex home', () => {
+ it('falls back to ~/.codex when neither the agent nor the environment names a Codex home', async () => {
const savedUserHome = process.env.HOME
delete process.env.CODEX_HOME
process.env.HOME = home
try {
mkdirSync(join(home, '.codex'))
writeFileSync(join(home, '.codex', 'session_index.jsonl'), JSON.stringify({ id: 't1', thread_name: 'Default home' }) + '\n')
- expect(codexThreadName('t1')).toBe('Default home')
+ // Configuration is captured at process startup; give this fresh HOME a fresh config module too.
+ vi.resetModules()
+ const fresh = await import('./sessionTitle.js')
+ expect(fresh.codexThreadName('t1')).toBe('Default home')
} finally {
process.env.HOME = savedUserHome
}
diff --git a/cli/src/lib/sessionTitle.ts b/cli/src/lib/sessionTitle.ts
index 203af1bcd..21b10a76c 100644
--- a/cli/src/lib/sessionTitle.ts
+++ b/cli/src/lib/sessionTitle.ts
@@ -15,9 +15,9 @@
* prompt ("Claude Code"), or just the folder. Those fall through to the numbered default.
*/
import { readFileSync, statSync } from 'node:fs'
-import { homedir } from 'node:os'
import { basename, join } from 'node:path'
import { ENGINES } from '../engines/types.js'
+import { launchCodexHome, sessionCodexHome } from './engineHomes.js'
/** An engine's own name, which is what a session is titled before it is about anything. */
const ENGINE_TITLES: ReadonlySet<string> = new Set([
@@ -73,7 +73,7 @@ let codexIndexCache: IndexCache | null = null
*/
export function codexThreadName(sessionId: string | null | undefined, codexHome?: string | null): string | null {
if (!sessionId) return null
- const home = codexHome || process.env.CODEX_HOME || join(homedir(), '.codex')
+ const home = launchCodexHome(codexHome)
const path = join(home, 'session_index.jsonl')
let stat
try { stat = statSync(path) } catch { return null }
@@ -104,11 +104,11 @@ export function resetCodexThreadNames(): void { codexIndexCache = null }
* recorded before this existed is read the same way.
*/
export function engineSessionTitle(
- session: { engine?: string | null; sessionId?: string | null; codexHome?: string | null },
+ session: { engine?: string | null; sessionId?: string | null; codexHome?: string | null; transcriptPath?: string | null },
terminalTitle: string | null | undefined,
): string | null {
if (session.engine === 'codex') {
- const named = codexThreadName(session.sessionId, session.codexHome)
+ const named = codexThreadName(session.sessionId, sessionCodexHome(session))
if (named) return named
}
return terminalTitle ?? null