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

threadHistoryPaging.test.ts

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