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/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..f38efea32e444 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?.(); }; @@ -1532,8 +1536,11 @@ export function CompactIdleThreadsRow() { function ScopedCompactIdleThreadsRow() { const settings = useScopedSettings(); const updateSettings = useUpdateScopedSettings(); - const { targets } = useSettingsScope(); + const { scope, targets } = useSettingsScope(); const idleCompaction = scopedIdleCompaction(targets.length > 0 ? targets : [{ settings }]); + // Under All environments the choice is saved for every environment; one too old to store + // "Never" is listed as such rather than blocking the choice. + const neverSelectable = scope.kind === "all" || idleCompaction.neverAvailable; return ( {mode.label} @@ -1818,6 +1825,7 @@ export function ThreadsSettingsPanel() { = {}): ServerSettings => ({ + ...DEFAULT_SERVER_SETTINGS, + compactIdleThreads: false, + idleCompaction: "onReturn", + ...overrides, +}); + +const lockedBy = (...lockedSettings: string[]): ManagedPolicySummary => ({ + organization: "Example Corp", + 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( + 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("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 }, [ + "idleCompaction", + ]), + ).toEqual({ sidebarAutoSettleOnMerge: true }); + }); +}); + +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", + 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("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 each differing environment with why it was not applied", () => { + const target = ( + label: string, + serverSettings: ServerSettings, + extra: { policy?: ManagedPolicySummary; canWrite?: boolean; failure?: string } = {}, + ) => ({ + environmentId: EnvironmentId.make(label), + label, + settings: serverSettings, + 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("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, reason }) => [label, reason]), + ).toEqual([ + ["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 new file mode 100644 index 0000000000000..1f160082acbdc --- /dev/null +++ b/apps/web/src/components/settings/serverSettingPreferences.ts @@ -0,0 +1,257 @@ +import { + type EnvironmentId, + globalIdleCompaction, + idleCompactionPatch, + isManagedSettingPath, + type ManagedPolicySummary, + readsIdleCompactionModes, + 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 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]; +} + +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. 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; + } + 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; +} + +/** 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. + */ +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 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 at most once per connection, so failed writes + * aren't repeated and two clients can't fight. A value changed elsewhere is set back now if + * this connection hasn't sent that patch yet, otherwise on the next connection. + * `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, and why. */ +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, + reason: differenceReason(target, preferences, differing), + }, + ]; + }); +} diff --git a/apps/web/src/components/settings/serverSettingPreferencesSync.ts b/apps/web/src/components/settings/serverSettingPreferencesSync.ts new file mode 100644 index 0000000000000..9579793e0ed8e --- /dev/null +++ b/apps/web/src/components/settings/serverSettingPreferencesSync.ts @@ -0,0 +1,133 @@ +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 { + 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 { nextPreferenceWrites, type PreferenceSyncAttempts } from "./serverSettingPreferences"; + +const connectedAtom = 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)); + return generation === null || config === null + ? [] + : [ + { + 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-connected")); + +const attempts: PreferenceSyncAttempts = new Map(); +const reportedFailures = new Set(); +let failures: ReadonlyMap = new Map(); +const failureListeners = new Set<() => void>(); + +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 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: target.settings }], + unavailableReason: null, + }, + (request) => + runAtomCommand(appAtomRegistry, serverEnvironment.updateSettings, request, { + reportFailure: false, + }), + () => undefined, + ).then(({ failedEnvironments }) => { + 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 it connects to. */ +export function startServerSettingPreferencesSync(): () => void { + const unsubscribes = [ + appAtomRegistry.subscribe(connectedAtom, 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..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, @@ -15,6 +16,7 @@ import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContex import { PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE, + useClientSettings, usePrimarySettingsAvailable, } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; @@ -30,7 +32,18 @@ import { scopedSettingsAreMixed, scopedSettingsSource, } from "./scopedSettings"; -import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings"; +import { + forgetServerSettingPreferences, + isCoveredSettingKey, + isServerSettingPreferenceKey, + serverSettingPreferenceDifferences, +} from "./serverSettingPreferences"; +import { useServerSettingPreferenceFailures } from "./serverSettingPreferencesSync"; +import { + updateServerSettingPreferences, + useClearProjectOverrides, + useClearScopedSettings, +} from "./useScopedSettings"; import { SettingInheritance, type SettingInheritanceState, @@ -314,6 +327,7 @@ export function SettingsRow({ managedPaths = EMPTY_MANAGED_PATHS, mixed: mixedOverride, managed, + preferenceStatus = true, children, className, ...rowProps @@ -331,6 +345,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); @@ -343,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) @@ -363,6 +387,15 @@ export function SettingsRow({ policy !== undefined && lockablePaths.some((path) => isManagedSettingPath(policy, path)), )?.organization; + const preferences = useClientSettings((settings) => settings.serverSettingPreferences); + const preferenceFailures = useServerSettingPreferenceFailures(); + 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 +425,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" ? ( @@ -454,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], + ) ); }), ); @@ -486,7 +528,61 @@ 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, + canWrite: writableIds.has(environment.environmentId), + failure: preferenceFailures.get(environment.environmentId), + }, + ] + : [], + ), + ); + 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. + {preferenceDifferences.length > 0 + ? ` Different on ${preferenceDifferences + .map(({ label, reason }) => `${label} (${reason.replace(/\.$/, "")})`) + .join(", ")}.` + : null}{" "} + + + ) : null; + const renderedStatus = + status && renderedPreferenceStatus ? ( + <> + {status} +

{renderedPreferenceStatus}
+ + ) : ( + (status ?? renderedPreferenceStatus) + ); return (
( selector?: (settings: UnifiedSettings) => T, @@ -101,8 +113,58 @@ 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 ( + requested: ScopedSettingsPatch, + options?: { + readonly onFailed?: () => void; + /** Update only all-environment settings already applied everywhere, as Restore defaults does. */ + readonly onlyExistingPreferences?: boolean; + }, + ) => { + const preferences = getClientSettings().serverSettingPreferences; + // A setting applied everywhere is changed under All environments, not on one environment. + const patch = + scope.kind === "environment" ? withoutPreferredFields(requested, preferences) : requested; + const planned = planScopedSettingsPatch(scope, environments, patch); + const plan = + scope.kind === "all" + ? { + ...planned, + serverWrites: skipBlockedPreferenceWrites(planned.serverWrites, { + policyOf: (environmentId) => + environments.find((environment) => environment.environmentId === environmentId) + ?.serverConfig?.managedPolicy, + canWrite: canWriteServerSettings, + }), + } + : planned; + const recordOptions = { onlyExisting: options?.onlyExistingPreferences === true }; + if ( + plan.unavailableReason === null && + recordServerSettingPreferences(preferences, scope, patch, recordOptions) + ) { + updateServerSettingPreferences( + (current) => + recordServerSettingPreferences(current, scope, patch, recordOptions) ?? 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() { diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 0cad979ea0d6e..01f39a8616365 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -8,7 +8,23 @@ 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. If a +connected environment's administrator locks the setting, or this connection can't change settings +there, the change is saved everywhere else. + +After that, the setting says it applies everywhere and lists any connected environment that still +has a different value, with the reason: managed there, no permission, a version too old to store +the value, a save that failed, or not applied yet. If the value is changed on an environment some +other way, such as from your phone or another computer, this app sets it back, at the latest the +next time it connects there. While one environment is selected, a setting this app applies everywhere is +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..70e8edf3b1d6e 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -95,6 +95,16 @@ 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; +/** The mode a server uses when neither its settings file nor a policy chooses one. */ +export const DEFAULT_IDLE_COMPACTION: IdleCompactionMode = "off"; + export const MAX_SNOOZE_PRESET_MINUTES = 30 * 24 * 60; export const MAX_SNOOZE_PRESETS = 8; export const SnoozePresetDay = Schema.Literals([ @@ -389,7 +399,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 +765,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]); @@ -1744,7 +1760,7 @@ export class ServerSettingsError extends Schema.TaggedError export type UnifiedSettings = Omit & ClientSettings; export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = { - ...DEFAULT_SERVER_SETTINGS, + ...withIdleCompaction(DEFAULT_SERVER_SETTINGS, DEFAULT_IDLE_COMPACTION), ...DEFAULT_CLIENT_SETTINGS, };