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

useSettings.ts

262 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 { ensureNativeApi } from "~/nativeApi";
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 extends UnifiedSettings = UnifiedSettings>(
71 selector?: (s: UnifiedSettings) => T,
72): T {
73 const serverSettings = useServerSettings();
74 const [clientSettings] = useLocalStorage(
75 CLIENT_SETTINGS_STORAGE_KEY,
76 DEFAULT_CLIENT_SETTINGS,
77 ClientSettingsSchema,
78 );
79​
80 const merged = useMemo<UnifiedSettings>(
81 () => ({
82 ...serverSettings,
83 ...clientSettings,
84 }),
85 [clientSettings, serverSettings],
86 );
87​
88 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
90​
91/**
92 * Returns an updater that routes each key to the correct backing store.
93 *
94 * Server keys are optimistically patched in atom-backed server state, then
95 * persisted via RPC. Client keys go straight to localStorage.
96 */
97export function useUpdateSettings() {
98 const [, setClientSettings] = useLocalStorage(
99 CLIENT_SETTINGS_STORAGE_KEY,
100 DEFAULT_CLIENT_SETTINGS,
101 ClientSettingsSchema,
102 );
103​
104 const updateSettings = useCallback(
105 (patch: Partial<UnifiedSettings>) => {
106 const { serverPatch, clientPatch } = splitPatch(patch);
107​
108 if (Object.keys(serverPatch).length > 0) {
109 const currentServerConfig = getServerConfig();
110 if (currentServerConfig) {
111 applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
112 }
113 // Fire-and-forget RPC — push will reconcile on success
114 void ensureNativeApi().server.updateSettings(serverPatch);
115 }
116​
117 if (Object.keys(clientPatch).length > 0) {
118 setClientSettings((prev) => ({ ...prev, ...clientPatch }));
119 }
120 },
121 [setClientSettings],
122 );
123​
124 const resetSettings = useCallback(() => {
125 updateSettings(DEFAULT_UNIFIED_SETTINGS);
126 }, [updateSettings]);
127​
128 return {
129 updateSettings,
130 resetSettings,
131 };
133​
134// ── One-time migration from localStorage ─────────────────────────────
135​
136export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
137 const patch: DeepMutable<ServerSettingsPatch> = {};
138​
139 if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
140 patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
141 }
142​
143 if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
144 patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
145 }
146​
147 if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
148 patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
149 }
150​
151 if (typeof legacySettings.codexBinaryPath === "string") {
152 patch.providers ??= {};
153 patch.providers.codex ??= {};
154 patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
155 }
156​
157 if (typeof legacySettings.codexHomePath === "string") {
158 patch.providers ??= {};
159 patch.providers.codex ??= {};
160 patch.providers.codex.homePath = legacySettings.codexHomePath;
161 }
162​
163 if (Array.isArray(legacySettings.customCodexModels)) {
164 patch.providers ??= {};
165 patch.providers.codex ??= {};
166 patch.providers.codex.customModels = normalizeCustomModelSlugs(
167 legacySettings.customCodexModels,
168 new Set<string>(),
169 "codex",
170 );
171 }
172​
173 if (Predicate.isString(legacySettings.claudeBinaryPath)) {
174 patch.providers ??= {};
175 patch.providers.claudeAgent ??= {};
176 patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
177 }
178​
179 if (Array.isArray(legacySettings.customClaudeModels)) {
180 patch.providers ??= {};
181 patch.providers.claudeAgent ??= {};
182 patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
183 legacySettings.customClaudeModels,
184 new Set<string>(),
185 "claudeAgent",
186 );
187 }
188​
189 return patch;
191​
192export function buildLegacyClientSettingsMigrationPatch(
193 legacySettings: Record<string, unknown>,
194): Partial<DeepMutable<ClientSettings>> {
195 const patch: Partial<DeepMutable<ClientSettings>> = {};
196​
197 if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
198 patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
199 }
200​
201 if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
202 patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
203 }
204​
205 if (Predicate.isBoolean(legacySettings.diffWordWrap)) {
206 patch.diffWordWrap = legacySettings.diffWordWrap;
207 }
208​
209 if (Schema.is(SidebarProjectSortOrder)(legacySettings.sidebarProjectSortOrder)) {
210 patch.sidebarProjectSortOrder = legacySettings.sidebarProjectSortOrder;
211 }
212​
213 if (Schema.is(SidebarThreadSortOrder)(legacySettings.sidebarThreadSortOrder)) {
214 patch.sidebarThreadSortOrder = legacySettings.sidebarThreadSortOrder;
215 }
216​
217 if (Schema.is(TimestampFormat)(legacySettings.timestampFormat)) {
218 patch.timestampFormat = legacySettings.timestampFormat;
219 }
220​
221 return patch;
223​
224/**
225 * Call once on app startup.
226 * If the legacy localStorage key exists, migrate its values to the new server
227 * and client storage formats, then remove the legacy key so this only runs once.
228 */
229export function migrateLocalSettingsToServer(): void {
230 if (typeof window === "undefined") return;
231​
232 const raw = localStorage.getItem(OLD_SETTINGS_KEY);
233 if (!raw) return;
234​
235 try {
236 const old = JSON.parse(raw);
237 if (!Predicate.isObject(old)) return;
238​
239 // Migrate server-relevant keys via RPC
240 const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
241 if (Object.keys(serverPatch).length > 0) {
242 const api = ensureNativeApi();
243 void api.server.updateSettings(serverPatch);
244 }
245​
246 // Migrate client-only keys to the new localStorage key
247 const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
248 if (Object.keys(clientPatch).length > 0) {
249 const existing = localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
250 const current = existing ? (JSON.parse(existing) as Record<string, unknown>) : {};
251 localStorage.setItem(
252 CLIENT_SETTINGS_STORAGE_KEY,
253 JSON.stringify({ ...current, ...clientPatch }),
254 );
255 }
256 } catch (error) {
257 console.error("[MIGRATION] Error migrating local settings:", error);
258 } finally {
259 // Remove the legacy key regardless to keep migration one-shot behavior.
260 localStorage.removeItem(OLD_SETTINGS_KEY);
261 }