Open History to see the last commit
1import {
2 EnvironmentResourceNotFoundError,
3 EnvironmentId,
4 EventId,
5 ORCHESTRATION_WS_METHODS,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9 TurnId,
10 type OrchestrationMessage,
11 type OrchestrationThread,
12 type OrchestrationThreadDetailSnapshot,
13 type OrchestrationThreadStreamItem,
14} from "@t3tools/contracts";
15import { describe, expect, it } from "@effect/vitest";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Stream from "effect/Stream";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23
24import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
25import {
26 AVAILABLE_CONNECTION_STATE,
27 PrimaryConnectionTarget,
28 type PreparedConnection,
29 type SupervisorConnectionState,
30} from "../connection/model.ts";
31import * as EnvironmentSupervisor from "../connection/supervisor.ts";
32import * as Persistence from "../platform/persistence.ts";
33import * as RpcSession from "../rpc/session.ts";
34import type { ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
35import {
36 INITIAL_THREAD_USER_TURN_LIMIT,
37 makeEnvironmentThreadState,
38 requestOlderThreadTurns,
39 ThreadSnapshotLoader,
40 type EnvironmentThreadState,
41} from "./threads.ts";
42
43const TARGET = new PrimaryConnectionTarget({
44 environmentId: EnvironmentId.make("environment-1"),
45 label: "Test environment",
46 httpBaseUrl: "https://environment.example.test",
47 wsBaseUrl: "wss://environment.example.test",
48});
49const THREAD_ID = ThreadId.make("thread-1");
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};
58
59function message(id: string, turnId: string, createdAt: string): OrchestrationMessage {
60 return {
61 id: id as OrchestrationMessage["id"],
62 role: "assistant",
63 text: `text of ${id}`,
64 turnId: TurnId.make(turnId),
65 streaming: false,
66 createdAt,
67 updatedAt: createdAt,
68 };
69}
70
71const OLDER_MESSAGE = message("message-old", "turn-1", "2026-04-01T00:00:00.000Z");
72const RECENT_MESSAGE = message("message-recent", "turn-2", "2026-04-01T01:00:00.000Z");
73
74// Reverts retain turns via checkpoints with checkpointTurnCount <= the revert's
75// turnCount, so both fixture turns carry one: reverting to turnCount 1 keeps
76// turn-1 (the older page's turn) and discards turn-2 (the loaded window's).
77function checkpoint(turnId: string, turnCount: number): OrchestrationThread["checkpoints"][number] {
78 return {
79 turnId: TurnId.make(turnId),
80 checkpointTurnCount: turnCount,
81 checkpointRef:
82 `checkpoint-${turnCount}` as OrchestrationThread["checkpoints"][number]["checkpointRef"],
83 status: "ready",
84 files: [],
85 assistantMessageId: null,
86 completedAt: "2026-04-01T01:00:00.000Z",
87 };
88}
89
90const BASE_THREAD: OrchestrationThread = {
91 id: THREAD_ID,
92 projectId: ProjectId.make("project-1"),
93 title: "Windowed thread",
94 modelSelection: {
95 instanceId: ProviderInstanceId.make("codex"),
96 model: "gpt-5.4",
97 },
98 runtimeMode: "full-access",
99 interactionMode: "default",
100 branch: "main",
101 worktreePath: null,
102 latestTurn: null,
103 createdAt: "2026-04-01T00:00:00.000Z",
104 updatedAt: "2026-04-01T00:00:00.000Z",
105 archivedAt: null,
106 settledOverride: null,
107 settledAt: null,
108 pullRequests: [],
109 deletedAt: null,
110 messages: [RECENT_MESSAGE],
111 proposedPlans: [],
112 activities: [],
113 checkpoints: [checkpoint("turn-2", 2)],
114 session: null,
115};
116
117const WINDOWED_SNAPSHOT: OrchestrationThreadDetailSnapshot = {
118 snapshotSequence: 10,
119 thread: BASE_THREAD,
120 page: { beforeCursor: "cursor-1", hasMore: true, snapshotSequence: 10 },
121};
122
123const OLDER_PAGE: OrchestrationThreadDetailSnapshot = {
124 snapshotSequence: 10,
125 thread: {
126 ...BASE_THREAD,
127 messages: [OLDER_MESSAGE],
128 checkpoints: [checkpoint("turn-1", 1)],
129 },
130 page: { beforeCursor: null, hasMore: false, snapshotSequence: 10 },
131};
132
133type LoaderResponse = Option.Option<OrchestrationThreadDetailSnapshot>;
134
135const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (options?: {
136 readonly paginationCapability?: boolean;
137 readonly reasoningCapability?: boolean;
138 readonly initialResponse?: LoaderResponse;
139 readonly olderResponseError?: EnvironmentResourceNotFoundError;
140 /** Cached snapshot returned by the cache store (simulates a warm cache). */
141 readonly cached?: OrchestrationThreadDetailSnapshot;
142}) {
143 const inputs = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
144 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
145 const loaderWindows = yield* Ref.make<ReadonlyArray<ThreadSnapshotWindow | undefined>>([]);
146 const loaderReasoning = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
147 const lastSubscribeInput = yield* Ref.make<Record<string, unknown> | undefined>(undefined);
148 const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
149 const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
150 // Older-page responses resolve through deferreds so tests can interleave
151 // live events with an in-flight page fetch.
152 const pendingPageResponses = yield* Queue.unbounded<Deferred.Deferred<LoaderResponse>>();
153 const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
154 AVAILABLE_CONNECTION_STATE,
155 );
156 const client = {
157 [ORCHESTRATION_WS_METHODS.subscribeThread]: (input: Record<string, unknown>) =>
158 Stream.unwrap(Ref.set(lastSubscribeInput, input).pipe(Effect.as(Stream.fromQueue(inputs)))),
159 } as unknown as WsRpcProtocolClient;
160 const session: RpcSession.RpcSession = {
161 client,
162 initialConfig: Effect.succeed({
163 threadSnapshotPagination: options?.paginationCapability !== false,
164 reasoningMessages: options?.reasoningCapability === true,
165 } as never),
166 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
167 ready: Effect.void,
168 probe: Effect.void,
169 closed: Effect.never,
170 };
171 const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
172 Option.some(session),
173 );
174 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
175 Option.some(PREPARED),
176 );
177 const snapshotLoader = ThreadSnapshotLoader.of({
178 load: (_prepared, _threadId, window, reasoningMessages) =>
179 Ref.update(loaderWindows, (current) => [...current, window]).pipe(
180 Effect.andThen(Ref.update(loaderReasoning, (current) => [...current, reasoningMessages])),
181 Effect.andThen(
182 window?.beforeCursor === undefined
183 ? Effect.succeed(
184 options?.initialResponse ?? Option.none<OrchestrationThreadDetailSnapshot>(),
185 )
186 : options?.olderResponseError !== undefined
187 ? Effect.fail(options.olderResponseError)
188 : Deferred.make<LoaderResponse>().pipe(
189 Effect.tap((deferred) => Queue.offer(pendingPageResponses, deferred)),
190 Effect.flatMap(Deferred.await),
191 ),
192 ),
193 ),
194 });
195 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
196 target: TARGET,
197 state: supervisorState,
198 session: supervisorSession,
199 prepared,
200 connect: Effect.void,
201 disconnect: Effect.void,
202 retryNow: Effect.void,
203 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
204 const cache = Persistence.EnvironmentCacheStore.of({
205 loadShell: () => Effect.succeedNone,
206 saveShell: () => Effect.void,
207 loadThread: () =>
208 Effect.succeed(options?.cached !== undefined ? Option.some(options.cached) : Option.none()),
209 saveThread: (_environmentId, thread) =>
210 Ref.update(savedThreads, (current) => [...current, thread]),
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 const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
222 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
223 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
224 Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
225 );
226 yield* SubscriptionRef.changes(threadState).pipe(
227 Stream.runForEach((state) => Queue.offer(observed, state)),
228 Effect.forkScoped,
229 );
230
231 const awaitState = (predicate: (state: EnvironmentThreadState) => boolean) =>
232 Queue.take(observed).pipe(Effect.repeat({ until: predicate }));
233 const resolveNextPage = (response: LoaderResponse) =>
234 Queue.take(pendingPageResponses).pipe(
235 Effect.flatMap((deferred) => Deferred.succeed(deferred, response)),
236 );
237
238 return {
239 inputs,
240 observed,
241 awaitState,
242 resolveNextPage,
243 loaderWindows,
244 loaderReasoning,
245 lastSubscribeInput,
246 savedThreads,
247 removedThreads,
248 threadState,
249 };
250});
251
252const hasMessage = (state: EnvironmentThreadState, id: string): boolean =>
253 Option.match(state.data, {
254 onNone: () => false,
255 onSome: (thread) => thread.messages.some((entry) => entry.id === id),
256 });
257
258const titleEvent = (title: string, sequence: number): OrchestrationThreadStreamItem => ({
259 kind: "event",
260 event: {
261 eventId: EventId.make(`event-title-${sequence}`),
262 sequence,
263 occurredAt: "2026-04-01T01:30:00.000Z",
264 commandId: null,
265 causationEventId: null,
266 correlationId: null,
267 metadata: {},
268 aggregateKind: "thread",
269 aggregateId: THREAD_ID,
270 type: "thread.meta-updated",
271 payload: {
272 threadId: THREAD_ID,
273 title,
274 updatedAt: "2026-04-01T01:30:00.000Z",
275 },
276 },
277});
278
279// Reverting to turnCount 1 retains only turns whose checkpoint count is <= 1:
280// turn-1 survives, turn-2 (the loaded window's newest turn) is discarded.
281const revertEvent = (sequence: number): OrchestrationThreadStreamItem => ({
282 kind: "event",
283 event: {
284 eventId: EventId.make(`event-revert-${sequence}`),
285 sequence,
286 occurredAt: "2026-04-01T02:00:00.000Z",
287 commandId: null,
288 causationEventId: null,
289 correlationId: null,
290 metadata: {},
291 aggregateKind: "thread",
292 aggregateId: THREAD_ID,
293 type: "thread.reverted",
294 payload: {
295 threadId: THREAD_ID,
296 turnCount: 1,
297 },
298 },
299});
300
301describe("thread pagination state", () => {
302 for (const reasoningCapability of [false, true]) {
303 it.effect(
304 `negotiates reasoning for initial, older and socket reads: ${reasoningCapability}`,
305 () =>
306 Effect.gen(function* () {
307 const harness = yield* makeHarness({
308 reasoningCapability,
309 initialResponse: Option.some(WINDOWED_SNAPSHOT),
310 });
311 yield* harness.awaitState((value) => Option.isSome(value.page));
312 const input = yield* Ref.get(harness.lastSubscribeInput);
313 expect(input?.reasoningMessages).toBe(reasoningCapability ? true : undefined);
314 expect(yield* Ref.get(harness.loaderReasoning)).toEqual([reasoningCapability]);
315 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
316 yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
317 yield* harness.awaitState((value) =>
318 Option.match(value.page, { onNone: () => false, onSome: (page) => !page.hasMore }),
319 );
320 expect(yield* Ref.get(harness.loaderReasoning)).toEqual([
321 reasoningCapability,
322 reasoningCapability,
323 ]);
324 }),
325 );
326 }
327
328 it.effect("windows the initial load when the server advertises pagination", () =>
329 Effect.gen(function* () {
330 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
331 const state = yield* harness.awaitState((value) => Option.isSome(value.page));
332 expect(Option.getOrThrow(state.page)).toEqual({
333 beforeCursor: "cursor-1",
334 hasMore: true,
335 loadingOlder: false,
336 });
337 const windows = yield* Ref.get(harness.loaderWindows);
338 expect(windows[0]?.turnLimit).toBe(INITIAL_THREAD_USER_TURN_LIMIT);
339 const subscribeInput = yield* Ref.get(harness.lastSubscribeInput);
340 expect(subscribeInput?.turnLimit).toBe(INITIAL_THREAD_USER_TURN_LIMIT);
341 }),
342 );
343
344 it.effect("does not send a window to servers without the capability", () =>
345 Effect.gen(function* () {
346 const harness = yield* makeHarness({
347 paginationCapability: false,
348 initialResponse: Option.some({ snapshotSequence: 10, thread: BASE_THREAD }),
349 });
350 const state = yield* harness.awaitState((value) => Option.isSome(value.data));
351 expect(Option.isNone(state.page)).toBe(true);
352 const windows = yield* Ref.get(harness.loaderWindows);
353 expect(windows[0]).toBeUndefined();
354 const subscribeInput = yield* Ref.get(harness.lastSubscribeInput);
355 expect(subscribeInput?.turnLimit).toBeUndefined();
356 }),
357 );
358
359 it.effect("merges an older page below the loaded window and clears the cursor", () =>
360 Effect.gen(function* () {
361 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
362 yield* harness.awaitState((value) => Option.isSome(value.page));
363
364 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
365 yield* harness.awaitState((value) =>
366 Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
367 );
368 yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
369
370 const state = yield* harness.awaitState((value) => hasMessage(value, "message-old"));
371 const thread = Option.getOrThrow(state.data);
372 // Older rows land before the loaded window's rows.
373 expect(thread.messages.map((entry) => entry.id)).toEqual(["message-old", "message-recent"]);
374 expect(Option.getOrThrow(state.page)).toEqual({
375 beforeCursor: null,
376 hasMore: false,
377 loadingOlder: false,
378 });
379 }),
380 );
381
382 it.effect(
383 "keeps an authoritative missing-thread response terminal while loading older turns",
384 () =>
385 Effect.gen(function* () {
386 const harness = yield* makeHarness({
387 initialResponse: Option.some(WINDOWED_SNAPSHOT),
388 olderResponseError: new EnvironmentResourceNotFoundError({
389 code: "not_found",
390 reason: "thread_not_found",
391 traceId: "trace-older-thread-not-found",
392 }),
393 });
394 yield* harness.awaitState((value) => Option.isSome(value.page));
395
396 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
397 const state = yield* harness.awaitState((value) => value.status === "deleted");
398
399 expect(Option.isNone(state.data)).toBe(true);
400 expect(Option.isNone(state.page)).toBe(true);
401 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
402 }),
403 );
404
405 it.effect("discards an in-flight older page when a revert rewrites history", () =>
406 Effect.gen(function* () {
407 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
408 yield* harness.awaitState((value) => Option.isSome(value.page));
409
410 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
411 yield* harness.awaitState((value) =>
412 Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
413 );
414 // Revert lands while the page fetch is in flight and removes turn-2.
415 yield* Queue.offer(harness.inputs, revertEvent(11));
416 yield* harness.awaitState((value) => !hasMessage(value, "message-recent"));
417 yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
418
419 const state = yield* harness.awaitState((value) =>
420 Option.match(value.page, { onNone: () => false, onSome: (page) => !page.loadingOlder }),
421 );
422 // The stale page was dropped: no resurrected rows, cursor unchanged.
423 expect(hasMessage(state, "message-old")).toBe(false);
424 expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
425 }),
426 );
427
428 it.effect("discards an in-flight older page when a fresh snapshot replaces the thread", () =>
429 Effect.gen(function* () {
430 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
431 yield* harness.awaitState((value) => Option.isSome(value.page));
432
433 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
434 yield* harness.awaitState((value) =>
435 Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
436 );
437 yield* Queue.offer(harness.inputs, {
438 kind: "snapshot",
439 snapshot: {
440 snapshotSequence: 20,
441 thread: { ...BASE_THREAD, title: "Replaced thread" },
442 page: { beforeCursor: "cursor-2", hasMore: true, snapshotSequence: 20 },
443 },
444 });
445 yield* harness.awaitState((value) =>
446 Option.match(value.data, {
447 onNone: () => false,
448 onSome: (thread) => thread.title === "Replaced thread",
449 }),
450 );
451 yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
452
453 const state = yield* harness.awaitState((value) =>
454 Option.match(value.page, { onNone: () => false, onSome: (page) => !page.loadingOlder }),
455 );
456 expect(hasMessage(state, "message-old")).toBe(false);
457 // The replacement snapshot's cursor wins over the discarded page's.
458 expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-2");
459 }),
460 );
461
462 it.effect("keeps a new page loading when a snapshot replaced a parked older page", () =>
463 Effect.gen(function* () {
464 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
465 yield* harness.awaitState((value) => Option.isSome(value.page));
466 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
467 yield* harness.resolveNextPage(
468 Option.some({
469 ...OLDER_PAGE,
470 snapshotSequence: 30,
471 page: { beforeCursor: null, hasMore: false, snapshotSequence: 30, threadSequence: 30 },
472 }),
473 );
474 yield* Queue.offer(harness.inputs, titleEvent("Waiting for old watermark", 11));
475 yield* harness.awaitState((value) =>
476 Option.exists(value.data, (thread) => thread.title === "Waiting for old watermark"),
477 );
478 expect(
479 Option.getOrThrow((yield* SubscriptionRef.get(harness.threadState)).page).loadingOlder,
480 ).toBe(true);
481
482 yield* Queue.offer(harness.inputs, {
483 kind: "snapshot",
484 snapshot: {
485 snapshotSequence: 20,
486 thread: { ...BASE_THREAD, title: "Replacement snapshot" },
487 page: { beforeCursor: "cursor-2", hasMore: true, snapshotSequence: 20 },
488 },
489 });
490 yield* harness.awaitState((value) =>
491 Option.exists(value.data, (thread) => thread.title === "Replacement snapshot"),
492 );
493 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
494 yield* harness.awaitState((value) =>
495 Option.exists(value.page, (page) => page.loadingOlder && page.beforeCursor === "cursor-2"),
496 );
497 yield* Queue.offer(harness.inputs, titleEvent("New request still loading", 21));
498 yield* harness.awaitState((value) =>
499 Option.exists(value.data, (thread) => thread.title === "New request still loading"),
500 );
501 const loading = yield* SubscriptionRef.get(harness.threadState);
502 expect(Option.getOrThrow(loading.page).loadingOlder).toBe(true);
503 expect(hasMessage(loading, "message-old")).toBe(false);
504 expect((yield* Ref.get(harness.loaderWindows)).map((window) => window?.beforeCursor)).toEqual(
505 [undefined, "cursor-1", "cursor-2"],
506 );
507
508 yield* harness.resolveNextPage(
509 Option.some({
510 ...OLDER_PAGE,
511 snapshotSequence: 21,
512 page: { beforeCursor: null, hasMore: false, snapshotSequence: 21, threadSequence: 21 },
513 }),
514 );
515 const completed = yield* harness.awaitState((value) => hasMessage(value, "message-old"));
516 expect(Option.getOrThrow(completed.page).loadingOlder).toBe(false);
517 expect(Option.getOrThrow(completed.page).beforeCursor).toBeNull();
518 }),
519 );
520
521 it.effect("discards an older page read from a projection behind the loaded state", () =>
522 Effect.gen(function* () {
523 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
524 yield* harness.awaitState((value) => Option.isSome(value.page));
525
526 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
527 yield* harness.awaitState((value) =>
528 Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
529 );
530 yield* harness.resolveNextPage(Option.some({ ...OLDER_PAGE, snapshotSequence: 5 }));
531
532 const state = yield* harness.awaitState((value) =>
533 Option.match(value.page, { onNone: () => false, onSome: (page) => !page.loadingOlder }),
534 );
535 expect(hasMessage(state, "message-old")).toBe(false);
536 expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
537 }),
538 );
539
540 it.effect("a merged history page never advances the live-event dedupe sequence", () =>
541 Effect.gen(function* () {
542 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
543 yield* harness.awaitState((value) => Option.isSome(value.page));
544
545 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
546 yield* harness.awaitState((value) =>
547 Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
548 );
549 // The page was captured at a newer projection sequence (12) than the
550 // loaded state (10); merging it must not swallow events 11-12.
551 yield* harness.resolveNextPage(
552 Option.some({
553 ...OLDER_PAGE,
554 snapshotSequence: 12,
555 page: { beforeCursor: null, hasMore: false, snapshotSequence: 12 },
556 }),
557 );
558 yield* harness.awaitState((value) => hasMessage(value, "message-old"));
559
560 // Event at sequence 11 must still apply after the merge: the revert
561 // discards turn-2, so the loaded window's row disappears while the
562 // merged older turn-1 row survives. If the merge had advanced the
563 // dedupe sequence to the page's 12, this event would be swallowed.
564 yield* Queue.offer(harness.inputs, revertEvent(11));
565 const state = yield* harness.awaitState(
566 (value) => !hasMessage(value, "message-recent") && hasMessage(value, "message-old"),
567 );
568 expect(hasMessage(state, "message-old")).toBe(true);
569 }),
570 );
571
572 it.effect("parks a page read ahead of the live state until events catch up", () =>
573 Effect.gen(function* () {
574 // A page whose thread watermark is ahead of the loaded state may
575 // contain streaming content the subscription has not delivered yet
576 // (e.g. an out-of-window subagent turn mid-stream); merging it
577 // immediately and then replaying those deltas would duplicate text.
578 // The page parks until the live state reaches the watermark.
579 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
580 yield* harness.awaitState((value) => Option.isSome(value.page));
581
582 requestOlderThreadTurns(TARGET.environmentId, THREAD_ID);
583 yield* harness.awaitState((value) =>
584 Option.match(value.page, { onNone: () => false, onSome: (page) => page.loadingOlder }),
585 );
586 // Page watermark 11 > loaded sequence 10: must park, not merge.
587 yield* harness.resolveNextPage(
588 Option.some({
589 ...OLDER_PAGE,
590 snapshotSequence: 11,
591 page: { beforeCursor: null, hasMore: false, snapshotSequence: 11, threadSequence: 11 },
592 }),
593 );
594
595 // A live event at sequence 11 arrives; only then does the page merge.
596 yield* Queue.offerAll(harness.inputs, [
597 titleEvent("Advanced past watermark", 11),
598 {
599 kind: "event",
600 event: {
601 eventId: EventId.make("event-after-page"),
602 sequence: 12,
603 aggregateKind: "thread",
604 aggregateId: THREAD_ID,
605 occurredAt: BASE_THREAD.createdAt,
606 commandId: null,
607 causationEventId: null,
608 correlationId: null,
609 metadata: {},
610 type: "thread.message-sent",
611 payload: {
612 ...OLDER_MESSAGE,
613 threadId: THREAD_ID,
614 messageId: OLDER_MESSAGE.id,
615 text: " continued",
616 streaming: true,
617 },
618 },
619 },
620 ]);
621 const state = yield* harness.awaitState(
622 (value) => Option.getOrNull(value.data)?.messages[0]?.text.endsWith(" continued") === true,
623 );
624 expect(Option.getOrThrow(state.data).messages[0]?.text).toBe(
625 `${OLDER_MESSAGE.text} continued`,
626 );
627 expect(hasMessage(state, "message-recent")).toBe(true);
628 expect(Option.getOrThrow(state.page).loadingOlder).toBe(false);
629 }),
630 );
631
632 it.effect("a revert keeps the page cursor and triggers no refresh fetch", () =>
633 Effect.gen(function* () {
634 // Cursors are an (anchor, turnId) keyset derived from event content, so
635 // they survive the revert projector's row rewrite: the machine keeps
636 // the stored cursor and performs no snapshot re-fetch. The revert
637 // reducer's turn filtering alone handles loaded history.
638 const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
639 yield* harness.awaitState((value) => Option.isSome(value.page));
640
641 yield* Queue.offer(harness.inputs, revertEvent(11));
642 const state = yield* harness.awaitState((value) => !hasMessage(value, "message-recent"));
643
644 expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
645 const windows = yield* Ref.get(harness.loaderWindows);
646 // Only the initial load hit the loader — no post-revert refresh fetch.
647 expect(windows.length).toBe(1);
648 }),
649 );
650
651 it.effect("drops a windowed cache when the server lacks the pagination capability", () =>
652 Effect.gen(function* () {
653 // Resuming a windowed cache via afterSequence against a pre-pagination
654 // server would render only the window forever with no way to load the
655 // rest: the machine must discard the cache and take a full snapshot.
656 const fullSnapshot: OrchestrationThreadDetailSnapshot = {
657 snapshotSequence: 20,
658 thread: { ...BASE_THREAD, title: "Full reload" },
659 };
660 const harness = yield* makeHarness({
661 paginationCapability: false,
662 cached: WINDOWED_SNAPSHOT,
663 initialResponse: Option.some(fullSnapshot),
664 });
665
666 const state = yield* harness.awaitState((value) =>
667 Option.match(value.data, {
668 onNone: () => false,
669 onSome: (thread) => thread.title === "Full reload",
670 }),
671 );
672 expect(Option.isNone(state.page)).toBe(true);
673 // The subscription resumed from the fresh full snapshot, not the
674 // discarded windowed cache's watermark, and sent no window fields.
675 const subscribeInput = yield* Ref.get(harness.lastSubscribeInput);
676 expect(subscribeInput?.turnLimit).toBeUndefined();
677 expect(subscribeInput?.afterSequence).toBe(20);
678 }),
679 );
680
681 it.effect("keeps a windowed cache when the server supports pagination", () =>
682 Effect.gen(function* () {
683 const harness = yield* makeHarness({ cached: WINDOWED_SNAPSHOT });
684 const state = yield* harness.awaitState((value) => Option.isSome(value.page));
685 expect(Option.getOrThrow(state.page).beforeCursor).toBe("cursor-1");
686 // Wait for the subscription (recorded when the WS method is invoked)
687 // before asserting its input.
688 const subscribeInput = yield* Ref.get(harness.lastSubscribeInput).pipe(
689 Effect.repeat({ until: (input) => input !== undefined }),
690 );
691 expect(subscribeInput?.afterSequence).toBe(10);
692 }),
693 );
694});