Open History to see the last commit
1/**
2 * Unified settings hook.
3 *
4 * Abstracts the split between server-authoritative settings (persisted in
5 * `settings.json` on the server, fetched via `server.getConfig`) and
6 * client-only settings (persisted in localStorage).
7 *
8 * Consumers use `useSettings(selector)` to read, and `useUpdateSettings()` to
9 * write. The hook transparently routes reads/writes to the correct backing
10 * store.
11 */
12import { useCallback, useMemo } from "react";
13import { useQuery, useQueryClient } from "@tanstack/react-query";
14import {
15 ServerSettings,
16 ServerSettingsPatch,
17 ServerConfig,
18 ModelSelection,
19 ThreadEnvMode,
20} from "@t3tools/contracts";
21import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
22import {
23 type ClientSettings,
24 ClientSettingsSchema,
25 DEFAULT_CLIENT_SETTINGS,
26 DEFAULT_UNIFIED_SETTINGS,
27 SidebarProjectSortOrder,
28 SidebarThreadSortOrder,
29 TimestampFormat,
30 UnifiedSettings,
31} from "@t3tools/contracts/settings";
32import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
33import { ensureNativeApi } from "~/nativeApi";
34import { useLocalStorage } from "./useLocalStorage";
35import { normalizeCustomModelSlugs } from "~/modelSelection";
36import { Predicate, Schema, Struct } from "effect";
37import { DeepMutable } from "effect/Types";
38import { deepMerge } from "@t3tools/shared/Struct";
39
40const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
41const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
42
43// ── Key sets for routing patches ─────────────────────────────────────
44
45const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
46
47function splitPatch(patch: Partial<UnifiedSettings>): {
48 serverPatch: ServerSettingsPatch;
49 clientPatch: Partial<ClientSettings>;
50} {
51 const serverPatch: Record<string, unknown> = {};
52 const clientPatch: Record<string, unknown> = {};
53 for (const [key, value] of Object.entries(patch)) {
54 if (SERVER_SETTINGS_KEYS.has(key)) {
55 serverPatch[key] = value;
56 } else {
57 clientPatch[key] = value;
58 }
59 }
60 return {
61 serverPatch: serverPatch as ServerSettingsPatch,
62 clientPatch: clientPatch as Partial<ClientSettings>,
63 };
64}
65
66// ── Hooks ────────────────────────────────────────────────────────────
67
68/**
69 * Read merged settings. Selector narrows the subscription so components
70 * only re-render when the slice they care about changes.
71 */
72
73export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
74 selector?: (s: UnifiedSettings) => T,
75): T {
76 const { data: serverConfig } = useQuery(serverConfigQueryOptions());
77 const [clientSettings] = useLocalStorage(
78 CLIENT_SETTINGS_STORAGE_KEY,
79 DEFAULT_CLIENT_SETTINGS,
80 ClientSettingsSchema,
81 );
82
83 const merged = useMemo<UnifiedSettings>(
84 () => ({
85 ...(serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS),
86 ...clientSettings,
87 }),
88 [serverConfig?.settings, clientSettings],
89 );
90
91 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
92}
93
94/**
95 * Returns an updater that routes each key to the correct backing store.
96 *
97 * Server keys are optimistically patched in the React Query cache, then
98 * persisted via RPC. Client keys go straight to localStorage.
99 */
100export function useUpdateSettings() {
101 const queryClient = useQueryClient();
102 const [, setClientSettings] = useLocalStorage(
103 CLIENT_SETTINGS_STORAGE_KEY,
104 DEFAULT_CLIENT_SETTINGS,
105 ClientSettingsSchema,
106 );
107
108 const updateSettings = useCallback(
109 (patch: Partial<UnifiedSettings>) => {
110 const { serverPatch, clientPatch } = splitPatch(patch);
111
112 if (Object.keys(serverPatch).length > 0) {
113 // Optimistic update of the React Query cache
114 queryClient.setQueryData<ServerConfig>(serverQueryKeys.config(), (old) => {
115 if (!old) return old;
116 return {
117 ...old,
118 settings: deepMerge(old.settings, serverPatch),
119 };
120 });
121 // Fire-and-forget RPC — push will reconcile on success
122 void ensureNativeApi().server.updateSettings(serverPatch);
123 }
124
125 if (Object.keys(clientPatch).length > 0) {
126 setClientSettings((prev) => ({ ...prev, ...clientPatch }));
127 }
128 },
129 [queryClient, setClientSettings],
130 );
131
132 const resetSettings = useCallback(() => {
133 updateSettings(DEFAULT_UNIFIED_SETTINGS);
134 }, [updateSettings]);
135
136 return {
137 updateSettings,
138 resetSettings,
139 };
140}
141
142// ── One-time migration from localStorage ─────────────────────────────
143
144export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
145 const patch: DeepMutable<ServerSettingsPatch> = {};
146
147 if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
148 patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
149 }
150
151 if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
152 patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
153 }
154
155 if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
156 patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
157 }
158
159 if (typeof legacySettings.codexBinaryPath === "string") {
160 patch.providers ??= {};
161 patch.providers.codex ??= {};
162 patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
163 }
164
165 if (typeof legacySettings.codexHomePath === "string") {
166 patch.providers ??= {};
167 patch.providers.codex ??= {};
168 patch.providers.codex.homePath = legacySettings.codexHomePath;
169 }
170
171 if (Array.isArray(legacySettings.customCodexModels)) {
172 patch.providers ??= {};
173 patch.providers.codex ??= {};
174 patch.providers.codex.customModels = normalizeCustomModelSlugs(
175 legacySettings.customCodexModels,
176 new Set<string>(),
177 "codex",
178 );
179 }
180
181 if (Predicate.isString(legacySettings.claudeBinaryPath)) {
182 patch.providers ??= {};
183 patch.providers.claudeAgent ??= {};
184 patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
185 }
186
187 if (Array.isArray(legacySettings.customClaudeModels)) {
188 patch.providers ??= {};
189 patch.providers.claudeAgent ??= {};
190 patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
191 legacySettings.customClaudeModels,
192 new Set<string>(),
193 "claudeAgent",
194 );
195 }
196
197 return patch;
198}
199
200export function buildLegacyClientSettingsMigrationPatch(
201 legacySettings: Record<string, unknown>,
202): Partial<DeepMutable<ClientSettings>> {
203 const patch: Partial<DeepMutable<ClientSettings>> = {};
204
205 if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
206 patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
207 }
208
209 if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
210 patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
211 }
212
213 if (Predicate.isBoolean(legacySettings.diffWordWrap)) {
214 patch.diffWordWrap = legacySettings.diffWordWrap;
215 }
216
217 if (Schema.is(SidebarProjectSortOrder)(legacySettings.sidebarProjectSortOrder)) {
218 patch.sidebarProjectSortOrder = legacySettings.sidebarProjectSortOrder;
219 }
220
221 if (Schema.is(SidebarThreadSortOrder)(legacySettings.sidebarThreadSortOrder)) {
222 patch.sidebarThreadSortOrder = legacySettings.sidebarThreadSortOrder;
223 }
224
225 if (Schema.is(TimestampFormat)(legacySettings.timestampFormat)) {
226 patch.timestampFormat = legacySettings.timestampFormat;
227 }
228
229 return patch;
230}
231
232/**
233 * Call once on app startup.
234 * If the legacy localStorage key exists, migrate its values to the new server
235 * and client storage formats, then remove the legacy key so this only runs once.
236 */
237export function migrateLocalSettingsToServer(): void {
238 if (typeof window === "undefined") return;
239
240 const raw = localStorage.getItem(OLD_SETTINGS_KEY);
241 if (!raw) return;
242
243 try {
244 const old = JSON.parse(raw);
245 if (!Predicate.isObject(old)) return;
246
247 // Migrate server-relevant keys via RPC
248 const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
249 if (Object.keys(serverPatch).length > 0) {
250 const api = ensureNativeApi();
251 void api.server.updateSettings(serverPatch);
252 }
253
254 // Migrate client-only keys to the new localStorage key
255 const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
256 if (Object.keys(clientPatch).length > 0) {
257 const existing = localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
258 const current = existing ? (JSON.parse(existing) as Record<string, unknown>) : {};
259 localStorage.setItem(
260 CLIENT_SETTINGS_STORAGE_KEY,
261 JSON.stringify({ ...current, ...clientPatch }),
262 );
263 }
264 } catch (error) {
265 console.error("[MIGRATION] Error migrating local settings:", error);
266 } finally {
267 // Remove the legacy key regardless to keep migration one-shot behavior.
268 localStorage.removeItem(OLD_SETTINGS_KEY);
269 }
270}