Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(settings): preserve self-hosted language models on restart (#2790)

Jrjy37f9409e0d1eb
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index 261c94924..942f05a97 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -25,15 +25,11 @@ import {
type InferenceScope,
type InferenceScopeDefinition,
} from "../../config/inferenceScopes";
-import {
- isProviderValidForMode,
- getCloudModel,
- getLocalModel,
- enterpriseProviderName,
-} from "../../models/ModelRegistry";
+import { getCloudModel, getLocalModel, enterpriseProviderName } from "../../models/ModelRegistry";
import { AUTO_REASONING_EFFORT, isReasoningEffortSupported } from "../../models/reasoningEffort";
import { selectableReasoningEffort } from "../../services/ai/chatRequestBody";
import { useManagedScopeResolution } from "../../stores/enterpriseIdentityStore";
+import { modeSwitchPatch } from "../../utils/llmModeSwitch";
import { requestSignIn } from "../../utils/requestSignIn";
import TestConnectionButton from "../TestConnectionButton";
import { getEnterpriseCallSettings } from "../../services/ai/enterpriseSettings";
@@ -147,18 +143,13 @@ export default function InferenceConfigEditor({
}
if (mode === effectiveMode) return;
- const patch: Parameters<typeof setResolvedLLMConfig>[1] = {
- mode,
- cloudMode: mode === "openwhispr" ? "openwhispr" : "byok",
- };
- if (!isProviderValidForMode(config.provider, mode)) {
- patch.provider = "";
- patch.model = "";
- }
- setResolvedLLMConfig(scope, patch);
+ setResolvedLLMConfig(
+ scope,
+ modeSwitchPatch({ provider: config.provider, model: config.model }, mode)
+ );
onModeChange?.(mode);
},
- [scope, config.provider, effectiveMode, isSignedIn, onModeChange, isModeAllowed]
+ [scope, config.provider, config.model, effectiveMode, isSignedIn, onModeChange, isModeAllowed]
);
const setMode = setField("mode");
diff --git a/src/config/inferenceScopes.ts b/src/config/inferenceScopes.ts
index fdd64af3f..b4a9ad5c7 100644
--- a/src/config/inferenceScopes.ts
+++ b/src/config/inferenceScopes.ts
@@ -125,3 +125,12 @@ export const INFERENCE_SCOPES = {
} as const satisfies Record<string, InferenceScopeDefinition>;
export type InferenceScope = keyof typeof INFERENCE_SCOPES;
+
+/**
+ * Whether a scope in this mode runs its provider/model pair against a cloud
+ * catalog. Self-hosted, local and enterprise modes share the model key but can
+ * keep an old cloud provider, so catalog repairs must leave them alone.
+ */
+export function usesCloudModelCatalog(mode: unknown): boolean {
+ return mode === "providers" || mode === "openwhispr";
+}
diff --git a/src/models/tinfoilModels.ts b/src/models/tinfoilModels.ts
index ef736ade9..fe3f630e3 100644
--- a/src/models/tinfoilModels.ts
+++ b/src/models/tinfoilModels.ts
@@ -10,7 +10,7 @@ import {
readCachedTinfoilModels,
writeCachedTinfoilModels,
} from "./tinfoilModelCache";
-import { INFERENCE_SCOPES } from "../config/inferenceScopes";
+import { INFERENCE_SCOPES, usesCloudModelCatalog } from "../config/inferenceScopes";
import { getSettings, setStringSetting } from "../stores/settingsStore";
import { recordTinfoilModelSwitch } from "../stores/tinfoilModelSwitchStore";
@@ -67,7 +67,8 @@ function reconcileSelectedModels(
const announced = new Set<string>();
for (const scope of Object.values(INFERENCE_SCOPES)) {
- const { provider, model } = scope.storeKeys;
+ const { mode, provider, model } = scope.storeKeys;
+ if (!usesCloudModelCatalog(settings[mode])) continue;
if (settings[provider] !== "tinfoil") continue;
const selected = settings[model];
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index dec4a3994..c2d758241 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -28,6 +28,7 @@ import {
type InferenceScope,
type InferenceScopeDefinition,
type InferenceScopeStoreKeys,
+ usesCloudModelCatalog,
} from "../config/inferenceScopes";
import { normalizeChineseScriptPreference } from "../utils/chineseScript";
import { adjustBedrockModelForRegion } from "../utils/bedrockRegions";
@@ -149,7 +150,7 @@ function canonicalTranscriptionBaseUrl(providerId: string): string | null {
);
}
-function reasoningModelBelongsToProvider(providerId: string, modelId: string): boolean {
+export function reasoningModelBelongsToProvider(providerId: string, modelId: string): boolean {
if (!modelId) return false;
// Custom and OpenRouter ids are free-form; any remembered id is valid.
// Tinfoil's registry entry is refreshed in place from its live catalog.
@@ -853,7 +854,13 @@ function migrateRetiredCloudModels() {
if (!isBrowser) return;
const swept = sweepRetiredCloudModelSelections(
localStorage,
- Object.values(INFERENCE_SCOPES).map(({ storeKeys }) => storeKeys)
+ Object.values(INFERENCE_SCOPES)
+ .map(({ storeKeys }) => storeKeys)
+ .filter(({ mode }) => {
+ const storedMode = localStorage.getItem(mode);
+ // An unset mode loads as the default, openwhispr.
+ return !storedMode || usesCloudModelCatalog(storedMode);
+ })
);
if (swept.length === 0) return;
@@ -3229,6 +3236,7 @@ export async function reconcileLocalModelSelections(): Promise<void> {
export function reconcileRetiredCloudModelSelections(): void {
const state = useSettingsStore.getState() as unknown as Record<string, unknown>;
for (const scope of Object.values(INFERENCE_SCOPES)) {
+ if (!usesCloudModelCatalog(state[scope.storeKeys.mode])) continue;
const provider = state[scope.storeKeys.provider] as string;
const model = state[scope.storeKeys.model] as string;
if (!provider || !model || provider === "tinfoil") continue;
diff --git a/src/utils/llmModeSwitch.ts b/src/utils/llmModeSwitch.ts
new file mode 100644
index 000000000..46f6b29e3
--- /dev/null
+++ b/src/utils/llmModeSwitch.ts
@@ -0,0 +1,28 @@
+import { reasoningModelBelongsToProvider, type ResolvedLLMConfig } from "../stores/settingsStore";
+import { isProviderValidForMode } from "../models/ModelRegistry";
+import type { InferenceMode } from "../types/electron";
+
+type LLMConfigPatch = Partial<Omit<ResolvedLLMConfig, "scope">>;
+
+// Every mode shares the scope's provider and model, so a switch clears what the
+// new mode can't use. In Providers that includes a model the kept provider
+// doesn't serve, such as a self-hosted model id left under Groq.
+export function modeSwitchPatch(
+ current: Pick<ResolvedLLMConfig, "provider" | "model">,
+ mode: InferenceMode
+): LLMConfigPatch {
+ const patch: LLMConfigPatch = {
+ mode,
+ cloudMode: mode === "openwhispr" ? "openwhispr" : "byok",
+ };
+ if (!isProviderValidForMode(current.provider, mode)) {
+ patch.provider = "";
+ patch.model = "";
+ } else if (
+ mode === "providers" &&
+ !reasoningModelBelongsToProvider(current.provider, current.model)
+ ) {
+ patch.model = "";
+ }
+ return patch;
+}
diff --git a/test/helpers/selfHostedModelPersistence.test.js b/test/helpers/selfHostedModelPersistence.test.js
new file mode 100644
index 000000000..7718809ed
--- /dev/null
+++ b/test/helpers/selfHostedModelPersistence.test.js
@@ -0,0 +1,165 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const MODES = ["self-hosted", "local", "enterprise", "providers", "openwhispr"];
+const CLOUD_MODES = new Set(["providers", "openwhispr"]);
+
+test("cloud model reconciliation respects each scope's active mode", async (t) => {
+ const { storage, window } = installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-self-hosted-model-persistence-test-",
+ });
+ const { INFERENCE_SCOPES } = await vite.ssrLoadModule("/config/inferenceScopes.ts");
+ // The optional vision override only supports cloud modes.
+ const scopes = Object.values(INFERENCE_SCOPES).filter((scope) => !scope.optional);
+
+ // Saves every scope in `mode` with a model `provider` no longer serves, then
+ // reloads the settings store, as a new renderer does on app restart.
+ async function restartWith({ mode, provider, model, skipStartupMigration }) {
+ storage.clear();
+ storage.setItem("_llmScopeKeysMigrated", "1");
+ if (skipStartupMigration) {
+ storage.setItem("_retiredGroqModelsMigrated", "1");
+ storage.setItem("_retiredTinfoilModelsMigrated2", "1");
+ }
+ for (const { storeKeys } of scopes) {
+ storage.setItem(storeKeys.mode, mode);
+ storage.setItem(storeKeys.provider, provider);
+ storage.setItem(storeKeys.model, model);
+ }
+ vite.moduleGraph.invalidateAll();
+ return vite.ssrLoadModule("/stores/settingsStore.ts");
+ }
+
+ function assertModels(useSettingsStore, expected) {
+ for (const { storeKeys } of scopes) {
+ assert.equal(useSettingsStore.getState()[storeKeys.model], expected, storeKeys.model);
+ assert.equal(storage.getItem(storeKeys.model), expected, `${storeKeys.model} in storage`);
+ }
+ }
+
+ async function tinfoilNoticeCount() {
+ const { consumeTinfoilModelSwitches } = await vite.ssrLoadModule(
+ "/stores/tinfoilModelSwitchStore.ts"
+ );
+ return consumeTinfoilModelSwitches().length;
+ }
+
+ for (const mode of MODES) {
+ const cloud = CLOUD_MODES.has(mode);
+
+ await t.test(`startup migration in ${mode} mode`, async () => {
+ const { useSettingsStore } = await restartWith({
+ mode,
+ provider: "tinfoil",
+ model: "glm-5-2",
+ });
+ assertModels(useSettingsStore, cloud ? "glm-5-3" : "glm-5-2");
+ assert.equal(await tinfoilNoticeCount(), cloud ? 1 : 0);
+ });
+
+ await t.test(`startup reconciliation in ${mode} mode`, async () => {
+ const { useSettingsStore, reconcileRetiredCloudModelSelections } = await restartWith({
+ mode,
+ provider: "groq",
+ model: "my-hosted-model",
+ skipStartupMigration: true,
+ });
+ reconcileRetiredCloudModelSelections();
+ assertModels(useSettingsStore, cloud ? "openai/gpt-oss-120b" : "my-hosted-model");
+ assert.equal(await tinfoilNoticeCount(), 0);
+ });
+
+ await t.test(`live Tinfoil catalog in ${mode} mode`, async () => {
+ const { useSettingsStore } = await restartWith({
+ mode,
+ provider: "tinfoil",
+ model: "glm-5-2",
+ skipStartupMigration: true,
+ });
+ window.electronAPI.getTinfoilChatModels = async () => [
+ { id: "glm-5-3", name: "GLM-5.3", description: "", supportsThinking: true },
+ ];
+ const { refreshTinfoilModels } = await vite.ssrLoadModule("/models/tinfoilModels.ts");
+ await refreshTinfoilModels();
+ assertModels(useSettingsStore, cloud ? "glm-5-3" : "glm-5-2");
+ assert.equal(await tinfoilNoticeCount(), cloud ? 1 : 0);
+ });
+ }
+});
+
+// The reported path: Chat's provider key was never written, so it loads as the
+// default Groq, and the app's own startup runs the repairs (#2789).
+test("a Self-Hosted Chat model survives the app's startup with the default provider", async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: { electronAPI: { getOpenAIKey: async () => "", setDictionary: async () => {} } },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-self-hosted-model-startup-test-",
+ });
+
+ for (const [mode, expected] of [
+ ["self-hosted", "my-hosted-model"],
+ ["providers", "openai/gpt-oss-120b"],
+ ]) {
+ storage.clear();
+ storage.setItem("_llmScopeKeysMigrated", "1");
+ // Already holds the agent name, so startup starts no cloud dictionary sync.
+ storage.setItem("customDictionary", '["OpenWhispr"]');
+ storage.setItem("chatAgentMode", mode);
+ storage.setItem("chatAgentModel", "my-hosted-model");
+ vite.moduleGraph.invalidateAll();
+ const { initializeSettings, useSettingsStore } = await vite.ssrLoadModule(
+ "/stores/settingsStore.ts"
+ );
+ try {
+ await initializeSettings();
+ } finally {
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ await i18n.changeLanguage("en");
+ }
+
+ const state = useSettingsStore.getState();
+ assert.equal(state.chatAgentProvider, "groq", mode);
+ assert.equal(state.chatAgentModel, expected, mode);
+ assert.equal(storage.getItem("chatAgentModel"), expected, `${mode} in storage`);
+ }
+});
+
+test("switching modes clears a model the new mode's provider doesn't serve", async (t) => {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-mode-switch-patch-test-",
+ });
+ const { modeSwitchPatch } = await vite.ssrLoadModule("/utils/llmModeSwitch.ts");
+ const selfHostedUnderGroq = { provider: "groq", model: "my-hosted-model" };
+
+ assert.deepEqual(modeSwitchPatch(selfHostedUnderGroq, "providers"), {
+ mode: "providers",
+ cloudMode: "byok",
+ model: "",
+ });
+ assert.deepEqual(
+ modeSwitchPatch({ provider: "groq", model: "openai/gpt-oss-120b" }, "providers"),
+ { mode: "providers", cloudMode: "byok" }
+ );
+ assert.deepEqual(modeSwitchPatch({ provider: "custom", model: "my-hosted-model" }, "providers"), {
+ mode: "providers",
+ cloudMode: "byok",
+ });
+ assert.deepEqual(modeSwitchPatch(selfHostedUnderGroq, "openwhispr"), {
+ mode: "openwhispr",
+ cloudMode: "openwhispr",
+ });
+ assert.deepEqual(modeSwitchPatch(selfHostedUnderGroq, "local"), {
+ mode: "local",
+ cloudMode: "byok",
+ provider: "",
+ model: "",
+ });
+ assert.deepEqual(
+ modeSwitchPatch({ provider: "groq", model: "openai/gpt-oss-120b" }, "self-hosted"),
+ { mode: "self-hosted", cloudMode: "byok" }
+ );
+});