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

threadHistoryPaging.test.ts

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