From f56af62a434a2c19552a9c5f75112c476b382cd9 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Sat, 28 Nov 2026 02:39:53 -0800 Subject: [PATCH 1/2] docs(codex): plan fresh native transcript ownership --- ...6-11-28-native-codex-transcript-identity.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 docs/plans/2026-11-28-native-codex-transcript-identity.md diff --git a/docs/plans/2026-11-28-native-codex-transcript-identity.md b/docs/plans/2026-11-28-native-codex-transcript-identity.md new file mode 100644 index 000000000..90ae50e0b --- /dev/null +++ b/docs/plans/2026-11-28-native-codex-transcript-identity.md @@ -0,0 +1,18 @@ +# Restore fresh native Codex transcript ownership + +## Evidence + +A fresh native Codex 0.172.0 pane can process prompts while Agent Code has no attached rollout. +A resumed pane already has its exact UUID and can read its transcript. +A disposable 0.172.0 TUI emitted SessionStart with source startup, a UUID and a rollout path. +The filename UUID equalled the root session_meta.id and the recorded source was cli. +The existing exact-ID locator and lease validate a candidate before tailing. Use that path. + +## Implementation and verification + +1. Install a private startup-only receipt for each fresh native launch. Keep reporting and user hooks independent. +2. Accept only root startup identities in the current launch. Wait for the verified rollout to become readable. +3. Reuse the existing exact-ID registration and stop ownership work on disposal or successful attachment. +4. Exercise concurrent same-directory launches, delayed files, invalid evidence, cleanup and real CLI compatibility. + +Refs #1565 From 6da9bf24d66a652fb011654022e935e8c07d2ced Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Sat, 28 Nov 2026 02:45:58 -0800 Subject: [PATCH 2/2] fix(codex): bind native startup transcripts to verified launch identities Keep the CLI startup receipt until its root rollout becomes readable, then use the existing exact-ID lease. This restores fresh terminal transcripts independently of proxy capture or TLDR grants. Refs #1565 --- ...-11-28-native-codex-transcript-identity.md | 6 + src/providers/codex/runtime/codexSession.ts | 42 +++--- .../nativeStartupReceipt.system.test.ts | 67 +++++++++ .../codex/runtime/nativeStartupReceipt.ts | 137 ++++++++++++++++++ .../shared/runtime/tldrHooks.test.ts | 20 ++- src/providers/shared/runtime/tldrHooks.ts | 59 +++++--- testing/live/codex-native-transcript.test.ts | 74 ++++++++++ 7 files changed, 365 insertions(+), 40 deletions(-) create mode 100644 src/providers/codex/runtime/nativeStartupReceipt.system.test.ts create mode 100644 src/providers/codex/runtime/nativeStartupReceipt.ts create mode 100644 testing/live/codex-native-transcript.test.ts diff --git a/docs/plans/2026-11-28-native-codex-transcript-identity.md b/docs/plans/2026-11-28-native-codex-transcript-identity.md index 90ae50e0b..132e660f1 100644 --- a/docs/plans/2026-11-28-native-codex-transcript-identity.md +++ b/docs/plans/2026-11-28-native-codex-transcript-identity.md @@ -16,3 +16,9 @@ The existing exact-ID locator and lease validate a candidate before tailing. Use 4. Exercise concurrent same-directory launches, delayed files, invalid evidence, cleanup and real CLI compatibility. Refs #1565 + +## Results + +Two installed Codex 0.172.0 TUIs shared a disposable home and cwd, with a localhost fixture and no TLDR or proxy. Both returned their own marker from the application transcript and distinct root session IDs. The personal SessionStart hook ran for both launches. Removing the launch identity hook reproduced the empty transcript on the same test. + +The receipt can arrive before headless startup or rollout creation. The existing exact-ID locator still owns the final filename, metadata and lease checks. Disabled or unsupported hooks provide no additional evidence. Existing panes need a fresh launch or a resume by known identity. diff --git a/src/providers/codex/runtime/codexSession.ts b/src/providers/codex/runtime/codexSession.ts index ca24ab579..caad54af9 100644 --- a/src/providers/codex/runtime/codexSession.ts +++ b/src/providers/codex/runtime/codexSession.ts @@ -1,6 +1,6 @@ import { excludeExternalControlFromCodex } from '@providers/shared/runtime/externalControlExclusion.js' -import { createCodexTldrHooks } from '@providers/shared/runtime/tldrHooks.js' -import type { PrivateCodexTldrHooks } from '@providers/shared/runtime/tldrHooks.js' +import { createCodexLaunchHooks } from '@providers/shared/runtime/tldrHooks.js' +import type { PrivateCodexLaunchHooks } from '@providers/shared/runtime/tldrHooks.js' import { EventEmitter } from 'events' import { mkdir } from 'fs/promises' import { join } from 'path' @@ -232,16 +232,16 @@ type CodexStartAttempt = { resumeRolloutPreparation: CodexResumeRolloutPreparation | null pty: ReturnType | null headless: CodexHeadless | null - /** Private TLDR hook header file (#917). Generation-owned like the proxy: a - * cancelled start must delete the file holding its bearer. */ - tldrHooks: PrivateCodexTldrHooks | null + /** Generation-owned hook receipts and optional TLDR credentials. A cancelled + * start revokes its watcher and removes its private directory. */ + launchHooks: PrivateCodexLaunchHooks | null rollbackPromise: Promise | null } export class CodexSession extends EventEmitter { private headless: CodexHeadless | null = null private pty: ReturnType | null = null - private tldrHooks: PrivateCodexTldrHooks | null = null + private launchHooks: PrivateCodexLaunchHooks | null = null private exited = false private composerReady = false /** The native-composer readiness last published after the startup latch @@ -325,7 +325,7 @@ export class CodexSession extends EventEmitter { resumeRolloutPreparation: null, pty: null, headless: null, - tldrHooks: null, + launchHooks: null, rollbackPromise: null, } // WHY generation identity, rather than a permanent `stopped` boolean, is @@ -469,17 +469,19 @@ export class CodexSession extends EventEmitter { // prompt-input profile (which must stay last) and the resume subcommand. // Created inside the rollback region because the header file holds the // session bearer. - const tldrHooks = await createCodexTldrHooks(this.builtInMcpServers, TLDR_HOOK_RUNTIME_DIR) + const launchHooks = await createCodexLaunchHooks( + this.builtInMcpServers, TLDR_HOOK_RUNTIME_DIR, !this.resumeSessionId && !this.proxyServer, + ) if (!this.isStartAttemptActive(attempt)) { // Stop may already have drained this attempt before the file existed; // this continuation is then its only owner. - try { await tldrHooks?.dispose() } catch { /* best-effort */ } + try { await launchHooks?.dispose() } catch { /* best-effort */ } return } - if (tldrHooks) { - attempt.tldrHooks = tldrHooks - this.tldrHooks = tldrHooks - args.push(...tldrHooks.args) + if (launchHooks) { + attempt.launchHooks = launchHooks + this.launchHooks = launchHooks + args.push(...launchHooks.args) } if (this.resumeSessionId) { // WHY app-level replacement waits until this exact boundary: proxy @@ -686,6 +688,9 @@ export class CodexSession extends EventEmitter { } this.headless.on('exit', ({ exitCode, signal }) => { + // The native process can exit without SessionManager calling stop. + // Revoke only this generation's watcher and private files. + void attempt.launchHooks?.dispose().catch(() => {}) this.exited = true this.composerReady = false this.nativeComposerPublished = 'ready' @@ -709,6 +714,7 @@ export class CodexSession extends EventEmitter { const res = await this.headless.start() if (!this.isStartAttemptActive(attempt)) return sessionsDir = res.sessionsDir + attempt.launchHooks?.startup?.start(sessionsDir, this.headless) } catch (err) { await this.rollbackStart(attempt) throw err @@ -774,7 +780,7 @@ export class CodexSession extends EventEmitter { resumeRolloutPreparation: this.resumeRolloutPreparation, pty: this.pty, headless: this.headless, - tldrHooks: this.tldrHooks, + launchHooks: this.launchHooks, rollbackPromise: null, } owned.cancelled = true @@ -790,8 +796,8 @@ export class CodexSession extends EventEmitter { const preparationTask = owned.resumeRolloutPreparationTask const preparation = owned.resumeRolloutPreparation const pty = owned.pty - const tldrHooks = owned.tldrHooks - owned.tldrHooks = null + const launchHooks = owned.launchHooks + owned.launchHooks = null owned.proxyAdapter = null owned.proxyServer = null owned.headless = null @@ -811,7 +817,7 @@ export class CodexSession extends EventEmitter { this.resumeRolloutPreparation = null } if (pty && this.pty === pty) this.pty = null - if (tldrHooks && this.tldrHooks === tldrHooks) this.tldrHooks = null + if (launchHooks && this.launchHooks === launchHooks) this.launchHooks = null owned.rollbackPromise = (async () => { try { proxyAdapter?.detach() } catch { /* best-effort */ } @@ -847,7 +853,7 @@ export class CodexSession extends EventEmitter { try { pty?.kill() } catch { /* best-effort */ } // After the PTY is gone, so a final in-flight hook is not denied its // credential while the provider can still act on the answer. - try { await tldrHooks?.dispose() } catch { /* best-effort */ } + try { await launchHooks?.dispose() } catch { /* best-effort */ } })() await owned.rollbackPromise // WHY keep a cancelled generation discoverable while cleanup is pending. diff --git a/src/providers/codex/runtime/nativeStartupReceipt.system.test.ts b/src/providers/codex/runtime/nativeStartupReceipt.system.test.ts new file mode 100644 index 000000000..407e76c81 --- /dev/null +++ b/src/providers/codex/runtime/nativeStartupReceipt.system.test.ts @@ -0,0 +1,67 @@ +import { execFileSync } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { createCodexLaunchHooks } from '@providers/shared/runtime/tldrHooks.js' + +const root = await mkdtemp(join(tmpdir(), 'codex-launch-id-')) +const hooks: NonNullable>>[] = [] +afterEach(async () => { + await Promise.all(hooks.splice(0).map(hook => hook.dispose())) + await rm(root, { recursive: true, force: true }) +}) + +async function launch() { + const hook = (await createCodexLaunchHooks([], root, true))! + hooks.push(hook) + const command = JSON.parse(/command=("(?:[^"\\]|\\.)*")/.exec(hook.args.find(arg => arg.startsWith('hooks.SessionStart='))!)![1]!) + const send = (session_id: string, override = {}) => execFileSync('/bin/sh', ['-c', command], { + input: JSON.stringify({ session_id, source: 'startup', hook_event_name: 'SessionStart', ...override }), + }) + const observed: string[] = [] + const owner = { + observeProviderThreadIdentity: (id: string) => { observed.push(id) }, + getSessionMeta: () => observed[0] ? { id: observed[0] } : null, + } + return { hook, send, observed, owner } +} + +it('keeps simultaneous private launches separate and waits for the root rollout to become durable', async () => { + const [a, b] = await Promise.all([launch(), launch()]) + const sessions = join(root, 'sessions') + await mkdir(sessions) + const [idA, idB, child, stale] = [randomUUID(), randomUUID(), randomUUID(), randomUUID()] as const + async function writeRollout(id: string, source: unknown = 'cli') { + await writeFile(join(sessions, `rollout-2026-11-28T12-00-00-${id}.jsonl`), + JSON.stringify({ type: 'session_meta', payload: { id, cwd: '/same/workspace', source } }) + '\n') + } + await Promise.all([writeRollout(idB), writeRollout(child, { subagent: {} }), writeRollout(stale)]) + a.send(stale, { source: 'resume' }) + a.send(stale, { hook_event_name: 'SubagentStart', agent_id: stale }) + a.send(stale, { transcript_path: `/elsewhere/rollout-date-${idB}.jsonl` }) + a.send(child) + a.send(idA) + a.hook.startup!.start(sessions, a.owner) + b.hook.startup!.start(sessions, b.owner) + b.send(idB) + await vi.waitFor(() => expect(b.observed).toEqual([idB])) + expect(a.observed).toEqual([]) + await writeRollout(idA) + await vi.waitFor(() => expect(a.observed).toEqual([idA])) +}) + +it('revokes an observed startup hint when its launch ends before rollout creation', async () => { + const a = await launch() + const id = randomUUID() + const sessions = join(root, 'sessions') + await mkdir(sessions) + a.hook.startup!.start(sessions, a.owner) + a.send(id) + await a.hook.dispose() + await writeFile(join(sessions, `rollout-date-${id}.jsonl`), + JSON.stringify({ type: 'session_meta', payload: { id, source: 'cli' } }) + '\n') + await new Promise(resolve => setTimeout(resolve, 180)) + expect(a.observed).toEqual([]) +}) diff --git a/src/providers/codex/runtime/nativeStartupReceipt.ts b/src/providers/codex/runtime/nativeStartupReceipt.ts new file mode 100644 index 000000000..02cccb15e --- /dev/null +++ b/src/providers/codex/runtime/nativeStartupReceipt.ts @@ -0,0 +1,137 @@ +import { watch, type FSWatcher } from 'node:fs' +import { open, readFile, readdir, unlink } from 'node:fs/promises' +import { basename, join } from 'node:path' +import { findCodexRolloutPathByThreadId } from 'codex-headless' + +type Owner = { + observeProviderThreadIdentity(id: string): void + getSessionMeta(): { id: string } | null +} + +const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i +const receiptName = /^start\.[a-zA-Z0-9]+\.json$/ + +type ThreadHint = { id: string; bucketPath?: string } + +function startupThread(raw: string): ThreadHint | null { + const event = JSON.parse(raw) + if (event?.hook_event_name !== 'SessionStart' || event.source !== 'startup' || + event.agent_id != null || event.agent_type != null || + typeof event.session_id !== 'string' || !UUID.test(event.session_id)) return null + const id = event.session_id.toLowerCase() + if (event.transcript_path != null && (typeof event.transcript_path !== 'string' || + !basename(event.transcript_path).toLowerCase().endsWith(`-${id}.jsonl`))) return null + // Only the documented date bucket and filename can select a fast-path read + // under the host's own sessions root. Never open a provider-supplied path. + const bucketPath = typeof event.transcript_path === 'string' + ? /\/(\d{4}\/\d{2}\/\d{2}\/rollout-[^/]+\.jsonl)$/.exec(event.transcript_path)?.[1] + : undefined + return { id, bucketPath } +} + +async function rootMetadata(file: string, id: string): Promise { + const handle = await open(file, 'r') + try { + // Match the locator's bounded prefix. A valid subagent rollout can also + // have a perfectly consistent UUID/filename, but cannot own this TUI. + const prefix = Buffer.alloc(256 * 1024) + const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0) + const line = JSON.parse(prefix.toString('utf8', 0, bytesRead).split('\n', 1)[0]!) + return line.type === 'session_meta' && line.payload?.id?.toLowerCase() === id && + line.payload.source === 'cli' && line.payload.parent_thread_id == null + } finally { await handle.close() } +} + +/** SessionStart is a launch-scoped statement from Codex itself. The file may + * arrive before headless starts or before the first rollout record is durable. + * Keep its UUID until the regular coordinator proves ownership and tails it. */ +export class NativeStartupReceipt { + private watcher?: FSWatcher + private timer?: NodeJS.Timeout + private stopped = false + + constructor(private directory: string) {} + + start(sessionsDir: string, owner: Owner): void { + if (this.stopped) return + let delay = 100 + let busy = false + let dirty = false + const inspect = async () => { + if (this.stopped || busy) return + busy = true + let retry = false + try { + retry = await this.offerReceipts(sessionsDir, owner) + } catch { retry = true } finally { + busy = false + if (!this.stopped && (dirty || retry || !this.watcher)) { + const timeout = dirty ? 0 : delay + delay = Math.min(delay * 2, 30_000) + dirty = false + this.timer = setTimeout(() => void inspect(), timeout) + this.timer.unref() + } + } + } + const wake = () => { + clearTimeout(this.timer) + if (busy) dirty = true + else void inspect() + } + try { + this.watcher = watch(this.directory, { persistent: false }, (_event, name) => { + if (name === null || receiptName.test(name)) wake() + }) + this.watcher.on('error', () => { + this.watcher?.close() + this.watcher = undefined + wake() + }) + } catch { /* Poll at a capped backoff when the OS cannot provide a watcher. */ } + wake() + } + + /** Report whether a receipt still needs another look. An unrelated or child + * receipt cannot block the root waiting beside it in the same directory. */ + private async offerReceipts(sessionsDir: string, owner: Owner): Promise { + let pending = false + for (const name of await readdir(this.directory)) { + if (this.stopped || !receiptName.test(name)) continue + const path = join(this.directory, name) + if (owner.getSessionMeta()) { + this.stop() + await unlink(path).catch(() => {}) + return false + } + + let hint: ThreadHint | null = null + try { hint = startupThread(await readFile(path, 'utf8')) } catch { /* Invalid or retired receipt. */ } + if (hint) { + try { + const file = hint.bucketPath + ? join(sessionsDir, hint.bucketPath) + : await findCodexRolloutPathByThreadId(sessionsDir, hint.id) + if (!file) { pending = true; continue } + if (await rootMetadata(file, hint.id)) { + if (!this.stopped) owner.observeProviderThreadIdentity(hint.id) + pending = true + continue + } + } catch { + // SessionStart can run before the file exists or its header is complete. + pending = true + continue + } + } + await unlink(path).catch(() => {}) + } + return pending + } + + stop(): void { + this.stopped = true + this.watcher?.close() + clearTimeout(this.timer) + } +} diff --git a/src/providers/shared/runtime/tldrHooks.test.ts b/src/providers/shared/runtime/tldrHooks.test.ts index 1b6853c35..8c8b7ace8 100644 --- a/src/providers/shared/runtime/tldrHooks.test.ts +++ b/src/providers/shared/runtime/tldrHooks.test.ts @@ -8,7 +8,7 @@ import { CODEX_SESSION_FLAGS_HOOK_SOURCE, claudeTldrHookSettings, codexHookTrustHash, - createCodexTldrHooks, + createCodexLaunchHooks, sweepStaleTldrHookFiles, tldrHookServer, } from './tldrHooks' @@ -61,7 +61,7 @@ describe('provider launch hooks', () => { it('pre-trusts exactly the Codex hooks it injects and keeps the bearer out of argv', async () => { const root = await appRoot() - const hooks = await createCodexTldrHooks([server()], root) + const hooks = await createCodexLaunchHooks([server()], root) expect(hooks).not.toBeNull() try { expect(hooks!.args.join(' ')).not.toContain('session-secret-token') @@ -100,8 +100,20 @@ describe('provider launch hooks', () => { } }) + it('keeps startup and reporting trust in the same invocation without exposing extra MCP grants', async () => { + const hooks = (await createCodexLaunchHooks([server()], await appRoot(), true))! + try { + const states = hooks.args.filter(arg => arg.startsWith('hooks.state=')) + expect(states).toHaveLength(1) + for (const label of ['session_start', 'user_prompt_submit', 'post_tool_use', 'stop']) { + expect(states[0]).toContain(`${CODEX_SESSION_FLAGS_HOOK_SOURCE}:${label}:0:0`) + } + expect(hooks.args.join(' ')).not.toContain('session-secret-token') + } finally { await hooks.dispose() } + }) + it('injects nothing for sessions without TLDR hooks or a bearer', async () => { - expect(await createCodexTldrHooks([server({ tldrHooks: undefined })], await appRoot())).toBeNull() + expect(await createCodexLaunchHooks([server({ tldrHooks: undefined })], await appRoot())).toBeNull() expect(tldrHookServer([server({ bearerToken: undefined })])).toBeUndefined() }) }) @@ -114,7 +126,7 @@ describe('stale Codex hook credentials', () => { await writeFile(join(root, 'codex-earlier-run', 'authorization'), 'Authorization: Bearer revoked\n') await sweepStaleTldrHookFiles(root) expect(await readdir(root)).toEqual([]) - const hooks = await createCodexTldrHooks([server()], root) + const hooks = await createCodexLaunchHooks([server()], root) expect(await readdir(root)).toHaveLength(1) await hooks!.dispose() }) diff --git a/src/providers/shared/runtime/tldrHooks.ts b/src/providers/shared/runtime/tldrHooks.ts index 4c3557e43..3fb7751b0 100644 --- a/src/providers/shared/runtime/tldrHooks.ts +++ b/src/providers/shared/runtime/tldrHooks.ts @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto' import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' +import { NativeStartupReceipt } from '@providers/codex/runtime/nativeStartupReceipt.js' import type { BuiltInMcpServerConfig } from '@mcp/shared/types.js' // Provider turn hooks that make TLDR reporting enforceable (#917). @@ -110,13 +111,16 @@ function shellQuote(value: string): string { return `'${value.replace(/'/g, `'\\''`)}'` } -export type PrivateCodexTldrHooks = { +export type PrivateCodexLaunchHooks = { args: string[] + startup?: NativeStartupReceipt dispose(): Promise } /** - * Materialize Codex's TLDR hooks: `--config` arguments plus a private header file. + * Combine the launch's reporting and optional root identity hooks into a single + * session-flags trust table. Assigning hooks.state twice would drop the earlier + * launch grants. Lower-priority personal/project hooks retain their own source. * * WHY `curl` reading a header file: Codex's `mcp_tool` hook handler would call * the MCP server directly, but a hook-only tool on that server is also listed to @@ -127,33 +131,52 @@ export type PrivateCodexTldrHooks = { * Callers own `dispose()` on normal stop and on every partial-start rollback, * matching the private Claude MCP config file's lifecycle. */ -export async function createCodexTldrHooks( +export async function createCodexLaunchHooks( servers: readonly BuiltInMcpServerConfig[], root: string, -): Promise { + captureStartup = false, +): Promise { const server = tldrHookServer(servers) - if (!server) return null + if (!server && !captureStartup) return null // `root` is app-owned rather than os.tmpdir(): this file must outlive days of // idleness, and macOS clears its temp directory after three. See // TLDR_HOOK_RUNTIME_DIR. 0700 because every entry holds a live bearer. - await mkdir(root, { recursive: true, mode: 0o700 }) - await chmod(root, 0o700) - const directory = await mkdtemp(join(root, 'codex-')) + let directory: string + try { + await mkdir(root, { recursive: true, mode: 0o700 }) + await chmod(root, 0o700) + directory = await mkdtemp(join(root, 'codex-')) + } catch (error) { + if (server) throw error + // A host identity hint is optional. A read-only state directory must not + // take away a native terminal which could previously launch without TLDR. + console.warn('[codex] Could not create the launch directory for transcript identity') + return null + } const headerPath = join(directory, 'authorization') try { - await writeFile(headerPath, `Authorization: Bearer ${server.bearerToken}\n`, { encoding: 'utf8', mode: 0o600 }) + if (server) await writeFile(headerPath, `Authorization: Bearer ${server.bearerToken}\n`, { encoding: 'utf8', mode: 0o600 }) } catch (error) { await rm(directory, { recursive: true, force: true }) throw error } const args: string[] = [] const trusted: string[] = [] - for (const event of EVENTS) { + const events = server ? EVENTS.map(event => ({ + ...event, + command: `curl -fsS -H @${shellQuote(headerPath)} --data-binary @- ${shellQuote(`${server.tldrHooks.baseUrl}/${event.route}`)}`, + })) : [] + const startup = captureStartup ? new NativeStartupReceipt(directory) : undefined + const startupEvent = { + provider: 'SessionStart', + label: 'session_start', + // A unique, atomically published receipt also survives startup preceding + // the host watcher. Other hooks and panes cannot overwrite this launch. + command: `f=$(/usr/bin/mktemp ${shellQuote(join(directory, 'start.XXXXXXXX'))}) && /bin/cat > "$f" && /bin/mv "$f" "$f.json"`, + } + for (const event of startup ? [...events, startupEvent] : events) { const handler: CodexCommandHandler = { - type: 'command', - command: `curl -fsS -H @${shellQuote(headerPath)} --data-binary @- ${shellQuote(`${server.tldrHooks.baseUrl}/${event.route}`)}`, - timeout: HOOK_TIMEOUT_SECONDS, - async: false, + type: 'command', command: event.command, timeout: HOOK_TIMEOUT_SECONDS, async: false, } args.push('--config', `hooks.${event.provider}=[{hooks=[{type="command",command=${JSON.stringify(handler.command)},timeout=${handler.timeout},async=${handler.async}}]}]`) const key = `${CODEX_SESSION_FLAGS_HOOK_SOURCE}:${event.label}:0:0` @@ -164,7 +187,8 @@ export async function createCodexTldrHooks( args.push('--config', `hooks.state={${trusted.join(',')}}`) return { args, - dispose: () => rm(directory, { recursive: true, force: true }), + startup, + dispose: async () => { startup?.stop(); await rm(directory, { recursive: true, force: true }) }, } } @@ -172,9 +196,8 @@ export async function createCodexTldrHooks( * Delete hook credential files left by an earlier app run. * * Every bearer they hold was revoked when that run's MCP host stopped, so they - * are dead weight rather than live credentials. A process that exits naturally - * never calls stop() on its session, so without this sweep those files would - * accumulate. Call only before any session registers: it removes every entry. + * are dead weight rather than live credentials. Crashes can leave a receipt + * or credential file behind. Call only before any session registers. */ export async function sweepStaleTldrHookFiles(root: string): Promise { let entries: string[] diff --git a/testing/live/codex-native-transcript.test.ts b/testing/live/codex-native-transcript.test.ts new file mode 100644 index 000000000..0dd79feff --- /dev/null +++ b/testing/live/codex-native-transcript.test.ts @@ -0,0 +1,74 @@ +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { asRecord } from '@shared/lib/asRecord' +import type { CodexSession } from '@providers/codex/runtime/codexSession' + +// Only local fake-provider traffic. The two real TUIs share a trusted cwd and +// Codex home, just like neighbouring terminal panes; only the launch differs. +it.skipIf(process.env.CODEX_NATIVE_TRANSCRIPT_LIVE !== '1')('attaches each native pane to its own user turn and preserves personal hooks', async () => { + const home = await realpath(await mkdtemp(join(tmpdir(), 'codex-identity-live-'))) + const configDir = join(home, '.codex') + const cwd = join(home, 'workspace') + const configPath = join(configDir, 'config.toml') + const userLog = join(home, 'user-hooks') + const sessions: CodexSession[] = [] + try { + vi.stubEnv('HOME', home) + vi.stubEnv('CODEX_HOME', configDir) + vi.stubEnv('CODEX_NATIVE_FIXTURE_KEY', 'local-fixture') + await Promise.all([mkdir(cwd), mkdir(configDir)]) + const { CodexSession } = await import('@providers/codex/runtime/codexSession') + const { codexHookTrustHash } = await import('@providers/shared/runtime/tldrHooks') + const userHook = { type: 'command' as const, command: `echo called >> '${userLog}'`, timeout: 10, async: false } + await writeFile(configPath, [ + 'model = "gpt-6-sol"', 'model_provider = "local_fixture"', + '[model_providers.local_fixture]', 'name = "Local fixture"', 'base_url = "http://127.0.0.1:9/v1"', + 'wire_api = "responses"', 'env_key = "CODEX_NATIVE_FIXTURE_KEY"', + `[projects.${JSON.stringify(cwd)}]`, 'trust_level = "trusted"', + '[hooks]', `SessionStart=[{hooks=[{type="command",command=${JSON.stringify(userHook.command)},timeout=10,async=false}]}]`, + `[hooks.state.${JSON.stringify(`${configPath}:session_start:0:0`)}]`, + `trusted_hash=${JSON.stringify(codexHookTrustHash('session_start', userHook))}`, + ].join('\n')) + const panes = ['first native smoke', 'second native smoke'].map(marker => { + const session = new CodexSession({ cwd, cols: 120, rows: 40, useProxy: false }) + sessions.push(session) + const ids = new Set() + const prompts = new Set() + session.on('pty-data', data => { + if (data.includes('\x1b[6n')) session.write('\x1b[1;1R') + if (data.includes('\x1b[c')) session.write('\x1b[?1;2c') + }) + session.on('jsonl-entry', (entry) => { + const payload = asRecord(entry.payload) + if (!payload) return + if (entry.type === 'session_meta' && typeof payload.id === 'string') ids.add(payload.id) + if (entry.type === 'response_item' && payload.role === 'user' && Array.isArray(payload.content)) { + for (const item of payload.content) { + const part = asRecord(item) + if (part?.type === 'input_text' && typeof part.text === 'string' && /native smoke$/.test(part.text)) prompts.add(part.text) + } + } + }) + return { session, marker, ids, prompts } + }) + await Promise.all(panes.map(async ({ session, marker }) => { + await session.start() + await vi.waitFor(() => expect(session.snapshotScreen()).toMatch(/for shortcuts/), { timeout: 20_000 }) + session.write(marker) + await vi.waitFor(() => expect(session.snapshotScreen()).toContain(marker), { timeout: 5_000 }) + session.write('\r') + })) + for (const pane of panes) { + await vi.waitFor(() => expect([...pane.prompts]).toEqual([pane.marker]), { timeout: 20_000 }) + expect(pane.ids.size).toBe(1) + } + expect(new Set(panes.flatMap(pane => [...pane.ids])).size).toBe(2) + expect((await readFile(userLog, 'utf8')).trim().split('\n')).toHaveLength(2) + } finally { + await Promise.allSettled(sessions.map(session => session.stop())) + vi.unstubAllEnvs() + await rm(home, { recursive: true, force: true }) + } +}, 65_000)