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

threadHistoryPaging.test.ts

735 lines24.9 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 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 makeProjection(visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) {
114 return {
115 thread: {
116 id: THREAD,
117 projectId: "project-1",
118 title: "Thread",
119 providerInstanceId: "codex",
120 modelSelection: { instanceId: "codex", model: "gpt-5" },
121 runtimeMode: "full-access",
122 interactionMode: "default",
123 branch: null,
124 worktreePath: null,
125 activeProviderThreadId: null,
126 lineage: {
127 parentThreadId: null,
128 relationshipToParent: null,
129 rootThreadId: THREAD,
130 },
131 forkedFrom: null,
132 createdBy: "user",
133 creationSource: "web",
134 createdAt: NOW,
135 updatedAt: NOW,
136 archivedAt: null,
137 deletedAt: null,
138 settledOverride: null,
139 settledAt: null,
140 },
141 runs: [{ id: "run-1" }],
142 attempts: [{ id: "attempt-1" }],
143 nodes: [],
144 subagents: [],
145 providerSessions: [],
146 providerThreads: [],
147 providerTurns: [],
148 runtimeRequests: [{ id: "req-1" }],
149 messages: [],
150 plans: [],
151 turnItems: visibleTurnItems.map((row) => row.item),
152 checkpointScopes: [],
153 checkpoints: [],
154 contextHandoffs: [],
155 contextTransfers: [],
156 visibleTurnItems,
157 updatedAt: NOW,
158 } as unknown as Parameters<typeof buildBoundedThreadProjection>[0]["projection"];
160​
161describe("threadHistoryPaging", () => {
162 it("builds a resumable bounded socket snapshot frame", () => {
163 const projection = makeProjection(Array.from({ length: 90 }, (_, index) => makeRow(index)));
164 const item = buildBoundedThreadStreamSnapshot({
165 snapshotSequence: 23,
166 projection,
167 });
168​
169 expect(item.kind).toBe("snapshot");
170 expect(item.snapshotSequence).toBe(23);
171 expect(item.projection.visibleTurnItems).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
172 expect(item.historyCursor).not.toBeNull();
173 expect(item.hasMoreHistory).toBe(true);
174 expect(item.latestLocalTurnOrdinal).toBe(90);
175 expect(item.payloadBudgetExceeded).toBe(false);
176 });
177​
178 it("keeps background turns with user turns, with main's 150-turn fan-out ceiling", () => {
179 const items = Array.from({ length: 161 }, (_, turn) => {
180 const row = makeRow(turn * 2);
181 if (row.item.type !== "command_execution") throw new Error("Expected command fixture");
182 const prompt: OrchestrationV2ProjectedTurnItem = {
183 ...row,
184 item: {
185 ...row.item,
186 type: "user_message",
187 createdBy: turn === 0 ? "user" : "agent",
188 creationSource: "provider",
189 inputIntent: "turn_start",
190 messageId: MessageId.make(`prompt-${turn}`),
191 text: `Prompt ${turn}`,
192 attachments: [],
193 },
194 };
195 return [prompt, makeRow(turn * 2 + 1)];
196 }).flat();
197 const first = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
198 expect(first.items).toHaveLength(300);
199 expect(first.items[0]?.sourceItemId).toBe("item-22");
200 const older = selectHistoryPageFromCursor({
201 items,
202 cursor: first.nextCursor!,
203 snapshotSequence: 1,
204 });
205 expect(older.items).toHaveLength(22);
206 expect(older.hasMoreHistory).toBe(false);
207 expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual(
208 items.map((row) => row.sourceItemId),
209 );
210 });
211​
212 it("counts runs that a notification started toward the 150-turn ceiling", () => {
213 const inRun = (index: number, run: number, item: object = {}) => {
214 const row = makeRow(index);
215 return {
216 ...row,
217 item: { ...row.item, runId: RunId.make(`run-${run}`), ...item },
218 } as OrchestrationV2ProjectedTurnItem;
219 };
220 const notification = (summary: string) => ({
221 type: "notification",
222 source: { kind: "monitor" },
223 outcome: "completed",
224 summary,
225 });
226 const items = Array.from({ length: 161 }, (_, run) => [
227 inRun(run * 4, run),
228 inRun(
229 run * 4 + 1,
230 run,
231 run === 0
232 ? {
233 type: "user_message",
234 createdBy: "user",
235 creationSource: "web",
236 inputIntent: "turn_start",
237 messageId: MessageId.make("prompt-0"),
238 text: "Prompt 0",
239 attachments: [],
240 }
241 : notification(`Wake ${run}`),
242 ),
243 inRun(run * 4 + 2, run, notification(`Steer ${run}`)),
244 inRun(run * 4 + 3, run),
245 ]).flat();
246 const first = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
247 expect(first.items).toHaveLength(150 * 4 - 1);
248 expect(first.items[0]?.sourceItemId).toBe(`item-${11 * 4 + 1}`);
249 const older = selectHistoryPageFromCursor({
250 items,
251 cursor: first.nextCursor!,
252 snapshotSequence: 1,
253 });
254 expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual(
255 items.map((row) => row.sourceItemId),
256 );
257 });
258​
259 it("pages agent-only child transcripts instead of dropping their earlier activity", () => {
260 const commandRows = Array.from({ length: 90 }, (_, index) => makeRow(index + 1));
261 const first = makeRow(0);
262 const prompt = {
263 ...first,
264 item: {
265 ...first.item,
266 type: "user_message" as const,
267 createdBy: "agent" as const,
268 creationSource: "provider" as const,
269 inputIntent: "turn_start" as const,
270 messageId: MessageId.make("child-prompt"),
271 text: "Inspect this project",
272 attachments: [],
273 },
274 } as OrchestrationV2ProjectedTurnItem;
275 const items = [prompt, ...commandRows];
276 const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
277​
278 expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
279 expect(recent.hasMoreHistory).toBe(true);
280 const older = selectHistoryPageFromCursor({
281 items,
282 cursor: recent.nextCursor!,
283 snapshotSequence: 1,
284 });
285 expect(older.items[0]?.item.type).toBe("user_message");
286 expect([...older.items, ...recent.items]).toHaveLength(items.length);
287 });
288​
289 it("encodes opaque cursors with stable source identity", () => {
290 const cursor = encodeThreadHistoryCursor({
291 snapshotSequence: 9,
292 sourceThreadId: THREAD,
293 sourceItemId: TurnItemId.make("item-3"),
294 position: 3,
295 });
296 expect(cursor.includes("{")).toBe(false);
297 expect(decodeThreadHistoryCursor(cursor)).toEqual({
298 v: 1,
299 seq: 9,
300 st: "thread-1",
301 si: "item-3",
302 p: 3,
303 });
304 });
305​
306 it("rejects malformed cursors", () => {
307 expect(() => decodeThreadHistoryCursor("not-valid")).toThrow(InvalidThreadHistoryCursorError);
308 expect(() =>
309 decodeThreadHistoryCursor(Buffer.from("{}", "utf8").toString("base64url")),
310 ).toThrow(InvalidThreadHistoryCursorError);
311 });
312​
313 it("rejects cursors longer than the maximum length before decoding", () => {
314 const oversized = "A".repeat(THREAD_HISTORY_CURSOR_MAX_LENGTH + 1);
315 expect(() => decodeThreadHistoryCursor(oversized)).toThrow(InvalidThreadHistoryCursorError);
316 });
317​
318 it("selects a recent window by item count", () => {
319 const items = Array.from({ length: 120 }, (_, index) => makeRow(index));
320 const page = selectRecentTimelineWindow({
321 items,
322 snapshotSequence: 4,
323 policy: { maxItems: 10, maxEncodedBytes: 10_000_000 },
324 });
325 expect(page.items).toHaveLength(10);
326 expect(page.items[0]?.sourceItemId).toBe("item-110");
327 expect(page.items[9]?.sourceItemId).toBe("item-119");
328 expect(page.hasMoreHistory).toBe(true);
329 expect(page.nextCursor).not.toBeNull();
330 const cursor = decodeThreadHistoryCursor(page.nextCursor!);
331 expect(cursor.si).toBe("item-110");
332 expect(cursor.seq).toBe(4);
333 });
334​
335 it("always includes at least one pathological oversized item", () => {
336 const items = [makeRow(0, { outputBytes: 2_000_000 }), makeRow(1, { outputBytes: 10 })];
337 const page = selectRecentTimelineWindow({
338 items,
339 snapshotSequence: 1,
340 policy: { maxItems: 50, maxEncodedBytes: 1_024 },
341 });
342 expect(page.items).toHaveLength(1);
343 expect(page.items[0]?.sourceItemId).toBe("item-1");
344 expect(page.hasMoreHistory).toBe(true);
345​
346 const older = selectHistoryPageFromCursor({
347 items,
348 cursor: page.nextCursor!,
349 snapshotSequence: 1,
350 policy: { maxItems: 50, maxEncodedBytes: 1_024 },
351 });
352 expect(older.items).toHaveLength(1);
353 expect(older.items[0]?.sourceItemId).toBe("item-0");
354 expect(older.hasMoreHistory).toBe(false);
355 expect(older.nextCursor).toBeNull();
356 });
357​
358 it("recovers identity-miss cursors when position is past a shrunken timeline", () => {
359 const items = Array.from({ length: 5 }, (_, index) => makeRow(index));
360 const cursor = encodeThreadHistoryCursor({
361 snapshotSequence: 3,
362 sourceThreadId: THREAD,
363 sourceItemId: TurnItemId.make("item-deleted-long-ago"),
364 position: 40,
365 });
366 const page = selectHistoryPageFromCursor({
367 items,
368 cursor,
369 snapshotSequence: 3,
370 policy: { maxItems: 2, maxEncodedBytes: 10_000_000 },
371 });
372 expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]);
373 expect(page.hasMoreHistory).toBe(true);
374 expect(page.nextCursor).not.toBeNull();
375 });
376​
377 it("keeps cursor resolution stable when newer items append", () => {
378 const initial = Array.from({ length: 20 }, (_, index) => makeRow(index));
379 const recent = selectRecentTimelineWindow({
380 items: initial,
381 snapshotSequence: 2,
382 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
383 });
384 const cursor = recent.nextCursor!;
385 const grown = [...initial, makeRow(20), makeRow(21)];
386 const older = selectHistoryPageFromCursor({
387 items: grown,
388 cursor,
389 snapshotSequence: 5,
390 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
391 });
392 expect(older.items.map((row) => row.sourceItemId)).toEqual([
393 "item-10",
394 "item-11",
395 "item-12",
396 "item-13",
397 "item-14",
398 ]);
399 expect(older.hasMoreHistory).toBe(true);
400 });
401​
402 it("builds a bounded projection that preserves non-timeline control state", () => {
403 const full = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
404 const bounded = buildBoundedThreadProjection({
405 projection: full,
406 snapshotSequence: 7,
407 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
408 });
409 expect(bounded.projection.runs).toEqual(full.runs);
410 expect(bounded.projection.runtimeRequests).toEqual(full.runtimeRequests);
411 expect(bounded.projection.attempts).toEqual(full.attempts);
412 expect(bounded.projection.visibleTurnItems).toHaveLength(5);
413 expect(bounded.projection.turnItems).toHaveLength(5);
414 expect(bounded.hasMoreHistory).toBe(true);
415 expect(bounded.historyCursor).not.toBeNull();
416 expect(bounded.projection.visibleTurnItems.map((row) => row.position)).toEqual([0, 1, 2, 3, 4]);
417 expect(bounded.latestLocalTurnOrdinal).toBe(40);
418 expect(computeLatestLocalTurnOrdinal(full.turnItems)).toBe(40);
419 });
420​
421 it("preserves linked control rows as one coherent graph", () => {
422 const base = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
423 const linked = {
424 ...base,
425 runs: [{ id: "run-linked", threadId: THREAD }],
426 attempts: [{ id: "attempt-linked", runId: "run-linked" }],
427 nodes: [{ id: "node-linked", runId: "run-linked", attemptId: "attempt-linked" }],
428 providerThreads: [{ id: "provider-thread-linked", runId: "run-linked" }],
429 providerTurns: [
430 {
431 id: "provider-turn-linked",
432 providerThreadId: "provider-thread-linked",
433 nodeId: "node-linked",
434 },
435 ],
436 checkpointScopes: [{ id: "scope-linked", runId: "run-linked" }],
437 checkpoints: [{ id: "checkpoint-linked", scopeId: "scope-linked" }],
438 } as unknown as typeof base;
439​
440 const bounded = buildBoundedThreadProjection({
441 projection: linked,
442 snapshotSequence: 7,
443 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
444 });
445​
446 expect(bounded.projection.runs).toEqual(linked.runs);
447 expect(bounded.projection.attempts).toEqual(linked.attempts);
448 expect(bounded.projection.nodes).toEqual(linked.nodes);
449 expect(bounded.projection.providerThreads).toEqual(linked.providerThreads);
450 expect(bounded.projection.providerTurns).toEqual(linked.providerTurns);
451 expect(bounded.projection.checkpointScopes).toEqual(linked.checkpointScopes);
452 expect(bounded.projection.checkpoints).toEqual(linked.checkpoints);
453 });
454​
455 it("carries a full-projection watermark when the bounded window is inherited-only", () => {
456 const localOlder = makeRow(0);
457 const localMid = makeRow(1);
458 const inherited = {
459 ...makeRow(2),
460 visibility: "inherited" as const,
461 sourceThreadId: ThreadId.make("parent-thread"),
462 item: {
463 ...makeRow(2).item,
464 threadId: ThreadId.make("parent-thread"),
465 },
466 };
467 const full = makeProjection([localOlder, localMid, inherited]);
468 const inheritedOnly = {
469 ...full,
470 visibleTurnItems: [inherited],
471 turnItems: [localOlder.item, localMid.item],
472 };
473 const bounded = buildBoundedThreadProjection({
474 projection: inheritedOnly,
475 snapshotSequence: 2,
476 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
477 });
478 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
479 String(inherited.sourceItemId),
480 ]);
481 expect(bounded.latestLocalTurnOrdinal).toBe(2);
482 expect(computeLatestLocalTurnOrdinal([])).toBeNull();
483 });
484​
485 it("retains an out-of-window run_interrupt_request needed by a visible result", () => {
486 const request = interruptRow(0, "run_interrupt_request");
487 const filler = makeRow(1);
488 const result = interruptRow(2, "run_interrupt_result");
489 const full = makeProjection([request, filler, result]);
490 const bounded = buildBoundedThreadProjection({
491 projection: full,
492 snapshotSequence: 3,
493 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
494 });
495​
496 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
497 "interrupt-res",
498 ]);
499 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
500 "interrupt-req",
501 "interrupt-res",
502 ]);
503 expect(bounded.hasMoreHistory).toBe(true);
504 });
505​
506 it("retains all run_interrupt_request items even when no result is in the initial window", () => {
507 const request = interruptRow(0, "run_interrupt_request");
508 const result = interruptRow(1, "run_interrupt_result");
509 const recent = makeRow(2);
510 const full = makeProjection([request, result, recent]);
511 const bounded = buildBoundedThreadProjection({
512 projection: full,
513 snapshotSequence: 4,
514 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
515 });
516​
517 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
518 "item-2",
519 ]);
520 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
521 "interrupt-req",
522 "item-2",
523 ]);
524 expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(
525 true,
526 );
527 expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(
528 false,
529 );
530 });
531​
532 it("charges local row.item duplication when measuring bounded timeline bytes", () => {
533 const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 }));
534 const full = makeProjection(rows);
535 const maxEncodedBytes = 12_000;
536 const bounded = buildBoundedThreadProjection({
537 projection: full,
538 snapshotSequence: 1,
539 policy: { maxItems: 50, maxEncodedBytes },
540 });
541​
542 const contribution = boundedTimelineEncodedBytes({
543 visibleTurnItems: bounded.projection.visibleTurnItems,
544 turnItems: bounded.projection.turnItems,
545 });
546 expect(contribution).toBeLessThanOrEqual(maxEncodedBytes);
547 expect(bounded.projection.visibleTurnItems.length).toBeGreaterThan(0);
548 expect(bounded.projection.visibleTurnItems.length).toBeLessThan(rows.length);
549​
550 const historyPage = selectRecentTimelineWindow({
551 items: rows,
552 snapshotSequence: 1,
553 policy: { maxItems: 50, maxEncodedBytes },
554 });
555 const historyBytes = historyPage.items.reduce(
556 (sum, row) => sum + projectedRowEncodedBytes(row),
557 0,
558 );
559 expect(historyBytes).toBeLessThanOrEqual(maxEncodedBytes);
560 expect(historyPage.items.length).toBeGreaterThan(bounded.projection.visibleTurnItems.length);
561​
562 const sample = rows[0]!;
563 expect(projectedRowBoundedSnapshotEncodedBytes(sample, THREAD)).toBeGreaterThan(
564 projectedRowEncodedBytes(sample),
565 );
566 });
567​
568 it("allows a single pathological bounded row to exceed the configured cap", () => {
569 const huge = makeRow(0, { outputBytes: 50_000 });
570 const full = makeProjection([huge]);
571 const maxEncodedBytes = 1_000;
572 const bounded = buildBoundedThreadProjection({
573 projection: full,
574 snapshotSequence: 1,
575 policy: { maxItems: 10, maxEncodedBytes },
576 });
577 expect(bounded.projection.visibleTurnItems).toHaveLength(1);
578 const contribution = boundedTimelineEncodedBytes({
579 visibleTurnItems: bounded.projection.visibleTurnItems,
580 turnItems: bounded.projection.turnItems,
581 });
582 expect(contribution).toBeGreaterThan(maxEncodedBytes);
583 });
584​
585 it("exposes conservative default page budgets", () => {
586 expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeGreaterThanOrEqual(50);
587 expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeLessThanOrEqual(100);
588 expect(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes).toBe(1_048_576);
589 });
590​
591 it("does not carry the full duplicated message table into a bounded snapshot", () => {
592 const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index)));
593 const full = {
594 ...projection,
595 messages: Array.from({ length: 2_000 }, (_, index) => ({
596 id: MessageId.make(`message-${index}`),
597 threadId: THREAD,
598 runId: RunId.make(`old-run-${index}`),
599 nodeId: null,
600 role: "assistant" as const,
601 text: "x".repeat(1_000),
602 attachments: [],
603 streaming: false,
604 createdBy: "agent" as const,
605 creationSource: "provider" as const,
606 createdAt: NOW,
607 updatedAt: NOW,
608 })),
609 } as typeof projection;
610​
611 const bounded = buildBoundedThreadProjection({
612 projection: full,
613 snapshotSequence: 9,
614 });
615​
616 expect(bounded.projection.messages).toEqual([]);
617 expect(Buffer.byteLength(JSON.stringify(bounded.projection), "utf8")).toBeLessThan(
618 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes + 100_000,
619 );
620 });
621​
622 it("omits historical control details that remain available from history items", () => {
623 const projection = makeProjection(Array.from({ length: 200 }, (_, index) => makeRow(index)));
624 const populated = {
625 ...projection,
626 plans: Array.from({ length: 120 }, (_, index) => ({
627 id: `plan-${index}`,
628 threadId: THREAD,
629 runId: null,
630 nodeId: `node-${index}`,
631 status: "completed",
632 kind: "proposed_plan",
633 markdown: "p".repeat(2_097_152),
634 })),
635 contextHandoffs: Array.from({ length: 120 }, (_, index) => ({
636 id: `handoff-${index}`,
637 threadId: THREAD,
638 targetRunId: "run-1",
639 fromProviderThreadIds: [],
640 toProviderThreadId: "provider-thread-1",
641 coveredRunOrdinals: { from: 1, to: 1 },
642 strategy: "manual_context",
643 status: "superseded",
644 summaryMessageId: null,
645 summaryText: "h".repeat(2_097_152),
646 createdByProviderInstanceId: null,
647 createdAt: NOW,
648 updatedAt: NOW,
649 })),
650 } as unknown as typeof projection;
651​
652 const bounded = buildBoundedThreadProjection({
653 projection: projectThreadProjectionForWire(populated),
654 snapshotSequence: 9,
655 });
656 const serializedBytes = Buffer.byteLength(JSON.stringify(bounded.projection), "utf8");
657​
658 expect(serializedBytes).toBeLessThanOrEqual(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes);
659 expect(bounded.payloadBudgetExceeded).toBe(false);
660 expect(bounded.projection.plans).toEqual([]);
661 expect(bounded.projection.contextHandoffs).toEqual([]);
662 expect(populated.plans).toHaveLength(120);
663 expect(
664 populated.plans[0]?.kind === "proposed_plan" ? populated.plans[0].markdown.length : 0,
665 ).toBe(2_097_152);
666 });
667​
668 it("preserves oversized actionable state and reports the budget exception", () => {
669 const projection = makeProjection([makeRow(0)]);
670 const actionable = {
671 ...projection,
672 plans: [
673 {
674 id: "plan-actionable",
675 threadId: THREAD,
676 runId: null,
677 nodeId: "node-actionable",
678 status: "active",
679 kind: "proposed_plan",
680 markdown: "a".repeat(2_097_152),
681 },
682 ],
683 } as unknown as typeof projection;
684​
685 const bounded = buildBoundedThreadProjection({ projection: actionable, snapshotSequence: 9 });
686​
687 expect(bounded.payloadBudgetExceeded).toBe(true);
688 expect(bounded.projection.plans[0]).toEqual(actionable.plans[0]);
689 expect(bounded.projection.visibleTurnItems).toEqual(actionable.visibleTurnItems);
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 expect(bounded.payloadBudgetExceeded).toBe(false);
734 });
735});