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): Karte und Picker teilen einen Riegel, der blockierte Klick sagt es und der Riegel laeuft ab
purple69a2efba6f08
diff --git a/src/api/__tests__/lu-engine-swap-lock.test.ts b/src/api/__tests__/lu-engine-swap-lock.test.tsnew file mode 100644index 00000000..dad06e32--- /dev/null+++ b/src/api/__tests__/lu-engine-swap-lock.test.ts@@ -0,0 +1,89 @@+/**+ * The one bolt in front of the LU Engine model swap.+ *+ * A14 fourth review: the bolt existed but it was a module variable inside+ * `useModels`, so it held the Installed card and nothing else. The composer's+ * picker calls `activateBuiltinModel` itself and guards it with its own+ * component state, which knows nothing about the card. Two doors into one+ * llama-server, and the second swap lands on a process the first is still+ * restarting, which is the ENG-4 crash from the side the ENG-4 fix never+ * covered.+ *+ * The behaviour across the two real doors is proven in+ * hooks/__tests__/installed-card-click-switches-the-backend.test.ts. What is+ * proven here is the bolt itself, including the one thing no caller can prove:+ * that a swap which never answers cannot lock the model list until the app is+ * restarted.+ *+ * Run: npx vitest run src/api/__tests__/lu-engine-swap-lock.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import {+ tryAcquireLuEngineSwap, releaseLuEngineSwap, luEngineSwapInFlight,+ __resetLuEngineSwapLockForTests, LU_ENGINE_SWAP_LOCK_MS,+} from '../lu-engine-swap-lock'++beforeEach(() => { __resetLuEngineSwapLockForTests() })+afterEach(() => { vi.useRealTimers() })++describe('one swap at a time', () => {+ it('lets the first caller through and turns the second one away', () => {+ expect(tryAcquireLuEngineSwap()).toBe(true)+ expect(tryAcquireLuEngineSwap(), 'the second door is not a second engine').toBe(false)+ expect(luEngineSwapInFlight()).toBe(true)+ })++ // NEGATIVE CONTROL: a bolt that never opens is a lock. The next click has to+ // get through the moment the swap is done.+ it('opens again on release', () => {+ tryAcquireLuEngineSwap()+ releaseLuEngineSwap()+ expect(luEngineSwapInFlight()).toBe(false)+ expect(tryAcquireLuEngineSwap()).toBe(true)+ })++ it('opens on release after a FAILED swap too', () => {+ tryAcquireLuEngineSwap()+ // What the callers do: release from a `finally`, so a rejected+ // activateBuiltinModel frees the next click exactly like a successful one.+ try { throw new Error('llama-server exited') } catch { /* the caller shows this */ }+ finally { releaseLuEngineSwap() }+ expect(tryAcquireLuEngineSwap(), 'a dead engine must not lock the list').toBe(true)+ })++ it('is one bolt across module copies, not one per import', async () => {+ // The bundler duplicates small modules, and two copies each seeing an idle+ // engine is the whole reason the state sits on globalThis. Re-importing is+ // as close as a test gets to that second copy.+ tryAcquireLuEngineSwap()+ vi.resetModules()+ const second = await import('../lu-engine-swap-lock')+ expect(second.tryAcquireLuEngineSwap(), 'a second copy saw an idle engine').toBe(false)+ })+})++describe('a swap that never answers', () => {+ it('gives the bolt up by itself instead of locking the app until a restart', () => {+ vi.useFakeTimers()+ expect(tryAcquireLuEngineSwap()).toBe(true)+ // A Tauri command whose answer is lost: no resolve, no reject, so the+ // `finally` that releases this never runs. Without a limit the card and+ // the picker are both dead for the rest of the session, and the house rule+ // is that the app heals itself before it complains.+ vi.advanceTimersByTime(LU_ENGINE_SWAP_LOCK_MS + 1)+ expect(luEngineSwapInFlight()).toBe(false)+ expect(tryAcquireLuEngineSwap()).toBe(true)+ })++ // NEGATIVE CONTROL: the limit is a last resort and must not cut a real swap+ // short. A cold GGUF load takes tens of seconds, and a bolt that opened+ // during one would let the second swap in, which is the crash this whole+ // module is against.+ it('still holds while a slow swap is running', () => {+ vi.useFakeTimers()+ tryAcquireLuEngineSwap()+ vi.advanceTimersByTime(LU_ENGINE_SWAP_LOCK_MS - 1_000)+ expect(luEngineSwapInFlight(), 'a slow start is not a dead one').toBe(true)+ expect(tryAcquireLuEngineSwap()).toBe(false)+ })+})diff --git a/src/api/lu-engine-swap-lock.ts b/src/api/lu-engine-swap-lock.tsnew file mode 100644index 00000000..a3146bcd--- /dev/null+++ b/src/api/lu-engine-swap-lock.ts@@ -0,0 +1,82 @@+/**+ * One bolt for the LU Engine model swap, shared by every door that can fire one.+ *+ * A14 third review put a bolt on the Installed card, because two cards clicked+ * in quick succession sent two `swap_bundled_model` calls at one engine and the+ * second one landed on a process the first was still restarting. The fourth+ * review found that the bolt only ever held that one door. It was a module+ * variable inside `useModels`, while the composer's picker calls+ * `activateBuiltinModel` itself and guards it with its own component state+ * (`selectingLms`), which knows nothing about the card and dies with the+ * dropdown. Card and picker are two doors into ONE llama-server: pick a model+ * in the composer, then click a card on the Models page a second later, and the+ * crash the third review fixed is back, arrived at from the side the fix never+ * covered.+ *+ * The state lives on globalThis for the same reason api/engine-swap-gate.ts+ * parks its own there: the bundler duplicates small modules, and two copies of+ * this bolt would each see an idle engine.+ *+ * This is NOT api/engine-swap-gate.ts and does not replace it. That gate lets+ * the SEND path wait for a swap it can see, so a message is not fired into the+ * hole a restart leaves. This one stops a second swap from being started at+ * all. One is a queue, the other is a door.+ */++/**+ * How long the bolt may stand without being released.+ *+ * Every holder releases in a `finally`, so this only matters when a swap never+ * settles at all: a Tauri command whose answer is lost, a promise that neither+ * resolves nor rejects. Without a limit that would lock the card and the picker+ * for the rest of the session and the only way back would be a restart, which+ * breaks the house rule that the app heals itself before it complains. Well+ * over any real swap: the send path waits 90 s for one (ENGINE_SWAP_WAIT_MS),+ * but that wait covers a cold GGUF load, while this only has to cover the UI+ * call handing the work over.+ */+export const LU_ENGINE_SWAP_LOCK_MS = 60_000++const KEY = '__lu_engine_swap_lock__'++interface Bolt {+ /** Wall clock at which an unreleased bolt gives up by itself. 0 when open. */+ heldUntil: number+}++function bolt(): Bolt {+ const g = globalThis as unknown as Record<string, Bolt>+ if (!g[KEY]) g[KEY] = { heldUntil: 0 }+ return g[KEY]+}++/** Test-only: open the bolt and forget any deadline. */+export function __resetLuEngineSwapLockForTests(): void {+ delete (globalThis as unknown as Record<string, unknown>)[KEY]+}++/** True while a swap started anywhere in the app is still running. */+export function luEngineSwapInFlight(): boolean {+ return bolt().heldUntil > Date.now()+}++/**+ * Take the bolt for a swap that is about to start.+ *+ * True when the caller may go ahead, and then the caller OWNS it and must+ * release it in a `finally`. False when someone else is mid swap, and then the+ * caller must not touch the engine and should say so: a click that returns in+ * silence reads as a broken button.+ */+export function tryAcquireLuEngineSwap(): boolean {+ const b = bolt()+ if (b.heldUntil > Date.now()) return false+ b.heldUntil = Date.now() + LU_ENGINE_SWAP_LOCK_MS+ return true+}++/** Give the bolt back. Called from a `finally`, so a rejected swap frees the+ * next click as surely as a successful one does. */+export function releaseLuEngineSwap(): void {+ bolt().heldUntil = 0+}diff --git a/src/api/lu-engine-switch.ts b/src/api/lu-engine-switch.tsindex 9ed5afc0..f25c263d 100644--- a/src/api/lu-engine-switch.ts+++ b/src/api/lu-engine-switch.ts@@ -25,6 +25,16 @@ 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.'+/**+ * What a click that ran into the swap bolt says (api/lu-engine-swap-lock).+ *+ * A14 fourth review: the blocked click returned in silence, which reads as a+ * dead button, and a dead button gets clicked again. One short sentence, the+ * same one on the card and in the picker, saying it is a wait and not a+ * refusal.+ */+export const LU_ENGINE_SWAP_BUSY_NOTE = 'The LU Engine is still switching, one moment.'+/*** The reason behind an `activateBuiltinModel` that answered false.*diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex cb805dc4..c8830bca 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -20,7 +20,10 @@ 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, luEngineStartFailureNote } from '../../api/lu-engine-switch'+import {+ ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE, LU_ENGINE_SWAP_BUSY_NOTE, luEngineStartFailureNote,+} from '../../api/lu-engine-switch'+import { tryAcquireLuEngineSwap, releaseLuEngineSwap } from '../../api/lu-engine-swap-lock'import { useLuEngineSwitchStore } from '../../stores/luEngineSwitchStore'import type { AIModel } from '../../types/models'@@ -739,6 +742,17 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredByif ((isManagedBuiltinActive() && getProviderIdFromModel(model.name) === 'openai')|| isBuiltinEngineEntry(model as unknown as InstalledModelLike)) {if (selectingLms || togglingLms) return+ // A14 fourth review: `selectingLms` is this component's own state and it+ // only ever knew about this dropdown, while the Installed card had a+ // bolt of its own that only ever knew about the card. Two doors into one+ // llama-server, and a pick here while a card swap is running sent the+ // second swap_bundled_model at a process the first was still restarting.+ // Both doors share one bolt now (api/lu-engine-swap-lock), and a blocked+ // pick says so in the dropdown's own line instead of doing nothing.+ if (!tryAcquireLuEngineSwap()) {+ setSelectError(LU_ENGINE_SWAP_BUSY_NOTE)+ return+ }setSelectError(null)setSelectingLms(id)try {@@ -764,6 +778,7 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBysetSelectError(luEngineStartFailureNote(model.name, e))} finally {setSelectingLms(null)+ releaseLuEngineSwap()}return}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 0fa55897..2683fd92 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@@ -68,6 +68,10 @@ const { useModels } = await import('../useModels')const { useModelStore } = await import('../../stores/modelStore')const { useProviderStore } = await import('../../stores/providerStore')const { useLuEngineSwitchStore } = await import('../../stores/luEngineSwitchStore')+const { LU_ENGINE_SWAP_BUSY_NOTE } = await import('../../api/lu-engine-switch')+const {+ tryAcquireLuEngineSwap, releaseLuEngineSwap, __resetLuEngineSwapLockForTests,+} = await import('../../api/lu-engine-swap-lock')const GGUF = 'openai::Qwen2.5-0.5B-Instruct-Q8_0'const SECOND_GGUF = 'openai::gemma-3-4b-it-Q4_K_M'@@ -95,7 +99,10 @@ beforeEach(() => {activateBuiltinModel.mockReset()activateBuiltinModel.mockResolvedValue(true)unloadModel.mockClear()- useLuEngineSwitchStore.setState({ note: null, generation: 0 })+ useLuEngineSwitchStore.setState({ note: null, tone: 'info', generation: 0 })+ // The bolt is app state, not hook state, so a test that leaves it shut would+ // silently block every test after it.+ __resetLuEngineSwapLockForTests()useProviderStore.getState().resetProvidersToDefaults()// Ollama in front, the openai slot parked, which is what onboarding leaves// behind when the user picks Ollama.@@ -257,3 +264,71 @@ describe('two LU Engine cards clicked in quick succession', () => {await act(async () => { await new Promise((r) => setTimeout(r, 0)) })})})++// ── A14 fourth review: the card and the picker are two doors, one engine ────++describe('the bolt is shared with the composer picker', () => {+ it('a swap the picker started blocks a card click', async () => {+ // Exactly what ModelSelector does one line before it calls+ // activateBuiltinModel. Before the bolt was shared, the card knew nothing+ // about this and sent a second swap_bundled_model at a llama-server the+ // picker's swap was still restarting.+ expect(tryAcquireLuEngineSwap(), 'the picker holds it').toBe(true)+ await clickCard(GGUF)+ expect(activateBuiltinModel, 'one engine, one swap').not.toHaveBeenCalled()+ // And the blocked click left the chat exactly where it was: the bolt is+ // taken BEFORE the slot is handed over, so nothing was evicted for a swap+ // that never happened.+ expect(useModelStore.getState().activeModel).toBe(OLLAMA)+ expect(useProviderStore.getState().providers.openai.managed).not.toBe(true)+ })++ // A14 fourth review, the small half: the blocked click returned in silence,+ // and a button that does nothing gets clicked again.+ it('and says so instead of doing nothing', async () => {+ tryAcquireLuEngineSwap()+ await clickCard(GGUF)+ expect(useLuEngineSwitchStore.getState().note).toBe(LU_ENGINE_SWAP_BUSY_NOTE)+ expect(useLuEngineSwitchStore.getState().tone, 'a wait is not a failure').toBe('info')+ })++ it('and a card swap blocks the picker the same way round', 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) })+ expect(tryAcquireLuEngineSwap(), 'the picker asks this before it swaps').toBe(false)++ // NEGATIVE CONTROL in the same frame: a bolt that never opens is a lock.+ await act(async () => { release(true) })+ await act(async () => { await new Promise((r) => setTimeout(r, 0)) })+ expect(tryAcquireLuEngineSwap(), 'the card is done, the picker may go').toBe(true)+ releaseLuEngineSwap()+ })++ // NEGATIVE CONTROL: an engine that refuses to start must free the next+ // click, or one bad GGUF takes the model list down for the session.+ it('frees the bolt after a swap that was rejected', async () => {+ activateBuiltinModel.mockRejectedValue(new Error('llama-server exited'))+ await clickCard(GGUF)+ expect(tryAcquireLuEngineSwap(), 'a failed start is a finished start').toBe(true)+ releaseLuEngineSwap()+ })++ // The picker itself has no render harness (see model-selector-lms.test.ts),+ // so its half of the wiring is pinned by reading the source. The weaker+ // proof, and labelled as such: it catches the picker going back to a bolt of+ // its own, not a picker that fails to render.+ it('and the picker really goes through the shared bolt', async () => {+ const { readFileSync } = await import('node:fs')+ const { resolve, dirname } = await import('node:path')+ const { fileURLToPath } = await import('node:url')+ const src = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../components/models/ModelSelector.tsx'),+ 'utf8',+ )+ expect(src).toContain("from '../../api/lu-engine-swap-lock'")+ expect(src).toContain('if (!tryAcquireLuEngineSwap()) {')+ expect(src, 'and gives it back in a finally').toContain('releaseLuEngineSwap()')+ })+})diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 37f7558c..8121d565 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -19,8 +19,10 @@ 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, LU_ENGINE_FILE_GONE, luEngineStartFailureNote,+ ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE, LU_ENGINE_FILE_GONE, LU_ENGINE_SWAP_BUSY_NOTE,+ luEngineStartFailureNote,} from '../api/lu-engine-switch'+import { tryAcquireLuEngineSwap, releaseLuEngineSwap } from '../api/lu-engine-swap-lock'import { useLuEngineSwitchStore } from '../stores/luEngineSwitchStore'import { useModelStore } from '../stores/modelStore'import { useProviderStore } from '../stores/providerStore'@@ -43,13 +45,6 @@ import type { PullProgress, AIModel, ModelCategory, ImageModel, VideoModel, Clou// starts a server that reports running:false.let builtinResumeAttempted = 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@@ -520,11 +515,23 @@ export function useModels() {// talking to has already been unloaded to make room.let switched = falseif (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+ // The bolt against two swap_bundled_model calls at one engine, where the+ // second lands on a process the first is still restarting. It is taken+ // HERE, before the slot is handed over, so a blocked click leaves the+ // chat exactly where it was.+ //+ // A14 fourth review moved it out of this file. It used to be a variable+ // up at the top of this module, which held the Installed card and+ // nothing else, while the picker guarded the same engine with its own+ // component state. Two doors, one llama-server, one bolt now+ // (api/lu-engine-swap-lock).+ //+ // And it says so. The click used to return in silence, which reads as a+ // dead button and gets clicked again.+ if (!tryAcquireLuEngineSwap()) {+ useLuEngineSwitchStore.getState().announce(LU_ENGINE_SWAP_BUSY_NOTE)+ return+ }switched = ensureLuEngineIsChatProvider()if (switched) useLuEngineSwitchStore.getState().announce(LU_ENGINE_SWITCH_NOTE)}@@ -537,7 +544,6 @@ export function useModels() {// 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 = trueconst sayItFailed = (reason: unknown) => {const line = luEngineStartFailureNote(name, reason)useLuEngineSwitchStore.getState()@@ -550,7 +556,14 @@ export function useModels() {// 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 })+ .finally(() => { if (isLuRow) releaseLuEngineSwap() })+ } else if (isLuRow) {+ // Nothing was started, so nothing will release the bolt in a finally.+ // Unreachable today (an LU row that got this far has just been given the+ // slot by ensureLuEngineIsChatProvider, and its name carries the openai+ // prefix the check reads), and left here because an unreleased bolt+ // costs the user his card until the 60 s limit runs out.+ releaseLuEngineSwap()}}, [setActiveModel])