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(agent): the built-in engine grows to the context the run budgets for
purplefe01a94193a9
diff --git a/src/api/__tests__/builtin-agent-ctx.test.ts b/src/api/__tests__/builtin-agent-ctx.test.tsnew file mode 100644index 00000000..46a2ae3c--- /dev/null+++ b/src/api/__tests__/builtin-agent-ctx.test.ts@@ -0,0 +1,169 @@+/**+ * Z36 finding 2 (W3 run 2026-08-16): an agent turn carries the tool+ * catalogue and outgrows the built-in engine's 8192 start default while the+ * GGUF itself was trained for 32k, and nobody ever restarted the engine+ * bigger, so the prompt silently overflowed the real window.+ * ensureBuiltinAgentCtx raises the managed engine to+ * min(ctx_train, AGENT_CONTEXT_CAP) before an agent run. These tests pin+ * when it raises, when it must NOT (the negative controls: already big+ * enough, no header value, explicit user tuning), and the fallback path+ * when the bigger KV cache does not fit the card.+ *+ * Run: npx vitest run src/api/__tests__/builtin-agent-ctx.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import fs from 'node:fs'+import path from 'node:path'++let managed = true+let enabled = true+vi.mock('../../stores/providerStore', () => ({+ useProviderStore: {+ getState: () => ({ providers: { openai: { enabled, managed } } }),+ },+}))++const tuning: Record<string, unknown> = {}+let contextWindowOverride = 0+vi.mock('../../stores/settingsStore', () => ({+ useSettingsStore: {+ getState: () => ({ settings: { builtinEngine: tuning, contextWindowOverride } }),+ },+}))++const backendCall = vi.fn()+vi.mock('../backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+}))++import { ensureBuiltinAgentCtx, __resetAgentCtxStateForTests } from '../builtin-ensure'+import { AGENT_CONTEXT_CAP } from '../../lib/context-window'++const MODELS = { models: [{ name: 'qwen3-8b', path: '/models/qwen3-8b.gguf', ctx_train: 32768 }] }++function mockEngine(opts: {+ running?: boolean+ ctx?: number | null+ list?: unknown+ swapFails?: boolean+}) {+ backendCall.mockImplementation(async (cmd: unknown) => {+ if (cmd === 'bundled_engine_status') {+ return { running: opts.running ?? true, healthy: opts.running ?? true, ctx: opts.ctx ?? null }+ }+ if (cmd === 'list_bundled_models') return opts.list ?? MODELS+ if (cmd === 'swap_bundled_model') {+ if (opts.swapFails) throw new Error('llama-server exited: failed to allocate KV cache')+ return { status: 'started' }+ }+ if (cmd === 'start_bundled_engine') return { status: 'started' }+ throw new Error(`unexpected command ${String(cmd)}`)+ })+}++const callsTo = (cmd: string) => backendCall.mock.calls.filter((c) => c[0] === cmd)++describe('ensureBuiltinAgentCtx', () => {+ beforeEach(() => {+ backendCall.mockReset()+ __resetAgentCtxStateForTests()+ managed = true+ enabled = true+ contextWindowOverride = 0+ for (const k of Object.keys(tuning)) delete tuning[k]+ tuning.ctx = 8192 // the untouched shipped default+ })++ it('raises a running 8192 engine to the GGUF trained ctx', async () => {+ mockEngine({ running: true, ctx: 8192 })+ await ensureBuiltinAgentCtx('openai::qwen3-8b')+ const swaps = callsTo('swap_bundled_model')+ expect(swaps).toHaveLength(1)+ expect(swaps[0][1]).toMatchObject({ modelPath: '/models/qwen3-8b.gguf', tuning: { ctx: 32768 } })+ })++ it('caps a 131072-trained model at AGENT_CONTEXT_CAP', async () => {+ mockEngine({+ running: true,+ ctx: 8192,+ list: { models: [{ name: 'big', path: '/m/big.gguf', ctx_train: 131072 }] },+ })+ await ensureBuiltinAgentCtx('big')+ expect(callsTo('swap_bundled_model')[0][1]).toMatchObject({ tuning: { ctx: AGENT_CONTEXT_CAP } })+ })++ it('NEGATIVE: leaves an engine alone that already runs at the target', async () => {+ mockEngine({ running: true, ctx: 32768 })+ await ensureBuiltinAgentCtx('qwen3-8b')+ expect(callsTo('swap_bundled_model')).toHaveLength(0)+ expect(callsTo('start_bundled_engine')).toHaveLength(0)+ })++ it('NEGATIVE: never raises when the GGUF header states no trained ctx', async () => {+ mockEngine({+ running: true,+ ctx: 8192,+ list: { models: [{ name: 'mystery', path: '/m/mystery.gguf', ctx_train: null }] },+ })+ await ensureBuiltinAgentCtx('mystery')+ expect(callsTo('swap_bundled_model')).toHaveLength(0)+ expect(callsTo('start_bundled_engine')).toHaveLength(0)+ })++ it('NEGATIVE: an explicit user engine ctx wins, nothing is even probed', async () => {+ tuning.ctx = 12288 // the user touched the expert setting+ mockEngine({ running: true, ctx: 12288 })+ await ensureBuiltinAgentCtx('qwen3-8b')+ expect(backendCall).not.toHaveBeenCalled()+ })++ it('contextWindowOverride wins over the GGUF ceiling', async () => {+ contextWindowOverride = 24576+ mockEngine({ running: true, ctx: 8192 })+ await ensureBuiltinAgentCtx('qwen3-8b')+ expect(callsTo('swap_bundled_model')[0][1]).toMatchObject({ tuning: { ctx: 24576 } })+ })++ it('starts a stopped engine directly at the agent ctx (no start-then-swap)', async () => {+ mockEngine({ running: false })+ await ensureBuiltinAgentCtx('qwen3-8b')+ expect(callsTo('swap_bundled_model')).toHaveLength(0)+ const starts = callsTo('start_bundled_engine')+ expect(starts).toHaveLength(1)+ expect(starts[0][1]).toMatchObject({ tuning: { ctx: 32768 } })+ })++ it('falls back to the previous tuning when the raise fails, and never retries that pair', async () => {+ mockEngine({ running: true, ctx: 8192, swapFails: true })+ await ensureBuiltinAgentCtx('qwen3-8b')+ // Fallback restart with the untouched settings tuning, chat survives.+ const starts = callsTo('start_bundled_engine')+ expect(starts).toHaveLength(1)+ expect(starts[0][1]).toMatchObject({ tuning: { ctx: 8192 } })+ // Second agent turn: the refusal is remembered, no swap attempt again.+ backendCall.mockClear()+ mockEngine({ running: true, ctx: 8192, swapFails: true })+ await ensureBuiltinAgentCtx('qwen3-8b')+ expect(callsTo('swap_bundled_model')).toHaveLength(0)+ })++ it('does nothing when the slot is not the managed engine', async () => {+ managed = false+ await ensureBuiltinAgentCtx('qwen3-8b')+ expect(backendCall).not.toHaveBeenCalled()+ })+})++describe('wiring: the agent surfaces actually call the raise', () => {+ const read = (rel: string) => fs.readFileSync(path.resolve(__dirname, rel), 'utf8')++ it('useAgentChat and useCodex raise the engine before resolving the run budget', () => {+ expect(read('../../hooks/useAgentChat.ts')).toContain('ensureBuiltinAgentCtx(modelToUse)')+ expect(read('../../hooks/useCodex.ts')).toContain('ensureBuiltinAgentCtx(modelToUse)')+ })++ it('the run budget reads the started ctx from the engine status (openai provider clamp)', () => {+ const src = read('../providers/openai-provider.ts')+ expect(src).toContain("backendCall<{ running?: boolean; ctx?: number | null }>('bundled_engine_status')")+ })+})diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.tsindex e321de2e..006753aa 100644--- a/src/api/builtin-ensure.ts+++ b/src/api/builtin-ensure.ts@@ -17,14 +17,17 @@import { backendCall } from './backend'import { useProviderStore } from '../stores/providerStore'import { useSettingsStore } from '../stores/settingsStore'+import { AGENT_CONTEXT_CAP } from '../lib/context-window'interface EngineStatusLite {running: booleanhealthy: boolean+ /** The `--ctx-size` the chat engine was started with (ENG-3). */+ ctx?: number | null}interface BundledList {- models?: Array<{ name: string; path: string }>+ models?: Array<{ name: string; path: string; ctx_train?: number | null }>}// Coalesce concurrent sends (chat + title generation) into ONE health-check /@@ -111,3 +114,92 @@ export async function ensureBuiltinEngineAlive(modelName: string): Promise<void>})()return inflight}++// The default the engine ships with. A settings ctx equal to it is treated as+// "never touched", anything else as an explicit user choice that wins in both+// directions (see ensureBuiltinAgentCtx below).+const ENGINE_DEFAULT_CTX = 8192++// Models whose raise attempt failed once (path -> refused ctx). Without this+// a card that cannot allocate the bigger KV cache would retry the failing+// restart on every single agent turn.+const refusedCtxByPath = new Map<string, number>()++/** Test-only: forget refused raises so unit tests stay isolated. */+export function __resetAgentCtxStateForTests(): void {+ refusedCtxByPath.clear()+}++/**+ * Z36 finding 2 (W3 run 2026-08-16): an agent turn carries the full tool+ * catalogue and routinely outgrows the engine's 8192 default, while the GGUF+ * itself was trained for far more (ctx_train 32k live). llama-server's ctx is+ * a START-time flag, so unlike Ollama's per-request num_ctx somebody has to+ * restart the engine bigger, and nobody did: the prompt silently overflowed.+ *+ * This raises the managed built-in engine to the same ceiling the Ollama+ * agent path already uses: min(ctx_train, AGENT_CONTEXT_CAP), floored at the+ * 8192 default. It only ever raises, never shrinks, and only when the GGUF+ * header states the model can take it (no RoPE extrapolation on a guess).+ * A user-set engine ctx (anything other than the untouched 8192 default) or+ * a contextWindowOverride wins outright, matching resolveAgentNumCtx.+ *+ * When the raise attempt fails (a small card may not fit the bigger KV+ * cache), the engine is restarted with the previous tuning so chat survives,+ * and the (path, ctx) pair is remembered so we never retry-loop. Never+ * throws: an agent run must start even when none of this works.+ */+export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {+ if (!isManagedBuiltinSlot()) return+ const settings = useSettingsStore.getState().settings+ const tuning = settings.builtinEngine as (typeof settings.builtinEngine) | undefined+ if (tuning && typeof tuning.ctx === 'number' && tuning.ctx > 0 && tuning.ctx !== ENGINE_DEFAULT_CTX) {+ return // explicit expert choice, do not second-guess it+ }++ let status: EngineStatusLite | null+ try {+ status = await backendCall<EngineStatusLite>('bundled_engine_status')+ } catch {+ return // non-Tauri context (tests/browser)+ }++ let models: Array<{ name: string; path: string; ctx_train?: number | null }>+ try {+ const res = await backendCall<BundledList>('list_bundled_models')+ models = res?.models ?? []+ } catch {+ return+ }+ const bare = modelName.includes('::') ? modelName.split('::')[1] : modelName+ const hit = models.find((m) => m.name === bare)+ if (!hit) return++ const override = settings.contextWindowOverride+ let want = 0+ if (typeof override === 'number' && override > 0) {+ want = override+ } else if (typeof hit.ctx_train === 'number' && hit.ctx_train > 0) {+ want = Math.max(ENGINE_DEFAULT_CTX, Math.min(hit.ctx_train, AGENT_CONTEXT_CAP))+ } else {+ return // the GGUF does not state a trained context, never raise on a guess+ }++ if (refusedCtxByPath.get(hit.path) === want) return+ const current = status?.running && typeof status.ctx === 'number' && status.ctx > 0 ? status.ctx : 0+ if (current >= want) return++ const raised = { ...(tuning ?? {}), ctx: want }+ try {+ await backendCall(status?.running ? 'swap_bundled_model' : 'start_bundled_engine', {+ modelPath: hit.path,+ tuning: raised,+ })+ } catch {+ refusedCtxByPath.set(hit.path, want)+ // Fall back to the previous tuning so the chat engine is not left dead.+ try {+ await backendCall('start_bundled_engine', { modelPath: hit.path, tuning })+ } catch { /* the lazy self-heal on the next send takes over */ }+ }+}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 78010e94..92e1627c 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -18,8 +18,8 @@ import { parseSSEStream } from '../sse'import { repairJson } from '../../lib/tool-call-repair'import { signalCreditsExhausted } from '../../lib/credits-exhausted'import { parseRetryAfter } from '../../lib/http-status'-import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost } from '../backend'-import { ensureBuiltinEngineAlive, explainDeadEngine } from '../builtin-ensure'+import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost, backendCall } from '../backend'+import { ensureBuiltinEngineAlive, explainDeadEngine, isManagedBuiltinSlot } from '../builtin-ensure'// Transport routing lives in the `useLocalProxy` getter (below) plus the shared// host helpers in backend.ts. A direct webview fetch only works for hosts the@@ -862,6 +862,20 @@ export class OpenAIProvider implements ProviderClient {*/async loadedContextLength(model: string): Promise<number | null> {if (!this.isLanBackend) return null+ // Managed built-in engine (Z36 finding 2): llama-server has no LM Studio+ // enhanced API, so this probe used to return null and the run budget fell+ // back to catalog/name heuristics, happily budgeting 32k against an+ // engine started with 8192. The engine status carries the true started+ // ctx; use it, uncached, because ensureBuiltinAgentCtx may have JUST+ // swapped the engine bigger and a 5-minute-old value would clamp wrong+ // (or, after a render offload restart, fail to clamp at all).+ if (isManagedBuiltinSlot()) {+ try {+ const s = await backendCall<{ running?: boolean; ctx?: number | null }>('bundled_engine_status')+ if (s?.running && typeof s.ctx === 'number' && s.ctx > 0) return s.ctx+ } catch { /* non-Tauri context, fall through to the LM Studio probe */ }+ return null+ }const cacheKey = `loaded|${this.baseUrl}|${model}`const hit = OpenAIProvider.probeCache.get(cacheKey)if (hit && Date.now() - hit.at < 300_000) return hit.ctxdiff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex ae9ca0c1..a3f84f58 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -38,6 +38,7 @@ import { summarizeTurn } from '../lib/turn-summary'import { buildVisionFeedback } from '../api/vision-feedback'import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'import { resolveAgentNumCtx } from '../lib/agent-num-ctx'+import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'import { useMemoryStore } from '../stores/memoryStore'import { useVoiceStore } from '../stores/voiceStore'import { autoSpeak } from '../lib/ttsBridge'@@ -327,6 +328,16 @@ export function useAgentChat() {// only early return before the try (no conv) resets both.setIsAgentRunning(true)+ // Z36 finding 2: an agent turn carries the tool catalogue and outgrows+ // the built-in engine's 8192 start default, and llama-server's ctx is a+ // start-time flag no per-request option can raise. Lift the engine to+ // the agent ceiling (min of the GGUF's trained ctx and AGENT_CONTEXT_CAP)+ // BEFORE resolveAgentNumCtx reads the started ctx as the run budget.+ // No-op for every other provider; never throws.+ try {+ await ensureBuiltinAgentCtx(modelToUse)+ } catch { /* run with whatever the engine has */ }+// Create or get conversationlet convId = store.activeConversationIdif (!convId) {diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex b36cc2dd..337ccbdc 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -58,6 +58,7 @@ import { truncateToolResult } from '../lib/truncate-tool-result'import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS, CODE_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'import { resolveAgentNumCtx } from '../lib/agent-num-ctx'+import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'import { AgentLoopGuard } from '../lib/agent-loop-guard'import { findStagedForPath, stagedReadResult, stagedListingNote } from '../lib/staged-overlay'import { applyAllStagedChanges } from '../lib/staged-apply'@@ -733,6 +734,14 @@ export function useCodex() {// every iteration, forgot the files it had just read, and looped on the// same file_read for minutes (Morgan, 2026-07-26). Both the num_ctx we// send and the compaction target below derive from this one value.+ // Z36 finding 2: raise the managed built-in engine to the agent ceiling+ // (min of the GGUF's trained ctx and AGENT_CONTEXT_CAP) BEFORE the+ // resolver below reads the started ctx as this run's budget. The coding+ // loop carries the same tool catalogue that outgrows the 8192 default.+ try {+ await ensureBuiltinAgentCtx(modelToUse)+ } catch { /* run with whatever the engine has */ }+const numCtx: number = await resolveAgentNumCtx(modelToUse, providerId, settings.contextWindowOverride, activeModel,)