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

threadHistoryPaging.test.ts

919 lines30.7 KB

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