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

threadDetail.test.ts

388 lines14.1 KB

1import {
2 EnvironmentId,
3 EventId,
4 MessageId,
5 RunId,
6 TurnItemId,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2TurnItem,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "@effect/vitest";
11import * as DateTime from "effect/DateTime";
12import * as Option from "effect/Option";
13import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
14​
15import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
16import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
17import type { ThreadStructureVisibleTurnItem } from "./models.ts";
18import {
19 createEnvironmentThreadDetailAtoms,
20 deriveWorkspaceMutationId,
21 sameThreadStructure,
22} from "./threadDetail.ts";
23import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts";
24import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";
25​
26const later = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
27​
28const assistant: OrchestrationV2TurnItem = {
29 id: TurnItemId.make("item-assistant"),
30 threadId: v2ThreadId,
31 runId: RunId.make("run-1"),
32 nodeId: null,
33 providerThreadId: null,
34 providerTurnId: null,
35 nativeItemRef: null,
36 parentItemId: null,
37 ordinal: 1,
38 status: "running",
39 title: null,
40 startedAt: v2Now,
41 completedAt: null,
42 updatedAt: v2Now,
43 type: "assistant_message",
44 messageId: MessageId.make("message-assistant"),
45 text: "Hel",
46 streaming: true,
47};
48​
49function withItem(item: OrchestrationV2TurnItem, updatedAt = v2Now) {
50 return {
51 ...v2Projection,
52 turnItems: [item],
53 visibleTurnItems: [
54 {
55 position: 0,
56 visibility: "local" as const,
57 sourceThreadId: v2ThreadId,
58 sourceItemId: item.id,
59 item,
60 },
61 ],
62 updatedAt,
63 };
65​
66describe("sameThreadStructure", () => {
67 const before = withItem(assistant);
68​
69 it("holds through streamed text", () => {
70 const next = withItem({ ...assistant, text: "Hello", updatedAt: later }, later);
71 expect(sameThreadStructure(before, next)).toBe(true);
72 });
73​
74 it("sees the item finish streaming", () => {
75 const next = withItem({ ...assistant, text: "Hello", streaming: false, status: "completed" });
76 expect(sameThreadStructure(before, next)).toBe(false);
77 });
78​
79 it("sees a new item", () => {
80 const next = { ...before, turnItems: [assistant, { ...assistant, id: TurnItemId.make("b") }] };
81 expect(sameThreadStructure(before, next)).toBe(false);
82 });
83​
84 it("sees other fields change on a streaming item", () => {
85 const next = withItem({ ...assistant, text: "Hello", title: "Answer" });
86 expect(sameThreadStructure(before, next)).toBe(false);
87 });
88​
89 it("holds through a visit mark", () => {
90 const thread = { ...before.thread, lastVisitedAt: later, updatedAt: later };
91 expect(sameThreadStructure(before, { ...before, thread })).toBe(true);
92 });
93​
94 it("sees other thread changes", () => {
95 const thread = { ...before.thread, title: "Renamed" };
96 expect(sameThreadStructure(before, { ...before, thread })).toBe(false);
97 });
98​
99 it("sees changes outside the turn items", () => {
100 expect(sameThreadStructure(before, { ...before, runs: [] })).toBe(false);
101 });
102});
103​
104describe("lastVisitedAtAtom", () => {
105 it("follows a visit mark the quiet thread holds through", () => {
106 const projection = withItem(assistant);
107 const state = Atom.make(
108 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),
109 );
110 const details = createEnvironmentThreadDetailAtoms(() => state);
111 const ref = { environmentId: EnvironmentId.make("env"), threadId: v2ThreadId };
112 const registry = AtomRegistry.make();
113 const unmountQuiet = registry.mount(details.quietThreadAtom(ref));
114 const unmountVisit = registry.mount(details.lastVisitedAtAtom(ref));
115 const quietBefore = registry.get(details.quietThreadAtom(ref));
116​
117 const visited = { ...projection, thread: { ...projection.thread, lastVisitedAt: later } };
118 registry.set(
119 state,
120 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(visited) }),
121 );
122​
123 expect(registry.get(details.quietThreadAtom(ref))).toBe(quietBefore);
124 expect(registry.get(details.lastVisitedAtAtom(ref))).toBe(later);
125 unmountQuiet();
126 unmountVisit();
127 registry.dispose();
128 });
129});
130​
131describe("quietThreadAtom", () => {
132 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
133​
134 function setup(initial: OrchestrationV2ThreadProjection) {
135 const stateAtom = Atom.make(
136 AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(initial) }),
137 );
138 const quietAtom = createEnvironmentThreadDetailAtoms(() => stateAtom).quietThreadAtom(ref);
139 const registry = AtomRegistry.make();
140 registry.mount(quietAtom);
141 return {
142 read: () => registry.get(quietAtom),
143 [Symbol.dispose]: () => registry.dispose(),
144 push: (projection: OrchestrationV2ThreadProjection | null) =>
145 registry.set(
146 stateAtom,
147 AsyncResult.success({
148 ...EMPTY_ENVIRONMENT_THREAD_STATE,
149 data: Option.fromNullishOr(projection),
150 }),
151 ),
152 };
153 }
154​
155 it("keeps the same value through streamed text", () => {
156 const thread = setup(withItem(assistant));
157 const first = thread.read();
158 thread.push(withItem({ ...assistant, text: "Hello", updatedAt: later }, later));
159 thread.push(withItem({ ...assistant, text: "Hello there", updatedAt: later }, later));
160 expect(thread.read()).toBe(first);
161 });
162​
163 it("passes a structure change on", () => {
164 const thread = setup(withItem(assistant));
165 const first = thread.read();
166 thread.push(withItem({ ...assistant, text: "Hello", updatedAt: later }, later));
167 thread.push(withItem({ ...assistant, text: "Hello", status: "completed", streaming: false }));
168 const next = thread.read();
169 expect(next).not.toBe(first);
170 expect(next?.projection.turnItems[0]).toMatchObject({ status: "completed", streaming: false });
171 });
172​
173 it("discards structure held before the thread resets", () => {
174 const initial = withItem(assistant);
175 using thread = setup(initial);
176 const first = thread.read();
177 thread.push(replaceItem(initial, { ...assistant, text: "Hello" }));
178 expect(thread.read()).toBe(first);
179 thread.push(null);
180 expect(thread.read()).toBeNull();
181 const reset = withItem({ ...assistant, title: "Restored", text: "New snapshot" });
182 thread.push(reset);
183 expect(thread.read()).not.toBe(first);
184 expect(thread.read()?.projection.turnItems[0]).toMatchObject({ title: "Restored" });
185 thread.push(replaceItem(reset, { ...assistant, title: "Restored", text: "More text" }));
186 expect(thread.read()?.projection.turnItems[0]).toMatchObject({ title: "Restored" });
187 });
188​
189 it("leaves out the fields that streaming moves", () => {
190 const thread = setup(withItem(assistant));
191 const projection = thread.read()?.projection;
192 expect(projection).not.toHaveProperty("updatedAt");
193 expect(projection?.thread).not.toHaveProperty("updatedAt");
194 expect(projection?.thread).not.toHaveProperty("lastVisitedAt");
195 expect(projection?.turnItems[0]).not.toHaveProperty("text");
196 expect(projection?.turnItems[0]).not.toHaveProperty("updatedAt");
197 expect(projection?.visibleTurnItems[0]?.item).not.toHaveProperty("text");
198 expect(projection?.visibleTurnItems[0]?.item).toMatchObject({
199 messageId: assistant.messageId,
200 streaming: true,
201 });
202 });
203});
204​
205describe("timelineVisibleTurnItemsAtom", () => {
206 const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
207​
208 it("holds through streamed assistant text while the message reads its own text", () => {
209 const stateAtom = Atom.make(
210 AsyncResult.success({
211 ...EMPTY_ENVIRONMENT_THREAD_STATE,
212 data: Option.some<OrchestrationV2ThreadProjection>(withItem(assistant)),
213 }),
214 );
215 const details = createEnvironmentThreadDetailAtoms(() => stateAtom);
216 const timelineAtom = details.timelineVisibleTurnItemsAtom(ref);
217 const textAtom = details.assistantMessageTextAtom(ref, assistant.id);
218 const registry = AtomRegistry.make();
219 registry.mount(timelineAtom);
220 registry.mount(textAtom);
221 const push = (item: OrchestrationV2TurnItem) =>
222 registry.set(
223 stateAtom,
224 AsyncResult.success({
225 ...EMPTY_ENVIRONMENT_THREAD_STATE,
226 data: Option.some(withItem(item, later)),
227 }),
228 );
229 const first = registry.get(timelineAtom);
230​
231 push({ ...assistant, text: "Hello", updatedAt: later });
232 expect(registry.get(timelineAtom)).toBe(first);
233 expect(registry.get(textAtom)).toBe("Hello");
234​
235 push({ ...assistant, text: "Hello", streaming: false, status: "completed" });
236 expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ text: "Hello", streaming: false });
237 registry.dispose();
238 });
239});
240​
241it("only compares replaced entries in a streamed reducer delta", () => {
242 const size = 100;
243 let slotReads = 0;
244 const countReads = <T>(items: ReadonlyArray<T>): ReadonlyArray<T> =>
245 new Proxy(items, {
246 get(target, key, receiver) {
247 if (typeof key === "string" && /^\d+$/.test(key)) slotReads++;
248 return Reflect.get(target, key, receiver);
249 },
250 });
251 const items = Array.from({ length: size }, (_, index) => ({
252 ...assistant,
253 id: TurnItemId.make(`item-${index}`),
254 ordinal: index,
255 }));
256 const before = {
257 ...v2Projection,
258 turnItems: countReads(items),
259 visibleTurnItems: countReads(
260 items.map((item, position) => ({
261 item,
262 position,
263 visibility: "local" as const,
264 sourceThreadId: v2ThreadId,
265 sourceItemId: item.id,
266 })),
267 ),
268 };
269 const next = applyOrchestrationV2ProjectionEvent(before, {
270 id: EventId.make("text-delta"),
271 type: "turn-item.updated",
272 threadId: v2ThreadId,
273 occurredAt: later,
274 payload: { ...items.at(-1)!, text: "Hello", updatedAt: later },
275 });
276 slotReads = 0;
277​
278 expect(sameThreadStructure(before, next!)).toBe(true);
279 expect(slotReads).toBeLessThanOrEqual(2);
280});
281​
282function replaceItem(projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem) {
283 return applyOrchestrationV2ProjectionEvent(projection, {
284 id: EventId.make(`event-${item.id}`),
285 type: "turn-item.updated",
286 threadId: v2ThreadId,
287 occurredAt: item.updatedAt,
288 payload: item,
289 })!;
291​
292it("matches full structure comparisons across streamed, batched, and reordered updates", () => {
293 const message = { ...assistant, ordinal: 2 };
294 const reasoning = {
295 ...assistant,
296 id: TurnItemId.make("reasoning"),
297 type: "reasoning" as const,
298 ordinal: 1,
299 };
300 const initial = mergeOlderHistoryIntoProjection(withItem(message), [
301 withItem(reasoning).visibleTurnItems[0]!,
302 ]);
303 const updates = [
304 { ...message, text: "Hello", updatedAt: later },
305 { ...reasoning, text: "Thinking", updatedAt: later },
306 { ...reasoning, text: "Done", status: "completed" as const, streaming: false },
307 { ...message, text: "Hello there", updatedAt: later },
308 { ...message, text: "Hello there", ordinal: 0 },
309 { ...message, text: "More text", ordinal: 0 },
310 { ...message, text: "More text", ordinal: 2 },
311 { ...message, text: "More text", runId: RunId.make("another-run") },
312 ];
313 const projections = [initial];
314 const withoutHints = (projection: OrchestrationV2ThreadProjection) => ({
315 ...projection,
316 turnItems: projection.turnItems.slice(),
317 visibleTurnItems: projection.visibleTurnItems.slice(),
318 });
319 const consecutive: boolean[] = [];
320 for (const item of updates) {
321 const previous = projections.at(-1)!;
322 const next = replaceItem(previous, item);
323 consecutive.push(sameThreadStructure(previous, next));
324 // All earlier snapshots include readers that skip one or several updates in a batch.
325 for (const before of projections) {
326 expect(sameThreadStructure(before, next)).toBe(
327 sameThreadStructure(withoutHints(before), withoutHints(next)),
328 );
329 }
330 projections.push(next);
331 }
332​
333 // A resumed snapshot can reuse item ids while changing a different row.
334 const snapshot = withoutHints(projections[1]!);
335 const resumed = replaceItem(snapshot, { ...reasoning, title: "Restored reasoning" });
336 const sibling = replaceItem(initial, { ...message, text: "Another stream" });
337 const reconnected = replaceItem(resumed, { ...message, text: "Resumed stream" });
338 for (const before of [initial, sibling, projections[1]!, resumed]) {
339 expect(sameThreadStructure(before, reconnected)).toBe(
340 sameThreadStructure(withoutHints(before), withoutHints(reconnected)),
341 );
342 }
343 expect(sameThreadStructure(sibling, reconnected)).toBe(false);
344 expect(sameThreadStructure(resumed, reconnected)).toBe(true);
345​
346 expect(consecutive).toEqual([true, true, false, true, false, true, false, false]);
347 expect(sameThreadStructure(initial, projections[4]!)).toBe(false);
348 expect(projections[5]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
349 [assistant.id, 0],
350 [reasoning.id, 1],
351 ]);
352 expect(projections[7]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
353 [reasoning.id, 0],
354 [assistant.id, 1],
355 ]);
356});
357​
358describe("deriveWorkspaceMutationId", () => {
359 const item = (id: string, type: string, status: string) =>
360 ({
361 item: { id: TurnItemId.make(id), type, status },
362 }) as unknown as ThreadStructureVisibleTurnItem;
363​
364 it("keys on the latest finished command or file change and the latest checkpoint", () => {
365 expect(
366 deriveWorkspaceMutationId(
367 [
368 item("edit", "file_change", "completed"),
369 item("reply", "assistant_message", "completed"),
370 item("command", "command_execution", "running"),
371 ],
372 "2026-01-01T00:00:00.000Z",
373 ),
374 ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
375 expect(
376 deriveWorkspaceMutationId(
377 [item("edit", "file_change", "completed"), item("mcp", "dynamic_tool", "completed")],
378 null,
379 ),
380 ).toBe(JSON.stringify(["mcp", null]));
381 });
382​
383 it("is null before anything could have touched the workspace", () => {
384 expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
385 null,
386 );
387 });
388});