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