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

threadHistoryMerge.test.ts

571 lines18.2 KB

1import type { OrchestrationV2ProjectedTurnItem, OrchestrationV2Subagent } 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 mergeOlderHistoryIntoProjection,
8 mergeOlderSubagentsIntoProjection,
9} from "./threadHistoryMerge.ts";
10import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
11import { derivePendingThreadRequests } from "./threadRequests.ts";
12​
13const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
14​
15function row(index: number): OrchestrationV2ProjectedTurnItem {
16 const id = `item-${index}` as never;
17 return {
18 position: index,
19 visibility: "local",
20 sourceThreadId: v2ThreadId,
21 sourceItemId: id,
22 item: {
23 id,
24 type: "command_execution",
25 threadId: v2ThreadId,
26 runId: null,
27 nodeId: null,
28 providerThreadId: null,
29 providerTurnId: null,
30 nativeItemRef: null,
31 parentItemId: null,
32 ordinal: index + 1,
33 status: "completed",
34 title: `Command ${index}`,
35 input: `cmd-${index}`,
36 output: `out-${index}`,
37 exitCode: 0,
38 startedAt: NOW,
39 completedAt: NOW,
40 updatedAt: NOW,
41 },
42 };
44​
45describe("threadHistoryMerge", () => {
46 it("fills activity around partial messages in canonical order and preserves live edits", () => {
47 const initial = { ...v2Projection, turnItems: [row(4).item], visibleTurnItems: [row(4)] };
48 const preview = [row(1), row(3)];
49 const partial = mergeOlderHistoryIntoProjection(initial, preview);
50 const updated = { ...row(1), item: { ...row(1).item, title: "newer live title" } };
51 const live = {
52 ...partial,
53 visibleTurnItems: partial.visibleTurnItems.map((entry) =>
54 entry.sourceItemId === updated.sourceItemId ? updated : entry,
55 ),
56 turnItems: partial.turnItems.map((item) =>
57 item.id === updated.item.id ? updated.item : item,
58 ),
59 };
60 const complete = mergeOlderHistoryIntoProjection(live, [row(0), row(1), row(2), row(3)]);
61 expect(complete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
62 "item-0",
63 "item-1",
64 "item-2",
65 "item-3",
66 "item-4",
67 ]);
68 expect(complete.visibleTurnItems[1]?.item).toBe(updated.item);
69 expect(complete.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3, 4]);
70 expect(new Set(complete.turnItems.map((item) => item.id)).size).toBe(5);
71 const anchorItem = {
72 ...updated.item,
73 deferredWork: { cursor: "work", itemCount: 4, lastOrdinal: 5 },
74 };
75 const deferred = {
76 ...live,
77 turnItems: live.turnItems.map((item) => (item.id === anchorItem.id ? anchorItem : item)),
78 visibleTurnItems: live.visibleTurnItems.map((entry) =>
79 entry.item.id === anchorItem.id ? { ...entry, item: anchorItem } : entry,
80 ),
81 };
82 const loadedWork = mergeOlderHistoryIntoProjection(deferred, [row(1), row(2), row(3)], {
83 anchorId: anchorItem.id,
84 nextCursor: null,
85 });
86 expect(loadedWork.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
87 "item-1",
88 "item-2",
89 "item-3",
90 "item-4",
91 ]);
92 expect(loadedWork.visibleTurnItems[0]?.item.title).toBe("newer live title");
93 expect(loadedWork.visibleTurnItems[0]?.item.deferredWork).toBeUndefined();
94 const hidden = {
95 ...partial,
96 visibleTurnItems: partial.visibleTurnItems.filter(
97 (entry) => entry.sourceItemId !== preview[0]!.sourceItemId,
98 ),
99 };
100 const hiddenComplete = mergeOlderHistoryIntoProjection(hidden, [
101 row(0),
102 row(1),
103 row(2),
104 row(3),
105 ]);
106 expect(hiddenComplete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
107 "item-0",
108 "item-2",
109 "item-3",
110 "item-4",
111 ]);
112 });
113​
114 it("prepends older rows and dedupes by source identity", () => {
115 const recent = [row(2), row(3)];
116 const projection = {
117 ...v2Projection,
118 turnItems: recent.map((entry) => entry.item),
119 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
120 };
121 const older = [row(0), row(1), row(2)];
122 const merged = mergeOlderHistoryIntoProjection(projection, older);
123 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
124 "item-0",
125 "item-1",
126 "item-2",
127 "item-3",
128 ]);
129 expect(merged.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3]);
130 expect(merged.turnItems.map((item) => item.id)).toEqual([
131 "item-2",
132 "item-3",
133 "item-0",
134 "item-1",
135 ]);
136 });
137​
138 it("adds older subagent records and keeps the newer record of one already held", () => {
139 const subagent = (id: string, model: string) =>
140 ({ id, model, status: "completed" }) as unknown as OrchestrationV2Subagent;
141 const live = subagent("agent-live", "claude-sonnet-live");
142 const projection = { ...v2Projection, subagents: [live] };
143 const merged = mergeOlderSubagentsIntoProjection(projection, [
144 subagent("agent-old", "claude-haiku-4-5-20251001"),
145 subagent("agent-live", "claude-sonnet-stale"),
146 ]);
147 expect(merged.subagents.map((agent) => [agent.id, agent.model])).toEqual([
148 ["agent-old", "claude-haiku-4-5-20251001"],
149 ["agent-live", "claude-sonnet-live"],
150 ]);
151 expect(mergeOlderSubagentsIntoProjection(projection, undefined)).toBe(projection);
152 });
153​
154 it("fills inherited activity without confusing identical item IDs from different source threads", () => {
155 const inherited = (index: number) => ({
156 ...row(index),
157 visibility: "inherited" as const,
158 sourceThreadId: "fork-source" as never,
159 });
160 const local = row(1);
161 const preview = { ...inherited(1), item: { ...row(1).item, title: "newer inherited title" } };
162 const projection = {
163 ...v2Projection,
164 turnItems: [local.item],
165 visibleTurnItems: [preview, local],
166 };
167 const merged = mergeOlderHistoryIntoProjection(projection, [inherited(0), inherited(1)]);
168 expect(
169 merged.visibleTurnItems.map((entry) => [entry.sourceThreadId, entry.sourceItemId]),
170 ).toEqual([
171 ["fork-source", "item-0"],
172 ["fork-source", "item-1"],
173 [v2ThreadId, "item-1"],
174 ]);
175 expect(merged.visibleTurnItems[1]?.item).toBe(preview.item);
176 expect(merged.turnItems).toEqual([local.item]);
177 expect(mergeOlderHistoryIntoProjection(merged, [inherited(0), inherited(1)])).toBe(merged);
178 });
179​
180 it("retains live rows that arrived after the older page was fetched", () => {
181 const live = [row(5), row(6)];
182 const projection = {
183 ...v2Projection,
184 turnItems: live.map((entry) => entry.item),
185 visibleTurnItems: live.map((entry, position) => ({ ...entry, position })),
186 };
187 const older = [row(3), row(4)];
188 const merged = mergeOlderHistoryIntoProjection(projection, older);
189 expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
190 "item-3",
191 "item-4",
192 "item-5",
193 "item-6",
194 ]);
195 });
196​
197 it("keeps an older answer before a full page that only covers the later part of a conversation page", () => {
198 const [question, olderAnswer, reasoningA, reasoningB, reasoningC, newerAnswer] = [
199 row(0),
200 row(1),
201 row(2),
202 row(3),
203 row(4),
204 row(5),
205 ];
206 const window = [row(6), row(7)];
207 const projection = {
208 ...v2Projection,
209 turnItems: window.map((entry) => entry.item),
210 visibleTurnItems: window.map((entry, position) => ({ ...entry, position })),
211 };
212 const conversation = mergeOlderHistoryIntoProjection(projection, [
213 question,
214 olderAnswer,
215 newerAnswer,
216 ]);
217 const full = mergeOlderHistoryIntoProjection(conversation, [
218 reasoningA,
219 reasoningB,
220 reasoningC,
221 newerAnswer,
222 ]);
223 expect(full.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
224 "item-0",
225 "item-1",
226 "item-2",
227 "item-3",
228 "item-4",
229 "item-5",
230 "item-6",
231 "item-7",
232 ]);
233 });
234​
235 it("does not resurrect a local item hidden while an older page was in flight", () => {
236 const stalePageRow = row(1);
237 const currentItem = {
238 ...stalePageRow.item,
239 output: "newer live output",
240 updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
241 };
242 const projection = {
243 ...v2Projection,
244 turnItems: [currentItem],
245 visibleTurnItems: [],
246 };
247​
248 const merged = mergeOlderHistoryIntoProjection(projection, [stalePageRow]);
249​
250 expect(merged).toBe(projection);
251 expect(merged.turnItems).toEqual([currentItem]);
252 expect(merged.visibleTurnItems).toEqual([]);
253 });
254​
255 it("retains merged older rows when a live turn-item update arrives", () => {
256 const recent = [row(2), row(3)];
257 const projection = {
258 ...v2Projection,
259 turnItems: recent.map((entry) => entry.item),
260 visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })),
261 };
262 const merged = mergeOlderHistoryIntoProjection(projection, [row(0), row(1)]);
263 const liveItem = {
264 ...row(3).item,
265 output: "streamed",
266 };
267 const next = applyOrchestrationV2ProjectionEvent(merged, {
268 id: "event-live-item" as never,
269 type: "turn-item.updated",
270 threadId: v2ThreadId,
271 occurredAt: NOW,
272 payload: liveItem,
273 } as never);
274 expect(next?.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([
275 "item-0",
276 "item-1",
277 "item-2",
278 "item-3",
279 ]);
280 expect(next?.visibleTurnItems[3]?.item).toEqual(liveItem);
281 });
282​
283 // regression: #25806 a pending question card retained outside the window shows when paged in
284 it.each(["completed", "rolled_back"] as const)(
285 "keeps a pending question actionable when paging a %s run",
286 (status) => {
287 const recent = row(5);
288 const runId = "question-run" as never;
289 const nodeId = "question-node" as never;
290 const card = {
291 id: "item-question" as never,
292 type: "user_input_request" as const,
293 threadId: v2ThreadId,
294 runId,
295 nodeId,
296 providerThreadId: null,
297 providerTurnId: null,
298 nativeItemRef: null,
299 parentItemId: null,
300 ordinal: 1,
301 status: "running" as const,
302 title: null,
303 requestId: "request-question" as never,
304 responseMode: "message" as const,
305 questions: [{ id: "scope", header: "Scope", question: "Which scope?", options: [] }],
306 startedAt: NOW,
307 completedAt: null,
308 updatedAt: NOW,
309 };
310 const coldOpen = {
311 ...v2Projection,
312 runs: [
313 {
314 id: runId,
315 threadId: v2ThreadId,
316 ordinal: 1,
317 providerInstanceId: v2Projection.thread.providerInstanceId,
318 modelSelection: v2Projection.thread.modelSelection,
319 providerThreadId: null,
320 userMessageId: "question-message" as never,
321 rootNodeId: nodeId,
322 activeAttemptId: null,
323 status,
324 requestedAt: NOW,
325 startedAt: NOW,
326 completedAt: NOW,
327 checkpointId: null,
328 contextHandoffId: null,
329 },
330 ],
331 runtimeRequests: [
332 {
333 id: card.requestId,
334 nodeId,
335 providerTurnId: null,
336 nativeRequestRef: null,
337 kind: "user_input" as const,
338 status: "pending" as const,
339 responseCapability: { type: "message" as const },
340 createdAt: NOW,
341 resolvedAt: null,
342 },
343 ],
344 turnItems: [card, recent.item],
345 visibleTurnItems: [{ ...recent, position: 0 }],
346 };
347​
348 // A row of the run that was never in the window, such as one paged in after a rollback.
349 const ran = { ...row(1), item: { ...row(1).item, runId } };
350 const merged = mergeOlderHistoryIntoProjection(coldOpen, [
351 { ...row(0), position: 0 },
352 ran,
353 {
354 position: 1,
355 visibility: "local",
356 sourceThreadId: v2ThreadId,
357 sourceItemId: card.id,
358 item: card,
359 },
360 ]);
361​
362 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(
363 status === "rolled_back"
364 ? ["item-0", "item-5"]
365 : ["item-0", "item-1", "item-question", "item-5"],
366 );
367 expect(merged.turnItems).toContain(card);
368 const pending = derivePendingThreadRequests(merged).userInputs;
369 expect(pending).toEqual(derivePendingThreadRequests(coldOpen).userInputs);
370 expect(pending).toHaveLength(1);
371 expect(pending[0]).toMatchObject({
372 requestId: card.requestId,
373 dismissible: true,
374 questions: card.questions.map((question) => ({ ...question, multiSelect: false })),
375 });
376 },
377 );
378​
379 it("keeps a history-page interrupt result visible when its request was retained at cold open", () => {
380 const runId = "run-interrupt-cold" as never;
381 const nodeId = "node-interrupt-cold" as never;
382 const recent = row(5);
383 const requestItem = {
384 id: "item-interrupt-request" as never,
385 type: "run_interrupt_request" as const,
386 threadId: v2ThreadId,
387 runId,
388 nodeId,
389 providerThreadId: null,
390 providerTurnId: null,
391 nativeItemRef: null,
392 parentItemId: null,
393 ordinal: 1,
394 status: "completed" as const,
395 title: null,
396 message: "Stopping",
397 startedAt: NOW,
398 completedAt: NOW,
399 updatedAt: NOW,
400 };
401 const resultItem = {
402 id: "item-interrupt-result" as never,
403 type: "run_interrupt_result" as const,
404 threadId: v2ThreadId,
405 runId,
406 nodeId,
407 providerThreadId: null,
408 providerTurnId: null,
409 nativeItemRef: null,
410 parentItemId: null,
411 ordinal: 2,
412 status: "completed" as const,
413 title: null,
414 message: "Stopped",
415 startedAt: NOW,
416 completedAt: NOW,
417 updatedAt: NOW,
418 };
419 const resultRow = {
420 position: 0,
421 visibility: "local" as const,
422 sourceThreadId: v2ThreadId,
423 sourceItemId: resultItem.id,
424 item: resultItem,
425 };
426 const coldOpen = {
427 ...v2Projection,
428 runs: [
429 {
430 id: runId,
431 threadId: v2ThreadId,
432 ordinal: 1,
433 providerInstanceId: "codex" as never,
434 modelSelection: { instanceId: "codex" as never, model: "gpt-5" },
435 providerThreadId: null,
436 userMessageId: "message-1" as never,
437 rootNodeId: nodeId,
438 activeAttemptId: null,
439 status: "running" as const,
440 requestedAt: NOW,
441 startedAt: NOW,
442 completedAt: null,
443 checkpointId: null,
444 contextHandoffId: null,
445 },
446 ],
447 attempts: [
448 {
449 id: "attempt-1" as never,
450 runId,
451 attemptOrdinal: 1,
452 rootNodeId: nodeId,
453 providerInstanceId: "codex" as never,
454 providerThreadId: "provider-thread-1" as never,
455 providerTurnId: null,
456 reason: "initial" as const,
457 status: "running" as const,
458 startedAt: NOW,
459 completedAt: null,
460 },
461 ],
462 turnItems: [requestItem, recent.item],
463 visibleTurnItems: [{ ...recent, position: 0 }],
464 };
465​
466 const requestMerged = mergeOlderHistoryIntoProjection(coldOpen, [
467 {
468 position: 0,
469 visibility: "local",
470 sourceThreadId: v2ThreadId,
471 sourceItemId: requestItem.id,
472 item: requestItem,
473 },
474 ]);
475 expect(requestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
476 "item-interrupt-request",
477 "item-5",
478 ]);
479​
480 const rolledBackRequestMerged = mergeOlderHistoryIntoProjection(
481 {
482 ...coldOpen,
483 runs: coldOpen.runs.map((run) => ({
484 ...run,
485 status: "rolled_back" as const,
486 completedAt: NOW,
487 })),
488 },
489 [
490 {
491 position: 0,
492 visibility: "local",
493 sourceThreadId: v2ThreadId,
494 sourceItemId: requestItem.id,
495 item: requestItem,
496 },
497 ],
498 );
499 expect(
500 rolledBackRequestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId)),
501 ).toEqual(["item-5"]);
502​
503 const merged = mergeOlderHistoryIntoProjection(coldOpen, [resultRow]);
504 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
505 "item-interrupt-result",
506 "item-5",
507 ]);
508 expect(merged.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(true);
509 expect(merged.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(true);
510​
511 const attemptSuperseded = applyOrchestrationV2ProjectionEvent(
512 merged,
513 {
514 id: "event-attempt-superseded" as never,
515 type: "run-attempt.updated",
516 threadId: v2ThreadId,
517 runId,
518 occurredAt: NOW,
519 payload: {
520 id: "attempt-1" as never,
521 runId,
522 attemptOrdinal: 1,
523 rootNodeId: nodeId,
524 providerInstanceId: "codex" as never,
525 providerThreadId: "provider-thread-1" as never,
526 providerTurnId: null,
527 reason: "initial",
528 status: "superseded",
529 startedAt: NOW,
530 completedAt: NOW,
531 },
532 } as never,
533 { partialTimeline: true },
534 );
535​
536 expect(attemptSuperseded?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
537 "item-interrupt-result",
538 "item-5",
539 ]);
540​
541 const withoutRequest = {
542 ...merged,
543 turnItems: merged.turnItems.filter((item) => item.type !== "run_interrupt_request"),
544 };
545 const hidden = applyOrchestrationV2ProjectionEvent(
546 withoutRequest,
547 {
548 id: "event-attempt-superseded-missing" as never,
549 type: "run-attempt.updated",
550 threadId: v2ThreadId,
551 runId,
552 occurredAt: NOW,
553 payload: {
554 id: "attempt-1" as never,
555 runId,
556 attemptOrdinal: 1,
557 rootNodeId: nodeId,
558 providerInstanceId: "codex" as never,
559 providerThreadId: "provider-thread-1" as never,
560 providerTurnId: null,
561 reason: "initial",
562 status: "superseded",
563 startedAt: NOW,
564 completedAt: NOW,
565 },
566 } as never,
567 { partialTimeline: true },
568 );
569 expect(hidden?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(["item-5"]);
570 });
571});