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
418/** Legacy sidebar opt-ins still count, so those users land in the boring sidebar. */
419export function useBoringSidebarEnabled(): boolean {
420 return useClientSettings(
421 (settings) => settings.boringSidebarEnabled || settings.legacySidebarEnabled,
422 );
423}
424
425export async function prepareModelPreferencesPatch(
426 settings: ServerSettings,
427 patch: ServerSettingsPatch,
428): Promise<ServerSettingsPatch> {
429 if (settings.favorites === null || settings.providerModelPreferences === null) {
430 await ensureClientSettingsHydrated();
431 }
432 return { ...modelPreferencesMigrationPatch(settings, getClientSettings()), ...patch };
433}
434
435export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
436 const settings = useAtomValue(
437 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
438 );
439 const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update");
440 return async (patch: ServerSettingsPatch) => {
441 if (!environmentId || !settings) return;
442 let prepared: ServerSettingsPatch;
443 try {
444 prepared = await prepareModelPreferencesPatch(settings, patch);
445 } catch {
446 toastManager.add({
447 type: "error",
448 title: "Model preferences not saved",
449 description: "Could not load saved model preferences. Try again.",
450 });
451 return;
452 }
453 return save({ environmentId, input: { patch: prepared } });
454 };
455}
456
457/** Send the desired state so two clients adding a favorite do not cancel each other. */
458export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId | null) {
459 const registry = use(RegistryContext);
460 const pendingFavorites = useRef(
461 new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
462 );
463 const save = useUpdateEnvironmentModelPreferences(environmentId);
464 return async (provider: ProviderInstanceId, model: string) => {
465 if (!environmentId) return;
466 const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
467 const settings = registry.get(settingsAtom);
468 if (!settings) return;
469 if (settings.favorites === null) {
470 try {
471 await ensureClientSettingsHydrated();
472 } catch {
473 toastManager.add({
474 type: "error",
475 title: "Favorites not saved",
476 description: "Could not load saved model preferences. Try again.",
477 });
478 return;
479 }
480 }
481 const currentSettings = registry.get(settingsAtom) ?? settings;
482 const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
483 const key = JSON.stringify([environmentId, provider, model]);
484 const previous = pendingFavorites.current.get(key);
485 // Keep the acknowledged choice until the config stream catches up with the RPC reply.
486 const previousFavorite =
487 previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
488 ? previous.favorite
489 : favorites.some((favorite) => favorite.provider === provider && favorite.model === model);
490 const pending = {
491 favorite: !previousFavorite,
492 settings: currentSettings,
493 pending: true,
494 };
495 pendingFavorites.current.set(key, pending);
496 const result = await save({
497 setModelFavorites: [{ provider, model, favorite: pending.favorite }],
498 });
499 if (
500 result &&
501 AsyncResult.isSuccess(result) &&
502 registry.get(settingsAtom)?.favorites === currentSettings.favorites
503 ) {
504 pending.pending = false;
505 }
506 if (pending.pending && pendingFavorites.current.get(key) === pending) {
507 if (
508 previous &&
509 !previous.pending &&
510 registry.get(settingsAtom)?.favorites === previous.settings.favorites
511 ) {
512 pendingFavorites.current.set(key, previous);
513 } else {
514 pendingFavorites.current.delete(key);
515 }
516 }
517 };
518}
519
520const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null);
521
522export function useEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
523 const settings = useAtomValue(
524 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
525 );
526 const legacy = useClientSettings(selectLegacyModelPreferences);
527 return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);
528}
529
530export function useEnvironmentSettings<T = UnifiedSettings>(
531 environmentId: EnvironmentId,
532 selector?: (settings: UnifiedSettings) => T,
533): T {
534 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
535 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
536}
537
538export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) {
539 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
540 reportFailure: false,
541 });
542 return (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
543 mutateProviderInstance({
544 environmentId,
545 input: { patch, providerInstanceMutation },
546 });
547}
548
549export function usePrimarySettings<T = UnifiedSettings>(
550 selector?: (settings: UnifiedSettings) => T,
551): T {
552 const settings = useAtomValue(primaryServerSettingsAtom);
553 return useMergedSettings(settings, selector);
554}
555
556export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
557 "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.";
558
559/** Hosted clients have no primary: usePrimarySettings reads defaults and cannot write. */
560export function usePrimarySettingsAvailable(): boolean {
561 const primaryEnvironment = usePrimaryEnvironment();
562 return primaryEnvironment !== null || !isHostedStaticApp();
563}
564
565function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
566 const { environments } = useEnvironments();
567 const targetIds = environments
568 .filter(supportsSharedSettingsSync)
569 .map(({ environmentId }) => environmentId);
570 const results = useAtomValue(environmentSessionStatesAtom(environmentIdsKey(targetIds)));
571 return targetIds.flatMap((environmentId, index) => {
572 const result = results[index]!;
573 // Let the server authorize shared edits with cold grants; suggestions still need confirmed grants.
574 if (includePending && result._tag === "Initial") {
575 return [environmentId];
576 }
577 const session = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null);
578 return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
579 ? [environmentId]
580 : [];
581 });
582}
583
584function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
585 useEnvironmentScope(environmentId, AuthSettingsWriteScope);
586 const persist = useAtomCommand(serverEnvironment.updateSettings, {
587 label: "server settings update",
588 reportFailure: false,
589 });
590 const { environments } = useEnvironments();
591 const persistServerSettings = async (
592 request: Parameters<typeof persist>[0],
593 onFailed?: () => void,
594 ) => {
595 const result = await persist(request);
596 if (result._tag === "Failure") onFailed?.();
597 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
598 const label =
599 environments.find((environment) => environment.environmentId === request.environmentId)
600 ?.label ?? request.environmentId;
601 const error = squashAtomCommandFailure(result);
602 toastManager.add({
603 type: "error",
604 title: "Setting not saved",
605 description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
606 });
607 }
608 return result;
609 };
610 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
611 const updateSettings = (
612 patch: UnifiedSettingsPatch,
613 options?: { readonly onFailed?: () => void },
614 ) => {
615 const { serverPatch, clientPatch } = splitPatch(patch);
616
617 const canWriteServerPatch =
618 environmentId === null ||
619 requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
620 readEnvironmentScope(environmentId, scope),
621 );
622 if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
623 options?.onFailed?.();
624 toastManager.add({
625 type: "warning",
626 title: "Setting not saved",
627 description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,
628 });
629 }
630 if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
631 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
632 // Dropping the write silently leaves the control looking saved.
633 const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) => {
634 options?.onFailed?.();
635 return toastManager.add({
636 type: "warning",
637 title: "Setting not saved",
638 description,
639 });
640 };
641 if (Object.keys(localPatch).length > 0) {
642 if (environmentId) {
643 void persistServerSettings(
644 { environmentId, input: { patch: localPatch } },
645 options?.onFailed,
646 );
647 } else {
648 warnUnsaved();
649 }
650 }
651 if (Object.keys(sharedPatch).length > 0) {
652 const sourceSettings = environments.find((target) => target.environmentId === environmentId)
653 ?.serverConfig?.settings;
654 const targets = new Set(sharedSettingsSyncTargetIds);
655 if (environmentId) {
656 targets.add(environmentId);
657 }
658 const writes: Array<Parameters<typeof persist>[0]> = [];
659 const deniedLabels: string[] = [];
660 for (const targetId of targets) {
661 const target = environments.find((candidate) => candidate.environmentId === targetId);
662 const targetPatch = filterSharedServerPatch(
663 sharedPatch,
664 target?.serverConfig?.settings,
665 sourceSettings,
666 targetId === environmentId,
667 );
668 if (Object.keys(targetPatch).length === 0) continue;
669 const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
670 if (
671 session._tag !== "Initial" &&
672 !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
673 readEnvironmentScope(targetId, scope),
674 )
675 ) {
676 deniedLabels.push(target?.label ?? targetId);
677 continue;
678 }
679 writes.push({
680 environmentId: targetId,
681 input: { patch: targetPatch },
682 });
683 }
684 if (writes.length === 0) {
685 warnUnsaved(
686 deniedLabels.length > 0
687 ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`
688 : targets.size > 0
689 ? "Update older servers to save this setting."
690 : undefined,
691 );
692 } else {
693 void Promise.all(
694 writes.map(async (request) => ({
695 label:
696 environments.find((target) => target.environmentId === request.environmentId)
697 ?.label ?? request.environmentId,
698 result: await persist(request),
699 })),
700 ).then((outcomes) => {
701 if (
702 deniedLabels.length > 0 ||
703 outcomes.some(({ result }) => result._tag === "Failure")
704 ) {
705 options?.onFailed?.();
706 }
707 const failures = outcomes.flatMap(({ label, result }) => {
708 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
709 const error = squashAtomCommandFailure(result);
710 return [
711 `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
712 ];
713 });
714 if (failures.length === 0) return;
715 const saved = outcomes
716 .filter(({ result }) => result._tag === "Success")
717 .map(({ label }) => label);
718 toastManager.add({
719 type: "error",
720 title: saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",
721 description: [
722 ...failures,
723 ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),
724 ].join("\n"),
725 });
726 });
727 }
728 }
729 }
730 if (Object.keys(clientPatch).length > 0) {
731 void persistClientSettingsPatch(clientPatch);
732 }
733 };
734
735 return updateSettings;
736}
737
738export function useUpdateEnvironmentSettings(environmentId: EnvironmentId | null) {
739 return useUpdateSettingsTarget(environmentId);
740}
741
742export function useUpdatePrimarySettings() {
743 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
744}
745
746export function updateClientSettings(patch: ClientSettingsPatch): Promise<void> {
747 return persistClientSettingsPatch(patch);
748}
749
750export function __resetClientSettingsPersistenceForTests(): void {
751 clientSettingsHydrationGeneration += 1;
752 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
753 clientSettingsHydrationStatus = "pending";
754 clientSettingsHydrationPromise = null;
755 clientSettingsPersistenceQueue = Promise.resolve();
756 deferredClientSettingsPatchCount = 0;
757 clientSettingsListeners.clear();
758 clientSettingsHydrationListeners.clear();
759}
760
761export function __setClientSettingsForTests(settings: ClientSettings): void {
762 clientSettingsHydrationGeneration += 1;
763 clientSettingsSnapshot = settings;
764 clientSettingsHydrationStatus = "ready";
765 clientSettingsHydrationPromise = null;
766}