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(lms): auto-load LM Studio models at 16K ctx + hide CLI console window

purpled7ca010acba6
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rs
index 9d6fede0..23336ba3 100644
--- a/src-tauri/src/commands/install.rs
+++ b/src-tauri/src/commands/install.rs
@@ -1883,7 +1883,14 @@ pub fn lmstudio_load_model(model: String, contextLength: Option<u32>) -> Result<
// with `-c <N>` (`lms load --context-length`). Without a context length
// this stays a plain load (the B3 power toggle path, unchanged).
if contextLength.is_some() {
- let _ = Command::new(&lms).args(["unload", &model]).output();
+ // Hide the console window the `lms` CLI would otherwise flash on
+ // Windows (CREATE_NO_WINDOW) — these run during normal model
+ // switching / the VRAM hand-off, not just at install time.
+ let mut unload = Command::new(&lms);
+ unload.args(["unload", &model]);
+ #[cfg(target_os = "windows")]
+ unload.creation_flags(CREATE_NO_WINDOW);
+ let _ = unload.output();
}
let ctx = contextLength.unwrap_or(0);
let ctx_str = ctx.to_string();
@@ -1892,8 +1899,11 @@ pub fn lmstudio_load_model(model: String, contextLength: Option<u32>) -> Result<
args.push("-c");
args.push(ctx_str.as_str());
}
- let output = Command::new(&lms)
- .args(&args)
+ let mut cmd = Command::new(&lms);
+ cmd.args(&args);
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ let output = cmd
.output()
.map_err(|e| format!("spawn lms load: {e}"))?;
if !output.status.success() {
@@ -1963,8 +1973,11 @@ pub fn lmstudio_model_context(model: String) -> Result<serde_json::Value, String
pub fn lmstudio_unload_model(model: String) -> Result<serde_json::Value, String> {
let lms = lmstudio_lms_path()
.ok_or_else(|| "lms CLI not found".to_string())?;
- let output = Command::new(&lms)
- .args(["unload", &model])
+ let mut cmd = Command::new(&lms);
+ cmd.args(["unload", &model]);
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ let output = cmd
.output()
.map_err(|e| format!("spawn lms unload: {e}"))?;
if !output.status.success() {
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 2b2322a9..5bff0556 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -63,10 +63,6 @@ interface OpenAIModelEntry {
owned_by?: string
}
-interface OpenAIError {
- error?: { message?: string; type?: string; code?: string }
-}
-
// ── Known context lengths for popular models ───────────────────
const KNOWN_CONTEXT: Record<string, number> = {
@@ -543,10 +539,23 @@ export class OpenAIProvider implements ProviderClient {
let code: string = 'network'
try {
- const data: OpenAIError = await res.json()
- if (data.error?.message) message = data.error.message
- if (data.error?.code) code = data.error.code
- } catch { /* use default */ }
+ const data = await res.json() as { error?: unknown; message?: string }
+ const err = data.error
+ // OpenAI & most servers: { error: { message, code } }. But LM Studio and
+ // llama.cpp commonly send a BARE string ({ error: "..." }) or a top-level
+ // { message: "..." }. The old object-only read missed both → the real
+ // reason (e.g. a context-window overflow) was swallowed and the user saw
+ // the opaque "Request failed". Handle all three shapes.
+ if (typeof err === 'string' && err.trim()) {
+ message = err
+ } else if (err && typeof err === 'object') {
+ const eo = err as { message?: string; code?: string }
+ if (eo.message) message = eo.message
+ if (eo.code) code = eo.code
+ } else if (typeof data.message === 'string' && data.message.trim()) {
+ message = data.message
+ }
+ } catch { /* non-JSON body → keep default */ }
// Map HTTP status to error code
if (res.status === 401 || res.status === 403) {
diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsx
index 0d9162af..71f9c806 100644
--- a/src/components/models/ModelSelector.tsx
+++ b/src/components/models/ModelSelector.tsx
@@ -279,6 +279,31 @@ export function shouldAutoLoadForSelect(
return isLms && !loaded.has(lmsIdOf(model))
}
+/**
+ * Context window (tokens) to request when LU auto-loads an LM Studio model.
+ *
+ * `lms load` WITHOUT `-c` pins the instance at LM Studio's small default
+ * (4096 on current builds). That silently breaks tool use: the chat-tools
+ * system prompt + the 5 curated tool schemas — let alone the full agent
+ * catalog — overflow 4K, and LM Studio answers /v1/chat/completions with a
+ * context-overflow error that surfaces as the opaque "LM Studio: Request
+ * failed", with NO retry (it's a 4xx). Proven live 2026-06-12: gemma-3-4b
+ * @4096 failed every chat-tools / agent turn; the identical turn @16384
+ * worked first try. So we always request a usable window — capped by the
+ * model's real max so we never ask for more than it supports (an 8K model
+ * stays 8K). 16K is enough for the tool schemas + a real conversation while
+ * keeping the KV-cache VRAM modest for the small local models LU targets.
+ */
+export const LMS_AUTOLOAD_CONTEXT = 16384
+
+export function lmsAutoLoadContext(model: AIModel): number {
+ const max =
+ 'contextLength' in model && typeof model.contextLength === 'number' && model.contextLength > 0
+ ? model.contextLength
+ : LMS_AUTOLOAD_CONTEXT
+ return Math.min(max, LMS_AUTOLOAD_CONTEXT)
+}
+
// ── Load toggle (On / Off) ────────────────────────────────────
//
// Per-row VRAM load indicator + control for LOCAL models (Ollama AND
@@ -382,7 +407,7 @@ export function ModelSelector() {
if (lmsLoaded.has(id)) {
await unloadLmStudioModel(id)
} else {
- await loadLmStudioModel(id)
+ await loadLmStudioModel(id, lmsAutoLoadContext(model))
}
const list = await listLoadedLmStudioModels()
setLmsLoaded(new Set(list))
@@ -439,7 +464,7 @@ export function ModelSelector() {
setSelectError(null)
setSelectingLms(id)
try {
- await loadLmStudioModel(id)
+ await loadLmStudioModel(id, lmsAutoLoadContext(model))
// Confirm it actually loaded before we route chat at it.
const list = await listLoadedLmStudioModels()
const loaded = new Set(list)
diff --git a/src/components/models/__tests__/model-selector-lms.test.ts b/src/components/models/__tests__/model-selector-lms.test.ts
index fbc16b27..6b910d78 100644
--- a/src/components/models/__tests__/model-selector-lms.test.ts
+++ b/src/components/models/__tests__/model-selector-lms.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { lmsIdOf, shouldAutoLoadForSelect } from '../ModelSelector'
+import { lmsIdOf, shouldAutoLoadForSelect, lmsAutoLoadContext, LMS_AUTOLOAD_CONTEXT } from '../ModelSelector'
import type { AIModel } from '../../../types/models'
// §18 — focused tests for the LM Studio select-time auto-load decision.
@@ -104,3 +104,33 @@ describe('shouldAutoLoadForSelect', () => {
expect(shouldAutoLoadForSelect(cloud, new Set())).toBe(false)
})
})
+
+// Root cause proven live 2026-06-12: `lms load` without `-c` pins the instance
+// at LM Studio's 4096 default, which overflows the moment tool schemas are in
+// play → opaque "LM Studio: Request failed" (a 4xx, so no retry). These lock in
+// that LU always asks for a usable window, capped by the model's real max.
+describe('lmsAutoLoadContext', () => {
+ it('caps a huge model max at the 16K auto-load window', () => {
+ // gemma-3-4b reports max 131072 — we must NOT load it that big (KV-cache
+ // VRAM blowup); 16K is the sweet spot.
+ expect(lmsAutoLoadContext(lmsModel('gemma-3-4b', { contextLength: 131072 }))).toBe(LMS_AUTOLOAD_CONTEXT)
+ expect(LMS_AUTOLOAD_CONTEXT).toBe(16384)
+ })
+
+ it('uses the model max when it is SMALLER than the window (never over-asks)', () => {
+ expect(lmsAutoLoadContext(lmsModel('tiny', { contextLength: 8192 }))).toBe(8192)
+ })
+
+ it('returns exactly the window when max equals it', () => {
+ expect(lmsAutoLoadContext(lmsModel('m', { contextLength: 16384 }))).toBe(16384)
+ })
+
+ it('falls back to the window when contextLength is missing', () => {
+ expect(lmsAutoLoadContext(lmsModel('m'))).toBe(LMS_AUTOLOAD_CONTEXT)
+ })
+
+ it('falls back to the window for a zero / bogus contextLength (never loads 0)', () => {
+ expect(lmsAutoLoadContext(lmsModel('m', { contextLength: 0 }))).toBe(LMS_AUTOLOAD_CONTEXT)
+ expect(lmsAutoLoadContext(lmsModel('m', { contextLength: -5 }))).toBe(LMS_AUTOLOAD_CONTEXT)
+ })
+})