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