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

orchestrationV2Projection.test.ts

901 lines28.8 KB

1import { describe, expect, it } from "vite-plus/test";
2import {
3 type ThreadPullRequestLink,
4 type OrchestrationV2DomainEvent,
5 type OrchestrationV2Run,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2TurnItem,
9 MessageId,
10 ProjectId,
11 ProviderInstanceId,
12 NodeId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunId,
16 ThreadId,
17 TurnItemId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20​
21import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
22​
23const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
24const threadId = ThreadId.make("thread-reducer");
25const runId = RunId.make("run-reducer");
26const run = {
27 id: runId,
28 threadId,
29 ordinal: 1,
30 providerInstanceId: ProviderInstanceId.make("codex"),
31 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
32 providerThreadId: null,
33 userMessageId: MessageId.make("message-reducer"),
34 rootNodeId: null,
35 activeAttemptId: null,
36 status: "completed",
37 requestedAt: now,
38 startedAt: now,
39 completedAt: now,
40 checkpointId: null,
41 contextHandoffId: null,
42} satisfies OrchestrationV2Run;
43​
44function commandItem(id: string, output = "done", ordinal = 1): OrchestrationV2TurnItem {
45 return {
46 id: TurnItemId.make(id),
47 threadId,
48 runId,
49 nodeId: null,
50 providerThreadId: null,
51 providerTurnId: null,
52 nativeItemRef: null,
53 parentItemId: null,
54 ordinal,
55 status: "completed",
56 title: null,
57 startedAt: now,
58 completedAt: now,
59 updatedAt: now,
60 type: "command_execution",
61 input: "pwd",
62 output,
63 exitCode: 0,
64 };
66const emptyProjection = {
67 thread: {
68 id: threadId,
69 projectId: ProjectId.make("project-reducer"),
70 title: "Reducer",
71 providerInstanceId: ProviderInstanceId.make("codex"),
72 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
73 runtimeMode: "full-access",
74 interactionMode: "default",
75 branch: null,
76 worktreePath: null,
77 activeProviderThreadId: null,
78 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
79 forkedFrom: null,
80 createdBy: "user",
81 creationSource: "web",
82 createdAt: now,
83 updatedAt: now,
84 archivedAt: null,
85 settledOverride: null,
86 settledAt: null,
87 lastVisitedAt: null,
88 deletedAt: null,
89 },
90 runs: [],
91 attempts: [],
92 nodes: [],
93 subagents: [],
94 providerSessions: [],
95 providerThreads: [],
96 providerTurns: [],
97 runtimeRequests: [],
98 messages: [],
99 plans: [],
100 turnItems: [],
101 checkpointScopes: [],
102 checkpoints: [],
103 contextHandoffs: [],
104 contextTransfers: [],
105 visibleTurnItems: [],
106 updatedAt: now,
107} as OrchestrationV2ThreadProjection;
108​
109describe("applyOrchestrationV2ProjectionEvent", () => {
110 it("applies a compact PR sync without replacing other links or thread metadata", () => {
111 const link = (number: number): ThreadPullRequestLink => ({
112 host: "github.com",
113 repository: "pingdotgg/t3code",
114 number,
115 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
116 source: "manual",
117 linkedAt: DateTime.formatIso(now),
118 snapshot: null,
119 stack: null,
120 });
121 const links = [link(1), link(2)];
122 const projection = {
123 ...emptyProjection,
124 thread: { ...emptyProjection.thread, pullRequests: links },
125 };
126 const updated = { ...links[1]!, source: "agent" as const };
127 const next = applyOrchestrationV2ProjectionEvent(projection, {
128 id: "compact-sync" as OrchestrationV2DomainEvent["id"],
129 type: "thread.pull-request-link-updated",
130 threadId,
131 occurredAt: now,
132 payload: updated,
133 });
134 expect(next?.thread).toEqual({ ...projection.thread, pullRequests: [links[0], updated] });
135 expect(next?.thread.pullRequests?.[0]).toBe(links[0]);
136 });
137​
138 it("keeps live token usage when the terminal provider turn omits it", () => {
139 const providerTurnId = ProviderTurnId.make("provider-turn-reducer");
140 const running = {
141 id: providerTurnId,
142 providerThreadId: ProviderThreadId.make("provider-thread-reducer"),
143 nodeId: NodeId.make("provider-node-reducer"),
144 runAttemptId: null,
145 nativeTurnRef: null,
146 ordinal: 1,
147 status: "running" as const,
148 startedAt: now,
149 completedAt: null,
150 tokenUsage: {
151 usedTokens: 50_000,
152 maxTokens: 200_000,
153 updatedAt: "2026-08-29T00:00:00.000Z",
154 },
155 };
156 const projection = { ...emptyProjection, providerTurns: [running] };
157 const event = {
158 id: "event-provider-turn-terminal",
159 type: "provider-turn.updated",
160 threadId,
161 driver: "codex",
162 occurredAt: now,
163 payload: {
164 ...running,
165 status: "completed",
166 completedAt: now,
167 tokenUsage: undefined,
168 },
169 } as OrchestrationV2DomainEvent;
170​
171 const next = applyOrchestrationV2ProjectionEvent(projection, event);
172​
173 expect(next?.providerTurns[0]?.status).toBe("completed");
174 expect(next?.providerTurns[0]?.tokenUsage).toEqual(running.tokenUsage);
175 });
176​
177 it("applies thread lifecycle payloads instead of leaving stale metadata", () => {
178 const archivedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
179 const event = {
180 id: "event-archive",
181 type: "thread.archived",
182 threadId,
183 occurredAt: archivedAt,
184 payload: { ...emptyProjection.thread, archivedAt, updatedAt: archivedAt },
185 } as OrchestrationV2DomainEvent;
186​
187 const next = applyOrchestrationV2ProjectionEvent(emptyProjection, event);
188 expect(next?.thread.archivedAt).toEqual(archivedAt);
189 expect(next?.updatedAt).toEqual(archivedAt);
190 });
191​
192 it("preserves visible row identity when run updates do not change membership", () => {
193 const item = commandItem("item-stable");
194 const visibleTurnItems = [
195 {
196 position: 0,
197 visibility: "local" as const,
198 sourceThreadId: threadId,
199 sourceItemId: item.id,
200 item,
201 },
202 ];
203 const projection = {
204 ...emptyProjection,
205 runs: [run],
206 turnItems: [item],
207 visibleTurnItems,
208 };
209 const event = {
210 id: "event-run-update",
211 type: "run.updated",
212 threadId,
213 runId,
214 occurredAt: now,
215 payload: { ...run, status: "completed" },
216 } as OrchestrationV2DomainEvent;
217​
218 const next = applyOrchestrationV2ProjectionEvent(projection, event);
219 expect(next?.visibleTurnItems).toBe(visibleTurnItems);
220 expect(next?.visibleTurnItems[0]).toBe(visibleTurnItems[0]);
221 });
222​
223 it("replaces only the updated visible item and retains its deferred work cursor", () => {
224 const deferredWork = { cursor: "remaining-work", itemCount: 100, lastOrdinal: 101 };
225 const first = { ...commandItem("item-first", "first"), deferredWork };
226 const second = commandItem("item-second", "second");
227 const firstRow = {
228 position: 0,
229 visibility: "local" as const,
230 sourceThreadId: threadId,
231 sourceItemId: first.id,
232 item: first,
233 };
234 const secondRow = {
235 position: 1,
236 visibility: "local" as const,
237 sourceThreadId: threadId,
238 sourceItemId: second.id,
239 item: second,
240 };
241 const updated = commandItem("item-first", "streamed output");
242 const projection = {
243 ...emptyProjection,
244 runs: [run],
245 turnItems: [first, second],
246 visibleTurnItems: [firstRow, secondRow],
247 };
248 const event = {
249 id: "event-item-update",
250 type: "turn-item.updated",
251 threadId,
252 runId,
253 occurredAt: now,
254 payload: updated,
255 } as OrchestrationV2DomainEvent;
256​
257 const next = applyOrchestrationV2ProjectionEvent(projection, event);
258 expect(next?.visibleTurnItems[0]?.item.deferredWork).toEqual(deferredWork);
259 expect(next?.visibleTurnItems).not.toBe(projection.visibleTurnItems);
260 expect(next?.visibleTurnItems[0]).not.toBe(firstRow);
261 expect(next?.visibleTurnItems[0]?.item).toEqual({ ...updated, deferredWork });
262 expect(next?.visibleTurnItems[1]).toBe(secondRow);
263 });
264​
265 it("inserts live turn items by authoritative ordinal", () => {
266 const queuedFuture = commandItem("item-queued-future", "queued", 300);
267 const activeAssistant = commandItem("item-active-assistant", "done", 201);
268 const queuedRow = {
269 position: 0,
270 visibility: "local" as const,
271 sourceThreadId: threadId,
272 sourceItemId: queuedFuture.id,
273 item: queuedFuture,
274 };
275 const projection = {
276 ...emptyProjection,
277 runs: [run],
278 turnItems: [queuedFuture],
279 visibleTurnItems: [queuedRow],
280 };
281 const event = {
282 id: "event-active-assistant",
283 type: "turn-item.updated",
284 threadId,
285 runId,
286 occurredAt: now,
287 payload: activeAssistant,
288 } as OrchestrationV2DomainEvent;
289​
290 const next = applyOrchestrationV2ProjectionEvent(projection, event);
291 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
292 activeAssistant.id,
293 queuedFuture.id,
294 ]);
295 expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
296 });
297​
298 it("moves an updated item to its new ordinal and renumbers the rows it passes", () => {
299 const inherited = {
300 ...commandItem("item-inherited", "parent", 0),
301 threadId: ThreadId.make("parent"),
302 };
303 const items = [
304 commandItem("item-a", "a", 1),
305 commandItem("item-b", "b", 2),
306 commandItem("item-c", "c", 2),
307 ];
308 const rows = [
309 {
310 position: 0,
311 visibility: "inherited" as const,
312 sourceThreadId: inherited.threadId,
313 sourceItemId: inherited.id,
314 item: inherited,
315 },
316 ...items.map((item, index) => ({
317 position: index + 1,
318 visibility: "local" as const,
319 sourceThreadId: threadId,
320 sourceItemId: item.id,
321 item,
322 })),
323 ];
324 const moved = commandItem("item-a", "moved", 2);
325 const next = applyOrchestrationV2ProjectionEvent(
326 { ...emptyProjection, runs: [run], turnItems: items, visibleTurnItems: rows },
327 {
328 id: "event-move",
329 type: "turn-item.updated",
330 threadId,
331 runId,
332 occurredAt: now,
333 payload: moved,
334 } as OrchestrationV2DomainEvent,
335 );
336​
337 // Equal ordinals order by id, so item-a stays ahead of item-b.
338 expect(next?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
339 ["item-inherited", 0],
340 ["item-a", 1],
341 ["item-b", 2],
342 ["item-c", 3],
343 ]);
344 expect(next?.visibleTurnItems[0]).toBe(rows[0]);
345 expect(next?.visibleTurnItems[1]?.item).toBe(moved);
346 expect(next?.turnItems.map((item) => item.id)).toEqual(["item-a", "item-b", "item-c"]);
347​
348 const later = commandItem("item-a", "later", 3);
349 const last = applyOrchestrationV2ProjectionEvent(next, {
350 id: "event-move-later",
351 type: "turn-item.updated",
352 threadId,
353 runId,
354 occurredAt: now,
355 payload: later,
356 } as OrchestrationV2DomainEvent);
357 expect(last?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
358 ["item-inherited", 0],
359 ["item-b", 1],
360 ["item-c", 2],
361 ["item-a", 3],
362 ]);
363 expect(last?.turnItems.at(0)).toBe(later);
364 });
365​
366 describe("partial timeline", () => {
367 const queuedRunId = RunId.make("run-queued");
368 const steerRunId = RunId.make("run-steer");
369 const queuedRun = { ...run, id: queuedRunId, ordinal: 2, status: "queued" } as const;
370 const steerRun = { ...run, id: steerRunId, ordinal: 3, status: "completed" } as const;
371 const runItem = (id: string, itemRunId: RunId, ordinal: number) => ({
372 ...commandItem(id, id, ordinal),
373 runId: itemRunId,
374 });
375 const windowOf = (
376 runs: ReadonlyArray<OrchestrationV2Run>,
377 items: ReadonlyArray<OrchestrationV2TurnItem>,
378 ): OrchestrationV2ThreadProjection => ({
379 ...emptyProjection,
380 runs,
381 turnItems: items,
382 visibleTurnItems: items.map((item, position) => ({
383 position,
384 visibility: "local" as const,
385 sourceThreadId: threadId,
386 sourceItemId: item.id,
387 item,
388 })),
389 });
390 const itemEvent = (payload: OrchestrationV2TurnItem) =>
391 ({
392 id: `event-${payload.id}`,
393 type: "turn-item.updated",
394 threadId,
395 occurredAt: now,
396 payload,
397 }) as OrchestrationV2DomainEvent;
398 const runEvent = (payload: OrchestrationV2Run) =>
399 ({
400 id: `event-${payload.id}-${payload.status}`,
401 type: "run.updated",
402 threadId,
403 occurredAt: now,
404 payload,
405 }) as OrchestrationV2DomainEvent;
406​
407 it("shows a queued run that starts after a newer steer raised the watermark", () => {
408 const steerItems = [
409 runItem("item-steer-user", steerRunId, 3_000_001),
410 runItem("item-steer-reply", steerRunId, 3_000_002),
411 ];
412 let projection: OrchestrationV2ThreadProjection | null = windowOf(
413 [run, queuedRun, steerRun],
414 steerItems,
415 );
416 let latestLocalTurnOrdinal = 3_000_002;
417 const queuedUser = runItem("item-queued-user", queuedRunId, 2_000_001);
418 const queuedReply = runItem("item-queued-reply", queuedRunId, 2_000_002);
419 for (const event of [
420 itemEvent(queuedUser),
421 runEvent({ ...queuedRun, status: "running" }),
422 itemEvent(queuedReply),
423 runEvent({ ...queuedRun, status: "completed" }),
424 ]) {
425 projection = applyOrchestrationV2ProjectionEvent(projection, event, {
426 partialTimeline: true,
427 latestLocalTurnOrdinal,
428 });
429 if (event.type === "turn-item.updated") {
430 latestLocalTurnOrdinal = Math.max(latestLocalTurnOrdinal, event.payload.ordinal);
431 }
432 }
433​
434 expect(projection?.visibleTurnItems.map((row) => row.item.id)).toEqual([
435 queuedUser.id,
436 queuedReply.id,
437 ...steerItems.map((item) => item.id),
438 ]);
439 expect(projection?.turnItems.map((item) => item.id)).toContain(queuedReply.id);
440 });
441​
442 it("keeps a running run's item when the window starts after its earlier items", () => {
443 const runningRun = { ...queuedRun, status: "running" } as const;
444 const steerItems = [
445 runItem("item-steer-user", steerRunId, 3_000_001),
446 runItem("item-steer-reply", steerRunId, 3_000_002),
447 ];
448 const projection = windowOf([run, runningRun, steerRun], steerItems);
449 const reply = runItem("item-running-reply", queuedRunId, 2_000_003);
450​
451 const next = applyOrchestrationV2ProjectionEvent(projection, itemEvent(reply), {
452 partialTimeline: true,
453 latestLocalTurnOrdinal: 3_000_002,
454 });
455​
456 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
457 reply.id,
458 ...steerItems.map((item) => item.id),
459 ]);
460 });
461​
462 it.each([
463 { name: "keeps an item of a run already in the window", itemRunId: steerRunId, kept: true },
464 { name: "drops an item of a finished run outside the window", itemRunId: runId, kept: false },
465 ])("$name that arrives below the watermark", ({ itemRunId, kept }) => {
466 const first = runItem("item-first", steerRunId, 3_000_001);
467 const later = runItem("item-later", steerRunId, 3_000_003);
468 const late = runItem("item-late", itemRunId, 3_000_002);
469 const projection = windowOf([run, steerRun], [first, later]);
470​
471 const next = applyOrchestrationV2ProjectionEvent(projection, itemEvent(late), {
472 partialTimeline: true,
473 latestLocalTurnOrdinal: later.ordinal,
474 });
475 if (kept) {
476 expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
477 first.id,
478 late.id,
479 later.id,
480 ]);
481 } else {
482 expect(next).toBe(projection);
483 }
484 });
485 });
486​
487 it("hides a steer that fell back to the queue until its run starts", () => {
488 const queuedRunId = RunId.make("run-requeued-steer");
489 const queuedRun = {
490 ...run,
491 id: queuedRunId,
492 ordinal: 2,
493 status: "queued",
494 startedAt: null,
495 } as const;
496 const reply = commandItem("item-reply", "reply", 102);
497 const steer: OrchestrationV2TurnItem = {
498 id: TurnItemId.make("item-steer"),
499 threadId,
500 runId,
501 nodeId: null,
502 providerThreadId: null,
503 providerTurnId: null,
504 nativeItemRef: null,
505 parentItemId: null,
506 ordinal: 101,
507 status: "completed",
508 title: null,
509 startedAt: now,
510 completedAt: now,
511 updatedAt: now,
512 type: "user_message",
513 messageId: MessageId.make("message-steer"),
514 inputIntent: "steer",
515 text: "steer",
516 attachments: [],
517 createdBy: "user",
518 creationSource: "web",
519 };
520 const event = (type: "run.updated" | "turn-item.updated", payload: unknown) =>
521 ({
522 id: `event-${type}`,
523 type,
524 threadId,
525 occurredAt: now,
526 payload,
527 }) as OrchestrationV2DomainEvent;
528 const apply = (
529 projection: OrchestrationV2ThreadProjection | null,
530 events: ReadonlyArray<OrchestrationV2DomainEvent>,
531 options?: Parameters<typeof applyOrchestrationV2ProjectionEvent>[2],
532 ) =>
533 events.reduce(
534 (next, item) => applyOrchestrationV2ProjectionEvent(next, item, options),
535 projection,
536 );
537 const visibleIds = (projection: OrchestrationV2ThreadProjection | null) =>
538 projection?.visibleTurnItems.map((row) => row.item.id);
539​
540 const accepted = apply(emptyProjection, [
541 event("run.updated", { ...run, status: "running" }),
542 event("turn-item.updated", steer),
543 event("turn-item.updated", reply),
544 ]);
545 expect(visibleIds(accepted)).toEqual([steer.id, reply.id]);
546​
547 const queuedSteer = event("turn-item.updated", {
548 ...steer,
549 runId: queuedRunId,
550 inputIntent: "queued_turn",
551 status: "pending",
552 startedAt: null,
553 completedAt: null,
554 });
555 const requeued = apply(accepted, [event("run.updated", queuedRun), queuedSteer]);
556 expect(visibleIds(requeued)).toEqual([reply.id]);
557​
558 // Servers publish the start's user item and run update in either order.
559 const starting = event("run.updated", { ...queuedRun, status: "starting" });
560 const dispatchedSteer = event("turn-item.updated", {
561 ...steer,
562 runId: queuedRunId,
563 inputIntent: "queued_turn",
564 });
565 expect(visibleIds(apply(requeued, [dispatchedSteer, starting]))).toEqual([steer.id, reply.id]);
566 expect(visibleIds(apply(requeued, [starting, dispatchedSteer]))).toEqual([steer.id, reply.id]);
567 const cancelled = event("run.updated", { ...queuedRun, status: "cancelled" });
568 expect(visibleIds(apply(requeued, [cancelled]))).toEqual([reply.id]);
569​
570 // A bounded snapshot taken while queued omits the hidden item, and the
571 // newer reply puts it below the watermark.
572 const bounded = {
573 ...requeued!,
574 turnItems: requeued!.turnItems.filter((item) => item.id !== steer.id),
575 };
576 const partial = { partialTimeline: true, latestLocalTurnOrdinal: reply.ordinal };
577 const failed = event("run.updated", { ...queuedRun, status: "failed" });
578 const failedSteer = event("turn-item.updated", {
579 ...steer,
580 runId: queuedRunId,
581 inputIntent: "queued_turn",
582 status: "failed",
583 startedAt: null,
584 });
585 const retained = apply(bounded, [failedSteer], partial);
586 expect(visibleIds(retained)).toEqual([reply.id]);
587 expect(visibleIds(apply(retained, [failed], partial))).toEqual([steer.id, reply.id]);
588 // Leaving the queue never invents an item the client did not receive.
589 expect(visibleIds(apply(bounded, [failed], partial))).toEqual([reply.id]);
590 });
591​
592 it("removes only hidden local items while preserving inherited rows", () => {
593 const inherited = commandItem("item-inherited");
594 const local = commandItem("item-local");
595 const inheritedRow = {
596 position: 0,
597 visibility: "inherited" as const,
598 sourceThreadId: ThreadId.make("thread-source"),
599 sourceItemId: inherited.id,
600 item: inherited,
601 };
602 const localRow = {
603 position: 1,
604 visibility: "local" as const,
605 sourceThreadId: threadId,
606 sourceItemId: local.id,
607 item: local,
608 };
609 const projection = {
610 ...emptyProjection,
611 runs: [run],
612 turnItems: [local],
613 visibleTurnItems: [inheritedRow, localRow],
614 };
615 const event = {
616 id: "event-run-rollback",
617 type: "run.updated",
618 threadId,
619 runId,
620 occurredAt: now,
621 payload: { ...run, status: "rolled_back" },
622 } as OrchestrationV2DomainEvent;
623​
624 const next = applyOrchestrationV2ProjectionEvent(projection, event);
625 expect(next?.visibleTurnItems).toEqual([inheritedRow]);
626 expect(next?.visibleTurnItems[0]).toBe(inheritedRow);
627 });
628});
629​
630it("does not scan every row against every run for a streaming item update", () => {
631 let runReads = 0;
632 const runs = Array.from({ length: 100 }, (_, index) => ({
633 ...run,
634 get id() {
635 runReads++;
636 return RunId.make(`run-${index}`);
637 },
638 }));
639 const items = Array.from({ length: 1000 }, (_, index) =>
640 commandItem(`item-${index}`, "before", index),
641 );
642 const projection = {
643 ...emptyProjection,
644 runs,
645 turnItems: items,
646 visibleTurnItems: items.map((item, position) => ({
647 item,
648 position,
649 visibility: "local" as const,
650 sourceThreadId: threadId,
651 sourceItemId: item.id,
652 })),
653 };
654 const payload = commandItem("item-999", "after", 999);
655 const next = applyOrchestrationV2ProjectionEvent(projection, {
656 id: "stream-update",
657 type: "turn-item.updated",
658 threadId,
659 occurredAt: now,
660 payload,
661 } as OrchestrationV2DomainEvent);
662 expect(next?.visibleTurnItems.at(-1)?.item).toBe(payload);
663 expect(next?.visibleTurnItems[0]).toBe(projection.visibleTurnItems[0]);
664 expect(runReads).toBeLessThanOrEqual(100);
665});
666​
667it("does not scan ordering or positions for a streamed replacement", () => {
668 const size = 100;
669 let ordinalReads = 0;
670 let positionReads = 0;
671 const items = Array.from({ length: size }, (_, index) => ({
672 ...commandItem(`item-${index}`, "before", index),
673 get ordinal() {
674 ordinalReads++;
675 return index;
676 },
677 }));
678 const rows = items.map((item, index) => ({
679 item,
680 get position() {
681 positionReads++;
682 return index;
683 },
684 visibility: "local" as const,
685 sourceThreadId: threadId,
686 sourceItemId: item.id,
687 }));
688 const payload = commandItem(`item-${size - 1}`, "after", size - 1);
689 const next = applyOrchestrationV2ProjectionEvent(
690 { ...emptyProjection, runs: [run], turnItems: items, visibleTurnItems: rows },
691 {
692 id: "stable-replacement",
693 type: "turn-item.updated",
694 threadId,
695 occurredAt: now,
696 payload,
697 } as OrchestrationV2DomainEvent,
698 );
699​
700 expect(ordinalReads).toBeLessThanOrEqual(2);
701 expect(positionReads).toBeLessThanOrEqual(2);
702 expect(next?.visibleTurnItems.at(-1)).toMatchObject({ item: payload, position: size - 1 });
703 expect(next?.visibleTurnItems[0]).toBe(rows[0]);
704 expect(items.at(-1)).toMatchObject({ output: "before" });
705 expect(rows.at(-1)?.item).toBe(items.at(-1));
706});
707​
708it("rechecks visibility when an existing item changes runs without changing ordinal", () => {
709 const first = commandItem("item-first", "first", 1);
710 const second = commandItem("item-second", "second", 2);
711 const rolledBackRun = { ...run, id: RunId.make("rolled-back"), status: "rolled_back" as const };
712 const projection = {
713 ...emptyProjection,
714 runs: [run, rolledBackRun],
715 turnItems: [first, second],
716 visibleTurnItems: [first, second].map((item, position) => ({
717 item,
718 position,
719 visibility: "local" as const,
720 sourceThreadId: threadId,
721 sourceItemId: item.id,
722 })),
723 };
724 const update = (payload: OrchestrationV2TurnItem) =>
725 ({
726 id: "visibility-update",
727 type: "turn-item.updated",
728 threadId,
729 occurredAt: now,
730 payload,
731 }) as OrchestrationV2DomainEvent;
732 const hidden = applyOrchestrationV2ProjectionEvent(
733 projection,
734 update({
735 ...first,
736 runId: rolledBackRun.id,
737 }),
738 );
739 expect(hidden?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
740 [second.id, 0],
741 ]);
742 const restored = applyOrchestrationV2ProjectionEvent(hidden, update(first));
743 expect(restored?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
744 [first.id, 0],
745 [second.id, 1],
746 ]);
747 expect(projection.visibleTurnItems[0]?.item).toBe(first);
748});
749​
750it("restores deduped bodies from the records it already holds, also in a partial timeline", () => {
751 const messageId = MessageId.make("message-deduped");
752 const subagentId = NodeId.make("node-deduped");
753 const reply = {
754 ...commandItem("item-reply", "", 400),
755 type: "assistant_message",
756 messageId,
757 text: "the full reply",
758 streaming: false,
759 } as unknown as OrchestrationV2TurnItem;
760 const subagent = {
761 id: subagentId,
762 threadId,
763 runId,
764 parentNodeId: NodeId.make("node-root"),
765 origin: "app_owned",
766 createdBy: "agent",
767 driver: "codex",
768 providerInstanceId: ProviderInstanceId.make("codex"),
769 providerThreadId: null,
770 childThreadId: null,
771 nativeTaskRef: null,
772 prompt: "the task brief",
773 title: null,
774 model: null,
775 status: "running",
776 result: null,
777 startedAt: now,
778 completedAt: null,
779 updatedAt: now,
780 } as OrchestrationV2ThreadProjection["subagents"][number];
781 const projection = {
782 ...emptyProjection,
783 runs: [run],
784 messages: [
785 {
786 id: messageId,
787 threadId,
788 runId,
789 nodeId: null,
790 role: "assistant",
791 text: "the full reply",
792 attachments: [],
793 streaming: false,
794 createdBy: "agent",
795 creationSource: "provider",
796 createdAt: now,
797 updatedAt: now,
798 },
799 ],
800 subagents: [subagent],
801 } as OrchestrationV2ThreadProjection;
802 const event = (type: string, payload: unknown) =>
803 ({
804 id: `event-${type}`,
805 type,
806 threadId,
807 runId,
808 occurredAt: now,
809 payload,
810 }) as OrchestrationV2DomainEvent;
811​
812 for (const options of [undefined, { partialTimeline: true, latestLocalTurnOrdinal: 300 }]) {
813 const withReply = applyOrchestrationV2ProjectionEvent(
814 projection,
815 event("turn-item.updated", { ...reply, text: "", textOmitted: true }),
816 options,
817 );
818 expect(withReply?.turnItems).toEqual([reply]);
819 expect(withReply?.visibleTurnItems.map((row) => row.item)).toEqual([reply]);
820 }
821 const progressed = applyOrchestrationV2ProjectionEvent(
822 projection,
823 event("subagent.updated", { ...subagent, prompt: "", promptOmitted: true, progress: "step 2" }),
824 );
825 expect(progressed?.subagents).toEqual([{ ...subagent, progress: "step 2" }]);
826});
827​
828describe("provider-thread.updated", () => {
829 const providerThread = (
830 id: string,
831 overrides: Partial<OrchestrationV2ProviderThread> = {},
832 ): OrchestrationV2ProviderThread =>
833 ({
834 id: ProviderThreadId.make(id),
835 driver: "codex",
836 providerInstanceId: ProviderInstanceId.make("codex"),
837 providerSessionId: null,
838 appThreadId: threadId,
839 ownerNodeId: null,
840 nativeThreadRef: null,
841 nativeConversationHeadRef: null,
842 status: "active",
843 firstRunOrdinal: 1,
844 lastRunOrdinal: 1,
845 handoffIds: [],
846 forkedFrom: null,
847 createdAt: now,
848 updatedAt: now,
849 ...overrides,
850 }) as OrchestrationV2ProviderThread;
851 const apply = (payload: unknown) =>
852 applyOrchestrationV2ProjectionEvent(emptyProjection, {
853 id: "event-provider-thread",
854 type: "provider-thread.updated",
855 threadId,
856 occurredAt: now,
857 payload,
858 } as OrchestrationV2DomainEvent);
859​
860 it("moves the thread's active provider thread to the new one", () => {
861 // The shell already knows the old thread, as it would after a provider switch.
862 const projection = applyOrchestrationV2ProjectionEvent(emptyProjection, {
863 id: "event-previous-thread",
864 type: "provider-thread.updated",
865 threadId,
866 occurredAt: now,
867 payload: providerThread("provider-thread-previous"),
868 } as OrchestrationV2DomainEvent);
869 expect(projection?.thread.activeProviderThreadId).toBe(
870 ProviderThreadId.make("provider-thread-previous"),
871 );
872​
873 const next = applyOrchestrationV2ProjectionEvent(projection, {
874 id: "event-next-thread",
875 type: "provider-thread.updated",
876 threadId,
877 occurredAt: now,
878 payload: providerThread("provider-thread-next"),
879 } as OrchestrationV2DomainEvent);
880 expect(next?.thread.activeProviderThreadId).toBe(ProviderThreadId.make("provider-thread-next"));
881 });
882​
883 it("keeps the active provider thread for queued placeholders and other threads", () => {
884 const queued = apply(
885 providerThread("provider-thread-queued", {
886 status: "not_loaded",
887 firstRunOrdinal: null,
888 providerSessionId: null,
889 }),
890 );
891 expect(queued?.thread.activeProviderThreadId).toBeNull();
892​
893 const foreign = apply(
894 providerThread("provider-thread-foreign", { appThreadId: ThreadId.make("other-thread") }),
895 );
896 expect(foreign?.thread.activeProviderThreadId).toBeNull();
897 expect(foreign?.providerThreads.map((thread) => thread.id)).toEqual([
898 ProviderThreadId.make("provider-thread-foreign"),
899 ]);
900 });
901});