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

threads-pagination.test.ts

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