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(backends): der verdraengte Motor gibt seinen Speicher frei
purpledf4854e713e6
diff --git a/src/lib/__tests__/displaced-engine-frees-its-memory.test.ts b/src/lib/__tests__/displaced-engine-frees-its-memory.test.tsnew file mode 100644index 00000000..075c47d5--- /dev/null+++ b/src/lib/__tests__/displaced-engine-frees-its-memory.test.ts@@ -0,0 +1,176 @@+/**+ * Nebenbefund 2 of the R12/R13 re-measure on the real 2.6.7 Windows build+ * (2026-08-30, ergebnis-r1213-nachmessung.md):+ *+ * "Der eingebaute Motor laeuft weiter, waehrend ein fremder Anbieter den+ * Slot haelt. Nach dem Anlegen von Jan blieb lu-llama-server.exe PID 7516+ * am Leben, samt geladenem Modell im Speicher. Erst ein App-Neustart+ * raeumt ihn weg: nach dem Neustart mit Jan im Slot startete gar kein+ * lu-llama-server mehr. Kein Fehler, aber RAM und VRAM bleiben bis zum+ * Neustart belegt, obwohl der Motor nichts mehr zu tun hat."+ *+ * The app already agreed the engine was finished: it does not start one at all+ * when Jan holds the slot at launch. Only the running one was never told.+ *+ * Round 7 answered the same question for the window's X (the model stayed in+ * VRAM after the window went to the tray) by routing the hide through+ * `offload_local_models`, the call the switch into Cloud mode makes, after a+ * grace period. This is that answer applied one door further along, with the+ * same call and the same grace period.+ *+ * Run: npx vitest run src/lib/__tests__/displaced-engine-frees-its-memory.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const backendCall = vi.fn(async (..._args: unknown[]) => ({}))+vi.mock('../../api/backend', () => ({+ backendCall: (...a: unknown[]) => backendCall(...a),+ isTauri: () => true,+}))++import {+ builtinHoldsLocalSlot,+ builtinSlotOffloadDecision,+ onLocalSlotChanged,+ __resetBuiltinSlotOffloadForTests,+ BUILTIN_SLOT_OFFLOAD_GRACE_MS,+} from '../builtin-slot-eviction'++const here = dirname(fileURLToPath(import.meta.url))+const repo = resolve(here, '../../..')+const read = (rel: string) => readFileSync(resolve(repo, rel), 'utf8')++/** The shipped state: the app's own engine serving the shared local slot. */+const BUILTIN = { enabled: true, managed: true }+/** What Add Provider, entry Jan, writes over it. */+const JAN = { enabled: true, managed: false }++beforeEach(() => {+ vi.useFakeTimers()+ backendCall.mockClear()+ __resetBuiltinSlotOffloadForTests()+})+afterEach(() => {+ __resetBuiltinSlotOffloadForTests()+ vi.useRealTimers()+})++describe('THE FIX: the engine that loses the slot lets go of its model', () => {+ it('the measured press releases it instead of holding it until a restart', () => {+ onLocalSlotChanged(BUILTIN, JAN)+ expect(backendCall).not.toHaveBeenCalled() // grace period first+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS)+ expect(backendCall).toHaveBeenCalledWith('offload_local_models', { includeComfyui: false })+ })++ it('it is the call the cloud switch makes, not a second mechanism', () => {+ const shell = read('src/components/layout/AppShell.tsx')+ expect(shell).toMatch(/backendCall\('offload_local_models'\)/)+ const evict = read('src/lib/builtin-slot-eviction.ts')+ expect(evict).toMatch(/backendCall\('offload_local_models', \{ includeComfyui: false \}\)/)+ // and it does NOT reach for a private unload path of its own+ expect(evict).not.toMatch(/stop_bundled_engine/)+ })++ it('the ComfyUI checkpoint is left alone, a chat slot is none of its business', () => {+ onLocalSlotChanged(BUILTIN, JAN)+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS)+ expect(backendCall.mock.calls[0][1]).toEqual({ includeComfyui: false })+ })++ it('a user who swaps straight back pays nothing, the same grace round 7 built', () => {+ onLocalSlotChanged(BUILTIN, JAN)+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS / 2)+ onLocalSlotChanged(JAN, BUILTIN) // Enable on the standby card+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS * 2)+ expect(backendCall).not.toHaveBeenCalled()+ })++ it('and a second change cannot let an older timer fire under it', () => {+ onLocalSlotChanged(BUILTIN, JAN)+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS - 1)+ onLocalSlotChanged(JAN, BUILTIN)+ onLocalSlotChanged(BUILTIN, JAN)+ vi.advanceTimersByTime(2) // the FIRST timer's moment has come and gone+ expect(backendCall).not.toHaveBeenCalled()+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS)+ expect(backendCall).toHaveBeenCalledTimes(1)+ })++ it('Disable on the engine itself frees it too, it is the same loss of the slot', () => {+ onLocalSlotChanged(BUILTIN, { enabled: false, managed: true })+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS)+ expect(backendCall).toHaveBeenCalledWith('offload_local_models', { includeComfyui: false })+ })++ it('the wiring: every write to the shared slot asks the question, once', () => {+ const store = read('src/stores/providerStore.ts')+ expect(store).toMatch(/import \{ onLocalSlotChanged \} from '\.\.\/lib\/builtin-slot-eviction'/)+ expect(store).toMatch(/if \(id === 'openai'\) onLocalSlotChanged\(before, get\(\)\.providers\.openai\)/)+ // resetProvidersToDefaults writes the slot without going through setProviderConfig+ expect(store).toMatch(/onLocalSlotChanged\(before, get\(\)\.providers\.openai\)\n\s*\},/)+ })+})++describe('NEGATIVE CONTROL: nobody else loses their model over this', () => {+ it('a takeover between two FOREIGN backends frees nothing', () => {+ // Jan replaced by LM Studio: no lu-llama-server was running, and evicting+ // the user's Ollama residents for it would be a fresh bug, not a fix.+ onLocalSlotChanged(JAN, { enabled: true, managed: false })+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS * 2)+ expect(backendCall).not.toHaveBeenCalled()+ })++ it('an unrelated edit on the slot the engine still holds frees nothing', () => {+ // Endpoint typed, API key saved, Test pressed: the engine keeps the slot.+ onLocalSlotChanged(BUILTIN, BUILTIN)+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS * 2)+ expect(backendCall).not.toHaveBeenCalled()+ })++ it('handing the slot BACK to the engine never unloads it', () => {+ onLocalSlotChanged(JAN, BUILTIN)+ vi.advanceTimersByTime(BUILTIN_SLOT_OFFLOAD_GRACE_MS * 2)+ expect(backendCall).not.toHaveBeenCalled()+ })++ it('the rule itself, read without a timer', () => {+ expect(builtinHoldsLocalSlot(BUILTIN)).toBe(true)+ expect(builtinHoldsLocalSlot(JAN)).toBe(false)+ expect(builtinHoldsLocalSlot({ enabled: false, managed: true })).toBe(false)+ expect(builtinHoldsLocalSlot(null)).toBe(false)++ expect(builtinSlotOffloadDecision(BUILTIN, JAN)).toBe('schedule')+ expect(builtinSlotOffloadDecision(JAN, BUILTIN)).toBe('cancel')+ expect(builtinSlotOffloadDecision(BUILTIN, BUILTIN)).toBe('cancel')+ expect(builtinSlotOffloadDecision(JAN, JAN)).toBe('none')+ })++ it('the grace period is a real wait and not a coffee break', () => {+ // Same bracket round 7 put on HIDE_OFFLOAD_GRACE: a zero would unload on+ // every stray click, a very long one would keep the finding alive.+ expect(BUILTIN_SLOT_OFFLOAD_GRACE_MS).toBeGreaterThanOrEqual(5_000)+ expect(BUILTIN_SLOT_OFFLOAD_GRACE_MS).toBeLessThanOrEqual(120_000)+ })++ it('the engine still comes back by itself, so nothing was thrown away', () => {+ // The lazy reload this leans on is the one a Create render already leans+ // on, and it predates this change.+ const ensure = read('src/api/builtin-ensure.ts')+ expect(ensure).toMatch(/offload_local_models/)+ expect(ensure).toMatch(/export async function ensureBuiltinEngineAlive/)+ })++ it('round 7 keeps its own wiring on the window X', () => {+ const main = read('src-tauri/src/main.rs')+ expect(main).toMatch(/offload_local_models_blocking\(&state, Some\(true\)\)/)+ expect(main).toMatch(/should_offload_after_hide/)+ })++ it('no em dash in the new copy', () => {+ expect(read('src/lib/builtin-slot-eviction.ts')).not.toMatch(/[–—]/)+ })+})diff --git a/src/lib/builtin-slot-eviction.ts b/src/lib/builtin-slot-eviction.tsnew file mode 100644index 00000000..629801a0--- /dev/null+++ b/src/lib/builtin-slot-eviction.ts@@ -0,0 +1,123 @@+/**+ * What happens to the built-in engine's RAM and VRAM when it loses the shared+ * local slot.+ *+ * Nebenbefund 2 of the R12/R13 re-measure on the real 2.6.7 Windows build+ * (2026-08-30, ergebnis-r1213-nachmessung.md):+ *+ * "Der eingebaute Motor laeuft weiter, waehrend ein fremder Anbieter den+ * Slot haelt. Nach dem Anlegen von Jan blieb lu-llama-server.exe PID 7516+ * am Leben, samt geladenem Modell im Speicher. Erst ein App-Neustart+ * raeumt ihn weg: nach dem Neustart mit Jan im Slot startete gar kein+ * lu-llama-server mehr."+ *+ * The same shape as round 7's close-to-tray finding, one door further along:+ * the app agrees the engine has nothing left to do, and the model sits in+ * memory anyway until the process is restarted. Round 7 answered it by routing+ * the hide through `offload_local_models`, the call the switch into Cloud mode+ * already made, after a short grace period so a mis-click costs nothing. This+ * is the same answer for the same question, so it is the same call and the same+ * grace period, not a second mechanism.+ *+ * The trigger is narrow on purpose. Only a slot the app's OWN engine was+ * holding can leave a `lu-llama-server` behind, so only that transition fires:+ * LM Studio replacing Jan frees nothing of ours and must not evict anybody's+ * Ollama residents for nothing.+ *+ * Nothing is lost by unloading. Everything comes back lazily on first use, the+ * way `builtin-ensure.ts` already revives the engine after a Create render did+ * exactly this call.+ */++import { backendCall, isTauri } from '../api/backend'+import { log } from './logger'++/** The part of the `openai` slot this decision reads. */+export interface BuiltinSlotView {+ enabled: boolean+ /** True only for the app's own bundled llama.cpp engine. */+ managed?: boolean+}++/**+ * Mis-click insurance, same idea and same length as round 7's+ * `HIDE_OFFLOAD_GRACE`: swap the slot away and straight back and nothing was+ * ever unloaded.+ */+export const BUILTIN_SLOT_OFFLOAD_GRACE_MS = 30_000++/** Is the app's own engine the backend serving the shared local slot. */+export function builtinHoldsLocalSlot(slot: BuiltinSlotView | null | undefined): boolean {+ return !!slot && slot.enabled === true && slot.managed === true+}++/**+ * What the slot change means for the engine's memory.+ *+ * 'schedule' the engine just lost the slot, start the grace timer+ * 'cancel' it holds the slot again, a pending unload is void+ * 'none' nothing about our engine changed+ *+ * Pure, so the rule can be read without a timer or a backend.+ */+export function builtinSlotOffloadDecision(+ before: BuiltinSlotView | null | undefined,+ after: BuiltinSlotView | null | undefined,+): 'schedule' | 'cancel' | 'none' {+ const had = builtinHoldsLocalSlot(before)+ const has = builtinHoldsLocalSlot(after)+ if (has) return 'cancel'+ return had ? 'schedule' : 'none'+}++// The pending unload. A generation counter rather than a bare handle for the+// same reason the Rust side keeps one: a timer whose grace period belongs to an+// older change must not fire under a newer one.+let pending: ReturnType<typeof setTimeout> | null = null+let generation = 0++/** Drop a pending unload without performing it. */+function cancelPending(): void {+ generation+++ if (pending !== null) {+ clearTimeout(pending)+ pending = null+ }+}++/**+ * Wire the decision to the call. Safe to invoke on every write to the `openai`+ * slot: it does nothing unless the app's own engine actually lost the slot, and+ * nothing at all outside the desktop build.+ *+ * `includeComfyui: false` for the same reason a local render passes it: the+ * image checkpoint has no part in a chat backend change, and freeing it here+ * would buy a slow reload on the next generate for nothing. That is the flag+ * the Create hand-off has always used.+ */+export function onLocalSlotChanged(+ before: BuiltinSlotView | null | undefined,+ after: BuiltinSlotView | null | undefined,+): void {+ const decision = builtinSlotOffloadDecision(before, after)+ if (decision === 'none') return+ if (decision === 'cancel') {+ cancelPending()+ return+ }+ if (!isTauri()) return+ cancelPending()+ const mine = generation+ pending = setTimeout(() => {+ if (mine !== generation) return+ pending = null+ backendCall('offload_local_models', { includeComfyui: false })+ .then(() => log.info('[builtin-slot] engine lost the local slot, released its model'))+ .catch((e) => log.warn('[builtin-slot] could not release the displaced engine', { err: e }))+ }, BUILTIN_SLOT_OFFLOAD_GRACE_MS)+}++/** Test-only: forget a pending unload so tests stay isolated. */+export function __resetBuiltinSlotOffloadForTests(): void {+ cancelPending()+}diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.tsindex 3106e094..fcc7dd26 100644--- a/src/stores/providerStore.ts+++ b/src/stores/providerStore.ts@@ -9,6 +9,7 @@ import { create } from 'zustand'import { persist } from 'zustand/middleware'import type { ProviderId, ProviderConfig } from '../api/providers/types'import { clearProviderCache } from '../api/providers/registry'+import { onLocalSlotChanged } from '../lib/builtin-slot-eviction'import { secretGet, secretSet, secretDelete } from '../api/backend'import { CLOUD_BASE } from '../api/cloud/config'@@ -136,6 +137,7 @@ export const useProviderStore = create<ProviderState>()(setHideBackendSelector: (hide) => set({ hideBackendSelector: hide }),setProviderConfig: (id, updates) => {+ const before = get().providers[id]set((state) => ({providers: {...state.providers,@@ -143,6 +145,12 @@ export const useProviderStore = create<ProviderState>()(},}))clearProviderCache() // invalidate cached clients+ // Every route that moves the shared local slot comes through here (Add+ // Provider, Enable on the standby card, Remove, Disable, onboarding), so+ // the memory question is asked here, once. R12/R13 measured the answer+ // it used to get: Jan takes the slot, lu-llama-server keeps PID and+ // model in RAM until the app is restarted. See lib/builtin-slot-eviction.+ if (id === 'openai') onLocalSlotChanged(before, get().providers.openai)},setProviderApiKey: (id, key) => {@@ -182,12 +190,14 @@ export const useProviderStore = create<ProviderState>()(},resetProvider: (id) => {+ const before = get().providers[id]set((state) => ({providers: {...state.providers,[id]: DEFAULT_PROVIDERS[id],},}))+ if (id === 'openai') onLocalSlotChanged(before, get().providers.openai)if (keychainReady) {void secretDelete(id).catch(() => { /* vault delete best-effort */ })}@@ -195,6 +205,7 @@ export const useProviderStore = create<ProviderState>()(},resetProvidersToDefaults: () => {+ const before = get().providers.openaiset((state) => {const next = {} as Record<ProviderId, ProviderConfig>for (const id of Object.keys(DEFAULT_PROVIDERS) as ProviderId[]) {@@ -207,6 +218,9 @@ export const useProviderStore = create<ProviderState>()(return { providers: next }})clearProviderCache()+ // Reset hands the slot back to the app's own engine, which voids a+ // pending unload rather than causing one.+ onLocalSlotChanged(before, get().providers.openai)},hydrateProviderKeys: async () => {