Open History to see the last commit
1import { Fragment, type ReactNode, createElement, useEffect } from "react";
2import {
3 DEFAULT_MODEL_BY_PROVIDER,
4 type ProviderKind,
5 ThreadId,
6 type OrchestrationReadModel,
7 type OrchestrationSessionStatus,
8} from "@t3tools/contracts";
9import {
10 inferProviderForModel,
11 resolveModelSlug,
12 resolveModelSlugForProvider,
13} from "@t3tools/shared/model";
14import { create } from "zustand";
15import { type ChatMessage, type Project, type Thread } from "./types";
16import { Debouncer } from "@tanstack/react-pacer";
17
18// ── State ────────────────────────────────────────────────────────────
19
20export interface AppState {
21 projects: Project[];
22 threads: Thread[];
23 threadsHydrated: boolean;
24}
25
26const PERSISTED_STATE_KEY = "t3code:renderer-state:v8";
27const LEGACY_PERSISTED_STATE_KEYS = [
28 "t3code:renderer-state:v7",
29 "t3code:renderer-state:v6",
30 "t3code:renderer-state:v5",
31 "t3code:renderer-state:v4",
32 "t3code:renderer-state:v3",
33 "codething:renderer-state:v4",
34 "codething:renderer-state:v3",
35 "codething:renderer-state:v2",
36 "codething:renderer-state:v1",
37] as const;
38
39const initialState: AppState = {
40 projects: [],
41 threads: [],
42 threadsHydrated: false,
43};
44const persistedExpandedProjectCwds = new Set<string>();
45const persistedProjectOrderCwds: string[] = [];
46
47// ── Persist helpers ──────────────────────────────────────────────────
48
49function readPersistedState(): AppState {
50 if (typeof window === "undefined") return initialState;
51 try {
52 const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
53 if (!raw) return initialState;
54 const parsed = JSON.parse(raw) as {
55 expandedProjectCwds?: string[];
56 projectOrderCwds?: string[];
57 };
58 persistedExpandedProjectCwds.clear();
59 persistedProjectOrderCwds.length = 0;
60 for (const cwd of parsed.expandedProjectCwds ?? []) {
61 if (typeof cwd === "string" && cwd.length > 0) {
62 persistedExpandedProjectCwds.add(cwd);
63 }
64 }
65 for (const cwd of parsed.projectOrderCwds ?? []) {
66 if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
67 persistedProjectOrderCwds.push(cwd);
68 }
69 }
70 return { ...initialState };
71 } catch {
72 return initialState;
73 }
74}
75
76let legacyKeysCleanedUp = false;
77
78function persistState(state: AppState): void {
79 if (typeof window === "undefined") return;
80 try {
81 window.localStorage.setItem(
82 PERSISTED_STATE_KEY,
83 JSON.stringify({
84 expandedProjectCwds: state.projects
85 .filter((project) => project.expanded)
86 .map((project) => project.cwd),
87 projectOrderCwds: state.projects.map((project) => project.cwd),
88 }),
89 );
90 if (!legacyKeysCleanedUp) {
91 legacyKeysCleanedUp = true;
92 for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
93 window.localStorage.removeItem(legacyKey);
94 }
95 }
96 } catch {
97 // Ignore quota/storage errors to avoid breaking chat UX.
98 }
99}
100const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
101
102// ── Pure helpers ──────────────────────────────────────────────────────
103
104function updateThread(
105 threads: Thread[],
106 threadId: ThreadId,
107 updater: (t: Thread) => Thread,
108): Thread[] {
109 let changed = false;
110 const next = threads.map((t) => {
111 if (t.id !== threadId) return t;
112 const updated = updater(t);
113 if (updated !== t) changed = true;
114 return updated;
115 });
116 return changed ? next : threads;
117}
118
119function mapProjectsFromReadModel(
120 incoming: OrchestrationReadModel["projects"],
121 previous: Project[],
122): Project[] {
123 const previousById = new Map(previous.map((project) => [project.id, project] as const));
124 const previousByCwd = new Map(previous.map((project) => [project.cwd, project] as const));
125 const previousOrderById = new Map(previous.map((project, index) => [project.id, index] as const));
126 const previousOrderByCwd = new Map(
127 previous.map((project, index) => [project.cwd, index] as const),
128 );
129 const persistedOrderByCwd = new Map(
130 persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const),
131 );
132 const usePersistedOrder = previous.length === 0;
133
134 const mappedProjects = incoming.map((project) => {
135 const existing = previousById.get(project.id) ?? previousByCwd.get(project.workspaceRoot);
136 return {
137 id: project.id,
138 name: project.title,
139 cwd: project.workspaceRoot,
140 model:
141 existing?.model ??
142 resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL_BY_PROVIDER.codex),
143 expanded:
144 existing?.expanded ??
145 (persistedExpandedProjectCwds.size > 0
146 ? persistedExpandedProjectCwds.has(project.workspaceRoot)
147 : true),
148 scripts: project.scripts.map((script) => ({ ...script })),
149 } satisfies Project;
150 });
151
152 return mappedProjects
153 .map((project, incomingIndex) => {
154 const previousIndex =
155 previousOrderById.get(project.id) ?? previousOrderByCwd.get(project.cwd);
156 const persistedIndex = usePersistedOrder ? persistedOrderByCwd.get(project.cwd) : undefined;
157 const orderIndex =
158 previousIndex ??
159 persistedIndex ??
160 (usePersistedOrder ? persistedProjectOrderCwds.length : previous.length) + incomingIndex;
161 return { project, incomingIndex, orderIndex };
162 })
163 .toSorted((a, b) => {
164 const byOrder = a.orderIndex - b.orderIndex;
165 if (byOrder !== 0) return byOrder;
166 return a.incomingIndex - b.incomingIndex;
167 })
168 .map((entry) => entry.project);
169}
170
171function toLegacySessionStatus(
172 status: OrchestrationSessionStatus,
173): "connecting" | "ready" | "running" | "error" | "closed" {
174 switch (status) {
175 case "starting":
176 return "connecting";
177 case "running":
178 return "running";
179 case "error":
180 return "error";
181 case "ready":
182 case "interrupted":
183 return "ready";
184 case "idle":
185 case "stopped":
186 return "closed";
187 }
188}
189
190function toLegacyProvider(providerName: string | null): ProviderKind {
191 if (providerName === "codex" || providerName === "claudeAgent") {
192 return providerName;
193 }
194 return "codex";
195}
196
197function inferProviderForThreadModel(input: {
198 readonly model: string;
199 readonly sessionProviderName: string | null;
200}): ProviderKind {
201 if (input.sessionProviderName === "codex" || input.sessionProviderName === "claudeAgent") {
202 return input.sessionProviderName;
203 }
204 return inferProviderForModel(input.model);
205}
206
207function resolveWsHttpOrigin(): string {
208 if (typeof window === "undefined") return "";
209 const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
210 const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
211 const wsCandidate =
212 typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
213 ? bridgeWsUrl
214 : typeof envWsUrl === "string" && envWsUrl.length > 0
215 ? envWsUrl
216 : null;
217 if (!wsCandidate) return window.location.origin;
218 try {
219 const wsUrl = new URL(wsCandidate);
220 const protocol =
221 wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
222 return `${protocol}//${wsUrl.host}`;
223 } catch {
224 return window.location.origin;
225 }
226}
227
228function toAttachmentPreviewUrl(rawUrl: string): string {
229 if (rawUrl.startsWith("/")) {
230 return `${resolveWsHttpOrigin()}${rawUrl}`;
231 }
232 return rawUrl;
233}
234
235function attachmentPreviewRoutePath(attachmentId: string): string {
236 return `/attachments/${encodeURIComponent(attachmentId)}`;
237}
238
239// ── Pure state transition functions ────────────────────────────────────
240
241export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState {
242 const projects = mapProjectsFromReadModel(
243 readModel.projects.filter((project) => project.deletedAt === null),
244 state.projects,
245 );
246 const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
247 const threads = readModel.threads
248 .filter((thread) => thread.deletedAt === null)
249 .map((thread) => {
250 const existing = existingThreadById.get(thread.id);
251 return {
252 id: thread.id,
253 codexThreadId: null,
254 projectId: thread.projectId,
255 title: thread.title,
256 model: resolveModelSlugForProvider(
257 inferProviderForThreadModel({
258 model: thread.model,
259 sessionProviderName: thread.session?.providerName ?? null,
260 }),
261 thread.model,
262 ),
263 runtimeMode: thread.runtimeMode,
264 interactionMode: thread.interactionMode,
265 session: thread.session
266 ? {
267 provider: toLegacyProvider(thread.session.providerName),
268 status: toLegacySessionStatus(thread.session.status),
269 orchestrationStatus: thread.session.status,
270 activeTurnId: thread.session.activeTurnId ?? undefined,
271 createdAt: thread.session.updatedAt,
272 updatedAt: thread.session.updatedAt,
273 ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
274 }
275 : null,
276 messages: thread.messages.map((message) => {
277 const attachments = message.attachments?.map((attachment) => ({
278 type: "image" as const,
279 id: attachment.id,
280 name: attachment.name,
281 mimeType: attachment.mimeType,
282 sizeBytes: attachment.sizeBytes,
283 previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
284 }));
285 const normalizedMessage: ChatMessage = {
286 id: message.id,
287 role: message.role,
288 text: message.text,
289 createdAt: message.createdAt,
290 streaming: message.streaming,
291 ...(message.streaming ? {} : { completedAt: message.updatedAt }),
292 ...(attachments && attachments.length > 0 ? { attachments } : {}),
293 };
294 return normalizedMessage;
295 }),
296 proposedPlans: thread.proposedPlans.map((proposedPlan) => ({
297 id: proposedPlan.id,
298 turnId: proposedPlan.turnId,
299 planMarkdown: proposedPlan.planMarkdown,
300 implementedAt: proposedPlan.implementedAt,
301 implementationThreadId: proposedPlan.implementationThreadId,
302 createdAt: proposedPlan.createdAt,
303 updatedAt: proposedPlan.updatedAt,
304 })),
305 error: thread.session?.lastError ?? null,
306 createdAt: thread.createdAt,
307 latestTurn: thread.latestTurn,
308 lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
309 branch: thread.branch,
310 worktreePath: thread.worktreePath,
311 turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
312 turnId: checkpoint.turnId,
313 completedAt: checkpoint.completedAt,
314 status: checkpoint.status,
315 assistantMessageId: checkpoint.assistantMessageId ?? undefined,
316 checkpointTurnCount: checkpoint.checkpointTurnCount,
317 checkpointRef: checkpoint.checkpointRef,
318 files: checkpoint.files.map((file) => ({ ...file })),
319 })),
320 activities: thread.activities.map((activity) => ({ ...activity })),
321 };
322 });
323 return {
324 ...state,
325 projects,
326 threads,
327 threadsHydrated: true,
328 };
329}
330
331export function markThreadVisited(
332 state: AppState,
333 threadId: ThreadId,
334 visitedAt?: string,
335): AppState {
336 const at = visitedAt ?? new Date().toISOString();
337 const visitedAtMs = Date.parse(at);
338 const threads = updateThread(state.threads, threadId, (thread) => {
339 const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
340 if (
341 Number.isFinite(previousVisitedAtMs) &&
342 Number.isFinite(visitedAtMs) &&
343 previousVisitedAtMs >= visitedAtMs
344 ) {
345 return thread;
346 }
347 return { ...thread, lastVisitedAt: at };
348 });
349 return threads === state.threads ? state : { ...state, threads };
350}
351
352export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
353 const threads = updateThread(state.threads, threadId, (thread) => {
354 if (!thread.latestTurn?.completedAt) return thread;
355 const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
356 if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
357 const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
358 if (thread.lastVisitedAt === unreadVisitedAt) return thread;
359 return { ...thread, lastVisitedAt: unreadVisitedAt };
360 });
361 return threads === state.threads ? state : { ...state, threads };
362}
363
364export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
365 return {
366 ...state,
367 projects: state.projects.map((p) => (p.id === projectId ? { ...p, expanded: !p.expanded } : p)),
368 };
369}
370
371export function setProjectExpanded(
372 state: AppState,
373 projectId: Project["id"],
374 expanded: boolean,
375): AppState {
376 let changed = false;
377 const projects = state.projects.map((p) => {
378 if (p.id !== projectId || p.expanded === expanded) return p;
379 changed = true;
380 return { ...p, expanded };
381 });
382 return changed ? { ...state, projects } : state;
383}
384
385export function reorderProjects(
386 state: AppState,
387 draggedProjectId: Project["id"],
388 targetProjectId: Project["id"],
389): AppState {
390 if (draggedProjectId === targetProjectId) return state;
391 const draggedIndex = state.projects.findIndex((project) => project.id === draggedProjectId);
392 const targetIndex = state.projects.findIndex((project) => project.id === targetProjectId);
393 if (draggedIndex < 0 || targetIndex < 0) return state;
394 const projects = [...state.projects];
395 const [draggedProject] = projects.splice(draggedIndex, 1);
396 if (!draggedProject) return state;
397 projects.splice(targetIndex, 0, draggedProject);
398 return { ...state, projects };
399}
400
401export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
402 const threads = updateThread(state.threads, threadId, (t) => {
403 if (t.error === error) return t;
404 return { ...t, error };
405 });
406 return threads === state.threads ? state : { ...state, threads };
407}
408
409export function setThreadBranch(
410 state: AppState,
411 threadId: ThreadId,
412 branch: string | null,
413 worktreePath: string | null,
414): AppState {
415 const threads = updateThread(state.threads, threadId, (t) => {
416 if (t.branch === branch && t.worktreePath === worktreePath) return t;
417 const cwdChanged = t.worktreePath !== worktreePath;
418 return {
419 ...t,
420 branch,
421 worktreePath,
422 ...(cwdChanged ? { session: null } : {}),
423 };
424 });
425 return threads === state.threads ? state : { ...state, threads };
426}
427
428// ── Zustand store ────────────────────────────────────────────────────
429
430interface AppStore extends AppState {
431 syncServerReadModel: (readModel: OrchestrationReadModel) => void;
432 markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
433 markThreadUnread: (threadId: ThreadId) => void;
434 toggleProject: (projectId: Project["id"]) => void;
435 setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
436 reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void;
437 setError: (threadId: ThreadId, error: string | null) => void;
438 setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
439}
440
441export const useStore = create<AppStore>((set) => ({
442 ...readPersistedState(),
443 syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
444 markThreadVisited: (threadId, visitedAt) =>
445 set((state) => markThreadVisited(state, threadId, visitedAt)),
446 markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)),
447 toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
448 setProjectExpanded: (projectId, expanded) =>
449 set((state) => setProjectExpanded(state, projectId, expanded)),
450 reorderProjects: (draggedProjectId, targetProjectId) =>
451 set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
452 setError: (threadId, error) => set((state) => setError(state, threadId, error)),
453 setThreadBranch: (threadId, branch, worktreePath) =>
454 set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
455}));
456
457// Persist state changes with debouncing to avoid localStorage thrashing
458useStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
459
460// Flush pending writes synchronously before page unload to prevent data loss.
461if (typeof window !== "undefined") {
462 window.addEventListener("beforeunload", () => {
463 debouncedPersistState.flush();
464 });
465}
466
467export function StoreProvider({ children }: { children: ReactNode }) {
468 useEffect(() => {
469 persistState(useStore.getState());
470 }, []);
471 return createElement(Fragment, null, children);
472}