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

orchestrationV2Projection.test.ts

538 lines17.1 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 compact visits without changing activity or transcript state", () => {
110 const visitedAt = DateTime.add(now, { hours: 1 });
111 const event = {
112 id: "event-visit-recorded",
113 type: "thread.visit-recorded",
114 threadId,
115 occurredAt: visitedAt,
116 payload: { lastVisitedAt: visitedAt },
117 } as OrchestrationV2DomainEvent;
118 const next = applyOrchestrationV2ProjectionEvent(emptyProjection, event);
119 expect(next?.thread.lastVisitedAt).toEqual(visitedAt);
120 expect(next?.thread.updatedAt).toEqual(now);
121 expect(next?.updatedAt).toEqual(now);
122 expect(next?.turnItems).toBe(emptyProjection.turnItems);
123 });
124​
125 it("applies a compact PR sync without replacing other links or thread metadata", () => {
126 const link = (number: number): ThreadPullRequestLink => ({
127 host: "github.com",
128 repository: "pingdotgg/t3code",
129 number,
130 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
131 source: "manual",
132 linkedAt: DateTime.formatIso(now),
133 snapshot: null,
134 stack: null,
135 });
136 const links = [link(1), link(2)];
137 const projection = {
138 ...emptyProjection,
139 thread: { ...emptyProjection.thread, pullRequests: links },
140 };
141 const updated = { ...links[1]!, source: "agent" as const };
142 const next = applyOrchestrationV2ProjectionEvent(projection, {
143 id: "compact-sync" as OrchestrationV2DomainEvent["id"],
144 type: "thread.pull-request-link-updated",
145 threadId,
146 occurredAt: now,
147 payload: updated,
148 });
149 expect(next?.thread).toEqual({ ...projection.thread, pullRequests: [links[0], updated] });
150 expect(next?.thread.pullRequests?.[0]).toBe(links[0]);
151 const snapshot = {
152 state: "open",
153 title: "Host title",
154 headBranch: "feature",
155 baseBranch: "main",
156 isDraft: false,
157 updatedAt: DateTime.formatIso(now),
158 syncedAt: DateTime.formatIso(now),
159 };
160 const synced = applyOrchestrationV2ProjectionEvent(projection, {
161 id: "host-sync",
162 type: "thread.pull-request-link-synced",
163 threadId,
164 occurredAt: DateTime.add(now, { hours: 1 }),
165 payload: { ...links[1], snapshot, stack: null },
166 } as OrchestrationV2DomainEvent);
167 expect(synced?.thread.pullRequests?.[1]?.snapshot).toEqual(snapshot);
168 expect(synced?.thread.pullRequests?.[0]).toBe(links[0]);
169 expect(synced?.thread.updatedAt).toEqual(now);
170 expect(synced?.updatedAt).toEqual(now);
171 expect(synced?.turnItems).toBe(projection.turnItems);
172 });
173​
174 it("keeps live token usage when the terminal provider turn omits it", () => {
175 const providerTurnId = ProviderTurnId.make("provider-turn-reducer");
176 const running = {
177 id: providerTurnId,
178 providerThreadId: ProviderThreadId.make("provider-thread-reducer"),
179 nodeId: NodeId.make("provider-node-reducer"),
180 runAttemptId: null,
181 nativeTurnRef: null,
182 ordinal: 1,
183 status: "running" as const,
184 startedAt: now,
185 completedAt: null,
186 tokenUsage: {
187 usedTokens: 50_000,
188 maxTokens: 200_000,
189 updatedAt: "2026-08-29T00:00:00.000Z",
190 },
191 };
192 const projection = { ...emptyProjection, providerTurns: [running] };
193 const event = {
194 id: "event-provider-turn-terminal",
195 type: "provider-turn.updated",
196 threadId,
197 driver: "codex",
198 occurredAt: now,
199 payload: {
200 ...running,
201 status: "completed",
202 completedAt: now,
203 tokenUsage: undefined,
204 },
205 } as OrchestrationV2DomainEvent;
206​
207 const next = applyOrchestrationV2ProjectionEvent(projection, event);
208​
209 expect(next?.providerTurns[0]?.status).toBe("completed");
210 expect(next?.providerTurns[0]?.tokenUsage).toEqual(running.tokenUsage);
211 });
212​
213 it("applies thread lifecycle payloads instead of leaving stale metadata", () => {
214 const archivedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
215 const event = {
216 id: "event-archive",
217 type: "thread.archived",
218 threadId,
219 occurredAt: archivedAt,
220 payload: { ...emptyProjection.thread, archivedAt, updatedAt: archivedAt },
221 } as OrchestrationV2DomainEvent;
222​
223 const next = applyOrchestrationV2ProjectionEvent(emptyProjection, event);
224 expect(next?.thread.archivedAt).toEqual(archivedAt);
225 expect(next?.updatedAt).toEqual(archivedAt);
226 });
227​
228 it("ignores events for another thread", () => {
229 const event = {
230 id: "event-other",
231 type: "thread.deleted",
232 threadId: ThreadId.make("thread-other"),
233 occurredAt: now,
234 payload: { ...emptyProjection.thread, id: ThreadId.make("thread-other"), deletedAt: now },
235 } as OrchestrationV2DomainEvent;
236​
237 expect(applyOrchestrationV2ProjectionEvent(emptyProjection, event)).toBe(emptyProjection);
238 });
239​
240 it("preserves visible row identity when run updates do not change membership", () => {
241 const item = commandItem("item-stable");
242 const visibleTurnItems = [
243 {
244 position: 0,
245 visibility: "local" as const,
246 sourceThreadId: threadId,
247 sourceItemId: item.id,
248 item,
249 },
250 ];
251 const projection = {
252 ...emptyProjection,
253 runs: [run],
254 turnItems: [item],
255 visibleTurnItems,
256 };
257 const event = {
258 id: "event-run-update",
259 type: "run.updated",
260 threadId,
261 runId,
262 occurredAt: now,
263 payload: { ...run, status: "completed" },
264 } as OrchestrationV2DomainEvent;
265​
266 const next = applyOrchestrationV2ProjectionEvent(projection, event);
267 expect(next?.visibleTurnItems).toBe(visibleTurnItems);
268 expect(next?.visibleTurnItems[0]).toBe(visibleTurnItems[0]);
269 });
270​
271 it("replaces only the updated visible item when membership is unchanged", () => {
272 const first = commandItem("item-first", "first");
273 const second = commandItem("item-second", "second");
274 const firstRow = {
275 position: 0,
276 visibility: "local" as const,
277 sourceThreadId: threadId,
278 sourceItemId: first.id,
279 item: first,
280 };
281 const secondRow = {
282 position: 1,
283 visibility: "local" as const,
284 sourceThreadId: threadId,
285 sourceItemId: second.id,
286 item: second,
287 };
288 const updated = commandItem("item-first", "streamed output");
289 const projection = {
290 ...emptyProjection,
291 runs: [run],
292 turnItems: [first, second],
293 visibleTurnItems: [firstRow, secondRow],
294 };
295 const event = {
296 id: "event-item-update",
297 type: "turn-item.updated",
298 threadId,
299 runId,
300 occurredAt: now,
301 payload: updated,
302 } as OrchestrationV2DomainEvent;
303​
304 const next = applyOrchestrationV2ProjectionEvent(projection, event);
305 expect(next?.visibleTurnItems).not.toBe(projection.visibleTurnItems);
306 expect(next?.visibleTurnItems[0]).not.toBe(firstRow);
307 expect(next?.visibleTurnItems[0]?.item).toBe(updated);
308 expect(next?.visibleTurnItems[1]).toBe(secondRow);
309 });
310​
311 it("inserts live turn items by authoritative ordinal", () => {
312 const queuedFuture = commandItem("item-queued-future", "queued", 300);
313 const activeAssistant = commandItem("item-active-assistant", "done", 201);
314 const queuedRow = {
315 position: 0,
316 visibility: "local" as const,
317 sourceThreadId: threadId,
318 sourceItemId: queuedFuture.id,
319 item: queuedFuture,
320 };
321 const projection = {
322 ...emptyProjection,
323 runs: [run],
324 turnItems: [queuedFuture],
325 visibleTurnItems: [queuedRow],
326 };
327 const event = {
328 id: "event-active-assistant",
329 type: "turn-item.updated",
330 threadId,
331 runId,
332 occurredAt: now,
333 payload: activeAssistant,
334 } as OrchestrationV2DomainEvent;
335​
336 const next = applyOrchestrationV2ProjectionEvent(projection, event);
337 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
338 activeAssistant.id,
339 queuedFuture.id,
340 ]);
341 expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
342 });
343​
344 describe("partial timeline", () => {
345 const queuedRunId = RunId.make("run-queued");
346 const steerRunId = RunId.make("run-steer");
347 const queuedRun = { ...run, id: queuedRunId, ordinal: 2, status: "queued" } as const;
348 const steerRun = { ...run, id: steerRunId, ordinal: 3, status: "completed" } as const;
349 const runItem = (id: string, itemRunId: RunId, ordinal: number) => ({
350 ...commandItem(id, id, ordinal),
351 runId: itemRunId,
352 });
353 const windowOf = (
354 runs: ReadonlyArray<OrchestrationV2Run>,
355 items: ReadonlyArray<OrchestrationV2TurnItem>,
356 ): OrchestrationV2ThreadProjection => ({
357 ...emptyProjection,
358 runs,
359 turnItems: items,
360 visibleTurnItems: items.map((item, position) => ({
361 position,
362 visibility: "local" as const,
363 sourceThreadId: threadId,
364 sourceItemId: item.id,
365 item,
366 })),
367 });
368 const itemEvent = (payload: OrchestrationV2TurnItem) =>
369 ({
370 id: `event-${payload.id}`,
371 type: "turn-item.updated",
372 threadId,
373 occurredAt: now,
374 payload,
375 }) as OrchestrationV2DomainEvent;
376 const runEvent = (payload: OrchestrationV2Run) =>
377 ({
378 id: `event-${payload.id}-${payload.status}`,
379 type: "run.updated",
380 threadId,
381 occurredAt: now,
382 payload,
383 }) as OrchestrationV2DomainEvent;
384​
385 it("shows a queued run that starts after a newer steer raised the watermark", () => {
386 const steerItems = [
387 runItem("item-steer-user", steerRunId, 3_000_001),
388 runItem("item-steer-reply", steerRunId, 3_000_002),
389 ];
390 let projection: OrchestrationV2ThreadProjection | null = windowOf(
391 [run, queuedRun, steerRun],
392 steerItems,
393 );
394 let latestLocalTurnOrdinal = 3_000_002;
395 const queuedUser = runItem("item-queued-user", queuedRunId, 2_000_001);
396 const queuedReply = runItem("item-queued-reply", queuedRunId, 2_000_002);
397 for (const event of [
398 itemEvent(queuedUser),
399 runEvent({ ...queuedRun, status: "running" }),
400 itemEvent(queuedReply),
401 runEvent({ ...queuedRun, status: "completed" }),
402 ]) {
403 projection = applyOrchestrationV2ProjectionEvent(projection, event, {
404 partialTimeline: true,
405 latestLocalTurnOrdinal,
406 });
407 if (event.type === "turn-item.updated") {
408 latestLocalTurnOrdinal = Math.max(latestLocalTurnOrdinal, event.payload.ordinal);
409 }
410 }
411​
412 expect(projection?.visibleTurnItems.map((row) => row.item.id)).toEqual([
413 queuedUser.id,
414 queuedReply.id,
415 ...steerItems.map((item) => item.id),
416 ]);
417 expect(projection?.turnItems.map((item) => item.id)).toContain(queuedReply.id);
418 });
419​
420 it("keeps a running run's item when the window starts after its earlier items", () => {
421 const runningRun = { ...queuedRun, status: "running" } as const;
422 const steerItems = [
423 runItem("item-steer-user", steerRunId, 3_000_001),
424 runItem("item-steer-reply", steerRunId, 3_000_002),
425 ];
426 const projection = windowOf([run, runningRun, steerRun], steerItems);
427 const reply = runItem("item-running-reply", queuedRunId, 2_000_003);
428​
429 const next = applyOrchestrationV2ProjectionEvent(projection, itemEvent(reply), {
430 partialTimeline: true,
431 latestLocalTurnOrdinal: 3_000_002,
432 });
433​
434 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
435 reply.id,
436 ...steerItems.map((item) => item.id),
437 ]);
438 });
439​
440 it.each([
441 { name: "keeps an item of a run already in the window", itemRunId: steerRunId, kept: true },
442 { name: "drops an item of a finished run outside the window", itemRunId: runId, kept: false },
443 ])("$name that arrives below the watermark", ({ itemRunId, kept }) => {
444 const first = runItem("item-first", steerRunId, 3_000_001);
445 const later = runItem("item-later", steerRunId, 3_000_003);
446 const late = runItem("item-late", itemRunId, 3_000_002);
447 const projection = windowOf([run, steerRun], [first, later]);
448​
449 const next = applyOrchestrationV2ProjectionEvent(projection, itemEvent(late), {
450 partialTimeline: true,
451 latestLocalTurnOrdinal: later.ordinal,
452 });
453 if (kept) {
454 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
455 first.id,
456 late.id,
457 later.id,
458 ]);
459 } else {
460 expect(next).toBe(projection);
461 }
462 });
463 });
464​
465 it("removes only hidden local items while preserving inherited rows", () => {
466 const inherited = commandItem("item-inherited");
467 const local = commandItem("item-local");
468 const inheritedRow = {
469 position: 0,
470 visibility: "inherited" as const,
471 sourceThreadId: ThreadId.make("thread-source"),
472 sourceItemId: inherited.id,
473 item: inherited,
474 };
475 const localRow = {
476 position: 1,
477 visibility: "local" as const,
478 sourceThreadId: threadId,
479 sourceItemId: local.id,
480 item: local,
481 };
482 const projection = {
483 ...emptyProjection,
484 runs: [run],
485 turnItems: [local],
486 visibleTurnItems: [inheritedRow, localRow],
487 };
488 const event = {
489 id: "event-run-rollback",
490 type: "run.updated",
491 threadId,
492 runId,
493 occurredAt: now,
494 payload: { ...run, status: "rolled_back" },
495 } as OrchestrationV2DomainEvent;
496​
497 const next = applyOrchestrationV2ProjectionEvent(projection, event);
498 expect(next?.visibleTurnItems).toEqual([inheritedRow]);
499 expect(next?.visibleTurnItems[0]).toBe(inheritedRow);
500 });
501});
502​
503it("does not scan every row against every run for a streaming item update", () => {
504 let runReads = 0;
505 const runs = Array.from({ length: 100 }, (_, index) => ({
506 ...run,
507 get id() {
508 runReads++;
509 return RunId.make(`run-${index}`);
510 },
511 }));
512 const items = Array.from({ length: 1000 }, (_, index) =>
513 commandItem(`item-${index}`, "before", index),
514 );
515 const projection = {
516 ...emptyProjection,
517 runs,
518 turnItems: items,
519 visibleTurnItems: items.map((item, position) => ({
520 item,
521 position,
522 visibility: "local" as const,
523 sourceThreadId: threadId,
524 sourceItemId: item.id,
525 })),
526 };
527 const payload = commandItem("item-999", "after", 999);
528 const next = applyOrchestrationV2ProjectionEvent(projection, {
529 id: "stream-update",
530 type: "turn-item.updated",
531 threadId,
532 occurredAt: now,
533 payload,
534 } as OrchestrationV2DomainEvent);
535 expect(next?.visibleTurnItems.at(-1)?.item).toBe(payload);
536 expect(next?.visibleTurnItems[0]).toBe(projection.visibleTurnItems[0]);
537 expect(runReads).toBeLessThanOrEqual(100);
538});