Open History to see the last commit
1/**
2 * Wiring tests for the durable-run attach path (Phase 3).
3 *
4 * These are wiring tests, not unit tests of `journalOptionsFor` /
5 * `alignedIfAttaching` themselves (covered in `@tanstack/ai-sandbox`'s own
6 * `durability.test.ts`). What is asserted here is that the REAL adapter call
7 * site in `../src/adapters/text.ts` actually reaches those helpers:
8 *
9 * - journaling is gated on the resolved sandbox-durability capability, not
10 * merely on a caller-supplied `runId` (Task 5);
11 * - `attach: true` makes `spawnNdjson` tail the EXISTING journal instead of
12 * starting a new agent (Task 7);
13 * - the journal path is derived from the caller-supplied `runId` (Task 5/7);
14 * - a durable run with no caller-supplied `runId` fails loudly instead of
15 * silently minting an unrecoverable one (Task 5).
16 *
17 * Every `runId` and `journalDir` below is minted per test. `journalPaths`'s
18 * default directory is a REAL host path (`/tmp/tanstack-runs`) that outlives
19 * any single sandbox or test run — see `journal.ts`'s own warning — so a
20 * fixed literal here would read a previous run's leftover journal.
21 */
22import { afterAll, describe, expect, it } from 'vitest'
23import * as fsp from 'node:fs/promises'
24import * as os from 'node:os'
25import * as path from 'node:path'
26import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
27import {
28 DurableRunIdRequiredError,
29 DurableThreadIdRequiredError,
30 SandboxCapability,
31 journalPaths,
32 journaledCommand,
33 provideSandboxDurability,
34} from '@tanstack/ai-sandbox'
35import { EventType, InMemoryRunStore } from '@tanstack/ai'
36import { codexText } from '../src/index'
37import type { InternalLogger } from '@tanstack/ai/adapter-internals'
38import type {
39 CapabilityContext,
40 StreamChunk,
41 StreamDurability,
42} from '@tanstack/ai'
43import type { SandboxHandle, SandboxRunDurability } from '@tanstack/ai-sandbox'
44
45const baseDir = path.join(
46 os.tmpdir(),
47 `tanstack-ai-codex-attach-test-${Date.now()}`,
48)
49const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
50
51afterAll(async () => {
52 try {
53 await fsp.rm(baseDir, { recursive: true, force: true })
54 } catch {
55 // Windows can report EBUSY here when a child process handle briefly
56 // outlives `sbx.destroy()`; this is a cleanup nicety, not part of what
57 // the test verifies, so a failure here must not fail the suite.
58 }
59})
60
61const noopLogger = {
62 request: () => {},
63 provider: () => {},
64 errors: () => {},
65 agentLoop: () => {},
66 warnings: () => {},
67 debug: () => {},
68} as unknown as InternalLogger
69
70// Stand-in for `codex exec --experimental-json`: reads the prompt from stdin
71// and emits canned thread-event JSONL, same shape `text-adapter.test.ts` uses.
72const FAKE_CODEX = [
73 `let input = ''`,
74 `process.stdin.on('data', (d) => { input += d })`,
75 `process.stdin.on('end', () => {`,
76 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
77 ` w({ type: 'thread.started', thread_id: 'th-1' })`,
78 ` w({ type: 'turn.started' })`,
79 ` w({ type: 'item.completed', item: { id: 'i1', type: 'agent_message', text: 'pong' } })`,
80 ` w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
81 `})`,
82].join('\n')
83
84/**
85 * Minimal in-memory `StreamDurability`. Only used to make the durability
86 * capability RESOLVABLE (`runs` + `durability.adapter` both present) — the
87 * journal itself (what `attach: true` actually tails) is a separate,
88 * in-sandbox file governed by `SandboxDurabilityOptions.journal`, not this
89 * adapter.
90 *
91 * `seed` pre-populates `snapshot()`, which is what `alignedIfAttaching` reads
92 * to decide what a previous host already delivered (see `align.ts`'s
93 * `alignToStoredLog`). Defaults to empty, i.e. nothing to align against.
94 */
95function fakeStreamDurability(
96 seed: Array<{ offset: string; chunk: StreamChunk }> = [],
97): StreamDurability {
98 return {
99 resumeFrom: () => null,
100 append: (chunks) => Promise.resolve(chunks.map((_, i) => String(i))),
101 read: () => (async function* () {})(),
102 close: () => Promise.resolve(),
103 snapshot: () => Promise.resolve(seed),
104 }
105}
106
107/**
108 * Records every command the handle spawns/execs, and forces the
109 * bounded-poll journal read strategy. Mirrors
110 * `translate-determinism.test.ts`'s `pollStrategyHandle`: on this host the
111 * follow strategy's `tail -f` pipeline can go undelivered for a payload
112 * under one stdio buffer, which is a property of this host's stdio, not of
113 * anything under test here.
114 */
115function recordingHandle(handle: SandboxHandle): {
116 handle: SandboxHandle
117 spawned: Array<string>
118} {
119 const spawned: Array<string> = []
120 return {
121 spawned,
122 handle: {
123 ...handle,
124 capabilities: { ...handle.capabilities, killableProcesses: false },
125 process: {
126 ...handle.process,
127 spawn: (command, options) => {
128 spawned.push(command)
129 return handle.process.spawn(command, options)
130 },
131 exec: (command, options) => {
132 spawned.push(command)
133 return handle.process.exec(command, options)
134 },
135 },
136 },
137 }
138}
139
140function capabilityContext(
141 handle: SandboxHandle,
142 durability?: SandboxRunDurability,
143): CapabilityContext {
144 const [, provideSandbox] = SandboxCapability
145 const ctx = {
146 capabilities: { markProvided: () => {}, has: () => true },
147 } as unknown as CapabilityContext
148 provideSandbox(ctx, handle)
149 if (durability !== undefined) provideSandboxDurability(ctx, durability)
150 return ctx
151}
152
153function durabilityWith(
154 overrides: Partial<SandboxRunDurability> = {},
155): SandboxRunDurability {
156 return {
157 runs: new InMemoryRunStore(),
158 adapter: fakeStreamDurability(),
159 journalDir: `/tmp/tanstack-runs-attach-${crypto.randomUUID()}`,
160 attach: false,
161 detachOnDisconnect: true,
162 ...overrides,
163 }
164}
165
166async function collect(
167 stream: AsyncIterable<StreamChunk>,
168): Promise<Array<StreamChunk>> {
169 const out: Array<StreamChunk> = []
170 for await (const chunk of stream) out.push(chunk)
171 return out
172}
173
174/**
175 * The DISTINCT `threadId`s stamped across a run's chunks.
176 *
177 * A set, not a list, because `threadId` appears on several chunk types
178 * (`RUN_STARTED`, `RUN_FINISHED`, …) and what matters is that they all agree on
179 * one id — the caller's on an attach, a generated one otherwise. Anything with
180 * more than one entry means the resolution ran twice.
181 */
182function threadIdsOf(chunks: Array<StreamChunk>): Array<string> {
183 const seen = new Set<string>()
184 for (const chunk of chunks) {
185 const value = (chunk as { threadId?: unknown }).threadId
186 if (typeof value === 'string') seen.add(value)
187 }
188 return [...seen]
189}
190
191function textOf(chunks: Array<StreamChunk>): string {
192 return chunks
193 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
194 .map((c) => (c as { delta?: string }).delta ?? '')
195 .join('')
196}
197
198describe('codex attach wiring', () => {
199 it('does NOT start an agent when attaching — it only tails the journal', async () => {
200 const sbx = await provider.create({})
201 const recorder = recordingHandle(sbx)
202 const runId = `r-attach-${crypto.randomUUID()}`
203 const durability = durabilityWith({ attach: true })
204 const paths = journalPaths(runId, durability.journalDir)
205
206 // Pre-populate the journal exactly as a previous host's journaled agent
207 // would have — through the shell (`journaledCommand`), not
208 // `sandbox.fs.write`: `journal.ts` rule 3 warns the journal directory is
209 // a REAL host path outside the virtualized sandbox root, so the two
210 // resolve differently. `journaledCommand` also appends the `__exit`
211 // sentinel, exactly like a completed prior run's journal would carry.
212 const priorEvents = [
213 '{"type":"thread.started","thread_id":"sess-1"}',
214 '{"type":"turn.started"}',
215 '{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"pong"}}',
216 '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}',
217 ].join('\\n')
218 const seed = await sbx.process.spawn(
219 journaledCommand(`printf '${priorEvents}\\n'`, paths),
220 )
221 expect(await seed.wait()).toBe(0)
222
223 // No `codexExecutable` override, and no fake codex script written at all:
224 // if attach were broken and this spawned a NEW agent anyway, it would try
225 // to run the real (uninstalled) `codex` binary and the run would fail
226 // loudly with a RUN_ERROR (or a rejected read), rather than this test
227 // silently passing regardless.
228 const adapter = codexText('gpt-5.5-codex')
229 const chunks = await collect(
230 adapter.chatStream({
231 model: 'gpt-5.5-codex',
232 messages: [{ role: 'user', content: 'say pong' }],
233 logger: noopLogger,
234 runId,
235 // A real attach always has the run record's `threadId` — core's
236 // `startRunDriver` hands it to `drive({ runId, threadId, signal })` —
237 // and `resolveDurableThreadId` now REQUIRES it, because an attach that
238 // mints a fresh one stamps every chunk with an id the stored log cannot
239 // match. Omitting it here (as this test originally did) exercised a
240 // configuration that could never align; supplying it keeps the subject
241 // of this test — that no agent is spawned on attach — unchanged.
242 threadId: `t-attach-${crypto.randomUUID()}`,
243 capabilities: capabilityContext(recorder.handle, durability),
244 }),
245 )
246
247 expect(textOf(chunks)).toContain('pong')
248 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
249 // The command codex's `buildCommand` produces always contains this exact
250 // flag; its absence from every spawned/exec'd command proves the agent
251 // itself was never started.
252 expect(
253 recorder.spawned.some((command) =>
254 command.includes('exec --experimental-json'),
255 ),
256 ).toBe(false)
257 await sbx.destroy()
258 })
259
260 it("aligns against the durability adapter's stored log when attaching, suppressing the already-delivered prefix", async () => {
261 // Distinct from the previous test: that one proves the in-sandbox JOURNAL
262 // is tailed instead of respawned. This one proves the SEPARATE
263 // cross-host durability log (`SandboxDurabilityOptions.adapter`, what
264 // `alignedIfAttaching` reads via `snapshot()`) is actually consulted —
265 // the two are different logs by design (see `durability.ts`'s module
266 // doc), and it is easy to wire one without the other.
267 const sbx = await provider.create({})
268 const runId = `r-align-${crypto.randomUUID()}`
269 const threadId = `t-align-${crypto.randomUUID()}`
270
271 // The stored "already delivered" prefix is exactly the RUN_STARTED chunk
272 // `translateThreadEvents` emits first (see `translate.ts`'s `startRun`).
273 // `chunkFingerprint` (what `alignToStoredLog` compares with) drops
274 // `timestamp`, so an arbitrary placeholder there still matches.
275 const storedRunStarted: StreamChunk = {
276 type: EventType.RUN_STARTED,
277 runId,
278 threadId,
279 model: 'gpt-5.5-codex',
280 timestamp: 0,
281 }
282 const durability = durabilityWith({
283 attach: true,
284 adapter: fakeStreamDurability([
285 { offset: 'o0', chunk: storedRunStarted },
286 ]),
287 })
288 const paths = journalPaths(runId, durability.journalDir)
289 const recorder = recordingHandle(sbx)
290
291 const priorEvents = [
292 '{"type":"thread.started","thread_id":"sess-1"}',
293 '{"type":"turn.started"}',
294 '{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"pong"}}',
295 '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}',
296 ].join('\\n')
297 const seed = await sbx.process.spawn(
298 journaledCommand(`printf '${priorEvents}\\n'`, paths),
299 )
300 expect(await seed.wait()).toBe(0)
301
302 const adapter = codexText('gpt-5.5-codex')
303 const chunks = await collect(
304 adapter.chatStream({
305 model: 'gpt-5.5-codex',
306 messages: [{ role: 'user', content: 'say pong' }],
307 logger: noopLogger,
308 runId,
309 threadId,
310 capabilities: capabilityContext(recorder.handle, durability),
311 }),
312 )
313
314 // The RUN_STARTED chunk was already "delivered" per the stored log, so
315 // alignment must suppress it — if `alignedIfAttaching` were bypassed, the
316 // freshly-translated RUN_STARTED would come through unsuppressed and this
317 // would fail.
318 expect(chunks.some((c) => c.type === 'RUN_STARTED')).toBe(false)
319 // Everything after the aligned prefix must still arrive.
320 expect(textOf(chunks)).toContain('pong')
321 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
322 await sbx.destroy()
323 })
324
325 it('starts the agent and tails when NOT attaching', async () => {
326 const sbx = await provider.create({})
327 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
328 const recorder = recordingHandle(sbx)
329 const runId = `r-fresh-${crypto.randomUUID()}`
330 const durability = durabilityWith({ attach: false })
331 const paths = journalPaths(runId, durability.journalDir)
332
333 const adapter = codexText('gpt-5.5-codex', {
334 codexExecutable: 'node fake-codex.mjs',
335 })
336 const chunks = await collect(
337 adapter.chatStream({
338 model: 'gpt-5.5-codex',
339 messages: [{ role: 'user', content: 'say pong' }],
340 logger: noopLogger,
341 runId,
342 capabilities: capabilityContext(recorder.handle, durability),
343 }),
344 )
345
346 expect(textOf(chunks)).toContain('pong')
347 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
348 // The agent's stdout was redirected into the journal (`>>`), not piped
349 // directly — proving `journal` reached `spawnNdjson` for a FRESH run too,
350 // not only on attach.
351 const journaled = recorder.spawned.filter((command) =>
352 command.includes(paths.journal),
353 )
354 expect(journaled.length).toBeGreaterThan(0)
355 expect(journaled.some((command) => command.includes('>>'))).toBe(true)
356 await sbx.destroy()
357 })
358
359 it('does NOT journal a non-durable run — byte-identical to a pre-durability run', async () => {
360 // The other side of the byte-identical guarantee `journalOptionsFor`
361 // documents: a run with no `SandboxDurabilityCapability` wired (no
362 // `runs`/`durability.adapter` given to `withSandbox`) must take
363 // `spawnNdjson`'s ORIGINAL unjournaled path — piping the agent's stdout
364 // directly rather than redirecting it into a file. A caller-supplied
365 // `runId` alone must not be enough to turn journaling on; only the
366 // resolved durability capability may.
367 const sbx = await provider.create({})
368 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
369 const recorder = recordingHandle(sbx)
370 const runId = `r-nondurable-${crypto.randomUUID()}`
371 const paths = journalPaths(runId)
372
373 const adapter = codexText('gpt-5.5-codex', {
374 codexExecutable: 'node fake-codex.mjs',
375 })
376 const chunks = await collect(
377 adapter.chatStream({
378 model: 'gpt-5.5-codex',
379 messages: [{ role: 'user', content: 'say pong' }],
380 logger: noopLogger,
381 runId,
382 // No durability capability provided at all — only the sandbox.
383 capabilities: capabilityContext(recorder.handle),
384 }),
385 )
386
387 expect(textOf(chunks)).toContain('pong')
388 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
389 expect(
390 recorder.spawned.some((command) => command.includes(paths.journal)),
391 ).toBe(false)
392 await sbx.destroy()
393 })
394
395 it('derives the journal path from the caller-supplied runId', async () => {
396 const sbx = await provider.create({})
397 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
398 const recorder = recordingHandle(sbx)
399 const runId = `r-derive-${crypto.randomUUID()}`
400 const otherRunId = `r-other-${crypto.randomUUID()}`
401 const durability = durabilityWith({ attach: false })
402 const paths = journalPaths(runId, durability.journalDir)
403 const otherPaths = journalPaths(otherRunId, durability.journalDir)
404
405 const adapter = codexText('gpt-5.5-codex', {
406 codexExecutable: 'node fake-codex.mjs',
407 })
408 await collect(
409 adapter.chatStream({
410 model: 'gpt-5.5-codex',
411 messages: [{ role: 'user', content: 'say pong' }],
412 logger: noopLogger,
413 runId,
414 capabilities: capabilityContext(recorder.handle, durability),
415 }),
416 )
417
418 expect(
419 recorder.spawned.some((command) => command.includes(paths.journal)),
420 ).toBe(true)
421 // Not just "a" journal path — THIS run's, derived from THIS runId, and no
422 // other run's path leaks in.
423 expect(
424 recorder.spawned.some((command) => command.includes(otherPaths.journal)),
425 ).toBe(false)
426 await sbx.destroy()
427 })
428
429 it('reuses the resolved runId for the stdin-fallback prompt file, not a re-derived one', async () => {
430 // The plan's own known omission for this package: the stdin-fallback
431 // branch (`sandbox.capabilities.writableStdin === false`) used to compute
432 // its prompt-file suffix from a SECOND, independent
433 // `options.runId ?? this.generateId()`, rather than the runId already
434 // resolved via `resolveDurableRunId` above it. When `options.runId` is
435 // absent, `this.generateId()` mints a fresh random id on EVERY call, so
436 // the two would silently diverge — invisible here (the prompt still gets
437 // read from the file it names), but defeating the point of a stable,
438 // caller-supplied `runId` for anything keyed off it. This test does not
439 // supply a `runId` at all, so a reintroduced bug is observable: the
440 // prompt-file suffix would stop matching the id the deterministic
441 // `createRunScopedIdGen(runId)` generator actually used.
442 //
443 // Uses a fully synthetic handle rather than `localProcessSandbox`: that
444 // provider's `fs.write` resolves an absolute path under the VIRTUALIZED
445 // sandbox root (`handle.ts`'s `resolve()`), while a shell redirect like
446 // `< /tmp/...` in a spawned command hits the REAL host `/tmp` — the same
447 // fs-vs-shell split `journal.ts` warns about for the journal path. That
448 // split is orthogonal to what this test checks (which `runId` gets used,
449 // not whether the file round-trips through a real sandbox), so a fake
450 // handle sidesteps it entirely instead of exercising an unrelated,
451 // pre-existing local-process limitation.
452 const spawned: Array<string> = []
453 const events = [
454 { type: 'thread.started', thread_id: 'th-1' },
455 { type: 'turn.started' },
456 {
457 type: 'item.started',
458 item: {
459 id: 'cmd-1',
460 type: 'command_execution',
461 command: 'ls',
462 status: 'in_progress',
463 },
464 },
465 {
466 type: 'item.completed',
467 item: {
468 id: 'cmd-1',
469 type: 'command_execution',
470 command: 'ls',
471 aggregated_output: 'file.txt\n',
472 exit_code: 0,
473 status: 'completed',
474 },
475 },
476 { type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } },
477 ]
478 const fakeHandle = {
479 id: 'fake',
480 provider: 'fake',
481 capabilities: {
482 fs: true,
483 exec: true,
484 env: false,
485 ports: false,
486 backgroundProcesses: true,
487 writableStdin: false,
488 killableProcesses: true,
489 snapshots: false,
490 networkPolicy: false,
491 durableFilesystem: false,
492 fork: false,
493 },
494 fs: {
495 read: () => Promise.resolve(''),
496 readBytes: () => Promise.resolve(new Uint8Array()),
497 write: () => Promise.resolve(),
498 list: () => Promise.resolve([]),
499 mkdir: () => Promise.resolve(),
500 remove: () => Promise.resolve(),
501 rename: () => Promise.resolve(),
502 exists: () => Promise.resolve(false),
503 },
504 git: {},
505 process: {
506 exec: () => Promise.reject(new Error('exec unused by this path')),
507 spawn: (command: string) => {
508 spawned.push(command)
509 return Promise.resolve({
510 pid: 1,
511 stdout: (async function* () {
512 for (const event of events) yield `${JSON.stringify(event)}\n`
513 })(),
514 stderr: (async function* () {})(),
515 stdin: {
516 write: () => Promise.resolve(),
517 end: () => Promise.resolve(),
518 },
519 wait: () => Promise.resolve(0),
520 kill: () => Promise.resolve(),
521 })
522 },
523 },
524 ports: {},
525 env: {},
526 destroy: () => Promise.resolve(),
527 } as unknown as SandboxHandle
528
529 const adapter = codexText('gpt-5.5-codex')
530 const chunks = await collect(
531 adapter.chatStream({
532 model: 'gpt-5.5-codex',
533 messages: [{ role: 'user', content: 'say pong' }],
534 logger: noopLogger,
535 // No runId: exercises the generated-fallback path this test targets.
536 capabilities: capabilityContext(fakeHandle),
537 }),
538 )
539
540 const toolResult = chunks.find((c) => c.type === 'TOOL_CALL_RESULT') as
541 | { messageId?: unknown }
542 | undefined
543 const messageId = toolResult?.messageId
544 expect(typeof messageId).toBe('string')
545 if (typeof messageId !== 'string') {
546 throw new Error('unreachable: asserted above')
547 }
548 // `createRunScopedIdGen(runId)` mints `${runId}-${counter}`; strip the
549 // counter to recover the runId the adapter actually resolved.
550 const resolvedRunId = messageId.replace(/-\d+$/, '')
551
552 const promptCommand = spawned.find((command) =>
553 command.includes('tanstack-codex-prompt-'),
554 )
555 expect(promptCommand).toBeDefined()
556 expect(promptCommand).toContain(
557 `/tmp/tanstack-codex-prompt-${resolvedRunId}`,
558 )
559 })
560
561 it('throws DurableRunIdRequiredError when durability is wired without a runId', async () => {
562 const durability = durabilityWith()
563 const ctx = {
564 capabilities: { markProvided: () => {}, has: () => true },
565 } as unknown as CapabilityContext
566 provideSandboxDurability(ctx, durability)
567
568 // No SandboxCapability needed: `resolveDurableRunId` throws before the
569 // adapter ever reaches `sandboxFrom(options)`, which is exactly the
570 // point — a durable run with no caller-supplied `runId` must fail before
571 // it spends a single token or touches a sandbox at all.
572 const adapter = codexText('gpt-5.5-codex')
573 await expect(
574 collect(
575 adapter.chatStream({
576 model: 'gpt-5.5-codex',
577 messages: [{ role: 'user', content: 'hi' }],
578 logger: noopLogger,
579 capabilities: ctx,
580 }),
581 ),
582 ).rejects.toThrow(DurableRunIdRequiredError)
583 })
584
585 it('throws DurableThreadIdRequiredError when ATTACHING without a threadId', async () => {
586 // The silent-divergence hole this closes: `threadId` lands in every
587 // emitted chunk, so an attach that mints a fresh one replays a stream the
588 // stored log cannot match at index 0. Before this guard the run started,
589 // read the journal, and only then failed alignment mid-stream.
590 const runId = `r-no-thread-${crypto.randomUUID()}`
591 const durability = durabilityWith({ attach: true })
592 const ctx = {
593 capabilities: { markProvided: () => {}, has: () => true },
594 } as unknown as CapabilityContext
595 provideSandboxDurability(ctx, durability)
596
597 // `runId` IS supplied, so `resolveDurableRunId` passes and the rejection
598 // can only come from the threadId guard. As with that guard, no
599 // SandboxCapability is needed: the refusal precedes `sandboxFrom`.
600 const adapter = codexText('gpt-5.5-codex')
601 await expect(
602 collect(
603 adapter.chatStream({
604 model: 'gpt-5.5-codex',
605 messages: [{ role: 'user', content: 'hi' }],
606 logger: noopLogger,
607 runId,
608 capabilities: ctx,
609 }),
610 ),
611 ).rejects.toThrow(DurableThreadIdRequiredError)
612 })
613
614 it('carries a caller-supplied threadId into the chunks when ATTACHING', async () => {
615 const sbx = await provider.create({})
616 const recorder = recordingHandle(sbx)
617 const runId = `r-thread-ok-${crypto.randomUUID()}`
618 const threadId = `t-reused-${crypto.randomUUID()}`
619 // Empty stored log, unlike the alignment test above: nothing is suppressed,
620 // so the RUN_STARTED chunk that carries `threadId` is observable.
621 const durability = durabilityWith({ attach: true })
622 const paths = journalPaths(runId, durability.journalDir)
623
624 const priorEvents = [
625 '{"type":"thread.started","thread_id":"sess-1"}',
626 '{"type":"turn.started"}',
627 '{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"pong"}}',
628 '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}',
629 ].join('\\n')
630 const seed = await sbx.process.spawn(
631 journaledCommand(`printf '${priorEvents}\\n'`, paths),
632 )
633 expect(await seed.wait()).toBe(0)
634
635 const adapter = codexText('gpt-5.5-codex')
636 const chunks = await collect(
637 adapter.chatStream({
638 model: 'gpt-5.5-codex',
639 messages: [{ role: 'user', content: 'say pong' }],
640 logger: noopLogger,
641 runId,
642 threadId,
643 capabilities: capabilityContext(recorder.handle, durability),
644 }),
645 )
646
647 expect(textOf(chunks)).toContain('pong')
648 // Not merely "it did not throw": the id the caller passed must be the id
649 // stamped on the stream, which is the only thing that makes the replay
650 // alignable against the stored log.
651 expect(threadIdsOf(chunks)).toEqual([threadId])
652 await sbx.destroy()
653 })
654
655 it('lets a durable FRESH run generate its own threadId', async () => {
656 // The regression bar for the guard: a fresh durable run is the run that
657 // ESTABLISHES the threadId, so it must still mint one. A guard keyed on
658 // `durable` alone (rather than durable AND attaching) would break this.
659 const sbx = await provider.create({})
660 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
661 const recorder = recordingHandle(sbx)
662 const runId = `r-fresh-thread-${crypto.randomUUID()}`
663 const durability = durabilityWith({ attach: false })
664
665 const adapter = codexText('gpt-5.5-codex', {
666 codexExecutable: 'node fake-codex.mjs',
667 })
668 const chunks = await collect(
669 adapter.chatStream({
670 model: 'gpt-5.5-codex',
671 messages: [{ role: 'user', content: 'say pong' }],
672 logger: noopLogger,
673 runId,
674 // threadId intentionally omitted.
675 capabilities: capabilityContext(recorder.handle, durability),
676 }),
677 )
678
679 expect(textOf(chunks)).toContain('pong')
680 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
681 const threadIds = threadIdsOf(chunks)
682 expect(threadIds).toHaveLength(1)
683 expect(threadIds[0]).toMatch(/.+/)
684 await sbx.destroy()
685 })
686
687 it('lets a NON-durable run generate its own threadId, unchanged', async () => {
688 const sbx = await provider.create({})
689 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
690 const recorder = recordingHandle(sbx)
691
692 const adapter = codexText('gpt-5.5-codex', {
693 codexExecutable: 'node fake-codex.mjs',
694 })
695 const chunks = await collect(
696 adapter.chatStream({
697 model: 'gpt-5.5-codex',
698 messages: [{ role: 'user', content: 'say pong' }],
699 logger: noopLogger,
700 // Neither runId nor threadId, and no durability capability: exactly a
701 // pre-durability run.
702 capabilities: capabilityContext(recorder.handle),
703 }),
704 )
705
706 expect(textOf(chunks)).toContain('pong')
707 const threadIds = threadIdsOf(chunks)
708 expect(threadIds).toHaveLength(1)
709 expect(threadIds[0]).toMatch(/.+/)
710 await sbx.destroy()
711 })
712})