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, useEffect, useMemo, useRef, useSyncExternalStore, use } from "react";
13import { RegistryContext, useAtomValue } from "@effect/atom-react";
14import {
15 DEFAULT_SERVER_SETTINGS,
16 AuthSettingsWriteScope,
17 requiredScopesForServerSettingsPatch,
18 type EnvironmentId,
19 type ProviderInstanceMutation,
20 type ProviderInstanceId,
21 ServerSettings,
22 type ServerSettingsPatch,
23 sessionGrantsScope,
24} from "@t3tools/contracts";
25import {
26 type ClientSettingsPatch,
27 type ClientSettings,
28 DEFAULT_CLIENT_SETTINGS,
29 type EnvironmentIdentificationMode,
30 type UnifiedSettings,
31} from "@t3tools/contracts/settings";
32import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
33import {
34 isAtomCommandInterrupted,
35 squashAtomCommandFailure,
36} from "@t3tools/client-runtime/state/runtime";
37import {
38 filterSharedServerPatch,
39 splitSharedServerPatch,
40 supportsSharedSettingsSync,
41} from "@t3tools/client-runtime/state/shared-settings";
42import { ensureLocalApi } from "~/localApi";
43import {
44 getThemeDefinition,
45 getThemePreviewSidebarArtwork,
46 resolveThemeHalf,
47 subscribeToThemePreview,
48 themeAllowsSidebarArtwork,
49} from "~/themePalette";
50import {
51 modelPreferencesMigrationPatch,
52 resolveModelPreferences,
53} from "@t3tools/shared/serverSettings";
54import * as Struct from "effect/Struct";
55import * as Option from "effect/Option";
56import { AsyncResult, Atom } from "effect/reactivity";
57import { toastManager } from "~/components/ui/toast";
58import { isHostedStaticApp } from "~/hostedPairing";
59import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
60import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
61import { useAtomCommand } from "~/state/use-atom-command";
62import { useTheme } from "./useTheme";
63import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
64import { appAtomRegistry } from "~/rpc/atomRegistry";
65
66const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
67
68type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
69
70const clientSettingsListeners = new Set<() => void>();
71const clientSettingsHydrationListeners = new Set<() => void>();
72type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying";
73let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
74let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending";
75let clientSettingsHydrationPromise: Promise<void> | null = null;
76let clientSettingsHydrationGeneration = 0;
77let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
78let deferredClientSettingsPatchCount = 0;
79
80function emitClientSettingsChange() {
81 for (const listener of clientSettingsListeners) {
82 listener();
83 }
84}
85
86function emitClientSettingsHydrationChange() {
87 for (const listener of clientSettingsHydrationListeners) {
88 listener();
89 }
90}
91
92function getClientSettingsSnapshot(): ClientSettings {
93 return clientSettingsSnapshot;
94}
95
96function replaceClientSettingsSnapshot(settings: ClientSettings): void {
97 clientSettingsSnapshot = settings;
98 emitClientSettingsChange();
99}
100
101function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void {
102 if (clientSettingsHydrationStatus === nextStatus) {
103 return;
104 }
105 clientSettingsHydrationStatus = nextStatus;
106 emitClientSettingsHydrationChange();
107}
108
109function subscribeClientSettings(listener: () => void): () => void {
110 clientSettingsListeners.add(listener);
111 void hydrateClientSettings().catch(() => undefined);
112 return () => {
113 clientSettingsListeners.delete(listener);
114 };
115}
116
117function getClientSettingsHydratedSnapshot(): boolean {
118 return clientSettingsHydrationStatus === "ready";
119}
120
121function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
122 return clientSettingsHydrationStatus;
123}
124
125function subscribeClientSettingsHydration(listener: () => void): () => void {
126 clientSettingsHydrationListeners.add(listener);
127 void hydrateClientSettings().catch(() => undefined);
128 return () => {
129 clientSettingsHydrationListeners.delete(listener);
130 };
131}
132
133async function hydrateClientSettings(): Promise<void> {
134 if (clientSettingsHydrationStatus === "ready") {
135 return;
136 }
137 if (clientSettingsHydrationPromise) {
138 return clientSettingsHydrationPromise;
139 }
140
141 const hydrationGeneration = clientSettingsHydrationGeneration;
142 setClientSettingsHydrationStatus(
143 clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying"
144 ? "retrying"
145 : "pending",
146 );
147 const nextHydration = (async () => {
148 try {
149 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
150 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
151 return;
152 }
153 if (persistedSettings) {
154 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
155 }
156 setClientSettingsHydrationStatus("ready");
157 } catch (error) {
158 if (hydrationGeneration === clientSettingsHydrationGeneration) {
159 setClientSettingsHydrationStatus("failed");
160 }
161 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
162 operation: "hydrate",
163 ...safeErrorLogAttributes(error),
164 });
165 throw error;
166 }
167 })();
168
169 const hydrationPromise = nextHydration.finally(() => {
170 if (clientSettingsHydrationPromise === hydrationPromise) {
171 clientSettingsHydrationPromise = null;
172 }
173 });
174 clientSettingsHydrationPromise = hydrationPromise;
175
176 return clientSettingsHydrationPromise;
177}
178
179const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
180 ensureLocalApi().persistence.setClientSettings(settings);
181
182function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
183 const result = clientSettingsPersistenceQueue.then(work);
184 clientSettingsPersistenceQueue = result.then(
185 () => undefined,
186 () => undefined,
187 );
188 return result;
189}
190
191export function persistClientSettingsPatch(
192 patch: ClientSettingsPatch,
193 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
194): Promise<void> {
195 // Patches queued before hydration must publish before newer optimistic patches.
196 const deferPatch =
197 clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0;
198 if (deferPatch) {
199 deferredClientSettingsPatchCount += 1;
200 } else {
201 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
202 }
203 return enqueueClientSettingsPersistence(async () => {
204 if (deferPatch) {
205 try {
206 if (clientSettingsHydrationStatus !== "ready") {
207 await hydrateClientSettings();
208 }
209 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
210 } finally {
211 deferredClientSettingsPatchCount -= 1;
212 }
213 }
214 await persist(getClientSettingsSnapshot());
215 }).catch((error) => {
216 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
217 operation: "persist",
218 ...safeErrorLogAttributes(error),
219 });
220 });
221}
222
223/**
224 * Persists a client-settings update before publishing it to the in-memory
225 * snapshot. If another settings write lands while persistence is pending, the
226 * updater is reapplied to that newer snapshot and persisted again so neither
227 * change is lost.
228 */
229export async function persistClientSettingsUpdate(
230 update: (current: ClientSettings) => ClientSettings,
231 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
232): Promise<ClientSettings> {
233 return enqueueClientSettingsPersistence(async () => {
234 if (clientSettingsHydrationStatus !== "ready") {
235 await hydrateClientSettings();
236 }
237 for (;;) {
238 const current = getClientSettingsSnapshot();
239 const next = update(current);
240 await persist(next);
241 if (getClientSettingsSnapshot() === current) {
242 replaceClientSettingsSnapshot(next);
243 return next;
244 }
245 }
246 });
247}
248
249// ── Key sets for routing patches ─────────────────────────────────────
250
251const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
252
253function splitPatch(patch: UnifiedSettingsPatch): {
254 serverPatch: ServerSettingsPatch;
255 clientPatch: ClientSettingsPatch;
256} {
257 const serverPatch: Record<string, unknown> = {};
258 const clientPatch: Record<string, unknown> = {};
259 for (const [key, value] of Object.entries(patch)) {
260 if (SERVER_SETTINGS_KEYS.has(key)) {
261 serverPatch[key] = value;
262 } else {
263 clientPatch[key] = value;
264 }
265 }
266 return {
267 serverPatch: serverPatch as ServerSettingsPatch,
268 clientPatch: clientPatch as ClientSettingsPatch,
269 };
270}
271
272// ── Hooks ────────────────────────────────────────────────────────────
273
274/**
275 * Non-hook accessor for the current merged client settings snapshot.
276 * Used by non-React code paths (e.g. runtime services) that need the latest
277 * settings without subscribing.
278 */
279export function getClientSettings(): ClientSettings {
280 return getClientSettingsSnapshot();
281}
282
283/**
284 * Resolves after settings load or storage confirms no saved settings exist.
285 * Failed reads reject and remain retryable. They must not allow defaults to
286 * overwrite saved preferences.
287 *
288 * The pre-hydration snapshot is just the schema defaults, so imperative paths
289 * that open a preview must await this or they bake the built-in viewport, zoom
290 * and appearance into a tab that never picks up the user's saved values.
291 */
292export function ensureClientSettingsHydrated(): Promise<void> {
293 return hydrateClientSettings();
294}
295
296export function useClientSettingsHydrated(): boolean {
297 return useSyncExternalStore(
298 subscribeClientSettingsHydration,
299 getClientSettingsHydratedSnapshot,
300 () => false,
301 );
302}
303
304export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
305 return useSyncExternalStore(
306 subscribeClientSettingsHydration,
307 getClientSettingsHydrationStatusSnapshot,
308 () => "pending",
309 );
310}
311
312function useClientSettingsValue(): ClientSettings {
313 return useSyncExternalStore(
314 subscribeClientSettings,
315 getClientSettingsSnapshot,
316 () => DEFAULT_CLIENT_SETTINGS,
317 );
318}
319
320export function mergeEnvironmentSettings(
321 serverSettings: ServerSettings,
322 clientSettings: ClientSettings,
323): UnifiedSettings {
324 // Decode drops retired client keys, but older untyped persistence adapters
325 // can still return them. Server-owned values must always win.
326 return {
327 ...clientSettings,
328 ...serverSettings,
329 ...resolveModelPreferences(serverSettings, clientSettings),
330 };
331}
332
333const pendingModelPreferencesMigrations = new Set<EnvironmentId>();
334
335/** Seed saved client preferences once without overwriting another client's edits. */
336export function useMigrateModelPreferences(
337 environmentId: EnvironmentId | null,
338 settings: ServerSettings | null,
339) {
340 const clientSettings = useClientSettingsValue();
341 const hydrated = useClientSettingsHydrated();
342 const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
343 useEffect(() => {
344 if (
345 !environmentId ||
346 !settings ||
347 !hydrated ||
348 pendingModelPreferencesMigrations.has(environmentId)
349 )
350 return;
351 const patch = modelPreferencesMigrationPatch(settings, clientSettings);
352 if (!patch) return;
353 pendingModelPreferencesMigrations.add(environmentId);
354 void migrate({ environmentId, input: { patch } }).finally(() =>
355 pendingModelPreferencesMigrations.delete(environmentId),
356 );
357 }, [clientSettings, environmentId, hydrated, migrate, settings]);
358}
359
360function useMergedSettings<T>(
361 serverSettings: ServerSettings,
362 selector: ((settings: UnifiedSettings) => T) | undefined,
363): T {
364 const clientSettings = useClientSettingsValue();
365
366 const merged = useMemo<UnifiedSettings>(
367 () => mergeEnvironmentSettings(serverSettings, clientSettings),
368 [clientSettings, serverSettings],
369 );
370
371 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
372}
373
374export function useClientSettings<T = ClientSettings>(
375 selector?: (settings: ClientSettings) => T,
376): T {
377 const settings = useClientSettingsValue();
378 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
379}
380
381export function resolveEnvironmentIdentificationMode(input: {
382 mode: EnvironmentIdentificationMode;
383 settingsHydrated: boolean;
384 paletteThemeActive?: boolean;
385 paletteThemeAllowsArtwork?: boolean;
386}): EnvironmentIdentificationMode {
387 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
388 if (!input.settingsHydrated) return "none";
389 // Artwork palettes are maintained for built-ins only. Keep an explicit
390 // "none", but use the theme-aware pill for user-controlled palettes.
391 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
392 ? "pill"
393 : input.mode;
394}
395
396export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
397 const settingsHydrated = useClientSettingsHydrated();
398 const mode = useClientSettingsValue().environmentIdentificationMode;
399 const { resolvedTheme, theme, themeHalves } = useTheme();
400 const previewSidebarArtwork = useSyncExternalStore(
401 subscribeToThemePreview,
402 getThemePreviewSidebarArtwork,
403 () => null,
404 );
405 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
406 const activeThemeDefinition = getThemeDefinition(activeTheme);
407 return resolveEnvironmentIdentificationMode({
408 mode,
409 settingsHydrated,
410 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
411 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
412 });
413}
414
415/**
416 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
417 * the default one.
418 *
419 * Held at the default sidebar until client settings hydrate: the pre-hydration
420 * snapshot is just the schema defaults, so resolving against it could mount one
421 * sidebar and then swap it out once persisted settings land — remounting the
422 * whole tree for everyone instead of only for legacy opt-ins.
423 */
424export function useLegacySidebarEnabled(): boolean {
425 const settingsHydrated = useClientSettingsHydrated();
426 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
427 return settingsHydrated && legacySidebarEnabled;
428}
429
430/** Hydrate legacy preferences before a mutation can claim either server-owned list. */
431export async function prepareModelPreferencesPatch(
432 settings: ServerSettings,
433 patch: ServerSettingsPatch,
434): Promise<ServerSettingsPatch> {
435 if (settings.favorites === null || settings.providerModelPreferences === null) {
436 await ensureClientSettingsHydrated();
437 }
438 return { ...modelPreferencesMigrationPatch(settings, getClientSettings()), ...patch };
439}
440
441export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
442 const settings = useAtomValue(
443 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
444 );
445 const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update");
446 return useCallback(
447 async (patch: ServerSettingsPatch) => {
448 if (!environmentId || !settings) return;
449 let prepared: ServerSettingsPatch;
450 try {
451 prepared = await prepareModelPreferencesPatch(settings, patch);
452 } catch {
453 toastManager.add({
454 type: "error",
455 title: "Model preferences not saved",
456 description: "Could not load saved model preferences. Try again.",
457 });
458 return;
459 }
460 return save({ environmentId, input: { patch: prepared } });
461 },
462 [environmentId, save, settings],
463 );
464}
465
466/** Send the desired state so two clients adding a favorite do not cancel each other. */
467export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId | null) {
468 const registry = use(RegistryContext);
469 const pendingFavorites = useRef(
470 new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
471 );
472 const save = useUpdateEnvironmentModelPreferences(environmentId);
473 return useCallback(
474 async (provider: ProviderInstanceId, model: string) => {
475 if (!environmentId) return;
476 const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
477 const settings = registry.get(settingsAtom);
478 if (!settings) return;
479 if (settings.favorites === null) {
480 try {
481 await ensureClientSettingsHydrated();
482 } catch {
483 toastManager.add({
484 type: "error",
485 title: "Favorites not saved",
486 description: "Could not load saved model preferences. Try again.",
487 });
488 return;
489 }
490 }
491 const currentSettings = registry.get(settingsAtom) ?? settings;
492 const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
493 const key = JSON.stringify([environmentId, provider, model]);
494 const previous = pendingFavorites.current.get(key);
495 // Keep the acknowledged choice until the config stream catches up with the RPC reply.
496 const previousFavorite =
497 previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
498 ? previous.favorite
499 : favorites.some(
500 (favorite) => favorite.provider === provider && favorite.model === model,
501 );
502 const pending = {
503 favorite: !previousFavorite,
504 settings: currentSettings,
505 pending: true,
506 };
507 pendingFavorites.current.set(key, pending);
508 try {
509 const result = await save({
510 setModelFavorites: [{ provider, model, favorite: pending.favorite }],
511 });
512 if (
513 result &&
514 AsyncResult.isSuccess(result) &&
515 registry.get(settingsAtom)?.favorites === currentSettings.favorites
516 ) {
517 pending.pending = false;
518 }
519 } finally {
520 if (pending.pending && pendingFavorites.current.get(key) === pending) {
521 if (
522 previous &&
523 !previous.pending &&
524 registry.get(settingsAtom)?.favorites === previous.settings.favorites
525 ) {
526 pendingFavorites.current.set(key, previous);
527 } else {
528 pendingFavorites.current.delete(key);
529 }
530 }
531 }
532 },
533 [environmentId, registry, save],
534 );
535}
536
537const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null);
538
539/** Model pickers may render before a settings target has been selected. */
540export function useEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
541 const settings = useAtomValue(
542 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
543 );
544 const legacy = useClientSettingsValue();
545 useMigrateModelPreferences(environmentId, settings);
546 return useMemo(
547 () => resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy),
548 [legacy, settings],
549 );
550}
551
552/** Read current settings for one environment, merged with client-local preferences. */
553export function useEnvironmentSettings<T = UnifiedSettings>(
554 environmentId: EnvironmentId,
555 selector?: (settings: UnifiedSettings) => T,
556): T {
557 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
558 useMigrateModelPreferences(environmentId, serverSettings);
559 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
560}
561
562/** Atomically mutate one provider instance against the server's latest settings snapshot. */
563export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) {
564 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
565 reportFailure: false,
566 });
567 return useCallback(
568 (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
569 mutateProviderInstance({
570 environmentId,
571 input: { patch, providerInstanceMutation },
572 }),
573 [environmentId, mutateProviderInstance],
574 );
575}
576
577/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
578export function usePrimarySettings<T = UnifiedSettings>(
579 selector?: (settings: UnifiedSettings) => T,
580): T {
581 const environment = usePrimaryEnvironment();
582 const settings = useAtomValue(primaryServerSettingsAtom);
583 useMigrateModelPreferences(
584 environment?.environmentId ?? null,
585 environment?.serverConfig?.settings ?? null,
586 );
587 return useMergedSettings(settings, selector);
588}
589
590export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
591 "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.";
592
593/**
594 * Whether primary-scoped server settings have a server to live on. The
595 * hosted app connects to every environment as a remote, so it has no primary:
596 * `usePrimarySettings` reads schema defaults there and writes have nowhere
597 * to go. Desktop and server-served web always have one.
598 */
599export function usePrimarySettingsAvailable(): boolean {
600 const primaryEnvironment = usePrimaryEnvironment();
601 return primaryEnvironment !== null || !isHostedStaticApp();
602}
603
604/** Connected sync targets, excluding grants already known to forbid settings writes. */
605function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
606 const { environments } = useEnvironments();
607 const writableTargetsAtom = useMemo(
608 () =>
609 Atom.make((get) =>
610 environments.filter(supportsSharedSettingsSync).flatMap((environment) => {
611 const result = get(environmentSession.sessionStateAtom(environment.environmentId));
612 // A cold grant must not drop a shared edit. The server authorizes the
613 // write; mismatch suggestions still wait for a confirmed grant.
614 if (includePending && result._tag === "Initial") {
615 return [environment.environmentId];
616 }
617 const session =
618 result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
619 return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
620 ? [environment.environmentId]
621 : [];
622 }),
623 ),
624 [environments, includePending],
625 );
626 return useAtomValue(writableTargetsAtom);
627}
628
629/**
630 * Returns an updater that routes each key to the correct backing store.
631 *
632 * Server keys are optimistically patched in atom-backed server state, then
633 * persisted via RPC. Shared server keys (see `SHARED_SERVER_SETTING_KEYS`)
634 * are written to every eligible sync target, not only the selected target, so
635 * a user preference does not silently drift between machines. Client keys go
636 * through client persistence.
637 */
638function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
639 // Mount this session even on pages without a visible permission-gated control.
640 useEnvironmentScope(environmentId, AuthSettingsWriteScope);
641 const persist = useAtomCommand(serverEnvironment.updateSettings, {
642 label: "server settings update",
643 reportFailure: false,
644 });
645 const { environments } = useEnvironments();
646 const persistServerSettings = useCallback(
647 async (request: Parameters<typeof persist>[0]) => {
648 const result = await persist(request);
649 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
650 const label =
651 environments.find((environment) => environment.environmentId === request.environmentId)
652 ?.label ?? request.environmentId;
653 const error = squashAtomCommandFailure(result);
654 toastManager.add({
655 type: "error",
656 title: "Setting not saved",
657 description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
658 });
659 }
660 return result;
661 },
662 [environments, persist],
663 );
664 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
665 const updateSettings = useCallback(
666 (patch: UnifiedSettingsPatch) => {
667 const { serverPatch, clientPatch } = splitPatch(patch);
668
669 const canWriteServerPatch =
670 environmentId === null ||
671 requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
672 readEnvironmentScope(environmentId, scope),
673 );
674 if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
675 toastManager.add({
676 type: "warning",
677 title: "Setting not saved",
678 description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,
679 });
680 }
681 if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
682 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
683 // Dropping the write silently leaves the control looking saved.
684 const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
685 toastManager.add({
686 type: "warning",
687 title: "Setting not saved",
688 description,
689 });
690 if (Object.keys(localPatch).length > 0) {
691 if (environmentId) {
692 void persistServerSettings({
693 environmentId,
694 input: { patch: localPatch },
695 });
696 } else {
697 warnUnsaved();
698 }
699 }
700 if (Object.keys(sharedPatch).length > 0) {
701 const sourceSettings = environments.find(
702 (target) => target.environmentId === environmentId,
703 )?.serverConfig?.settings;
704 const targets = new Set(sharedSettingsSyncTargetIds);
705 if (environmentId) {
706 targets.add(environmentId);
707 }
708 const writes: Array<Parameters<typeof persist>[0]> = [];
709 const deniedLabels: string[] = [];
710 for (const targetId of targets) {
711 const target = environments.find((candidate) => candidate.environmentId === targetId);
712 const targetPatch = filterSharedServerPatch(
713 sharedPatch,
714 target?.serverConfig?.environment.capabilities,
715 target?.serverConfig?.settings,
716 sourceSettings,
717 targetId === environmentId,
718 );
719 if (Object.keys(targetPatch).length === 0) continue;
720 const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
721 if (
722 session._tag !== "Initial" &&
723 !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
724 readEnvironmentScope(targetId, scope),
725 )
726 ) {
727 deniedLabels.push(target?.label ?? targetId);
728 continue;
729 }
730 writes.push({
731 environmentId: targetId,
732 input: { patch: targetPatch },
733 });
734 }
735 if (writes.length === 0) {
736 warnUnsaved(
737 deniedLabels.length > 0
738 ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`
739 : targets.size > 0
740 ? "Update older servers to save this setting."
741 : undefined,
742 );
743 } else {
744 void Promise.all(
745 writes.map(async (request) => ({
746 label:
747 environments.find((target) => target.environmentId === request.environmentId)
748 ?.label ?? request.environmentId,
749 result: await persist(request),
750 })),
751 ).then((outcomes) => {
752 const failures = outcomes.flatMap(({ label, result }) => {
753 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
754 const error = squashAtomCommandFailure(result);
755 return [
756 `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
757 ];
758 });
759 if (failures.length === 0) return;
760 const saved = outcomes
761 .filter(({ result }) => result._tag === "Success")
762 .map(({ label }) => label);
763 toastManager.add({
764 type: "error",
765 title:
766 saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",
767 description: [
768 ...failures,
769 ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),
770 ].join("\n"),
771 });
772 });
773 }
774 }
775 }
776 if (Object.keys(clientPatch).length > 0) {
777 void persistClientSettingsPatch(clientPatch);
778 }
779 },
780 [environmentId, environments, persist, persistServerSettings, sharedSettingsSyncTargetIds],
781 );
782
783 return updateSettings;
784}
785
786export function useUpdateEnvironmentSettings(environmentId: EnvironmentId | null) {
787 return useUpdateSettingsTarget(environmentId);
788}
789
790export function useUpdatePrimarySettings() {
791 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
792}
793
794export function useUpdateClientSettings() {
795 return useCallback((patch: ClientSettingsPatch) => {
796 return persistClientSettingsPatch(patch);
797 }, []);
798}
799
800export function __resetClientSettingsPersistenceForTests(): void {
801 clientSettingsHydrationGeneration += 1;
802 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
803 clientSettingsHydrationStatus = "pending";
804 clientSettingsHydrationPromise = null;
805 clientSettingsPersistenceQueue = Promise.resolve();
806 deferredClientSettingsPatchCount = 0;
807 clientSettingsListeners.clear();
808 clientSettingsHydrationListeners.clear();
809}
810
811export function __setClientSettingsForTests(settings: ClientSettings): void {
812 clientSettingsHydrationGeneration += 1;
813 clientSettingsSnapshot = settings;
814 clientSettingsHydrationStatus = "ready";
815 clientSettingsHydrationPromise = null;
816}