Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 type ModelSelection,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderSessionId,
11 ProviderThreadId,
12 ProviderTurnId,
13 RunAttemptId,
14 RunId,
15 ThreadId,
16 TurnItemId,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Schema from "effect/Schema";
22import * as SqlClient from "effect/unstable/sql/SqlClient";
23
24import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
25import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
26import {
27 isTurnItemAtOrBeforeRun,
28 ProjectionStoreV2,
29 layer as projectionStoreLayer,
30} from "./ProjectionStore.ts";
31
32const TestLayer = Layer.mergeAll(
33 projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
34 SqlitePersistenceMemory,
35);
36const modelSelection = {
37 instanceId: ProviderInstanceId.make("codex"),
38 model: "gpt-5.4",
39} satisfies ModelSelection;
40const driver = ProviderDriverKind.make("codex");
41const providerInstanceId = modelSelection.instanceId;
42const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
43
44it("includes imported runless history when selecting fork context through a run", () => {
45 const firstRunId = RunId.make("run:projection-imported-fork:1");
46 const secondRunId = RunId.make("run:projection-imported-fork:2");
47 const runOrdinalById = new Map([
48 [firstRunId, 1],
49 [secondRunId, 2],
50 ]);
51
52 assert.isTrue(
53 isTurnItemAtOrBeforeRun({
54 historyOrigin: "v1_import",
55 itemRunId: null,
56 runOrdinalById,
57 sourceRunOrdinal: 1,
58 }),
59 );
60 assert.isFalse(
61 isTurnItemAtOrBeforeRun({
62 historyOrigin: undefined,
63 itemRunId: null,
64 runOrdinalById,
65 sourceRunOrdinal: 1,
66 }),
67 );
68 assert.isTrue(
69 isTurnItemAtOrBeforeRun({
70 historyOrigin: "v1_import",
71 itemRunId: firstRunId,
72 runOrdinalById,
73 sourceRunOrdinal: 1,
74 }),
75 );
76 assert.isFalse(
77 isTurnItemAtOrBeforeRun({
78 historyOrigin: "v1_import",
79 itemRunId: secondRunId,
80 runOrdinalById,
81 sourceRunOrdinal: 1,
82 }),
83 );
84});
85
86it.layer(TestLayer)("ProjectionStoreV2", (it) => {
87 it.effect("does not treat visited or marked-unread state as thread activity", () =>
88 Effect.gen(function* () {
89 const projectionStore = yield* ProjectionStoreV2;
90 const createdAt = yield* DateTime.now;
91 const visitedOccurredAt = DateTime.add(createdAt, { seconds: 1 });
92 const markedUnreadOccurredAt = DateTime.add(createdAt, { seconds: 2 });
93 const threadId = ThreadId.make("thread:projection-read-state");
94 const projectId = ProjectId.make("project:projection-read-state");
95 const thread = {
96 createdBy: "user" as const,
97 creationSource: "web" as const,
98 id: threadId,
99 projectId,
100 title: "Projection read state",
101 providerInstanceId,
102 modelSelection,
103 runtimeMode: "full-access" as const,
104 interactionMode: "default" as const,
105 branch: null,
106 worktreePath: null,
107 activeProviderThreadId: null,
108 lineage: {
109 parentThreadId: null,
110 relationshipToParent: null,
111 rootThreadId: threadId,
112 },
113 forkedFrom: null,
114 createdAt,
115 updatedAt: createdAt,
116 archivedAt: null,
117 settledOverride: null,
118 settledAt: null,
119 lastVisitedAt: null,
120 deletedAt: null,
121 };
122
123 yield* projectionStore.apply({
124 id: EventId.make("event:projection-read-state:created"),
125 type: "thread.created",
126 threadId,
127 occurredAt: createdAt,
128 payload: thread,
129 });
130 yield* projectionStore.apply({
131 id: EventId.make("event:projection-read-state:visited"),
132 type: "thread.visited",
133 threadId,
134 occurredAt: visitedOccurredAt,
135 payload: { ...thread, lastVisitedAt: createdAt },
136 });
137
138 const visited = yield* projectionStore.getThreadProjection(threadId);
139 assert.deepEqual(visited.thread.lastVisitedAt, createdAt);
140 assert.deepEqual(visited.thread.updatedAt, createdAt);
141
142 yield* projectionStore.apply({
143 id: EventId.make("event:projection-read-state:marked-unread"),
144 type: "thread.marked-unread",
145 threadId,
146 occurredAt: markedUnreadOccurredAt,
147 payload: thread,
148 });
149
150 const markedUnread = yield* projectionStore.getThreadProjection(threadId);
151 assert.isNull(markedUnread.thread.lastVisitedAt);
152 assert.deepEqual(markedUnread.thread.updatedAt, createdAt);
153 }),
154 );
155
156 it.effect("only exposes interruptible runs through the shell activeRunId", () =>
157 Effect.gen(function* () {
158 const projectionStore = yield* ProjectionStoreV2;
159 const now = yield* DateTime.now;
160 const threadId = ThreadId.make("thread:projection-shell-interruptible");
161 const projectId = ProjectId.make("project:projection-shell-interruptible");
162 const runId = RunId.make("run:projection-shell-interruptible");
163 const rootNodeId = NodeId.make("node:projection-shell-interruptible");
164 const run = {
165 id: runId,
166 threadId,
167 ordinal: 1,
168 providerInstanceId,
169 modelSelection,
170 providerThreadId: null,
171 userMessageId: MessageId.make("message:projection-shell-interruptible"),
172 rootNodeId,
173 activeAttemptId: null,
174 status: "running" as const,
175 requestedAt: now,
176 startedAt: now,
177 completedAt: null,
178 checkpointId: null,
179 contextHandoffId: null,
180 };
181
182 yield* projectionStore.apply({
183 id: EventId.make("event:projection-shell-interruptible:thread"),
184 type: "thread.created",
185 threadId,
186 occurredAt: now,
187 payload: {
188 createdBy: "user",
189 creationSource: "web",
190 id: threadId,
191 projectId,
192 title: "Interruptible shell run",
193 providerInstanceId,
194 modelSelection,
195 runtimeMode: "full-access",
196 interactionMode: "default",
197 branch: null,
198 worktreePath: null,
199 activeProviderThreadId: null,
200 lineage: {
201 parentThreadId: null,
202 relationshipToParent: null,
203 rootThreadId: threadId,
204 },
205 forkedFrom: null,
206 createdAt: now,
207 updatedAt: now,
208 archivedAt: null,
209 settledOverride: null,
210 settledAt: null,
211 lastVisitedAt: null,
212 deletedAt: null,
213 },
214 });
215 yield* projectionStore.apply({
216 id: EventId.make("event:projection-shell-interruptible:running"),
217 type: "run.created",
218 threadId,
219 runId,
220 nodeId: rootNodeId,
221 driver,
222 occurredAt: now,
223 payload: run,
224 });
225
226 let shell = (yield* projectionStore.getShellSnapshot()).threads.find(
227 (thread) => thread.id === threadId,
228 );
229 assert.equal(shell?.status, "running");
230 assert.equal(shell?.activeRunId, runId);
231 assert.equal(
232 shell?.latestRunRequestedAt && DateTime.toEpochMillis(shell.latestRunRequestedAt),
233 DateTime.toEpochMillis(now),
234 );
235 assert.equal(
236 shell?.latestRunStartedAt && DateTime.toEpochMillis(shell.latestRunStartedAt),
237 DateTime.toEpochMillis(now),
238 );
239 assert.isNull(shell?.latestRunCompletedAt);
240
241 yield* projectionStore.apply({
242 id: EventId.make("event:projection-shell-interruptible:waiting"),
243 type: "run.updated",
244 threadId,
245 runId,
246 nodeId: rootNodeId,
247 driver,
248 occurredAt: now,
249 payload: { ...run, status: "waiting" },
250 });
251
252 shell = (yield* projectionStore.getShellSnapshot()).threads.find(
253 (thread) => thread.id === threadId,
254 );
255 assert.equal(shell?.status, "waiting");
256 assert.isNull(shell?.activeRunId);
257 }),
258 );
259
260 it.effect("projects one shared provider session into multiple thread bindings", () =>
261 Effect.gen(function* () {
262 const projectionStore = yield* ProjectionStoreV2;
263 const now = yield* DateTime.now;
264 const projectId = ProjectId.make("project:projection-shared-provider-session");
265 const firstThreadId = ThreadId.make("thread:projection-shared-provider-session:first");
266 const secondThreadId = ThreadId.make("thread:projection-shared-provider-session:second");
267 const providerSessionId = ProviderSessionId.make(
268 "provider-session:projection-shared-provider-session",
269 );
270 const makeThread = (threadId: ThreadId) => ({
271 createdBy: "user" as const,
272 creationSource: "web" as const,
273 id: threadId,
274 projectId,
275 title: "Shared provider session",
276 providerInstanceId,
277 modelSelection,
278 runtimeMode: "full-access" as const,
279 interactionMode: "default" as const,
280 branch: null,
281 worktreePath: null,
282 activeProviderThreadId: null,
283 lineage: {
284 parentThreadId: null,
285 relationshipToParent: null,
286 rootThreadId: threadId,
287 },
288 forkedFrom: null,
289 createdAt: now,
290 updatedAt: now,
291 archivedAt: null,
292 settledOverride: null,
293 settledAt: null,
294 lastVisitedAt: null,
295 deletedAt: null,
296 });
297 const session = {
298 id: providerSessionId,
299 driver,
300 providerInstanceId,
301 status: "error" as const,
302 cwd: "/workspace",
303 model: modelSelection.model,
304 capabilities: CodexProviderCapabilitiesV2,
305 createdAt: now,
306 updatedAt: now,
307 lastError: "provider process exited",
308 };
309
310 yield* projectionStore.apply({
311 id: EventId.make("event:projection-shared-provider-session:first-thread"),
312 type: "thread.created",
313 threadId: firstThreadId,
314 occurredAt: now,
315 payload: makeThread(firstThreadId),
316 });
317 yield* projectionStore.apply({
318 id: EventId.make("event:projection-shared-provider-session:second-thread"),
319 type: "thread.created",
320 threadId: secondThreadId,
321 occurredAt: now,
322 payload: makeThread(secondThreadId),
323 });
324 for (const [threadId, suffix] of [
325 [firstThreadId, "first"],
326 [secondThreadId, "second"],
327 ] as const) {
328 yield* projectionStore.apply({
329 id: EventId.make(`event:projection-shared-provider-session:${suffix}-binding`),
330 type: "provider-session.attached",
331 threadId,
332 driver,
333 providerInstanceId,
334 occurredAt: now,
335 payload: session,
336 });
337 }
338
339 assert.deepEqual(
340 (yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions.map(
341 (value) => value.id,
342 ),
343 [providerSessionId],
344 );
345 assert.deepEqual(
346 (yield* projectionStore.getThreadProjection(secondThreadId)).providerSessions.map(
347 (value) => value.id,
348 ),
349 [providerSessionId],
350 );
351 assert.deepEqual(
352 (yield* projectionStore.getShellSnapshot()).threads
353 .filter((thread) => thread.id === firstThreadId || thread.id === secondThreadId)
354 .map((thread) => ({
355 id: thread.id,
356 lastError: thread.lastError,
357 })),
358 [
359 { id: firstThreadId, lastError: "provider process exited" },
360 { id: secondThreadId, lastError: "provider process exited" },
361 ],
362 );
363
364 yield* projectionStore.apply({
365 id: EventId.make("event:projection-shared-provider-session:first-detached"),
366 type: "provider-session.detached",
367 threadId: firstThreadId,
368 driver,
369 providerInstanceId,
370 occurredAt: now,
371 payload: { providerSessionId, detachedAt: now },
372 });
373
374 assert.lengthOf(
375 (yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions,
376 0,
377 );
378 assert.lengthOf(
379 (yield* projectionStore.getThreadProjection(secondThreadId)).providerSessions,
380 1,
381 );
382 }),
383 );
384
385 it.effect("builds shell snapshots without decoding full turn item payloads", () =>
386 Effect.gen(function* () {
387 const projectionStore = yield* ProjectionStoreV2;
388 const sql = yield* SqlClient.SqlClient;
389 const now = yield* DateTime.now;
390 const nowIso = DateTime.formatIso(now);
391 const threadId = ThreadId.make("thread:projection-shell-stale-item");
392 const projectId = ProjectId.make("project:projection-shell");
393
394 yield* projectionStore.apply({
395 id: EventId.make("event:projection-shell-thread-created"),
396 type: "thread.created",
397 threadId,
398 occurredAt: now,
399 payload: {
400 createdBy: "user",
401 creationSource: "web",
402 id: threadId,
403 projectId,
404 title: "Projection shell",
405 providerInstanceId,
406 modelSelection: modelSelection,
407 runtimeMode: "full-access",
408 interactionMode: "default",
409 branch: null,
410 worktreePath: null,
411 activeProviderThreadId: null,
412 lineage: {
413 parentThreadId: null,
414 relationshipToParent: null,
415 rootThreadId: threadId,
416 },
417 forkedFrom: null,
418 createdAt: now,
419 updatedAt: now,
420 archivedAt: null,
421 settledOverride: null,
422 settledAt: null,
423 lastVisitedAt: null,
424 deletedAt: null,
425 },
426 });
427
428 yield* sql`
429 INSERT INTO orchestration_v2_projection_turn_items (
430 turn_item_id,
431 thread_id,
432 run_id,
433 node_id,
434 provider_thread_id,
435 provider_turn_id,
436 parent_item_id,
437 ordinal,
438 type,
439 status,
440 updated_at,
441 payload_json
442 )
443 VALUES (
444 ${"turn-item:stale-user-message"},
445 ${threadId},
446 ${null},
447 ${null},
448 ${null},
449 ${null},
450 ${null},
451 ${0},
452 ${"user_message"},
453 ${"completed"},
454 ${nowIso},
455 ${encodeUnknownJsonString({
456 id: "turn-item:stale-user-message",
457 threadId,
458 runId: null,
459 nodeId: null,
460 providerThreadId: null,
461 providerTurnId: null,
462 nativeItemRef: null,
463 parentItemId: null,
464 ordinal: 0,
465 status: "completed",
466 title: null,
467 startedAt: nowIso,
468 completedAt: nowIso,
469 updatedAt: nowIso,
470 type: "user_message",
471 messageId: "message:stale-user-message",
472 text: "stale user message",
473 attachments: [],
474 })}
475 )
476 `;
477
478 const shell = yield* projectionStore.getShellSnapshot();
479 const fullProjectionExit = yield* Effect.exit(projectionStore.getThreadProjection(threadId));
480
481 assert.deepEqual(
482 shell.threads
483 .filter((thread) => thread.id === threadId)
484 .map((thread) => ({
485 id: thread.id,
486 itemCount: thread.itemCount,
487 visibleItemCount: thread.visibleItemCount,
488 status: thread.status,
489 })),
490 [
491 {
492 id: threadId,
493 itemCount: 1,
494 visibleItemCount: 1,
495 status: "idle",
496 },
497 ],
498 );
499 assert.equal(fullProjectionExit._tag, "Failure");
500 }),
501 );
502
503 it.effect("counts imported runless history inherited by fork shells", () =>
504 Effect.gen(function* () {
505 const projectionStore = yield* ProjectionStoreV2;
506 const now = yield* DateTime.now;
507 const projectId = ProjectId.make("project:projection-imported-fork-shell");
508 const sourceThreadId = ThreadId.make("thread:projection-imported-fork-shell:source");
509 const targetThreadId = ThreadId.make("thread:projection-imported-fork-shell:target");
510 const sourceRunId = RunId.make("run:projection-imported-fork-shell:source");
511 const rootNodeId = NodeId.make("node:projection-imported-fork-shell:source");
512
513 yield* projectionStore.apply({
514 id: EventId.make("event:projection-imported-fork-shell:source-thread"),
515 type: "thread.created",
516 threadId: sourceThreadId,
517 occurredAt: now,
518 payload: {
519 createdBy: "system",
520 creationSource: "server",
521 id: sourceThreadId,
522 projectId,
523 title: "Imported fork source",
524 providerInstanceId,
525 modelSelection,
526 runtimeMode: "full-access",
527 interactionMode: "default",
528 branch: null,
529 worktreePath: null,
530 activeProviderThreadId: null,
531 historyOrigin: "v1_import",
532 lineage: {
533 parentThreadId: null,
534 relationshipToParent: null,
535 rootThreadId: sourceThreadId,
536 },
537 forkedFrom: null,
538 createdAt: now,
539 updatedAt: now,
540 archivedAt: null,
541 settledOverride: null,
542 settledAt: null,
543 lastVisitedAt: null,
544 deletedAt: null,
545 },
546 });
547 yield* projectionStore.apply({
548 id: EventId.make("event:projection-imported-fork-shell:target-thread"),
549 type: "thread.created",
550 threadId: targetThreadId,
551 occurredAt: now,
552 payload: {
553 createdBy: "user",
554 creationSource: "web",
555 id: targetThreadId,
556 projectId,
557 title: "Imported fork target",
558 providerInstanceId,
559 modelSelection,
560 runtimeMode: "full-access",
561 interactionMode: "default",
562 branch: null,
563 worktreePath: null,
564 activeProviderThreadId: null,
565 lineage: {
566 parentThreadId: sourceThreadId,
567 relationshipToParent: "fork",
568 rootThreadId: sourceThreadId,
569 },
570 forkedFrom: {
571 type: "run",
572 threadId: sourceThreadId,
573 runId: sourceRunId,
574 },
575 createdAt: now,
576 updatedAt: now,
577 archivedAt: null,
578 settledOverride: null,
579 settledAt: null,
580 lastVisitedAt: null,
581 deletedAt: null,
582 },
583 });
584 yield* projectionStore.apply({
585 id: EventId.make("event:projection-imported-fork-shell:source-run"),
586 type: "run.created",
587 threadId: sourceThreadId,
588 runId: sourceRunId,
589 nodeId: rootNodeId,
590 driver,
591 occurredAt: now,
592 payload: {
593 id: sourceRunId,
594 threadId: sourceThreadId,
595 ordinal: 1,
596 providerInstanceId,
597 modelSelection,
598 providerThreadId: null,
599 userMessageId: MessageId.make("message:projection-imported-fork-shell:run"),
600 rootNodeId,
601 activeAttemptId: null,
602 status: "completed",
603 requestedAt: now,
604 startedAt: now,
605 completedAt: now,
606 checkpointId: null,
607 contextHandoffId: null,
608 },
609 });
610
611 const applyAssistantItem = (suffix: string, runId: RunId | null, ordinal: number) =>
612 projectionStore.apply({
613 id: EventId.make(`event:projection-imported-fork-shell:item:${suffix}`),
614 type: "turn-item.updated",
615 threadId: sourceThreadId,
616 ...(runId === null ? {} : { runId }),
617 occurredAt: now,
618 payload: {
619 id: TurnItemId.make(`turn-item:projection-imported-fork-shell:${suffix}`),
620 threadId: sourceThreadId,
621 runId,
622 nodeId: null,
623 providerThreadId: null,
624 providerTurnId: null,
625 nativeItemRef: null,
626 parentItemId: null,
627 ordinal,
628 status: "completed",
629 title: null,
630 startedAt: now,
631 completedAt: now,
632 updatedAt: now,
633 type: "assistant_message",
634 messageId: MessageId.make(`message:projection-imported-fork-shell:${suffix}`),
635 text: suffix,
636 streaming: false,
637 },
638 });
639
640 yield* applyAssistantItem("imported-one", null, 1);
641 yield* applyAssistantItem("imported-two", null, 2);
642 yield* applyAssistantItem("native-run", sourceRunId, 3);
643
644 const shell = yield* projectionStore.getShellSnapshot();
645 const targetShell = shell.threads.find((thread) => thread.id === targetThreadId);
646 const targetProjection = yield* projectionStore.getThreadProjection(targetThreadId);
647
648 assert.isDefined(targetShell);
649 assert.equal(targetShell.itemCount, 0);
650 assert.equal(targetShell.visibleItemCount, 4);
651 assert.equal(targetProjection.visibleTurnItems.length, 4);
652 }),
653 );
654
655 it.effect("removes rolled back runs from the active visible projection", () =>
656 Effect.gen(function* () {
657 const projectionStore = yield* ProjectionStoreV2;
658 const now = yield* DateTime.now;
659 const threadId = ThreadId.make("thread:projection-rollback-prune");
660 const projectId = ProjectId.make("project:projection-rollback-prune");
661 const runId = RunId.make("run:projection-rollback-prune");
662 const attemptId = RunAttemptId.make("attempt:projection-rollback-prune");
663 const rootNodeId = NodeId.make("node:projection-rollback-prune:root");
664 const assistantNodeId = NodeId.make("node:projection-rollback-prune:assistant");
665 const providerThreadId = ProviderThreadId.make("provider-thread:projection-rollback-prune");
666 const providerTurnId = ProviderTurnId.make("provider-turn:projection-rollback-prune");
667 const userMessageId = MessageId.make("message:projection-rollback-prune:user");
668 const assistantMessageId = MessageId.make("message:projection-rollback-prune:assistant");
669 const userTurnItemId = TurnItemId.make("turn-item:projection-rollback-prune:user");
670 const assistantTurnItemId = TurnItemId.make("turn-item:projection-rollback-prune:assistant");
671
672 yield* projectionStore.apply({
673 id: EventId.make("event:projection-rollback-prune:thread-created"),
674 type: "thread.created",
675 threadId,
676 occurredAt: now,
677 payload: {
678 createdBy: "user",
679 creationSource: "web",
680 id: threadId,
681 projectId,
682 title: "Projection rollback prune",
683 providerInstanceId,
684 modelSelection,
685 runtimeMode: "full-access",
686 interactionMode: "default",
687 branch: null,
688 worktreePath: null,
689 activeProviderThreadId: providerThreadId,
690 lineage: {
691 parentThreadId: null,
692 relationshipToParent: null,
693 rootThreadId: threadId,
694 },
695 forkedFrom: null,
696 createdAt: now,
697 updatedAt: now,
698 archivedAt: null,
699 settledOverride: null,
700 settledAt: null,
701 lastVisitedAt: null,
702 deletedAt: null,
703 },
704 });
705 yield* projectionStore.apply({
706 id: EventId.make("event:projection-rollback-prune:provider-thread"),
707 type: "provider-thread.updated",
708 threadId,
709 driver,
710 occurredAt: now,
711 payload: {
712 id: providerThreadId,
713 driver,
714 providerInstanceId,
715 providerSessionId: null,
716 appThreadId: threadId,
717 ownerNodeId: null,
718 nativeThreadRef: null,
719 nativeConversationHeadRef: null,
720 status: "active",
721 firstRunOrdinal: 1,
722 lastRunOrdinal: 1,
723 handoffIds: [],
724 forkedFrom: null,
725 createdAt: now,
726 updatedAt: now,
727 },
728 });
729 yield* projectionStore.apply({
730 id: EventId.make("event:projection-rollback-prune:run-created"),
731 type: "run.created",
732 threadId,
733 runId,
734 nodeId: rootNodeId,
735 driver,
736 occurredAt: now,
737 payload: {
738 id: runId,
739 threadId,
740 ordinal: 1,
741 providerInstanceId,
742 modelSelection,
743 providerThreadId,
744 userMessageId,
745 rootNodeId,
746 activeAttemptId: attemptId,
747 status: "completed",
748 requestedAt: now,
749 startedAt: now,
750 completedAt: now,
751 checkpointId: null,
752 contextHandoffId: null,
753 },
754 });
755 yield* projectionStore.apply({
756 id: EventId.make("event:projection-rollback-prune:attempt-created"),
757 type: "run-attempt.created",
758 threadId,
759 runId,
760 nodeId: rootNodeId,
761 driver,
762 occurredAt: now,
763 payload: {
764 id: attemptId,
765 runId,
766 attemptOrdinal: 1,
767 rootNodeId,
768 providerInstanceId,
769 providerThreadId,
770 providerTurnId,
771 reason: "initial",
772 status: "completed",
773 startedAt: now,
774 completedAt: now,
775 },
776 });
777 yield* projectionStore.apply({
778 id: EventId.make("event:projection-rollback-prune:root-node"),
779 type: "node.updated",
780 threadId,
781 runId,
782 nodeId: rootNodeId,
783 driver,
784 occurredAt: now,
785 payload: {
786 id: rootNodeId,
787 threadId,
788 runId,
789 parentNodeId: null,
790 rootNodeId,
791 kind: "root_turn",
792 status: "completed",
793 countsForRun: true,
794 providerThreadId,
795 providerTurnId: null,
796 nativeItemRef: null,
797 runtimeRequestId: null,
798 checkpointScopeId: null,
799 startedAt: now,
800 completedAt: now,
801 },
802 });
803 yield* projectionStore.apply({
804 id: EventId.make("event:projection-rollback-prune:assistant-node"),
805 type: "node.updated",
806 threadId,
807 runId,
808 nodeId: assistantNodeId,
809 driver,
810 occurredAt: now,
811 payload: {
812 id: assistantNodeId,
813 threadId,
814 runId,
815 parentNodeId: rootNodeId,
816 rootNodeId,
817 kind: "assistant_message",
818 status: "completed",
819 countsForRun: false,
820 providerThreadId,
821 providerTurnId,
822 nativeItemRef: null,
823 runtimeRequestId: null,
824 checkpointScopeId: null,
825 startedAt: now,
826 completedAt: now,
827 },
828 });
829 yield* projectionStore.apply({
830 id: EventId.make("event:projection-rollback-prune:provider-turn"),
831 type: "provider-turn.updated",
832 threadId,
833 runId,
834 nodeId: rootNodeId,
835 driver,
836 occurredAt: now,
837 payload: {
838 id: providerTurnId,
839 providerThreadId,
840 nodeId: rootNodeId,
841 runAttemptId: attemptId,
842 nativeTurnRef: null,
843 ordinal: 1,
844 status: "completed",
845 startedAt: now,
846 completedAt: now,
847 },
848 });
849 yield* projectionStore.apply({
850 id: EventId.make("event:projection-rollback-prune:user-message"),
851 type: "message.updated",
852 threadId,
853 runId,
854 nodeId: rootNodeId,
855 driver,
856 occurredAt: now,
857 payload: {
858 createdBy: "user",
859 creationSource: "web",
860 id: userMessageId,
861 threadId,
862 runId,
863 nodeId: rootNodeId,
864 role: "user",
865 text: "rolled back user",
866 attachments: [],
867 streaming: false,
868 createdAt: now,
869 updatedAt: now,
870 },
871 });
872 yield* projectionStore.apply({
873 id: EventId.make("event:projection-rollback-prune:assistant-message"),
874 type: "message.updated",
875 threadId,
876 runId,
877 nodeId: assistantNodeId,
878 driver,
879 occurredAt: now,
880 payload: {
881 createdBy: "agent",
882 creationSource: "provider",
883 id: assistantMessageId,
884 threadId,
885 runId,
886 nodeId: assistantNodeId,
887 role: "assistant",
888 text: "rolled back assistant",
889 attachments: [],
890 streaming: false,
891 createdAt: now,
892 updatedAt: now,
893 },
894 });
895 yield* projectionStore.apply({
896 id: EventId.make("event:projection-rollback-prune:user-item"),
897 type: "turn-item.updated",
898 threadId,
899 runId,
900 nodeId: rootNodeId,
901 driver,
902 occurredAt: now,
903 payload: {
904 createdBy: "user",
905 creationSource: "web",
906 id: userTurnItemId,
907 threadId,
908 runId,
909 nodeId: rootNodeId,
910 providerThreadId,
911 providerTurnId: null,
912 nativeItemRef: null,
913 parentItemId: null,
914 ordinal: 100,
915 status: "completed",
916 title: null,
917 startedAt: now,
918 completedAt: now,
919 updatedAt: now,
920 type: "user_message",
921 messageId: userMessageId,
922 inputIntent: "turn_start",
923 text: "rolled back user",
924 attachments: [],
925 },
926 });
927 yield* projectionStore.apply({
928 id: EventId.make("event:projection-rollback-prune:assistant-item"),
929 type: "turn-item.updated",
930 threadId,
931 runId,
932 nodeId: assistantNodeId,
933 driver,
934 occurredAt: now,
935 payload: {
936 id: assistantTurnItemId,
937 threadId,
938 runId,
939 nodeId: assistantNodeId,
940 providerThreadId,
941 providerTurnId,
942 nativeItemRef: null,
943 parentItemId: null,
944 ordinal: 101,
945 status: "completed",
946 title: null,
947 startedAt: now,
948 completedAt: now,
949 updatedAt: now,
950 type: "assistant_message",
951 messageId: assistantMessageId,
952 text: "rolled back assistant",
953 streaming: false,
954 },
955 });
956 yield* projectionStore.apply({
957 id: EventId.make("event:projection-rollback-prune:run-rolled-back"),
958 type: "run.updated",
959 threadId,
960 runId,
961 nodeId: rootNodeId,
962 driver,
963 occurredAt: now,
964 payload: {
965 id: runId,
966 threadId,
967 ordinal: 1,
968 providerInstanceId,
969 modelSelection,
970 providerThreadId,
971 userMessageId,
972 rootNodeId,
973 activeAttemptId: attemptId,
974 status: "rolled_back",
975 requestedAt: now,
976 startedAt: now,
977 completedAt: now,
978 checkpointId: null,
979 contextHandoffId: null,
980 },
981 });
982 yield* projectionStore.apply({
983 id: EventId.make("event:projection-rollback-prune:root-rolled-back"),
984 type: "node.updated",
985 threadId,
986 runId,
987 nodeId: rootNodeId,
988 driver,
989 occurredAt: now,
990 payload: {
991 id: rootNodeId,
992 threadId,
993 runId,
994 parentNodeId: null,
995 rootNodeId,
996 kind: "root_turn",
997 status: "rolled_back",
998 countsForRun: true,
999 providerThreadId,
1000 providerTurnId: null,
1001 nativeItemRef: null,
1002 runtimeRequestId: null,
1003 checkpointScopeId: null,
1004 startedAt: now,
1005 completedAt: now,
1006 },
1007 });
1008
1009 const projection = yield* projectionStore.getThreadProjection(threadId);
1010
1011 assert.deepEqual(
1012 projection.runs.map((run) => run.status),
1013 ["rolled_back"],
1014 );
1015 assert.deepEqual(
1016 projection.nodes.map((node) => [node.id, node.status]),
1017 [
1018 [assistantNodeId, "completed"],
1019 [rootNodeId, "rolled_back"],
1020 ],
1021 );
1022 assert.lengthOf(projection.providerTurns, 1);
1023 assert.lengthOf(projection.messages, 2);
1024 assert.lengthOf(projection.turnItems, 2);
1025 assert.lengthOf(projection.visibleTurnItems, 0);
1026 }),
1027 );
1028
1029 it.effect("keeps fork visible items stable after a source run is rolled back", () =>
1030 Effect.gen(function* () {
1031 const projectionStore = yield* ProjectionStoreV2;
1032 const now = yield* DateTime.now;
1033 const projectId = ProjectId.make("project:projection-fork-source-rollback");
1034 const sourceThreadId = ThreadId.make("thread:projection-fork-source-rollback:source");
1035 const targetThreadId = ThreadId.make("thread:projection-fork-source-rollback:target");
1036 const sourceProviderThreadId = ProviderThreadId.make(
1037 "provider-thread:projection-fork-source-rollback:source",
1038 );
1039 const targetProviderThreadId = ProviderThreadId.make(
1040 "provider-thread:projection-fork-source-rollback:target",
1041 );
1042 const sourceRun1Id = RunId.make("run:projection-fork-source-rollback:source:1");
1043 const sourceRun2Id = RunId.make("run:projection-fork-source-rollback:source:2");
1044 const sourceRun1NodeId = NodeId.make("node:projection-fork-source-rollback:source:1");
1045 const sourceRun2NodeId = NodeId.make("node:projection-fork-source-rollback:source:2");
1046
1047 yield* projectionStore.apply({
1048 id: EventId.make("event:projection-fork-source-rollback:source-thread"),
1049 type: "thread.created",
1050 threadId: sourceThreadId,
1051 occurredAt: now,
1052 payload: {
1053 createdBy: "user",
1054 creationSource: "web",
1055 id: sourceThreadId,
1056 projectId,
1057 title: "Projection fork source rollback source",
1058 providerInstanceId,
1059 modelSelection,
1060 runtimeMode: "full-access",
1061 interactionMode: "default",
1062 branch: null,
1063 worktreePath: null,
1064 activeProviderThreadId: sourceProviderThreadId,
1065 lineage: {
1066 parentThreadId: null,
1067 relationshipToParent: null,
1068 rootThreadId: sourceThreadId,
1069 },
1070 forkedFrom: null,
1071 createdAt: now,
1072 updatedAt: now,
1073 archivedAt: null,
1074 settledOverride: null,
1075 settledAt: null,
1076 lastVisitedAt: null,
1077 deletedAt: null,
1078 },
1079 });
1080 yield* projectionStore.apply({
1081 id: EventId.make("event:projection-fork-source-rollback:target-thread"),
1082 type: "thread.created",
1083 threadId: targetThreadId,
1084 occurredAt: now,
1085 payload: {
1086 createdBy: "user",
1087 creationSource: "web",
1088 id: targetThreadId,
1089 projectId,
1090 title: "Projection fork source rollback target",
1091 providerInstanceId,
1092 modelSelection,
1093 runtimeMode: "full-access",
1094 interactionMode: "default",
1095 branch: null,
1096 worktreePath: null,
1097 activeProviderThreadId: targetProviderThreadId,
1098 lineage: {
1099 parentThreadId: sourceThreadId,
1100 relationshipToParent: "fork",
1101 rootThreadId: sourceThreadId,
1102 },
1103 forkedFrom: {
1104 type: "run",
1105 threadId: sourceThreadId,
1106 runId: sourceRun2Id,
1107 },
1108 createdAt: now,
1109 updatedAt: now,
1110 archivedAt: null,
1111 settledOverride: null,
1112 settledAt: null,
1113 lastVisitedAt: null,
1114 deletedAt: null,
1115 },
1116 });
1117
1118 for (const [ordinal, runId, nodeId, promptText, responseText] of [
1119 [1, sourceRun1Id, sourceRun1NodeId, "source one", "one"],
1120 [2, sourceRun2Id, sourceRun2NodeId, "source two", "two"],
1121 ] as const) {
1122 yield* projectionStore.apply({
1123 id: EventId.make(`event:projection-fork-source-rollback:run-${ordinal}`),
1124 type: "run.created",
1125 threadId: sourceThreadId,
1126 runId,
1127 nodeId,
1128 driver,
1129 occurredAt: now,
1130 payload: {
1131 id: runId,
1132 threadId: sourceThreadId,
1133 ordinal,
1134 providerInstanceId,
1135 modelSelection,
1136 providerThreadId: sourceProviderThreadId,
1137 userMessageId: MessageId.make(
1138 `message:projection-fork-source-rollback:user:${ordinal}`,
1139 ),
1140 rootNodeId: nodeId,
1141 activeAttemptId: null,
1142 status: "completed",
1143 requestedAt: now,
1144 startedAt: now,
1145 completedAt: now,
1146 checkpointId: null,
1147 contextHandoffId: null,
1148 },
1149 });
1150 yield* projectionStore.apply({
1151 id: EventId.make(`event:projection-fork-source-rollback:user-item-${ordinal}`),
1152 type: "turn-item.updated",
1153 threadId: sourceThreadId,
1154 runId,
1155 nodeId,
1156 driver,
1157 occurredAt: now,
1158 payload: {
1159 createdBy: "user",
1160 creationSource: "web",
1161 id: TurnItemId.make(`turn-item:projection-fork-source-rollback:user:${ordinal}`),
1162 threadId: sourceThreadId,
1163 runId,
1164 nodeId,
1165 providerThreadId: sourceProviderThreadId,
1166 providerTurnId: null,
1167 nativeItemRef: null,
1168 parentItemId: null,
1169 ordinal: ordinal * 100,
1170 status: "completed",
1171 title: null,
1172 startedAt: now,
1173 completedAt: now,
1174 updatedAt: now,
1175 type: "user_message",
1176 messageId: MessageId.make(`message:projection-fork-source-rollback:user:${ordinal}`),
1177 inputIntent: "turn_start",
1178 text: promptText,
1179 attachments: [],
1180 },
1181 });
1182 yield* projectionStore.apply({
1183 id: EventId.make(`event:projection-fork-source-rollback:assistant-item-${ordinal}`),
1184 type: "turn-item.updated",
1185 threadId: sourceThreadId,
1186 runId,
1187 nodeId,
1188 driver,
1189 occurredAt: now,
1190 payload: {
1191 id: TurnItemId.make(`turn-item:projection-fork-source-rollback:assistant:${ordinal}`),
1192 threadId: sourceThreadId,
1193 runId,
1194 nodeId,
1195 providerThreadId: sourceProviderThreadId,
1196 providerTurnId: null,
1197 nativeItemRef: null,
1198 parentItemId: null,
1199 ordinal: ordinal * 100 + 1,
1200 status: "completed",
1201 title: null,
1202 startedAt: now,
1203 completedAt: now,
1204 updatedAt: now,
1205 type: "assistant_message",
1206 messageId: MessageId.make(
1207 `message:projection-fork-source-rollback:assistant:${ordinal}`,
1208 ),
1209 text: responseText,
1210 streaming: false,
1211 },
1212 });
1213 }
1214
1215 const targetBeforeRollback = yield* projectionStore.getThreadProjection(targetThreadId);
1216 assert.deepEqual(
1217 targetBeforeRollback.visibleTurnItems.map((row) => row.item.type),
1218 ["user_message", "assistant_message", "user_message", "assistant_message", "fork"],
1219 );
1220
1221 yield* projectionStore.apply({
1222 id: EventId.make("event:projection-fork-source-rollback:run-2-rolled-back"),
1223 type: "run.updated",
1224 threadId: sourceThreadId,
1225 runId: sourceRun2Id,
1226 nodeId: sourceRun2NodeId,
1227 driver,
1228 occurredAt: now,
1229 payload: {
1230 id: sourceRun2Id,
1231 threadId: sourceThreadId,
1232 ordinal: 2,
1233 providerInstanceId,
1234 modelSelection,
1235 providerThreadId: sourceProviderThreadId,
1236 userMessageId: MessageId.make("message:projection-fork-source-rollback:user:2"),
1237 rootNodeId: sourceRun2NodeId,
1238 activeAttemptId: null,
1239 status: "rolled_back",
1240 requestedAt: now,
1241 startedAt: now,
1242 completedAt: now,
1243 checkpointId: null,
1244 contextHandoffId: null,
1245 },
1246 });
1247
1248 const targetAfterRollback = yield* projectionStore.getThreadProjection(targetThreadId);
1249 assert.deepEqual(
1250 targetAfterRollback.visibleTurnItems.map((row) => [
1251 row.visibility,
1252 row.item.type,
1253 row.item.type === "user_message" || row.item.type === "assistant_message"
1254 ? row.item.text
1255 : row.item.title,
1256 ]),
1257 [
1258 ["inherited", "user_message", "source one"],
1259 ["inherited", "assistant_message", "one"],
1260 ["inherited", "user_message", "source two"],
1261 ["inherited", "assistant_message", "two"],
1262 ["synthetic", "fork", "Forked from conversation"],
1263 ],
1264 );
1265 }),
1266 );
1267});