From dac0eddd59753b7b8362fc6326245284f22e7dcb Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Thu, 12 Nov 2026 02:25:51 +0100 Subject: [PATCH 1/4] feat(web): apply chosen server settings to every environment Co-Authored-By: Claude Opus 5.5 --- apps/web/src/appInit.tsx | 2 + .../components/settings/SettingsPanels.tsx | 1 + .../settings/serverSettingPreferences.test.ts | 146 ++++++++++++++++++ .../settings/serverSettingPreferences.ts | 122 +++++++++++++++ .../settings/serverSettingPreferencesSync.ts | 97 ++++++++++++ .../components/settings/settingsLayout.tsx | 90 ++++++++++- .../components/settings/useScopedSettings.ts | 25 ++- docs/user/project-settings.md | 13 +- packages/contracts/src/settings.ts | 30 +++- 9 files changed, 510 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/components/settings/serverSettingPreferences.test.ts create mode 100644 apps/web/src/components/settings/serverSettingPreferences.ts create mode 100644 apps/web/src/components/settings/serverSettingPreferencesSync.ts diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index eb1a5f56f3504..26e41e8b29e8c 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -16,6 +16,7 @@ import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToas import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast"; import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice"; import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews"; +import { startServerSettingPreferencesSync } from "./components/settings/serverSettingPreferencesSync"; import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation"; import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun"; import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator"; @@ -188,6 +189,7 @@ export function startAppServices(): AppRouter { startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); startModelPreferencesMigration(); + startServerSettingPreferencesSync(); startAgentOpenedPreviews(); if (isElectron) startElectronBrowserHost(); startPreviewTitleRecording(); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 6123b47332e3e..1b827cbfb30c2 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -1818,6 +1818,7 @@ export function ThreadsSettingsPanel() { = {}): ServerSettings => ({ + ...DEFAULT_SERVER_SETTINGS, + compactIdleThreads: false, + idleCompaction: "onReturn", + ...overrides, +}); + +const lockedBy = (...lockedSettings: string[]): ManagedPolicySummary => ({ + organization: "Example Corp", + lockedSettings, +}); + +describe("recording server setting preferences", () => { + it("records only covered keys from a change made for all environments", () => { + expect( + recordServerSettingPreferences( + { sidebarAutoSettleOnMerge: true }, + { kind: "all" }, + { idleCompaction: "off", sidebarAutoSettleAfterDays: null, snoozeLimitedThreads: true }, + ), + ).toEqual({ + sidebarAutoSettleOnMerge: true, + idleCompaction: "off", + sidebarAutoSettleAfterDays: null, + }); + }); + + it("records nothing for a single environment or a change to uncovered keys", () => { + expect( + recordServerSettingPreferences({}, { kind: "environment" }, { idleCompaction: "off" }), + ).toBeNull(); + expect( + recordServerSettingPreferences({}, { kind: "all" }, { snoozeLimitedThreads: true }), + ).toBeNull(); + }); + + it("forgets only the keys that stop applying", () => { + expect( + forgetServerSettingPreferences({ idleCompaction: "off", sidebarAutoSettleOnMerge: true }, [ + "idleCompaction", + ]), + ).toEqual({ sidebarAutoSettleOnMerge: true }); + }); +}); + +describe("applying server setting preferences on connect", () => { + const preferences = { + idleCompaction: "off", + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: 3, + } as const; + + it("writes only the keys whose value differs", () => { + expect( + planServerSettingPreferencesPatch( + preferences, + settings({ idleCompaction: "off", sidebarAutoSettleOnMerge: true }), + undefined, + ), + ).toEqual({ sidebarAutoSettleAfterDays: 3 }); + expect( + planServerSettingPreferencesPatch( + preferences, + settings({ + idleCompaction: "off", + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: 3, + }), + undefined, + ), + ).toEqual({}); + }); + + it("gives a new server with built-in defaults every preference", () => { + expect(planServerSettingPreferencesPatch(preferences, settings(), undefined)).toEqual( + preferences, + ); + }); + + it("leaves keys the server's policy locks", () => { + expect( + planServerSettingPreferencesPatch( + preferences, + settings(), + lockedBy("sidebarAutoSettleOnMerge", "compactIdleThreads"), + ), + ).toEqual({ sidebarAutoSettleAfterDays: 3 }); + }); + + it("writes idle compaction in the form each server version reads", () => { + const plan = (mode: "off" | "beforeCacheExpires", serverSettings: ServerSettings) => + planServerSettingPreferencesPatch({ idleCompaction: mode }, serverSettings, undefined); + const { idleCompaction: _absent, ...withoutModes } = settings(); + expect(plan("off", settings())).toEqual({ idleCompaction: "off" }); + expect(plan("off", { ...withoutModes, compactIdleThreads: "onReturn" })).toEqual({ + compactIdleThreads: "off", + }); + expect(plan("beforeCacheExpires", withoutModes)).toEqual({ compactIdleThreads: true }); + // A server with only the switch cannot store "Never", and its switch is already off. + expect(plan("off", withoutModes)).toEqual({}); + }); +}); + +describe("environments that differ from a preference", () => { + it("lists differing environments and marks those whose policy locks the setting", () => { + const target = ( + label: string, + serverSettings: ServerSettings, + policy?: ManagedPolicySummary, + ) => ({ + environmentId: EnvironmentId.make(label), + label, + settings: serverSettings, + managedPolicy: policy, + }); + expect( + serverSettingPreferenceDifferences( + { idleCompaction: "off" }, + ["idleCompaction", "compactIdleThreads"], + [ + target("Same", settings({ idleCompaction: "off" })), + target("Different", settings()), + target("Managed", settings(), lockedBy("idleCompaction")), + ], + ).map(({ label, locked }) => ({ label, locked })), + ).toEqual([ + { label: "Different", locked: false }, + { label: "Managed", locked: true }, + ]); + }); +}); diff --git a/apps/web/src/components/settings/serverSettingPreferences.ts b/apps/web/src/components/settings/serverSettingPreferences.ts new file mode 100644 index 0000000000000..db7936543adc5 --- /dev/null +++ b/apps/web/src/components/settings/serverSettingPreferences.ts @@ -0,0 +1,122 @@ +import { + type EnvironmentId, + globalIdleCompaction, + idleCompactionPatch, + isManagedSettingPath, + type ManagedPolicySummary, + type ServerSettings, + ServerSettingPreferences, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import * as Equal from "effect/Equal"; + +import type { ResolvedSettingsScope } from "./settingsScope"; + +export type ServerSettingPreferenceKey = keyof typeof ServerSettingPreferences.fields; + +const PREFERENCE_KEYS = Object.keys( + ServerSettingPreferences.fields, +) as ServerSettingPreferenceKey[]; +const PREFERENCE_KEY_SET = new Set(PREFERENCE_KEYS); + +export function isServerSettingPreferenceKey(key: string): key is ServerSettingPreferenceKey { + return PREFERENCE_KEY_SET.has(key); +} + +/** The value a server uses, from whichever field its version stores it in. */ +function serverValue(settings: ServerSettings, key: ServerSettingPreferenceKey): unknown { + return key === "idleCompaction" ? globalIdleCompaction(settings) : settings[key]; +} + +function isPreferenceLocked( + policy: ManagedPolicySummary | undefined, + key: ServerSettingPreferenceKey, +): boolean { + const paths = key === "idleCompaction" ? ["idleCompaction", "compactIdleThreads"] : [key]; + return paths.some((path) => isManagedSettingPath(policy, path)); +} + +/** A change made for all environments becomes this client's preference for its keys. */ +export function recordServerSettingPreferences( + current: ServerSettingPreferences, + scope: Pick, + patch: ServerSettingsPatch, +): ServerSettingPreferences | null { + if (scope.kind !== "all") return null; + const next: Record = { ...current }; + let recorded = false; + for (const key of PREFERENCE_KEYS) { + if (patch[key] === undefined) continue; + next[key] = patch[key]; + recorded = true; + } + return recorded ? (next as ServerSettingPreferences) : null; +} + +export function forgetServerSettingPreferences( + current: ServerSettingPreferences, + keys: readonly ServerSettingPreferenceKey[], +): ServerSettingPreferences { + const next: Record = { ...current }; + for (const key of keys) delete next[key]; + return next as ServerSettingPreferences; +} + +/** + * The patch that brings one server in line with the preferences, in the form its version + * reads. Keys its administrator locks are left alone. + */ +export function planServerSettingPreferencesPatch( + preferences: ServerSettingPreferences, + settings: ServerSettings, + policy: ManagedPolicySummary | undefined, +): ServerSettingsPatch { + const patch: ServerSettingsPatch = {}; + for (const key of PREFERENCE_KEYS) { + const value = preferences[key]; + if (value === undefined || isPreferenceLocked(policy, key)) continue; + if (Equal.equals(serverValue(settings, key), value)) continue; + const write: ServerSettingsPatch = + key === "idleCompaction" + ? idleCompactionPatch(settings, preferences.idleCompaction!) + : { [key]: value }; + // A server from before idle compaction modes stores "Never" as the switch it already has off. + const unchanged = Object.entries(write).every(([field, next]) => + Equal.equals(settings[field as keyof ServerSettings], next), + ); + if (!unchanged) Object.assign(patch, write); + } + return patch; +} + +export interface ServerSettingPreferenceTarget { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly settings: ServerSettings; + readonly managedPolicy: ManagedPolicySummary | undefined; +} + +/** Connected environments whose value for any of `keys` differs from the preference. */ +export function serverSettingPreferenceDifferences( + preferences: ServerSettingPreferences, + keys: readonly string[], + targets: readonly ServerSettingPreferenceTarget[], +) { + const followed = keys.filter(isServerSettingPreferenceKey); + return targets.flatMap((target) => { + const differing = followed.filter( + (key) => + preferences[key] !== undefined && + !Equal.equals(serverValue(target.settings, key), preferences[key]), + ); + return differing.length === 0 + ? [] + : [ + { + environmentId: target.environmentId, + label: target.label, + locked: differing.some((key) => isPreferenceLocked(target.managedPolicy, key)), + }, + ]; + }); +} diff --git a/apps/web/src/components/settings/serverSettingPreferencesSync.ts b/apps/web/src/components/settings/serverSettingPreferencesSync.ts new file mode 100644 index 0000000000000..89a672911aeee --- /dev/null +++ b/apps/web/src/components/settings/serverSettingPreferencesSync.ts @@ -0,0 +1,97 @@ +import { type EnvironmentId, requiredScopesForServerSettingsPatch } from "@t3tools/contracts"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { environmentCatalog } from "~/connection/catalog"; +import { + getClientSettings, + isClientSettingsHydrated, + subscribeClientSettings, + subscribeClientSettingsHydration, +} from "~/hooks/useSettings"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { readEnvironment } from "~/state/environments"; +import { serverEnvironment } from "~/state/server"; +import { environmentSession, readEnvironmentScope } from "~/state/session"; +import { toastManager } from "../ui/toast"; +import { persistScopedSettingsPatch } from "./scopedSettings"; +import { planServerSettingPreferencesPatch } from "./serverSettingPreferences"; + +const targetsAtom = Atom.make((get) => + [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => { + const generation = Option.match( + AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), + { + onNone: () => null, + onSome: (connection) => (connection.phase === "connected" ? connection.generation : null), + }, + ); + const config = get(serverEnvironment.configValueAtom(environmentId)); + // Write permission is known only once the session loads. + const sessionLoaded = + get(environmentSession.sessionStateAtom(environmentId))._tag !== "Initial"; + return generation === null || config === null || !sessionLoaded + ? [] + : [{ environmentId, generation, config }]; + }), +).pipe(Atom.withLabel("web-server-setting-preferences-targets")); + +const attemptedGenerations = new Map(); + +function applyServerSettingPreferences(): void { + if (!isClientSettingsHydrated()) return; + const preferences = getClientSettings().serverSettingPreferences; + for (const { environmentId, generation, config } of appAtomRegistry.get(targetsAtom)) { + if (attemptedGenerations.get(environmentId) === generation) continue; + attemptedGenerations.set(environmentId, generation); + const patch = planServerSettingPreferencesPatch( + preferences, + config.settings, + config.managedPolicy, + ); + if (Object.keys(patch).length === 0) continue; + if ( + !requiredScopesForServerSettingsPatch(patch).every((scope) => + readEnvironmentScope(environmentId, scope), + ) + ) { + continue; + } + const label = readEnvironment(environmentId)?.label ?? environmentId; + void persistScopedSettingsPatch( + { + clientPatch: {}, + hasClientWrite: false, + serverWrites: [{ environmentId, label, patch, previous: config.settings }], + unavailableReason: null, + }, + (request) => + runAtomCommand(appAtomRegistry, serverEnvironment.updateSettings, request, { + reportFailure: false, + }), + () => undefined, + ).then(({ failedEnvironments }) => { + for (const failed of failedEnvironments) { + toastManager.add({ + type: "error", + title: "Settings not applied", + description: `Could not apply your all-environment settings on ${failed.label}: ${failed.message}`, + }); + } + }); + } +} + +/** Applies this client's all-environment settings to each server, once per connection. */ +export function startServerSettingPreferencesSync(): () => void { + const unsubscribes = [ + appAtomRegistry.subscribe(targetsAtom, applyServerSettingPreferences), + subscribeClientSettings(applyServerSettingPreferences), + subscribeClientSettingsHydration(applyServerSettingPreferences), + ]; + applyServerSettingPreferences(); + return () => { + for (const unsubscribe of unsubscribes) unsubscribe(); + }; +} diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index e5d555bf8f7c0..1feda1090cda0 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -15,6 +15,8 @@ import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContex import { PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE, + persistClientSettingsUpdate, + useClientSettings, usePrimarySettingsAvailable, } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; @@ -30,6 +32,11 @@ import { scopedSettingsAreMixed, scopedSettingsSource, } from "./scopedSettings"; +import { + forgetServerSettingPreferences, + isServerSettingPreferenceKey, + serverSettingPreferenceDifferences, +} from "./serverSettingPreferences"; import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings"; import { SettingInheritance, @@ -314,6 +321,7 @@ export function SettingsRow({ managedPaths = EMPTY_MANAGED_PATHS, mixed: mixedOverride, managed, + preferenceStatus = true, children, className, ...rowProps @@ -331,6 +339,8 @@ export function SettingsRow({ mixed?: boolean; /** Why an administrator's policy turns this row's control off, from the contract's denial helpers. */ managed?: string | undefined; + /** False on a row that repeats another row's setting, so its all-environments status shows once. */ + preferenceStatus?: boolean; children?: ReactNode; }) { const targetRef = useSettingsSearchTarget(rowProps.id); @@ -363,6 +373,14 @@ export function SettingsRow({ policy !== undefined && lockablePaths.some((path) => isManagedSettingPath(policy, path)), )?.organization; + const preferences = useClientSettings((settings) => settings.serverSettingPreferences); + const preferenceKeys = serverScoped + ? settingKeys + .filter(isServerSettingPreferenceKey) + .filter((key) => preferences[key] !== undefined) + : []; + const environmentScopeFollows = + context?.scope.kind === "environment" && preferenceKeys.length > 0; const clearOverrides = useClearScopedSettings(); const clearProjectOverrides = useClearProjectOverrides(); const isProjectScope = @@ -392,8 +410,10 @@ export function SettingsRow({ ); const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys); const renderedReset = - unavailable || managedBy !== undefined || managed !== undefined ? null : isProjectScope && - scopedKeys.length > 0 ? ( + unavailable || + managedBy !== undefined || + managed !== undefined || + environmentScopeFollows ? null : isProjectScope && scopedKeys.length > 0 ? ( source === "project" || source === "mixed" ? ( @@ -486,7 +510,65 @@ export function SettingsRow({ : {})} /> ) : null; - const renderedStatus = status; + const preferenceDifferences = + context === null || preferenceKeys.length === 0 + ? [] + : serverSettingPreferenceDifferences( + preferences, + preferenceKeys, + context.connectedEnvironments.flatMap((environment) => + environment.serverConfig + ? [ + { + environmentId: environment.environmentId, + label: environment.label, + settings: environment.serverConfig.settings, + managedPolicy: environment.serverConfig.managedPolicy, + }, + ] + : [], + ), + ); + const listLabels = (locked: boolean) => + preferenceDifferences + .filter((difference) => difference.locked === locked) + .map((difference) => difference.label) + .join(", "); + const renderedPreferenceStatus = + preferenceStatus && + context !== null && + (context.scope.kind === "all" || context.scope.kind === "environment") && + preferenceKeys.length > 0 ? ( + <> + Applied to every environment this app connects to, including new ones. + {listLabels(false) ? ` Different on ${listLabels(false)}.` : null} + {listLabels(true) ? ` Not applied on ${listLabels(true)}: managed there.` : null}{" "} + + + ) : null; + const renderedStatus = + status && renderedPreferenceStatus ? ( + <> + {status} +
{renderedPreferenceStatus}
+ + ) : ( + (status ?? renderedPreferenceStatus) + ); return (
( selector?: (settings: UnifiedSettings) => T, @@ -101,8 +107,21 @@ export function useUpdateScopedSettings() { const { scope, environments } = useSettingsScope(); const run = useRunScopedPlan(); /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */ - return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) => - run(planScopedSettingsPatch(scope, environments, patch), options?.onFailed); + return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) => { + const plan = planScopedSettingsPatch(scope, environments, patch); + if ( + plan.unavailableReason === null && + recordServerSettingPreferences(getClientSettings().serverSettingPreferences, scope, patch) + ) { + void persistClientSettingsUpdate((current) => ({ + ...current, + serverSettingPreferences: + recordServerSettingPreferences(current.serverSettingPreferences, scope, patch) ?? + current.serverSettingPreferences, + })); + } + run(plan, options?.onFailed); + }; } export function useClearScopedSettings() { diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 0cad979ea0d6e..5fee59127308d 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -8,7 +8,18 @@ and stay selected as you move between categories or search for a setting. Preferences saved on this device, such as appearance, confirmations and browser profiles, always show and ignore the selection. Everything else is stored on a server. Choose one environment to edit its settings, or leave **All environments** to edit every connected environment at once. -Offline environments keep their current values; this is a bulk edit, not a synced global default. +Offline environments keep their current values; for most settings this is a bulk edit, not a +synced global default. + +A few settings follow you instead: **Compact idle threads**, **Auto-settle when a pull request +merges or closes**, and **Auto-settle inactive threads** with its number of days. When you change +one with **All environments** selected, this app remembers the choice and applies it to every +environment it connects to, including ones that were offline and ones you add later. The setting +then says it applies everywhere and names any connected environment that still has a different +value. An environment whose administrator locks the setting keeps its own value. While one +environment is selected, these settings are read-only; choose **Stop applying everywhere** to let +each environment keep its own value again. The choice is saved on this device only, so other +devices and the mobile app don't apply it. Choose a project to override settings for it on the selected environments. A layers icon beside each server row's title shows where the value comes from: the built-in default, the environment, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 405626dbaf8c7..8ff2cf1884963 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -95,6 +95,14 @@ export const SidebarAutoSettleAfterDays = Schema.Number.check( ); export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type; +export const IDLE_COMPACTION_MODES = [ + { value: "onReturn", label: "When you return" }, + { value: "beforeCacheExpires", label: "Before the cache expires (beta)" }, + { value: "off", label: "Never" }, +] as const; +export const IdleCompactionMode = Schema.Literals(IDLE_COMPACTION_MODES.map((mode) => mode.value)); +export type IdleCompactionMode = typeof IdleCompactionMode.Type; + export const MAX_SNOOZE_PRESET_MINUTES = 30 * 24 * 60; export const MAX_SNOOZE_PRESETS = 8; export const SnoozePresetDay = Schema.Literals([ @@ -389,7 +397,21 @@ export const VoiceTranscriptionDestination = Schema.Union([ ]); export type VoiceTranscriptionDestination = typeof VoiceTranscriptionDestination.Type; +/** + * Server settings this client applies to every environment it connects to. Each key is recorded + * when the setting is changed for all environments; an absent key is not applied. + */ +export const ServerSettingPreferences = Schema.Struct({ + idleCompaction: Schema.optionalKey(IdleCompactionMode), + sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), + sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)), +}); +export type ServerSettingPreferences = typeof ServerSettingPreferences.Type; + export const ClientSettingsSchema = Schema.Struct({ + serverSettingPreferences: ServerSettingPreferences.pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), notificationMode: NotificationMode.pipe( Schema.withDecodingDefault(Effect.succeed("off" as const)), ), @@ -741,14 +763,6 @@ export type CodexSettings = typeof CodexSettings.Type; const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/; -export const IDLE_COMPACTION_MODES = [ - { value: "onReturn", label: "When you return" }, - { value: "beforeCacheExpires", label: "Before the cache expires (beta)" }, - { value: "off", label: "Never" }, -] as const; -export const IdleCompactionMode = Schema.Literals(IDLE_COMPACTION_MODES.map((mode) => mode.value)); -export type IdleCompactionMode = typeof IdleCompactionMode.Type; - // Shipped clients reject the whole server config unless `compactIdleThreads` is boolean. // Keep the mode in `idleCompaction`, but accept strings from older servers. const LegacyCompactIdleThreads = Schema.Union([Schema.Boolean, IdleCompactionMode]); From 78b960076e59ec16c8371dd3b98e9965070c0019 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Thu, 12 Nov 2026 02:29:17 +0100 Subject: [PATCH 2/4] fix(web): report a failed save of the all-environment settings Co-Authored-By: Claude Opus 5.5 --- .../components/settings/settingsLayout.tsx | 17 ++++++------- .../components/settings/useScopedSettings.ts | 25 ++++++++++++++----- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index 1feda1090cda0..5855e78303d7a 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -15,7 +15,6 @@ import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContex import { PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE, - persistClientSettingsUpdate, useClientSettings, usePrimarySettingsAvailable, } from "../../hooks/useSettings"; @@ -37,7 +36,11 @@ import { isServerSettingPreferenceKey, serverSettingPreferenceDifferences, } from "./serverSettingPreferences"; -import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings"; +import { + updateServerSettingPreferences, + useClearProjectOverrides, + useClearScopedSettings, +} from "./useScopedSettings"; import { SettingInheritance, type SettingInheritanceState, @@ -547,13 +550,9 @@ export function SettingsRow({ size="xs" variant="link" onClick={() => - void persistClientSettingsUpdate((current) => ({ - ...current, - serverSettingPreferences: forgetServerSettingPreferences( - current.serverSettingPreferences, - preferenceKeys, - ), - })) + updateServerSettingPreferences((current) => + forgetServerSettingPreferences(current, preferenceKeys), + ) } > Stop applying everywhere diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.ts index 35ffbed24fbe2..7a2d087ddf6e6 100644 --- a/apps/web/src/components/settings/useScopedSettings.ts +++ b/apps/web/src/components/settings/useScopedSettings.ts @@ -10,6 +10,7 @@ import { AsyncResult } from "effect/reactivity"; import { DEFAULT_SERVER_SETTINGS, type ProjectScopedServerSettingKey, + type ServerSettingPreferences, type ServerSettings, type UnifiedSettings, } from "@t3tools/contracts"; @@ -113,17 +114,29 @@ export function useUpdateScopedSettings() { plan.unavailableReason === null && recordServerSettingPreferences(getClientSettings().serverSettingPreferences, scope, patch) ) { - void persistClientSettingsUpdate((current) => ({ - ...current, - serverSettingPreferences: - recordServerSettingPreferences(current.serverSettingPreferences, scope, patch) ?? - current.serverSettingPreferences, - })); + updateServerSettingPreferences( + (current) => recordServerSettingPreferences(current, scope, patch) ?? current, + ); } run(plan, options?.onFailed); }; } +export function updateServerSettingPreferences( + update: (current: ServerSettingPreferences) => ServerSettingPreferences, +) { + void persistClientSettingsUpdate((current) => ({ + ...current, + serverSettingPreferences: update(current.serverSettingPreferences), + })).catch(() => + toastManager.add({ + type: "error", + title: "All-environment setting not saved", + description: "This app could not save which settings it applies everywhere. Try again.", + }), + ); +} + export function useClearScopedSettings() { const context = useOptionalSettingsScope(); const run = useRunScopedPlan(); From f14305b517656a17a2629b25dafc9e4a68682284 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Thu, 12 Nov 2026 02:46:59 +0100 Subject: [PATCH 3/4] fix(web): re-plan all-environment settings as configs arrive, and explain gaps Plan the writes again whenever a connected server's config, its session, or the preferences change, and send each distinct patch at most once per connection, so a cached config, a late session, a preference saved while connecting, or a replaced connection no longer skips a server. Under All environments, covered settings save where they can instead of locking the row, and the row says why each differing server was not changed. Restore defaults only updates preferences already set, a single-environment write leaves them alone, and the client's default for idle compaction is Never, matching what servers without a saved choice use. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/serverSettings.ts | 3 +- .../components/settings/SettingsPanels.tsx | 146 +++++++++--------- .../settings/serverSettingPreferences.test.ts | 142 ++++++++++++++++- .../settings/serverSettingPreferences.ts | 141 ++++++++++++++++- .../settings/serverSettingPreferencesSync.ts | 110 ++++++++----- .../components/settings/settingsLayout.tsx | 35 +++-- .../components/settings/useScopedSettings.ts | 40 ++++- docs/user/project-settings.md | 17 +- packages/contracts/src/settings.ts | 4 +- 9 files changed, 496 insertions(+), 142 deletions(-) diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index f69cd31726b08..3006d64340c23 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -1,4 +1,5 @@ import { + DEFAULT_IDLE_COMPACTION, DEFAULT_SERVER_SETTINGS, ModelSelection, ProjectId, @@ -833,7 +834,7 @@ const make = Effect.gen(function* () { settings, savedIdleCompaction || settings.idleCompaction !== undefined ? globalIdleCompaction(settings) - : "off", + : DEFAULT_IDLE_COMPACTION, ); // A file that failed to decode must stay on disk for the user to repair. diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 1b827cbfb30c2..ebe7252760002 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -639,77 +639,81 @@ export function useSettingsRestore(onRestored?: () => void) { notifyThemeRestoreFailure(); return; } - updateSettings({ - appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, - diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, - chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, - effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, - mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, - timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, - notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode, - inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled, - wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap, - persistComposerContextStrip: DEFAULT_UNIFIED_SETTINGS.persistComposerContextStrip, - diffFilesCollapsed: DEFAULT_UNIFIED_SETTINGS.diffFilesCollapsed, - diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace, - diffLayout: DEFAULT_UNIFIED_SETTINGS.diffLayout, - proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled, - showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu, - composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled, - sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut, - followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, - toolCallVisibility: DEFAULT_UNIFIED_SETTINGS.toolCallVisibility, - screenReaderAnnouncements: DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements, - environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, - glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, - panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, - sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, - sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, - sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled, - sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, - sidebarAutoSettleKeepPullRequests: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests, - sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, - autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, - snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, - snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets, - responseStreamingMode: DEFAULT_UNIFIED_SETTINGS.responseStreamingMode, - enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, - continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, - backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity, - backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile, - automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval, - providerHealthRefreshInterval: DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval, - defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode, - newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin, - addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory, - ghqCloneLayout: DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout, - confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive, - confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete, - confirmThreadUnpin: DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin, - confirmQuit: DEFAULT_UNIFIED_SETTINGS.confirmQuit, - textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection, - threadTitleInstructions: DEFAULT_UNIFIED_SETTINGS.threadTitleInstructions, - fontFamilySans: DEFAULT_UNIFIED_SETTINGS.fontFamilySans, - fontFamilyComposer: DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer, - fontFamilyCode: DEFAULT_UNIFIED_SETTINGS.fontFamilyCode, - fontFamilyTerminal: DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal, - fontSizeInterface: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface, - fontSizePrompt: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt, - fontSizeCode: DEFAULT_UNIFIED_SETTINGS.fontSizeCode, - fontSizeTerminal: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal, - browserDefaultViewport: DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport, - browserDefaultZoomFactor: DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor, - browserDefaultAppearance: DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance, - browserRecordingFrameRate: DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate, - browserRecordingShowKeyPresses: DEFAULT_UNIFIED_SETTINGS.browserRecordingShowKeyPresses, - browserRecordingShowMousePresses: DEFAULT_UNIFIED_SETTINGS.browserRecordingShowMousePresses, - browserLinkTarget: DEFAULT_UNIFIED_SETTINGS.browserLinkTarget, - browserSearchEngine: DEFAULT_UNIFIED_SETTINGS.browserSearchEngine, - browserCustomSearchUrl: DEFAULT_UNIFIED_SETTINGS.browserCustomSearchUrl, - browserAutoShowFloatingPreview: DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview, - pullRequestLinksOpenInApp: DEFAULT_UNIFIED_SETTINGS.pullRequestLinksOpenInApp, - enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess, - }); + updateSettings( + { + appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, + diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, + chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, + effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, + mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, + timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, + notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode, + inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled, + wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap, + persistComposerContextStrip: DEFAULT_UNIFIED_SETTINGS.persistComposerContextStrip, + diffFilesCollapsed: DEFAULT_UNIFIED_SETTINGS.diffFilesCollapsed, + diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace, + diffLayout: DEFAULT_UNIFIED_SETTINGS.diffLayout, + proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled, + showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu, + composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled, + sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut, + followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, + toolCallVisibility: DEFAULT_UNIFIED_SETTINGS.toolCallVisibility, + screenReaderAnnouncements: DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements, + environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, + glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, + panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, + sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, + sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, + sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled, + sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, + sidebarAutoSettleKeepPullRequests: + DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests, + sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, + autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, + snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, + snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets, + responseStreamingMode: DEFAULT_UNIFIED_SETTINGS.responseStreamingMode, + enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, + continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, + backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity, + backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile, + automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval, + providerHealthRefreshInterval: DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval, + defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode, + newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin, + addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory, + ghqCloneLayout: DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout, + confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive, + confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete, + confirmThreadUnpin: DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin, + confirmQuit: DEFAULT_UNIFIED_SETTINGS.confirmQuit, + textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection, + threadTitleInstructions: DEFAULT_UNIFIED_SETTINGS.threadTitleInstructions, + fontFamilySans: DEFAULT_UNIFIED_SETTINGS.fontFamilySans, + fontFamilyComposer: DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer, + fontFamilyCode: DEFAULT_UNIFIED_SETTINGS.fontFamilyCode, + fontFamilyTerminal: DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal, + fontSizeInterface: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface, + fontSizePrompt: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt, + fontSizeCode: DEFAULT_UNIFIED_SETTINGS.fontSizeCode, + fontSizeTerminal: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal, + browserDefaultViewport: DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport, + browserDefaultZoomFactor: DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor, + browserDefaultAppearance: DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance, + browserRecordingFrameRate: DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate, + browserRecordingShowKeyPresses: DEFAULT_UNIFIED_SETTINGS.browserRecordingShowKeyPresses, + browserRecordingShowMousePresses: DEFAULT_UNIFIED_SETTINGS.browserRecordingShowMousePresses, + browserLinkTarget: DEFAULT_UNIFIED_SETTINGS.browserLinkTarget, + browserSearchEngine: DEFAULT_UNIFIED_SETTINGS.browserSearchEngine, + browserCustomSearchUrl: DEFAULT_UNIFIED_SETTINGS.browserCustomSearchUrl, + browserAutoShowFloatingPreview: DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview, + pullRequestLinksOpenInApp: DEFAULT_UNIFIED_SETTINGS.pullRequestLinksOpenInApp, + enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess, + }, + { onlyExistingPreferences: true }, + ); onRestored?.(); }; diff --git a/apps/web/src/components/settings/serverSettingPreferences.test.ts b/apps/web/src/components/settings/serverSettingPreferences.test.ts index 41c75ef1fb835..87b5f4d6c5bbb 100644 --- a/apps/web/src/components/settings/serverSettingPreferences.test.ts +++ b/apps/web/src/components/settings/serverSettingPreferences.test.ts @@ -8,9 +8,14 @@ import { describe, expect, it } from "vite-plus/test"; import { forgetServerSettingPreferences, + nextPreferenceWrites, planServerSettingPreferencesPatch, + type PreferenceSyncAttempts, + type PreferenceSyncTarget, recordServerSettingPreferences, serverSettingPreferenceDifferences, + skipBlockedPreferenceWrites, + withoutPreferredFields, } from "./serverSettingPreferences"; const settings = (overrides: Partial = {}): ServerSettings => ({ @@ -25,6 +30,9 @@ const lockedBy = (...lockedSettings: string[]): ManagedPolicySummary => ({ lockedSettings, }); +const laptop = EnvironmentId.make("laptop"); +const server = EnvironmentId.make("server"); + describe("recording server setting preferences", () => { it("records only covered keys from a change made for all environments", () => { expect( @@ -49,6 +57,18 @@ describe("recording server setting preferences", () => { ).toBeNull(); }); + it("only updates existing preferences when restoring defaults", () => { + const restore = { sidebarAutoSettleOnMerge: false, sidebarAutoSettleAfterDays: 7 }; + expect( + recordServerSettingPreferences({ sidebarAutoSettleOnMerge: true }, { kind: "all" }, restore, { + onlyExisting: true, + }), + ).toEqual({ sidebarAutoSettleOnMerge: false }); + expect( + recordServerSettingPreferences({}, { kind: "all" }, restore, { onlyExisting: true }), + ).toBeNull(); + }); + it("forgets only the keys that stop applying", () => { expect( forgetServerSettingPreferences({ idleCompaction: "off", sidebarAutoSettleOnMerge: true }, [ @@ -58,6 +78,44 @@ describe("recording server setting preferences", () => { }); }); +describe("writes made from Settings", () => { + it("leave fields applied everywhere out of a single environment's write", () => { + expect( + withoutPreferredFields( + { + idleCompaction: "onReturn" as const, + compactIdleThreads: false, + sidebarAutoSettleOnMerge: false, + snoozeLimitedThreads: true, + }, + { idleCompaction: "off" }, + ), + ).toEqual({ sidebarAutoSettleOnMerge: false, snoozeLimitedThreads: true }); + }); + + it("skip what an environment's policy or this connection's permissions block under All environments", () => { + const writes = [ + { environmentId: laptop, patch: { idleCompaction: "off" as const } }, + { environmentId: server, patch: { compactIdleThreads: false } }, + { environmentId: EnvironmentId.make("readonly"), patch: { sidebarAutoSettleOnMerge: true } }, + { + environmentId: EnvironmentId.make("readonly"), + patch: { sidebarAutoSettleOnMerge: true, snoozeLimitedThreads: true }, + }, + ]; + const kept = skipBlockedPreferenceWrites(writes, { + policyOf: (environmentId) => + environmentId === server ? lockedBy("compactIdleThreads") : undefined, + canWrite: (environmentId) => environmentId !== "readonly", + }); + expect(kept.map(({ environmentId, patch }) => ({ environmentId, patch }))).toEqual([ + writes[0], + // A write that also changes uncovered settings still goes, and reports its failure. + writes[3], + ]); + }); +}); + describe("applying server setting preferences on connect", () => { const preferences = { idleCompaction: "off", @@ -116,31 +174,99 @@ describe("applying server setting preferences on connect", () => { }); }); +describe("deciding when to write preferences", () => { + const preferences = { sidebarAutoSettleOnMerge: true } as const; + const target = (overrides: Partial = {}): PreferenceSyncTarget => ({ + environmentId: server, + generation: 1, + settings: settings(), + managedPolicy: undefined, + sessionReady: true, + ...overrides, + }); + const decide = ( + attempts: PreferenceSyncAttempts, + connected: readonly PreferenceSyncTarget[], + prefs: Parameters[2] = preferences, + canWrite = true, + ) => nextPreferenceWrites(attempts, connected, prefs, () => canWrite).map(({ patch }) => patch); + + it("waits for the session, including one that failed to load, and for write permission", () => { + const attempts: PreferenceSyncAttempts = new Map(); + expect(decide(attempts, [target({ sessionReady: false })])).toEqual([]); + expect(decide(attempts, [target()], preferences, false)).toEqual([]); + expect(decide(attempts, [target()])).toEqual([{ sidebarAutoSettleOnMerge: true }]); + }); + + it("plans again when the fresh config arrives after a cached one", () => { + const attempts: PreferenceSyncAttempts = new Map(); + expect( + decide(attempts, [target({ settings: settings({ sidebarAutoSettleOnMerge: true }) })]), + ).toEqual([]); + expect(decide(attempts, [target()])).toEqual([{ sidebarAutoSettleOnMerge: true }]); + }); + + it("sends each patch once per connection, so a failed write is not repeated", () => { + const attempts: PreferenceSyncAttempts = new Map(); + expect(decide(attempts, [target()])).toHaveLength(1); + expect(decide(attempts, [target()])).toEqual([]); + // A preference changed during the connection is a different patch. + expect(decide(attempts, [target()], { sidebarAutoSettleAfterDays: 5 })).toEqual([ + { sidebarAutoSettleAfterDays: 5 }, + ]); + }); + + it("writes again after a reconnect, even when the new connection restarts its count", () => { + const attempts: PreferenceSyncAttempts = new Map(); + expect(decide(attempts, [target()])).toHaveLength(1); + expect(decide(attempts, [])).toEqual([]); + expect(decide(attempts, [target()])).toEqual([{ sidebarAutoSettleOnMerge: true }]); + expect(decide(attempts, [target({ generation: 2 })])).toEqual([ + { sidebarAutoSettleOnMerge: true }, + ]); + }); + + it("applies a preference saved while a server was connecting once it connects", () => { + const attempts: PreferenceSyncAttempts = new Map(); + expect(decide(attempts, [], preferences)).toEqual([]); + expect(decide(attempts, [target()], preferences)).toEqual([{ sidebarAutoSettleOnMerge: true }]); + }); +}); + describe("environments that differ from a preference", () => { - it("lists differing environments and marks those whose policy locks the setting", () => { + it("lists each differing environment with why it was not applied", () => { const target = ( label: string, serverSettings: ServerSettings, - policy?: ManagedPolicySummary, + extra: { policy?: ManagedPolicySummary; canWrite?: boolean; failure?: string } = {}, ) => ({ environmentId: EnvironmentId.make(label), label, settings: serverSettings, - managedPolicy: policy, + managedPolicy: extra.policy, + canWrite: extra.canWrite ?? true, + failure: extra.failure, }); + const { idleCompaction: _absent, ...switchOnly } = settings(); expect( serverSettingPreferenceDifferences( { idleCompaction: "off" }, ["idleCompaction", "compactIdleThreads"], [ target("Same", settings({ idleCompaction: "off" })), - target("Different", settings()), - target("Managed", settings(), lockedBy("idleCompaction")), + target("Pending", settings()), + target("Managed", settings(), { policy: lockedBy("idleCompaction") }), + target("Readonly", settings(), { canWrite: false }), + target("Old", switchOnly), + target("Failed", settings(), { failure: "The save failed." }), ], - ).map(({ label, locked }) => ({ label, locked })), + ).map(({ label, reason }) => [label, reason]), ).toEqual([ - { label: "Different", locked: false }, - { label: "Managed", locked: true }, + ["Pending", "not applied yet"], + ["Managed", "managed there"], + ["Readonly", "no permission to change settings"], + ["Old", "can't store Never, update T3 Code there"], + ["Failed", "not saved: The save failed."], ]); }); }); diff --git a/apps/web/src/components/settings/serverSettingPreferences.ts b/apps/web/src/components/settings/serverSettingPreferences.ts index db7936543adc5..d0ddb576cb1b0 100644 --- a/apps/web/src/components/settings/serverSettingPreferences.ts +++ b/apps/web/src/components/settings/serverSettingPreferences.ts @@ -4,6 +4,7 @@ import { idleCompactionPatch, isManagedSettingPath, type ManagedPolicySummary, + readsIdleCompactionModes, type ServerSettings, ServerSettingPreferences, type ServerSettingsPatch, @@ -23,6 +24,16 @@ export function isServerSettingPreferenceKey(key: string): key is ServerSettingP return PREFERENCE_KEY_SET.has(key); } +/** The preference a server settings field belongs to; older servers keep idle compaction in `compactIdleThreads`. */ +function preferenceKeyOf(field: string): ServerSettingPreferenceKey | null { + if (field === "compactIdleThreads") return "idleCompaction"; + return isServerSettingPreferenceKey(field) ? field : null; +} + +export function isCoveredSettingKey(field: string): boolean { + return preferenceKeyOf(field) !== null; +} + /** The value a server uses, from whichever field its version stores it in. */ function serverValue(settings: ServerSettings, key: ServerSettingPreferenceKey): unknown { return key === "idleCompaction" ? globalIdleCompaction(settings) : settings[key]; @@ -36,17 +47,22 @@ function isPreferenceLocked( return paths.some((path) => isManagedSettingPath(policy, path)); } -/** A change made for all environments becomes this client's preference for its keys. */ +/** + * A change made for all environments becomes this client's preference for its keys. With + * `onlyExisting`, as for Restore defaults, only preferences already set are updated. + */ export function recordServerSettingPreferences( current: ServerSettingPreferences, scope: Pick, patch: ServerSettingsPatch, + options?: { readonly onlyExisting?: boolean }, ): ServerSettingPreferences | null { if (scope.kind !== "all") return null; const next: Record = { ...current }; let recorded = false; for (const key of PREFERENCE_KEYS) { if (patch[key] === undefined) continue; + if (options?.onlyExisting && current[key] === undefined) continue; next[key] = patch[key]; recorded = true; } @@ -62,6 +78,51 @@ export function forgetServerSettingPreferences( return next as ServerSettingPreferences; } +/** Drops fields whose preference is set, which one environment must not change on its own. */ +export function withoutPreferredFields

( + patch: P, + preferences: ServerSettingPreferences, +): P { + return Object.fromEntries( + Object.entries(patch).filter(([field]) => { + const key = preferenceKeyOf(field); + return key === null || preferences[key] === undefined; + }), + ) as P; +} + +/** + * Under All environments, a covered setting is still saved where it can be: fields an + * environment's policy locks are dropped, and an environment this connection cannot change + * settings on is skipped when the write holds only covered fields. + */ +export function skipBlockedPreferenceWrites< + W extends { readonly environmentId: EnvironmentId; readonly patch: ServerSettingsPatch }, +>( + writes: readonly W[], + environment: { + readonly policyOf: (environmentId: EnvironmentId) => ManagedPolicySummary | undefined; + readonly canWrite: (environmentId: EnvironmentId, patch: ServerSettingsPatch) => boolean; + }, +): W[] { + return writes.flatMap((write) => { + const policy = environment.policyOf(write.environmentId); + const fields = Object.keys(write.patch); + const kept = fields.filter((field) => { + const key = preferenceKeyOf(field); + return key === null || !isPreferenceLocked(policy, key); + }); + if (kept.length === 0) return []; + const patch = Object.fromEntries( + kept.map((field) => [field, write.patch[field as keyof ServerSettingsPatch]]), + ) as ServerSettingsPatch; + if (kept.every(isCoveredSettingKey) && !environment.canWrite(write.environmentId, patch)) { + return []; + } + return [kept.length === fields.length ? write : { ...write, patch }]; + }); +} + /** * The patch that brings one server in line with the preferences, in the form its version * reads. Keys its administrator locks are left alone. @@ -89,14 +150,88 @@ export function planServerSettingPreferencesPatch( return patch; } +export interface PreferenceSyncTarget { + readonly environmentId: EnvironmentId; + readonly generation: number; + readonly settings: ServerSettings; + readonly managedPolicy: ManagedPolicySummary | undefined; + /** False until the auth session has loaded; a failed load also waits for a retry. */ + readonly sessionReady: boolean; +} + +/** Patches already sent to each connected environment during its current connection. */ +export type PreferenceSyncAttempts = Map< + EnvironmentId, + { readonly generation: number; readonly patches: Set } +>; + +/** + * The writes to send now. Each distinct patch goes to an environment at most once per + * connection, so a failed or dropped write is not repeated, a value another client changes + * is set back only on the next connection, and a config that arrives late is planned again. + * `connected` lists every environment connected right now; the rest are forgotten. + */ +export function nextPreferenceWrites( + attempts: PreferenceSyncAttempts, + connected: readonly PreferenceSyncTarget[], + preferences: ServerSettingPreferences, + canWrite: (environmentId: EnvironmentId, patch: ServerSettingsPatch) => boolean, +) { + const connectedIds = new Set(connected.map((target) => target.environmentId)); + for (const environmentId of attempts.keys()) { + if (!connectedIds.has(environmentId)) attempts.delete(environmentId); + } + return connected.flatMap((target) => { + if (!target.sessionReady) return []; + const patch = planServerSettingPreferencesPatch( + preferences, + target.settings, + target.managedPolicy, + ); + if (Object.keys(patch).length === 0 || !canWrite(target.environmentId, patch)) return []; + const key = JSON.stringify(patch); + let entry = attempts.get(target.environmentId); + if (entry?.generation !== target.generation) { + entry = { generation: target.generation, patches: new Set() }; + attempts.set(target.environmentId, entry); + } + if (entry.patches.has(key)) return []; + entry.patches.add(key); + return [{ environmentId: target.environmentId, patch, patchKey: key }]; + }); +} + export interface ServerSettingPreferenceTarget { readonly environmentId: EnvironmentId; readonly label: string; readonly settings: ServerSettings; readonly managedPolicy: ManagedPolicySummary | undefined; + readonly canWrite: boolean; + /** Why this app's last write of the preferences failed there, if it did. */ + readonly failure: string | undefined; +} + +/** Why an environment's value differs from the preference. */ +function differenceReason( + target: ServerSettingPreferenceTarget, + preferences: ServerSettingPreferences, + differing: readonly ServerSettingPreferenceKey[], +): string { + if (differing.some((key) => isPreferenceLocked(target.managedPolicy, key))) { + return "managed there"; + } + if (!target.canWrite) return "no permission to change settings"; + if ( + differing.includes("idleCompaction") && + preferences.idleCompaction === "off" && + !readsIdleCompactionModes(target.settings) + ) { + return "can't store Never, update T3 Code there"; + } + return target.failure === undefined ? "not applied yet" : `not saved: ${target.failure}`; } -/** Connected environments whose value for any of `keys` differs from the preference. */ +/** Connected environments whose value for any of `keys` differs from the preference, and why. */ export function serverSettingPreferenceDifferences( preferences: ServerSettingPreferences, keys: readonly string[], @@ -115,7 +250,7 @@ export function serverSettingPreferenceDifferences( { environmentId: target.environmentId, label: target.label, - locked: differing.some((key) => isPreferenceLocked(target.managedPolicy, key)), + reason: differenceReason(target, preferences, differing), }, ]; }); diff --git a/apps/web/src/components/settings/serverSettingPreferencesSync.ts b/apps/web/src/components/settings/serverSettingPreferencesSync.ts index 89a672911aeee..9579793e0ed8e 100644 --- a/apps/web/src/components/settings/serverSettingPreferencesSync.ts +++ b/apps/web/src/components/settings/serverSettingPreferencesSync.ts @@ -1,7 +1,12 @@ -import { type EnvironmentId, requiredScopesForServerSettingsPatch } from "@t3tools/contracts"; +import { + type EnvironmentId, + requiredScopesForServerSettingsPatch, + type ServerSettingsPatch, +} from "@t3tools/contracts"; import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; +import { useSyncExternalStore } from "react"; import { environmentCatalog } from "~/connection/catalog"; import { @@ -16,9 +21,9 @@ import { serverEnvironment } from "~/state/server"; import { environmentSession, readEnvironmentScope } from "~/state/session"; import { toastManager } from "../ui/toast"; import { persistScopedSettingsPatch } from "./scopedSettings"; -import { planServerSettingPreferencesPatch } from "./serverSettingPreferences"; +import { nextPreferenceWrites, type PreferenceSyncAttempts } from "./serverSettingPreferences"; -const targetsAtom = Atom.make((get) => +const connectedAtom = Atom.make((get) => [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => { const generation = Option.match( AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), @@ -28,42 +33,70 @@ const targetsAtom = Atom.make((get) => }, ); const config = get(serverEnvironment.configValueAtom(environmentId)); - // Write permission is known only once the session loads. - const sessionLoaded = - get(environmentSession.sessionStateAtom(environmentId))._tag !== "Initial"; - return generation === null || config === null || !sessionLoaded + return generation === null || config === null ? [] - : [{ environmentId, generation, config }]; + : [ + { + environmentId, + generation, + settings: config.settings, + managedPolicy: config.managedPolicy, + serverVersion: config.environment.serverVersion, + sessionReady: + get(environmentSession.sessionStateAtom(environmentId))._tag === "Success", + }, + ]; }), -).pipe(Atom.withLabel("web-server-setting-preferences-targets")); +).pipe(Atom.withLabel("web-server-setting-preferences-connected")); + +const attempts: PreferenceSyncAttempts = new Map(); +const reportedFailures = new Set(); +let failures: ReadonlyMap = new Map(); +const failureListeners = new Set<() => void>(); -const attemptedGenerations = new Map(); +function setFailure(environmentId: EnvironmentId, message: string | undefined) { + if (failures.get(environmentId) === message) return; + const next = new Map(failures); + if (message === undefined) next.delete(environmentId); + else next.set(environmentId, message); + failures = next; + for (const listener of failureListeners) listener(); +} + +function subscribeFailures(listener: () => void) { + failureListeners.add(listener); + return () => { + failureListeners.delete(listener); + }; +} + +/** Why this app's last write of its all-environment settings failed, per environment. */ +export function useServerSettingPreferenceFailures(): ReadonlyMap { + return useSyncExternalStore(subscribeFailures, () => failures); +} + +export const canWriteServerSettings = (environmentId: EnvironmentId, patch: ServerSettingsPatch) => + requiredScopesForServerSettingsPatch(patch).every((scope) => + readEnvironmentScope(environmentId, scope), + ); function applyServerSettingPreferences(): void { if (!isClientSettingsHydrated()) return; - const preferences = getClientSettings().serverSettingPreferences; - for (const { environmentId, generation, config } of appAtomRegistry.get(targetsAtom)) { - if (attemptedGenerations.get(environmentId) === generation) continue; - attemptedGenerations.set(environmentId, generation); - const patch = planServerSettingPreferencesPatch( - preferences, - config.settings, - config.managedPolicy, - ); - if (Object.keys(patch).length === 0) continue; - if ( - !requiredScopesForServerSettingsPatch(patch).every((scope) => - readEnvironmentScope(environmentId, scope), - ) - ) { - continue; - } + const connected = appAtomRegistry.get(connectedAtom); + const writes = nextPreferenceWrites( + attempts, + connected, + getClientSettings().serverSettingPreferences, + canWriteServerSettings, + ); + for (const { environmentId, patch, patchKey } of writes) { + const target = connected.find((candidate) => candidate.environmentId === environmentId)!; const label = readEnvironment(environmentId)?.label ?? environmentId; void persistScopedSettingsPatch( { clientPatch: {}, hasClientWrite: false, - serverWrites: [{ environmentId, label, patch, previous: config.settings }], + serverWrites: [{ environmentId, label, patch, previous: target.settings }], unavailableReason: null, }, (request) => @@ -72,21 +105,24 @@ function applyServerSettingPreferences(): void { }), () => undefined, ).then(({ failedEnvironments }) => { - for (const failed of failedEnvironments) { - toastManager.add({ - type: "error", - title: "Settings not applied", - description: `Could not apply your all-environment settings on ${failed.label}: ${failed.message}`, - }); - } + const failed = failedEnvironments[0]; + setFailure(environmentId, failed?.message); + const reportKey = JSON.stringify([environmentId, target.serverVersion, patchKey]); + if (failed === undefined || reportedFailures.has(reportKey)) return; + reportedFailures.add(reportKey); + toastManager.add({ + type: "error", + title: "Settings not applied", + description: `Could not apply your all-environment settings on ${label}: ${failed.message}`, + }); }); } } -/** Applies this client's all-environment settings to each server, once per connection. */ +/** Applies this client's all-environment settings to each server it connects to. */ export function startServerSettingPreferencesSync(): () => void { const unsubscribes = [ - appAtomRegistry.subscribe(targetsAtom, applyServerSettingPreferences), + appAtomRegistry.subscribe(connectedAtom, applyServerSettingPreferences), subscribeClientSettings(applyServerSettingPreferences), subscribeClientSettingsHydration(applyServerSettingPreferences), ]; diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index 5855e78303d7a..29f90638a5bb3 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -5,6 +5,7 @@ import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/sessi import { useServerConfigs } from "../../state/entities"; import { InfoIcon, Undo2Icon } from "lucide-react"; import { + DEFAULT_IDLE_COMPACTION, DEFAULT_SERVER_SETTINGS, isManagedSettingPath, type ServerSettings, @@ -33,9 +34,11 @@ import { } from "./scopedSettings"; import { forgetServerSettingPreferences, + isCoveredSettingKey, isServerSettingPreferenceKey, serverSettingPreferenceDifferences, } from "./serverSettingPreferences"; +import { useServerSettingPreferenceFailures } from "./serverSettingPreferencesSync"; import { updateServerSettingPreferences, useClearProjectOverrides, @@ -356,15 +359,23 @@ export function SettingsRow({ context?.connectedEnvironments ?? [], AuthSettingsWriteScope, ); + // Under All environments a covered setting saves where it can and lists the rest with reasons. + const coveredUnderAll = + context?.scope.kind === "all" && + serverScoped && + managedPaths.length === 0 && + settingKeys.length > 0 && + settingKeys.every(isCoveredSettingKey); const canWriteSettings = context ? context.connectedEnvironments.length > 0 && - context.connectedEnvironments.every((target) => writableIds.has(target.environmentId)) + (coveredUnderAll || + context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))) : primaryCanWrite; const serverConfigs = useServerConfigs(); // An administrator's lock on any target wins over every other reason a control is inert. const lockablePaths = [...settingKeys, ...managedPaths]; const managedBy = - lockablePaths.length === 0 + lockablePaths.length === 0 || coveredUnderAll ? undefined : (context ? context.connectedEnvironments.map((environment) => environment.serverConfig) @@ -377,6 +388,7 @@ export function SettingsRow({ lockablePaths.some((path) => isManagedSettingPath(policy, path)), )?.organization; const preferences = useClientSettings((settings) => settings.serverSettingPreferences); + const preferenceFailures = useServerSettingPreferenceFailures(); const preferenceKeys = serverScoped ? settingKeys .filter(isServerSettingPreferenceKey) @@ -481,7 +493,10 @@ export function SettingsRow({ const environmentSettings = environmentSettingsById.get(candidate.environmentId); return ( environmentSettings !== undefined && - !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key]) + !Equal.equals( + environmentSettings[key], + key === "idleCompaction" ? DEFAULT_IDLE_COMPACTION : DEFAULT_SERVER_SETTINGS[key], + ) ); }), ); @@ -527,16 +542,13 @@ export function SettingsRow({ label: environment.label, settings: environment.serverConfig.settings, managedPolicy: environment.serverConfig.managedPolicy, + canWrite: writableIds.has(environment.environmentId), + failure: preferenceFailures.get(environment.environmentId), }, ] : [], ), ); - const listLabels = (locked: boolean) => - preferenceDifferences - .filter((difference) => difference.locked === locked) - .map((difference) => difference.label) - .join(", "); const renderedPreferenceStatus = preferenceStatus && context !== null && @@ -544,8 +556,11 @@ export function SettingsRow({ preferenceKeys.length > 0 ? ( <> Applied to every environment this app connects to, including new ones. - {listLabels(false) ? ` Different on ${listLabels(false)}.` : null} - {listLabels(true) ? ` Not applied on ${listLabels(true)}: managed there.` : null}{" "} + {preferenceDifferences.length > 0 + ? ` Different on ${preferenceDifferences + .map(({ label, reason }) => `${label} (${reason.replace(/\.$/, "")})`) + .join(", ")}.` + : null}{" "}