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(engine): a dead built-in engine says so instead of leaking the proxy error
purple96ed90eb7306
diff --git a/src/api/__tests__/builtin-engine-dead-port.test.ts b/src/api/__tests__/builtin-engine-dead-port.test.tsnew file mode 100644index 00000000..ec2a342f--- /dev/null+++ b/src/api/__tests__/builtin-engine-dead-port.test.ts@@ -0,0 +1,144 @@+/**+ * A fresh install must not greet people with a proxy stack trace+ * (applejames, Discord 2026-08-01, Windows 10, 2.5.10):+ *+ * Error: proxy_localhost_stream_chunked: error sending request for url+ * (http://127.0.0.1:8127/v1/chat/completions)+ *+ * They had run onboarding, had qwen 0.5 installed, clicked New Chat, and got+ * that. Two holes led there and both are covered below:+ *+ * 1. the self-heal returned quietly when the picked model was not among the+ * bundled files, so the send went ahead into a port with nothing behind it+ * 2. nothing translated a refused connection to our own engine, so the raw+ * transport error reached the chat bubble+ *+ * Run: npx vitest run src/api/__tests__/builtin-engine-dead-port.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 { ensureBuiltinEngineAlive, explainDeadEngine, isManagedBuiltinSlot } from '../builtin-ensure'+import { backendCall } from '../backend'+import { useProviderStore } from '../../stores/providerStore'++const MANAGED_URL = 'http://127.0.0.1:8127/v1'++const asManagedSlot = () => {+ useProviderStore.setState((s) => ({+ providers: {+ ...s.providers,+ openai: { ...s.providers.openai, enabled: true, managed: true, baseUrl: MANAGED_URL },+ },+ }))+}++const asForeignSlot = () => {+ useProviderStore.setState((s) => ({+ providers: {+ ...s.providers,+ openai: { ...s.providers.openai, enabled: true, managed: false, baseUrl: 'https://api.openai.com/v1' },+ },+ }))+}++describe('explainDeadEngine', () => {+ const raw = 'proxy_localhost_stream_chunked: error sending request for url (http://127.0.0.1:8127/v1/chat/completions)'++ it('turns the exact reported error into a sentence naming the engine and the port', () => {+ const out = explainDeadEngine(new Error(raw), MANAGED_URL) as Error+ expect(out.message).toMatch(/built-in engine is not answering on 127\.0\.0\.1:8127/i)+ expect(out.message).toMatch(/Settings/i)+ })++ it('keeps the original text so a bug report still carries it', () => {+ const out = explainDeadEngine(new Error(raw), MANAGED_URL) as Error+ expect(out.message).toContain('proxy_localhost_stream_chunked')+ })++ it('covers the other shapes a refused local connection takes', () => {+ for (const msg of [+ 'error sending request for url (http://127.0.0.1:8127/v1/chat/completions): connection refused',+ 'TypeError: Failed to fetch http://127.0.0.1:8127/v1/chat/completions',+ 'ECONNREFUSED 127.0.0.1:8127',+ ]) {+ const out = explainDeadEngine(new Error(msg), MANAGED_URL) as Error+ expect(out.message).toMatch(/built-in engine is not answering/i)+ }+ })++ it('leaves a real HTTP error alone — that text is the server speaking', () => {+ const httpErr = new Error('HTTP 400: {"error":"context length exceeded"}')+ expect(explainDeadEngine(httpErr, MANAGED_URL)).toBe(httpErr)+ })++ it('leaves a failure against a different host alone', () => {+ const other = new Error('error sending request for url (https://api.openai.com/v1/chat/completions)')+ expect(explainDeadEngine(other, MANAGED_URL)).toBe(other)+ })+})++describe('ensureBuiltinEngineAlive — the model is gone', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ asManagedSlot()+ })++ it('says which model is missing instead of letting the send hit a dead port', async () => {+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {+ if (cmd === 'bundled_engine_status') return { running: false, healthy: false }+ if (cmd === 'list_bundled_models') return { models: [] }+ throw new Error(`unexpected command ${cmd}`)+ }) as never)++ await expect(ensureBuiltinEngineAlive('qwen2.5-0.5b-instruct-q4_k_m.gguf'))+ .rejects.toThrow(/no model file named "qwen2\.5-0\.5b-instruct-q4_k_m\.gguf"/i)+ })++ it('points at the Models page as the way out', async () => {+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {+ if (cmd === 'bundled_engine_status') return { running: false, healthy: false }+ if (cmd === 'list_bundled_models') return { models: [{ name: 'something-else.gguf', path: '/m/other.gguf' }] }+ throw new Error(`unexpected command ${cmd}`)+ }) as never)++ await expect(ensureBuiltinEngineAlive('qwen2.5-0.5b.gguf')).rejects.toThrow(/Open Models/i)+ })++ it('restarts the engine when the model IS there (regression guard)', async () => {+ const calls: string[] = []+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {+ calls.push(cmd)+ if (cmd === 'bundled_engine_status') return { running: false, healthy: false }+ if (cmd === 'list_bundled_models') return { models: [{ name: 'qwen2.5-0.5b.gguf', path: '/m/qwen2.5-0.5b.gguf' }] }+ if (cmd === 'start_bundled_engine') return { status: 'started' }+ throw new Error(`unexpected command ${cmd}`)+ }) as never)++ await expect(ensureBuiltinEngineAlive('qwen2.5-0.5b.gguf')).resolves.toBeUndefined()+ expect(calls).toContain('start_bundled_engine')+ })++ it('does nothing at all when the engine is already healthy', async () => {+ const calls: string[] = []+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {+ calls.push(cmd)+ if (cmd === 'bundled_engine_status') return { running: true, healthy: true }+ throw new Error(`unexpected command ${cmd}`)+ }) as never)++ await expect(ensureBuiltinEngineAlive('qwen2.5-0.5b.gguf')).resolves.toBeUndefined()+ expect(calls).toEqual(['bundled_engine_status'])+ })++ it('stays out of the way when the slot is somebody else s server', async () => {+ asForeignSlot()+ expect(isManagedBuiltinSlot()).toBe(false)+ await expect(ensureBuiltinEngineAlive('gpt-4o')).resolves.toBeUndefined()+ expect(backendCall).not.toHaveBeenCalled()+ })+})diff --git a/src/api/__tests__/builtin-ensure.test.ts b/src/api/__tests__/builtin-ensure.test.tsindex 40abe3a6..1cc7b749 100644--- a/src/api/__tests__/builtin-ensure.test.ts+++ b/src/api/__tests__/builtin-ensure.test.ts@@ -74,9 +74,14 @@ describe('ensureBuiltinEngineAlive', () => {expect(starts[0][1]).toEqual({ modelPath: '/models/qwen2.5-0.5b.gguf', tuning: TUNING })})- it('leaves foreign models alone (openai-compat server that is not ours)', async () => {+ it('never starts our engine for a model that is not one of ours, and says why', async () => {mockEngine({ healthy: false })- await ensureBuiltinEngineAlive('gpt-4o-mini')+ // The slot is managed, so the send is about to hit our own port with+ // nothing behind it. Returning quietly here is what handed applejames a+ // raw "proxy_localhost_stream_chunked" on a fresh install (2026-08-01), so+ // the guard still refuses to start anything, but it no longer pretends+ // the send will work.+ await expect(ensureBuiltinEngineAlive('gpt-4o-mini')).rejects.toThrow(/no model file named "gpt-4o-mini"/i)expect(callsTo('start_bundled_engine')).toHaveLength(0)})diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.tsindex e66f3ec7..e321de2e 100644--- a/src/api/builtin-ensure.ts+++ b/src/api/builtin-ensure.ts@@ -32,6 +32,25 @@ interface BundledList {// same promise is exactly "wait for the restart the other call kicked off".let inflight: Promise<void> | null = null+/**+ * Rewrite a transport failure against our own engine into something a user can+ * act on. The Rust proxy reports a refused connection verbatim+ * ("proxy_localhost_stream_chunked: error sending request for url+ * (http://127.0.0.1:8127/v1/chat/completions)"), which reads like the app is+ * broken rather than like the engine is down. Only touches errors that never+ * reached an HTTP response — a real status code carries the server's own words+ * and must survive untouched.+ */+export function explainDeadEngine(err: unknown, baseUrl: string): unknown {+ const msg = err instanceof Error ? err.message : String(err ?? '')+ 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}`,+ )+}+/** True when the `openai` slot is the app-managed built-in engine. */export function isManagedBuiltinSlot(): boolean {const cfg = useProviderStore.getState().providers.openai@@ -67,7 +86,19 @@ export async function ensureBuiltinEngineAlive(modelName: string): Promise<void>}const bare = modelName.includes('::') ? modelName.split('::')[1] : modelNameconst hit = models.find((m) => m.name === bare)- if (!hit) return // not a bundled GGUF — some other openai-compat server+ if (!hit) {+ // The slot IS our engine (managed), the engine is NOT healthy, and the+ // model the picker is holding is not on disk where the engine looks.+ // Returning quietly here sent the send straight into a dead port, and+ // the user got "proxy_localhost_stream_chunked: error sending request+ // for url (http://127.0.0.1:8127/v1/chat/completions)" as their first+ // impression of the app (applejames, Discord 2026-08-01, fresh install+ // on Windows 10 — they gave up on the built-in engine and moved to+ // Ollama). Say what is actually wrong instead.+ throw new Error(+ `The built-in engine has no model file named "${bare}". It may have been deleted, moved, or the download did not finish. Open Models, install it again, then pick it in the chat.`,+ )+ }// Restart with the user's expert tuning, not bare defaults — otherwise a// self-heal would silently drop a configured ctx/KV-quant until the nextdiff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 33bc2e11..1070f5dd 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -18,7 +18,7 @@ import { parseSSEStream } from '../sse'import { repairJson } from '../../lib/tool-call-repair'import { signalCreditsExhausted } from '../../lib/credits-exhausted'import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost } from '../backend'-import { ensureBuiltinEngineAlive } from '../builtin-ensure'+import { ensureBuiltinEngineAlive, explainDeadEngine } 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@@ -213,6 +213,22 @@ export class OpenAIProvider implements ProviderClient {return this.isLanBackend || !isDirectFetchAllowed(hostnameOf(this.baseUrl))}+ /**+ * Run a send and, when this slot is the app's own engine, translate a+ * transport failure into a sentence about the engine. A refused connection+ * to 127.0.0.1:8127 used to surface as the raw proxy error, which is how a+ * fresh Windows install introduced itself to applejames on 2026-08-01 before+ * they moved to Ollama. Anything that reached an HTTP response is untouched.+ */+ private async sendOrExplain(send: () => Promise<Response>): Promise<Response> {+ try {+ return await send()+ } catch (err) {+ if (this.config.managed === true) throw explainDeadEngine(err, this.baseUrl)+ throw err+ }+ }+private get headers(): Record<string, string> {const h: Record<string, string> = {'Content-Type': 'application/json',@@ -300,12 +316,12 @@ export class OpenAIProvider implements ProviderClient {if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)const fetcher = this.useLocalProxy ? localFetchStream : fetch- let res = await fetcher(`${this.baseUrl}/chat/completions`, {+ let res = await this.sendOrExplain(() => fetcher(`${this.baseUrl}/chat/completions`, {method: 'POST',headers: this.headers,body: JSON.stringify(body),signal: options?.signal,- } as any)+ } as any))// Retry without reasoning_effort if the model/endpoint rejects it. The LU// Cloud proxy deliberately passes upstream 400 AND 422 (DeepInfra's@@ -472,12 +488,12 @@ export class OpenAIProvider implements ProviderClient {if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)const fetcher = this.useLocalProxy ? localFetch : fetch- let res = await fetcher(`${this.baseUrl}/chat/completions`, {+ let res = await this.sendOrExplain(() => fetcher(`${this.baseUrl}/chat/completions`, {method: 'POST',headers: this.headers,body: JSON.stringify(body),signal: options?.signal,- } as any)+ } as any))if (!res.ok && (res.status === 400 || res.status === 422) && ('reasoning_effort' in body || 'stream_options' in body)) {delete body.reasoning_effort