Skip to content

Commit b34501a

Browse files
fix(web,mobile): stop the model preferences migration from looping on older servers (pingdotgg#18581)
Co-authored-by: Julius Marminge <[email protected]>
1 parent dcd2658 commit b34501a

3 files changed

Lines changed: 179 additions & 11 deletions

File tree

‎apps/mobile/src/features/threads/ThreadSettingsSheet.tsx‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ import {
6666
import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
6767
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
6868
import { ChatGptSharingStatus } from "./ChatGptSharingStatus";
69+
import { environmentCatalog } from "../../connection/catalog";
70+
import { useEnvironmentQuery } from "../../state/query";
6971
import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
7072
import { mobilePreferencesAtom } from "../../state/preferences";
7173
import { useAtomCommand } from "../../state/use-atom-command";
@@ -124,6 +126,8 @@ const EMPTY_MODEL_FAVORITES: ReadonlyArray<{
124126
readonly model: string;
125127
}> = [];
126128
const FAVORITES_PROVIDER_FILTER = "@favorites";
129+
// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
130+
const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
127131
function ProviderHeader(props: {
128132
readonly driver: string | undefined;
129133
readonly iconUrl: string | undefined;
@@ -336,6 +340,10 @@ function ThreadSettingsSessionProvider(
336340
const configs = useAtomValue(environmentServerConfigsAtom);
337341
const config = props.environmentId ? configs.get(props.environmentId) : undefined;
338342
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;
339347
const [manageHidden, setManageHidden] = useState(false);
340348
const pendingHidden = useRef(new Set<string>());
341349
const pendingFavorites = useRef(
@@ -364,10 +372,26 @@ function ThreadSettingsSessionProvider(
364372
}).favorites;
365373
const saveSettings = useAtomCommand(serverEnvironment.updateSettings, "model favorites update");
366374
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;
368383
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+
]);
371395
const favoriteKeys = new Set(
372396
modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
373397
);

‎apps/web/src/hooks/useSettings.favorites.browser.test.tsx‎

Lines changed: 133 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ import {
66
type ServerSettings,
77
type ServerSettingsPatch,
88
} from "@t3tools/contracts";
9+
import {
10+
AVAILABLE_CONNECTION_STATE,
11+
type SupervisorConnectionState,
12+
} from "@t3tools/client-runtime/connection";
913
import * as Cause from "effect/Cause";
1014
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
1115
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
@@ -15,9 +19,31 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
1519

1620
const state = vi.hoisted(() => ({
1721
settings: new Map<string, unknown>(),
22+
connections: new Map<
23+
EnvironmentId,
24+
Atom.Writable<AsyncResult.AsyncResult<SupervisorConnectionState>>
25+
>(),
1826
persist: vi.fn(),
1927
}));
2028

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+
2147
vi.mock(import("~/state/server"), async (original) => {
2248
const actual = await original();
2349
return {
@@ -33,7 +59,7 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({
3359
useAtomCommand: (() => state.persist) as never,
3460
}));
3561

36-
import { useToggleEnvironmentModelFavorite } from "./useSettings";
62+
import { useEnvironmentModelPreferences, useToggleEnvironmentModelFavorite } from "./useSettings";
3763

3864
const primaryId = EnvironmentId.make("primary");
3965
const remoteId = EnvironmentId.make("remote");
@@ -85,6 +111,7 @@ beforeEach(() => {
85111
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
86112
registry = AtomRegistry.make();
87113
state.settings.clear();
114+
state.connections.clear();
88115
durable = new Map();
89116
toggles = [];
90117
writes = [];
@@ -260,3 +287,108 @@ describe("environment favorite toggles", () => {
260287
expect(durable.get(primaryId)!.favorites).toEqual([]);
261288
});
262289
});
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‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import * as Option from "effect/Option";
4747
import { AsyncResult, Atom } from "effect/reactivity";
4848
import { toastManager } from "~/components/ui/toast";
4949
import { isHostedStaticApp } from "~/hostedPairing";
50+
import { environmentCatalog } from "~/connection/catalog";
5051
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
5152
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
5253
import { useAtomCommand } from "~/state/use-atom-command";
@@ -324,7 +325,18 @@ export function mergeEnvironmentSettings(
324325
};
325326
}
326327

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+
);
328340

329341
const selectLegacyModelPreferences = (settings: ClientSettings) => ({
330342
favorites: settings.favorites,
@@ -337,22 +349,22 @@ export function useMigrateModelPreferences(
337349
) {
338350
const clientSettings = useClientSettings(selectLegacyModelPreferences);
339351
const hydrated = useClientSettingsHydrated();
352+
const connectionGeneration = useAtomValue(connectionGenerationAtom(environmentId));
340353
const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
341354
useEffect(() => {
342355
if (
343356
!environmentId ||
344357
!settings ||
345358
!hydrated ||
346-
pendingModelPreferencesMigrations.has(environmentId)
359+
connectionGeneration === null ||
360+
attemptedMigrationGenerations.get(environmentId) === connectionGeneration
347361
)
348362
return;
349363
const patch = modelPreferencesMigrationPatch(settings, clientSettings);
350364
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]);
356368
}
357369

358370
/** Selecting inside the client store keeps a client write from re-rendering unaffected readers. */

0 commit comments

Comments
 (0)