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

threadHistoryMerge.test.ts

800 lines27.2 KB

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