Open History to see the last commit
1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2Subagent,
4 OrchestrationV2ThreadProjection,
5} from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as DateTime from "effect/DateTime";
8
9import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
10import {
11 applyHistoryRangeMeta,
12 EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET,
13 EMPTY_THREAD_HISTORY_META,
14 historyGapSeamsByRow,
15 MAX_AUTO_CONTINUE_HISTORY_BYTES,
16 MAX_AUTO_CONTINUE_HISTORY_ITEMS,
17 MAX_AUTO_CONTINUE_HISTORY_PAGES,
18 mergeOlderHistoryIntoProjection,
19 mergeOlderSubagentsIntoProjection,
20 nextEarlierHistoryContinuationBudget,
21 type ThreadHistoryMeta,
22} from "./threadHistoryMerge.ts";
23import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
24import { derivePendingThreadRequests } from "./threadRequests.ts";
25
26const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
27
28function row(index: number) {
29 const id = `item-${index}` as never;
30 return {
31 position: index,
32 visibility: "local",
33 sourceThreadId: v2ThreadId,
34 sourceItemId: id,
35 item: {
36 id,
37 type: "command_execution",
38 threadId: v2ThreadId,
39 runId: null,
40 nodeId: null,
41 providerThreadId: null,
42 providerTurnId: null,
43 nativeItemRef: null,
44 parentItemId: null,
45 ordinal: index + 1,
46 status: "completed",
47 title: `Command ${index}`,
48 input: `cmd-${index}`,
49 output: `out-${index}`,
50 exitCode: 0,
51 startedAt: NOW,
52 completedAt: NOW,
53 updatedAt: NOW,
54 },
55 } satisfies OrchestrationV2ProjectedTurnItem;
56}
57
58describe("threadHistoryMerge", () => {
59 it("keeps each seam at its canonical ordinal when rendered rows fold or disappear", () => {
60 const visible = [row(10), row(20), row(30)];
61 const history = {
62 ...EMPTY_THREAD_HISTORY_META,
63 gaps: visible.map(({ sourceItemId, item }) => ({
64 seamItemId: sourceItemId,
65 cursor: sourceItemId,
66 ordinal: item.ordinal,
67 })),
68 };
69 const rows = [
70 { id: "earlier", endOrdinal: 5 },
71 { id: "folded", endOrdinal: 25 },
72 ];
73 expect([...historyGapSeamsByRow(history.gaps, rows, (row) => row.endOrdinal)]).toEqual([
74 ["folded", ["item-10", "item-20"]],
75 [null, ["item-30"]],
76 ]);
77 });
78
79 it("keeps a gap below a detached page when a stop request precedes the loaded ranges", () => {
80 const dependency = row(1);
81 const request: OrchestrationV2ProjectedTurnItem = {
82 ...dependency,
83 item: { ...dependency.item, type: "run_interrupt_request", message: "Stopping" },
84 };
85 const history = {
86 ...EMPTY_THREAD_HISTORY_META,
87 historyCursor: "before-4000",
88 hasMoreHistory: true,
89 };
90 const page = {
91 items: [row(1000), row(1499)],
92 nextCursor: "before-1000",
93 hasMoreHistory: true,
94 detached: true as const,
95 };
96 expect(applyHistoryRangeMeta(history, [request, row(4000)], page, "before-4000")).toMatchObject(
97 {
98 historyCursor: "before-1000",
99 gaps: [
100 { seamItemId: "item-4000", cursor: "before-4000", ordinal: 4001, afterOrdinal: 1500 },
101 ],
102 },
103 );
104 });
105
106 it("clears the top cursor when a lower gap has already reached the start", () => {
107 const history = {
108 ...EMPTY_THREAD_HISTORY_META,
109 historyCursor: "before-10",
110 hasMoreHistory: true,
111 gaps: [{ cursor: "before-90", seamItemId: "item-90", ordinal: 91, afterOrdinal: 11 }],
112 };
113 const page = { items: [row(10)], nextCursor: null, hasMoreHistory: false };
114 expect(applyHistoryRangeMeta(history, [row(10), row(90)], page, "before-90")).toMatchObject({
115 historyCursor: null,
116 hasMoreHistory: false,
117 });
118 });
119
120 it("continues filling a gap after its seam row disappears", () => {
121 const history = {
122 ...EMPTY_THREAD_HISTORY_META,
123 gaps: [{ cursor: "before-90", seamItemId: "item-90", ordinal: 91, afterOrdinal: 11 }],
124 };
125 const visible = [row(10), row(100)];
126 const rows = visible.map((row) => ({ id: row.sourceItemId, ordinal: row.item.ordinal }));
127 expect([...historyGapSeamsByRow(history.gaps, rows, (row) => row.ordinal)]).toEqual([
128 ["item-100", ["item-90"]],
129 ]);
130 const page = { items: [row(70)], nextCursor: "before-70", hasMoreHistory: true };
131 expect(applyHistoryRangeMeta(history, visible, page, "before-90").gaps).toEqual([
132 { cursor: "before-70", seamItemId: "item-70", ordinal: 71, afterOrdinal: 11 },
133 ]);
134 });
135
136 it("keeps a gap when its stale cursor returns only newer rows already loaded", () => {
137 const history = {
138 ...EMPTY_THREAD_HISTORY_META,
139 historyCursor: "before-10",
140 hasMoreHistory: true,
141 gaps: [{ cursor: "before-900", seamItemId: "item-899", ordinal: 900, afterOrdinal: 20 }],
142 };
143 const visible = [row(9), row(19), row(1725), row(1799)];
144 const overlap = { items: visible.slice(2), nextCursor: "before-1726", hasMoreHistory: true };
145 const next = applyHistoryRangeMeta(history, visible, overlap, "before-900");
146 expect(next.gaps).toEqual([
147 { cursor: "before-1726", seamItemId: "item-899", ordinal: 900, afterOrdinal: 20 },
148 ]);
149
150 const fill = {
151 items: [row(19), row(20), row(298)],
152 nextCursor: "before-20",
153 hasMoreHistory: true,
154 };
155 expect(applyHistoryRangeMeta(next, visible, fill, "before-1726")).toMatchObject({
156 historyCursor: "before-10",
157 });
158 expect(applyHistoryRangeMeta(next, visible, fill, "before-1726").gaps).toBeUndefined();
159 });
160
161 it("advances only the part of a gap covered by a page, even when it overlaps live rows", () => {
162 const history = {
163 ...EMPTY_THREAD_HISTORY_META,
164 gaps: [{ cursor: "before-900", seamItemId: "item-899", ordinal: 900, afterOrdinal: 20 }],
165 };
166 const visible = [row(19), row(824), row(849), row(899)];
167 const fetched = {
168 items: Array.from({ length: 75 }, (_, offset) => row(824 + offset)),
169 nextCursor: "before-825",
170 hasMoreHistory: true,
171 };
172 const partial = applyHistoryRangeMeta(history, visible, fetched, "before-900");
173 expect(partial.gaps).toEqual([
174 { cursor: "before-825", seamItemId: "item-824", ordinal: 825, afterOrdinal: 20 },
175 ]);
176
177 const fill = {
178 items: Array.from({ length: 805 }, (_, offset) => row(19 + offset)),
179 nextCursor: "before-20",
180 hasMoreHistory: true,
181 };
182 expect(
183 applyHistoryRangeMeta(partial, [row(19), ...fetched.items, row(899)], fill, "before-825")
184 .gaps,
185 ).toBeUndefined();
186 });
187
188 it("splits at the top cursor even when a live row appears before it", () => {
189 const history = {
190 ...EMPTY_THREAD_HISTORY_META,
191 historyCursor: "before-900",
192 hasMoreHistory: true,
193 topSeam: { seamItemId: "item-899", ordinal: 900 },
194 };
195 const visible = [row(849), row(899)];
196 const detached = {
197 items: [row(579), row(849)],
198 nextCursor: "before-580",
199 hasMoreHistory: true,
200 detached: true as const,
201 };
202 expect(applyHistoryRangeMeta(history, visible, detached, "before-900")).toMatchObject({
203 historyCursor: "before-580",
204 topSeam: { seamItemId: "item-579", ordinal: 580 },
205 gaps: [{ cursor: "before-900", seamItemId: "item-899", ordinal: 900, afterOrdinal: 850 }],
206 });
207 });
208
209 it("fills activity around partial messages in canonical order and preserves live edits", () => {
210 const initial = { ...v2Projection, turnItems: [row(4).item], visibleTurnItems: [row(4)] };
211 const preview = [row(1), row(3)];
212 const partial = mergeOlderHistoryIntoProjection(initial, preview);
213 const updated = { ...row(1), item: { ...row(1).item, title: "newer live title" } };
214 const live = {
215 ...partial,
216 visibleTurnItems: partial.visibleTurnItems.map((entry) =>
217 entry.sourceItemId === updated.sourceItemId ? updated : entry,
218 ),
219 turnItems: partial.turnItems.map((item) =>
220 item.id === updated.item.id ? updated.item : item,
221 ),
222 };
223 const complete = mergeOlderHistoryIntoProjection(live, [row(0), row(1), row(2), row(3)]);
224 expect(complete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
225 "item-0",
226 "item-1",
227 "item-2",
228 "item-3",
229 "item-4",
230 ]);
231 expect(complete.visibleTurnItems[1]?.item).toBe(updated.item);
232 expect(complete.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3, 4]);
233 expect(new Set(complete.turnItems.map((item) => item.id)).size).toBe(5);
234 const anchorItem = {
235 ...updated.item,
236 deferredWork: { cursor: "work", itemCount: 4, lastOrdinal: 5 },
237 };
238 const deferred = {
239 ...live,
240 turnItems: live.turnItems.map((item) => (item.id === anchorItem.id ? anchorItem : item)),
241 visibleTurnItems: live.visibleTurnItems.map((entry) =>
242 entry.item.id === anchorItem.id ? { ...entry, item: anchorItem } : entry,
243 ),
244 };
245 const loadedWork = mergeOlderHistoryIntoProjection(deferred, [row(1), row(2), row(3)], {
246 anchorId: anchorItem.id,
247 nextCursor: null,
248 });
249 expect(loadedWork.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
250 "item-1",
251 "item-2",
252 "item-3",
253 "item-4",
254 ]);
255 expect(loadedWork.visibleTurnItems[0]?.item.title).toBe("newer live title");
256 expect(loadedWork.visibleTurnItems[0]?.item.deferredWork).toBeUndefined();
257 const hidden = {
258 ...partial,
259 visibleTurnItems: partial.visibleTurnItems.filter(
260 (entry) => entry.sourceItemId !== preview[0]!.sourceItemId,
261 ),
262 };
263 const hiddenComplete = mergeOlderHistoryIntoProjection(hidden, [
264 row(0),
265 row(1),
266 row(2),
267 row(3),
268 ]);
269 expect(hiddenComplete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
270 "item-0",
271 "item-2",
272 "item-3",
273 "item-4",
274 ]);
275 });
276
277 it("places pages beside gaps by ordinal and tracks what each leaves unloaded", () => {
278 const rows = (first: number, last: number) =>
279 Array.from({ length: last - first + 1 }, (_, offset) => row(first + offset));
280 let projection: OrchestrationV2ThreadProjection = {
281 ...v2Projection,
282 turnItems: [],
283 visibleTurnItems: rows(90, 99),
284 };
285 let history: ThreadHistoryMeta = {
286 ...EMPTY_THREAD_HISTORY_META,
287 historyCursor: "before-90",
288 hasMoreHistory: true,
289 };
290 const land = (page: Parameters<typeof applyHistoryRangeMeta>[2], requestCursor: string) => {
291 history = applyHistoryRangeMeta(history, projection.visibleTurnItems, page, requestCursor);
292 projection = mergeOlderHistoryIntoProjection(projection, page.items, undefined, true);
293 return projection.visibleTurnItems.map((entry) => entry.item.ordinal - 1);
294 };
295 const page = (first: number, last: number, detached?: true) => ({
296 items: rows(first, last),
297 nextCursor: first === 0 ? null : `before-${first}`,
298 hasMoreHistory: first > 0,
299 ...(detached ? { detached } : {}),
300 });
301
302 // A jump far back: the page around the target, and a gap down to the rows held.
303 expect(land(page(10, 19, true), "before-90")).toEqual([
304 ...rows(10, 19).map((entry) => entry.position),
305 ...rows(90, 99).map((entry) => entry.position),
306 ]);
307 expect(history).toMatchObject({
308 historyCursor: "before-10",
309 hasMoreHistory: true,
310 gaps: [{ cursor: "before-90", seamItemId: "item-90", afterOrdinal: 20, ordinal: 91 }],
311 });
312
313 // A second jump inside that gap splits it in two.
314 land(page(50, 59, true), "before-90");
315 expect(history.gaps).toEqual([
316 { cursor: "before-50", seamItemId: "item-50", ordinal: 51, afterOrdinal: 20 },
317 { cursor: "before-90", seamItemId: "item-90", afterOrdinal: 60, ordinal: 91 },
318 ]);
319
320 // Filling the lower gap moves its seam up, then closes it once a page reaches held rows.
321 land(page(70, 89), "before-90");
322 expect(history.gaps).toEqual([
323 { cursor: "before-50", seamItemId: "item-50", ordinal: 51, afterOrdinal: 20 },
324 { cursor: "before-70", seamItemId: "item-70", ordinal: 71, afterOrdinal: 60 },
325 ]);
326 land(page(58, 69), "before-70");
327 expect(history.gaps).toEqual([
328 { cursor: "before-50", seamItemId: "item-50", ordinal: 51, afterOrdinal: 20 },
329 ]);
330
331 // A fill that runs past the stretch above it closes that gap and loads on above it.
332 const filled = land(page(5, 49), "before-50");
333 expect(filled).toEqual(rows(5, 99).map((entry) => entry.position));
334 expect(history.gaps).toBeUndefined();
335 expect(history).toMatchObject({ historyCursor: "before-5", hasMoreHistory: true });
336
337 // The stop request a page carries from outside its range says nothing of where it starts.
338 const request = { ...row(2), item: { ...row(2).item, type: "run_interrupt_request" } };
339 projection = { ...projection, visibleTurnItems: rows(90, 99) };
340 history = { ...EMPTY_THREAD_HISTORY_META, historyCursor: "before-90", hasMoreHistory: true };
341 land({ ...page(40, 49, true), items: [request as never, ...rows(40, 49)] }, "before-90");
342 expect(history).toMatchObject({
343 historyCursor: "before-40",
344 gaps: [{ cursor: "before-90", seamItemId: "item-90", afterOrdinal: 50, ordinal: 91 }],
345 });
346 });
347
348 it("prepends older rows and dedupes by source identity", () => {
349 const recent = [row(2), row(3)];
350 const projection = {
351 ...v2Projection,
352 turnItems: recent.map((entry) => entry.item),
353 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
354 };
355 const older = [row(0), row(1), row(2)];
356 const merged = mergeOlderHistoryIntoProjection(projection, older);
357 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
358 "item-0",
359 "item-1",
360 "item-2",
361 "item-3",
362 ]);
363 expect(merged.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3]);
364 expect(merged.turnItems.map((item) => item.id)).toEqual([
365 "item-2",
366 "item-3",
367 "item-0",
368 "item-1",
369 ]);
370 });
371
372 it("adds older subagent records and keeps the newer record of one already held", () => {
373 const subagent = (id: string, model: string) =>
374 ({ id, model, status: "completed" }) as unknown as OrchestrationV2Subagent;
375 const live = subagent("agent-live", "claude-sonnet-live");
376 const projection = { ...v2Projection, subagents: [live] };
377 const merged = mergeOlderSubagentsIntoProjection(projection, [
378 subagent("agent-old", "claude-haiku-4-5-20251001"),
379 subagent("agent-live", "claude-sonnet-stale"),
380 ]);
381 expect(merged.subagents.map((agent) => [agent.id, agent.model])).toEqual([
382 ["agent-old", "claude-haiku-4-5-20251001"],
383 ["agent-live", "claude-sonnet-live"],
384 ]);
385 expect(mergeOlderSubagentsIntoProjection(projection, undefined)).toBe(projection);
386 });
387
388 it("fills inherited activity without confusing identical item IDs from different source threads", () => {
389 const inherited = (index: number) => ({
390 ...row(index),
391 visibility: "inherited" as const,
392 sourceThreadId: "fork-source" as never,
393 });
394 const local = row(1);
395 const preview = { ...inherited(1), item: { ...row(1).item, title: "newer inherited title" } };
396 const projection = {
397 ...v2Projection,
398 turnItems: [local.item],
399 visibleTurnItems: [preview, local],
400 };
401 const merged = mergeOlderHistoryIntoProjection(projection, [inherited(0), inherited(1)]);
402 expect(
403 merged.visibleTurnItems.map((entry) => [entry.sourceThreadId, entry.sourceItemId]),
404 ).toEqual([
405 ["fork-source", "item-0"],
406 ["fork-source", "item-1"],
407 [v2ThreadId, "item-1"],
408 ]);
409 expect(merged.visibleTurnItems[1]?.item).toBe(preview.item);
410 expect(merged.turnItems).toEqual([local.item]);
411 expect(mergeOlderHistoryIntoProjection(merged, [inherited(0), inherited(1)])).toBe(merged);
412 });
413
414 it("retains live rows that arrived after the older page was fetched", () => {
415 const live = [row(5), row(6)];
416 const projection = {
417 ...v2Projection,
418 turnItems: live.map((entry) => entry.item),
419 visibleTurnItems: live.map((entry, position) => ({ ...entry, position })),
420 };
421 const older = [row(3), row(4)];
422 const merged = mergeOlderHistoryIntoProjection(projection, older);
423 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
424 "item-3",
425 "item-4",
426 "item-5",
427 "item-6",
428 ]);
429 });
430
431 it("keeps an older answer before a full page that only covers the later part of a conversation page", () => {
432 const [question, olderAnswer, reasoningA, reasoningB, reasoningC, newerAnswer] = [
433 row(0),
434 row(1),
435 row(2),
436 row(3),
437 row(4),
438 row(5),
439 ];
440 const window = [row(6), row(7)];
441 const projection = {
442 ...v2Projection,
443 turnItems: window.map((entry) => entry.item),
444 visibleTurnItems: window.map((entry, position) => ({ ...entry, position })),
445 };
446 const conversation = mergeOlderHistoryIntoProjection(projection, [
447 question,
448 olderAnswer,
449 newerAnswer,
450 ]);
451 const full = mergeOlderHistoryIntoProjection(conversation, [
452 reasoningA,
453 reasoningB,
454 reasoningC,
455 newerAnswer,
456 ]);
457 expect(full.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
458 "item-0",
459 "item-1",
460 "item-2",
461 "item-3",
462 "item-4",
463 "item-5",
464 "item-6",
465 "item-7",
466 ]);
467 });
468
469 it("does not resurrect a local item hidden while an older page was in flight", () => {
470 const stalePageRow = row(1);
471 const currentItem = {
472 ...stalePageRow.item,
473 output: "newer live output",
474 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
475 };
476 const projection = {
477 ...v2Projection,
478 turnItems: [currentItem],
479 visibleTurnItems: [],
480 };
481
482 const merged = mergeOlderHistoryIntoProjection(projection, [stalePageRow]);
483
484 expect(merged).toBe(projection);
485 expect(merged.turnItems).toEqual([currentItem]);
486 expect(merged.visibleTurnItems).toEqual([]);
487 });
488
489 it("retains merged older rows when a live turn-item update arrives", () => {
490 const recent = [row(2), row(3)];
491 const projection = {
492 ...v2Projection,
493 turnItems: recent.map((entry) => entry.item),
494 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
495 };
496 const merged = mergeOlderHistoryIntoProjection(projection, [row(0), row(1)]);
497 const liveItem = {
498 ...row(3).item,
499 output: "streamed",
500 };
501 const next = applyOrchestrationV2ProjectionEvent(merged, {
502 id: "event-live-item" as never,
503 type: "turn-item.updated",
504 threadId: v2ThreadId,
505 occurredAt: NOW,
506 payload: liveItem,
507 } as never);
508 expect(next?.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
509 "item-0",
510 "item-1",
511 "item-2",
512 "item-3",
513 ]);
514 expect(next?.visibleTurnItems[3]?.item).toEqual(liveItem);
515 });
516
517 // regression: #25806 a pending question card retained outside the window shows when paged in
518 it.each(["completed", "rolled_back"] as const)(
519 "keeps a pending question actionable when paging a %s run",
520 (status) => {
521 const recent = row(5);
522 const runId = "question-run" as never;
523 const nodeId = "question-node" as never;
524 const card = {
525 id: "item-question" as never,
526 type: "user_input_request" as const,
527 threadId: v2ThreadId,
528 runId,
529 nodeId,
530 providerThreadId: null,
531 providerTurnId: null,
532 nativeItemRef: null,
533 parentItemId: null,
534 ordinal: 1,
535 status: "running" as const,
536 title: null,
537 requestId: "request-question" as never,
538 responseMode: "message" as const,
539 questions: [{ id: "scope", header: "Scope", question: "Which scope?", options: [] }],
540 startedAt: NOW,
541 completedAt: null,
542 updatedAt: NOW,
543 };
544 const coldOpen = {
545 ...v2Projection,
546 runs: [
547 {
548 id: runId,
549 threadId: v2ThreadId,
550 ordinal: 1,
551 providerInstanceId: v2Projection.thread.providerInstanceId,
552 modelSelection: v2Projection.thread.modelSelection,
553 providerThreadId: null,
554 userMessageId: "question-message" as never,
555 rootNodeId: nodeId,
556 activeAttemptId: null,
557 status,
558 requestedAt: NOW,
559 startedAt: NOW,
560 completedAt: NOW,
561 checkpointId: null,
562 contextHandoffId: null,
563 },
564 ],
565 runtimeRequests: [
566 {
567 id: card.requestId,
568 nodeId,
569 providerTurnId: null,
570 nativeRequestRef: null,
571 kind: "user_input" as const,
572 status: "pending" as const,
573 responseCapability: { type: "message" as const },
574 createdAt: NOW,
575 resolvedAt: null,
576 },
577 ],
578 turnItems: [card, recent.item],
579 visibleTurnItems: [{ ...recent, position: 0 }],
580 };
581
582 // A row of the run that was never in the window, such as one paged in after a rollback.
583 const ran = { ...row(1), item: { ...row(1).item, runId } };
584 const merged = mergeOlderHistoryIntoProjection(coldOpen, [
585 { ...row(0), position: 0 },
586 ran,
587 {
588 position: 1,
589 visibility: "local",
590 sourceThreadId: v2ThreadId,
591 sourceItemId: card.id,
592 item: card,
593 },
594 ]);
595
596 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(
597 status === "rolled_back"
598 ? ["item-0", "item-5"]
599 : ["item-0", "item-1", "item-question", "item-5"],
600 );
601 expect(merged.turnItems).toContain(card);
602 const pending = derivePendingThreadRequests(merged).userInputs;
603 expect(pending).toEqual(derivePendingThreadRequests(coldOpen).userInputs);
604 expect(pending).toHaveLength(1);
605 expect(pending[0]).toMatchObject({
606 requestId: card.requestId,
607 dismissible: true,
608 questions: card.questions.map((question) => ({ ...question, multiSelect: false })),
609 });
610 },
611 );
612
613 it("keeps a history-page interrupt result visible when its request was retained at cold open", () => {
614 const runId = "run-interrupt-cold" as never;
615 const nodeId = "node-interrupt-cold" as never;
616 const recent = row(5);
617 const requestItem = {
618 id: "item-interrupt-request" as never,
619 type: "run_interrupt_request" as const,
620 threadId: v2ThreadId,
621 runId,
622 nodeId,
623 providerThreadId: null,
624 providerTurnId: null,
625 nativeItemRef: null,
626 parentItemId: null,
627 ordinal: 1,
628 status: "completed" as const,
629 title: null,
630 message: "Stopping",
631 startedAt: NOW,
632 completedAt: NOW,
633 updatedAt: NOW,
634 };
635 const resultItem = {
636 id: "item-interrupt-result" as never,
637 type: "run_interrupt_result" as const,
638 threadId: v2ThreadId,
639 runId,
640 nodeId,
641 providerThreadId: null,
642 providerTurnId: null,
643 nativeItemRef: null,
644 parentItemId: null,
645 ordinal: 2,
646 status: "completed" as const,
647 title: null,
648 message: "Stopped",
649 startedAt: NOW,
650 completedAt: NOW,
651 updatedAt: NOW,
652 };
653 const resultRow = {
654 position: 0,
655 visibility: "local" as const,
656 sourceThreadId: v2ThreadId,
657 sourceItemId: resultItem.id,
658 item: resultItem,
659 };
660 const coldOpen = {
661 ...v2Projection,
662 runs: [
663 {
664 id: runId,
665 threadId: v2ThreadId,
666 ordinal: 1,
667 providerInstanceId: "codex" as never,
668 modelSelection: { instanceId: "codex" as never, model: "gpt-5" },
669 providerThreadId: null,
670 userMessageId: "message-1" as never,
671 rootNodeId: nodeId,
672 activeAttemptId: null,
673 status: "running" as const,
674 requestedAt: NOW,
675 startedAt: NOW,
676 completedAt: null,
677 checkpointId: null,
678 contextHandoffId: null,
679 },
680 ],
681 attempts: [
682 {
683 id: "attempt-1" as never,
684 runId,
685 attemptOrdinal: 1,
686 rootNodeId: nodeId,
687 providerInstanceId: "codex" as never,
688 providerThreadId: "provider-thread-1" as never,
689 providerTurnId: null,
690 reason: "initial" as const,
691 status: "running" as const,
692 startedAt: NOW,
693 completedAt: null,
694 },
695 ],
696 turnItems: [requestItem, recent.item],
697 visibleTurnItems: [{ ...recent, position: 0 }],
698 };
699
700 const requestMerged = mergeOlderHistoryIntoProjection(coldOpen, [
701 {
702 position: 0,
703 visibility: "local",
704 sourceThreadId: v2ThreadId,
705 sourceItemId: requestItem.id,
706 item: requestItem,
707 },
708 ]);
709 expect(requestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
710 "item-interrupt-request",
711 "item-5",
712 ]);
713
714 const rolledBackRequestMerged = mergeOlderHistoryIntoProjection(
715 {
716 ...coldOpen,
717 runs: coldOpen.runs.map((run) => ({
718 ...run,
719 status: "rolled_back" as const,
720 completedAt: NOW,
721 })),
722 },
723 [
724 {
725 position: 0,
726 visibility: "local",
727 sourceThreadId: v2ThreadId,
728 sourceItemId: requestItem.id,
729 item: requestItem,
730 },
731 ],
732 );
733 expect(
734 rolledBackRequestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId)),
735 ).toEqual(["item-5"]);
736
737 const merged = mergeOlderHistoryIntoProjection(coldOpen, [resultRow]);
738 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
739 "item-interrupt-result",
740 "item-5",
741 ]);
742 expect(merged.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(true);
743 expect(merged.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(true);
744
745 const attemptSuperseded = applyOrchestrationV2ProjectionEvent(
746 merged,
747 {
748 id: "event-attempt-superseded" as never,
749 type: "run-attempt.updated",
750 threadId: v2ThreadId,
751 runId,
752 occurredAt: NOW,
753 payload: {
754 id: "attempt-1" as never,
755 runId,
756 attemptOrdinal: 1,
757 rootNodeId: nodeId,
758 providerInstanceId: "codex" as never,
759 providerThreadId: "provider-thread-1" as never,
760 providerTurnId: null,
761 reason: "initial",
762 status: "superseded",
763 startedAt: NOW,
764 completedAt: NOW,
765 },
766 } as never,
767 { partialTimeline: true },
768 );
769
770 expect(attemptSuperseded?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
771 "item-interrupt-result",
772 "item-5",
773 ]);
774
775 const withoutRequest = {
776 ...merged,
777 turnItems: merged.turnItems.filter((item) => item.type !== "run_interrupt_request"),
778 };
779 const hidden = applyOrchestrationV2ProjectionEvent(
780 withoutRequest,
781 {
782 id: "event-attempt-superseded-missing" as never,
783 type: "run-attempt.updated",
784 threadId: v2ThreadId,
785 runId,
786 occurredAt: NOW,
787 payload: {
788 id: "attempt-1" as never,
789 runId,
790 attemptOrdinal: 1,
791 rootNodeId: nodeId,
792 providerInstanceId: "codex" as never,
793 providerThreadId: "provider-thread-1" as never,
794 providerTurnId: null,
795 reason: "initial",
796 status: "superseded",
797 startedAt: NOW,
798 completedAt: NOW,
799 },
800 } as never,
801 { partialTimeline: true },
802 );
803 expect(hidden?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(["item-5"]);
804 });
805
806 it("keeps paging across notifications and agent turns when hasEarlierUserMessage is set, within per-click bounds", () => {
807 const notification = {
808 ...row(1),
809 item: {
810 ...row(1).item,
811 type: "notification" as const,
812 source: { kind: "monitor" as const },
813 outcome: "completed" as const,
814 summary: "Checks finished",
815 },
816 };
817 const next = nextEarlierHistoryContinuationBudget(
818 {
819 items: [notification],
820 hasMoreHistory: true,
821 hasEarlierUserMessage: true,
822 },
823 EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET,
824 );
825 expect(next).toEqual({
826 pages: 1,
827 items: 1,
828 bytes: JSON.stringify([notification]).length,
829 });
830 expect(
831 nextEarlierHistoryContinuationBudget(
832 {
833 items: [notification],
834 hasMoreHistory: true,
835 hasEarlierUserMessage: true,
836 },
837 { pages: MAX_AUTO_CONTINUE_HISTORY_PAGES - 2, items: 1, bytes: 1 },
838 ),
839 ).not.toBeNull();
840 expect(
841 nextEarlierHistoryContinuationBudget(
842 {
843 items: [notification],
844 hasMoreHistory: true,
845 hasEarlierUserMessage: true,
846 },
847 { pages: MAX_AUTO_CONTINUE_HISTORY_PAGES - 1, items: 1, bytes: 1 },
848 ),
849 ).toBeNull();
850 expect(
851 nextEarlierHistoryContinuationBudget(
852 {
853 items: [notification],
854 hasMoreHistory: true,
855 hasEarlierUserMessage: true,
856 },
857 { pages: 1, items: MAX_AUTO_CONTINUE_HISTORY_ITEMS - 2, bytes: 1 },
858 ),
859 ).not.toBeNull();
860 expect(
861 nextEarlierHistoryContinuationBudget(
862 {
863 items: [notification],
864 hasMoreHistory: true,
865 hasEarlierUserMessage: true,
866 },
867 { pages: 1, items: MAX_AUTO_CONTINUE_HISTORY_ITEMS - 1, bytes: 1 },
868 ),
869 ).toBeNull();
870 expect(
871 nextEarlierHistoryContinuationBudget(
872 {
873 items: [notification],
874 hasMoreHistory: true,
875 hasEarlierUserMessage: true,
876 },
877 { pages: 1, items: 1, bytes: MAX_AUTO_CONTINUE_HISTORY_BYTES - 1 },
878 ),
879 ).toBeNull();
880 expect(
881 nextEarlierHistoryContinuationBudget(
882 {
883 items: [notification],
884 hasMoreHistory: true,
885 },
886 EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET,
887 ),
888 ).toBeNull();
889 expect(
890 nextEarlierHistoryContinuationBudget(
891 {
892 items: [row(1)],
893 hasMoreHistory: true,
894 },
895 EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET,
896 ),
897 ).not.toBeNull();
898 expect(
899 nextEarlierHistoryContinuationBudget(
900 {
901 items: [row(1)],
902 hasMoreHistory: true,
903 detached: true,
904 hasEarlierUserMessage: true,
905 },
906 EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET,
907 ),
908 ).toBeNull();
909 expect(
910 nextEarlierHistoryContinuationBudget(
911 {
912 items: [row(1)],
913 hasMoreHistory: false,
914 hasEarlierUserMessage: true,
915 },
916 EMPTY_EARLIER_HISTORY_CONTINUATION_BUDGET,
917 ),
918 ).toBeNull();
919 });
920});