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

threadHistoryPaging.test.ts

1,074 lines36.4 KB

1import {
2 MessageId,
3 NodeId,
4 RunId,
5 RuntimeRequestId,
6 ThreadId,
7 TurnItemId,
8 type OrchestrationV2ProjectedTurnItem,
9 type OrchestrationV2TurnItem,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as DateTime from "effect/DateTime";
13​
14import {
15 buildBoundedThreadProjection,
16 deferWorkHistoryRows,
17 boundedTimelineEncodedBytes,
18 computeLatestLocalTurnOrdinal,
19 decodeThreadHistoryCursor,
20 encodeThreadHistoryCursor,
21 projectedRowBoundedSnapshotEncodedBytes,
22 projectedRowEncodedBytes,
23 selectHistoryPageFromCursor,
24 selectDeferredWorkPage,
25 selectRecentTimelineWindow,
26 THREAD_HISTORY_PAGE_POLICY,
27} from "./threadHistoryPaging.ts";
28import { projectThreadProjectionForWire } from "./WireProjection.ts";
29​
30const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
31const THREAD = ThreadId.make("thread-1");
32const RUN = RunId.make("run-interrupt-1");
33const NODE = NodeId.make("node-interrupt-1");
34​
35function makeRow(
36 index: number,
37 options?: { readonly outputBytes?: number },
38): OrchestrationV2ProjectedTurnItem {
39 const id = TurnItemId.make(`item-${index}`);
40 const output =
41 options?.outputBytes !== undefined ? "x".repeat(options.outputBytes) : `output-${index}`;
42 return {
43 position: index,
44 visibility: "local",
45 sourceThreadId: THREAD,
46 sourceItemId: id,
47 item: {
48 id,
49 type: "command_execution",
50 threadId: THREAD,
51 runId: null,
52 nodeId: null,
53 providerThreadId: null,
54 providerTurnId: null,
55 nativeItemRef: null,
56 parentItemId: null,
57 ordinal: index + 1,
58 status: "completed",
59 title: `Command ${index}`,
60 input: `cmd-${index}`,
61 output,
62 exitCode: 0,
63 startedAt: NOW,
64 completedAt: NOW,
65 updatedAt: NOW,
66 },
67 };
69​
70it("reads before a rolled-back history anchor even after new rows occupy its old position", () => {
71 const beforeRollback = Array.from({ length: 974 }, (_, index) => makeRow(index));
72 const initial = selectRecentTimelineWindow({ items: beforeRollback, snapshotSequence: 1 });
73 expect(initial.items[0]?.item.ordinal).toBe(900);
74 const afterRollback = [
75 ...beforeRollback.slice(0, 299),
76 ...Array.from({ length: 900 }, (_, index) => makeRow(1200 + index)),
77 ].map((row, position) => ({ ...row, position }));
78​
79 const older = selectHistoryPageFromCursor({
80 items: afterRollback,
81 cursor: initial.nextCursor!,
82 snapshotSequence: 2,
83 });
84 expect(older.items.map((row) => row.item.ordinal)).toEqual(
85 Array.from({ length: 75 }, (_, index) => 225 + index),
86 );
87});
88​
89function makeTurnStart(
90 index: number,
91 createdBy: "user" | "agent",
92): OrchestrationV2ProjectedTurnItem {
93 const row = makeRow(index);
94 return {
95 ...row,
96 item: {
97 ...row.item,
98 type: "user_message",
99 createdBy,
100 creationSource: "provider",
101 inputIntent: "turn_start",
102 messageId: MessageId.make(`prompt-${index}`),
103 text: `Prompt ${index}`,
104 attachments: [],
105 },
106 } as OrchestrationV2ProjectedTurnItem;
108​
109function interruptItem(
110 id: string,
111 type: "run_interrupt_request" | "run_interrupt_result",
112 ordinal: number,
113): OrchestrationV2TurnItem {
114 return {
115 id: TurnItemId.make(id),
116 type,
117 threadId: THREAD,
118 runId: RUN,
119 nodeId: NODE,
120 providerThreadId: null,
121 providerTurnId: null,
122 nativeItemRef: null,
123 parentItemId: null,
124 ordinal,
125 status: "completed",
126 title: type,
127 message: type === "run_interrupt_request" ? "Stopping" : "Stopped",
128 startedAt: NOW,
129 completedAt: NOW,
130 updatedAt: NOW,
131 } as OrchestrationV2TurnItem;
133​
134function interruptRow(
135 index: number,
136 type: "run_interrupt_request" | "run_interrupt_result",
137): OrchestrationV2ProjectedTurnItem {
138 const item = interruptItem(
139 type === "run_interrupt_request" ? "interrupt-req" : "interrupt-res",
140 type,
141 index + 1,
142 );
143 return {
144 position: index,
145 visibility: "local",
146 sourceThreadId: THREAD,
147 sourceItemId: item.id,
148 item,
149 };
151​
152function makeProjection(visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) {
153 return {
154 thread: {
155 id: THREAD,
156 projectId: "project-1",
157 title: "Thread",
158 providerInstanceId: "codex",
159 modelSelection: { instanceId: "codex", model: "gpt-5" },
160 runtimeMode: "full-access",
161 interactionMode: "default",
162 branch: null,
163 worktreePath: null,
164 activeProviderThreadId: null,
165 lineage: {
166 parentThreadId: null,
167 relationshipToParent: null,
168 rootThreadId: THREAD,
169 },
170 forkedFrom: null,
171 createdBy: "user",
172 creationSource: "web",
173 createdAt: NOW,
174 updatedAt: NOW,
175 archivedAt: null,
176 deletedAt: null,
177 settledOverride: null,
178 settledAt: null,
179 },
180 runs: [{ id: "run-1" }],
181 attempts: [{ id: "attempt-1" }],
182 nodes: [],
183 subagents: [],
184 providerSessions: [],
185 providerThreads: [],
186 providerTurns: [],
187 runtimeRequests: [{ id: "req-1" }],
188 messages: [],
189 plans: [],
190 turnItems: visibleTurnItems.map((row) => row.item),
191 checkpointScopes: [],
192 checkpoints: [],
193 contextHandoffs: [],
194 contextTransfers: [],
195 visibleTurnItems,
196 updatedAt: NOW,
197 } as unknown as Parameters<typeof buildBoundedThreadProjection>[0]["projection"];
199​
200describe("threadHistoryPaging", () => {
201 it("defers completed work above 150 items and keeps conversation and persistent rows", () => {
202 const work = Array.from({ length: 151 }, (_, index) => {
203 const row = makeRow(index);
204 return { ...row, item: { ...row.item, runId: RUN, runStatus: "completed" } };
205 });
206 expect(deferWorkHistoryRows(work.slice(0, 150))).toHaveLength(150);
207 // A jump to an entry folds the smaller groups on its way too.
208 const folded = deferWorkHistoryRows(work.slice(0, 2), 1);
209 expect(folded.map((row) => row.item.deferredWork?.itemCount)).toEqual([2]);
210 const target = work[1]!;
211 expect(deferWorkHistoryRows(work.slice(0, 2), 1, target.sourceItemId)).toEqual([
212 ...folded,
213 target,
214 ]);
215 expect(deferWorkHistoryRows(work.slice(0, 1), 1)[0]!.item.deferredWork).toBeUndefined();
216 const deferredWork = deferWorkHistoryRows(work)[0]!.item.deferredWork!;
217 expect(deferredWork.itemCount).toBe(151);
218 expect(decodeThreadHistoryCursor(deferredWork.cursor).p).toBe(151);
219 const superseded = work.map((row) => ({
220 ...row,
221 item: { ...row.item, runStatus: "running", attemptId: "old", attemptStatus: "superseded" },
222 }));
223 const active = work.map((row, index) => ({
224 ...row,
225 sourceItemId: TurnItemId.make(`active-${index}`),
226 position: row.position + work.length,
227 item: { ...row.item, runStatus: "running", attemptId: "active", attemptStatus: "running" },
228 }));
229 const attempts = deferWorkHistoryRows([...superseded, ...active]);
230 expect(attempts[0]?.item.deferredWork?.itemCount).toBe(151);
231 expect(attempts.slice(1)).toEqual(active);
232 const compaction = {
233 ...work[0]!,
234 sourceItemId: TurnItemId.make("compaction"),
235 item: {
236 ...work[0]!.item,
237 type: "compaction" as const,
238 },
239 };
240 const persistent = {
241 ...work[0]!,
242 sourceItemId: TurnItemId.make("render"),
243 item: {
244 ...work[0]!.item,
245 type: "dynamic_tool" as const,
246 persistentOutput: true,
247 },
248 };
249 const deferred = deferWorkHistoryRows([
250 ...work.slice(0, 30),
251 compaction,
252 persistent,
253 ...work.slice(30),
254 ]);
255 expect(deferred.map((row) => row.sourceItemId)).toEqual(["item-0", "compaction", "render"]);
256 expect(deferred[0]?.item.deferredWork?.itemCount).toBe(151);
257 for (const runStatus of ["running", "failed", "interrupted", "cancelled"]) {
258 expect(
259 deferWorkHistoryRows(work.map((row) => ({ ...row, item: { ...row.item, runStatus } }))),
260 ).toHaveLength(151);
261 }
262 const interrupted = {
263 ...compaction,
264 item: { ...compaction.item, type: "run_interrupt_result" as const },
265 };
266 expect(deferWorkHistoryRows([...work, interrupted])).toHaveLength(152);
267 const failed = {
268 ...compaction,
269 item: {
270 ...compaction.item,
271 type: "error" as const,
272 status: "failed" as const,
273 nodeId: "root-node",
274 parentItemId: null,
275 },
276 };
277 expect(deferWorkHistoryRows([...work, failed])).toHaveLength(152);
278 });
279​
280 it("keeps a human turn whole up to the turn row budget and pages a longer one from inside", () => {
281 const humanTurn = (length: number) => {
282 const items = Array.from({ length }, (_, index) => makeRow(index));
283 items[0] = {
284 ...items[0]!,
285 item: {
286 ...items[0]!.item,
287 type: "user_message",
288 createdBy: "user",
289 creationSource: "web",
290 inputIntent: "turn_start",
291 messageId: MessageId.make("long-human-turn"),
292 text: "Continue",
293 attachments: [],
294 },
295 } as OrchestrationV2ProjectedTurnItem;
296 return items;
297 };
298​
299 const whole = selectRecentTimelineWindow({ items: humanTurn(180), snapshotSequence: 1 });
300 expect(whole.items).toHaveLength(180);
301 expect(whole.hasMoreHistory).toBe(false);
302​
303 const items = humanTurn(THREAD_HISTORY_PAGE_POLICY.maxTurnItems + 100);
304 const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
305 expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
306 const loaded = [...recent.items];
307 let cursor = recent.nextCursor;
308 for (let pages = 0; cursor !== null; pages += 1) {
309 expect(pages).toBeLessThan(items.length);
310 const page = selectHistoryPageFromCursor({ items, cursor, snapshotSequence: 1 });
311 expect(page.items.length).toBeGreaterThan(0);
312 expect(page.items.length).toBeLessThanOrEqual(
313 page.items[0]?.item.type === "user_message"
314 ? THREAD_HISTORY_PAGE_POLICY.maxTurnItems
315 : THREAD_HISTORY_PAGE_POLICY.maxItems,
316 );
317 loaded.unshift(...page.items);
318 cursor = page.nextCursor;
319 }
320 expect(loaded.map((row) => row.sourceItemId)).toEqual(items.map((row) => row.sourceItemId));
321​
322 const large = items
323 .slice(0, 12)
324 .map((row) =>
325 row.item.type === "command_execution"
326 ? { ...row, item: { ...row.item, output: "x".repeat(200_000) } }
327 : row,
328 );
329 const bounded = buildBoundedThreadProjection({
330 projection: makeProjection(large),
331 snapshotSequence: 1,
332 });
333 expect(bounded.projection.visibleTurnItems.length).toBeLessThan(large.length);
334 expect(boundedTimelineEncodedBytes(bounded.projection)).toBeLessThanOrEqual(
335 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes,
336 );
337 });
338​
339 it("keeps background turns with user turns, with main's 150-turn fan-out ceiling", () => {
340 const items = Array.from({ length: 161 }, (_, turn) => {
341 const row = makeRow(turn * 2);
342 if (row.item.type !== "command_execution") throw new Error("Expected command fixture");
343 const prompt: OrchestrationV2ProjectedTurnItem = {
344 ...row,
345 item: {
346 ...row.item,
347 type: "user_message",
348 createdBy: turn === 0 ? "user" : "agent",
349 creationSource: "provider",
350 inputIntent: "turn_start",
351 messageId: MessageId.make(`prompt-${turn}`),
352 text: `Prompt ${turn}`,
353 attachments: [],
354 },
355 };
356 return [prompt, makeRow(turn * 2 + 1)];
357 }).flat();
358 const policy = { ...THREAD_HISTORY_PAGE_POLICY, maxItems: 1_000, maxEncodedBytes: 10_000_000 };
359 const first = selectRecentTimelineWindow({ items, snapshotSequence: 1, policy });
360 expect(first.items).toHaveLength(300);
361 expect(first.items[0]?.sourceItemId).toBe("item-22");
362 const older = selectHistoryPageFromCursor({
363 items,
364 cursor: first.nextCursor!,
365 snapshotSequence: 1,
366 policy,
367 });
368 expect(older.items).toHaveLength(22);
369 expect(older.hasMoreHistory).toBe(false);
370 expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual(
371 items.map((row) => row.sourceItemId),
372 );
373 });
374​
375 it("counts runs that a notification started toward the 150-turn ceiling", () => {
376 const inRun = (index: number, run: number, item: object = {}) => {
377 const row = makeRow(index);
378 return {
379 ...row,
380 item: { ...row.item, runId: RunId.make(`run-${run}`), ...item },
381 } as OrchestrationV2ProjectedTurnItem;
382 };
383 const notification = (summary: string) => ({
384 type: "notification",
385 source: { kind: "monitor" },
386 outcome: "completed",
387 summary,
388 });
389 const items = Array.from({ length: 161 }, (_, run) => [
390 inRun(run * 4, run),
391 inRun(
392 run * 4 + 1,
393 run,
394 run === 0
395 ? {
396 type: "user_message",
397 createdBy: "user",
398 creationSource: "web",
399 inputIntent: "turn_start",
400 messageId: MessageId.make("prompt-0"),
401 text: "Prompt 0",
402 attachments: [],
403 }
404 : notification(`Wake ${run}`),
405 ),
406 inRun(run * 4 + 2, run, notification(`Steer ${run}`)),
407 inRun(run * 4 + 3, run),
408 ]).flat();
409 const policy = {
410 ...THREAD_HISTORY_PAGE_POLICY,
411 maxItems: 1_000,
412 maxTurnItems: 1_000,
413 maxEncodedBytes: 10_000_000,
414 };
415 const first = selectRecentTimelineWindow({ items, snapshotSequence: 1, policy });
416 expect(first.items).toHaveLength(150 * 4 - 1);
417 expect(first.items[0]?.sourceItemId).toBe(`item-${11 * 4 + 1}`);
418 const older = selectHistoryPageFromCursor({
419 items,
420 cursor: first.nextCursor!,
421 snapshotSequence: 1,
422 policy,
423 });
424 expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual(
425 items.map((row) => row.sourceItemId),
426 );
427​
428 // A caller that holds only the newest rows gets the same page when it says what it left
429 // out: a user turn, and run 3, whose late notification is then not a new turn.
430 const late = items.with(402, inRun(402, 3, notification("Late")));
431 const cursor = encodeThreadHistoryCursor({
432 snapshotSequence: 1,
433 sourceThreadId: THREAD,
434 sourceItemId: late.at(-1)!.sourceItemId,
435 position: late.length - 1,
436 });
437 const prefix = { hasUserTurn: true, startedRuns: new Set(["run-3"]) };
438 const whole = selectHistoryPageFromCursor({ items: late, cursor, snapshotSequence: 1, policy });
439 expect(whole.items[0]?.sourceItemId).toBe(`item-${11 * 4 + 1}`);
440 expect(
441 selectHistoryPageFromCursor({
442 items: late.slice(22),
443 cursor,
444 snapshotSequence: 1,
445 policy,
446 prefix,
447 }),
448 ).toEqual({ ...whole, oldestScanned: late[45] });
449 // A part that ends above the page reports its first row, so the caller reads further back.
450 expect(
451 selectHistoryPageFromCursor({
452 items: late.slice(60),
453 cursor,
454 snapshotSequence: 1,
455 policy,
456 prefix,
457 }).oldestScanned,
458 ).toBe(late[60]);
459 });
460​
461 it("pages agent-only child transcripts instead of dropping their earlier activity", () => {
462 const commandRows = Array.from({ length: 90 }, (_, index) => makeRow(index + 1));
463 const first = makeRow(0);
464 const prompt = {
465 ...first,
466 item: {
467 ...first.item,
468 type: "user_message" as const,
469 createdBy: "agent" as const,
470 creationSource: "provider" as const,
471 inputIntent: "turn_start" as const,
472 messageId: MessageId.make("child-prompt"),
473 text: "Inspect this project",
474 attachments: [],
475 },
476 } as OrchestrationV2ProjectedTurnItem;
477 const items = [prompt, ...commandRows];
478 const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
479​
480 expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
481 expect(recent.hasMoreHistory).toBe(true);
482 const older = selectHistoryPageFromCursor({
483 items,
484 cursor: recent.nextCursor!,
485 snapshotSequence: 1,
486 });
487 expect(older.items[0]?.item.type).toBe("user_message");
488 expect([...older.items, ...recent.items]).toHaveLength(items.length);
489 });
490​
491 it("always includes at least one pathological oversized item", () => {
492 for (const humanTurn of [false, true]) {
493 const oversized = makeRow(0, { outputBytes: 2_000_000 });
494 const items = [
495 humanTurn
496 ? ({
497 ...oversized,
498 item: {
499 ...oversized.item,
500 type: "user_message",
501 createdBy: "user",
502 creationSource: "web",
503 inputIntent: "turn_start",
504 messageId: MessageId.make("oversized-human-turn"),
505 text: "x".repeat(2_000_000),
506 attachments: [],
507 },
508 } as OrchestrationV2ProjectedTurnItem)
509 : oversized,
510 makeRow(1, { outputBytes: 10 }),
511 ];
512 const policy = { ...THREAD_HISTORY_PAGE_POLICY, maxItems: 50, maxEncodedBytes: 1_024 };
513 const page = selectRecentTimelineWindow({ items, snapshotSequence: 1, policy });
514 expect(page.items).toHaveLength(1);
515 expect(page.items[0]?.sourceItemId).toBe("item-1");
516 expect(page.hasMoreHistory).toBe(true);
517​
518 const older = selectHistoryPageFromCursor({
519 items,
520 cursor: page.nextCursor!,
521 snapshotSequence: 1,
522 policy,
523 });
524 expect(older.items).toHaveLength(1);
525 expect(older.items[0]?.sourceItemId).toBe("item-0");
526 expect(older.hasMoreHistory).toBe(false);
527 expect(older.nextCursor).toBeNull();
528 expect([...older.items, ...page.items].map((row) => row.sourceItemId)).toEqual(
529 items.map((row) => row.sourceItemId),
530 );
531 }
532 });
533​
534 it.each([
535 {
536 name: "item ceiling",
537 items: Array.from({ length: 5 }, (_, index) => makeRow(index)),
538 policy: { maxItems: 3, maxEncodedBytes: 1_000 },
539 admitted: 3,
540 measured: 3,
541 },
542 {
543 name: "user turn ceiling",
544 items: [makeRow(0), makeTurnStart(1, "user"), makeRow(2)],
545 policy: { maxUserTurns: 1, maxItems: 100, maxEncodedBytes: 1_000 },
546 admitted: 2,
547 measured: 2,
548 },
549 {
550 name: "raw turn ceiling",
551 items: [
552 makeTurnStart(0, "user"),
553 ...Array.from({ length: 151 }, (_, index) => makeTurnStart(index + 1, "agent")),
554 ],
555 policy: { maxUserTurns: 10, maxItems: 1_000, maxEncodedBytes: 1_000_000 },
556 admitted: 150,
557 measured: 150,
558 },
559 {
560 name: "byte budget, which still admits an exact fit",
561 items: Array.from({ length: 5 }, (_, index) => makeRow(index)),
562 policy: { maxItems: 100, maxEncodedBytes: 20 },
563 admitted: 2,
564 measured: 3,
565 },
566 {
567 name: "byte budget, which still admits an oversized first row",
568 items: Array.from({ length: 5 }, (_, index) => makeRow(index)),
569 policy: { maxItems: 100, maxEncodedBytes: 5 },
570 admitted: 1,
571 measured: 2,
572 },
573 ])("measures only the rows needed to stop at the $name", (testCase) => {
574 const measured: OrchestrationV2ProjectedTurnItem[] = [];
575 const page = selectRecentTimelineWindow({
576 items: testCase.items,
577 snapshotSequence: 1,
578 policy: testCase.policy,
579 rowEncodedBytes: (row) => {
580 measured.push(row);
581 return 10;
582 },
583 });
584​
585 expect(page.items.map((row) => row.sourceItemId)).toEqual(
586 testCase.items.slice(-testCase.admitted).map((row) => row.sourceItemId),
587 );
588 expect(measured).toHaveLength(testCase.measured);
589 expect(page.hasMoreHistory).toBe(true);
590 expect(decodeThreadHistoryCursor(page.nextCursor!).si).toBe(page.items[0]?.sourceItemId);
591 });
592​
593 it("recovers identity-miss cursors when position is past a shrunken timeline", () => {
594 const items = Array.from({ length: 5 }, (_, index) => makeRow(index));
595 const cursor = encodeThreadHistoryCursor({
596 snapshotSequence: 3,
597 sourceThreadId: THREAD,
598 sourceItemId: TurnItemId.make("item-deleted-long-ago"),
599 position: 40,
600 });
601 const page = selectHistoryPageFromCursor({
602 items,
603 cursor,
604 snapshotSequence: 3,
605 policy: { maxItems: 2, maxEncodedBytes: 10_000_000 },
606 });
607 expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]);
608 expect(page.hasMoreHistory).toBe(true);
609 expect(page.nextCursor).not.toBeNull();
610 const sparse = [makeRow(0), makeRow(10), makeRow(20)];
611 const middle = selectHistoryPageFromCursor({
612 items: sparse,
613 cursor: encodeThreadHistoryCursor({
614 snapshotSequence: 3,
615 sourceThreadId: THREAD,
616 sourceItemId: "item-hidden",
617 position: 15,
618 }),
619 snapshotSequence: 3,
620 });
621 expect(middle.items.map((row) => row.sourceItemId)).toEqual(["item-0", "item-10"]);
622 const work = Array.from({ length: 80 }, (_, index) => {
623 const row = makeRow(index);
624 return { ...row, item: { ...row.item, runId: RUN, ordinal: index + 100 } };
625 });
626 const tail = work[75]!;
627 const deferred = selectDeferredWorkPage({
628 items: work.filter((row) => row !== tail).map((row, position) => ({ ...row, position })),
629 cursor: encodeThreadHistoryCursor({
630 snapshotSequence: 3,
631 sourceThreadId: THREAD,
632 sourceItemId: tail.sourceItemId,
633 position: tail.item.ordinal,
634 inclusive: true,
635 }),
636 throughEntryId: work[0]!.sourceItemId,
637 snapshotSequence: 3,
638 });
639 expect(deferred.items.map((row) => row.sourceItemId)).toEqual(
640 work.slice(0, 75).map((row) => row.sourceItemId),
641 );
642 expect(deferred.nextCursor).toBeNull();
643 });
644​
645 it("reaches a jump target far back in one page that stops at its turn", () => {
646 // 200 user turns of 10 rows; the cursor sits at the newest row.
647 const items = Array.from({ length: 2000 }, (_, index) =>
648 index % 10 === 0 ? makeTurnStart(index, "user") : makeRow(index),
649 );
650 const newest = items.at(-1)!;
651 const cursor = encodeThreadHistoryCursor({
652 snapshotSequence: 1,
653 sourceThreadId: THREAD,
654 sourceItemId: newest.sourceItemId,
655 position: newest.position,
656 });
657 const target = items[505]!;
658 const page = selectHistoryPageFromCursor({
659 items,
660 cursor,
661 snapshotSequence: 1,
662 throughEntryId: target.item.id,
663 });
664 expect(page.items[0]!.sourceItemId).toBe(items[500]!.sourceItemId);
665 expect(page.items).toHaveLength(1499);
666 expect(page.hasMoreHistory).toBe(true);
667 });
668​
669 it("keeps cursor resolution stable when newer items append", () => {
670 const initial = Array.from({ length: 20 }, (_, index) => makeRow(index));
671 const recent = selectRecentTimelineWindow({
672 items: initial,
673 snapshotSequence: 2,
674 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
675 });
676 const cursor = recent.nextCursor!;
677 const grown = [...initial, makeRow(20), makeRow(21)];
678 const older = selectHistoryPageFromCursor({
679 items: grown,
680 cursor,
681 snapshotSequence: 5,
682 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
683 });
684 expect(older.items.map((row) => row.sourceItemId)).toEqual([
685 "item-10",
686 "item-11",
687 "item-12",
688 "item-13",
689 "item-14",
690 ]);
691 expect(older.hasMoreHistory).toBe(true);
692 });
693​
694 it("builds a bounded projection that preserves non-timeline control state", () => {
695 const full = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
696 const bounded = buildBoundedThreadProjection({
697 projection: full,
698 snapshotSequence: 7,
699 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
700 });
701 expect(bounded.projection.runs).toEqual(full.runs);
702 expect(bounded.projection.runtimeRequests).toEqual(full.runtimeRequests);
703 expect(bounded.projection.attempts).toEqual(full.attempts);
704 expect(bounded.projection.visibleTurnItems).toHaveLength(5);
705 expect(bounded.projection.turnItems).toHaveLength(5);
706 expect(bounded.hasMoreHistory).toBe(true);
707 expect(bounded.historyCursor).not.toBeNull();
708 expect(bounded.projection.visibleTurnItems.map((row) => row.position)).toEqual([0, 1, 2, 3, 4]);
709 expect(bounded.latestLocalTurnOrdinal).toBe(40);
710 expect(computeLatestLocalTurnOrdinal(full.turnItems)).toBe(40);
711 });
712​
713 it("carries a full-projection watermark when the bounded window is inherited-only", () => {
714 const localOlder = makeRow(0);
715 const localMid = makeRow(1);
716 const inherited = {
717 ...makeRow(2),
718 visibility: "inherited" as const,
719 sourceThreadId: ThreadId.make("parent-thread"),
720 item: {
721 ...makeRow(2).item,
722 threadId: ThreadId.make("parent-thread"),
723 },
724 };
725 const full = makeProjection([localOlder, localMid, inherited]);
726 const inheritedOnly = {
727 ...full,
728 visibleTurnItems: [inherited],
729 turnItems: [localOlder.item, localMid.item],
730 };
731 const bounded = buildBoundedThreadProjection({
732 projection: inheritedOnly,
733 snapshotSequence: 2,
734 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
735 });
736 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
737 String(inherited.sourceItemId),
738 ]);
739 expect(bounded.latestLocalTurnOrdinal).toBe(2);
740 expect(computeLatestLocalTurnOrdinal([])).toBeNull();
741 });
742​
743 it("retains an out-of-window run_interrupt_request needed by a visible result", () => {
744 const request = interruptRow(0, "run_interrupt_request");
745 const filler = makeRow(1);
746 const result = interruptRow(2, "run_interrupt_result");
747 const full = makeProjection([request, filler, result]);
748 const bounded = buildBoundedThreadProjection({
749 projection: full,
750 snapshotSequence: 3,
751 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
752 });
753​
754 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
755 "interrupt-res",
756 ]);
757 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
758 "interrupt-req",
759 "interrupt-res",
760 ]);
761 expect(bounded.hasMoreHistory).toBe(true);
762 });
763​
764 it("charges local row.item duplication when measuring bounded timeline bytes", () => {
765 const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 }));
766 const full = makeProjection(rows);
767 const maxEncodedBytes = 12_000;
768 const bounded = buildBoundedThreadProjection({
769 projection: full,
770 snapshotSequence: 1,
771 policy: { maxItems: 50, maxEncodedBytes },
772 });
773​
774 const contribution = boundedTimelineEncodedBytes({
775 visibleTurnItems: bounded.projection.visibleTurnItems,
776 turnItems: bounded.projection.turnItems,
777 });
778 expect(contribution).toBeLessThanOrEqual(maxEncodedBytes);
779 expect(bounded.projection.visibleTurnItems.length).toBeGreaterThan(0);
780 expect(bounded.projection.visibleTurnItems.length).toBeLessThan(rows.length);
781​
782 const historyPage = selectRecentTimelineWindow({
783 items: rows,
784 snapshotSequence: 1,
785 policy: { maxItems: 50, maxEncodedBytes },
786 });
787 const historyBytes = historyPage.items.reduce(
788 (sum, row) => sum + projectedRowEncodedBytes(row),
789 0,
790 );
791 expect(historyBytes).toBeLessThanOrEqual(maxEncodedBytes);
792 expect(historyPage.items.length).toBeGreaterThan(bounded.projection.visibleTurnItems.length);
793​
794 const sample = rows[0]!;
795 expect(projectedRowBoundedSnapshotEncodedBytes(sample, THREAD)).toBeGreaterThan(
796 projectedRowEncodedBytes(sample),
797 );
798 });
799​
800 it("does not carry the full duplicated message table into a bounded snapshot", () => {
801 const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index)));
802 const full = {
803 ...projection,
804 messages: Array.from({ length: 2_000 }, (_, index) => ({
805 id: MessageId.make(`message-${index}`),
806 threadId: THREAD,
807 runId: RunId.make(`old-run-${index}`),
808 nodeId: null,
809 role: "assistant" as const,
810 text: "x".repeat(1_000),
811 attachments: [],
812 streaming: false,
813 createdBy: "agent" as const,
814 creationSource: "provider" as const,
815 createdAt: NOW,
816 updatedAt: NOW,
817 })),
818 } as typeof projection;
819​
820 const bounded = buildBoundedThreadProjection({
821 projection: full,
822 snapshotSequence: 9,
823 });
824​
825 expect(bounded.projection.messages).toEqual([]);
826 expect(Buffer.byteLength(JSON.stringify(bounded.projection), "utf8")).toBeLessThan(
827 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes + 100_000,
828 );
829 });
830​
831 it("keeps a workflow coordinator's script outside the bounded window", () => {
832 const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index)));
833 const message = (index: number, workflowScript?: boolean) => ({
834 id: MessageId.make(`message-${index}`),
835 threadId: THREAD,
836 runId: RunId.make(`old-run-${index}`),
837 nodeId: null,
838 role: "user" as const,
839 text: `message ${index}`,
840 attachments: [],
841 streaming: false,
842 createdBy: "agent" as const,
843 creationSource: "provider" as const,
844 createdAt: NOW,
845 updatedAt: NOW,
846 ...(workflowScript === undefined ? {} : { workflowScript }),
847 });
848 const full = {
849 ...projection,
850 messages: [message(0, true), message(1, false), message(2)],
851 } as typeof projection;
852​
853 const bounded = buildBoundedThreadProjection({ projection: full, snapshotSequence: 9 });
854​
855 expect(bounded.projection.messages.map((retained) => retained.id)).toEqual([
856 MessageId.make("message-0"),
857 ]);
858 });
859​
860 it("omits historical control details that remain available from history items", () => {
861 const projection = makeProjection(Array.from({ length: 200 }, (_, index) => makeRow(index)));
862 const populated = {
863 ...projection,
864 plans: Array.from({ length: 120 }, (_, index) => ({
865 id: `plan-${index}`,
866 threadId: THREAD,
867 runId: null,
868 nodeId: `node-${index}`,
869 status: "completed",
870 kind: "proposed_plan",
871 markdown: "p".repeat(2_097_152),
872 })),
873 contextHandoffs: Array.from({ length: 120 }, (_, index) => ({
874 id: `handoff-${index}`,
875 threadId: THREAD,
876 targetRunId: "run-1",
877 fromProviderThreadIds: [],
878 toProviderThreadId: "provider-thread-1",
879 coveredRunOrdinals: { from: 1, to: 1 },
880 strategy: "manual_context",
881 status: "superseded",
882 summaryMessageId: null,
883 summaryText: "h".repeat(2_097_152),
884 createdByProviderInstanceId: null,
885 createdAt: NOW,
886 updatedAt: NOW,
887 })),
888 } as unknown as typeof projection;
889​
890 const bounded = buildBoundedThreadProjection({
891 projection: projectThreadProjectionForWire(populated),
892 snapshotSequence: 9,
893 });
894 const serializedBytes = Buffer.byteLength(JSON.stringify(bounded.projection), "utf8");
895​
896 expect(serializedBytes).toBeLessThanOrEqual(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes);
897 expect(bounded.projection.plans).toEqual([]);
898 expect(bounded.projection.contextHandoffs).toEqual([]);
899 expect(populated.plans).toHaveLength(120);
900 expect(
901 populated.plans[0]?.kind === "proposed_plan" ? populated.plans[0].markdown.length : 0,
902 ).toBe(2_097_152);
903 });
904​
905 it.each([40_000, 80_000])(
906 "reserves pending question cards before visible history: %s bytes",
907 (questionBytes) => {
908 const rows = Array.from({ length: 20 }, (_, index) =>
909 makeRow(index + 1, { outputBytes: 1_500 }),
910 );
911 const requestId = RuntimeRequestId.make("pending-question");
912 const card: OrchestrationV2TurnItem = {
913 id: TurnItemId.make("pending-question-card"),
914 type: "user_input_request",
915 threadId: THREAD,
916 runId: null,
917 nodeId: NODE,
918 providerThreadId: null,
919 providerTurnId: null,
920 nativeItemRef: null,
921 parentItemId: null,
922 ordinal: 1,
923 status: "completed",
924 title: null,
925 requestId,
926 responseMode: "message",
927 questions: [
928 { id: "scope", header: "Scope", question: "q".repeat(questionBytes), options: [] },
929 ],
930 startedAt: NOW,
931 completedAt: NOW,
932 updatedAt: NOW,
933 };
934 const projection = {
935 ...makeProjection(rows),
936 turnItems: [card, ...rows.map((row) => row.item)],
937 runtimeRequests: [
938 {
939 id: requestId,
940 nodeId: NODE,
941 providerTurnId: null,
942 nativeRequestRef: null,
943 kind: "user_input" as const,
944 status: "pending" as const,
945 responseCapability: { type: "message" as const },
946 createdAt: NOW,
947 resolvedAt: null,
948 },
949 ],
950 };
951 const policy = { ...THREAD_HISTORY_PAGE_POLICY, maxEncodedBytes: 64_000 };
952​
953 const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 9, policy });
954​
955 expect(bounded.projection.turnItems).toContain(card);
956 expect(bounded.projection.visibleTurnItems.length).toBeGreaterThan(0);
957 expect(bounded.hasMoreHistory).toBe(true);
958 if (questionBytes < policy.maxEncodedBytes) {
959 expect(Buffer.byteLength(JSON.stringify(bounded.projection), "utf8")).toBeLessThanOrEqual(
960 policy.maxEncodedBytes,
961 );
962 } else {
963 expect(bounded.projection.visibleTurnItems).toHaveLength(1);
964 }
965 },
966 );
967​
968 it("preserves oversized actionable state", () => {
969 const projection = makeProjection([makeRow(0)]);
970 const actionable = {
971 ...projection,
972 plans: [
973 {
974 id: "plan-actionable",
975 threadId: THREAD,
976 runId: null,
977 nodeId: "node-actionable",
978 status: "active",
979 kind: "proposed_plan",
980 markdown: "a".repeat(2_097_152),
981 },
982 ],
983 } as unknown as typeof projection;
984​
985 const bounded = buildBoundedThreadProjection({ projection: actionable, snapshotSequence: 9 });
986​
987 expect(bounded.projection.plans[0]).toEqual(actionable.plans[0]);
988 expect(bounded.projection.visibleTurnItems).toEqual(actionable.visibleTurnItems);
989 });
990​
991 it.each([false, true])(
992 "keeps agent-only turns visible when checkpoint file lists fill the byte budget (stored interrupt request: %s)",
993 (withInterruptRequest) => {
994 const items = Array.from({ length: 3 }, (_, turn) => {
995 const first = makeRow(turn * 5);
996 const prompt = {
997 ...first,
998 item: {
999 ...first.item,
1000 type: "user_message" as const,
1001 createdBy: "agent" as const,
1002 creationSource: "provider" as const,
1003 inputIntent: "turn_start" as const,
1004 messageId: MessageId.make(`agent-prompt-${turn}`),
1005 text: `Step ${turn}`,
1006 attachments: [],
1007 },
1008 } as OrchestrationV2ProjectedTurnItem;
1009 return [prompt, ...Array.from({ length: 4 }, (_, index) => makeRow(turn * 5 + index + 1))];
1010 }).flat();
1011 const files = Array.from(
1012 { length: 15_000 },
1013 (_, index) =>
1014 `work/ws-${index % 40}/.jj/repo/store/extra/${index.toString(16).padStart(40, "0")}`,
1015 );
1016 const base = makeProjection(items);
1017 const projection = {
1018 ...base,
1019 turnItems: withInterruptRequest
1020 ? [interruptItem("old-interrupt-req", "run_interrupt_request", 0), ...base.turnItems]
1021 : base.turnItems,
1022 checkpoints: [{ id: "checkpoint-1", files }],
1023 } as unknown as ReturnType<typeof makeProjection>;
1024​
1025 const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 1 });
1026​
1027 expect(bounded.projection.visibleTurnItems).toHaveLength(items.length);
1028 expect(bounded.hasMoreHistory).toBe(false);
1029 },
1030 );
1031​
1032 it("keeps paged historical plan detail in the turn item and only status in its artifact", () => {
1033 const detail = "Implement the historical plan exactly.\n".repeat(1_000);
1034 const item = {
1035 ...makeRow(0).item,
1036 type: "proposed_plan",
1037 planId: "plan-historical-visible",
1038 markdown: detail,
1039 streaming: false,
1040 } as OrchestrationV2TurnItem;
1041 const row = {
1042 ...makeRow(0),
1043 sourceItemId: item.id,
1044 item,
1045 } as OrchestrationV2ProjectedTurnItem;
1046 const base = makeProjection([row]);
1047 const projection = {
1048 ...base,
1049 plans: [
1051 id: "plan-historical-visible",
1052 threadId: THREAD,
1053 runId: null,
1054 nodeId: "node-historical-visible",
1055 status: "completed",
1056 kind: "proposed_plan",
1057 markdown: detail,
1058 },
1059 ],
1060 } as unknown as typeof base;
1061​
1062 const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 9 });
1063​
1064 expect(bounded.projection.visibleTurnItems[0]?.item).toMatchObject({
1065 type: "proposed_plan",
1066 markdown: detail,
1067 });
1068 expect(bounded.projection.plans[0]).toMatchObject({
1069 status: "completed",
1070 markdown: "",
1071 detailInTurnItem: true,
1072 });
1073 });
1074});