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

threadHistoryPaging.test.ts

1,074 lines36.2 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 { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError";
13import * as DateTime from "effect/DateTime";
14​
15import {
16 buildBoundedThreadProjection,
17 deferWorkHistoryRows,
18 boundedTimelineEncodedBytes,
19 computeLatestLocalTurnOrdinal,
20 decodeThreadHistoryCursor,
21 encodeThreadHistoryCursor,
22 projectedRowBoundedSnapshotEncodedBytes,
23 projectedRowEncodedBytes,
24 selectHistoryPageFromCursor,
25 selectDeferredWorkPage,
26 selectRecentTimelineWindow,
27 THREAD_HISTORY_PAGE_POLICY,
28} from "./threadHistoryPaging.ts";
29import { projectThreadProjectionForWire } from "./WireProjection.ts";
30​
31const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
32const THREAD = ThreadId.make("thread-1");
33const RUN = RunId.make("run-interrupt-1");
34const NODE = NodeId.make("node-interrupt-1");
35​
36function makeRow(
37 index: number,
38 options?: { readonly outputBytes?: number },
39): OrchestrationV2ProjectedTurnItem {
40 const id = TurnItemId.make(`item-${index}`);
41 const output =
42 options?.outputBytes !== undefined ? "x".repeat(options.outputBytes) : `output-${index}`;
43 return {
44 position: index,
45 visibility: "local",
46 sourceThreadId: THREAD,
47 sourceItemId: id,
48 item: {
49 id,
50 type: "command_execution",
51 threadId: THREAD,
52 runId: null,
53 nodeId: null,
54 providerThreadId: null,
55 providerTurnId: null,
56 nativeItemRef: null,
57 parentItemId: null,
58 ordinal: index + 1,
59 status: "completed",
60 title: `Command ${index}`,
61 input: `cmd-${index}`,
62 output,
63 exitCode: 0,
64 startedAt: NOW,
65 completedAt: NOW,
66 updatedAt: NOW,
67 },
68 };
70​
71function makeTurnStart(
72 index: number,
73 createdBy: "user" | "agent",
74): OrchestrationV2ProjectedTurnItem {
75 const row = makeRow(index);
76 return {
77 ...row,
78 item: {
79 ...row.item,
80 type: "user_message",
81 createdBy,
82 creationSource: "provider",
83 inputIntent: "turn_start",
84 messageId: MessageId.make(`prompt-${index}`),
85 text: `Prompt ${index}`,
86 attachments: [],
87 },
88 } as OrchestrationV2ProjectedTurnItem;
90​
91function interruptItem(
92 id: string,
93 type: "run_interrupt_request" | "run_interrupt_result",
94 ordinal: number,
95): OrchestrationV2TurnItem {
96 return {
97 id: TurnItemId.make(id),
98 type,
99 threadId: THREAD,
100 runId: RUN,
101 nodeId: NODE,
102 providerThreadId: null,
103 providerTurnId: null,
104 nativeItemRef: null,
105 parentItemId: null,
106 ordinal,
107 status: "completed",
108 title: type,
109 message: type === "run_interrupt_request" ? "Stopping" : "Stopped",
110 startedAt: NOW,
111 completedAt: NOW,
112 updatedAt: NOW,
113 } as OrchestrationV2TurnItem;
115​
116function interruptRow(
117 index: number,
118 type: "run_interrupt_request" | "run_interrupt_result",
119): OrchestrationV2ProjectedTurnItem {
120 const item = interruptItem(
121 type === "run_interrupt_request" ? "interrupt-req" : "interrupt-res",
122 type,
123 index + 1,
124 );
125 return {
126 position: index,
127 visibility: "local",
128 sourceThreadId: THREAD,
129 sourceItemId: item.id,
130 item,
131 };
133​
134function makeProjection(visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) {
135 return {
136 thread: {
137 id: THREAD,
138 projectId: "project-1",
139 title: "Thread",
140 providerInstanceId: "codex",
141 modelSelection: { instanceId: "codex", model: "gpt-5" },
142 runtimeMode: "full-access",
143 interactionMode: "default",
144 branch: null,
145 worktreePath: null,
146 activeProviderThreadId: null,
147 lineage: {
148 parentThreadId: null,
149 relationshipToParent: null,
150 rootThreadId: THREAD,
151 },
152 forkedFrom: null,
153 createdBy: "user",
154 creationSource: "web",
155 createdAt: NOW,
156 updatedAt: NOW,
157 archivedAt: null,
158 deletedAt: null,
159 settledOverride: null,
160 settledAt: null,
161 },
162 runs: [{ id: "run-1" }],
163 attempts: [{ id: "attempt-1" }],
164 nodes: [],
165 subagents: [],
166 providerSessions: [],
167 providerThreads: [],
168 providerTurns: [],
169 runtimeRequests: [{ id: "req-1" }],
170 messages: [],
171 plans: [],
172 turnItems: visibleTurnItems.map((row) => row.item),
173 checkpointScopes: [],
174 checkpoints: [],
175 contextHandoffs: [],
176 contextTransfers: [],
177 visibleTurnItems,
178 updatedAt: NOW,
179 } as unknown as Parameters<typeof buildBoundedThreadProjection>[0]["projection"];
181​
182describe("threadHistoryPaging", () => {
183 it("defers completed work above 150 items and keeps conversation and persistent rows", () => {
184 const work = Array.from({ length: 151 }, (_, index) => {
185 const row = makeRow(index);
186 return { ...row, item: { ...row.item, runId: RUN, runStatus: "completed" } };
187 });
188 expect(deferWorkHistoryRows(work.slice(0, 150))).toHaveLength(150);
189 const deferredWork = deferWorkHistoryRows(work)[0]!.item.deferredWork!;
190 expect(deferredWork.itemCount).toBe(151);
191 expect(decodeThreadHistoryCursor(deferredWork.cursor).p).toBe(151);
192 const superseded = work.map((row) => ({
193 ...row,
194 item: { ...row.item, runStatus: "running", attemptId: "old", attemptStatus: "superseded" },
195 }));
196 const active = work.map((row, index) => ({
197 ...row,
198 sourceItemId: TurnItemId.make(`active-${index}`),
199 position: row.position + work.length,
200 item: { ...row.item, runStatus: "running", attemptId: "active", attemptStatus: "running" },
201 }));
202 const attempts = deferWorkHistoryRows([...superseded, ...active]);
203 expect(attempts[0]?.item.deferredWork?.itemCount).toBe(151);
204 expect(attempts.slice(1)).toEqual(active);
205 const compaction = {
206 ...work[0]!,
207 sourceItemId: TurnItemId.make("compaction"),
208 item: {
209 ...work[0]!.item,
210 type: "compaction" as const,
211 },
212 };
213 const persistent = {
214 ...work[0]!,
215 sourceItemId: TurnItemId.make("render"),
216 item: {
217 ...work[0]!.item,
218 type: "dynamic_tool" as const,
219 persistentOutput: true,
220 },
221 };
222 const deferred = deferWorkHistoryRows([
223 ...work.slice(0, 30),
224 compaction,
225 persistent,
226 ...work.slice(30),
227 ]);
228 expect(deferred.map((row) => row.sourceItemId)).toEqual(["item-0", "compaction", "render"]);
229 expect(deferred[0]?.item.deferredWork?.itemCount).toBe(151);
230 for (const runStatus of ["running", "failed", "interrupted", "cancelled"]) {
231 expect(
232 deferWorkHistoryRows(work.map((row) => ({ ...row, item: { ...row.item, runStatus } }))),
233 ).toHaveLength(151);
234 }
235 const interrupted = {
236 ...compaction,
237 item: { ...compaction.item, type: "run_interrupt_result" as const },
238 };
239 expect(deferWorkHistoryRows([...work, interrupted])).toHaveLength(152);
240 const failed = {
241 ...compaction,
242 item: {
243 ...compaction.item,
244 type: "error" as const,
245 status: "failed" as const,
246 nodeId: "root-node",
247 parentItemId: null,
248 },
249 };
250 expect(deferWorkHistoryRows([...work, failed])).toHaveLength(152);
251 });
252​
253 it("keeps a human turn whole up to the turn row budget and pages a longer one from inside", () => {
254 const humanTurn = (length: number) => {
255 const items = Array.from({ length }, (_, index) => makeRow(index));
256 items[0] = {
257 ...items[0]!,
258 item: {
259 ...items[0]!.item,
260 type: "user_message",
261 createdBy: "user",
262 creationSource: "web",
263 inputIntent: "turn_start",
264 messageId: MessageId.make("long-human-turn"),
265 text: "Continue",
266 attachments: [],
267 },
268 } as OrchestrationV2ProjectedTurnItem;
269 return items;
270 };
271​
272 const whole = selectRecentTimelineWindow({ items: humanTurn(180), snapshotSequence: 1 });
273 expect(whole.items).toHaveLength(180);
274 expect(whole.hasMoreHistory).toBe(false);
275​
276 const items = humanTurn(THREAD_HISTORY_PAGE_POLICY.maxTurnItems + 100);
277 const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
278 expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
279 const loaded = [...recent.items];
280 let cursor = recent.nextCursor;
281 for (let pages = 0; cursor !== null; pages += 1) {
282 expect(pages).toBeLessThan(items.length);
283 const page = selectHistoryPageFromCursor({ items, cursor, snapshotSequence: 1 });
284 expect(page.items.length).toBeGreaterThan(0);
285 expect(page.items.length).toBeLessThanOrEqual(
286 page.items[0]?.item.type === "user_message"
287 ? THREAD_HISTORY_PAGE_POLICY.maxTurnItems
288 : THREAD_HISTORY_PAGE_POLICY.maxItems,
289 );
290 loaded.unshift(...page.items);
291 cursor = page.nextCursor;
292 }
293 expect(loaded.map((row) => row.sourceItemId)).toEqual(items.map((row) => row.sourceItemId));
294​
295 const large = items
296 .slice(0, 12)
297 .map((row) =>
298 row.item.type === "command_execution"
299 ? { ...row, item: { ...row.item, output: "x".repeat(200_000) } }
300 : row,
301 );
302 const bounded = buildBoundedThreadProjection({
303 projection: makeProjection(large),
304 snapshotSequence: 1,
305 });
306 expect(bounded.projection.visibleTurnItems.length).toBeLessThan(large.length);
307 expect(boundedTimelineEncodedBytes(bounded.projection)).toBeLessThanOrEqual(
308 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes,
309 );
310 });
311​
312 it("keeps background turns with user turns, with main's 150-turn fan-out ceiling", () => {
313 const items = Array.from({ length: 161 }, (_, turn) => {
314 const row = makeRow(turn * 2);
315 if (row.item.type !== "command_execution") throw new Error("Expected command fixture");
316 const prompt: OrchestrationV2ProjectedTurnItem = {
317 ...row,
318 item: {
319 ...row.item,
320 type: "user_message",
321 createdBy: turn === 0 ? "user" : "agent",
322 creationSource: "provider",
323 inputIntent: "turn_start",
324 messageId: MessageId.make(`prompt-${turn}`),
325 text: `Prompt ${turn}`,
326 attachments: [],
327 },
328 };
329 return [prompt, makeRow(turn * 2 + 1)];
330 }).flat();
331 const policy = { ...THREAD_HISTORY_PAGE_POLICY, maxItems: 1_000, maxEncodedBytes: 10_000_000 };
332 const first = selectRecentTimelineWindow({ items, snapshotSequence: 1, policy });
333 expect(first.items).toHaveLength(300);
334 expect(first.items[0]?.sourceItemId).toBe("item-22");
335 const older = selectHistoryPageFromCursor({
336 items,
337 cursor: first.nextCursor!,
338 snapshotSequence: 1,
339 policy,
340 });
341 expect(older.items).toHaveLength(22);
342 expect(older.hasMoreHistory).toBe(false);
343 expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual(
344 items.map((row) => row.sourceItemId),
345 );
346 });
347​
348 it("counts runs that a notification started toward the 150-turn ceiling", () => {
349 const inRun = (index: number, run: number, item: object = {}) => {
350 const row = makeRow(index);
351 return {
352 ...row,
353 item: { ...row.item, runId: RunId.make(`run-${run}`), ...item },
354 } as OrchestrationV2ProjectedTurnItem;
355 };
356 const notification = (summary: string) => ({
357 type: "notification",
358 source: { kind: "monitor" },
359 outcome: "completed",
360 summary,
361 });
362 const items = Array.from({ length: 161 }, (_, run) => [
363 inRun(run * 4, run),
364 inRun(
365 run * 4 + 1,
366 run,
367 run === 0
368 ? {
369 type: "user_message",
370 createdBy: "user",
371 creationSource: "web",
372 inputIntent: "turn_start",
373 messageId: MessageId.make("prompt-0"),
374 text: "Prompt 0",
375 attachments: [],
376 }
377 : notification(`Wake ${run}`),
378 ),
379 inRun(run * 4 + 2, run, notification(`Steer ${run}`)),
380 inRun(run * 4 + 3, run),
381 ]).flat();
382 const policy = {
383 ...THREAD_HISTORY_PAGE_POLICY,
384 maxItems: 1_000,
385 maxTurnItems: 1_000,
386 maxEncodedBytes: 10_000_000,
387 };
388 const first = selectRecentTimelineWindow({ items, snapshotSequence: 1, policy });
389 expect(first.items).toHaveLength(150 * 4 - 1);
390 expect(first.items[0]?.sourceItemId).toBe(`item-${11 * 4 + 1}`);
391 const older = selectHistoryPageFromCursor({
392 items,
393 cursor: first.nextCursor!,
394 snapshotSequence: 1,
395 policy,
396 });
397 expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual(
398 items.map((row) => row.sourceItemId),
399 );
400 });
401​
402 it("pages agent-only child transcripts instead of dropping their earlier activity", () => {
403 const commandRows = Array.from({ length: 90 }, (_, index) => makeRow(index + 1));
404 const first = makeRow(0);
405 const prompt = {
406 ...first,
407 item: {
408 ...first.item,
409 type: "user_message" as const,
410 createdBy: "agent" as const,
411 creationSource: "provider" as const,
412 inputIntent: "turn_start" as const,
413 messageId: MessageId.make("child-prompt"),
414 text: "Inspect this project",
415 attachments: [],
416 },
417 } as OrchestrationV2ProjectedTurnItem;
418 const items = [prompt, ...commandRows];
419 const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
420​
421 expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
422 expect(recent.hasMoreHistory).toBe(true);
423 const older = selectHistoryPageFromCursor({
424 items,
425 cursor: recent.nextCursor!,
426 snapshotSequence: 1,
427 });
428 expect(older.items[0]?.item.type).toBe("user_message");
429 expect([...older.items, ...recent.items]).toHaveLength(items.length);
430 });
431​
432 it("always includes at least one pathological oversized item", () => {
433 for (const humanTurn of [false, true]) {
434 const oversized = makeRow(0, { outputBytes: 2_000_000 });
435 const items = [
436 humanTurn
437 ? ({
438 ...oversized,
439 item: {
440 ...oversized.item,
441 type: "user_message",
442 createdBy: "user",
443 creationSource: "web",
444 inputIntent: "turn_start",
445 messageId: MessageId.make("oversized-human-turn"),
446 text: "x".repeat(2_000_000),
447 attachments: [],
448 },
449 } as OrchestrationV2ProjectedTurnItem)
450 : oversized,
451 makeRow(1, { outputBytes: 10 }),
452 ];
453 const policy = { ...THREAD_HISTORY_PAGE_POLICY, maxItems: 50, maxEncodedBytes: 1_024 };
454 const page = selectRecentTimelineWindow({ items, snapshotSequence: 1, policy });
455 expect(page.items).toHaveLength(1);
456 expect(page.items[0]?.sourceItemId).toBe("item-1");
457 expect(page.hasMoreHistory).toBe(true);
458​
459 const older = selectHistoryPageFromCursor({
460 items,
461 cursor: page.nextCursor!,
462 snapshotSequence: 1,
463 policy,
464 });
465 expect(older.items).toHaveLength(1);
466 expect(older.items[0]?.sourceItemId).toBe("item-0");
467 expect(older.hasMoreHistory).toBe(false);
468 expect(older.nextCursor).toBeNull();
469 expect([...older.items, ...page.items].map((row) => row.sourceItemId)).toEqual(
470 items.map((row) => row.sourceItemId),
471 );
472 }
473 });
474​
475 it.each([
476 {
477 name: "item ceiling",
478 items: Array.from({ length: 5 }, (_, index) => makeRow(index)),
479 policy: { maxItems: 3, maxEncodedBytes: 1_000 },
480 admitted: 3,
481 measured: 3,
482 },
483 {
484 name: "user turn ceiling",
485 items: [makeRow(0), makeTurnStart(1, "user"), makeRow(2)],
486 policy: { maxUserTurns: 1, maxItems: 100, maxEncodedBytes: 1_000 },
487 admitted: 2,
488 measured: 2,
489 },
490 {
491 name: "raw turn ceiling",
492 items: [
493 makeTurnStart(0, "user"),
494 ...Array.from({ length: 151 }, (_, index) => makeTurnStart(index + 1, "agent")),
495 ],
496 policy: { maxUserTurns: 10, maxItems: 1_000, maxEncodedBytes: 1_000_000 },
497 admitted: 150,
498 measured: 150,
499 },
500 {
501 name: "byte budget, which still admits an exact fit",
502 items: Array.from({ length: 5 }, (_, index) => makeRow(index)),
503 policy: { maxItems: 100, maxEncodedBytes: 20 },
504 admitted: 2,
505 measured: 3,
506 },
507 {
508 name: "byte budget, which still admits an oversized first row",
509 items: Array.from({ length: 5 }, (_, index) => makeRow(index)),
510 policy: { maxItems: 100, maxEncodedBytes: 5 },
511 admitted: 1,
512 measured: 2,
513 },
514 ])("measures only the rows needed to stop at the $name", (testCase) => {
515 const measured: OrchestrationV2ProjectedTurnItem[] = [];
516 const page = selectRecentTimelineWindow({
517 items: testCase.items,
518 snapshotSequence: 1,
519 policy: testCase.policy,
520 rowEncodedBytes: (row) => {
521 measured.push(row);
522 return 10;
523 },
524 });
525​
526 expect(page.items.map((row) => row.sourceItemId)).toEqual(
527 testCase.items.slice(-testCase.admitted).map((row) => row.sourceItemId),
528 );
529 expect(measured).toHaveLength(testCase.measured);
530 expect(page.hasMoreHistory).toBe(true);
531 expect(decodeThreadHistoryCursor(page.nextCursor!).si).toBe(page.items[0]?.sourceItemId);
532 });
533​
534 it("recovers identity-miss cursors when position is past a shrunken timeline", () => {
535 const items = Array.from({ length: 5 }, (_, index) => makeRow(index));
536 const cursor = encodeThreadHistoryCursor({
537 snapshotSequence: 3,
538 sourceThreadId: THREAD,
539 sourceItemId: TurnItemId.make("item-deleted-long-ago"),
540 position: 40,
541 });
542 const page = selectHistoryPageFromCursor({
543 items,
544 cursor,
545 snapshotSequence: 3,
546 policy: { maxItems: 2, maxEncodedBytes: 10_000_000 },
547 });
548 expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]);
549 expect(page.hasMoreHistory).toBe(true);
550 expect(page.nextCursor).not.toBeNull();
551 const sparse = [makeRow(0), makeRow(10), makeRow(20)];
552 const middle = selectHistoryPageFromCursor({
553 items: sparse,
554 cursor: encodeThreadHistoryCursor({
555 snapshotSequence: 3,
556 sourceThreadId: THREAD,
557 sourceItemId: "item-hidden",
558 position: 15,
559 }),
560 snapshotSequence: 3,
561 });
562 expect(middle.items.map((row) => row.sourceItemId)).toEqual(["item-0", "item-10"]);
563 const work = Array.from({ length: 80 }, (_, index) => {
564 const row = makeRow(index);
565 return { ...row, item: { ...row.item, runId: RUN, ordinal: index + 100 } };
566 });
567 const tail = work[75]!;
568 const deferred = selectDeferredWorkPage({
569 items: work.filter((row) => row !== tail).map((row, position) => ({ ...row, position })),
570 cursor: encodeThreadHistoryCursor({
571 snapshotSequence: 3,
572 sourceThreadId: THREAD,
573 sourceItemId: tail.sourceItemId,
574 position: tail.item.ordinal,
575 inclusive: true,
576 }),
577 throughEntryId: work[0]!.sourceItemId,
578 snapshotSequence: 3,
579 });
580 expect(deferred.items.map((row) => row.sourceItemId)).toEqual(
581 work.slice(0, 75).map((row) => row.sourceItemId),
582 );
583 expect(deferred.nextCursor).toBeNull();
584 });
585​
586 it("keeps cursor resolution stable when newer items append", () => {
587 const initial = Array.from({ length: 20 }, (_, index) => makeRow(index));
588 const recent = selectRecentTimelineWindow({
589 items: initial,
590 snapshotSequence: 2,
591 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
592 });
593 const cursor = recent.nextCursor!;
594 const grown = [...initial, makeRow(20), makeRow(21)];
595 const older = selectHistoryPageFromCursor({
596 items: grown,
597 cursor,
598 snapshotSequence: 5,
599 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
600 });
601 expect(older.items.map((row) => row.sourceItemId)).toEqual([
602 "item-10",
603 "item-11",
604 "item-12",
605 "item-13",
606 "item-14",
607 ]);
608 expect(older.hasMoreHistory).toBe(true);
609 });
610​
611 it("builds a bounded projection that preserves non-timeline control state", () => {
612 const full = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
613 const bounded = buildBoundedThreadProjection({
614 projection: full,
615 snapshotSequence: 7,
616 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
617 });
618 expect(bounded.projection.runs).toEqual(full.runs);
619 expect(bounded.projection.runtimeRequests).toEqual(full.runtimeRequests);
620 expect(bounded.projection.attempts).toEqual(full.attempts);
621 expect(bounded.projection.visibleTurnItems).toHaveLength(5);
622 expect(bounded.projection.turnItems).toHaveLength(5);
623 expect(bounded.hasMoreHistory).toBe(true);
624 expect(bounded.historyCursor).not.toBeNull();
625 expect(bounded.projection.visibleTurnItems.map((row) => row.position)).toEqual([0, 1, 2, 3, 4]);
626 expect(bounded.latestLocalTurnOrdinal).toBe(40);
627 expect(computeLatestLocalTurnOrdinal(full.turnItems)).toBe(40);
628 });
629​
630 it("carries a full-projection watermark when the bounded window is inherited-only", () => {
631 const localOlder = makeRow(0);
632 const localMid = makeRow(1);
633 const inherited = {
634 ...makeRow(2),
635 visibility: "inherited" as const,
636 sourceThreadId: ThreadId.make("parent-thread"),
637 item: {
638 ...makeRow(2).item,
639 threadId: ThreadId.make("parent-thread"),
640 },
641 };
642 const full = makeProjection([localOlder, localMid, inherited]);
643 const inheritedOnly = {
644 ...full,
645 visibleTurnItems: [inherited],
646 turnItems: [localOlder.item, localMid.item],
647 };
648 const bounded = buildBoundedThreadProjection({
649 projection: inheritedOnly,
650 snapshotSequence: 2,
651 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
652 });
653 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
654 String(inherited.sourceItemId),
655 ]);
656 expect(bounded.latestLocalTurnOrdinal).toBe(2);
657 expect(computeLatestLocalTurnOrdinal([])).toBeNull();
658 });
659​
660 it("retains an out-of-window run_interrupt_request needed by a visible result", () => {
661 const request = interruptRow(0, "run_interrupt_request");
662 const filler = makeRow(1);
663 const result = interruptRow(2, "run_interrupt_result");
664 const full = makeProjection([request, filler, result]);
665 const bounded = buildBoundedThreadProjection({
666 projection: full,
667 snapshotSequence: 3,
668 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
669 });
670​
671 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
672 "interrupt-res",
673 ]);
674 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
675 "interrupt-req",
676 "interrupt-res",
677 ]);
678 expect(bounded.hasMoreHistory).toBe(true);
679 });
680​
681 it("keeps a limited run resumable when later notification wakes outgrow the window", () => {
682 const limitedNode = NodeId.make("node-limited");
683 const limited = {
684 id: RunId.make("run-limited"),
685 ordinal: 1,
686 status: "failed",
687 startedAt: NOW,
688 completedAt: NOW,
689 rootNodeId: limitedNode,
690 };
691 const limitError = {
692 ...makeRow(0).item,
693 id: TurnItemId.make("limit-error"),
694 type: "error",
695 runId: limited.id,
696 nodeId: limitedNode,
697 status: "failed",
698 failure: {
699 class: "usage_limit",
700 message: "Plan limit reached.",
701 code: "usageLimitExceeded",
702 retryable: null,
703 resetAt: "2026-06-20T05:00:00.000Z",
704 },
705 } as unknown as OrchestrationV2TurnItem;
706 const wakes = Array.from({ length: 6 }, (_, index) => {
707 const nodeId = NodeId.make(`node-wake-${index}`);
708 const run = {
709 ...limited,
710 id: RunId.make(`run-wake-${index}`),
711 ordinal: index + 2,
712 status: "completed",
713 completedAt: DateTime.add(NOW, { seconds: index + 1 }),
714 rootNodeId: nodeId,
715 };
716 const row = makeRow(index + 1);
717 const item = {
718 ...row.item,
719 id: TurnItemId.make(`wake-notification-${index}`),
720 type: "notification",
721 runId: run.id,
722 nodeId,
723 source: { kind: "delegated_task", taskIds: [] },
724 outcome: "failed",
725 summary: "Subagent failed",
726 detail: "d".repeat(50_000),
727 } as unknown as OrchestrationV2TurnItem;
728 return { run, row: { ...row, sourceItemId: item.id, item } };
729 });
730 const rows = [{ ...makeRow(0), sourceItemId: limitError.id, item: limitError }].concat(
731 wakes.map(({ row }) => row),
732 );
733 const full = {
734 ...makeProjection(rows),
735 runs: [limited, ...wakes.map(({ run }) => run)],
736 } as unknown as ReturnType<typeof makeProjection>;
737 const bounded = buildBoundedThreadProjection({
738 projection: full,
739 snapshotSequence: 1,
740 policy: { maxItems: 2, maxEncodedBytes: 10_000_000 },
741 });
742​
743 expect(bounded.projection.visibleTurnItems).toHaveLength(2);
744 expect(
745 usageLimitBlockedRun(bounded.projection.runs, bounded.projection.turnItems, null)?.id,
746 ).toBe(limited.id);
747 // Retained wake starts are stubs: a 50 KB notification detail must not reach the snapshot.
748 const visibleIds = new Set(bounded.projection.visibleTurnItems.map((row) => row.sourceItemId));
749 const retained = bounded.projection.turnItems.filter((item) => !visibleIds.has(item.id));
750 expect(retained.length).toBeGreaterThan(0);
751 expect(JSON.stringify(retained).length).toBeLessThan(10_000);
752​
753 // Evidence past a quarter of the budget is dropped, so the snapshot stays within it.
754 const tight = buildBoundedThreadProjection({
755 projection: full,
756 snapshotSequence: 1,
757 policy: { maxItems: 2, maxEncodedBytes: 8_000 },
758 });
759 expect(
760 usageLimitBlockedRun(tight.projection.runs, tight.projection.turnItems, null),
761 ).toBeNull();
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});