Skip to content

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: global HTTP/HTTPS proxy with live apply (no restart)

nash_suc4ddfbd8cb14
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c3e6393c..207cee6a 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,6 +1,7 @@
mod clip_server;
mod commands;
mod panic_guard;
+mod proxy;
mod types;
use panic_guard::run_guarded;
@@ -13,6 +14,22 @@ fn clip_server_status() -> String {
.unwrap_or_else(|e| format!("error: {e}"))
}
+/// Apply a proxy configuration to the process env immediately, so the
+/// next outbound HTTP request picks it up without needing the user to
+/// restart the app. tauri-plugin-http builds a fresh
+/// `reqwest::ClientBuilder` per fetch and reqwest's `auto_sys_proxy`
+/// re-reads HTTP_PROXY / HTTPS_PROXY / NO_PROXY each time, so updating
+/// these env vars is sufficient to flip the proxy on/off live.
+///
+/// Returns the same human-readable summary `apply_proxy_env` produces
+/// for logging.
+#[tauri::command]
+fn set_proxy_env(config: proxy::ProxyConfig) -> String {
+ let summary = proxy::apply_proxy_env(&config);
+ eprintln!("[proxy] live update: {summary}");
+ summary
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
clip_server::start_clip_server();
@@ -33,6 +50,25 @@ pub fn run() {
if let Ok(dir) = app.path().resource_dir() {
commands::fs::set_resource_dir_hint(dir);
}
+ // Apply user-configured global HTTP proxy by setting
+ // HTTP_PROXY / HTTPS_PROXY / NO_PROXY env vars BEFORE
+ // any HTTP request is made. tauri-plugin-http's reqwest
+ // client reads these on first construction. Lives next
+ // to the resource-dir hint so the proxy applies to
+ // everything: LLM, embedding, update check, deep
+ // research, captioning. See src-tauri/src/proxy.rs.
+ if let Ok(dir) = app.path().app_data_dir() {
+ let store_path = dir.join("app-state.json");
+ eprintln!("[proxy] reading from {}", store_path.display());
+ if let Some(cfg) = proxy::read_proxy_config_from_store(&store_path) {
+ let summary = proxy::apply_proxy_env(&cfg);
+ eprintln!("[proxy] {summary}");
+ } else {
+ eprintln!("[proxy] no proxyConfig in store, requests go direct");
+ }
+ } else {
+ eprintln!("[proxy] could not resolve app_data_dir");
+ }
// Registry of running `claude` subprocesses, keyed by the
// frontend-generated stream id. Populated by claude_cli_spawn,
// drained on process exit or by claude_cli_kill.
@@ -71,6 +107,7 @@ pub fn run() {
commands::extract_images::extract_office_images_cmd,
commands::extract_images::extract_and_save_pdf_images_cmd,
commands::extract_images::extract_and_save_office_images_cmd,
+ set_proxy_env,
])
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
diff --git a/src-tauri/src/proxy.rs b/src-tauri/src/proxy.rs
new file mode 100644
index 00000000..dfe78368
--- /dev/null
+++ b/src-tauri/src/proxy.rs
@@ -0,0 +1,456 @@
+//! Global outbound HTTP proxy plumbing.
+//!
+//! At app launch we read the user-set proxy config out of the same
+//! `app-state.json` the frontend's tauri-plugin-store writes, and
+//! translate it into HTTP_PROXY / HTTPS_PROXY / NO_PROXY environment
+//! variables. reqwest (used by tauri-plugin-http) reads those env
+//! vars on client construction and routes every outbound request
+//! through the configured proxy.
+//!
+//! Reading the on-disk JSON directly (rather than going through a
+//! Rust binding to plugin-store) keeps this module independent of
+//! plugin lifecycle: we only need a stable file path and serde.
+//! Cost is one duplicated key name (`proxyConfig`) — see
+//! src/lib/project-store.ts for the matching write site.
+
+use std::path::Path;
+
+use serde::{Deserialize, Serialize};
+
+const DEFAULT_BYPASS_LIST: &str =
+ "localhost,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,*.local";
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ProxyConfig {
+ #[serde(default)]
+ pub enabled: bool,
+ #[serde(default)]
+ pub url: String,
+ #[serde(default = "default_true", rename = "bypassLocal")]
+ pub bypass_local: bool,
+}
+
+// Hand-written Default impl so its `bypass_local` matches what
+// serde produces for a missing field — `derive(Default)` would
+// give `false`, which would silently disagree with the
+// "missing-key means bypass on" semantics encoded by the serde
+// `default = "default_true"` attribute. No caller invokes
+// `ProxyConfig::default()` today, but pinning the two paths to
+// the same value avoids a footgun if one ever does.
+impl Default for ProxyConfig {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ url: String::new(),
+ bypass_local: true,
+ }
+ }
+}
+
+fn default_true() -> bool {
+ true
+}
+
+/// Read `proxyConfig` out of the project's `app-state.json`. Returns
+/// None if the file doesn't exist, can't be parsed, or has no proxy
+/// section — caller treats those identically to "no proxy".
+pub fn read_proxy_config_from_store(store_path: &Path) -> Option<ProxyConfig> {
+ let content = std::fs::read_to_string(store_path).ok()?;
+ let json: serde_json::Value = serde_json::from_str(&content).ok()?;
+ let proxy = json.get("proxyConfig")?;
+ serde_json::from_value(proxy.clone()).ok()
+}
+
+/// Apply a proxy config by setting the env vars reqwest reads.
+/// Returns a short human-readable summary for logging.
+///
+/// Validates the URL scheme — only `http://` and `https://` are
+/// accepted in this version. Anything else (SOCKS5, malformed,
+/// missing scheme) is treated as "disabled" so the user doesn't
+/// silently trip over a half-working proxy.
+///
+/// Concurrency note: `std::env::set_var` mutates process-wide
+/// state and is racy if any other thread reads env at the same
+/// instant. Two callers exist: (1) the Tauri setup hook, which
+/// runs before any HTTP client thread starts (safe), and (2)
+/// the `set_proxy_env` IPC command, which can race with an
+/// in-flight `reqwest::Client::new()` reading HTTP_PROXY. The
+/// race window is microseconds and the worst case is one fetch
+/// reading the previous value — acceptable for a user-initiated
+/// toggle, and matches what every other "global proxy switch"
+/// in similar apps does. Documented here so a future Rust
+/// edition that hard-fails on this pattern doesn't surprise us.
+pub fn apply_proxy_env(config: &ProxyConfig) -> String {
+ // Every "disabled" path MUST clear all three env vars, not just
+ // return — otherwise toggling the proxy off after it was on
+ // leaves the previous values in place and reqwest keeps routing
+ // through the now-removed proxy. The same applies to invalid
+ // URLs and unsupported schemes (treat as disabled).
+ let url = config.url.trim();
+ let invalid_scheme =
+ !url.starts_with("http://") && !url.starts_with("https://");
+
+ if !config.enabled || url.is_empty() || invalid_scheme {
+ clear_proxy_env();
+ return if !config.enabled {
+ "disabled".to_string()
+ } else if url.is_empty() {
+ "disabled (empty url)".to_string()
+ } else {
+ // Mask before logging — an invalid URL might still
+ // contain a password the user mis-typed.
+ format!("disabled (unsupported scheme: {})", redact_url(url))
+ };
+ }
+
+ std::env::set_var("HTTP_PROXY", url);
+ std::env::set_var("HTTPS_PROXY", url);
+ if config.bypass_local {
+ std::env::set_var("NO_PROXY", DEFAULT_BYPASS_LIST);
+ } else {
+ // Bypass off — clear NO_PROXY so a previously-set value
+ // doesn't leak through.
+ std::env::remove_var("NO_PROXY");
+ }
+ format!(
+ "enabled ({}, bypass_local={})",
+ redact_url(url),
+ config.bypass_local
+ )
+}
+
+/// Strip embedded basic-auth credentials from a URL before logging.
+/// `http://user:pass@host:port` → `http://***@host:port`. URLs
+/// without credentials pass through untouched. Used so stderr /
+/// Console.app / journalctl output doesn't persist proxy
+/// passwords.
+fn redact_url(url: &str) -> String {
+ // Find `scheme://` then check for `user[:pass]@` between that
+ // and the next `/` (or end). If found, replace with `***@`.
+ let scheme_end = match url.find("://") {
+ Some(i) => i + 3,
+ None => return url.to_string(),
+ };
+ let after_scheme = &url[scheme_end..];
+ // The userinfo segment, if present, is up to the first '@'
+ // that comes BEFORE the first '/'. A '@' after a '/' is part
+ // of the path and must not be matched.
+ let path_start = after_scheme.find('/').unwrap_or(after_scheme.len());
+ let userinfo_end = match after_scheme[..path_start].find('@') {
+ Some(i) => i,
+ None => return url.to_string(), // no credentials embedded
+ };
+ let mut out = String::with_capacity(url.len());
+ out.push_str(&url[..scheme_end]);
+ out.push_str("***");
+ out.push_str(&after_scheme[userinfo_end..]);
+ out
+}
+
+/// Remove all three proxy env vars. Called whenever the user
+/// disables the proxy or supplies an invalid URL — this is what
+/// makes "turn off proxy" actually take effect for the next fetch
+/// (without it, the previous HTTP_PROXY / HTTPS_PROXY / NO_PROXY
+/// stay set in the process env and reqwest keeps using them).
+fn clear_proxy_env() {
+ std::env::remove_var("HTTP_PROXY");
+ std::env::remove_var("HTTPS_PROXY");
+ std::env::remove_var("NO_PROXY");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Cargo runs tests in parallel by default and these tests all
+ /// touch the same process-wide env vars. Without serializing
+ /// them, one test's set_var leaks into another test's
+ /// assertion. A single mutex shared across the test module
+ /// forces them to run one at a time without bringing in a
+ /// `serial_test` dependency.
+ static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+ /// Run a closure with the proxy-related env vars cleared (and
+ /// serialized via ENV_MUTEX), then restore whatever was there
+ /// before — keeps tests from contaminating each other or the
+ /// host shell.
+ fn isolated<F: FnOnce()>(f: F) {
+ // Recover from poison — a panic in one test leaves the
+ // mutex poisoned, but we have no shared state inside it
+ // so resuming with the inner () is safe.
+ let _guard = ENV_MUTEX.lock().unwrap_or_else(|p| p.into_inner());
+ let snap = (
+ std::env::var("HTTP_PROXY").ok(),
+ std::env::var("HTTPS_PROXY").ok(),
+ std::env::var("NO_PROXY").ok(),
+ );
+ std::env::remove_var("HTTP_PROXY");
+ std::env::remove_var("HTTPS_PROXY");
+ std::env::remove_var("NO_PROXY");
+
+ f();
+
+ match snap.0 {
+ Some(v) => std::env::set_var("HTTP_PROXY", v),
+ None => std::env::remove_var("HTTP_PROXY"),
+ }
+ match snap.1 {
+ Some(v) => std::env::set_var("HTTPS_PROXY", v),
+ None => std::env::remove_var("HTTPS_PROXY"),
+ }
+ match snap.2 {
+ Some(v) => std::env::set_var("NO_PROXY", v),
+ None => std::env::remove_var("NO_PROXY"),
+ }
+ }
+
+ #[test]
+ fn disabled_sets_no_env() {
+ isolated(|| {
+ let s = apply_proxy_env(&ProxyConfig {
+ enabled: false,
+ url: "http://x:1".into(),
+ bypass_local: true,
+ });
+ assert!(s.contains("disabled"));
+ assert!(std::env::var("HTTP_PROXY").is_err());
+ assert!(std::env::var("HTTPS_PROXY").is_err());
+ });
+ }
+
+ #[test]
+ fn enabled_sets_both_proxy_envs() {
+ isolated(|| {
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "http://127.0.0.1:7890".into(),
+ bypass_local: true,
+ });
+ assert_eq!(
+ std::env::var("HTTP_PROXY").unwrap(),
+ "http://127.0.0.1:7890"
+ );
+ assert_eq!(
+ std::env::var("HTTPS_PROXY").unwrap(),
+ "http://127.0.0.1:7890"
+ );
+ let no_proxy = std::env::var("NO_PROXY").unwrap();
+ assert!(no_proxy.contains("localhost"));
+ assert!(no_proxy.contains("127.0.0.0/8"));
+ assert!(no_proxy.contains("192.168.0.0/16"));
+ });
+ }
+
+ #[test]
+ fn bypass_local_off_clears_no_proxy() {
+ isolated(|| {
+ std::env::set_var("NO_PROXY", "stale-value");
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "http://x:1".into(),
+ bypass_local: false,
+ });
+ // The stale value must be cleared so the user's intent
+ // (everything goes through the proxy) is honored.
+ assert!(std::env::var("NO_PROXY").is_err());
+ });
+ }
+
+ #[test]
+ fn rejects_unsupported_schemes() {
+ isolated(|| {
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "socks5://x:1".into(),
+ bypass_local: true,
+ });
+ assert!(std::env::var("HTTP_PROXY").is_err());
+ });
+ }
+
+ #[test]
+ fn rejects_empty_url() {
+ isolated(|| {
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: " ".into(),
+ bypass_local: true,
+ });
+ assert!(std::env::var("HTTP_PROXY").is_err());
+ });
+ }
+
+ #[test]
+ fn disable_after_enable_clears_previously_set_env_vars() {
+ // Regression: if the user enabled the proxy, then disables
+ // it, the next request must NOT keep going through the
+ // (now-removed) proxy. apply_proxy_env's "disabled" path
+ // must actively unset HTTP_PROXY / HTTPS_PROXY / NO_PROXY,
+ // not just return without writing.
+ isolated(|| {
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "http://127.0.0.1:7890".into(),
+ bypass_local: true,
+ });
+ assert_eq!(
+ std::env::var("HTTP_PROXY").unwrap(),
+ "http://127.0.0.1:7890",
+ );
+
+ apply_proxy_env(&ProxyConfig {
+ enabled: false,
+ url: "http://127.0.0.1:7890".into(),
+ bypass_local: true,
+ });
+ assert!(std::env::var("HTTP_PROXY").is_err());
+ assert!(std::env::var("HTTPS_PROXY").is_err());
+ assert!(std::env::var("NO_PROXY").is_err());
+ });
+ }
+
+ #[test]
+ fn unsupported_scheme_after_enable_clears_env() {
+ // Same regression class for invalid-URL changes — switching
+ // the URL to something we won't apply (socks5://) must clear
+ // any previously-applied http(s) values, not silently keep
+ // them.
+ isolated(|| {
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "http://127.0.0.1:7890".into(),
+ bypass_local: true,
+ });
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "socks5://x:1".into(),
+ bypass_local: true,
+ });
+ assert!(std::env::var("HTTP_PROXY").is_err());
+ });
+ }
+
+ #[test]
+ fn https_proxy_url_is_supported() {
+ isolated(|| {
+ apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "https://proxy.corp:443".into(),
+ bypass_local: false,
+ });
+ assert_eq!(
+ std::env::var("HTTPS_PROXY").unwrap(),
+ "https://proxy.corp:443"
+ );
+ });
+ }
+
+ #[test]
+ fn redacts_basic_auth_credentials_in_url() {
+ assert_eq!(
+ redact_url("http://user:[email protected]:8080"),
+ "http://***@proxy.corp:8080",
+ );
+ // URL with path after host: '@' in path must not be matched
+ assert_eq!(
+ redact_url("http://user:[email protected]:8080/some@path"),
+ "http://***@proxy.corp:8080/some@path",
+ );
+ // Username only (no password)
+ assert_eq!(
+ redact_url("http://[email protected]:8080"),
+ "http://***@proxy.corp:8080",
+ );
+ // No credentials — pass through
+ assert_eq!(
+ redact_url("http://proxy.corp:8080"),
+ "http://proxy.corp:8080",
+ );
+ // No scheme at all (defensive — invalid URL shouldn't crash)
+ assert_eq!(redact_url("garbage"), "garbage");
+ }
+
+ #[test]
+ fn apply_proxy_env_summary_does_not_leak_password() {
+ isolated(|| {
+ let summary = apply_proxy_env(&ProxyConfig {
+ enabled: true,
+ url: "http://secretuser:[email protected]:8080".into(),
+ bypass_local: true,
+ });
+ assert!(!summary.contains("secretpass"));
+ assert!(!summary.contains("secretuser"));
+ assert!(summary.contains("***"));
+ assert!(summary.contains("proxy.corp:8080"));
+ });
+ }
+
+ #[test]
+ fn default_trait_matches_serde_missing_field_semantics() {
+ // Regression: derive(Default) makes bypass_local = false, but
+ // serde with `default = "default_true"` makes a missing field
+ // = true. The two must agree so a ProxyConfig::default() and
+ // a serde-deserialized empty `{}` produce identical values.
+ let default_via_trait = ProxyConfig::default();
+ let default_via_serde: ProxyConfig = serde_json::from_str("{}").unwrap();
+ assert_eq!(default_via_trait.enabled, default_via_serde.enabled);
+ assert_eq!(default_via_trait.url, default_via_serde.url);
+ assert_eq!(
+ default_via_trait.bypass_local, default_via_serde.bypass_local,
+ "Default trait and serde-default must agree on bypass_local",
+ );
+ // And both should be the safe default: bypass on, proxy off.
+ assert!(!default_via_trait.enabled);
+ assert!(default_via_trait.bypass_local);
+ }
+
+ #[test]
+ fn parses_camelcase_bypassLocal_field() {
+ // Frontend writes `bypassLocal` (camelCase). We must accept
+ // that exact spelling — verify the serde rename works.
+ let json = r#"{"enabled": true, "url": "http://x:1", "bypassLocal": false}"#;
+ let cfg: ProxyConfig = serde_json::from_str(json).unwrap();
+ assert!(cfg.enabled);
+ assert_eq!(cfg.url, "http://x:1");
+ assert!(!cfg.bypass_local);
+ }
+
+ #[test]
+ fn missing_proxyConfig_returns_none() {
+ let dir = tempdir_for_test();
+ let path = dir.join("missing.json");
+ assert!(read_proxy_config_from_store(&path).is_none());
+ }
+
+ #[test]
+ fn parses_proxy_config_from_store_file() {
+ let dir = tempdir_for_test();
+ let path = dir.join("app-state.json");
+ std::fs::write(
+ &path,
+ r#"{"proxyConfig": {"enabled": true, "url": "http://x:1", "bypassLocal": true}}"#,
+ )
+ .unwrap();
+ let cfg = read_proxy_config_from_store(&path).unwrap();
+ assert!(cfg.enabled);
+ assert_eq!(cfg.url, "http://x:1");
+ }
+
+ #[test]
+ fn ignores_store_file_with_no_proxy_section() {
+ let dir = tempdir_for_test();
+ let path = dir.join("app-state.json");
+ std::fs::write(&path, r#"{"otherKey": "value"}"#).unwrap();
+ assert!(read_proxy_config_from_store(&path).is_none());
+ }
+
+ fn tempdir_for_test() -> std::path::PathBuf {
+ let stamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let dir = std::env::temp_dir().join(format!("llm-wiki-proxy-test-{stamp}"));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+}
diff --git a/src/App.tsx b/src/App.tsx
index 0339a7e8..eb86f332 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,7 +5,7 @@ import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
import { useChatStore } from "@/stores/chat-store"
import { listDirectory, openProject } from "@/commands/fs"
-import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId } from "@/lib/project-store"
+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId, loadProxyConfig } from "@/lib/project-store"
import { loadReviewItems, loadChatHistory } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
@@ -222,6 +222,10 @@ function App() {
if (savedOutputLang) {
useWikiStore.getState().setOutputLanguage(savedOutputLang)
}
+ const savedProxy = await loadProxyConfig()
+ if (savedProxy) {
+ useWikiStore.getState().setProxyConfig(savedProxy)
+ }
const savedLang = await loadLanguage()
if (savedLang) {
await i18n.changeLanguage(savedLang)
diff --git a/src/components/settings/sections/network-section.tsx b/src/components/settings/sections/network-section.tsx
new file mode 100644
index 00000000..7121e785
--- /dev/null
+++ b/src/components/settings/sections/network-section.tsx
@@ -0,0 +1,102 @@
+import { useTranslation } from "react-i18next"
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import { AlertTriangle } from "lucide-react"
+import { validateProxyUrl } from "@/lib/proxy-config"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+export function NetworkSection({ draft, setDraft }: Props) {
+ const { t } = useTranslation()
+
+ // Live URL validation — only flag the user when they've actually
+ // typed something. Empty + enabled is "form not yet finished",
+ // not a hard error.
+ const trimmed = draft.proxyUrl.trim()
+ const validation = trimmed === "" ? null : validateProxyUrl(trimmed)
+ const showError = draft.proxyEnabled && validation && !validation.ok
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">
+ {t("settings.sections.network.title", { defaultValue: "Network" })}
+ </h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t("settings.sections.network.description", {
+ defaultValue:
+ "Route all outbound HTTP requests (LLM, embedding, search, update check) through a proxy. Changes apply on Save — no restart needed.",
+ })}
+ </p>
+ </div>
+
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={draft.proxyEnabled}
+ onChange={(e) => setDraft("proxyEnabled", e.target.checked)}
+ className="h-4 w-4"
+ />
+ <span className="text-sm">
+ {t("settings.sections.network.enable", {
+ defaultValue: "Enable proxy",
+ })}
+ </span>
+ </label>
+
+ <div className="space-y-2">
+ <Label htmlFor="proxy-url">
+ {t("settings.sections.network.url", { defaultValue: "Proxy URL" })}
+ </Label>
+ <Input
+ id="proxy-url"
+ value={draft.proxyUrl}
+ onChange={(e) => setDraft("proxyUrl", e.target.value)}
+ placeholder="http://127.0.0.1:7890"
+ disabled={!draft.proxyEnabled}
+ className={showError ? "border-destructive" : ""}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.network.urlHelp", {
+ defaultValue:
+ "Full URL with scheme. Supported: http://, https://. (SOCKS5 not supported in this version.)",
+ })}
+ </p>
+ {showError && validation && !validation.ok && (
+ <p className="flex items-center gap-1 text-xs text-destructive">
+ <AlertTriangle className="h-3 w-3" />
+ {validation.error}
+ </p>
+ )}
+ </div>
+
+ <label className="flex items-start gap-2">
+ <input
+ type="checkbox"
+ checked={draft.proxyBypassLocal}
+ onChange={(e) => setDraft("proxyBypassLocal", e.target.checked)}
+ disabled={!draft.proxyEnabled}
+ className="mt-0.5 h-4 w-4"
+ />
+ <div className="space-y-1">
+ <span className="text-sm">
+ {t("settings.sections.network.bypassLocal", {
+ defaultValue: "Bypass proxy for local addresses (recommended)",
+ })}
+ </span>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.network.bypassLocalHelp", {
+ defaultValue:
+ "Requests to localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and *.local don't go through the proxy. Keep this on if you use Ollama / LM Studio / other local or LAN-deployed LLMs.",
+ })}
+ </p>
+ </div>
+ </label>
+
+ </div>
+ )
+}
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
index 951f3b26..aae8b94d 100644
--- a/src/components/settings/settings-types.ts
+++ b/src/components/settings/settings-types.ts
@@ -45,6 +45,13 @@ export interface SettingsDraft {
outputLanguage: string
maxHistoryMessages: number
+ // Network — global outbound HTTP proxy. Persisted to app-state.json
+ // and read by the Rust setup hook on app launch (changes apply
+ // after restart). See src/lib/proxy-config.ts.
+ proxyEnabled: boolean
+ proxyUrl: string
+ proxyBypassLocal: boolean
+
// UI
uiLanguage: string
}
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index a4e0271c..2878d208 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -7,8 +7,10 @@ import {
Palette,
Info,
Image as ImageIcon,
+ Network,
} from "lucide-react"
import { useTranslation } from "react-i18next"
+import { invoke } from "@tauri-apps/api/core"
import i18n from "@/i18n"
import { Button } from "@/components/ui/button"
import { useWikiStore } from "@/stores/wiki-store"
@@ -22,6 +24,7 @@ import { MultimodalSection } from "./sections/multimodal-section"
import { WebSearchSection } from "./sections/web-search-section"
import { OutputSection } from "./sections/output-section"
import { InterfaceSection } from "./sections/interface-section"
+import { NetworkSection } from "./sections/network-section"
import { AboutSection } from "./sections/about-section"
type CategoryId =
@@ -29,6 +32,7 @@ type CategoryId =
| "embedding"
| "multimodal"
| "web-search"
+ | "network"
| "output"
| "interface"
| "about"
@@ -47,6 +51,7 @@ const CATEGORIES: Category[] = [
{ id: "embedding", labelKey: "settings.categories.embedding", icon: Binary },
{ id: "multimodal", labelKey: "settings.categories.multimodal", icon: ImageIcon },
{ id: "web-search", labelKey: "settings.categories.webSearch", icon: Globe },
+ { id: "network", labelKey: "settings.categories.network", icon: Network },
{ id: "output", labelKey: "settings.categories.output", icon: Languages },
{ id: "interface", labelKey: "settings.categories.interface", icon: Palette },
{ id: "about", labelKey: "settings.categories.about", icon: Info },
@@ -58,6 +63,7 @@ function initialDraft(
embed: ReturnType<typeof useWikiStore.getState>["embeddingConfig"],
multimodal: ReturnType<typeof useWikiStore.getState>["multimodalConfig"],
outputLanguage: ReturnType<typeof useWikiStore.getState>["outputLanguage"],
+ proxy: ReturnType<typeof useWikiStore.getState>["proxyConfig"],
maxHistoryMessages: number,
uiLanguage: string,
): SettingsDraft {
@@ -88,6 +94,9 @@ function initialDraft(
searchApiKey: search.apiKey,
outputLanguage,
maxHistoryMessages,
+ proxyEnabled: proxy.enabled,
+ proxyUrl: proxy.url,
+ proxyBypassLocal: proxy.bypassLocal,
uiLanguage,
}
}
@@ -104,6 +113,8 @@ export function SettingsView() {
const setMultimodalConfig = useWikiStore((s) => s.setMultimodalConfig)
const outputLanguage = useWikiStore((s) => s.outputLanguage)
const setOutputLanguage = useWikiStore((s) => s.setOutputLanguage)
+ const proxyConfig = useWikiStore((s) => s.proxyConfig)
+ const setProxyConfig = useWikiStore((s) => s.setProxyConfig)
const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)
const setMaxHistoryMessages = useChatStore((s) => s.setMaxHistoryMessages)
// Drives the red dot next to the "About" row in the settings
@@ -125,6 +136,7 @@ export function SettingsView() {
embeddingConfig,
multimodalConfig,
outputLanguage,
+ proxyConfig,
maxHistoryMessages,
i18n.language,
),
@@ -139,6 +151,7 @@ export function SettingsView() {
embeddingConfig,
multimodalConfig,
outputLanguage,
+ proxyConfig,
maxHistoryMessages,
i18n.language,
),
@@ -149,6 +162,7 @@ export function SettingsView() {
embeddingConfig,
multimodalConfig,
outputLanguage,
+ proxyConfig,
maxHistoryMessages,
])
@@ -163,6 +177,7 @@ export function SettingsView() {
saveEmbeddingConfig,
saveMultimodalConfig,
saveOutputLanguage,
+ saveProxyConfig,
} = await import("@/lib/project-store")
const newLlm = {
@@ -201,6 +216,12 @@ export function SettingsView() {
concurrency: Math.max(1, Math.min(16, draft.multimodalConcurrency || 4)),
}
+ const newProxy = {
+ enabled: draft.proxyEnabled,
+ url: draft.proxyUrl.trim(),
+ bypassLocal: draft.proxyBypassLocal,
+ }
+
setLlmConfig(newLlm)
await saveLlmConfig(newLlm)
setSearchApiConfig(newSearch)
@@ -211,6 +232,17 @@ export function SettingsView() {
await saveMultimodalConfig(newMultimodal)
setOutputLanguage(draft.outputLanguage as typeof outputLanguage)
await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage)
+ setProxyConfig(newProxy)
+ await saveProxyConfig(newProxy)
+ // Apply the proxy env vars LIVE so the next outbound request
+ // picks them up — no app restart needed. tauri-plugin-http
+ // builds a fresh reqwest client per fetch and reqwest reads
+ // env vars at build time, so changing them here is enough.
+ try {
+ await invoke<string>("set_proxy_env", { config: newProxy })
+ } catch (err) {
+ console.warn("[proxy] live update failed; restart will still apply:", err)
+ }
setMaxHistoryMessages(draft.maxHistoryMessages)
if (draft.uiLanguage !== i18n.language) {
@@ -226,6 +258,7 @@ export function SettingsView() {
setSearchApiConfig,
setEmbeddingConfig,
setOutputLanguage,
+ setProxyConfig,
setMaxHistoryMessages,
outputLanguage,
])
@@ -243,6 +276,8 @@ export function SettingsView() {
return <MultimodalSection draft={draft} setDraft={setDraft} />
case "web-search":
return <WebSearchSection draft={draft} setDraft={setDraft} />
+ case "network":
+ return <NetworkSection draft={draft} setDraft={setDraft} />
case "output":
return <OutputSection draft={draft} setDraft={setDraft} />
case "interface":
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 4febb40e..2bd82b40 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -107,6 +107,7 @@
"embedding": "Embeddings",
"multimodal": "Image Captioning",
"webSearch": "Web Search",
+ "network": "Network",
"output": "Output",
"interface": "Interface",
"about": "About"
@@ -184,6 +185,15 @@
"title": "Web Search",
"description": "Used by Deep Research to pull fresh external context."
},
+ "network": {
+ "title": "Network",
+ "description": "Route all outbound HTTP requests (LLM, embedding, search, update check) through a proxy. Changes apply on Save — no restart needed.",
+ "enable": "Enable proxy",
+ "url": "Proxy URL",
+ "urlHelp": "Full URL with scheme. Supported: http://, https://. (SOCKS5 not supported in this version.)",
+ "bypassLocal": "Bypass proxy for local addresses (recommended)",
+ "bypassLocalHelp": "Requests to localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and *.local don't go through the proxy. Keep this on if you use Ollama / LM Studio / other local or LAN-deployed LLMs."
+ },
"output": {
"title": "Output Preferences",
"description": "Controls for generated content — language, conversation history length.",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 2db739c4..39378c7e 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -107,6 +107,7 @@
"embedding": "向量嵌入",
"multimodal": "图片描述",
"webSearch": "网页搜索",
+ "network": "网络",
"output": "输出偏好",
"interface": "界面",
"about": "关于"
@@ -184,6 +185,15 @@
"title": "网页搜索",
"description": "Deep Research 会用它拉取最新的外部上下文。"
},
+ "network": {
+ "title": "网络",
+ "description": "让所有外部 HTTP 请求(LLM、向量、搜索、更新检查)走代理。点击保存即时生效,不需要重启应用。",
+ "enable": "启用代理",
+ "url": "代理地址",
+ "urlHelp": "完整 URL,必须带协议头。支持:http://、https://(当前版本不支持 SOCKS5)。",
+ "bypassLocal": "本地地址不走代理(推荐)",
+ "bypassLocalHelp": "对 localhost、127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16 以及 *.local 的请求会绕过代理。如果你用 Ollama / LM Studio 或局域网内的 LLM 服务,请保持开启。"
+ },
"output": {
"title": "输出偏好",
"description": "影响生成内容的语言、对话历史长度等参数。",
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index b6aca953..278d2dae 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -1,6 +1,6 @@
import { load } from "@tauri-apps/plugin-store"
import type { WikiProject } from "@/types/wiki"
-import type { LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProviderConfigs } from "@/stores/wiki-store"
+import type { LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProviderConfigs, ProxyConfig } from "@/stores/wiki-store"
const STORE_NAME = "app-state.json"
const RECENT_PROJECTS_KEY = "recentProjects"
@@ -108,6 +108,31 @@ export async function loadMultimodalConfig(): Promise<MultimodalConfig | null> {
return (await store.get<MultimodalConfig>(MULTIMODAL_KEY)) ?? null
}
+// IMPORTANT: Keep this key in sync with the Rust setup hook
+// (src-tauri/src/proxy.rs), which reads this exact field name from
+// the same `app-state.json` store at app launch to translate the
+// config into HTTP_PROXY / HTTPS_PROXY / NO_PROXY env vars.
+const PROXY_CONFIG_KEY = "proxyConfig"
+
+export async function saveProxyConfig(config: ProxyConfig): Promise<void> {
+ const store = await getStore()
+ await store.set(PROXY_CONFIG_KEY, config)
+ // Force-flush to disk. The store is opened with `autoSave: true`,
+ // which is a 100ms debounce — not an immediate write. For most
+ // settings that's fine, but the proxy config is on the startup
+ // critical path: the Rust setup hook reads `app-state.json` on
+ // launch to apply HTTP_PROXY / HTTPS_PROXY / NO_PROXY. If the
+ // user saves and quits within the debounce window the disk
+ // value would lag behind in-memory, and the next launch would
+ // boot with the wrong proxy.
+ await store.save()
+}
+
+export async function loadProxyConfig(): Promise<ProxyConfig | null> {
+ const store = await getStore()
+ return (await store.get<ProxyConfig>(PROXY_CONFIG_KEY)) ?? null
+}
+
export async function removeFromRecentProjects(
path: string
): Promise<void> {
diff --git a/src/lib/proxy-config.test.ts b/src/lib/proxy-config.test.ts
new file mode 100644
index 00000000..403df4eb
--- /dev/null
+++ b/src/lib/proxy-config.test.ts
@@ -0,0 +1,104 @@
+import { describe, it, expect } from "vitest"
+import {
+ validateProxyUrl,
+ buildNoProxyValue,
+ isProxyActive,
+ DEFAULT_BYPASS_LIST,
+ type ProxyConfig,
+} from "./proxy-config"
+
+describe("validateProxyUrl", () => {
+ it("accepts http:// URLs", () => {
+ expect(validateProxyUrl("http://127.0.0.1:7890")).toEqual({ ok: true })
+ expect(validateProxyUrl("http://proxy.corp.local:8080")).toEqual({ ok: true })
+ })
+
+ it("accepts https:// URLs", () => {
+ expect(validateProxyUrl("https://proxy.corp:443")).toEqual({ ok: true })
+ })
+
+ it("accepts URLs with embedded auth", () => {
+ expect(validateProxyUrl("http://user:[email protected]:7890")).toEqual({ ok: true })
+ })
+
+ it("rejects URLs with no scheme", () => {
+ // URL parser behaves differently across Node versions ("127.0.0.1:7890"
+ // throws on some, parses to protocol="127.0.0.1:" on others). Either
+ // way the URL must be REJECTED — the exact error message isn't part
+ // of the contract.
+ expect(validateProxyUrl("127.0.0.1:7890").ok).toBe(false)
+ expect(validateProxyUrl("proxy.example.com:8080").ok).toBe(false)
+ })
+
+ it("rejects unsupported schemes (v1: HTTP/HTTPS only)", () => {
+ expect(validateProxyUrl("socks5://127.0.0.1:1080")).toMatchObject({
+ ok: false,
+ })
+ expect(validateProxyUrl("ftp://x")).toMatchObject({ ok: false })
+ })
+
+ it("rejects empty / whitespace input", () => {
+ expect(validateProxyUrl("")).toMatchObject({ ok: false })
+ expect(validateProxyUrl(" ")).toMatchObject({ ok: false })
+ })
+
+ it("rejects malformed URLs", () => {
+ expect(validateProxyUrl("http://").ok).toBe(false)
+ expect(validateProxyUrl("not-a-url").ok).toBe(false)
+ expect(validateProxyUrl("http:").ok).toBe(false)
+ })
+
+ it("rejects URLs missing a host", () => {
+ expect(validateProxyUrl("http://:7890")).toMatchObject({ ok: false })
+ })
+})
+
+describe("buildNoProxyValue", () => {
+ it("returns the default bypass list when bypassLocal is true", () => {
+ expect(buildNoProxyValue(true)).toBe(DEFAULT_BYPASS_LIST)
+ })
+
+ it("returns null when bypassLocal is false (no NO_PROXY env var should be set)", () => {
+ expect(buildNoProxyValue(false)).toBeNull()
+ })
+
+ it("default list covers the standard private networks and localhost", () => {
+ const v = buildNoProxyValue(true)!
+ expect(v).toContain("localhost")
+ expect(v).toContain("127.0.0.0/8")
+ expect(v).toContain("10.0.0.0/8")
+ expect(v).toContain("172.16.0.0/12")
+ expect(v).toContain("192.168.0.0/16")
+ expect(v).toContain("*.local")
+ })
+})
+
+describe("isProxyActive", () => {
+ it("is false when disabled", () => {
+ const cfg: ProxyConfig = { enabled: false, url: "http://x:1", bypassLocal: true }
+ expect(isProxyActive(cfg)).toBe(false)
+ })
+
+ it("is false when enabled but URL is empty / whitespace", () => {
+ expect(isProxyActive({ enabled: true, url: "", bypassLocal: true })).toBe(false)
+ expect(isProxyActive({ enabled: true, url: " ", bypassLocal: true })).toBe(false)
+ })
+
+ it("is false when enabled and URL is malformed", () => {
+ expect(
+ isProxyActive({ enabled: true, url: "not-a-url", bypassLocal: true }),
+ ).toBe(false)
+ expect(
+ isProxyActive({ enabled: true, url: "ftp://x:1", bypassLocal: true }),
+ ).toBe(false)
+ })
+
+ it("is true when enabled with a valid http(s) URL", () => {
+ expect(
+ isProxyActive({ enabled: true, url: "http://127.0.0.1:7890", bypassLocal: true }),
+ ).toBe(true)
+ expect(
+ isProxyActive({ enabled: true, url: "https://proxy.corp:443", bypassLocal: false }),
+ ).toBe(true)
+ })
+})
diff --git a/src/lib/proxy-config.ts b/src/lib/proxy-config.ts
new file mode 100644
index 00000000..abebb2b1
--- /dev/null
+++ b/src/lib/proxy-config.ts
@@ -0,0 +1,104 @@
+/**
+ * Global HTTP/HTTPS proxy configuration.
+ *
+ * Persisted to the same `app-state.json` store as other settings.
+ * The Rust setup hook (src-tauri/src/proxy.rs) reads this on app
+ * launch and translates it into HTTP_PROXY / HTTPS_PROXY / NO_PROXY
+ * environment variables — reqwest (used by tauri-plugin-http) picks
+ * those up automatically and routes every outbound HTTP request
+ * through the configured proxy.
+ *
+ * Changes apply on app restart; the UI surfaces a "Restart now"
+ * button so users don't have to do it manually.
+ *
+ * v1 supports HTTP and HTTPS proxies only. SOCKS5 needs a reqwest
+ * cargo feature flag and is deferred.
+ */
+
+export interface ProxyConfig {
+ enabled: boolean
+ /**
+ * Full proxy URL with scheme, e.g. `http://127.0.0.1:7890`.
+ * Embedded basic auth (`http://user:pass@host:port`) is fine —
+ * stored verbatim alongside other API keys (no separate secret
+ * store).
+ */
+ url: string
+ /**
+ * When true, requests to localhost / 127.x / private RFC1918
+ * networks / *.local hostnames bypass the proxy. Recommended
+ * default — without it, Ollama / LM Studio / LAN-deployed LLMs
+ * get sent to the external proxy and fail.
+ */
+ bypassLocal: boolean
+}
+
+export const DEFAULT_PROXY_CONFIG: ProxyConfig = {
+ enabled: false,
+ url: "",
+ bypassLocal: true,
+}
+
+/**
+ * The list applied to NO_PROXY when bypassLocal is on. reqwest's
+ * NO_PROXY parser accepts comma-separated hostnames, IP literals,
+ * CIDR blocks, and `*.suffix` wildcards.
+ *
+ * Covers: loopback, all RFC1918 private blocks, RFC6762 multicast
+ * DNS suffix. Not user-editable in v1 — toggle bypassLocal on/off
+ * is the whole UI.
+ */
+export const DEFAULT_BYPASS_LIST =
+ "localhost,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,*.local"
+
+const SUPPORTED_SCHEMES = ["http:", "https:"] as const
+
+export type ValidateResult = { ok: true } | { ok: false; error: string }
+
+export function validateProxyUrl(url: string): ValidateResult {
+ const trimmed = url.trim()
+ if (trimmed === "") return { ok: false, error: "URL is empty" }
+
+ let parsed: URL
+ try {
+ parsed = new URL(trimmed)
+ } catch {
+ return { ok: false, error: "Not a valid URL" }
+ }
+
+ if (!parsed.protocol) {
+ return { ok: false, error: "URL is missing a scheme (http:// or https://)" }
+ }
+ if (!SUPPORTED_SCHEMES.includes(parsed.protocol as (typeof SUPPORTED_SCHEMES)[number])) {
+ return {
+ ok: false,
+ error: `Unsupported scheme "${parsed.protocol}". Use http:// or https://`,
+ }
+ }
+ if (!parsed.hostname) {
+ return { ok: false, error: "URL is missing a host" }
+ }
+ return { ok: true }
+}
+
+/**
+ * Build the value that should be written to the NO_PROXY env var,
+ * or `null` to indicate NO_PROXY should not be set (everything goes
+ * through the proxy when bypass is off).
+ */
+export function buildNoProxyValue(bypassLocal: boolean): string | null {
+ return bypassLocal ? DEFAULT_BYPASS_LIST : null
+}
+
+/**
+ * "Should the proxy actually take effect?" Composite check used by
+ * the Rust startup hook and any UI element that needs to surface
+ * the effective proxy state. False if disabled, URL empty, or URL
+ * malformed — these all collapse to "no proxy" rather than half-
+ * applying a broken config.
+ */
+export function isProxyActive(cfg: ProxyConfig): boolean {
+ if (!cfg.enabled) return false
+ if (cfg.url.trim() === "") return false
+ return validateProxyUrl(cfg.url).ok
+}
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index 049bdb94..ff5891cc 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -74,6 +74,19 @@ interface EmbeddingConfig {
* behind a single-GPU server's batch slot, so we cap the slider
* UI at a tasteful max in the settings view.
*/
+/**
+ * Global outbound HTTP proxy. When `enabled` and `url` is a valid
+ * http(s) URL, the Rust setup hook reads this on app launch and
+ * sets HTTP_PROXY / HTTPS_PROXY / NO_PROXY env vars before the
+ * reqwest client used by tauri-plugin-http is constructed. Changes
+ * apply on app restart only.
+ */
+interface ProxyConfig {
+ enabled: boolean
+ url: string
+ bypassLocal: boolean
+}
+
interface MultimodalConfig {
enabled: boolean
/** Reuse `llmConfig` for caption calls. When true, the fields
@@ -163,6 +176,7 @@ interface WikiState {
embeddingConfig: EmbeddingConfig
multimodalConfig: MultimodalConfig
outputLanguage: OutputLanguage
+ proxyConfig: ProxyConfig
dataVersion: number
setProject: (project: WikiProject | null) => void
@@ -179,6 +193,7 @@ interface WikiState {
setEmbeddingConfig: (config: EmbeddingConfig) => void
setMultimodalConfig: (config: MultimodalConfig) => void
setOutputLanguage: (lang: OutputLanguage) => void
+ setProxyConfig: (config: ProxyConfig) => void
bumpDataVersion: () => void
}
@@ -241,6 +256,12 @@ export const useWikiStore = create<WikiState>((set) => ({
outputLanguage: "auto",
+ proxyConfig: {
+ enabled: false,
+ url: "",
+ bypassLocal: true,
+ },
+
setLlmConfig: (llmConfig) => set({ llmConfig }),
setProviderConfigs: (providerConfigs) => set({ providerConfigs }),
setActivePresetId: (activePresetId) => set({ activePresetId }),
@@ -248,7 +269,8 @@ export const useWikiStore = create<WikiState>((set) => ({
setEmbeddingConfig: (embeddingConfig) => set({ embeddingConfig }),
setMultimodalConfig: (multimodalConfig) => set({ multimodalConfig }),
setOutputLanguage: (outputLanguage) => set({ outputLanguage }),
+ setProxyConfig: (proxyConfig) => set({ proxyConfig }),
bumpDataVersion: () => set((state) => ({ dataVersion: state.dataVersion + 1 })),
}))
-export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage }
+export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProxyConfig }