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(engine): defer the two other unguarded local unloads next to the LU Engine stop

purple0437612d2bfe
diff --git a/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts b/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
index 933ab5a3..ec54657c 100644
--- a/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
+++ b/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
@@ -10,8 +10,16 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'
* (`lib/cloud-offload-defer.ts`) bewachte bis jetzt nur AppShells eigenen
* `offload_local_models`-Aufruf, nicht diesen hier.
*
+ * Auflage 1.1 (lu-301/bau/review-offload2.md): dieselbe Funktion hatte ZWEI
+ * weitere unbewachte Nachbarzweige auf dem selben Klick: `unloadLmStudioModel`
+ * und Ollamas `unloadModel`. Alle drei laufen jetzt durch EINEN Helfer
+ * (`deferLocalUnload`), hier je einzeln getestet.
+ *
* Dieser Test faehrt den ECHTEN `modelStore` gegen den ECHTEN
- * `generationStore`, nur `backendCall` ist gemockt (kein Tauri-Invoke).
+ * `generationStore` und die ECHTE `isLmStudioProvider` (Auflage 1.5: der
+ * Mock war unnoetig, die Funktion ist rein). Nur `backendCall` und die
+ * Provider-Aufrufe selbst (`unloadModel`, `unloadLmStudioModel`) sind
+ * gemockt (kein Tauri-Invoke, kein echtes Netzwerk).
*
* Lauf: npx vitest run src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
*/
@@ -30,9 +38,6 @@ vi.mock('../../api/ollama', () => ({
vi.mock('../../api/lmstudio', () => ({
unloadLmStudioModel: (...a: unknown[]) => unloadLmStudioModel(...a),
}))
-vi.mock('../../lib/hf-to-provider', () => ({
- isLmStudioProvider: (n?: string) => (n || '').includes('LM Studio'),
-}))
import { useModelStore } from '../modelStore'
import { useGenerationStore } from '../generationStore'
@@ -42,23 +47,30 @@ const builtin = (name: string): AIModel =>
({ name: `openai::${name}`, model: name, size: 1, type: 'text', provider: 'openai', providerName: 'LU Engine' } as unknown as AIModel)
const cloudModel = (name: string): AIModel =>
({ name, model: name, size: 1, type: 'text', provider: 'anthropic', providerName: 'Anthropic' } as unknown as AIModel)
+const lmsModel = (name: string): AIModel =>
+ ({ name: `openai::${name}`, model: name, size: 1, type: 'text', provider: 'openai', providerName: 'LM Studio' } as unknown as AIModel)
+const ollamaModel = (name: string): AIModel =>
+ ({ name, model: name, size: 1, type: 'text' } as unknown as AIModel)
const CONV_ID = 'conv-with-a-running-local-turn'
+const CONV_ID_2 = 'a-second-conv-with-its-own-local-turn'
const RUN_TOKEN = {}
-
-describe('modelStore.setActiveModel defers stop_bundled_engine while a local run is booked', () => {
- beforeEach(() => {
- backendCall.mockClear()
- useModelStore.setState({
- models: [builtin('qwenA'), cloudModel('claude-x')],
- activeModel: 'openai::qwenA',
- })
- useGenerationStore.setState({ runs: {}, generating: {}, aborters: {} })
+const RUN_TOKEN_2 = {}
+
+beforeEach(() => {
+ backendCall.mockClear()
+ unloadModel.mockClear()
+ unloadLmStudioModel.mockClear()
+ useModelStore.setState({
+ models: [builtin('qwenA'), builtin('qwenB'), cloudModel('claude-x'), lmsModel('mistral'), ollamaModel('llama3')],
+ activeModel: 'openai::qwenA',
})
+ useGenerationStore.setState({ runs: {}, generating: {}, aborters: {} })
+})
+describe('the LU Engine stop (built-in -> non-built-in)', () => {
it('does NOT stop the engine while a local run is booked, and fires exactly once after it ends', () => {
useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
-
// The mode-switch reselect AppShell.tsx does on entering Cloud.
useModelStore.getState().setActiveModel('claude-x')
@@ -86,4 +98,124 @@ describe('modelStore.setActiveModel defers stop_bundled_engine while a local run
expect(backendCall).not.toHaveBeenCalledWith('stop_bundled_engine')
})
+
+ // Auflage 1.3(a): a run that ends through its error path books and ends
+ // the SAME way a normal run does: generationStore.runs has no separate
+ // "failed" state, run-slot.ts's `finally` calls `endRun` regardless of
+ // outcome (documented in offload2.md). This test pins that the deferred
+ // stop does not care WHY the run ended, only THAT it did.
+ it('Auflage 1.3(a): a run that ends via its error path (finally, not success) still releases the deferred stop', () => {
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+ useModelStore.getState().setActiveModel('claude-x')
+ expect(backendCall).not.toHaveBeenCalledWith('stop_bundled_engine')
+
+ // run-slot.ts's `finally` calls endRun on every exit path, error
+ // included; there is nothing else to simulate an error exit with here.
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(backendCall).toHaveBeenCalledWith('stop_bundled_engine')
+ })
+
+ // Auflage 1.3(c): a second, unrelated local run overlaps the first. The
+ // stop must wait for BOTH, not just the one that happened to be booked
+ // when Cloud was clicked.
+ it('Auflage 1.3(c): two overlapping local runs, the stop waits for the LAST one to end', () => {
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+ useGenerationStore.getState().bookRun(CONV_ID_2, 'local', RUN_TOKEN_2)
+ useModelStore.getState().setActiveModel('claude-x')
+
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(backendCall).not.toHaveBeenCalledWith('stop_bundled_engine')
+
+ useGenerationStore.getState().endRun(CONV_ID_2, RUN_TOKEN_2)
+ expect(backendCall).toHaveBeenCalledWith('stop_bundled_engine')
+ })
+
+ // Auflage 1.3(b) / 1.4: switching Cloud/Local/Cloud during the SAME long
+ // local run used to register a SEPARATE pending stop each time it entered
+ // Cloud with a built-in model active, each harmless alone
+ // (stop_bundled_engine is idempotent), but the bauer's report claimed
+ // "exactly once" and that only held for a single switch. `deferLocalUnload`
+ // dedupes by target, so the count stays exactly one no matter how many
+ // times the user flips before the run ends.
+ it('Auflage 1.4: Cloud/Local/Cloud twice during one run still stops the engine exactly once', () => {
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+
+ useModelStore.getState().setActiveModel('claude-x') // Cloud: schedules a stop
+ useModelStore.getState().setActiveModel('openai::qwenA') // Local: no new schedule (prevIsBuiltin is false here)
+ useModelStore.getState().setActiveModel('claude-x') // Cloud again: prevIsBuiltin is true again, schedules a SECOND stop pre-fix
+
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+
+ expect(backendCall.mock.calls.filter((c) => c[0] === 'stop_bundled_engine')).toHaveLength(1)
+ })
+})
+
+describe('the LM Studio unload (Auflage 1.1)', () => {
+ it('does NOT unload while a local run is booked, and fires exactly once after it ends', () => {
+ useModelStore.setState({ activeModel: 'openai::mistral' })
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+
+ useModelStore.getState().setActiveModel('claude-x')
+ expect(unloadLmStudioModel).not.toHaveBeenCalled()
+
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(unloadLmStudioModel).toHaveBeenCalledWith('mistral')
+ expect(unloadLmStudioModel).toHaveBeenCalledTimes(1)
+ })
+
+ it('Gegenprobe: without an active local run, the unload fires immediately (unchanged behaviour)', () => {
+ useModelStore.setState({ activeModel: 'openai::mistral' })
+ useModelStore.getState().setActiveModel('claude-x')
+ expect(unloadLmStudioModel).toHaveBeenCalledWith('mistral')
+ })
+
+ it('Gegenprobe: picking the SAME LM Studio model again before the run ends means NO unload ever fires', () => {
+ useModelStore.setState({ activeModel: 'openai::mistral' })
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+
+ useModelStore.getState().setActiveModel('claude-x') // defers
+ useModelStore.getState().setActiveModel('openai::mistral') // picked again
+
+ unloadLmStudioModel.mockClear()
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(unloadLmStudioModel).not.toHaveBeenCalled()
+ })
+})
+
+describe('the Ollama unload (Auflage 1.1)', () => {
+ it('does NOT unload while a local run is booked, and fires exactly once after it ends', () => {
+ useModelStore.setState({ activeModel: 'llama3' })
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+
+ useModelStore.getState().setActiveModel('claude-x')
+ expect(unloadModel).not.toHaveBeenCalled()
+
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(unloadModel).toHaveBeenCalledWith('llama3')
+ expect(unloadModel).toHaveBeenCalledTimes(1)
+ })
+
+ it('Gegenprobe: without an active local run, the unload fires immediately (unchanged behaviour)', () => {
+ useModelStore.setState({ activeModel: 'llama3' })
+ useModelStore.getState().setActiveModel('claude-x')
+ expect(unloadModel).toHaveBeenCalledWith('llama3')
+ })
+
+ it('Gegenprobe: picking the SAME Ollama model again before the run ends means NO unload ever fires', () => {
+ useModelStore.setState({ activeModel: 'llama3' })
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+
+ useModelStore.getState().setActiveModel('claude-x') // defers unloading llama3
+ // Picking llama3 again routes THIS call's own prev ('claude-x', a bare
+ // name with no '::') through the same bare-Ollama branch, scheduling an
+ // unrelated deferred unload of 'claude-x' under its own target key, a
+ // pre-existing quirk (a cloud model name with no provider prefix is
+ // indistinguishable from a bare Ollama one) this test does not touch.
+ // The assertion below is scoped to llama3, not "unloadModel never runs".
+ useModelStore.getState().setActiveModel('llama3')
+
+ unloadModel.mockClear()
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(unloadModel).not.toHaveBeenCalledWith('llama3')
+ })
})
diff --git a/src/stores/modelStore.ts b/src/stores/modelStore.ts
index be48707e..2da6e75c 100644
--- a/src/stores/modelStore.ts
+++ b/src/stores/modelStore.ts
@@ -31,6 +31,45 @@ import { ensureBuiltinEngineAlive, builtinSlotSwitchedOff } from '../api/builtin
import { isBuiltinEngineEntry, type InstalledModelLike } from '../lib/lmstudio-match'
import type { ProviderId } from '../api/providers/types'
+/**
+ * B6 followup (Auflage 1.1, lu-301/bau/review-offload2.md): `stop_bundled_engine`
+ * was not the only unguarded stop in `setActiveModel`. `unloadLmStudioModel`
+ * and Ollama's `unloadModel` sit right next to it, in the SAME function, fired
+ * by the SAME Cloud-switch click (`AppShell.tsx`'s mode-switch reselect calls
+ * `setActiveModel` on every entry into Cloud), and both target backends
+ * `run-lane-of-model.ts` counts as the LOCAL lane. All three now go through
+ * this one helper instead of three near-identical copies of "defer, then
+ * recheck at fire time".
+ *
+ * `target` dedupes: a second call for the SAME target cancels the FIRST
+ * pending one before scheduling its own, so switching Cloud/Local/Cloud
+ * repeatedly during one long local run leaves exactly one pending unload
+ * per target, not one per switch (Auflage 1.4: they used to stack, each
+ * harmless on its own since `stop_bundled_engine` is idempotent, but the
+ * bauer's own report claimed "exactly once" and that was only true for a
+ * single switch).
+ *
+ * `stillWanted` is read at FIRE TIME, not at scheduling time: the user may
+ * have switched back to the model (or, for the shared LU Engine, to ANY
+ * built-in model: the engine serves one at a time regardless of which)
+ * while this was waiting for the local lane to free up. Returning true skips
+ * the unload entirely.
+ */
+const pendingLocalUnloads = new Map<string, () => void>()
+
+function deferLocalUnload(target: string, stillWanted: () => boolean, unload: () => void): void {
+ pendingLocalUnloads.get(target)?.()
+ pendingLocalUnloads.delete(target)
+ let fired = false
+ const cancel = offloadWhenLocalLaneFree(useGenerationStore, () => {
+ fired = true
+ pendingLocalUnloads.delete(target)
+ if (stillWanted()) return
+ unload()
+ })
+ if (!fired) pendingLocalUnloads.set(target, cancel)
+}
+
export interface PullState {
progress: PullProgress
controller: AbortController
@@ -271,8 +310,19 @@ export const useModelStore = create<ModelState>()(
!!prevModel && 'providerName' in prevModel && isLuEngineName(prevModel.providerName)
if (prevIsLms) {
const bareKey = prev.replace(/^[^:]+::/, '') // strip LU's routing prefix
- unloadLmStudioModel(bareKey).catch((e) =>
- log.warn('[modelStore] failed to unload previous LM Studio model', { model: prev, err: e }),
+ // B6 (klaerung-n7.md) / Auflage 1.1 (review-offload2.md): this LM
+ // Studio unload sits in the SAME function as the LU Engine stop
+ // below and fires on the SAME Cloud-switch click, at a model
+ // `run-lane-of-model.ts` counts as local: it used to run
+ // unguarded while the built-in-engine branch right next to it
+ // already had the fix. `stillWanted` here means "the user picked
+ // this exact model again before the local lane freed up".
+ deferLocalUnload(
+ `lms:${bareKey}`,
+ () => get().activeModel === prev,
+ () => unloadLmStudioModel(bareKey).catch((e) =>
+ log.warn('[modelStore] failed to unload previous LM Studio model', { model: prev, err: e }),
+ ),
)
} else if (prevIsBuiltin) {
const nextModel = get().models.find((m) => m.name === name)
@@ -292,21 +342,28 @@ export const useModelStore = create<ModelState>()(
// Local or picked another built-in model themselves (this same
// function runs again for that), so the stop must look at the
// CURRENT active model, not the one that was picked when this
- // closure was created.
- offloadWhenLocalLaneFree(useGenerationStore, () => {
- const stillActiveModel = get().activeModel
- const stillActiveEntry = stillActiveModel
- ? get().models.find((m) => m.name === stillActiveModel)
- : undefined
- const stillNonBuiltin =
- !stillActiveEntry ||
- !('providerName' in stillActiveEntry) ||
- !isLuEngineName(stillActiveEntry.providerName)
- if (!stillNonBuiltin) return
- backendCall('stop_bundled_engine').catch((e) =>
+ // closure was created. Every built-in model shares the ONE
+ // engine process, so the check is "is ANY built-in model active
+ // again", not just this exact one (a different built-in pick
+ // takes the swap branch below, on ITS OWN call, and must not be
+ // undone by a stop this call scheduled earlier).
+ deferLocalUnload(
+ 'builtin-engine',
+ () => {
+ const stillActiveModel = get().activeModel
+ const stillActiveEntry = stillActiveModel
+ ? get().models.find((m) => m.name === stillActiveModel)
+ : undefined
+ return (
+ !!stillActiveEntry &&
+ 'providerName' in stillActiveEntry &&
+ isLuEngineName(stillActiveEntry.providerName)
+ )
+ },
+ () => backendCall('stop_bundled_engine').catch((e) =>
log.warn('[modelStore] failed to stop the LU Engine on switch-away', { err: e }),
- )
- })
+ ),
+ )
} else if (name) {
// built-in → DIFFERENT built-in: llama-server serves exactly ONE
// gguf and ignores the request's model field, and the send-path
@@ -329,8 +386,20 @@ export const useModelStore = create<ModelState>()(
)
}
} else if (!prev.includes('::')) {
- unloadModel(prev).catch((e) =>
- log.warn('[modelStore] failed to unload previous model', { model: prev, err: e }),
+ // Same guard, same reason as the LM Studio branch above (Auflage
+ // 1.1): a bare Ollama name is local too (run-lane-of-model.ts),
+ // and this fires on the same Cloud-switch click. Whether Ollama's
+ // own `keep_alive: 0` waits out a request already in flight on
+ // that model is the SERVER's call, not observable from this repo
+ // (researched, not measured, in review-offload2.md); deferring
+ // here costs nothing either way and closes the loophole without
+ // relying on an unverified assumption about Ollama's scheduler.
+ deferLocalUnload(
+ `ollama:${prev}`,
+ () => get().activeModel === prev,
+ () => unloadModel(prev).catch((e) =>
+ log.warn('[modelStore] failed to unload previous model', { model: prev, err: e }),
+ ),
)
}
},