Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime";
2import {
3 CheckpointRef,
4 DEFAULT_MODEL,
5 EnvironmentId,
6 EventId,
7 MessageId,
8 ProjectId,
9 ProviderInstanceId,
10 ThreadId,
11 TurnId,
12 type OrchestrationEvent,
13} from "@t3tools/contracts";
14import { describe, expect, it } from "vitest";
15
16import {
17 applyOrchestrationEvent,
18 applyOrchestrationEvents,
19 removeEnvironmentState,
20 selectEnvironmentState,
21 selectProjectsAcrossEnvironments,
22 selectThreadByRef,
23 selectThreadExistsByRef,
24 setThreadBranch,
25 selectThreadsAcrossEnvironments,
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 instanceId: ProviderInstanceId.make("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 instanceId: ProviderInstanceId.make("codex"),
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("environment state removal", () => {
251 it("drops local state for removed environments", () => {
252 const removedThread = makeThread({
253 environmentId: remoteEnvironmentId,
254 id: ThreadId.make("thread-removed"),
255 });
256 const keptThread = makeThread({ id: ThreadId.make("thread-kept") });
257 const removedState = makeState(removedThread).environmentStateById[remoteEnvironmentId]!;
258 const keptState = makeState(keptThread).environmentStateById[localEnvironmentId]!;
259 const state: AppState = {
260 activeEnvironmentId: remoteEnvironmentId,
261 environmentStateById: {
262 [remoteEnvironmentId]: removedState,
263 [localEnvironmentId]: keptState,
264 },
265 };
266
267 const next = removeEnvironmentState(state, remoteEnvironmentId);
268
269 expect(next.activeEnvironmentId).toBeNull();
270 expect(next.environmentStateById[remoteEnvironmentId]).toBeUndefined();
271 expect(next.environmentStateById[localEnvironmentId]).toBe(keptState);
272 });
273
274 it("preserves active environment when removing a different environment", () => {
275 const state = makeState(makeThread());
276
277 const next = removeEnvironmentState(state, remoteEnvironmentId);
278
279 expect(next).toBe(state);
280 });
281});
282
283describe("thread selection memoization", () => {
284 it("returns stable thread references for repeated reads of the same state", () => {
285 const thread = makeThread({
286 messages: [
287 {
288 id: MessageId.make("message-1"),
289 role: "user",
290 text: "hello",
291 createdAt: "2026-02-13T00:01:00.000Z",
292 streaming: false,
293 },
294 ],
295 activities: [
296 {
297 id: EventId.make("activity-1"),
298 tone: "info",
299 kind: "step",
300 summary: "working",
301 payload: {},
302 turnId: TurnId.make("turn-1"),
303 createdAt: "2026-02-13T00:01:30.000Z",
304 },
305 ],
306 proposedPlans: [
307 {
308 id: "plan-1",
309 turnId: null,
310 planMarkdown: "plan",
311 implementedAt: null,
312 implementationThreadId: null,
313 createdAt: "2026-02-13T00:02:00.000Z",
314 updatedAt: "2026-02-13T00:02:00.000Z",
315 },
316 ],
317 turnDiffSummaries: [
318 {
319 turnId: TurnId.make("turn-1"),
320 completedAt: "2026-02-13T00:03:00.000Z",
321 files: [],
322 },
323 ],
324 });
325 const state = makeState(thread);
326 const ref = scopeThreadRef(thread.environmentId, thread.id);
327
328 const first = selectThreadByRef(state, ref);
329 const second = selectThreadByRef(state, ref);
330
331 expect(first).toBeDefined();
332 expect(second).toBe(first);
333 expect(second?.messages).toBe(first?.messages);
334 expect(second?.activities).toBe(first?.activities);
335 expect(second?.proposedPlans).toBe(first?.proposedPlans);
336 expect(second?.turnDiffSummaries).toBe(first?.turnDiffSummaries);
337 });
338
339 it("reuses the derived thread when the app state wrapper changes but thread data does not", () => {
340 const thread = makeThread({
341 messages: [
342 {
343 id: MessageId.make("message-1"),
344 role: "assistant",
345 text: "done",
346 createdAt: "2026-02-13T00:01:00.000Z",
347 streaming: false,
348 },
349 ],
350 });
351 const state = makeState(thread);
352 const ref = scopeThreadRef(thread.environmentId, thread.id);
353 const wrappedState: AppState = {
354 ...state,
355 environmentStateById: { ...state.environmentStateById },
356 };
357
358 const first = selectThreadByRef(state, ref);
359 const second = selectThreadByRef(wrappedState, ref);
360
361 expect(second).toBe(first);
362 });
363
364 it("updates the derived thread when the underlying thread data changes", () => {
365 const thread = makeThread();
366 const ref = scopeThreadRef(thread.environmentId, thread.id);
367 const firstState = makeState(thread);
368 const secondState = makeState({
369 ...thread,
370 messages: [
371 {
372 id: MessageId.make("message-2"),
373 role: "user",
374 text: "new",
375 createdAt: "2026-02-13T00:04:00.000Z",
376 streaming: false,
377 },
378 ],
379 });
380
381 const first = selectThreadByRef(firstState, ref);
382 const second = selectThreadByRef(secondState, ref);
383
384 expect(second).not.toBe(first);
385 expect(second?.messages).toHaveLength(1);
386 expect(second?.messages[0]?.text).toBe("new");
387 });
388
389 it("checks thread existence without materializing the full thread", () => {
390 const thread = makeThread();
391 const state = makeState(thread);
392 const ref = scopeThreadRef(thread.environmentId, thread.id);
393
394 expect(selectThreadExistsByRef(state, ref)).toBe(true);
395 expect(
396 selectThreadExistsByRef(
397 state,
398 scopeThreadRef(thread.environmentId, ThreadId.make("missing")),
399 ),
400 ).toBe(false);
401 expect(selectThreadExistsByRef(state, null)).toBe(false);
402 });
403});
404
405describe("setThreadBranch", () => {
406 it("updates only the scoped thread environment", () => {
407 const sharedThreadId = ThreadId.make("thread-shared");
408 const localThread = makeThread({
409 id: sharedThreadId,
410 environmentId: localEnvironmentId,
411 branch: "local-branch",
412 });
413 const remoteThread = makeThread({
414 id: sharedThreadId,
415 environmentId: remoteEnvironmentId,
416 branch: "remote-branch",
417 });
418 const state: AppState = {
419 activeEnvironmentId: localEnvironmentId,
420 environmentStateById: {
421 [localEnvironmentId]: environmentStateOf(makeState(localThread), localEnvironmentId),
422 [remoteEnvironmentId]: environmentStateOf(makeState(remoteThread), remoteEnvironmentId),
423 },
424 };
425
426 const next = setThreadBranch(
427 state,
428 scopeThreadRef(remoteEnvironmentId, sharedThreadId),
429 "remote-next",
430 "/tmp/remote-worktree",
431 );
432
433 expect(
434 environmentStateOf(next, localEnvironmentId).threadShellById[sharedThreadId]?.branch,
435 ).toBe("local-branch");
436 expect(
437 environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.branch,
438 ).toBe("remote-next");
439 expect(
440 environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.worktreePath,
441 ).toBe("/tmp/remote-worktree");
442 });
443});
444
445describe("incremental orchestration updates", () => {
446 it("does not mark bootstrap complete for incremental events", () => {
447 const state = withActiveEnvironmentState(localEnvironmentStateOf(makeState(makeThread())), {
448 bootstrapComplete: false,
449 });
450
451 const next = applyOrchestrationEvent(
452 state,
453 makeEvent("thread.meta-updated", {
454 threadId: ThreadId.make("thread-1"),
455 title: "Updated title",
456 updatedAt: "2026-02-27T00:00:01.000Z",
457 }),
458 localEnvironmentId,
459 );
460
461 expect(localEnvironmentStateOf(next).bootstrapComplete).toBe(false);
462 });
463
464 it("preserves state identity for no-op project and thread deletes", () => {
465 const thread = makeThread();
466 const state = makeState(thread);
467
468 const nextAfterProjectDelete = applyOrchestrationEvent(
469 state,
470 makeEvent("project.deleted", {
471 projectId: ProjectId.make("project-missing"),
472 deletedAt: "2026-02-27T00:00:01.000Z",
473 }),
474 localEnvironmentId,
475 );
476 const nextAfterThreadDelete = applyOrchestrationEvent(
477 state,
478 makeEvent("thread.deleted", {
479 threadId: ThreadId.make("thread-missing"),
480 deletedAt: "2026-02-27T00:00:01.000Z",
481 }),
482 localEnvironmentId,
483 );
484
485 expect(nextAfterProjectDelete).toBe(state);
486 expect(nextAfterThreadDelete).toBe(state);
487 });
488
489 it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
490 const originalProjectId = ProjectId.make("project-1");
491 const recreatedProjectId = ProjectId.make("project-2");
492 const state: AppState = makeEmptyState({
493 projectIds: [originalProjectId],
494 projectById: {
495 [originalProjectId]: {
496 id: originalProjectId,
497 environmentId: localEnvironmentId,
498 name: "Project",
499 cwd: "/tmp/project",
500 defaultModelSelection: {
501 instanceId: ProviderInstanceId.make("codex"),
502 model: DEFAULT_MODEL,
503 },
504 createdAt: "2026-02-27T00:00:00.000Z",
505 updatedAt: "2026-02-27T00:00:00.000Z",
506 scripts: [],
507 },
508 },
509 });
510
511 const next = applyOrchestrationEvent(
512 state,
513 makeEvent("project.created", {
514 projectId: recreatedProjectId,
515 title: "Project Recreated",
516 workspaceRoot: "/tmp/project",
517 defaultModelSelection: {
518 instanceId: ProviderInstanceId.make("codex"),
519 model: DEFAULT_MODEL,
520 },
521 scripts: [],
522 createdAt: "2026-02-27T00:00:01.000Z",
523 updatedAt: "2026-02-27T00:00:01.000Z",
524 }),
525 localEnvironmentId,
526 );
527
528 expect(projectsOf(next)).toHaveLength(1);
529 expect(projectsOf(next)[0]?.id).toBe(recreatedProjectId);
530 expect(projectsOf(next)[0]?.cwd).toBe("/tmp/project");
531 expect(projectsOf(next)[0]?.name).toBe("Project Recreated");
532 expect(localEnvironmentStateOf(next).projectIds).toEqual([recreatedProjectId]);
533 expect(localEnvironmentStateOf(next).projectById[originalProjectId]).toBeUndefined();
534 expect(localEnvironmentStateOf(next).projectById[recreatedProjectId]?.id).toBe(
535 recreatedProjectId,
536 );
537 });
538
539 it("removes stale project index entries when thread.created recreates a thread under a new project", () => {
540 const originalProjectId = ProjectId.make("project-1");
541 const recreatedProjectId = ProjectId.make("project-2");
542 const threadId = ThreadId.make("thread-1");
543 const thread = makeThread({
544 id: threadId,
545 projectId: originalProjectId,
546 });
547 const state = withActiveEnvironmentState(localEnvironmentStateOf(makeState(thread)), {
548 projectIds: [originalProjectId, recreatedProjectId],
549 projectById: {
550 [originalProjectId]: {
551 id: originalProjectId,
552 environmentId: localEnvironmentId,
553 name: "Project 1",
554 cwd: "/tmp/project-1",
555 defaultModelSelection: {
556 instanceId: ProviderInstanceId.make("codex"),
557 model: DEFAULT_MODEL,
558 },
559 createdAt: "2026-02-27T00:00:00.000Z",
560 updatedAt: "2026-02-27T00:00:00.000Z",
561 scripts: [],
562 },
563 [recreatedProjectId]: {
564 id: recreatedProjectId,
565 environmentId: localEnvironmentId,
566 name: "Project 2",
567 cwd: "/tmp/project-2",
568 defaultModelSelection: {
569 instanceId: ProviderInstanceId.make("codex"),
570 model: DEFAULT_MODEL,
571 },
572 createdAt: "2026-02-27T00:00:00.000Z",
573 updatedAt: "2026-02-27T00:00:00.000Z",
574 scripts: [],
575 },
576 },
577 });
578
579 const next = applyOrchestrationEvent(
580 state,
581 makeEvent("thread.created", {
582 threadId,
583 projectId: recreatedProjectId,
584 title: "Recovered thread",
585 modelSelection: {
586 instanceId: ProviderInstanceId.make("codex"),
587 model: DEFAULT_MODEL,
588 },
589 runtimeMode: DEFAULT_RUNTIME_MODE,
590 interactionMode: DEFAULT_INTERACTION_MODE,
591 branch: null,
592 worktreePath: null,
593 createdAt: "2026-02-27T00:00:01.000Z",
594 updatedAt: "2026-02-27T00:00:01.000Z",
595 }),
596 localEnvironmentId,
597 );
598
599 expect(threadsOf(next)).toHaveLength(1);
600 expect(threadsOf(next)[0]?.projectId).toBe(recreatedProjectId);
601 expect(localEnvironmentStateOf(next).threadIdsByProjectId[originalProjectId]).toBeUndefined();
602 expect(localEnvironmentStateOf(next).threadIdsByProjectId[recreatedProjectId]).toEqual([
603 threadId,
604 ]);
605 });
606
607 it("updates only the affected thread for message events", () => {
608 const thread1 = makeThread({
609 id: ThreadId.make("thread-1"),
610 messages: [
611 {
612 id: MessageId.make("message-1"),
613 role: "assistant",
614 text: "hello",
615 turnId: TurnId.make("turn-1"),
616 createdAt: "2026-02-27T00:00:00.000Z",
617 completedAt: "2026-02-27T00:00:00.000Z",
618 streaming: false,
619 },
620 ],
621 });
622 const thread2 = makeThread({ id: ThreadId.make("thread-2") });
623 const baseState = makeState(thread1);
624 const baseEnvironmentState = localEnvironmentStateOf(baseState);
625 const state = withActiveEnvironmentState(baseEnvironmentState, {
626 threadIds: [thread1.id, thread2.id],
627 threadShellById: {
628 ...baseEnvironmentState.threadShellById,
629 [thread2.id]: {
630 id: thread2.id,
631 environmentId: thread2.environmentId,
632 codexThreadId: thread2.codexThreadId,
633 projectId: thread2.projectId,
634 title: thread2.title,
635 modelSelection: thread2.modelSelection,
636 runtimeMode: thread2.runtimeMode,
637 interactionMode: thread2.interactionMode,
638 error: thread2.error,
639 createdAt: thread2.createdAt,
640 archivedAt: thread2.archivedAt,
641 updatedAt: thread2.updatedAt,
642 branch: thread2.branch,
643 worktreePath: thread2.worktreePath,
644 },
645 },
646 threadSessionById: {
647 ...baseEnvironmentState.threadSessionById,
648 [thread2.id]: thread2.session,
649 },
650 threadTurnStateById: {
651 ...baseEnvironmentState.threadTurnStateById,
652 [thread2.id]: {
653 latestTurn: thread2.latestTurn,
654 },
655 },
656 messageIdsByThreadId: {
657 ...baseEnvironmentState.messageIdsByThreadId,
658 [thread2.id]: [],
659 },
660 messageByThreadId: {
661 ...baseEnvironmentState.messageByThreadId,
662 [thread2.id]: {},
663 },
664 activityIdsByThreadId: {
665 ...baseEnvironmentState.activityIdsByThreadId,
666 [thread2.id]: [],
667 },
668 activityByThreadId: {
669 ...baseEnvironmentState.activityByThreadId,
670 [thread2.id]: {},
671 },
672 proposedPlanIdsByThreadId: {
673 ...baseEnvironmentState.proposedPlanIdsByThreadId,
674 [thread2.id]: [],
675 },
676 proposedPlanByThreadId: {
677 ...baseEnvironmentState.proposedPlanByThreadId,
678 [thread2.id]: {},
679 },
680 turnDiffIdsByThreadId: {
681 ...baseEnvironmentState.turnDiffIdsByThreadId,
682 [thread2.id]: [],
683 },
684 turnDiffSummaryByThreadId: {
685 ...baseEnvironmentState.turnDiffSummaryByThreadId,
686 [thread2.id]: {},
687 },
688 sidebarThreadSummaryById: {
689 ...baseEnvironmentState.sidebarThreadSummaryById,
690 },
691 threadIdsByProjectId: {
692 [thread1.projectId]: [thread1.id, thread2.id],
693 },
694 });
695
696 const next = applyOrchestrationEvent(
697 state,
698 makeEvent("thread.message-sent", {
699 threadId: thread1.id,
700 messageId: MessageId.make("message-1"),
701 role: "assistant",
702 text: " world",
703 turnId: TurnId.make("turn-1"),
704 streaming: true,
705 createdAt: "2026-02-27T00:00:01.000Z",
706 updatedAt: "2026-02-27T00:00:01.000Z",
707 }),
708 localEnvironmentId,
709 );
710
711 expect(threadsOf(next)[0]?.messages[0]?.text).toBe("hello world");
712 expect(threadsOf(next)[0]?.latestTurn?.state).toBe("running");
713 const nextEnvironmentState = next.environmentStateById[localEnvironmentId];
714 const previousEnvironmentState = state.environmentStateById[localEnvironmentId];
715 expect(nextEnvironmentState?.threadShellById[thread2.id]).toBe(
716 previousEnvironmentState?.threadShellById[thread2.id],
717 );
718 expect(nextEnvironmentState?.threadSessionById[thread2.id]).toBe(
719 previousEnvironmentState?.threadSessionById[thread2.id],
720 );
721 expect(nextEnvironmentState?.messageIdsByThreadId[thread2.id]).toBe(
722 previousEnvironmentState?.messageIdsByThreadId[thread2.id],
723 );
724 expect(nextEnvironmentState?.messageByThreadId[thread2.id]).toBe(
725 previousEnvironmentState?.messageByThreadId[thread2.id],
726 );
727 });
728
729 it("applies replay batches in sequence and updates session state", () => {
730 const thread = makeThread({
731 latestTurn: {
732 turnId: TurnId.make("turn-1"),
733 state: "running",
734 requestedAt: "2026-02-27T00:00:00.000Z",
735 startedAt: "2026-02-27T00:00:00.000Z",
736 completedAt: null,
737 assistantMessageId: null,
738 },
739 });
740 const state = makeState(thread);
741
742 const next = applyOrchestrationEvents(
743 state,
744 [
745 makeEvent(
746 "thread.session-set",
747 {
748 threadId: thread.id,
749 session: {
750 threadId: thread.id,
751 status: "running",
752 providerName: "codex",
753 runtimeMode: "full-access",
754 activeTurnId: TurnId.make("turn-1"),
755 lastError: null,
756 updatedAt: "2026-02-27T00:00:02.000Z",
757 },
758 },
759 { sequence: 2 },
760 ),
761 makeEvent(
762 "thread.message-sent",
763 {
764 threadId: thread.id,
765 messageId: MessageId.make("assistant-1"),
766 role: "assistant",
767 text: "done",
768 turnId: TurnId.make("turn-1"),
769 streaming: false,
770 createdAt: "2026-02-27T00:00:03.000Z",
771 updatedAt: "2026-02-27T00:00:03.000Z",
772 },
773 { sequence: 3 },
774 ),
775 ],
776 localEnvironmentId,
777 );
778
779 expect(threadsOf(next)[0]?.session?.status).toBe("running");
780 expect(threadsOf(next)[0]?.latestTurn?.state).toBe("completed");
781 expect(threadsOf(next)[0]?.messages).toHaveLength(1);
782 });
783
784 it("does not regress latestTurn when an older turn diff completes late", () => {
785 const state = makeState(
786 makeThread({
787 latestTurn: {
788 turnId: TurnId.make("turn-2"),
789 state: "running",
790 requestedAt: "2026-02-27T00:00:02.000Z",
791 startedAt: "2026-02-27T00:00:03.000Z",
792 completedAt: null,
793 assistantMessageId: null,
794 },
795 }),
796 );
797
798 const next = applyOrchestrationEvent(
799 state,
800 makeEvent("thread.turn-diff-completed", {
801 threadId: ThreadId.make("thread-1"),
802 turnId: TurnId.make("turn-1"),
803 checkpointTurnCount: 1,
804 checkpointRef: CheckpointRef.make("checkpoint-1"),
805 status: "ready",
806 files: [],
807 assistantMessageId: MessageId.make("assistant-1"),
808 completedAt: "2026-02-27T00:00:04.000Z",
809 }),
810 localEnvironmentId,
811 );
812
813 expect(threadsOf(next)[0]?.turnDiffSummaries).toHaveLength(1);
814 expect(threadsOf(next)[0]?.latestTurn).toEqual(threadsOf(state)[0]?.latestTurn);
815 });
816
817 it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
818 const turnId = TurnId.make("turn-1");
819 const state = makeState(
820 makeThread({
821 latestTurn: {
822 turnId,
823 state: "completed",
824 requestedAt: "2026-02-27T00:00:00.000Z",
825 startedAt: "2026-02-27T00:00:00.000Z",
826 completedAt: "2026-02-27T00:00:02.000Z",
827 assistantMessageId: MessageId.make("assistant:turn-1"),
828 },
829 turnDiffSummaries: [
830 {
831 turnId,
832 completedAt: "2026-02-27T00:00:02.000Z",
833 status: "ready",
834 checkpointTurnCount: 1,
835 checkpointRef: CheckpointRef.make("checkpoint-1"),
836 assistantMessageId: MessageId.make("assistant:turn-1"),
837 files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
838 },
839 ],
840 }),
841 );
842
843 const next = applyOrchestrationEvent(
844 state,
845 makeEvent("thread.message-sent", {
846 threadId: ThreadId.make("thread-1"),
847 messageId: MessageId.make("assistant-real"),
848 role: "assistant",
849 text: "final answer",
850 turnId,
851 streaming: false,
852 createdAt: "2026-02-27T00:00:03.000Z",
853 updatedAt: "2026-02-27T00:00:03.000Z",
854 }),
855 localEnvironmentId,
856 );
857
858 expect(threadsOf(next)[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
859 MessageId.make("assistant-real"),
860 );
861 expect(threadsOf(next)[0]?.latestTurn?.assistantMessageId).toBe(
862 MessageId.make("assistant-real"),
863 );
864 });
865
866 it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
867 const state = makeState(
868 makeThread({
869 messages: [
870 {
871 id: MessageId.make("user-1"),
872 role: "user",
873 text: "first",
874 turnId: TurnId.make("turn-1"),
875 createdAt: "2026-02-27T00:00:00.000Z",
876 completedAt: "2026-02-27T00:00:00.000Z",
877 streaming: false,
878 },
879 {
880 id: MessageId.make("assistant-1"),
881 role: "assistant",
882 text: "first reply",
883 turnId: TurnId.make("turn-1"),
884 createdAt: "2026-02-27T00:00:01.000Z",
885 completedAt: "2026-02-27T00:00:01.000Z",
886 streaming: false,
887 },
888 {
889 id: MessageId.make("user-2"),
890 role: "user",
891 text: "second",
892 turnId: TurnId.make("turn-2"),
893 createdAt: "2026-02-27T00:00:02.000Z",
894 completedAt: "2026-02-27T00:00:02.000Z",
895 streaming: false,
896 },
897 ],
898 proposedPlans: [
899 {
900 id: "plan-1",
901 turnId: TurnId.make("turn-1"),
902 planMarkdown: "plan 1",
903 implementedAt: null,
904 implementationThreadId: null,
905 createdAt: "2026-02-27T00:00:00.000Z",
906 updatedAt: "2026-02-27T00:00:00.000Z",
907 },
908 {
909 id: "plan-2",
910 turnId: TurnId.make("turn-2"),
911 planMarkdown: "plan 2",
912 implementedAt: null,
913 implementationThreadId: null,
914 createdAt: "2026-02-27T00:00:02.000Z",
915 updatedAt: "2026-02-27T00:00:02.000Z",
916 },
917 ],
918 activities: [
919 {
920 id: EventId.make("activity-1"),
921 tone: "info",
922 kind: "step",
923 summary: "one",
924 payload: {},
925 turnId: TurnId.make("turn-1"),
926 createdAt: "2026-02-27T00:00:00.000Z",
927 },
928 {
929 id: EventId.make("activity-2"),
930 tone: "info",
931 kind: "step",
932 summary: "two",
933 payload: {},
934 turnId: TurnId.make("turn-2"),
935 createdAt: "2026-02-27T00:00:02.000Z",
936 },
937 ],
938 turnDiffSummaries: [
939 {
940 turnId: TurnId.make("turn-1"),
941 completedAt: "2026-02-27T00:00:01.000Z",
942 status: "ready",
943 checkpointTurnCount: 1,
944 checkpointRef: CheckpointRef.make("ref-1"),
945 files: [],
946 },
947 {
948 turnId: TurnId.make("turn-2"),
949 completedAt: "2026-02-27T00:00:03.000Z",
950 status: "ready",
951 checkpointTurnCount: 2,
952 checkpointRef: CheckpointRef.make("ref-2"),
953 files: [],
954 },
955 ],
956 }),
957 );
958
959 const next = applyOrchestrationEvent(
960 state,
961 makeEvent("thread.reverted", {
962 threadId: ThreadId.make("thread-1"),
963 turnCount: 1,
964 }),
965 localEnvironmentId,
966 );
967
968 expect(threadsOf(next)[0]?.messages.map((message) => message.id)).toEqual([
969 "user-1",
970 "assistant-1",
971 ]);
972 expect(threadsOf(next)[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
973 expect(threadsOf(next)[0]?.activities.map((activity) => activity.id)).toEqual([
974 EventId.make("activity-1"),
975 ]);
976 expect(threadsOf(next)[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
977 TurnId.make("turn-1"),
978 ]);
979 });
980
981 it("clears pending source proposed plans after revert before a new session-set event", () => {
982 const thread = makeThread({
983 latestTurn: {
984 turnId: TurnId.make("turn-2"),
985 state: "completed",
986 requestedAt: "2026-02-27T00:00:02.000Z",
987 startedAt: "2026-02-27T00:00:02.000Z",
988 completedAt: "2026-02-27T00:00:03.000Z",
989 assistantMessageId: MessageId.make("assistant-2"),
990 sourceProposedPlan: {
991 threadId: ThreadId.make("thread-source"),
992 planId: "plan-2" as never,
993 },
994 },
995 pendingSourceProposedPlan: {
996 threadId: ThreadId.make("thread-source"),
997 planId: "plan-2" as never,
998 },
999 turnDiffSummaries: [
1000 {
1001 turnId: TurnId.make("turn-1"),
1002 completedAt: "2026-02-27T00:00:01.000Z",
1003 status: "ready",
1004 checkpointTurnCount: 1,
1005 checkpointRef: CheckpointRef.make("ref-1"),
1006 files: [],
1007 },
1008 {
1009 turnId: TurnId.make("turn-2"),
1010 completedAt: "2026-02-27T00:00:03.000Z",
1011 status: "ready",
1012 checkpointTurnCount: 2,
1013 checkpointRef: CheckpointRef.make("ref-2"),
1014 files: [],
1015 },
1016 ],
1017 });
1018 const reverted = applyOrchestrationEvent(
1019 makeState(thread),
1020 makeEvent("thread.reverted", {
1021 threadId: thread.id,
1022 turnCount: 1,
1023 }),
1024 localEnvironmentId,
1025 );
1026
1027 expect(threadsOf(reverted)[0]?.pendingSourceProposedPlan).toBeUndefined();
1028
1029 const next = applyOrchestrationEvent(
1030 reverted,
1031 makeEvent("thread.session-set", {
1032 threadId: thread.id,
1033 session: {
1034 threadId: thread.id,
1035 status: "running",
1036 providerName: "codex",
1037 runtimeMode: "full-access",
1038 activeTurnId: TurnId.make("turn-3"),
1039 lastError: null,
1040 updatedAt: "2026-02-27T00:00:04.000Z",
1041 },
1042 }),
1043 localEnvironmentId,
1044 );
1045
1046 expect(threadsOf(next)[0]?.latestTurn).toMatchObject({
1047 turnId: TurnId.make("turn-3"),
1048 state: "running",
1049 });
1050 expect(threadsOf(next)[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
1051 });
1052});