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
116function getClientSettingsHydratedSnapshot(): boolean {
117 return clientSettingsHydrationStatus === "ready";
118}
119
120function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
121 return clientSettingsHydrationStatus;
122}
123
124function 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
268/** Failed reads reject and remain retryable so defaults cannot overwrite saved preferences. */
269export function ensureClientSettingsHydrated(): Promise<void> {
270 return hydrateClientSettings();
271}
272
273export function useClientSettingsHydrated(): boolean {
274 return useSyncExternalStore(
275 subscribeClientSettingsHydration,
276 getClientSettingsHydratedSnapshot,
277 () => false,
278 );
279}
280
281export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
282 return useSyncExternalStore(
283 subscribeClientSettingsHydration,
284 getClientSettingsHydrationStatusSnapshot,
285 () => "pending",
286 );
287}
288
289const getDefaultClientSettings = () => DEFAULT_CLIENT_SETTINGS;
290const selectWholeClientSettings = (settings: ClientSettings) => settings;
291
292/** Structurally equal selections retain their reference and skip rendering. */
293export function useClientSettings<T = ClientSettings>(
294 selector?: (settings: ClientSettings) => T,
295): T {
296 return useSyncExternalStoreWithSelector(
297 subscribeClientSettings,
298 getClientSettingsSnapshot,
299 getDefaultClientSettings,
300 selector ?? (selectWholeClientSettings as (settings: ClientSettings) => T),
301 Equal.equals,
302 );
303}
304
305export function mergeEnvironmentSettings(
306 serverSettings: ServerSettings,
307 clientSettings: ClientSettings,
308): UnifiedSettings {
309 // Older untyped adapters can return retired client keys; server values must win.
310 return {
311 ...clientSettings,
312 ...serverSettings,
313 ...resolveModelPreferences(serverSettings, clientSettings),
314 };
315}
316
317const selectLegacyModelPreferences = (settings: ClientSettings) => ({
318 favorites: settings.favorites,
319 providerModelPreferences: settings.providerModelPreferences,
320});
321
322// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
323const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
324
325const modelPreferencesMigrationTargetsAtom = Atom.make((get) =>
326 [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => {
327 const generation = Option.match(
328 AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
329 {
330 onNone: () => null,
331 onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),
332 },
333 );
334 const settings = get(serverEnvironment.settingsValueAtom(environmentId));
335 return generation === null || settings === null
336 ? []
337 : [{ environmentId, generation, settings }];
338 }),
339).pipe(Atom.withLabel("web-model-preferences-migration-targets"));
340
341function migrateModelPreferences(): void {
342 if (clientSettingsHydrationStatus !== "ready") return;
343 for (const { environmentId, generation, settings } of appAtomRegistry.get(
344 modelPreferencesMigrationTargetsAtom,
345 )) {
346 if (attemptedMigrationGenerations.get(environmentId) === generation) continue;
347 const patch = modelPreferencesMigrationPatch(settings, clientSettingsSnapshot);
348 if (!patch) continue;
349 attemptedMigrationGenerations.set(environmentId, generation);
350 void runAtomCommand(
351 appAtomRegistry,
352 serverEnvironment.updateSettings,
353 { environmentId, input: { patch } },
354 { reportFailure: false },
355 );
356 }
357}
358
359/** Moves this client's legacy model preferences onto each server, once per connection. */
360export function startModelPreferencesMigration(): () => void {
361 const unsubscribes = [
362 appAtomRegistry.subscribe(modelPreferencesMigrationTargetsAtom, migrateModelPreferences),
363 subscribeClientSettings(migrateModelPreferences),
364 subscribeClientSettingsHydration(migrateModelPreferences),
365 ];
366 migrateModelPreferences();
367 return () => {
368 for (const unsubscribe of unsubscribes) unsubscribe();
369 };
370}
371
372export function useMergedSettings<T = UnifiedSettings>(
373 serverSettings: ServerSettings,
374 selector?: (settings: UnifiedSettings) => T,
375): T {
376 return useClientSettings((clientSettings) => {
377 const merged = mergeEnvironmentSettings(serverSettings, clientSettings);
378 return selector ? selector(merged) : (merged as T);
379 });
380}
381
382export function resolveEnvironmentIdentificationMode(input: {
383 mode: EnvironmentIdentificationMode;
384 settingsHydrated: boolean;
385 paletteThemeActive?: boolean;
386 paletteThemeAllowsArtwork?: boolean;
387}): EnvironmentIdentificationMode {
388 if (!input.settingsHydrated) return "none";
389 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
390 ? "pill"
391 : input.mode;
392}
393
394export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
395 const settingsHydrated = useClientSettingsHydrated();
396 const mode = useClientSettings((settings) => settings.environmentIdentificationMode);
397 const { resolvedTheme, theme, themeHalves } = useTheme();
398 const previewSidebarArtwork = useSyncExternalStore(
399 subscribeToThemePreview,
400 getThemePreviewSidebarArtwork,
401 () => null,
402 );
403 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
404 const activeThemeDefinition = getThemeDefinition(activeTheme);
405 return resolveEnvironmentIdentificationMode({
406 mode,
407 settingsHydrated,
408 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
409 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
410 });
411}
412
413/** Wait for hydration: swapping sidebar implementations after mount remounts the whole tree. */
414export function useLegacySidebarEnabled(): boolean {
415 const settingsHydrated = useClientSettingsHydrated();
416 const legacySidebarEnabled = useClientSettings((settings) => settings.legacySidebarEnabled);
417 return settingsHydrated && legacySidebarEnabled;
418}
419
420export async function prepareModelPreferencesPatch(
421 settings: ServerSettings,
422 patch: ServerSettingsPatch,
423): Promise<ServerSettingsPatch> {
424 if (settings.favorites === null || settings.providerModelPreferences === null) {
425 await ensureClientSettingsHydrated();
426 }
427 return { ...modelPreferencesMigrationPatch(settings, getClientSettings()), ...patch };
428}
429
430export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
431 const settings = useAtomValue(
432 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
433 );
434 const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update");
435 return async (patch: ServerSettingsPatch) => {
436 if (!environmentId || !settings) return;
437 let prepared: ServerSettingsPatch;
438 try {
439 prepared = await prepareModelPreferencesPatch(settings, patch);
440 } catch {
441 toastManager.add({
442 type: "error",
443 title: "Model preferences not saved",
444 description: "Could not load saved model preferences. Try again.",
445 });
446 return;
447 }
448 return save({ environmentId, input: { patch: prepared } });
449 };
450}
451
452/** Send the desired state so two clients adding a favorite do not cancel each other. */
453export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId | null) {
454 const registry = use(RegistryContext);
455 const pendingFavorites = useRef(
456 new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
457 );
458 const save = useUpdateEnvironmentModelPreferences(environmentId);
459 return async (provider: ProviderInstanceId, model: string) => {
460 if (!environmentId) return;
461 const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
462 const settings = registry.get(settingsAtom);
463 if (!settings) return;
464 if (settings.favorites === null) {
465 try {
466 await ensureClientSettingsHydrated();
467 } catch {
468 toastManager.add({
469 type: "error",
470 title: "Favorites not saved",
471 description: "Could not load saved model preferences. Try again.",
472 });
473 return;
474 }
475 }
476 const currentSettings = registry.get(settingsAtom) ?? settings;
477 const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
478 const key = JSON.stringify([environmentId, provider, model]);
479 const previous = pendingFavorites.current.get(key);
480 // Keep the acknowledged choice until the config stream catches up with the RPC reply.
481 const previousFavorite =
482 previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
483 ? previous.favorite
484 : favorites.some((favorite) => favorite.provider === provider && favorite.model === model);
485 const pending = {
486 favorite: !previousFavorite,
487 settings: currentSettings,
488 pending: true,
489 };
490 pendingFavorites.current.set(key, pending);
491 const result = await save({
492 setModelFavorites: [{ provider, model, favorite: pending.favorite }],
493 });
494 if (
495 result &&
496 AsyncResult.isSuccess(result) &&
497 registry.get(settingsAtom)?.favorites === currentSettings.favorites
498 ) {
499 pending.pending = false;
500 }
501 if (pending.pending && pendingFavorites.current.get(key) === pending) {
502 if (
503 previous &&
504 !previous.pending &&
505 registry.get(settingsAtom)?.favorites === previous.settings.favorites
506 ) {
507 pendingFavorites.current.set(key, previous);
508 } else {
509 pendingFavorites.current.delete(key);
510 }
511 }
512 };
513}
514
515const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null);
516
517export function useEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
518 const settings = useAtomValue(
519 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
520 );
521 const legacy = useClientSettings(selectLegacyModelPreferences);
522 return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);
523}
524
525export function useEnvironmentSettings<T = UnifiedSettings>(
526 environmentId: EnvironmentId,
527 selector?: (settings: UnifiedSettings) => T,
528): T {
529 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
530 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
531}
532
533export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) {
534 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
535 reportFailure: false,
536 });
537 return (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
538 mutateProviderInstance({
539 environmentId,
540 input: { patch, providerInstanceMutation },
541 });
542}
543
544export function usePrimarySettings<T = UnifiedSettings>(
545 selector?: (settings: UnifiedSettings) => T,
546): T {
547 const settings = useAtomValue(primaryServerSettingsAtom);
548 return useMergedSettings(settings, selector);
549}
550
551export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
552 "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.";
553
554/** Hosted clients have no primary: usePrimarySettings reads defaults and cannot write. */
555export function usePrimarySettingsAvailable(): boolean {
556 const primaryEnvironment = usePrimaryEnvironment();
557 return primaryEnvironment !== null || !isHostedStaticApp();
558}
559
560function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
561 const { environments } = useEnvironments();
562 const targetIds = environments
563 .filter(supportsSharedSettingsSync)
564 .map(({ environmentId }) => environmentId);
565 const results = useAtomValue(environmentSessionStatesAtom(environmentIdsKey(targetIds)));
566 return targetIds.flatMap((environmentId, index) => {
567 const result = results[index]!;
568 // Let the server authorize shared edits with cold grants; suggestions still need confirmed grants.
569 if (includePending && result._tag === "Initial") {
570 return [environmentId];
571 }
572 const session = result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
573 return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
574 ? [environmentId]
575 : [];
576 });
577}
578
579function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
580 useEnvironmentScope(environmentId, AuthSettingsWriteScope);
581 const persist = useAtomCommand(serverEnvironment.updateSettings, {
582 label: "server settings update",
583 reportFailure: false,
584 });
585 const { environments } = useEnvironments();
586 const persistServerSettings = async (request: Parameters<typeof persist>[0]) => {
587 const result = await persist(request);
588 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
589 const label =
590 environments.find((environment) => environment.environmentId === request.environmentId)
591 ?.label ?? request.environmentId;
592 const error = squashAtomCommandFailure(result);
593 toastManager.add({
594 type: "error",
595 title: "Setting not saved",
596 description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
597 });
598 }
599 return result;
600 };
601 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
602 const updateSettings = (patch: UnifiedSettingsPatch) => {
603 const { serverPatch, clientPatch } = splitPatch(patch);
604
605 const canWriteServerPatch =
606 environmentId === null ||
607 requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
608 readEnvironmentScope(environmentId, scope),
609 );
610 if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
611 toastManager.add({
612 type: "warning",
613 title: "Setting not saved",
614 description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,
615 });
616 }
617 if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
618 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
619 // Dropping the write silently leaves the control looking saved.
620 const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
621 toastManager.add({
622 type: "warning",
623 title: "Setting not saved",
624 description,
625 });
626 if (Object.keys(localPatch).length > 0) {
627 if (environmentId) {
628 void persistServerSettings({
629 environmentId,
630 input: { patch: localPatch },
631 });
632 } else {
633 warnUnsaved();
634 }
635 }
636 if (Object.keys(sharedPatch).length > 0) {
637 const sourceSettings = environments.find((target) => target.environmentId === environmentId)
638 ?.serverConfig?.settings;
639 const targets = new Set(sharedSettingsSyncTargetIds);
640 if (environmentId) {
641 targets.add(environmentId);
642 }
643 const writes: Array<Parameters<typeof persist>[0]> = [];
644 const deniedLabels: string[] = [];
645 for (const targetId of targets) {
646 const target = environments.find((candidate) => candidate.environmentId === targetId);
647 const targetPatch = filterSharedServerPatch(
648 sharedPatch,
649 target?.serverConfig?.environment.capabilities,
650 target?.serverConfig?.settings,
651 sourceSettings,
652 targetId === environmentId,
653 );
654 if (Object.keys(targetPatch).length === 0) continue;
655 const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
656 if (
657 session._tag !== "Initial" &&
658 !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
659 readEnvironmentScope(targetId, scope),
660 )
661 ) {
662 deniedLabels.push(target?.label ?? targetId);
663 continue;
664 }
665 writes.push({
666 environmentId: targetId,
667 input: { patch: targetPatch },
668 });
669 }
670 if (writes.length === 0) {
671 warnUnsaved(
672 deniedLabels.length > 0
673 ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`
674 : targets.size > 0
675 ? "Update older servers to save this setting."
676 : undefined,
677 );
678 } else {
679 void Promise.all(
680 writes.map(async (request) => ({
681 label:
682 environments.find((target) => target.environmentId === request.environmentId)
683 ?.label ?? request.environmentId,
684 result: await persist(request),
685 })),
686 ).then((outcomes) => {
687 const failures = outcomes.flatMap(({ label, result }) => {
688 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
689 const error = squashAtomCommandFailure(result);
690 return [
691 `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
692 ];
693 });
694 if (failures.length === 0) return;
695 const saved = outcomes
696 .filter(({ result }) => result._tag === "Success")
697 .map(({ label }) => label);
698 toastManager.add({
699 type: "error",
700 title: saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",
701 description: [
702 ...failures,
703 ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),
704 ].join("\n"),
705 });
706 });
707 }
708 }
709 }
710 if (Object.keys(clientPatch).length > 0) {
711 void persistClientSettingsPatch(clientPatch);
712 }
713 };
714
715 return updateSettings;
716}
717
718export function useUpdateEnvironmentSettings(environmentId: EnvironmentId | null) {
719 return useUpdateSettingsTarget(environmentId);
720}
721
722export function useUpdatePrimarySettings() {
723 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
724}
725
726export function updateClientSettings(patch: ClientSettingsPatch): Promise<void> {
727 return persistClientSettingsPatch(patch);
728}
729
730export function __resetClientSettingsPersistenceForTests(): void {
731 clientSettingsHydrationGeneration += 1;
732 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
733 clientSettingsHydrationStatus = "pending";
734 clientSettingsHydrationPromise = null;
735 clientSettingsPersistenceQueue = Promise.resolve();
736 deferredClientSettingsPatchCount = 0;
737 clientSettingsListeners.clear();
738 clientSettingsHydrationListeners.clear();
739}
740
741export function __setClientSettingsForTests(settings: ClientSettings): void {
742 clientSettingsHydrationGeneration += 1;
743 clientSettingsSnapshot = settings;
744 clientSettingsHydrationStatus = "ready";
745 clientSettingsHydrationPromise = null;
746}