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

store.test.ts

1,018 lines31.3 KB

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