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