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