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(chat): context-window dropdown with auto-reload + true LM Studio context
purpleb0888bdb64d2
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsindex da683688..0f599630 100644--- a/src-tauri/src/commands/install.rs+++ b/src-tauri/src/commands/install.rs@@ -1856,8 +1856,9 @@ pub fn lmstudio_list_loaded() -> Result<serde_json::Value, String> {Ok(serde_json::json!({ "loaded": loaded }))}+#[allow(non_snake_case)]#[tauri::command]-pub fn lmstudio_load_model(model: String) -> Result<serde_json::Value, String> {+pub fn lmstudio_load_model(model: String, contextLength: Option<u32>) -> Result<serde_json::Value, String> {let lms = lmstudio_lms_path().ok_or_else(|| "lms CLI not found — install LM Studio first".to_string())?;// `lms load` blocks until the model is in memory. The caller is expected@@ -1874,24 +1875,88 @@ pub fn lmstudio_load_model(model: String) -> Result<serde_json::Value, String> {// loads the first/preferred match, which is exactly the scripted behaviour// we want. Verified: `lms load -y <key>` returns in ~4s and `lms ps` shows// the model loaded.+ //+ // contextLength: LM Studio fixes the context window at LOAD time (the+ // OpenAI-compat HTTP API has no per-request num_ctx). To CHANGE it we must+ // reload — so when a context length is requested we unload the current+ // instance first (best-effort; a no-op if nothing is loaded) and reload+ // 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();+ }+ 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 output = Command::new(&lms)- .args(["load", &model, "-y"])+ .args(&args).output().map_err(|e| format!("spawn lms load: {e}"))?;if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);let stdout = String::from_utf8_lossy(&output.stdout);eprintln!(- "[lmstudio_load_model] FAILED model='{}' code={:?}\n stderr={:?}\n stdout={:?}",+ "[lmstudio_load_model] FAILED model='{}' ctx={:?} code={:?}\n stderr={:?}\n stdout={:?}",model,+ contextLength,output.status.code(),stderr.trim(),stdout.trim());return Err(format!("lms load failed: {}", stderr.trim()));}- eprintln!("[lmstudio_load_model] OK model='{}'", model);- Ok(serde_json::json!({ "ok": true, "model": model }))+ eprintln!("[lmstudio_load_model] OK model='{}' ctx={:?}", model, contextLength);+ Ok(serde_json::json!({ "ok": true, "model": model, "contextLength": contextLength }))+}++/// Read a model's context window from LM Studio's enhanced REST API+/// (`GET /api/v0/models`). Returns `loaded_context_length` (what the model is+/// ACTUALLY running with right now — the value the chat truly uses) and+/// `max_context_length` (the model's ceiling). Both are null when LM Studio+/// isn't running or the model isn't found. Reading the list endpoint (not the+/// per-id one) sidesteps URL-encoding issues with publisher/slash ids.+#[tauri::command]+pub fn lmstudio_model_context(model: String) -> Result<serde_json::Value, String> {+ let null_json = serde_json::json!({ "loaded": serde_json::Value::Null, "max": serde_json::Value::Null, "state": serde_json::Value::Null });+ let client = match reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_millis(2000))+ .build()+ {+ Ok(c) => c,+ Err(_) => return Ok(null_json),+ };+ let url = format!("http://localhost:{}/api/v0/models", LMSTUDIO_DEFAULT_PORT);+ let resp = match client.get(&url).send() {+ Ok(r) => r,+ Err(_) => return Ok(null_json),+ };+ if !resp.status().is_success() {+ return Ok(null_json);+ }+ let body: serde_json::Value = match resp.json() {+ Ok(b) => b,+ Err(_) => return Ok(null_json),+ };+ let entry = body+ .get("data")+ .and_then(|d| d.as_array())+ .and_then(|arr| arr.iter().find(|m| m.get("id").and_then(|i| i.as_str()) == Some(model.as_str())));+ match entry {+ Some(m) => {+ let loaded = m.get("loaded_context_length").and_then(|v| v.as_u64());+ let max = m+ .get("max_context_length")+ .and_then(|v| v.as_u64())+ .or_else(|| m.get("context_length").and_then(|v| v.as_u64()));+ let state = m.get("state").and_then(|v| v.as_str());+ Ok(serde_json::json!({ "loaded": loaded, "max": max, "state": state }))+ }+ None => Ok(null_json),+ }}#[tauri::command]diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 96750489..a858b39e 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -114,6 +114,7 @@ fn main() {commands::install::lmstudio_server_status,commands::install::lmstudio_list_loaded,commands::install::lmstudio_load_model,+ commands::install::lmstudio_model_context,commands::install::lmstudio_unload_model,commands::install::install_python,commands::install::install_python_status,diff --git a/src/api/lmstudio.ts b/src/api/lmstudio.tsindex 587735eb..2c0d3f70 100644--- a/src/api/lmstudio.ts+++ b/src/api/lmstudio.ts@@ -16,10 +16,38 @@ export async function listLoadedLmStudioModels(): Promise<string[]> {}}-export async function loadLmStudioModel(model: string): Promise<void> {- await backendCall('lmstudio_load_model', { model })+/**+ * Load (or RELOAD) a model in LM Studio. When `contextLength` is given the+ * bridge unloads the current instance first and reloads with `lms load -c <N>`,+ * because LM Studio fixes the context window at load time (the OpenAI-compat+ * HTTP API has no per-request num_ctx). Omit it for a plain load.+ */+export async function loadLmStudioModel(model: string, contextLength?: number): Promise<void> {+ await backendCall('lmstudio_load_model', { model, contextLength: contextLength && contextLength > 0 ? contextLength : null })}export async function unloadLmStudioModel(model: string): Promise<void> {await backendCall('lmstudio_unload_model', { model })}++export interface LmStudioModelContext {+ /** The context window the model is ACTUALLY running with (null = not loaded). */+ loaded: number | null+ /** The model's maximum context window. */+ max: number | null+ /** LM Studio state, e.g. "loaded" | "not-loaded". */+ state: string | null+}++/**+ * Read a model's real context window from LM Studio's enhanced REST API.+ * `loaded` is the source of truth for the TokenCounter denominator — it's what+ * the chat actually uses, not the model's theoretical max.+ */+export async function getLmStudioModelContext(model: string): Promise<LmStudioModelContext> {+ try {+ return await backendCall<LmStudioModelContext>('lmstudio_model_context', { model })+ } catch {+ return { loaded: null, max: null, state: null }+ }+}diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex b7d23136..de5dec72 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -63,6 +63,24 @@ export async function getModelContextCached(name: string): Promise<number> {return v}+/**+ * Force Ollama to (re)load a model with a specific num_ctx RIGHT NOW, so a+ * context-window change from the dropdown takes effect immediately instead of+ * silently on the next chat. Ollama keys its loaded runner by num_ctx, so an+ * `/api/generate` with an empty prompt + `options.num_ctx` swaps the resident+ * KV cache to the new size; `keep_alive` keeps the reloaded model warm.+ * Best-effort — failures are swallowed (the next real chat still sends num_ctx).+ */+export async function warmupOllamaContext(model: string, numCtx: number): Promise<void> {+ if (!model || !numCtx || numCtx <= 0) return+ try {+ await localFetch(ollamaUrl("/generate"), {+ method: "POST",+ body: JSON.stringify({ model, prompt: "", stream: false, keep_alive: "30m", options: { num_ctx: numCtx } }),+ })+ } catch { /* best-effort warmup — non-fatal */ }+}+export async function chatStream(model: string,messages: { role: string; content: string }[],diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex e0b4a3de..4cf6d576 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -17,6 +17,7 @@ import { isAgentCompatible, isThinkingCompatible } from '../../lib/model-compatiimport { FileText, Bot, ChevronDown, Download, Brain, Wrench, Radio, RefreshCw, X } from 'lucide-react'import { PluginsDropdown } from './PluginsDropdown'import { TokenCounter } from './TokenCounter'+import { ContextDropdown } from './ContextDropdown'import { MemoryDebugToggle } from './MemoryDebugPanel'import { ABCompare } from './ABCompare'import { useCompareStore } from '../../stores/compareStore'@@ -192,6 +193,9 @@ export function ChatView() {{/* Token Counter */}<TokenCounter />+ {/* Context window picker (Ollama num_ctx / LM Studio loaded ctx) */}+ <ContextDropdown />+{/* Memory Debug */}<MemoryDebugToggle />diff --git a/src/components/chat/ContextDropdown.tsx b/src/components/chat/ContextDropdown.tsxnew file mode 100644index 00000000..a6cfa78a--- /dev/null+++ b/src/components/chat/ContextDropdown.tsx@@ -0,0 +1,114 @@+import { useState } from 'react'+import { ChevronDown, Check, Loader2 } from 'lucide-react'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { getProviderIdFromModel, displayModelName } from '../../api/providers'+import { getModelContextCached, warmupOllamaContext } from '../../api/ollama'+import { loadLmStudioModel } from '../../api/lmstudio'+import { effectiveContextWindow } from '../../lib/context-window'+import { useActiveContextWindow } from '../../hooks/useActiveContextWindow'++const PRESETS = [4096, 8192, 16384, 32768, 65536, 131072]++const fmt = (n: number) =>+ n <= 0 ? 'Auto'+ : n % 1024 === 0 ? `${n / 1024}K`+ : n >= 1000 ? `${Math.round(n / 1000)}K`+ : String(n)++/**+ * Context-window picker for the active LOCAL model. Sets `contextWindowOverride`+ * and AUTO-RELOADS the model so the change takes effect immediately:+ * - Ollama: warm the model with the new num_ctx (Ollama reloads its runner).+ * - LM Studio: `lms load -c <N>` (unload + reload — context is load-time there).+ * Hidden for cloud models (their context is fixed and not adjustable here).+ */+export function ContextDropdown() {+ const activeModel = useModelStore((s) => s.activeModel)+ const override = useSettingsStore((s) => s.settings.contextWindowOverride)+ const updateSettings = useSettingsStore((s) => s.updateSettings)+ const [open, setOpen] = useState(false)+ const [busy, setBusy] = useState(false)+ const [tick, setTick] = useState(0)+ const ctx = useActiveContextWindow(tick)++ if (!activeModel || !ctx.adjustable) return null++ const max = ctx.modelMax > 0 ? ctx.modelMax : 131072+ const options = PRESETS.filter((p) => p <= Math.max(max, 4096))+ const showMax = ctx.modelMax > 0 && !options.includes(ctx.modelMax) && ctx.modelMax > (options[options.length - 1] || 0)++ const apply = async (value: number) => {+ setOpen(false)+ if (value === override) return+ setBusy(true)+ updateSettings({ contextWindowOverride: value }) // 0 = Auto+ try {+ const providerId = getProviderIdFromModel(activeModel)+ if (providerId === 'ollama') {+ const target = value > 0+ ? value+ : effectiveContextWindow(await getModelContextCached(activeModel).catch(() => 0), 0)+ await warmupOllamaContext(activeModel, target)+ } else if (ctx.provider === 'lmstudio') {+ // value 0 (Auto) -> reload without -c so LM Studio picks its default.+ await loadLmStudioModel(displayModelName(activeModel), value > 0 ? value : undefined)+ }+ } catch {+ /* non-fatal — the counter will simply keep its prior value */+ } finally {+ setBusy(false)+ setTick((t) => t + 1) // re-read the model's real loaded context+ // Tell the token counter (and any other consumer) to re-read too.+ window.dispatchEvent(new Event('lu-context-reloaded'))+ }+ }++ const rowCls = (selected: boolean) =>+ `flex items-center justify-between gap-3 text-left px-2 py-1 rounded-md text-[0.6rem] transition-colors ${+ selected+ ? 'bg-gray-100 dark:bg-white/[0.08] text-gray-900 dark:text-white font-medium'+ : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-200'+ }`++ return (+ <div className="relative">+ <button+ onClick={() => setOpen((o) => !o)}+ disabled={busy}+ title={`Context window — ${ctx.provider === 'lmstudio' ? "LM Studio's loaded context" : 'Ollama num_ctx'}. Changing it reloads the model so it takes effect now.`}+ className="flex items-center gap-1 px-1.5 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem] font-mono tabular-nums disabled:opacity-60"+ >+ {busy ? <Loader2 size={9} className="animate-spin" /> : null}+ <span>ctx {fmt(ctx.contextWindow)}</span>+ <ChevronDown size={8} className={`transition-transform ${open ? 'rotate-180' : ''}`} />+ </button>+ {open && (+ <>+ <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />+ <div className="absolute right-0 top-full mt-1 z-50 min-w-[140px] rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl p-1 flex flex-col gap-0.5">+ <button onClick={() => apply(0)} className={rowCls(override === 0)}>+ <span>Auto{ctx.provider === 'ollama' ? ` · ${fmt(effectiveContextWindow(ctx.modelMax, 0))}` : ''}</span>+ {override === 0 && <Check size={10} />}+ </button>+ {options.map((p) => (+ <button key={p} onClick={() => apply(p)} className={rowCls(override === p)}>+ <span>{fmt(p)}</span>+ {override === p && <Check size={10} />}+ </button>+ ))}+ {showMax && (+ <button onClick={() => apply(ctx.modelMax)} className={rowCls(override === ctx.modelMax)}>+ <span>{fmt(ctx.modelMax)} · max</span>+ {override === ctx.modelMax && <Check size={10} />}+ </button>+ )}+ <div className="mt-0.5 px-2 pt-1 border-t border-gray-100 dark:border-white/[0.06] text-[0.5rem] text-gray-400 leading-snug">+ Reloads the model on change.+ </div>+ </div>+ </>+ )}+ </div>+ )+}diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsxindex 9f534c27..36f49919 100644--- a/src/components/chat/TokenCounter.tsx+++ b/src/components/chat/TokenCounter.tsx@@ -1,24 +1,16 @@-import { useState, useEffect } from 'react'import { useChatStore } from '../../stores/chatStore'-import { useModelStore } from '../../stores/modelStore'-import { useSettingsStore } from '../../stores/settingsStore'-import { estimateTokens, getModelMaxTokens } from '../../lib/context-compaction'-import { effectiveContextWindow } from '../../lib/context-window'+import { estimateTokens } from '../../lib/context-compaction'+import { useActiveContextWindow } from '../../hooks/useActiveContextWindow'export function TokenCounter() {const activeConversationId = useChatStore((s) => s.activeConversationId)const conversations = useChatStore((s) => s.conversations)- const activeModel = useModelStore((s) => s.activeModel)- // Settings override — when the user bumps maxTokens in Settings the counter- // should reflect that immediately, not just on next model switch. Bug #4- // (phantomderp v2.4.3): the bar stayed pinned to the model's default- // (e.g. 8.2k) even after the user moved the slider to 16384. Subscribing- // to the settings store fixes the staleness — `useSettingsStore` re-renders- // any consumer on every settings update.- // Context-window override (num_ctx), NOT maxTokens (that's the output limit- // num_predict — using it as the denominator was a long-standing mismatch).- const contextOverride = useSettingsStore((s) => s.settings.contextWindowOverride)- const [modelMaxTokens, setModelMaxTokens] = useState<number>(4096)++ // The denominator is the REAL context window the active model runs with —+ // provider-aware and shared with the Context dropdown so the two never drift+ // (David: "muss immer stimmen"). Ollama = the num_ctx we send; LM Studio =+ // loaded_context_length (what it actually loaded), NOT the model's max.+ const ctx = useActiveContextWindow()const conversation = conversations.find((c) => c.id === activeConversationId)const messages = conversation?.messages || []@@ -38,19 +30,11 @@ export function TokenCounter() {const usedTokens = lastUsage ? lastUsage.totalTokens : estimatedconst isReal = !!lastUsage- // Fetch max tokens when model changes — only the model-side default is- // cached here; the user override is read live from the settings store.- useEffect(() => {- if (!activeModel) return- getModelMaxTokens(activeModel).then(setModelMaxTokens).catch(() => setModelMaxTokens(4096))- }, [activeModel])-if (!activeConversationId || messages.length === 0) return null- // Denominator = the context window we actually send to the model (num_ctx):- // the override if set, else the model's real context capped for VRAM safety.- // Same formula the Ollama provider uses, so display and reality can't drift.- const maxTokens = effectiveContextWindow(modelMaxTokens, contextOverride)+ // Resolved real context window; fall back to the VRAM-safe default only while+ // the provider probe is still in flight (ctx not resolved yet).+ const maxTokens = ctx.contextWindow > 0 ? ctx.contextWindow : 16384const ratio = maxTokens > 0 ? usedTokens / maxTokens : 0const color = ratio > 0.8 ? 'text-red-400' : ratio > 0.5 ? 'text-amber-400' : 'text-gray-500'@@ -58,9 +42,14 @@ export function TokenCounter() {const formatK = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)+ const source = ctx.provider === 'lmstudio'+ ? "LM Studio loaded context"+ : ctx.provider === 'ollama'+ ? 'Ollama num_ctx'+ : 'model context'const title = isReal- ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (num_ctx) — real, reported by the model (includes system prompt + tools + RAG)`- : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (num_ctx) — estimate until the first reply`+ ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — real, reported by the model (includes system prompt + tools + RAG)`+ : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — estimate until the first reply`return (<div className={`flex items-center gap-1.5 px-2 py-1 ${color}`} title={title}>diff --git a/src/hooks/useActiveContextWindow.ts b/src/hooks/useActiveContextWindow.tsnew file mode 100644index 00000000..f8fe868e--- /dev/null+++ b/src/hooks/useActiveContextWindow.ts@@ -0,0 +1,115 @@+import { useState, useEffect } from 'react'+import { useModelStore } from '../stores/modelStore'+import { useSettingsStore } from '../stores/settingsStore'+import { getProviderIdFromModel, displayModelName } from '../api/providers'+import { getModelContextCached } from '../api/ollama'+import { getLmStudioModelContext } from '../api/lmstudio'+import { getModelMaxTokens } from '../lib/context-compaction'+import { effectiveContextWindow } from '../lib/context-window'++export type CtxProvider = 'ollama' | 'lmstudio' | 'cloud' | 'unknown'++export interface ActiveContext {+ /** Which backend the active model runs on. */+ provider: CtxProvider+ /** The context window the model is ACTUALLY using right now — the TRUE+ * denominator for the token counter. */+ contextWindow: number+ /** The model's ceiling, used to cap the dropdown presets (0 = unknown). */+ modelMax: number+ /** True when the value is the model's real, confirmed live context (Ollama+ * num_ctx, or LM Studio's loaded_context_length) rather than a fallback. */+ isTrue: boolean+ /** Whether the user can change it from the dropdown (local backends only). */+ adjustable: boolean+}++/**+ * Resolve the REAL context window of the active model, provider-aware, so the+ * TokenCounter denominator and the Context dropdown agree and never lie:+ * - Ollama: num_ctx we send = effectiveContextWindow(realCtx, override).+ * - LM Studio: loaded_context_length from the enhanced REST API — the value+ * the model is genuinely running with (NOT its theoretical max).+ * - Cloud: the model's fixed max (can't be changed; not adjustable).+ *+ * `reloadTick` lets the dropdown force a re-read right after it reloads a model.+ */+export function useActiveContextWindow(reloadTick = 0): ActiveContext {+ const activeModel = useModelStore((s) => s.activeModel)+ const override = useSettingsStore((s) => s.settings.contextWindowOverride)+ const [state, setState] = useState<ActiveContext>({+ provider: 'unknown', contextWindow: 0, modelMax: 0, isTrue: false, adjustable: false,+ })++ // Re-read whenever a model reload finishes anywhere (the Context dropdown+ // fires this), so every consumer — counter AND dropdown — reflects the new+ // loaded context at the same time instead of drifting.+ const [reloadBump, setReloadBump] = useState(0)+ useEffect(() => {+ const onReloaded = () => setReloadBump((b) => b + 1)+ window.addEventListener('lu-context-reloaded', onReloaded)+ return () => window.removeEventListener('lu-context-reloaded', onReloaded)+ }, [])++ useEffect(() => {+ if (!activeModel) {+ setState({ provider: 'unknown', contextWindow: 0, modelMax: 0, isTrue: false, adjustable: false })+ return+ }+ let cancelled = false+ const providerId = getProviderIdFromModel(activeModel)++ ;(async () => {+ // ── Ollama: num_ctx is per-request, so what we send == what runs. ──+ if (providerId === 'ollama') {+ const max = await getModelContextCached(activeModel).catch(() => 0)+ if (cancelled) return+ setState({+ provider: 'ollama',+ contextWindow: effectiveContextWindow(max, override),+ modelMax: max,+ isTrue: true,+ adjustable: true,+ })+ return+ }++ // ── openai-compat: probe LM Studio's enhanced API. A real loaded/max+ // value means it IS LM Studio; null means a cloud/other openai server. ──+ if (providerId === 'openai') {+ const modelId = displayModelName(activeModel)+ const info = await getLmStudioModelContext(modelId)+ if (cancelled) return+ if (info.loaded || info.max) {+ const loaded = info.loaded ?? 0+ const max = info.max ?? loaded+ setState({+ provider: 'lmstudio',+ contextWindow: loaded > 0+ ? loaded // TRUE: what LM Studio actually loaded+ : (override > 0 ? override : Math.min(max || 8192, 16384)),+ modelMax: max,+ isTrue: loaded > 0,+ adjustable: true,+ })+ return+ }+ }++ // ── Cloud / other: fixed context, not adjustable from here. ──+ const max = await getModelMaxTokens(activeModel).catch(() => 4096)+ if (cancelled) return+ setState({+ provider: 'cloud',+ contextWindow: effectiveContextWindow(max, override),+ modelMax: max,+ isTrue: false,+ adjustable: false,+ })+ })()++ return () => { cancelled = true }+ }, [activeModel, override, reloadTick, reloadBump])++ return state+}