Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-cli): configure the web search provider from /settings and jan config (#9420)
Akarshan Biswasdd7bd4f5f348
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 171298a3a..01218d89b 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -18,7 +18,8 @@ use app_lib::core::cli::{cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,cli_get_thread, cli_list_messages, cli_list_threads, cli_plugin_install, cli_plugin_list,- cli_plugin_remove, cli_plugin_search, ResumeRequest, SessionFlags,+ cli_plugin_remove, cli_plugin_search, cli_web_search_reset, cli_web_search_set,+ cli_web_search_status, ResumeRequest, SessionFlags,};use std::fmt::Write as _;@@ -610,6 +611,22 @@ enum AgentConfigCommands {List,/// Print the config file path (scaffolding a template if absent)Path,+ /// Choose the backend for the web_search/web_fetch tools (no flags: show it)+ WebSearch {+ /// Backend: exa (default, keyless), tavily (needs a key), searxng (needs+ /// --endpoint) or you+ #[arg(long, conflicts_with = "reset")]+ provider: Option<String>,+ /// API key for the backend, kept in the secret store ("" clears it)+ #[arg(long, requires = "provider")]+ api_key: Option<String>,+ /// Instance URL for a self-hosted backend such as SearXNG ("" clears it)+ #[arg(long, value_name = "URL", requires = "provider")]+ endpoint: Option<String>,+ /// Go back to the default backend+ #[arg(long)]+ reset: bool,+ },}// ── Threads subcommands ────────────────────────────────────────────────────@@ -1332,6 +1349,24 @@ fn handle_agent_config(cmd: AgentConfigCommands) -> Result<(), String> {println!("{}", path.display());Ok(())}+ AgentConfigCommands::WebSearch {+ provider,+ api_key,+ endpoint,+ reset,+ } => {+ if reset {+ let path = cli_web_search_reset()?;+ println!("Web search reset to the default backend in {}", path.display());+ } else if let Some(provider) = provider {+ let path = cli_web_search_set(&provider, api_key, endpoint)?;+ println!("Web search now uses '{provider}' ({})", path.display());+ } else {+ let status = cli_web_search_status();+ println!("{}", serde_json::to_string_pretty(&status).unwrap());+ }+ Ok(())+ }}}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 6f2b1e681..c00f346a4 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -244,8 +244,8 @@ async fn execute_text("skill_read" => skill_read(args, ctx),"skill_write" => skill_write(args, ctx),// Native web tools: compiled into the agent core, not an MCP server.- "web_search" => crate::tools::web::web_search(args).await,- "web_fetch" => crate::tools::web::web_fetch(args).await,+ "web_search" => crate::tools::web::web_search(args, ctx.web_search).await,+ "web_fetch" => crate::tools::web::web_fetch(args, ctx.web_search).await,other => format!("ERROR: unknown built-in tool '{other}'"),}}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 77d3fabf9..0fb722773 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -206,6 +206,10 @@ pub struct ToolContext<'a> {/// `None` keeps the pull-only behaviour, which is right for a surface with/// no conversation to deliver into.pub shell_done_sink: Option<ShellDoneSink>,+ /// The backend `web_search`/`web_fetch` use, as the host's settings chose+ /// it. `None` keeps the default: keyless Exa, upgraded by an `EXA_API_KEY`+ /// in the environment.+ pub web_search: Option<&'a tauri_plugin_websearch::provider::WebSearchConfig>,}impl std::fmt::Debug for ToolContext<'_> {@@ -241,6 +245,11 @@ impl std::fmt::Debug for ToolContext<'_> {.field("plan_mode", &self.plan_mode).field("hook_sink", &self.hook_sink.is_some()).field("shell_done_sink", &self.shell_done_sink.is_some())+ // The config can hold an API key, so only the backend id is shown.+ .field(+ "web_search",+ &self.web_search.map(|c| c.provider.as_deref().unwrap_or("default")),+ ).finish()}}@@ -390,9 +399,20 @@ impl<'a> ToolContext<'a> {plan_mode: false,hook_sink: None,shell_done_sink: None,+ web_search: None,}}+ /// Route the web tools to the host's chosen backend. See+ /// [`Self::web_search`].+ pub fn with_web_search(+ mut self,+ config: Option<&'a tauri_plugin_websearch::provider::WebSearchConfig>,+ ) -> Self {+ self.web_search = config;+ self+ }+/// Report finished background shells to `sink`. See/// [`Self::shell_done_sink`].pub fn with_shell_done_sink(mut self, sink: ShellDoneSink) -> Self {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/web.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/web.rsindex 0b5b29bf8..2139ceed1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/web.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/web.rs@@ -9,11 +9,14 @@//! `tauri_plugin_websearch::provider` and are shared with the desktop//! `web_search`/`web_fetch` Tauri commands so there is a single implementation.//! This module owns only the agent tool contract: argument parsing/validation,-//! selecting the keyless-vs-keyed Exa path from the process environment, and-//! rendering normalized results as compact, model-friendly text.+//! picking the backend (the host's [`WebSearchConfig`] when it supplies one,+//! else Exa with an optional key from the process environment), and rendering+//! normalized results as compact, model-friendly text.use serde_json::Value;-use tauri_plugin_websearch::provider::{clamp_count, create_provider, FetchedPage, SearchResult};+use tauri_plugin_websearch::provider::{+ clamp_count, provider_meta, FetchedPage, SearchProvider, SearchResult, WebSearchConfig,+};/// Upper bound on the readable text `web_fetch` returns. Mirrors the plugin's/// internal bound; used here only to phrase the truncation notice.@@ -38,9 +41,21 @@ fn exa_api_key() -> Option<String> {None}+/// The backend for one call. The host's selection wins; an Exa selection with+/// no stored key (and no selection at all) still honours the Exa env vars, so+/// an existing `EXA_API_KEY` setup keeps working after a provider is chosen.+fn backend(config: Option<&WebSearchConfig>) -> Result<Box<dyn SearchProvider>, String> {+ let mut config = config.cloned().unwrap_or_default();+ let is_exa = provider_meta(config.provider.as_deref()).is_some_and(|m| m.id == "exa");+ if is_exa && !config.api_key.as_deref().is_some_and(|k| !k.trim().is_empty()) {+ config.api_key = exa_api_key();+ }+ config.create().map_err(|e| format!("ERROR: {e}"))+}+/// Execute the `web_search` built-in. Returns the tool-result text; errors are/// returned as a `String` starting with "ERROR" to match the other handlers.-pub async fn web_search(args: &Value) -> String {+pub async fn web_search(args: &Value, config: Option<&WebSearchConfig>) -> String {let Some(query) = args.get("query").and_then(|v| v.as_str()).map(str::trim) else {return "ERROR: web_search requires a 'query' string argument.".to_string();};@@ -48,7 +63,7 @@ pub async fn web_search(args: &Value) -> String {return "ERROR: web_search 'query' must not be empty.".to_string();}let count = clamp_count(args.get("count").and_then(|v| v.as_u64()));- let provider = match create_provider(None, exa_api_key(), None) {+ let provider = match backend(config) {Ok(p) => p,Err(e) => return e,};@@ -63,7 +78,7 @@ pub async fn web_search(args: &Value) -> String {/// Execute the `web_fetch` built-in. Returns bounded readable content with its/// source URL/title; errors start with "ERROR".-pub async fn web_fetch(args: &Value) -> String {+pub async fn web_fetch(args: &Value, config: Option<&WebSearchConfig>) -> String {let Some(url) = args.get("url").and_then(|v| v.as_str()).map(str::trim) else {return "ERROR: web_fetch requires a 'url' string argument.".to_string();};@@ -73,7 +88,7 @@ pub async fn web_fetch(args: &Value) -> String {if !(url.starts_with("http://") || url.starts_with("https://")) {return format!("ERROR: web_fetch 'url' must be an http(s) URL, got: {url}");}- let provider = match create_provider(None, exa_api_key(), None) {+ let provider = match backend(config) {Ok(p) => p,Err(e) => return e,};@@ -123,14 +138,33 @@ mod tests {#[tokio::test]async fn web_search_requires_query() {- assert!(web_search(&json!({})).await.starts_with("ERROR"));- assert!(web_search(&json!({"query": " "})).await.starts_with("ERROR"));+ assert!(web_search(&json!({}), None).await.starts_with("ERROR"));+ assert!(web_search(&json!({"query": " "}), None).await.starts_with("ERROR"));}#[tokio::test]async fn web_fetch_validates_url() {- assert!(web_fetch(&json!({})).await.starts_with("ERROR"));- assert!(web_fetch(&json!({"url": "ftp://x"})).await.starts_with("ERROR"));+ assert!(web_fetch(&json!({}), None).await.starts_with("ERROR"));+ assert!(web_fetch(&json!({"url": "ftp://x"}), None).await.starts_with("ERROR"));+ }++ /// A configured backend that cannot be built (a keyed provider with no+ /// key) surfaces as a tool ERROR before any request is made, instead of+ /// silently falling back to Exa.+ #[tokio::test]+ async fn configured_provider_is_used_and_validated() {+ let tavily = WebSearchConfig {+ provider: Some("tavily".into()),+ ..Default::default()+ };+ let out = web_search(&json!({"query": "q"}), Some(&tavily)).await;+ assert!(out.starts_with("ERROR") && out.contains("Tavily"), "got: {out}");+ let searx = WebSearchConfig {+ provider: Some("searxng".into()),+ ..Default::default()+ };+ let out = web_fetch(&json!({"url": "https://x.example"}), Some(&searx)).await;+ assert!(out.starts_with("ERROR") && out.contains("SearXNG"), "got: {out}");}#[test]@@ -165,7 +199,7 @@ mod tests {#[tokio::test]#[ignore]async fn web_search_live_keyless() {- let out = web_search(&json!({ "query": "capital of France", "count": 2 })).await;+ let out = web_search(&json!({ "query": "capital of France", "count": 2 }), None).await;assert!(!out.starts_with("ERROR"), "unexpected error: {out}");assert!(out.to_lowercase().contains("paris"), "got: {out}");}diff --git a/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs b/src-tauri/plugins/tauri-plugin-websearch/src/provider.rsindex 6e0adc6b3..a2093d11e 100644--- a/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs+++ b/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs@@ -75,6 +75,95 @@ pub trait SearchProvider: Send + Sync {async fn fetch(&self, url: &str) -> Result<FetchedPage, String>;}+/// Static description of one selectable backend: what settings surfaces need to+/// render its form (does it need a key, an instance URL) and where its API key+/// lives in the secret store. The desktop's `WEB_SEARCH_PROVIDERS` uses the+/// same ids and secret keys, so a key saved on one surface is found by the other.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct ProviderMeta {+ /// Id accepted by [`create_provider`].+ pub id: &'static str,+ pub label: &'static str,+ /// Works with no API key (a key only upgrades it).+ pub keyless: bool,+ /// Secret-store record holding the API key; `None` for key-less backends.+ pub secret_key: Option<&'static str>,+ /// Needs a user-supplied instance URL (`endpoint`).+ pub requires_endpoint: bool,+}++/// Every backend [`create_provider`] accepts, default first.+pub const PROVIDERS: &[ProviderMeta] = &[+ ProviderMeta {+ id: "exa",+ label: "Exa",+ keyless: true,+ secret_key: Some("exa-api-key"),+ requires_endpoint: false,+ },+ ProviderMeta {+ id: "tavily",+ label: "Tavily",+ keyless: false,+ secret_key: Some("tavily-api-key"),+ requires_endpoint: false,+ },+ ProviderMeta {+ id: "searxng",+ label: "SearXNG",+ keyless: true,+ secret_key: None,+ requires_endpoint: true,+ },+ ProviderMeta {+ id: "you",+ label: "You.com",+ keyless: true,+ secret_key: Some("you-api-key"),+ requires_endpoint: false,+ },+];++/// Look up a backend by id (case-insensitive; empty/absent is the default).+pub fn provider_meta(provider: Option<&str>) -> Option<&'static ProviderMeta> {+ match provider.map(|s| s.trim().to_ascii_lowercase()).as_deref() {+ None | Some("") => PROVIDERS.first(),+ Some(id) => PROVIDERS.iter().find(|p| p.id == id),+ }+}++/// A resolved backend selection: what [`create_provider`] is called with. Built+/// by the host from its own settings store; `Default` is the keyless default.+#[derive(Clone, Default, PartialEq, Eq)]+pub struct WebSearchConfig {+ pub provider: Option<String>,+ pub api_key: Option<String>,+ pub endpoint: Option<String>,+}++impl std::fmt::Debug for WebSearchConfig {+ /// Hand-written so the API key never reaches a log: hosts embed this in+ /// structs that derive `Debug`.+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("WebSearchConfig")+ .field("provider", &self.provider)+ .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))+ .field("endpoint", &self.endpoint)+ .finish()+ }+}++impl WebSearchConfig {+ /// Build the backend this selection names.+ pub fn create(&self) -> Result<Box<dyn SearchProvider>, String> {+ create_provider(+ self.provider.as_deref(),+ self.api_key.clone(),+ self.endpoint.clone(),+ )+ }+}+/// Build the backend for `provider` (case-insensitive; empty/absent selects the/// default). `api_key` is used by keyed backends; `endpoint` by self-hosted ones/// (e.g. a SearXNG instance URL).@@ -705,7 +794,7 @@ impl SearchProvider for YouComProvider {async fn fetch(&self, url: &str) -> Result<FetchedPage, String> {match &self.mode {// No keyless content endpoint, so read the page directly.- YouComMode::Hosted => fetch_url_direct(&self.client, url, "You.com").await,+ YouComMode::Hosted => fetch_url_direct(url, "You.com").await,YouComMode::Rest(key) => {let parsed = self.post_rest(@@ -853,7 +942,7 @@ impl SearchProvider for SearxngProvider {}async fn fetch(&self, url: &str) -> Result<FetchedPage, String> {- fetch_url_direct(&self.client, url, "SearXNG").await+ fetch_url_direct(url, "SearXNG").await}}@@ -890,16 +979,138 @@ fn normalize_searxng_search(body: &Value, count: u32) -> Vec<SearchResult> {/// Fetch a URL directly and return its bounded body, titled from its `<title>`./// Used by backends that have no content-extraction endpoint on the active/// transport, so `web_fetch` still answers instead of erroring.-async fn fetch_url_direct(- client: &reqwest::Client,- url: &str,- provider: &str,-) -> Result<FetchedPage, String> {- let resp = client- .get(url)- .send()- .await- .map_err(|e| format!("{provider} fetch request failed: {e}"))?;+/// Redirect hops a direct fetch follows, each re-vetted.+const DIRECT_FETCH_MAX_REDIRECTS: usize = 5;++/// Whether `ip` is an address on the public internet. A direct fetch runs+/// from the user's machine on a URL the model chose, so loopback, private,+/// link-local (cloud metadata), CGNAT, multicast and unspecified targets are+/// refused: otherwise a prompt-injected page could make the agent read local+/// services and LAN hosts through an auto-allowed tool.+fn is_public_ip(ip: std::net::IpAddr) -> bool {+ use std::net::IpAddr;+ match ip {+ IpAddr::V4(v4) => {+ let o = v4.octets();+ !(v4.is_loopback()+ || v4.is_private()+ || v4.is_link_local()+ || v4.is_unspecified()+ || v4.is_broadcast()+ || v4.is_multicast()+ || v4.is_documentation()+ || o[0] == 0+ // 100.64.0.0/10, carrier-grade NAT.+ || (o[0] == 100 && (o[1] & 0xc0) == 64))+ }+ IpAddr::V6(v6) => {+ if let Some(v4) = v6.to_ipv4_mapped() {+ return is_public_ip(IpAddr::V4(v4));+ }+ let s = v6.segments();+ let embedded = |hi: u16, lo: u16| {+ std::net::Ipv4Addr::new((hi >> 8) as u8, hi as u8, (lo >> 8) as u8, lo as u8)+ };+ // NAT64 (64:ff9b::/96) and 6to4 (2002::/16) carry an IPv4 address+ // a translating network delivers to; judge them by it.+ if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {+ return is_public_ip(IpAddr::V4(embedded(s[6], s[7])));+ }+ if s[0] == 0x2002 {+ return is_public_ip(IpAddr::V4(embedded(s[1], s[2])));+ }+ !(v6.is_loopback()+ || v6.is_unspecified()+ || v6.is_multicast()+ // fc00::/7 unique local, fe80::/10 link-local, fec0::/10+ // deprecated site-local.+ || (s[0] & 0xfe00) == 0xfc00+ || (s[0] & 0xffc0) == 0xfe80+ || (s[0] & 0xffc0) == 0xfec0)+ }+ }+}++/// Resolve `url`'s host and return the address to connect to, refusing any+/// target that is not public. Every resolved address must pass, so a name with+/// one public and one private record cannot be used to reach the private one.+async fn vet_direct_target(url: &reqwest::Url) -> Result<std::net::SocketAddr, String> {+ if !matches!(url.scheme(), "http" | "https") {+ return Err(format!("only http(s) URLs can be fetched, got: {url}"));+ }+ let port = url+ .port_or_known_default()+ .ok_or_else(|| format!("no port for {url}"))?;+ let host = url+ .host_str()+ .filter(|h| !h.is_empty())+ .ok_or_else(|| format!("no host in {url}"))?;+ // An IPv6 literal comes back bracketed; a literal is used as-is so it is+ // vetted without a lookup.+ let literal = host.trim_start_matches('[').trim_end_matches(']');+ let addrs: Vec<std::net::SocketAddr> = match literal.parse::<std::net::IpAddr>() {+ Ok(ip) => vec![(ip, port).into()],+ Err(_) => tokio::net::lookup_host((host, port))+ .await+ .map_err(|e| format!("could not resolve {host}: {e}"))?+ .collect(),+ };+ let first = *addrs+ .first()+ .ok_or_else(|| format!("no address for {url}"))?;+ if let Some(bad) = addrs.iter().find(|a| !is_public_ip(a.ip())) {+ return Err(format!(+ "refusing to fetch {url}: it resolves to a local or private address ({})",+ bad.ip()+ ));+ }+ Ok(first)+}++/// GET a URL straight from this machine. Each hop (the URL and every+/// redirect) is vetted by [`vet_direct_target`], and the connection is pinned+/// to the vetted address so a second DNS answer cannot swap in a private one.+///+/// Proxies from the environment are ignored on purpose: a proxy resolves the+/// name itself, so the pin would no longer decide what is fetched, and a name+/// that is only private inside the proxy's network would pass the vetting.+async fn fetch_url_direct(url: &str, provider: &str) -> Result<FetchedPage, String> {+ let mut current =+ reqwest::Url::parse(url).map_err(|e| format!("{provider} fetch: invalid URL {url}: {e}"))?;+ let mut hops = 0;+ let resp = loop {+ let addr = vet_direct_target(¤t).await?;+ let mut builder = reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECS))+ .redirect(reqwest::redirect::Policy::none())+ .no_proxy();+ if let Some(domain) = current.domain() {+ builder = builder.resolve(domain, addr);+ }+ let client = builder+ .build()+ .map_err(|e| format!("failed to build HTTP client for {provider}: {e}"))?;+ let resp = client+ .get(current.clone())+ .send()+ .await+ .map_err(|e| format!("{provider} fetch request failed: {e}"))?;+ if !resp.status().is_redirection() {+ break resp;+ }+ hops += 1;+ if hops > DIRECT_FETCH_MAX_REDIRECTS {+ return Err(format!("{provider} fetch: too many redirects for {url}"));+ }+ let location = resp+ .headers()+ .get(reqwest::header::LOCATION)+ .and_then(|v| v.to_str().ok())+ .ok_or_else(|| format!("{provider} fetch: redirect without a Location header"))?;+ current = current+ .join(location)+ .map_err(|e| format!("{provider} fetch: bad redirect target {location}: {e}"))?;+ };let status = resp.status();let body = resp.text()@@ -992,6 +1203,81 @@ mod tests {assert!(create_provider(Some("Exa"), None, None).is_ok());}+ #[test]+ fn public_ip_check_refuses_local_and_private_ranges() {+ for ip in [+ "127.0.0.1",+ "10.1.2.3",+ "172.16.0.1",+ "192.168.1.1",+ "169.254.169.254",+ "100.64.0.1",+ "0.0.0.0",+ "::1",+ "fd00::1",+ "fe80::1",+ "::ffff:127.0.0.1",+ "64:ff9b::7f00:1",+ "64:ff9b::a00:1",+ "2002:c0a8:101::1",+ "2002:7f00:1::1",+ "fec0::1",+ ] {+ assert!(!is_public_ip(ip.parse().unwrap()), "{ip} must be refused");+ }+ for ip in [+ "1.1.1.1",+ "93.184.216.34",+ "2606:4700:4700::1111",+ "64:ff9b::101:101",+ "2002:101:101::1",+ ] {+ assert!(is_public_ip(ip.parse().unwrap()), "{ip} must be allowed");+ }+ }++ /// Literal and named local targets are refused before any request is made.+ #[tokio::test]+ async fn direct_fetch_refuses_local_targets() {+ for url in [+ "http://127.0.0.1:9/",+ "http://localhost:9/",+ "http://[::1]:9/",+ "http://169.254.169.254/latest/meta-data/",+ ] {+ let err = fetch_url_direct(url, "SearXNG").await.unwrap_err();+ assert!(err.contains("local or private"), "{url}: {err}");+ }+ }++ #[test]+ fn web_search_config_debug_redacts_the_key() {+ let config = WebSearchConfig {+ provider: Some("tavily".into()),+ api_key: Some("tvly-secret".into()),+ endpoint: None,+ };+ let printed = format!("{config:?}");+ assert!(!printed.contains("tvly-secret"), "{printed}");+ assert!(printed.contains("redacted"), "{printed}");+ }++ #[test]+ fn every_listed_provider_is_constructible() {+ for meta in PROVIDERS {+ let key = (!meta.keyless).then(|| "k".to_string());+ let endpoint = meta.requires_endpoint.then(|| "https://x.example".to_string());+ assert!(+ create_provider(Some(meta.id), key, endpoint).is_ok(),+ "{} must be accepted by create_provider",+ meta.id+ );+ }+ assert_eq!(provider_meta(None).map(|m| m.id), Some("exa"));+ assert_eq!(provider_meta(Some("Tavily")).map(|m| m.id), Some("tavily"));+ assert!(provider_meta(Some("brave")).is_none());+ }+#[test]fn create_provider_rejects_unknown() {match create_provider(Some("brave"), None, None) {diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex d9fc40668..4e3af0549 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -86,6 +86,15 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # to opt in; [] reads JAN.md only. A# # project's agent.toml [context] wins#+# [web_search] # backend for the web_search/web_fetch+# provider = "tavily" # tools: "exa" (default, keyless),+# # "tavily" (needs a key), "searxng"+# # (needs endpoint) or "you". Keys are+# # kept in the secret store: set them+# # with /settings or `jan config+# # web-search --api-key`, not here+# endpoint = "https://searx.example.com"+## [experimental] # features that may change or go away# acp = true # allow `jan acp`, the Agent Client# # Protocol server editors such as Zed@@ -208,10 +217,32 @@ struct GlobalConfigToml {/// graduating a feature is deleting its key rather than migrating it.#[serde(default, skip_serializing_if = "ExperimentalSection::is_empty")]experimental: ExperimentalSection,+ /// `[web_search]` -- which backend answers the native `web_search` and+ /// `web_fetch` tools. The API key is not here: it lives in the secret+ /// store, under the record the desktop's Web Search settings use.+ #[serde(default, skip_serializing_if = "WebSearchSection::is_empty")]+ web_search: WebSearchSection,#[serde(default)]providers: HashMap<String, GlobalProviderEntry>,}+/// `[web_search]` in `~/.jan/config.toml`. Each key is `None` when unset.+#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]+pub(crate) struct WebSearchSection {+ /// Backend id (`exa`, `tavily`, `searxng`, `you`). `None` = Exa.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub provider: Option<String>,+ /// Instance URL for a self-hosted backend (SearXNG).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub endpoint: Option<String>,+}++impl WebSearchSection {+ fn is_empty(&self) -> bool {+ self.provider.is_none() && self.endpoint.is_none()+ }+}+/// `[tui]` in `~/.jan/config.toml`. Each key is `None` when unset.#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]struct TuiSection {@@ -512,6 +543,76 @@ pub(crate) fn prune_threads_enabled() -> bool {.unwrap_or(false)}+/// `[web_search]` in `~/.jan/config.toml`. Unset on an unreadable or malformed+/// config: the default backend still works, and a preference file must never+/// stop a session from starting.+pub(crate) fn web_search_setting() -> WebSearchSection {+ load_raw().map(|config| config.web_search).unwrap_or_default()+}++/// The web tools' backend for a CLI run: `[web_search]` plus the provider's API+/// key from the secret store. The key is read only when the index says one is+/// stored, so a run never opens a keychain prompt for a key that is not there.+///+/// With no provider chosen the secret store is not touched at all: the default+/// stays keyless Exa upgraded by `EXA_API_KEY`, exactly as before this setting+/// existed, rather than silently picking up a key the desktop stored. Once a+/// provider is chosen its stored key wins over the env var.+/// An unknown provider id is passed through as-is: building it then fails with+/// a clear tool error instead of silently searching with a different backend.+#[cfg(feature = "cli")]+pub(crate) fn resolve_web_search() -> tauri_plugin_websearch::provider::WebSearchConfig {+ use crate::core::server::provider_secrets::{has_stored_key, load_provider_keys};+ let section = web_search_setting();+ if section.provider.as_deref().is_none_or(|p| p.trim().is_empty()) {+ return tauri_plugin_websearch::provider::WebSearchConfig::default();+ }+ let api_key = tauri_plugin_websearch::provider::provider_meta(section.provider.as_deref())+ .and_then(|meta| meta.secret_key)+ .filter(|record| has_stored_key(record))+ .and_then(|record| load_provider_keys(record).into_iter().next());+ tauri_plugin_websearch::provider::WebSearchConfig {+ provider: section.provider,+ api_key,+ endpoint: section.endpoint,+ }+}++/// Persist `[web_search]` into `~/.jan/config.toml`, format-preserving like+/// [`set_global_key`]. A `None` field removes that key; the table goes too once+/// it is empty, so resetting leaves no stray header behind.+#[cfg(feature = "cli")]+pub(crate) fn set_web_search(section: &WebSearchSection) -> Result<PathBuf, String> {+ let path = ensure_global_config()?;+ let raw = std::fs::read_to_string(&path)+ .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;+ let mut doc = raw+ .parse::<toml_edit::DocumentMut>()+ .map_err(|e| parse_error(&path, &e, e.message()))?;++ let table = doc["web_search"].or_insert(toml_edit::Item::Table(toml_edit::Table::new()));+ if let Some(table) = table.as_table_like_mut() {+ for (key, value) in [("provider", §ion.provider), ("endpoint", §ion.endpoint)] {+ match value.as_deref().map(str::trim).filter(|v| !v.is_empty()) {+ Some(v) => {+ table.insert(key, toml_edit::value(v));+ }+ None => {+ table.remove(key);+ }+ }+ }+ }+ if doc["web_search"].as_table_like().is_some_and(|t| t.is_empty()) {+ doc.remove("web_search");+ }++ std::fs::write(&path, doc.to_string())+ .map_err(|e| format!("Failed to write {}: {e}", path.display()))?;+ restrict_permissions(&path);+ Ok(path)+}+/// Host env-var names the sandboxed `bash` may inherit beyond the base/// allowlist (`env_passthrough` in `~/.jan/config.toml`), merged under a/// project's `[tools].env_passthrough`. Empty on an unreadable or malformed@@ -1264,6 +1365,34 @@ mod tests {});}+ /// `[web_search]` round-trips format-preserving, never lands inside a+ /// provider table, and an emptied section removes its header.+ #[test]+ fn set_web_search_round_trips_and_clears_the_table() {+ with_temp_home(|home| {+ let path = home.join(".jan").join("config.toml");+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, "# keep me\n[providers.p]\nbase_url = \"https://x\"\n")+ .unwrap();+ set_web_search(&WebSearchSection {+ provider: Some("searxng".into()),+ endpoint: Some("https://searx.example".into()),+ })+ .expect("set");+ let raw = std::fs::read_to_string(&path).unwrap();+ assert!(raw.contains("# keep me"), "{raw}");+ let section = web_search_setting();+ assert_eq!(section.provider.as_deref(), Some("searxng"));+ assert_eq!(section.endpoint.as_deref(), Some("https://searx.example"));+ assert!(load_global_config().unwrap().contains_key("p"));++ set_web_search(&WebSearchSection::default()).expect("reset");+ let raw = std::fs::read_to_string(&path).unwrap();+ assert!(!raw.contains("[web_search]"), "{raw}");+ assert_eq!(web_search_setting(), WebSearchSection::default());+ });+ }+/// A first toggle on a machine with no config must land in a real file/// rather than error, and that file should be the documented template.#[test]diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex dbba9dac8..9ab069640 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -739,6 +739,9 @@ struct CompositeToolInvoker {/// `~/.jan/config.toml` with the project's `[tools]` section.env_passthrough: Vec<String>,env_set: Vec<(String, String)>,+ /// Backend for `web_search`/`web_fetch`, resolved once per run from+ /// `[web_search]` (see [`resolve_web_search`]). `None` keeps the default.+ web_search: Option<tauri_plugin_websearch::provider::WebSearchConfig>,permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,events: mpsc::UnboundedSender<StreamEvent>,permission_requests: PermissionRegistry,@@ -1001,6 +1004,15 @@ fn resolve_env_set(project: Vec<(String, String)>) -> Vec<(String, String)> {merge_env_set(global, project)}+/// The web tools' backend for this run. `[web_search]` lives in the CLI's+/// `~/.jan/config.toml`; the desktop has no such file and keeps the default.+fn resolve_web_search() -> Option<tauri_plugin_websearch::provider::WebSearchConfig> {+ #[cfg(feature = "cli")]+ return Some(crate::core::agent::global_config::resolve_web_search());+ #[cfg(not(feature = "cli"))]+ None+}+fn merge_env_passthrough(mut global: Vec<String>, project: Vec<String>) -> Vec<String> {global.extend(project);global@@ -1187,6 +1199,7 @@ impl CompositeToolInvoker {.with_scratch_root(&self.scratch_root).with_env_passthrough(&self.env_passthrough).with_env_set(&self.env_set)+ .with_web_search(self.web_search.as_ref()).with_hooks(&self.hooks,self.run_mode == crate::core::agent::plan::RunMode::Plan,@@ -2598,6 +2611,7 @@ impl ToolInvoker for CompositeToolInvoker {let sandbox = self.sandbox;let hidden = self.hidden_root.clone();let scratch = self.scratch_root.clone();+ let web_search = self.web_search.clone();// Hooks come along: a read is still a tool call, and a// PreToolUse policy that stopped applying to whatever happened// to be batched concurrently would be no policy at all.@@ -2620,6 +2634,7 @@ impl ToolInvoker for CompositeToolInvoker {.with_sandbox(sandbox).with_hidden_root(hidden.as_deref()).with_scratch_root(&scratch)+ .with_web_search(web_search.as_ref()).with_hooks(&hooks, planning, Some(hook_sink));let (text, diff, images) = execute_builtin_with_diff(tool, &args, &ctx).await;ToolOutcome {@@ -3883,6 +3898,7 @@ async fn orchestrate_inner(scratch_root: scratch_root.clone(),env_passthrough: settings.env_passthrough,env_set: settings.env_set,+ web_search: resolve_web_search(),project_root: root.clone(),allowed_names: allowed_names.clone(),permissions: permissions.clone(),@@ -8735,6 +8751,7 @@ mod tests {scratch_root: tauri_plugin_agent_tools::workspace::scratch_dir("test-session"),env_passthrough: Vec::new(),env_set: Vec::new(),+ web_search: None,project_root: root,allowed_names: None,// Read-only default => write PROMPTS.diff --git a/src-tauri/src/core/cli/mcp_serve.rs b/src-tauri/src/core/cli/mcp_serve.rsindex 9422dfc95..aa4eb3a98 100644--- a/src-tauri/src/core/cli/mcp_serve.rs+++ b/src-tauri/src/core/cli/mcp_serve.rs@@ -48,6 +48,7 @@ fn options_for(project: &str, flags: &ServeFlags) -> Result<ServeOptions, Stringopts.enabled_skills = settings.enabled_skills;opts.allow_network = settings.allow_network.unwrap_or(false);opts.sandbox = settings.sandbox.unwrap_or(true);+ opts.web_search = Some(crate::core::agent::global_config::resolve_web_search());opts.served = ServedTools {allow_write: flags.allow_write,allow_exec: flags.allow_exec,diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 429c484e7..16725641d 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1211,6 +1211,109 @@ pub fn cli_agent_config_list() -> Result<serde_json::Value, String> {}))}+/// Choose the backend for the native `web_search`/`web_fetch` tools: the+/// `[web_search]` table in `~/.jan/config.toml` plus the provider's API key in+/// the secret store, under the same record the desktop's Web Search settings+/// write, so a key entered on either surface serves both.+///+/// `api_key` and `endpoint` merge like [`cli_agent_config_set`]: `None` keeps+/// what is stored, `Some("")` clears it. The resulting selection is validated+/// before anything is written, so a keyed backend with no key or a SearXNG with+/// no instance URL is refused rather than saved and failing on every search.+pub fn cli_web_search_set(+ provider: &str,+ api_key: Option<String>,+ endpoint: Option<String>,+) -> Result<PathBuf, String> {+ use crate::core::agent::global_config::{web_search_setting, WebSearchSection};+ use crate::core::server::provider_secrets;+ use tauri_plugin_websearch::provider::{provider_meta, PROVIDERS};++ let meta = provider_meta(Some(provider)).ok_or_else(|| {+ let ids: Vec<&str> = PROVIDERS.iter().map(|p| p.id).collect();+ format!("unknown web search provider '{provider}' (one of: {})", ids.join(", "))+ })?;+ let api_key = api_key.map(|k| k.trim().to_string());+ if meta.secret_key.is_none() && api_key.as_deref().is_some_and(|k| !k.is_empty()) {+ return Err(format!("{} does not use an API key", meta.label));+ }+ let endpoint = endpoint.map(|e| e.trim().trim_end_matches('/').to_string());+ // Only a self-hosted backend keeps an instance URL; switching away from one+ // drops it, so the status never shows a URL the chosen backend ignores.+ let endpoint = if meta.requires_endpoint {+ match endpoint {+ Some(e) if e.is_empty() => None,+ Some(e) => Some(e),+ None => web_search_setting().endpoint,+ }+ } else if endpoint.as_deref().is_some_and(|e| !e.is_empty()) {+ return Err(format!("{} does not use an instance URL", meta.label));+ } else {+ None+ };+ let effective_key = match (&api_key, meta.secret_key) {+ (Some(k), _) => Some(k.clone()).filter(|k| !k.is_empty()),+ (None, Some(record)) if provider_secrets::has_stored_key(record) => {+ provider_secrets::load_provider_keys(record).into_iter().next()+ }+ (None, _) => None,+ };+ tauri_plugin_websearch::provider::WebSearchConfig {+ provider: Some(meta.id.to_string()),+ api_key: effective_key,+ endpoint: endpoint.clone(),+ }+ .create()?;++ // The config goes first: it is the write that can fail on user input (an+ // unparseable file), and the key record is shared with the desktop, so it+ // must not be replaced or deleted for a selection that was never saved. A+ // failed key write then puts the previous selection back.+ let previous = web_search_setting();+ let path = crate::core::agent::global_config::set_web_search(&WebSearchSection {+ provider: Some(meta.id.to_string()),+ endpoint,+ })?;+ if let (Some(key), Some(record)) = (api_key, meta.secret_key) {+ let stored = if key.is_empty() {+ provider_secrets::delete_provider_keys(record)+ } else {+ provider_secrets::store_provider_keys(record, &[key])+ };+ if let Err(e) = stored {+ let _ = crate::core::agent::global_config::set_web_search(&previous);+ return Err(format!("failed to store the {} API key: {e}", meta.label));+ }+ }+ Ok(path)+}++/// Drop `[web_search]` so the keyless default applies again. Stored API keys+/// are left alone: the desktop reads the same records.+pub fn cli_web_search_reset() -> Result<PathBuf, String> {+ crate::core::agent::global_config::set_web_search(&Default::default())+}++/// The current web search selection as JSON, API key reported as present or+/// absent only. `has_api_key` answers "will a run use a stored key", so with+/// no provider chosen it is false even if the desktop stored an Exa key: the+/// unconfigured default ignores it (see `global_config::resolve_web_search`).+pub fn cli_web_search_status() -> serde_json::Value {+ let section = crate::core::agent::global_config::web_search_setting();+ let meta = tauri_plugin_websearch::provider::provider_meta(section.provider.as_deref());+ let chosen = section.provider.as_deref().is_some_and(|p| !p.trim().is_empty());+ let has_api_key = chosen+ && meta+ .and_then(|m| m.secret_key)+ .is_some_and(crate::core::server::provider_secrets::has_stored_key);+ serde_json::json!({+ "provider": meta.map(|m| m.id).or(section.provider.as_deref()),+ "label": meta.map(|m| m.label),+ "has_api_key": has_api_key,+ "endpoint": section.endpoint,+ })+}+/// List plugins installed for a project.pub fn cli_plugin_list(project: &str) -> Vec<crate::core::agent::plugins::InstalledPlugin> {crate::core::agent::plugins::installed(&resolve_project_root(project))diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex f2db3cb88..870928f0d 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -4300,6 +4300,8 @@ struct App {mcp_auth_cancel: bool,/// Active OpenAI-compatible provider wizard (docked); owns the keyboard.provider_prompt: Option<ProviderPrompt>,+ /// Active `/settings > web search` form (docked); owns the keyboard.+ web_search_prompt: Option<WebSearchPrompt>,/// Providers already probed for a missing model list this session/// (success or failure). A dead/unreachable upstream must not be re-contacted/// on every bare `/model` -- that would freeze the render loop for the whole@@ -5080,6 +5082,7 @@ impl App {mcp_auth: None,mcp_auth_cancel: false,provider_prompt: None,+ web_search_prompt: None,probed_models: std::collections::HashSet::new(),model_pinned: false,login_submit: None,@@ -5791,7 +5794,10 @@ impl App {Some("finish the message to the subagent above")} else if self.vibe_confirm.is_some() {Some("answer the proposal above")- } else if self.mcp_prompt.is_some() || self.provider_prompt.is_some() {+ } else if self.mcp_prompt.is_some()+ || self.provider_prompt.is_some()+ || self.web_search_prompt.is_some()+ {Some("finish the wizard above")} else if self.readout.is_some() {// A readout takes the keyboard while it is docked -- `q`, `m` and@@ -13676,6 +13682,8 @@ fn route_paste_event(app: &mut App, event: Event) {prompt.paste(&text);} else if let Some(prompt) = app.provider_prompt.as_mut() {prompt.paste(&text);+ } else if let Some(prompt) = app.web_search_prompt.as_mut() {+ prompt.paste(&text);} else if !app.ask_queue.is_empty() {handle_ask_paste(app, &text);} else {@@ -14451,6 +14459,12 @@ async fn handle_key(return;}+ // The web search form owns the keyboard while open.+ if app.web_search_prompt.is_some() {+ handle_web_search_prompt_key(app, key, ctrl);+ return;+ }+// A pending permission prompt captures y/a/n; Ctrl-C or Ctrl-D cancels the// run and denies everything queued, so it can't be wedged waiting on an// unanswered prompt. Several subagents can have requests queued at once@@ -14774,6 +14788,16 @@ async fn handle_key(let key = picker.items[picker.selected].value.clone();// (picker borrow ends here; nothing below reads it before rebuild)let toml_path = app.agent_dir.join("agent.toml");+ if key == WEB_SEARCH_SETTINGS_ROW {+ match super::cli_web_search_reset() {+ Ok(_) => {+ app.note("web search reset to the default (Exa); takes effect on the next run");+ reopen_settings_on(app, WEB_SEARCH_SETTINGS_ROW);+ }+ Err(e) => app.note(&format!("failed to reset web search: {e}")),+ }+ return;+ }let Some(def) = AGENT_SETTINGS.iter().find(|d| d.key == key) else {// The leading "providers" row has no key to unset.return;@@ -14923,6 +14947,9 @@ async fn handle_key(open_provider_settings(app);} else if value == SUBAGENTS_SETTINGS_ROW {open_subagent_settings(app, None);+ } else if value == WEB_SEARCH_SETTINGS_ROW {+ app.picker = None;+ app.web_search_prompt = Some(WebSearchPrompt::load());} else if value == SMOL_MODEL_KEY {let current =crate::core::agent::global_config::global_value(SMOL_MODEL_KEY);@@ -16568,6 +16595,10 @@ const PROVIDERS_SETTINGS_ROW: &str = "__providers__";/// model screen (`open_subagent_settings`).const SUBAGENTS_SETTINGS_ROW: &str = "__subagents__";+/// Sentinel row value in the `/settings` picker that docks the web search+/// backend form (`WebSearchPrompt`).+const WEB_SEARCH_SETTINGS_ROW: &str = "__web_search__";+/// The `/settings` row whose Enter opens the model picker instead of a text/// dock. Still an [`AGENT_SETTINGS`] def, so `x` and `/vibe-setting` reach it.const SMOL_MODEL_KEY: &str = "smol_model";@@ -17271,6 +17302,276 @@ impl ProviderPrompt {}}+/// Docked form for `/settings > web search`, the TUI twin of the desktop's Web+/// Search page: pick the backend, then give it what it needs -- an API key+/// (optional for keyless backends) or an instance URL (SearXNG). Saved through+/// `cli_web_search_set`, the same path as `jan config web-search`.+struct WebSearchPrompt {+ /// Index into `tauri_plugin_websearch::provider::PROVIDERS`.+ provider: usize,+ field: WebSearchField,+ /// What was typed for the key. The stored key is never loaded here (it+ /// must not be echoable), so an untouched field means "keep it".+ api_key: String,+ key_touched: bool,+ /// Whether the selected backend has a key in the secret store. Looked up+ /// when the backend is chosen, not per frame: the check reads (and may+ /// decrypt) files, which has no place on the render loop.+ key_stored: bool,+ endpoint: String,+ error: Option<String>,+}++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+enum WebSearchField {+ Provider,+ /// The API key or the instance URL, whichever the backend asks for.+ Value,+}++impl WebSearchPrompt {+ /// Prefilled from `[web_search]`; an unknown stored id opens on the default.+ fn load() -> Self {+ use tauri_plugin_websearch::provider::{provider_meta, PROVIDERS};+ let section = crate::core::agent::global_config::web_search_setting();+ let provider = provider_meta(section.provider.as_deref())+ .and_then(|m| PROVIDERS.iter().position(|p| p.id == m.id))+ .unwrap_or(0);+ let mut prompt = Self {+ provider,+ field: WebSearchField::Provider,+ api_key: String::new(),+ key_touched: false,+ key_stored: false,+ endpoint: section.endpoint.unwrap_or_default(),+ error: None,+ };+ prompt.refresh_key_stored();+ prompt+ }++ fn refresh_key_stored(&mut self) {+ self.key_stored = self+ .meta()+ .secret_key+ .is_some_and(crate::core::server::provider_secrets::has_stored_key);+ }++ fn meta(&self) -> &'static tauri_plugin_websearch::provider::ProviderMeta {+ &tauri_plugin_websearch::provider::PROVIDERS[self.provider]+ }++ /// Step the backend selection. A key typed for one backend is never saved+ /// under another, so switching discards it.+ fn cycle_provider(&mut self, forward: bool) {+ let n = tauri_plugin_websearch::provider::PROVIDERS.len();+ self.provider = if forward {+ (self.provider + 1) % n+ } else {+ (self.provider + n - 1) % n+ };+ self.api_key.clear();+ self.key_touched = false;+ self.error = None;+ self.refresh_key_stored();+ }++ fn toggle_field(&mut self) {+ self.field = match self.field {+ WebSearchField::Provider => WebSearchField::Value,+ WebSearchField::Value => WebSearchField::Provider,+ };+ }++ fn push(&mut self, text: &str) {+ if self.field != WebSearchField::Value {+ return;+ }+ if self.meta().requires_endpoint {+ self.endpoint.push_str(text);+ } else {+ self.api_key.push_str(text);+ self.key_touched = true;+ }+ }++ fn pop(&mut self) {+ if self.field != WebSearchField::Value {+ return;+ }+ if self.meta().requires_endpoint {+ self.endpoint.pop();+ } else {+ self.api_key.pop();+ self.key_touched = true;+ }+ }++ fn paste(&mut self, text: &str) {+ self.push(super::secret_input::pasted(text));+ }++ /// Value-row label and contents. The key renders masked, or says whether+ /// one is stored when nothing was typed.+ fn value_row(&self) -> (&'static str, String) {+ let meta = self.meta();+ if meta.requires_endpoint {+ return ("instance url", self.endpoint.clone());+ }+ if !self.key_touched {+ return (+ "api key",+ if self.key_stored { "(stored)" } else { "(none)" }.to_string(),+ );+ }+ ("api key", super::secret_input::mask(self.api_key.chars().count()))+ }++ /// What the backend needs, worded like the desktop page.+ fn help(&self) -> String {+ let meta = self.meta();+ if meta.requires_endpoint {+ format!("Required. The base URL of your {} instance, with the JSON API enabled.", meta.label)+ } else if meta.keyless {+ format!(+ "Optional. A {} API key gives higher rate limits and structured results; \+ leave empty for the free keyless endpoint.",+ meta.label+ )+ } else {+ format!("Required. {} needs an API key to return results.", meta.label)+ }+ }++ fn save(&self) -> Result<(), String> {+ let meta = self.meta();+ let (api_key, endpoint) = if meta.requires_endpoint {+ (None, Some(self.endpoint.clone()))+ } else {+ (self.key_touched.then(|| self.api_key.clone()), None)+ };+ super::cli_web_search_set(meta.id, api_key, endpoint).map(|_| ())+ }+}++/// Keyboard for the web search dock: Up/Down/Tab move, Left/Right change the+/// backend on its row, chars/backspace edit the value row, Enter saves and+/// returns to `/settings`, Esc cancels back to it.+fn handle_web_search_prompt_key(app: &mut App, key: KeyEvent, ctrl: bool) {+ if key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c')) {+ app.web_search_prompt = None;+ return reopen_settings_on(app, WEB_SEARCH_SETTINGS_ROW);+ }+ let Some(prompt) = app.web_search_prompt.as_mut() else {+ return;+ };+ match key.code {+ KeyCode::Up | KeyCode::Down | KeyCode::Tab | KeyCode::BackTab => prompt.toggle_field(),+ KeyCode::Left if prompt.field == WebSearchField::Provider => prompt.cycle_provider(false),+ KeyCode::Right if prompt.field == WebSearchField::Provider => prompt.cycle_provider(true),+ KeyCode::Enter => match prompt.save() {+ Ok(()) => {+ let label = prompt.meta().label;+ app.web_search_prompt = None;+ app.note(&format!("web search now uses {label}; takes effect on the next run"));+ reopen_settings_on(app, WEB_SEARCH_SETTINGS_ROW);+ }+ Err(e) => prompt.error = Some(e),+ },+ KeyCode::Backspace => prompt.pop(),+ KeyCode::Char(ch) if !ctrl => prompt.push(ch.encode_utf8(&mut [0; 4])),+ _ => {}+ }+}++/// Rebuild `/settings` (so the row's hint reflects a write) with the cursor on+/// `row`.+fn reopen_settings_on(app: &mut App, row: &str) {+ open_settings_screen(app);+ select_settings_row(app, row);+}++/// The web search dock's contents at `width`.+fn web_search_prompt_lines(prompt: &WebSearchPrompt, width: u16) -> Vec<Line<'static>> {+ let dim = Style::new().fg(theme::muted());+ let max = width.max(1) as usize;+ let row = |selected: bool, label: &str, value: String, cursor: bool| {+ let style = if selected { Style::new().bold() } else { dim };+ let marker = if selected { "\u{203a} " } else { " " };+ let mut spans = vec![+ Span::styled(format!("{marker}{label}: "), style),+ Span::styled(value, style),+ ];+ if selected && cursor {+ spans.push(Span::styled("\u{2588}", Style::new().fg(theme::accent())));+ }+ Line::from(spans)+ };+ let on_provider = prompt.field == WebSearchField::Provider;+ let mut lines = vec![row(+ on_provider,+ "provider",+ format!("\u{2039} {} \u{203a}", prompt.meta().label),+ false,+ )];+ let (label, value) = prompt.value_row();+ lines.push(row(!on_provider, label, value, true));+ lines.extend(wrap_text(&prompt.help(), dim, max).into_iter().map(Line::from));+ if let Some(error) = &prompt.error {+ lines.extend(wrap_text(error, Style::new().red(), max).into_iter().map(Line::from));+ }+ let hint = if on_provider {+ "\u{2190}/\u{2192} change provider \u{b7} \u{2191}/\u{2193} move \u{b7} Enter save \u{b7} Esc cancel"+ } else if prompt.meta().requires_endpoint {+ "\u{2191}/\u{2193} move \u{b7} Enter save \u{b7} Esc cancel"+ } else {+ "\u{2191}/\u{2193} move \u{b7} Enter save \u{b7} Esc cancel (type to replace the key, blank out to clear)"+ };+ lines.extend(wrap_text(hint, dim, max).into_iter().map(Line::from));+ lines+}++fn web_search_prompt_rect(+ prompt: &WebSearchPrompt,+ body: ratatui::layout::Rect,+ input: ratatui::layout::Rect,+) -> ratatui::layout::Rect {+ let height = (web_search_prompt_lines(prompt, panel_inner_width(input.width)).len() as u16 + 2)+ .min(body.height);+ ratatui::layout::Rect {+ x: input.x,+ y: input.y.saturating_sub(height).max(body.y),+ width: input.width,+ height,+ }+}++fn draw_web_search_prompt(f: &mut Frame, area: ratatui::layout::Rect, prompt: &WebSearchPrompt) {+ use ratatui::widgets::Clear;+ let block = panel_block(theme::border_active())+ .title(Span::styled(" web search ", title_style(theme::border_active())));+ f.render_widget(Clear, area);+ let inner = block.inner(area);+ f.render_widget(block, area);+ f.render_widget(Paragraph::new(web_search_prompt_lines(prompt, inner.width)), inner);+}++/// `/settings` hint for the web search row: the backend, and what it is+/// running on (a stored key, the keyless tier, an instance URL).+fn web_search_settings_hint() -> String {+ let status = super::cli_web_search_status();+ let label = status["label"]+ .as_str()+ .or(status["provider"].as_str())+ .unwrap_or("Exa");+ let detail = match (status["endpoint"].as_str(), status["has_api_key"].as_bool()) {+ (Some(url), _) if status["provider"] == "searxng" => url.to_string(),+ (_, Some(true)) => "key set".to_string(),+ _ => "no key".to_string(),+ };+ format!("= {label} ({detail})")+}+/// Value of an `[agent]` key in `agent.toml` as a display string, `None` when/// unset or the file is unreadable. Reads the inner value directly so the/// display is not padded by the document's alignment.@@ -17390,6 +17691,13 @@ fn build_agent_settings_items(toml_path: &std::path::Path) -> Vec<PickerItem> {checkbox: None,spans: None,});+ items.push(PickerItem {+ value: WEB_SEARCH_SETTINGS_ROW.to_string(),+ label: "web search".to_string(),+ hint: Some(web_search_settings_hint()),+ checkbox: None,+ spans: None,+ });items.extend(AGENT_SETTINGS.iter()@@ -21979,6 +22287,8 @@ fn draw(f: &mut Frame, app: &mut App) {height,};draw_provider_prompt(f, rect, prompt);+ } else if let Some(prompt) = &app.web_search_prompt {+ draw_web_search_prompt(f, web_search_prompt_rect(prompt, chunks[1], chunks[2]), prompt);} else if !app.ask_queue.is_empty() {let queue_len = app.ask_queue.len();let ask = app.ask_queue.front_mut().expect("checked non-empty above");@@ -31520,8 +31830,9 @@ mod tests {super::settings_command(&mut app, "");let picker = app.picker.as_ref().expect("bare /settings opens picker");assert_eq!(picker.kind, PickerKind::AgentSettings);- // The leading "providers" and "subagents" rows plus a row per def.- assert_eq!(picker.items.len(), AGENT_SETTINGS.len() + 2);+ // The leading "providers", "subagents" and "web search" rows plus a+ // row per def.+ assert_eq!(picker.items.len(), AGENT_SETTINGS.len() + 3);assert_eq!(picker.items[0].value, PROVIDERS_SETTINGS_ROW);let row = picker.items@@ -32473,6 +32784,158 @@ mod tests {});}+ /// `/settings` lists a web search row; Enter docks the form, Right picks+ /// the next backend (Tavily), a typed key is masked on screen, and Enter+ /// writes `[web_search]` plus the key under the desktop's secret record,+ /// then returns to the menu with the new backend in the hint.+ #[test]+ fn settings_web_search_row_saves_provider_and_key() {+ with_isolated_login_state(|| {+ let rt = tokio::runtime::Runtime::new().unwrap();+ let mut app = test_app();+ super::open_settings_screen(&mut app);+ let picker = app.picker.as_mut().expect("settings open");+ let idx = picker+ .items+ .iter()+ .position(|i| i.value == super::WEB_SEARCH_SETTINGS_ROW)+ .expect("web search row listed");+ assert_eq!(picker.items[idx].hint.as_deref(), Some("= Exa (no key)"));+ picker.selected = idx;+ rt.block_on(async {+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(app.web_search_prompt.is_some(), "form docked");+ press(&mut app, KeyCode::Right, KeyModifiers::NONE).await;+ assert_eq!(app.web_search_prompt.as_ref().unwrap().meta().id, "tavily");++ // Tavily needs a key: saving without one is refused in place.+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ let prompt = app.web_search_prompt.as_ref().expect("still open");+ assert!(prompt.error.as_deref().unwrap_or("").contains("Tavily"));++ press(&mut app, KeyCode::Down, KeyModifiers::NONE).await;+ for ch in "tvly-secret".chars() {+ press(&mut app, KeyCode::Char(ch), KeyModifiers::NONE).await;+ }+ });+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(!screen.contains("tvly-secret"), "key must be masked: {screen}");+ rt.block_on(press(&mut app, KeyCode::Enter, KeyModifiers::NONE));+ assert!(app.web_search_prompt.is_none(), "saved and closed");++ let section = crate::core::agent::global_config::web_search_setting();+ assert_eq!(section.provider.as_deref(), Some("tavily"));+ assert_eq!(+ crate::core::server::provider_secrets::load_provider_keys("tavily-api-key"),+ vec!["tvly-secret".to_string()]+ );+ let resolved = crate::core::agent::global_config::resolve_web_search();+ assert_eq!(resolved.api_key.as_deref(), Some("tvly-secret"));++ let picker = app.picker.as_ref().expect("back on /settings");+ let row = &picker.items[picker.selected];+ assert_eq!(row.value, super::WEB_SEARCH_SETTINGS_ROW);+ assert_eq!(row.hint.as_deref(), Some("= Tavily (key set)"));++ // `x` on the row resets to the default backend.+ rt.block_on(press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE));+ assert_eq!(+ crate::core::agent::global_config::web_search_setting(),+ Default::default()+ );+ });+ }++ /// With no provider chosen, a key the desktop stored for Exa is not picked+ /// up: the default stays keyless Exa plus `EXA_API_KEY`. Choosing Exa+ /// explicitly is what opts the stored key in.+ #[test]+ fn unconfigured_web_search_ignores_a_stored_exa_key() {+ with_isolated_login_state(|| {+ crate::core::server::provider_secrets::store_provider_keys(+ "exa-api-key",+ &["desktop-key".to_string()],+ )+ .unwrap();+ assert_eq!(+ crate::core::agent::global_config::resolve_web_search(),+ Default::default()+ );+ // Status and the /settings hint agree with what a run uses.+ assert_eq!(super::super::cli_web_search_status()["has_api_key"], false);+ assert_eq!(super::web_search_settings_hint(), "= Exa (no key)");++ super::super::cli_web_search_set("exa", None, None).expect("choose exa");+ let resolved = crate::core::agent::global_config::resolve_web_search();+ assert_eq!(resolved.api_key.as_deref(), Some("desktop-key"));+ assert_eq!(super::super::cli_web_search_status()["has_api_key"], true);+ assert_eq!(super::web_search_settings_hint(), "= Exa (key set)");+ });+ }++ /// A config that cannot be written must leave the shared key record alone:+ /// the desktop reads it too.+ #[test]+ fn web_search_set_keeps_the_key_when_the_config_write_fails() {+ with_isolated_login_state(|| {+ crate::core::server::provider_secrets::store_provider_keys(+ "tavily-api-key",+ &["old".to_string()],+ )+ .unwrap();+ let path = crate::core::agent::global_config::ensure_global_config().unwrap();+ std::fs::write(&path, "not = [valid toml\n").unwrap();+ assert!(+ super::super::cli_web_search_set("tavily", Some("new".into()), None).is_err()+ );+ assert_eq!(+ crate::core::server::provider_secrets::load_provider_keys("tavily-api-key"),+ vec!["old".to_string()]+ );+ });+ }++ /// SearXNG asks for an instance URL instead of a key, and a pasted URL+ /// lands in that field.+ #[test]+ fn web_search_prompt_searxng_takes_an_instance_url() {+ with_isolated_login_state(|| {+ let mut app = test_app();+ let mut prompt = super::WebSearchPrompt::load();+ while prompt.meta().id != "searxng" {+ prompt.cycle_provider(true);+ }+ prompt.toggle_field();+ assert_eq!(prompt.value_row().0, "instance url");+ assert!(prompt.save().is_err(), "no instance URL must not save");+ assert!(super::super::cli_web_search_set("brave", None, None).is_err());+ app.web_search_prompt = Some(prompt);+ super::route_paste_event(+ &mut app,+ Event::Paste(" https://searx.example/ ".into()),+ );+ let prompt = app.web_search_prompt.as_ref().unwrap();+ assert_eq!(prompt.endpoint, "https://searx.example/");+ prompt.save().expect("saved");+ let section = crate::core::agent::global_config::web_search_setting();+ assert_eq!(section.provider.as_deref(), Some("searxng"));+ assert_eq!(section.endpoint.as_deref(), Some("https://searx.example"));++ // Switching to a backend with no instance URL drops the old one,+ // and offering it one is refused.+ super::super::cli_web_search_set("you", None, None).expect("switch");+ let section = crate::core::agent::global_config::web_search_setting();+ assert_eq!(section.provider.as_deref(), Some("you"));+ assert_eq!(section.endpoint, None);+ assert!(super::super::cli_web_search_set(+ "you",+ None,+ Some("https://searx.example".into())+ )+ .is_err());+ });+ }+#[test]fn provider_prompt_save_writes_global_config() {crate::core::agent::global_config::with_temp_home(|_| {diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rsindex 1e23056da..6a079094e 100644--- a/src-tauri/src/core/mcp/server/mod.rs+++ b/src-tauri/src/core/mcp/server/mod.rs@@ -104,6 +104,8 @@ pub struct ServeOptions {pub scratch_root: Option<PathBuf>,/// Which tools are offered. See [`ServedTools`].pub served: ServedTools,+ /// Backend for `web_search`/`web_fetch`. `None` keeps the default.+ pub web_search: Option<tauri_plugin_websearch::provider::WebSearchConfig>,}impl ServeOptions {@@ -120,6 +122,7 @@ impl ServeOptions {sandbox: true,scratch_root: None,served: ServedTools::default(),+ web_search: None,}}}@@ -206,7 +209,8 @@ impl JanToolServer {&self.opts.project_root,&self.opts.enabled_skills,))- .with_skill_user_root(self.opts.user_store_root.as_deref());+ .with_skill_user_root(self.opts.user_store_root.as_deref())+ .with_web_search(self.opts.web_search.as_ref());if let Some(scratch) = self.opts.scratch_root.as_deref() {ctx = ctx.with_scratch_root(scratch);}