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

threads-pagination.test.ts

543 lines21.4 KB

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