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(proxy): eine tote Verbindung sagt nicht mehr, das Netz sei schuld
purplec4bc42b2ef35
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rsindex cfeff5ec..94b705d6 100644--- a/src-tauri/src/commands/proxy.rs+++ b/src-tauri/src/commands/proxy.rs@@ -978,6 +978,9 @@ async fn pump_proxy_stream(first_chunk_grace: Duration,sink: &(dyn Fn(Vec<u8>) -> bool + Send + Sync),) -> Result<(), String> {+ // Lives outside the pump because the EOF marker below has to know whether a+ // single byte of an answer ever reached the renderer.+ let mut seen_first_chunk = false;let run = async {let http_method = method.unwrap_or_else(|| "GET".to_string());@@ -1004,7 +1007,6 @@ async fn pump_proxy_stream(use futures_util::StreamExt;let mut stream = resp.bytes_stream();- let mut seen_first_chunk = false;loop {let window = if seen_first_chunk { idle } else { first_chunk_grace };tokio::select! {@@ -1050,7 +1052,18 @@ async fn pump_proxy_stream(// renderer then held the stream open on its 15 s grace timer — Stop looked// frozen for fifteen seconds on the proxy-first loopback path, which is the// default for the built-in engine, Ollama and LM Studio.- sink(Vec::new());+ //+ // But NOT when the pump died before a single byte arrived. The marker settles+ // the renderer's Response as 200 with an empty body, and the real error, which+ // only reaches JS one tick later on the rejected invoke, is then thrown away+ // as a late answer. Every unreachable local backend read as "The connection+ // dropped before the model finished its answer. Check your network and try+ // again." while the truth was a refused connection on 127.0.0.1 (counter-check+ // P1, 2026-09-04, LU Engine switched off). A failure with no answer behind it+ // must travel as a failure.+ if run.is_ok() || seen_first_chunk {+ sink(Vec::new());+ }run}@@ -1824,13 +1837,24 @@ mod tests {}/// The renderer closes its ReadableStream on the empty chunk and on nothing- /// else; the invoke result does not close it. Every path that returned- /// without the marker left the reader hanging on a 15 s grace timer, which- /// is why Stop looked frozen — and Stop during connect or during the model- /// load was exactly such a path. Loopback is proxy-first in Tauri, so this- /// is the default route for the built-in engine, Ollama and LM Studio.+ /// else; the invoke result does not close it. A path that ends without the+ /// marker leaves the reader hanging on a 15 s grace timer, which is why Stop+ /// used to look frozen. Loopback is proxy-first in Tauri, so this is the+ /// default route for the built-in engine, Ollama and LM Studio.+ ///+ /// The marker is NOT free, though, and the first version of this test had+ /// that backwards. It settles the renderer's Response as 200 with an empty+ /// body. Send it after a failure that produced no answer, and the real+ /// error, which reaches JS one tick later on the rejected invoke, arrives+ /// too late and is dropped: every unreachable local backend came out as+ /// "The connection dropped before the model finished its answer. Check your+ /// network and try again." (counter-check P1, 2026-09-04, LU Engine+ /// switched off; the truth was a refused connection on 127.0.0.1). So the+ /// rule is: end what has an end. A cancel and a finished body have one, and+ /// so does a stream that died after delivering data. A connect failure and+ /// a rejected status do not, and they must travel as failures.#[test]- fn every_exit_path_ends_with_the_eof_marker() {+ fn the_marker_ends_an_answer_and_never_hides_a_failure() {let rt = tokio::runtime::Runtime::new().unwrap();rt.block_on(async {let short = Duration::from_millis(200);@@ -1845,6 +1869,7 @@ mod tests {assert_eq!(chunks, vec![Vec::<u8>::new()], "cancel must still emit EOF");// 2. Nothing listening: the failure happens before the first byte.+ // No marker, or the refused connection reads as a dropped answer.let dead = {let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let p = l.local_addr().unwrap().port();@@ -1855,9 +1880,10 @@ mod tests {let (out, chunks) = pump_and_collect(&format!("http://127.0.0.1:{}/", dead), &token, short, short).await;assert!(out.is_err());- assert_eq!(chunks.last(), Some(&Vec::<u8>::new()), "connect failure must emit EOF");+ assert!(chunks.is_empty(), "a refused connection must not look like an ended answer: {chunks:?}");- // 3. The backend answers, but with an error status.+ // 3. The backend answers, but with an error status. Same rule: the+ // renderer has to see the status and the body, not an empty 200.let port = raw_stub("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 5\r\nConnection: close\r\n\r\nboom",None,@@ -1866,7 +1892,7 @@ mod tests {let (out, chunks) = pump_and_collect(&format!("http://127.0.0.1:{}/", port), &token, short, short).await;assert!(out.is_err());- assert_eq!(chunks.last(), Some(&Vec::<u8>::new()), "HTTP error must emit EOF");+ assert!(chunks.is_empty(), "a rejected status must not look like an ended answer: {chunks:?}");// 4. The ordinary path: chunks, then the marker, in that order.let port = raw_stub(@@ -1879,6 +1905,20 @@ mod tests {assert!(out.is_ok(), "{out:?}");assert_eq!(chunks.first().map(|c| c.as_slice()), Some(&b"hello"[..]));assert_eq!(chunks.last(), Some(&Vec::<u8>::new()));++ // 5. The backend delivers, then goes quiet with the socket open.+ // There IS half an answer in the window, so it gets a clean end+ // and the reader keeps what it already has.+ let port = raw_stub(+ "HTTP/1.1 200 OK\r\nContent-Length: 32\r\n\r\nhalf",+ Some(Duration::from_secs(2)),+ ).await;+ let token = tokio_util::sync::CancellationToken::new();+ let (out, chunks) = pump_and_collect(+ &format!("http://127.0.0.1:{}/", port), &token, short, short).await;+ assert!(out.is_err(), "the idle window has to fire: {out:?}");+ assert_eq!(chunks.first().map(|c| c.as_slice()), Some(&b"half"[..]));+ assert_eq!(chunks.last(), Some(&Vec::<u8>::new()), "data seen, so the stream gets an end");});}@@ -1914,6 +1954,13 @@ mod tests {/// token, which for a large GGUF takes minutes. Cutting that at the idle/// timeout would break loading rather than protect it, so the window before/// the first chunk is its own, much longer one.+ ///+ /// When it does run out there is no answer to end, so no marker either, and+ /// the reason travels as the failure it is. Before 04.09.2026 the marker+ /// went out anyway, the renderer settled a 200 with an empty body, and the+ /// sentence about a model that may still be loading was dropped as a late+ /// answer. What the user read instead was "the connection dropped, check+ /// your network", on a machine whose network was fine.#[test]fn silence_before_the_first_chunk_gets_the_model_load_window() {let rt = tokio::runtime::Runtime::new().unwrap();@@ -1931,7 +1978,7 @@ mod tests {).await;let err = out.expect_err("the load window has to end eventually too");assert!(err.contains("sent nothing"), "wrong reason: {err}");- assert_eq!(chunks, vec![Vec::<u8>::new()]);+ assert!(chunks.is_empty(), "nothing arrived, so there is nothing to end: {chunks:?}");});}diff --git a/src/api/__tests__/eine-abgeschaltete-engine-nennt-den-schalter.test.ts b/src/api/__tests__/eine-abgeschaltete-engine-nennt-den-schalter.test.tsnew file mode 100644index 00000000..d843610c--- /dev/null+++ b/src/api/__tests__/eine-abgeschaltete-engine-nennt-den-schalter.test.ts@@ -0,0 +1,93 @@+/**+ * Der Fehlfund aus dem Persona-Lauf P1 am 04.09.2026, Build 4.+ *+ * Der Tester hat die LU Engine in Settings, AI Backends ueber Disable+ * abgeschaltet und danach im Chat etwas abgeschickt. Was er las:+ *+ * The connection dropped before the model finished its answer.+ * Check your network and try again.+ *+ * Sein Netz war in Ordnung. Er hatte den Anbieter selbst ausgeschaltet, und+ * der Satz schickte ihn in die falsche Richtung.+ *+ * Zwei Loecher fuehrten dahin, dieses hier ist das obere: `isManagedBuiltinSlot`+ * gibt bei einem abgeschalteten Steckplatz false zurueck, und+ * `ensureBuiltinEngineAlive` ist dann still ausgestiegen. Die Anfrage lief in+ * den toten Port, und was danach passierte, entschied ein Wettlauf im Proxy+ * (siehe `the_marker_ends_an_answer_and_never_hides_a_failure` in proxy.rs).+ *+ * Lauf: npx vitest run src/api/__tests__/eine-abgeschaltete-engine-nennt-den-schalter.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 {+ BUILTIN_SLOT_OFF_MESSAGE,+ builtinSlotSwitchedOff,+ ensureBuiltinEngineAlive,+ isManagedBuiltinSlot,+} from '../builtin-ensure'+import { backendCall } from '../backend'+import { useProviderStore } from '../../stores/providerStore'++const setzeSteckplatz = (patch: { enabled: boolean; managed: boolean }) => {+ useProviderStore.setState((s) => ({+ providers: {+ ...s.providers,+ openai: { ...s.providers.openai, ...patch, baseUrl: 'http://127.0.0.1:8127/v1' },+ },+ }))+}++beforeEach(() => {+ vi.mocked(backendCall).mockReset()+})++describe('builtinSlotSwitchedOff', () => {+ it('trennt die zwei Faelle, die isManagedBuiltinSlot in einen Topf wirft', () => {+ setzeSteckplatz({ enabled: false, managed: true })+ expect(isManagedBuiltinSlot()).toBe(false)+ expect(builtinSlotSwitchedOff()).toBe(true)++ setzeSteckplatz({ enabled: true, managed: false })+ expect(isManagedBuiltinSlot()).toBe(false)+ expect(builtinSlotSwitchedOff()).toBe(false)+ })++ it('ist falsch, solange die Engine laeuft', () => {+ setzeSteckplatz({ enabled: true, managed: true })+ expect(builtinSlotSwitchedOff()).toBe(false)+ })+})++describe('ensureBuiltinEngineAlive bei abgeschaltetem Steckplatz', () => {+ it('sagt, dass der Schalter aus ist, statt in den toten Port zu senden', async () => {+ setzeSteckplatz({ enabled: false, managed: true })+ await expect(ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M'))+ .rejects.toThrow(BUILTIN_SLOT_OFF_MESSAGE)+ // Und zwar OHNE das Rust-Backend zu fragen: der Zustand steht schon fest.+ expect(vi.mocked(backendCall)).not.toHaveBeenCalled()+ })++ it('nennt den Weg zurueck und redet nicht vom Netz', async () => {+ setzeSteckplatz({ enabled: false, managed: true })+ const fehler = await ensureBuiltinEngineAlive('openai::egal').then(+ () => null,+ (e: unknown) => e as Error,+ )+ expect(fehler).toBeInstanceOf(Error)+ expect(fehler!.message).toMatch(/Settings, AI Backends/)+ expect(fehler!.message).not.toMatch(/network/i)+ expect(fehler!.message).not.toMatch(/connection dropped/i)+ })++ it('laesst einen fremden Steckplatz weiter in Ruhe', async () => {+ setzeSteckplatz({ enabled: true, managed: false })+ await expect(ensureBuiltinEngineAlive('openai::gpt-4o')).resolves.toBeUndefined()+ expect(vi.mocked(backendCall)).not.toHaveBeenCalled()+ })+})diff --git a/src/api/__tests__/fremde-lokale-server-heissen-beim-namen.test.ts b/src/api/__tests__/fremde-lokale-server-heissen-beim-namen.test.tsnew file mode 100644index 00000000..acda52c0--- /dev/null+++ b/src/api/__tests__/fremde-lokale-server-heissen-beim-namen.test.ts@@ -0,0 +1,104 @@+/**+ * Der Nachlauf zum P1-Fehlfund: nachdem die Schlussmarke im Proxy nicht mehr+ * jede Fehlermeldung verschluckt (proxy.rs), kommt die rohe Zeile+ *+ * proxy_localhost_stream_chunked: error sending request for url+ * (http://127.0.0.1:1234/v1/chat/completions)+ *+ * wirklich bei den Anbietern an. Beim eigenen Motor war die Uebersetzung schon+ * da. Bei LM Studio, llama.cpp, vLLM und Ollama war sie es nicht, und ohne sie+ * haette mein Fix einen Rust-Befehlsnamen ins Chatfenster gestellt. Genau das+ * pruefen diese Tests, einmal je Anbieter.+ *+ * Lauf: npx vitest run src/api/__tests__/fremde-lokale-server-heissen-beim-namen.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { ProviderConfig } from '../providers/types'++vi.mock('../backend', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../backend')>()+ return {+ ...actual,+ isTauri: () => false,+ localFetch: vi.fn(),+ localFetchStream: vi.fn(),+ ollamaUrl: (path: string) => `http://127.0.0.1:11434${path}`,+ }+})++import { OpenAIProvider } from '../providers/openai-provider'+import { OllamaProvider } from '../providers/ollama-provider'+import { localFetchStream } from '../backend'++const stream = localFetchStream as ReturnType<typeof vi.fn>++/** Genau das, was der Proxy bei einer abgelehnten Verbindung zurueckgibt. */+const abgelehnt = (url: string) =>+ new Response(+ JSON.stringify({ error: `proxy_localhost_stream_chunked: error sending request for url (${url})` }),+ { status: 503 },+ )++const lmStudio: ProviderConfig = {+ id: 'openai', name: 'LM Studio', enabled: true,+ baseUrl: 'http://127.0.0.1:1234/v1', apiKey: 'x', isLocal: true,+}++const echteCloud: ProviderConfig = {+ id: 'openai', name: 'OpenAI', enabled: true,+ baseUrl: 'https://api.openai.com/v1', apiKey: 'x', isLocal: false,+}++const ollama: ProviderConfig = {+ id: 'ollama', name: 'Ollama', enabled: true,+ baseUrl: 'http://127.0.0.1:11434', apiKey: '', isLocal: true,+}++const fehlerVon = async (gen: AsyncGenerator<unknown>): Promise<Error> => {+ try {+ for await (const _ of gen) { /* bis zum Knall */ }+ } catch (e) {+ return e as Error+ }+ throw new Error('es kam gar kein Fehler')+}++beforeEach(() => { vi.clearAllMocks() })++describe('ein fremder lokaler Server, der nicht laeuft', () => {+ it('wird beim Namen genannt, nicht mit einem Rust-Befehl', async () => {+ stream.mockResolvedValue(abgelehnt('http://127.0.0.1:1234/v1/chat/completions'))+ const e = await fehlerVon(new OpenAIProvider(lmStudio).chatStream('irgendwas', []))+ expect(e.message).toContain('LM Studio')+ expect(e.message).toContain('127.0.0.1:1234')+ expect(e.message).toContain('Settings, AI Backends')+ expect(e.message).not.toContain('proxy_localhost_stream_chunked')+ expect(e.message).not.toMatch(/network/i)+ })++ it('gilt auch fuer Ollama, das denselben Proxy nimmt', async () => {+ stream.mockResolvedValue(abgelehnt('http://127.0.0.1:11434/api/chat'))+ const e = await fehlerVon(new OllamaProvider(ollama).chatStream('llama3', []))+ expect(e.message).toContain('Ollama')+ expect(e.message).toContain('127.0.0.1:11434')+ expect(e.message).not.toContain('proxy_localhost_stream_chunked')+ })+})++describe('was NICHT uebersetzt werden darf', () => {+ it('ein echter Serverfehler behaelt die Worte des Servers', async () => {+ stream.mockResolvedValue(new Response(+ JSON.stringify({ error: { message: 'context length exceeded' } }), { status: 400 },+ ))+ const e = await fehlerVon(new OpenAIProvider(lmStudio).chatStream('irgendwas', []))+ expect(e.message).toContain('context length exceeded')+ expect(e.message).not.toContain('is not answering')+ })++ it('ein Cloud-Anbieter bekommt keinen Satz ueber das Starten von Servern', async () => {+ stream.mockResolvedValue(abgelehnt('https://api.openai.com/v1/chat/completions'))+ const e = await fehlerVon(new OpenAIProvider(echteCloud).chatStream('gpt-4o', []))+ expect(e.message).not.toContain('is not answering')+ expect(e.message).not.toContain('Start it and send again')+ })+})diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.tsindex c18182b5..75d7da40 100644--- a/src/api/builtin-ensure.ts+++ b/src/api/builtin-ensure.ts@@ -29,6 +29,7 @@ import {builtinModelMismatchMessage,builtinModelNameFromPath,} from '../lib/builtin-model-identity'+import { hostOf, isLocalTransportFailure } from '../lib/local-backend-transport'interface EngineStatusLite {running: boolean@@ -95,9 +96,8 @@ export function explainDeadEngine(err: unknown, baseUrl: string): unknown {*/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|proxy_localhost/i.test(msg)- if (!isTransport || !msg.includes(host.split(':')[0])) return null+ const host = hostOf(baseUrl)+ if (!isLocalTransportFailure(msg, baseUrl)) 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.@@ -111,6 +111,25 @@ export function isManagedBuiltinSlot(): boolean {return !!cfg?.enabled && cfg.managed === true}+/**+ * The built-in slot exists, but the user turned it off in Settings.+ *+ * This is the second half of `isManagedBuiltinSlot`, and it matters because the+ * two false cases mean opposite things. A slot that is not managed at all is+ * someone else's endpoint and we have nothing to say about it. A managed slot+ * that is switched off is our engine, deliberately stopped, and a send aimed at+ * it can only fail. Saying so beats letting the request run into a dead port+ * and explaining the wreck afterwards.+ */+export function builtinSlotSwitchedOff(): boolean {+ const cfg = useProviderStore.getState().providers.openai+ return !!cfg && cfg.managed === true && !cfg.enabled+}++/** What the chat says when the send was aimed at a switched-off engine. */+export const BUILTIN_SLOT_OFF_MESSAGE =+ 'The LU Engine is switched off in Settings, AI Backends. Turn it back on there, or pick a model from another provider.'+/*** Point the managed slot at the port the engine really came up on.*@@ -177,6 +196,12 @@ export async function builtinReloadNeeded(modelName: string): Promise<string | n* says, so "the engine is healthy" was never enough to send.*/export async function ensureBuiltinEngineAlive(modelName: string): Promise<void> {+ // Switched off by hand: nothing here may start it again, and nothing may let+ // the send through either. Without this the request went to the dead port,+ // the proxy failure lost its race against the stream's end marker, and the+ // chat blamed the user's network for a switch the user had flipped+ // (counter-check P1, 2026-09-04).+ if (builtinSlotSwitchedOff()) throw new Error(BUILTIN_SLOT_OFF_MESSAGE)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 gapdiff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex db4c1c36..9389f186 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -11,6 +11,7 @@ import type {} from './types'import { ProviderError } from './types'import { localFetch, localFetchStream, ollamaUrl } from '../backend'+import { isLocalTransportFailure, localBackendUnreachableMessage } from '../../lib/local-backend-transport'import { parseNDJSONStream } from '../stream'import { idleAbortGuard, isStreamIdleTimeout, STREAM_IDLE_TIMEOUT_MS } from '../stream-idle'import { repairToolCallArgs, extractToolCallsFromContent } from '../../lib/tool-call-repair'@@ -500,6 +501,16 @@ export class OllamaProvider implements ProviderClient {try {const { parseOllamaError, chatStyleMessage } = await import('../../lib/ollama-errors')const parsed = await parseOllamaError(res, fallback, model)+ // Ollama is not running, or moved: the proxy's raw line arrives as the+ // error body and would go straight into the bubble, Rust command name and+ // all. Caught here rather than in ollama-errors, because only this side+ // knows which address was asked (04.09.2026, same round as proxy.rs).+ const wo = this.apiUrl('')+ if (isLocalTransportFailure(parsed.raw ?? '', wo)) {+ return new ProviderError(+ localBackendUnreachableMessage('Ollama', wo), 'ollama', 'network', status, model,+ )+ }const message = chatStyleMessage(parsed)let code = 'network'if (parsed.kind === 'missing-blob') code = 'ollama_missing_blob'diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 4f92ce83..e40e45d8 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -22,6 +22,7 @@ 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, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'+import { isLocalTransportFailure, localBackendUnreachableMessage } from '../../lib/local-backend-transport'import { applyTemplateContract } from './normalize-system'import { clampEffort, hasEffortLadder, DEFAULT_EFFORT } from '../../lib/effort'import {@@ -1482,6 +1483,16 @@ export class OpenAIProvider implements ProviderClient {message = friendlycode = 'network'}+ } else if (+ isPrivateOrLanHost(hostnameOf(this.baseUrl)) &&+ isLocalTransportFailure(message, this.baseUrl)+ ) {+ // Someone else's server on this machine or on the LAN: LM Studio,+ // llama.cpp, vLLM, a box in the next room. Same raw proxy line, same+ // house rule, only the name changes. Nothing to translate for a cloud+ // endpoint, whose own words are the honest answer.+ message = localBackendUnreachableMessage(this.config.name, this.baseUrl)+ code = 'network'}return new ProviderError(message, 'openai', code, res.status, undefined, parseRetryAfter(res))diff --git a/src/lib/__tests__/kein-rust-name-im-chatfenster.test.ts b/src/lib/__tests__/kein-rust-name-im-chatfenster.test.tsnew file mode 100644index 00000000..6b190725--- /dev/null+++ b/src/lib/__tests__/kein-rust-name-im-chatfenster.test.ts@@ -0,0 +1,89 @@+/**+ * Die zweite Haelfte des P1-Fehlfunds vom 04.09.2026.+ *+ * Der Proxy gibt eine abgelehnte Verbindung als+ * Response(503, {"error": "proxy_localhost_stream_chunked: error sending+ * request for url (http://127.0.0.1:8127/v1/chat/completions)"})+ * zurueck. Bis zu diesem Tag hat das niemanden gestoert, weil die Meldung ihr+ * Wettrennen gegen die Schlussmarke des Streams verlor und der Nutzer+ * stattdessen "the connection dropped, check your network" las. Falsch, aber+ * harmlos aussehend. Seit das Rennen entschieden ist (proxy.rs), kommt die+ * echte Zeile an, und jetzt muss jeder Anbieter sie uebersetzen. Sonst steht+ * ein Rust-Befehlsname im Chatfenster, und das ist Hausregel-Bruch.+ *+ * Lauf: npx vitest run src/lib/__tests__/kein-rust-name-im-chatfenster.test.ts+ */+import { describe, it, expect } from 'vitest'+import {+ hostOf,+ isLocalTransportFailure,+ localBackendUnreachableMessage,+} from '../local-backend-transport'++const ROH =+ 'proxy_localhost_stream_chunked: error sending request for url (http://127.0.0.1:8127/v1/chat/completions)'++describe('hostOf', () => {+ it('schneidet Schema und Pfad weg und laesst den Port stehen', () => {+ expect(hostOf('http://127.0.0.1:8127/v1')).toBe('127.0.0.1:8127')+ expect(hostOf('https://192.168.0.54:11434')).toBe('192.168.0.54:11434')+ expect(hostOf('http://localhost:1234/v1/chat/completions')).toBe('localhost:1234')+ })++ it('gibt bei Unsinn eine leere Zeichenkette statt zu werfen', () => {+ expect(hostOf('')).toBe('')+ expect(hostOf(undefined as unknown as string)).toBe('')+ })+})++describe('isLocalTransportFailure', () => {+ it('erkennt jede Form, in der eine abgelehnte Verbindung ankommt', () => {+ for (const msg of [+ ROH,+ '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',+ 'tcp connect error 127.0.0.1:8127',+ ]) {+ expect(isLocalTransportFailure(msg, 'http://127.0.0.1:8127/v1')).toBe(true)+ }+ })++ it('laesst die eigenen Worte des Servers in Ruhe', () => {+ const echt = 'HTTP 400: {"error":"context length exceeded"}'+ expect(isLocalTransportFailure(echt, 'http://127.0.0.1:8127/v1')).toBe(false)+ })++ it('schiebt den Fehler eines FREMDEN Servers nicht diesem hier zu', () => {+ // Zwei lokale Server nebeneinander: wer 11434 nicht erreicht, soll nicht+ // hoeren, er solle 8127 neu starten.+ const andrer = 'error sending request for url (http://127.0.0.1:11434/api/chat)'+ expect(isLocalTransportFailure(andrer, 'http://127.0.0.1:8127/v1')).toBe(false)+ expect(isLocalTransportFailure(andrer, 'http://127.0.0.1:11434')).toBe(true)+ })++ it('faellt bei einer leeren Adresse auf falsch zurueck, statt alles zu treffen', () => {+ expect(isLocalTransportFailure(ROH, '')).toBe(false)+ })+})++describe('localBackendUnreachableMessage', () => {+ const satz = localBackendUnreachableMessage('LM Studio', 'http://127.0.0.1:1234/v1')++ it('nennt den Anbieter, die Adresse und den Weg in die Einstellungen', () => {+ expect(satz).toContain('LM Studio')+ expect(satz).toContain('127.0.0.1:1234')+ expect(satz).toContain('Settings, AI Backends')+ })++ it('redet bei einer Adresse auf diesem Rechner NICHT vom Netz', () => {+ expect(satz).not.toMatch(/network/i)+ expect(satz).not.toMatch(/internet/i)+ expect(satz).not.toMatch(/connection dropped/i)+ })++ it('traegt keinen Rust-Befehlsnamen und keinen Bindestrich-Gedankenstrich', () => {+ expect(satz).not.toContain('proxy_localhost')+ expect(satz).not.toMatch(/[–—]/)+ })+})diff --git a/src/lib/builtin-slot-eviction.ts b/src/lib/builtin-slot-eviction.tsindex 9bd3f4b8..f00867a5 100644--- a/src/lib/builtin-slot-eviction.ts+++ b/src/lib/builtin-slot-eviction.ts@@ -154,7 +154,10 @@ async function bringEngineBack(): Promise<void> {const { useModelStore } = await import('../stores/modelStore')const gewaehlt = useModelStore.getState().activeModelif (!gewaehlt) return- const { ensureBuiltinEngineAlive } = await import('../api/builtin-ensure')+ const { ensureBuiltinEngineAlive, builtinSlotSwitchedOff } = await import('../api/builtin-ensure')+ // Der Nutzer hat die Engine in den Einstellungen ausgeschaltet. Der+ // Steckplatz gehoert ihr wieder, aber niemand hat sie zurueckgebeten.+ if (builtinSlotSwitchedOff()) returnawait ensureBuiltinEngineAlive(gewaehlt)log.info('[builtin-slot] engine has the local slot again, brought it back')} catch (e) {diff --git a/src/lib/local-backend-transport.ts b/src/lib/local-backend-transport.tsnew file mode 100644index 00000000..385c56c3--- /dev/null+++ b/src/lib/local-backend-transport.ts@@ -0,0 +1,65 @@+/**+ * One reading of "the local backend did not answer", shared by everyone who+ * talks to a server on this machine or on the LAN.+ *+ * The Rust proxy hands a refused connection back as+ * `Response(503, {"error": "proxy_localhost_stream_chunked: error sending+ * request for url (http://127.0.0.1:8127/v1/chat/completions)"})`. That text+ * names a Rust command and a port and tells the user nothing they can act on,+ * so no provider may put it in a chat bubble. Until 04.09.2026 nobody had to:+ * the proxy's end-of-stream marker won the race against the rejection and the+ * chat said "the connection dropped, check your network" instead, which was+ * worse, because it was wrong. With that race closed (see proxy.rs) the real+ * message arrives, and every provider needs the same two answers about it:+ * is this a transport failure against MY host, and what do I say instead.+ */++/** The shapes a refused or broken local connection arrives in. */+const TRANSPORT_RE =+ /error sending request|connection refused|failed to fetch|ECONNREFUSED|tcp connect|proxy_localhost/i++/**+ * True when `message` is a transport failure against `baseUrl`'s host.+ *+ * Three halves, and each one earned its place. Without the pattern check a real+ * HTTP error from the server would be swallowed and replaced by our guess.+ * Without the hostname check a failure against a different machine would be+ * blamed on this one. And without the port check, the two servers people+ * actually run side by side on 127.0.0.1, our engine on 8127 and Ollama on+ * 11434, are indistinguishable: whoever could not reach one was told to restart+ * the other. The port is only demanded when the message names one at all, so+ * the barer shapes (`ECONNREFUSED 127.0.0.1`, a browser's `Failed to fetch`)+ * still land.+ */+export function isLocalTransportFailure(message: string, baseUrl: string): boolean {+ const msg = String(message ?? '')+ const host = hostOf(baseUrl)+ if (!host) return false+ if (!TRANSPORT_RE.test(msg)) return false+ const [name, port] = [host.split(':')[0], host.split(':')[1]]+ if (!name || !msg.includes(name)) return false+ if (!port) return true+ const genannt = [...msg.matchAll(new RegExp(`${maskiert(name)}:(\\d+)`, 'g'))].map((m) => m[1])+ return genannt.length === 0 || genannt.includes(port)+}++/** Punkte in einer IP sind sonst Platzhalter fuer jedes Zeichen. */+function maskiert(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+}++/** `127.0.0.1:8127` out of `http://127.0.0.1:8127/v1`, and '' when it is not a URL. */+export function hostOf(baseUrl: string): string {+ return String(baseUrl ?? '').replace(/^https?:\/\//, '').replace(/\/.*$/, '')+}++/**+ * What the user reads when a backend that is not our own engine went silent.+ *+ * Deliberately without a "check your network" line: the address is on this+ * machine or on the LAN, so the internet is never the answer. The three causes+ * named are the three that actually happen, in the order they happen.+ */+export function localBackendUnreachableMessage(name: string, baseUrl: string): string {+ return `${name} is not answering on ${hostOf(baseUrl)}. It is either not running, still starting up, or listening on a different address. Start it and send again, or pick a different backend in Settings, AI Backends.`+}