Open History to see the last commit
1import type { OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3import * as DateTime from "effect/DateTime";
4
5import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
6import {
7 applyHistoryPageMeta,
8 clearActiveHistoryLoading,
9 isActiveHistoryRequestCursor,
10 mergeOlderHistoryIntoProjection,
11 shouldShowLoadEarlierControl,
12} from "./threadHistoryMerge.ts";
13import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
14
15const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
16
17function row(index: number): OrchestrationV2ProjectedTurnItem {
18 const id = `item-${index}` as never;
19 return {
20 position: index,
21 visibility: "local",
22 sourceThreadId: v2ThreadId,
23 sourceItemId: id,
24 item: {
25 id,
26 type: "command_execution",
27 threadId: v2ThreadId,
28 runId: null,
29 nodeId: null,
30 providerThreadId: null,
31 providerTurnId: null,
32 nativeItemRef: null,
33 parentItemId: null,
34 ordinal: index + 1,
35 status: "completed",
36 title: `Command ${index}`,
37 input: `cmd-${index}`,
38 output: `out-${index}`,
39 exitCode: 0,
40 startedAt: NOW,
41 completedAt: NOW,
42 updatedAt: NOW,
43 },
44 };
45}
46
47describe("threadHistoryMerge", () => {
48 it("fills activity around partial messages in canonical order and preserves live edits", () => {
49 const initial = { ...v2Projection, turnItems: [row(4).item], visibleTurnItems: [row(4)] };
50 const preview = [row(1), row(3)];
51 const partial = mergeOlderHistoryIntoProjection(initial, preview);
52 const updated = { ...row(1), item: { ...row(1).item, title: "newer live title" } };
53 const live = {
54 ...partial,
55 visibleTurnItems: partial.visibleTurnItems.map((entry) =>
56 entry.sourceItemId === updated.sourceItemId ? updated : entry,
57 ),
58 turnItems: partial.turnItems.map((item) =>
59 item.id === updated.item.id ? updated.item : item,
60 ),
61 };
62 const complete = mergeOlderHistoryIntoProjection(live, [row(0), row(1), row(2), row(3)]);
63 expect(complete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
64 "item-0",
65 "item-1",
66 "item-2",
67 "item-3",
68 "item-4",
69 ]);
70 expect(complete.visibleTurnItems[1]?.item).toBe(updated.item);
71 expect(complete.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3, 4]);
72 expect(new Set(complete.turnItems.map((item) => item.id)).size).toBe(5);
73 const hidden = {
74 ...partial,
75 visibleTurnItems: partial.visibleTurnItems.filter(
76 (entry) => entry.sourceItemId !== preview[0]!.sourceItemId,
77 ),
78 };
79 const hiddenComplete = mergeOlderHistoryIntoProjection(hidden, [
80 row(0),
81 row(1),
82 row(2),
83 row(3),
84 ]);
85 expect(hiddenComplete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
86 "item-0",
87 "item-2",
88 "item-3",
89 "item-4",
90 ]);
91 });
92
93 it("prepends older rows and dedupes by source identity", () => {
94 const recent = [row(2), row(3)];
95 const projection = {
96 ...v2Projection,
97 turnItems: recent.map((entry) => entry.item),
98 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
99 };
100 const older = [row(0), row(1), row(2)];
101 const merged = mergeOlderHistoryIntoProjection(projection, older);
102 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
103 "item-0",
104 "item-1",
105 "item-2",
106 "item-3",
107 ]);
108 expect(merged.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3]);
109 expect(merged.turnItems.map((item) => item.id)).toEqual([
110 "item-2",
111 "item-3",
112 "item-0",
113 "item-1",
114 ]);
115 });
116
117 it("fills inherited activity without confusing identical item IDs from different source threads", () => {
118 const inherited = (index: number) => ({
119 ...row(index),
120 visibility: "inherited" as const,
121 sourceThreadId: "fork-source" as never,
122 });
123 const local = row(1);
124 const preview = { ...inherited(1), item: { ...row(1).item, title: "newer inherited title" } };
125 const projection = {
126 ...v2Projection,
127 turnItems: [local.item],
128 visibleTurnItems: [preview, local],
129 };
130 const merged = mergeOlderHistoryIntoProjection(projection, [inherited(0), inherited(1)]);
131 expect(
132 merged.visibleTurnItems.map((entry) => [entry.sourceThreadId, entry.sourceItemId]),
133 ).toEqual([
134 ["fork-source", "item-0"],
135 ["fork-source", "item-1"],
136 [v2ThreadId, "item-1"],
137 ]);
138 expect(merged.visibleTurnItems[1]?.item).toBe(preview.item);
139 expect(merged.turnItems).toEqual([local.item]);
140 expect(mergeOlderHistoryIntoProjection(merged, [inherited(0), inherited(1)])).toBe(merged);
141 });
142
143 it("retains live rows that arrived after the older page was fetched", () => {
144 const live = [row(5), row(6)];
145 const projection = {
146 ...v2Projection,
147 turnItems: live.map((entry) => entry.item),
148 visibleTurnItems: live.map((entry, position) => ({ ...entry, position })),
149 };
150 const older = [row(3), row(4)];
151 const merged = mergeOlderHistoryIntoProjection(projection, older);
152 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
153 "item-3",
154 "item-4",
155 "item-5",
156 "item-6",
157 ]);
158 });
159
160 it("does not resurrect a local item hidden while an older page was in flight", () => {
161 const stalePageRow = row(1);
162 const currentItem = {
163 ...stalePageRow.item,
164 output: "newer live output",
165 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
166 };
167 const projection = {
168 ...v2Projection,
169 turnItems: [currentItem],
170 visibleTurnItems: [],
171 };
172
173 const merged = mergeOlderHistoryIntoProjection(projection, [stalePageRow]);
174
175 expect(merged).toBe(projection);
176 expect(merged.turnItems).toEqual([currentItem]);
177 expect(merged.visibleTurnItems).toEqual([]);
178 });
179
180 it("marks history expanded after a successful page", () => {
181 const next = applyHistoryPageMeta(
182 {
183 historyCursor: "cursor-a",
184 hasMoreHistory: true,
185 loading: true,
186 error: null,
187 expanded: false,
188 latestLocalTurnOrdinal: 42,
189 },
190 { nextCursor: "cursor-b", hasMoreHistory: true },
191 );
192 expect(next).toEqual({
193 historyCursor: "cursor-b",
194 hasMoreHistory: true,
195 loading: false,
196 error: null,
197 expanded: true,
198 latestLocalTurnOrdinal: 42,
199 });
200 });
201
202 it("only applies history responses for the active request cursor", () => {
203 expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: "cursor-a" })).toBe(true);
204 expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: "cursor-b" })).toBe(false);
205 expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: null })).toBe(false);
206 });
207
208 it("clears loading on interrupt only for the active request cursor", () => {
209 const loading = {
210 historyCursor: "cursor-a",
211 hasMoreHistory: true,
212 loading: true,
213 error: null,
214 expanded: false,
215 latestLocalTurnOrdinal: 10,
216 };
217 expect(clearActiveHistoryLoading("cursor-a", loading)).toEqual({
218 ...loading,
219 loading: false,
220 });
221 expect(
222 clearActiveHistoryLoading("cursor-a", { ...loading, historyCursor: "cursor-b" }),
223 ).toEqual({ ...loading, historyCursor: "cursor-b" });
224 const idle = { ...loading, loading: false };
225 expect(clearActiveHistoryLoading("cursor-a", idle)).toBe(idle);
226 });
227
228 it("shows the load-earlier control when history remains or a local error is set", () => {
229 expect(
230 shouldShowLoadEarlierControl({
231 historyCursor: "c",
232 hasMoreHistory: true,
233 loading: false,
234 error: null,
235 expanded: false,
236 latestLocalTurnOrdinal: null,
237 }),
238 ).toBe(true);
239 expect(
240 shouldShowLoadEarlierControl({
241 historyCursor: null,
242 hasMoreHistory: false,
243 loading: false,
244 error: "Could not load earlier activity.",
245 expanded: true,
246 latestLocalTurnOrdinal: null,
247 }),
248 ).toBe(true);
249 expect(
250 shouldShowLoadEarlierControl({
251 historyCursor: null,
252 hasMoreHistory: false,
253 loading: false,
254 error: null,
255 expanded: false,
256 latestLocalTurnOrdinal: null,
257 }),
258 ).toBe(false);
259 });
260
261 it("retains merged older rows when a live turn-item update arrives", () => {
262 const recent = [row(2), row(3)];
263 const projection = {
264 ...v2Projection,
265 turnItems: recent.map((entry) => entry.item),
266 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
267 };
268 const merged = mergeOlderHistoryIntoProjection(projection, [row(0), row(1)]);
269 const liveItem = {
270 ...row(3).item,
271 output: "streamed",
272 };
273 const next = applyOrchestrationV2ProjectionEvent(merged, {
274 id: "event-live-item" as never,
275 type: "turn-item.updated",
276 threadId: v2ThreadId,
277 occurredAt: NOW,
278 payload: liveItem,
279 } as never);
280 expect(next?.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
281 "item-0",
282 "item-1",
283 "item-2",
284 "item-3",
285 ]);
286 expect(next?.visibleTurnItems[3]?.item).toEqual(liveItem);
287 });
288
289 it("keeps a history-page interrupt result visible when its request was retained at cold open", () => {
290 const runId = "run-interrupt-cold" as never;
291 const nodeId = "node-interrupt-cold" as never;
292 const recent = row(5);
293 const requestItem = {
294 id: "item-interrupt-request" as never,
295 type: "run_interrupt_request" as const,
296 threadId: v2ThreadId,
297 runId,
298 nodeId,
299 providerThreadId: null,
300 providerTurnId: null,
301 nativeItemRef: null,
302 parentItemId: null,
303 ordinal: 1,
304 status: "completed" as const,
305 title: null,
306 message: "Stopping",
307 startedAt: NOW,
308 completedAt: NOW,
309 updatedAt: NOW,
310 };
311 const resultItem = {
312 id: "item-interrupt-result" as never,
313 type: "run_interrupt_result" as const,
314 threadId: v2ThreadId,
315 runId,
316 nodeId,
317 providerThreadId: null,
318 providerTurnId: null,
319 nativeItemRef: null,
320 parentItemId: null,
321 ordinal: 2,
322 status: "completed" as const,
323 title: null,
324 message: "Stopped",
325 startedAt: NOW,
326 completedAt: NOW,
327 updatedAt: NOW,
328 };
329 const resultRow = {
330 position: 0,
331 visibility: "local" as const,
332 sourceThreadId: v2ThreadId,
333 sourceItemId: resultItem.id,
334 item: resultItem,
335 };
336 const coldOpen = {
337 ...v2Projection,
338 runs: [
339 {
340 id: runId,
341 threadId: v2ThreadId,
342 ordinal: 1,
343 providerInstanceId: "codex" as never,
344 modelSelection: { instanceId: "codex" as never, model: "gpt-5" },
345 providerThreadId: null,
346 userMessageId: "message-1" as never,
347 rootNodeId: nodeId,
348 activeAttemptId: null,
349 status: "running" as const,
350 requestedAt: NOW,
351 startedAt: NOW,
352 completedAt: null,
353 checkpointId: null,
354 contextHandoffId: null,
355 },
356 ],
357 attempts: [
358 {
359 id: "attempt-1" as never,
360 runId,
361 attemptOrdinal: 1,
362 rootNodeId: nodeId,
363 providerInstanceId: "codex" as never,
364 providerThreadId: "provider-thread-1" as never,
365 providerTurnId: null,
366 reason: "initial" as const,
367 status: "running" as const,
368 startedAt: NOW,
369 completedAt: null,
370 },
371 ],
372 turnItems: [requestItem, recent.item],
373 visibleTurnItems: [{ ...recent, position: 0 }],
374 };
375
376 const requestMerged = mergeOlderHistoryIntoProjection(coldOpen, [
377 {
378 position: 0,
379 visibility: "local",
380 sourceThreadId: v2ThreadId,
381 sourceItemId: requestItem.id,
382 item: requestItem,
383 },
384 ]);
385 expect(requestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
386 "item-interrupt-request",
387 "item-5",
388 ]);
389
390 const rolledBackRequestMerged = mergeOlderHistoryIntoProjection(
391 {
392 ...coldOpen,
393 runs: coldOpen.runs.map((run) => ({
394 ...run,
395 status: "rolled_back" as const,
396 completedAt: NOW,
397 })),
398 },
399 [
400 {
401 position: 0,
402 visibility: "local",
403 sourceThreadId: v2ThreadId,
404 sourceItemId: requestItem.id,
405 item: requestItem,
406 },
407 ],
408 );
409 expect(
410 rolledBackRequestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId)),
411 ).toEqual(["item-5"]);
412
413 const merged = mergeOlderHistoryIntoProjection(coldOpen, [resultRow]);
414 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
415 "item-interrupt-result",
416 "item-5",
417 ]);
418 expect(merged.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(true);
419 expect(merged.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(true);
420
421 const attemptSuperseded = applyOrchestrationV2ProjectionEvent(
422 merged,
423 {
424 id: "event-attempt-superseded" as never,
425 type: "run-attempt.updated",
426 threadId: v2ThreadId,
427 runId,
428 occurredAt: NOW,
429 payload: {
430 id: "attempt-1" as never,
431 runId,
432 attemptOrdinal: 1,
433 rootNodeId: nodeId,
434 providerInstanceId: "codex" as never,
435 providerThreadId: "provider-thread-1" as never,
436 providerTurnId: null,
437 reason: "initial",
438 status: "superseded",
439 startedAt: NOW,
440 completedAt: NOW,
441 },
442 } as never,
443 { partialTimeline: true },
444 );
445
446 expect(attemptSuperseded?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
447 "item-interrupt-result",
448 "item-5",
449 ]);
450
451 const withoutRequest = {
452 ...merged,
453 turnItems: merged.turnItems.filter((item) => item.type !== "run_interrupt_request"),
454 };
455 const hidden = applyOrchestrationV2ProjectionEvent(
456 withoutRequest,
457 {
458 id: "event-attempt-superseded-missing" as never,
459 type: "run-attempt.updated",
460 threadId: v2ThreadId,
461 runId,
462 occurredAt: NOW,
463 payload: {
464 id: "attempt-1" as never,
465 runId,
466 attemptOrdinal: 1,
467 rootNodeId: nodeId,
468 providerInstanceId: "codex" as never,
469 providerThreadId: "provider-thread-1" as never,
470 providerTurnId: null,
471 reason: "initial",
472 status: "superseded",
473 startedAt: NOW,
474 completedAt: NOW,
475 },
476 } as never,
477 { partialTimeline: true },
478 );
479 expect(hidden?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(["item-5"]);
480 });
481});