Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(llamacpp): send engine requests direct, not through a proxy (#9352) (#9353)
Thinh Le498f3b000a0e
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex cb44bbca1..f6d2da8c4 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -48,6 +48,7 @@ import {setDefaultEmbeddingModelId,type EmbedBatchResult,} from './util'+import { loopbackFetch } from './loopback-fetch'import {generatePreset,threadCacheDir,@@ -1060,7 +1061,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}try {const url = `http://127.0.0.1:${engine.port}/props?model=${encodeURIComponent(modelId)}`- const res = await fetch(url, {+ const res = await loopbackFetch(url, {headers: { Authorization: `Bearer ${engine.apiKey}` },})if (!res.ok) return undefined@@ -2410,7 +2411,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng)}}- const response = await fetch(url, {+ const response = await loopbackFetch(url, {method: 'POST',headers,body,@@ -2523,7 +2524,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngreturn this.handleStreamingResponse(url, headers, body, abortController)}// Handle non-streaming response- const response = await fetch(url, {+ const response = await loopbackFetch(url, {method: 'POST',headers,body,@@ -2904,7 +2905,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngconst sInfo = await this.ensureEmbeddingModelLoaded()const counts: number[] = []for (const text of texts) {- const res = await fetch(`http://localhost:${sInfo.port}/tokenize`, {+ const res = await loopbackFetch(`http://localhost:${sInfo.port}/tokenize`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -2963,7 +2964,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngmodel: session.model_id,encoding_format: 'float',})- const response = await fetch(baseUrl, {+ const response = await loopbackFetch(baseUrl, {method: 'POST',headers,body,diff --git a/extensions/llamacpp-extension/src/loopback-fetch.ts b/extensions/llamacpp-extension/src/loopback-fetch.tsnew file mode 100644index 000000000..da2276a2c--- /dev/null+++ b/extensions/llamacpp-extension/src/loopback-fetch.ts@@ -0,0 +1,21 @@+import { fetch as httpFetch } from '@tauri-apps/plugin-http'++/**+ * Requests to Jan's own engine, 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 and does not exempt loopback unless+ * `NO_PROXY` names it. 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.+ *+ * Same technique as `loopbackFetch` in `web-app/src/lib/model-factory.ts`; the+ * extension is a separate bundle and cannot import from the web app. Only for+ * the engine's loopback port, never for a remote provider.+ */+export const LOOPBACK_DIRECT_PROXY = {+ all: { url: 'http://127.0.0.1:9', noProxy: 'localhost,127.0.0.1,::1' },+}++export const loopbackFetch: typeof httpFetch = (input, init) =>+ httpFetch(input, { ...init, proxy: LOOPBACK_DIRECT_PROXY })diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex 62177f84a..5f0c3f349 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -18,6 +18,11 @@ vi.mock('../backend-settings')// Mock fetch globallyglobal.fetch = vi.fn()+// The engine requests go through the Tauri HTTP plugin (reqwest), not the+// webview's fetch.+const httpFetch = vi.hoisted(() => vi.fn())+vi.mock('@tauri-apps/plugin-http', () => ({ fetch: httpFetch }))+// Mock tauri-plugin-llamacpp-api (partial mock)vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {const actual = await vi.importActual<@@ -448,7 +453,7 @@ describe('llamacpp_extension', () => {}]}- global.fetch = vi.fn().mockResolvedValue({+ httpFetch.mockResolvedValue({ok: true,json: () => Promise.resolve(mockResponse)})@@ -462,7 +467,7 @@ describe('llamacpp_extension', () => {const result = await extension.chat(request)expect(result).toEqual(mockResponse)- expect(fetch).toHaveBeenCalledWith(+ expect(httpFetch).toHaveBeenCalledWith('http://localhost:3000/v1/chat/completions',expect.objectContaining({method: 'POST',@@ -1498,3 +1503,110 @@ describe('forgetThreadCache', () => {).not.toContain('/')})})++// Jan's requests to its own engine must not be captured by a proxy. reqwest+// reads HTTP(S)_PROXY and the OS proxy and only skips loopback when NO_PROXY+// names it, so each request names a proxy of its own whose no-proxy list+// covers every loopback host (#9352).+describe('engine requests bypass a configured proxy', () => {+ let extension: llamacpp_extension+ const session = {+ model_id: 'test-model',+ pid: 1,+ port: 3000,+ api_key: 'test-key',+ }++ const okJson = (body: unknown) => ({ ok: true, json: async () => body })++ const expectDirect = (urlPart: string) => {+ const call = httpFetch.mock.calls.find(([url]) =>+ String(url).includes(urlPart)+ )+ expect(call, `no plugin-http request to ${urlPart}`).toBeDefined()+ const noProxy = (call![1] as { proxy?: { all?: { noProxy?: string } } })+ .proxy?.all?.noProxy+ expect(noProxy?.split(',')).toEqual(+ expect.arrayContaining(['localhost', '127.0.0.1', '::1'])+ )+ }++ beforeEach(() => {+ vi.clearAllMocks()+ httpFetch.mockReset()+ extension = new llamacpp_extension()+ })++ it('sends the embeddings request direct', async () => {+ vi.spyOn(+ extension as never,+ 'ensureEmbeddingModelLoaded' as never+ ).mockResolvedValue(session as never)+ vi.spyOn(extension as never, 'embedBatchBudget' as never).mockResolvedValue(+ 512 as never+ )+ httpFetch.mockResolvedValue(+ okJson({ data: [{ embedding: [0.1], index: 0 }], usage: {} })+ )++ await extension.embed(['hello'])++ expectDirect('/v1/embeddings')+ })++ it('sends the tokenize request direct', async () => {+ vi.spyOn(+ extension as never,+ 'ensureEmbeddingModelLoaded' as never+ ).mockResolvedValue(session as never)+ httpFetch.mockResolvedValue(okJson({ tokens: [1, 2, 3] }))++ await expect(extension.countEmbeddingTokens(['hello'])).resolves.toEqual([3])++ expectDirect('/tokenize')+ })++ it('sends the props request direct', async () => {+ vi.spyOn(extension as never, 'getEngineInfo' as never).mockResolvedValue({+ port: 3000,+ apiKey: 'k',+ } as never)+ vi.spyOn(extension as never, 'getLoadedModels' as never).mockResolvedValue([+ 'test-model',+ ] as never)+ httpFetch.mockResolvedValue(+ okJson({ default_generation_settings: { n_ctx: 4096 } })+ )++ await expect(extension.getModelProps('test-model')).resolves.toMatchObject({+ nCtx: 4096,+ })++ expectDirect('/props')+ })++ it('sends chat requests direct, streaming or not', async () => {+ vi.spyOn(+ extension as never,+ 'ensureHealthySession' as never+ ).mockResolvedValue(session as never)+ httpFetch.mockResolvedValue({ ok: false, status: 500, json: async () => null })++ const request = {+ model: 'test-model',+ messages: [{ role: 'user', content: 'hi' }],+ }+ await extension.chat({ ...request, stream: false }).catch(() => {})+ expectDirect('/v1/chat/completions')++ httpFetch.mockClear()+ const stream = (await extension.chat({+ ...request,+ stream: true,+ })) as AsyncIterable<unknown>+ await stream[Symbol.asyncIterator]()+ .next()+ .catch(() => {})+ expectDirect('/v1/chat/completions')+ })+})