TypeScript
fix(settings): share restart continuation across environments (#9933)
mariaf47a3fe90354
diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsxindex 41c2076ac7b..3bd25a20c8d 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx@@ -44,6 +44,7 @@ import {type ServerSettingsPatch,} from "@t3tools/contracts";import {+ filterSharedServerPatch,findSharedSettingsMismatches,pickSharedServerSettings,supportsSharedSettingsSync,@@ -584,11 +585,13 @@ function AutoSettleSettingsRows() {const mismatches = findSharedSettingsMismatches({primaryEnvironmentId: reference.environmentId,primarySettings: referenceSettings,+ primaryCapabilities: reference.serverConfig?.environment.capabilities,environments: environments.map((environment) => ({environmentId: environment.environmentId,label: environment.label,syncEligible: supportsSharedSettingsSync(environment),settings: environment.serverConfig?.settings ?? null,+ capabilities: environment.serverConfig?.environment.capabilities,})),});@@ -652,11 +655,22 @@ function AutoSettleSettingsRows() {<PressableaccessibilityRole="button"onPress={() => {- const patch = pickSharedServerSettings(referenceSettings);+ const patch = pickSharedServerSettings(+ referenceSettings,+ reference.serverConfig?.environment.capabilities,+ );for (const mismatch of mismatches) {+ const target = environments.find(+ (candidate) => candidate.environmentId === mismatch.environmentId,+ );void updateSettings({environmentId: mismatch.environmentId,- input: { patch },+ input: {+ patch: filterSharedServerPatch(+ patch,+ target?.serverConfig?.environment.capabilities,+ ),+ },});}}}diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex cfecfc00c86..eab723d7909 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -219,6 +219,7 @@ export const make = Effect.gen(function* () {pullRequests: true,threadSettlement: true,threadAutoSettlement: true,+ threadRestartContinuation: true,threadSnooze: true,environmentThemes: true,usageLimitSources: true,diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex 8482e37440a..e79464d1757 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -2439,7 +2439,7 @@ export function GeneralSettingsPanel() {<SettingsRow{...searchableSetting("continue-threads-after-server-update")}serverScoped- description="Automatically resume interrupted threads when this environment starts again after an update, crash, or machine restart."+ description="Automatically resume interrupted threads after an update, crash, or machine restart. Applies to this environment and all connected environments that support it. Update older servers first."resetAction={settings.continueThreadsAfterServerUpdate !==DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate ? (diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.tsindex bed80616e4a..52a6fec12f0 100644--- a/apps/web/src/hooks/useSettings.ts+++ b/apps/web/src/hooks/useSettings.ts@@ -26,6 +26,7 @@ import {} from "@t3tools/contracts/settings";import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";import {+ filterSharedServerPatch,findSharedSettingsMismatches,pickSharedServerSettings,splitSharedServerPatch,@@ -368,18 +369,6 @@ export function usePrimarySettingsAvailable(): boolean {return primaryEnvironment !== null || !isHostedStaticApp();}-/** Environments that can receive a shared settings write right now. */-function useSharedSettingsSyncTargetIds(): ReadonlyArray<EnvironmentId> {- const { environments } = useEnvironments();- return useMemo(- () =>- environments- .filter(supportsSharedSettingsSync)- .map((environment) => environment.environmentId),- [environments],- );-}-/*** Returns an updater that routes each key to the correct backing store.*@@ -394,7 +383,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {serverEnvironment.updateSettings,"server settings update",);- const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds();+ const { environments } = useEnvironments();const updateSettings = useCallback((patch: UnifiedSettingsPatch) => {const { serverPatch, clientPatch } = splitPatch(patch);@@ -402,11 +391,11 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {if (Object.keys(serverPatch).length > 0) {const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);// Dropping the write silently leaves the control looking saved.- const warnUnsaved = () =>+ const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>toastManager.add({type: "warning",title: "Setting not saved",- description: PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,+ description,});if (Object.keys(localPatch).length > 0) {if (environmentId) {@@ -419,26 +408,38 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {}}if (Object.keys(sharedPatch).length > 0) {- const targets = new Set(sharedSettingsSyncTargetIds);+ const targets = new Set(+ environments.filter(supportsSharedSettingsSync).map((target) => target.environmentId),+ );if (environmentId) {targets.add(environmentId);}- if (targets.size === 0) {- warnUnsaved();- }+ let wroteToTarget = false;for (const targetId of targets) {+ const target = environments.find((candidate) => candidate.environmentId === targetId);+ const targetPatch = filterSharedServerPatch(+ sharedPatch,+ target?.serverConfig?.environment.capabilities,+ );+ if (Object.keys(targetPatch).length === 0) continue;+ wroteToTarget = true;void persistServerSettings({environmentId: targetId,- input: { patch: sharedPatch },+ input: { patch: targetPatch },});}+ if (!wroteToTarget) {+ warnUnsaved(+ targets.size > 0 ? "Update older servers to save this setting." : undefined,+ );+ }}}if (Object.keys(clientPatch).length > 0) {persistClientSettingsPatch(clientPatch);}},- [environmentId, persistServerSettings, sharedSettingsSyncTargetIds],+ [environmentId, environments, persistServerSettings],);return updateSettings;@@ -453,6 +454,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {export function useSharedSettingsSync() {const primaryEnvironment = usePrimaryEnvironment();const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;+ const primaryCapabilities = primaryEnvironment?.serverConfig?.environment.capabilities;// Read the loaded config, not `primaryServerSettingsAtom`: that atom falls// back to defaults while the primary is disconnected, and "apply to all"// must never push defaults over real values. Same for a primary too old to@@ -472,28 +474,35 @@ export function useSharedSettingsSync() {findSharedSettingsMismatches({primaryEnvironmentId,primarySettings,+ primaryCapabilities,environments: environments.map((environment) => ({environmentId: environment.environmentId,label: environment.label,syncEligible: supportsSharedSettingsSync(environment),settings: environment.serverConfig?.settings ?? null,+ capabilities: environment.serverConfig?.environment.capabilities,})),}),- [environments, primaryEnvironmentId, primarySettings],+ [environments, primaryEnvironmentId, primarySettings, primaryCapabilities],);const applyToAll = useCallback(() => {if (primarySettings === null) {return;}- const patch = pickSharedServerSettings(primarySettings);+ const patch = pickSharedServerSettings(primarySettings, primaryCapabilities);for (const mismatch of mismatches) {+ const target = environments.find(+ (candidate) => candidate.environmentId === mismatch.environmentId,+ );void persistServerSettings({environmentId: mismatch.environmentId,- input: { patch },+ input: {+ patch: filterSharedServerPatch(patch, target?.serverConfig?.environment.capabilities),+ },});}- }, [mismatches, persistServerSettings, primarySettings]);+ }, [environments, mismatches, persistServerSettings, primarySettings, primaryCapabilities]);return { mismatches, applyToAll };}diff --git a/docs/user/updating.md b/docs/user/updating.mdindex 14500cbe462..d72df7382f5 100644--- a/docs/user/updating.md+++ b/docs/user/updating.md@@ -11,12 +11,15 @@ Server updates restart the connection and can interrupt active agents andterminal commands. Saved threads, settings, and project files remain.**Settings → General → Continue threads after restarts** is off by default.-Enable it for each environment to resume supported active threads after an-update, crash, or machine restart. T3 Code must start again on that machine;+Enable it to resume supported active threads after an update, crash, or machine+restart. Changes are saved to connected environments that support this setting;+update older servers first. If a supported environment was offline or has a+different value, use **Apply to all** in Settings after it connects.+T3 Code must start again on that machine;the setting does not enable automatic startup. Terminal commands may still beinterrupted, and threads without saved provider resume state need a new message.-If you previously enabled continuation for updates, enable this environment-setting once to allow recovery without a connected client.+If you previously enabled continuation for updates, enable this setting once+to allow recovery without a connected client.## Update a connected serverdiff --git a/packages/client-runtime/src/state/sharedSettings.test.ts b/packages/client-runtime/src/state/sharedSettings.test.tsindex 8c46a9f3357..8cf0e3bc7f0 100644--- a/packages/client-runtime/src/state/sharedSettings.test.ts+++ b/packages/client-runtime/src/state/sharedSettings.test.ts@@ -2,6 +2,7 @@ import { DEFAULT_SERVER_SETTINGS, EnvironmentId } from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import {+ filterSharedServerPatch,findSharedSettingsMismatches,pickSharedServerSettings,splitSharedServerPatch,@@ -11,6 +12,7 @@ import {const primaryId = EnvironmentId.make("env-primary");const laptopId = EnvironmentId.make("env-laptop");const boxId = EnvironmentId.make("env-box");+const restartCapabilities = { threadRestartContinuation: true };describe("supportsSharedSettingsSync", () => {it("accepts only connected servers that advertise the shared-settings capability", () => {@@ -40,16 +42,24 @@ describe("splitSharedServerPatch", () => {const { sharedPatch, localPatch } = splitSharedServerPatch({sidebarAutoSettleAfterDays: 7,sidebarAutoSettleOnMerge: false,+ continueThreadsAfterServerUpdate: true,enableAgentBrowserAccess: false,});- expect(sharedPatch).toEqual({ sidebarAutoSettleAfterDays: 7, sidebarAutoSettleOnMerge: false });+ expect(sharedPatch).toEqual({+ sidebarAutoSettleAfterDays: 7,+ sidebarAutoSettleOnMerge: false,+ continueThreadsAfterServerUpdate: true,+ });expect(localPatch).toEqual({ enableAgentBrowserAccess: false });});});describe("pickSharedServerSettings", () => {it("returns only the shared keys", () => {- expect(Object.keys(pickSharedServerSettings(DEFAULT_SERVER_SETTINGS)).sort()).toEqual([+ expect(+ Object.keys(pickSharedServerSettings(DEFAULT_SERVER_SETTINGS, restartCapabilities)).sort(),+ ).toEqual([+ "continueThreadsAfterServerUpdate","defaultThreadEnvMode","newWorktreesStartFromOrigin","sidebarAutoSettleAfterDays",@@ -59,9 +69,106 @@ describe("pickSharedServerSettings", () => {});});+describe("filterSharedServerPatch", () => {+ it.each([true, false])("preserves supported restart preference %s", (enabled) => {+ const patch = { continueThreadsAfterServerUpdate: enabled, sidebarAutoSettleAfterDays: 7 };+ expect(filterSharedServerPatch(patch, restartCapabilities)).toEqual(patch);+ });++ it.each([undefined, {}, { threadRestartContinuation: false }])(+ "omits only the unsupported restart preference with capabilities %j",+ (capabilities) => {+ expect(+ filterSharedServerPatch(+ { continueThreadsAfterServerUpdate: true, sidebarAutoSettleAfterDays: 7 },+ capabilities,+ ),+ ).toEqual({ sidebarAutoSettleAfterDays: 7 });+ expect(pickSharedServerSettings(DEFAULT_SERVER_SETTINGS, capabilities)).not.toHaveProperty(+ "continueThreadsAfterServerUpdate",+ );+ },+ );+});+describe("findSharedSettingsMismatches", () => {const primarySettings = { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 7 };+ it.each([true, false])(+ "detects remote restart continuation drift when the preference is %s",+ (enabled) => {+ const settings = { ...primarySettings, continueThreadsAfterServerUpdate: enabled };+ const remoteSettings = { ...settings, continueThreadsAfterServerUpdate: !enabled };+ const environment = {+ environmentId: boxId,+ label: "Remote Box",+ syncEligible: true,+ settings: remoteSettings,+ capabilities: restartCapabilities,+ };+ expect(+ findSharedSettingsMismatches({+ primaryEnvironmentId: primaryId,+ primarySettings: settings,+ primaryCapabilities: restartCapabilities,+ environments: [environment],+ }),+ ).toEqual([{ environmentId: boxId, label: "Remote Box" }]);+ expect(+ findSharedSettingsMismatches({+ primaryEnvironmentId: primaryId,+ primarySettings: settings,+ primaryCapabilities: restartCapabilities,+ environments: [+ {+ ...environment,+ settings: Object.assign(+ {},+ remoteSettings,+ pickSharedServerSettings(settings, restartCapabilities),+ ),+ },+ ],+ }),+ ).toEqual([]);+ },+ );++ it.each([+ [undefined, restartCapabilities],+ [restartCapabilities, undefined],+ [undefined, undefined],+ ])(+ "ignores restart drift unless both servers support it (%j, %j)",+ (primaryCapabilities, capabilities) => {+ const environment = {+ environmentId: boxId,+ label: "Remote Box",+ syncEligible: true,+ capabilities,+ settings: { ...primarySettings, continueThreadsAfterServerUpdate: true },+ };+ const input = {+ primaryEnvironmentId: primaryId,+ primarySettings,+ primaryCapabilities,+ environments: [environment],+ };+ expect(findSharedSettingsMismatches(input)).toEqual([]);+ expect(+ findSharedSettingsMismatches({+ ...input,+ environments: [+ {+ ...environment,+ settings: { ...environment.settings, sidebarAutoSettleAfterDays: 14 },+ },+ ],+ }),+ ).toEqual([{ environmentId: boxId, label: "Remote Box" }]);+ },+ );+it("lists sync-eligible environments whose shared settings differ", () => {const mismatches = findSharedSettingsMismatches({primaryEnvironmentId: primaryId,diff --git a/packages/client-runtime/src/state/sharedSettings.ts b/packages/client-runtime/src/state/sharedSettings.tsindex f3236ef2035..c578de9c706 100644--- a/packages/client-runtime/src/state/sharedSettings.ts+++ b/packages/client-runtime/src/state/sharedSettings.ts@@ -21,6 +21,7 @@ import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";/** Server keys that hold a user preference rather than machine config. */export const SHARED_SERVER_SETTING_KEYS = [+ "continueThreadsAfterServerUpdate","sidebarAutoSettleAfterDays","sidebarAutoSettleOnMerge","defaultThreadEnvMode",@@ -52,15 +53,27 @@ export function splitSharedServerPatch(patch: ServerSettingsPatch): {};}-/** The shared subset of one environment's settings, as a patch that can be written elsewhere. */-export function pickSharedServerSettings(settings: ServerSettings): ServerSettingsPatch {- return Struct.pick(settings, SHARED_SERVER_SETTING_KEYS);+/** Omit restart recovery on servers that cannot persist its preference. */+export function filterSharedServerPatch(+ patch: ServerSettingsPatch,+ capabilities: Pick<ExecutionEnvironmentCapabilities, "threadRestartContinuation"> | undefined,+): ServerSettingsPatch {+ return capabilities?.threadRestartContinuation === true+ ? patch+ : Struct.omit(patch, ["continueThreadsAfterServerUpdate"]);+}++/** The shared subset supported by one environment. */+export function pickSharedServerSettings(+ settings: ServerSettings,+ capabilities?: Pick<ExecutionEnvironmentCapabilities, "threadRestartContinuation">,+): ServerSettingsPatch {+ return filterSharedServerPatch(Struct.pick(settings, SHARED_SERVER_SETTING_KEYS), capabilities);}/*** Whether an environment can participate in shared-settings sync right now.- * Auto-settlement is the newest feature backed by a shared key, so a server- * advertising `threadAutoSettlement` can hold every shared key.+ * Auto-settlement establishes baseline support; newer preferences are filtered separately.*/export function supportsSharedSettingsSync(environment: {readonly connection: { readonly phase: EnvironmentConnectionPhase };@@ -81,12 +94,15 @@ export interface SharedSettingsEnvironment {readonly label: string;readonly syncEligible: boolean;readonly settings: ServerSettings | null;+ readonly capabilities?:+ | Pick<ExecutionEnvironmentCapabilities, "threadRestartContinuation">+ | undefined;}/*** Shared-settings sync targets whose values differ from the primary* environment's. Other environments are skipped: nothing can be read from or- * written to them, or their server cannot hold every shared key. With no+ * written to them, or their server lacks baseline shared-settings support. With no* primary settings loaded there is nothing to compare against, so nothing is* reported. Callers must pass the real loaded settings, never a default* fallback, or "apply to all" would push defaults over real values.@@ -94,12 +110,18 @@ export interface SharedSettingsEnvironment {export function findSharedSettingsMismatches(input: {readonly primaryEnvironmentId: EnvironmentId | null;readonly primarySettings: ServerSettings | null;+ readonly primaryCapabilities?:+ | Pick<ExecutionEnvironmentCapabilities, "threadRestartContinuation">+ | undefined;readonly environments: ReadonlyArray<SharedSettingsEnvironment>;}): ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }> {if (input.primaryEnvironmentId === null || input.primarySettings === null) {return [];}- const expected = pickSharedServerSettings(input.primarySettings);+ const primarySettings = pickSharedServerSettings(+ input.primarySettings,+ input.primaryCapabilities,+ );return input.environments.flatMap((environment) => {if (environment.environmentId === input.primaryEnvironmentId ||@@ -108,7 +130,11 @@ export function findSharedSettingsMismatches(input: {) {return [];}- const actual = pickSharedServerSettings(environment.settings);+ const expected = filterSharedServerPatch(primarySettings, environment.capabilities);+ const actual = filterSharedServerPatch(+ pickSharedServerSettings(environment.settings, environment.capabilities),+ input.primaryCapabilities,+ );return Equal.equals(actual, expected)? []: [{ environmentId: environment.environmentId, label: environment.label }];diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 38347ebc92b..6edcff005d8 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -94,6 +94,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({threadSettlement: Schema.optionalKey(Schema.Boolean),/** Server evaluates merge and inactivity settlement without a client. */threadAutoSettlement: Schema.optionalKey(Schema.Boolean),+ /** Server persists the opt-in for continuing interrupted threads after restarts. */+ threadRestartContinuation: Schema.optionalKey(Schema.Boolean),/** Server understands thread.snooze / thread.unsnooze commands. Sameversion-skew contract as threadSettlement. */threadSnooze: Schema.optionalKey(Schema.Boolean),