TypeScript
fix(settings): older clients connect again after idle compaction modes (#23454)
Julius Marminge43879d970204
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.tsindex a23d44fc282..ac4e0d39428 100644--- a/apps/server/src/serverSettings.test.ts+++ b/apps/server/src/serverSettings.test.ts@@ -212,6 +212,29 @@ it.layer(NodeServices.layer)("server settings", (it) => {}).pipe(Effect.provide(layerServerSettings())),);+ it.effect("moves an idle compaction mode saved in the legacy switch to its own field", () =>+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fs = yield* FileSystem.FileSystem;+ const service = yield* ServerSettingsModule.ServerSettingsService;+ yield* fs.writeFileString(config.settingsPath, `{ "compactIdleThreads": "off" }`);++ const settings = yield* service.getSettings;+ // Shipped clients decode the switch as a boolean and drop the config otherwise.+ assert.strictEqual(settings.compactIdleThreads, false);+ assert.equal(settings.idleCompaction, "off");+ }).pipe(Effect.provide(layerServerSettings())),+ );++ it.effect("tells clients it reads idle compaction modes before any settings are saved", () =>+ Effect.gen(function* () {+ const service = yield* ServerSettingsModule.ServerSettingsService;+ const settings = yield* service.getSettings;+ assert.equal(settings.idleCompaction, "onReturn");+ assert.strictEqual(settings.compactIdleThreads, false);+ }).pipe(Effect.provide(layerServerSettings())),+ );+it.effect("saves through a symlinked settings file without replacing the link", () =>Effect.gen(function* () {const config = yield* ServerConfig.ServerConfig;diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.tsindex 5289b7b4d75..65c114c75ca 100644--- a/apps/server/src/serverSettings.ts+++ b/apps/server/src/serverSettings.ts@@ -15,6 +15,8 @@ import {ServerSettings,ServerSettingsError,type ServerSettingsPatch,+ globalIdleCompaction,+ withIdleCompaction,} from "@t3tools/contracts";import * as Cache from "effect/Cache";import * as Cause from "effect/Cause";@@ -117,6 +119,7 @@ const normalizeServerSettings = (encodeServerSettings(settings).pipe(Effect.flatMap(decodeServerSettings),Effect.map(foldProviderInstanceEnabledFlags),+ Effect.map((next) => withIdleCompaction(next, globalIdleCompaction(next))),Effect.map((next) => ({ ...next, ...deriveLegacyProjectOverrides(next) })),Effect.mapError((cause) =>@@ -685,6 +688,10 @@ const make = Effect.gen(function* () {settings = decoded.value;}}+ // Settings saved by a server that kept the mode in `compactIdleThreads` move+ // it to `idleCompaction`, so that switch goes to clients as a boolean. The+ // defaults gain the field too, which tells clients this server reads modes.+ settings = withIdleCompaction(settings, globalIdleCompaction(settings));// A file that failed to decode must stay on disk for the user to repair.const settingsFileTrusted = Option.isNone(parseFailure);diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex 649f26ee1e7..c733fae9353 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -7,6 +7,7 @@ import { useEffect, useRef, useState } from "react";import {type DesktopUpdateChannel,IDLE_COMPACTION_MODES,+ globalIdleCompaction,ProviderDriverKind,type ProviderInstanceId,type SidebarProjectGroupingMode,@@ -51,6 +52,7 @@ import {} from "./useScopedSettings";import { useScopedModelDisabledReason } from "./useScopedModelAvailability";import { useSettingsScope } from "./SettingsScopeContext";+import { scopedIdleCompaction } from "./scopedSettings";import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";import { useDesktopUpdateState } from "../../state/desktopUpdate";import {@@ -785,7 +787,8 @@ export function GeneralSettingsPanel() {const settings = useScopedSettings();const updateSettings = useUpdateScopedSettings();const navigate = useNavigate();- const { scope, environment, connectedEnvironments, target } = useSettingsScope();+ const { scope, environment, connectedEnvironments, target, targets } = useSettingsScope();+ const idleCompaction = scopedIdleCompaction(targets.length > 0 ? targets : [{ settings }]);const environmentId = environment?.environmentId ?? null;const isEnvironmentScope = scope.environmentIds.length === 1 && environmentId !== null;const hasServerTargets = connectedEnvironments.length > 0;@@ -996,40 +999,46 @@ export function GeneralSettingsPanel() {<SettingsRowserverScoped- settingKeys={["compactIdleThreads"]}+ settingKeys={["idleCompaction", "compactIdleThreads"]}+ mixed={idleCompaction.mixed}{...searchableSetting("compact-idle-threads")}description="When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this."resetAction={- settings.compactIdleThreads !== DEFAULT_UNIFIED_SETTINGS.compactIdleThreads ? (+ globalIdleCompaction(settings) !== globalIdleCompaction(DEFAULT_UNIFIED_SETTINGS) ? (<SettingResetButtonlabel="compact idle threads"onClick={() =>- updateSettings({- compactIdleThreads: DEFAULT_UNIFIED_SETTINGS.compactIdleThreads,- })+ updateSettings({ idleCompaction: globalIdleCompaction(DEFAULT_UNIFIED_SETTINGS) })}/>) : null}control={<Select- value={settings.compactIdleThreads}+ value={idleCompaction.mixed ? null : globalIdleCompaction(settings)}onValueChange={(value) => {const mode = IDLE_COMPACTION_MODES.find((candidate) => candidate.value === value);- if (mode) updateSettings({ compactIdleThreads: mode.value });+ if (mode) updateSettings({ idleCompaction: mode.value });}}><SelectTrigger size="sm" className="w-full sm:w-56" aria-label="Compact idle threads"><SelectValue>- {- IDLE_COMPACTION_MODES.find((mode) => mode.value === settings.compactIdleThreads)- ?.label+ {(value: string | null) =>+ value === null+ ? "Mixed"+ : IDLE_COMPACTION_MODES.find((mode) => mode.value === value)?.label}</SelectValue></SelectTrigger><SelectPopup align="end" alignItemWithTrigger={false}>{IDLE_COMPACTION_MODES.map((mode) => (- <SelectItem hideIndicator key={mode.value} value={mode.value}>+ <SelectItem+ hideIndicator+ key={mode.value}+ value={mode.value}+ // A server from before modes has only the on/off switch, so it cannot store "Never".+ disabled={mode.value === "off" && !idleCompaction.neverAvailable}+ >{mode.label}</SelectItem>))}diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.tsindex c03e466d1e2..3354b46a303 100644--- a/apps/web/src/components/settings/scopedSettings.test.ts+++ b/apps/web/src/components/settings/scopedSettings.test.ts@@ -17,6 +17,7 @@ import {planProjectOverridesClear,planScopedSettingsClear,planScopedSettingsPatch,+ scopedIdleCompaction,resolveScopedSettingsTargets,scopedSettingsAreMixed,scopedSettingsSource,@@ -192,6 +193,42 @@ describe("scoped settings writes", () => {]);});+ it("compares idle compaction by mode, and offers Never only where every server stores it", () => {+ const fixed = {+ settings: {+ ...DEFAULT_SERVER_SETTINGS,+ compactIdleThreads: false,+ idleCompaction: "onReturn" as const,+ },+ };+ const modes = {+ settings: { ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: "onReturn" as const },+ };+ const legacy = { settings: { ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: false } };+ expect(scopedIdleCompaction([fixed, modes])).toEqual({ mixed: false, neverAvailable: true });+ expect(scopedIdleCompaction([fixed, legacy])).toEqual({ mixed: false, neverAvailable: false });+ expect(+ scopedIdleCompaction([fixed, { settings: { ...fixed.settings, idleCompaction: "off" } }])+ .mixed,+ ).toBe(true);+ });++ it("sends an idle compaction mode in the form each environment's server reads", () => {+ const targets = [+ environment("Fixed", { settings: { compactIdleThreads: false, idleCompaction: "onReturn" } }),+ environment("Modes", { settings: { compactIdleThreads: "onReturn" } }),+ environment("Switch", { settings: { compactIdleThreads: false } }),+ ];+ const plan = planScopedSettingsPatch(resolveSettingsScope({}, [], targets), targets, {+ idleCompaction: "beforeCacheExpires",+ });+ expect(plan.serverWrites.map((write) => write.patch)).toEqual([+ { idleCompaction: "beforeCacheExpires" },+ { compactIdleThreads: "beforeCacheExpires" },+ { compactIdleThreads: true },+ ]);+ });+it("writes an aggregate preference only to connected environments with loaded configuration", async () => {const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });const persistClient = vi.fn();diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.tsindex 1a0c761208a..097b3a51128 100644--- a/apps/web/src/components/settings/scopedSettings.ts+++ b/apps/web/src/components/settings/scopedSettings.ts@@ -2,7 +2,10 @@ import {ClientSettingsSchema,type ClientSettingsPatch,type EnvironmentId,+ globalIdleCompaction,+ idleCompactionPatch,isNullableProjectSettingsOverride,+ readsIdleCompactionModes,PROJECT_SCOPED_SERVER_SETTING_KEYS,type ProjectId,type ProjectScopedServerSettingKey,@@ -138,6 +141,19 @@ export function scopedSettingsAreMixed();}+/**+ * Servers store the idle compaction mode differently by version, so selected+ * environments are compared by the mode each resolves to, and "Never" is offered+ * only when every one of them can store it.+ */+export function scopedIdleCompaction(targets: readonly Pick<ScopedSettingsTarget, "settings">[]) {+ const modes = targets.map((candidate) => globalIdleCompaction(candidate.settings));+ return {+ mixed: modes.some((mode) => mode !== modes[0]),+ neverAvailable: targets.every((candidate) => readsIdleCompactionModes(candidate.settings)),+ };+}+export type ScopedSettingSource = ProjectSettingSource | "mixed";export function scopedSettingsSource(@@ -201,6 +217,13 @@ function projectOverrideWrites(return [...writes.values()];}+/** Puts an idle compaction mode in the form each destination server reads. */+function forDestination(previous: ServerSettings, patch: ServerSettingsPatch): ServerSettingsPatch {+ if (patch.idleCompaction === undefined) return patch;+ const { idleCompaction, compactIdleThreads: _legacy, ...rest } = patch;+ return { ...rest, ...idleCompactionPatch(previous, idleCompaction) };+}+export function planScopedSettingsPatch(scope: ResolvedSettingsScope,environments: readonly ScopedSettingsEnvironment[],@@ -278,12 +301,13 @@ export function planScopedSettingsPatch(environmentId: environment.environmentId,label: environment.label,previous,- patch:+ patch: forDestination(+ previous,previous.worktreeCleanup != null &&- serverPatch.storageCleanup &&- Object.keys(serverPatch.storageCleanup).some((key) =>- key.startsWith("worktree"),- )+ serverPatch.storageCleanup &&+ Object.keys(serverPatch.storageCleanup).some((key) =>+ key.startsWith("worktree"),+ )? {...serverPatch,worktreeCleanup: {@@ -299,6 +323,7 @@ export function planScopedSettingsPatch(},}: serverPatch,+ ),},];})diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.tsindex fb25e1c1869..25523c2d0fb 100644--- a/packages/contracts/src/settings.test.ts+++ b/packages/contracts/src/settings.test.ts@@ -8,12 +8,15 @@ import {ClientSettingsPatch,ClaudeSettings,DEFAULT_SERVER_SETTINGS,+ globalIdleCompaction,+ idleCompactionPatch,requiredScopesForProjectMutation,resolveIdleCompaction,resolveProjectProviderInstanceEnabled,resolveProviderInstanceEnabled,ServerSettings,ServerSettingsPatch,+ withIdleCompaction,} from "./settings.ts";const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);@@ -138,7 +141,7 @@ describe("custom model settings", () => {describe("resolveIdleCompaction", () => {it("lets a Claude instance override the global default", () => {const settings = decodeServerSettings({- compactIdleThreads: "off",+ idleCompaction: "off",providerInstances: {claude_work: { driver: "claudeAgent", config: { idleCompaction: "onReturn" } },claude_personal: { driver: "claudeAgent" },@@ -151,11 +154,38 @@ describe("resolveIdleCompaction", () => {expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claudeAgent"))).toBe("off");});- it("keeps the legacy beta switch's behavior", () => {- expect(decodeServerSettings({ compactIdleThreads: true }).compactIdleThreads).toBe(+ it("reads the mode from the legacy switch, in either form servers saved it", () => {+ expect(globalIdleCompaction(decodeServerSettings({ compactIdleThreads: true }))).toBe("beforeCacheExpires",);- expect(decodeServerSettings({}).compactIdleThreads).toBe("onReturn");+ expect(globalIdleCompaction(decodeServerSettings({ compactIdleThreads: "off" }))).toBe("off");+ expect(globalIdleCompaction(decodeServerSettings({}))).toBe("onReturn");+ });++ it("keeps the legacy switch a boolean, as shipped clients decode it", () => {+ const encode = Schema.encodeSync(Schema.toCodecJson(ServerSettings));+ for (const mode of ["onReturn", "beforeCacheExpires", "off"] as const) {+ const encoded = encode(withIdleCompaction(DEFAULT_SERVER_SETTINGS, mode)) as {+ readonly compactIdleThreads: unknown;+ readonly idleCompaction: unknown;+ };+ expect(encoded.compactIdleThreads).toBe(mode === "beforeCacheExpires");+ expect(encoded.idleCompaction).toBe(mode);+ }+ });++ it("patches the field the server reads", () => {+ expect(+ idleCompactionPatch({ compactIdleThreads: false, idleCompaction: "onReturn" }, "off"),+ ).toEqual({+ idleCompaction: "off",+ });+ expect(idleCompactionPatch({ compactIdleThreads: "onReturn" }, "off")).toEqual({+ compactIdleThreads: "off",+ });+ expect(idleCompactionPatch({ compactIdleThreads: false }, "beforeCacheExpires")).toEqual({+ compactIdleThreads: true,+ });});});diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 67b850f2d7e..fbe4d945cff 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -652,17 +652,12 @@ export const IDLE_COMPACTION_MODES = [export const IdleCompactionMode = Schema.Literals(IDLE_COMPACTION_MODES.map((mode) => mode.value));export type IdleCompactionMode = typeof IdleCompactionMode.Type;-// `compactIdleThreads` was a beta on/off switch for compacting before the cache expires.-const LegacyCompactIdleThreads = Schema.Boolean.pipe(- Schema.decodeTo(- IdleCompactionMode,- SchemaTransformation.transform({- decode: (enabled): IdleCompactionMode => (enabled ? "beforeCacheExpires" : "onReturn"),- encode: (mode) => mode === "beforeCacheExpires",- }),- ),-);-const IdleCompactionModeSetting = Schema.Union([IdleCompactionMode, LegacyCompactIdleThreads]);+// `compactIdleThreads` was a beta on/off switch for compacting before the cache+// expires. Shipped clients decode it as a boolean and drop the whole server config+// otherwise, so it stays a boolean on the wire and the mode lives in+// `idleCompaction`. Servers before that split sent the mode here, so a string is+// still read.+const LegacyCompactIdleThreads = Schema.Union([Schema.Boolean, IdleCompactionMode]);const INSTANCE_IDLE_COMPACTION_MODES = [{ value: "default", label: "Use default" },@@ -1202,9 +1197,10 @@ export const ServerSettings = Schema.Struct({sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),),- compactIdleThreads: IdleCompactionModeSetting.pipe(- Schema.withDecodingDefault(Effect.succeed("onReturn" as const)),+ compactIdleThreads: LegacyCompactIdleThreads.pipe(+ Schema.withDecodingDefault(Effect.succeed(false)),),+ idleCompaction: Schema.optionalKey(IdleCompactionMode),snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(@@ -1380,8 +1376,41 @@ export const resolveProjectProviderInstanceEnabled = (const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);+type IdleCompactionSettings = Pick<ServerSettings, "compactIdleThreads" | "idleCompaction">;++/** The environment-wide idle compaction mode, from whichever field the settings carry. */+export const globalIdleCompaction = (settings: IdleCompactionSettings): IdleCompactionMode =>+ settings.idleCompaction ??+ (typeof settings.compactIdleThreads === "string"+ ? settings.compactIdleThreads+ : settings.compactIdleThreads+ ? "beforeCacheExpires"+ : "onReturn");++/** Sets the mode, and the legacy switch shipped clients still read alongside it. */+export const withIdleCompaction = <S extends IdleCompactionSettings>(+ settings: S,+ mode: IdleCompactionMode,+): S => ({ ...settings, idleCompaction: mode, compactIdleThreads: mode === "beforeCacheExpires" });++/** Whether a server reads modes, rather than only the boolean switch from before them. */+export const readsIdleCompactionModes = (settings: IdleCompactionSettings) =>+ settings.idleCompaction !== undefined || typeof settings.compactIdleThreads === "string";++/**+ * The patch that sets `mode` in the form the server's settings show it reads:+ * the mode for a server that has `idleCompaction` or kept the mode in the legacy+ * field, the boolean switch for a server from before modes.+ */+export const idleCompactionPatch = (settings: IdleCompactionSettings, mode: IdleCompactionMode) =>+ settings.idleCompaction !== undefined+ ? { idleCompaction: mode }+ : readsIdleCompactionModes(settings)+ ? { compactIdleThreads: mode }+ : { compactIdleThreads: mode === "beforeCacheExpires" };+export const resolveIdleCompaction = (- settings: Pick<ServerSettings, "providerInstances" | "compactIdleThreads">,+ settings: Pick<ServerSettings, "providerInstances" | "compactIdleThreads" | "idleCompaction">,instanceId: ProviderInstanceId,): IdleCompactionMode => {const instance = Object.hasOwn(settings.providerInstances, instanceId)@@ -1391,7 +1420,7 @@ export const resolveIdleCompaction = (Option.map((config) => config.idleCompaction),Option.getOrElse(() => "default" as const),);- return override === "default" ? settings.compactIdleThreads : override;+ return override === "default" ? globalIdleCompaction(settings) : override;};export const ServerSettingsOperation = Schema.Literals([@@ -1535,7 +1564,8 @@ export const ServerSettingsPatch = Schema.Struct({deviceHosts: Schema.optionalKey(SshDeviceHostConfigs),easDeviceHosts: Schema.optionalKey(EasDeviceHostConfigs),sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),- compactIdleThreads: Schema.optionalKey(IdleCompactionMode),+ compactIdleThreads: Schema.optionalKey(LegacyCompactIdleThreads),+ idleCompaction: Schema.optionalKey(IdleCompactionMode),sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean),sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.tsindex d35cd148605..51815954ad3 100644--- a/packages/shared/src/serverSettings.test.ts+++ b/packages/shared/src/serverSettings.test.ts@@ -52,6 +52,16 @@ describe("fallbackTextGenerationModelSelection", () => {});describe("serverSettings helpers", () => {+ it("translates a shipped client's idle compaction switch into a mode", () => {+ const off = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { idleCompaction: "off" });+ expect([off.idleCompaction, off.compactIdleThreads]).toEqual(["off", false]);+ // Turning the old switch off keeps "Never" instead of reverting to the default.+ const stillOff = applyServerSettingsPatch(off, { compactIdleThreads: false });+ expect(stillOff.idleCompaction).toBe("off");+ const on = applyServerSettingsPatch(off, { compactIdleThreads: true });+ expect([on.idleCompaction, on.compactIdleThreads]).toEqual(["beforeCacheExpires", true]);+ });+it("changes a cleanup rule without replacing the machine's other rules", () => {const enabled = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {storageCleanup: { worktreeAfterDays: 8, worktreeOnMerge: true, logsAfterDays: 30 },diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.tsindex 5371cf76e8a..786126998c9 100644--- a/packages/shared/src/serverSettings.ts+++ b/packages/shared/src/serverSettings.ts@@ -4,6 +4,8 @@ import {DEFAULT_TEXT_GENERATION_MODEL,DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,defaultInstanceIdForDriver,+ globalIdleCompaction,+ type IdleCompactionMode,isProviderAvailable,isUnconfiguredDefaultInstanceEnabled,resolveProjectProviderInstanceEnabled,@@ -18,6 +20,7 @@ import {type ServerProvider,ServerSettings,type ServerSettingsPatch,+ withIdleCompaction,} from "@t3tools/contracts";import * as Option from "effect/Option";import * as Schema from "effect/Schema";@@ -359,6 +362,22 @@ function translateLegacyProjectOverridePatch(} as ServerSettingsPatch;}+/**+ * A client from before `idleCompaction` patches the old boolean switch. Turning+ * it off keeps "Never" rather than reverting to the default.+ */+function patchedIdleCompaction(+ current: ServerSettings,+ patch: ServerSettingsPatch,+): IdleCompactionMode {+ if (patch.idleCompaction !== undefined) return patch.idleCompaction;+ const legacy = patch.compactIdleThreads;+ if (legacy === undefined) return globalIdleCompaction(current);+ if (typeof legacy === "string") return legacy;+ if (legacy) return "beforeCacheExpires";+ return globalIdleCompaction(current) === "off" ? "off" : "onReturn";+}+export function applyServerSettingsPatch(current: ServerSettings,rawPatch: ServerSettingsPatch,@@ -598,7 +617,7 @@ export function applyServerSettingsPatch(normalizedBackgroundActivity,);const nextWithReplacements = {- ...nextWithReplacementsBase,+ ...withIdleCompaction(nextWithReplacementsBase, patchedIdleCompaction(current, patch)),...deriveLegacyProjectOverrides(nextWithReplacementsBase),backgroundActivity: normalizedBackgroundActivity,automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,