Skip to content
TypeScript

fix(web,mobile): stop the model preferences migration from looping on older servers (#18581)

F4llenb34501a466d9
diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
index 3d3c471cb9e..c8e10580e93 100644
--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
@@ -66,6 +66,8 @@ import {
import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { ChatGptSharingStatus } from "./ChatGptSharingStatus";
+import { environmentCatalog } from "../../connection/catalog";
+import { useEnvironmentQuery } from "../../state/query";
import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -124,6 +126,8 @@ const EMPTY_MODEL_FAVORITES: ReadonlyArray<{
readonly model: string;
}> = [];
const FAVORITES_PROVIDER_FILTER = "@favorites";
+// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
+const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
function ProviderHeader(props: {
readonly driver: string | undefined;
readonly iconUrl: string | undefined;
@@ -336,6 +340,10 @@ function ThreadSettingsSessionProvider(
const configs = useAtomValue(environmentServerConfigsAtom);
const config = props.environmentId ? configs.get(props.environmentId) : undefined;
const settings = config?.settings;
+ const connection = useEnvironmentQuery(
+ props.environmentId ? environmentCatalog.stateAtom(props.environmentId) : null,
+ ).data;
+ const connectionGeneration = connection?.phase === "connected" ? connection.generation : null;
const [manageHidden, setManageHidden] = useState(false);
const pendingHidden = useRef(new Set<string>());
const pendingFavorites = useRef(
@@ -364,10 +372,26 @@ function ThreadSettingsSessionProvider(
}).favorites;
const saveSettings = useAtomCommand(serverEnvironment.updateSettings, "model favorites update");
useEffect(() => {
- if (!props.environmentId || !settings || !AsyncResult.isSuccess(preferences)) return;
+ if (
+ !props.environmentId ||
+ !settings ||
+ !AsyncResult.isSuccess(preferences) ||
+ connectionGeneration === null ||
+ attemptedMigrationGenerations.get(props.environmentId) === connectionGeneration
+ )
+ return;
const patch = modelPreferencesMigrationPatch(settings, { favorites: legacyFavorites });
- if (patch) void saveSettings({ environmentId: props.environmentId, input: { patch } });
- }, [legacyFavorites, preferences, props.environmentId, saveSettings, settings]);
+ if (!patch) return;
+ attemptedMigrationGenerations.set(props.environmentId, connectionGeneration);
+ void saveSettings({ environmentId: props.environmentId, input: { patch } });
+ }, [
+ connectionGeneration,
+ legacyFavorites,
+ preferences,
+ props.environmentId,
+ saveSettings,
+ settings,
+ ]);
const favoriteKeys = new Set(
modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
);
diff --git a/apps/web/src/hooks/useSettings.favorites.browser.test.tsx b/apps/web/src/hooks/useSettings.favorites.browser.test.tsx
index 90c5cac5fca..fa9298d2ac1 100644
--- a/apps/web/src/hooks/useSettings.favorites.browser.test.tsx
+++ b/apps/web/src/hooks/useSettings.favorites.browser.test.tsx
@@ -6,6 +6,10 @@ import {
type ServerSettings,
type ServerSettingsPatch,
} from "@t3tools/contracts";
+import {
+ AVAILABLE_CONNECTION_STATE,
+ type SupervisorConnectionState,
+} from "@t3tools/client-runtime/connection";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
@@ -15,9 +19,31 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
const state = vi.hoisted(() => ({
settings: new Map<string, unknown>(),
+ connections: new Map<
+ EnvironmentId,
+ Atom.Writable<AsyncResult.AsyncResult<SupervisorConnectionState>>
+ >(),
persist: vi.fn(),
}));
+vi.mock(import("~/connection/catalog"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ environmentCatalog: {
+ ...actual.environmentCatalog,
+ stateAtom: ((id: EnvironmentId) => state.connections.get(id)) as never,
+ },
+ };
+});
+vi.mock("~/localApi", () => ({
+ ensureLocalApi: () => ({
+ persistence: {
+ getClientSettings: async () => ({ favorites: [{ provider, model }] }),
+ },
+ }),
+}));
+
vi.mock(import("~/state/server"), async (original) => {
const actual = await original();
return {
@@ -33,7 +59,7 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({
useAtomCommand: (() => state.persist) as never,
}));
-import { useToggleEnvironmentModelFavorite } from "./useSettings";
+import { useEnvironmentModelPreferences, useToggleEnvironmentModelFavorite } from "./useSettings";
const primaryId = EnvironmentId.make("primary");
const remoteId = EnvironmentId.make("remote");
@@ -85,6 +111,7 @@ beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
registry = AtomRegistry.make();
state.settings.clear();
+ state.connections.clear();
durable = new Map();
toggles = [];
writes = [];
@@ -260,3 +287,108 @@ describe("environment favorite toggles", () => {
expect(durable.get(primaryId)!.favorites).toEqual([]);
});
});
+
+function ModelPreferencesReader({ environmentId }: { environmentId: EnvironmentId }) {
+ useEnvironmentModelPreferences(environmentId);
+ return null;
+}
+
+describe("legacy model preferences migration", () => {
+ it.each(["succeeds", "fails"] as const)(
+ "waits for connection and retries only after reconnect when the first save %s",
+ async (outcome) => {
+ const environmentId = EnvironmentId.make(`migration-${outcome}`);
+ const otherId = EnvironmentId.make(`other-${outcome}`);
+ for (const id of [environmentId, otherId]) {
+ state.settings.set(
+ id,
+ Atom.keepAlive(Atom.make<ServerSettings | null>(DEFAULT_SERVER_SETTINGS)),
+ );
+ state.connections.set(
+ id,
+ Atom.keepAlive(
+ Atom.make<AsyncResult.AsyncResult<SupervisorConnectionState>>(
+ AsyncResult.success(AVAILABLE_CONNECTION_STATE),
+ ),
+ ),
+ );
+ }
+ let finishFirstSave = () => {};
+ const firstSave = new Promise((resolve) => {
+ finishFirstSave = () =>
+ resolve(
+ outcome === "succeeds"
+ ? AsyncResult.success(DEFAULT_SERVER_SETTINGS)
+ : AsyncResult.failure(Cause.fail(new Error("save failed"))),
+ );
+ });
+ state.persist
+ .mockReturnValueOnce(firstSave)
+ .mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
+ const renderReader = (id = environmentId) =>
+ act(() =>
+ root.render(
+ <RegistryContext.Provider value={registry}>
+ <ModelPreferencesReader key={id} environmentId={id} />
+ </RegistryContext.Provider>,
+ ),
+ );
+ const connect = (id: EnvironmentId, generation: number) =>
+ act(() =>
+ registry.set(
+ state.connections.get(id)!,
+ AsyncResult.success({
+ ...AVAILABLE_CONNECTION_STATE,
+ desired: true,
+ generation,
+ phase: "connected",
+ }),
+ ),
+ );
+ const pushSettings = (id = environmentId) =>
+ act(() => registry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS }));
+ const migration = (id: EnvironmentId) => ({
+ environmentId: id,
+ input: { patch: { migrateModelPreferences: { favorites: [{ provider, model }] } } },
+ });
+
+ await renderReader();
+ await pushSettings();
+ expect(state.persist).not.toHaveBeenCalled();
+
+ await connect(environmentId, 1);
+ expect(state.persist).toHaveBeenCalledExactlyOnceWith(migration(environmentId));
+ await pushSettings();
+ expect(state.persist).toHaveBeenCalledTimes(1);
+ await act(finishFirstSave);
+ await pushSettings();
+ await pushSettings();
+ expect(state.persist).toHaveBeenCalledTimes(1);
+
+ await connect(otherId, 7);
+ await pushSettings(otherId);
+ expect(state.persist).toHaveBeenCalledTimes(1);
+ await renderReader(otherId);
+ expect(state.persist).toHaveBeenLastCalledWith(migration(otherId));
+ await renderReader();
+ await pushSettings();
+ expect(state.persist).toHaveBeenCalledTimes(2);
+
+ await act(() =>
+ registry.set(
+ state.connections.get(environmentId)!,
+ AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }),
+ ),
+ );
+ await pushSettings();
+ expect(state.persist).toHaveBeenCalledTimes(2);
+ await connect(environmentId, 2);
+ await pushSettings();
+ expect(state.persist.mock.calls).toEqual([
+ [migration(environmentId)],
+ [migration(otherId)],
+ [migration(environmentId)],
+ ]);
+ },
+ );
+});
diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts
index 985a06d1acc..9ea16d4ec7e 100644
--- a/apps/web/src/hooks/useSettings.ts
+++ b/apps/web/src/hooks/useSettings.ts
@@ -47,6 +47,7 @@ import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/reactivity";
import { toastManager } from "~/components/ui/toast";
import { isHostedStaticApp } from "~/hostedPairing";
+import { environmentCatalog } from "~/connection/catalog";
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
@@ -324,7 +325,18 @@ export function mergeEnvironmentSettings(
};
}
-const pendingModelPreferencesMigrations = new Set<EnvironmentId>();
+// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
+const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
+const connectionGenerationAtom = Atom.family((environmentId: EnvironmentId | null) =>
+ Atom.make((get) =>
+ environmentId === null
+ ? null
+ : Option.match(AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), {
+ onNone: () => null,
+ onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),
+ }),
+ ),
+);
const selectLegacyModelPreferences = (settings: ClientSettings) => ({
favorites: settings.favorites,
@@ -337,22 +349,22 @@ export function useMigrateModelPreferences(
) {
const clientSettings = useClientSettings(selectLegacyModelPreferences);
const hydrated = useClientSettingsHydrated();
+ const connectionGeneration = useAtomValue(connectionGenerationAtom(environmentId));
const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
useEffect(() => {
if (
!environmentId ||
!settings ||
!hydrated ||
- pendingModelPreferencesMigrations.has(environmentId)
+ connectionGeneration === null ||
+ attemptedMigrationGenerations.get(environmentId) === connectionGeneration
)
return;
const patch = modelPreferencesMigrationPatch(settings, clientSettings);
if (!patch) return;
- pendingModelPreferencesMigrations.add(environmentId);
- void migrate({ environmentId, input: { patch } }).finally(() =>
- pendingModelPreferencesMigrations.delete(environmentId),
- );
- }, [clientSettings, environmentId, hydrated, migrate, settings]);
+ attemptedMigrationGenerations.set(environmentId, connectionGeneration);
+ void migrate({ environmentId, input: { patch } });
+ }, [clientSettings, connectionGeneration, environmentId, hydrated, migrate, settings]);
}
/** Selecting inside the client store keeps a client write from re-rendering unaffected readers. */