Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useSettings.ts

827 lines29.6 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { useRef, useSyncExternalStore, use } from "react";
3import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector";
4import { RegistryContext, useAtomValue } from "@effect/atom-react";
5import {
6 DEFAULT_SERVER_SETTINGS,
7 AuthSettingsWriteScope,
8 requiredScopesForServerSettingsPatch,
9 type EnvironmentId,
10 type ProviderInstanceMutation,
11 type ProviderInstanceId,
12 ServerSettings,
13 type ServerSettingsPatch,
14 sessionGrantsScope,
15} from "@t3tools/contracts";
16import {
17 type ClientSettingsPatch,
18 type ClientSettings,
19 DEFAULT_CLIENT_SETTINGS,
20 type EnvironmentIdentificationMode,
21 type UnifiedSettings,
22} from "@t3tools/contracts/settings";
23import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
24import {
25 isAtomCommandInterrupted,
26 runAtomCommand,
27 squashAtomCommandFailure,
28} from "@t3tools/client-runtime/state/runtime";
29import {
30 filterSharedServerPatch,
31 splitSharedServerPatch,
32 supportsSharedSettingsSync,
33} from "@t3tools/client-runtime/state/shared-settings";
34import { ensureLocalApi } from "~/localApi";
35import { subscribeBrowserClientSettingsWrites } from "~/clientPersistenceStorage";
36import {
37 getThemeDefinition,
38 getThemePreviewSidebarArtwork,
39 resolveThemeHalf,
40 subscribeToThemePreview,
41 themeAllowsSidebarArtwork,
42} from "~/themePalette";
43import {
44 modelPreferencesMigrationPatch,
45 resolveModelPreferences,
46} from "@t3tools/shared/serverSettings";
47import * as Equal from "effect/Equal";
48import * as Struct from "effect/Struct";
49import * as Option from "effect/Option";
50import { AsyncResult, Atom } from "effect/reactivity";
51import { toastManager } from "~/components/ui/toast";
52import { isHostedStaticApp } from "~/hostedPairing";
53import { environmentCatalog } from "~/connection/catalog";
54import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
55import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
56import { useAtomCommand } from "~/state/use-atom-command";
57import { useTheme } from "./useTheme";
58import { msg } from "gt-react";
59import { m } from "~/i18n/messages";
60import {
61 environmentSession,
62 environmentSessionStatesAtom,
63 readEnvironmentScope,
64 useEnvironmentScope,
65} from "~/state/session";
66import { environmentIdsKey } from "~/state/environmentAtomList";
67import { appAtomRegistry } from "~/rpc/atomRegistry";
68​
69const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
70​
71type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
72​
73const clientSettingsListeners = new Set<() => void>();
74const clientSettingsHydrationListeners = new Set<() => void>();
75type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying";
76let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
77let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending";
78let clientSettingsHydrationPromise: Promise<void> | null = null;
79let clientSettingsHydrationGeneration = 0;
80let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
81let deferredClientSettingsPatchCount = 0;
82let unsubscribeOtherTabClientSettings: (() => void) | null = null;
83​
84function emitClientSettingsChange() {
85 for (const listener of clientSettingsListeners) {
86 listener();
87 }
89​
90function emitClientSettingsHydrationChange() {
91 for (const listener of clientSettingsHydrationListeners) {
92 listener();
93 }
95​
96function getClientSettingsSnapshot(): ClientSettings {
97 return clientSettingsSnapshot;
99​
100function replaceClientSettingsSnapshot(settings: ClientSettings): void {
101 clientSettingsSnapshot = settings;
102 emitClientSettingsChange();
104​
105function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void {
106 if (clientSettingsHydrationStatus === nextStatus) {
107 return;
108 }
109 clientSettingsHydrationStatus = nextStatus;
110 emitClientSettingsHydrationChange();
112​
113export function subscribeClientSettings(listener: () => void): () => void {
114 clientSettingsListeners.add(listener);
115 void hydrateClientSettings().catch(() => undefined);
116 return () => {
117 clientSettingsListeners.delete(listener);
118 };
120​
121export function getClientSettingsHydratedSnapshot(): boolean {
122 return clientSettingsHydrationStatus === "ready";
124​
125function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
126 return clientSettingsHydrationStatus;
128​
129export function subscribeClientSettingsHydration(listener: () => void): () => void {
130 clientSettingsHydrationListeners.add(listener);
131 void hydrateClientSettings().catch(() => undefined);
132 return () => {
133 clientSettingsHydrationListeners.delete(listener);
134 };
136​
137async function hydrateClientSettings(): Promise<void> {
138 if (clientSettingsHydrationStatus === "ready") {
139 return;
140 }
141 if (clientSettingsHydrationPromise) {
142 return clientSettingsHydrationPromise;
143 }
144​
145 const hydrationGeneration = clientSettingsHydrationGeneration;
146 setClientSettingsHydrationStatus(
147 clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying"
148 ? "retrying"
149 : "pending",
150 );
151 const nextHydration = (async () => {
152 try {
153 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
154 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
155 return;
156 }
157 if (persistedSettings) {
158 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
159 }
160 unsubscribeOtherTabClientSettings ??= subscribeBrowserClientSettingsWrites(
161 refreshClientSettingsFromOtherTab,
162 );
163 setClientSettingsHydrationStatus("ready");
164 } catch (error) {
165 if (hydrationGeneration === clientSettingsHydrationGeneration) {
166 setClientSettingsHydrationStatus("failed");
167 }
168 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
169 operation: "hydrate",
170 ...safeErrorLogAttributes(error),
171 });
172 throw error;
173 }
174 })();
175​
176 const hydrationPromise = nextHydration.finally(() => {
177 if (clientSettingsHydrationPromise === hydrationPromise) {
178 clientSettingsHydrationPromise = null;
179 }
180 });
181 clientSettingsHydrationPromise = hydrationPromise;
182​
183 return clientSettingsHydrationPromise;
185​
186function refreshClientSettingsFromOtherTab(): void {
187 void enqueueClientSettingsPersistence(async () => {
188 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
189 if (persistedSettings) {
190 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
191 }
192 }).catch((error) => {
193 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} refresh failed`, {
194 operation: "refresh",
195 ...safeErrorLogAttributes(error),
196 });
197 });
199​
200const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
201 ensureLocalApi().persistence.setClientSettings(settings);
202​
203function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
204 const result = clientSettingsPersistenceQueue.then(work);
205 clientSettingsPersistenceQueue = result.then(
206 () => undefined,
207 () => undefined,
208 );
209 return result;
211​
212export function persistClientSettingsPatch(
213 patch: ClientSettingsPatch,
214 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
215): Promise<void> {
216 // Patches queued before hydration must publish before newer optimistic patches.
217 const deferPatch =
218 clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0;
219 if (deferPatch) {
220 deferredClientSettingsPatchCount += 1;
221 } else {
222 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
223 }
224 return enqueueClientSettingsPersistence(async () => {
225 if (deferPatch) {
226 try {
227 if (clientSettingsHydrationStatus !== "ready") {
228 await hydrateClientSettings();
229 }
230 } finally {
231 deferredClientSettingsPatchCount -= 1;
232 }
233 }
234 // Also reapplies an optimistic patch that a refresh from another tab replaced.
235 const current = getClientSettingsSnapshot();
236 if (
237 !Object.entries(patch).every(([key, value]) => current[key as keyof ClientSettings] === value)
238 ) {
239 replaceClientSettingsSnapshot({ ...current, ...patch });
240 }
241 await persist(getClientSettingsSnapshot());
242 }).catch((error) => {
243 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
244 operation: "persist",
245 ...safeErrorLogAttributes(error),
246 });
247 });
249​
250/** Reapply to newer snapshots after pending writes to avoid losing concurrent changes. */
251export async function persistClientSettingsUpdate(
252 update: (current: ClientSettings) => ClientSettings,
253 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
254): Promise<ClientSettings> {
255 return enqueueClientSettingsPersistence(async () => {
256 if (clientSettingsHydrationStatus !== "ready") {
257 await hydrateClientSettings();
258 }
259 for (;;) {
260 const current = getClientSettingsSnapshot();
261 const next = update(current);
262 await persist(next);
263 if (getClientSettingsSnapshot() === current) {
264 replaceClientSettingsSnapshot(next);
265 return next;
266 }
267 }
268 });
270​
271const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
272​
273function splitPatch(patch: UnifiedSettingsPatch): {
274 serverPatch: ServerSettingsPatch;
275 clientPatch: ClientSettingsPatch;
276} {
277 const serverPatch: Record<string, unknown> = {};
278 const clientPatch: Record<string, unknown> = {};
279 for (const [key, value] of Object.entries(patch)) {
280 if (SERVER_SETTINGS_KEYS.has(key)) {
281 serverPatch[key] = value;
282 } else {
283 clientPatch[key] = value;
284 }
285 }
286 return {
287 serverPatch: serverPatch as ServerSettingsPatch,
288 clientPatch: clientPatch as ClientSettingsPatch,
289 };
291​
292export function getClientSettings(): ClientSettings {
293 return getClientSettingsSnapshot();
295​
296export function isClientSettingsHydrated(): boolean {
297 return getClientSettingsHydratedSnapshot();
299​
300/** Failed reads reject and remain retryable so defaults cannot overwrite saved preferences. */
301export function ensureClientSettingsHydrated(): Promise<void> {
302 return hydrateClientSettings();
304​
305export function useClientSettingsHydrated(): boolean {
306 return useSyncExternalStore(
307 subscribeClientSettingsHydration,
308 getClientSettingsHydratedSnapshot,
309 () => false,
310 );
312​
313export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
314 return useSyncExternalStore(
315 subscribeClientSettingsHydration,
316 getClientSettingsHydrationStatusSnapshot,
317 () => "pending",
318 );
320​
321const getDefaultClientSettings = () => DEFAULT_CLIENT_SETTINGS;
322const selectWholeClientSettings = (settings: ClientSettings) => settings;
323​
324/** Structurally equal selections retain their reference and skip rendering. */
325export function useClientSettings<T = ClientSettings>(
326 selector?: (settings: ClientSettings) => T,
327): T {
328 return useSyncExternalStoreWithSelector(
329 subscribeClientSettings,
330 getClientSettingsSnapshot,
331 getDefaultClientSettings,
332 selector ?? (selectWholeClientSettings as (settings: ClientSettings) => T),
333 Equal.equals,
334 );
336​
337export function mergeEnvironmentSettings(
338 serverSettings: ServerSettings,
339 clientSettings: ClientSettings,
340): UnifiedSettings {
341 // Older untyped adapters can return retired client keys; server values must win.
342 return {
343 ...clientSettings,
344 ...serverSettings,
345 ...resolveModelPreferences(serverSettings, clientSettings),
346 };
348​
349const selectLegacyModelPreferences = (settings: ClientSettings) => ({
350 favorites: settings.favorites,
351 providerModelPreferences: settings.providerModelPreferences,
352});
353​
354// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
355const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
356​
357const modelPreferencesMigrationTargetsAtom = Atom.make((get) =>
358 [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => {
359 const generation = Option.match(
360 AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
361 {
362 onNone: () => null,
363 onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),
364 },
365 );
366 const settings = get(serverEnvironment.settingsValueAtom(environmentId));
367 return generation === null || settings === null
368 ? []
369 : [{ environmentId, generation, settings }];
370 }),
371).pipe(Atom.withLabel("web-model-preferences-migration-targets"));
372​
373function migrateModelPreferences(): void {
374 if (clientSettingsHydrationStatus !== "ready") return;
375 for (const { environmentId, generation, settings } of appAtomRegistry.get(
376 modelPreferencesMigrationTargetsAtom,
377 )) {
378 if (attemptedMigrationGenerations.get(environmentId) === generation) continue;
379 const patch = modelPreferencesMigrationPatch(settings, clientSettingsSnapshot);
380 if (!patch) continue;
381 attemptedMigrationGenerations.set(environmentId, generation);
382 void runAtomCommand(
383 appAtomRegistry,
384 serverEnvironment.updateSettings,
385 { environmentId, input: { patch } },
386 { reportFailure: false },
387 );
388 }
390​
391/** Moves this client's legacy model preferences onto each server, once per connection. */
392export function startModelPreferencesMigration(): () => void {
393 const unsubscribes = [
394 appAtomRegistry.subscribe(modelPreferencesMigrationTargetsAtom, migrateModelPreferences),
395 subscribeClientSettings(migrateModelPreferences),
396 subscribeClientSettingsHydration(migrateModelPreferences),
397 ];
398 migrateModelPreferences();
399 return () => {
400 for (const unsubscribe of unsubscribes) unsubscribe();
401 };
403​
404export function useMergedSettings<T = UnifiedSettings>(
405 serverSettings: ServerSettings,
406 selector?: (settings: UnifiedSettings) => T,
407): T {
408 return useClientSettings((clientSettings) => {
409 const merged = mergeEnvironmentSettings(serverSettings, clientSettings);
410 return selector ? selector(merged) : (merged as T);
411 });
413​
414function resolveEnvironmentIdentificationMode(input: {
415 mode: EnvironmentIdentificationMode;
416 settingsHydrated: boolean;
417 paletteThemeActive?: boolean;
418 paletteThemeAllowsArtwork?: boolean;
419}): EnvironmentIdentificationMode {
420 if (!input.settingsHydrated) return "none";
421 const isArtwork = input.mode !== "pill" && input.mode !== "none";
422 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && isArtwork
423 ? "pill"
424 : input.mode;
426​
427export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
428 const settingsHydrated = useClientSettingsHydrated();
429 const mode = useClientSettings((settings) => settings.environmentIdentificationMode);
430 const { resolvedTheme, theme, themeHalves } = useTheme();
431 const previewSidebarArtwork = useSyncExternalStore(
432 subscribeToThemePreview,
433 getThemePreviewSidebarArtwork,
434 () => null,
435 );
436 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
437 const activeThemeDefinition = getThemeDefinition(activeTheme);
438 return resolveEnvironmentIdentificationMode({
439 mode,
440 settingsHydrated,
441 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
442 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
443 });
445​
446export async function prepareModelPreferencesPatch(
447 settings: ServerSettings,
448 patch: ServerSettingsPatch,
449): Promise<ServerSettingsPatch> {
450 if (settings.favorites === null || settings.providerModelPreferences === null) {
451 await ensureClientSettingsHydrated();
452 }
453 return { ...modelPreferencesMigrationPatch(settings, getClientSettings()), ...patch };
455​
456export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
457 const settings = useAtomValue(
458 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
459 );
460 const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update");
461 return async (patch: ServerSettingsPatch) => {
462 if (!environmentId || !settings) return;
463 let prepared: ServerSettingsPatch;
464 try {
465 prepared = await prepareModelPreferencesPatch(settings, patch);
466 } catch {
467 toastManager.add({
468 type: "error",
469 title: m(msg("Model preferences not saved")),
470 description: m(msg("Could not load saved model preferences. Try again.")),
471 });
472 return;
473 }
474 return save({ environmentId, input: { patch: prepared } });
475 };
477​
478/** Send the desired state so two clients adding a favorite do not cancel each other. */
479export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId | null) {
480 const registry = use(RegistryContext);
481 const pendingFavorites = useRef(
482 new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
483 );
484 const save = useUpdateEnvironmentModelPreferences(environmentId);
485 return async (provider: ProviderInstanceId, model: string) => {
486 if (!environmentId) return;
487 const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
488 const settings = registry.get(settingsAtom);
489 if (!settings) return;
490 if (settings.favorites === null) {
491 try {
492 await ensureClientSettingsHydrated();
493 } catch {
494 toastManager.add({
495 type: "error",
496 title: m(msg("Favorites not saved")),
497 description: m(msg("Could not load saved model preferences. Try again.")),
498 });
499 return;
500 }
501 }
502 const currentSettings = registry.get(settingsAtom) ?? settings;
503 const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
504 const key = JSON.stringify([environmentId, provider, model]);
505 const previous = pendingFavorites.current.get(key);
506 // Keep the acknowledged choice until the config stream catches up with the RPC reply.
507 const previousFavorite =
508 previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
509 ? previous.favorite
510 : favorites.some((favorite) => favorite.provider === provider && favorite.model === model);
511 const pending = {
512 favorite: !previousFavorite,
513 settings: currentSettings,
514 pending: true,
515 };
516 pendingFavorites.current.set(key, pending);
517 const result = await save({
518 setModelFavorites: [{ provider, model, favorite: pending.favorite }],
519 });
520 if (
521 result &&
522 AsyncResult.isSuccess(result) &&
523 registry.get(settingsAtom)?.favorites === currentSettings.favorites
524 ) {
525 pending.pending = false;
526 }
527 if (pending.pending && pendingFavorites.current.get(key) === pending) {
528 if (
529 previous &&
530 !previous.pending &&
531 registry.get(settingsAtom)?.favorites === previous.settings.favorites
532 ) {
533 pendingFavorites.current.set(key, previous);
534 } else {
535 pendingFavorites.current.delete(key);
536 }
537 }
538 };
540​
541const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null);
542​
543export function useEnvironmentModelPreferences(environmentId: EnvironmentId | null) {
544 const settings = useAtomValue(
545 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
546 );
547 const legacy = useClientSettings(selectLegacyModelPreferences);
548 return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);
550​
551export function useEnvironmentSettings<T = UnifiedSettings>(
552 environmentId: EnvironmentId,
553 selector?: (settings: UnifiedSettings) => T,
554): T {
555 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
556 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
558​
559export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) {
560 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
561 reportFailure: false,
562 });
563 return (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
564 mutateProviderInstance({
565 environmentId,
566 input: { patch, providerInstanceMutation },
567 });
569​
570export function usePrimarySettings<T = UnifiedSettings>(
571 selector?: (settings: UnifiedSettings) => T,
572): T {
573 const settings = useAtomValue(primaryServerSettingsAtom);
574 return useMergedSettings(settings, selector);
576​
577export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE = msg(
578 "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.",
579);
580​
581/** Hosted clients have no primary: usePrimarySettings reads defaults and cannot write. */
582export function usePrimarySettingsAvailable(): boolean {
583 const primaryEnvironment = usePrimaryEnvironment();
584 return primaryEnvironment !== null || !isHostedStaticApp();
586​
587function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
588 const { environments } = useEnvironments();
589 const targetIds = environments
590 .filter(supportsSharedSettingsSync)
591 .map(({ environmentId }) => environmentId);
592 const results = useAtomValue(environmentSessionStatesAtom(environmentIdsKey(targetIds)));
593 return targetIds.flatMap((environmentId, index) => {
594 const result = results[index]!;
595 // Let the server authorize shared edits with cold grants; suggestions still need confirmed grants.
596 if (includePending && result._tag === "Initial") {
597 return [environmentId];
598 }
599 const session = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null);
600 return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
601 ? [environmentId]
602 : [];
603 });
605​
606function deniedSettingsDescription(environmentLabel: string | null | undefined): string {
607 return environmentLabel == null
608 ? m(msg("This connection lacks permission to change settings on the selected environment."))
609 : m(
610 msg`This connection lacks permission to change settings on ${{ environments: environmentLabel }}.`,
611 );
613​
614function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
615 useEnvironmentScope(environmentId, AuthSettingsWriteScope);
616 const persist = useAtomCommand(serverEnvironment.updateSettings, {
617 label: "server settings update",
618 reportFailure: false,
619 });
620 const { environments } = useEnvironments();
621 const persistServerSettings = async (
622 request: Parameters<typeof persist>[0],
623 onFailed?: () => void,
624 ) => {
625 const result = await persist(request);
626 if (result._tag === "Failure") onFailed?.();
627 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
628 const label =
629 environments.find((environment) => environment.environmentId === request.environmentId)
630 ?.label ?? request.environmentId;
631 const error = squashAtomCommandFailure(result);
632 toastManager.add({
633 type: "error",
634 title: m(msg("Setting not saved")),
635 description: m(
636 msg`Could not save on ${{ label }}: ${{
637 error:
638 (error instanceof Error ? thrownErrorMessage(error, m) : null) ??
639 m(msg("The save failed. Try reconnecting and saving again.")),
640 }}`,
641 ),
642 });
643 }
644 return result;
645 };
646 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
647 const updateSettings = (
648 patch: UnifiedSettingsPatch,
649 options?: { readonly onFailed?: () => void; readonly onSaved?: () => void },
650 ) => {
651 const { serverPatch, clientPatch } = splitPatch(patch);
652​
653 const canWriteServerPatch =
654 environmentId === null ||
655 requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
656 readEnvironmentScope(environmentId, scope),
657 );
658 if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
659 options?.onFailed?.();
660 toastManager.add({
661 type: "warning",
662 title: m(msg("Setting not saved")),
663 description: deniedSettingsDescription(
664 environments.find((target) => target.environmentId === environmentId)?.label,
665 ),
666 });
667 }
668 if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
669 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
670 // Dropping the write silently leaves the control looking saved.
671 const warnUnsaved = (description = m(PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE)) => {
672 options?.onFailed?.();
673 return toastManager.add({
674 type: "warning",
675 title: m(msg("Setting not saved")),
676 description,
677 });
678 };
679 if (Object.keys(localPatch).length > 0) {
680 if (environmentId) {
681 void persistServerSettings(
682 { environmentId, input: { patch: localPatch } },
683 options?.onFailed,
684 ).then((result) => {
685 if (result._tag === "Success") options?.onSaved?.();
686 });
687 } else {
688 warnUnsaved();
689 }
690 }
691 if (Object.keys(sharedPatch).length > 0) {
692 const sourceSettings = environments.find((target) => target.environmentId === environmentId)
693 ?.serverConfig?.settings;
694 const targets = new Set(sharedSettingsSyncTargetIds);
695 if (environmentId) {
696 targets.add(environmentId);
697 }
698 const writes: Array<Parameters<typeof persist>[0]> = [];
699 const deniedLabels: string[] = [];
700 for (const targetId of targets) {
701 const target = environments.find((candidate) => candidate.environmentId === targetId);
702 const targetPatch = filterSharedServerPatch(
703 sharedPatch,
704 target?.serverConfig?.settings,
705 sourceSettings,
706 targetId === environmentId,
707 );
708 if (Object.keys(targetPatch).length === 0) continue;
709 const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
710 if (
711 session._tag !== "Initial" &&
712 !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
713 readEnvironmentScope(targetId, scope),
714 )
715 ) {
716 deniedLabels.push(target?.label ?? targetId);
717 continue;
718 }
719 writes.push({
720 environmentId: targetId,
721 input: { patch: targetPatch },
722 });
723 }
724 if (writes.length === 0) {
725 warnUnsaved(
726 deniedLabels.length > 0
727 ? m(
728 msg`This connection lacks permission to change settings on ${{ environments: deniedLabels.join(", ") }}.`,
729 )
730 : targets.size > 0
731 ? m(msg("Update older servers to save this setting."))
732 : undefined,
733 );
734 } else {
735 void Promise.all(
736 writes.map(async (request) => ({
737 label:
738 environments.find((target) => target.environmentId === request.environmentId)
739 ?.label ?? request.environmentId,
740 result: await persist(request),
741 })),
742 ).then((outcomes) => {
743 if (
744 deniedLabels.length > 0 ||
745 outcomes.some(({ result }) => result._tag === "Failure")
746 ) {
747 options?.onFailed?.();
748 }
749 const failures = outcomes.flatMap(({ label, result }) => {
750 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
751 const error = squashAtomCommandFailure(result);
752 return [
753 m(
754 msg`Could not save on ${{ label }}: ${{
755 error:
756 (error instanceof Error ? thrownErrorMessage(error, m) : null) ??
757 m(msg("The save failed. Try reconnecting and saving again.")),
758 }}`,
759 ),
760 ];
761 });
762 if (
763 deniedLabels.length === 0 &&
764 outcomes.every(({ result }) => result._tag === "Success")
765 ) {
766 options?.onSaved?.();
767 }
768 if (failures.length === 0) return;
769 const saved = outcomes
770 .filter(({ result }) => result._tag === "Success")
771 .map(({ label }) => label);
772 toastManager.add({
773 type: "error",
774 title:
775 saved.length > 0
776 ? m(msg("Setting saved on some environments"))
777 : m(msg("Setting not saved")),
778 description: [
779 ...failures,
780 ...(saved.length > 0
781 ? [m(msg`Saved on ${{ environments: saved.join(", ") }}.`)]
782 : []),
783 ].join("\n"),
784 });
785 });
786 }
787 }
788 }
789 if (Object.keys(clientPatch).length > 0) {
790 void persistClientSettingsPatch(clientPatch);
791 }
792 };
793​
794 return updateSettings;
796​
797export function useUpdateEnvironmentSettings(environmentId: EnvironmentId | null) {
798 return useUpdateSettingsTarget(environmentId);
800​
801export function useUpdatePrimarySettings() {
802 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
804​
805export function updateClientSettings(patch: ClientSettingsPatch): Promise<void> {
806 return persistClientSettingsPatch(patch);
808​
809export function __resetClientSettingsPersistenceForTests(): void {
810 clientSettingsHydrationGeneration += 1;
811 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
812 clientSettingsHydrationStatus = "pending";
813 clientSettingsHydrationPromise = null;
814 clientSettingsPersistenceQueue = Promise.resolve();
815 deferredClientSettingsPatchCount = 0;
816 unsubscribeOtherTabClientSettings?.();
817 unsubscribeOtherTabClientSettings = null;
818 clientSettingsListeners.clear();
819 clientSettingsHydrationListeners.clear();
821​
822export function __setClientSettingsForTests(settings: ClientSettings): void {
823 clientSettingsHydrationGeneration += 1;
824 clientSettingsSnapshot = settings;
825 clientSettingsHydrationStatus = "ready";
826 clientSettingsHydrationPromise = null;