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