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

orchestrationV2Projection.test.ts

478 lines15.1 KB

1import { describe, expect, it } from "vite-plus/test";
2import {
3 type OrchestrationV2DomainEvent,
4 type OrchestrationV2Run,
5 type OrchestrationV2ThreadProjection,
6 type OrchestrationV2TurnItem,
7 MessageId,
8 ProjectId,
9 ProviderInstanceId,
10 NodeId,
11 ProviderThreadId,
12 ProviderTurnId,
13 RunId,
14 ThreadId,
15 TurnItemId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18​
19import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
20​
21const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
22const threadId = ThreadId.make("thread-reducer");
23const runId = RunId.make("run-reducer");
24const run = {
25 id: runId,
26 threadId,
27 ordinal: 1,
28 providerInstanceId: ProviderInstanceId.make("codex"),
29 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
30 providerThreadId: null,
31 userMessageId: MessageId.make("message-reducer"),
32 rootNodeId: null,
33 activeAttemptId: null,
34 status: "completed",
35 requestedAt: now,
36 startedAt: now,
37 completedAt: now,
38 checkpointId: null,
39 contextHandoffId: null,
40} satisfies OrchestrationV2Run;
41​
42function commandItem(id: string, output = "done", ordinal = 1): OrchestrationV2TurnItem {
43 return {
44 id: TurnItemId.make(id),
45 threadId,
46 runId,
47 nodeId: null,
48 providerThreadId: null,
49 providerTurnId: null,
50 nativeItemRef: null,
51 parentItemId: null,
52 ordinal,
53 status: "completed",
54 title: null,
55 startedAt: now,
56 completedAt: now,
57 updatedAt: now,
58 type: "command_execution",
59 input: "pwd",
60 output,
61 exitCode: 0,
62 };
64const emptyProjection = {
65 thread: {
66 id: threadId,
67 projectId: ProjectId.make("project-reducer"),
68 title: "Reducer",
69 providerInstanceId: ProviderInstanceId.make("codex"),
70 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
71 runtimeMode: "full-access",
72 interactionMode: "default",
73 branch: null,
74 worktreePath: null,
75 activeProviderThreadId: null,
76 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
77 forkedFrom: null,
78 createdBy: "user",
79 creationSource: "web",
80 createdAt: now,
81 updatedAt: now,
82 archivedAt: null,
83 settledOverride: null,
84 settledAt: null,
85 lastVisitedAt: null,
86 deletedAt: null,
87 },
88 runs: [],
89 attempts: [],
90 nodes: [],
91 subagents: [],
92 providerSessions: [],
93 providerThreads: [],
94 providerTurns: [],
95 runtimeRequests: [],
96 messages: [],
97 plans: [],
98 turnItems: [],
99 checkpointScopes: [],
100 checkpoints: [],
101 contextHandoffs: [],
102 contextTransfers: [],
103 visibleTurnItems: [],
104 updatedAt: now,
105} as OrchestrationV2ThreadProjection;
106​
107describe("applyOrchestrationV2ProjectionEvent", () => {
108 it("keeps live token usage when the terminal provider turn omits it", () => {
109 const providerTurnId = ProviderTurnId.make("provider-turn-reducer");
110 const running = {
111 id: providerTurnId,
112 providerThreadId: ProviderThreadId.make("provider-thread-reducer"),
113 nodeId: NodeId.make("provider-node-reducer"),
114 runAttemptId: null,
115 nativeTurnRef: null,
116 ordinal: 1,
117 status: "running" as const,
118 startedAt: now,
119 completedAt: null,
120 tokenUsage: {
121 usedTokens: 50_000,
122 maxTokens: 200_000,
123 updatedAt: "2026-08-29T00:00:00.000Z",
124 },
125 };
126 const projection = { ...emptyProjection, providerTurns: [running] };
127 const event = {
128 id: "event-provider-turn-terminal",
129 type: "provider-turn.updated",
130 threadId,
131 driver: "codex",
132 occurredAt: now,
133 payload: {
134 ...running,
135 status: "completed",
136 completedAt: now,
137 tokenUsage: undefined,
138 },
139 } as OrchestrationV2DomainEvent;
140​
141 const next = applyOrchestrationV2ProjectionEvent(projection, event);
142​
143 expect(next?.providerTurns[0]?.status).toBe("completed");
144 expect(next?.providerTurns[0]?.tokenUsage).toEqual(running.tokenUsage);
145 });
146​
147 it("applies thread lifecycle payloads instead of leaving stale metadata", () => {
148 const archivedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
149 const event = {
150 id: "event-archive",
151 type: "thread.archived",
152 threadId,
153 occurredAt: archivedAt,
154 payload: { ...emptyProjection.thread, archivedAt, updatedAt: archivedAt },
155 } as OrchestrationV2DomainEvent;
156​
157 const next = applyOrchestrationV2ProjectionEvent(emptyProjection, event);
158 expect(next?.thread.archivedAt).toEqual(archivedAt);
159 expect(next?.updatedAt).toEqual(archivedAt);
160 });
161​
162 it("ignores events for another thread", () => {
163 const event = {
164 id: "event-other",
165 type: "thread.deleted",
166 threadId: ThreadId.make("thread-other"),
167 occurredAt: now,
168 payload: { ...emptyProjection.thread, id: ThreadId.make("thread-other"), deletedAt: now },
169 } as OrchestrationV2DomainEvent;
170​
171 expect(applyOrchestrationV2ProjectionEvent(emptyProjection, event)).toBe(emptyProjection);
172 });
173​
174 it("preserves visible row identity when run updates do not change membership", () => {
175 const item = commandItem("item-stable");
176 const visibleTurnItems = [
177 {
178 position: 0,
179 visibility: "local" as const,
180 sourceThreadId: threadId,
181 sourceItemId: item.id,
182 item,
183 },
184 ];
185 const projection = {
186 ...emptyProjection,
187 runs: [run],
188 turnItems: [item],
189 visibleTurnItems,
190 };
191 const event = {
192 id: "event-run-update",
193 type: "run.updated",
194 threadId,
195 runId,
196 occurredAt: now,
197 payload: { ...run, status: "completed" },
198 } as OrchestrationV2DomainEvent;
199​
200 const next = applyOrchestrationV2ProjectionEvent(projection, event);
201 expect(next?.visibleTurnItems).toBe(visibleTurnItems);
202 expect(next?.visibleTurnItems[0]).toBe(visibleTurnItems[0]);
203 });
204​
205 it("replaces only the updated visible item when membership is unchanged", () => {
206 const first = commandItem("item-first", "first");
207 const second = commandItem("item-second", "second");
208 const firstRow = {
209 position: 0,
210 visibility: "local" as const,
211 sourceThreadId: threadId,
212 sourceItemId: first.id,
213 item: first,
214 };
215 const secondRow = {
216 position: 1,
217 visibility: "local" as const,
218 sourceThreadId: threadId,
219 sourceItemId: second.id,
220 item: second,
221 };
222 const updated = commandItem("item-first", "streamed output");
223 const projection = {
224 ...emptyProjection,
225 runs: [run],
226 turnItems: [first, second],
227 visibleTurnItems: [firstRow, secondRow],
228 };
229 const event = {
230 id: "event-item-update",
231 type: "turn-item.updated",
232 threadId,
233 runId,
234 occurredAt: now,
235 payload: updated,
236 } as OrchestrationV2DomainEvent;
237​
238 const next = applyOrchestrationV2ProjectionEvent(projection, event);
239 expect(next?.visibleTurnItems).not.toBe(projection.visibleTurnItems);
240 expect(next?.visibleTurnItems[0]).not.toBe(firstRow);
241 expect(next?.visibleTurnItems[0]?.item).toBe(updated);
242 expect(next?.visibleTurnItems[1]).toBe(secondRow);
243 });
244​
245 it("inserts live turn items by authoritative ordinal", () => {
246 const queuedFuture = commandItem("item-queued-future", "queued", 300);
247 const activeAssistant = commandItem("item-active-assistant", "done", 201);
248 const queuedRow = {
249 position: 0,
250 visibility: "local" as const,
251 sourceThreadId: threadId,
252 sourceItemId: queuedFuture.id,
253 item: queuedFuture,
254 };
255 const projection = {
256 ...emptyProjection,
257 runs: [run],
258 turnItems: [queuedFuture],
259 visibleTurnItems: [queuedRow],
260 };
261 const event = {
262 id: "event-active-assistant",
263 type: "turn-item.updated",
264 threadId,
265 runId,
266 occurredAt: now,
267 payload: activeAssistant,
268 } as OrchestrationV2DomainEvent;
269​
270 const next = applyOrchestrationV2ProjectionEvent(projection, event);
271 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
272 activeAssistant.id,
273 queuedFuture.id,
274 ]);
275 expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
276 });
277​
278 describe("partial timeline", () => {
279 const queuedRunId = RunId.make("run-queued");
280 const steerRunId = RunId.make("run-steer");
281 const queuedRun = { ...run, id: queuedRunId, ordinal: 2, status: "queued" } as const;
282 const steerRun = { ...run, id: steerRunId, ordinal: 3, status: "completed" } as const;
283 const runItem = (id: string, itemRunId: RunId, ordinal: number) => ({
284 ...commandItem(id, id, ordinal),
285 runId: itemRunId,
286 });
287 const windowOf = (
288 runs: ReadonlyArray<OrchestrationV2Run>,
289 items: ReadonlyArray<OrchestrationV2TurnItem>,
290 ): OrchestrationV2ThreadProjection => ({
291 ...emptyProjection,
292 runs,
293 turnItems: items,
294 visibleTurnItems: items.map((item, position) => ({
295 position,
296 visibility: "local" as const,
297 sourceThreadId: threadId,
298 sourceItemId: item.id,
299 item,
300 })),
301 });
302 const itemEvent = (payload: OrchestrationV2TurnItem) =>
303 ({
304 id: `event-${payload.id}`,
305 type: "turn-item.updated",
306 threadId,
307 occurredAt: now,
308 payload,
309 }) as OrchestrationV2DomainEvent;
310 const runEvent = (payload: OrchestrationV2Run) =>
311 ({
312 id: `event-${payload.id}-${payload.status}`,
313 type: "run.updated",
314 threadId,
315 occurredAt: now,
316 payload,
317 }) as OrchestrationV2DomainEvent;
318​
319 it("shows a queued run that starts after a newer steer raised the watermark", () => {
320 // Run 2 was queued first, run 3 was steered in and ran first. Its items
321 // sit in run 3's band and already raised the watermark past run 2's band.
322 const steerItems = [
323 runItem("item-steer-user", steerRunId, 3_000_001),
324 runItem("item-steer-reply", steerRunId, 3_000_002),
325 ];
326 let projection: OrchestrationV2ThreadProjection | null = windowOf(
327 [run, queuedRun, steerRun],
328 steerItems,
329 );
330 let latestLocalTurnOrdinal = 3_000_002;
331 // Same order the orchestrator commits a queued start: the user message
332 // lands while the run is still queued, then the run starts and replies.
333 const queuedUser = runItem("item-queued-user", queuedRunId, 2_000_001);
334 const queuedReply = runItem("item-queued-reply", queuedRunId, 2_000_002);
335 for (const event of [
336 itemEvent(queuedUser),
337 runEvent({ ...queuedRun, status: "running" }),
338 itemEvent(queuedReply),
339 runEvent({ ...queuedRun, status: "completed" }),
340 ]) {
341 projection = applyOrchestrationV2ProjectionEvent(projection, event, {
342 partialTimeline: true,
343 latestLocalTurnOrdinal,
344 });
345 if (event.type === "turn-item.updated") {
346 latestLocalTurnOrdinal = Math.max(latestLocalTurnOrdinal, event.payload.ordinal);
347 }
348 }
349​
350 expect(projection?.visibleTurnItems.map((row) => row.item.id)).toEqual([
351 queuedUser.id,
352 queuedReply.id,
353 ...steerItems.map((item) => item.id),
354 ]);
355 expect(projection?.turnItems.map((item) => item.id)).toContain(queuedReply.id);
356 });
357​
358 it("keeps a running run's item when the window starts after its earlier items", () => {
359 // The bounded window begins inside run 3; run 2 started and kept going,
360 // but none of its rows made it into the window.
361 const runningRun = { ...queuedRun, status: "running" } as const;
362 const steerItems = [
363 runItem("item-steer-user", steerRunId, 3_000_001),
364 runItem("item-steer-reply", steerRunId, 3_000_002),
365 ];
366 const projection = windowOf([run, runningRun, steerRun], steerItems);
367 const reply = runItem("item-running-reply", queuedRunId, 2_000_003);
368​
369 const next = applyOrchestrationV2ProjectionEvent(projection, itemEvent(reply), {
370 partialTimeline: true,
371 latestLocalTurnOrdinal: 3_000_002,
372 });
373​
374 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
375 reply.id,
376 ...steerItems.map((item) => item.id),
377 ]);
378 });
379​
380 it.each([
381 { name: "keeps an item of a run already in the window", itemRunId: steerRunId, kept: true },
382 { name: "drops an item of a finished run outside the window", itemRunId: runId, kept: false },
383 ])("$name that arrives below the watermark", ({ itemRunId, kept }) => {
384 const first = runItem("item-first", steerRunId, 3_000_001);
385 const later = runItem("item-later", steerRunId, 3_000_003);
386 const late = runItem("item-late", itemRunId, 3_000_002);
387 const projection = windowOf([run, steerRun], [first, later]);
388​
389 const next = applyOrchestrationV2ProjectionEvent(projection, itemEvent(late), {
390 partialTimeline: true,
391 latestLocalTurnOrdinal: later.ordinal,
392 });
393 if (kept) {
394 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
395 first.id,
396 late.id,
397 later.id,
398 ]);
399 } else {
400 expect(next).toBe(projection);
401 }
402 });
403 });
404​
405 it("removes only hidden local items while preserving inherited rows", () => {
406 const inherited = commandItem("item-inherited");
407 const local = commandItem("item-local");
408 const inheritedRow = {
409 position: 0,
410 visibility: "inherited" as const,
411 sourceThreadId: ThreadId.make("thread-source"),
412 sourceItemId: inherited.id,
413 item: inherited,
414 };
415 const localRow = {
416 position: 1,
417 visibility: "local" as const,
418 sourceThreadId: threadId,
419 sourceItemId: local.id,
420 item: local,
421 };
422 const projection = {
423 ...emptyProjection,
424 runs: [run],
425 turnItems: [local],
426 visibleTurnItems: [inheritedRow, localRow],
427 };
428 const event = {
429 id: "event-run-rollback",
430 type: "run.updated",
431 threadId,
432 runId,
433 occurredAt: now,
434 payload: { ...run, status: "rolled_back" },
435 } as OrchestrationV2DomainEvent;
436​
437 const next = applyOrchestrationV2ProjectionEvent(projection, event);
438 expect(next?.visibleTurnItems).toEqual([inheritedRow]);
439 expect(next?.visibleTurnItems[0]).toBe(inheritedRow);
440 });
441});
442​
443it("does not scan every row against every run for a streaming item update", () => {
444 let runReads = 0;
445 const runs = Array.from({ length: 100 }, (_, index) => ({
446 ...run,
447 get id() {
448 runReads++;
449 return RunId.make(`run-${index}`);
450 },
451 }));
452 const items = Array.from({ length: 1000 }, (_, index) =>
453 commandItem(`item-${index}`, "before", index),
454 );
455 const projection = {
456 ...emptyProjection,
457 runs,
458 turnItems: items,
459 visibleTurnItems: items.map((item, position) => ({
460 item,
461 position,
462 visibility: "local" as const,
463 sourceThreadId: threadId,
464 sourceItemId: item.id,
465 })),
466 };
467 const payload = commandItem("item-999", "after", 999);
468 const next = applyOrchestrationV2ProjectionEvent(projection, {
469 id: "stream-update",
470 type: "turn-item.updated",
471 threadId,
472 occurredAt: now,
473 payload,
474 } as OrchestrationV2DomainEvent);
475 expect(next?.visibleTurnItems.at(-1)?.item).toBe(payload);
476 expect(next?.visibleTurnItems[0]).toBe(projection.visibleTurnItems[0]);
477 expect(runReads).toBeLessThanOrEqual(100);
478});