The best way to control Claude Code, Codex and more from any computer or phone

main
ts 566 lines 18 KB
Raw
1 import type { OrchestrationV2ProjectedTurnItem, OrchestrationV2Subagent } from "@t3tools/contracts";
2 import { describe, expect, it } from "@effect/vitest";
3 import * as DateTime from "effect/DateTime";
4
5 import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
6 import {
7 mergeOlderHistoryIntoProjection,
8 mergeOlderSubagentsIntoProjection,
9 } from "./threadHistoryMerge.ts";
10 import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
11 import { derivePendingThreadRequests } from "./threadRequests.ts";
12
13 const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
14
15 function 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 };
43 }
44
45 describe("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 const merged = mergeOlderHistoryIntoProjection(coldOpen, [
349 { ...row(0), position: 0 },
350 {
351 position: 1,
352 visibility: "local",
353 sourceThreadId: v2ThreadId,
354 sourceItemId: card.id,
355 item: card,
356 },
357 ]);
358
359 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(
360 status === "rolled_back" ? ["item-0", "item-5"] : ["item-0", "item-question", "item-5"],
361 );
362 expect(merged.turnItems).toContain(card);
363 const pending = derivePendingThreadRequests(merged).userInputs;
364 expect(pending).toEqual(derivePendingThreadRequests(coldOpen).userInputs);
365 expect(pending).toHaveLength(1);
366 expect(pending[0]).toMatchObject({
367 requestId: card.requestId,
368 dismissible: true,
369 questions: card.questions.map((question) => ({ ...question, multiSelect: false })),
370 });
371 },
372 );
373
374 it("keeps a history-page interrupt result visible when its request was retained at cold open", () => {
375 const runId = "run-interrupt-cold" as never;
376 const nodeId = "node-interrupt-cold" as never;
377 const recent = row(5);
378 const requestItem = {
379 id: "item-interrupt-request" as never,
380 type: "run_interrupt_request" as const,
381 threadId: v2ThreadId,
382 runId,
383 nodeId,
384 providerThreadId: null,
385 providerTurnId: null,
386 nativeItemRef: null,
387 parentItemId: null,
388 ordinal: 1,
389 status: "completed" as const,
390 title: null,
391 message: "Stopping",
392 startedAt: NOW,
393 completedAt: NOW,
394 updatedAt: NOW,
395 };
396 const resultItem = {
397 id: "item-interrupt-result" as never,
398 type: "run_interrupt_result" as const,
399 threadId: v2ThreadId,
400 runId,
401 nodeId,
402 providerThreadId: null,
403 providerTurnId: null,
404 nativeItemRef: null,
405 parentItemId: null,
406 ordinal: 2,
407 status: "completed" as const,
408 title: null,
409 message: "Stopped",
410 startedAt: NOW,
411 completedAt: NOW,
412 updatedAt: NOW,
413 };
414 const resultRow = {
415 position: 0,
416 visibility: "local" as const,
417 sourceThreadId: v2ThreadId,
418 sourceItemId: resultItem.id,
419 item: resultItem,
420 };
421 const coldOpen = {
422 ...v2Projection,
423 runs: [
424 {
425 id: runId,
426 threadId: v2ThreadId,
427 ordinal: 1,
428 providerInstanceId: "codex" as never,
429 modelSelection: { instanceId: "codex" as never, model: "gpt-5" },
430 providerThreadId: null,
431 userMessageId: "message-1" as never,
432 rootNodeId: nodeId,
433 activeAttemptId: null,
434 status: "running" as const,
435 requestedAt: NOW,
436 startedAt: NOW,
437 completedAt: null,
438 checkpointId: null,
439 contextHandoffId: null,
440 },
441 ],
442 attempts: [
443 {
444 id: "attempt-1" as never,
445 runId,
446 attemptOrdinal: 1,
447 rootNodeId: nodeId,
448 providerInstanceId: "codex" as never,
449 providerThreadId: "provider-thread-1" as never,
450 providerTurnId: null,
451 reason: "initial" as const,
452 status: "running" as const,
453 startedAt: NOW,
454 completedAt: null,
455 },
456 ],
457 turnItems: [requestItem, recent.item],
458 visibleTurnItems: [{ ...recent, position: 0 }],
459 };
460
461 const requestMerged = mergeOlderHistoryIntoProjection(coldOpen, [
462 {
463 position: 0,
464 visibility: "local",
465 sourceThreadId: v2ThreadId,
466 sourceItemId: requestItem.id,
467 item: requestItem,
468 },
469 ]);
470 expect(requestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
471 "item-interrupt-request",
472 "item-5",
473 ]);
474
475 const rolledBackRequestMerged = mergeOlderHistoryIntoProjection(
476 {
477 ...coldOpen,
478 runs: coldOpen.runs.map((run) => ({
479 ...run,
480 status: "rolled_back" as const,
481 completedAt: NOW,
482 })),
483 },
484 [
485 {
486 position: 0,
487 visibility: "local",
488 sourceThreadId: v2ThreadId,
489 sourceItemId: requestItem.id,
490 item: requestItem,
491 },
492 ],
493 );
494 expect(
495 rolledBackRequestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId)),
496 ).toEqual(["item-5"]);
497
498 const merged = mergeOlderHistoryIntoProjection(coldOpen, [resultRow]);
499 expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
500 "item-interrupt-result",
501 "item-5",
502 ]);
503 expect(merged.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(true);
504 expect(merged.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(true);
505
506 const attemptSuperseded = applyOrchestrationV2ProjectionEvent(
507 merged,
508 {
509 id: "event-attempt-superseded" as never,
510 type: "run-attempt.updated",
511 threadId: v2ThreadId,
512 runId,
513 occurredAt: NOW,
514 payload: {
515 id: "attempt-1" as never,
516 runId,
517 attemptOrdinal: 1,
518 rootNodeId: nodeId,
519 providerInstanceId: "codex" as never,
520 providerThreadId: "provider-thread-1" as never,
521 providerTurnId: null,
522 reason: "initial",
523 status: "superseded",
524 startedAt: NOW,
525 completedAt: NOW,
526 },
527 } as never,
528 { partialTimeline: true },
529 );
530
531 expect(attemptSuperseded?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([
532 "item-interrupt-result",
533 "item-5",
534 ]);
535
536 const withoutRequest = {
537 ...merged,
538 turnItems: merged.turnItems.filter((item) => item.type !== "run_interrupt_request"),
539 };
540 const hidden = applyOrchestrationV2ProjectionEvent(
541 withoutRequest,
542 {
543 id: "event-attempt-superseded-missing" as never,
544 type: "run-attempt.updated",
545 threadId: v2ThreadId,
546 runId,
547 occurredAt: NOW,
548 payload: {
549 id: "attempt-1" as never,
550 runId,
551 attemptOrdinal: 1,
552 rootNodeId: nodeId,
553 providerInstanceId: "codex" as never,
554 providerThreadId: "provider-thread-1" as never,
555 providerTurnId: null,
556 reason: "initial",
557 status: "superseded",
558 startedAt: NOW,
559 completedAt: NOW,
560 },
561 } as never,
562 { partialTimeline: true },
563 );
564 expect(hidden?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(["item-5"]);
565 });
566 });