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

store.ts

452 lines15.0 KB

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