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

threadHistoryPaging.test.ts

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