The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 00:30 UTC
fix(web,mobile): stop the model preferences migration from looping on older servers (#18581)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
F4llen committed
Oct 19, 2026 at 17:21 UTC
b34501a466d9e6302c41c88a69eca2770a5c5995
3 files changed
+179
-11
apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+27
-3
@@ -66,6 +66,8 @@ import {
66
import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
67
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
68
import { ChatGptSharingStatus } from "./ChatGptSharingStatus";
69
+import { environmentCatalog } from "../../connection/catalog";
70
+import { useEnvironmentQuery } from "../../state/query";
71
import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
72
import { mobilePreferencesAtom } from "../../state/preferences";
73
import { useAtomCommand } from "../../state/use-atom-command";
@@ -124,6 +126,8 @@ const EMPTY_MODEL_FAVORITES: ReadonlyArray<{
126
readonly model: string;
127
}> = [];
128
const FAVORITES_PROVIDER_FILTER = "@favorites";
129
+// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
130
+const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
131
function ProviderHeader(props: {
132
readonly driver: string | undefined;
133
readonly iconUrl: string | undefined;
@@ -336,6 +340,10 @@ function ThreadSettingsSessionProvider(
340
const configs = useAtomValue(environmentServerConfigsAtom);
341
const config = props.environmentId ? configs.get(props.environmentId) : undefined;
342
const settings = config?.settings;
343
+ const connection = useEnvironmentQuery(
344
+ props.environmentId ? environmentCatalog.stateAtom(props.environmentId) : null,
345
+ ).data;
346
+ const connectionGeneration = connection?.phase === "connected" ? connection.generation : null;
347
const [manageHidden, setManageHidden] = useState(false);
348
const pendingHidden = useRef(new Set<string>());
349
const pendingFavorites = useRef(
@@ -364,10 +372,26 @@ function ThreadSettingsSessionProvider(
372
}).favorites;
373
const saveSettings = useAtomCommand(serverEnvironment.updateSettings, "model favorites update");
374
useEffect(() => {
367
- if (!props.environmentId || !settings || !AsyncResult.isSuccess(preferences)) return;
375
+ if (
376
+ !props.environmentId ||
377
+ !settings ||
378
+ !AsyncResult.isSuccess(preferences) ||
379
+ connectionGeneration === null ||
380
+ attemptedMigrationGenerations.get(props.environmentId) === connectionGeneration
381
+ )
382
+ return;
383
const patch = modelPreferencesMigrationPatch(settings, { favorites: legacyFavorites });
369
- if (patch) void saveSettings({ environmentId: props.environmentId, input: { patch } });
370
- }, [legacyFavorites, preferences, props.environmentId, saveSettings, settings]);
384
+ if (!patch) return;
385
+ attemptedMigrationGenerations.set(props.environmentId, connectionGeneration);
386
+ void saveSettings({ environmentId: props.environmentId, input: { patch } });
387
+ }, [
388
+ connectionGeneration,
389
+ legacyFavorites,
390
+ preferences,
391
+ props.environmentId,
392
+ saveSettings,
393
+ settings,
394
+ ]);
395
const favoriteKeys = new Set(
396
modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
397
);
apps/web/src/hooks/useSettings.favorites.browser.test.tsx
+133
-1
@@ -6,6 +6,10 @@ import {
6
type ServerSettings,
7
type ServerSettingsPatch,
8
} from "@t3tools/contracts";
9
+import {
10
+ AVAILABLE_CONNECTION_STATE,
11
+ type SupervisorConnectionState,
12
+} from "@t3tools/client-runtime/connection";
13
import * as Cause from "effect/Cause";
14
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
@@ -15,9 +19,31 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
19
20
const state = vi.hoisted(() => ({
21
settings: new Map<string, unknown>(),
22
+ connections: new Map<
23
+ EnvironmentId,
24
+ Atom.Writable<AsyncResult.AsyncResult<SupervisorConnectionState>>
25
+ >(),
26
persist: vi.fn(),
27
}));
28
29
+vi.mock(import("~/connection/catalog"), async (original) => {
30
+ const actual = await original();
31
+ return {
32
+ ...actual,
33
+ environmentCatalog: {
34
+ ...actual.environmentCatalog,
35
+ stateAtom: ((id: EnvironmentId) => state.connections.get(id)) as never,
36
+ },
37
+ };
38
+});
39
+vi.mock("~/localApi", () => ({
40
+ ensureLocalApi: () => ({
41
+ persistence: {
42
+ getClientSettings: async () => ({ favorites: [{ provider, model }] }),
43
+ },
44
+ }),
45
+}));
46
+
47
vi.mock(import("~/state/server"), async (original) => {
48
const actual = await original();
49
return {
@@ -33,7 +59,7 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({
59
useAtomCommand: (() => state.persist) as never,
60
}));
61
36
-import { useToggleEnvironmentModelFavorite } from "./useSettings";
62
+import { useEnvironmentModelPreferences, useToggleEnvironmentModelFavorite } from "./useSettings";
63
64
const primaryId = EnvironmentId.make("primary");
65
const remoteId = EnvironmentId.make("remote");
@@ -85,6 +111,7 @@ beforeEach(() => {
111
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
112
registry = AtomRegistry.make();
113
state.settings.clear();
114
+ state.connections.clear();
115
durable = new Map();
116
toggles = [];
117
writes = [];
@@ -260,3 +287,108 @@ describe("environment favorite toggles", () => {
287
expect(durable.get(primaryId)!.favorites).toEqual([]);
288
});
289
});
290
+
291
+function ModelPreferencesReader({ environmentId }: { environmentId: EnvironmentId }) {
292
+ useEnvironmentModelPreferences(environmentId);
293
+ return null;
294
+}
295
+
296
+describe("legacy model preferences migration", () => {
297
+ it.each(["succeeds", "fails"] as const)(
298
+ "waits for connection and retries only after reconnect when the first save %s",
299
+ async (outcome) => {
300
+ const environmentId = EnvironmentId.make(`migration-${outcome}`);
301
+ const otherId = EnvironmentId.make(`other-${outcome}`);
302
+ for (const id of [environmentId, otherId]) {
303
+ state.settings.set(
304
+ id,
305
+ Atom.keepAlive(Atom.make<ServerSettings | null>(DEFAULT_SERVER_SETTINGS)),
306
+ );
307
+ state.connections.set(
308
+ id,
309
+ Atom.keepAlive(
310
+ Atom.make<AsyncResult.AsyncResult<SupervisorConnectionState>>(
311
+ AsyncResult.success(AVAILABLE_CONNECTION_STATE),
312
+ ),
313
+ ),
314
+ );
315
+ }
316
+ let finishFirstSave = () => {};
317
+ const firstSave = new Promise((resolve) => {
318
+ finishFirstSave = () =>
319
+ resolve(
320
+ outcome === "succeeds"
321
+ ? AsyncResult.success(DEFAULT_SERVER_SETTINGS)
322
+ : AsyncResult.failure(Cause.fail(new Error("save failed"))),
323
+ );
324
+ });
325
+ state.persist
326
+ .mockReturnValueOnce(firstSave)
327
+ .mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
328
+ const renderReader = (id = environmentId) =>
329
+ act(() =>
330
+ root.render(
331
+ <RegistryContext.Provider value={registry}>
332
+ <ModelPreferencesReader key={id} environmentId={id} />
333
+ </RegistryContext.Provider>,
334
+ ),
335
+ );
336
+ const connect = (id: EnvironmentId, generation: number) =>
337
+ act(() =>
338
+ registry.set(
339
+ state.connections.get(id)!,
340
+ AsyncResult.success({
341
+ ...AVAILABLE_CONNECTION_STATE,
342
+ desired: true,
343
+ generation,
344
+ phase: "connected",
345
+ }),
346
+ ),
347
+ );
348
+ const pushSettings = (id = environmentId) =>
349
+ act(() => registry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS }));
350
+ const migration = (id: EnvironmentId) => ({
351
+ environmentId: id,
352
+ input: { patch: { migrateModelPreferences: { favorites: [{ provider, model }] } } },
353
+ });
354
+
355
+ await renderReader();
356
+ await pushSettings();
357
+ expect(state.persist).not.toHaveBeenCalled();
358
+
359
+ await connect(environmentId, 1);
360
+ expect(state.persist).toHaveBeenCalledExactlyOnceWith(migration(environmentId));
361
+ await pushSettings();
362
+ expect(state.persist).toHaveBeenCalledTimes(1);
363
+ await act(finishFirstSave);
364
+ await pushSettings();
365
+ await pushSettings();
366
+ expect(state.persist).toHaveBeenCalledTimes(1);
367
+
368
+ await connect(otherId, 7);
369
+ await pushSettings(otherId);
370
+ expect(state.persist).toHaveBeenCalledTimes(1);
371
+ await renderReader(otherId);
372
+ expect(state.persist).toHaveBeenLastCalledWith(migration(otherId));
373
+ await renderReader();
374
+ await pushSettings();
375
+ expect(state.persist).toHaveBeenCalledTimes(2);
376
+
377
+ await act(() =>
378
+ registry.set(
379
+ state.connections.get(environmentId)!,
380
+ AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }),
381
+ ),
382
+ );
383
+ await pushSettings();
384
+ expect(state.persist).toHaveBeenCalledTimes(2);
385
+ await connect(environmentId, 2);
386
+ await pushSettings();
387
+ expect(state.persist.mock.calls).toEqual([
388
+ [migration(environmentId)],
389
+ [migration(otherId)],
390
+ [migration(environmentId)],
391
+ ]);
392
+ },
393
+ );
394
+});
apps/web/src/hooks/useSettings.ts
+19
-7
@@ -47,6 +47,7 @@ import * as Option from "effect/Option";
47
import { AsyncResult, Atom } from "effect/reactivity";
48
import { toastManager } from "~/components/ui/toast";
49
import { isHostedStaticApp } from "~/hostedPairing";
50
+import { environmentCatalog } from "~/connection/catalog";
51
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
52
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
53
import { useAtomCommand } from "~/state/use-atom-command";
@@ -324,7 +325,18 @@ export function mergeEnvironmentSettings(
325
};
326
}
327
327
-const pendingModelPreferencesMigrations = new Set<EnvironmentId>();
328
+// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
329
+const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
330
+const connectionGenerationAtom = Atom.family((environmentId: EnvironmentId | null) =>
331
+ Atom.make((get) =>
332
+ environmentId === null
333
+ ? null
334
+ : Option.match(AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), {
335
+ onNone: () => null,
336
+ onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),
337
+ }),
338
+ ),
339
+);
340
341
const selectLegacyModelPreferences = (settings: ClientSettings) => ({
342
favorites: settings.favorites,
@@ -337,22 +349,22 @@ export function useMigrateModelPreferences(
349
) {
350
const clientSettings = useClientSettings(selectLegacyModelPreferences);
351
const hydrated = useClientSettingsHydrated();
352
+ const connectionGeneration = useAtomValue(connectionGenerationAtom(environmentId));
353
const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
354
useEffect(() => {
355
if (
356
!environmentId ||
357
!settings ||
358
!hydrated ||
346
- pendingModelPreferencesMigrations.has(environmentId)
359
+ connectionGeneration === null ||
360
+ attemptedMigrationGenerations.get(environmentId) === connectionGeneration
361
)
362
return;
363
const patch = modelPreferencesMigrationPatch(settings, clientSettings);
364
if (!patch) return;
351
- pendingModelPreferencesMigrations.add(environmentId);
352
- void migrate({ environmentId, input: { patch } }).finally(() =>
353
- pendingModelPreferencesMigrations.delete(environmentId),
354
- );
355
- }, [clientSettings, environmentId, hydrated, migrate, settings]);
365
+ attemptedMigrationGenerations.set(environmentId, connectionGeneration);
366
+ void migrate({ environmentId, input: { patch } });
367
+ }, [clientSettings, connectionGeneration, environmentId, hydrated, migrate, settings]);
368
}
369
370
/** Selecting inside the client store keeps a client write from re-rendering unaffected readers. */