Open History to see the last commit
1import {
2 MessageId,
3 NodeId,
4 RunId,
5 ThreadId,
6 TurnItemId,
7 type OrchestrationV2ProjectedTurnItem,
8 type OrchestrationV2TurnItem,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "@effect/vitest";
11import * as DateTime from "effect/DateTime";
12
13import {
14 buildBoundedThreadProjection,
15 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 { projectThreadProjectionForWire } from "./WireProjection.ts";
28
29const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
30const THREAD = ThreadId.make("thread-1");
31const RUN = RunId.make("run-interrupt-1");
32const NODE = NodeId.make("node-interrupt-1");
33
34function makeRow(
35 index: number,
36 options?: { readonly outputBytes?: number },
37): OrchestrationV2ProjectedTurnItem {
38 const id = TurnItemId.make(`item-${index}`);
39 const output =
40 options?.outputBytes !== undefined ? "x".repeat(options.outputBytes) : `output-${index}`;
41 return {
42 position: index,
43 visibility: "local",
44 sourceThreadId: THREAD,
45 sourceItemId: id,
46 item: {
47 id,
48 type: "command_execution",
49 threadId: THREAD,
50 runId: null,
51 nodeId: null,
52 providerThreadId: null,
53 providerTurnId: null,
54 nativeItemRef: null,
55 parentItemId: null,
56 ordinal: index + 1,
57 status: "completed",
58 title: `Command ${index}`,
59 input: `cmd-${index}`,
60 output,
61 exitCode: 0,
62 startedAt: NOW,
63 completedAt: NOW,
64 updatedAt: NOW,
65 },
66 };
67}
68
69function interruptItem(
70 id: string,
71 type: "run_interrupt_request" | "run_interrupt_result",
72 ordinal: number,
73): OrchestrationV2TurnItem {
74 return {
75 id: TurnItemId.make(id),
76 type,
77 threadId: THREAD,
78 runId: RUN,
79 nodeId: NODE,
80 providerThreadId: null,
81 providerTurnId: null,
82 nativeItemRef: null,
83 parentItemId: null,
84 ordinal,
85 status: "completed",
86 title: type,
87 message: type === "run_interrupt_request" ? "Stopping" : "Stopped",
88 startedAt: NOW,
89 completedAt: NOW,
90 updatedAt: NOW,
91 } as OrchestrationV2TurnItem;
92}
93
94function interruptRow(
95 index: number,
96 type: "run_interrupt_request" | "run_interrupt_result",
97): OrchestrationV2ProjectedTurnItem {
98 const item = interruptItem(
99 type === "run_interrupt_request" ? "interrupt-req" : "interrupt-res",
100 type,
101 index + 1,
102 );
103 return {
104 position: index,
105 visibility: "local",
106 sourceThreadId: THREAD,
107 sourceItemId: item.id,
108 item,
109 };
110}
111
112function makeProjection(visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) {
113 return {
114 thread: {
115 id: THREAD,
116 projectId: "project-1",
117 title: "Thread",
118 providerInstanceId: "codex",
119 modelSelection: { instanceId: "codex", model: "gpt-5" },
120 runtimeMode: "full-access",
121 interactionMode: "default",
122 branch: null,
123 worktreePath: null,
124 activeProviderThreadId: null,
125 lineage: {
126 parentThreadId: null,
127 relationshipToParent: null,
128 rootThreadId: THREAD,
129 },
130 forkedFrom: null,
131 createdBy: "user",
132 creationSource: "web",
133 createdAt: NOW,
134 updatedAt: NOW,
135 archivedAt: null,
136 deletedAt: null,
137 settledOverride: null,
138 settledAt: null,
139 },
140 runs: [{ id: "run-1" }],
141 attempts: [{ id: "attempt-1" }],
142 nodes: [],
143 subagents: [],
144 providerSessions: [],
145 providerThreads: [],
146 providerTurns: [],
147 runtimeRequests: [{ id: "req-1" }],
148 messages: [],
149 plans: [],
150 turnItems: visibleTurnItems.map((row) => row.item),
151 checkpointScopes: [],
152 checkpoints: [],
153 contextHandoffs: [],
154 contextTransfers: [],
155 visibleTurnItems,
156 updatedAt: NOW,
157 } as unknown as Parameters<typeof buildBoundedThreadProjection>[0]["projection"];
158}
159
160describe("threadHistoryPaging", () => {
161 it("encodes opaque cursors with stable source identity", () => {
162 const cursor = encodeThreadHistoryCursor({
163 snapshotSequence: 9,
164 sourceThreadId: THREAD,
165 sourceItemId: TurnItemId.make("item-3"),
166 position: 3,
167 });
168 expect(cursor.includes("{")).toBe(false);
169 expect(decodeThreadHistoryCursor(cursor)).toEqual({
170 v: 1,
171 seq: 9,
172 st: "thread-1",
173 si: "item-3",
174 p: 3,
175 });
176 });
177
178 it("rejects malformed cursors", () => {
179 expect(() => decodeThreadHistoryCursor("not-valid")).toThrow(InvalidThreadHistoryCursorError);
180 expect(() =>
181 decodeThreadHistoryCursor(Buffer.from("{}", "utf8").toString("base64url")),
182 ).toThrow(InvalidThreadHistoryCursorError);
183 });
184
185 it("rejects cursors longer than the maximum length before decoding", () => {
186 const oversized = "A".repeat(THREAD_HISTORY_CURSOR_MAX_LENGTH + 1);
187 expect(() => decodeThreadHistoryCursor(oversized)).toThrow(InvalidThreadHistoryCursorError);
188 });
189
190 it("selects a recent window by item count", () => {
191 const items = Array.from({ length: 120 }, (_, index) => makeRow(index));
192 const page = selectRecentTimelineWindow({
193 items,
194 snapshotSequence: 4,
195 policy: { maxItems: 10, maxEncodedBytes: 10_000_000 },
196 });
197 expect(page.items).toHaveLength(10);
198 expect(page.items[0]?.sourceItemId).toBe("item-110");
199 expect(page.items[9]?.sourceItemId).toBe("item-119");
200 expect(page.hasMoreHistory).toBe(true);
201 expect(page.nextCursor).not.toBeNull();
202 const cursor = decodeThreadHistoryCursor(page.nextCursor!);
203 expect(cursor.si).toBe("item-110");
204 expect(cursor.seq).toBe(4);
205 });
206
207 it("always includes at least one pathological oversized item", () => {
208 const items = [makeRow(0, { outputBytes: 2_000_000 }), makeRow(1, { outputBytes: 10 })];
209 const page = selectRecentTimelineWindow({
210 items,
211 snapshotSequence: 1,
212 policy: { maxItems: 50, maxEncodedBytes: 1_024 },
213 });
214 expect(page.items).toHaveLength(1);
215 expect(page.items[0]?.sourceItemId).toBe("item-1");
216 expect(page.hasMoreHistory).toBe(true);
217
218 const older = selectHistoryPageFromCursor({
219 items,
220 cursor: page.nextCursor!,
221 snapshotSequence: 1,
222 policy: { maxItems: 50, maxEncodedBytes: 1_024 },
223 });
224 expect(older.items).toHaveLength(1);
225 expect(older.items[0]?.sourceItemId).toBe("item-0");
226 expect(older.hasMoreHistory).toBe(false);
227 expect(older.nextCursor).toBeNull();
228 });
229
230 it("recovers identity-miss cursors when position is past a shrunken timeline", () => {
231 const items = Array.from({ length: 5 }, (_, index) => makeRow(index));
232 const cursor = encodeThreadHistoryCursor({
233 snapshotSequence: 3,
234 sourceThreadId: THREAD,
235 sourceItemId: TurnItemId.make("item-deleted-long-ago"),
236 position: 40,
237 });
238 const page = selectHistoryPageFromCursor({
239 items,
240 cursor,
241 snapshotSequence: 3,
242 policy: { maxItems: 2, maxEncodedBytes: 10_000_000 },
243 });
244 // Clamp exclusive end to items.length and page backward so the client can
245 // dedupe and advance rather than permanently 400 on a dead cursor.
246 expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]);
247 expect(page.hasMoreHistory).toBe(true);
248 expect(page.nextCursor).not.toBeNull();
249 });
250
251 it("keeps cursor resolution stable when newer items append", () => {
252 const initial = Array.from({ length: 20 }, (_, index) => makeRow(index));
253 const recent = selectRecentTimelineWindow({
254 items: initial,
255 snapshotSequence: 2,
256 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
257 });
258 const cursor = recent.nextCursor!;
259 const grown = [...initial, makeRow(20), makeRow(21)];
260 const older = selectHistoryPageFromCursor({
261 items: grown,
262 cursor,
263 snapshotSequence: 5,
264 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
265 });
266 expect(older.items.map((row) => row.sourceItemId)).toEqual([
267 "item-10",
268 "item-11",
269 "item-12",
270 "item-13",
271 "item-14",
272 ]);
273 expect(older.hasMoreHistory).toBe(true);
274 });
275
276 it("builds a bounded projection that preserves non-timeline control state", () => {
277 const full = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
278 const bounded = buildBoundedThreadProjection({
279 projection: full,
280 snapshotSequence: 7,
281 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
282 });
283 expect(bounded.projection.runs).toEqual(full.runs);
284 expect(bounded.projection.runtimeRequests).toEqual(full.runtimeRequests);
285 expect(bounded.projection.attempts).toEqual(full.attempts);
286 expect(bounded.projection.visibleTurnItems).toHaveLength(5);
287 expect(bounded.projection.turnItems).toHaveLength(5);
288 expect(bounded.hasMoreHistory).toBe(true);
289 expect(bounded.historyCursor).not.toBeNull();
290 expect(bounded.projection.visibleTurnItems.map((row) => row.position)).toEqual([0, 1, 2, 3, 4]);
291 // Watermark comes from the full projection, not the trimmed window.
292 expect(bounded.latestLocalTurnOrdinal).toBe(40);
293 expect(computeLatestLocalTurnOrdinal(full.turnItems)).toBe(40);
294 });
295
296 it("preserves linked control rows as one coherent graph", () => {
297 const base = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index)));
298 const linked = {
299 ...base,
300 runs: [{ id: "run-linked", threadId: THREAD }],
301 attempts: [{ id: "attempt-linked", runId: "run-linked" }],
302 nodes: [{ id: "node-linked", runId: "run-linked", attemptId: "attempt-linked" }],
303 providerThreads: [{ id: "provider-thread-linked", runId: "run-linked" }],
304 providerTurns: [
305 {
306 id: "provider-turn-linked",
307 providerThreadId: "provider-thread-linked",
308 nodeId: "node-linked",
309 },
310 ],
311 checkpointScopes: [{ id: "scope-linked", runId: "run-linked" }],
312 checkpoints: [{ id: "checkpoint-linked", scopeId: "scope-linked" }],
313 } as unknown as typeof base;
314
315 const bounded = buildBoundedThreadProjection({
316 projection: linked,
317 snapshotSequence: 7,
318 policy: { maxItems: 5, maxEncodedBytes: 10_000_000 },
319 });
320
321 expect(bounded.projection.runs).toEqual(linked.runs);
322 expect(bounded.projection.attempts).toEqual(linked.attempts);
323 expect(bounded.projection.nodes).toEqual(linked.nodes);
324 expect(bounded.projection.providerThreads).toEqual(linked.providerThreads);
325 expect(bounded.projection.providerTurns).toEqual(linked.providerTurns);
326 expect(bounded.projection.checkpointScopes).toEqual(linked.checkpointScopes);
327 expect(bounded.projection.checkpoints).toEqual(linked.checkpoints);
328 });
329
330 it("carries a full-projection watermark when the bounded window is inherited-only", () => {
331 const localOlder = makeRow(0);
332 const localMid = makeRow(1);
333 const inherited = {
334 ...makeRow(2),
335 visibility: "inherited" as const,
336 sourceThreadId: ThreadId.make("parent-thread"),
337 item: {
338 ...makeRow(2).item,
339 threadId: ThreadId.make("parent-thread"),
340 },
341 };
342 // Full projection still has local turnItems even if the recent window is
343 // only the inherited row (e.g. after aggressive byte budget on a large
344 // local item that is not selected into the recent page). Use a synthetic
345 // projection with local turnItems and inherited-only visible window.
346 const full = makeProjection([localOlder, localMid, inherited]);
347 // Force an inherited-only visible window by rebuilding with only inherited
348 // visible rows while retaining full local turnItems for the watermark.
349 const inheritedOnly = {
350 ...full,
351 visibleTurnItems: [inherited],
352 turnItems: [localOlder.item, localMid.item],
353 };
354 const bounded = buildBoundedThreadProjection({
355 projection: inheritedOnly,
356 snapshotSequence: 2,
357 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
358 });
359 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
360 String(inherited.sourceItemId),
361 ]);
362 expect(bounded.latestLocalTurnOrdinal).toBe(2);
363 expect(computeLatestLocalTurnOrdinal([])).toBeNull();
364 });
365
366 it("retains an out-of-window run_interrupt_request needed by a visible result", () => {
367 // Older request sits outside a 1-row recent window; result is visible alone.
368 const request = interruptRow(0, "run_interrupt_request");
369 const filler = makeRow(1);
370 const result = interruptRow(2, "run_interrupt_result");
371 const full = makeProjection([request, filler, result]);
372 const bounded = buildBoundedThreadProjection({
373 projection: full,
374 snapshotSequence: 3,
375 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
376 });
377
378 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
379 "interrupt-res",
380 ]);
381 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
382 "interrupt-req",
383 "interrupt-res",
384 ]);
385 expect(bounded.hasMoreHistory).toBe(true);
386 });
387
388 it("retains all run_interrupt_request items even when no result is in the initial window", () => {
389 // Cold open: recent window is only filler. Request and result both live on
390 // older pages, but the request must still ride in turnItems so a later
391 // history page can introduce the result safely under live attempt updates.
392 const request = interruptRow(0, "run_interrupt_request");
393 const result = interruptRow(1, "run_interrupt_result");
394 const recent = makeRow(2);
395 const full = makeProjection([request, result, recent]);
396 const bounded = buildBoundedThreadProjection({
397 projection: full,
398 snapshotSequence: 4,
399 policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
400 });
401
402 expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
403 "item-2",
404 ]);
405 expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
406 "interrupt-req",
407 "item-2",
408 ]);
409 expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(
410 true,
411 );
412 expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(
413 false,
414 );
415 });
416
417 it("charges local row.item duplication when measuring bounded timeline bytes", () => {
418 const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 }));
419 const full = makeProjection(rows);
420 const maxEncodedBytes = 12_000;
421 const bounded = buildBoundedThreadProjection({
422 projection: full,
423 snapshotSequence: 1,
424 policy: { maxItems: 50, maxEncodedBytes },
425 });
426
427 const contribution = boundedTimelineEncodedBytes({
428 visibleTurnItems: bounded.projection.visibleTurnItems,
429 turnItems: bounded.projection.turnItems,
430 });
431 expect(contribution).toBeLessThanOrEqual(maxEncodedBytes);
432 expect(bounded.projection.visibleTurnItems.length).toBeGreaterThan(0);
433 expect(bounded.projection.visibleTurnItems.length).toBeLessThan(rows.length);
434
435 // History pages only charge the projected row once (no turnItems copy).
436 const historyPage = selectRecentTimelineWindow({
437 items: rows,
438 snapshotSequence: 1,
439 policy: { maxItems: 50, maxEncodedBytes },
440 });
441 const historyBytes = historyPage.items.reduce(
442 (sum, row) => sum + projectedRowEncodedBytes(row),
443 0,
444 );
445 expect(historyBytes).toBeLessThanOrEqual(maxEncodedBytes);
446 expect(historyPage.items.length).toBeGreaterThan(bounded.projection.visibleTurnItems.length);
447
448 // Dual-cost for one local row exceeds the plain row cost.
449 const sample = rows[0]!;
450 expect(projectedRowBoundedSnapshotEncodedBytes(sample, THREAD)).toBeGreaterThan(
451 projectedRowEncodedBytes(sample),
452 );
453 });
454
455 it("allows a single pathological bounded row to exceed the configured cap", () => {
456 const huge = makeRow(0, { outputBytes: 50_000 });
457 const full = makeProjection([huge]);
458 const maxEncodedBytes = 1_000;
459 const bounded = buildBoundedThreadProjection({
460 projection: full,
461 snapshotSequence: 1,
462 policy: { maxItems: 10, maxEncodedBytes },
463 });
464 expect(bounded.projection.visibleTurnItems).toHaveLength(1);
465 const contribution = boundedTimelineEncodedBytes({
466 visibleTurnItems: bounded.projection.visibleTurnItems,
467 turnItems: bounded.projection.turnItems,
468 });
469 expect(contribution).toBeGreaterThan(maxEncodedBytes);
470 });
471
472 it("exposes conservative default page budgets", () => {
473 expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeGreaterThanOrEqual(50);
474 expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeLessThanOrEqual(100);
475 expect(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes).toBe(1_048_576);
476 });
477
478 it("does not carry the full duplicated message table into a bounded snapshot", () => {
479 const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index)));
480 const full = {
481 ...projection,
482 messages: Array.from({ length: 2_000 }, (_, index) => ({
483 id: MessageId.make(`message-${index}`),
484 threadId: THREAD,
485 runId: RunId.make(`old-run-${index}`),
486 nodeId: null,
487 role: "assistant" as const,
488 text: "x".repeat(1_000),
489 attachments: [],
490 streaming: false,
491 createdBy: "agent" as const,
492 creationSource: "provider" as const,
493 createdAt: NOW,
494 updatedAt: NOW,
495 })),
496 } as typeof projection;
497
498 const bounded = buildBoundedThreadProjection({
499 projection: full,
500 snapshotSequence: 9,
501 });
502
503 expect(bounded.projection.messages).toEqual([]);
504 expect(Buffer.byteLength(JSON.stringify(bounded.projection), "utf8")).toBeLessThan(
505 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes + 100_000,
506 );
507 });
508
509 it("omits historical control details that remain available from history items", () => {
510 const projection = makeProjection(Array.from({ length: 200 }, (_, index) => makeRow(index)));
511 const populated = {
512 ...projection,
513 plans: Array.from({ length: 120 }, (_, index) => ({
514 id: `plan-${index}`,
515 threadId: THREAD,
516 runId: null,
517 nodeId: `node-${index}`,
518 status: "completed",
519 kind: "proposed_plan",
520 markdown: "p".repeat(2_097_152),
521 })),
522 contextHandoffs: Array.from({ length: 120 }, (_, index) => ({
523 id: `handoff-${index}`,
524 threadId: THREAD,
525 targetRunId: "run-1",
526 fromProviderThreadIds: [],
527 toProviderThreadId: "provider-thread-1",
528 coveredRunOrdinals: { from: 1, to: 1 },
529 strategy: "manual_context",
530 status: "superseded",
531 summaryMessageId: null,
532 summaryText: "h".repeat(2_097_152),
533 createdByProviderInstanceId: null,
534 createdAt: NOW,
535 updatedAt: NOW,
536 })),
537 } as unknown as typeof projection;
538
539 const bounded = buildBoundedThreadProjection({
540 projection: projectThreadProjectionForWire(populated),
541 snapshotSequence: 9,
542 });
543 const serializedBytes = Buffer.byteLength(JSON.stringify(bounded.projection), "utf8");
544
545 expect(serializedBytes).toBeLessThanOrEqual(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes);
546 expect(bounded.payloadBudgetExceeded).toBe(false);
547 expect(bounded.projection.plans).toEqual([]);
548 expect(bounded.projection.contextHandoffs).toEqual([]);
549 expect(populated.plans).toHaveLength(120);
550 expect(
551 populated.plans[0]?.kind === "proposed_plan" ? populated.plans[0].markdown.length : 0,
552 ).toBe(2_097_152);
553 });
554
555 it("preserves oversized actionable state and reports the budget exception", () => {
556 const projection = makeProjection([]);
557 const actionable = {
558 ...projection,
559 plans: [
560 {
561 id: "plan-actionable",
562 threadId: THREAD,
563 runId: null,
564 nodeId: "node-actionable",
565 status: "active",
566 kind: "proposed_plan",
567 markdown: "a".repeat(2_097_152),
568 },
569 ],
570 } as unknown as typeof projection;
571
572 const bounded = buildBoundedThreadProjection({ projection: actionable, snapshotSequence: 9 });
573
574 expect(bounded.payloadBudgetExceeded).toBe(true);
575 expect(bounded.projection.plans[0]).toEqual(actionable.plans[0]);
576 });
577
578 it("keeps paged historical plan detail in the turn item and only status in its artifact", () => {
579 const detail = "Implement the historical plan exactly.\n".repeat(1_000);
580 const item = {
581 ...makeRow(0).item,
582 type: "proposed_plan",
583 planId: "plan-historical-visible",
584 markdown: detail,
585 streaming: false,
586 } as OrchestrationV2TurnItem;
587 const row = {
588 ...makeRow(0),
589 sourceItemId: item.id,
590 item,
591 } as OrchestrationV2ProjectedTurnItem;
592 const base = makeProjection([row]);
593 const projection = {
594 ...base,
595 plans: [
596 {
597 id: "plan-historical-visible",
598 threadId: THREAD,
599 runId: null,
600 nodeId: "node-historical-visible",
601 status: "completed",
602 kind: "proposed_plan",
603 markdown: detail,
604 },
605 ],
606 } as unknown as typeof base;
607
608 const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 9 });
609
610 expect(bounded.projection.visibleTurnItems[0]?.item).toMatchObject({
611 type: "proposed_plan",
612 markdown: detail,
613 });
614 expect(bounded.projection.plans[0]).toMatchObject({
615 status: "completed",
616 markdown: "",
617 detailInTurnItem: true,
618 });
619 expect(bounded.payloadBudgetExceeded).toBe(false);
620 });
621});