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(engine): a speaker change stops handing back context, and the header re-reads it

purple50babc9c39d4
diff --git a/src/api/__tests__/builtin-swap-ctx.test.ts b/src/api/__tests__/builtin-swap-ctx.test.ts
new file mode 100644
index 00000000..89629a5b
--- /dev/null
+++ b/src/api/__tests__/builtin-swap-ctx.test.ts
@@ -0,0 +1,176 @@
+/**
+ * Counter-check round 2, side finding 3 (installed Windows build, 2026-08-29).
+ *
+ * In a two-model group chat the header said "ctx 32K" and the counter
+ * "555/32.8k", while every swap_bundled_model of that round asked for
+ * "ctx": 8192 and llama-server's /props confirmed 8192. Four times the context
+ * on screen than in the process.
+ *
+ * The 32K was real: an earlier agent turn had raised the engine through
+ * ensureBuiltinAgentCtx. The group round then went through
+ * ensureBuiltinEngineAlive, which restarts with the raw settings tuning whose
+ * untouched default is 8192, so every speaker change handed context back.
+ *
+ * Fixed on both sides: the swap keeps what the engine already holds, and every
+ * start/swap tells the display to re-read the engine, so the number on screen
+ * is the loaded one even where nothing could be kept.
+ *
+ * Run: npx vitest run src/api/__tests__/builtin-swap-ctx.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../backend', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../backend')>()
+ return { ...actual, backendCall: vi.fn() }
+})
+
+import { preservedSwapCtx, ENGINE_DEFAULT_CTX } from '../../lib/builtin-ctx'
+import { ensureBuiltinEngineAlive } from '../builtin-ensure'
+import { __resetEngineSwapGateForTests } from '../engine-swap-gate'
+import { backendCall } from '../backend'
+import { useProviderStore } from '../../stores/providerStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+
+describe('preservedSwapCtx', () => {
+ it('keeps the 32K the engine already runs instead of dropping to 8192', () => {
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 32768, ctxTrain: 131072 })).toBe(32768)
+ })
+
+ it('clamps to what the incoming GGUF was trained for', () => {
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 32768, ctxTrain: 16384 })).toBe(16384)
+ })
+
+ it('treats a missing tuning value as the untouched default', () => {
+ expect(preservedSwapCtx({ tuningCtx: undefined, currentCtx: 32768, ctxTrain: 32768 })).toBe(32768)
+ expect(preservedSwapCtx({ tuningCtx: 0, currentCtx: 24576, ctxTrain: 32768 })).toBe(24576)
+ })
+
+ // NEGATIVE CONTROLS: every reason NOT to touch the tuning.
+ it('leaves an expert value alone in both directions', () => {
+ expect(preservedSwapCtx({ tuningCtx: 4096, currentCtx: 32768, ctxTrain: 131072 })).toBeUndefined()
+ expect(preservedSwapCtx({ tuningCtx: 65536, currentCtx: 8192, ctxTrain: 131072 })).toBeUndefined()
+ })
+
+ it('never guesses when the GGUF header is silent about ctx_train', () => {
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 32768, ctxTrain: null })).toBeUndefined()
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 32768, ctxTrain: 0 })).toBeUndefined()
+ })
+
+ it('does nothing when no context is being given back', () => {
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 8192, ctxTrain: 131072 })).toBeUndefined()
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 4096, ctxTrain: 131072 })).toBeUndefined()
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: null, ctxTrain: 131072 })).toBeUndefined()
+ })
+
+ it('never raises above the default on a clamp that lands below it', () => {
+ expect(preservedSwapCtx({ tuningCtx: 8192, currentCtx: 32768, ctxTrain: 4096 })).toBeUndefined()
+ expect(ENGINE_DEFAULT_CTX).toBe(8192)
+ })
+})
+
+// ── The group round itself ───────────────────────────────────────────────────
+
+const MANAGED_URL = 'http://127.0.0.1:8127/v1'
+const GEMMA = '/m/gemma-3-4b-it-abliterated-Q4_K_M.gguf'
+const HERMES = '/m/Hermes-3-Llama-3.2-3B.Q4_K_M.gguf'
+
+/** The engine as the counter-check found it: up on Gemma with 32K loaded. */
+function engineOnGemmaAt32k(models: Array<{ name: string; path: string; ctx_train?: number }>) {
+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') {
+ return { running: true, healthy: true, ctx: 32768, model_path: GEMMA }
+ }
+ if (cmd === 'list_bundled_models') return { models }
+ return { status: 'started' }
+ }) as never)
+}
+
+const swapArgs = () =>
+ vi.mocked(backendCall).mock.calls.find((c) => c[0] === 'swap_bundled_model')?.[1] as
+ | { modelPath: string; tuning?: { ctx?: number } }
+ | undefined
+
+// The suite runs on the node environment (vitest.config.ts), so there is no
+// DOM. A bare EventTarget is all announceContextReload touches, and it lets
+// the test watch the event the header listens for.
+beforeEach(() => {
+ ;(globalThis as unknown as { window: EventTarget }).window = new EventTarget()
+ vi.mocked(backendCall).mockReset()
+ __resetEngineSwapGateForTests()
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: { ...s.providers.openai, enabled: true, managed: true, baseUrl: MANAGED_URL },
+ },
+ }))
+ useSettingsStore.setState((s) => ({
+ settings: { ...s.settings, builtinEngine: { ...s.settings.builtinEngine, ctx: 8192 } },
+ }))
+})
+
+describe('a group speaker change stops shrinking the context', () => {
+ it('swaps to the next speaker keeping 32K, not the 8192 default', async () => {
+ engineOnGemmaAt32k([
+ { name: 'gemma-3-4b-it-abliterated-Q4_K_M', path: GEMMA, ctx_train: 32768 },
+ { name: 'Hermes-3-Llama-3.2-3B.Q4_K_M', path: HERMES, ctx_train: 131072 },
+ ])
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ expect(swapArgs()?.modelPath).toBe(HERMES)
+ expect(swapArgs()?.tuning?.ctx).toBe(32768)
+ })
+
+ // NEGATIVE CONTROL: the model coming in cannot take 32K, so the swap must
+ // ask for what its header allows and no more.
+ it('clamps to the incoming model trained context', async () => {
+ engineOnGemmaAt32k([
+ { name: 'gemma-3-4b-it-abliterated-Q4_K_M', path: GEMMA, ctx_train: 32768 },
+ { name: 'Hermes-3-Llama-3.2-3B.Q4_K_M', path: HERMES, ctx_train: 16384 },
+ ])
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ expect(swapArgs()?.tuning?.ctx).toBe(16384)
+ })
+
+ // NEGATIVE CONTROL: an expert ctx is a decision, and the group round must
+ // not quietly override it.
+ it('leaves an expert ctx exactly where the user put it', async () => {
+ useSettingsStore.setState((s) => ({
+ settings: { ...s.settings, builtinEngine: { ...s.settings.builtinEngine, ctx: 4096 } },
+ }))
+ engineOnGemmaAt32k([
+ { name: 'gemma-3-4b-it-abliterated-Q4_K_M', path: GEMMA, ctx_train: 32768 },
+ { name: 'Hermes-3-Llama-3.2-3B.Q4_K_M', path: HERMES, ctx_train: 131072 },
+ ])
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ expect(swapArgs()?.tuning?.ctx).toBe(4096)
+ })
+})
+
+describe('the display re-reads the engine after every swap', () => {
+ it('fires lu-context-reloaded so the header cannot keep a stale number', async () => {
+ const seen = vi.fn()
+ window.addEventListener('lu-context-reloaded', seen)
+ engineOnGemmaAt32k([
+ { name: 'gemma-3-4b-it-abliterated-Q4_K_M', path: GEMMA, ctx_train: 32768 },
+ { name: 'Hermes-3-Llama-3.2-3B.Q4_K_M', path: HERMES, ctx_train: 131072 },
+ ])
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ window.removeEventListener('lu-context-reloaded', seen)
+ expect(seen).toHaveBeenCalled()
+ })
+
+ // NEGATIVE CONTROL: nothing was restarted, so nothing may claim it was.
+ // A stray event on every send would make the header re-probe for nothing.
+ it('stays quiet when the engine already holds the right model', async () => {
+ const seen = vi.fn()
+ window.addEventListener('lu-context-reloaded', seen)
+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') {
+ return { running: true, healthy: true, ctx: 32768, model_path: HERMES }
+ }
+ return { models: [] }
+ }) as never)
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ window.removeEventListener('lu-context-reloaded', seen)
+ expect(seen).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index 4cec6b0d..d125e83e 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -21,6 +21,7 @@ import { useProviderStore } from '../stores/providerStore'
import { useSettingsStore } from '../stores/settingsStore'
import { builtinSlotStatus, type SlotStatus } from '../lib/builtin-slot-status'
import { AGENT_CONTEXT_CAP } from '../lib/context-window'
+import { ENGINE_DEFAULT_CTX, preservedSwapCtx } from '../lib/builtin-ctx'
import {
bareBuiltinModelName,
builtinModelMatches,
@@ -181,7 +182,7 @@ async function loadBuiltinModel(modelName: string): Promise<void> {
const rightModel = builtinModelMatches(status?.model_path, modelName)
if (status?.healthy && rightModel) return
- let models: Array<{ name: string; path: string }>
+ let models: Array<{ name: string; path: string; ctx_train?: number | null }>
try {
const res = await backendCall<BundledList>('list_bundled_models')
models = res?.models ?? []
@@ -214,19 +215,39 @@ async function loadBuiltinModel(modelName: string): Promise<void> {
// Restart with the user's expert tuning, not bare defaults — otherwise a
// self-heal would silently drop a configured ctx/KV-quant until the next
// manual model pick.
- const tuning = useSettingsStore.getState().settings.builtinEngine
+ const settingsTuning = useSettingsStore.getState().settings.builtinEngine
+ // ... and do not hand back context the engine already holds. A group round
+ // restarts the engine before every speaker; with the raw 8192 default in the
+ // tuning that shrank a 32K engine to 8K on each swap while the header still
+ // promised 32K (counter-check round 2, 2026-08-29). See lib/builtin-ctx.ts.
+ const keepCtx = preservedSwapCtx({
+ tuningCtx: settingsTuning?.ctx,
+ currentCtx: status?.ctx,
+ ctxTrain: hit.ctx_train,
+ })
+ const tuning = keepCtx ? { ...(settingsTuning ?? {}), ctx: keepCtx } : settingsTuning
// A running engine holding the WRONG model is a swap (stop, then start on
// the same port). Everything else is a plain start, which is idempotent for
// the same model and tuning, so an engine that is merely still warming up is
// never torn down and restarted for nothing.
const cmd = status?.running && !rightModel ? 'swap_bundled_model' : 'start_bundled_engine'
await trackEngineSwap(backendCall(cmd, { modelPath: hit.path, tuning }))
+ // The engine is a different process with a different ctx now. Tell the
+ // header and the token counter to re-read it, so the number on screen is the
+ // one llama-server actually started with even when the raise above was
+ // refused or skipped. Second half of the same finding: the display must not
+ // be able to lie, whatever the swap ended up asking for.
+ announceContextReload()
}
-// 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
+/** Ask every context consumer to re-read the engine. No-op outside a DOM. */
+function announceContextReload(): void {
+ try {
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
+ window.dispatchEvent(new Event('lu-context-reloaded'))
+ }
+ } catch { /* a missing DOM is not a reason to fail a send */ }
+}
// Models whose raise attempt failed once (path -> refused ctx). Without this
// a card that cannot allocate the bigger KV cache would retry the failing
@@ -303,11 +324,13 @@ export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {
modelPath: hit.path,
tuning: raised,
}))
+ announceContextReload()
} 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 })
+ await trackEngineSwap(backendCall('start_bundled_engine', { modelPath: hit.path, tuning }))
+ announceContextReload()
} catch { /* the lazy self-heal on the next send takes over */ }
}
}
diff --git a/src/lib/builtin-ctx.ts b/src/lib/builtin-ctx.ts
new file mode 100644
index 00000000..8a08e5b5
--- /dev/null
+++ b/src/lib/builtin-ctx.ts
@@ -0,0 +1,71 @@
+/**
+ * How big a context the built-in engine gets when a swap restarts it.
+ *
+ * WHAT WENT WRONG (counter-check round 2, installed Windows build,
+ * 2026-08-29). During a two-model group chat the header read "ctx 32K" and the
+ * token counter "555/32.8k", while every `swap_bundled_model` of that same
+ * round asked for `"ctx": 8192` and llama-server's /props confirmed 8192. The
+ * user was shown four times the context that was actually loaded, and anybody
+ * writing near the edge would silently lose history.
+ *
+ * WHERE THE 32K CAME FROM. `ensureBuiltinAgentCtx` had raised the engine for
+ * an earlier agent turn (min of the GGUF's trained ctx and AGENT_CONTEXT_CAP).
+ * The group round then went through `ensureBuiltinEngineAlive`, which restarts
+ * with the RAW settings tuning, and the untouched default there is 8192. So
+ * the swap did not merely fail to match the display: it handed context back
+ * that the machine had already proved it could allocate, on every speaker
+ * change.
+ *
+ * THE CHOICE. Of the two ways to end the lie, this is the one that helps the
+ * user: the swap keeps what the engine already runs instead of the display
+ * being talked down to 8192. It is also the cautious half of the pair, because
+ * it never asks for more than this machine has already granted once, and never
+ * more than the GGUF header states the model was trained for. Where the header
+ * says nothing, nothing is raised (no RoPE extrapolation on a guess) and the
+ * display re-read that `loadBuiltinModel` fires after every start covers the
+ * rest: whatever the engine comes back with is what the header shows.
+ *
+ * An expert ctx set by hand wins outright in both directions, exactly as it
+ * does in `ensureBuiltinAgentCtx`.
+ */
+
+/** The ctx llama-server is started with when nobody has said otherwise. A
+ * settings value equal to it counts as "never touched". */
+export const ENGINE_DEFAULT_CTX = 8192
+
+export interface SwapCtxInput {
+ /** `settings.builtinEngine.ctx` — the expert tuning value. */
+ tuningCtx?: number | null
+ /** `bundled_engine_status.ctx` — what the running engine was started with. */
+ currentCtx?: number | null
+ /** `ctx_train` of the GGUF that is about to be loaded (header value). */
+ ctxTrain?: number | null
+}
+
+/**
+ * The ctx to put in the swap tuning, or undefined to leave the tuning alone.
+ *
+ * undefined on purpose rather than a number: "do not touch the user's tuning"
+ * and "use 8192" are different intentions, and only the caller knows what the
+ * rest of the tuning object holds.
+ */
+export function preservedSwapCtx(input: SwapCtxInput): number | undefined {
+ const tuning = num(input.tuningCtx)
+ // An expert value that is anything other than the untouched default is a
+ // decision, not an accident. Never second-guess it.
+ if (tuning > 0 && tuning !== ENGINE_DEFAULT_CTX) return undefined
+
+ const base = tuning > 0 ? tuning : ENGINE_DEFAULT_CTX
+ const current = num(input.currentCtx)
+ if (current <= base) return undefined // nothing is being given back
+
+ const train = num(input.ctxTrain)
+ if (train <= 0) return undefined // the header is silent, do not guess
+
+ const keep = Math.min(current, train)
+ return keep > base ? keep : undefined
+}
+
+function num(v: number | null | undefined): number {
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0
+}