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

store.ts

1,161 lines40.0 KB

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