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

threadHistoryPaging.test.ts

703 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 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("pages agent-only child transcripts instead of dropping their earlier activity", () => {
213 const commandRows = Array.from({ length: 90 }, (_, index) => makeRow(index + 1));
214 const first = makeRow(0);
215 const prompt = {
216 ...first,
217 item: {
218 ...first.item,
219 type: "user_message" as const,
220 createdBy: "agent" as const,
221 creationSource: "provider" as const,
222 inputIntent: "turn_start" as const,
223 messageId: MessageId.make("child-prompt"),
224 text: "Inspect this project",
225 attachments: [],
226 },
227 } as OrchestrationV2ProjectedTurnItem;
228 const items = [prompt, ...commandRows];
229 const recent = selectRecentTimelineWindow({ items, snapshotSequence: 1 });
230​
231 expect(recent.items).toHaveLength(THREAD_HISTORY_PAGE_POLICY.maxItems);
232 expect(recent.hasMoreHistory).toBe(true);
233 const older = selectHistoryPageFromCursor({
234 items,
235 cursor: recent.nextCursor!,
236 snapshotSequence: 1,
237 });
238 expect(older.items[0]?.item.type).toBe("user_message");
239 expect([...older.items, ...recent.items]).toHaveLength(items.length);
240 });
241​
242 it("encodes opaque cursors with stable source identity", () => {
243 const cursor = encodeThreadHistoryCursor({
244 snapshotSequence: 9,
245 sourceThreadId: THREAD,
246 sourceItemId: TurnItemId.make("item-3"),
247 position: 3,
248 });
249 expect(cursor.includes("{")).toBe(false);
250 expect(decodeThreadHistoryCursor(cursor)).toEqual({
251 v: 1,
252 seq: 9,
253 st: "thread-1",
254 si: "item-3",
255 p: 3,
256 });
257 });
258​
259 it("rejects malformed cursors", () => {
260 expect(() => decodeThreadHistoryCursor("not-valid")).toThrow(InvalidThreadHistoryCursorError);
261 expect(() =>
262 decodeThreadHistoryCursor(Buffer.from("{}", "utf8").toString("base64url")),
263 ).toThrow(InvalidThreadHistoryCursorError);
264 });
265​
266 it("rejects cursors longer than the maximum length before decoding", () => {
267 const oversized = "A".repeat(THREAD_HISTORY_CURSOR_MAX_LENGTH + 1);
268 expect(() => decodeThreadHistoryCursor(oversized)).toThrow(InvalidThreadHistoryCursorError);
269 });
270​
271 it("selects a recent window by item count", () => {
272 const items = Array.from({ length: 120 }, (_, index) => makeRow(index));
273 const page = selectRecentTimelineWindow({
274 items,
275 snapshotSequence: 4,
276 policy: { maxItems: 10, maxEncodedBytes: 10_000_000 },
277 });
278 expect(page.items).toHaveLength(10);
279 expect(page.items[0]?.sourceItemId).toBe("item-110");
280 expect(page.items[9]?.sourceItemId).toBe("item-119");
281 expect(page.hasMoreHistory).toBe(true);
282 expect(page.nextCursor).not.toBeNull();
283 const cursor = decodeThreadHistoryCursor(page.nextCursor!);
284 expect(cursor.si).toBe("item-110");
285 expect(cursor.seq).toBe(4);
286 });
287​
288 it("always includes at least one pathological oversized item", () => {
289 const items = [makeRow(0, { outputBytes: 2_000_000 }), makeRow(1, { outputBytes: 10 })];
290 const page = selectRecentTimelineWindow({
291 items,
292 snapshotSequence: 1,
293 policy: { maxItems: 50, maxEncodedBytes: 1_024 },
294 });
295 expect(page.items).toHaveLength(1);
296 expect(page.items[0]?.sourceItemId).toBe("item-1");
297 expect(page.hasMoreHistory).toBe(true);
298​
299 const older = selectHistoryPageFromCursor({
300 items,
301 cursor: page.nextCursor!,
302 snapshotSequence: 1,
303 policy: { maxItems: 50, maxEncodedBytes: 1_024 },
304 });
305 expect(older.items).toHaveLength(1);
306 expect(older.items[0]?.sourceItemId).toBe("item-0");
307 expect(older.hasMoreHistory).toBe(false);
308 expect(older.nextCursor).toBeNull();
309 });
310​
311 it("recovers identity-miss cursors when position is past a shrunken timeline", () => {
312 const items = Array.from({ length: 5 }, (_, index) => makeRow(index));
313 const cursor = encodeThreadHistoryCursor({
314 snapshotSequence: 3,
315 sourceThreadId: THREAD,
316 sourceItemId: TurnItemId.make("item-deleted-long-ago"),
317 position: 40,
318 });
319 const page = selectHistoryPageFromCursor({
320 items,
321 cursor,
322 snapshotSequence: 3,
323 policy: { maxItems: 2, maxEncodedBytes: 10_000_000 },
324 });
325 // Clamp exclusive end to items.length and page backward so the client can
326 // dedupe and advance rather than permanently 400 on a dead cursor.
327 expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]);
328 expect(page.hasMoreHistory).toBe(true);
329 expect(page.nextCursor).not.toBeNull();
330 });
331​
332 it("keeps cursor resolution stable when newer items append", () => {
333 const initial = Array.from({ length: 20 }, (_, index) => makeRow(index));
334 const recent = selectRecentTimelineWindow({
335 items: initial,
336 snapshotSequence: 2,
337 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
338 });
339 const cursor = recent.nextCursor!;
340 const grown = [...initial, makeRow(20), makeRow(21)];
341 const older = selectHistoryPageFromCursor({
342 items: grown,
343 cursor,
344 snapshotSequence: 5,
345 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
346 });
347 expect(older.items.map((row) => row.sourceItemId)).toEqual([
348 "item-10",
349 "item-11",
350 "item-12",
351 "item-13",
352 "item-14",
353 ]);
354 expect(older.hasMoreHistory).toBe(true);
355 });
356​
357 it("builds a bounded projection that preserves non-timeline control state", () => {
358 const full = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
359 const bounded = buildBoundedThreadProjection({
360 projection: full,
361 snapshotSequence: 7,
362 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
363 });
364 expect(bounded.projection.runs).toEqual(full.runs);
365 expect(bounded.projection.runtimeRequests).toEqual(full.runtimeRequests);
366 expect(bounded.projection.attempts).toEqual(full.attempts);
367 expect(bounded.projection.visibleTurnItems).toHaveLength(5);
368 expect(bounded.projection.turnItems).toHaveLength(5);
369 expect(bounded.hasMoreHistory).toBe(true);
370 expect(bounded.historyCursor).not.toBeNull();
371 expect(bounded.projection.visibleTurnItems.map((row) => row.position)).toEqual([0, 1, 2, 3, 4]);
372 // Watermark comes from the full projection, not the trimmed window.
373 expect(bounded.latestLocalTurnOrdinal).toBe(40);
374 expect(computeLatestLocalTurnOrdinal(full.turnItems)).toBe(40);
375 });
376​
377 it("preserves linked control rows as one coherent graph", () => {
378 const base = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
379 const linked = {
380 ...base,
381 runs: [{ id: "run-linked", threadId: THREAD }],
382 attempts: [{ id: "attempt-linked", runId: "run-linked" }],
383 nodes: [{ id: "node-linked", runId: "run-linked", attemptId: "attempt-linked" }],
384 providerThreads: [{ id: "provider-thread-linked", runId: "run-linked" }],
385 providerTurns: [
386 {
387 id: "provider-turn-linked",
388 providerThreadId: "provider-thread-linked",
389 nodeId: "node-linked",
390 },
391 ],
392 checkpointScopes: [{ id: "scope-linked", runId: "run-linked" }],
393 checkpoints: [{ id: "checkpoint-linked", scopeId: "scope-linked" }],
394 } as unknown as typeof base;
395​
396 const bounded = buildBoundedThreadProjection({
397 projection: linked,
398 snapshotSequence: 7,
399 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
400 });
401​
402 expect(bounded.projection.runs).toEqual(linked.runs);
403 expect(bounded.projection.attempts).toEqual(linked.attempts);
404 expect(bounded.projection.nodes).toEqual(linked.nodes);
405 expect(bounded.projection.providerThreads).toEqual(linked.providerThreads);
406 expect(bounded.projection.providerTurns).toEqual(linked.providerTurns);
407 expect(bounded.projection.checkpointScopes).toEqual(linked.checkpointScopes);
408 expect(bounded.projection.checkpoints).toEqual(linked.checkpoints);
409 });
410​
411 it("carries a full-projection watermark when the bounded window is inherited-only", () => {
412 const localOlder = makeRow(0);
413 const localMid = makeRow(1);
414 const inherited = {
415 ...makeRow(2),
416 visibility: "inherited" as const,
417 sourceThreadId: ThreadId.make("parent-thread"),
418 item: {
419 ...makeRow(2).item,
420 threadId: ThreadId.make("parent-thread"),
421 },
422 };
423 // Full projection still has local turnItems even if the recent window is
424 // only the inherited row (e.g. after aggressive byte budget on a large
425 // local item that is not selected into the recent page). Use a synthetic
426 // projection with local turnItems and inherited-only visible window.
427 const full = makeProjection([localOlder, localMid, inherited]);
428 // Force an inherited-only visible window by rebuilding with only inherited
429 // visible rows while retaining full local turnItems for the watermark.
430 const inheritedOnly = {
431 ...full,
432 visibleTurnItems: [inherited],
433 turnItems: [localOlder.item, localMid.item],
434 };
435 const bounded = buildBoundedThreadProjection({
436 projection: inheritedOnly,
437 snapshotSequence: 2,
438 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
439 });
440 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
441 String(inherited.sourceItemId),
442 ]);
443 expect(bounded.latestLocalTurnOrdinal).toBe(2);
444 expect(computeLatestLocalTurnOrdinal([])).toBeNull();
445 });
446​
447 it("retains an out-of-window run_interrupt_request needed by a visible result", () => {
448 // Older request sits outside a 1-row recent window; result is visible alone.
449 const request = interruptRow(0, "run_interrupt_request");
450 const filler = makeRow(1);
451 const result = interruptRow(2, "run_interrupt_result");
452 const full = makeProjection([request, filler, result]);
453 const bounded = buildBoundedThreadProjection({
454 projection: full,
455 snapshotSequence: 3,
456 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
457 });
458​
459 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
460 "interrupt-res",
461 ]);
462 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
463 "interrupt-req",
464 "interrupt-res",
465 ]);
466 expect(bounded.hasMoreHistory).toBe(true);
467 });
468​
469 it("retains all run_interrupt_request items even when no result is in the initial window", () => {
470 // Cold open: recent window is only filler. Request and result both live on
471 // older pages, but the request must still ride in turnItems so a later
472 // history page can introduce the result safely under live attempt updates.
473 const request = interruptRow(0, "run_interrupt_request");
474 const result = interruptRow(1, "run_interrupt_result");
475 const recent = makeRow(2);
476 const full = makeProjection([request, result, recent]);
477 const bounded = buildBoundedThreadProjection({
478 projection: full,
479 snapshotSequence: 4,
480 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
481 });
482​
483 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
484 "item-2",
485 ]);
486 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
487 "interrupt-req",
488 "item-2",
489 ]);
490 expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(
491 true,
492 );
493 expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(
494 false,
495 );
496 });
497​
498 it("charges local row.item duplication when measuring bounded timeline bytes", () => {
499 const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 }));
500 const full = makeProjection(rows);
501 const maxEncodedBytes = 12_000;
502 const bounded = buildBoundedThreadProjection({
503 projection: full,
504 snapshotSequence: 1,
505 policy: { maxItems: 50, maxEncodedBytes },
506 });
507​
508 const contribution = boundedTimelineEncodedBytes({
509 visibleTurnItems: bounded.projection.visibleTurnItems,
510 turnItems: bounded.projection.turnItems,
511 });
512 expect(contribution).toBeLessThanOrEqual(maxEncodedBytes);
513 expect(bounded.projection.visibleTurnItems.length).toBeGreaterThan(0);
514 expect(bounded.projection.visibleTurnItems.length).toBeLessThan(rows.length);
515​
516 // History pages only charge the projected row once (no turnItems copy).
517 const historyPage = selectRecentTimelineWindow({
518 items: rows,
519 snapshotSequence: 1,
520 policy: { maxItems: 50, maxEncodedBytes },
521 });
522 const historyBytes = historyPage.items.reduce(
523 (sum, row) => sum + projectedRowEncodedBytes(row),
524 0,
525 );
526 expect(historyBytes).toBeLessThanOrEqual(maxEncodedBytes);
527 expect(historyPage.items.length).toBeGreaterThan(bounded.projection.visibleTurnItems.length);
528​
529 // Dual-cost for one local row exceeds the plain row cost.
530 const sample = rows[0]!;
531 expect(projectedRowBoundedSnapshotEncodedBytes(sample, THREAD)).toBeGreaterThan(
532 projectedRowEncodedBytes(sample),
533 );
534 });
535​
536 it("allows a single pathological bounded row to exceed the configured cap", () => {
537 const huge = makeRow(0, { outputBytes: 50_000 });
538 const full = makeProjection([huge]);
539 const maxEncodedBytes = 1_000;
540 const bounded = buildBoundedThreadProjection({
541 projection: full,
542 snapshotSequence: 1,
543 policy: { maxItems: 10, maxEncodedBytes },
544 });
545 expect(bounded.projection.visibleTurnItems).toHaveLength(1);
546 const contribution = boundedTimelineEncodedBytes({
547 visibleTurnItems: bounded.projection.visibleTurnItems,
548 turnItems: bounded.projection.turnItems,
549 });
550 expect(contribution).toBeGreaterThan(maxEncodedBytes);
551 });
552​
553 it("exposes conservative default page budgets", () => {
554 expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeGreaterThanOrEqual(50);
555 expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeLessThanOrEqual(100);
556 expect(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes).toBe(1_048_576);
557 });
558​
559 it("does not carry the full duplicated message table into a bounded snapshot", () => {
560 const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index)));
561 const full = {
562 ...projection,
563 messages: Array.from({ length: 2_000 }, (_, index) => ({
564 id: MessageId.make(`message-${index}`),
565 threadId: THREAD,
566 runId: RunId.make(`old-run-${index}`),
567 nodeId: null,
568 role: "assistant" as const,
569 text: "x".repeat(1_000),
570 attachments: [],
571 streaming: false,
572 createdBy: "agent" as const,
573 creationSource: "provider" as const,
574 createdAt: NOW,
575 updatedAt: NOW,
576 })),
577 } as typeof projection;
578​
579 const bounded = buildBoundedThreadProjection({
580 projection: full,
581 snapshotSequence: 9,
582 });
583​
584 expect(bounded.projection.messages).toEqual([]);
585 expect(Buffer.byteLength(JSON.stringify(bounded.projection), "utf8")).toBeLessThan(
586 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes + 100_000,
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.payloadBudgetExceeded).toBe(false);
628 expect(bounded.projection.plans).toEqual([]);
629 expect(bounded.projection.contextHandoffs).toEqual([]);
630 expect(populated.plans).toHaveLength(120);
631 expect(
632 populated.plans[0]?.kind === "proposed_plan" ? populated.plans[0].markdown.length : 0,
633 ).toBe(2_097_152);
634 });
635​
636 it("preserves oversized actionable state and reports the budget exception", () => {
637 const projection = makeProjection([makeRow(0)]);
638 const actionable = {
639 ...projection,
640 plans: [
641 {
642 id: "plan-actionable",
643 threadId: THREAD,
644 runId: null,
645 nodeId: "node-actionable",
646 status: "active",
647 kind: "proposed_plan",
648 markdown: "a".repeat(2_097_152),
649 },
650 ],
651 } as unknown as typeof projection;
652​
653 const bounded = buildBoundedThreadProjection({ projection: actionable, snapshotSequence: 9 });
654​
655 expect(bounded.payloadBudgetExceeded).toBe(true);
656 expect(bounded.projection.plans[0]).toEqual(actionable.plans[0]);
657 expect(bounded.projection.visibleTurnItems).toEqual(actionable.visibleTurnItems);
658 });
659​
660 it("keeps paged historical plan detail in the turn item and only status in its artifact", () => {
661 const detail = "Implement the historical plan exactly.\n".repeat(1_000);
662 const item = {
663 ...makeRow(0).item,
664 type: "proposed_plan",
665 planId: "plan-historical-visible",
666 markdown: detail,
667 streaming: false,
668 } as OrchestrationV2TurnItem;
669 const row = {
670 ...makeRow(0),
671 sourceItemId: item.id,
672 item,
673 } as OrchestrationV2ProjectedTurnItem;
674 const base = makeProjection([row]);
675 const projection = {
676 ...base,
677 plans: [
678 {
679 id: "plan-historical-visible",
680 threadId: THREAD,
681 runId: null,
682 nodeId: "node-historical-visible",
683 status: "completed",
684 kind: "proposed_plan",
685 markdown: detail,
686 },
687 ],
688 } as unknown as typeof base;
689​
690 const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 9 });
691​
692 expect(bounded.projection.visibleTurnItems[0]?.item).toMatchObject({
693 type: "proposed_plan",
694 markdown: detail,
695 });
696 expect(bounded.projection.plans[0]).toMatchObject({
697 status: "completed",
698 markdown: "",
699 detailInTurnItem: true,
700 });
701 expect(bounded.payloadBudgetExceeded).toBe(false);
702 });
703});