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

threadDetail.test.ts

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