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

threadDetail.test.ts

594 lines21.3 KB

1import {
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";
17import { describe, expect, it } from "@effect/vitest";
18import * as DateTime from "effect/DateTime";
19import * as Option from "effect/Option";
20import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
21​
22import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
23import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
24import type { ThreadStructureVisibleTurnItem } from "./models.ts";
25import {
26 createEnvironmentThreadDetailAtoms,
27 deriveWorkspaceMutationId,
28 sameThreadStructure,
29} from "./threadDetail.ts";
30import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts";
31import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";
32​
33const later = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
34​
35const 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​
56const 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​
71function 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 };
92​
93describe("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​
137describe("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​
164describe("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​
238describe("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, text: " " })),
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 blank = registry.get(timelineAtom);
263 push({ ...assistant, text: "Hel", updatedAt: later });
264 const first = registry.get(timelineAtom);
265 expect(first).not.toBe(blank);
266 expect(first[0]?.item).toMatchObject({ text: "Hel", streaming: true });
267​
268 push({ ...assistant, text: "Hello", updatedAt: later });
269 expect(registry.get(timelineAtom)).toBe(first);
270 expect(registry.get(textAtom)).toBe("Hello");
271​
272 push({ ...assistant, text: "Hello", streaming: false, status: "completed" });
273 expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ text: "Hello", streaming: false });
274 registry.dispose();
275 });
276});
277​
278it("only compares replaced entries in a streamed reducer delta", () => {
279 const size = 100;
280 let slotReads = 0;
281 const countReads = <T>(items: ReadonlyArray<T>): ReadonlyArray<T> =>
282 new Proxy(items, {
283 get(target, key, receiver) {
284 if (typeof key === "string" && /^\d+$/.test(key)) slotReads++;
285 return Reflect.get(target, key, receiver);
286 },
287 });
288 const items = Array.from({ length: size }, (_, index) => ({
289 ...assistant,
290 id: TurnItemId.make(`item-${index}`),
291 ordinal: index,
292 }));
293 const before = {
294 ...v2Projection,
295 turnItems: countReads(items),
296 visibleTurnItems: countReads(
297 items.map((item, position) => ({
298 item,
299 position,
300 visibility: "local" as const,
301 sourceThreadId: v2ThreadId,
302 sourceItemId: item.id,
303 })),
304 ),
305 };
306 const next = applyOrchestrationV2ProjectionEvent(before, {
307 id: EventId.make("text-delta"),
308 type: "turn-item.updated",
309 threadId: v2ThreadId,
310 occurredAt: later,
311 payload: { ...items.at(-1)!, text: "Hello", updatedAt: later },
312 });
313 slotReads = 0;
314​
315 expect(sameThreadStructure(before, next!)).toBe(true);
316 expect(slotReads).toBeLessThanOrEqual(2);
317});
318​
319describe("derived thread state through a streamed message", () => {
320 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
321 const runId = RunId.make("run-1");
322 const streamed: OrchestrationV2ConversationMessage = {
323 id: MessageId.make("message-assistant"),
324 threadId: v2ThreadId,
325 runId,
326 nodeId: null,
327 role: "assistant",
328 text: "Hel",
329 attachments: [],
330 streaming: true,
331 createdBy: "agent",
332 creationSource: "provider",
333 createdAt: v2Now,
334 updatedAt: v2Now,
335 };
336 const queuedMessage: OrchestrationV2ConversationMessage = {
337 ...streamed,
338 id: MessageId.make("message-queued"),
339 runId: RunId.make("run-2"),
340 role: "user",
341 text: "Then run the tests",
342 streaming: false,
343 createdBy: "user",
344 creationSource: "mobile",
345 };
346 const queuedRun: OrchestrationV2Run = {
347 id: RunId.make("run-2"),
348 threadId: v2ThreadId,
349 ordinal: 2,
350 providerInstanceId: v2Projection.thread.providerInstanceId,
351 modelSelection: v2Projection.thread.modelSelection,
352 providerThreadId: null,
353 userMessageId: queuedMessage.id,
354 rootNodeId: null,
355 activeAttemptId: null,
356 status: "queued",
357 requestedAt: v2Now,
358 startedAt: null,
359 completedAt: null,
360 checkpointId: null,
361 contextHandoffId: null,
362 };
363 const checkpoint = (ordinal: number): OrchestrationV2Checkpoint => ({
364 id: CheckpointId.make(`checkpoint-${ordinal}`),
365 threadId: v2ThreadId,
366 scopeId: CheckpointScopeId.make("scope"),
367 runId,
368 nodeId: NodeId.make("node"),
369 parentCheckpointId: null,
370 ordinalWithinScope: ordinal,
371 appRunOrdinal: ordinal,
372 ref: CheckpointRef.make(`refs/t3/checkpoint-${ordinal}`),
373 status: "ready",
374 files: [],
375 capturedAt: v2Now,
376 });
377 const initial: OrchestrationV2ThreadProjection = {
378 ...v2Projection,
379 runs: [queuedRun],
380 messages: [streamed, queuedMessage],
381 checkpoints: [checkpoint(1)],
382 };
383​
384 function setup() {
385 const stateAtom = Atom.make(
386 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(initial) }),
387 );
388 const details = createEnvironmentThreadDetailAtoms(() => stateAtom);
389 const queue = details.queueWorkflowAtom(ref);
390 const checkpoints = details.checkpointSummariesAtom(ref);
391 const registry = AtomRegistry.make();
392 registry.mount(queue);
393 registry.mount(checkpoints);
394 let projection = initial;
395 return {
396 queue: () => registry.get(queue),
397 checkpoints: () => registry.get(checkpoints),
398 apply: (event: Parameters<typeof applyOrchestrationV2ProjectionEvent>[1]) => {
399 projection = applyOrchestrationV2ProjectionEvent(projection, event)!;
400 registry.set(
401 stateAtom,
402 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),
403 );
404 },
405 [Symbol.dispose]: () => registry.dispose(),
406 };
407 }
408​
409 const messageUpdated = (message: OrchestrationV2ConversationMessage) => ({
410 id: EventId.make(`event-${message.id}-${message.text.length}`),
411 type: "message.updated" as const,
412 threadId: v2ThreadId,
413 occurredAt: later,
414 payload: message,
415 });
416​
417 it("keeps the queue workflow through streamed text and follows a queued message edit", () => {
418 using thread = setup();
419 const first = thread.queue();
420 thread.apply(messageUpdated({ ...streamed, text: "Hello", updatedAt: later }));
421 thread.apply(messageUpdated({ ...streamed, text: "Hello there", updatedAt: later }));
422 expect(thread.queue()).toBe(first);
423​
424 thread.apply(messageUpdated({ ...queuedMessage, text: "Then run lint", updatedAt: later }));
425 expect(thread.queue()?.queuedRuns.map((queued) => queued.text)).toEqual(["Then run lint"]);
426 });
427​
428 it("keeps checkpoint summaries through streamed text and follows new assistant messages and checkpoints", () => {
429 using thread = setup();
430 const first = thread.checkpoints();
431 thread.apply(messageUpdated({ ...streamed, text: "Hello", updatedAt: later }));
432 thread.apply(messageUpdated({ ...streamed, text: "Hello there", updatedAt: later }));
433 expect(thread.checkpoints()).toBe(first);
434​
435 const followUp = { ...streamed, id: MessageId.make("message-follow-up"), text: "Done" };
436 thread.apply(messageUpdated(followUp));
437 expect(thread.checkpoints().map((summary) => summary.assistantMessageId)).toEqual([
438 followUp.id,
439 ]);
440​
441 thread.apply({
442 id: EventId.make("checkpoint-2"),
443 type: "checkpoint.captured",
444 threadId: v2ThreadId,
445 occurredAt: later,
446 payload: checkpoint(2),
447 });
448 expect(thread.checkpoints().map((summary) => summary.checkpointTurnCount)).toEqual([1, 2]);
449 });
450});
451​
452it("blocks promoting a queued message when only the Stop marker arrives", () => {
453 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
454 const running = {
455 ...v2Projection,
456 thread: { ...v2Projection.thread, activeProviderThreadId: "provider-thread" },
457 runs: [
458 { id: "active", ordinal: 1, status: "running", userMessageId: "first", activeAttemptId: "a" },
459 { id: "queued", ordinal: 2, status: "queued", userMessageId: "second" },
460 ],
461 providerThreads: [{ id: "provider-thread", providerSessionId: "session" }],
462 providerSessions: [
463 {
464 id: "session",
465 status: "running",
466 capabilities: { turns: { supportsActiveSteering: true } },
467 },
468 ],
469 providerTurns: [{ runAttemptId: "a", status: "running" }],
470 } as unknown as OrchestrationV2ThreadProjection;
471 const state = (projection: OrchestrationV2ThreadProjection) =>
472 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) });
473 const stateAtom = Atom.make(state(running));
474 const queue = createEnvironmentThreadDetailAtoms(() => stateAtom).queueWorkflowAtom(ref);
475 const registry = AtomRegistry.make();
476 registry.mount(queue);
477 expect(registry.get(queue)?.queuedRuns[0]?.stopBlocksPromotion).toBe(false);
478​
479 const stop = {
480 runId: "active",
481 type: "run_interrupt_request",
482 } as unknown as OrchestrationV2TurnItem;
483 registry.set(stateAtom, state({ ...running, turnItems: [stop] }));
484 expect(registry.get(queue)?.queuedRuns[0]?.stopBlocksPromotion).toBe(true);
485 registry.dispose();
486});
487​
488function replaceItem(projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem) {
489 return applyOrchestrationV2ProjectionEvent(projection, {
490 id: EventId.make(`event-${item.id}`),
491 type: "turn-item.updated",
492 threadId: v2ThreadId,
493 occurredAt: item.updatedAt,
494 payload: item,
495 })!;
497​
498it("matches full structure comparisons across streamed, batched, and reordered updates", () => {
499 const message = { ...assistant, ordinal: 2 };
500 const reasoning = {
501 ...assistant,
502 id: TurnItemId.make("reasoning"),
503 type: "reasoning" as const,
504 ordinal: 1,
505 };
506 const initial = mergeOlderHistoryIntoProjection(withItem(message), [
507 withItem(reasoning).visibleTurnItems[0]!,
508 ]);
509 const updates = [
510 { ...message, text: "Hello", updatedAt: later },
511 { ...reasoning, text: "Thinking", updatedAt: later },
512 { ...reasoning, text: "Done", status: "completed" as const, streaming: false },
513 { ...message, text: "Hello there", updatedAt: later },
514 { ...message, text: "Hello there", ordinal: 0 },
515 { ...message, text: "More text", ordinal: 0 },
516 { ...message, text: "More text", ordinal: 2 },
517 { ...message, text: "More text", runId: RunId.make("another-run") },
518 ];
519 const projections = [initial];
520 const withoutHints = (projection: OrchestrationV2ThreadProjection) => ({
521 ...projection,
522 turnItems: projection.turnItems.slice(),
523 visibleTurnItems: projection.visibleTurnItems.slice(),
524 });
525 const consecutive: boolean[] = [];
526 for (const item of updates) {
527 const previous = projections.at(-1)!;
528 const next = replaceItem(previous, item);
529 consecutive.push(sameThreadStructure(previous, next));
530 // All earlier snapshots include readers that skip one or several updates in a batch.
531 for (const before of projections) {
532 expect(sameThreadStructure(before, next)).toBe(
533 sameThreadStructure(withoutHints(before), withoutHints(next)),
534 );
535 }
536 projections.push(next);
537 }
538​
539 // A resumed snapshot can reuse item ids while changing a different row.
540 const snapshot = withoutHints(projections[1]!);
541 const resumed = replaceItem(snapshot, { ...reasoning, title: "Restored reasoning" });
542 const sibling = replaceItem(initial, { ...message, text: "Another stream" });
543 const reconnected = replaceItem(resumed, { ...message, text: "Resumed stream" });
544 for (const before of [initial, sibling, projections[1]!, resumed]) {
545 expect(sameThreadStructure(before, reconnected)).toBe(
546 sameThreadStructure(withoutHints(before), withoutHints(reconnected)),
547 );
548 }
549 expect(sameThreadStructure(sibling, reconnected)).toBe(false);
550 expect(sameThreadStructure(resumed, reconnected)).toBe(true);
551​
552 expect(consecutive).toEqual([true, true, false, true, false, true, false, false]);
553 expect(sameThreadStructure(initial, projections[4]!)).toBe(false);
554 expect(projections[5]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
555 [assistant.id, 0],
556 [reasoning.id, 1],
557 ]);
558 expect(projections[7]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
559 [reasoning.id, 0],
560 [assistant.id, 1],
561 ]);
562});
563​
564describe("deriveWorkspaceMutationId", () => {
565 const item = (id: string, type: string, status: string) =>
566 ({
567 item: { id: TurnItemId.make(id), type, status },
568 }) as unknown as ThreadStructureVisibleTurnItem;
569​
570 it("keys on the latest finished command or file change and the latest checkpoint", () => {
571 expect(
572 deriveWorkspaceMutationId(
573 [
574 item("edit", "file_change", "completed"),
575 item("reply", "assistant_message", "completed"),
576 item("command", "command_execution", "running"),
577 ],
578 "2026-01-01T00:00:00.000Z",
579 ),
580 ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
581 expect(
582 deriveWorkspaceMutationId(
583 [item("edit", "file_change", "completed"), item("mcp", "dynamic_tool", "completed")],
584 null,
585 ),
586 ).toBe(JSON.stringify(["mcp", null]));
587 });
588​
589 it("is null before anything could have touched the workspace", () => {
590 expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
591 null,
592 );
593 });
594});