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