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