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

store.ts

405 lines13.9 KB

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