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
feat(models): unload an unused chat model on Ollama and LM Studio too (#235)
purple4170d0cff76b
diff --git a/src-tauri/src/commands/install/lmstudio.rs b/src-tauri/src/commands/install/lmstudio.rsindex c31bd2e8..15949a29 100644--- a/src-tauri/src/commands/install/lmstudio.rs+++ b/src-tauri/src/commands/install/lmstudio.rs@@ -613,6 +613,7 @@ pub async fn lmstudio_load_model(contextLength: Option<u32>,timeout_ms: Option<u64>,call_id: Option<String>,+ ttlSeconds: Option<u32>,) -> Result<serde_json::Value, String> {// Registered here, before the blocking pool is asked for a thread, so a// cancel finds the load from its first moment on.@@ -624,13 +625,39 @@ pub async fn lmstudio_load_model(None => (CancellationToken::new(), None),};let deadline = Instant::now() + lms_limit(timeout_ms, LMS_LOAD_LIMIT);- let result = tokio::task::spawn_blocking(move || lmstudio_load_model_blocking(model, contextLength, deadline, &cancel))+ let result = tokio::task::spawn_blocking(move || lmstudio_load_model_blocking(model, contextLength, ttlSeconds, deadline, &cancel)).await.map_err(|e| format!("lmstudio_load_model task: {e}"));drop(guard);result?}+/// The arguments of `lms load`: `-c` for a context length, `--ttl` for the+/// idle time from Settings (GH #235), both only when set.+fn lms_load_args(model: &str, context_length: Option<u32>, ttl_seconds: Option<u32>) -> Vec<String> {+ let mut args = vec!["load".to_string(), model.to_string(), "-y".to_string()];+ if let Some(ctx) = context_length.filter(|c| *c > 0) {+ args.push("-c".into());+ args.push(ctx.to_string());+ }+ if let Some(ttl) = ttl_seconds.filter(|t| *t > 0) {+ args.push("--ttl".into());+ args.push(ttl.to_string());+ }+ args+}++/// True when `lms load` failed because it does not know `--ttl`.+fn lms_refused_ttl(end: &LmsEnd) -> bool {+ match end {+ LmsEnd::Exited { success: false, stdout, stderr } => {+ let text = format!("{stderr}\n{stdout}").to_lowercase();+ text.contains("ttl") && (text.contains("unknown") || text.contains("unexpected") || text.contains("unrecognized"))+ }+ _ => false,+ }+}+/// End the load that was started with this `call_id`. The `lms` process is/// killed and the load command answers with an error.#[tauri::command]@@ -643,6 +670,7 @@ pub fn lmstudio_cancel_load(call_id: String) -> Result<(), String> {fn lmstudio_load_model_blocking(model: String,contextLength: Option<u32>,+ ttlSeconds: Option<u32>,deadline: Instant,cancel: &CancellationToken,) -> Result<serde_json::Value, String> {@@ -682,17 +710,19 @@ fn lmstudio_load_model_blocking(Ok(LmsEnd::Exited { .. }) | Err(_) => {}}}- let ctx = contextLength.unwrap_or(0);- let ctx_str = ctx.to_string();- let mut args: Vec<&str> = vec!["load", model.as_str(), "-y"];- if ctx > 0 {- args.push("-c");- args.push(ctx_str.as_str());- }+ let args = lms_load_args(&model, contextLength, ttlSeconds);let mut cmd = crate::process_util::foreign_system_command(&lms);cmd.args(&args);- let end = run_lms(cmd, deadline, cancel)+ let mut end = run_lms(cmd, deadline, cancel).map_err(|e| format!("spawn lms load: {}", os_error::english(&e)))?;+ // GH #235: an `lms` older than the idle TTL (LM Studio 0.3.9) refuses+ // `--ttl`; the model then loads as before, without it.+ if ttlSeconds.is_some() && lms_refused_ttl(&end) {+ let mut cmd = crate::process_util::foreign_system_command(&lms);+ cmd.args(lms_load_args(&model, contextLength, None));+ end = run_lms(cmd, deadline, cancel)+ .map_err(|e| format!("spawn lms load: {}", os_error::english(&e)))?;+ }match end {LmsEnd::Cancelled => {eprintln!("[lmstudio_load_model] CANCELLED model='{}' ctx={:?}", model, contextLength);@@ -1240,3 +1270,32 @@ mod tests {assert!(lmstudio_chat_model_file("publisher/repo/tales-of-2024-q4.gguf"));}}++#[cfg(test)]+mod idle_ttl_tests {+ use super::{lms_load_args, lms_refused_ttl, LmsEnd};++ /// GH #235: the idle time from Settings reaches `lms load` as `--ttl`.+ #[test]+ fn a_set_idle_time_loads_with_lm_studios_ttl() {+ assert_eq!(lms_load_args("qwen", None, Some(1800)), ["load", "qwen", "-y", "--ttl", "1800"]);+ assert_eq!(lms_load_args("qwen", Some(8192), Some(600)), ["load", "qwen", "-y", "-c", "8192", "--ttl", "600"]);+ }++ #[test]+ fn negative_control_no_idle_time_loads_as_before() {+ assert_eq!(lms_load_args("qwen", None, None), ["load", "qwen", "-y"]);+ assert_eq!(lms_load_args("qwen", Some(0), Some(0)), ["load", "qwen", "-y"]);+ assert_eq!(lms_load_args("qwen", Some(4096), None), ["load", "qwen", "-y", "-c", "4096"]);+ }++ #[test]+ fn an_lms_that_does_not_know_ttl_is_told_apart_from_a_failed_load() {+ let old = LmsEnd::Exited { success: false, stdout: String::new(), stderr: "error: unknown option '--ttl'".into() };+ assert!(lms_refused_ttl(&old));+ let oom = LmsEnd::Exited { success: false, stdout: String::new(), stderr: "Failed to load model: out of memory".into() };+ assert!(!lms_refused_ttl(&oom));+ assert!(!lms_refused_ttl(&LmsEnd::TimedOut));+ assert!(!lms_refused_ttl(&LmsEnd::Exited { success: true, stdout: String::new(), stderr: String::new() }));+ }+}diff --git a/src/api/lmstudio.ts b/src/api/lmstudio.tsindex 01437166..5973c137 100644--- a/src/api/lmstudio.ts+++ b/src/api/lmstudio.ts@@ -7,6 +7,7 @@import { isLfm3Model, lmStudioRuntimeNote } from '../lib/lmstudio-runtime'import { backendCall } from './backend'import { callLimit, CallTimeoutError, type CallLimitOptions } from '../lib/call-limit'+import { lmsTtlArg } from '../lib/idle-unload'import { lmStudioReason } from '../lib/lmstudio-switch'import { log } from '../lib/logger'import { detailOf } from '../lib/error-text'@@ -167,6 +168,8 @@ export async function loadLmStudioModel(model: string, contextLength?: number, ocontextLength: window,timeoutMs: limitMs + BRIDGE_SLACK_MS,callId,+ // GH #235: the idle time from Settings, as LM Studio's own TTL.+ ...lmsTtlArg(),})await limit.race(bridge)} catch (e) {diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex d4aad21f..b109e138 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -7,6 +7,7 @@ import { oneEntryPerName } from "../lib/one-entry-per-name"import { isLocalTransportFailure, localBackendUnreachableMessage } from "../lib/local-backend-transport"import { ollamaWindowFor, type WindowChoice, type WindowUse } from "../lib/context-window"import { useSettingsStore } from "../stores/settingsStore"+import { ollamaKeepAlive } from "../lib/idle-unload"import { callLimit, CallTimeoutError, type CallLimitOptions } from "../lib/call-limit"import { clampContextWindow } from "../lib/number-limits"@@ -275,7 +276,7 @@ export async function reloadOllamaWithWindow(model: string, use: WindowUse): Proconst window = await limit.race(ollamaWindowOption(model, use))await localFetch(ollamaUrl("/generate"), {method: "POST",- body: JSON.stringify({ model, prompt: "", stream: false, keep_alive: "30m", options: window }),+ body: JSON.stringify({ model, prompt: "", stream: false, keep_alive: ollamaKeepAlive("30m"), options: window }),signal: limit.signal,timeoutMs: OLLAMA_LOAD_LIMIT_MS + PROXY_SLACK_MS,})@@ -559,7 +560,7 @@ export async function loadModel(name: string, options?: OllamaCallOptions): Promconst window = await limit.race(ollamaWindowOption(name))const res = await localFetch(ollamaUrl("/generate"), {method: "POST",- body: JSON.stringify({ model: name, prompt: "", stream: false, keep_alive: "10m", options: window }),+ body: JSON.stringify({ model: name, prompt: "", stream: false, keep_alive: ollamaKeepAlive("10m"), options: window }),signal: limit.signal,timeoutMs: limitMs + PROXY_SLACK_MS,})diff --git a/src/api/providers/__tests__/idle-unload-on-every-backend.test.ts b/src/api/providers/__tests__/idle-unload-on-every-backend.test.tsnew file mode 100644index 00000000..ba1d8bae--- /dev/null+++ b/src/api/providers/__tests__/idle-unload-on-every-backend.test.ts@@ -0,0 +1,156 @@+/**+ * GH #235 (Ducky-94): "free VRAM without restarting", an idle timer that+ * unloads the chat model. LU had it for the LU Engine only (engine_idle.rs).+ * The same setting now reaches Ollama as `keep_alive` and LM Studio as its+ * own idle TTL (`lms load --ttl`, `ttl` on a request), and it sits in a+ * section of its own under AI Backends, not inside the LU Engine section that+ * an Ollama user never sees. Unload all was already there.+ *+ * Run: npx vitest run src/api/providers/__tests__/idle-unload-on-every-backend.test.ts+ */+import { describe, it, expect, vi, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import type { ProviderConfig, ChatStreamChunk } from '../types'+import type { OpenAIChatRequest } from '../openai-provider'++const streamBody = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n'+type Init = { body?: string }+let sent: { url: string; body: OpenAIChatRequest }[]+let gets: string[]+let facts: Record<string, unknown>++function answer(url: string, init: Init | undefined): Response {+ if (typeof init?.body === 'string') {+ const body = JSON.parse(init.body) as OpenAIChatRequest+ sent.push({ url, body })+ if (body.stream) return new Response(streamBody, { status: 200 })+ return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { status: 200 })+ }+ gets.push(url)+ const hit = Object.keys(facts).sort((a, b) => b.length - a.length).find((suffix) => url.endsWith(suffix))+ return hit ? new Response(JSON.stringify(facts[hit]), { status: 200 }) : new Response('not found', { status: 404 })+}++async function setup(config: ProviderConfig, minutes: number, serverFacts: Record<string, unknown> = {}) {+ vi.resetModules()+ sent = []+ gets = []+ facts = serverFacts+ vi.doMock('../../backend', () => ({+ localFetch: vi.fn(async (url: string, init?: Init) => answer(url, init)),+ localFetchStream: vi.fn(async (url: string, init?: Init) => answer(url, init)),+ backendCall: vi.fn(),+ isPrivateOrLanHost: (host: string) => host === 'localhost' || host === '127.0.0.1',+ isDirectFetchAllowed: () => true,+ hostnameOf: (url: string) => new URL(url).hostname,+ ensureProxyAllowsHost: vi.fn(),+ isTauri: () => false,+ }))+ vi.doMock('../../builtin-ensure', () => ({+ ensureBuiltinEngineAlive: vi.fn(),+ explainDeadEngine: (e: unknown) => e,+ explainEngineTransportMessage: (m: string) => m,+ isManagedBuiltinSlot: () => false,+ }))+ const { useSettingsStore } = await import('../../../stores/settingsStore')+ useSettingsStore.getState().updateSettings({ engineIdleUnloadMinutes: minutes })+ const mod = await import('../openai-provider')+ return new mod.OpenAIProvider(config)+}++async function drain(gen: AsyncGenerator<ChatStreamChunk>) {+ for await (const _ of gen) { /* the fetch fires on the first next() */ }+}+const chatBody = () => sent.filter((s) => s.url.endsWith('/chat/completions')).map((s) => s.body)[0]++const local = (name: string, port: number): ProviderConfig => ({+ id: 'openai', name, apiKey: '', enabled: true, baseUrl: `http://localhost:${port}/v1`, isLocal: true,+})+const LM_STUDIO = local('LM Studio', 1234)+const KOBOLD = local('KoboldCpp', 5001)+const ENGINE: ProviderConfig = { ...local('LU Engine', 8127), baseUrl: 'http://127.0.0.1:8127/v1', managed: true }+const LMS_FACTS = { '/api/v1/models': { models: [{ type: 'llm', key: 'qwen3-8b' }] } }+const KOBOLD_FACTS = { '/api/extra/version': { result: 'KoboldCpp', version: '1.123' } }++afterEach(() => {+ vi.doUnmock('../../backend')+ vi.doUnmock('../../builtin-ensure')+ vi.restoreAllMocks()+ vi.resetModules()+})++describe('LM Studio gets the idle time as its own TTL', () => {+ it('on a chat request, in seconds', async () => {+ const p = await setup(LM_STUDIO, 15, LMS_FACTS)+ await drain(p.chatStream('qwen3-8b', [{ role: 'user', content: 'hi' }]))+ expect(chatBody().ttl).toBe(900)+ })++ it('on a tool call too', async () => {+ const p = await setup(LM_STUDIO, 60, LMS_FACTS)+ await p.chatWithTools('qwen3-8b', [{ role: 'user', content: 'hi' }], [])+ expect(chatBody().ttl).toBe(3600)+ })++ it('NEGATIVE CONTROL: with Never, no ttl and no extra question to the server', async () => {+ const p = await setup(LM_STUDIO, 0, LMS_FACTS)+ await drain(p.chatStream('qwen3-8b', [{ role: 'user', content: 'hi' }]))+ expect(chatBody()).not.toHaveProperty('ttl')+ expect(gets.filter((u) => u.endsWith('/api/v1/models'))).toEqual([])+ })++ it('NEGATIVE CONTROL: KoboldCpp and the LU Engine never see the field', async () => {+ let p = await setup(KOBOLD, 15, KOBOLD_FACTS)+ await drain(p.chatStream('m', [{ role: 'user', content: 'hi' }]))+ expect(chatBody()).not.toHaveProperty('ttl')+ p = await setup(ENGINE, 15)+ await drain(p.chatStream('m', [{ role: 'user', content: 'hi' }]))+ expect(chatBody()).not.toHaveProperty('ttl')+ })+})++describe('the values each backend gets', () => {+ it('Ollama: the minutes as keep_alive, and with Never what the call always sent', async () => {+ vi.resetModules()+ const { useSettingsStore } = await import('../../../stores/settingsStore')+ const { ollamaKeepAlive, lmStudioTtlSeconds, lmsTtlArg } = await import('../../../lib/idle-unload')+ useSettingsStore.getState().updateSettings({ engineIdleUnloadMinutes: 10 })+ expect(ollamaKeepAlive('30m')).toBe('10m')+ expect(lmStudioTtlSeconds()).toBe(600)+ expect(lmsTtlArg()).toEqual({ ttlSeconds: 600 })+ useSettingsStore.getState().updateSettings({ engineIdleUnloadMinutes: 0 })+ expect(ollamaKeepAlive('30m')).toBe('30m')+ expect(ollamaKeepAlive('10m')).toBe('10m')+ expect(lmStudioTtlSeconds()).toBeUndefined()+ expect(lmsTtlArg()).toEqual({})+ })+})++describe('every place that keeps a model loaded asks the setting', () => {+ const src = (p: string) => readFileSync(resolve(__dirname, '../../..', p), 'utf8')++ it('no Ollama request keeps a model warm with a fixed time any more', () => {+ for (const f of ['api/providers/ollama-provider.ts', 'lib/ollama-stream-tools.ts', 'api/ollama.ts']) {+ const text = src(f)+ expect(text, f).not.toMatch(/keep_alive:\s*['"]\d+m['"]/)+ expect(text, f).toMatch(/keep_alive:\s*ollamaKeepAlive\(/)+ }+ // The unload stays an unload.+ expect(src('api/ollama.ts')).toMatch(/keep_alive: 0 \}/)+ })++ it('every LM Studio load carries the TTL', () => {+ for (const f of ['api/lmstudio.ts', 'api/vram-handoff.ts']) {+ const calls = src(f).split("backendCall('lmstudio_load_model', {").slice(1).map((rest) => rest.slice(0, rest.indexOf('\n })')))+ expect(calls.length, f).toBeGreaterThan(0)+ for (const c of calls) expect(c, f).toMatch(/\.\.\.lmsTtlArg\(\)/)+ }+ })++ it('the setting is in its own section under AI Backends, no longer only in the LU Engine one', () => {+ const page = src('components/settings/SettingsPage.tsx')+ expect(page).toMatch(/<Section title="Unused models">\s*<IdleUnloadSetting \/>/)+ expect(src('components/settings/BuiltinEngineSettings.tsx')).not.toMatch(/engine-idle-unload/)+ })+})diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 740281e3..b2594f82 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -22,6 +22,7 @@ import { isLocalTransportFailure, localBackendUnreachableMessage } from '../../limport { parseNDJSONStream } from '../stream'import { chatFirstReplyMs } from '../../lib/chat-reply-timeout'import { useSettingsStore } from '../../stores/settingsStore'+import { ollamaKeepAlive } from '../../lib/idle-unload'import { idleAbortGuard, isStreamIdleTimeout, STREAM_IDLE_TIMEOUT_MS } from '../stream-idle'import { repairToolCallArgs, extractToolCallsFromContent } from '../../lib/tool-call-repair'import { applyTemplateContract } from './normalize-system'@@ -156,7 +157,7 @@ export class OllamaProvider implements ProviderClient {stream: true,// Audit A6: match the agent transport so a long turn never pays a// cold multi-GB reload after Ollama's 5-minute default idle unload.- keep_alive: '30m',+ keep_alive: ollamaKeepAlive('30m'),}// v2.4.6 Bug L: dropped hardcoded `num_gpu: 99`. Old code forced ALL@@ -329,7 +330,7 @@ export class OllamaProvider implements ProviderClient {tools,stream: false,// Audit A6: see chatStream above.- keep_alive: '30m',+ keep_alive: ollamaKeepAlive('30m'),}// v2.4.6 Bug L: see chatStream() above, same num_gpu:99 removal.diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 156d1a3d..c9eccd12 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -56,6 +56,7 @@ import {import type { ResolvedContextWindow } from '../../lib/context-source'import { contextWindowKey, storedWindow, capIsDerivable } from '../../lib/context-source'import { useSettingsStore } from '../../stores/settingsStore'+import { lmStudioTtlSeconds } from '../../lib/idle-unload'import { endpointKey, withExtraModels } from '../../lib/extra-model-ids'import { log } from '../../lib/logger'import { estimateTokens } from '../../lib/token-estimate'@@ -130,6 +131,9 @@ export interface OpenAIChatRequest {/** One rung of the effort ladder ('none' and 'minimal' mean off). Stepped* down, then deleted, by sendChat. */reasoning_effort?: string+ /** GH #235: LM Studio's idle time in seconds, only to LM Studio and only+ * with a time set in Settings. */+ ttl?: numberchat_template_kwargs?: Record<string, unknown>/** Think budget for the bundled engine only (llama-server b9949 reads it* per request, tools/server/server-common.cpp). Never sent anywhere else. */@@ -767,6 +771,18 @@ export class OpenAIProvider implements ProviderClient {* when the composer offered rungs for this model, so a model without them* keeps exactly the request it had before.*/+ /**+ * GH #235: the idle time from Settings, as LM Studio's own TTL, so a model+ * LM Studio loaded for this request (JIT) is unloaded after it too. Asked+ * only with a time set, and only of a local server that is not the LU+ * Engine (which has its own watch) or LU Cloud.+ */+ private async applyIdleTtl(body: OpenAIChatRequest): Promise<void> {+ const ttl = lmStudioTtlSeconds()+ if (!ttl || this.config.managed === true || !this.isLanBackend || this.config.id === 'lu-cloud') return+ if (await this.localEffortServer().catch(() => 'unknown') === 'lmstudio') body.ttl = ttl+ }+private async applyLocalEffortForm(body: OpenAIChatRequest, model: string, options?: ChatOptions): Promise<void> {if (options?.thinking !== true || !hasEffortLadder(options?.effortLevels)) returnif (body.reasoning_effort === undefined) return@@ -1155,6 +1171,7 @@ export class OpenAIProvider implements ProviderClient {if (tmplKwargs) body.chat_template_kwargs = tmplKwargsthis.applyThinkBudget(body, options)await this.applyLocalEffortForm(body, model, options)+ await this.applyIdleTtl(body)this.keepEffortOffEngineTopLevel(body)// Round 10, phone only: the caller ends the messages with a cut answer// and the engine of the phone goes on inside it. Absent on every other send.@@ -1402,6 +1419,7 @@ export class OpenAIProvider implements ProviderClient {if (tmplKwargs) body.chat_template_kwargs = tmplKwargsthis.applyThinkBudget(body, options)await this.applyLocalEffortForm(body, model, options)+ await this.applyIdleTtl(body)this.keepEffortOffEngineTopLevel(body)if (options?.jsonSchema && this.config.id !== 'lu-cloud') {body.response_format = { type: 'json_schema', json_schema: { name: 'answer', schema: options.jsonSchema } }diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex a3787218..88be2114 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -94,6 +94,7 @@ import { aspectFrame, parseAspectRatio } from '../lib/aspect-frame'import { buildWithFixups, wasDeclined } from '../lib/render-fixups'import { renderFixupDeps } from './render-fixup-deps'import { cancelFreeAfterRender, freeAfterRenderMode, scheduleFreeAfterRender } from '../lib/free-after-render'+import { lmsTtlArg } from '../lib/idle-unload'/*** Is the ComfyUI we are about to render on running on the processor?@@ -1374,6 +1375,7 @@ async function runHandoff(await backendCall('lmstudio_load_model', {model: evictedLms.id,...(evictedLms.contextLength ? { contextLength: evictedLms.contextLength } : {}),+ ...lmsTtlArg(),})} catch (e) {log.warn('vram_handoff.lms_reload_failed', { lmsModel: evictedLms.id, err: String(e) })@@ -2833,6 +2835,7 @@ async function restoreParked(): Promise<void> {await backendCall('lmstudio_load_model', {model: todo.lms.id,...(todo.lms.contextLength ? { contextLength: todo.lms.contextLength } : {}),+ ...lmsTtlArg(),})} catch (e) {log.warn('render_juggle.lms_reload_failed', { model: todo.lms.id, err: String(e instanceof Error ? e.message : e) })diff --git a/src/components/settings/BuiltinEngineSettings.tsx b/src/components/settings/BuiltinEngineSettings.tsxindex bc7a0aaf..afc4bdaf 100644--- a/src/components/settings/BuiltinEngineSettings.tsx+++ b/src/components/settings/BuiltinEngineSettings.tsx@@ -17,7 +17,6 @@ import { fitActionsOf } from '../../lib/engine-fit'import { FitActionButtons } from '../ui/FitActionButtons'import type { BuiltinEngineTuning } from '../../types/settings'import { isMacOS, isWindows } from '../../api/backend'-import { ENGINE_IDLE_UNLOAD_CHOICES, idleUnloadLabel, idleUnloadMinutes } from '../../lib/engine-idle-unload'import { engineOffloadWords, gpuLayersHint, gpuLayersLabel, gpuLayersTitle } from '../../lib/mac-pc-words'type KvType = BuiltinEngineTuning['cacheTypeK']@@ -52,7 +51,6 @@ function modelNameFromPath(path: string | null): string | null {*/export function BuiltinEngineSettings() {const tuning = useSettingsStore((s) => s.settings.builtinEngine)- const idleMinutes = useSettingsStore((s) => idleUnloadMinutes(s.settings.engineIdleUnloadMinutes))const updateSettings = useSettingsStore((s) => s.updateSettings)const [dirty, setDirty] = useState(false)@@ -283,24 +281,6 @@ export function BuiltinEngineSettings() {</div></label>- {/* Unload when unused (Discord 21.10.2026). Takes effect at once, no restart. */}- <div className="flex items-center justify-between">- <span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Unload the model when unused</span>- <select- value={idleMinutes}- onChange={(e) => updateSettings({ engineIdleUnloadMinutes: Number(e.target.value) })}- className={selectCls}- data-testid="engine-idle-unload"- >- {ENGINE_IDLE_UNLOAD_CHOICES.map((m) => (- <option key={m} value={m}>{idleUnloadLabel(m)}</option>- ))}- </select>- </div>- <div className="t-micro text-gray-500 leading-relaxed">- The engine keeps the model in memory so answers start at once. With a time set, it frees that memory after the model went unused that long; the next chat message loads it again, which takes a moment.- </div>-{/* Apply */}<div className="pt-2 border-t border-white/[0.06] space-y-1.5"><div className="flex items-center justify-between gap-2">diff --git a/src/components/settings/IdleUnloadSetting.tsx b/src/components/settings/IdleUnloadSetting.tsxnew file mode 100644index 00000000..5ed562d5--- /dev/null+++ b/src/components/settings/IdleUnloadSetting.tsx@@ -0,0 +1,35 @@+// GH #235: one setting frees the memory of a chat model nobody uses, on the+// LU Engine, Ollama and LM Studio alike. It used to sit in the LU Engine+// section, which only shows when LU runs its own engine.+import { useSettingsStore } from '../../stores/settingsStore'+import { ENGINE_IDLE_UNLOAD_CHOICES, idleUnloadLabel, idleUnloadMinutes } from '../../lib/engine-idle-unload'++const selectCls =+ 'px-1.5 py-0.5 rounded bg-transparent border border-gray-300 dark:border-white/8 text-[0.65rem] text-gray-700 dark:text-gray-300 focus:outline-none focus:border-white/20 [&>option]:bg-gray-900'++/** The note under the choice, so it says what Never means on each backend. */+export const IDLE_UNLOAD_NOTE =+ 'LU Engine, Ollama and LM Studio keep a model in memory so answers start at once. With a time set, each frees that memory after the model went unused that long; the next message loads it again, which takes a moment. With Never, the LU Engine and LM Studio keep the model and Ollama frees it after 30 minutes.'++export function IdleUnloadSetting() {+ const idleMinutes = useSettingsStore((s) => idleUnloadMinutes(s.settings.engineIdleUnloadMinutes))+ const updateSettings = useSettingsStore((s) => s.updateSettings)+ return (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Unload the chat model when unused</span>+ <select+ value={idleMinutes}+ onChange={(e) => updateSettings({ engineIdleUnloadMinutes: Number(e.target.value) })}+ className={selectCls}+ data-testid="engine-idle-unload"+ >+ {ENGINE_IDLE_UNLOAD_CHOICES.map((m) => (+ <option key={m} value={m}>{idleUnloadLabel(m)}</option>+ ))}+ </select>+ </div>+ <div className="t-micro text-gray-500 leading-relaxed">{IDLE_UNLOAD_NOTE}</div>+ </div>+ )+}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex f6eb8fa8..5eaa69a3 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -56,6 +56,7 @@ import { ComfyFolderTargets } from './ComfyFolderTargets'import { ChatbotImporter } from '../import/ChatbotImporter'import { ProviderSettings } from './ProviderConfig'import { BuiltinEngineSettings } from './BuiltinEngineSettings'+import { IdleUnloadSetting } from './IdleUnloadSetting'import { MlxMediaSettings } from './MlxMediaSettings'import { CustomNodesSettings } from './CustomNodesSettings'import { useProviderStore } from '../../stores/providerStore'@@ -2360,6 +2361,11 @@ export function SettingsPage() {<ProviderSettings /></Section>+ {/* GH #235: for every local backend, so not in the LU Engine section. */}+ <Section title="Unused models">+ <IdleUnloadSetting />+ </Section>+<Section title="Storage"><HowtoRow topic="storage" /><HowtoRow topic="gguf-file" />diff --git a/src/lib/__tests__/the-engine-can-unload-an-unused-model.test.tsx b/src/lib/__tests__/the-engine-can-unload-an-unused-model.test.tsxindex 15ace44a..5930829d 100644--- a/src/lib/__tests__/the-engine-can-unload-an-unused-model.test.tsx+++ b/src/lib/__tests__/the-engine-can-unload-an-unused-model.test.tsx@@ -26,6 +26,7 @@ vi.mock('@tauri-apps/api/event', () => ({import { idleUnloadLabel, idleUnloadMinutes, idleUnloadedNote, startEngineIdleUnloadSync, ENGINE_IDLE_UNLOADED_EVENT } from '../engine-idle-unload'import { BuiltinEngineSettings } from '../../components/settings/BuiltinEngineSettings'+import { IdleUnloadSetting } from '../../components/settings/IdleUnloadSetting'import { useSettingsStore } from '../../stores/settingsStore'import { useLuEngineSwitchStore } from '../../stores/luEngineSwitchStore'import { DEFAULT_SETTINGS } from '../constants'@@ -59,7 +60,7 @@ describe('unloading an unused model', () => {await startEngineIdleUnloadSync()expect(idleCalls()).toEqual([{ minutes: 30 }])- render(<BuiltinEngineSettings />)+ render(<IdleUnloadSetting />)fireEvent.change(screen.getByTestId('engine-idle-unload'), { target: { value: '10' } })expect(useSettingsStore.getState().settings.engineIdleUnloadMinutes).toBe(10)await vi.waitFor(() => expect(idleCalls()).toContainEqual({ minutes: 10 }))diff --git a/src/lib/idle-unload.ts b/src/lib/idle-unload.tsnew file mode 100644index 00000000..ad416f01--- /dev/null+++ b/src/lib/idle-unload.ts@@ -0,0 +1,32 @@+// GH #235: one setting unloads a chat model nobody uses, on every local+// backend. The LU Engine's watch lives in Rust (engine-idle-unload.ts); Ollama+// and LM Studio each have a timer of their own, and LU hands them the minutes:+// Ollama as `keep_alive` on every request, LM Studio as `--ttl` when LU loads a+// model and as `ttl` on every request (a model LM Studio loaded by itself).+import { useSettingsStore } from '../stores/settingsStore'++/** The stored minutes, 0 for never (same reading as engine-idle-unload.ts). */+export function idleMinutesSetting(): number {+ const v = useSettingsStore.getState().settings.engineIdleUnloadMinutes+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.round(v) : 0+}++/** Ollama's `keep_alive` for a request. With no time set, the value the call+ * always sent (LU keeps a model warm 30 minutes for a long agent step). */+export function ollamaKeepAlive(usual: string): string {+ const minutes = idleMinutesSetting()+ return minutes > 0 ? `${minutes}m` : usual+}++/** LM Studio's idle time in seconds, undefined when none is set (LM Studio+ * then keeps the model as it always did). */+export function lmStudioTtlSeconds(): number | undefined {+ const minutes = idleMinutesSetting()+ return minutes > 0 ? minutes * 60 : undefined+}++/** The `ttlSeconds` argument of `lmstudio_load_model`, or nothing. */+export function lmsTtlArg(): { ttlSeconds?: number } {+ const ttl = lmStudioTtlSeconds()+ return ttl ? { ttlSeconds: ttl } : {}+}diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.tsindex c941e6aa..efd87797 100644--- a/src/lib/ollama-stream-tools.ts+++ b/src/lib/ollama-stream-tools.ts@@ -2,6 +2,7 @@ import { resolveMessageAttachments } from './chat-attachments'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'import { ollamaUrl, localFetchStream } from '../api/backend'import { ollamaWindowOption } from '../api/ollama'+import { ollamaKeepAlive } from './idle-unload'import type { WindowChoice } from './context-window'import { isLocalTransportFailure, localBackendUnreachableMessage } from './local-backend-transport'import { repairToolCallArgs } from './tool-call-repair'@@ -91,7 +92,7 @@ export async function streamOllamaChatWithTools(// default idle. An agent step that runs a 10-minute build came back to a// cold model and paid a multi-GB reload before the next thought — several// times per long session. 30m matches the warm-up call in api/ollama.ts.- keep_alive: '30m',+ keep_alive: ollamaKeepAlive('30m'),options: {},}if (options.temperature !== undefined) body.options.temperature = options.temperaturediff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.tsindex 047a7b8f..36f7eefc 100644--- a/src/lib/settings-catalog.ts+++ b/src/lib/settings-catalog.ts@@ -257,7 +257,7 @@ export const CATALOG: readonly CatalogEntry[] = [e('chatRecall', 'Recall older messages', 'general', 'After a compaction, send the older messages that relate to the new one along, found by a local embedding model.', bool()),e('autoCompactThreshold', 'Auto-compact at', 'general', 'How full the context window gets before auto-compact runs.', compactThreshold),e('contextWindowOverride', 'Context window (Ollama)', 'general', 'num_ctx sent to Ollama, in tokens. Other backends ignore it; an API model whose server reports no window gets its own from the context button in the chat.', int(0, CONTEXT_WINDOW_MAX, 'tokens', 'auto')),- e('engineIdleUnloadMinutes', 'Unload the model when unused', 'backends', 'Minutes without use before LU Engine frees the model.', int(0, 1_440, 'min', 'never')),+ e('engineIdleUnloadMinutes', 'Unload the chat model when unused', 'backends', 'Minutes without use before LU Engine, Ollama or LM Studio frees the model.', int(0, 1_440, 'min', 'never')),e('builtinEngine.ctx', 'Context window (LU Engine)', 'backends', 'Context size of LU Engine, in tokens. Applies on the next engine start.', int(0, 1_048_576, 'tokens', 'default 8192')),e('attachmentTokenLimit', 'Attachment limit', 'general', 'Most tokens one attached text file may take.', int(0, 1_048_576, 'tokens', 'no limit'), { lockOverride: 'A number of tokens, not a token.' }),e('contextDecay', 'Context decay', 'agent', 'Shorten old tool results in long agent runs.', bool()),