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(agent): drop the empty husk a stripped tool-call array leaves behind

purple3ace47aa4628
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 22c6f43b..920653b3 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -26,8 +26,7 @@ import { mediaCallSucceeded } from '../lib/media-result'
import { summarizeTurn } from '../lib/turn-summary'
import { buildVisionFeedback } from '../api/vision-feedback'
import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
-import { getModelContextCached } from '../api/ollama'
-import { effectiveContextWindow } from '../lib/context-window'
+import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
import { useMemoryStore } from '../stores/memoryStore'
import { useVoiceStore } from '../stores/voiceStore'
import { autoSpeak } from '../lib/ttsBridge'
@@ -64,8 +63,15 @@ async function extractMemories(userMsg: string, assistantMsg: string, conversati
const messages = buildExtractionPrompt(userMsg, assistantMsg, existingSummary)
const { provider, modelId } = getProviderForModel(activeModel)
+ // Same num_ctx as the turn that just finished. This call runs on the SAME
+ // model right after it, and Ollama reloads whenever num_ctx changes — sending
+ // nothing here dropped the user's context back to Ollama's default and cost a
+ // second model load on every single turn (seen live 2026-07-25).
+ const numCtx = await resolveAgentNumCtx(
+ modelId, getProviderIdFromModel(activeModel), useSettingsStore.getState().settings.contextWindowOverride,
+ )
let fullResponse = ''
- const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 500 })
+ const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 500, contextWindow: numCtx })
for await (const chunk of stream) {
if (chunk.content) fullResponse += chunk.content
if (chunk.done) break
@@ -640,15 +646,12 @@ export function useAgentChat() {
: settings.thinkingEnabled === true)
: undefined
- // num_ctx (David: "muss immer stimmen"): the override, else the model's
- // REAL context (capped for VRAM), floored at 8192 so feeding a generated
- // image back for vision feedback never overflows a 4096-default model.
- let agentCtx: number = settings.contextWindowOverride || 8192
- if (providerId === 'ollama' && !settings.contextWindowOverride) {
- try {
- agentCtx = Math.max(effectiveContextWindow(await getModelContextCached(modelId), 0), 8192)
- } catch { /* keep the 8192 floor on failure */ }
- }
+ // num_ctx (David: "muss immer stimmen"). Shared resolver so the memory
+ // extraction that runs after this turn sends the SAME value and Ollama
+ // does not reload the model at its default between the two.
+ const agentCtx: number = await resolveAgentNumCtx(
+ modelId, providerId, settings.contextWindowOverride,
+ )
const chatOptions = {
// Small-Model Mode (Knob 6): gently clamp temperature for tool turns.
// FOLKLORE, not measured — research found NO temperature finding for
diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.ts
index 25c39e45..96461bdc 100644
--- a/src/hooks/useMemory.ts
+++ b/src/hooks/useMemory.ts
@@ -10,7 +10,9 @@ import { useCallback } from 'react'
import { useMemoryStore } from '../stores/memoryStore'
import { useModelStore } from '../stores/modelStore'
import { useProviderStore } from '../stores/providerStore'
-import { getProviderForModel } from '../api/providers'
+import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
+import { useSettingsStore } from '../stores/settingsStore'
+import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
import {
buildExtractionPrompt,
parseExtractionResponse,
@@ -86,11 +88,22 @@ export async function extractMemoriesFromPair(
// Use active provider for extraction call
const { provider, modelId } = getProviderForModel(activeModel)
+ // Same num_ctx as the chat that just ran on this model. Ollama reloads the
+ // model whenever num_ctx changes between requests, so an options-less
+ // extraction call silently dropped the user's context back to the default
+ // and paid a second model load per turn.
+ const numCtx = await resolveAgentNumCtx(
+ modelId,
+ getProviderIdFromModel(activeModel),
+ useSettingsStore.getState().settings.contextWindowOverride,
+ )
+
// Collect full response via streaming
let fullResponse = ''
const stream = provider.chatStream(modelId, messages, {
temperature: 0.1,
maxTokens: 500,
+ contextWindow: numCtx,
})
for await (const chunk of stream) {
diff --git a/src/lib/__tests__/agent-num-ctx.test.ts b/src/lib/__tests__/agent-num-ctx.test.ts
new file mode 100644
index 00000000..70858d8a
--- /dev/null
+++ b/src/lib/__tests__/agent-num-ctx.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// The Ollama probe is the only I/O in the resolver.
+vi.mock('../../api/ollama', () => ({
+ getModelContextCached: vi.fn(),
+}))
+
+import { resolveAgentNumCtx } from '../agent-num-ctx'
+import { getModelContextCached } from '../../api/ollama'
+
+const probe = getModelContextCached as unknown as ReturnType<typeof vi.fn>
+
+describe('resolveAgentNumCtx — one num_ctx per model, per turn', () => {
+ beforeEach(() => probe.mockReset())
+
+ it('lets an explicit override win without probing the model', async () => {
+ expect(await resolveAgentNumCtx('qwen2.5-coder:14b', 'ollama', 32768)).toBe(32768)
+ expect(probe).not.toHaveBeenCalled()
+ })
+
+ it('uses the model context capped for VRAM when there is no override', async () => {
+ probe.mockResolvedValue(131072)
+ // DEFAULT_CONTEXT_CAP keeps the KV cache off a consumer GPU's back.
+ expect(await resolveAgentNumCtx('qwen2.5-coder:14b', 'ollama', 0)).toBe(16384)
+ })
+
+ it('floors at 8192 so vision feedback never overflows a 4096-default model', async () => {
+ probe.mockResolvedValue(4096)
+ expect(await resolveAgentNumCtx('tiny:1b', 'ollama', 0)).toBe(8192)
+ })
+
+ // NOT pinned: the resolver's catch branch (Ollama unreachable -> keep the
+ // 8192 floor). A vi.fn() that throws is recorded as a mock RESULT and this
+ // vitest version reports it as a test failure even when the code under test
+ // catches it — verified with a sync throw, an async throw and .resolves, all
+ // three report identically while the returned value is correct. Left
+ // uncovered rather than shipping a red test for working code.
+
+ it('does not probe Ollama for a cloud model', async () => {
+ expect(await resolveAgentNumCtx('Qwen/Qwen3-Coder-480B', 'lu-cloud', 0)).toBe(8192)
+ expect(probe).not.toHaveBeenCalled()
+ })
+
+ // The reason this resolver exists: the chat request and the memory-extraction
+ // request that follows it hit the SAME model, and Ollama reloads the model
+ // whenever num_ctx changes between requests. Same inputs must give the same
+ // number, or every turn pays a second model load (seen live 2026-07-25:
+ // chat sent 32768, extraction sent nothing, `ollama ps` fell back to 4096).
+ it('is stable across calls so the follow-up request never forces a reload', async () => {
+ probe.mockResolvedValue(32768)
+ const chat = await resolveAgentNumCtx('qwen2.5-coder:14b', 'ollama', 0)
+ const extraction = await resolveAgentNumCtx('qwen2.5-coder:14b', 'ollama', 0)
+ expect(extraction).toBe(chat)
+ })
+})
diff --git a/src/lib/__tests__/loose-tool-parse.test.ts b/src/lib/__tests__/loose-tool-parse.test.ts
index b7ef8fd1..a90934f9 100644
--- a/src/lib/__tests__/loose-tool-parse.test.ts
+++ b/src/lib/__tests__/loose-tool-parse.test.ts
@@ -319,4 +319,18 @@ describe('stripToolCallText — leftover Hermes tags', () => {
const prose = 'the log said ool_call> which is odd'
expect(stripToolCallText(prose, KN)).toBe(prose)
})
+
+ // Captured on the ship exe 2026-07-25 (Agent, qwen2.5-coder:14b): asked for
+ // two tools in one step, the model emitted them natively AND echoed both as
+ // one ```json ARRAY. The two objects were stripped by range and the user was
+ // left with a "notes" block containing nothing but `[`, a comma and `]`.
+ it('leaves no empty husk when an echoed call ARRAY is stripped', () => {
+ const echoed = 'Running both now.\n\n```json\n[\n {"name": "run_tests", "arguments": {}},\n {"name": "shell_execute", "arguments": {"command": "echo hi"}}\n]\n```'
+ expect(stripToolCallText(echoed, KN)).toBe('Running both now.')
+ })
+
+ it('never drops a fence that still carries real content', () => {
+ const code = 'Here is the patch:\n\n```js\nconst a = 1\n```'
+ expect(stripToolCallText(code, KN)).toContain('const a = 1')
+ })
})
diff --git a/src/lib/__tests__/strip-model-noise.test.ts b/src/lib/__tests__/strip-model-noise.test.ts
index ea896625..aeca204b 100644
--- a/src/lib/__tests__/strip-model-noise.test.ts
+++ b/src/lib/__tests__/strip-model-noise.test.ts
@@ -57,4 +57,20 @@ describe('stripModelNoise', () => {
expect(stripModelNoise('LOOP_DONE')).toBe('')
expect(stripModelNoise('ool_call>')).toBe('')
})
+
+ // Captured on the ship exe 2026-07-25: the model wrote BOTH of its calls as
+ // one ```json array while also emitting them natively. The objects were
+ // lifted out by range and the bubble showed an empty block holding `[ , ]`.
+ it('drops a fence whose body was fully consumed, leaving no empty husk', () => {
+ const husk = 'Running both now.\n\n```json\n[\n ,\n \n]\n```'
+ expect(stripModelNoise(husk, { aggressive: true })).toBe('Running both now.')
+ })
+
+ // The husk rule must not eat a fence that still carries content, and it is
+ // aggressive-only so a plain chat asked for an empty array still gets one.
+ it('keeps a fence that still has content, and an empty array in plain chat', () => {
+ const code = 'Here:\n\n```js\nconst a = 1\n```'
+ expect(stripModelNoise(code, { aggressive: true })).toContain('const a = 1')
+ expect(stripModelNoise('```json\n[]\n```')).toContain('[]')
+ })
})
diff --git a/src/lib/agent-num-ctx.ts b/src/lib/agent-num-ctx.ts
new file mode 100644
index 00000000..2f90f0b0
--- /dev/null
+++ b/src/lib/agent-num-ctx.ts
@@ -0,0 +1,41 @@
+/**
+ * The num_ctx an agent turn runs with — resolved in ONE place because every
+ * request that touches the SAME Ollama model must send the SAME value.
+ *
+ * Ollama allocates the KV cache at load time and RELOADS the model whenever
+ * num_ctx changes between requests. Captured off the wire on the ship exe
+ * (2026-07-25): the chat request went out with `num_ctx: 32768` and the memory
+ * extraction that follows EVERY agent turn went out with no options at all, so
+ * Ollama threw away the 32k allocation and reloaded the model at its own
+ * default. `ollama ps` then reported `context_length: 4096` while LU's own bar
+ * still said "ctx 32K", and each turn paid for two model loads instead of one.
+ *
+ * So: same model, same num_ctx, no reload. Callers that talk to a different
+ * model (a dedicated small extraction model, say) are free to resolve their own.
+ */
+
+import { getModelContextCached } from '../api/ollama'
+import { effectiveContextWindow } from './context-window'
+
+/**
+ * @param modelId provider-local model id (already stripped of any prefix)
+ * @param providerId 'ollama' | 'openai' | 'lu-cloud' | …
+ * @param override the user's contextWindowOverride (0 = none)
+ *
+ * The override wins outright. Without one, Ollama models get their REAL context
+ * capped for VRAM, floored at 8192 so feeding a generated image back for vision
+ * feedback never overflows a 4096-default model.
+ */
+export async function resolveAgentNumCtx(
+ modelId: string,
+ providerId: string,
+ override: number | undefined,
+): Promise<number> {
+ let ctx: number = override || 8192
+ if (providerId === 'ollama' && !override) {
+ try {
+ ctx = Math.max(effectiveContextWindow(await getModelContextCached(modelId), 0), 8192)
+ } catch { /* keep the 8192 floor on failure */ }
+ }
+ return ctx
+}
diff --git a/src/lib/loose-tool-parse.ts b/src/lib/loose-tool-parse.ts
index 1052ba1e..34d57215 100644
--- a/src/lib/loose-tool-parse.ts
+++ b/src/lib/loose-tool-parse.ts
@@ -298,6 +298,14 @@ export function stripToolCallText(text: string, known: string[]): string {
/["']?(?:arguments|parameters|params|prompt)["']?\s*[:=]/.test(inner)
return looksLikeCall ? '' : m
})
+ // A fence whose BODY was consumed by the strip above still leaves its
+ // container behind. Live Agent run on the ship exe (2026-07-25): the model
+ // wrote both of its calls as one ```json ARRAY next to perfectly good native
+ // tool_calls, the two objects were lifted out by range, and the bubble was
+ // left showing a "notes" block containing `[` , `,` , `]`. A fence with no
+ // letter or digit left in it carries nothing for the user, so drop it whole.
+ out = out.replace(/```[a-z_]*\s*([\s\S]*?)```/gi, (m, inner) =>
+ /[A-Za-z0-9]/.test(inner) ? m : '')
return out
// Strip special-token tool-call wrappers some models leave in the prose
// (Phi-4: <|tool_call|>/<|tool|>; Mistral: [TOOL_CALLS]) so they don't show
diff --git a/src/lib/strip-model-noise.ts b/src/lib/strip-model-noise.ts
index b26dd235..d9dbc153 100644
--- a/src/lib/strip-model-noise.ts
+++ b/src/lib/strip-model-noise.ts
@@ -75,6 +75,14 @@ export function stripModelNoise(text: string, opts: StripOptions = {}): string {
const { ranges } = extractToolCallsWithRanges(t)
if (ranges.length) t = stripRanges(t, ranges)
} catch { /* ignore — never let a strip error hide the answer */ }
+ // Range-based stripping removes the CALLS but leaves whatever wrapped them.
+ // Live Agent run on the ship exe 2026-07-25: the model wrote its two calls
+ // as one ```json array, both objects were lifted out, and the user was left
+ // with a block containing `[` , `,` , `]`. A fence with no letter or digit
+ // left in it is pure residue. Aggressive tier only, so a plain-chat answer
+ // that is deliberately an empty array still renders.
+ t = t.replace(/```[a-z_]*\s*([\s\S]*?)```/gi, (m, inner) =>
+ /[A-Za-z0-9]/.test(inner) ? m : '')
}
return t.trim()