Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(llamacpp): never route engine loopback requests through a proxy (#9182)
James Dam2c06784c954a
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex 16f76fb8e..59125019f 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -37,11 +37,12 @@ async fn engine_endpoint<R: Runtime>(Ok((h.port, h.api_key.clone(), h.pid))}+/// Loopback only, so never through a proxy; see `loopback_client_builder`.async fn http_client() -> reqwest::Client {- reqwest::Client::builder()+ crate::engine::worker::loopback_client_builder().timeout(Duration::from_secs(600)).build()- .unwrap_or_else(|_| reqwest::Client::new())+ .unwrap_or_else(|_| crate::engine::worker::loopback_client())}/// Payload for the `llamacpp-model-load-progress` event, mirrored from thediff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rsindex 81a76931f..307dd0840 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs@@ -281,7 +281,7 @@ async fn abort_unload_watcher(state: &Arc<LlamacppState>) {/// Models with a request in flight, from the worker's own `/models` listing./// An unreachable worker reports none -- it cannot be generating.async fn busy_models(port: u16, api_key: &str) -> Vec<String> {- let Ok(resp) = reqwest::Client::new()+ let Ok(resp) = worker::loopback_client().get(format!("http://127.0.0.1:{port}/models")).bearer_auth(api_key).send()@@ -401,7 +401,7 @@ pub async fn reload_engine_models(body["slot_cache_mib"] = serde_json::json!(m);}- let resp = reqwest::Client::new()+ let resp = worker::loopback_client().post(format!("http://127.0.0.1:{port}/models/reload")).bearer_auth(&api_key).json(&body)@@ -520,7 +520,7 @@ pub async fn erase_thread_slot_state(body.insert("model".into(), serde_json::Value::String(m));}let body = serde_json::Value::Object(body);- let client = reqwest::Client::new();+ let client = worker::loopback_client();let resp = client.post(format!("http://127.0.0.1:{port}/slots/state/erase")).bearer_auth(&api_key)diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rsindex 16cab8ba4..d3d7e66ee 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rs@@ -63,7 +63,7 @@ async fn subscribe_once<R: Runtime>() -> Result<(), String> {use futures_util::StreamExt;- let resp = reqwest::Client::new()+ let resp = super::worker::loopback_client().get(format!("http://127.0.0.1:{port}/models/sse")).bearer_auth(api_key).send()diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rsindex cfbfac53e..0d7fa671b 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs@@ -206,6 +206,27 @@ const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15)+/// A client for the worker's loopback port, with proxies switched off.+///+/// reqwest picks up `HTTP(S)_PROXY`/`ALL_PROXY` from the environment, and on+/// Windows and macOS the system proxy too, and neither exempts 127.0.0.1+/// unless `NO_PROXY` says so. A VPN client, a proxy tool or a corporate PAC+/// setup then captures the request meant for the worker, and every model load+/// fails with a bare "error sending request for url (http://127.0.0.1:...)"+/// even though the worker is up and listening. The worker is on this machine+/// by construction, so there is never a proxy worth going through.+///+/// Internet-facing clients (model downloads, remote gguf reads) deliberately+/// do not use this: they must keep honouring the user's proxy.+pub fn loopback_client_builder() -> reqwest::ClientBuilder {+ reqwest::Client::builder().no_proxy()+}++/// [`loopback_client_builder`] with reqwest's defaults otherwise.+pub fn loopback_client() -> reqwest::Client {+ loopback_client_builder().build().unwrap_or_default()+}+/// How long to wait for the handshake. Generous because a cold page-cache read/// of the preset plus binding a port can be slow on a loaded machine, but far/// short of a model load -- the worker answers before loading anything.diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 82535c149..ba8cb1d99 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -3595,9 +3595,11 @@ async fn orchestrate_inner(if model_id.is_none() {// The llama.cpp router is a desktop-only listing call on the app's// reqwest 0.12 stack, not agent upstream traffic, so it does not use- // the genai client threaded through `OrchestrationArgs`.+ // the genai client threaded through `OrchestrationArgs`. It only+ // ever reaches the worker on 127.0.0.1, so it never goes through a+ // proxy: a system or env proxy would otherwise capture loopback too.static ROUTER_CLIENT: std::sync::LazyLock<reqwest::Client> =- std::sync::LazyLock::new(reqwest::Client::new);+ std::sync::LazyLock::new(tauri_plugin_llamacpp::engine::worker::loopback_client);if let Some(first) = router_first_model(llama_state, &ROUTER_CLIENT).await {model_id = Some(first);}diff --git a/web-app/src/lib/__tests__/model-factory.deep.test.ts b/web-app/src/lib/__tests__/model-factory.deep.test.tsindex 04c219ebd..08bab350c 100644--- a/web-app/src/lib/__tests__/model-factory.deep.test.ts+++ b/web-app/src/lib/__tests__/model-factory.deep.test.ts@@ -88,7 +88,7 @@ vi.mock('@/lib/provider-api-keys', () => ({}),}))-import { ModelFactory } from '../model-factory'+import { ModelFactory, LOOPBACK_DIRECT_PROXY } from '../model-factory'import { invoke } from '@tauri-apps/api/core'import { fetch as httpFetch } from '@tauri-apps/plugin-http'@@ -251,6 +251,22 @@ describe('model-factory deep coverage', () => {expect(body.auto_compact).toBeUndefined()})+ // The engine is on loopback; a system or env proxy must never see the+ // request, or a VPN or corporate proxy breaks local chat.+ it('sends to the engine with every loopback host exempt from proxies', async () => {+ vi.mocked(invoke).mockResolvedValue({ port: 8080, api_key: 'k' })+ await ModelFactory.createModel('m', mkProvider('llamacpp'), {})+ await getOpts().fetch('http://localhost:8080/v1/chat/completions', {+ method: 'POST',+ body: JSON.stringify({ messages: [] }),+ })+ const init = vi.mocked(httpFetch).mock.calls[0][1] as any+ expect(init.proxy).toEqual(LOOPBACK_DIRECT_PROXY)+ for (const host of ['localhost', '127.0.0.1', '::1']) {+ expect(init.proxy.all.noProxy.split(',')).toContain(host)+ }+ })+it('throws when startModel fails with Error', async () => {mockStartModel.mockRejectedValueOnce(new Error('GPU fail'))await expect(ModelFactory.createModel('m', mkProvider('llamacpp'), {})).rejects.toThrow('Failed to start model: GPU fail')@@ -305,6 +321,7 @@ describe('model-factory deep coverage', () => {await new Promise((r) => setTimeout(r, 20))expect(vi.mocked(httpFetch)).toHaveBeenCalledTimes(2)expect(vi.mocked(httpFetch).mock.calls[1][0]).toBe('http://localhost:9090/v1/cancel')+ expect((vi.mocked(httpFetch).mock.calls[1][1] as any).proxy).toEqual(LOOPBACK_DIRECT_PROXY)})it('throws when startModel fails', async () => {diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex bfcf12004..48bac94e5 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -887,6 +887,29 @@ function requireRemoteApiKey(return key}+/**+ * Requests to the local engine and MLX servers, sent so that no proxy can+ * capture them.+ *+ * `@tauri-apps/plugin-http` sends from Rust's reqwest, which reads+ * `HTTP(S)_PROXY` and the OS proxy setting (on Windows, the registry one) and+ * does not exempt loopback unless `NO_PROXY` names it. With a VPN client, a+ * proxy tool or a corporate proxy configured, the chat request to+ * `http://localhost:<port>` is then sent to that proxy and fails, although the+ * server is up. Naming any proxy turns reqwest's environment and system lookup+ * off, and the no-proxy list covers every loopback host, so the placeholder+ * address is never dialled: these requests always go direct.+ *+ * Only for loopback servers. Remote providers keep `getRuntimeFetch`, which+ * must go on honouring the user's proxy.+ */+export const LOOPBACK_DIRECT_PROXY = {+ all: { url: 'http://127.0.0.1:9', noProxy: 'localhost,127.0.0.1,::1' },+}++export const loopbackFetch: typeof globalThis.fetch = (input, init) =>+ httpFetch(input, { ...init, proxy: LOOPBACK_DIRECT_PROXY })+function getRuntimeFetch(): typeof globalThis.fetch {const maybeWindow = globalThis as typeof globalThis & {__TAURI__?: unknown@@ -1041,7 +1064,7 @@ export class ModelFactory {// but never for a preserve_thinking model: its template re-emits prior// <think> from that field, so stripping it would diverge the KV-cache prefix.let customFetch = createCustomFetch(- httpFetch,+ loopbackFetch,parameters,true,onLlamacppServerError,@@ -1116,7 +1139,7 @@ export class ModelFactory {// raw stream) with every other provider, then layer MLX's /cancel-on-abort// on top.let baseCustomFetch = createCustomFetch(- httpFetch,+ loopbackFetch,parameters,false,undefined,@@ -1133,7 +1156,7 @@ export class ModelFactory {// to stop MLX inference immediately.if (init?.signal) {init.signal.addEventListener('abort', () => {- httpFetch(`${baseUrl}/v1/cancel`, {+ loopbackFetch(`${baseUrl}/v1/cancel`, {method: 'POST',headers: { ...authHeaders, 'Content-Type': 'application/json' },body: JSON.stringify({}),