LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
fix: Ollama 403 on Windows — explicit Origin override (v0.3.12-rc1)
nash_su863ba5607c2f
diff --git a/package.json b/package.jsonindex 3cd46c6f..6dd2a2e2 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.3.11",+ "version": "0.3.12-rc1","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 491b9a88..c3d9ad08 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4414,7 +4414,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.3.11"+version = "0.3.12-rc1"dependencies = ["arrow-array","arrow-schema",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 51568bde..5d1df5d4 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.3.11"+version = "0.3.12-rc1"description = "LLM Wiki - A personal knowledge base for LLM concepts"authors = []edition = "2021"diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex f8062e8f..c3587eb7 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "LLM Wiki",- "version": "0.3.11",+ "version": "0.3.12-rc1","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/lib/__tests__/llm-providers.test.ts b/src/lib/__tests__/llm-providers.test.tsindex 9e81bd29..8c27c054 100644--- a/src/lib/__tests__/llm-providers.test.ts+++ b/src/lib/__tests__/llm-providers.test.ts@@ -303,3 +303,105 @@ describe("Sampling override translation across wires", () => {expect(body.max_tokens).toBe(8192)})})++// ── Origin header for local LLM providers (Ollama + custom OpenAI) ──+//+// Pinned by a real packet capture from a Windows user (v0.3.11) where+// plugin-http auto-injected `origin: http://tauri.localhost`,+// triggering Ollama 403 because that origin isn't in the default+// `OLLAMA_ORIGINS` allowlist. Setting Origin = same-origin makes+// Ollama always trust the request.+//+// Plugin-http v2.5.x respects user-set headers (override behavior+// confirmed by reading dist-js/index.js line 71-75), and the+// `unsafe-headers` Cargo feature ensures Rust-side reqwest forwards+// it. So this header surfacing here = bytes on the wire.++describe("Origin header — local LLM CORS workaround", () => {+ it("Ollama provider sets Origin to the request's own host (localhost)", () => {+ const cfg = getProviderConfig({+ provider: "ollama",+ apiKey: "",+ model: "llama3",+ ollamaUrl: "http://localhost:11434",+ customEndpoint: "",+ maxContextSize: 8192,+ })+ expect(cfg.headers["Origin"]).toBe("http://localhost:11434")+ })++ it("Ollama provider Origin reflects remote LAN deployment (not localhost)", () => {+ const cfg = getProviderConfig({+ provider: "ollama",+ apiKey: "",+ model: "llama3",+ ollamaUrl: "http://192.168.1.50:11434",+ customEndpoint: "",+ maxContextSize: 8192,+ })+ expect(cfg.headers["Origin"]).toBe("http://192.168.1.50:11434")+ })++ it("Ollama provider strips trailing /v1 before deriving Origin", () => {+ // User pasted "http://localhost:11434/v1" as their Ollama URL. The+ // URL the provider builds will be "http://localhost:11434/v1/chat/completions",+ // so Origin must still be "http://localhost:11434" (URL.origin+ // never includes a path anyway, but pinning this catches a+ // regression where someone derives Origin from the full URL string+ // by hand).+ const cfg = getProviderConfig({+ provider: "ollama",+ apiKey: "",+ model: "llama3",+ ollamaUrl: "http://localhost:11434/v1",+ customEndpoint: "",+ maxContextSize: 8192,+ })+ expect(cfg.headers["Origin"]).toBe("http://localhost:11434")+ })++ it("custom OpenAI-compat endpoint also gets a same-origin Origin (LM Studio / llama.cpp / vLLM)", () => {+ const cfg = getProviderConfig({+ provider: "custom",+ apiKey: "",+ model: "qwen3",+ ollamaUrl: "",+ customEndpoint: "http://127.0.0.1:1234",+ maxContextSize: 8192,+ apiMode: "chat_completions",+ } as RealLlmConfig)+ expect(cfg.headers["Origin"]).toBe("http://127.0.0.1:1234")+ })++ it("commercial provider (OpenAI) does NOT get an explicit Origin override", () => {+ // OpenAI's CORS doesn't care about Origin (auth is via API key).+ // Setting Origin would just be noise. Pin that we DON'T touch+ // commercial endpoints.+ const cfg = getProviderConfig({+ provider: "openai",+ apiKey: "k",+ model: "gpt-4o",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 128000,+ })+ expect(cfg.headers["Origin"]).toBeUndefined()+ })++ it("malformed ollamaUrl falls back gracefully (no Origin header) instead of crashing", () => {+ // Settings UI normalizes URLs but a stale config from an older+ // version could carry rubbish. Origin parsing must not throw.+ const cfg = getProviderConfig({+ provider: "ollama",+ apiKey: "",+ model: "llama3",+ ollamaUrl: "not a url",+ customEndpoint: "",+ maxContextSize: 8192,+ })+ expect(cfg.headers["Origin"]).toBeUndefined()+ // The URL itself will obviously be broken — but the provider+ // builder shouldn't have thrown.+ expect(typeof cfg.url).toBe("string")+ })+})diff --git a/src/lib/llm-client.real-llm.test.ts b/src/lib/llm-client.real-llm.test.tsnew file mode 100644index 00000000..5882fd2c--- /dev/null+++ b/src/lib/llm-client.real-llm.test.ts@@ -0,0 +1,295 @@+/**+ * End-to-end TCP test: drive `streamChat` against a local fake Ollama+ * server and assert the request lands with our explicit `Origin`+ * header (NOT a webview-injected `http://tauri.localhost`).+ *+ * Scope of what this proves vs. what it can't prove:+ *+ * ✓ Bytes-on-wire: from `getProviderConfig` → `streamChat` →+ * fetch → real TCP, the headers we asked for actually reach+ * the server. Catches regressions where future refactors strip+ * or rename the Origin header anywhere in the pipeline.+ *+ * ✗ plugin-http v2.5.x merge semantics: under Node, `tauri-fetch`+ * falls back to `globalThis.fetch` (undici), which never+ * auto-injects Origin. So the "user-set Origin overrides+ * plugin-http auto-injection" claim isn't exercised here —+ * that's verified by reading+ * `node_modules/@tauri-apps/plugin-http/dist-js/index.js`+ * line 71-75 (browser-default headers only fill keys the user+ * hasn't already set) plus a manual Windows packet capture+ * against a real desktop build. This test catches regressions+ * on OUR side; the upstream plugin behavior is verified+ * out-of-band.+ *+ * Lives in a `.real-llm.` file so it's excluded from the fast+ * mocked suite — it stands up a real listening socket and+ * shouldn't run on every save.+ */+import { describe, it, expect, vi } from "vitest"+import { createServer, type Server, type IncomingMessage, type ServerResponse } from "node:http"+import type { AddressInfo } from "node:net"++// streamChat doesn't touch Tauri commands or fs, but the module graph+// pulls them in transitively. Stub for sanity.+vi.mock("@tauri-apps/api/core", () => ({+ invoke: vi.fn().mockResolvedValue(undefined),+}))+vi.mock("@/commands/fs", () => ({+ readFile: vi.fn(),+ listDirectory: vi.fn(),+}))++import { streamChat } from "./llm-client"+import type { LlmConfig } from "@/stores/wiki-store"++interface FakeOllamaHandle {+ url: string+ receivedRequests: () => Array<{ origin?: string; userAgent?: string; body: string }>+ setRejectMode: (mode: RejectMode) => void+ close: () => Promise<void>+}++type RejectMode =+ | { kind: "accept-same-origin"; selfOrigin: string }+ | { kind: "reject-all" }++/**+ * Start a fake Ollama-compatible server on 127.0.0.1. Behavior is+ * scriptable per test:+ * - "accept-same-origin": 200 + SSE stream when the request's+ * Origin equals the configured selfOrigin; 403 with a body+ * mimicking Ollama's real CORS rejection otherwise.+ * - "reject-all": every request returns 403 (lets us prove the+ * server's CORS check is actually being exercised).+ *+ * The server records each incoming request so tests can assert what+ * Origin / User-Agent actually reached the wire.+ */+async function startFakeOllamaServer(initialMode: RejectMode): Promise<FakeOllamaHandle> {+ let mode = initialMode+ const requests: Array<{ origin?: string; userAgent?: string; body: string }> = []+ let server: Server | null = null++ const url = await new Promise<string>((resolve, reject) => {+ server = createServer((req: IncomingMessage, res: ServerResponse) => {+ const chunks: Buffer[] = []+ req.on("data", (c: Buffer) => chunks.push(c))+ req.on("end", () => {+ const body = Buffer.concat(chunks).toString("utf-8")+ const origin = req.headers["origin"] as string | undefined+ const userAgent = req.headers["user-agent"] as string | undefined+ requests.push({ origin, userAgent, body })++ // Mimic Ollama's CORS check.+ const allow =+ mode.kind === "accept-same-origin" && origin === mode.selfOrigin+ if (!allow) {+ res.statusCode = 403+ res.setHeader("Content-Type", "text/plain")+ res.end("Forbidden: origin not in allowlist")+ return+ }++ // Stream a tiny OpenAI-compatible SSE response. parseOpenAiLine+ // expects `data: ` prefix and a `[DONE]` terminator.+ res.statusCode = 200+ res.setHeader("Content-Type", "text/event-stream")+ res.setHeader("Cache-Control", "no-cache")+ const sse = [+ `data: ${JSON.stringify({ choices: [{ delta: { content: "hello" } }] })}`,+ ``,+ `data: ${JSON.stringify({ choices: [{ delta: { content: " world" } }] })}`,+ ``,+ `data: [DONE]`,+ ``,+ ``,+ ].join("\n")+ res.end(sse)+ })+ })+ server.on("error", reject)+ server.listen(0, "127.0.0.1", () => {+ const addr = server!.address() as AddressInfo+ resolve(`http://127.0.0.1:${addr.port}`)+ })+ })++ return {+ url,+ receivedRequests: () => [...requests],+ setRejectMode: (m: RejectMode) => {+ mode = m+ },+ close: () =>+ new Promise<void>((resolve) => {+ if (server) server.close(() => resolve())+ else resolve()+ }),+ }+}++const TEST_TIMEOUT_MS = 30_000++describe("streamChat against a fake Ollama server (real TCP)", () => {+ it(+ "sends Origin = same-origin so Ollama's CORS check passes (regardless of OLLAMA_ORIGINS / version)",+ async () => {+ const server = await startFakeOllamaServer({+ kind: "accept-same-origin",+ selfOrigin: "", // set after we know the URL+ })+ try {+ // selfOrigin must equal the server's own root URL.+ server.setRejectMode({ kind: "accept-same-origin", selfOrigin: server.url })++ const cfg: LlmConfig = {+ provider: "ollama",+ apiKey: "",+ model: "llama3",+ ollamaUrl: server.url,+ customEndpoint: "",+ maxContextSize: 8192,+ }++ const tokens: string[] = []+ const state: { done: boolean; error: Error | null } = { done: false, error: null }+ await streamChat(+ cfg,+ [{ role: "user", content: "hi" }],+ {+ onToken: (t) => {+ tokens.push(t)+ },+ onDone: () => {+ state.done = true+ },+ onError: (e) => {+ state.error = e+ },+ },+ )++ expect(state.error, `streamChat reported error: ${state.error?.message}`).toBeNull()+ expect(state.done).toBe(true)+ expect(tokens.join("")).toBe("hello world")++ const reqs = server.receivedRequests()+ expect(reqs).toHaveLength(1)+ // Bytes-on-wire assertion: our explicit Origin made it through.+ expect(reqs[0].origin).toBe(server.url)+ // Body is the OpenAI-shape JSON we'd expect.+ const parsed = JSON.parse(reqs[0].body) as { model: string; messages: unknown[] }+ expect(parsed.model).toBe("llama3")+ expect(parsed.messages).toEqual([{ role: "user", content: "hi" }])+ } finally {+ await server.close()+ }+ },+ TEST_TIMEOUT_MS,+ )++ it(+ "the fake server's CORS check actually rejects mismatched origins (proves the test isn't trivially green)",+ async () => {+ // Sanity check: if our Origin override regressed, the server+ // would reject. We force a wrong-origin scenario by setting the+ // server to "accept only http://something-else" and confirming+ // that streamChat surfaces a 4xx error.+ const server = await startFakeOllamaServer({+ kind: "accept-same-origin",+ selfOrigin: "http://impossible-mismatch.test",+ })+ try {+ const cfg: LlmConfig = {+ provider: "ollama",+ apiKey: "",+ model: "llama3",+ ollamaUrl: server.url,+ customEndpoint: "",+ maxContextSize: 8192,+ }++ const state: { done: boolean; error: Error | null } = { done: false, error: null }+ await streamChat(+ cfg,+ [{ role: "user", content: "hi" }],+ {+ onToken: () => {},+ onDone: () => {+ state.done = true+ },+ onError: (e) => {+ state.error = e+ },+ },+ )++ // streamChat reports HTTP errors via onError; the request still+ // resolves cleanly (no thrown exception).+ expect(state.error, "expected the 403 to surface as an onError, not silent success").not.toBeNull()+ expect(state.error!.message).toMatch(/403/)+ expect(state.done).toBe(false)++ const reqs = server.receivedRequests()+ expect(reqs).toHaveLength(1)+ // The request DID reach the server with our Origin — the 403+ // was generated by the server's allowlist mismatch, not a+ // pre-flight failure or network error.+ expect(reqs[0].origin).toBe(server.url)+ } finally {+ await server.close()+ }+ },+ TEST_TIMEOUT_MS,+ )++ it(+ "custom OpenAI-compat endpoint (LM Studio / llama.cpp) also sends Origin = same-origin",+ async () => {+ const server = await startFakeOllamaServer({+ kind: "accept-same-origin",+ selfOrigin: "",+ })+ try {+ // The custom branch builds the URL by appending /chat/completions+ // to customEndpoint. Our same-origin Origin is derived from the+ // base URL, NOT the full /chat/completions path — but URL.origin+ // strips the path anyway.+ server.setRejectMode({ kind: "accept-same-origin", selfOrigin: server.url })++ const cfg: LlmConfig = {+ provider: "custom",+ apiKey: "",+ model: "qwen3",+ ollamaUrl: "",+ customEndpoint: server.url,+ maxContextSize: 8192,+ apiMode: "chat_completions",+ }++ const state: { done: boolean; error: Error | null } = { done: false, error: null }+ await streamChat(+ cfg,+ [{ role: "user", content: "hi" }],+ {+ onToken: () => {},+ onDone: () => {+ state.done = true+ },+ onError: (e) => {+ state.error = e+ },+ },+ )++ expect(state.error).toBeNull()+ expect(state.done).toBe(true)+ expect(server.receivedRequests()[0].origin).toBe(server.url)+ } finally {+ await server.close()+ }+ },+ TEST_TIMEOUT_MS,+ )+})diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.tsindex 4f2c492f..12e114d9 100644--- a/src/lib/llm-providers.ts+++ b/src/lib/llm-providers.ts@@ -31,6 +31,44 @@ interface ProviderConfig {const JSON_CONTENT_TYPE = "application/json"+/**+ * Origin header for local-LLM endpoints (Ollama, LM Studio, llama.cpp+ * server, LocalAI, vLLM, …).+ *+ * Why we set this explicitly:+ * `@tauri-apps/plugin-http` v2.5.x auto-injects the webview's+ * own Origin (`tauri://localhost` on macOS/Linux,+ * `http://tauri.localhost` on Windows). Ollama's default+ * `OLLAMA_ORIGINS` allowlist accepts `tauri://*` since ~0.1.30+ * but NOT `http://tauri.localhost` — so Windows users hit 403+ * even when everything is configured correctly. A user packet+ * capture (v0.3.11) confirmed the request carrying+ * `origin: http://tauri.localhost`.+ *+ * Setting Origin to the request's own host = same-origin, which+ * Ollama always trusts regardless of `OLLAMA_ORIGINS` value or+ * Ollama version.+ *+ * Why this works at all:+ * plugin-http's JS shim respects user-set headers (see+ * `node_modules/@tauri-apps/plugin-http/dist-js/index.js`,+ * the loop after `new Request(input, init)` only fills+ * browser-default headers when the user did NOT already set+ * them). On the Rust side, the `unsafe-headers` feature flag+ * in `src-tauri/Cargo.toml` lets reqwest forward Origin+ * without stripping it. End-to-end this means our value wins.+ *+ * If `url` can't be parsed (mis-typed config), we return {} —+ * better to send no override than to crash building the request.+ */+function sameOriginHeader(url: string): Record<string, string> {+ try {+ return { Origin: new URL(url).origin }+ } catch {+ return {}+ }+}+function parseOpenAiLine(line: string): string | null {if (!line.startsWith("data: ")) return nullconst data = line.slice(6).trim()@@ -294,6 +332,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {url: `${ollamaBase}/v1/chat/completions`,headers: {"Content-Type": JSON_CONTENT_TYPE,+ ...sameOriginHeader(ollamaBase),},buildBody: (messages, overrides) => {const body: Record<string, unknown> = {@@ -363,6 +402,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {headers: {"Content-Type": JSON_CONTENT_TYPE,...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),+ // Local OpenAI-compatible servers (LM Studio, llama.cpp,+ // vLLM, LocalAI) often share Ollama's CORS sensitivity.+ // Same rationale as the `ollama` branch above.+ ...sameOriginHeader(base),},buildBody: (messages, overrides) => ({...buildOpenAiBody(messages, overrides),