Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(models): der Klick auf der Installed-Karte macht die ganze Arbeit

purpleb2b1b13d6773
diff --git a/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts b/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts
new file mode 100644
index 00000000..7ade101f
--- /dev/null
+++ b/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts
@@ -0,0 +1,161 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * A14 second review, the heavy one: a click on an LU Engine card under
+ * Installed did half the job, and the half it skipped was the point.
+ *
+ * The guard on the activation path asked "is the openai slot already ours".
+ * With Ollama in front the answer is no, so a click wrote openai::<gguf> into
+ * the store, unloaded the Ollama model to make room for a model nobody was
+ * starting, and then switched nothing and started nothing. The user was left
+ * on a model that answers from nowhere, with his Ollama model evicted, and no
+ * line on screen saying anything had happened.
+ *
+ * The Use button on Discover and the composer's picker both did the whole job
+ * already. This drives the third door, the Installed card, through the same
+ * route: hand the slot over, announce it, then start the engine.
+ *
+ * Run: npx vitest run src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+const activateBuiltinModel = vi.fn(async () => true)
+const unloadModel = vi.fn(async () => undefined)
+
+vi.mock('../../api/backend', () => ({
+ isTauri: () => true,
+ isMacOS: () => true,
+ isWindows: () => false,
+ isLinux: () => false,
+ backendCall: vi.fn(async () => null),
+ secretGet: vi.fn().mockRejectedValue(new Error('no vault')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+vi.mock('../../api/comfyui', () => ({
+ getInstalledImageModels: vi.fn(async () => []),
+ getInstalledVideoModels: vi.fn(async () => []),
+ checkComfyConnection: vi.fn(async () => false),
+ readModelDiskSizes: vi.fn(async () => new Map()),
+}))
+vi.mock('../../api/ollama', () => ({
+ listModels: vi.fn(async () => []),
+ unloadModel: (...a: unknown[]) => unloadModel(...(a as [])),
+ pullModel: vi.fn(),
+ pullModelTauri: vi.fn(),
+ deleteModel: vi.fn(),
+ showModel: vi.fn(),
+}))
+vi.mock('../../api/providers', async () => {
+ const actual = await vi.importActual<typeof import('../../api/providers')>('../../api/providers')
+ return { ...actual, getEnabledProviders: () => [] }
+})
+vi.mock('../../api/engine', async () => {
+ const actual = await vi.importActual<typeof import('../../api/engine')>('../../api/engine')
+ return {
+ ...actual,
+ listBundledModels: vi.fn(async () => []),
+ isManagedBuiltinActive: () => false,
+ bundledEngineStatus: vi.fn(async () => ({ running: true, healthy: true, port: 8127 })),
+ bundledEmbedStatus: vi.fn(async () => ({ running: true, healthy: true, port: 8128 })),
+ startBundledEmbed: vi.fn(),
+ activateBuiltinModel: (...a: unknown[]) => activateBuiltinModel(...(a as [])),
+ }
+})
+
+const { useModels } = await import('../useModels')
+const { useModelStore } = await import('../../stores/modelStore')
+const { useProviderStore } = await import('../../stores/providerStore')
+const { useLuEngineSwitchStore } = await import('../../stores/luEngineSwitchStore')
+
+const GGUF = 'openai::Qwen2.5-0.5B-Instruct-Q8_0'
+const OLLAMA = 'llama3.2:3b'
+
+/** The Installed list as David's Mac draws it: an Ollama model in front, one
+ * GGUF from the LU Engine folder beside it. */
+function installedList() {
+ return [
+ { name: OLLAMA, model: OLLAMA, size: 1, type: 'text', provider: 'ollama', providerName: 'Ollama' },
+ { name: GGUF, model: 'Qwen2.5-0.5B-Instruct-Q8_0', size: 1, type: 'text', provider: 'openai', providerName: 'LU Engine' },
+ ] as never
+}
+
+/** The click ModelManager's card makes. */
+async function clickCard(name: string) {
+ const { result } = renderHook(() => useModels())
+ await act(async () => { result.current.setActiveModel(name) })
+ return result
+}
+
+beforeEach(() => {
+ activateBuiltinModel.mockClear()
+ unloadModel.mockClear()
+ useLuEngineSwitchStore.setState({ note: null, generation: 0 })
+ useProviderStore.getState().resetProvidersToDefaults()
+ // Ollama in front, the openai slot parked, which is what onboarding leaves
+ // behind when the user picks Ollama.
+ useProviderStore.getState().setProviderConfig('ollama', { enabled: true })
+ useProviderStore.getState().setProviderConfig('openai', { enabled: false, managed: false })
+ useModelStore.setState({ models: installedList(), activeModel: OLLAMA })
+})
+
+describe('clicking an LU Engine card while Ollama holds the chat', () => {
+ it('hands the chat slot to the LU Engine', async () => {
+ await clickCard(GGUF)
+ const slot = useProviderStore.getState().providers.openai
+ expect(slot.enabled, 'the slot has to be on for anything to route there').toBe(true)
+ expect(slot.managed, 'and it has to be OUR engine in it').toBe(true)
+ expect(slot.name).toBe('LU Engine')
+ })
+
+ it('starts the engine on that GGUF', async () => {
+ await clickCard(GGUF)
+ expect(activateBuiltinModel).toHaveBeenCalledWith(GGUF)
+ })
+
+ it('says on screen that the chat backend moved', async () => {
+ await clickCard(GGUF)
+ expect(useLuEngineSwitchStore.getState().note)
+ .toBe('Switched your chat provider to the LU Engine for this model.')
+ })
+
+ it('and the model really is the active one afterwards', async () => {
+ await clickCard(GGUF)
+ expect(useModelStore.getState().activeModel).toBe(GGUF)
+ })
+
+ // NEGATIVE CONTROL: a click on the Ollama card is untouched by all of this.
+ // It must not move the slot, must not start the engine, and must not print a
+ // line about a switch that never happened.
+ it('leaves an Ollama card alone', async () => {
+ useModelStore.setState({ activeModel: GGUF })
+ await clickCard(OLLAMA)
+ expect(useProviderStore.getState().providers.openai.managed).not.toBe(true)
+ expect(activateBuiltinModel).not.toHaveBeenCalled()
+ expect(useLuEngineSwitchStore.getState().note).toBeNull()
+ })
+
+ // NEGATIVE CONTROL: with the LU Engine already in front there is no switch,
+ // so no line, but the GGUF swap still has to happen.
+ it('swaps without announcing when the engine already held the chat', async () => {
+ useProviderStore.getState().setProviderConfig('openai', { enabled: true, managed: true, name: 'LU Engine' })
+ await clickCard(GGUF)
+ expect(activateBuiltinModel).toHaveBeenCalledWith(GGUF)
+ expect(useLuEngineSwitchStore.getState().note).toBeNull()
+ })
+
+ // NEGATIVE CONTROL: an LM Studio row shares provider id 'openai' with ours.
+ // Clicking it must not hand the slot to our engine and evict LM Studio.
+ it('never mistakes an LM Studio row for one of ours', async () => {
+ const LMS = 'openai::qwen2.5-0.5b-instruct'
+ useModelStore.setState({
+ models: [{ name: LMS, model: 'qwen2.5-0.5b-instruct', size: 1, type: 'text', provider: 'openai', providerName: 'LM Studio' }] as never,
+ activeModel: null,
+ })
+ useProviderStore.getState().setProviderConfig('openai', { enabled: true, managed: false, name: 'LM Studio', baseUrl: 'http://localhost:1234/v1' })
+ await clickCard(LMS)
+ expect(useProviderStore.getState().providers.openai.name).toBe('LM Studio')
+ expect(useLuEngineSwitchStore.getState().note).toBeNull()
+ })
+})
diff --git a/src/hooks/__tests__/lu-engine-resume-routing.test.ts b/src/hooks/__tests__/lu-engine-resume-routing.test.ts
index de62103f..19bf0352 100644
--- a/src/hooks/__tests__/lu-engine-resume-routing.test.ts
+++ b/src/hooks/__tests__/lu-engine-resume-routing.test.ts
@@ -110,8 +110,9 @@ describe('the boot resume goes to the right process', () => {
describe('the once-per-session flag is raised on the attempt, not on the success', () => {
it('a machine with no sidecar does not re-attempt the resume on every refresh', async () => {
managedBuiltin = true
- // No sidecar: the command has no route and throws, the way it does in the
- // web and remote-bridge builds and on a broken install.
+ // No sidecar, and the backend SAYS so: the command is not in this build's
+ // invoke handler, which is the web and remote-bridge case and a broken
+ // install. A refusal is an answer, so the one shot is spent.
listBundledModels.mockRejectedValue(new Error('command list_bundled_models not found'))
const refresh = await bootAndRefresh()
expect(startBundledEmbed).not.toHaveBeenCalled()
@@ -141,3 +142,49 @@ describe('the once-per-session flag is raised on the attempt, not on the success
expect(bundledEngineStatus).not.toHaveBeenCalled()
})
})
+
+// ── A14 second review 3: a launch race is not an answer ─────────────────────
+
+describe('a call that never got through does not spend the one shot', () => {
+ it('a timeout on the first refresh leaves the resume owed', async () => {
+ managedBuiltin = true
+ // The moment this actually runs: right after launch, antivirus scanning
+ // the fresh install, the command layer still coming up behind the window.
+ // Spending the shot here left the engine the user had running yesterday
+ // dead until he re-picked the model by hand, which is GH #118 again.
+ listBundledModels.mockRejectedValue(new Error('invoke timed out after 5000ms'))
+ const refresh = await bootAndRefresh()
+ expect(bundledEngineStatus).not.toHaveBeenCalled()
+
+ // Half a second later the backend is up and the next refresh gets through.
+ listBundledModels.mockResolvedValue([CHAT, EMBED])
+ await refresh()
+ expect(bundledEngineStatus, 'the resume was still owed').toHaveBeenCalled()
+ expect(startBundledEmbed).toHaveBeenCalledWith(EMBED.path)
+
+ // And now it is spent, so it does not run a third time.
+ bundledEngineStatus.mockClear()
+ await refresh()
+ expect(bundledEngineStatus).not.toHaveBeenCalled()
+ })
+
+ it('a dead transport counts the same as a timeout', async () => {
+ managedBuiltin = true
+ listBundledModels.mockRejectedValue(new Error('Failed to fetch'))
+ const refresh = await bootAndRefresh()
+ listBundledModels.mockResolvedValue([CHAT, EMBED])
+ await refresh()
+ expect(bundledEngineStatus).toHaveBeenCalled()
+ })
+
+ // NEGATIVE CONTROL: the refusal really must still spend it, or the web build
+ // asks the same dead question on every single model refresh forever.
+ it('but a plain refusal still spends it', async () => {
+ managedBuiltin = true
+ listBundledModels.mockRejectedValue(new Error('Unknown command list_bundled_models'))
+ const refresh = await bootAndRefresh()
+ listBundledModels.mockResolvedValue([CHAT, EMBED])
+ await refresh()
+ expect(bundledEngineStatus).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.ts
index 0cc0fdf5..48addf5b 100644
--- a/src/hooks/useModels.ts
+++ b/src/hooks/useModels.ts
@@ -15,7 +15,11 @@ import { log } from '../lib/logger'
import { cloudModelRow } from '../lib/cloud-model-row'
import { runEngineResume } from '../lib/engine-resume-policy'
import { engineStartIsWorthRetrying } from '../lib/engine-start-failure'
+import { commandIsUnavailable } from '../lib/engine-command-availability'
import { dropDuplicateLuEngineRows } from '../lib/lu-engine-rows'
+import { isBuiltinEngineEntry, type InstalledModelLike } from '../lib/lmstudio-match'
+import { ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE } from '../api/lu-engine-switch'
+import { useLuEngineSwitchStore } from '../stores/luEngineSwitchStore'
import { useModelStore } from '../stores/modelStore'
import { useProviderStore } from '../stores/providerStore'
import { useSettingsStore } from '../stores/settingsStore'
@@ -242,17 +246,27 @@ export function useModels() {
// the web and remote-bridge builds, which have no sidecar to start,
// still get nothing and are unchanged.
//
- // A14 review 6: the once-per-session flag is raised BEFORE the call, not
- // after a successful one. fetchModels runs from several mounted
- // components and on every refresh event, so raising it afterwards meant
- // a machine without a sidecar (web, remote bridge, a broken install)
- // re-attempted the whole resume on every single refresh, forever.
+ // A14 review 6 and its follow-up: the once-per-session flag is spent on
+ // an ANSWER, not on an attempt and not on a success.
+ //
+ // - answered with a list the resume runs, once, and never again.
+ // - answered "no such command" this build has no sidecar, so the shot
+ // is spent too and the web, bridge and broken-install cases stop
+ // re-attempting the whole resume on every refresh forever.
+ // - no answer at all (timeout, dead transport) nothing was learned,
+ // so nothing is spent. This is the launch race: the command layer
+ // coming up behind the window. Spending the shot there left the
+ // engine the user had running yesterday dead for the session.
const firstPassThisSession = !builtinResumeAttempted
- builtinResumeAttempted = true
let bundledRaw: BundledModel[] | null = null
+ let backendAnswered = false
try {
bundledRaw = await listBundledModels()
- } catch { /* engine command unavailable, non-critical */ }
+ backendAnswered = true
+ } catch (e) {
+ backendAnswered = commandIsUnavailable(e)
+ }
+ if (backendAnswered) builtinResumeAttempted = true
if (bundledRaw) {
const bundled = bundledToAIModels(bundledRaw).filter(m => !isEmbeddingModel(m.name))
// One file, one row: with the folder pointed at ~/.lmstudio/models,
@@ -454,14 +468,28 @@ export function useModels() {
return models.filter((m: AIModel) => m.type === filter)
}
- // Selecting a built-in model must also swap the loaded GGUF: the managed
- // engine serves one model per process, so activation → swap_bundled_model.
+ // Selecting an LU Engine model must also swap the loaded GGUF: the managed
+ // engine serves one model per process, so activation means swap_bundled_model.
// Other providers just set the active model as before.
+ //
+ // A14 second review: this did half the job and the half it skipped was the
+ // whole point. The guard was "is the openai slot already ours", so a click
+ // on an LU Engine card under Installed while Ollama held the chat wrote
+ // openai::<gguf> into the store, unloaded the Ollama model to make room, and
+ // then started nothing and switched nothing. The user was left on a model
+ // that answered from nowhere. Same route as the picker and the Use button
+ // now: hand the slot over, say so, then start.
const activateModel = useCallback((name: string) => {
+ const row = useModelStore.getState().models.find((m) => m.name === name)
+ if (isBuiltinEngineEntry(row as unknown as InstalledModelLike | undefined)) {
+ if (ensureLuEngineIsChatProvider()) {
+ useLuEngineSwitchStore.getState().announce(LU_ENGINE_SWITCH_NOTE)
+ }
+ }
setActiveModel(name)
const cfg = useProviderStore.getState().providers.openai
if (cfg.enabled && cfg.managed && getProviderIdFromModel(name) === 'openai') {
- void activateBuiltinModel(name).catch(() => { /* engine unavailable — non-critical */ })
+ void activateBuiltinModel(name).catch(() => { /* engine unavailable, non-critical */ })
}
}, [setActiveModel])
diff --git a/src/lib/engine-command-availability.ts b/src/lib/engine-command-availability.ts
new file mode 100644
index 00000000..2426526d
--- /dev/null
+++ b/src/lib/engine-command-availability.ts
@@ -0,0 +1,55 @@
+/**
+ * Did the backend ANSWER, or did the call simply not get through.
+ *
+ * A14 second review: the boot resume gets one shot per app session, and the
+ * flag that spends it was raised before the call. That is right for a machine
+ * that has no sidecar and will never have one, and wrong for the moment this
+ * actually runs: right after launch, with the antivirus still scanning the
+ * fresh install and the Tauri command layer coming up behind the window. A
+ * first call that loses that race used to spend the only shot, and the engine
+ * the user left running yesterday stayed dead until he re-picked the model by
+ * hand. That is GH #118 again, one door further along.
+ *
+ * So the shot is spent on an ANSWER, and a refusal counts as one: a backend
+ * that says "I do not have that command" has answered, and waiting will not
+ * change its mind. A timeout or a dead transport has said nothing at all.
+ */
+
+/** Rejections that mean "this build does not have that command". Lower-cased
+ * fragments, matched against the message Tauri hands across as a string. */
+const NO_SUCH_COMMAND = [
+ // Tauri's own wording for a command that is not in the invoke handler, and
+ // the shapes the HTTP bridge and the web build produce for the same thing.
+ 'not found',
+ 'unknown command',
+ 'no such command',
+ 'invalid command',
+ 'command not allowed',
+ 'not allowed by scope',
+ 'not implemented',
+ // No Tauri at all: `backendCall` outside the desktop build.
+ 'not running in tauri',
+ 'is not a function',
+ 'not available in this build',
+]
+
+/** The message behind an unknown thrown value. */
+export function commandFailureText(err: unknown): string {
+ if (err instanceof Error) return err.message
+ if (typeof err === 'string') return err
+ return String(err ?? '')
+}
+
+/**
+ * True when the failure is the backend saying it does not have this command.
+ *
+ * Deliberately the narrow half. Everything unrecognised counts as "no answer"
+ * and is retried, because the cost of retrying is one extra command on the
+ * next model refresh and the cost of not retrying is a dead engine for the
+ * rest of the session.
+ */
+export function commandIsUnavailable(err: unknown): boolean {
+ const msg = commandFailureText(err).toLowerCase()
+ if (!msg) return false
+ return NO_SUCH_COMMAND.some((m) => msg.includes(m))
+}