Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime";
2import {
3 CheckpointRef,
4 DEFAULT_MODEL_BY_PROVIDER,
5 EnvironmentId,
6 EventId,
7 MessageId,
8 ProjectId,
9 ThreadId,
10 TurnId,
11 type OrchestrationEvent,
12 type OrchestrationReadModel,
13} from "@t3tools/contracts";
14import { describe, expect, it } from "vitest";
15
16import {
17 applyOrchestrationEvent,
18 applyOrchestrationEvents,
19 selectEnvironmentState,
20 selectProjectsAcrossEnvironments,
21 selectThreadByRef,
22 selectThreadExistsByRef,
23 setThreadBranch,
24 selectThreadsAcrossEnvironments,
25 syncServerReadModel,
26 type AppState,
27 type EnvironmentState,
28} from "./store";
29import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
30
31const localEnvironmentId = EnvironmentId.make("environment-local");
32const remoteEnvironmentId = EnvironmentId.make("environment-remote");
33
34function withActiveEnvironmentState(
35 environmentState: EnvironmentState,
36 overrides: Partial<AppState & EnvironmentState> = {},
37): AppState {
38 const {
39 activeEnvironmentId: overrideActiveEnvironmentId,
40 environmentStateById: overrideEnvironmentStateById,
41 ...environmentOverrides
42 } = overrides;
43 const activeEnvironmentId = overrideActiveEnvironmentId ?? localEnvironmentId;
44 const mergedEnvironmentState = {
45 ...environmentState,
46 ...environmentOverrides,
47 };
48 const environmentStateById =
49 overrideEnvironmentStateById ??
50 (activeEnvironmentId
51 ? {
52 [activeEnvironmentId]: mergedEnvironmentState,
53 }
54 : {});
55
56 return {
57 activeEnvironmentId,
58 environmentStateById,
59 };
60}
61
62function makeThread(overrides: Partial<Thread> = {}): Thread {
63 return {
64 id: ThreadId.make("thread-1"),
65 environmentId: localEnvironmentId,
66 codexThreadId: null,
67 projectId: ProjectId.make("project-1"),
68 title: "Thread",
69 modelSelection: {
70 provider: "codex",
71 model: "gpt-5-codex",
72 },
73 runtimeMode: DEFAULT_RUNTIME_MODE,
74 interactionMode: DEFAULT_INTERACTION_MODE,
75 session: null,
76 messages: [],
77 turnDiffSummaries: [],
78 activities: [],
79 proposedPlans: [],
80 error: null,
81 createdAt: "2026-02-13T00:00:00.000Z",
82 archivedAt: null,
83 latestTurn: null,
84 branch: null,
85 worktreePath: null,
86 ...overrides,
87 };
88}
89
90function makeState(thread: Thread): AppState {
91 const projectId = ProjectId.make("project-1");
92 const project = {
93 id: projectId,
94 environmentId: thread.environmentId,
95 name: "Project",
96 cwd: "/tmp/project",
97 defaultModelSelection: {
98 provider: "codex" as const,
99 model: "gpt-5-codex",
100 },
101 createdAt: "2026-02-13T00:00:00.000Z",
102 updatedAt: "2026-02-13T00:00:00.000Z",
103 scripts: [],
104 };
105 const threadIdsByProjectId: EnvironmentState["threadIdsByProjectId"] = {
106 [thread.projectId]: [thread.id],
107 };
108 const environmentState = {
109 projectIds: [projectId],
110 projectById: {
111 [projectId]: project,
112 },
113 threadIds: [thread.id],
114 threadIdsByProjectId,
115 threadShellById: {
116 [thread.id]: {
117 id: thread.id,
118 environmentId: thread.environmentId,
119 codexThreadId: thread.codexThreadId,
120 projectId: thread.projectId,
121 title: thread.title,
122 modelSelection: thread.modelSelection,
123 runtimeMode: thread.runtimeMode,
124 interactionMode: thread.interactionMode,
125 error: thread.error,
126 createdAt: thread.createdAt,
127 archivedAt: thread.archivedAt,
128 updatedAt: thread.updatedAt,
129 branch: thread.branch,
130 worktreePath: thread.worktreePath,
131 },
132 },
133 threadSessionById: {
134 [thread.id]: thread.session,
135 },
136 threadTurnStateById: {
137 [thread.id]: {
138 latestTurn: thread.latestTurn,
139 ...(thread.pendingSourceProposedPlan
140 ? { pendingSourceProposedPlan: thread.pendingSourceProposedPlan }
141 : {}),
142 },
143 },
144 messageIdsByThreadId: {
145 [thread.id]: thread.messages.map((message) => message.id),
146 },
147 messageByThreadId: {
148 [thread.id]: Object.fromEntries(
149 thread.messages.map((message) => [message.id, message] as const),
150 ) as EnvironmentState["messageByThreadId"][ThreadId],
151 },
152 activityIdsByThreadId: {
153 [thread.id]: thread.activities.map((activity) => activity.id),
154 },
155 activityByThreadId: {
156 [thread.id]: Object.fromEntries(
157 thread.activities.map((activity) => [activity.id, activity] as const),
158 ) as EnvironmentState["activityByThreadId"][ThreadId],
159 },
160 proposedPlanIdsByThreadId: {
161 [thread.id]: thread.proposedPlans.map((plan) => plan.id),
162 },
163 proposedPlanByThreadId: {
164 [thread.id]: Object.fromEntries(
165 thread.proposedPlans.map((plan) => [plan.id, plan] as const),
166 ) as EnvironmentState["proposedPlanByThreadId"][ThreadId],
167 },
168 turnDiffIdsByThreadId: {
169 [thread.id]: thread.turnDiffSummaries.map((summary) => summary.turnId),
170 },
171 turnDiffSummaryByThreadId: {
172 [thread.id]: Object.fromEntries(
173 thread.turnDiffSummaries.map((summary) => [summary.turnId, summary] as const),
174 ) as EnvironmentState["turnDiffSummaryByThreadId"][ThreadId],
175 },
176 sidebarThreadSummaryById: {},
177 bootstrapComplete: true,
178 };
179 return withActiveEnvironmentState(environmentState, {
180 activeEnvironmentId: thread.environmentId,
181 });
182}
183
184function makeEmptyState(overrides: Partial<AppState & EnvironmentState> = {}): AppState {
185 const environmentState: EnvironmentState = {
186 projectIds: [],
187 projectById: {},
188 threadIds: [],
189 threadIdsByProjectId: {},
190 threadShellById: {},
191 threadSessionById: {},
192 threadTurnStateById: {},
193 messageIdsByThreadId: {},
194 messageByThreadId: {},
195 activityIdsByThreadId: {},
196 activityByThreadId: {},
197 proposedPlanIdsByThreadId: {},
198 proposedPlanByThreadId: {},
199 turnDiffIdsByThreadId: {},
200 turnDiffSummaryByThreadId: {},
201 sidebarThreadSummaryById: {},
202 bootstrapComplete: true,
203 };
204 return withActiveEnvironmentState(environmentState, overrides);
205}
206
207function localEnvironmentStateOf(state: AppState): EnvironmentState {
208 return selectEnvironmentState(state, localEnvironmentId);
209}
210
211function environmentStateOf(state: AppState, environmentId: EnvironmentId): EnvironmentState {
212 return selectEnvironmentState(state, environmentId);
213}
214
215function projectsOf(state: AppState) {
216 return selectProjectsAcrossEnvironments(state);
217}
218
219function threadsOf(state: AppState) {
220 return selectThreadsAcrossEnvironments(state);
221}
222
223function makeEvent<T extends OrchestrationEvent["type"]>(
224 type: T,
225 payload: Extract<OrchestrationEvent, { type: T }>["payload"],
226 overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
227): Extract<OrchestrationEvent, { type: T }> {
228 const sequence = overrides.sequence ?? 1;
229 return {
230 sequence,
231 eventId: EventId.make(`event-${sequence}`),
232 aggregateKind: "thread",
233 aggregateId:
234 "threadId" in payload
235 ? payload.threadId
236 : "projectId" in payload
237 ? payload.projectId
238 : ProjectId.make("project-1"),
239 occurredAt: "2026-02-27T00:00:00.000Z",
240 commandId: null,
241 causationEventId: null,
242 correlationId: null,
243 metadata: {},
244 type,
245 payload,
246 ...overrides,
247 } as Extract<OrchestrationEvent, { type: T }>;
248}
249
250describe("thread selection memoization", () => {
251 it("returns stable thread references for repeated reads of the same state", () => {
252 const thread = makeThread({
253 messages: [
254 {
255 id: MessageId.make("message-1"),
256 role: "user",
257 text: "hello",
258 createdAt: "2026-02-13T00:01:00.000Z",
259 streaming: false,
260 },
261 ],
262 activities: [
263 {
264 id: EventId.make("activity-1"),
265 tone: "info",
266 kind: "step",
267 summary: "working",
268 payload: {},
269 turnId: TurnId.make("turn-1"),
270 createdAt: "2026-02-13T00:01:30.000Z",
271 },
272 ],
273 proposedPlans: [
274 {
275 id: "plan-1",
276 turnId: null,
277 planMarkdown: "plan",
278 implementedAt: null,
279 implementationThreadId: null,
280 createdAt: "2026-02-13T00:02:00.000Z",
281 updatedAt: "2026-02-13T00:02:00.000Z",
282 },
283 ],
284 turnDiffSummaries: [
285 {
286 turnId: TurnId.make("turn-1"),
287 completedAt: "2026-02-13T00:03:00.000Z",
288 files: [],
289 },
290 ],
291 });
292 const state = makeState(thread);
293 const ref = scopeThreadRef(thread.environmentId, thread.id);
294
295 const first = selectThreadByRef(state, ref);
296 const second = selectThreadByRef(state, ref);
297
298 expect(first).toBeDefined();
299 expect(second).toBe(first);
300 expect(second?.messages).toBe(first?.messages);
301 expect(second?.activities).toBe(first?.activities);
302 expect(second?.proposedPlans).toBe(first?.proposedPlans);
303 expect(second?.turnDiffSummaries).toBe(first?.turnDiffSummaries);
304 });
305
306 it("reuses the derived thread when the app state wrapper changes but thread data does not", () => {
307 const thread = makeThread({
308 messages: [
309 {
310 id: MessageId.make("message-1"),
311 role: "assistant",
312 text: "done",
313 createdAt: "2026-02-13T00:01:00.000Z",
314 streaming: false,
315 },
316 ],
317 });
318 const state = makeState(thread);
319 const ref = scopeThreadRef(thread.environmentId, thread.id);
320 const wrappedState: AppState = {
321 ...state,
322 environmentStateById: { ...state.environmentStateById },
323 };
324
325 const first = selectThreadByRef(state, ref);
326 const second = selectThreadByRef(wrappedState, ref);
327
328 expect(second).toBe(first);
329 });
330
331 it("updates the derived thread when the underlying thread data changes", () => {
332 const thread = makeThread();
333 const ref = scopeThreadRef(thread.environmentId, thread.id);
334 const firstState = makeState(thread);
335 const secondState = makeState({
336 ...thread,
337 messages: [
338 {
339 id: MessageId.make("message-2"),
340 role: "user",
341 text: "new",
342 createdAt: "2026-02-13T00:04:00.000Z",
343 streaming: false,
344 },
345 ],
346 });
347
348 const first = selectThreadByRef(firstState, ref);
349 const second = selectThreadByRef(secondState, ref);
350
351 expect(second).not.toBe(first);
352 expect(second?.messages).toHaveLength(1);
353 expect(second?.messages[0]?.text).toBe("new");
354 });
355
356 it("checks thread existence without materializing the full thread", () => {
357 const thread = makeThread();
358 const state = makeState(thread);
359 const ref = scopeThreadRef(thread.environmentId, thread.id);
360
361 expect(selectThreadExistsByRef(state, ref)).toBe(true);
362 expect(
363 selectThreadExistsByRef(
364 state,
365 scopeThreadRef(thread.environmentId, ThreadId.make("missing")),
366 ),
367 ).toBe(false);
368 expect(selectThreadExistsByRef(state, null)).toBe(false);
369 });
370});
371
372function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"][number]>) {
373 return {
374 id: ThreadId.make("thread-1"),
375 projectId: ProjectId.make("project-1"),
376 title: "Thread",
377 modelSelection: {
378 provider: "codex",
379 model: "gpt-5.3-codex",
380 },
381 runtimeMode: DEFAULT_RUNTIME_MODE,
382 interactionMode: DEFAULT_INTERACTION_MODE,
383 branch: null,
384 worktreePath: null,
385 latestTurn: null,
386 createdAt: "2026-02-27T00:00:00.000Z",
387 updatedAt: "2026-02-27T00:00:00.000Z",
388 archivedAt: null,
389 deletedAt: null,
390 messages: [],
391 activities: [],
392 proposedPlans: [],
393 checkpoints: [],
394 session: null,
395 ...overrides,
396 } satisfies OrchestrationReadModel["threads"][number];
397}
398
399function makeReadModel(thread: OrchestrationReadModel["threads"][number]): OrchestrationReadModel {
400 return {
401 snapshotSequence: 1,
402 updatedAt: "2026-02-27T00:00:00.000Z",
403 projects: [
404 {
405 id: ProjectId.make("project-1"),
406 title: "Project",
407 workspaceRoot: "/tmp/project",
408 defaultModelSelection: {
409 provider: "codex",
410 model: "gpt-5.3-codex",
411 },
412 createdAt: "2026-02-27T00:00:00.000Z",
413 updatedAt: "2026-02-27T00:00:00.000Z",
414 deletedAt: null,
415 scripts: [],
416 },
417 ],
418 threads: [thread],
419 };
420}
421
422function makeReadModelProject(
423 overrides: Partial<OrchestrationReadModel["projects"][number]>,
424): OrchestrationReadModel["projects"][number] {
425 return {
426 id: ProjectId.make("project-1"),
427 title: "Project",
428 workspaceRoot: "/tmp/project",
429 defaultModelSelection: {
430 provider: "codex",
431 model: "gpt-5.3-codex",
432 },
433 createdAt: "2026-02-27T00:00:00.000Z",
434 updatedAt: "2026-02-27T00:00:00.000Z",
435 deletedAt: null,
436 scripts: [],
437 ...overrides,
438 };
439}
440
441describe("setThreadBranch", () => {
442 it("updates only the scoped thread environment", () => {
443 const sharedThreadId = ThreadId.make("thread-shared");
444 const localThread = makeThread({
445 id: sharedThreadId,
446 environmentId: localEnvironmentId,
447 branch: "local-branch",
448 });
449 const remoteThread = makeThread({
450 id: sharedThreadId,
451 environmentId: remoteEnvironmentId,
452 branch: "remote-branch",
453 });
454 const state: AppState = {
455 activeEnvironmentId: localEnvironmentId,
456 environmentStateById: {
457 [localEnvironmentId]: environmentStateOf(makeState(localThread), localEnvironmentId),
458 [remoteEnvironmentId]: environmentStateOf(makeState(remoteThread), remoteEnvironmentId),
459 },
460 };
461
462 const next = setThreadBranch(
463 state,
464 scopeThreadRef(remoteEnvironmentId, sharedThreadId),
465 "remote-next",
466 "/tmp/remote-worktree",
467 );
468
469 expect(
470 environmentStateOf(next, localEnvironmentId).threadShellById[sharedThreadId]?.branch,
471 ).toBe("local-branch");
472 expect(
473 environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.branch,
474 ).toBe("remote-next");
475 expect(
476 environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.worktreePath,
477 ).toBe("/tmp/remote-worktree");
478 });
479});
480
481describe("store read model sync", () => {
482 it("marks bootstrap complete after snapshot sync", () => {
483 const initialState = withActiveEnvironmentState(
484 localEnvironmentStateOf(makeState(makeThread())),
485 {
486 bootstrapComplete: false,
487 },
488 );
489
490 const next = syncServerReadModel(
491 initialState,
492 makeReadModel(makeReadModelThread({})),
493 localEnvironmentId,
494 );
495
496 expect(localEnvironmentStateOf(next).bootstrapComplete).toBe(true);
497 });
498
499 it("preserves claude model slugs without an active session", () => {
500 const initialState = makeState(makeThread());
501 const readModel = makeReadModel(
502 makeReadModelThread({
503 modelSelection: {
504 provider: "claudeAgent",
505 model: "claude-opus-4-6",
506 },
507 }),
508 );
509
510 const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
511
512 expect(threadsOf(next)[0]?.modelSelection.model).toBe("claude-opus-4-6");
513 });
514
515 it("resolves claude aliases when session provider is claudeAgent", () => {
516 const initialState = makeState(makeThread());
517 const readModel = makeReadModel(
518 makeReadModelThread({
519 modelSelection: {
520 provider: "claudeAgent",
521 model: "sonnet",
522 },
523 session: {
524 threadId: ThreadId.make("thread-1"),
525 status: "ready",
526 providerName: "claudeAgent",
527 runtimeMode: "approval-required",
528 activeTurnId: null,
529 lastError: null,
530 updatedAt: "2026-02-27T00:00:00.000Z",
531 },
532 }),
533 );
534
535 const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
536
537 expect(threadsOf(next)[0]?.modelSelection.model).toBe("claude-sonnet-4-6");
538 });
539
540 it("preserves project and thread updatedAt timestamps from the read model", () => {
541 const initialState = makeState(makeThread());
542 const readModel = makeReadModel(
543 makeReadModelThread({
544 updatedAt: "2026-02-27T00:05:00.000Z",
545 }),
546 );
547
548 const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
549
550 expect(projectsOf(next)[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");
551 expect(threadsOf(next)[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
552 });
553
554 it("maps archivedAt from the read model", () => {
555 const initialState = makeState(makeThread());
556 const archivedAt = "2026-02-28T00:00:00.000Z";
557 const next = syncServerReadModel(
558 initialState,
559 makeReadModel(
560 makeReadModelThread({
561 archivedAt,
562 }),
563 ),
564 localEnvironmentId,
565 );
566
567 expect(threadsOf(next)[0]?.archivedAt).toBe(archivedAt);
568 });
569
570 it("replaces projects using snapshot order during recovery", () => {
571 const project1 = ProjectId.make("project-1");
572 const project2 = ProjectId.make("project-2");
573 const project3 = ProjectId.make("project-3");
574 const initialState: AppState = makeEmptyState({
575 projectIds: [project2, project1],
576 projectById: {
577 [project2]: {
578 id: project2,
579 environmentId: localEnvironmentId,
580 name: "Project 2",
581 cwd: "/tmp/project-2",
582 defaultModelSelection: {
583 provider: "codex",
584 model: DEFAULT_MODEL_BY_PROVIDER.codex,
585 },
586 createdAt: "2026-02-27T00:00:00.000Z",
587 updatedAt: "2026-02-27T00:00:00.000Z",
588 scripts: [],
589 },
590 [project1]: {
591 id: project1,
592 environmentId: localEnvironmentId,
593 name: "Project 1",
594 cwd: "/tmp/project-1",
595 defaultModelSelection: {
596 provider: "codex",
597 model: DEFAULT_MODEL_BY_PROVIDER.codex,
598 },
599 createdAt: "2026-02-27T00:00:00.000Z",
600 updatedAt: "2026-02-27T00:00:00.000Z",
601 scripts: [],
602 },
603 },
604 });
605 const readModel: OrchestrationReadModel = {
606 snapshotSequence: 2,
607 updatedAt: "2026-02-27T00:00:00.000Z",
608 projects: [
609 makeReadModelProject({
610 id: project1,
611 title: "Project 1",
612 workspaceRoot: "/tmp/project-1",
613 }),
614 makeReadModelProject({
615 id: project2,
616 title: "Project 2",
617 workspaceRoot: "/tmp/project-2",
618 }),
619 makeReadModelProject({
620 id: project3,
621 title: "Project 3",
622 workspaceRoot: "/tmp/project-3",
623 }),
624 ],
625 threads: [],
626 };
627
628 const next = syncServerReadModel(initialState, readModel, localEnvironmentId);
629
630 expect(projectsOf(next).map((project) => project.id)).toEqual([project1, project2, project3]);
631 });
632});
633
634describe("incremental orchestration updates", () => {
635 it("does not mark bootstrap complete for incremental events", () => {
636 const state = withActiveEnvironmentState(localEnvironmentStateOf(makeState(makeThread())), {
637 bootstrapComplete: false,
638 });
639
640 const next = applyOrchestrationEvent(
641 state,
642 makeEvent("thread.meta-updated", {
643 threadId: ThreadId.make("thread-1"),
644 title: "Updated title",
645 updatedAt: "2026-02-27T00:00:01.000Z",
646 }),
647 localEnvironmentId,
648 );
649
650 expect(localEnvironmentStateOf(next).bootstrapComplete).toBe(false);
651 });
652
653 it("preserves state identity for no-op project and thread deletes", () => {
654 const thread = makeThread();
655 const state = makeState(thread);
656
657 const nextAfterProjectDelete = applyOrchestrationEvent(
658 state,
659 makeEvent("project.deleted", {
660 projectId: ProjectId.make("project-missing"),
661 deletedAt: "2026-02-27T00:00:01.000Z",
662 }),
663 localEnvironmentId,
664 );
665 const nextAfterThreadDelete = applyOrchestrationEvent(
666 state,
667 makeEvent("thread.deleted", {
668 threadId: ThreadId.make("thread-missing"),
669 deletedAt: "2026-02-27T00:00:01.000Z",
670 }),
671 localEnvironmentId,
672 );
673
674 expect(nextAfterProjectDelete).toBe(state);
675 expect(nextAfterThreadDelete).toBe(state);
676 });
677
678 it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
679 const originalProjectId = ProjectId.make("project-1");
680 const recreatedProjectId = ProjectId.make("project-2");
681 const state: AppState = makeEmptyState({
682 projectIds: [originalProjectId],
683 projectById: {
684 [originalProjectId]: {
685 id: originalProjectId,
686 environmentId: localEnvironmentId,
687 name: "Project",
688 cwd: "/tmp/project",
689 defaultModelSelection: {
690 provider: "codex",
691 model: DEFAULT_MODEL_BY_PROVIDER.codex,
692 },
693 createdAt: "2026-02-27T00:00:00.000Z",
694 updatedAt: "2026-02-27T00:00:00.000Z",
695 scripts: [],
696 },
697 },
698 });
699
700 const next = applyOrchestrationEvent(
701 state,
702 makeEvent("project.created", {
703 projectId: recreatedProjectId,
704 title: "Project Recreated",
705 workspaceRoot: "/tmp/project",
706 defaultModelSelection: {
707 provider: "codex",
708 model: DEFAULT_MODEL_BY_PROVIDER.codex,
709 },
710 scripts: [],
711 createdAt: "2026-02-27T00:00:01.000Z",
712 updatedAt: "2026-02-27T00:00:01.000Z",
713 }),
714 localEnvironmentId,
715 );
716
717 expect(projectsOf(next)).toHaveLength(1);
718 expect(projectsOf(next)[0]?.id).toBe(recreatedProjectId);
719 expect(projectsOf(next)[0]?.cwd).toBe("/tmp/project");
720 expect(projectsOf(next)[0]?.name).toBe("Project Recreated");
721 expect(localEnvironmentStateOf(next).projectIds).toEqual([recreatedProjectId]);
722 expect(localEnvironmentStateOf(next).projectById[originalProjectId]).toBeUndefined();
723 expect(localEnvironmentStateOf(next).projectById[recreatedProjectId]?.id).toBe(
724 recreatedProjectId,
725 );
726 });
727
728 it("removes stale project index entries when thread.created recreates a thread under a new project", () => {
729 const originalProjectId = ProjectId.make("project-1");
730 const recreatedProjectId = ProjectId.make("project-2");
731 const threadId = ThreadId.make("thread-1");
732 const thread = makeThread({
733 id: threadId,
734 projectId: originalProjectId,
735 });
736 const state = withActiveEnvironmentState(localEnvironmentStateOf(makeState(thread)), {
737 projectIds: [originalProjectId, recreatedProjectId],
738 projectById: {
739 [originalProjectId]: {
740 id: originalProjectId,
741 environmentId: localEnvironmentId,
742 name: "Project 1",
743 cwd: "/tmp/project-1",
744 defaultModelSelection: {
745 provider: "codex",
746 model: DEFAULT_MODEL_BY_PROVIDER.codex,
747 },
748 createdAt: "2026-02-27T00:00:00.000Z",
749 updatedAt: "2026-02-27T00:00:00.000Z",
750 scripts: [],
751 },
752 [recreatedProjectId]: {
753 id: recreatedProjectId,
754 environmentId: localEnvironmentId,
755 name: "Project 2",
756 cwd: "/tmp/project-2",
757 defaultModelSelection: {
758 provider: "codex",
759 model: DEFAULT_MODEL_BY_PROVIDER.codex,
760 },
761 createdAt: "2026-02-27T00:00:00.000Z",
762 updatedAt: "2026-02-27T00:00:00.000Z",
763 scripts: [],
764 },
765 },
766 });
767
768 const next = applyOrchestrationEvent(
769 state,
770 makeEvent("thread.created", {
771 threadId,
772 projectId: recreatedProjectId,
773 title: "Recovered thread",
774 modelSelection: {
775 provider: "codex",
776 model: DEFAULT_MODEL_BY_PROVIDER.codex,
777 },
778 runtimeMode: DEFAULT_RUNTIME_MODE,
779 interactionMode: DEFAULT_INTERACTION_MODE,
780 branch: null,
781 worktreePath: null,
782 createdAt: "2026-02-27T00:00:01.000Z",
783 updatedAt: "2026-02-27T00:00:01.000Z",
784 }),
785 localEnvironmentId,
786 );
787
788 expect(threadsOf(next)).toHaveLength(1);
789 expect(threadsOf(next)[0]?.projectId).toBe(recreatedProjectId);
790 expect(localEnvironmentStateOf(next).threadIdsByProjectId[originalProjectId]).toBeUndefined();
791 expect(localEnvironmentStateOf(next).threadIdsByProjectId[recreatedProjectId]).toEqual([
792 threadId,
793 ]);
794 });
795
796 it("updates only the affected thread for message events", () => {
797 const thread1 = makeThread({
798 id: ThreadId.make("thread-1"),
799 messages: [
800 {
801 id: MessageId.make("message-1"),
802 role: "assistant",
803 text: "hello",
804 turnId: TurnId.make("turn-1"),
805 createdAt: "2026-02-27T00:00:00.000Z",
806 completedAt: "2026-02-27T00:00:00.000Z",
807 streaming: false,
808 },
809 ],
810 });
811 const thread2 = makeThread({ id: ThreadId.make("thread-2") });
812 const baseState = makeState(thread1);
813 const baseEnvironmentState = localEnvironmentStateOf(baseState);
814 const state = withActiveEnvironmentState(baseEnvironmentState, {
815 threadIds: [thread1.id, thread2.id],
816 threadShellById: {
817 ...baseEnvironmentState.threadShellById,
818 [thread2.id]: {
819 id: thread2.id,
820 environmentId: thread2.environmentId,
821 codexThreadId: thread2.codexThreadId,
822 projectId: thread2.projectId,
823 title: thread2.title,
824 modelSelection: thread2.modelSelection,
825 runtimeMode: thread2.runtimeMode,
826 interactionMode: thread2.interactionMode,
827 error: thread2.error,
828 createdAt: thread2.createdAt,
829 archivedAt: thread2.archivedAt,
830 updatedAt: thread2.updatedAt,
831 branch: thread2.branch,
832 worktreePath: thread2.worktreePath,
833 },
834 },
835 threadSessionById: {
836 ...baseEnvironmentState.threadSessionById,
837 [thread2.id]: thread2.session,
838 },
839 threadTurnStateById: {
840 ...baseEnvironmentState.threadTurnStateById,
841 [thread2.id]: {
842 latestTurn: thread2.latestTurn,
843 },
844 },
845 messageIdsByThreadId: {
846 ...baseEnvironmentState.messageIdsByThreadId,
847 [thread2.id]: [],
848 },
849 messageByThreadId: {
850 ...baseEnvironmentState.messageByThreadId,
851 [thread2.id]: {},
852 },
853 activityIdsByThreadId: {
854 ...baseEnvironmentState.activityIdsByThreadId,
855 [thread2.id]: [],
856 },
857 activityByThreadId: {
858 ...baseEnvironmentState.activityByThreadId,
859 [thread2.id]: {},
860 },
861 proposedPlanIdsByThreadId: {
862 ...baseEnvironmentState.proposedPlanIdsByThreadId,
863 [thread2.id]: [],
864 },
865 proposedPlanByThreadId: {
866 ...baseEnvironmentState.proposedPlanByThreadId,
867 [thread2.id]: {},
868 },
869 turnDiffIdsByThreadId: {
870 ...baseEnvironmentState.turnDiffIdsByThreadId,
871 [thread2.id]: [],
872 },
873 turnDiffSummaryByThreadId: {
874 ...baseEnvironmentState.turnDiffSummaryByThreadId,
875 [thread2.id]: {},
876 },
877 sidebarThreadSummaryById: {
878 ...baseEnvironmentState.sidebarThreadSummaryById,
879 },
880 threadIdsByProjectId: {
881 [thread1.projectId]: [thread1.id, thread2.id],
882 },
883 });
884
885 const next = applyOrchestrationEvent(
886 state,
887 makeEvent("thread.message-sent", {
888 threadId: thread1.id,
889 messageId: MessageId.make("message-1"),
890 role: "assistant",
891 text: " world",
892 turnId: TurnId.make("turn-1"),
893 streaming: true,
894 createdAt: "2026-02-27T00:00:01.000Z",
895 updatedAt: "2026-02-27T00:00:01.000Z",
896 }),
897 localEnvironmentId,
898 );
899
900 expect(threadsOf(next)[0]?.messages[0]?.text).toBe("hello world");
901 expect(threadsOf(next)[0]?.latestTurn?.state).toBe("running");
902 const nextEnvironmentState = next.environmentStateById[localEnvironmentId];
903 const previousEnvironmentState = state.environmentStateById[localEnvironmentId];
904 expect(nextEnvironmentState?.threadShellById[thread2.id]).toBe(
905 previousEnvironmentState?.threadShellById[thread2.id],
906 );
907 expect(nextEnvironmentState?.threadSessionById[thread2.id]).toBe(
908 previousEnvironmentState?.threadSessionById[thread2.id],
909 );
910 expect(nextEnvironmentState?.messageIdsByThreadId[thread2.id]).toBe(
911 previousEnvironmentState?.messageIdsByThreadId[thread2.id],
912 );
913 expect(nextEnvironmentState?.messageByThreadId[thread2.id]).toBe(
914 previousEnvironmentState?.messageByThreadId[thread2.id],
915 );
916 });
917
918 it("applies replay batches in sequence and updates session state", () => {
919 const thread = makeThread({
920 latestTurn: {
921 turnId: TurnId.make("turn-1"),
922 state: "running",
923 requestedAt: "2026-02-27T00:00:00.000Z",
924 startedAt: "2026-02-27T00:00:00.000Z",
925 completedAt: null,
926 assistantMessageId: null,
927 },
928 });
929 const state = makeState(thread);
930
931 const next = applyOrchestrationEvents(
932 state,
933 [
934 makeEvent(
935 "thread.session-set",
936 {
937 threadId: thread.id,
938 session: {
939 threadId: thread.id,
940 status: "running",
941 providerName: "codex",
942 runtimeMode: "full-access",
943 activeTurnId: TurnId.make("turn-1"),
944 lastError: null,
945 updatedAt: "2026-02-27T00:00:02.000Z",
946 },
947 },
948 { sequence: 2 },
949 ),
950 makeEvent(
951 "thread.message-sent",
952 {
953 threadId: thread.id,
954 messageId: MessageId.make("assistant-1"),
955 role: "assistant",
956 text: "done",
957 turnId: TurnId.make("turn-1"),
958 streaming: false,
959 createdAt: "2026-02-27T00:00:03.000Z",
960 updatedAt: "2026-02-27T00:00:03.000Z",
961 },
962 { sequence: 3 },
963 ),
964 ],
965 localEnvironmentId,
966 );
967
968 expect(threadsOf(next)[0]?.session?.status).toBe("running");
969 expect(threadsOf(next)[0]?.latestTurn?.state).toBe("completed");
970 expect(threadsOf(next)[0]?.messages).toHaveLength(1);
971 });
972
973 it("does not regress latestTurn when an older turn diff completes late", () => {
974 const state = makeState(
975 makeThread({
976 latestTurn: {
977 turnId: TurnId.make("turn-2"),
978 state: "running",
979 requestedAt: "2026-02-27T00:00:02.000Z",
980 startedAt: "2026-02-27T00:00:03.000Z",
981 completedAt: null,
982 assistantMessageId: null,
983 },
984 }),
985 );
986
987 const next = applyOrchestrationEvent(
988 state,
989 makeEvent("thread.turn-diff-completed", {
990 threadId: ThreadId.make("thread-1"),
991 turnId: TurnId.make("turn-1"),
992 checkpointTurnCount: 1,
993 checkpointRef: CheckpointRef.make("checkpoint-1"),
994 status: "ready",
995 files: [],
996 assistantMessageId: MessageId.make("assistant-1"),
997 completedAt: "2026-02-27T00:00:04.000Z",
998 }),
999 localEnvironmentId,
1000 );
1001
1002 expect(threadsOf(next)[0]?.turnDiffSummaries).toHaveLength(1);
1003 expect(threadsOf(next)[0]?.latestTurn).toEqual(threadsOf(state)[0]?.latestTurn);
1004 });
1005
1006 it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
1007 const turnId = TurnId.make("turn-1");
1008 const state = makeState(
1009 makeThread({
1010 latestTurn: {
1011 turnId,
1012 state: "completed",
1013 requestedAt: "2026-02-27T00:00:00.000Z",
1014 startedAt: "2026-02-27T00:00:00.000Z",
1015 completedAt: "2026-02-27T00:00:02.000Z",
1016 assistantMessageId: MessageId.make("assistant:turn-1"),
1017 },
1018 turnDiffSummaries: [
1019 {
1020 turnId,
1021 completedAt: "2026-02-27T00:00:02.000Z",
1022 status: "ready",
1023 checkpointTurnCount: 1,
1024 checkpointRef: CheckpointRef.make("checkpoint-1"),
1025 assistantMessageId: MessageId.make("assistant:turn-1"),
1026 files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
1027 },
1028 ],
1029 }),
1030 );
1031
1032 const next = applyOrchestrationEvent(
1033 state,
1034 makeEvent("thread.message-sent", {
1035 threadId: ThreadId.make("thread-1"),
1036 messageId: MessageId.make("assistant-real"),
1037 role: "assistant",
1038 text: "final answer",
1039 turnId,
1040 streaming: false,
1041 createdAt: "2026-02-27T00:00:03.000Z",
1042 updatedAt: "2026-02-27T00:00:03.000Z",
1043 }),
1044 localEnvironmentId,
1045 );
1046
1047 expect(threadsOf(next)[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
1048 MessageId.make("assistant-real"),
1049 );
1050 expect(threadsOf(next)[0]?.latestTurn?.assistantMessageId).toBe(
1051 MessageId.make("assistant-real"),
1052 );
1053 });
1054
1055 it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
1056 const state = makeState(
1057 makeThread({
1058 messages: [
1059 {
1060 id: MessageId.make("user-1"),
1061 role: "user",
1062 text: "first",
1063 turnId: TurnId.make("turn-1"),
1064 createdAt: "2026-02-27T00:00:00.000Z",
1065 completedAt: "2026-02-27T00:00:00.000Z",
1066 streaming: false,
1067 },
1068 {
1069 id: MessageId.make("assistant-1"),
1070 role: "assistant",
1071 text: "first reply",
1072 turnId: TurnId.make("turn-1"),
1073 createdAt: "2026-02-27T00:00:01.000Z",
1074 completedAt: "2026-02-27T00:00:01.000Z",
1075 streaming: false,
1076 },
1077 {
1078 id: MessageId.make("user-2"),
1079 role: "user",
1080 text: "second",
1081 turnId: TurnId.make("turn-2"),
1082 createdAt: "2026-02-27T00:00:02.000Z",
1083 completedAt: "2026-02-27T00:00:02.000Z",
1084 streaming: false,
1085 },
1086 ],
1087 proposedPlans: [
1088 {
1089 id: "plan-1",
1090 turnId: TurnId.make("turn-1"),
1091 planMarkdown: "plan 1",
1092 implementedAt: null,
1093 implementationThreadId: null,
1094 createdAt: "2026-02-27T00:00:00.000Z",
1095 updatedAt: "2026-02-27T00:00:00.000Z",
1096 },
1097 {
1098 id: "plan-2",
1099 turnId: TurnId.make("turn-2"),
1100 planMarkdown: "plan 2",
1101 implementedAt: null,
1102 implementationThreadId: null,
1103 createdAt: "2026-02-27T00:00:02.000Z",
1104 updatedAt: "2026-02-27T00:00:02.000Z",
1105 },
1106 ],
1107 activities: [
1108 {
1109 id: EventId.make("activity-1"),
1110 tone: "info",
1111 kind: "step",
1112 summary: "one",
1113 payload: {},
1114 turnId: TurnId.make("turn-1"),
1115 createdAt: "2026-02-27T00:00:00.000Z",
1116 },
1117 {
1118 id: EventId.make("activity-2"),
1119 tone: "info",
1120 kind: "step",
1121 summary: "two",
1122 payload: {},
1123 turnId: TurnId.make("turn-2"),
1124 createdAt: "2026-02-27T00:00:02.000Z",
1125 },
1126 ],
1127 turnDiffSummaries: [
1128 {
1129 turnId: TurnId.make("turn-1"),
1130 completedAt: "2026-02-27T00:00:01.000Z",
1131 status: "ready",
1132 checkpointTurnCount: 1,
1133 checkpointRef: CheckpointRef.make("ref-1"),
1134 files: [],
1135 },
1136 {
1137 turnId: TurnId.make("turn-2"),
1138 completedAt: "2026-02-27T00:00:03.000Z",
1139 status: "ready",
1140 checkpointTurnCount: 2,
1141 checkpointRef: CheckpointRef.make("ref-2"),
1142 files: [],
1143 },
1144 ],
1145 }),
1146 );
1147
1148 const next = applyOrchestrationEvent(
1149 state,
1150 makeEvent("thread.reverted", {
1151 threadId: ThreadId.make("thread-1"),
1152 turnCount: 1,
1153 }),
1154 localEnvironmentId,
1155 );
1156
1157 expect(threadsOf(next)[0]?.messages.map((message) => message.id)).toEqual([
1158 "user-1",
1159 "assistant-1",
1160 ]);
1161 expect(threadsOf(next)[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
1162 expect(threadsOf(next)[0]?.activities.map((activity) => activity.id)).toEqual([
1163 EventId.make("activity-1"),
1164 ]);
1165 expect(threadsOf(next)[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
1166 TurnId.make("turn-1"),
1167 ]);
1168 });
1169
1170 it("clears pending source proposed plans after revert before a new session-set event", () => {
1171 const thread = makeThread({
1172 latestTurn: {
1173 turnId: TurnId.make("turn-2"),
1174 state: "completed",
1175 requestedAt: "2026-02-27T00:00:02.000Z",
1176 startedAt: "2026-02-27T00:00:02.000Z",
1177 completedAt: "2026-02-27T00:00:03.000Z",
1178 assistantMessageId: MessageId.make("assistant-2"),
1179 sourceProposedPlan: {
1180 threadId: ThreadId.make("thread-source"),
1181 planId: "plan-2" as never,
1182 },
1183 },
1184 pendingSourceProposedPlan: {
1185 threadId: ThreadId.make("thread-source"),
1186 planId: "plan-2" as never,
1187 },
1188 turnDiffSummaries: [
1189 {
1190 turnId: TurnId.make("turn-1"),
1191 completedAt: "2026-02-27T00:00:01.000Z",
1192 status: "ready",
1193 checkpointTurnCount: 1,
1194 checkpointRef: CheckpointRef.make("ref-1"),
1195 files: [],
1196 },
1197 {
1198 turnId: TurnId.make("turn-2"),
1199 completedAt: "2026-02-27T00:00:03.000Z",
1200 status: "ready",
1201 checkpointTurnCount: 2,
1202 checkpointRef: CheckpointRef.make("ref-2"),
1203 files: [],
1204 },
1205 ],
1206 });
1207 const reverted = applyOrchestrationEvent(
1208 makeState(thread),
1209 makeEvent("thread.reverted", {
1210 threadId: thread.id,
1211 turnCount: 1,
1212 }),
1213 localEnvironmentId,
1214 );
1215
1216 expect(threadsOf(reverted)[0]?.pendingSourceProposedPlan).toBeUndefined();
1217
1218 const next = applyOrchestrationEvent(
1219 reverted,
1220 makeEvent("thread.session-set", {
1221 threadId: thread.id,
1222 session: {
1223 threadId: thread.id,
1224 status: "running",
1225 providerName: "codex",
1226 runtimeMode: "full-access",
1227 activeTurnId: TurnId.make("turn-3"),
1228 lastError: null,
1229 updatedAt: "2026-02-27T00:00:04.000Z",
1230 },
1231 }),
1232 localEnvironmentId,
1233 );
1234
1235 expect(threadsOf(next)[0]?.latestTurn).toMatchObject({
1236 turnId: TurnId.make("turn-3"),
1237 state: "running",
1238 });
1239 expect(threadsOf(next)[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
1240 });
1241});