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
feat: support custom LLM request headers
nash_su40c6a84c7ff7
diff --git a/src-tauri/src/agent/provider.rs b/src-tauri/src/agent/provider.rsindex 919aae60..fb895c0b 100644--- a/src-tauri/src/agent/provider.rs+++ b/src-tauri/src/agent/provider.rs@@ -1,3 +1,4 @@+use std::collections::BTreeMap;use std::future::Future;use std::pin::Pin;use std::time::Duration;@@ -48,6 +49,10 @@ pub struct LlmConfig {// do not reinterpret it as provider tokens without migrating callers.#[serde(default)]pub max_context_size: Option<usize>,+ /// Provider-specific gateway headers. Values are validated again before+ /// each request because app-state may be edited outside the settings UI.+ #[serde(default)]+ pub custom_headers: BTreeMap<String, String>,}impl LlmConfig {@@ -506,8 +511,7 @@ impl LlmClient {let response = self.client.post(url)- .header("Content-Type", "application/json")- .header("x-goog-api-key", self.config.api_key.trim())+ .headers(google_headers(&self.config)?).json(&body).send().await@@ -563,8 +567,7 @@ impl LlmClient {let response = self.client.post(url)- .header("Content-Type", "application/json")- .header("x-goog-api-key", self.config.api_key.trim())+ .headers(google_headers(&self.config)?).json(&body).send().await@@ -594,7 +597,7 @@ impl LlmClient {}fn openai_headers(config: &LlmConfig, url: &str) -> Result<HeaderMap, String> {- let mut headers = HeaderMap::new();+ let mut headers = custom_headers(config)?;headers.insert("Content-Type", HeaderValue::from_static("application/json"));let key = config.api_key.trim();if !key.is_empty() {@@ -616,7 +619,7 @@ fn openai_headers(config: &LlmConfig, url: &str) -> Result<HeaderMap, String> {}fn anthropic_headers(config: &LlmConfig, url: &str) -> Result<HeaderMap, String> {- let mut headers = HeaderMap::new();+ let mut headers = custom_headers(config)?;headers.insert("Content-Type", HeaderValue::from_static("application/json"));headers.insert("anthropic-version",@@ -643,6 +646,31 @@ fn anthropic_headers(config: &LlmConfig, url: &str) -> Result<HeaderMap, String>Ok(headers)}+fn google_headers(config: &LlmConfig) -> Result<HeaderMap, String> {+ let mut headers = custom_headers(config)?;+ headers.insert("Content-Type", HeaderValue::from_static("application/json"));+ if !config.api_key.trim().is_empty() {+ headers.insert(+ "x-goog-api-key",+ HeaderValue::from_str(config.api_key.trim())+ .map_err(|err| format!("Invalid API key header: {err}"))?,+ );+ }+ Ok(headers)+}++fn custom_headers(config: &LlmConfig) -> Result<HeaderMap, String> {+ let mut headers = HeaderMap::new();+ for (name, value) in &config.custom_headers {+ let name = HeaderName::from_bytes(name.trim().as_bytes())+ .map_err(|err| format!("Invalid custom header name '{name}': {err}"))?;+ let value = HeaderValue::from_str(value.trim())+ .map_err(|err| format!("Invalid custom header value for '{name}': {err}"))?;+ headers.insert(name, value);+ }+ Ok(headers)+}+fn openai_user_content(user: &str, images: &[AgentImage]) -> Value {if images.is_empty() {return Value::String(user.to_string());@@ -962,9 +990,30 @@ mod tests {reasoning: None,max_tokens: None,max_context_size: None,+ custom_headers: BTreeMap::new(),}}+ #[test]+ fn custom_headers_are_validated_and_required_auth_wins_case_insensitively() {+ let mut config = config("openai");+ config+ .custom_headers+ .insert("X-Tenant-ID".into(), "team-a".into());+ config+ .custom_headers+ .insert("authorization".into(), "Custom secret".into());+ let headers =+ openai_headers(&config, "https://api.openai.com/v1/chat/completions").unwrap();+ assert_eq!(headers.get("x-tenant-id").unwrap(), "team-a");+ assert_eq!(headers.get("authorization").unwrap(), "Bearer key");++ config+ .custom_headers+ .insert("X-Bad".into(), "ok\r\nInjected: yes".into());+ assert!(custom_headers(&config).is_err());+ }+#[test]fn ollama_url_normalizes_common_endpoint_shapes() {assert_eq!(diff --git a/src-tauri/src/agent/runtime.rs b/src-tauri/src/agent/runtime.rsindex 37fe13b7..5554da77 100644--- a/src-tauri/src/agent/runtime.rs+++ b/src-tauri/src/agent/runtime.rs@@ -4085,6 +4085,7 @@ mod tests {reasoning: None,max_tokens: None,max_context_size: Some(8_000),+ custom_headers: Default::default(),};let fitted = fit_context_to_model(context, Some(&config));assert!(fitted.system.contains("system"));@@ -4109,6 +4110,7 @@ mod tests {reasoning: None,max_tokens: None,max_context_size: Some(8_000),+ custom_headers: Default::default(),};let fitted = fit_context_to_model(context, Some(&config));diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 5cf59f50..2a7d1bba 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -1847,6 +1847,7 @@ fn project_llm_config(parsed: &Value, project_id: &str) -> Option<agent::provide"azureApiVersion","maxContextSize","reasoning",+ "customHeaders",] {if let Some(value) = provider.get(key) {profile_object.insert(key.to_string(), value.clone());@@ -2803,7 +2804,7 @@ mod tests {let state = json!({"llmConfig": { "provider": "openai", "apiKey": "global", "model": "gpt-global", "ollamaUrl": "", "customEndpoint": "", "maxContextSize": 1000 },"providerConfigs": {- "deepseek": { "apiKey": "rotated", "model": "provider-model", "baseUrl": "https://new.example/v1", "apiMode": "chat_completions" }+ "deepseek": { "apiKey": "rotated", "model": "provider-model", "baseUrl": "https://new.example/v1", "apiMode": "chat_completions", "customHeaders": { "X-Tenant-ID": "team-a" } }},"projectLlmOverrides": {"project-a": {@@ -2819,6 +2820,10 @@ mod tests {assert_eq!(config.api_key, "rotated");assert_eq!(config.model, "project-model");assert_eq!(config.custom_endpoint, "https://new.example/v1");+ assert_eq!(+ config.custom_headers.get("X-Tenant-ID").map(String::as_str),+ Some("team-a")+ );}#[test]diff --git a/src/components/settings/preset-resolver.ts b/src/components/settings/preset-resolver.tsindex 52f7ec0e..a599d049 100644--- a/src/components/settings/preset-resolver.ts+++ b/src/components/settings/preset-resolver.ts@@ -44,6 +44,7 @@ export function resolveConfig(typeof ov.requestTimeoutMinutes === "number" && Number.isFinite(ov.requestTimeoutMinutes)? Math.max(1, Math.min(1440, Math.floor(ov.requestTimeoutMinutes))): fallback.requestTimeoutMinutes+ const customHeaders = ov.customHeadersif (preset.provider === "custom") {return {@@ -57,6 +58,7 @@ export function resolveConfig(reasoning,localCliIsolation: false,requestTimeoutMinutes,+ customHeaders,}}@@ -71,6 +73,7 @@ export function resolveConfig(reasoning,localCliIsolation: false,requestTimeoutMinutes,+ customHeaders,}}@@ -87,6 +90,7 @@ export function resolveConfig(reasoning,localCliIsolation: false,requestTimeoutMinutes,+ customHeaders,}}@@ -120,5 +124,6 @@ export function resolveConfig(reasoning,localCliIsolation: false,requestTimeoutMinutes,+ customHeaders,}}diff --git a/src/components/settings/sections/llm-provider-section.tsx b/src/components/settings/sections/llm-provider-section.tsxindex c4ba85f1..c2e4198b 100644--- a/src/components/settings/sections/llm-provider-section.tsx+++ b/src/components/settings/sections/llm-provider-section.tsx@@ -15,6 +15,26 @@ import { testLlmConnection, testLlmFunction, type ProviderTestResult } from "@/limport { projectLlmProfile, resolveProjectLlmConfig } from "@/lib/llm-task-routing"import { saveProjectLlmOverride } from "@/lib/project-store"+const HTTP_HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/++export function llmHeadersToText(headers: Record<string, string> | undefined): string {+ return Object.entries(headers ?? {}).map(([name, value]) => `${name}: ${value}`).join("\n")+}++export function parseLlmHeadersText(text: string): Record<string, string> {+ const headers: Record<string, string> = {}+ for (const rawLine of text.split(/\r?\n/)) {+ const line = rawLine.trim()+ if (!line || line.startsWith("#")) continue+ const separator = line.indexOf(":")+ if (separator <= 0) continue+ const name = line.slice(0, separator).trim()+ const value = line.slice(separator + 1).trim()+ if (HTTP_HEADER_NAME_RE.test(name) && value && !/[\r\n]/.test(value)) headers[name] = value+ }+ return headers+}+export function LlmProviderSection() {const { t } = useTranslation()const providerConfigs = useWikiStore((s) => s.providerConfigs)@@ -362,9 +382,11 @@ function PresetRow({const localCliIsolation = ov.localCliIsolation === trueconst codexCliTimeoutMinutes = Math.max(1, Math.min(240, ov.codexCliTimeoutMinutes ?? 10))const requestTimeoutMinutes = Math.max(1, Math.min(1440, ov.requestTimeoutMinutes ?? 30))+ const [headersText, setHeadersText] = useState(() => llmHeadersToText(ov.customHeaders))const isLocalCliProvider = preset.provider === "claude-code" || preset.provider === "codex-cli"const [testState, setTestState] = useState<ProviderTestState>({ kind: "idle" })const hasConfig = !!apiKey || !!ov.baseUrl || !!ov.model || !!ov.azureApiVersion || !!ov.azureModelFamily+ || Object.keys(ov.customHeaders ?? {}).length > 0// Local CLI providers authenticate via their own existing login state// (inherited by the spawned subprocess), so no API key field is shown.// Ollama ditto for its local-only model.@@ -667,6 +689,22 @@ function PresetRow({</div>{!isLocalCliProvider && (+ <>+ <div className="space-y-2">+ <Label>{t("settings.sections.llm.customHeaders")}</Label>+ <textarea+ value={headersText}+ onChange={(event) => setHeadersText(event.target.value)}+ onBlur={() => onChange({ customHeaders: parseLlmHeadersText(headersText) })}+ rows={3}+ spellCheck={false}+ placeholder="X-Tenant-ID: team-a"+ className="w-full resize-y rounded-md border bg-background px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring"+ />+ <p className="text-xs text-muted-foreground">+ {t("settings.sections.llm.customHeadersHint")}+ </p>+ </div><div className="space-y-2"><Label>{t("settings.sections.llm.requestTimeout", "Request timeout (minutes)")}</Label><Input@@ -682,6 +720,7 @@ function PresetRow({{t("settings.sections.llm.requestTimeoutHint", "Increase this for slow local CPU models. The default is 30 minutes.")}</p></div>+ </>)}<ReasoningControlsdiff --git a/src/i18n/en.json b/src/i18n/en.jsonindex a14e0c55..387f1b45 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -520,6 +520,8 @@"codexCliTimeoutHint": "Overall timeout for one Codex CLI request. Raise this for long PDF ingest or slower local/network sessions.","requestTimeout": "Request timeout (minutes)","requestTimeoutHint": "Increase this for slow local CPU models. The default is 30 minutes.",+ "customHeaders": "Custom request headers",+ "customHeadersHint": "Optional. Enter one Header-Name: value per line. Content-Type and configured API-key headers take precedence.","cliStatus": "CLI status","checkingCli": "Checking…","recheckCli": "Re-check",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex e35f9452..c654bebb 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -520,6 +520,8 @@"codexCliTimeoutHint": "单次 Codex CLI 请求的总超时时间。长 PDF 摄取或较慢的本地 / 网络会话可适当调大。","requestTimeout": "请求超时时间(分钟)","requestTimeoutHint": "本地 CPU 模型响应较慢时可适当调高,默认 30 分钟。",+ "customHeaders": "自定义请求头",+ "customHeadersHint": "可选。每行填写一条 Header-Name: value。Content-Type 和已配置的 API 密钥请求头优先。","cliStatus": "CLI 状态","checkingCli": "正在检查……","recheckCli": "重新检查",diff --git a/src/lib/__tests__/llm-providers.test.ts b/src/lib/__tests__/llm-providers.test.tsindex f7650b7e..1f6c6611 100644--- a/src/lib/__tests__/llm-providers.test.ts+++ b/src/lib/__tests__/llm-providers.test.ts@@ -5,6 +5,7 @@ import {getProviderConfig,parseAnthropicLine,parseGoogleLine,+ mergeLlmRequestHeaders,} from "../llm-providers"import type { LlmConfig as RealLlmConfig } from "@/stores/wiki-store"@@ -18,6 +19,40 @@ const makeConfig = (overrides: Partial<RealLlmConfig> = {}): RealLlmConfig => ({...overrides,})+describe("custom LLM request headers", () => {+ it("adds gateway headers and preserves protocol authentication precedence", () => {+ const cfg = getProviderConfig(makeConfig({+ provider: "openai",+ apiKey: "real-key",+ customHeaders: { "X-Tenant-ID": "team-a", authorization: "Custom secret" },+ }))+ expect(cfg.headers["X-Tenant-ID"]).toBe("team-a")+ expect(cfg.headers.Authorization).toBe("Bearer real-key")+ expect(cfg.headers.authorization).toBeUndefined()+ })++ it("allows custom Authorization when a custom endpoint has no API key", () => {+ const cfg = getProviderConfig(makeConfig({+ provider: "custom",+ apiKey: "",+ customEndpoint: "https://gateway.example/v1",+ customHeaders: { Authorization: "Basic gateway-token" },+ }))+ expect(cfg.headers.Authorization).toBe("Basic gateway-token")+ })++ it("drops malformed names and newline-bearing values", () => {+ expect(mergeLlmRequestHeaders({+ "Bad Header": "value",+ "X-Good": "ok",+ "X-Injection": "safe\r\nInjected: yes",+ }, { "Content-Type": "application/json" })).toEqual({+ "X-Good": "ok",+ "Content-Type": "application/json",+ })+ })+})+describe("MiniMax Provider", () => {it("uses the Anthropic Messages endpoint under /anthropic", () => {const cfg = getProviderConfig(makeConfig())diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.tsindex 13faa9f4..a8239dca 100644--- a/src/lib/llm-providers.ts+++ b/src/lib/llm-providers.ts@@ -66,6 +66,31 @@ interface ProviderConfig {}const JSON_CONTENT_TYPE = "application/json"+const HTTP_HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/++/**+ * Merge user-supplied gateway headers with protocol headers. Names are+ * compared case-insensitively so a differently-cased duplicate cannot bypass+ * authentication precedence. Invalid names and CR/LF values are ignored at+ * this boundary because persisted settings may predate UI validation.+ */+export function mergeLlmRequestHeaders(+ custom: Record<string, string> | undefined,+ required: Record<string, string>,+): Record<string, string> {+ const merged = new Map<string, [string, string]>()+ for (const [name, value] of Object.entries(custom ?? {})) {+ const trimmedName = name.trim()+ const trimmedValue = value.trim()+ if (!HTTP_HEADER_NAME_RE.test(trimmedName) || !trimmedValue || /[\r\n]/.test(trimmedValue)) continue+ merged.set(trimmedName.toLowerCase(), [trimmedName, trimmedValue])+ }+ for (const [name, value] of Object.entries(required)) {+ if (!value) continue+ merged.set(name.toLowerCase(), [name, value])+ }+ return Object.fromEntries(merged.values())+}/*** Origin header for local-LLM endpoints (Ollama, LM Studio, llama.cpp@@ -699,7 +724,8 @@ export function buildAnthropicUrl(base: string): string {return `${trimmed}/v1/messages`}-function buildAnthropicHeaders(apiKey: string, url: string): Record<string, string> {+function buildAnthropicHeaders(config: LlmConfig, url: string): Record<string, string> {+ const apiKey = config.apiKeyconst base: Record<string, string> = {"Content-Type": JSON_CONTENT_TYPE,"anthropic-version": "2023-06-01",@@ -710,7 +736,7 @@ function buildAnthropicHeaders(apiKey: string, url: string): Record<string, stribase["x-api-key"] = apiKeybase["anthropic-dangerous-direct-browser-access"] = "true"}- return base+ return mergeLlmRequestHeaders(config.customHeaders, base)}/**@@ -825,10 +851,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {case "openai":return {url: "https://api.openai.com/v1/chat/completions",- headers: {+ headers: mergeLlmRequestHeaders(config.customHeaders, {"Content-Type": JSON_CONTENT_TYPE,Authorization: `Bearer ${apiKey}`,- },+ }),buildBody: (messages, overrides) => ({...buildOpenAiCompatibleBody(config, messages, overrides),model,@@ -840,7 +866,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {const url = buildAnthropicUrl("https://api.anthropic.com")return {url,- headers: buildAnthropicHeaders(apiKey, url),+ headers: buildAnthropicHeaders(config, url),buildBody: (messages, overrides) => {assertMiniMaxImageSupport(url, model, messages)return {@@ -860,10 +886,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {const encodedModel = encodeURIComponent(model)return {url: `https://generativelanguage.googleapis.com/v1beta/models/${encodedModel}:streamGenerateContent?alt=sse`,- headers: {+ headers: mergeLlmRequestHeaders(config.customHeaders, {"Content-Type": JSON_CONTENT_TYPE,"x-goog-api-key": apiKey,- },+ }),buildBody: (messages, overrides) => buildGoogleBody(messages, {...(overrides ?? {}),reasoning: effectiveReasoning(config, overrides),@@ -879,10 +905,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {model,config.azureApiVersion ?? AZURE_OPENAI_API_VERSION,),- headers: {+ headers: mergeLlmRequestHeaders(config.customHeaders, {"Content-Type": JSON_CONTENT_TYPE,"api-key": apiKey,- },+ }),buildBody: (messages, overrides) =>buildOpenAiCompatibleBody(config, messages, overrides),parseStream: parseOpenAiLine,@@ -902,10 +928,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {}return {url: `${ollamaBase}/v1/chat/completions`,- headers: {+ headers: mergeLlmRequestHeaders(config.customHeaders, {"Content-Type": JSON_CONTENT_TYPE,...localLlmOriginHeader(),- },+ }),buildBody: (messages, overrides) => ({...buildOpenAiCompatibleBody(config, messages, overrides),model,@@ -923,7 +949,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {const url = buildAnthropicUrl(customEndpoint || "https://api.minimax.io/anthropic")return {url,- headers: buildAnthropicHeaders(apiKey, url),+ headers: buildAnthropicHeaders(config, url),buildBody: (messages, overrides) => {assertMiniMaxImageSupport(url, model, messages)return {@@ -955,7 +981,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {const url = buildAnthropicUrl(customEndpoint)return {url,- headers: buildAnthropicHeaders(apiKey, url),+ headers: buildAnthropicHeaders(config, url),buildBody: (messages, overrides) => {assertMiniMaxImageSupport(url, model, messages)return {@@ -983,7 +1009,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {const azure = isAzureOpenAiEndpoint(url)return {url,- headers: {+ headers: mergeLlmRequestHeaders(config.customHeaders, {"Content-Type": JSON_CONTENT_TYPE,...(apiKey? azure@@ -995,7 +1021,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {// workaround. Public custom gateways may reject unexpected// browser Origin headers, so leave them untouched....(!azure && isLocalOrPrivateHttpEndpoint(url) ? localLlmOriginHeader() : {}),- },+ }),buildBody: (messages, overrides) => {const body = buildOpenAiCompatibleBody(config, messages, overrides)if (!azure) body.model = modeldiff --git a/src/lib/llm-task-routing.test.ts b/src/lib/llm-task-routing.test.tsindex 96d0d5e5..a688c0c9 100644--- a/src/lib/llm-task-routing.test.ts+++ b/src/lib/llm-task-routing.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest"-import { resolveProjectLlmConfig, resolveTaskLlmConfig } from "./llm-task-routing"+import { projectLlmProfile, resolveProjectLlmConfig, resolveTaskLlmConfig } from "./llm-task-routing"import type { LlmConfig } from "@/stores/wiki-store"const fallback: LlmConfig = {@@ -64,6 +64,15 @@ describe("resolveTaskLlmConfig", () => {})describe("resolveProjectLlmConfig", () => {+ it("does not duplicate API keys or custom headers into project profiles", () => {+ const profile = projectLlmProfile({+ ...fallback,+ customHeaders: { Authorization: "Bearer gateway-secret" },+ })+ expect(profile).not.toHaveProperty("apiKey")+ expect(profile).not.toHaveProperty("customHeaders")+ })+it("keeps the global config when project overrides are disabled", () => {expect(resolveProjectLlmConfig(fallback, {}, {enabled: false,diff --git a/src/lib/llm-task-routing.ts b/src/lib/llm-task-routing.tsindex 72e1f811..18142094 100644--- a/src/lib/llm-task-routing.ts+++ b/src/lib/llm-task-routing.ts@@ -30,8 +30,10 @@ export function resolveProjectLlmConfig(return resolveConfig(preset, override, globalConfig)}-export function projectLlmProfile(config: LlmConfig): Omit<LlmConfig, "apiKey"> {- const { apiKey: _apiKey, ...profile } = config+export function projectLlmProfile(config: LlmConfig): Omit<LlmConfig, "apiKey" | "customHeaders"> {+ // Headers can contain gateway credentials, so keep them in the provider+ // credential record and merge them at runtime just like the API key.+ const { apiKey: _apiKey, customHeaders: _customHeaders, ...profile } = configreturn profile}diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex 5743679f..8ad13c58 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -45,6 +45,8 @@ interface LlmConfig {codexCliTimeoutMinutes?: number/** HTTP LLM request backstop. Defaults to 30 minutes for legacy configs. */requestTimeoutMinutes?: number+ /** Optional headers added to every HTTP request for this provider preset. */+ customHeaders?: Record<string, string>}export type SearchProvider =@@ -323,6 +325,7 @@ export interface ProviderOverride {localCliIsolation?: booleancodexCliTimeoutMinutes?: numberrequestTimeoutMinutes?: number+ customHeaders?: Record<string, string>}export type ProviderConfigs = Record<string, ProviderOverride>@@ -350,7 +353,7 @@ export interface ProjectLlmOverride {* providerConfigs[presetId], so rotating a key never requires rewriting* every project override and credentials are not duplicated per project.*/- profile?: Omit<LlmConfig, "apiKey">+ profile?: Omit<LlmConfig, "apiKey" | "customHeaders">}export interface ExternalPreview {