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