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

threadHistoryMerge.test.ts

416 lines12.5 KB

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 };
46​
47describe("threadHistoryMerge", () => {
48 it("prepends older rows and dedupes by source identity", () => {
49 const recent = [row(2), row(3)];
50 const projection = {
51 ...v2Projection,
52 turnItems: recent.map((entry) => entry.item),
53 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
54 };
55 const older = [row(0), row(1), row(2)];
56 const merged = mergeOlderHistoryIntoProjection(projection, older);
57 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
58 "item-0",
59 "item-1",
60 "item-2",
61 "item-3",
62 ]);
63 expect(merged.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3]);
64 expect(merged.turnItems.map((item) => item.id)).toEqual([
65 "item-2",
66 "item-3",
67 "item-0",
68 "item-1",
69 ]);
70 });
71​
72 it("retains live rows that arrived after the older page was fetched", () => {
73 const live = [row(5), row(6)];
74 const projection = {
75 ...v2Projection,
76 turnItems: live.map((entry) => entry.item),
77 visibleTurnItems: live.map((entry, position) => ({ ...entry, position })),
78 };
79 const older = [row(3), row(4)];
80 const merged = mergeOlderHistoryIntoProjection(projection, older);
81 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
82 "item-3",
83 "item-4",
84 "item-5",
85 "item-6",
86 ]);
87 });
88​
89 it("does not resurrect a local item hidden while an older page was in flight", () => {
90 const stalePageRow = row(1);
91 const currentItem = {
92 ...stalePageRow.item,
93 output: "newer live output",
94 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
95 };
96 const projection = {
97 ...v2Projection,
98 turnItems: [currentItem],
99 visibleTurnItems: [],
100 };
101​
102 const merged = mergeOlderHistoryIntoProjection(projection, [stalePageRow]);
103​
104 expect(merged).toBe(projection);
105 expect(merged.turnItems).toEqual([currentItem]);
106 expect(merged.visibleTurnItems).toEqual([]);
107 });
108​
109 it("marks history expanded after a successful page", () => {
110 const next = applyHistoryPageMeta(
111 {
112 historyCursor: "cursor-a",
113 hasMoreHistory: true,
114 loading: true,
115 error: null,
116 expanded: false,
117 latestLocalTurnOrdinal: 42,
118 },
119 { nextCursor: "cursor-b", hasMoreHistory: true },
120 );
121 expect(next).toEqual({
122 historyCursor: "cursor-b",
123 hasMoreHistory: true,
124 loading: false,
125 error: null,
126 expanded: true,
127 latestLocalTurnOrdinal: 42,
128 });
129 });
130​
131 it("only applies history responses for the active request cursor", () => {
132 expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: "cursor-a" })).toBe(true);
133 expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: "cursor-b" })).toBe(false);
134 expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: null })).toBe(false);
135 });
136​
137 it("clears loading on interrupt only for the active request cursor", () => {
138 const loading = {
139 historyCursor: "cursor-a",
140 hasMoreHistory: true,
141 loading: true,
142 error: null,
143 expanded: false,
144 latestLocalTurnOrdinal: 10,
145 };
146 expect(clearActiveHistoryLoading("cursor-a", loading)).toEqual({
147 ...loading,
148 loading: false,
149 });
150 // Stale cursor must not mutate replacement progressive meta.
151 expect(
152 clearActiveHistoryLoading("cursor-a", { ...loading, historyCursor: "cursor-b" }),
153 ).toEqual({ ...loading, historyCursor: "cursor-b" });
154 // Already idle: identity-preserving no-op shape.
155 const idle = { ...loading, loading: false };
156 expect(clearActiveHistoryLoading("cursor-a", idle)).toBe(idle);
157 });
158​
159 it("shows the load-earlier control when history remains or a local error is set", () => {
160 expect(
161 shouldShowLoadEarlierControl({
162 historyCursor: "c",
163 hasMoreHistory: true,
164 loading: false,
165 error: null,
166 expanded: false,
167 latestLocalTurnOrdinal: null,
168 }),
169 ).toBe(true);
170 expect(
171 shouldShowLoadEarlierControl({
172 historyCursor: null,
173 hasMoreHistory: false,
174 loading: false,
175 error: "Could not load earlier activity.",
176 expanded: true,
177 latestLocalTurnOrdinal: null,
178 }),
179 ).toBe(true);
180 expect(
181 shouldShowLoadEarlierControl({
182 historyCursor: null,
183 hasMoreHistory: false,
184 loading: false,
185 error: null,
186 expanded: false,
187 latestLocalTurnOrdinal: null,
188 }),
189 ).toBe(false);
190 });
191​
192 it("retains merged older rows when a live turn-item update arrives", () => {
193 const recent = [row(2), row(3)];
194 const projection = {
195 ...v2Projection,
196 turnItems: recent.map((entry) => entry.item),
197 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
198 };
199 const merged = mergeOlderHistoryIntoProjection(projection, [row(0), row(1)]);
200 const liveItem = {
201 ...row(3).item,
202 output: "streamed",
203 };
204 const next = applyOrchestrationV2ProjectionEvent(merged, {
205 id: "event-live-item" as never,
206 type: "turn-item.updated",
207 threadId: v2ThreadId,
208 occurredAt: NOW,
209 payload: liveItem,
210 } as never);
211 expect(next?.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
212 "item-0",
213 "item-1",
214 "item-2",
215 "item-3",
216 ]);
217 expect(next?.visibleTurnItems[3]?.item).toEqual(liveItem);
218 });
219​
220 it("keeps a history-page interrupt result visible when its request was retained at cold open", () => {
221 // Cold bounded window: only a recent filler. Request was retained in
222 // turnItems (not visible). Result arrives later via load-earlier merge.
223 const runId = "run-interrupt-cold" as never;
224 const nodeId = "node-interrupt-cold" as never;
225 const recent = row(5);
226 const requestItem = {
227 id: "item-interrupt-request" as never,
228 type: "run_interrupt_request" as const,
229 threadId: v2ThreadId,
230 runId,
231 nodeId,
232 providerThreadId: null,
233 providerTurnId: null,
234 nativeItemRef: null,
235 parentItemId: null,
236 ordinal: 1,
237 status: "completed" as const,
238 title: null,
239 message: "Stopping",
240 startedAt: NOW,
241 completedAt: NOW,
242 updatedAt: NOW,
243 };
244 const resultItem = {
245 id: "item-interrupt-result" as never,
246 type: "run_interrupt_result" as const,
247 threadId: v2ThreadId,
248 runId,
249 nodeId,
250 providerThreadId: null,
251 providerTurnId: null,
252 nativeItemRef: null,
253 parentItemId: null,
254 ordinal: 2,
255 status: "completed" as const,
256 title: null,
257 message: "Stopped",
258 startedAt: NOW,
259 completedAt: NOW,
260 updatedAt: NOW,
261 };
262 const resultRow = {
263 position: 0,
264 visibility: "local" as const,
265 sourceThreadId: v2ThreadId,
266 sourceItemId: resultItem.id,
267 item: resultItem,
268 };
269 const coldOpen = {
270 ...v2Projection,
271 runs: [
272 {
273 id: runId,
274 threadId: v2ThreadId,
275 ordinal: 1,
276 providerInstanceId: "codex" as never,
277 modelSelection: { instanceId: "codex" as never, model: "gpt-5" },
278 providerThreadId: null,
279 userMessageId: "message-1" as never,
280 rootNodeId: nodeId,
281 activeAttemptId: null,
282 status: "running" as const,
283 requestedAt: NOW,
284 startedAt: NOW,
285 completedAt: null,
286 checkpointId: null,
287 contextHandoffId: null,
288 },
289 ],
290 attempts: [
291 {
292 id: "attempt-1" as never,
293 runId,
294 attemptOrdinal: 1,
295 rootNodeId: nodeId,
296 providerInstanceId: "codex" as never,
297 providerThreadId: "provider-thread-1" as never,
298 providerTurnId: null,
299 reason: "initial" as const,
300 status: "running" as const,
301 startedAt: NOW,
302 completedAt: null,
303 },
304 ],
305 // Request retained from full projection; no result yet in the window.
306 turnItems: [requestItem, recent.item],
307 visibleTurnItems: [{ ...recent, position: 0 }],
308 };
309​
310 const requestMerged = mergeOlderHistoryIntoProjection(coldOpen, [
311 {
312 position: 0,
313 visibility: "local",
314 sourceThreadId: v2ThreadId,
315 sourceItemId: requestItem.id,
316 item: requestItem,
317 },
318 ]);
319 expect(requestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
320 "item-interrupt-request",
321 "item-5",
322 ]);
323​
324 const rolledBackRequestMerged = mergeOlderHistoryIntoProjection(
325 {
326 ...coldOpen,
327 runs: coldOpen.runs.map((run) => ({
328 ...run,
329 status: "rolled_back" as const,
330 completedAt: NOW,
331 })),
332 },
333 [
334 {
335 position: 0,
336 visibility: "local",
337 sourceThreadId: v2ThreadId,
338 sourceItemId: requestItem.id,
339 item: requestItem,
340 },
341 ],
342 );
343 expect(
344 rolledBackRequestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId)),
345 ).toEqual(["item-5"]);
346​
347 const merged = mergeOlderHistoryIntoProjection(coldOpen, [resultRow]);
348 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
349 "item-interrupt-result",
350 "item-5",
351 ]);
352 expect(merged.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(true);
353 expect(merged.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(true);
354​
355 const attemptSuperseded = applyOrchestrationV2ProjectionEvent(
356 merged,
357 {
358 id: "event-attempt-superseded" as never,
359 type: "run-attempt.updated",
360 threadId: v2ThreadId,
361 runId,
362 occurredAt: NOW,
363 payload: {
364 id: "attempt-1" as never,
365 runId,
366 attemptOrdinal: 1,
367 rootNodeId: nodeId,
368 providerInstanceId: "codex" as never,
369 providerThreadId: "provider-thread-1" as never,
370 providerTurnId: null,
371 reason: "initial",
372 status: "superseded",
373 startedAt: NOW,
374 completedAt: NOW,
375 },
376 } as never,
377 { partialTimeline: true },
378 );
379​
380 expect(attemptSuperseded?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
381 "item-interrupt-result",
382 "item-5",
383 ]);
384​
385 // Without the cold-open retained request, the same update would hide the result.
386 const withoutRequest = {
387 ...merged,
388 turnItems: merged.turnItems.filter((item) => item.type !== "run_interrupt_request"),
389 };
390 const hidden = applyOrchestrationV2ProjectionEvent(
391 withoutRequest,
392 {
393 id: "event-attempt-superseded-missing" as never,
394 type: "run-attempt.updated",
395 threadId: v2ThreadId,
396 runId,
397 occurredAt: NOW,
398 payload: {
399 id: "attempt-1" as never,
400 runId,
401 attemptOrdinal: 1,
402 rootNodeId: nodeId,
403 providerInstanceId: "codex" as never,
404 providerThreadId: "provider-thread-1" as never,
405 providerTurnId: null,
406 reason: "initial",
407 status: "superseded",
408 startedAt: NOW,
409 completedAt: NOW,
410 },
411 } as never,
412 { partialTimeline: true },
413 );
414 expect(hidden?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(["item-5"]);
415 });
416});