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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(models): der Karten-Klick zeigt einen toten Engine-Start, riegelt doppelte Swaps ab und der Boot-Resume laeuft auch nebenlaeufig nur einmal
purple3acc06089922
diff --git a/src/api/lu-engine-switch.ts b/src/api/lu-engine-switch.tsindex 93c9e4bc..9ed5afc0 100644--- a/src/api/lu-engine-switch.ts+++ b/src/api/lu-engine-switch.ts@@ -20,10 +20,35 @@ import { useProviderStore } from '../stores/providerStore'import { PROVIDER_PRESETS } from './providers/types'import { slotTakeoverUpdate } from '../lib/openai-slot-handover'import { LU_ENGINE_NAME } from '../lib/engine-name'+import { displayModelName } from './providers'/** What the user is told when the pick moved his chat backend. */export const LU_ENGINE_SWITCH_NOTE = 'Switched your chat provider to the LU Engine for this model.'+/**+ * The reason behind an `activateBuiltinModel` that answered false.+ *+ * It resolves the GGUF path from the last `list_bundled_models`, refreshes+ * that list once, and only then gives up, so a false here means the file the+ * row stands for is not in the folder any more.+ */+export const LU_ENGINE_FILE_GONE =+ 'the file behind that row is not in the LU Engine folder any more. Check Settings, AI Backends, Model Storage.'++/**+ * The one sentence a failed engine start gets, wherever it was triggered.+ *+ * A14 third review: the picker said this and the Installed card said nothing.+ * The card swallowed the failure with `.catch(() => {})`, so a dead+ * llama-server left the slot handed over, the Ollama model already unloaded,+ * and one cheerful line on screen saying the chat provider had moved. Both+ * doors read from here now, so the two cannot drift apart.+ */+export function luEngineStartFailureNote(modelName: string, reason: unknown): string {+ const text = reason instanceof Error ? reason.message : String(reason)+ return `Couldn't start the LU Engine with "${displayModelName(modelName)}": ${text}`+}+/** The shipped address of the engine. The real port is written back by* `syncBuiltinEnginePort` as soon as it starts, exactly as it is for a* takeover from the provider card. */diff --git a/src/components/chat/LuEngineSwitchBar.tsx b/src/components/chat/LuEngineSwitchBar.tsxindex 7349bccc..785d603a 100644--- a/src/components/chat/LuEngineSwitchBar.tsx+++ b/src/components/chat/LuEngineSwitchBar.tsx@@ -5,12 +5,23 @@* standing statements live, so it survives the dropdown closing under it. Not* an alarm colour, because nothing went wrong: the user asked for this by* picking an LU Engine model, he just has to be told what it cost him.+ *+ * A14 third review added the second tone. A start that dies AFTER the slot has+ * been handed over is the one thing that reaches this bar and is not the+ * user's own doing, and the Installed card used to swallow it whole.*/import { X } from 'lucide-react'import { useLuEngineSwitchStore } from '../../stores/luEngineSwitchStore'export function LuEngineSwitchBar() {const note = useLuEngineSwitchStore((s) => s.note)+ const tone = useLuEngineSwitchStore((s) => s.tone)+ // A failed start after the slot has already been handed over is the one+ // thing here the user has to act on, so it does not get the quiet grey the+ // switch itself gets.+ const skin = tone === 'error'+ ? 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-300'+ : 'bg-white/5 border-white/10 text-gray-600 dark:text-gray-300'// The live region stays MOUNTED and its text changes, which is the only// shape a screen reader actually announces: a region that appears at the// same moment as its content is usually read as page furniture and skipped.@@ -21,7 +32,8 @@ export function LuEngineSwitchBar() {{note && (<divdata-testid="lu-engine-switch-note"- className="mx-3 mb-1.5 flex items-start gap-2 px-2 py-1 rounded-md bg-white/5 border border-white/10 text-[0.62rem] text-gray-600 dark:text-gray-300"+ data-tone={tone}+ className={`mx-3 mb-1.5 flex items-start gap-2 px-2 py-1 rounded-md border text-[0.62rem] ${skin}`}><span className="flex-1 leading-snug">{note}</span><buttondiff --git a/src/components/chat/__tests__/lu-engine-switch-note-is-visible.test.ts b/src/components/chat/__tests__/lu-engine-switch-note-is-visible.test.tsindex 79d94f47..abfa34dd 100644--- a/src/components/chat/__tests__/lu-engine-switch-note-is-visible.test.ts+++ b/src/components/chat/__tests__/lu-engine-switch-note-is-visible.test.ts@@ -81,6 +81,31 @@ describe('the line survives the pick that caused it', () => {expect(useProviderStore.getState().providers.openai.managed).toBe(true)})+ // A14 third review: the Installed card used to swallow a failed start+ // whole, so the only line on screen was the cheerful one. The failure goes+ // into this same bar now, and it must not be drawn as the quiet grey note+ // beside it.+ it('draws a failed start as an error, not as the quiet switch line', async () => {+ render(createElement(LuEngineSwitchBar))+ await act(async () => {+ pickAnLuEngineModel()+ useLuEngineSwitchStore.getState().announce('Couldn\'t start the LU Engine with "x": boom', 'error')+ })+ const line = screen.getByTestId('lu-engine-switch-note')+ expect(line.getAttribute('data-tone')).toBe('error')+ expect(line.className).toContain('red')+ })++ // NEGATIVE CONTROL: the switch itself is not an alarm. The user asked for+ // it by picking the model, so it keeps the quiet skin.+ it('keeps the plain skin for the switch itself', async () => {+ render(createElement(LuEngineSwitchBar))+ await act(async () => { pickAnLuEngineModel() })+ const line = screen.getByTestId('lu-engine-switch-note')+ expect(line.getAttribute('data-tone')).toBe('info')+ expect(line.className).not.toContain('red')+ })+it('clears itself after a while instead of standing forever', async () => {vi.useFakeTimers()render(createElement(LuEngineSwitchBar))diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex 466c5f86..cb805dc4 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -20,7 +20,7 @@ import { noChatBackendEnabled } from '../../lib/provider-visibility'import { cloudTeaserModels } from '../../lib/cloud-teaser-models'import { splitLuEngineRows, needsLuEngineHeading, LU_ENGINE_GROUP } 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 { ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE, luEngineStartFailureNote } from '../../api/lu-engine-switch'import { useLuEngineSwitchStore } from '../../stores/luEngineSwitchStore'import type { AIModel } from '../../types/models'@@ -759,7 +759,9 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy}setOpen(false)} catch (e) {- setSelectError(`Couldn't start the LU Engine with "${displayModelName(model.name)}": ${e instanceof Error ? e.message : String(e)}`)+ // Shared with the Installed card, which used to swallow this failure+ // whole. One sentence, one place it is written (A14 third review).+ setSelectError(luEngineStartFailureNote(model.name, e))} finally {setSelectingLms(null)}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.tsindex 7ade101f..0fa55897 100644--- a/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts+++ b/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts@@ -70,14 +70,17 @@ const { useProviderStore } = await import('../../stores/providerStore')const { useLuEngineSwitchStore } = await import('../../stores/luEngineSwitchStore')const GGUF = 'openai::Qwen2.5-0.5B-Instruct-Q8_0'+const SECOND_GGUF = 'openai::gemma-3-4b-it-Q4_K_M'const OLLAMA = 'llama3.2:3b'+const SWITCH_NOTE = 'Switched your chat provider to the LU Engine for this model.'-/** The Installed list as David's Mac draws it: an Ollama model in front, one- * GGUF from the LU Engine folder beside it. */+/** The Installed list as David's Mac draws it: an Ollama model in front, two+ * GGUFs 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' },+ { name: SECOND_GGUF, model: 'gemma-3-4b-it-Q4_K_M', size: 1, type: 'text', provider: 'openai', providerName: 'LU Engine' },] as never}@@ -89,7 +92,8 @@ async function clickCard(name: string) {}beforeEach(() => {- activateBuiltinModel.mockClear()+ activateBuiltinModel.mockReset()+ activateBuiltinModel.mockResolvedValue(true)unloadModel.mockClear()useLuEngineSwitchStore.setState({ note: null, generation: 0 })useProviderStore.getState().resetProvidersToDefaults()@@ -116,8 +120,8 @@ describe('clicking an LU Engine card while Ollama holds the chat', () => {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.')+ expect(useLuEngineSwitchStore.getState().note).toBe(SWITCH_NOTE)+ expect(useLuEngineSwitchStore.getState().tone, 'nothing went wrong yet').toBe('info')})it('and the model really is the active one afterwards', async () => {@@ -159,3 +163,97 @@ describe('clicking an LU Engine card while Ollama holds the chat', () => {expect(useLuEngineSwitchStore.getState().note).toBeNull()})})++// ── A14 third review: a start that dies must not look like a start ──────────++describe('when the engine does not come up for the card that was clicked', () => {+ it('names the real reason instead of swallowing it', async () => {+ activateBuiltinModel.mockRejectedValue(new Error('llama-server exited: unknown model architecture'))+ await clickCard(GGUF)+ const { note, tone } = useLuEngineSwitchStore.getState()+ // The picker's sentence, word for word, from the shared helper.+ expect(note).toContain('Couldn\'t start the LU Engine with "Qwen2.5-0.5B-Instruct-Q8_0"')+ // Including the tail Rust appends, which is the whole point of showing it.+ expect(note).toContain('unknown model architecture')+ expect(tone, 'a dead engine is not a quiet grey line').toBe('error')+ })++ it('keeps saying that the chat backend has already moved', async () => {+ // The slot was handed over BEFORE the start, and the Ollama model was+ // unloaded to make room. A failure that only names the failure would leave+ // the user guessing what he is talking to now.+ activateBuiltinModel.mockRejectedValue(new Error('port 8127 is taken'))+ await clickCard(GGUF)+ const note = useLuEngineSwitchStore.getState().note+ expect(note, 'the switch sentence has to survive the failure').toContain(SWITCH_NOTE)+ expect(note, 'and stand beside the failure, not instead of it').toContain('port 8127 is taken')+ expect(useProviderStore.getState().providers.openai.managed).toBe(true)+ })++ it('treats a false answer as a failure too, and says which file is gone', async () => {+ // activateBuiltinModel answers false when it cannot resolve the GGUF path,+ // even after refreshing the list once. Nothing was started.+ activateBuiltinModel.mockResolvedValue(false)+ await clickCard(GGUF)+ const { note, tone } = useLuEngineSwitchStore.getState()+ expect(note).toContain('Couldn\'t start the LU Engine with "Qwen2.5-0.5B-Instruct-Q8_0"')+ expect(note).toContain('not in the LU Engine folder any more')+ expect(tone).toBe('error')+ })++ // NEGATIVE CONTROL: a start that works says nothing about a failure, and the+ // line stays the quiet one.+ it('says nothing of the sort when the start works', async () => {+ await clickCard(GGUF)+ expect(useLuEngineSwitchStore.getState().note).toBe(SWITCH_NOTE)+ expect(useLuEngineSwitchStore.getState().tone).toBe('info')+ })+})++// ── A14 third review: one swap at a time, as in the picker ─────────────────++describe('two LU Engine cards clicked in quick succession', () => {+ it('send one swap, not two', async () => {+ // Two cards, two clicks, and the first swap still running. Without the+ // bolt this is two swap_bundled_model calls at one engine, the second one+ // landing on a process the first is still restarting.+ let release: (v: boolean) => void = () => {}+ activateBuiltinModel.mockImplementation(() => new Promise<boolean>((r) => { release = r }))+ const { result } = renderHook(() => useModels())+ await act(async () => {+ result.current.setActiveModel(GGUF)+ result.current.setActiveModel(SECOND_GGUF)+ })+ expect(activateBuiltinModel).toHaveBeenCalledTimes(1)+ expect(activateBuiltinModel).toHaveBeenCalledWith(GGUF)+ // The blocked click changed nothing else either: it never reached the+ // store, so the engine is still pointed at the first card.+ expect(useModelStore.getState().activeModel).toBe(GGUF)++ // NEGATIVE CONTROL in the same frame: the bolt is a bolt, not a lock. Once+ // the first swap is done the next click gets through. Counted as "more+ // than before" rather than as an exact number, because the store's own+ // chokepoint swaps built-in to built-in as well and Rust's argv+ // idempotence makes that pair a no-op (modelStore.ts).+ await act(async () => { release(true) })+ await act(async () => { await new Promise((r) => setTimeout(r, 0)) })+ const before = activateBuiltinModel.mock.calls.length+ await act(async () => { result.current.setActiveModel(SECOND_GGUF) })+ expect(activateBuiltinModel.mock.calls.length).toBeGreaterThan(before)+ expect(activateBuiltinModel).toHaveBeenLastCalledWith(SECOND_GGUF)+ await act(async () => { release(true) })+ })++ // NEGATIVE CONTROL: the bolt belongs to the LU Engine path only. An Ollama+ // card clicked while a swap is running is not blocked by it.+ it('never blocks a click on another backend', async () => {+ let release: (v: boolean) => void = () => {}+ activateBuiltinModel.mockImplementation(() => new Promise<boolean>((r) => { release = r }))+ const { result } = renderHook(() => useModels())+ await act(async () => { result.current.setActiveModel(GGUF) })+ await act(async () => { result.current.setActiveModel(OLLAMA) })+ expect(useModelStore.getState().activeModel).toBe(OLLAMA)+ await act(async () => { release(true) })+ await act(async () => { await new Promise((r) => setTimeout(r, 0)) })+ })+})diff --git a/src/hooks/__tests__/lu-engine-resume-routing.test.ts b/src/hooks/__tests__/lu-engine-resume-routing.test.tsindex 19bf0352..05a2f871 100644--- a/src/hooks/__tests__/lu-engine-resume-routing.test.ts+++ b/src/hooks/__tests__/lu-engine-resume-routing.test.ts@@ -113,7 +113,9 @@ describe('the once-per-session flag is raised on the attempt, not on the success// 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'))+ // The literal from src/api/backend.ts, not an invented wording:+ // the HTTP bridge's endpoint table throws exactly this.+ listBundledModels.mockRejectedValue(new Error('Unknown backend command: list_bundled_models'))const refresh = await bootAndRefresh()expect(startBundledEmbed).not.toHaveBeenCalled()expect(bundledEngineStatus).not.toHaveBeenCalled()@@ -181,10 +183,70 @@ describe('a call that never got through does not spend the one shot', () => {// 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'))+ listBundledModels.mockRejectedValue(new Error('Unknown backend command: list_bundled_models'))const refresh = await bootAndRefresh()listBundledModels.mockResolvedValue([CHAT, EMBED])await refresh()expect(bundledEngineStatus).not.toHaveBeenCalled()})})++// ── A14 third review: two mounted components are two first passes ───────────++describe('two overlapping first passes', () => {+ /** Both passes wait on ONE pending list call, which is what the launch race+ * looks like: the Models page and the composer both mount, both ask, and+ * the backend answers both at once. */+ async function twoPassesOn(answer: () => Promise<unknown>) {+ vi.resetModules()+ const { useModels } = await import('../useModels')+ listBundledModels.mockImplementation(answer as never)+ const a = renderHook(() => useModels())+ const b = renderHook(() => useModels())+ const both = async () => {+ await act(async () => {+ await Promise.all([a.result.current.fetchModels(), b.result.current.fetchModels()])+ })+ await act(async () => { await new Promise((r) => setTimeout(r, 0)) })+ }+ await both()+ return both+ }++ it('start the boot resume once, not twice', async () => {+ managedBuiltin = true+ // The flag used to be READ before the await and WRITTEN after it, so both+ // passes read "first pass" and both fired the resume: two llama-server+ // starts on one port, on the machine with the least room to spare.+ // resumeEmbedServer runs once per resume, so its start counts them.+ await twoPassesOn(async () => [CHAT, EMBED])+ expect(startBundledEmbed).toHaveBeenCalledTimes(1)+ })++ // NEGATIVE CONTROL: the claim is given back when nothing was learned. Two+ // passes that both lose the launch race must leave the resume owed, exactly+ // as one pass does, or the Runde-3 contract dies the moment a second+ // component is mounted.+ it('leave the resume owed when neither of them got an answer', async () => {+ managedBuiltin = true+ const again = await twoPassesOn(async () => { throw new Error('invoke timed out after 5000ms') })+ expect(startBundledEmbed).not.toHaveBeenCalled()+ listBundledModels.mockImplementation(async () => [CHAT, EMBED] as never)+ await again()+ expect(bundledEngineStatus, 'the resume was still owed').toHaveBeenCalled()+ expect(startBundledEmbed).toHaveBeenCalledTimes(1)+ })++ // NEGATIVE CONTROL: a refusal still spends the shot, even when the pass that+ // heard it was racing another one.+ it('spend the shot once on a refusal, and never ask again', async () => {+ managedBuiltin = true+ const again = await twoPassesOn(async () => {+ throw new Error('Unknown backend command: list_bundled_models')+ })+ listBundledModels.mockImplementation(async () => [CHAT, EMBED] as never)+ await again()+ expect(bundledEngineStatus).not.toHaveBeenCalled()+ expect(startBundledEmbed).not.toHaveBeenCalled()+ })+})diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 48addf5b..7031344a 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -18,7 +18,9 @@ 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 {+ ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE, LU_ENGINE_FILE_GONE, luEngineStartFailureNote,+} from '../api/lu-engine-switch'import { useLuEngineSwitchStore } from '../stores/luEngineSwitchStore'import { useModelStore } from '../stores/modelStore'import { useProviderStore } from '../stores/providerStore'@@ -41,6 +43,27 @@ import type { PullProgress, AIModel, ModelCategory, ImageModel, VideoModel, Clou// starts a server that reports running:false.let builtinResumeAttempted = false+// A14 third review: `fetchModels` runs from several mounted components at+// once, and the flag above was READ before the await and WRITTEN after it, so+// two first passes that overlapped both read "first pass" and both fired the+// resume. That is two llama-server starts on one port, on the machine with the+// least room to spare.+//+// The claim is taken here, before the await, and only the pass holding it may+// spend the shot or hand it back. A pass that answered while the claim holder+// was still waiting must NOT spend it: it skipped the resume, so spending it+// would leave the resume owed forever. A claim holder that got no answer gives+// the claim back, which keeps the Runde-3 contract (a timeout does not eat the+// shot) intact under concurrency.+let builtinResumeClaimed = false++// A14 third review, the other half: two LU Engine cards clicked in quick+// succession fired two `swap_bundled_model` calls at one engine. The picker+// has had a bolt against this since ENG-4 (`selectingLms`); the Installed card+// had none, and a hook-local ref would not have been one either, because the+// two clicks can land in two different mounted components.+let luEngineSwapInFlight = false+// GH #118: the boot resume used to be a single shot, and a failure was// swallowed without a word. The one moment it runs is the worst moment to ask// a machine for a GPU: right after login, with the antivirus scanning the@@ -257,7 +280,11 @@ export function useModels() {// 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+ //+ // A14 third review: the claim is taken BEFORE the await, so two passes+ // racing out of two mounted components cannot both be the first one.+ const firstPassThisSession = !builtinResumeAttempted && !builtinResumeClaimed+ if (firstPassThisSession) builtinResumeClaimed = truelet bundledRaw: BundledModel[] | null = nulllet backendAnswered = falsetry {@@ -266,7 +293,13 @@ export function useModels() {} catch (e) {backendAnswered = commandIsUnavailable(e)}- if (backendAnswered) builtinResumeAttempted = true+ // Only the pass that holds the claim may spend the shot or give it back.+ // A pass that skipped the resume must not spend it on the holder's+ // behalf, or the resume it skipped would never happen.+ if (firstPassThisSession) {+ if (backendAnswered) builtinResumeAttempted = true+ else builtinResumeClaimed = false+ }if (bundledRaw) {const bundled = bundledToAIModels(bundledRaw).filter(m => !isEmbeddingModel(m.name))// One file, one row: with the folder pointed at ~/.lmstudio/models,@@ -481,15 +514,43 @@ export function useModels() {// 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)- }+ const isLuRow = isBuiltinEngineEntry(row as unknown as InstalledModelLike | undefined)+ // Did THIS click move the chat backend. A failure afterwards has to keep+ // saying so: the slot has already changed hands and the model the user was+ // talking to has already been unloaded to make room.+ let switched = false+ if (isLuRow) {+ // A14 third review: the bolt the picker has had since ENG-4. Two LU+ // cards clicked in quick succession used to send two swap_bundled_model+ // calls at one engine, and the second one lands on a process the first+ // one is still restarting.+ if (luEngineSwapInFlight) return+ switched = ensureLuEngineIsChatProvider()+ if (switched) useLuEngineSwitchStore.getState().announce(LU_ENGINE_SWITCH_NOTE)}setActiveModel(name)const cfg = useProviderStore.getState().providers.openaiif (cfg.enabled && cfg.managed && getProviderIdFromModel(name) === 'openai') {- void activateBuiltinModel(name).catch(() => { /* engine unavailable, non-critical */ })+ // A14 third review: this used to be `.catch(() => {})`. A dead+ // llama-server then left the slot handed over, the Ollama model already+ // unloaded to make room, and one cheerful line on screen saying the chat+ // provider had moved. The picker names the real reason with the stderr+ // tail Rust appends; the card says the same sentence now, from the same+ // helper, in the status row that is drawn right above the list.+ if (isLuRow) luEngineSwapInFlight = true+ const sayItFailed = (reason: unknown) => {+ const line = luEngineStartFailureNote(name, reason)+ useLuEngineSwitchStore.getState()+ .announce(switched ? `${LU_ENGINE_SWITCH_NOTE} ${line}` : line, 'error')+ }+ void activateBuiltinModel(name)+ // False is not a shrug: the path could not be resolved even after a+ // refresh, so the row stands for a file that is no longer there.+ .then((swapped) => { if (!swapped && isLuRow) sayItFailed(LU_ENGINE_FILE_GONE) })+ // Not an LU row: some other model in the openai slot, and the engine+ // has nothing to say about it. Unchanged, non-critical.+ .catch((e) => { if (isLuRow) sayItFailed(e) })+ .finally(() => { if (isLuRow) luEngineSwapInFlight = false })}}, [setActiveModel])diff --git a/src/lib/__tests__/engine-command-availability.test.ts b/src/lib/__tests__/engine-command-availability.test.tsnew file mode 100644index 00000000..0119c3ce--- /dev/null+++ b/src/lib/__tests__/engine-command-availability.test.ts@@ -0,0 +1,71 @@+/**+ * A14 third review: the module that decides whether the backend ANSWERED did+ * not recognise the one refusal the app actually produces.+ *+ * `backendCall` outside the desktop build routes through the HTTP bridge's+ * endpoint table and throws `Unknown backend command: <name>` for anything not+ * in it. None of the fragments matched that, so every web and remote-bridge+ * refresh treated the refusal as "no answer" and asked the same dead question+ * again, forever. The two tests that were meant to cover this used invented+ * wordings and passed on strings nothing ever throws.+ *+ * So the literal from src/api/backend.ts is pinned here, from the source file+ * itself, and not retyped from memory.+ *+ * Run: npx vitest run src/lib/__tests__/engine-command-availability.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'+import { commandIsUnavailable, commandFailureText } from '../engine-command-availability'++const backendSrc = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../api/backend.ts'),+ 'utf8',+)++describe('the refusal the HTTP bridge really throws', () => {+ it('is still worded the way this module expects', () => {+ // The source guard. If someone rewords the throw, this fails here rather+ // than in a web build six weeks later.+ expect(backendSrc).toContain('Unknown backend command: ${command}')+ })++ it('counts as an answer', () => {+ expect(commandIsUnavailable(new Error('Unknown backend command: list_bundled_models'))).toBe(true)+ })++ it('counts as an answer as a bare string too', () => {+ // Tauri hands rejections across as strings, not as Errors.+ expect(commandIsUnavailable('Unknown backend command: swap_bundled_model')).toBe(true)+ expect(commandFailureText('Unknown backend command: swap_bundled_model'))+ .toContain('Unknown backend command')+ })++ // NEGATIVE CONTROL: everything unrecognised must stay "no answer", because+ // the cost of retrying is one extra command and the cost of not retrying is+ // a dead engine for the rest of the session.+ it('and a call that never got through still counts as nothing learned', () => {+ for (const msg of [+ 'invoke timed out after 5000ms',+ 'Failed to fetch',+ 'NetworkError when attempting to fetch resource',+ 'The backend command took too long',+ ]) {+ expect(commandIsUnavailable(new Error(msg)), msg).toBe(false)+ }+ })++ // NEGATIVE CONTROL: the older refusals are still recognised.+ it('keeps recognising the wordings it already knew', () => {+ for (const msg of [+ 'command not_a_command not found',+ 'Unknown command foo',+ 'not running in Tauri',+ 'not implemented',+ ]) {+ expect(commandIsUnavailable(new Error(msg)), msg).toBe(true)+ }+ })+})diff --git a/src/lib/engine-command-availability.ts b/src/lib/engine-command-availability.tsindex 2426526d..b6f48f50 100644--- a/src/lib/engine-command-availability.ts+++ b/src/lib/engine-command-availability.ts@@ -22,6 +22,14 @@ const NO_SUCH_COMMAND = [// the shapes the HTTP bridge and the web build produce for the same thing.'not found','unknown command',+ // A14 third review: the one refusal this module was written for was the one+ // it did not recognise. `backendCall` outside Tauri routes through the HTTP+ // bridge's endpoint table and throws `Unknown backend command: <name>` for+ // anything not in it, which matches none of the fragments above, so the web+ // and remote-bridge builds re-asked the same dead question on every single+ // model refresh. The literal lives in src/api/backend.ts and is pinned by+ // engine-command-availability.test.ts.+ 'unknown backend command','no such command','invalid command','command not allowed',diff --git a/src/stores/luEngineSwitchStore.ts b/src/stores/luEngineSwitchStore.tsindex 23a7ead6..55981cbc 100644--- a/src/stores/luEngineSwitchStore.ts+++ b/src/stores/luEngineSwitchStore.ts@@ -21,12 +21,21 @@ import { create } from 'zustand'* short enough that it is gone by the time the user sends his next message. */export const LU_ENGINE_SWITCH_NOTE_MS = 12_000+/**+ * How the line is drawn. 'info' is the switch itself, which is not an alarm:+ * the user asked for it by picking the model. 'error' is a start that failed+ * after the slot had already been handed over, which is the one case where the+ * user has to act (A14 third review).+ */+export type LuEngineNoteTone = 'info' | 'error'+interface LuEngineSwitchState {note: string | null+ tone: LuEngineNoteTone/** Bumped on every announcement, so a timer belonging to an older one cannot* clear a newer line. Same reason the slot-eviction timer keeps one. */generation: number- announce: (note: string) => void+ announce: (note: string, tone?: LuEngineNoteTone) => voiddismiss: () => void}@@ -46,18 +55,19 @@ function cancelPending(): void {export const useLuEngineSwitchStore = create<LuEngineSwitchState>((set, get) => ({note: null,+ tone: 'info',generation: 0,- announce: (note) => {+ announce: (note, tone = 'info') => {cancelPending()const generation = get().generation + 1- set({ note, generation })+ set({ note, tone, generation })pending = setTimeout(() => {pending = null- if (get().generation === generation) set({ note: null })+ if (get().generation === generation) set({ note: null, tone: 'info' })}, LU_ENGINE_SWITCH_NOTE_MS)},dismiss: () => {cancelPending()- set({ note: null, generation: get().generation + 1 })+ set({ note: null, tone: 'info', generation: get().generation + 1 })},}))