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(vram-handoff): evict from LIVE GPU state - the agent-loop pin was dead in release builds
purple23984a16c939
diff --git a/src/api/__tests__/agent-context-singleton.test.ts b/src/api/__tests__/agent-context-singleton.test.tsnew file mode 100644index 00000000..83af6b2e--- /dev/null+++ b/src/api/__tests__/agent-context-singleton.test.ts@@ -0,0 +1,79 @@+/**+ * agent-context duplication guard (v2.5.3 live E2E find, 2026-06-11).+ *+ * The rolldown-based production build DUPLICATED the agent-context module:+ * the App chunk inlined one copy (written by useAgentChat/useCodex) while the+ * dynamically imported mcp/vram-handoff graph read the separate chunk's copy+ * — so getActiveAgentModel() was always null in the release app and VRAM+ * eviction silently never ran (proven via live console capture + the `noid`+ * literal appearing in two dist chunks).+ *+ * The fix parks the mutable state on `globalThis.__LU_AGENT_CTX`. These tests+ * simulate "two bundled copies" with vi.resetModules() + a fresh dynamic+ * import: a SECOND module instance must see state written by the FIRST.+ *+ * Run: npx vitest run src/api/__tests__/agent-context-singleton.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++type AgentContextModule = typeof import('../agent-context')++async function freshCopy(): Promise<AgentContextModule> {+ vi.resetModules()+ return (await import('../agent-context')) as AgentContextModule+}++beforeEach(async () => {+ // Start every test from a clean carrier, whatever earlier tests did.+ delete (globalThis as Record<string, unknown>).__LU_AGENT_CTX+})++describe('agent-context state survives module duplication', () => {+ it('a second module copy sees the agent model pinned by the first', async () => {+ const copyA = await freshCopy()+ copyA.setActiveAgentModel({ name: 'gemma4:e4b', providerId: 'ollama', remote: false })++ const copyB = await freshCopy()+ expect(copyB.getActiveAgentModel()).toEqual({+ name: 'gemma4:e4b',+ providerId: 'ollama',+ remote: false,+ })+ })++ it('chatId and workspace cross copies the same way', async () => {+ const copyA = await freshCopy()+ copyA.setActiveChatId('my-chat-abc123')+ copyA.setActiveWorkspace({ kind: 'folder', path: 'C:/repo', extraPaths: ['C:/other'] })++ const copyB = await freshCopy()+ expect(copyB.getActiveChatId()).toBe('my-chat-abc123')+ expect(copyB.getActiveWorkspace()).toEqual({+ kind: 'folder',+ path: 'C:/repo',+ extraPaths: ['C:/other'],+ })+ })++ it('clearActiveChatId in one copy clears for all copies', async () => {+ const copyA = await freshCopy()+ copyA.setActiveChatId('chat-1')+ copyA.setActiveAgentModel({ name: 'qwen/qwen2.5-vl-7b', providerId: 'openai', remote: false })++ const copyB = await freshCopy()+ copyB.clearActiveChatId()++ expect(copyA.getActiveChatId()).toBeNull()+ expect(copyA.getActiveAgentModel()).toBeNull()+ expect(copyA.getActiveWorkspace()).toBeNull()+ })++ it('plain set/get round-trip still works within one copy', async () => {+ const ctx = await freshCopy()+ expect(ctx.getActiveAgentModel()).toBeNull()+ ctx.setActiveAgentModel({ name: 'x', providerId: 'ollama', remote: true })+ expect(ctx.getActiveAgentModel()).toEqual({ name: 'x', providerId: 'ollama', remote: true })+ ctx.setActiveAgentModel(null)+ expect(ctx.getActiveAgentModel()).toBeNull()+ })+})diff --git a/src/api/__tests__/vram-handoff-lms.test.ts b/src/api/__tests__/vram-handoff-lms.test.tsindex 9134771b..64f87b10 100644--- a/src/api/__tests__/vram-handoff-lms.test.ts+++ b/src/api/__tests__/vram-handoff-lms.test.ts@@ -14,7 +14,7 @@ vi.mock('../backend', async (importOriginal) => {return { ...actual, backendCall: vi.fn() }})-import { detectLmsTextModel, estimateLmsTextVramBytes } from '../vram-handoff'+import { detectLmsTextModel, detectAnyLoadedLmsModel, estimateLmsTextVramBytes, pickResidentOllamaTarget } from '../vram-handoff'import { backendCall } from '../backend'beforeEach(() => {@@ -52,6 +52,73 @@ describe('detectLmsTextModel', () => {})})+describe('detectAnyLoadedLmsModel (live-state fallback)', () => {+ // Why this exists: the pinned agent-loop model proved unreliable in the+ // release build (rolldown duplicated agent-context → the pin read null) and+ // Codex never pinned at all. Live E2E 2026-06-11: qwen2.5-vl-7b stayed+ // resident through SDXL + SVD generations because the pin-gated detection+ // never ran. This fallback asks the LM Studio REST what is ACTUALLY loaded.+ it('returns the first loaded model with its context length', async () => {+ vi.mocked(backendCall)+ .mockResolvedValueOnce({ loaded: ['qwen/qwen2.5-vl-7b'] } as never)+ .mockResolvedValueOnce({ loaded: 8192, max: 128000, state: 'loaded' } as never)+ const r = await detectAnyLoadedLmsModel()+ expect(r).toEqual({ id: 'qwen/qwen2.5-vl-7b', contextLength: 8192 })+ expect(backendCall).toHaveBeenNthCalledWith(1, 'lmstudio_list_loaded', {})+ expect(backendCall).toHaveBeenNthCalledWith(2, 'lmstudio_model_context', { model: 'qwen/qwen2.5-vl-7b' })+ })++ it('nothing loaded → null', async () => {+ vi.mocked(backendCall).mockResolvedValue({ loaded: [] } as never)+ expect(await detectAnyLoadedLmsModel()).toBeNull()+ })++ it('LM Studio absent / command error → null', async () => {+ vi.mocked(backendCall).mockRejectedValue(new Error('connection refused'))+ expect(await detectAnyLoadedLmsModel()).toBeNull()+ })++ it('context probe failure still returns the model (reload without -c)', async () => {+ vi.mocked(backendCall)+ .mockResolvedValueOnce({ loaded: ['some-model-7b'] } as never)+ .mockRejectedValueOnce(new Error('timeout'))+ expect(await detectAnyLoadedLmsModel()).toEqual({ id: 'some-model-7b', contextLength: null })+ })+})++describe('pickResidentOllamaTarget (live-state fallback)', () => {+ const gemma = { name: 'gemma4:e4b', sizeVram: 5_000_000_000 }+ const coder = { name: 'qwen2.5-coder:14b', sizeVram: 9_000_000_000 }++ it('empty resident list → null', () => {+ expect(pickResidentOllamaTarget([], null)).toBeNull()+ })++ it('pinned local-ollama model wins when resident', () => {+ const active = { name: 'gemma4:e4b', providerId: 'ollama', remote: false }+ expect(pickResidentOllamaTarget([coder, gemma], active)).toEqual(gemma)+ })++ it('pin lost (null) → largest resident model', () => {+ expect(pickResidentOllamaTarget([gemma, coder], null)).toEqual(coder)+ })++ it('pinned model not resident → largest resident model', () => {+ const active = { name: 'llama3:8b', providerId: 'ollama', remote: false }+ expect(pickResidentOllamaTarget([gemma, coder], active)).toEqual(coder)+ })++ it('cloud/remote pins never match — falls back to largest', () => {+ expect(pickResidentOllamaTarget([gemma], { name: 'gemma4:e4b', providerId: 'openai', remote: false })).toEqual(gemma)+ expect(pickResidentOllamaTarget([coder, gemma], { name: 'gemma4:e4b', providerId: 'ollama', remote: true })).toEqual(coder)+ })++ it('single model with unknown size is still the target', () => {+ const m = { name: 'mystery:latest' }+ expect(pickResidentOllamaTarget([m], null)).toEqual(m)+ })+})+describe('estimateLmsTextVramBytes', () => {it('parses parameter counts from common ids', () => {expect(estimateLmsTextVramBytes('qwen/qwen2.5-vl-7b')).toBe(Math.round(7 * 0.75 * 1e9))diff --git a/src/api/agent-context.ts b/src/api/agent-context.tsindex 964c3afb..0dca964a 100644--- a/src/api/agent-context.ts+++ b/src/api/agent-context.ts@@ -21,8 +21,29 @@import type { AgentWorkspace } from '../types/agent-workspace'-let activeChatId: string | null = null-let activeWorkspace: AgentWorkspace | null = null+/**+ * Duplication-proof state carrier (v2.5.3 live E2E find, 2026-06-11).+ *+ * The rolldown-based Vite 8 build DUPLICATES this small module: the App+ * chunk inlines its own copy (used by useAgentChat/useCodex) while the+ * async mcp/vram-handoff graph imports the separate agent-context chunk.+ * Proven live on the release build: the hook's setActiveAgentModel wrote+ * copy A while vramHandoffGenerate's getActiveAgentModel read copy B —+ * always null — so VRAM eviction silently never ran, and the builtin+ * tools' chatId/workspace scoping read nulls the same way (grep the dist+ * for the `noid` slug literal: it appears in TWO chunks).+ *+ * Plain `let` module state is therefore NOT a singleton here. Parking the+ * state on `globalThis` makes every bundled copy share one store, whatever+ * the chunker decides. Do not "simplify" this back to module-level lets.+ */+interface AgentCtxState {+ chatId: string | null+ workspace: AgentWorkspace | null+ model: ActiveAgentModel | null+}+const _g = globalThis as typeof globalThis & { __LU_AGENT_CTX?: AgentCtxState }+const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, workspace: null, model: null })/*** The text model driving the current agent loop. Pinned by useAgentChat right@@ -44,28 +65,26 @@ export interface ActiveAgentModel {remote: boolean}-let activeAgentModel: ActiveAgentModel | null = null-export function setActiveChatId(id: string | null | undefined): void {- activeChatId = id ? String(id) : null+ ctx.chatId = id ? String(id) : null}export function getActiveChatId(): string | null {- return activeChatId+ return ctx.chatId}export function setActiveAgentModel(model: ActiveAgentModel | null | undefined): void {- activeAgentModel = model && model.name ? { name: model.name, providerId: model.providerId, remote: !!model.remote } : null+ ctx.model = model && model.name ? { name: model.name, providerId: model.providerId, remote: !!model.remote } : null}export function getActiveAgentModel(): ActiveAgentModel | null {- return activeAgentModel+ return ctx.model}export function clearActiveChatId(): void {- activeChatId = null- activeWorkspace = null- activeAgentModel = null+ ctx.chatId = null+ ctx.workspace = null+ ctx.model = null}// ── Multi-Repo Agent (Sprint C #8 from uselu) ──────────────────@@ -96,7 +115,7 @@ export function setActiveWorkspace(ws: AgentWorkspace | null | undefined): void),): []- activeWorkspace = {+ ctx.workspace = {kind: 'folder',path: ws.path,extraPaths: cleanedExtras.length > 0 ? cleanedExtras : undefined,@@ -105,12 +124,12 @@ export function setActiveWorkspace(ws: AgentWorkspace | null | undefined): void// Sandbox (or unset) → leave pointer null so the bridge falls back// to its own per-chat sandbox path. Setting it to { kind: 'sandbox' }// would just duplicate state the bridge already owns.- activeWorkspace = null+ ctx.workspace = null}}export function getActiveWorkspace(): AgentWorkspace | null {- return activeWorkspace+ return ctx.workspace}/**diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex 6be00d7d..10386e2f 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -395,6 +395,48 @@ export async function detectLmsTextModel(return null}+/** Live-truth fallback (v2.5.3 follow-up): whatever the LOCAL LM Studio REST+ * reports as loaded holds VRAM — regardless of which provider the chat uses+ * or whether the agent-loop pin survived (rolldown chunk duplication ate it+ * in the release build, and Codex never pinned). Returns the first loaded+ * model with its loaded context length, or null when LM Studio is absent /+ * nothing is loaded. */+export async function detectAnyLoadedLmsModel(): Promise<LmsTextModel | null> {+ try {+ const list = await backendCall<{ loaded: string[] }>('lmstudio_list_loaded', {})+ const id = Array.isArray(list?.loaded) ? list.loaded.find((m) => typeof m === 'string' && m) : undefined+ if (!id) return null+ let contextLength: number | null = null+ try {+ const info = await backendCall<{ loaded: number | null }>('lmstudio_model_context', { model: id })+ contextLength = typeof info?.loaded === 'number' ? info.loaded : null+ } catch { /* context unknown — reload without -c */ }+ return { id, contextLength }+ } catch {+ return null+ }+}++/** Pure pick: which resident Ollama model is the evict-then-reload target?+ * The pinned agent-loop model wins when it is actually resident; otherwise+ * the largest resident one (in practice: the chat model). Exported for the+ * unit tests — the live-state fallback this feeds exists because the pin+ * alone proved unreliable (chunk duplication / unpinned callers). */+export function pickResidentOllamaTarget(+ resident: { name: string; sizeVram?: number }[],+ active: { name: string; providerId: string; remote: boolean } | null,+): { name: string; sizeVram?: number } | null {+ if (resident.length === 0) return null+ const preferred =+ active && active.providerId === 'ollama' && active.remote === false+ ? resident.find((m) => m.name === active.name)+ : undefined+ return (+ preferred ??+ resident.reduce((a, b) => (((b.sizeVram ?? 0) > (a.sizeVram ?? 0)) ? b : a))+ )+}+/** Rough VRAM estimate for an LM Studio text model from its id's parameter* count ("…-7b…" → ~5.3 GB at Q4 + context overhead). LM Studio's REST has* no VRAM figure, so this feeds decideUnload the same way Ollama's@@ -577,72 +619,75 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promireturn `Error: Could not query ComfyUI models — ${e instanceof Error ? e.message : String(e)}. Is ComfyUI installed and reachable?`}- // Which text model do we reload afterwards? From the active agent loop.+ // Which text model do we reload afterwards? The pinned agent-loop model is+ // the PREFERENCE — but the pin has proven fragile in the wild (the rolldown+ // build duplicated agent-context so the pin read null in the release app,+ // and Codex never pinned at all; live E2E 2026-06-11). What actually holds+ // VRAM is authoritative, so the decision now starts from the LIVE state:+ // /api/ps for a local Ollama, the LM Studio REST for a local LM Studio.+ // Cloud providers / remote bases never show up in either probe, so they+ // skip juggling exactly as before.const active = getActiveAgentModel()- // Cloud (openai/anthropic/openrouter/...) OR a remote Ollama base hold NO- // local VRAM — there is nothing to free or restore, so skip all juggling and- // just generate. `active.remote` is set by useAgentChat from the Ollama base- // host; providerId !== 'ollama' covers the cloud providers.- const textIsLocalOllama =- !!active && active.providerId === 'ollama' && active.remote === false && isOllamaLocal()- const textModel = textIsLocalOllama ? active!.name : null-- // LM Studio (v2.5.3, live E2E 2026-06-10): an 'openai' provider can be a- // LOCAL LM Studio holding real VRAM. Pre-fix the orchestrator skipped all- // juggling for it — on a 12 GB card qwen2.5-vl-7b (~5 GB) stayed resident- // and an SDXL generation thrashed at 11.9/12 GB. Detection is empirical,- // not metadata-based: the model id reports state==='loaded' on the local- // LM Studio REST (lmstudio_model_context) → it holds local VRAM.- const lmsTarget = textModel ? null : await detectLmsTextModel(active)-- // ── Decide unload (only relevant for a local Ollama text model) ──- let willUnload = false- if (textModel) {++ // ── Ollama side (live): resident models from /api/ps ──────────────+ let textModel: string | null = null+ let textVramBytes: number | undefined+ if (isOllamaLocal()) {try {- const [resident, footprint, systemVram, mode] = await Promise.all([- getResidentModels(),- Promise.resolve(estimateModelFootprintGB(targetModel)),- getSystemVRAM(),- Promise.resolve(getExclusiveVramMode()),- ])- const textEntry = resident.find((m) => m.name === textModel)- const decision = decideUnload({- textVramBytes: textEntry?.sizeVram,- modelFootprintGB: footprint,- systemVramGB: systemVram,- mode,- })- willUnload = decision.unload- log.info('vram_handoff.decision', { kind, targetModel, textModel, ...decision })- } catch (e) {- // Decision probe failed — default to NOT unloading (safer; attempt gen).- log.warn('vram_handoff.decision_failed', { err: String(e) })- willUnload = false+ const resident = await getResidentModels()+ const candidate = pickResidentOllamaTarget(resident, active)+ if (candidate) {+ textModel = candidate.name+ textVramBytes = candidate.sizeVram+ }+ } catch {+ // /api/ps unreachable → treat as nothing resident (no Ollama to juggle).}}- // ── Decide unload for a local LM Studio text model — same decideUnload- // math, same exclusiveVramMode setting. LM Studio's REST reports no VRAM- // figure, so the resident size is a parameter-count heuristic from the id- // (estimateLmsTextVramBytes); unknown sizes keep the safe no-evict default.+ // ── LM Studio side (live): pinned context first, then list_loaded ──+ // detectLmsTextModel covers the pinned 'openai' chat model; the fallback+ // covers everything the pin misses (Codex, cloud chat with a stray loaded+ // LMS model, lost pin). Both only ever match the LOCAL LM Studio REST.+ let lmsTarget = await detectLmsTextModel(active)+ if (!lmsTarget) lmsTarget = await detectAnyLoadedLmsModel()+ const lmsVramBytes = lmsTarget ? estimateLmsTextVramBytes(lmsTarget.id) : undefined++ // ── Decide: one shared fits/doesn't-fit call over EVERYTHING resident.+ // If the sum doesn't co-exist with the generation footprint, free BOTH+ // sides — over-evicting is lossless (both reload in the finally), while+ // under-evicting risks the exact 11.9/12 GB thrash this exists to avoid.+ let willUnload = falselet willUnloadLms = false- if (lmsTarget) {+ if (textModel || lmsTarget) {try {const [footprint, systemVram, mode] = await Promise.all([Promise.resolve(estimateModelFootprintGB(targetModel)),getSystemVRAM(),Promise.resolve(getExclusiveVramMode()),])+ const residentBytes = (textVramBytes ?? 0) + (lmsVramBytes ?? 0)const decision = decideUnload({- textVramBytes: estimateLmsTextVramBytes(lmsTarget.id),+ textVramBytes: residentBytes > 0 ? residentBytes : undefined,modelFootprintGB: footprint,systemVramGB: systemVram,mode,})- willUnloadLms = decision.unload- log.info('vram_handoff.decision_lms', { kind, targetModel, lmsModel: lmsTarget.id, ...decision })+ willUnload = decision.unload && !!textModel+ willUnloadLms = decision.unload && !!lmsTarget+ log.info('vram_handoff.decision', {+ kind,+ targetModel,+ textModel,+ lmsModel: lmsTarget?.id ?? null,+ textVramBytes,+ lmsVramBytes,+ ...decision,+ })} catch (e) {- log.warn('vram_handoff.decision_lms_failed', { err: String(e) })+ // Decision probe failed — default to NOT unloading (safer; attempt gen).+ log.warn('vram_handoff.decision_failed', { err: String(e) })+ willUnload = falsewillUnloadLms = false}}diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 46aafae5..b1abc2b3 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -10,11 +10,11 @@ import { usePermissionStore } from '../stores/permissionStore'import { getToolCallingStrategy } from '../lib/model-compatibility'import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { chatNonStreaming } from '../api/agents'-import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace } from '../api/agent-context'+import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel } from '../api/agent-context'import { resolveWorkspace } from '../api/agents/workspace-resolve'import { useAgentModeStore } from '../stores/agentModeStore'import { loadLurules, renderRulesSection, type RulesReader } from '../lib/lurules'-import { backendCall } from '../api/backend'+import { backendCall, isOllamaLocal } from '../api/backend'import { planWithArchitect, renderArchitectPlanSection } from '../api/agents/architect'import { fetchRepoMap, renderRepoMapSection } from '../api/agents/repo-map'import { isLocalModelByName } from '../api/agents/model-locality'@@ -276,6 +276,17 @@ export function useCodex() {: 'native'const modelToUse = activeModel.includes('::') ? activeModel.split('::')[1] : activeModel+ // Pin the text model driving this Codex run — parity with useAgentChat.+ // The VRAM hand-off orchestrator (image/video generation in Code mode,+ // v2.5.3) prefers this pin to pick its evict-then-reload target; without+ // it the live-state fallback still evicts, but the pin guarantees the+ // reload hits exactly the model this thread is using. Cleared in finally.+ setActiveAgentModel({+ name: modelToUse,+ providerId,+ remote: providerId === 'ollama' ? !isOllamaLocal() : false,+ })+// Build permissions — auto-approve reads, confirm writesconst permissions = usePermissionStore.getState().getEffectivePermissions(convId)