Open History to see the last commit
1import { describe, expect, expectTypeOf, it, vi } from 'vitest'
2import { EventType, InMemoryRunStore, memoryStream } from '@tanstack/ai'
3import { DEFAULT_JOURNAL_DIR } from '../src/journal'
4import {
5 DurableRunIdRequiredError,
6 DurableThreadIdRequiredError,
7 alignedIfAttaching,
8 journalOptionsFor,
9 resolveDurableRunId,
10 resolveDurableThreadId,
11 resolveSandboxDurability,
12} from '../src/durability'
13import { captureLogger, collectChunks, fakeLog, fromChunkValues } from './fakes'
14import type {
15 SandboxDurabilityOptions,
16 SandboxRunDurability,
17} from '../src/durability'
18import type { StreamChunk, StreamDurability } from '@tanstack/ai'
19
20const adapterFor = (runId: string): StreamDurability =>
21 memoryStream(new Request(`https://x/run?runId=${runId}`))
22
23function text(messageId: string, delta: string): StreamChunk {
24 return {
25 type: EventType.TEXT_MESSAGE_CONTENT,
26 messageId,
27 delta,
28 timestamp: 1,
29 }
30}
31
32function bridged(name: string): StreamChunk {
33 return { type: EventType.CUSTOM, name, value: {}, timestamp: 1 }
34}
35
36/**
37 * `resolveSandboxDurability` never returns `undefined` for a fully-wired pair,
38 * but its type says it might. Narrowing here (rather than `!`) keeps the
39 * assertion in the test where a regression that DID return `undefined` would
40 * fail loudly instead of being asserted away.
41 */
42function resolvedDurability(
43 durability: Parameters<typeof resolveSandboxDurability>[0],
44): NonNullable<ReturnType<typeof resolveSandboxDurability>> {
45 const resolved = resolveSandboxDurability(durability)
46 if (resolved === undefined) {
47 throw new Error('expected resolveSandboxDurability to resolve')
48 }
49 return resolved
50}
51
52describe('resolveDurableRunId', () => {
53 it('returns a caller-supplied runId unchanged, durable or not', () => {
54 const fallback = vi.fn(() => 'generated')
55 for (const durable of [true, false]) {
56 expect(
57 resolveDurableRunId('caller-run', {
58 durable,
59 adapter: 'codex',
60 fallback,
61 }),
62 ).toBe('caller-run')
63 }
64 expect(fallback).not.toHaveBeenCalled()
65 })
66
67 it("falls back when durability is OFF, preserving today's behavior exactly", () => {
68 const fallback = vi.fn(() => 'generated')
69 expect(
70 resolveDurableRunId(undefined, {
71 durable: false,
72 adapter: 'codex',
73 fallback,
74 }),
75 ).toBe('generated')
76 expect(fallback).toHaveBeenCalledTimes(1)
77 })
78
79 it('throws when durability is ON and no runId was supplied', () => {
80 const fallback = vi.fn(() => 'generated')
81 expect(() =>
82 resolveDurableRunId(undefined, {
83 durable: true,
84 adapter: 'codex',
85 fallback,
86 }),
87 ).toThrow(DurableRunIdRequiredError)
88 // Decisive: the fallback must NOT run. A generated id would produce a
89 // journal path no successor host can recompute — an unrecoverable run that
90 // LOOKS durable.
91 expect(fallback).not.toHaveBeenCalled()
92 })
93
94 it('names the adapter and the fix in the message', () => {
95 try {
96 resolveDurableRunId(undefined, {
97 durable: true,
98 adapter: 'claude-code',
99 fallback: () => 'x',
100 })
101 expect.unreachable('should have thrown')
102 } catch (error) {
103 expect(error).toBeInstanceOf(DurableRunIdRequiredError)
104 expect((error as Error).message).toContain('claude-code')
105 expect((error as Error).message).toContain('runId')
106 }
107 })
108
109 it('rejects an empty string, which journalPaths would reject anyway', () => {
110 const fallback = vi.fn(() => 'generated')
111 expect(() =>
112 resolveDurableRunId('', { durable: true, adapter: 'codex', fallback }),
113 ).toThrow(DurableRunIdRequiredError)
114 expect(fallback).not.toHaveBeenCalled()
115 })
116
117 it('falls back on an empty string when durability is OFF, never returning it', () => {
118 // An empty runId is not a runId. Non-durable callers get a generated id
119 // rather than an id that would resolve to the journal directory itself.
120 expect(
121 resolveDurableRunId('', {
122 durable: false,
123 adapter: 'codex',
124 fallback: () => 'generated',
125 }),
126 ).toBe('generated')
127 })
128})
129
130describe('resolveDurableThreadId', () => {
131 /** The four durable×attaching quadrants, with no caller-supplied threadId. */
132 const quadrants = [
133 { durable: false, attaching: false },
134 { durable: false, attaching: true },
135 { durable: true, attaching: false },
136 { durable: true, attaching: true },
137 ]
138
139 it('returns a caller-supplied threadId unchanged in every quadrant', () => {
140 const fallback = vi.fn(() => 'generated')
141 for (const quadrant of quadrants) {
142 expect(
143 resolveDurableThreadId('caller-thread', {
144 ...quadrant,
145 adapter: 'codex',
146 fallback,
147 }),
148 ).toBe('caller-thread')
149 }
150 expect(fallback).not.toHaveBeenCalled()
151 })
152
153 it('falls back in the three non-attaching-durable quadrants', () => {
154 // The regression bar: only durable AND attaching may change behavior.
155 // Everything else must be byte-identical to the bare
156 // `options.threadId ?? this.generateId()` it replaced.
157 for (const quadrant of quadrants.slice(0, 3)) {
158 const fallback = vi.fn(() => 'generated')
159 expect(
160 resolveDurableThreadId(undefined, {
161 ...quadrant,
162 adapter: 'codex',
163 fallback,
164 }),
165 ).toBe('generated')
166 expect(fallback).toHaveBeenCalledTimes(1)
167 }
168 })
169
170 it('lets a durable FRESH run mint its own threadId — it establishes it', () => {
171 // Deliberately separate from the loop above, because this is the row an
172 // over-simplified `if (options.durable) throw` would break: every durable
173 // run that has ever worked starts fresh, with no record to reuse an id from.
174 const fallback = vi.fn(() => 'fresh-thread')
175 expect(
176 resolveDurableThreadId(undefined, {
177 durable: true,
178 attaching: false,
179 adapter: 'codex',
180 fallback,
181 }),
182 ).toBe('fresh-thread')
183 expect(fallback).toHaveBeenCalledTimes(1)
184 })
185
186 it('throws when a durable run is ATTACHING and no threadId was supplied', () => {
187 const fallback = vi.fn(() => 'generated')
188 expect(() =>
189 resolveDurableThreadId(undefined, {
190 durable: true,
191 attaching: true,
192 adapter: 'codex',
193 fallback,
194 }),
195 ).toThrow(DurableThreadIdRequiredError)
196 // Decisive: no generated id may exist even transiently. One would land in
197 // every chunk and diverge from the stored log at index 0.
198 expect(fallback).not.toHaveBeenCalled()
199 })
200
201 it('names the adapter and the concrete fix in the message', () => {
202 try {
203 resolveDurableThreadId(undefined, {
204 durable: true,
205 attaching: true,
206 adapter: 'claude-code',
207 fallback: () => 'x',
208 })
209 expect.unreachable('should have thrown')
210 } catch (error) {
211 expect(error).toBeInstanceOf(DurableThreadIdRequiredError)
212 const message = (error as Error).message
213 expect(message).toContain('claude-code')
214 expect(message).toContain('threadId')
215 // The fix must be readable without opening the source: which callback
216 // hands the id over, and where it has to be passed.
217 expect(message).toContain('drive({ runId, threadId, signal })')
218 expect(message).toContain('chat(')
219 }
220 })
221
222 it('rejects an empty string on the attach path', () => {
223 const fallback = vi.fn(() => 'generated')
224 expect(() =>
225 resolveDurableThreadId('', {
226 durable: true,
227 attaching: true,
228 adapter: 'codex',
229 fallback,
230 }),
231 ).toThrow(DurableThreadIdRequiredError)
232 expect(fallback).not.toHaveBeenCalled()
233 })
234
235 it('falls back on an empty string off the attach path, never returning it', () => {
236 expect(
237 resolveDurableThreadId('', {
238 durable: true,
239 attaching: false,
240 adapter: 'codex',
241 fallback: () => 'generated',
242 }),
243 ).toBe('generated')
244 })
245})
246
247describe('the reaper owns the detached-run TTL, and nothing else declares one', () => {
248 // `ReapOptions.detachedRunTtlMs` is the single source of truth. A duplicate
249 // TTL on `withSandbox` was read by NOBODY — the only enforcer,
250 // `reapDetachedRuns`, runs from a cron with no `CapabilityContext`, so it
251 // cannot reach the capability bus this option's parsed value was published
252 // on. Two knobs in two units at two call sites is silent divergence: `'30m'`
253 // here and `5 * 60_000` at the sweep expired runs at five minutes while the
254 // config claimed thirty, and nothing warned.
255 //
256 // These are TYPE assertions, which this repo checks (`pnpm exec tsc` covers
257 // `tests/**`). Re-adding the option makes both of them hard errors.
258 it('withSandbox durability options declare no TTL', () => {
259 expectTypeOf<SandboxDurabilityOptions>().not.toHaveProperty(
260 'detachedRunTtl',
261 )
262 expectTypeOf<SandboxRunDurability>().not.toHaveProperty('detachedRunTtlMs')
263 })
264
265 it('rejects a TTL passed to withSandbox durability at the type level', () => {
266 const options: SandboxDurabilityOptions = {
267 adapter: adapterFor('r-ttl'),
268 // @ts-expect-error -- `detachedRunTtl` no longer exists; the reaper's
269 // `detachedRunTtlMs` is the only TTL. A typo can no longer become a
270 // silent 30-minute token burn, because there is nothing to mistype.
271 detachedRunTtl: '30m',
272 }
273 void options
274 })
275})
276
277describe('resolveSandboxDurability', () => {
278 it('requires BOTH stores, and says nothing when only one is wired', () => {
279 const runs = new InMemoryRunStore()
280 // Neither.
281 expect(resolveSandboxDurability(undefined)).toBeUndefined()
282 expect(resolveSandboxDurability({})).toBeUndefined()
283 // Only `runs`: a record with no event log cannot be replayed.
284 expect(resolveSandboxDurability({ runs })).toBeUndefined()
285 // Only `durability`: a log with no record cannot be found, claimed, or
286 // reaped.
287 expect(
288 resolveSandboxDurability({ durability: { adapter: adapterFor('r1') } }),
289 ).toBeUndefined()
290 })
291
292 it('resolves both stores into the capability payload with defaults', () => {
293 const runs = new InMemoryRunStore()
294 const adapter = adapterFor('r1')
295 const resolved = resolveSandboxDurability({ runs, durability: { adapter } })
296 expect(resolved).toEqual({
297 runs,
298 adapter,
299 journalDir: DEFAULT_JOURNAL_DIR,
300 attach: false,
301 detachOnDisconnect: true,
302 })
303 // Omitted, not present-and-undefined: the field is optional and the
304 // capability payload must not carry an explicit `undefined`.
305 expect(Object.keys(resolved ?? {})).not.toContain('pollIntervalMs')
306 })
307
308 it('carries every explicit option through, including a false detach', () => {
309 const runs = new InMemoryRunStore()
310 const adapter = adapterFor('r2')
311 expect(
312 resolveSandboxDurability({
313 runs,
314 durability: {
315 adapter,
316 journal: '/srv/runs',
317 attach: true,
318 detachOnDisconnect: false,
319 pollIntervalMs: 250,
320 },
321 }),
322 ).toEqual({
323 runs,
324 adapter,
325 journalDir: '/srv/runs',
326 attach: true,
327 detachOnDisconnect: false,
328 pollIntervalMs: 250,
329 })
330 })
331})
332
333describe('journalOptionsFor', () => {
334 it('is undefined when the run is not durable, so spawnNdjson keeps its old path', () => {
335 // `isJournaled` tests `options.journal !== undefined`, so `undefined` here
336 // is what preserves the unjournaled spawn path byte for byte.
337 expect(journalOptionsFor(undefined, 'joff-1')).toBeUndefined()
338 })
339
340 it('carries runId, dir and attach from the resolved durability', () => {
341 const runs = new InMemoryRunStore()
342 const durability = resolvedDurability({
343 runs,
344 durability: {
345 adapter: fakeLog(),
346 journal: '/var/j',
347 attach: true,
348 pollIntervalMs: 10,
349 attachWaitMs: 250,
350 },
351 })
352 expect(journalOptionsFor(durability, 'jopt-attach')).toEqual({
353 runId: 'jopt-attach',
354 dir: '/var/j',
355 attach: true,
356 pollIntervalMs: 10,
357 // Only on an attach: the run record is what tells `awaitAttachableJournal`
358 // "not written yet" from "will never be written".
359 runs,
360 attachWaitMs: 250,
361 })
362 })
363
364 it('omits runs on a NON-attach run, where journal absence proves nothing', () => {
365 // A fresh run's journal is created by its own `journaledCommand` spawn
366 // moments after this option object is built, so gating on its absence would
367 // fail every new run. Not carrying the store makes that impossible.
368 const durability = resolvedDurability({
369 runs: new InMemoryRunStore(),
370 durability: { adapter: fakeLog(), attach: false, attachWaitMs: 250 },
371 })
372 const options = journalOptionsFor(durability, 'jopt-fresh')
373 expect(Object.keys(options ?? {})).not.toContain('runs')
374 expect(Object.keys(options ?? {})).not.toContain('attachWaitMs')
375 })
376
377 it('always supplies dir, even though JournalOptions.dir is optional', () => {
378 // A successor host recomputes the journal path from these options. Leaving
379 // `dir` out would make it re-derive the default independently, so the two
380 // hosts would agree only by coincidence.
381 const durability = resolvedDurability({
382 runs: new InMemoryRunStore(),
383 durability: { adapter: fakeLog() },
384 })
385 const options = journalOptionsFor(durability, 'jopt-dir')
386 expect(options?.dir).toBe(DEFAULT_JOURNAL_DIR)
387 expect(Object.keys(options ?? {})).toContain('dir')
388 })
389
390 it('omits pollIntervalMs when unset, rather than passing undefined through', () => {
391 const durability = resolvedDurability({
392 runs: new InMemoryRunStore(),
393 durability: { adapter: fakeLog() },
394 })
395 const options = journalOptionsFor(durability, 'jopt-default')
396 expect(options).toEqual({
397 runId: 'jopt-default',
398 dir: DEFAULT_JOURNAL_DIR,
399 attach: false,
400 })
401 expect(Object.keys(options ?? {})).not.toContain('pollIntervalMs')
402 })
403})
404
405describe('alignedIfAttaching', () => {
406 it('passes the stream through untouched when not attaching', async () => {
407 // A log with entries in it: proof that a NON-attach run does not align,
408 // which matters because a fresh run's own chunks would otherwise be
409 // classified as "already stored" and silently suppressed.
410 const adapter = fakeLog([text('m1', 'a')])
411 // `fakeLog` COPIES its seed, so assert against the log itself — asserting
412 // against the array passed in would be vacuous.
413 expect(await adapter.snapshot()).toEqual([
414 { offset: 'o:0', chunk: text('m1', 'a') },
415 ])
416 const durability = resolvedDurability({
417 runs: new InMemoryRunStore(),
418 durability: { adapter },
419 })
420 const source = fromChunkValues([text('m1', 'a'), text('m1', 'b')])
421 const wrapped = alignedIfAttaching(source, durability)
422 // Delivery first: without the `attach` guard, `text('m1', 'a')` matches the
423 // seeded entry and is SUPPRESSED — silent data loss, not a slow path.
424 expect(await collectChunks(wrapped)).toEqual([
425 text('m1', 'a'),
426 text('m1', 'b'),
427 ])
428 // Identity, not just equality: nothing wraps a non-attach stream at all.
429 expect(wrapped).toBe(source)
430 })
431
432 it('passes the stream through untouched when the run is not durable at all', async () => {
433 const source = fromChunkValues([text('m1', 'a')])
434 const wrapped = alignedIfAttaching(source, undefined)
435 expect(wrapped).toBe(source)
436 expect(await collectChunks(wrapped)).toEqual([text('m1', 'a')])
437 })
438
439 it('suppresses the stored prefix when attaching', async () => {
440 const adapter = fakeLog([text('m1', 'a')])
441 expect(await adapter.snapshot()).toHaveLength(1)
442 const durability = resolvedDurability({
443 runs: new InMemoryRunStore(),
444 durability: { adapter, attach: true },
445 })
446 expect(
447 await collectChunks(
448 alignedIfAttaching(
449 fromChunkValues([text('m1', 'a'), text('m1', 'b')]),
450 durability,
451 ),
452 ),
453 ).toEqual([text('m1', 'b')])
454 })
455
456 it('tolerates a bridged CUSTOM chunk in the stored log when attaching', async () => {
457 // Without `isOutOfBand: isBridgeCustomChunk` this replay diverges at the
458 // bridged entry, so a bridged-tool run could never be taken over.
459 const adapter = fakeLog([text('m1', 'a'), bridged('code_mode:console')])
460 expect(await adapter.snapshot()).toHaveLength(2)
461 const durability = resolvedDurability({
462 runs: new InMemoryRunStore(),
463 durability: { adapter, attach: true },
464 })
465 expect(
466 await collectChunks(
467 alignedIfAttaching(
468 fromChunkValues([text('m1', 'a'), text('m1', 'b')]),
469 durability,
470 ),
471 ),
472 ).toEqual([text('m1', 'b')])
473 })
474
475 it('forwards the logger so the alignment summary is observable', async () => {
476 const adapter = fakeLog([text('m1', 'a')])
477 const durability = resolvedDurability({
478 runs: new InMemoryRunStore(),
479 durability: { adapter, attach: true },
480 })
481 const { logger, calls } = captureLogger()
482 await collectChunks(
483 alignedIfAttaching(
484 fromChunkValues([text('m1', 'a'), text('m1', 'b')]),
485 durability,
486 logger,
487 ),
488 )
489 expect(calls.some((call) => call.msg.includes('journal alignment'))).toBe(
490 true,
491 )
492 })
493})