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 titleSummaryState: thread.titleSummaryState,
257 model: resolveModelSlugForProvider(
258 inferProviderForThreadModel({
259 model: thread.model,
260 sessionProviderName: thread.session?.providerName ?? null,
261 }),
262 thread.model,
263 ),
264 runtimeMode: thread.runtimeMode,
265 interactionMode: thread.interactionMode,
266 session: thread.session
267 ? {
268 provider: toLegacyProvider(thread.session.providerName),
269 status: toLegacySessionStatus(thread.session.status),
270 orchestrationStatus: thread.session.status,
271 activeTurnId: thread.session.activeTurnId ?? undefined,
272 createdAt: thread.session.updatedAt,
273 updatedAt: thread.session.updatedAt,
274 ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
275 }
276 : null,
277 messages: thread.messages.map((message) => {
278 const attachments = message.attachments?.map((attachment) => ({
279 type: "image" as const,
280 id: attachment.id,
281 name: attachment.name,
282 mimeType: attachment.mimeType,
283 sizeBytes: attachment.sizeBytes,
284 previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
285 }));
286 const normalizedMessage: ChatMessage = {
287 id: message.id,
288 role: message.role,
289 text: message.text,
290 createdAt: message.createdAt,
291 streaming: message.streaming,
292 ...(message.streaming ? {} : { completedAt: message.updatedAt }),
293 ...(attachments && attachments.length > 0 ? { attachments } : {}),
294 };
295 return normalizedMessage;
296 }),
297 proposedPlans: thread.proposedPlans.map((proposedPlan) => ({
298 id: proposedPlan.id,
299 turnId: proposedPlan.turnId,
300 planMarkdown: proposedPlan.planMarkdown,
301 implementedAt: proposedPlan.implementedAt,
302 implementationThreadId: proposedPlan.implementationThreadId,
303 createdAt: proposedPlan.createdAt,
304 updatedAt: proposedPlan.updatedAt,
305 })),
306 error: thread.session?.lastError ?? null,
307 createdAt: thread.createdAt,
308 latestTurn: thread.latestTurn,
309 lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
310 branch: thread.branch,
311 worktreePath: thread.worktreePath,
312 turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
313 turnId: checkpoint.turnId,
314 completedAt: checkpoint.completedAt,
315 status: checkpoint.status,
316 assistantMessageId: checkpoint.assistantMessageId ?? undefined,
317 checkpointTurnCount: checkpoint.checkpointTurnCount,
318 checkpointRef: checkpoint.checkpointRef,
319 files: checkpoint.files.map((file) => ({ ...file })),
320 })),
321 activities: thread.activities.map((activity) => ({ ...activity })),
322 };
323 });
324 return {
325 ...state,
326 projects,
327 threads,
328 threadsHydrated: true,
329 };
330}
331
332export function markThreadVisited(
333 state: AppState,
334 threadId: ThreadId,
335 visitedAt?: string,
336): AppState {
337 const at = visitedAt ?? new Date().toISOString();
338 const visitedAtMs = Date.parse(at);
339 const threads = updateThread(state.threads, threadId, (thread) => {
340 const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
341 if (
342 Number.isFinite(previousVisitedAtMs) &&
343 Number.isFinite(visitedAtMs) &&
344 previousVisitedAtMs >= visitedAtMs
345 ) {
346 return thread;
347 }
348 return { ...thread, lastVisitedAt: at };
349 });
350 return threads === state.threads ? state : { ...state, threads };
351}
352
353export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
354 const threads = updateThread(state.threads, threadId, (thread) => {
355 if (!thread.latestTurn?.completedAt) return thread;
356 const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
357 if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
358 const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
359 if (thread.lastVisitedAt === unreadVisitedAt) return thread;
360 return { ...thread, lastVisitedAt: unreadVisitedAt };
361 });
362 return threads === state.threads ? state : { ...state, threads };
363}
364
365export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
366 return {
367 ...state,
368 projects: state.projects.map((p) => (p.id === projectId ? { ...p, expanded: !p.expanded } : p)),
369 };
370}
371
372export function setProjectExpanded(
373 state: AppState,
374 projectId: Project["id"],
375 expanded: boolean,
376): AppState {
377 let changed = false;
378 const projects = state.projects.map((p) => {
379 if (p.id !== projectId || p.expanded === expanded) return p;
380 changed = true;
381 return { ...p, expanded };
382 });
383 return changed ? { ...state, projects } : state;
384}
385
386export function reorderProjects(
387 state: AppState,
388 draggedProjectId: Project["id"],
389 targetProjectId: Project["id"],
390): AppState {
391 if (draggedProjectId === targetProjectId) return state;
392 const draggedIndex = state.projects.findIndex((project) => project.id === draggedProjectId);
393 const targetIndex = state.projects.findIndex((project) => project.id === targetProjectId);
394 if (draggedIndex < 0 || targetIndex < 0) return state;
395 const projects = [...state.projects];
396 const [draggedProject] = projects.splice(draggedIndex, 1);
397 if (!draggedProject) return state;
398 projects.splice(targetIndex, 0, draggedProject);
399 return { ...state, projects };
400}
401
402export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
403 const threads = updateThread(state.threads, threadId, (t) => {
404 if (t.error === error) return t;
405 return { ...t, error };
406 });
407 return threads === state.threads ? state : { ...state, threads };
408}
409
410export function setThreadBranch(
411 state: AppState,
412 threadId: ThreadId,
413 branch: string | null,
414 worktreePath: string | null,
415): AppState {
416 const threads = updateThread(state.threads, threadId, (t) => {
417 if (t.branch === branch && t.worktreePath === worktreePath) return t;
418 const cwdChanged = t.worktreePath !== worktreePath;
419 return {
420 ...t,
421 branch,
422 worktreePath,
423 ...(cwdChanged ? { session: null } : {}),
424 };
425 });
426 return threads === state.threads ? state : { ...state, threads };
427}
428
429// ── Zustand store ────────────────────────────────────────────────────
430
431interface AppStore extends AppState {
432 syncServerReadModel: (readModel: OrchestrationReadModel) => void;
433 markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
434 markThreadUnread: (threadId: ThreadId) => void;
435 toggleProject: (projectId: Project["id"]) => void;
436 setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
437 reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void;
438 setError: (threadId: ThreadId, error: string | null) => void;
439 setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
440}
441
442export const useStore = create<AppStore>((set) => ({
443 ...readPersistedState(),
444 syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
445 markThreadVisited: (threadId, visitedAt) =>
446 set((state) => markThreadVisited(state, threadId, visitedAt)),
447 markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)),
448 toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
449 setProjectExpanded: (projectId, expanded) =>
450 set((state) => setProjectExpanded(state, projectId, expanded)),
451 reorderProjects: (draggedProjectId, targetProjectId) =>
452 set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
453 setError: (threadId, error) => set((state) => setError(state, threadId, error)),
454 setThreadBranch: (threadId, branch, worktreePath) =>
455 set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
456}));
457
458// Persist state changes with debouncing to avoid localStorage thrashing
459useStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
460
461// Flush pending writes synchronously before page unload to prevent data loss.
462if (typeof window !== "undefined") {
463 window.addEventListener("beforeunload", () => {
464 debouncedPersistState.flush();
465 });
466}
467
468export function StoreProvider({ children }: { children: ReactNode }) {
469 useEffect(() => {
470 persistState(useStore.getState());
471 }, []);
472 return createElement(Fragment, null, children);
473}