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

useSettings.ts

260 lines8.5 KB

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