Open History to see the last commit
1import {
2 type OrchestrationEvent,
3 type OrchestrationMessage,
4 type OrchestrationProposedPlan,
5 type ProviderKind,
6 ThreadId,
7 type OrchestrationReadModel,
8 type OrchestrationSession,
9 type OrchestrationCheckpointSummary,
10 type OrchestrationThread,
11 type OrchestrationSessionStatus,
12} from "@t3tools/contracts";
13import { resolveModelSlugForProvider } from "@t3tools/shared/model";
14import { create } from "zustand";
15import { type ChatMessage, type Project, type Thread } from "./types";
16
17// ── State ────────────────────────────────────────────────────────────
18
19export interface AppState {
20 projects: Project[];
21 threads: Thread[];
22 bootstrapComplete: boolean;
23}
24
25const initialState: AppState = {
26 projects: [],
27 threads: [],
28 bootstrapComplete: false,
29};
30const MAX_THREAD_MESSAGES = 2_000;
31const MAX_THREAD_CHECKPOINTS = 500;
32const MAX_THREAD_PROPOSED_PLANS = 200;
33const MAX_THREAD_ACTIVITIES = 500;
34
35// ── Pure helpers ──────────────────────────────────────────────────────
36
37function updateThread(
38 threads: Thread[],
39 threadId: ThreadId,
40 updater: (t: Thread) => Thread,
41): Thread[] {
42 let changed = false;
43 const next = threads.map((t) => {
44 if (t.id !== threadId) return t;
45 const updated = updater(t);
46 if (updated !== t) changed = true;
47 return updated;
48 });
49 return changed ? next : threads;
50}
51
52function updateProject(
53 projects: Project[],
54 projectId: Project["id"],
55 updater: (project: Project) => Project,
56): Project[] {
57 let changed = false;
58 const next = projects.map((project) => {
59 if (project.id !== projectId) {
60 return project;
61 }
62 const updated = updater(project);
63 if (updated !== project) {
64 changed = true;
65 }
66 return updated;
67 });
68 return changed ? next : projects;
69}
70
71function normalizeModelSelection<T extends { provider: "codex" | "claudeAgent"; model: string }>(
72 selection: T,
73): T {
74 return {
75 ...selection,
76 model: resolveModelSlugForProvider(selection.provider, selection.model),
77 };
78}
79
80function mapProjectScripts(scripts: ReadonlyArray<Project["scripts"][number]>): Project["scripts"] {
81 return scripts.map((script) => ({ ...script }));
82}
83
84function mapSession(session: OrchestrationSession): Thread["session"] {
85 return {
86 provider: toLegacyProvider(session.providerName),
87 status: toLegacySessionStatus(session.status),
88 orchestrationStatus: session.status,
89 activeTurnId: session.activeTurnId ?? undefined,
90 createdAt: session.updatedAt,
91 updatedAt: session.updatedAt,
92 ...(session.lastError ? { lastError: session.lastError } : {}),
93 };
94}
95
96function mapMessage(message: OrchestrationMessage): ChatMessage {
97 const attachments = message.attachments?.map((attachment) => ({
98 type: "image" as const,
99 id: attachment.id,
100 name: attachment.name,
101 mimeType: attachment.mimeType,
102 sizeBytes: attachment.sizeBytes,
103 previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
104 }));
105
106 return {
107 id: message.id,
108 role: message.role,
109 text: message.text,
110 turnId: message.turnId,
111 createdAt: message.createdAt,
112 streaming: message.streaming,
113 ...(message.streaming ? {} : { completedAt: message.updatedAt }),
114 ...(attachments && attachments.length > 0 ? { attachments } : {}),
115 };
116}
117
118function mapProposedPlan(proposedPlan: OrchestrationProposedPlan): Thread["proposedPlans"][number] {
119 return {
120 id: proposedPlan.id,
121 turnId: proposedPlan.turnId,
122 planMarkdown: proposedPlan.planMarkdown,
123 implementedAt: proposedPlan.implementedAt,
124 implementationThreadId: proposedPlan.implementationThreadId,
125 createdAt: proposedPlan.createdAt,
126 updatedAt: proposedPlan.updatedAt,
127 };
128}
129
130function mapTurnDiffSummary(
131 checkpoint: OrchestrationCheckpointSummary,
132): Thread["turnDiffSummaries"][number] {
133 return {
134 turnId: checkpoint.turnId,
135 completedAt: checkpoint.completedAt,
136 status: checkpoint.status,
137 assistantMessageId: checkpoint.assistantMessageId ?? undefined,
138 checkpointTurnCount: checkpoint.checkpointTurnCount,
139 checkpointRef: checkpoint.checkpointRef,
140 files: checkpoint.files.map((file) => ({ ...file })),
141 };
142}
143
144function mapThread(thread: OrchestrationThread): Thread {
145 return {
146 id: thread.id,
147 codexThreadId: null,
148 projectId: thread.projectId,
149 title: thread.title,
150 modelSelection: normalizeModelSelection(thread.modelSelection),
151 runtimeMode: thread.runtimeMode,
152 interactionMode: thread.interactionMode,
153 session: thread.session ? mapSession(thread.session) : null,
154 messages: thread.messages.map(mapMessage),
155 proposedPlans: thread.proposedPlans.map(mapProposedPlan),
156 error: thread.session?.lastError ?? null,
157 createdAt: thread.createdAt,
158 archivedAt: thread.archivedAt,
159 updatedAt: thread.updatedAt,
160 latestTurn: thread.latestTurn,
161 pendingSourceProposedPlan: thread.latestTurn?.sourceProposedPlan,
162 branch: thread.branch,
163 worktreePath: thread.worktreePath,
164 turnDiffSummaries: thread.checkpoints.map(mapTurnDiffSummary),
165 activities: thread.activities.map((activity) => ({ ...activity })),
166 };
167}
168
169function mapProject(project: OrchestrationReadModel["projects"][number]): Project {
170 return {
171 id: project.id,
172 name: project.title,
173 cwd: project.workspaceRoot,
174 defaultModelSelection: project.defaultModelSelection
175 ? normalizeModelSelection(project.defaultModelSelection)
176 : null,
177 createdAt: project.createdAt,
178 updatedAt: project.updatedAt,
179 scripts: mapProjectScripts(project.scripts),
180 };
181}
182
183function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
184 if (status === "error") {
185 return "error" as const;
186 }
187 if (status === "missing") {
188 return "interrupted" as const;
189 }
190 return "completed" as const;
191}
192
193function compareActivities(
194 left: Thread["activities"][number],
195 right: Thread["activities"][number],
196): number {
197 if (left.sequence !== undefined && right.sequence !== undefined) {
198 if (left.sequence !== right.sequence) {
199 return left.sequence - right.sequence;
200 }
201 } else if (left.sequence !== undefined) {
202 return 1;
203 } else if (right.sequence !== undefined) {
204 return -1;
205 }
206
207 return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
208}
209
210function buildLatestTurn(params: {
211 previous: Thread["latestTurn"];
212 turnId: NonNullable<Thread["latestTurn"]>["turnId"];
213 state: NonNullable<Thread["latestTurn"]>["state"];
214 requestedAt: string;
215 startedAt: string | null;
216 completedAt: string | null;
217 assistantMessageId: NonNullable<Thread["latestTurn"]>["assistantMessageId"];
218 sourceProposedPlan?: Thread["pendingSourceProposedPlan"];
219}): NonNullable<Thread["latestTurn"]> {
220 const resolvedPlan =
221 params.previous?.turnId === params.turnId
222 ? params.previous.sourceProposedPlan
223 : params.sourceProposedPlan;
224 return {
225 turnId: params.turnId,
226 state: params.state,
227 requestedAt: params.requestedAt,
228 startedAt: params.startedAt,
229 completedAt: params.completedAt,
230 assistantMessageId: params.assistantMessageId,
231 ...(resolvedPlan ? { sourceProposedPlan: resolvedPlan } : {}),
232 };
233}
234
235function rebindTurnDiffSummariesForAssistantMessage(
236 turnDiffSummaries: ReadonlyArray<Thread["turnDiffSummaries"][number]>,
237 turnId: Thread["turnDiffSummaries"][number]["turnId"],
238 assistantMessageId: NonNullable<Thread["latestTurn"]>["assistantMessageId"],
239): Thread["turnDiffSummaries"] {
240 let changed = false;
241 const nextSummaries = turnDiffSummaries.map((summary) => {
242 if (summary.turnId !== turnId || summary.assistantMessageId === assistantMessageId) {
243 return summary;
244 }
245 changed = true;
246 return {
247 ...summary,
248 assistantMessageId: assistantMessageId ?? undefined,
249 };
250 });
251 return changed ? nextSummaries : [...turnDiffSummaries];
252}
253
254function retainThreadMessagesAfterRevert(
255 messages: ReadonlyArray<ChatMessage>,
256 retainedTurnIds: ReadonlySet<string>,
257 turnCount: number,
258): ChatMessage[] {
259 const retainedMessageIds = new Set<string>();
260 for (const message of messages) {
261 if (message.role === "system") {
262 retainedMessageIds.add(message.id);
263 continue;
264 }
265 if (
266 message.turnId !== undefined &&
267 message.turnId !== null &&
268 retainedTurnIds.has(message.turnId)
269 ) {
270 retainedMessageIds.add(message.id);
271 }
272 }
273
274 const retainedUserCount = messages.filter(
275 (message) => message.role === "user" && retainedMessageIds.has(message.id),
276 ).length;
277 const missingUserCount = Math.max(0, turnCount - retainedUserCount);
278 if (missingUserCount > 0) {
279 const fallbackUserMessages = messages
280 .filter(
281 (message) =>
282 message.role === "user" &&
283 !retainedMessageIds.has(message.id) &&
284 (message.turnId === undefined ||
285 message.turnId === null ||
286 retainedTurnIds.has(message.turnId)),
287 )
288 .toSorted(
289 (left, right) =>
290 left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
291 )
292 .slice(0, missingUserCount);
293 for (const message of fallbackUserMessages) {
294 retainedMessageIds.add(message.id);
295 }
296 }
297
298 const retainedAssistantCount = messages.filter(
299 (message) => message.role === "assistant" && retainedMessageIds.has(message.id),
300 ).length;
301 const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
302 if (missingAssistantCount > 0) {
303 const fallbackAssistantMessages = messages
304 .filter(
305 (message) =>
306 message.role === "assistant" &&
307 !retainedMessageIds.has(message.id) &&
308 (message.turnId === undefined ||
309 message.turnId === null ||
310 retainedTurnIds.has(message.turnId)),
311 )
312 .toSorted(
313 (left, right) =>
314 left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
315 )
316 .slice(0, missingAssistantCount);
317 for (const message of fallbackAssistantMessages) {
318 retainedMessageIds.add(message.id);
319 }
320 }
321
322 return messages.filter((message) => retainedMessageIds.has(message.id));
323}
324
325function retainThreadActivitiesAfterRevert(
326 activities: ReadonlyArray<Thread["activities"][number]>,
327 retainedTurnIds: ReadonlySet<string>,
328): Thread["activities"] {
329 return activities.filter(
330 (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
331 );
332}
333
334function retainThreadProposedPlansAfterRevert(
335 proposedPlans: ReadonlyArray<Thread["proposedPlans"][number]>,
336 retainedTurnIds: ReadonlySet<string>,
337): Thread["proposedPlans"] {
338 return proposedPlans.filter(
339 (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
340 );
341}
342
343function toLegacySessionStatus(
344 status: OrchestrationSessionStatus,
345): "connecting" | "ready" | "running" | "error" | "closed" {
346 switch (status) {
347 case "starting":
348 return "connecting";
349 case "running":
350 return "running";
351 case "error":
352 return "error";
353 case "ready":
354 case "interrupted":
355 return "ready";
356 case "idle":
357 case "stopped":
358 return "closed";
359 }
360}
361
362function toLegacyProvider(providerName: string | null): ProviderKind {
363 if (providerName === "codex" || providerName === "claudeAgent") {
364 return providerName;
365 }
366 return "codex";
367}
368
369function resolveWsHttpOrigin(): string {
370 if (typeof window === "undefined") return "";
371 const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
372 const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
373 const wsCandidate =
374 typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
375 ? bridgeWsUrl
376 : typeof envWsUrl === "string" && envWsUrl.length > 0
377 ? envWsUrl
378 : null;
379 if (!wsCandidate) return window.location.origin;
380 try {
381 const wsUrl = new URL(wsCandidate);
382 const protocol =
383 wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
384 return `${protocol}//${wsUrl.host}`;
385 } catch {
386 return window.location.origin;
387 }
388}
389
390function toAttachmentPreviewUrl(rawUrl: string): string {
391 if (rawUrl.startsWith("/")) {
392 return `${resolveWsHttpOrigin()}${rawUrl}`;
393 }
394 return rawUrl;
395}
396
397function attachmentPreviewRoutePath(attachmentId: string): string {
398 return `/attachments/${encodeURIComponent(attachmentId)}`;
399}
400
401// ── Pure state transition functions ────────────────────────────────────
402
403export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState {
404 const projects = readModel.projects
405 .filter((project) => project.deletedAt === null)
406 .map(mapProject);
407 const threads = readModel.threads.filter((thread) => thread.deletedAt === null).map(mapThread);
408 return {
409 ...state,
410 projects,
411 threads,
412 bootstrapComplete: true,
413 };
414}
415
416export function applyOrchestrationEvent(state: AppState, event: OrchestrationEvent): AppState {
417 switch (event.type) {
418 case "project.created": {
419 const existingIndex = state.projects.findIndex(
420 (project) =>
421 project.id === event.payload.projectId || project.cwd === event.payload.workspaceRoot,
422 );
423 const nextProject = mapProject({
424 id: event.payload.projectId,
425 title: event.payload.title,
426 workspaceRoot: event.payload.workspaceRoot,
427 defaultModelSelection: event.payload.defaultModelSelection,
428 scripts: event.payload.scripts,
429 createdAt: event.payload.createdAt,
430 updatedAt: event.payload.updatedAt,
431 deletedAt: null,
432 });
433 const projects =
434 existingIndex >= 0
435 ? state.projects.map((project, index) =>
436 index === existingIndex ? nextProject : project,
437 )
438 : [...state.projects, nextProject];
439 return { ...state, projects };
440 }
441
442 case "project.meta-updated": {
443 const projects = updateProject(state.projects, event.payload.projectId, (project) => ({
444 ...project,
445 ...(event.payload.title !== undefined ? { name: event.payload.title } : {}),
446 ...(event.payload.workspaceRoot !== undefined ? { cwd: event.payload.workspaceRoot } : {}),
447 ...(event.payload.defaultModelSelection !== undefined
448 ? {
449 defaultModelSelection: event.payload.defaultModelSelection
450 ? normalizeModelSelection(event.payload.defaultModelSelection)
451 : null,
452 }
453 : {}),
454 ...(event.payload.scripts !== undefined
455 ? { scripts: mapProjectScripts(event.payload.scripts) }
456 : {}),
457 updatedAt: event.payload.updatedAt,
458 }));
459 return projects === state.projects ? state : { ...state, projects };
460 }
461
462 case "project.deleted": {
463 const projects = state.projects.filter((project) => project.id !== event.payload.projectId);
464 return projects.length === state.projects.length ? state : { ...state, projects };
465 }
466
467 case "thread.created": {
468 const existing = state.threads.find((thread) => thread.id === event.payload.threadId);
469 const nextThread = mapThread({
470 id: event.payload.threadId,
471 projectId: event.payload.projectId,
472 title: event.payload.title,
473 modelSelection: event.payload.modelSelection,
474 runtimeMode: event.payload.runtimeMode,
475 interactionMode: event.payload.interactionMode,
476 branch: event.payload.branch,
477 worktreePath: event.payload.worktreePath,
478 latestTurn: null,
479 createdAt: event.payload.createdAt,
480 updatedAt: event.payload.updatedAt,
481 archivedAt: null,
482 deletedAt: null,
483 messages: [],
484 proposedPlans: [],
485 activities: [],
486 checkpoints: [],
487 session: null,
488 });
489 const threads = existing
490 ? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
491 : [...state.threads, nextThread];
492 return { ...state, threads };
493 }
494
495 case "thread.deleted": {
496 const threads = state.threads.filter((thread) => thread.id !== event.payload.threadId);
497 return threads.length === state.threads.length ? state : { ...state, threads };
498 }
499
500 case "thread.archived": {
501 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
502 ...thread,
503 archivedAt: event.payload.archivedAt,
504 updatedAt: event.payload.updatedAt,
505 }));
506 return threads === state.threads ? state : { ...state, threads };
507 }
508
509 case "thread.unarchived": {
510 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
511 ...thread,
512 archivedAt: null,
513 updatedAt: event.payload.updatedAt,
514 }));
515 return threads === state.threads ? state : { ...state, threads };
516 }
517
518 case "thread.meta-updated": {
519 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
520 ...thread,
521 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
522 ...(event.payload.modelSelection !== undefined
523 ? { modelSelection: normalizeModelSelection(event.payload.modelSelection) }
524 : {}),
525 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
526 ...(event.payload.worktreePath !== undefined
527 ? { worktreePath: event.payload.worktreePath }
528 : {}),
529 updatedAt: event.payload.updatedAt,
530 }));
531 return threads === state.threads ? state : { ...state, threads };
532 }
533
534 case "thread.runtime-mode-set": {
535 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
536 ...thread,
537 runtimeMode: event.payload.runtimeMode,
538 updatedAt: event.payload.updatedAt,
539 }));
540 return threads === state.threads ? state : { ...state, threads };
541 }
542
543 case "thread.interaction-mode-set": {
544 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
545 ...thread,
546 interactionMode: event.payload.interactionMode,
547 updatedAt: event.payload.updatedAt,
548 }));
549 return threads === state.threads ? state : { ...state, threads };
550 }
551
552 case "thread.turn-start-requested": {
553 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
554 ...thread,
555 ...(event.payload.modelSelection !== undefined
556 ? { modelSelection: normalizeModelSelection(event.payload.modelSelection) }
557 : {}),
558 runtimeMode: event.payload.runtimeMode,
559 interactionMode: event.payload.interactionMode,
560 pendingSourceProposedPlan: event.payload.sourceProposedPlan,
561 updatedAt: event.occurredAt,
562 }));
563 return threads === state.threads ? state : { ...state, threads };
564 }
565
566 case "thread.turn-interrupt-requested": {
567 if (event.payload.turnId === undefined) {
568 return state;
569 }
570 const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
571 const latestTurn = thread.latestTurn;
572 if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
573 return thread;
574 }
575 return {
576 ...thread,
577 latestTurn: buildLatestTurn({
578 previous: latestTurn,
579 turnId: event.payload.turnId,
580 state: "interrupted",
581 requestedAt: latestTurn.requestedAt,
582 startedAt: latestTurn.startedAt ?? event.payload.createdAt,
583 completedAt: latestTurn.completedAt ?? event.payload.createdAt,
584 assistantMessageId: latestTurn.assistantMessageId,
585 }),
586 updatedAt: event.occurredAt,
587 };
588 });
589 return threads === state.threads ? state : { ...state, threads };
590 }
591
592 case "thread.message-sent": {
593 const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
594 const message = mapMessage({
595 id: event.payload.messageId,
596 role: event.payload.role,
597 text: event.payload.text,
598 ...(event.payload.attachments !== undefined
599 ? { attachments: event.payload.attachments }
600 : {}),
601 turnId: event.payload.turnId,
602 streaming: event.payload.streaming,
603 createdAt: event.payload.createdAt,
604 updatedAt: event.payload.updatedAt,
605 });
606 const existingMessage = thread.messages.find((entry) => entry.id === message.id);
607 const messages = existingMessage
608 ? thread.messages.map((entry) =>
609 entry.id !== message.id
610 ? entry
611 : {
612 ...entry,
613 text: message.streaming
614 ? `${entry.text}${message.text}`
615 : message.text.length > 0
616 ? message.text
617 : entry.text,
618 streaming: message.streaming,
619 ...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
620 ...(message.streaming
621 ? entry.completedAt !== undefined
622 ? { completedAt: entry.completedAt }
623 : {}
624 : message.completedAt !== undefined
625 ? { completedAt: message.completedAt }
626 : {}),
627 ...(message.attachments !== undefined
628 ? { attachments: message.attachments }
629 : {}),
630 },
631 )
632 : [...thread.messages, message];
633 const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);
634 const turnDiffSummaries =
635 event.payload.role === "assistant" && event.payload.turnId !== null
636 ? rebindTurnDiffSummariesForAssistantMessage(
637 thread.turnDiffSummaries,
638 event.payload.turnId,
639 event.payload.messageId,
640 )
641 : thread.turnDiffSummaries;
642 const latestTurn: Thread["latestTurn"] =
643 event.payload.role === "assistant" &&
644 event.payload.turnId !== null &&
645 (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
646 ? buildLatestTurn({
647 previous: thread.latestTurn,
648 turnId: event.payload.turnId,
649 state: event.payload.streaming
650 ? "running"
651 : thread.latestTurn?.state === "interrupted"
652 ? "interrupted"
653 : thread.latestTurn?.state === "error"
654 ? "error"
655 : "completed",
656 requestedAt:
657 thread.latestTurn?.turnId === event.payload.turnId
658 ? thread.latestTurn.requestedAt
659 : event.payload.createdAt,
660 startedAt:
661 thread.latestTurn?.turnId === event.payload.turnId
662 ? (thread.latestTurn.startedAt ?? event.payload.createdAt)
663 : event.payload.createdAt,
664 sourceProposedPlan: thread.pendingSourceProposedPlan,
665 completedAt: event.payload.streaming
666 ? thread.latestTurn?.turnId === event.payload.turnId
667 ? (thread.latestTurn.completedAt ?? null)
668 : null
669 : event.payload.updatedAt,
670 assistantMessageId: event.payload.messageId,
671 })
672 : thread.latestTurn;
673 return {
674 ...thread,
675 messages: cappedMessages,
676 turnDiffSummaries,
677 latestTurn,
678 updatedAt: event.occurredAt,
679 };
680 });
681 return threads === state.threads ? state : { ...state, threads };
682 }
683
684 case "thread.session-set": {
685 const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
686 ...thread,
687 session: mapSession(event.payload.session),
688 error: event.payload.session.lastError ?? null,
689 latestTurn:
690 event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
691 ? buildLatestTurn({
692 previous: thread.latestTurn,
693 turnId: event.payload.session.activeTurnId,
694 state: "running",
695 requestedAt:
696 thread.latestTurn?.turnId === event.payload.session.activeTurnId
697 ? thread.latestTurn.requestedAt
698 : event.payload.session.updatedAt,
699 startedAt:
700 thread.latestTurn?.turnId === event.payload.session.activeTurnId
701 ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt)
702 : event.payload.session.updatedAt,
703 completedAt: null,
704 assistantMessageId:
705 thread.latestTurn?.turnId === event.payload.session.activeTurnId
706 ? thread.latestTurn.assistantMessageId
707 : null,
708 sourceProposedPlan: thread.pendingSourceProposedPlan,
709 })
710 : thread.latestTurn,
711 updatedAt: event.occurredAt,
712 }));
713 return threads === state.threads ? state : { ...state, threads };
714 }
715
716 case "thread.session-stop-requested": {
717 const threads = updateThread(state.threads, event.payload.threadId, (thread) =>
718 thread.session === null
719 ? thread
720 : {
721 ...thread,
722 session: {
723 ...thread.session,
724 status: "closed",
725 orchestrationStatus: "stopped",
726 activeTurnId: undefined,
727 updatedAt: event.payload.createdAt,
728 },
729 updatedAt: event.occurredAt,
730 },
731 );
732 return threads === state.threads ? state : { ...state, threads };
733 }
734
735 case "thread.proposed-plan-upserted": {
736 const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
737 const proposedPlan = mapProposedPlan(event.payload.proposedPlan);
738 const proposedPlans = [
739 ...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id),
740 proposedPlan,
741 ]
742 .toSorted(
743 (left, right) =>
744 left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
745 )
746 .slice(-MAX_THREAD_PROPOSED_PLANS);
747 return {
748 ...thread,
749 proposedPlans,
750 updatedAt: event.occurredAt,
751 };
752 });
753 return threads === state.threads ? state : { ...state, threads };
754 }
755
756 case "thread.turn-diff-completed": {
757 const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
758 const checkpoint = mapTurnDiffSummary({
759 turnId: event.payload.turnId,
760 checkpointTurnCount: event.payload.checkpointTurnCount,
761 checkpointRef: event.payload.checkpointRef,
762 status: event.payload.status,
763 files: event.payload.files,
764 assistantMessageId: event.payload.assistantMessageId,
765 completedAt: event.payload.completedAt,
766 });
767 const existing = thread.turnDiffSummaries.find(
768 (entry) => entry.turnId === checkpoint.turnId,
769 );
770 if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
771 return thread;
772 }
773 const turnDiffSummaries = [
774 ...thread.turnDiffSummaries.filter((entry) => entry.turnId !== checkpoint.turnId),
775 checkpoint,
776 ]
777 .toSorted(
778 (left, right) =>
779 (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) -
780 (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
781 )
782 .slice(-MAX_THREAD_CHECKPOINTS);
783 const latestTurn =
784 thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
785 ? buildLatestTurn({
786 previous: thread.latestTurn,
787 turnId: event.payload.turnId,
788 state: checkpointStatusToLatestTurnState(event.payload.status),
789 requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
790 startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
791 completedAt: event.payload.completedAt,
792 assistantMessageId: event.payload.assistantMessageId,
793 sourceProposedPlan: thread.pendingSourceProposedPlan,
794 })
795 : thread.latestTurn;
796 return {
797 ...thread,
798 turnDiffSummaries,
799 latestTurn,
800 updatedAt: event.occurredAt,
801 };
802 });
803 return threads === state.threads ? state : { ...state, threads };
804 }
805
806 case "thread.reverted": {
807 const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
808 const turnDiffSummaries = thread.turnDiffSummaries
809 .filter(
810 (entry) =>
811 entry.checkpointTurnCount !== undefined &&
812 entry.checkpointTurnCount <= event.payload.turnCount,
813 )
814 .toSorted(
815 (left, right) =>
816 (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) -
817 (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
818 )
819 .slice(-MAX_THREAD_CHECKPOINTS);
820 const retainedTurnIds = new Set(turnDiffSummaries.map((entry) => entry.turnId));
821 const messages = retainThreadMessagesAfterRevert(
822 thread.messages,
823 retainedTurnIds,
824 event.payload.turnCount,
825 ).slice(-MAX_THREAD_MESSAGES);
826 const proposedPlans = retainThreadProposedPlansAfterRevert(
827 thread.proposedPlans,
828 retainedTurnIds,
829 ).slice(-MAX_THREAD_PROPOSED_PLANS);
830 const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
831 const latestCheckpoint = turnDiffSummaries.at(-1) ?? null;
832
833 return {
834 ...thread,
835 turnDiffSummaries,
836 messages,
837 proposedPlans,
838 activities,
839 pendingSourceProposedPlan: undefined,
840 latestTurn:
841 latestCheckpoint === null
842 ? null
843 : {
844 turnId: latestCheckpoint.turnId,
845 state: checkpointStatusToLatestTurnState(
846 (latestCheckpoint.status ?? "ready") as "ready" | "missing" | "error",
847 ),
848 requestedAt: latestCheckpoint.completedAt,
849 startedAt: latestCheckpoint.completedAt,
850 completedAt: latestCheckpoint.completedAt,
851 assistantMessageId: latestCheckpoint.assistantMessageId ?? null,
852 },
853 updatedAt: event.occurredAt,
854 };
855 });
856 return threads === state.threads ? state : { ...state, threads };
857 }
858
859 case "thread.activity-appended": {
860 const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
861 const activities = [
862 ...thread.activities.filter((activity) => activity.id !== event.payload.activity.id),
863 { ...event.payload.activity },
864 ]
865 .toSorted(compareActivities)
866 .slice(-MAX_THREAD_ACTIVITIES);
867 return {
868 ...thread,
869 activities,
870 updatedAt: event.occurredAt,
871 };
872 });
873 return threads === state.threads ? state : { ...state, threads };
874 }
875
876 case "thread.approval-response-requested":
877 case "thread.user-input-response-requested":
878 return state;
879 }
880
881 return state;
882}
883
884export function applyOrchestrationEvents(
885 state: AppState,
886 events: ReadonlyArray<OrchestrationEvent>,
887): AppState {
888 if (events.length === 0) {
889 return state;
890 }
891 return events.reduce((nextState, event) => applyOrchestrationEvent(nextState, event), state);
892}
893
894export const selectProjectById =
895 (projectId: Project["id"] | null | undefined) =>
896 (state: AppState): Project | undefined =>
897 projectId ? state.projects.find((project) => project.id === projectId) : undefined;
898
899export const selectThreadById =
900 (threadId: ThreadId | null | undefined) =>
901 (state: AppState): Thread | undefined =>
902 threadId ? state.threads.find((thread) => thread.id === threadId) : undefined;
903
904export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
905 const threads = updateThread(state.threads, threadId, (t) => {
906 if (t.error === error) return t;
907 return { ...t, error };
908 });
909 return threads === state.threads ? state : { ...state, threads };
910}
911
912export function setThreadBranch(
913 state: AppState,
914 threadId: ThreadId,
915 branch: string | null,
916 worktreePath: string | null,
917): AppState {
918 const threads = updateThread(state.threads, threadId, (t) => {
919 if (t.branch === branch && t.worktreePath === worktreePath) return t;
920 const cwdChanged = t.worktreePath !== worktreePath;
921 return {
922 ...t,
923 branch,
924 worktreePath,
925 ...(cwdChanged ? { session: null } : {}),
926 };
927 });
928 return threads === state.threads ? state : { ...state, threads };
929}
930
931// ── Zustand store ────────────────────────────────────────────────────
932
933interface AppStore extends AppState {
934 syncServerReadModel: (readModel: OrchestrationReadModel) => void;
935 applyOrchestrationEvent: (event: OrchestrationEvent) => void;
936 applyOrchestrationEvents: (events: ReadonlyArray<OrchestrationEvent>) => void;
937 setError: (threadId: ThreadId, error: string | null) => void;
938 setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
939}
940
941export const useStore = create<AppStore>((set) => ({
942 ...initialState,
943 syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
944 applyOrchestrationEvent: (event) => set((state) => applyOrchestrationEvent(state, event)),
945 applyOrchestrationEvents: (events) => set((state) => applyOrchestrationEvents(state, events)),
946 setError: (threadId, error) => set((state) => setError(state, threadId, error)),
947 setThreadBranch: (threadId, branch, worktreePath) =>
948 set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
949}));