Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threads-sync.test.ts

1,345 lines48.7 KB

1import {
2 EnvironmentId,
3 EventId,
4 MessageId,
5 ORCHESTRATION_V2_WS_METHODS,
6 ThreadId,
7 TurnItemId,
8 type OrchestrationV2ThreadDetailSnapshot,
9 type OrchestrationV2ThreadProjection,
10 type OrchestrationV2ThreadStreamItem,
11 type OrchestrationV2TurnItem,
12} from "@t3tools/contracts";
13import { describe, expect, it } from "@effect/vitest";
14import * as DateTime from "effect/DateTime";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Fiber from "effect/Fiber";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Scope from "effect/Scope";
23import * as Stream from "effect/Stream";
24import * as SubscriptionRef from "effect/SubscriptionRef";
25import * as TestClock from "effect/testing/TestClock";
26import { HttpClient, HttpClientResponse } from "effect/http";
27​
28import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
29import {
30 AVAILABLE_CONNECTION_STATE,
31 PrimaryConnectionTarget,
32 type PreparedConnection,
33 type SupervisorConnectionState,
34} from "../connection/model.ts";
35import * as ConnectionWakeups from "../connection/wakeups.ts";
36import * as EnvironmentSupervisor from "../connection/supervisor.ts";
37import * as Persistence from "../platform/persistence.ts";
38import * as RpcSession from "../rpc/session.ts";
39import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
40import * as ThreadHistoryController from "./threadHistoryController.ts";
41import {
42 EMPTY_ENVIRONMENT_THREAD_STATE,
43 makeEnvironmentThreadState,
44 type EnvironmentThreadState,
45 type ThreadSnapshotLoadResult,
46} from "./threads.ts";
47import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
48​
49const TARGET = new PrimaryConnectionTarget({
50 environmentId: EnvironmentId.make("environment-1"),
51 label: "Test environment",
52 httpBaseUrl: "https://environment.example.test",
53 wsBaseUrl: "wss://environment.example.test",
54});
55const THREAD_ID = v2ThreadId;
56const CACHED_SNAPSHOT_SEQUENCE = 7;
57const PREPARED: PreparedConnection = {
58 environmentId: TARGET.environmentId,
59 label: TARGET.label,
60 httpBaseUrl: TARGET.httpBaseUrl,
61 socketUrl: TARGET.wsBaseUrl,
62 httpAuthorization: null,
63 target: TARGET,
64};
65const BASE_PROJECTION: OrchestrationV2ThreadProjection = {
66 ...v2Projection,
67 thread: { ...v2Projection.thread, title: "Cached thread" },
68};
69​
70type TestThreadInput = OrchestrationV2ThreadStreamItem | Error;
71​
72function testSession(
73 client: WsRpcProtocolClient,
74 config?: { readonly completionMarker?: boolean },
75): RpcSession.RpcSession {
76 return {
77 client,
78 initialConfig: Effect.succeed(
79 config?.completionMarker === true
80 ? ({ threadResumeCompletionMarker: true } as never)
81 : ({} as never),
82 ),
83 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
84 ready: Effect.void,
85 probe: Effect.void,
86 closed: Effect.never,
87 };
89​
90function awaitThreadState(
91 observed: Queue.Queue<EnvironmentThreadState>,
92 predicate: (state: EnvironmentThreadState) => boolean,
93) {
94 return Queue.take(observed).pipe(
95 Effect.repeat({
96 until: predicate,
97 }),
98 );
100​
101const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
102 readonly cached?: OrchestrationV2ThreadProjection;
103 readonly cachedHistory?: {
104 readonly historyCursor: string | null;
105 readonly hasMoreHistory: boolean;
106 readonly latestLocalTurnOrdinal?: number | null;
107 };
108 readonly httpSnapshot?: ThreadSnapshotLoadResult;
109 readonly completionMarker?: boolean;
110 readonly resumeCache?: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]>;
111 readonly loadCached?: ReturnType<Persistence.EnvironmentCacheStore["Service"]["loadThread"]>;
112 readonly saveThread?: Persistence.EnvironmentCacheStore["Service"]["saveThread"];
113 readonly historyPaging?: "enabled" | "no-http" | "no-controller";
114 readonly historyHttpClient?: HttpClient.HttpClient;
115}) {
116 const inputs = yield* Queue.unbounded<TestThreadInput>();
117 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
118 const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
119 const retryCount = yield* Ref.make(0);
120 const subscriptionCount = yield* Ref.make(0);
121 const loaderCalls = yield* Ref.make(0);
122 const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
123 const lastRequestCompletionMarker = yield* Ref.make(false);
124 const lastAcceptBoundedSnapshot = yield* Ref.make<true | undefined>(undefined);
125 const lastAcceptCompactTurnItems = yield* Ref.make<true | undefined>(undefined);
126 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
127 const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationV2ThreadDetailSnapshot>>([]);
128 const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
129 const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
130 AVAILABLE_CONNECTION_STATE,
131 );
132 const streamFrom = (queue: Queue.Queue<TestThreadInput>) =>
133 Stream.fromQueue(queue).pipe(
134 Stream.mapEffect((input) =>
135 input instanceof Error ? Effect.fail(input) : Effect.succeed(input),
136 ),
137 );
138 const client = {
139 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: {
140 readonly afterSequence?: number;
141 readonly requestCompletionMarker?: true;
142 readonly acceptBoundedSnapshot?: true;
143 readonly acceptCompactTurnItems?: true;
144 }) =>
145 Stream.unwrap(
146 Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
147 Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
148 Effect.andThen(
149 Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true),
150 ),
151 Effect.andThen(Ref.set(lastAcceptBoundedSnapshot, input.acceptBoundedSnapshot)),
152 Effect.andThen(Ref.set(lastAcceptCompactTurnItems, input.acceptCompactTurnItems)),
153 Effect.as(streamFrom(inputs)),
154 ),
155 ),
156 } as unknown as WsRpcProtocolClient;
157 const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
158 Option.some(testSession(client, options)),
159 );
160 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
161 Option.some(PREPARED),
162 );
163 const snapshotLoader = ThreadSnapshotLoader.ThreadSnapshotLoader.of({
164 load: (_prepared, threadId) =>
165 Ref.update(loaderCalls, (count) => count + 1).pipe(
166 Effect.as(
167 threadId === THREAD_ID
168 ? (options?.httpSnapshot ??
169 ({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult))
170 : ({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
171 ),
172 ),
173 });
174 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
175 target: TARGET,
176 state: supervisorState,
177 session: supervisorSession,
178 prepared,
179 connect: Effect.void,
180 disconnect: Effect.void,
181 retryNow: Ref.update(retryCount, (count) => count + 1),
182 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
183 const cache = Persistence.EnvironmentCacheStore.of({
184 loadShell: () => Effect.succeedNone,
185 saveShell: () => Effect.void,
186 loadThread: (_environmentId, threadId) =>
187 options?.loadCached ??
188 Effect.succeed(
189 threadId === THREAD_ID && options?.cached !== undefined
190 ? Option.some({
191 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
192 projection: options.cached,
193 ...(options.cachedHistory === undefined
194 ? {}
195 : {
196 historyCursor: options.cachedHistory.historyCursor,
197 hasMoreHistory: options.cachedHistory.hasMoreHistory,
198 ...(options.cachedHistory.latestLocalTurnOrdinal === undefined
199 ? {}
200 : {
201 latestLocalTurnOrdinal: options.cachedHistory.latestLocalTurnOrdinal,
202 }),
203 }),
204 })
205 : Option.none(),
206 ),
207 saveThread: (environmentId, thread) =>
208 Ref.update(savedThreads, (current) => [...current, thread]).pipe(
209 Effect.andThen(options?.saveThread?.(environmentId, thread) ?? Effect.void),
210 ),
211 removeThread: (_environmentId, threadId) =>
212 Ref.update(removedThreads, (current) => [...current, threadId]),
213 loadServerConfig: () => Effect.succeedNone,
214 saveServerConfig: () => Effect.void,
215 loadVcsRefs: () => Effect.succeedNone,
216 saveVcsRefs: () => Effect.void,
217 removeVcsRefs: () => Effect.void,
218 clearVcsRefs: () => Effect.void,
219 clear: () => Effect.void,
220 });
221 let makeThreadState = makeEnvironmentThreadState(THREAD_ID, options?.resumeCache).pipe(
222 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
223 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
224 Effect.provideService(ThreadSnapshotLoader.ThreadSnapshotLoader, snapshotLoader),
225 Effect.provideService(
226 ConnectionWakeups.ConnectionWakeups,
227 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
228 ),
229 );
230 if (options?.historyPaging !== "no-http") {
231 makeThreadState = makeThreadState.pipe(
232 Effect.provideService(
233 HttpClient.HttpClient,
234 options?.historyHttpClient ??
235 HttpClient.make(() => Effect.die("Unexpected history HTTP request")),
236 ),
237 );
238 }
239 const historyController = yield* ThreadHistoryController.ThreadHistoryController.pipe(
240 Effect.provide(ThreadHistoryController.layer),
241 );
242 if (options?.historyPaging !== "no-controller") {
243 makeThreadState = makeThreadState.pipe(
244 Effect.provideService(ThreadHistoryController.ThreadHistoryController, historyController),
245 );
246 }
247 const threadState = yield* makeThreadState;
248 yield* SubscriptionRef.changes(threadState).pipe(
249 Stream.runForEach((state) =>
250 Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
251 ),
252 Effect.forkScoped,
253 );
254​
255 return {
256 threadState,
257 loadEarlier: (throughEntryId?: string) =>
258 historyController.loadEarlier(TARGET.environmentId, THREAD_ID, throughEntryId),
259 inputs,
260 observed,
261 latest,
262 retryCount,
263 subscriptionCount,
264 loaderCalls,
265 lastSubscribeAfterSequence,
266 lastRequestCompletionMarker,
267 lastAcceptBoundedSnapshot,
268 lastAcceptCompactTurnItems,
269 supervisorState,
270 supervisorSession,
271 savedThreads,
272 removedThreads,
273 wakeups,
274 replaceSession: SubscriptionRef.set(
275 supervisorSession,
276 Option.some(testSession(client, options)),
277 ),
278 };
279});
280​
281const snapshot = (
282 projection: OrchestrationV2ThreadProjection,
283 snapshotSequence = 1,
284): Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "snapshot" }> => ({
285 kind: "snapshot",
286 snapshotSequence,
287 projection,
288});
289​
290const synchronized = (): OrchestrationV2ThreadStreamItem => ({ kind: "synchronized" });
291​
292const titleUpdated = (title: string, sequence = 2): OrchestrationV2ThreadStreamItem => {
293 const occurredAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
294 return {
295 kind: "event",
296 sequence,
297 event: {
298 id: EventId.make("event-title"),
299 type: "thread.metadata-updated",
300 threadId: THREAD_ID,
301 occurredAt,
302 payload: { ...v2Projection.thread, title, updatedAt: occurredAt },
303 },
304 };
305};
306​
307const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => {
308 const occurredAt = DateTime.makeUnsafe("2026-06-20T02:00:00.000Z");
309 return {
310 kind: "event",
311 sequence,
312 event: {
313 id: EventId.make("event-deleted"),
314 type: "thread.deleted",
315 threadId: THREAD_ID,
316 occurredAt,
317 payload: { ...v2Projection.thread, updatedAt: occurredAt, deletedAt: occurredAt },
318 },
319 };
320};
321​
322describe("EnvironmentThreads", () => {
323 it.effect("loads the server thread when its local cache read fails", () =>
324 Effect.gen(function* () {
325 const h = yield* makeHarness({
326 loadCached: Effect.fail(
327 new Persistence.ConnectionPersistenceError({
328 operation: "load-thread",
329 message: "The database connection is closing.",
330 }),
331 ),
332 httpSnapshot: {
333 _tag: "present",
334 snapshot: { snapshotSequence: 7, projection: BASE_PROJECTION },
335 },
336 });
337​
338 const state = yield* awaitThreadState(h.observed, (value) => value.status === "live");
339 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
340 expect(yield* Ref.get(h.loaderCalls)).toBe(1);
341 expect(yield* Ref.get(h.subscriptionCount)).toBe(1);
342 }),
343 );
344​
345 it.effect("flushes newer data after an older background write completes", () =>
346 Effect.gen(function* () {
347 const writing = yield* Deferred.make<void>();
348 const written = yield* Deferred.make<void>();
349 const release = yield* Deferred.make<void>();
350 const saved = yield* Effect.scoped(
351 Effect.gen(function* () {
352 const h = yield* makeHarness({
353 cached: BASE_PROJECTION,
354 saveThread: (_environmentId, snapshot) =>
355 snapshot.snapshotSequence === 8
356 ? Deferred.succeed(writing, undefined).pipe(
357 Effect.andThen(Deferred.await(release)),
358 Effect.andThen(Deferred.succeed(written, undefined)),
359 )
360 : Effect.void,
361 });
362 yield* Queue.offer(h.inputs, titleUpdated("First update", 8));
363 yield* awaitThreadState(
364 h.observed,
365 (value) => Option.getOrNull(value.data)?.thread.title === "First update",
366 );
367 yield* TestClock.adjust("500 millis");
368 yield* Deferred.await(writing);
369 yield* Queue.offer(h.inputs, titleUpdated("Newer update", 9));
370 yield* awaitThreadState(
371 h.observed,
372 (value) => Option.getOrNull(value.data)?.thread.title === "Newer update",
373 );
374 yield* Deferred.succeed(release, undefined);
375 yield* Deferred.await(written);
376 return h.savedThreads;
377 }),
378 );
379 expect(
380 (yield* Ref.get(saved)).map((snapshot) => [
381 snapshot.snapshotSequence,
382 snapshot.projection.thread.title,
383 ]),
384 ).toEqual([
385 [8, "First update"],
386 [9, "Newer update"],
387 ]);
388 }),
389 );
390​
391 it.effect("does not resume past a canceled event whose data was not applied", () =>
392 Effect.gen(function* () {
393 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
394 snapshot: undefined,
395 owner: undefined,
396 };
397 const scope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
398 Scope.close(scope, Exit.void),
399 );
400 const first = yield* makeHarness({
401 httpSnapshot: {
402 _tag: "present",
403 snapshot: {
404 projection: BASE_PROJECTION,
405 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
406 },
407 },
408 resumeCache,
409 }).pipe(Effect.provideService(Scope.Scope, scope));
410 yield* awaitThreadState(first.observed, (value) => value.status === "live");
411 const applying = yield* Deferred.make<void>();
412 const update = titleUpdated("Not applied", 8);
413 if (update.kind !== "event") return yield* Effect.die("Expected an event");
414 let sequenceReads = 0;
415 Object.defineProperty(update, "sequence", {
416 get: () => {
417 if (++sequenceReads === 2) Deferred.doneUnsafe(applying, Exit.void);
418 return 8;
419 },
420 });
421 yield* first.threadState.semaphore.take(1);
422 yield* Queue.offer(first.inputs, update);
423 yield* Deferred.await(applying);
424 yield* Scope.close(scope, Exit.void);
425 yield* first.threadState.semaphore.release(1);
426​
427 const resumed = yield* makeHarness({ resumeCache });
428 const state = yield* awaitThreadState(resumed.observed, (value) => value.status === "live");
429 expect(Option.getOrThrow(state.data).thread.title).toBe(BASE_PROJECTION.thread.title);
430 expect(yield* Ref.get(resumed.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
431 expect(yield* Ref.get(first.savedThreads)).toEqual([
432 {
433 projection: BASE_PROJECTION,
434 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
435 historyCursor: null,
436 hasMoreHistory: false,
437 latestLocalTurnOrdinal: null,
438 },
439 ]);
440 }),
441 );
442​
443 it.effect("prevents an old scope from replacing its successor's cached data", () =>
444 Effect.gen(function* () {
445 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
446 snapshot: undefined,
447 owner: undefined,
448 };
449 const oldScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
450 Scope.close(scope, Exit.void),
451 );
452 const old = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache }).pipe(
453 Effect.provideService(Scope.Scope, oldScope),
454 );
455 yield* awaitThreadState(old.observed, (value) => value.status === "live");
456 const successor = yield* makeHarness({ resumeCache });
457 yield* Queue.offer(successor.inputs, titleUpdated("Successor title", 9));
458 yield* awaitThreadState(
459 successor.observed,
460 (value) => Option.getOrNull(value.data)?.thread.title === "Successor title",
461 );
462 yield* Queue.offer(old.inputs, titleUpdated("Old scope title", 8));
463 yield* awaitThreadState(
464 old.observed,
465 (value) => Option.getOrNull(value.data)?.thread.title === "Old scope title",
466 );
467 yield* Scope.close(oldScope, Exit.void);
468​
469 expect(resumeCache.snapshot?.sequence).toBe(9);
470 expect(Option.getOrThrow(resumeCache.snapshot!.state.data).thread.title).toBe(
471 "Successor title",
472 );
473 expect(yield* Ref.get(old.savedThreads)).toEqual([]);
474 }),
475 );
476​
477 it.effect("does not let a delayed cache read replace an initialized successor", () =>
478 Effect.gen(function* () {
479 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
480 snapshot: undefined,
481 owner: undefined,
482 };
483 const loading = yield* Deferred.make<void>();
484 const response = yield* Deferred.make<Option.Option<OrchestrationV2ThreadDetailSnapshot>>();
485 const oldFiber = yield* makeHarness({
486 resumeCache,
487 loadCached: Deferred.succeed(loading, undefined).pipe(
488 Effect.andThen(Deferred.await(response)),
489 ),
490 }).pipe(Effect.forkScoped);
491 yield* Deferred.await(loading);
492 const successor = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache });
493 yield* awaitThreadState(successor.observed, (value) => value.status === "live");
494 yield* Deferred.succeed(
495 response,
496 Option.some({
497 snapshotSequence: 3,
498 projection: {
499 ...BASE_PROJECTION,
500 thread: { ...BASE_PROJECTION.thread, title: "Old disk data" },
501 },
502 }),
503 );
504 const old = yield* Fiber.join(oldFiber);
505 yield* awaitThreadState(old.observed, (value) => value.status === "live");
506​
507 expect(resumeCache.snapshot?.sequence).toBe(CACHED_SNAPSHOT_SEQUENCE);
508 expect(Option.getOrThrow(resumeCache.snapshot!.state.data).thread.title).toBe(
509 BASE_PROJECTION.thread.title,
510 );
511 }),
512 );
513​
514 it.effect("does not let an old deletion remove its successor's persisted cache", () =>
515 Effect.gen(function* () {
516 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
517 snapshot: undefined,
518 owner: undefined,
519 };
520 const old = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache });
521 yield* awaitThreadState(old.observed, (value) => value.status === "live");
522 const successor = yield* makeHarness({ resumeCache });
523 yield* Queue.offer(successor.inputs, titleUpdated("Successor title", 9));
524 yield* awaitThreadState(
525 successor.observed,
526 (value) => Option.getOrNull(value.data)?.thread.title === "Successor title",
527 );
528 const update = deleted();
529 if (update.kind !== "event") return yield* Effect.die("Expected an event");
530 yield* Queue.offer(old.inputs, { ...update, sequence: 8 });
531 yield* awaitThreadState(old.observed, (value) => value.status === "deleted");
532​
533 expect(resumeCache.snapshot?.sequence).toBe(9);
534 expect(yield* Ref.get(old.removedThreads)).toEqual([]);
535 }),
536 );
537​
538 it.effect("retains a deletion instead of restoring the old disk snapshot", () =>
539 Effect.gen(function* () {
540 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
541 snapshot: undefined,
542 owner: undefined,
543 };
544 yield* Effect.scoped(
545 Effect.gen(function* () {
546 const first = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache });
547 const update = deleted();
548 if (update.kind !== "event") return yield* Effect.die("Expected an event");
549 yield* Queue.offer(first.inputs, { ...update, sequence: 8 });
550 yield* awaitThreadState(first.observed, (value) => value.status === "deleted");
551 }),
552 );
553 const resumed = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache });
554 const state = yield* awaitThreadState(
555 resumed.observed,
556 (value) => value.status === "deleted",
557 );
558 expect(Option.isNone(state.data)).toBe(true);
559 expect(yield* Ref.get(resumed.loaderCalls)).toBe(0);
560 }),
561 );
562​
563 it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
564 Effect.gen(function* () {
565 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
566​
567 yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
568 yield* awaitThreadState(
569 harness.observed,
570 (value) =>
571 value.status === "live" &&
572 Option.isSome(value.data) &&
573 value.data.value.thread.title === "Live title",
574 );
575​
576 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
577 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
578 }),
579 );
580​
581 it.effect("keeps progressive history metadata from a bounded socket fallback", () =>
582 Effect.gen(function* () {
583 const olderItem = {
584 id: "item:older",
585 threadId: THREAD_ID,
586 runId: null,
587 nodeId: null,
588 providerThreadId: null,
589 providerTurnId: null,
590 nativeItemRef: null,
591 parentItemId: null,
592 ordinal: 1,
593 status: "completed",
594 title: null,
595 startedAt: "2026-06-20T00:00:00.000Z",
596 completedAt: "2026-06-20T00:00:00.000Z",
597 updatedAt: "2026-06-20T00:00:00.000Z",
598 type: "command_execution",
599 input: "pwd",
600 output: "older history",
601 exitCode: 0,
602 };
603 const harness = yield* makeHarness({
604 historyHttpClient: HttpClient.make((request, url) => {
605 expect(url.searchParams.get("cursor")).toBe("socket-history-cursor");
606 expect(url.searchParams.get("throughEntryId")).toBe(olderItem.id);
607 return Effect.succeed(
608 HttpClientResponse.fromWeb(
609 request,
610 Response.json({
611 snapshotSequence: 14,
612 items: [
613 {
614 position: 0,
615 visibility: "local",
616 sourceThreadId: THREAD_ID,
617 sourceItemId: olderItem.id,
618 item: olderItem,
619 },
620 ],
621 nextCursor: null,
622 hasMoreHistory: false,
623 }),
624 ),
625 );
626 }),
627 });
628 yield* Queue.offer(harness.inputs, {
629 kind: "snapshot",
630 snapshotSequence: 14,
631 projection: BASE_PROJECTION,
632 historyCursor: "socket-history-cursor",
633 hasMoreHistory: true,
634 latestLocalTurnOrdinal: 47,
635 payloadBudgetExceeded: false,
636 });
637​
638 const state = yield* awaitThreadState(
639 harness.observed,
640 (value) =>
641 value.status === "live" && value.history.historyCursor === "socket-history-cursor",
642 );
643 expect(state.history).toMatchObject({
644 historyCursor: "socket-history-cursor",
645 hasMoreHistory: true,
646 loading: false,
647 error: null,
648 expanded: false,
649 latestLocalTurnOrdinal: 47,
650 });
651 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBeUndefined();
652 expect(yield* Ref.get(harness.lastAcceptBoundedSnapshot)).toBe(true);
653​
654 yield* TestClock.adjust("500 millis");
655 yield* Effect.yieldNow;
656 expect((yield* Ref.get(harness.savedThreads)).at(-1)).toMatchObject({
657 snapshotSequence: 14,
658 historyCursor: "socket-history-cursor",
659 hasMoreHistory: true,
660 latestLocalTurnOrdinal: 47,
661 });
662 expect(yield* harness.loadEarlier(olderItem.id)).toEqual({ _tag: "loaded" });
663 const expanded = yield* SubscriptionRef.get(harness.threadState);
664 expect(
665 Option.getOrThrow(expanded.data).turnItems.some((item) => item.id === olderItem.id),
666 ).toBe(true);
667 expect(expanded.history.hasMoreHistory).toBe(false);
668 }),
669 );
670​
671 it.effect.each(["complete", "replacement snapshot", "retry"] as const)(
672 "progressively reveals conversation history before activity, then handles %s",
673 (mode) =>
674 Effect.gen(function* () {
675 const common = {
676 threadId: THREAD_ID,
677 runId: null,
678 nodeId: null,
679 providerThreadId: null,
680 providerTurnId: null,
681 nativeItemRef: null,
682 parentItemId: null,
683 status: "completed",
684 title: null,
685 startedAt: "2026-06-20T00:00:00.000Z",
686 completedAt: "2026-06-20T00:00:00.000Z",
687 updatedAt: "2026-06-20T00:00:00.000Z",
688 };
689 const message = {
690 ...common,
691 id: "item:older-message",
692 ordinal: 1,
693 type: "assistant_message",
694 messageId: "message:older",
695 text: "COD4 result",
696 streaming: false,
697 };
698 const activity = {
699 ...common,
700 id: "item:older-command",
701 ordinal: 2,
702 type: "command_execution",
703 input: "pwd",
704 output: "",
705 exitCode: 0,
706 };
707 const projected = (item: typeof message | typeof activity, position: number) => ({
708 position,
709 visibility: "local",
710 sourceThreadId: THREAD_ID,
711 sourceItemId: item.id,
712 item,
713 });
714 const activityStarted = yield* Deferred.make<void>();
715 const releaseActivity = yield* Deferred.make<void>();
716 let activityRequests = 0;
717 const harness = yield* makeHarness({
718 historyHttpClient: HttpClient.make((request, url) =>
719 Effect.gen(function* () {
720 expect(url.searchParams.get("cursor")).toBe("progressive-cursor");
721 const conversationOnly = url.searchParams.get("view") === "conversation";
722 if (!conversationOnly && activityRequests++ === 0) {
723 yield* Deferred.succeed(activityStarted, undefined);
724 yield* Deferred.await(releaseActivity);
725 if (mode === "retry")
726 return HttpClientResponse.fromWeb(
727 request,
728 new Response("Activity unavailable", { status: 503 }),
729 );
730 }
731 return HttpClientResponse.fromWeb(
732 request,
733 Response.json({
734 snapshotSequence: 14,
735 items: conversationOnly
736 ? [projected(message, 0)]
737 : [projected(message, 0), projected(activity, 1)],
738 nextCursor: "next-cursor",
739 hasMoreHistory: true,
740 }),
741 );
742 }),
743 ),
744 });
745 yield* Queue.offer(harness.inputs, {
746 ...snapshot(BASE_PROJECTION, 14),
747 historyCursor: "progressive-cursor",
748 hasMoreHistory: true,
749 latestLocalTurnOrdinal: 47,
750 payloadBudgetExceeded: false,
751 });
752 yield* awaitThreadState(
753 harness.observed,
754 (state) => state.history.historyCursor === "progressive-cursor",
755 );
756 const loading = yield* harness.loadEarlier(message.messageId).pipe(Effect.forkScoped);
757 yield* Deferred.await(activityStarted);
758 const preview = yield* SubscriptionRef.get(harness.threadState);
759 expect(preview.history).toMatchObject({
760 loading: true,
761 historyCursor: "progressive-cursor",
762 expanded: true,
763 });
764 expect(
765 Option.getOrThrow(preview.data).visibleTurnItems.map((row) => row.sourceItemId),
766 ).toEqual([message.id]);
767 if (mode === "replacement snapshot") {
768 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION, 15));
769 yield* awaitThreadState(
770 harness.observed,
771 (state) => state.history.historyCursor === null,
772 );
773 }
774 yield* Deferred.succeed(releaseActivity, undefined);
775 const result = yield* Fiber.join(loading);
776 if (mode === "replacement snapshot") {
777 expect(result).toEqual({ _tag: "noop" });
778 const state = yield* SubscriptionRef.get(harness.threadState);
779 expect(Option.getOrThrow(state.data).visibleTurnItems).toEqual(
780 BASE_PROJECTION.visibleTurnItems,
781 );
782 expect(state.history.historyCursor).toBeNull();
783 return;
784 }
785 if (mode === "retry") {
786 expect(result._tag).toBe("error");
787 expect(yield* harness.loadEarlier()).toEqual({ _tag: "loaded" });
788 } else expect(result).toEqual({ _tag: "loaded" });
789 const complete = yield* SubscriptionRef.get(harness.threadState);
790 expect(complete.history).toMatchObject({
791 loading: false,
792 historyCursor: "next-cursor",
793 error: null,
794 latestLocalTurnOrdinal: 47,
795 });
796 expect(
797 Option.getOrThrow(complete.data).visibleTurnItems.map((row) => row.sourceItemId),
798 ).toEqual([message.id, activity.id]);
799 expect(Option.getOrThrow(complete.data).turnItems).toHaveLength(2);
800 }),
801 );
802​
803 it.effect("restores compact socket snapshot turnItems before reducing and caching", () =>
804 Effect.gen(function* () {
805 const at = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
806 const command = (id: string, ordinal: number, threadId = THREAD_ID) =>
807 ({
808 id: TurnItemId.make(id),
809 threadId,
810 runId: null,
811 nodeId: null,
812 providerThreadId: null,
813 providerTurnId: null,
814 nativeItemRef: null,
815 parentItemId: null,
816 ordinal,
817 status: "completed" as const,
818 title: null,
819 startedAt: at,
820 completedAt: at,
821 updatedAt: at,
822 type: "command_execution" as const,
823 input: id,
824 output: id,
825 exitCode: 0,
826 }) satisfies OrchestrationV2TurnItem;
827 const parentThread = ThreadId.make("thread:compact-parent");
828 const inherited = command("parent-item", 1, parentThread);
829 const local = [command("local-1", 1), command("local-2", 2)];
830 const retainedRequest = {
831 ...command("retained-request", 0),
832 type: "run_interrupt_request" as const,
833 message: "Stop",
834 } as unknown as OrchestrationV2TurnItem;
835 const visibleTurnItems = [
836 {
837 position: 0,
838 visibility: "inherited" as const,
839 sourceThreadId: parentThread,
840 sourceItemId: inherited.id,
841 item: inherited,
842 },
843 ...local.map((item, index) => ({
844 position: index + 1,
845 visibility: "local" as const,
846 sourceThreadId: THREAD_ID,
847 sourceItemId: item.id,
848 item,
849 })),
850 ];
851 const harness = yield* makeHarness();
852 yield* Queue.offer(harness.inputs, {
853 kind: "snapshot",
854 snapshotSequence: 5,
855 projection: { ...BASE_PROJECTION, turnItems: [retainedRequest], visibleTurnItems },
856 historyCursor: "compact-cursor",
857 hasMoreHistory: true,
858 latestLocalTurnOrdinal: 2,
859 payloadBudgetExceeded: false,
860 turnItemsOmitLocalVisible: true,
861 });
862​
863 const seeded = yield* awaitThreadState(
864 harness.observed,
865 (value) => value.history.historyCursor === "compact-cursor",
866 );
867 expect(Option.getOrThrow(seeded.data).turnItems).toEqual([...local, retainedRequest]);
868 expect(yield* Ref.get(harness.lastAcceptBoundedSnapshot)).toBe(true);
869 expect(yield* Ref.get(harness.lastAcceptCompactTurnItems)).toBe(true);
870​
871 const updated = { ...local[1]!, output: "updated", ordinal: 2 };
872 yield* Queue.offer(harness.inputs, {
873 kind: "event",
874 sequence: 6,
875 event: {
876 id: EventId.make("event-compact-update"),
877 type: "turn-item.updated",
878 threadId: THREAD_ID,
879 occurredAt: at,
880 payload: updated,
881 },
882 });
883 const live = yield* awaitThreadState(harness.observed, (value) =>
884 Option.exists(value.data, (data) =>
885 data.turnItems.some(
886 (item) => item.type === "command_execution" && item.output === "updated",
887 ),
888 ),
889 );
890 expect(Option.getOrThrow(live.data).turnItems.map((item) => String(item.id))).toEqual([
891 "local-1",
892 "local-2",
893 "retained-request",
894 ]);
895​
896 yield* TestClock.adjust("500 millis");
897 yield* Effect.yieldNow;
898 const saved = (yield* Ref.get(harness.savedThreads)).at(-1);
899 expect(saved?.projection.turnItems.map((item) => String(item.id))).toEqual([
900 "local-1",
901 "local-2",
902 "retained-request",
903 ]);
904 expect(saved && "turnItemsOmitLocalVisible" in saved).toBe(false);
905 }),
906 );
907​
908 it.effect("installs bounded snapshot history meta and resumes via afterSequence", () =>
909 Effect.gen(function* () {
910 const httpProjection: OrchestrationV2ThreadProjection = {
911 ...BASE_PROJECTION,
912 thread: { ...BASE_PROJECTION.thread, title: "Bounded title" },
913 };
914 const harness = yield* makeHarness({
915 httpSnapshot: {
916 _tag: "present",
917 snapshot: { snapshotSequence: 11, projection: httpProjection },
918 history: {
919 historyCursor: "opaque-cursor",
920 hasMoreHistory: true,
921 },
922 },
923 });
924 yield* Queue.offer(harness.inputs, titleUpdated("Live after bounded", 12));
925​
926 const state = yield* awaitThreadState(
927 harness.observed,
928 (value) =>
929 value.status === "live" &&
930 Option.isSome(value.data) &&
931 value.data.value.thread.title === "Live after bounded" &&
932 value.history.hasMoreHistory,
933 );
934​
935 expect(state.history).toMatchObject({
936 historyCursor: "opaque-cursor",
937 hasMoreHistory: true,
938 loading: false,
939 error: null,
940 expanded: false,
941 });
942 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(11);
943 expect(yield* Ref.get(harness.lastAcceptBoundedSnapshot)).toBe(true);
944 expect(Option.getOrThrow(state.data).thread.title).toBe("Live after bounded");
945 }),
946 );
947​
948 it.effect("legacy warm cache without history meta stays complete (no false load-earlier)", () =>
949 Effect.gen(function* () {
950 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
951 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
952 expect(state.history).toMatchObject({
953 historyCursor: null,
954 hasMoreHistory: false,
955 expanded: false,
956 });
957 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
958 expect(yield* Ref.get(harness.lastAcceptBoundedSnapshot)).toBeUndefined();
959 }),
960 );
961​
962 it.effect.each(["disk", "retained"] as const)(
963 "retains paging support through a complete bounded %s cache",
964 (cacheKind) =>
965 Effect.gen(function* () {
966 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
967 snapshot: undefined,
968 owner: undefined,
969 };
970 const cold = yield* Effect.scoped(
971 Effect.gen(function* () {
972 const harness = yield* makeHarness({
973 resumeCache,
974 httpSnapshot: {
975 _tag: "present",
976 snapshot: { snapshotSequence: 4, projection: BASE_PROJECTION },
977 history: {
978 historyCursor: null,
979 hasMoreHistory: false,
980 latestLocalTurnOrdinal: null,
981 },
982 },
983 });
984 yield* Queue.offer(harness.inputs, titleUpdated("Complete bounded", 5));
985 yield* awaitThreadState(
986 harness.observed,
987 (value) =>
988 value.status === "live" &&
989 Option.isSome(value.data) &&
990 value.data.value.thread.title === "Complete bounded",
991 );
992 return harness;
993 }),
994 );
995 const saved = (yield* Ref.get(cold.savedThreads)).at(-1);
996 expect(saved).toMatchObject({
997 snapshotSequence: 5,
998 historyCursor: null,
999 hasMoreHistory: false,
1000 latestLocalTurnOrdinal: null,
1001 });
1002​
1003 const warm = yield* makeHarness(
1004 cacheKind === "retained"
1005 ? { resumeCache }
1006 : { loadCached: Effect.succeed(Option.some(saved!)) },
1007 );
1008 yield* Queue.offer(warm.inputs, titleUpdated("Grown while closed", 200));
1009 yield* awaitThreadState(
1010 warm.observed,
1011 (value) =>
1012 value.status === "live" &&
1013 Option.isSome(value.data) &&
1014 value.data.value.thread.title === "Grown while closed",
1015 );
1016 expect(yield* Ref.get(warm.loaderCalls)).toBe(0);
1017 expect(yield* Ref.get(warm.lastSubscribeAfterSequence)).toBe(5);
1018 expect(yield* Ref.get(warm.lastAcceptBoundedSnapshot)).toBe(true);
1019 }),
1020 );
1021​
1022 it.effect("socket snapshot clears progressive history meta left from a bounded window", () =>
1023 Effect.gen(function* () {
1024 const harness = yield* makeHarness({
1025 cached: {
1026 ...BASE_PROJECTION,
1027 thread: { ...BASE_PROJECTION.thread, title: "Warm progressive" },
1028 },
1029 cachedHistory: {
1030 historyCursor: "stale-cursor",
1031 hasMoreHistory: true,
1032 },
1033 });
1034​
1035 yield* Queue.offer(
1036 harness.inputs,
1037 snapshot(
1039 ...BASE_PROJECTION,
1040 thread: { ...BASE_PROJECTION.thread, title: "Full socket snapshot" },
1041 },
1042 CACHED_SNAPSHOT_SEQUENCE + 1,
1043 ),
1044 );
1045​
1046 const state = yield* awaitThreadState(
1047 harness.observed,
1048 (value) =>
1049 value.status === "live" &&
1050 Option.isSome(value.data) &&
1051 value.data.value.thread.title === "Full socket snapshot" &&
1052 value.history.historyCursor === null &&
1053 value.history.hasMoreHistory === false,
1054 );
1055​
1056 expect(state.history).toMatchObject({
1057 historyCursor: null,
1058 hasMoreHistory: false,
1059 expanded: false,
1060 loading: false,
1061 error: null,
1062 });
1063​
1064 yield* TestClock.adjust("500 millis");
1065 yield* Effect.yieldNow;
1066 const saved = (yield* Ref.get(harness.savedThreads)).at(-1);
1067 expect(saved?.projection.thread.title).toBe("Full socket snapshot");
1068 expect(saved?.historyCursor).toBeNull();
1069 expect(saved?.hasMoreHistory).toBe(false);
1070 }),
1071 );
1072​
1073 it.effect("installs and advances latestLocalTurnOrdinal for partial progressive windows", () =>
1074 Effect.gen(function* () {
1075 const harness = yield* makeHarness({
1076 httpSnapshot: {
1077 _tag: "present",
1078 snapshot: {
1079 snapshotSequence: 3,
1080 projection: {
1081 ...BASE_PROJECTION,
1082 thread: { ...BASE_PROJECTION.thread, title: "Watermark seed" },
1083 },
1084 latestLocalTurnOrdinal: 15,
1085 },
1086 history: {
1087 historyCursor: "wm-cursor",
1088 hasMoreHistory: true,
1089 latestLocalTurnOrdinal: 15,
1090 },
1091 },
1092 });
1093​
1094 const seeded = yield* awaitThreadState(
1095 harness.observed,
1096 (value) =>
1097 Option.isSome(value.data) &&
1098 value.data.value.thread.title === "Watermark seed" &&
1099 value.history.latestLocalTurnOrdinal === 15,
1100 );
1101 expect(seeded.history.latestLocalTurnOrdinal).toBe(15);
1102​
1103 yield* TestClock.adjust("500 millis");
1104 yield* Effect.yieldNow;
1105 const savedSeed = (yield* Ref.get(harness.savedThreads)).at(-1);
1106 expect(savedSeed?.latestLocalTurnOrdinal).toBe(15);
1107​
1108 const newer = {
1109 id: TurnItemId.make("item-newer-live"),
1110 threadId: THREAD_ID,
1111 runId: null,
1112 nodeId: null,
1113 providerThreadId: null,
1114 providerTurnId: null,
1115 nativeItemRef: null,
1116 parentItemId: null,
1117 ordinal: 22,
1118 status: "completed" as const,
1119 title: null,
1120 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
1121 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
1122 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
1123 type: "command_execution" as const,
1124 input: "echo newer",
1125 output: "newer",
1126 exitCode: 0,
1127 } satisfies OrchestrationV2TurnItem;
1128​
1129 yield* Queue.offer(harness.inputs, {
1130 kind: "event",
1131 sequence: 4,
1132 event: {
1133 id: EventId.make("event-newer-item"),
1134 type: "turn-item.updated",
1135 threadId: THREAD_ID,
1136 occurredAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
1137 payload: newer,
1138 },
1139 });
1140​
1141 const advanced = yield* awaitThreadState(
1142 harness.observed,
1143 (value) =>
1144 value.status === "live" &&
1145 Option.isSome(value.data) &&
1146 value.history.latestLocalTurnOrdinal === 22 &&
1147 value.data.value.turnItems.some((item) => String(item.id) === String(newer.id)),
1148 );
1149 expect(advanced.history.latestLocalTurnOrdinal).toBe(22);
1150 expect(advanced.history.historyCursor).toBe("wm-cursor");
1151 }),
1152 );
1153​
1154 it.effect("falls back to the socket when the HTTP snapshot is only unavailable", () =>
1155 Effect.gen(function* () {
1156 const harness = yield* makeHarness({
1157 httpSnapshot: { _tag: "unavailable" },
1158 });
1159​
1160 yield* Queue.offer(
1161 harness.inputs,
1162 snapshot({
1163 ...BASE_PROJECTION,
1164 thread: { ...BASE_PROJECTION.thread, title: "Socket title" },
1165 }),
1166 );
1167​
1168 const state = yield* awaitThreadState(
1169 harness.observed,
1170 (value) =>
1171 value.status === "live" &&
1172 Option.isSome(value.data) &&
1173 value.data.value.thread.title === "Socket title",
1174 );
1175​
1176 expect(Option.getOrThrow(state.data).thread.title).toBe("Socket title");
1177 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
1178 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
1179 expect(yield* Ref.get(harness.removedThreads)).toEqual([]);
1180 }),
1181 );
1182​
1183 it.effect("does not recreate a deleted cache from a queued save or finalizer", () =>
1184 Effect.gen(function* () {
1185 const scope = yield* Scope.make();
1186 const harness = yield* makeHarness().pipe(Effect.provideService(Scope.Scope, scope));
1187 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
1188 yield* awaitThreadState(harness.observed, (value) => value.status === "live");
1189 yield* TestClock.adjust("500 millis");
1190 expect(yield* Ref.get(harness.savedThreads)).toHaveLength(1);
1191​
1192 yield* Queue.offer(harness.inputs, titleUpdated("Queued before deletion"));
1193 yield* awaitThreadState(
1194 harness.observed,
1195 (value) =>
1196 Option.isSome(value.data) && value.data.value.thread.title === "Queued before deletion",
1197 );
1198 yield* Queue.offer(harness.inputs, deleted());
1199 const state = yield* awaitThreadState(
1200 harness.observed,
1201 (value) => value.status === "deleted",
1202 );
1203 expect(Option.isNone(state.data)).toBe(true);
1204 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
1205​
1206 yield* TestClock.adjust("10 seconds");
1207 expect(yield* Ref.get(harness.savedThreads)).toHaveLength(1);
1208 yield* Scope.close(scope, Exit.void);
1209 expect(yield* Ref.get(harness.savedThreads)).toHaveLength(1);
1210 }),
1211 );
1212​
1213 it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
1214 Effect.gen(function* () {
1215 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
1216 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
1217 yield* Queue.offer(harness.inputs, new Error("stream failed"));
1218​
1219 const state = yield* awaitThreadState(harness.observed, (value) =>
1220 Option.isSome(value.error),
1221 );
1222​
1223 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
1224 expect(Option.getOrThrow(state.error)).toBe("stream failed");
1225 expect(yield* Ref.get(harness.retryCount)).toBe(0);
1226​
1227 yield* harness.replaceSession;
1228 for (let attempt = 0; attempt < 100; attempt += 1) {
1229 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
1230 break;
1232 yield* Effect.yieldNow;
1234 yield* Queue.offer(
1235 harness.inputs,
1236 snapshot({
1237 ...BASE_PROJECTION,
1238 thread: { ...BASE_PROJECTION.thread, title: "Recovered thread" },
1239 }),
1240 );
1241 const recovered = yield* awaitThreadState(
1242 harness.observed,
1243 (value) =>
1244 value.status === "live" &&
1245 Option.isSome(value.data) &&
1246 value.data.value.thread.title === "Recovered thread",
1247 );
1248​
1249 expect(Option.isNone(recovered.error)).toBe(true);
1250 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1251 }),
1252 );
1253​
1254 it.effect("keeps replayed updates synchronizing until the completion marker arrives", () =>
1255 Effect.gen(function* () {
1256 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
1257 yield* awaitThreadState(
1258 harness.observed,
1259 (value) => value.status === "synchronizing" && Option.isSome(value.data),
1260 );
1261 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
1262​
1263 yield* Queue.offer(
1264 harness.inputs,
1265 titleUpdated("Caught-up title", CACHED_SNAPSHOT_SEQUENCE + 1),
1266 );
1267 const catchingUp = yield* awaitThreadState(
1268 harness.observed,
1269 (value) =>
1270 value.status === "synchronizing" &&
1271 Option.isSome(value.data) &&
1272 value.data.value.thread.title === "Caught-up title",
1273 );
1274 expect(catchingUp.status).toBe("synchronizing");
1275​
1276 yield* Queue.offer(harness.inputs, synchronized());
1277 const live = yield* awaitThreadState(
1278 harness.observed,
1279 (value) => value.status === "live" && Option.isSome(value.data),
1280 );
1281 expect(Option.getOrThrow(live.data).thread.title).toBe("Caught-up title");
1282 }),
1283 );
1284​
1285 it.effect("skips an unknown event type and resumes after it", () =>
1286 Effect.gen(function* () {
1287 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
1288 const unknown = (sequence: number): OrchestrationV2ThreadStreamItem => ({
1289 kind: "unknown-event",
1290 sequence,
1291 eventType: "run.from-a-future-server",
1292 });
1293 const occurredAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
1294 yield* Queue.offerAll(harness.inputs, [
1296 kind: "event",
1297 sequence: CACHED_SNAPSHOT_SEQUENCE + 1,
1298 event: {
1299 id: EventId.make("event-message"),
1300 type: "message.updated",
1301 threadId: THREAD_ID,
1302 occurredAt,
1303 payload: {
1304 id: MessageId.make("message-before"),
1305 threadId: THREAD_ID,
1306 runId: null,
1307 nodeId: null,
1308 role: "assistant",
1309 text: "Before",
1310 streaming: false,
1311 attachments: [],
1312 createdBy: "agent",
1313 creationSource: "provider",
1314 createdAt: occurredAt,
1315 updatedAt: occurredAt,
1316 },
1317 },
1318 },
1319 unknown(CACHED_SNAPSHOT_SEQUENCE + 2),
1320 titleUpdated("After", CACHED_SNAPSHOT_SEQUENCE + 3),
1321 unknown(CACHED_SNAPSHOT_SEQUENCE + 4),
1322 synchronized(),
1323 ]);
1324 const live = yield* awaitThreadState(
1325 harness.observed,
1326 (value) =>
1327 value.status === "live" &&
1328 Option.isSome(value.data) &&
1329 value.data.value.thread.title === "After",
1330 );
1331 expect(Option.isNone(live.error)).toBe(true);
1332 expect(Option.getOrThrow(live.data).messages.map((message) => message.text)).toEqual([
1333 "Before",
1334 ]);
1335​
1336 yield* harness.replaceSession;
1337 for (let attempt = 0; attempt < 100; attempt += 1) {
1338 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
1339 yield* Effect.yieldNow;
1341 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1342 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 4);
1343 }),
1344 );
1345});