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): the LM Studio line follows the server and counts what the list shows
purplec438b98e156e
diff --git a/src-tauri/src/commands/install/lmstudio.rs b/src-tauri/src/commands/install/lmstudio.rsindex 95ed850a..c9137670 100644--- a/src-tauri/src/commands/install/lmstudio.rs+++ b/src-tauri/src/commands/install/lmstudio.rs@@ -112,29 +112,67 @@ pub(crate) fn lmstudio_lms_path() -> Option<PathBuf> {None}-/// Soft-detect LM Studio by scanning `~/.lmstudio/models/` for GGUF files.-/// Returns the number of GGUF files found (0 if the dir is missing or empty).+/// True when a GGUF under `~/.lmstudio/models/` is a model the chat picker+/// will list once the server runs. `rel` is the lowercased path below the+/// models dir (`publisher/repo/file.gguf`).///-/// Rationale: even when `lms.exe` isn't on any search path (system-wide-/// install missed by our fallback, GUI never launched, etc.), the presence-/// of GGUFs in the canonical models dir is a strong signal that the user-/// *has* LM Studio and just hasn't started the server. Surfacing that in the-/// onboarding lets us show "LM Studio models detected — start server?" instead-/// of the dead-end "no LM Studio".-fn lmstudio_models_present() -> u32 {- let home = match dirs::home_dir() {- Some(h) => h,- None => return 0,+/// The line in the picker says "N models on disk" next to its Start button,+/// and after the click the list has to show N rows. Counting every GGUF said 8+/// where the list showed 7 (Windows box, 05.10.2026). Three kinds of file are+/// no row of their own:+/// - an embedding model: the picker drops those by name, with the patterns+/// of `EMBEDDING_GGUF_PATTERNS` in src/api/engine.ts, repeated here;+/// - a vision projector (`mmproj-*.gguf`), which rides along with its model;+/// - the further parts of a split model (`-00002-of-00003.gguf`).+fn lmstudio_chat_model_file(rel: &str) -> bool {+ const EMBEDDING_MARKS: [&str; 5] = ["embed", "bge-", "e5-", "gte-", "sentence-"];+ if EMBEDDING_MARKS.iter().any(|m| rel.contains(m)) {+ return false;+ }+ let file = rel.rsplit(['/', '\\']).next().unwrap_or(rel);+ if file.contains("mmproj") {+ return false;+ }+ // "<name>-00002-of-00003.gguf": only the first part stands for the model.+ let stem = file.strip_suffix(".gguf").unwrap_or(file);+ if let Some((head, total)) = stem.rsplit_once("-of-") {+ let all_digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit());+ if let Some((_, part)) = head.rsplit_once('-') {+ if all_digits(total) && all_digits(part) {+ return part.trim_start_matches('0') == "1";+ }+ }+ }+ true+}++/// What `~/.lmstudio/models/` holds.+#[derive(Default)]+struct LmStudioModelsOnDisk {+ /// Any GGUF at all. Even when `lms.exe` isn't on any search path+ /// (system-wide install missed by our fallback, GUI never launched), a+ /// GGUF in the canonical models dir is a strong signal that the user *has*+ /// LM Studio and just hasn't started the server.+ any: bool,+ /// The models the chat picker will list, see `lmstudio_chat_model_file`.+ chat_models: u32,+}++/// Soft-detect LM Studio by scanning `~/.lmstudio/models/` for GGUF files.+fn lmstudio_models_present() -> LmStudioModelsOnDisk {+ let mut found = LmStudioModelsOnDisk::default();+ let models_dir = match dirs::home_dir() {+ Some(h) => h.join(".lmstudio").join("models"),+ None => return found,};- let models_dir = home.join(".lmstudio").join("models");if !models_dir.exists() {- return 0;+ return found;}// The standard layout is ~/.lmstudio/models/<publisher>/<repo>/<file>.gguf —// up to three levels deep. We walk lazily and stop after the first 1000// matches; the user does not care about the exact count past "many".- fn walk(dir: &Path, depth: u32, found: &mut u32) {- if *found >= 1000 || depth > 4 {+ fn walk(root: &Path, dir: &Path, depth: u32, found: &mut LmStudioModelsOnDisk) {+ if found.chat_models >= 1000 || depth > 4 {return;}let entries = match std::fs::read_dir(dir) {@@ -144,18 +182,21 @@ fn lmstudio_models_present() -> u32 {for entry in entries.flatten() {let path = entry.path();if path.is_dir() {- walk(&path, depth + 1, found);+ walk(root, &path, depth + 1, found);} else if path.extension().and_then(|e| e.to_str()).map(|s| s.eq_ignore_ascii_case("gguf")).unwrap_or(false) {- *found += 1;- if *found >= 1000 {- return;+ found.any = true;+ let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().to_lowercase();+ if lmstudio_chat_model_file(&rel) {+ found.chat_models += 1;+ if found.chat_models >= 1000 {+ return;+ }}}}}- let mut count: u32 = 0;- walk(&models_dir, 0, &mut count);- count+ walk(&models_dir, &models_dir, 0, &mut found);+ found}#[cfg(target_os = "windows")]@@ -322,15 +363,16 @@ fn start_lmstudio_server_blocking() -> Result<serde_json::Value, String> {#[tauri::command]pub async fn lmstudio_server_status() -> Result<serde_json::Value, String> {tokio::task::spawn_blocking(|| -> Result<serde_json::Value, String> {- let model_count = lmstudio_models_present();+ let on_disk = lmstudio_models_present();Ok(serde_json::json!({"running": lmstudio_server_running(),"port": LMSTUDIO_DEFAULT_PORT,"lms_present": lmstudio_lms_path().is_some(),// Soft-detect signals — onboarding shows "Start LM Studio server?"// when models are present even if lms.exe couldn't be located.- "models_detected": model_count > 0,- "model_count": model_count,+ "models_detected": on_disk.any,+ // The rows the chat picker will show, not the files on disk.+ "model_count": on_disk.chat_models,}))}).await@@ -553,3 +595,42 @@ fn lmstudio_unload_model_blocking(model: String) -> Result<serde_json::Value, St}Ok(serde_json::json!({ "ok": true, "model": model }))}++#[cfg(test)]+mod tests {+ use super::lmstudio_chat_model_file;++ /// The picker line says "N models on disk" and the list then shows N rows.+ /// Windows box, 05.10.2026: every GGUF was counted, the line said 8, the+ /// list showed 7.+ #[test]+ fn counts_what_the_chat_picker_lists() {+ let on_disk = [+ "lmstudio-community/qwen3-8b-gguf/qwen3-8b-q4_k_m.gguf",+ "lmstudio-community/gemma-3-12b-it-gguf/gemma-3-12b-it-q4_k_m.gguf",+ "lmstudio-community/gemma-3-12b-it-gguf/mmproj-model-f16.gguf",+ "nomic-ai/nomic-embed-text-v1.5-gguf/nomic-embed-text-v1.5.q4_k_m.gguf",+ "baai/bge-m3-gguf/bge-m3-q8_0.gguf",+ "bartowski/big-model-gguf/big-model-q4_k_m-00001-of-00003.gguf",+ "bartowski/big-model-gguf/big-model-q4_k_m-00002-of-00003.gguf",+ "bartowski/big-model-gguf/big-model-q4_k_m-00003-of-00003.gguf",+ ];+ let listed: Vec<&str> = on_disk.iter().copied().filter(|f| lmstudio_chat_model_file(f)).collect();+ assert_eq!(+ listed,+ [+ "lmstudio-community/qwen3-8b-gguf/qwen3-8b-q4_k_m.gguf",+ "lmstudio-community/gemma-3-12b-it-gguf/gemma-3-12b-it-q4_k_m.gguf",+ "bartowski/big-model-gguf/big-model-q4_k_m-00001-of-00003.gguf",+ ]+ );+ }++ #[test]+ fn a_windows_path_and_an_ordinary_name_with_of_in_it_count() {+ assert!(lmstudio_chat_model_file("publisher\\repo\\model-q4_k_m.gguf"));+ assert!(!lmstudio_chat_model_file("publisher\\repo\\mmproj-model-f16.gguf"));+ assert!(lmstudio_chat_model_file("publisher/repo/best-of-breed-7b.gguf"));+ assert!(lmstudio_chat_model_file("publisher/repo/tales-of-2024-q4.gguf"));+ }+}diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex 1abdb9a0..5c06876c 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -153,8 +153,8 @@ function sameStringSet(prev: Set<string>, next: string[]): boolean {// returns nothing and LM Studio is silently dropped from the dropdown.// v2.4.4 added a "Start LM Studio server" hint to onboarding, but the// chat picker (where users actually look for their models) never got-// the same treatment. This banner closes that gap. Polls-// `lmstudio_server_status` on dropdown open; renders inline when LM+// the same treatment. This banner closes that gap. Asks+// `lmstudio_server_status` while the dropdown is open; renders inline when LM// Studio is detected on disk (lms.exe present OR models in// ~/.lmstudio/models/) AND its server isn't running. Clicking "Start// Server" hits the same Tauri command the Settings panel uses, then@@ -171,10 +171,18 @@ export interface LmStudioServerStatus {running: booleanport: numberlms_present: boolean+ /** Any GGUF in LM Studio's models folder. */models_detected: boolean+ /** The models the chat picker lists once the server runs: no embedding+ * models, no vision projectors, a split model once. */model_count: number}+/** How often the line asks the server while the menu is open. */+const LMSTUDIO_STATUS_POLL_MS = 1500+/** How long "starting" stands before the Start button comes back. */+const LMSTUDIO_START_WAIT_MS = 30_000+// One line with a state dot, a short sentence and a text button (David,// 05.10.2026). It used to be a box of three text blocks and a full-width// button, about as tall as five model rows. What the click does is unchanged.@@ -188,55 +196,92 @@ function LmStudioStatusLine({ onStarted }: { onStarted: () => void }) {// tooltip of the button, the line itself stays one line.const replacesBuiltinEngine = useProviderStore((s) => adoptionReplacesBuiltinEngine(s.providers.openai))+ // The line follows the server for as long as the menu is open. It used to+ // ask once on open and for six seconds after "Start": a server that needed+ // longer came up, its models reached the list, and the line above them went+ // on saying "server off" (Windows box, 05.10.2026).+ const refreshRef = useRef<() => Promise<void>>(async () => {})+ const startAsked = useRef(false)+ const onStartedRef = useRef(onStarted)+ useEffect(() => { onStartedRef.current = onStarted }, [onStarted])useEffect(() => {let cancelled = false- backendCall<LmStudioServerStatus>('lmstudio_server_status')- .then(s => { if (!cancelled) setStatus(s) })- .catch(() => { /* not Tauri / endpoint missing → just don't render */ })- return () => { cancelled = true }+ let timer: ReturnType<typeof setTimeout> | undefined+ let wasRunning: boolean | null = null+ let following = false+ let asked = 0+ const refresh = async () => {+ clearTimeout(timer)+ const mine = ++asked+ const fresh = await backendCall<LmStudioServerStatus>('lmstudio_server_status').catch(() => null)+ // A newer question is on its way (the click on "Start" asks at once):+ // that one answers and keeps the rhythm.+ if (cancelled || mine !== asked) return+ // Not Tauri, endpoint missing, or no LM Studio on this machine: there+ // is nothing to follow, so the line stays away and nothing keeps asking.+ // One answer that fails later on is not that: the line keeps what it+ // last knew and asks again.+ const detected = !!fresh && (fresh.lms_present || fresh.models_detected)+ if (!fresh && following) timer = setTimeout(() => void refresh(), LMSTUDIO_STATUS_POLL_MS)+ if (!fresh || !detected) return+ following = true+ const cameUp = fresh.running && wasRunning === false+ wasRunning = fresh.running+ if (cameUp) {+ // After a click on "Start" this is the moment the line promised: the+ // models have to appear. A running server is only half of that. The+ // picker lists ENABLED provider slots, so without the slot the models+ // stay invisible and the button leads into a dead end (Nebenbefund 4,+ // R8 re-measure). Same call the BackendSelector makes, no+ // LM-Studio-only path. A server someone started elsewhere takes no+ // slot: nobody asked for that here.+ if (startAsked.current) {+ startAsked.current = false+ const update = lmStudioSlotUpdate(useProviderStore.getState().providers.openai)+ if (update) {+ useProviderStore.getState().setProviderConfig('openai', update)+ // Opus review, R13D follow-up: this click is the deliberate+ // pick `adoptionReplacesBuiltinEngine` already warns about+ // above, not an eviction bug, so the missing-engine notice+ // must not fire because of it. See lib/builtin-engine-presence.ts.+ if (update.managed === false) useProviderStore.getState().setEngineOptedOut(true)+ }+ }+ setStarting(false)+ onStartedRef.current()+ }+ setStatus(fresh)+ timer = setTimeout(() => void refresh(), LMSTUDIO_STATUS_POLL_MS)+ }+ refreshRef.current = refresh+ void refresh()+ return () => { cancelled = true; clearTimeout(timer) }}, [])+ // "Starting" is a promise with an end: a server that has not answered by+ // then gets its Start button back. The line keeps following it either way.+ useEffect(() => {+ if (!starting) return+ const timer = setTimeout(() => setStarting(false), LMSTUDIO_START_WAIT_MS)+ return () => clearTimeout(timer)+ }, [starting])+// Render only when LM Studio is on disk but its server is off. If// running, models are already in the list; if neither lms.exe nor any// models are present, the user just doesn't have LM Studio.- const detected = !!status && (status.lms_present || status.models_detected)- if (!status || status.running || !detected) return null+ if (!status || status.running) return nullconst handleStart = async (e: React.MouseEvent) => {e.stopPropagation()if (starting) returnsetStarting(true)setStartError('')+ startAsked.current = truetry {await backendCall('start_lmstudio_server')- // The CLI takes a second or two to bind 1234, poll status- // briefly so the line replaces itself with the models list- // instead of leaving the spinner spinning forever.- for (let i = 0; i < 8; i++) {- await new Promise(r => setTimeout(r, 750))- const fresh = await backendCall<LmStudioServerStatus>('lmstudio_server_status').catch(() => null)- if (fresh) {- setStatus(fresh)- if (fresh.running) {- // A running server is only half of what the line promises. The- // picker lists ENABLED provider slots, so without this the models- // stay invisible and the button leads into a dead end- // (Nebenbefund 4, R8 re-measure). Same call the BackendSelector- // makes, no LM-Studio-only path.- const update = lmStudioSlotUpdate(useProviderStore.getState().providers.openai)- if (update) {- useProviderStore.getState().setProviderConfig('openai', update)- // Opus review, R13D follow-up: this click is the deliberate- // pick `adoptionReplacesBuiltinEngine` already warns about- // above, not an eviction bug, so the missing-engine notice- // must not fire because of it. See lib/builtin-engine-presence.ts.- if (update.managed === false) useProviderStore.getState().setEngineOptedOut(true)- }- onStarted()- break- }- }- }+ // The CLI takes a moment to bind 1234. Ask right away, the line then+ // keeps asking on its own until the server answers.+ await refreshRef.current()} catch (e) {// Tauris `invoke` lehnt mit einem STRING ab (die Rust-Seite gibt// `Result<_, String>` zurueck), ein `e.message` haette im ausgelieferten@@ -244,8 +289,8 @@ function LmStudioStatusLine({ onStarted }: { onStarted: () => void }) {// Projekt genau diese Frage beantwortet (lib/error-text.ts): String,// Error oder sonst etwas.const detail = detailOf(e)+ startAsked.current = falsesetStartError(detail ? detail.slice(0, 80) : 'Start failed')- } finally {setStarting(false)}}diff --git a/src/components/models/__tests__/lmstudio-status-line.test.tsx b/src/components/models/__tests__/lmstudio-status-line.test.tsxindex 316c95fe..a9054949 100644--- a/src/components/models/__tests__/lmstudio-status-line.test.tsx+++ b/src/components/models/__tests__/lmstudio-status-line.test.tsx@@ -36,7 +36,7 @@ vi.mock('../../../api/ollama', () => ({unloadAllModels: vi.fn(async () => {}),}))const backendCall = vi.fn(async (_cmd: string): Promise<unknown> => null)-vi.mock('../../../api/backend', () => ({ backendCall: (cmd: string) => backendCall(cmd) }))+vi.mock('../../../api/backend', () => ({ backendCall: (cmd: string) => backendCall(cmd), isTauri: () => false }))vi.mock('../../../api/builtin-ensure', () => ({ diagnoseBuiltinEngine: vi.fn(async () => null) }))const { ModelSelector, lmStudioLineText, lmStudioStartTitle } = await import('../ModelSelector')@@ -65,6 +65,9 @@ async function open(status: unknown, mode: 'local' | 'cloud' = 'local') {useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: mode } })render(createElement(ModelSelector))await act(async () => { fireEvent.click(screen.getByLabelText('Select chat model')) })+ // The selector loads its list on mount and on open. What counts below is a+ // reload the line asked for.+ fetchModels.mockClear()return { setStatus: (s: unknown) => { serverStatus = s } }}@@ -148,13 +151,13 @@ describe('Start', () => {it('starts the server, hands LM Studio the slot and reloads the list, as before', async () => {vi.useFakeTimers()const probe = await open(OFF)- probe.setStatus(RUNNING)await act(async () => { fireEvent.click(startButton()) })expect(backendCall).toHaveBeenCalledWith('start_lmstudio_server')expect(line()!.getAttribute('data-state')).toBe('starting')expect(line()!.querySelector('.st')!.textContent).toBe('LM Studio server starting')expect(screen.queryByRole('button', { name: 'Start' })).toBeNull()- await act(async () => { await vi.advanceTimersByTimeAsync(800) })+ probe.setStatus(RUNNING)+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })expect(fetchModels).toHaveBeenCalled()const openai = useProviderStore.getState().providers.openaiexpect(openai.managed).toBe(false)@@ -178,3 +181,100 @@ describe('Start', () => {expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()})})++// Windows box, 05.10.2026: after "Start" the models came into the list, and+// the line above them kept saying "server off" for as long as the menu stayed+// open. It asked the server once on open and for six seconds after the click.+describe('the line follows the server while the menu is open', () => {+ const statusCalls = () => backendCall.mock.calls.filter(([cmd]) => cmd === 'lmstudio_server_status').length++ it('a server that needs longer than a few seconds still takes the line away and brings its models', async () => {+ vi.useFakeTimers()+ const probe = await open(OFF)+ await act(async () => { fireEvent.click(startButton()) })+ await act(async () => { await vi.advanceTimersByTimeAsync(12_000) })+ expect(line()!.getAttribute('data-state')).toBe('starting')+ expect(fetchModels).not.toHaveBeenCalled()+ probe.setStatus(RUNNING)+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })+ expect(line()).toBeNull()+ expect(fetchModels).toHaveBeenCalled()+ expect(useProviderStore.getState().providers.openai.baseUrl).toContain('1234')+ })++ it('gives the Start button back after the wait, and still follows a server that comes late', async () => {+ vi.useFakeTimers()+ const probe = await open(OFF)+ await act(async () => { fireEvent.click(startButton()) })+ await act(async () => { await vi.advanceTimersByTimeAsync(31_000) })+ expect(line()!.getAttribute('data-state')).toBe('off')+ expect(startButton()).toBeTruthy()+ probe.setStatus(RUNNING)+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })+ expect(line()).toBeNull()+ expect(useProviderStore.getState().providers.openai.managed).toBe(false)+ })++ it('a server started somewhere else takes the line away, reloads the list and takes no slot', async () => {+ vi.useFakeTimers()+ const probe = await open(OFF)+ probe.setStatus(RUNNING)+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })+ expect(line()).toBeNull()+ expect(fetchModels).toHaveBeenCalledTimes(1)+ const openai = useProviderStore.getState().providers.openai+ expect(openai.managed).toBe(true)+ expect(openai.baseUrl).toContain('8127')+ })++ it('a server that stops brings the line back, with the count of that moment', async () => {+ vi.useFakeTimers()+ const probe = await open(RUNNING)+ expect(line()).toBeNull()+ probe.setStatus({ ...OFF, model_count: 3 })+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })+ expect(line()!.querySelector('.st')!.textContent).toBe('LM Studio server off, 3 models on disk')+ // Nothing came up, so nothing is reloaded.+ expect(fetchModels).not.toHaveBeenCalled()+ })++ it('one failed answer does not end the following', async () => {+ vi.useFakeTimers()+ const probe = await open(OFF)+ backendCall.mockImplementationOnce(async () => { throw 'lmstudio_server_status task: cancelled' })+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })+ expect(line()!.getAttribute('data-state')).toBe('off')+ probe.setStatus(RUNNING)+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })+ expect(line()).toBeNull()+ })++ it('asks once and then leaves it when LM Studio is not on this machine', async () => {+ vi.useFakeTimers()+ await open({ running: false, port: 1234, lms_present: false, models_detected: false, model_count: 0 })+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })+ expect(statusCalls()).toBe(1)+ })++ it('asks once and then leaves it where the question itself fails (no Tauri)', async () => {+ vi.useFakeTimers()+ backendCall.mockImplementation(async () => { throw 'not running (e2e)' })+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'local' } })+ render(createElement(ModelSelector))+ await act(async () => { fireEvent.click(screen.getByLabelText('Select chat model')) })+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })+ expect(line()).toBeNull()+ expect(statusCalls()).toBe(1)+ })++ it('stops asking when the menu closes', async () => {+ vi.useFakeTimers()+ await open(OFF)+ await act(async () => { await vi.advanceTimersByTimeAsync(3200) })+ const before = statusCalls()+ expect(before).toBeGreaterThan(1)+ cleanup()+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })+ expect(statusCalls()).toBe(before)+ })+})diff --git a/src/lib/__tests__/lmstudio-backend-adopt.test.ts b/src/lib/__tests__/lmstudio-backend-adopt.test.tsindex 3345bf30..8fb48958 100644--- a/src/lib/__tests__/lmstudio-backend-adopt.test.ts+++ b/src/lib/__tests__/lmstudio-backend-adopt.test.ts@@ -112,7 +112,7 @@ describe('ModelSelector LM Studio banner', () => {it('adopts before it refetches, or the refetch reads the old slot', () => {const adopt = src.indexOf("setProviderConfig('openai', update)")- const refetch = src.indexOf('onStarted()', adopt)+ const refetch = src.indexOf('onStartedRef.current()', adopt)expect(adopt).toBeGreaterThan(-1)expect(refetch).toBeGreaterThan(adopt)})