Open History to see the last commit
1/**
2 * Environment-scoped settings hooks.
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 * Live server settings always require an environment id. Primary-environment
9 * access is intentionally named as such so environment-sensitive consumers
10 * cannot silently read the wrong server's settings.
11 */
12import { useCallback, useMemo, useSyncExternalStore } from "react";
13import { useAtomValue } from "@effect/atom-react";
14import {
15 DEFAULT_SERVER_SETTINGS,
16 type EnvironmentId,
17 type ProviderInstanceMutation,
18 ServerSettings,
19 type ServerSettingsPatch,
20} from "@t3tools/contracts";
21import {
22 type ClientSettingsPatch,
23 type ClientSettings,
24 DEFAULT_CLIENT_SETTINGS,
25 type EnvironmentIdentificationMode,
26 type UnifiedSettings,
27} from "@t3tools/contracts/settings";
28import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
29import {
30 filterSharedServerPatch,
31 findSharedSettingsMismatches,
32 pickSharedServerSettings,
33 splitSharedServerPatch,
34 supportsSharedSettingsSync,
35} from "@t3tools/client-runtime/state/shared-settings";
36import { ensureLocalApi } from "~/localApi";
37import {
38 getThemeDefinition,
39 getThemePreviewSidebarArtwork,
40 resolveThemeHalf,
41 subscribeToThemePreview,
42 themeAllowsSidebarArtwork,
43} from "~/themePalette";
44import * as Struct from "effect/Struct";
45import { toastManager } from "~/components/ui/toast";
46import { isHostedStaticApp } from "~/hostedPairing";
47import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
48import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
49import { useAtomCommand } from "~/state/use-atom-command";
50import { useTheme } from "./useTheme";
51
52const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
53
54type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
55
56const clientSettingsListeners = new Set<() => void>();
57const clientSettingsHydrationListeners = new Set<() => void>();
58type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying";
59let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
60let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending";
61let clientSettingsHydrationPromise: Promise<void> | null = null;
62let clientSettingsHydrationGeneration = 0;
63let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
64let deferredClientSettingsPatchCount = 0;
65
66function emitClientSettingsChange() {
67 for (const listener of clientSettingsListeners) {
68 listener();
69 }
70}
71
72function emitClientSettingsHydrationChange() {
73 for (const listener of clientSettingsHydrationListeners) {
74 listener();
75 }
76}
77
78function getClientSettingsSnapshot(): ClientSettings {
79 return clientSettingsSnapshot;
80}
81
82function replaceClientSettingsSnapshot(settings: ClientSettings): void {
83 clientSettingsSnapshot = settings;
84 emitClientSettingsChange();
85}
86
87function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void {
88 if (clientSettingsHydrationStatus === nextStatus) {
89 return;
90 }
91 clientSettingsHydrationStatus = nextStatus;
92 emitClientSettingsHydrationChange();
93}
94
95function subscribeClientSettings(listener: () => void): () => void {
96 clientSettingsListeners.add(listener);
97 void hydrateClientSettings().catch(() => undefined);
98 return () => {
99 clientSettingsListeners.delete(listener);
100 };
101}
102
103function getClientSettingsHydratedSnapshot(): boolean {
104 return clientSettingsHydrationStatus === "ready";
105}
106
107function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
108 return clientSettingsHydrationStatus;
109}
110
111function subscribeClientSettingsHydration(listener: () => void): () => void {
112 clientSettingsHydrationListeners.add(listener);
113 void hydrateClientSettings().catch(() => undefined);
114 return () => {
115 clientSettingsHydrationListeners.delete(listener);
116 };
117}
118
119async function hydrateClientSettings(): Promise<void> {
120 if (clientSettingsHydrationStatus === "ready") {
121 return;
122 }
123 if (clientSettingsHydrationPromise) {
124 return clientSettingsHydrationPromise;
125 }
126
127 const hydrationGeneration = clientSettingsHydrationGeneration;
128 setClientSettingsHydrationStatus(
129 clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying"
130 ? "retrying"
131 : "pending",
132 );
133 const nextHydration = (async () => {
134 try {
135 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
136 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
137 return;
138 }
139 if (persistedSettings) {
140 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
141 }
142 setClientSettingsHydrationStatus("ready");
143 } catch (error) {
144 if (hydrationGeneration === clientSettingsHydrationGeneration) {
145 setClientSettingsHydrationStatus("failed");
146 }
147 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
148 operation: "hydrate",
149 ...safeErrorLogAttributes(error),
150 });
151 throw error;
152 }
153 })();
154
155 const hydrationPromise = nextHydration.finally(() => {
156 if (clientSettingsHydrationPromise === hydrationPromise) {
157 clientSettingsHydrationPromise = null;
158 }
159 });
160 clientSettingsHydrationPromise = hydrationPromise;
161
162 return clientSettingsHydrationPromise;
163}
164
165const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
166 ensureLocalApi().persistence.setClientSettings(settings);
167
168function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
169 const result = clientSettingsPersistenceQueue.then(work);
170 clientSettingsPersistenceQueue = result.then(
171 () => undefined,
172 () => undefined,
173 );
174 return result;
175}
176
177export function persistClientSettingsPatch(
178 patch: ClientSettingsPatch,
179 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
180): Promise<void> {
181 // Patches queued before hydration must publish before newer optimistic patches.
182 const deferPatch =
183 clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0;
184 if (deferPatch) {
185 deferredClientSettingsPatchCount += 1;
186 } else {
187 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
188 }
189 return enqueueClientSettingsPersistence(async () => {
190 if (deferPatch) {
191 try {
192 if (clientSettingsHydrationStatus !== "ready") {
193 await hydrateClientSettings();
194 }
195 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
196 } finally {
197 deferredClientSettingsPatchCount -= 1;
198 }
199 }
200 await persist(getClientSettingsSnapshot());
201 }).catch((error) => {
202 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
203 operation: "persist",
204 ...safeErrorLogAttributes(error),
205 });
206 });
207}
208
209/**
210 * Persists a client-settings update before publishing it to the in-memory
211 * snapshot. If another settings write lands while persistence is pending, the
212 * updater is reapplied to that newer snapshot and persisted again so neither
213 * change is lost.
214 */
215export async function persistClientSettingsUpdate(
216 update: (current: ClientSettings) => ClientSettings,
217 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
218): Promise<ClientSettings> {
219 return enqueueClientSettingsPersistence(async () => {
220 if (clientSettingsHydrationStatus !== "ready") {
221 await hydrateClientSettings();
222 }
223 for (;;) {
224 const current = getClientSettingsSnapshot();
225 const next = update(current);
226 await persist(next);
227 if (getClientSettingsSnapshot() === current) {
228 replaceClientSettingsSnapshot(next);
229 return next;
230 }
231 }
232 });
233}
234
235// ── Key sets for routing patches ─────────────────────────────────────
236
237const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
238
239function splitPatch(patch: UnifiedSettingsPatch): {
240 serverPatch: ServerSettingsPatch;
241 clientPatch: ClientSettingsPatch;
242} {
243 const serverPatch: Record<string, unknown> = {};
244 const clientPatch: Record<string, unknown> = {};
245 for (const [key, value] of Object.entries(patch)) {
246 if (SERVER_SETTINGS_KEYS.has(key)) {
247 serverPatch[key] = value;
248 } else {
249 clientPatch[key] = value;
250 }
251 }
252 return {
253 serverPatch: serverPatch as ServerSettingsPatch,
254 clientPatch: clientPatch as ClientSettingsPatch,
255 };
256}
257
258// ── Hooks ────────────────────────────────────────────────────────────
259
260/**
261 * Non-hook accessor for the current merged client settings snapshot.
262 * Used by non-React code paths (e.g. runtime services) that need the latest
263 * settings without subscribing.
264 */
265export function getClientSettings(): ClientSettings {
266 return getClientSettingsSnapshot();
267}
268
269/**
270 * Resolves after settings load or storage confirms no saved settings exist.
271 * Failed reads reject and remain retryable. They must not allow defaults to
272 * overwrite saved preferences.
273 *
274 * The pre-hydration snapshot is just the schema defaults, so imperative paths
275 * that open a preview must await this or they bake the built-in viewport, zoom
276 * and appearance into a tab that never picks up the user's saved values.
277 */
278export function ensureClientSettingsHydrated(): Promise<void> {
279 return hydrateClientSettings();
280}
281
282export function useClientSettingsHydrated(): boolean {
283 return useSyncExternalStore(
284 subscribeClientSettingsHydration,
285 getClientSettingsHydratedSnapshot,
286 () => false,
287 );
288}
289
290export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
291 return useSyncExternalStore(
292 subscribeClientSettingsHydration,
293 getClientSettingsHydrationStatusSnapshot,
294 () => "pending",
295 );
296}
297
298function useClientSettingsValue(): ClientSettings {
299 return useSyncExternalStore(
300 subscribeClientSettings,
301 getClientSettingsSnapshot,
302 () => DEFAULT_CLIENT_SETTINGS,
303 );
304}
305
306export function mergeEnvironmentSettings(
307 serverSettings: ServerSettings,
308 clientSettings: ClientSettings,
309): UnifiedSettings {
310 // Decode drops retired client keys, but older untyped persistence adapters
311 // can still return them. Server-owned values must always win.
312 return { ...clientSettings, ...serverSettings };
313}
314
315function useMergedSettings<T>(
316 serverSettings: ServerSettings,
317 selector: ((settings: UnifiedSettings) => T) | undefined,
318): T {
319 const clientSettings = useClientSettingsValue();
320
321 const merged = useMemo<UnifiedSettings>(
322 () => mergeEnvironmentSettings(serverSettings, clientSettings),
323 [clientSettings, serverSettings],
324 );
325
326 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
327}
328
329export function useClientSettings<T = ClientSettings>(
330 selector?: (settings: ClientSettings) => T,
331): T {
332 const settings = useClientSettingsValue();
333 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
334}
335
336export function resolveEnvironmentIdentificationMode(input: {
337 mode: EnvironmentIdentificationMode;
338 settingsHydrated: boolean;
339 paletteThemeActive?: boolean;
340 paletteThemeAllowsArtwork?: boolean;
341}): EnvironmentIdentificationMode {
342 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
343 if (!input.settingsHydrated) return "none";
344 // Artwork palettes are maintained for built-ins only. Keep an explicit
345 // "none", but use the theme-aware pill for user-controlled palettes.
346 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
347 ? "pill"
348 : input.mode;
349}
350
351export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
352 const settingsHydrated = useClientSettingsHydrated();
353 const mode = useClientSettingsValue().environmentIdentificationMode;
354 const { resolvedTheme, theme, themeHalves } = useTheme();
355 const previewSidebarArtwork = useSyncExternalStore(
356 subscribeToThemePreview,
357 getThemePreviewSidebarArtwork,
358 () => null,
359 );
360 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
361 const activeThemeDefinition = getThemeDefinition(activeTheme);
362 return resolveEnvironmentIdentificationMode({
363 mode,
364 settingsHydrated,
365 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
366 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
367 });
368}
369
370/**
371 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
372 * the default one.
373 *
374 * Held at the default sidebar until client settings hydrate: the pre-hydration
375 * snapshot is just the schema defaults, so resolving against it could mount one
376 * sidebar and then swap it out once persisted settings land — remounting the
377 * whole tree for everyone instead of only for legacy opt-ins.
378 */
379export function useLegacySidebarEnabled(): boolean {
380 const settingsHydrated = useClientSettingsHydrated();
381 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
382 return settingsHydrated && legacySidebarEnabled;
383}
384
385/** Read current settings for one environment, merged with client-local preferences. */
386export function useEnvironmentSettings<T = UnifiedSettings>(
387 environmentId: EnvironmentId,
388 selector?: (settings: UnifiedSettings) => T,
389): T {
390 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
391 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
392}
393
394/** Atomically mutate one provider instance against the server's latest settings snapshot. */
395export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) {
396 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
397 reportFailure: false,
398 });
399 return useCallback(
400 (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
401 mutateProviderInstance({
402 environmentId,
403 input: { patch, providerInstanceMutation },
404 }),
405 [environmentId, mutateProviderInstance],
406 );
407}
408
409/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
410export function usePrimarySettings<T = UnifiedSettings>(
411 selector?: (settings: UnifiedSettings) => T,
412): T {
413 return useMergedSettings(useAtomValue(primaryServerSettingsAtom), selector);
414}
415
416export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
417 "This setting is saved on a server, and the hosted app is not anchored to one. Change it from the desktop app or from the server's own address.";
418
419/**
420 * Whether primary-scoped server settings have a server to live on. The
421 * hosted app connects to every environment as a remote, so it has no primary:
422 * `usePrimarySettings` reads schema defaults there and writes have nowhere
423 * to go. Desktop and server-served web always have one.
424 */
425export function usePrimarySettingsAvailable(): boolean {
426 const primaryEnvironment = usePrimaryEnvironment();
427 return primaryEnvironment !== null || !isHostedStaticApp();
428}
429
430/**
431 * Returns an updater that routes each key to the correct backing store.
432 *
433 * Server keys are optimistically patched in atom-backed server state, then
434 * persisted via RPC. Shared server keys (see `SHARED_SERVER_SETTING_KEYS`)
435 * are written to every eligible sync target, not only the selected target, so
436 * a user preference does not silently drift between machines. Client keys go
437 * through client persistence.
438 */
439function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
440 const persistServerSettings = useAtomCommand(
441 serverEnvironment.updateSettings,
442 "server settings update",
443 );
444 const { environments } = useEnvironments();
445 const updateSettings = useCallback(
446 (patch: UnifiedSettingsPatch) => {
447 const { serverPatch, clientPatch } = splitPatch(patch);
448
449 if (Object.keys(serverPatch).length > 0) {
450 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
451 // Dropping the write silently leaves the control looking saved.
452 const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
453 toastManager.add({
454 type: "warning",
455 title: "Setting not saved",
456 description,
457 });
458 if (Object.keys(localPatch).length > 0) {
459 if (environmentId) {
460 void persistServerSettings({
461 environmentId,
462 input: { patch: localPatch },
463 });
464 } else {
465 warnUnsaved();
466 }
467 }
468 if (Object.keys(sharedPatch).length > 0) {
469 const sourceSettings = environments.find(
470 (target) => target.environmentId === environmentId,
471 )?.serverConfig?.settings;
472 const targets = new Set(
473 environments.filter(supportsSharedSettingsSync).map((target) => target.environmentId),
474 );
475 if (environmentId) {
476 targets.add(environmentId);
477 }
478 let wroteToTarget = false;
479 for (const targetId of targets) {
480 const target = environments.find((candidate) => candidate.environmentId === targetId);
481 const targetPatch = filterSharedServerPatch(
482 sharedPatch,
483 target?.serverConfig?.environment.capabilities,
484 target?.serverConfig?.settings,
485 sourceSettings,
486 targetId === environmentId,
487 );
488 if (Object.keys(targetPatch).length === 0) continue;
489 wroteToTarget = true;
490 void persistServerSettings({
491 environmentId: targetId,
492 input: { patch: targetPatch },
493 });
494 }
495 if (!wroteToTarget) {
496 warnUnsaved(
497 targets.size > 0 ? "Update older servers to save this setting." : undefined,
498 );
499 }
500 }
501 }
502 if (Object.keys(clientPatch).length > 0) {
503 void persistClientSettingsPatch(clientPatch);
504 }
505 },
506 [environmentId, environments, persistServerSettings],
507 );
508
509 return updateSettings;
510}
511
512/**
513 * Shared-settings sync targets whose values differ from the primary's,
514 * plus an action that writes the primary's values to all of them. Drift
515 * happens when an environment was offline during an edit or was changed by
516 * an older client.
517 */
518export function useSharedSettingsSync() {
519 const primaryEnvironment = usePrimaryEnvironment();
520 const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
521 const primaryCapabilities = primaryEnvironment?.serverConfig?.environment.capabilities;
522 // Read the loaded config, not `primaryServerSettingsAtom`: that atom falls
523 // back to defaults while the primary is disconnected, and "apply to all"
524 // must never push defaults over real values. Same for a primary too old to
525 // hold the shared keys: its decoded defaults are not a source of truth.
526 const primarySettings =
527 primaryEnvironment !== null && supportsSharedSettingsSync(primaryEnvironment)
528 ? (primaryEnvironment.serverConfig?.settings ?? null)
529 : null;
530 const { environments } = useEnvironments();
531 const persistServerSettings = useAtomCommand(
532 serverEnvironment.updateSettings,
533 "server settings update",
534 );
535
536 const mismatches = useMemo(
537 () =>
538 findSharedSettingsMismatches({
539 primaryEnvironmentId,
540 primarySettings,
541 primaryCapabilities,
542 environments: environments.map((environment) => ({
543 environmentId: environment.environmentId,
544 label: environment.label,
545 syncEligible: supportsSharedSettingsSync(environment),
546 settings: environment.serverConfig?.settings ?? null,
547 capabilities: environment.serverConfig?.environment.capabilities,
548 })),
549 }),
550 [environments, primaryEnvironmentId, primarySettings, primaryCapabilities],
551 );
552
553 const applyToAll = useCallback(() => {
554 if (primarySettings === null) {
555 return;
556 }
557 const patch = pickSharedServerSettings(primarySettings, primaryCapabilities);
558 for (const mismatch of mismatches) {
559 const target = environments.find(
560 (candidate) => candidate.environmentId === mismatch.environmentId,
561 );
562 void persistServerSettings({
563 environmentId: mismatch.environmentId,
564 input: {
565 patch: filterSharedServerPatch(
566 patch,
567 target?.serverConfig?.environment.capabilities,
568 target?.serverConfig?.settings,
569 primarySettings,
570 ),
571 },
572 });
573 }
574 }, [environments, mismatches, persistServerSettings, primarySettings, primaryCapabilities]);
575
576 return { mismatches, applyToAll };
577}
578
579export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
580 return useUpdateSettingsTarget(environmentId);
581}
582
583export function useUpdatePrimarySettings() {
584 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
585}
586
587export function useUpdateClientSettings() {
588 return useCallback((patch: ClientSettingsPatch) => {
589 return persistClientSettingsPatch(patch);
590 }, []);
591}
592
593export function __resetClientSettingsPersistenceForTests(): void {
594 clientSettingsHydrationGeneration += 1;
595 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
596 clientSettingsHydrationStatus = "pending";
597 clientSettingsHydrationPromise = null;
598 clientSettingsPersistenceQueue = Promise.resolve();
599 deferredClientSettingsPatchCount = 0;
600 clientSettingsListeners.clear();
601 clientSettingsHydrationListeners.clear();
602}
603
604export function __setClientSettingsForTests(settings: ClientSettings): void {
605 clientSettingsHydrationGeneration += 1;
606 clientSettingsSnapshot = settings;
607 clientSettingsHydrationStatus = "ready";
608 clientSettingsHydrationPromise = null;
609}