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

threadHistoryPaging.test.ts

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