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