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

useSettings.ts

740 lines26.4 KB

1import { useEffect, useRef, useSyncExternalStore, use } from "react";
2import { RegistryContext, useAtomValue } from "@effect/atom-react";
3import {
4 DEFAULT_SERVER_SETTINGS,
5 AuthSettingsWriteScope,
6 requiredScopesForServerSettingsPatch,
7 type EnvironmentId,
8 type ProviderInstanceMutation,
9 type ProviderInstanceId,
10 ServerSettings,
11 type ServerSettingsPatch,
12 sessionGrantsScope,
13} from "@t3tools/contracts";
14import {
15 type ClientSettingsPatch,
16 type ClientSettings,
17 DEFAULT_CLIENT_SETTINGS,
18 type EnvironmentIdentificationMode,
19 type UnifiedSettings,
20} from "@t3tools/contracts/settings";
21import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
22import {
23 isAtomCommandInterrupted,
24 squashAtomCommandFailure,
25} from "@t3tools/client-runtime/state/runtime";
26import {
27 filterSharedServerPatch,
28 splitSharedServerPatch,
29 supportsSharedSettingsSync,
30} from "@t3tools/client-runtime/state/shared-settings";
31import { ensureLocalApi } from "~/localApi";
32import {
33 getThemeDefinition,
34 getThemePreviewSidebarArtwork,
35 resolveThemeHalf,
36 subscribeToThemePreview,
37 themeAllowsSidebarArtwork,
38} from "~/themePalette";
39import {
40 modelPreferencesMigrationPatch,
41 resolveModelPreferences,
42} from "@t3tools/shared/serverSettings";
43import * as Struct from "effect/Struct";
44import * as Option from "effect/Option";
45import { AsyncResult, Atom } from "effect/reactivity";
46import { toastManager } from "~/components/ui/toast";
47import { isHostedStaticApp } from "~/hostedPairing";
48import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
49import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
50import { useAtomCommand } from "~/state/use-atom-command";
51import { useTheme } from "./useTheme";
52import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
53import { appAtomRegistry } from "~/rpc/atomRegistry";
54​
55const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
56​
57type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
58​
59const clientSettingsListeners = new Set<() => void>();
60const clientSettingsHydrationListeners = new Set<() => void>();
61type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying";
62let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
63let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending";
64let clientSettingsHydrationPromise: Promise<void> | null = null;
65let clientSettingsHydrationGeneration = 0;
66let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
67let deferredClientSettingsPatchCount = 0;
68​
69function emitClientSettingsChange() {
70 for (const listener of clientSettingsListeners) {
71 listener();
72 }
74​
75function emitClientSettingsHydrationChange() {
76 for (const listener of clientSettingsHydrationListeners) {
77 listener();
78 }
80​
81function getClientSettingsSnapshot(): ClientSettings {
82 return clientSettingsSnapshot;
84​
85function replaceClientSettingsSnapshot(settings: ClientSettings): void {
86 clientSettingsSnapshot = settings;
87 emitClientSettingsChange();
89​
90function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void {
91 if (clientSettingsHydrationStatus === nextStatus) {
92 return;
93 }
94 clientSettingsHydrationStatus = nextStatus;
95 emitClientSettingsHydrationChange();
97​
98function subscribeClientSettings(listener: () => void): () => void {
99 clientSettingsListeners.add(listener);
100 void hydrateClientSettings().catch(() => undefined);
101 return () => {
102 clientSettingsListeners.delete(listener);
103 };
105​
106function getClientSettingsHydratedSnapshot(): boolean {
107 return clientSettingsHydrationStatus === "ready";
109​
110function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
111 return clientSettingsHydrationStatus;
113​
114function subscribeClientSettingsHydration(listener: () => void): () => void {
115 clientSettingsHydrationListeners.add(listener);
116 void hydrateClientSettings().catch(() => undefined);
117 return () => {
118 clientSettingsHydrationListeners.delete(listener);
119 };
121​
122async function hydrateClientSettings(): Promise<void> {
123 if (clientSettingsHydrationStatus === "ready") {
124 return;
125 }
126 if (clientSettingsHydrationPromise) {
127 return clientSettingsHydrationPromise;
128 }
129​
130 const hydrationGeneration = clientSettingsHydrationGeneration;
131 setClientSettingsHydrationStatus(
132 clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying"
133 ? "retrying"
134 : "pending",
135 );
136 const nextHydration = (async () => {
137 try {
138 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
139 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
140 return;
141 }
142 if (persistedSettings) {
143 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
144 }
145 setClientSettingsHydrationStatus("ready");
146 } catch (error) {
147 if (hydrationGeneration === clientSettingsHydrationGeneration) {
148 setClientSettingsHydrationStatus("failed");
149 }
150 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
151 operation: "hydrate",
152 ...safeErrorLogAttributes(error),
153 });
154 throw error;
155 }
156 })();
157​
158 const hydrationPromise = nextHydration.finally(() => {
159 if (clientSettingsHydrationPromise === hydrationPromise) {
160 clientSettingsHydrationPromise = null;
161 }
162 });
163 clientSettingsHydrationPromise = hydrationPromise;
164​
165 return clientSettingsHydrationPromise;
167​
168const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
169 ensureLocalApi().persistence.setClientSettings(settings);
170​
171function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
172 const result = clientSettingsPersistenceQueue.then(work);
173 clientSettingsPersistenceQueue = result.then(
174 () => undefined,
175 () => undefined,
176 );
177 return result;
179​
180export function persistClientSettingsPatch(
181 patch: ClientSettingsPatch,
182 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
183): Promise<void> {
184 // Patches queued before hydration must publish before newer optimistic patches.
185 const deferPatch =
186 clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0;
187 if (deferPatch) {
188 deferredClientSettingsPatchCount += 1;
189 } else {
190 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
191 }
192 return enqueueClientSettingsPersistence(async () => {
193 if (deferPatch) {
194 try {
195 if (clientSettingsHydrationStatus !== "ready") {
196 await hydrateClientSettings();
197 }
198 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
199 } finally {
200 deferredClientSettingsPatchCount -= 1;
201 }
202 }
203 await persist(getClientSettingsSnapshot());
204 }).catch((error) => {
205 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
206 operation: "persist",
207 ...safeErrorLogAttributes(error),
208 });
209 });
211​
212/**
213 * If another settings write lands while persistence is pending, the updater is
214 * reapplied to that newer snapshot and persisted again so neither change is
215 * lost.
216 */
217export async function persistClientSettingsUpdate(
218 update: (current: ClientSettings) => ClientSettings,
219 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
220): Promise<ClientSettings> {
221 return enqueueClientSettingsPersistence(async () => {
222 if (clientSettingsHydrationStatus !== "ready") {
223 await hydrateClientSettings();
224 }
225 for (;;) {
226 const current = getClientSettingsSnapshot();
227 const next = update(current);
228 await persist(next);
229 if (getClientSettingsSnapshot() === current) {
230 replaceClientSettingsSnapshot(next);
231 return next;
232 }
233 }
234 });
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 };
257​
258export function getClientSettings(): ClientSettings {
259 return getClientSettingsSnapshot();
261​
262/**
263 * Failed reads reject and remain retryable. They must not allow defaults to overwrite saved
264 * preferences.
265 */
266export function ensureClientSettingsHydrated(): Promise<void> {
267 return hydrateClientSettings();
269​
270export function useClientSettingsHydrated(): boolean {
271 return useSyncExternalStore(
272 subscribeClientSettingsHydration,
273 getClientSettingsHydratedSnapshot,
274 () => false,
275 );
277​
278export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
279 return useSyncExternalStore(
280 subscribeClientSettingsHydration,
281 getClientSettingsHydrationStatusSnapshot,
282 () => "pending",
283 );
285​
286function useClientSettingsValue(): ClientSettings {
287 return useSyncExternalStore(
288 subscribeClientSettings,
289 getClientSettingsSnapshot,
290 () => DEFAULT_CLIENT_SETTINGS,
291 );
293​
294export function mergeEnvironmentSettings(
295 serverSettings: ServerSettings,
296 clientSettings: ClientSettings,
297): UnifiedSettings {
298 // Decode drops retired client keys, but older untyped persistence adapters
299 // can still return them. Server-owned values must always win.
300 return {
301 ...clientSettings,
302 ...serverSettings,
303 ...resolveModelPreferences(serverSettings, clientSettings),
304 };
306​
307const pendingModelPreferencesMigrations = new Set<EnvironmentId>();
308​
309export function useMigrateModelPreferences(
310 environmentId: EnvironmentId | null,
311 settings: ServerSettings | null,
312) {
313 const clientSettings = useClientSettingsValue();
314 const hydrated = useClientSettingsHydrated();
315 const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
316 useEffect(() => {
317 if (
318 !environmentId ||
319 !settings ||
320 !hydrated ||
321 pendingModelPreferencesMigrations.has(environmentId)
322 )
323 return;
324 const patch = modelPreferencesMigrationPatch(settings, clientSettings);
325 if (!patch) return;
326 pendingModelPreferencesMigrations.add(environmentId);
327 void migrate({ environmentId, input: { patch } }).finally(() =>
328 pendingModelPreferencesMigrations.delete(environmentId),
329 );
330 }, [clientSettings, environmentId, hydrated, migrate, settings]);
332​
333// A hook of its own so callers passing an inline selector still get one merged
334// object per settings change instead of one per render.
335function useMergedEnvironmentSettings(
336 serverSettings: ServerSettings,
337 clientSettings: ClientSettings,
338): UnifiedSettings {
339 "use memo";
340 return mergeEnvironmentSettings(serverSettings, clientSettings);
342​
343function useMergedSettings<T>(
344 serverSettings: ServerSettings,
345 selector: ((settings: UnifiedSettings) => T) | undefined,
346): T {
347 const merged = useMergedEnvironmentSettings(serverSettings, useClientSettingsValue());
348 return selector ? selector(merged) : (merged as T);
350​
351export function useClientSettings<T = ClientSettings>(
352 selector?: (settings: ClientSettings) => T,
353): T {
354 const settings = useClientSettingsValue();
355 return selector ? selector(settings) : (settings as T);
357​
358export function resolveEnvironmentIdentificationMode(input: {
359 mode: EnvironmentIdentificationMode;
360 settingsHydrated: boolean;
361 paletteThemeActive?: boolean;
362 paletteThemeAllowsArtwork?: boolean;
363}): EnvironmentIdentificationMode {
364 if (!input.settingsHydrated) return "none";
365 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
366 ? "pill"
367 : input.mode;
369​
370export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
371 const settingsHydrated = useClientSettingsHydrated();
372 const mode = useClientSettingsValue().environmentIdentificationMode;
373 const { resolvedTheme, theme, themeHalves } = useTheme();
374 const previewSidebarArtwork = useSyncExternalStore(
375 subscribeToThemePreview,
376 getThemePreviewSidebarArtwork,
377 () => null,
378 );
379 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
380 const activeThemeDefinition = getThemeDefinition(activeTheme);
381 return resolveEnvironmentIdentificationMode({
382 mode,
383 settingsHydrated,
384 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
385 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
386 });
388​
389/**
390 * Held at the default sidebar until client settings hydrate: the pre-hydration snapshot is just
391 * the schema defaults, so resolving against it could mount one sidebar and then swap it out
392 * once persisted settings land — remounting the whole tree for everyone instead of only for
393 * legacy opt-ins.
394 */
395export function useLegacySidebarEnabled(): boolean {
396 const settingsHydrated = useClientSettingsHydrated();
397 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
398 return settingsHydrated && legacySidebarEnabled;
400​
401export async function prepareModelPreferencesPatch(
402 settings: ServerSettings,
403 patch: ServerSettingsPatch,
404): Promise<ServerSettingsPatch> {
405 if (settings.favorites === null || settings.providerModelPreferences === null) {
406 await ensureClientSettingsHydrated();
407 }
408 return { ...modelPreferencesMigrationPatch(settings, getClientSettings()), ...patch };
410​
411export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
412 const settings = useAtomValue(
413 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
414 );
415 const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update");
416 return async (patch: ServerSettingsPatch) => {
417 if (!environmentId || !settings) return;
418 let prepared: ServerSettingsPatch;
419 try {
420 prepared = await prepareModelPreferencesPatch(settings, patch);
421 } catch {
422 toastManager.add({
423 type: "error",
424 title: "Model preferences not saved",
425 description: "Could not load saved model preferences. Try again.",
426 });
427 return;
428 }
429 return save({ environmentId, input: { patch: prepared } });
430 };
432​
433/** Send the desired state so two clients adding a favorite do not cancel each other. */
434export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId | null) {
435 const registry = use(RegistryContext);
436 const pendingFavorites = useRef(
437 new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
438 );
439 const save = useUpdateEnvironmentModelPreferences(environmentId);
440 return async (provider: ProviderInstanceId, model: string) => {
441 if (!environmentId) return;
442 const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
443 const settings = registry.get(settingsAtom);
444 if (!settings) return;
445 if (settings.favorites === null) {
446 try {
447 await ensureClientSettingsHydrated();
448 } catch {
449 toastManager.add({
450 type: "error",
451 title: "Favorites not saved",
452 description: "Could not load saved model preferences. Try again.",
453 });
454 return;
455 }
456 }
457 const currentSettings = registry.get(settingsAtom) ?? settings;
458 const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
459 const key = JSON.stringify([environmentId, provider, model]);
460 const previous = pendingFavorites.current.get(key);
461 // Keep the acknowledged choice until the config stream catches up with the RPC reply.
462 const previousFavorite =
463 previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
464 ? previous.favorite
465 : favorites.some((favorite) => favorite.provider === provider && favorite.model === model);
466 const pending = {
467 favorite: !previousFavorite,
468 settings: currentSettings,
469 pending: true,
470 };
471 pendingFavorites.current.set(key, pending);
472 // save settles into a result and never rejects, so the rollback below always runs.
473 const result = await save({
474 setModelFavorites: [{ provider, model, favorite: pending.favorite }],
475 });
476 if (
477 result &&
478 AsyncResult.isSuccess(result) &&
479 registry.get(settingsAtom)?.favorites === currentSettings.favorites
480 ) {
481 pending.pending = false;
482 }
483 if (pending.pending && pendingFavorites.current.get(key) === pending) {
484 if (
485 previous &&
486 !previous.pending &&
487 registry.get(settingsAtom)?.favorites === previous.settings.favorites
488 ) {
489 pendingFavorites.current.set(key, previous);
490 } else {
491 pendingFavorites.current.delete(key);
492 }
493 }
494 };
496​
497const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null);
498​
499export function useEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
500 const settings = useAtomValue(
501 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
502 );
503 const legacy = useClientSettingsValue();
504 useMigrateModelPreferences(environmentId, settings);
505 return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);
507​
508export function useEnvironmentSettings<T = UnifiedSettings>(
509 environmentId: EnvironmentId,
510 selector?: (settings: UnifiedSettings) => T,
511): T {
512 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
513 useMigrateModelPreferences(environmentId, serverSettings);
514 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
516​
517export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) {
518 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
519 reportFailure: false,
520 });
521 return (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
522 mutateProviderInstance({
523 environmentId,
524 input: { patch, providerInstanceMutation },
525 });
527​
528export function usePrimarySettings<T = UnifiedSettings>(
529 selector?: (settings: UnifiedSettings) => T,
530): T {
531 const environment = usePrimaryEnvironment();
532 const settings = useAtomValue(primaryServerSettingsAtom);
533 useMigrateModelPreferences(
534 environment?.environmentId ?? null,
535 environment?.serverConfig?.settings ?? null,
536 );
537 return useMergedSettings(settings, selector);
539​
540export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
541 "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.";
542​
543/**
544 * The hosted app connects to every environment as a remote, so it has no
545 * primary: `usePrimarySettings` reads schema defaults there and writes have
546 * nowhere to go.
547 */
548export function usePrimarySettingsAvailable(): boolean {
549 const primaryEnvironment = usePrimaryEnvironment();
550 return primaryEnvironment !== null || !isHostedStaticApp();
552​
553function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
554 const { environments } = useEnvironments();
555 const writableTargetsAtom = Atom.make((get) =>
556 environments.filter(supportsSharedSettingsSync).flatMap((environment) => {
557 const result = get(environmentSession.sessionStateAtom(environment.environmentId));
558 // A cold grant must not drop a shared edit. The server authorizes the
559 // write; mismatch suggestions still wait for a confirmed grant.
560 if (includePending && result._tag === "Initial") {
561 return [environment.environmentId];
562 }
563 const session =
564 result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
565 return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
566 ? [environment.environmentId]
567 : [];
568 }),
569 );
570 return useAtomValue(writableTargetsAtom);
572​
573function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
574 useEnvironmentScope(environmentId, AuthSettingsWriteScope);
575 const persist = useAtomCommand(serverEnvironment.updateSettings, {
576 label: "server settings update",
577 reportFailure: false,
578 });
579 const { environments } = useEnvironments();
580 const persistServerSettings = async (request: Parameters<typeof persist>[0]) => {
581 const result = await persist(request);
582 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
583 const label =
584 environments.find((environment) => environment.environmentId === request.environmentId)
585 ?.label ?? request.environmentId;
586 const error = squashAtomCommandFailure(result);
587 toastManager.add({
588 type: "error",
589 title: "Setting not saved",
590 description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
591 });
592 }
593 return result;
594 };
595 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
596 const updateSettings = (patch: UnifiedSettingsPatch) => {
597 const { serverPatch, clientPatch } = splitPatch(patch);
598​
599 const canWriteServerPatch =
600 environmentId === null ||
601 requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
602 readEnvironmentScope(environmentId, scope),
603 );
604 if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
605 toastManager.add({
606 type: "warning",
607 title: "Setting not saved",
608 description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,
609 });
610 }
611 if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
612 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
613 // Dropping the write silently leaves the control looking saved.
614 const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
615 toastManager.add({
616 type: "warning",
617 title: "Setting not saved",
618 description,
619 });
620 if (Object.keys(localPatch).length > 0) {
621 if (environmentId) {
622 void persistServerSettings({
623 environmentId,
624 input: { patch: localPatch },
625 });
626 } else {
627 warnUnsaved();
628 }
629 }
630 if (Object.keys(sharedPatch).length > 0) {
631 const sourceSettings = environments.find((target) => target.environmentId === environmentId)
632 ?.serverConfig?.settings;
633 const targets = new Set(sharedSettingsSyncTargetIds);
634 if (environmentId) {
635 targets.add(environmentId);
636 }
637 const writes: Array<Parameters<typeof persist>[0]> = [];
638 const deniedLabels: string[] = [];
639 for (const targetId of targets) {
640 const target = environments.find((candidate) => candidate.environmentId === targetId);
641 const targetPatch = filterSharedServerPatch(
642 sharedPatch,
643 target?.serverConfig?.environment.capabilities,
644 target?.serverConfig?.settings,
645 sourceSettings,
646 targetId === environmentId,
647 );
648 if (Object.keys(targetPatch).length === 0) continue;
649 const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
650 if (
651 session._tag !== "Initial" &&
652 !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
653 readEnvironmentScope(targetId, scope),
654 )
655 ) {
656 deniedLabels.push(target?.label ?? targetId);
657 continue;
658 }
659 writes.push({
660 environmentId: targetId,
661 input: { patch: targetPatch },
662 });
663 }
664 if (writes.length === 0) {
665 warnUnsaved(
666 deniedLabels.length > 0
667 ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`
668 : targets.size > 0
669 ? "Update older servers to save this setting."
670 : undefined,
671 );
672 } else {
673 void Promise.all(
674 writes.map(async (request) => ({
675 label:
676 environments.find((target) => target.environmentId === request.environmentId)
677 ?.label ?? request.environmentId,
678 result: await persist(request),
679 })),
680 ).then((outcomes) => {
681 const failures = outcomes.flatMap(({ label, result }) => {
682 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
683 const error = squashAtomCommandFailure(result);
684 return [
685 `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
686 ];
687 });
688 if (failures.length === 0) return;
689 const saved = outcomes
690 .filter(({ result }) => result._tag === "Success")
691 .map(({ label }) => label);
692 toastManager.add({
693 type: "error",
694 title: saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",
695 description: [
696 ...failures,
697 ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),
698 ].join("\n"),
699 });
700 });
701 }
702 }
703 }
704 if (Object.keys(clientPatch).length > 0) {
705 void persistClientSettingsPatch(clientPatch);
706 }
707 };
708​
709 return updateSettings;
711​
712export function useUpdateEnvironmentSettings(environmentId: EnvironmentId | null) {
713 return useUpdateSettingsTarget(environmentId);
715​
716export function useUpdatePrimarySettings() {
717 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
719​
720export function useUpdateClientSettings() {
721 return (patch: ClientSettingsPatch) => persistClientSettingsPatch(patch);
723​
724export function __resetClientSettingsPersistenceForTests(): void {
725 clientSettingsHydrationGeneration += 1;
726 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
727 clientSettingsHydrationStatus = "pending";
728 clientSettingsHydrationPromise = null;
729 clientSettingsPersistenceQueue = Promise.resolve();
730 deferredClientSettingsPatchCount = 0;
731 clientSettingsListeners.clear();
732 clientSettingsHydrationListeners.clear();
734​
735export function __setClientSettingsForTests(settings: ClientSettings): void {
736 clientSettingsHydrationGeneration += 1;
737 clientSettingsSnapshot = settings;
738 clientSettingsHydrationStatus = "ready";
739 clientSettingsHydrationPromise = null;