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

store.ts

413 lines13.7 KB

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