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

orchestrationV2Projection.test.ts

569 lines17.8 KB

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