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

main
ts 554 lines 19.5 KB
Raw
1 import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 EnvironmentId,
6 EventId,
7 MessageId,
8 NodeId,
9 RunId,
10 TurnItemId,
11 type OrchestrationV2Checkpoint,
12 type OrchestrationV2ConversationMessage,
13 type OrchestrationV2Run,
14 type OrchestrationV2ThreadProjection,
15 type OrchestrationV2TurnItem,
16 } from "@t3tools/contracts";
17 import { describe, expect, it } from "@effect/vitest";
18 import * as DateTime from "effect/DateTime";
19 import * as Option from "effect/Option";
20 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
21
22 import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
23 import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
24 import type { ThreadStructureVisibleTurnItem } from "./models.ts";
25 import {
26 createEnvironmentThreadDetailAtoms,
27 deriveWorkspaceMutationId,
28 sameThreadStructure,
29 } from "./threadDetail.ts";
30 import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts";
31 import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";
32
33 const later = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
34
35 const assistant: OrchestrationV2TurnItem = {
36 id: TurnItemId.make("item-assistant"),
37 threadId: v2ThreadId,
38 runId: RunId.make("run-1"),
39 nodeId: null,
40 providerThreadId: null,
41 providerTurnId: null,
42 nativeItemRef: null,
43 parentItemId: null,
44 ordinal: 1,
45 status: "running",
46 title: null,
47 startedAt: v2Now,
48 completedAt: null,
49 updatedAt: v2Now,
50 type: "assistant_message",
51 messageId: MessageId.make("message-assistant"),
52 text: "Hel",
53 streaming: true,
54 };
55
56 const assistantMessage: OrchestrationV2ConversationMessage = {
57 createdBy: "agent",
58 creationSource: "provider",
59 id: MessageId.make("message-assistant"),
60 threadId: v2ThreadId,
61 runId: RunId.make("run-1"),
62 nodeId: null,
63 role: "assistant",
64 text: "Hel",
65 attachments: [],
66 streaming: true,
67 createdAt: v2Now,
68 updatedAt: v2Now,
69 };
70
71 function withItem(
72 item: OrchestrationV2TurnItem,
73 updatedAt = v2Now,
74 message: OrchestrationV2ConversationMessage = assistantMessage,
75 ) {
76 return {
77 ...v2Projection,
78 messages: [message],
79 turnItems: [item],
80 visibleTurnItems: [
81 {
82 position: 0,
83 visibility: "local" as const,
84 sourceThreadId: v2ThreadId,
85 sourceItemId: item.id,
86 item,
87 },
88 ],
89 updatedAt,
90 };
91 }
92
93 describe("sameThreadStructure", () => {
94 const before = withItem(assistant);
95
96 it("holds through streamed text", () => {
97 const next = withItem({ ...assistant, text: "Hello", updatedAt: later }, later, {
98 ...assistantMessage,
99 text: "Hello",
100 updatedAt: later,
101 });
102 expect(sameThreadStructure(before, next)).toBe(true);
103 });
104
105 it("sees the item finish streaming", () => {
106 const next = withItem({ ...assistant, text: "Hello", streaming: false, status: "completed" });
107 expect(sameThreadStructure(before, next)).toBe(false);
108 const message = { ...assistantMessage, text: "Hello", streaming: false };
109 expect(sameThreadStructure(before, withItem(assistant, v2Now, message))).toBe(false);
110 });
111
112 it("sees a new item", () => {
113 const next = { ...before, turnItems: [assistant, { ...assistant, id: TurnItemId.make("b") }] };
114 expect(sameThreadStructure(before, next)).toBe(false);
115 });
116
117 it("sees other fields change on a streaming item", () => {
118 const next = withItem({ ...assistant, text: "Hello", title: "Answer" });
119 expect(sameThreadStructure(before, next)).toBe(false);
120 });
121
122 it("holds through a visit mark", () => {
123 const thread = { ...before.thread, lastVisitedAt: later, updatedAt: later };
124 expect(sameThreadStructure(before, { ...before, thread })).toBe(true);
125 });
126
127 it("sees other thread changes", () => {
128 const thread = { ...before.thread, title: "Renamed" };
129 expect(sameThreadStructure(before, { ...before, thread })).toBe(false);
130 });
131
132 it("sees changes outside the turn items", () => {
133 expect(sameThreadStructure(before, { ...before, runs: [] })).toBe(false);
134 });
135 });
136
137 describe("lastVisitedAtAtom", () => {
138 it("follows a visit mark the quiet thread holds through", () => {
139 const projection = withItem(assistant);
140 const state = Atom.make(
141 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),
142 );
143 const details = createEnvironmentThreadDetailAtoms(() => state);
144 const ref = { environmentId: EnvironmentId.make("env"), threadId: v2ThreadId };
145 const registry = AtomRegistry.make();
146 const unmountQuiet = registry.mount(details.quietThreadAtom(ref));
147 const unmountVisit = registry.mount(details.lastVisitedAtAtom(ref));
148 const quietBefore = registry.get(details.quietThreadAtom(ref));
149
150 const visited = { ...projection, thread: { ...projection.thread, lastVisitedAt: later } };
151 registry.set(
152 state,
153 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(visited) }),
154 );
155
156 expect(registry.get(details.quietThreadAtom(ref))).toBe(quietBefore);
157 expect(registry.get(details.lastVisitedAtAtom(ref))).toBe(later);
158 unmountQuiet();
159 unmountVisit();
160 registry.dispose();
161 });
162 });
163
164 describe("quietThreadAtom", () => {
165 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
166
167 function setup(initial: OrchestrationV2ThreadProjection) {
168 const stateAtom = Atom.make(
169 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(initial) }),
170 );
171 const quietAtom = createEnvironmentThreadDetailAtoms(() => stateAtom).quietThreadAtom(ref);
172 const registry = AtomRegistry.make();
173 registry.mount(quietAtom);
174 return {
175 read: () => registry.get(quietAtom),
176 [Symbol.dispose]: () => registry.dispose(),
177 push: (projection: OrchestrationV2ThreadProjection | null) =>
178 registry.set(
179 stateAtom,
180 AsyncResult.success({
181 ...EMPTY_ENVIRONMENT_THREAD_STATE,
182 data: Option.fromNullishOr(projection),
183 }),
184 ),
185 };
186 }
187
188 it("keeps the same value through streamed text", () => {
189 const thread = setup(withItem(assistant));
190 const first = thread.read();
191 thread.push(withItem({ ...assistant, text: "Hello", updatedAt: later }, later));
192 thread.push(withItem({ ...assistant, text: "Hello there", updatedAt: later }, later));
193 expect(thread.read()).toBe(first);
194 });
195
196 it("passes a structure change on", () => {
197 const thread = setup(withItem(assistant));
198 const first = thread.read();
199 thread.push(withItem({ ...assistant, text: "Hello", updatedAt: later }, later));
200 thread.push(withItem({ ...assistant, text: "Hello", status: "completed", streaming: false }));
201 const next = thread.read();
202 expect(next).not.toBe(first);
203 expect(next?.projection.turnItems[0]).toMatchObject({ status: "completed", streaming: false });
204 });
205
206 it("discards structure held before the thread resets", () => {
207 const initial = withItem(assistant);
208 using thread = setup(initial);
209 const first = thread.read();
210 thread.push(replaceItem(initial, { ...assistant, text: "Hello" }));
211 expect(thread.read()).toBe(first);
212 thread.push(null);
213 expect(thread.read()).toBeNull();
214 const reset = withItem({ ...assistant, title: "Restored", text: "New snapshot" });
215 thread.push(reset);
216 expect(thread.read()).not.toBe(first);
217 expect(thread.read()?.projection.turnItems[0]).toMatchObject({ title: "Restored" });
218 thread.push(replaceItem(reset, { ...assistant, title: "Restored", text: "More text" }));
219 expect(thread.read()?.projection.turnItems[0]).toMatchObject({ title: "Restored" });
220 });
221
222 it("leaves out the fields that streaming moves", () => {
223 const thread = setup(withItem(assistant));
224 const projection = thread.read()?.projection;
225 expect(projection).not.toHaveProperty("updatedAt");
226 expect(projection?.thread).not.toHaveProperty("updatedAt");
227 expect(projection?.thread).not.toHaveProperty("lastVisitedAt");
228 expect(projection?.turnItems[0]).not.toHaveProperty("text");
229 expect(projection?.turnItems[0]).not.toHaveProperty("updatedAt");
230 expect(projection?.visibleTurnItems[0]?.item).not.toHaveProperty("text");
231 expect(projection?.visibleTurnItems[0]?.item).toMatchObject({
232 messageId: assistant.messageId,
233 streaming: true,
234 });
235 });
236 });
237
238 describe("timelineVisibleTurnItemsAtom", () => {
239 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
240
241 it("holds through streamed assistant text while the message reads its own text", () => {
242 const stateAtom = Atom.make(
243 AsyncResult.success({
244 ...EMPTY_ENVIRONMENT_THREAD_STATE,
245 data: Option.some<OrchestrationV2ThreadProjection>(withItem(assistant)),
246 }),
247 );
248 const details = createEnvironmentThreadDetailAtoms(() => stateAtom);
249 const timelineAtom = details.timelineVisibleTurnItemsAtom(ref);
250 const textAtom = details.assistantMessageTextAtom(ref, assistant.id);
251 const registry = AtomRegistry.make();
252 registry.mount(timelineAtom);
253 registry.mount(textAtom);
254 const push = (item: OrchestrationV2TurnItem) =>
255 registry.set(
256 stateAtom,
257 AsyncResult.success({
258 ...EMPTY_ENVIRONMENT_THREAD_STATE,
259 data: Option.some(withItem(item, later)),
260 }),
261 );
262 const first = registry.get(timelineAtom);
263
264 push({ ...assistant, text: "Hello", updatedAt: later });
265 expect(registry.get(timelineAtom)).toBe(first);
266 expect(registry.get(textAtom)).toBe("Hello");
267
268 push({ ...assistant, text: "Hello", streaming: false, status: "completed" });
269 expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ text: "Hello", streaming: false });
270 registry.dispose();
271 });
272 });
273
274 it("only compares replaced entries in a streamed reducer delta", () => {
275 const size = 100;
276 let slotReads = 0;
277 const countReads = <T>(items: ReadonlyArray<T>): ReadonlyArray<T> =>
278 new Proxy(items, {
279 get(target, key, receiver) {
280 if (typeof key === "string" && /^\d+$/.test(key)) slotReads++;
281 return Reflect.get(target, key, receiver);
282 },
283 });
284 const items = Array.from({ length: size }, (_, index) => ({
285 ...assistant,
286 id: TurnItemId.make(`item-${index}`),
287 ordinal: index,
288 }));
289 const before = {
290 ...v2Projection,
291 turnItems: countReads(items),
292 visibleTurnItems: countReads(
293 items.map((item, position) => ({
294 item,
295 position,
296 visibility: "local" as const,
297 sourceThreadId: v2ThreadId,
298 sourceItemId: item.id,
299 })),
300 ),
301 };
302 const next = applyOrchestrationV2ProjectionEvent(before, {
303 id: EventId.make("text-delta"),
304 type: "turn-item.updated",
305 threadId: v2ThreadId,
306 occurredAt: later,
307 payload: { ...items.at(-1)!, text: "Hello", updatedAt: later },
308 });
309 slotReads = 0;
310
311 expect(sameThreadStructure(before, next!)).toBe(true);
312 expect(slotReads).toBeLessThanOrEqual(2);
313 });
314
315 describe("derived thread state through a streamed message", () => {
316 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
317 const runId = RunId.make("run-1");
318 const streamed: OrchestrationV2ConversationMessage = {
319 id: MessageId.make("message-assistant"),
320 threadId: v2ThreadId,
321 runId,
322 nodeId: null,
323 role: "assistant",
324 text: "Hel",
325 attachments: [],
326 streaming: true,
327 createdBy: "agent",
328 creationSource: "provider",
329 createdAt: v2Now,
330 updatedAt: v2Now,
331 };
332 const queuedMessage: OrchestrationV2ConversationMessage = {
333 ...streamed,
334 id: MessageId.make("message-queued"),
335 runId: RunId.make("run-2"),
336 role: "user",
337 text: "Then run the tests",
338 streaming: false,
339 createdBy: "user",
340 creationSource: "mobile",
341 };
342 const queuedRun: OrchestrationV2Run = {
343 id: RunId.make("run-2"),
344 threadId: v2ThreadId,
345 ordinal: 2,
346 providerInstanceId: v2Projection.thread.providerInstanceId,
347 modelSelection: v2Projection.thread.modelSelection,
348 providerThreadId: null,
349 userMessageId: queuedMessage.id,
350 rootNodeId: null,
351 activeAttemptId: null,
352 status: "queued",
353 requestedAt: v2Now,
354 startedAt: null,
355 completedAt: null,
356 checkpointId: null,
357 contextHandoffId: null,
358 };
359 const checkpoint = (ordinal: number): OrchestrationV2Checkpoint => ({
360 id: CheckpointId.make(`checkpoint-${ordinal}`),
361 threadId: v2ThreadId,
362 scopeId: CheckpointScopeId.make("scope"),
363 runId,
364 nodeId: NodeId.make("node"),
365 parentCheckpointId: null,
366 ordinalWithinScope: ordinal,
367 appRunOrdinal: ordinal,
368 ref: CheckpointRef.make(`refs/t3/checkpoint-${ordinal}`),
369 status: "ready",
370 files: [],
371 capturedAt: v2Now,
372 });
373 const initial: OrchestrationV2ThreadProjection = {
374 ...v2Projection,
375 runs: [queuedRun],
376 messages: [streamed, queuedMessage],
377 checkpoints: [checkpoint(1)],
378 };
379
380 function setup() {
381 const stateAtom = Atom.make(
382 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(initial) }),
383 );
384 const details = createEnvironmentThreadDetailAtoms(() => stateAtom);
385 const queue = details.queueWorkflowAtom(ref);
386 const checkpoints = details.checkpointSummariesAtom(ref);
387 const registry = AtomRegistry.make();
388 registry.mount(queue);
389 registry.mount(checkpoints);
390 let projection = initial;
391 return {
392 queue: () => registry.get(queue),
393 checkpoints: () => registry.get(checkpoints),
394 apply: (event: Parameters<typeof applyOrchestrationV2ProjectionEvent>[1]) => {
395 projection = applyOrchestrationV2ProjectionEvent(projection, event)!;
396 registry.set(
397 stateAtom,
398 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),
399 );
400 },
401 [Symbol.dispose]: () => registry.dispose(),
402 };
403 }
404
405 const messageUpdated = (message: OrchestrationV2ConversationMessage) => ({
406 id: EventId.make(`event-${message.id}-${message.text.length}`),
407 type: "message.updated" as const,
408 threadId: v2ThreadId,
409 occurredAt: later,
410 payload: message,
411 });
412
413 it("keeps the queue workflow through streamed text and follows a queued message edit", () => {
414 using thread = setup();
415 const first = thread.queue();
416 thread.apply(messageUpdated({ ...streamed, text: "Hello", updatedAt: later }));
417 thread.apply(messageUpdated({ ...streamed, text: "Hello there", updatedAt: later }));
418 expect(thread.queue()).toBe(first);
419
420 thread.apply(messageUpdated({ ...queuedMessage, text: "Then run lint", updatedAt: later }));
421 expect(thread.queue()?.queuedRuns.map((queued) => queued.text)).toEqual(["Then run lint"]);
422 });
423
424 it("keeps checkpoint summaries through streamed text and follows new assistant messages and checkpoints", () => {
425 using thread = setup();
426 const first = thread.checkpoints();
427 thread.apply(messageUpdated({ ...streamed, text: "Hello", updatedAt: later }));
428 thread.apply(messageUpdated({ ...streamed, text: "Hello there", updatedAt: later }));
429 expect(thread.checkpoints()).toBe(first);
430
431 const followUp = { ...streamed, id: MessageId.make("message-follow-up"), text: "Done" };
432 thread.apply(messageUpdated(followUp));
433 expect(thread.checkpoints().map((summary) => summary.assistantMessageId)).toEqual([
434 followUp.id,
435 ]);
436
437 thread.apply({
438 id: EventId.make("checkpoint-2"),
439 type: "checkpoint.captured",
440 threadId: v2ThreadId,
441 occurredAt: later,
442 payload: checkpoint(2),
443 });
444 expect(thread.checkpoints().map((summary) => summary.checkpointTurnCount)).toEqual([1, 2]);
445 });
446 });
447
448 function replaceItem(projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem) {
449 return applyOrchestrationV2ProjectionEvent(projection, {
450 id: EventId.make(`event-${item.id}`),
451 type: "turn-item.updated",
452 threadId: v2ThreadId,
453 occurredAt: item.updatedAt,
454 payload: item,
455 })!;
456 }
457
458 it("matches full structure comparisons across streamed, batched, and reordered updates", () => {
459 const message = { ...assistant, ordinal: 2 };
460 const reasoning = {
461 ...assistant,
462 id: TurnItemId.make("reasoning"),
463 type: "reasoning" as const,
464 ordinal: 1,
465 };
466 const initial = mergeOlderHistoryIntoProjection(withItem(message), [
467 withItem(reasoning).visibleTurnItems[0]!,
468 ]);
469 const updates = [
470 { ...message, text: "Hello", updatedAt: later },
471 { ...reasoning, text: "Thinking", updatedAt: later },
472 { ...reasoning, text: "Done", status: "completed" as const, streaming: false },
473 { ...message, text: "Hello there", updatedAt: later },
474 { ...message, text: "Hello there", ordinal: 0 },
475 { ...message, text: "More text", ordinal: 0 },
476 { ...message, text: "More text", ordinal: 2 },
477 { ...message, text: "More text", runId: RunId.make("another-run") },
478 ];
479 const projections = [initial];
480 const withoutHints = (projection: OrchestrationV2ThreadProjection) => ({
481 ...projection,
482 turnItems: projection.turnItems.slice(),
483 visibleTurnItems: projection.visibleTurnItems.slice(),
484 });
485 const consecutive: boolean[] = [];
486 for (const item of updates) {
487 const previous = projections.at(-1)!;
488 const next = replaceItem(previous, item);
489 consecutive.push(sameThreadStructure(previous, next));
490 // All earlier snapshots include readers that skip one or several updates in a batch.
491 for (const before of projections) {
492 expect(sameThreadStructure(before, next)).toBe(
493 sameThreadStructure(withoutHints(before), withoutHints(next)),
494 );
495 }
496 projections.push(next);
497 }
498
499 // A resumed snapshot can reuse item ids while changing a different row.
500 const snapshot = withoutHints(projections[1]!);
501 const resumed = replaceItem(snapshot, { ...reasoning, title: "Restored reasoning" });
502 const sibling = replaceItem(initial, { ...message, text: "Another stream" });
503 const reconnected = replaceItem(resumed, { ...message, text: "Resumed stream" });
504 for (const before of [initial, sibling, projections[1]!, resumed]) {
505 expect(sameThreadStructure(before, reconnected)).toBe(
506 sameThreadStructure(withoutHints(before), withoutHints(reconnected)),
507 );
508 }
509 expect(sameThreadStructure(sibling, reconnected)).toBe(false);
510 expect(sameThreadStructure(resumed, reconnected)).toBe(true);
511
512 expect(consecutive).toEqual([true, true, false, true, false, true, false, false]);
513 expect(sameThreadStructure(initial, projections[4]!)).toBe(false);
514 expect(projections[5]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
515 [assistant.id, 0],
516 [reasoning.id, 1],
517 ]);
518 expect(projections[7]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
519 [reasoning.id, 0],
520 [assistant.id, 1],
521 ]);
522 });
523
524 describe("deriveWorkspaceMutationId", () => {
525 const item = (id: string, type: string, status: string) =>
526 ({
527 item: { id: TurnItemId.make(id), type, status },
528 }) as unknown as ThreadStructureVisibleTurnItem;
529
530 it("keys on the latest finished command or file change and the latest checkpoint", () => {
531 expect(
532 deriveWorkspaceMutationId(
533 [
534 item("edit", "file_change", "completed"),
535 item("reply", "assistant_message", "completed"),
536 item("command", "command_execution", "running"),
537 ],
538 "2026-01-01T00:00:00.000Z",
539 ),
540 ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
541 expect(
542 deriveWorkspaceMutationId(
543 [item("edit", "file_change", "completed"), item("mcp", "dynamic_tool", "completed")],
544 null,
545 ),
546 ).toBe(JSON.stringify(["mcp", null]));
547 });
548
549 it("is null before anything could have touched the workspace", () => {
550 expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
551 null,
552 );
553 });
554 });