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

store.test.ts

1,178 lines36.2 KB

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