Open History to see the last commit
1import {
2 type Dispatch,
3 type ReactNode,
4 createContext,
5 createElement,
6 useContext,
7 useEffect,
8 useReducer,
9} from "react";
10
11import type { ProviderEvent, ProviderSession } from "@acme/contracts";
12import { resolveModelSlug } from "./model-logic";
13import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
14import {
15 applyEventToMessages,
16 asObject,
17 asString,
18 evolveSession,
19} from "./session-logic";
20import {
21 DEFAULT_RUNTIME_MODE,
22 type Project,
23 type RuntimeMode,
24 type Thread,
25} from "./types";
26
27// ── Actions ──────────────────────────────────────────────────────────
28
29type Action =
30 | { type: "ADD_PROJECT"; project: Project }
31 | { type: "TOGGLE_PROJECT"; projectId: string }
32 | { type: "ADD_THREAD"; thread: Thread }
33 | { type: "SET_ACTIVE_THREAD"; threadId: string }
34 | { type: "TOGGLE_DIFF" }
35 | {
36 type: "APPLY_EVENT";
37 event: ProviderEvent;
38 activeAssistantItemRef: { current: string | null };
39 }
40 | { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
41 | { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
42 | { type: "SET_ERROR"; threadId: string; error: string | null }
43 | { type: "SET_THREAD_TITLE"; threadId: string; title: string }
44 | { type: "SET_THREAD_MODEL"; threadId: string; model: string }
45 | { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
46
47// ── State ────────────────────────────────────────────────────────────
48
49export interface AppState {
50 projects: Project[];
51 threads: Thread[];
52 activeThreadId: string | null;
53 runtimeMode: RuntimeMode;
54 diffOpen: boolean;
55}
56
57const PERSISTED_STATE_KEY = "codething:renderer-state:v3";
58const LEGACY_PERSISTED_STATE_KEYS = [
59 "codething:renderer-state:v2",
60 "codething:renderer-state:v1",
61] as const;
62
63const initialState: AppState = {
64 projects: [],
65 threads: [],
66 activeThreadId: null,
67 runtimeMode: DEFAULT_RUNTIME_MODE,
68 diffOpen: false,
69};
70
71// ── Helpers ──────────────────────────────────────────────────────────
72
73function readPersistedState(): AppState {
74 if (typeof window === "undefined") return initialState;
75
76 try {
77 const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
78 const [legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
79 const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
80 const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
81 const raw = rawCurrent ?? rawLegacyV2 ?? rawLegacyV1;
82 if (!raw) return initialState;
83 const hydrated = hydratePersistedState(
84 raw,
85 !rawCurrent && !rawLegacyV2 && Boolean(rawLegacyV1),
86 );
87 if (!hydrated) return initialState;
88
89 return { ...hydrated, diffOpen: false };
90 } catch {
91 return initialState;
92 }
93}
94
95function persistState(state: AppState): void {
96 if (typeof window === "undefined") return;
97
98 try {
99 window.localStorage.setItem(
100 PERSISTED_STATE_KEY,
101 JSON.stringify(toPersistedState(state)),
102 );
103 for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
104 window.localStorage.removeItem(legacyKey);
105 }
106 } catch {
107 // Ignore quota/storage errors to avoid breaking chat UX.
108 }
109}
110
111function updateThread(
112 threads: Thread[],
113 threadId: string,
114 updater: (t: Thread) => Thread,
115): Thread[] {
116 return threads.map((t) => (t.id === threadId ? updater(t) : t));
117}
118
119function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
120 return threads.find((t) => t.session?.sessionId === sessionId);
121}
122
123function getEventTurnId(event: ProviderEvent): string | undefined {
124 if (event.turnId) return event.turnId;
125 const payload = asObject(event.payload);
126 const turn = asObject(payload?.turn);
127 return asString(turn?.id);
128}
129
130function durationMs(startIso: string, endIso: string): number | undefined {
131 const start = Date.parse(startIso);
132 const end = Date.parse(endIso);
133 if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
134 return undefined;
135 }
136
137 return end - start;
138}
139
140function updateTurnFields(
141 thread: Thread,
142 event: ProviderEvent,
143): Partial<Thread> {
144 if (event.method === "turn/started") {
145 return {
146 latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
147 latestTurnStartedAt: event.createdAt,
148 latestTurnCompletedAt: undefined,
149 latestTurnDurationMs: undefined,
150 };
151 }
152
153 if (event.method === "turn/completed") {
154 const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
155 const startedAt =
156 completedTurnId && completedTurnId === thread.latestTurnId
157 ? thread.latestTurnStartedAt
158 : undefined;
159 const elapsed =
160 startedAt && startedAt.length > 0
161 ? durationMs(startedAt, event.createdAt)
162 : undefined;
163
164 return {
165 latestTurnId: completedTurnId ?? thread.latestTurnId,
166 latestTurnCompletedAt: event.createdAt,
167 latestTurnDurationMs: elapsed,
168 };
169 }
170
171 return {};
172}
173
174// ── Reducer ──────────────────────────────────────────────────────────
175
176function reducer(state: AppState, action: Action): AppState {
177 switch (action.type) {
178 case "ADD_PROJECT":
179 return {
180 ...state,
181 projects: [
182 ...state.projects,
183 {
184 ...action.project,
185 model: resolveModelSlug(action.project.model),
186 },
187 ],
188 };
189
190 case "TOGGLE_PROJECT":
191 return {
192 ...state,
193 projects: state.projects.map((p) =>
194 p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
195 ),
196 };
197
198 case "ADD_THREAD":
199 return {
200 ...state,
201 threads: [
202 ...state.threads,
203 {
204 ...action.thread,
205 model: resolveModelSlug(action.thread.model),
206 },
207 ],
208 activeThreadId: action.thread.id,
209 };
210
211 case "SET_ACTIVE_THREAD":
212 return { ...state, activeThreadId: action.threadId };
213
214 case "TOGGLE_DIFF":
215 return { ...state, diffOpen: !state.diffOpen };
216
217 case "APPLY_EVENT": {
218 const { event, activeAssistantItemRef } = action;
219 const target = findThreadBySessionId(state.threads, event.sessionId);
220 if (!target) return state;
221
222 return {
223 ...state,
224 threads: updateThread(state.threads, target.id, (t) => ({
225 ...t,
226 session: t.session ? evolveSession(t.session, event) : t.session,
227 messages: applyEventToMessages(
228 t.messages,
229 event,
230 activeAssistantItemRef,
231 ),
232 events: [event, ...t.events],
233 error:
234 event.kind === "error" && event.message ? event.message : t.error,
235 ...updateTurnFields(t, event),
236 })),
237 };
238 }
239
240 case "UPDATE_SESSION":
241 return {
242 ...state,
243 threads: updateThread(state.threads, action.threadId, (t) => ({
244 ...t,
245 session: action.session,
246 events: [],
247 error: null,
248 latestTurnId: undefined,
249 latestTurnStartedAt: undefined,
250 latestTurnCompletedAt: undefined,
251 latestTurnDurationMs: undefined,
252 })),
253 };
254
255 case "PUSH_USER_MESSAGE":
256 return {
257 ...state,
258 threads: updateThread(state.threads, action.threadId, (t) => ({
259 ...t,
260 messages: [
261 ...t.messages,
262 {
263 id: action.id,
264 role: "user" as const,
265 text: action.text,
266 createdAt: new Date().toISOString(),
267 streaming: false,
268 },
269 ],
270 })),
271 };
272
273 case "SET_ERROR":
274 return {
275 ...state,
276 threads: updateThread(state.threads, action.threadId, (t) => ({
277 ...t,
278 error: action.error,
279 })),
280 };
281
282 case "SET_THREAD_TITLE":
283 return {
284 ...state,
285 threads: updateThread(state.threads, action.threadId, (t) => ({
286 ...t,
287 title: action.title,
288 })),
289 };
290
291 case "SET_THREAD_MODEL":
292 return {
293 ...state,
294 threads: updateThread(state.threads, action.threadId, (t) => ({
295 ...t,
296 model: resolveModelSlug(action.model),
297 })),
298 };
299
300 case "SET_RUNTIME_MODE":
301 return {
302 ...state,
303 runtimeMode: action.mode,
304 };
305
306 default:
307 return state;
308 }
309}
310
311// ── Context ──────────────────────────────────────────────────────────
312
313const StoreContext = createContext<{
314 state: AppState;
315 dispatch: Dispatch<Action>;
316}>({ state: initialState, dispatch: () => {} });
317
318export function StoreProvider({ children }: { children: ReactNode }) {
319 const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
320
321 useEffect(() => {
322 persistState(state);
323 }, [state]);
324
325 return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
326}
327
328export function useStore() {
329 return useContext(StoreContext);
330}