Open History to see the last commit
1import {
2 EnvironmentId,
3 EventId,
4 ORCHESTRATION_V2_WS_METHODS,
5 ThreadId,
6 TurnItemId,
7 type OrchestrationV2ThreadDetailSnapshot,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2ThreadStreamItem,
10 type OrchestrationV2TurnItem,
11} from "@t3tools/contracts";
12import { describe, expect, it } from "@effect/vitest";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import * as TestClock from "effect/testing/TestClock";
21
22import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
23import {
24 AVAILABLE_CONNECTION_STATE,
25 PrimaryConnectionTarget,
26 type PreparedConnection,
27 type SupervisorConnectionState,
28} from "../connection/model.ts";
29import * as ConnectionWakeups from "../connection/wakeups.ts";
30import * as EnvironmentSupervisor from "../connection/supervisor.ts";
31import * as Persistence from "../platform/persistence.ts";
32import * as RpcSession from "../rpc/session.ts";
33import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
34import {
35 EMPTY_ENVIRONMENT_THREAD_STATE,
36 makeEnvironmentThreadState,
37 ThreadSnapshotLoader,
38 type EnvironmentThreadState,
39 type ThreadSnapshotLoadResult,
40} from "./threads.ts";
41
42const TARGET = new PrimaryConnectionTarget({
43 environmentId: EnvironmentId.make("environment-1"),
44 label: "Test environment",
45 httpBaseUrl: "https://environment.example.test",
46 wsBaseUrl: "wss://environment.example.test",
47});
48const THREAD_ID = v2ThreadId;
49const CACHED_SNAPSHOT_SEQUENCE = 7;
50const PREPARED: PreparedConnection = {
51 environmentId: TARGET.environmentId,
52 label: TARGET.label,
53 httpBaseUrl: TARGET.httpBaseUrl,
54 socketUrl: TARGET.wsBaseUrl,
55 httpAuthorization: null,
56 target: TARGET,
57};
58const BASE_PROJECTION: OrchestrationV2ThreadProjection = {
59 ...v2Projection,
60 thread: { ...v2Projection.thread, title: "Cached thread" },
61};
62
63type TestThreadInput = OrchestrationV2ThreadStreamItem | Error;
64
65function testSession(
66 client: WsRpcProtocolClient,
67 config?: { readonly completionMarker?: boolean },
68): RpcSession.RpcSession {
69 return {
70 client,
71 initialConfig: Effect.succeed({
72 threadResumeCompletionMarker: config?.completionMarker === true,
73 } as never),
74 ready: Effect.void,
75 probe: Effect.void,
76 closed: Effect.never,
77 };
78}
79
80function awaitThreadState(
81 observed: Queue.Queue<EnvironmentThreadState>,
82 predicate: (state: EnvironmentThreadState) => boolean,
83) {
84 return Queue.take(observed).pipe(
85 Effect.repeat({
86 until: predicate,
87 }),
88 );
89}
90
91const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
92 readonly cached?: OrchestrationV2ThreadProjection;
93 readonly cachedHistory?: {
94 readonly historyCursor: string | null;
95 readonly hasMoreHistory: boolean;
96 readonly latestLocalTurnOrdinal?: number | null;
97 };
98 readonly httpSnapshot?: ThreadSnapshotLoadResult;
99 readonly completionMarker?: boolean;
100}) {
101 const inputs = yield* Queue.unbounded<TestThreadInput>();
102 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
103 const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
104 const retryCount = yield* Ref.make(0);
105 const subscriptionCount = yield* Ref.make(0);
106 const loaderCalls = yield* Ref.make(0);
107 const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
108 const lastRequestCompletionMarker = yield* Ref.make(false);
109 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
110 const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationV2ThreadDetailSnapshot>>([]);
111 const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
112 const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
113 AVAILABLE_CONNECTION_STATE,
114 );
115 const streamFrom = (queue: Queue.Queue<TestThreadInput>) =>
116 Stream.fromQueue(queue).pipe(
117 Stream.mapEffect((input) =>
118 input instanceof Error ? Effect.fail(input) : Effect.succeed(input),
119 ),
120 );
121 const client = {
122 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: {
123 readonly afterSequence?: number;
124 readonly requestCompletionMarker?: true;
125 }) =>
126 Stream.unwrap(
127 Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
128 Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
129 Effect.andThen(
130 Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true),
131 ),
132 Effect.as(streamFrom(inputs)),
133 ),
134 ),
135 } as unknown as WsRpcProtocolClient;
136 const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
137 Option.some(testSession(client, options)),
138 );
139 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
140 Option.some(PREPARED),
141 );
142 const snapshotLoader = ThreadSnapshotLoader.of({
143 load: (_prepared, threadId) =>
144 Ref.update(loaderCalls, (count) => count + 1).pipe(
145 Effect.as(
146 threadId === THREAD_ID
147 ? (options?.httpSnapshot ??
148 ({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult))
149 : ({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
150 ),
151 ),
152 });
153 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
154 target: TARGET,
155 state: supervisorState,
156 session: supervisorSession,
157 prepared,
158 connect: Effect.void,
159 disconnect: Effect.void,
160 retryNow: Ref.update(retryCount, (count) => count + 1),
161 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
162 const cache = Persistence.EnvironmentCacheStore.of({
163 loadShell: () => Effect.succeed(Option.none()),
164 saveShell: () => Effect.void,
165 loadThread: (_environmentId, threadId) =>
166 Effect.succeed(
167 threadId === THREAD_ID && options?.cached !== undefined
168 ? Option.some({
169 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
170 projection: options.cached,
171 ...(options.cachedHistory === undefined
172 ? {}
173 : {
174 historyCursor: options.cachedHistory.historyCursor,
175 hasMoreHistory: options.cachedHistory.hasMoreHistory,
176 ...(options.cachedHistory.latestLocalTurnOrdinal === undefined
177 ? {}
178 : {
179 latestLocalTurnOrdinal: options.cachedHistory.latestLocalTurnOrdinal,
180 }),
181 }),
182 })
183 : Option.none(),
184 ),
185 saveThread: (_environmentId, snapshot) =>
186 Ref.update(savedThreads, (current) => [...current, snapshot]),
187 removeThread: (_environmentId, threadId) =>
188 Ref.update(removedThreads, (current) => [...current, threadId]),
189 loadServerConfig: () => Effect.succeed(Option.none()),
190 saveServerConfig: () => Effect.void,
191 loadVcsRefs: () => Effect.succeed(Option.none()),
192 saveVcsRefs: () => Effect.void,
193 removeVcsRefs: () => Effect.void,
194 clearVcsRefs: () => Effect.void,
195 clear: () => Effect.void,
196 });
197 const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
198 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
199 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
200 Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
201 Effect.provideService(
202 ConnectionWakeups.ConnectionWakeups,
203 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
204 ),
205 );
206 yield* SubscriptionRef.changes(threadState).pipe(
207 Stream.runForEach((state) =>
208 Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
209 ),
210 Effect.forkScoped,
211 );
212
213 return {
214 inputs,
215 observed,
216 latest,
217 retryCount,
218 subscriptionCount,
219 loaderCalls,
220 lastSubscribeAfterSequence,
221 lastRequestCompletionMarker,
222 supervisorState,
223 supervisorSession,
224 savedThreads,
225 removedThreads,
226 wakeups,
227 replaceSession: SubscriptionRef.set(
228 supervisorSession,
229 Option.some(testSession(client, options)),
230 ),
231 };
232});
233
234const snapshot = (
235 projection: OrchestrationV2ThreadProjection,
236 snapshotSequence = 1,
237): OrchestrationV2ThreadStreamItem => ({
238 kind: "snapshot",
239 snapshotSequence,
240 projection,
241});
242
243const synchronized = (): OrchestrationV2ThreadStreamItem => ({ kind: "synchronized" });
244
245const titleUpdated = (title: string, sequence = 2): OrchestrationV2ThreadStreamItem => {
246 const occurredAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
247 return {
248 kind: "event",
249 sequence,
250 event: {
251 id: EventId.make("event-title"),
252 type: "thread.metadata-updated",
253 threadId: THREAD_ID,
254 occurredAt,
255 payload: { ...v2Projection.thread, title, updatedAt: occurredAt },
256 },
257 };
258};
259
260const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => {
261 const occurredAt = DateTime.makeUnsafe("2026-06-20T02:00:00.000Z");
262 return {
263 kind: "event",
264 sequence,
265 event: {
266 id: EventId.make("event-deleted"),
267 type: "thread.deleted",
268 threadId: THREAD_ID,
269 occurredAt,
270 payload: { ...v2Projection.thread, updatedAt: occurredAt, deletedAt: occurredAt },
271 },
272 };
273};
274
275describe("EnvironmentThreads", () => {
276 it.effect("publishes cached data immediately from a warm cache", () =>
277 Effect.gen(function* () {
278 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
279 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
280
281 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
282 expect(Option.isNone(state.error)).toBe(true);
283 }),
284 );
285
286 it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
287 Effect.gen(function* () {
288 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
289
290 // The warm cache reaches live from the cached data, and a live event
291 // applies on top of it.
292 yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
293 yield* awaitThreadState(
294 harness.observed,
295 (value) =>
296 value.status === "live" &&
297 Option.isSome(value.data) &&
298 value.data.value.thread.title === "Live title",
299 );
300
301 // The subscription resumed from the cached sequence and never fetched the
302 // full snapshot over HTTP.
303 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
304 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
305 }),
306 );
307
308 it.effect("reduces live events and persists the latest thread", () =>
309 Effect.gen(function* () {
310 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
311 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
312 yield* Queue.offer(harness.inputs, titleUpdated("Live title"));
313
314 const state = yield* awaitThreadState(
315 harness.observed,
316 (value) =>
317 value.status === "live" &&
318 Option.isSome(value.data) &&
319 value.data.value.thread.title === "Live title",
320 );
321 yield* TestClock.adjust("500 millis");
322 yield* Effect.yieldNow;
323
324 expect(Option.getOrThrow(state.data).thread.title).toBe("Live title");
325 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.projection.thread.title).toBe(
326 "Live title",
327 );
328 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
329 }),
330 );
331
332 it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
333 Effect.gen(function* () {
334 const httpProjection: OrchestrationV2ThreadProjection = {
335 ...BASE_PROJECTION,
336 thread: { ...BASE_PROJECTION.thread, title: "HTTP title" },
337 };
338 const harness = yield* makeHarness({
339 httpSnapshot: {
340 _tag: "present",
341 snapshot: { snapshotSequence: 1, projection: httpProjection },
342 },
343 });
344 // No socket snapshot is pushed; only a live event arrives over the socket.
345 // It can only be applied if the HTTP snapshot already seeded the thread.
346 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
347
348 const state = yield* awaitThreadState(
349 harness.observed,
350 (value) =>
351 value.status === "live" &&
352 Option.isSome(value.data) &&
353 value.data.value.thread.title === "Live title",
354 );
355
356 expect(Option.getOrThrow(state.data).thread.title).toBe("Live title");
357 // Cold cache: the full snapshot was loaded over HTTP and the socket
358 // resumed from that snapshot's sequence.
359 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
360 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
361 }),
362 );
363
364 it.effect("installs bounded snapshot history meta and resumes via afterSequence", () =>
365 Effect.gen(function* () {
366 const httpProjection: OrchestrationV2ThreadProjection = {
367 ...BASE_PROJECTION,
368 thread: { ...BASE_PROJECTION.thread, title: "Bounded title" },
369 };
370 const harness = yield* makeHarness({
371 httpSnapshot: {
372 _tag: "present",
373 snapshot: { snapshotSequence: 11, projection: httpProjection },
374 history: {
375 historyCursor: "opaque-cursor",
376 hasMoreHistory: true,
377 },
378 },
379 });
380 yield* Queue.offer(harness.inputs, titleUpdated("Live after bounded", 12));
381
382 const state = yield* awaitThreadState(
383 harness.observed,
384 (value) =>
385 value.status === "live" &&
386 Option.isSome(value.data) &&
387 value.data.value.thread.title === "Live after bounded" &&
388 value.history.hasMoreHistory,
389 );
390
391 expect(state.history).toMatchObject({
392 historyCursor: "opaque-cursor",
393 hasMoreHistory: true,
394 loading: false,
395 error: null,
396 expanded: false,
397 });
398 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(11);
399 // Bounded HTTP success must not require a socket snapshot frame.
400 expect(Option.getOrThrow(state.data).thread.title).toBe("Live after bounded");
401 }),
402 );
403
404 it.effect("persists progressive history meta with a settled bounded snapshot", () =>
405 Effect.gen(function* () {
406 const httpProjection: OrchestrationV2ThreadProjection = {
407 ...BASE_PROJECTION,
408 thread: { ...BASE_PROJECTION.thread, title: "Bounded cache title" },
409 };
410 const harness = yield* makeHarness({
411 httpSnapshot: {
412 _tag: "present",
413 snapshot: { snapshotSequence: 4, projection: httpProjection },
414 history: {
415 historyCursor: "cursor-oldest",
416 hasMoreHistory: true,
417 },
418 },
419 });
420 // Bounded install alone (settled) must enqueue progressive meta with the
421 // projection. Never persist the partial window as a complete full snapshot.
422 yield* awaitThreadState(
423 harness.observed,
424 (value) =>
425 Option.isSome(value.data) &&
426 value.data.value.thread.title === "Bounded cache title" &&
427 value.history.historyCursor === "cursor-oldest",
428 );
429 yield* TestClock.adjust("500 millis");
430 yield* Effect.yieldNow;
431
432 const savedAll = yield* Ref.get(harness.savedThreads);
433 expect(savedAll.length).toBeGreaterThanOrEqual(1);
434 const first = savedAll[0];
435 expect(first?.snapshotSequence).toBe(4);
436 expect(first?.projection.thread.title).toBe("Bounded cache title");
437 expect(first?.historyCursor).toBe("cursor-oldest");
438 expect(first?.hasMoreHistory).toBe(true);
439 // No earlier complete-looking entry without progressive meta.
440 expect(
441 savedAll.some(
442 (entry) =>
443 entry.projection.thread.title === "Bounded cache title" &&
444 entry.historyCursor === undefined &&
445 entry.hasMoreHistory === undefined,
446 ),
447 ).toBe(false);
448
449 // A later live update still carries the progressive cursor.
450 yield* Queue.offer(harness.inputs, titleUpdated("Settled bounded", 5));
451 yield* awaitThreadState(
452 harness.observed,
453 (value) =>
454 value.status === "live" &&
455 Option.isSome(value.data) &&
456 value.data.value.thread.title === "Settled bounded",
457 );
458 yield* TestClock.adjust("500 millis");
459 yield* Effect.yieldNow;
460
461 const saved = (yield* Ref.get(harness.savedThreads)).at(-1);
462 expect(saved?.snapshotSequence).toBe(5);
463 expect(saved?.projection.thread.title).toBe("Settled bounded");
464 expect(saved?.historyCursor).toBe("cursor-oldest");
465 expect(saved?.hasMoreHistory).toBe(true);
466 }),
467 );
468
469 it.effect("warm resume restores progressive history meta and skips HTTP", () =>
470 Effect.gen(function* () {
471 const harness = yield* makeHarness({
472 cached: {
473 ...BASE_PROJECTION,
474 thread: { ...BASE_PROJECTION.thread, title: "Cached bounded" },
475 },
476 cachedHistory: {
477 historyCursor: "warm-cursor",
478 hasMoreHistory: true,
479 },
480 });
481
482 // Apply a live event so the subscription is known to have resumed from cache.
483 yield* Queue.offer(
484 harness.inputs,
485 titleUpdated("Cached bounded live", CACHED_SNAPSHOT_SEQUENCE + 1),
486 );
487 const state = yield* awaitThreadState(
488 harness.observed,
489 (value) =>
490 value.status === "live" &&
491 Option.isSome(value.data) &&
492 value.data.value.thread.title === "Cached bounded live" &&
493 value.history.hasMoreHistory,
494 );
495
496 expect(state.history).toMatchObject({
497 historyCursor: "warm-cursor",
498 hasMoreHistory: true,
499 expanded: false,
500 });
501 // Warm progressive cache must not re-download; resume via afterSequence.
502 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
503 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
504 }),
505 );
506
507 it.effect("legacy warm cache without history meta stays complete (no false load-earlier)", () =>
508 Effect.gen(function* () {
509 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
510 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
511 expect(state.history).toMatchObject({
512 historyCursor: null,
513 hasMoreHistory: false,
514 expanded: false,
515 });
516 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
517 }),
518 );
519
520 it.effect("socket snapshot clears progressive history meta left from a bounded window", () =>
521 Effect.gen(function* () {
522 const harness = yield* makeHarness({
523 cached: {
524 ...BASE_PROJECTION,
525 thread: { ...BASE_PROJECTION.thread, title: "Warm progressive" },
526 },
527 cachedHistory: {
528 historyCursor: "stale-cursor",
529 hasMoreHistory: true,
530 },
531 });
532
533 yield* Queue.offer(
534 harness.inputs,
535 snapshot(
536 {
537 ...BASE_PROJECTION,
538 thread: { ...BASE_PROJECTION.thread, title: "Full socket snapshot" },
539 },
540 CACHED_SNAPSHOT_SEQUENCE + 1,
541 ),
542 );
543
544 const state = yield* awaitThreadState(
545 harness.observed,
546 (value) =>
547 value.status === "live" &&
548 Option.isSome(value.data) &&
549 value.data.value.thread.title === "Full socket snapshot" &&
550 value.history.historyCursor === null &&
551 value.history.hasMoreHistory === false,
552 );
553
554 expect(state.history).toMatchObject({
555 historyCursor: null,
556 hasMoreHistory: false,
557 expanded: false,
558 loading: false,
559 error: null,
560 });
561
562 // Settled full snapshot persistence must not keep the stale cursor.
563 yield* TestClock.adjust("500 millis");
564 yield* Effect.yieldNow;
565 const saved = (yield* Ref.get(harness.savedThreads)).at(-1);
566 expect(saved?.projection.thread.title).toBe("Full socket snapshot");
567 expect(saved?.historyCursor).toBeUndefined();
568 expect(saved?.hasMoreHistory).toBeUndefined();
569 }),
570 );
571
572 it.effect("live events preserve progressive history meta under atomic setThread", () =>
573 Effect.gen(function* () {
574 const harness = yield* makeHarness({
575 httpSnapshot: {
576 _tag: "present",
577 snapshot: {
578 snapshotSequence: 8,
579 projection: {
580 ...BASE_PROJECTION,
581 thread: { ...BASE_PROJECTION.thread, title: "Bounded seed" },
582 },
583 },
584 history: {
585 historyCursor: "keep-me",
586 hasMoreHistory: true,
587 },
588 },
589 });
590
591 yield* Queue.offer(harness.inputs, titleUpdated("Live preserves meta", 9));
592 const state = yield* awaitThreadState(
593 harness.observed,
594 (value) =>
595 value.status === "live" &&
596 Option.isSome(value.data) &&
597 value.data.value.thread.title === "Live preserves meta",
598 );
599
600 expect(state.history).toMatchObject({
601 historyCursor: "keep-me",
602 hasMoreHistory: true,
603 expanded: false,
604 });
605 }),
606 );
607
608 it.effect("bounded HTTP install sets projection and progressive meta atomically", () =>
609 Effect.gen(function* () {
610 // One setThread with explicit history (not applyItem reset + later meta).
611 const harness = yield* makeHarness({
612 httpSnapshot: {
613 _tag: "present",
614 snapshot: {
615 snapshotSequence: 2,
616 projection: {
617 ...BASE_PROJECTION,
618 thread: { ...BASE_PROJECTION.thread, title: "Bounded atomic install" },
619 },
620 },
621 history: {
622 historyCursor: "post-install-cursor",
623 hasMoreHistory: true,
624 },
625 },
626 });
627
628 const state = yield* awaitThreadState(
629 harness.observed,
630 (value) =>
631 Option.isSome(value.data) &&
632 value.data.value.thread.title === "Bounded atomic install" &&
633 value.history.historyCursor === "post-install-cursor" &&
634 value.history.hasMoreHistory === true,
635 );
636
637 expect(state.history).toMatchObject({
638 historyCursor: "post-install-cursor",
639 hasMoreHistory: true,
640 loading: false,
641 error: null,
642 expanded: false,
643 });
644 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(2);
645 }),
646 );
647
648 it.effect("dropped partial-timeline turn item is a true applyItem no-op", () =>
649 Effect.gen(function* () {
650 const recent = {
651 id: TurnItemId.make("item-window"),
652 threadId: THREAD_ID,
653 runId: null,
654 nodeId: null,
655 providerThreadId: null,
656 providerTurnId: null,
657 nativeItemRef: null,
658 parentItemId: null,
659 ordinal: 10,
660 status: "completed" as const,
661 title: null,
662 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
663 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
664 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
665 type: "command_execution" as const,
666 input: "pwd",
667 output: "ok",
668 exitCode: 0,
669 } satisfies OrchestrationV2TurnItem;
670 const recentRow = {
671 position: 0,
672 visibility: "local" as const,
673 sourceThreadId: THREAD_ID,
674 sourceItemId: recent.id,
675 item: recent,
676 };
677 const boundedProjection: OrchestrationV2ThreadProjection = {
678 ...BASE_PROJECTION,
679 thread: { ...BASE_PROJECTION.thread, title: "Partial noop" },
680 turnItems: [recent],
681 visibleTurnItems: [recentRow],
682 };
683 const harness = yield* makeHarness({
684 httpSnapshot: {
685 _tag: "present",
686 snapshot: {
687 snapshotSequence: 5,
688 projection: boundedProjection,
689 latestLocalTurnOrdinal: 10,
690 },
691 history: {
692 historyCursor: "partial-cursor",
693 hasMoreHistory: true,
694 latestLocalTurnOrdinal: 10,
695 },
696 },
697 });
698
699 const seeded = yield* awaitThreadState(
700 harness.observed,
701 (value) =>
702 value.status === "live" &&
703 Option.isSome(value.data) &&
704 value.data.value.thread.title === "Partial noop" &&
705 value.history.historyCursor === "partial-cursor",
706 );
707 const seededProjection = Option.getOrThrow(seeded.data);
708 yield* TestClock.adjust("500 millis");
709 yield* Effect.yieldNow;
710 const savedBefore = (yield* Ref.get(harness.savedThreads)).length;
711
712 const older = {
713 ...recent,
714 id: TurnItemId.make("item-old-outside"),
715 ordinal: 3,
716 output: "must-not-append",
717 } satisfies OrchestrationV2TurnItem;
718 yield* Queue.offer(harness.inputs, {
719 kind: "event",
720 sequence: 6,
721 event: {
722 id: EventId.make("event-old-partial"),
723 type: "turn-item.updated",
724 threadId: THREAD_ID,
725 occurredAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
726 payload: older,
727 },
728 });
729
730 // Allow the event to be processed without requiring a state transition.
731 for (let attempt = 0; attempt < 30; attempt += 1) {
732 yield* Effect.yieldNow;
733 }
734 // Drive a later unrelated title update so we know the stream continued.
735 yield* Queue.offer(harness.inputs, titleUpdated("After dropped event", 7));
736 const after = yield* awaitThreadState(
737 harness.observed,
738 (value) =>
739 value.status === "live" &&
740 Option.isSome(value.data) &&
741 value.data.value.thread.title === "After dropped event",
742 );
743
744 // The dropped event must not have appended the old item.
745 expect(Option.getOrThrow(after.data).turnItems.map((item) => String(item.id))).toEqual([
746 String(recent.id),
747 ]);
748 // Watermark unchanged (only advanced on successful newer turn-item applies).
749 expect(after.history.latestLocalTurnOrdinal).toBe(10);
750 // No persistence enqueue from the dropped event itself.
751 const savedAfterDrop = (yield* Ref.get(harness.savedThreads)).length;
752 expect(savedAfterDrop).toBe(savedBefore);
753 // Seeded projection reference path: event path kept partial meta intact.
754 expect(after.history.historyCursor).toBe("partial-cursor");
755 expect(after.history.hasMoreHistory).toBe(true);
756 // Title event applied; drop itself did not clear progressive meta.
757 expect(seededProjection.turnItems.map((item) => String(item.id))).toEqual([
758 String(recent.id),
759 ]);
760 }),
761 );
762
763 it.effect("installs and advances latestLocalTurnOrdinal for partial progressive windows", () =>
764 Effect.gen(function* () {
765 const harness = yield* makeHarness({
766 httpSnapshot: {
767 _tag: "present",
768 snapshot: {
769 snapshotSequence: 3,
770 projection: {
771 ...BASE_PROJECTION,
772 thread: { ...BASE_PROJECTION.thread, title: "Watermark seed" },
773 },
774 latestLocalTurnOrdinal: 15,
775 },
776 history: {
777 historyCursor: "wm-cursor",
778 hasMoreHistory: true,
779 latestLocalTurnOrdinal: 15,
780 },
781 },
782 });
783
784 const seeded = yield* awaitThreadState(
785 harness.observed,
786 (value) =>
787 Option.isSome(value.data) &&
788 value.data.value.thread.title === "Watermark seed" &&
789 value.history.latestLocalTurnOrdinal === 15,
790 );
791 expect(seeded.history.latestLocalTurnOrdinal).toBe(15);
792
793 yield* TestClock.adjust("500 millis");
794 yield* Effect.yieldNow;
795 const savedSeed = (yield* Ref.get(harness.savedThreads)).at(-1);
796 expect(savedSeed?.latestLocalTurnOrdinal).toBe(15);
797
798 const newer = {
799 id: TurnItemId.make("item-newer-live"),
800 threadId: THREAD_ID,
801 runId: null,
802 nodeId: null,
803 providerThreadId: null,
804 providerTurnId: null,
805 nativeItemRef: null,
806 parentItemId: null,
807 ordinal: 22,
808 status: "completed" as const,
809 title: null,
810 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
811 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
812 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"),
813 type: "command_execution" as const,
814 input: "echo newer",
815 output: "newer",
816 exitCode: 0,
817 } satisfies OrchestrationV2TurnItem;
818
819 yield* Queue.offer(harness.inputs, {
820 kind: "event",
821 sequence: 4,
822 event: {
823 id: EventId.make("event-newer-item"),
824 type: "turn-item.updated",
825 threadId: THREAD_ID,
826 occurredAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
827 payload: newer,
828 },
829 });
830
831 const advanced = yield* awaitThreadState(
832 harness.observed,
833 (value) =>
834 value.status === "live" &&
835 Option.isSome(value.data) &&
836 value.history.latestLocalTurnOrdinal === 22 &&
837 value.data.value.turnItems.some((item) => String(item.id) === String(newer.id)),
838 );
839 expect(advanced.history.latestLocalTurnOrdinal).toBe(22);
840 expect(advanced.history.historyCursor).toBe("wm-cursor");
841 }),
842 );
843
844 it.effect("warm resume restores latestLocalTurnOrdinal from progressive cache", () =>
845 Effect.gen(function* () {
846 const harness = yield* makeHarness({
847 cached: {
848 ...BASE_PROJECTION,
849 thread: { ...BASE_PROJECTION.thread, title: "Warm watermark" },
850 },
851 cachedHistory: {
852 historyCursor: "warm-wm-cursor",
853 hasMoreHistory: true,
854 latestLocalTurnOrdinal: 33,
855 },
856 });
857
858 const state = yield* awaitThreadState(
859 harness.observed,
860 (value) =>
861 Option.isSome(value.data) &&
862 value.data.value.thread.title === "Warm watermark" &&
863 value.history.latestLocalTurnOrdinal === 33,
864 );
865 expect(state.history).toMatchObject({
866 historyCursor: "warm-wm-cursor",
867 hasMoreHistory: true,
868 latestLocalTurnOrdinal: 33,
869 expanded: false,
870 });
871 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
872 }),
873 );
874
875 it.effect("marks a cold definitive HTTP miss deleted without socket subscribe or retry", () =>
876 Effect.gen(function* () {
877 const harness = yield* makeHarness({
878 httpSnapshot: { _tag: "missing" },
879 });
880
881 const state = yield* awaitThreadState(
882 harness.observed,
883 (value) => value.status === "deleted",
884 );
885
886 expect(Option.isNone(state.data)).toBe(true);
887 expect(Option.isNone(state.error)).toBe(true);
888 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
889 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
890 expect(yield* Ref.get(harness.subscriptionCount)).toBe(0);
891
892 // A definitive miss must not schedule the expected-failure retry path.
893 yield* TestClock.adjust("1 second");
894 for (let attempt = 0; attempt < 20; attempt += 1) {
895 yield* Effect.yieldNow;
896 }
897 yield* harness.replaceSession;
898 yield* Queue.offer(harness.wakeups, "application-active");
899 for (let attempt = 0; attempt < 20; attempt += 1) {
900 yield* Effect.yieldNow;
901 }
902 expect(yield* Ref.get(harness.subscriptionCount)).toBe(0);
903 expect(yield* Ref.get(harness.retryCount)).toBe(0);
904 expect(yield* Ref.get(harness.loaderCalls)).toBe(1);
905 expect((yield* Ref.get(harness.latest)).status).toBe("deleted");
906 }),
907 );
908
909 it.effect("falls back to the socket when the HTTP snapshot is only unavailable", () =>
910 Effect.gen(function* () {
911 const harness = yield* makeHarness({
912 httpSnapshot: { _tag: "unavailable" },
913 });
914
915 yield* Queue.offer(
916 harness.inputs,
917 snapshot({
918 ...BASE_PROJECTION,
919 thread: { ...BASE_PROJECTION.thread, title: "Socket title" },
920 }),
921 );
922
923 const state = yield* awaitThreadState(
924 harness.observed,
925 (value) =>
926 value.status === "live" &&
927 Option.isSome(value.data) &&
928 value.data.value.thread.title === "Socket title",
929 );
930
931 expect(Option.getOrThrow(state.data).thread.title).toBe("Socket title");
932 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
933 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
934 expect(yield* Ref.get(harness.removedThreads)).toEqual([]);
935 }),
936 );
937
938 it.effect("ignores replayed thread events at or below the snapshot sequence", () =>
939 Effect.gen(function* () {
940 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
941 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
942 yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1));
943 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
944
945 const state = yield* awaitThreadState(
946 harness.observed,
947 (value) =>
948 value.status === "live" &&
949 Option.isSome(value.data) &&
950 value.data.value.thread.title === "Live title",
951 );
952
953 expect(Option.getOrThrow(state.data).thread.title).toBe("Live title");
954 }),
955 );
956
957 it.effect("removes cached data when the thread is deleted", () =>
958 Effect.gen(function* () {
959 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
960 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
961 yield* Queue.offer(harness.inputs, deleted());
962
963 const state = yield* awaitThreadState(
964 harness.observed,
965 (value) => value.status === "deleted",
966 );
967
968 expect(Option.isNone(state.data)).toBe(true);
969 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
970 }),
971 );
972
973 it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
974 Effect.gen(function* () {
975 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
976 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
977 yield* Queue.offer(harness.inputs, new Error("stream failed"));
978
979 const state = yield* awaitThreadState(harness.observed, (value) =>
980 Option.isSome(value.error),
981 );
982
983 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
984 expect(Option.getOrThrow(state.error)).toBe("stream failed");
985 expect(yield* Ref.get(harness.retryCount)).toBe(0);
986
987 yield* harness.replaceSession;
988 for (let attempt = 0; attempt < 100; attempt += 1) {
989 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
990 break;
991 }
992 yield* Effect.yieldNow;
993 }
994 yield* Queue.offer(
995 harness.inputs,
996 snapshot({
997 ...BASE_PROJECTION,
998 thread: { ...BASE_PROJECTION.thread, title: "Recovered thread" },
999 }),
1000 );
1001 const recovered = yield* awaitThreadState(
1002 harness.observed,
1003 (value) =>
1004 value.status === "live" &&
1005 Option.isSome(value.data) &&
1006 value.data.value.thread.title === "Recovered thread",
1007 );
1008
1009 expect(Option.isNone(recovered.error)).toBe(true);
1010 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1011 }),
1012 );
1013
1014 it.effect("recovers from a transient domain failure without replacing the session", () =>
1015 Effect.gen(function* () {
1016 const harness = yield* makeHarness();
1017 yield* Queue.offer(harness.inputs, new Error("thread not found yet"));
1018
1019 const failed = yield* awaitThreadState(harness.observed, (value) =>
1020 Option.isSome(value.error),
1021 );
1022 expect(Option.getOrThrow(failed.error)).toBe("thread not found yet");
1023 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
1024
1025 yield* TestClock.adjust("250 millis");
1026 for (let attempt = 0; attempt < 100; attempt += 1) {
1027 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
1028 break;
1029 }
1030 yield* Effect.yieldNow;
1031 }
1032 yield* Queue.offer(
1033 harness.inputs,
1034 snapshot({
1035 ...BASE_PROJECTION,
1036 thread: { ...BASE_PROJECTION.thread, title: "Materialized thread" },
1037 }),
1038 );
1039
1040 const recovered = yield* awaitThreadState(
1041 harness.observed,
1042 (value) =>
1043 value.status === "live" &&
1044 Option.isSome(value.data) &&
1045 value.data.value.thread.title === "Materialized thread",
1046 );
1047
1048 expect(Option.isNone(recovered.error)).toBe(true);
1049 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1050 expect(yield* Ref.get(harness.retryCount)).toBe(0);
1051 }),
1052 );
1053
1054 it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () =>
1055 Effect.gen(function* () {
1056 const harness = yield* makeHarness({ cached: BASE_PROJECTION });
1057 yield* SubscriptionRef.set(harness.supervisorState, {
1058 desired: true,
1059 network: "online",
1060 phase: "connecting",
1061 stage: "synchronizing",
1062 attempt: 1,
1063 generation: 0,
1064 lastFailure: null,
1065 retryAt: null,
1066 });
1067 yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION));
1068 yield* awaitThreadState(harness.observed, (value) => value.status === "live");
1069
1070 yield* SubscriptionRef.set(harness.supervisorState, {
1071 desired: true,
1072 network: "online",
1073 phase: "connected",
1074 stage: null,
1075 attempt: 1,
1076 generation: 1,
1077 lastFailure: null,
1078 retryAt: null,
1079 });
1080 for (let index = 0; index < 10; index += 1) {
1081 yield* Effect.yieldNow;
1082 }
1083
1084 expect((yield* Ref.get(harness.latest)).status).toBe("live");
1085 }),
1086 );
1087
1088 it.effect("keeps replayed updates synchronizing until the completion marker arrives", () =>
1089 Effect.gen(function* () {
1090 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
1091 yield* awaitThreadState(
1092 harness.observed,
1093 (value) => value.status === "synchronizing" && Option.isSome(value.data),
1094 );
1095 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
1096
1097 yield* Queue.offer(
1098 harness.inputs,
1099 titleUpdated("Caught-up title", CACHED_SNAPSHOT_SEQUENCE + 1),
1100 );
1101 const catchingUp = yield* awaitThreadState(
1102 harness.observed,
1103 (value) =>
1104 value.status === "synchronizing" &&
1105 Option.isSome(value.data) &&
1106 value.data.value.thread.title === "Caught-up title",
1107 );
1108 expect(catchingUp.status).toBe("synchronizing");
1109
1110 yield* Queue.offer(harness.inputs, synchronized());
1111 const live = yield* awaitThreadState(
1112 harness.observed,
1113 (value) => value.status === "live" && Option.isSome(value.data),
1114 );
1115 expect(Option.getOrThrow(live.data).thread.title).toBe("Caught-up title");
1116 }),
1117 );
1118
1119 it.effect("resumes replacement sessions from the latest applied sequence", () =>
1120 Effect.gen(function* () {
1121 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
1122 yield* Queue.offer(
1123 harness.inputs,
1124 titleUpdated("Latest title", CACHED_SNAPSHOT_SEQUENCE + 1),
1125 );
1126 yield* Queue.offer(harness.inputs, synchronized());
1127 yield* awaitThreadState(
1128 harness.observed,
1129 (value) =>
1130 value.status === "live" &&
1131 Option.isSome(value.data) &&
1132 value.data.value.thread.title === "Latest title",
1133 );
1134
1135 yield* harness.replaceSession;
1136 for (let attempt = 0; attempt < 100; attempt += 1) {
1137 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
1138 yield* Effect.yieldNow;
1139 }
1140
1141 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1142 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
1143 expect((yield* Ref.get(harness.latest)).status).toBe("synchronizing");
1144 }),
1145 );
1146
1147 it.effect("resubscribes on app foreground from the latest applied sequence", () =>
1148 Effect.gen(function* () {
1149 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
1150 yield* Queue.offer(
1151 harness.inputs,
1152 titleUpdated("Latest title", CACHED_SNAPSHOT_SEQUENCE + 1),
1153 );
1154 yield* Queue.offer(harness.inputs, synchronized());
1155 yield* awaitThreadState(
1156 harness.observed,
1157 (value) =>
1158 value.status === "live" &&
1159 Option.isSome(value.data) &&
1160 value.data.value.thread.title === "Latest title",
1161 );
1162
1163 yield* Queue.offer(harness.wakeups, "application-active");
1164 const synchronizing = yield* awaitThreadState(
1165 harness.observed,
1166 (value) => value.status === "synchronizing" && Option.isSome(value.data),
1167 );
1168 for (let attempt = 0; attempt < 100; attempt += 1) {
1169 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
1170 yield* Effect.yieldNow;
1171 }
1172
1173 expect(synchronizing.status).toBe("synchronizing");
1174 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1175 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
1176 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
1177 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
1178
1179 yield* Queue.offer(harness.inputs, synchronized());
1180 const live = yield* awaitThreadState(
1181 harness.observed,
1182 (value) => value.status === "live" && Option.isSome(value.data),
1183 );
1184 expect(Option.getOrThrow(live.data).thread.title).toBe("Latest title");
1185
1186 yield* Queue.offer(harness.wakeups, "application-active-probe");
1187 for (let attempt = 0; attempt < 100; attempt += 1) {
1188 if ((yield* Ref.get(harness.subscriptionCount)) >= 3) break;
1189 yield* Effect.yieldNow;
1190 }
1191 expect(yield* Ref.get(harness.subscriptionCount)).toBe(3);
1192
1193 yield* Queue.offer(harness.wakeups, "application-active-reconnect");
1194 for (let attempt = 0; attempt < 10; attempt += 1) {
1195 yield* Effect.yieldNow;
1196 }
1197 expect(yield* Ref.get(harness.subscriptionCount)).toBe(3);
1198 }),
1199 );
1200});