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