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 send waits out the model swap it started, and says so in english

purpleb6d6d36c9517
diff --git a/src/api/__tests__/builtin-engine-dead-port.test.ts b/src/api/__tests__/builtin-engine-dead-port.test.ts
index ec2a342f..7da2d1ea 100644
--- a/src/api/__tests__/builtin-engine-dead-port.test.ts
+++ b/src/api/__tests__/builtin-engine-dead-port.test.ts
@@ -55,9 +55,14 @@ describe('explainDeadEngine', () => {
expect(out.message).toMatch(/Settings/i)
})
- it('keeps the original text so a bug report still carries it', () => {
+ // Changed 2026-08-29 (counter-check round 2). The raw line used to be
+ // appended for bug reports, which put "proxy_localhost_stream_chunked" in
+ // front of the user. House rule: no raw Rust error in a chat bubble. The
+ // original is written to the app log instead, see explainEngineTransportMessage.
+ it('keeps the internal Rust command name out of the bubble', () => {
const out = explainDeadEngine(new Error(raw), MANAGED_URL) as Error
- expect(out.message).toContain('proxy_localhost_stream_chunked')
+ expect(out.message).not.toContain('proxy_localhost_stream_chunked')
+ expect(out.message).not.toContain('Original error')
})
it('covers the other shapes a refused local connection takes', () => {
diff --git a/src/api/__tests__/engine-swap-race.test.ts b/src/api/__tests__/engine-swap-race.test.ts
new file mode 100644
index 00000000..b85a6f97
--- /dev/null
+++ b/src/api/__tests__/engine-swap-race.test.ts
@@ -0,0 +1,204 @@
+/**
+ * Counter-check round 2, side finding 2 (installed Windows build, 2026-08-29).
+ *
+ * Two model switches in quick succession, then send at once. What appeared in
+ * the chat bubble:
+ *
+ * Error: proxy_localhost_stream_chunked: error sending request for url
+ * (http://127.0.0.1:8127/v1/chat/completions)
+ *
+ * Two separate faults, one test file:
+ * 1. the send went out while the app's OWN swap was still restarting
+ * llama-server, so it fired into a port with nothing behind it
+ * 2. when a transport failure does get through, the user reads the name of a
+ * Rust command instead of a sentence
+ *
+ * Run: npx vitest run src/api/__tests__/engine-swap-race.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(), localFetch: vi.fn(), localFetchStream: vi.fn() }
+})
+
+import {
+ trackEngineSwap,
+ waitForEngineSwap,
+ engineSwapInFlight,
+ __resetEngineSwapGateForTests,
+} from '../engine-swap-gate'
+import { ensureBuiltinEngineAlive, explainEngineTransportMessage } from '../builtin-ensure'
+import { backendCall, localFetch } from '../backend'
+import { OpenAIProvider } from '../providers/openai-provider'
+import { useProviderStore } from '../../stores/providerStore'
+
+const MANAGED_URL = 'http://127.0.0.1:8127/v1'
+const RAW = 'proxy_localhost_stream_chunked: error sending request for url (http://127.0.0.1:8127/v1/chat/completions)'
+
+const asManagedSlot = () => {
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: { ...s.providers.openai, enabled: true, managed: true, baseUrl: MANAGED_URL },
+ },
+ }))
+}
+
+function deferred<T>() {
+ let resolve!: (v: T) => void
+ let reject!: (e: unknown) => void
+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
+ return { promise, resolve, reject }
+}
+
+beforeEach(() => {
+ __resetEngineSwapGateForTests()
+ vi.mocked(backendCall).mockReset()
+ vi.mocked(localFetch).mockReset()
+ asManagedSlot()
+})
+
+const managedProvider = () =>
+ new OpenAIProvider({
+ id: 'openai', name: 'Built-in Engine', enabled: true,
+ baseUrl: MANAGED_URL, apiKey: '', isLocal: true, managed: true,
+ } as never)
+
+describe('engine swap gate', () => {
+ it('reports an idle engine when nothing is loading', async () => {
+ expect(engineSwapInFlight()).toBe(false)
+ expect(await waitForEngineSwap(50)).toBe('idle')
+ })
+
+ it('a send waits for a swap that is still running', async () => {
+ const d = deferred<void>()
+ trackEngineSwap(d.promise)
+ expect(engineSwapInFlight()).toBe(true)
+
+ let done = false
+ const waiting = waitForEngineSwap(5_000).then((r) => { done = true; return r })
+ await Promise.resolve()
+ expect(done).toBe(false) // still parked on the swap
+
+ d.resolve()
+ expect(await waiting).toBe('settled')
+ expect(engineSwapInFlight()).toBe(false)
+ })
+
+ it('a failed swap clears the light instead of wedging every later send', async () => {
+ const d = deferred<void>()
+ trackEngineSwap(d.promise).catch(() => undefined)
+ d.reject(new Error('engine refused to start'))
+ expect(await waitForEngineSwap(5_000)).toBe('settled')
+ expect(engineSwapInFlight()).toBe(false)
+ })
+
+ // NEGATIVE CONTROL: the wait must have a deadline. A swap that never
+ // finishes may not hold a send hostage forever.
+ it('gives up on a swap that outlasts the deadline', async () => {
+ trackEngineSwap(deferred<void>().promise)
+ expect(await waitForEngineSwap(20)).toBe('timeout')
+ })
+
+ it('the promise handed to the caller is untouched', async () => {
+ const p = Promise.resolve('value')
+ expect(await trackEngineSwap(p)).toBe('value')
+ })
+})
+
+describe('ensureBuiltinEngineAlive waits the swap out before probing', () => {
+ it('does not touch the engine while a swap is in flight', async () => {
+ const swap = deferred<void>()
+ trackEngineSwap(swap.promise)
+ vi.mocked(backendCall).mockResolvedValue({
+ running: true, healthy: true, model_path: '/m/Hermes.gguf',
+ } as never)
+
+ const send = ensureBuiltinEngineAlive('openai::Hermes')
+ await Promise.resolve()
+ await Promise.resolve()
+ // The status probe is the first thing the old code did. It must not have
+ // happened yet: that probe answering "healthy" mid-restart is exactly how
+ // the send was let through into the gap.
+ expect(vi.mocked(backendCall)).not.toHaveBeenCalled()
+
+ swap.resolve()
+ await send
+ expect(vi.mocked(backendCall).mock.calls.map((c) => c[0])).toContain('bundled_engine_status')
+ })
+
+ // NEGATIVE CONTROL: with no swap running the send must not be delayed at
+ // all, otherwise the fix would tax every ordinary message.
+ it('probes straight away when no swap is running', async () => {
+ vi.mocked(backendCall).mockResolvedValue({
+ running: true, healthy: true, model_path: '/m/Hermes.gguf',
+ } as never)
+ await ensureBuiltinEngineAlive('openai::Hermes')
+ expect(vi.mocked(backendCall).mock.calls.map((c) => c[0])).toContain('bundled_engine_status')
+ })
+})
+
+describe('a transport failure that still gets through is labelled in English', () => {
+ it('rewrites the exact body the proxy hands back as a 503', () => {
+ const out = explainEngineTransportMessage(RAW, MANAGED_URL)
+ expect(out).toMatch(/built-in engine is not answering on 127\.0\.0\.1:8127/i)
+ expect(out).toMatch(/still loading a model/i)
+ expect(out).not.toContain('proxy_localhost_stream_chunked')
+ })
+
+ it('covers the shorter proxy_localhost variant too', () => {
+ const out = explainEngineTransportMessage(
+ 'proxy_localhost: error sending request for url (http://127.0.0.1:8127/v1/models)',
+ MANAGED_URL,
+ )
+ expect(out).toMatch(/built-in engine is not answering/i)
+ })
+
+ // NEGATIVE CONTROL: a real answer from the server keeps the server's own
+ // words, and a failure against somebody else's host is none of our business.
+ it('leaves a real server message and a foreign host alone', () => {
+ expect(explainEngineTransportMessage('context length exceeded', MANAGED_URL)).toBeNull()
+ expect(
+ explainEngineTransportMessage(
+ 'error sending request for url (https://api.openai.com/v1/chat/completions)',
+ MANAGED_URL,
+ ),
+ ).toBeNull()
+ })
+})
+
+describe('the provider really hands the plain sentence on (wiring)', () => {
+ // The transport failure does NOT arrive as a thrown error: localFetchStream
+ // turns it into Response(503, {"error": "proxy_localhost_stream_chunked ..."}),
+ // which is why sendOrExplain never saw it and the raw text reached the
+ // bubble. This drives the real provider through that exact shape.
+ it('a 503 from our own proxy comes out as a sentence, not a command name', async () => {
+ vi.mocked(backendCall).mockResolvedValue({
+ running: true, healthy: true, model_path: '/m/Hermes.gguf',
+ } as never)
+ vi.mocked(localFetch).mockResolvedValue(
+ new Response(JSON.stringify({ error: RAW }), { status: 503 }) as never,
+ )
+ const err = await managedProvider()
+ .chatWithTools('Hermes', [{ role: 'user', content: 'hi' }] as never, [] as never)
+ .then(() => null, (e: Error) => e)
+ expect(err?.message).toMatch(/built-in engine is not answering/i)
+ expect(err?.message).not.toContain('proxy_localhost_stream_chunked')
+ })
+
+ // NEGATIVE CONTROL: when the engine DID answer, its own words must survive.
+ // Rewriting a real 400 would hide the actual reason from the user.
+ it('a real engine answer keeps the engine words', async () => {
+ vi.mocked(backendCall).mockResolvedValue({
+ running: true, healthy: true, model_path: '/m/Hermes.gguf',
+ } as never)
+ vi.mocked(localFetch).mockResolvedValue(
+ new Response(JSON.stringify({ error: 'the request exceeds the available context size' }), { status: 400 }) as never,
+ )
+ const err = await managedProvider()
+ .chatWithTools('Hermes', [{ role: 'user', content: 'hi' }] as never, [] as never)
+ .then(() => null, (e: Error) => e)
+ expect(err?.message).toMatch(/exceeds the available context size/i)
+ })
+})
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index 653e3c8c..4cec6b0d 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -15,6 +15,8 @@
*/
import { backendCall } from './backend'
+import { trackEngineSwap, waitForEngineSwap } from './engine-swap-gate'
+import { log } from '../lib/logger'
import { useProviderStore } from '../stores/providerStore'
import { useSettingsStore } from '../stores/settingsStore'
import { builtinSlotStatus, type SlotStatus } from '../lib/builtin-slot-status'
@@ -62,12 +64,35 @@ let inflight: { key: string; promise: Promise<void> } | null = null
*/
export function explainDeadEngine(err: unknown, baseUrl: string): unknown {
const msg = err instanceof Error ? err.message : String(err ?? '')
+ const friendly = explainEngineTransportMessage(msg, baseUrl)
+ return friendly ? new Error(friendly) : err
+}
+
+/**
+ * The same translation for a message that arrived as a RESPONSE BODY rather
+ * than as a thrown error, which is the shape the counter-check actually hit.
+ *
+ * `localFetchStream` does not reject when the Rust proxy cannot reach the
+ * engine: it hands back `Response(503, {"error": "proxy_localhost_stream_chunked:
+ * error sending request for url (http://127.0.0.1:8127/v1/chat/completions)"})`.
+ * So `sendOrExplain` never saw a throw, `parseError` lifted the body verbatim,
+ * and the user read an internal Rust command name in their chat bubble.
+ *
+ * Returns the replacement text, or null when the message is not a transport
+ * failure against this engine (a real HTTP status carries the server's own
+ * words and must survive untouched). The raw text is not appended: it names a
+ * Rust function and a port, which tells the user nothing they can act on.
+ */
+export function explainEngineTransportMessage(message: string, baseUrl: string): string | null {
+ const msg = String(message ?? '')
const host = baseUrl.replace(/^https?:\/\//, '').replace(/\/.*$/, '')
- const isTransport = /error sending request|connection refused|failed to fetch|ECONNREFUSED|tcp connect/i.test(msg)
- if (!isTransport || !msg.includes(host.split(':')[0])) return err
- return new Error(
- `The built-in engine is not answering on ${host}. It either failed to start or was shut down. Open Settings, AI Backends, Built-in Engine and start it again, or pick a different backend. Original error: ${msg}`,
- )
+ const isTransport = /error sending request|connection refused|failed to fetch|ECONNREFUSED|tcp connect|proxy_localhost/i.test(msg)
+ if (!isTransport || !msg.includes(host.split(':')[0])) return null
+ // The raw line still exists for a bug report, it just lives in the app log
+ // now instead of in the chat bubble. House rule: no raw Rust error in front
+ // of a user.
+ log.warn('[builtin-engine] transport failure hidden behind a plain sentence', { raw: msg, host })
+ return `The built-in engine is not answering on ${host}. It is either still loading a model, failed to start, or was shut down. Wait for the model to finish loading and send again, or open Settings, AI Backends, Built-in Engine and start it there.`
}
/** True when the `openai` slot is the app-managed built-in engine. */
@@ -117,6 +142,13 @@ export async function builtinReloadNeeded(modelName: string): Promise<string | n
*/
export async function ensureBuiltinEngineAlive(modelName: string): Promise<void> {
if (!isManagedBuiltinSlot()) return
+ // Self-heal before an error message: a swap the app itself started is still
+ // tearing down and restarting llama-server, and a send fired into that gap
+ // is a guaranteed transport failure. Wait it out, then probe. The wait has a
+ // deadline so a wedged swap can never hold a send forever; past it the
+ // health check below decides what happens and says so in English.
+ // (Counter-check round 2, 2026-08-29: two picks in a row, then send.)
+ await waitForEngineSwap()
const key = bareBuiltinModelName(modelName)
if (inflight && inflight.key === key) return inflight.promise
const earlier = inflight?.promise
@@ -188,7 +220,7 @@ async function loadBuiltinModel(modelName: string): Promise<void> {
// 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 backendCall(cmd, { modelPath: hit.path, tuning })
+ await trackEngineSwap(backendCall(cmd, { modelPath: hit.path, tuning }))
}
// The default the engine ships with. A settings ctx equal to it is treated as
@@ -267,10 +299,10 @@ export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {
const raised = { ...(tuning ?? {}), ctx: want }
try {
- await backendCall(status?.running ? 'swap_bundled_model' : 'start_bundled_engine', {
+ await trackEngineSwap(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.
diff --git a/src/api/engine-swap-gate.ts b/src/api/engine-swap-gate.ts
new file mode 100644
index 00000000..1439a9c9
--- /dev/null
+++ b/src/api/engine-swap-gate.ts
@@ -0,0 +1,94 @@
+/**
+ * One traffic light for the single built-in engine process.
+ *
+ * WHAT WENT WRONG (counter-check round 2, installed Windows build,
+ * 2026-08-29). Two quick model switches followed by an immediate send put this
+ * in the chat bubble:
+ *
+ * Error: proxy_localhost_stream_chunked: error sending request for url
+ * (http://127.0.0.1:8127/v1/chat/completions)
+ *
+ * Timeline from the wire capture: the picker fired swap_bundled_model twice
+ * (06:17:05 and 06:17:12), llama-server restarted three times in a row, and at
+ * 06:17:32 the send went out into the gap where no process was listening. The
+ * engine came up seven seconds later. The app shot at a hole it had dug
+ * itself.
+ *
+ * The house rule is self-healing before an error message, so the send path
+ * waits for a swap it can see instead of racing it. This module is what makes
+ * the swap visible: `api/engine.ts` registers every start and swap, and
+ * `builtin-ensure.ts` waits on it before probing engine health.
+ *
+ * State lives on globalThis for the same reason agent-context.ts parks its
+ * state there: the bundler duplicates small modules, and two copies of this
+ * gate would each see an idle engine.
+ */
+
+/** How long a send waits for a swap before giving up on it and probing anyway.
+ * A large GGUF on a slow disk takes tens of seconds; past that something is
+ * wrong and the caller is better served by its own health check, which knows
+ * how to say so in English. */
+export const ENGINE_SWAP_WAIT_MS = 90_000
+
+const KEY = '__lu_engine_swap_gate__'
+
+interface Gate { current?: Promise<unknown> }
+
+function gate(): Gate {
+ const g = globalThis as unknown as Record<string, Gate>
+ if (!g[KEY]) g[KEY] = {}
+ return g[KEY]
+}
+
+/** Test-only: forget any tracked swap. */
+export function __resetEngineSwapGateForTests(): void {
+ delete (globalThis as unknown as Record<string, unknown>)[KEY]
+}
+
+/** True while a start or swap this app issued is still running. */
+export function engineSwapInFlight(): boolean {
+ return gate().current !== undefined
+}
+
+/**
+ * Register an engine start/swap and hand the caller its own promise back
+ * unchanged, so error handling at the call site is untouched. The gate holds a
+ * failure-proof view of it: a rejected swap clears the light instead of
+ * wedging every later send.
+ */
+export function trackEngineSwap<T>(p: Promise<T>): Promise<T> {
+ const g = gate()
+ const quiet = p.then(
+ () => undefined,
+ () => undefined,
+ )
+ g.current = quiet
+ void quiet.then(() => {
+ if (g.current === quiet) g.current = undefined
+ })
+ return p
+}
+
+/**
+ * Wait for a swap that is already running.
+ *
+ * 'idle' when there was nothing to wait for, 'settled' when the swap finished
+ * (well or badly, the caller re-probes either way), 'timeout' when it outlasted
+ * the deadline. Never throws and never rejects: the caller's next step is a
+ * health check, and that is what decides what the user is told.
+ */
+export async function waitForEngineSwap(
+ timeoutMs: number = ENGINE_SWAP_WAIT_MS,
+): Promise<'idle' | 'settled' | 'timeout'> {
+ const current = gate().current
+ if (!current) return 'idle'
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const deadline = new Promise<'timeout'>((resolve) => {
+ timer = setTimeout(() => resolve('timeout'), timeoutMs)
+ })
+ try {
+ return await Promise.race([current.then(() => 'settled' as const), deadline])
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+}
diff --git a/src/api/engine.ts b/src/api/engine.ts
index 93987980..082df54a 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -12,6 +12,7 @@
*/
import { backendCall } from './backend'
+import { trackEngineSwap } from './engine-swap-gate'
import { prefixModelName } from './providers'
import { useProviderStore } from '../stores/providerStore'
import { useSettingsStore } from '../stores/settingsStore'
@@ -85,9 +86,15 @@ export function isManagedBuiltinActive(): boolean {
}
/** Start the built-in engine with a specific GGUF. Idempotent for the same
- * model + tuning (the Rust side compares the resulting argv). */
+ * model + tuning (the Rust side compares the resulting argv).
+ *
+ * Registered with the swap gate so a send that arrives while the engine is
+ * still coming up waits for it instead of hitting the dead port (counter-check
+ * round 2, 2026-08-29). */
export function startBundledEngine(modelPath: string, tuning?: BuiltinEngineTuning) {
- return backendCall('start_bundled_engine', { modelPath, tuning: tuning ?? tuningFromSettings() })
+ return trackEngineSwap(
+ backendCall('start_bundled_engine', { modelPath, tuning: tuning ?? tuningFromSettings() }),
+ )
}
/** Stop the managed engine child if one is running. */
@@ -100,9 +107,15 @@ export function bundledEngineStatus() {
return backendCall<EngineStatus>('bundled_engine_status')
}
-/** Swap the loaded model (stop → start on the same port). */
+/** Swap the loaded model (stop → start on the same port).
+ *
+ * This is the call the model picker makes on every activation, and the one the
+ * counter-check raced: two switches in a row, then a send into the restart gap.
+ * Registering it here is what lets the send path wait it out. */
export function swapBundledModel(modelPath: string, tuning?: BuiltinEngineTuning) {
- return backendCall('swap_bundled_model', { modelPath, tuning: tuning ?? tuningFromSettings() })
+ return trackEngineSwap(
+ backendCall('swap_bundled_model', { modelPath, tuning: tuning ?? tuningFromSettings() }),
+ )
}
/** Start the built-in embeddings server (P5) with a specific embedding GGUF.
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 9636065a..87c292b4 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -19,7 +19,7 @@ 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, backendCall } from '../backend'
-import { ensureBuiltinEngineAlive, explainDeadEngine, isManagedBuiltinSlot } from '../builtin-ensure'
+import { ensureBuiltinEngineAlive, explainDeadEngine, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'
import { applyTemplateContract } from './normalize-system'
// Transport routing lives in the `useLocalProxy` getter (below) plus the shared
@@ -1107,6 +1107,20 @@ export class OpenAIProvider implements ProviderClient {
"no need to restart LU."
}
+ // Our OWN engine could not be reached. The failure never arrives as a
+ // thrown error on the streaming path: localFetchStream turns a refused
+ // connection into Response(503, {"error": "proxy_localhost_stream_chunked:
+ // ..."}), so the raw Rust command name landed in the chat bubble
+ // (counter-check round 2, 2026-08-29). Say it in English instead. Last in
+ // the chain so a server that answered with real words keeps them.
+ if (this.config.managed === true) {
+ const friendly = explainEngineTransportMessage(message, this.baseUrl)
+ if (friendly) {
+ message = friendly
+ code = 'network'
+ }
+ }
+
return new ProviderError(message, 'openai', code, res.status, undefined, parseRetryAfter(res))
}
}