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

store.test.ts

1,017 lines31.2 KB

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