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