Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(web-search): native web_search/web_fetch via tauri-plugin-websearch (#8464)

Akarshan Biswas508e782221da
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 3eb19d22d..efeff2951 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -65,6 +65,7 @@ dependencies = [
"tauri-plugin-store",
"tauri-plugin-updater",
"tauri-plugin-vector-db",
+ "tauri-plugin-websearch",
"tempfile",
"thiserror 2.0.17",
"tokio",
@@ -7099,6 +7100,21 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "tauri-plugin-websearch"
+version = "0.8.3"
+dependencies = [
+ "async-trait",
+ "log",
+ "reqwest 0.12.23",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.17",
+ "tokio",
+]
+
[[package]]
name = "tauri-runtime"
version = "2.10.1"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index e542b1e2e..11cf709b4 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -99,6 +99,7 @@ tauri-plugin-hardware = { path = "./plugins/tauri-plugin-hardware", optional = t
tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp" }
tauri-plugin-vector-db = { path = "./plugins/tauri-plugin-vector-db" }
tauri-plugin-rag = { path = "./plugins/tauri-plugin-rag" }
+tauri-plugin-websearch = { path = "./plugins/tauri-plugin-websearch" }
# `default-features = false` drops the plugin's default `rustls-tls` (bundled
# Mozilla roots) so `native-tls` reads the OS trust store instead. Other
# features re-list the plugin's defaults so behaviour is otherwise unchanged.
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index 486b39009..17d194473 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -27,6 +27,7 @@
"store:default",
"vector-db:default",
"rag:default",
+ "websearch:default",
"hardware:default",
"deep-link:default",
"llamacpp:default",
diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.json
index f23b76b59..9259cdc71 100644
--- a/src-tauri/capabilities/desktop.json
+++ b/src-tauri/capabilities/desktop.json
@@ -26,6 +26,7 @@
"store:default",
"vector-db:default",
"rag:default",
+ "websearch:default",
"llamacpp:default",
"deep-link:default",
"hardware:default",
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-vector-db/permissions/autogenerated/reference.md
index b859ecb87..01ae76ee5 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-vector-db/permissions/autogenerated/reference.md
@@ -288,6 +288,84 @@ Denies the list_attachments command without any pre-configured scope.
<tr>
<td>
+`vector-db:allow-memory-clear`
+
+</td>
+<td>
+
+Enables the memory_clear command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`vector-db:deny-memory-clear`
+
+</td>
+<td>
+
+Denies the memory_clear command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`vector-db:allow-memory-index`
+
+</td>
+<td>
+
+Enables the memory_index command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`vector-db:deny-memory-index`
+
+</td>
+<td>
+
+Denies the memory_index command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`vector-db:allow-memory-search`
+
+</td>
+<td>
+
+Enables the memory_search command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`vector-db:deny-memory-search`
+
+</td>
+<td>
+
+Denies the memory_search command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`vector-db:allow-search-collection`
</td>
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-vector-db/permissions/schemas/schema.json
index 6410337c5..0a5ed8ea3 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-vector-db/permissions/schemas/schema.json
@@ -414,6 +414,42 @@
"const": "deny-list-attachments",
"markdownDescription": "Denies the list_attachments command without any pre-configured scope."
},
+ {
+ "description": "Enables the memory_clear command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-memory-clear",
+ "markdownDescription": "Enables the memory_clear command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the memory_clear command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-memory-clear",
+ "markdownDescription": "Denies the memory_clear command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the memory_index command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-memory-index",
+ "markdownDescription": "Enables the memory_index command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the memory_index command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-memory-index",
+ "markdownDescription": "Denies the memory_index command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the memory_search command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-memory-search",
+ "markdownDescription": "Enables the memory_search command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the memory_search command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-memory-search",
+ "markdownDescription": "Denies the memory_search command without any pre-configured scope."
+ },
{
"description": "Enables the search_collection command without any pre-configured scope.",
"type": "string",
diff --git a/src-tauri/plugins/tauri-plugin-websearch/.gitignore b/src-tauri/plugins/tauri-plugin-websearch/.gitignore
new file mode 100644
index 000000000..5d3934a86
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/.gitignore
@@ -0,0 +1,12 @@
+/.vs
+.DS_Store
+package-lock.json
+yarn.lock
+
+/.tauri
+/target
+Cargo.lock
+node_modules/
+
+dist-js
+dist
diff --git a/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml b/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml
new file mode 100644
index 000000000..2e40ac199
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "tauri-plugin-websearch"
+version = "0.8.3"
+authors = ["Jan <[email protected]>"]
+description = "Tauri plugin providing native, provider-neutral web_search / web_fetch tools (Exa backend by default)"
+license = "MIT"
+repository = "https://github.com/janhq/jan"
+edition = "2021"
+rust-version = "1.77.2"
+exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
+links = "tauri-plugin-websearch"
+
+[dependencies]
+async-trait = "0.1"
+log = "0.4"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+tauri = { version = "2.5.0", default-features = false, features = [] }
+thiserror = "2.0.12"
+tokio = { version = "1", features = ["full"] }
+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
+
+[build-dependencies]
+tauri-plugin = { version = "2.3.1", features = ["build"] }
diff --git a/src-tauri/plugins/tauri-plugin-websearch/build.rs b/src-tauri/plugins/tauri-plugin-websearch/build.rs
new file mode 100644
index 000000000..2785adfda
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/build.rs
@@ -0,0 +1,5 @@
+const COMMANDS: &[&str] = &["web_search", "web_fetch"];
+
+fn main() {
+ tauri_plugin::Builder::new(COMMANDS).build();
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-websearch/guest-js/index.ts
new file mode 100644
index 000000000..3c61bfc7c
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/guest-js/index.ts
@@ -0,0 +1,34 @@
+import { invoke } from '@tauri-apps/api/core'
+import { SearchResult, FetchedPage } from './types'
+
+export { SearchResult, FetchedPage } from './types'
+
+export async function webSearch(
+ query: string,
+ count?: number,
+ apiKey?: string,
+ provider?: string,
+ endpoint?: string
+): Promise<SearchResult[]> {
+ return await invoke('plugin:websearch|web_search', {
+ query,
+ count,
+ provider,
+ apiKey,
+ endpoint,
+ })
+}
+
+export async function webFetch(
+ url: string,
+ apiKey?: string,
+ provider?: string,
+ endpoint?: string
+): Promise<FetchedPage> {
+ return await invoke('plugin:websearch|web_fetch', {
+ url,
+ provider,
+ apiKey,
+ endpoint,
+ })
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-websearch/guest-js/types.ts
new file mode 100644
index 000000000..d309d82d7
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/guest-js/types.ts
@@ -0,0 +1,13 @@
+export interface SearchResult {
+ title: string
+ url: string
+ snippet: string
+ published_at?: string
+}
+
+export interface FetchedPage {
+ url: string
+ title: string
+ content: string
+ truncated: boolean
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/package.json b/src-tauri/plugins/tauri-plugin-websearch/package.json
new file mode 100644
index 000000000..4ca5821c0
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@janhq/tauri-plugin-websearch-api",
+ "version": "0.8.3",
+ "private": true,
+ "description": "Tauri plugin API for native web_search / web_fetch tools",
+ "type": "module",
+ "types": "./dist-js/index.d.ts",
+ "main": "./dist-js/index.cjs",
+ "module": "./dist-js/index.js",
+ "exports": {
+ "types": "./dist-js/index.d.ts",
+ "import": "./dist-js/index.js",
+ "require": "./dist-js/index.cjs"
+ },
+ "files": [
+ "dist-js",
+ "README.md"
+ ],
+ "scripts": {
+ "build": "rollup -c",
+ "prepublishOnly": "yarn build",
+ "pretest": "yarn build"
+ },
+ "dependencies": {
+ "@tauri-apps/api": ">=2.0.0-beta.6"
+ },
+ "devDependencies": {
+ "@rollup/plugin-typescript": "^12.0.0",
+ "rollup": "^4.9.6",
+ "tslib": "^2.6.2",
+ "typescript": "^5.3.3"
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/permissions/default.toml b/src-tauri/plugins/tauri-plugin-websearch/permissions/default.toml
new file mode 100644
index 000000000..2cce7d2d5
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/permissions/default.toml
@@ -0,0 +1,6 @@
+[default]
+description = "Default permissions for the web search plugin"
+permissions = [
+ "allow-web-search",
+ "allow-web-fetch",
+]
diff --git a/src-tauri/plugins/tauri-plugin-websearch/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-websearch/permissions/schemas/schema.json
new file mode 100644
index 000000000..be57cd18f
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/permissions/schemas/schema.json
@@ -0,0 +1,330 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the web_fetch command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-web-fetch",
+ "markdownDescription": "Enables the web_fetch command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the web_fetch command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-web-fetch",
+ "markdownDescription": "Denies the web_fetch command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the web_search command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-web-search",
+ "markdownDescription": "Enables the web_search command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the web_search command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-web-search",
+ "markdownDescription": "Denies the web_search command without any pre-configured scope."
+ },
+ {
+ "description": "Default permissions for the web search plugin\n#### This default permission set includes:\n\n- `allow-web-search`\n- `allow-web-fetch`",
+ "type": "string",
+ "const": "default",
+ "markdownDescription": "Default permissions for the web search plugin\n#### This default permission set includes:\n\n- `allow-web-search`\n- `allow-web-fetch`"
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/src-tauri/plugins/tauri-plugin-websearch/rollup.config.js b/src-tauri/plugins/tauri-plugin-websearch/rollup.config.js
new file mode 100644
index 000000000..8b4768ff6
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/rollup.config.js
@@ -0,0 +1,31 @@
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { cwd } from 'node:process'
+import typescript from '@rollup/plugin-typescript'
+
+const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))
+
+export default {
+ input: 'guest-js/index.ts',
+ output: [
+ {
+ file: pkg.exports.import,
+ format: 'esm'
+ },
+ {
+ file: pkg.exports.require,
+ format: 'cjs'
+ }
+ ],
+ plugins: [
+ typescript({
+ declaration: true,
+ declarationDir: dirname(pkg.exports.import)
+ })
+ ],
+ external: [
+ /^@tauri-apps\/api/,
+ ...Object.keys(pkg.dependencies || {}),
+ ...Object.keys(pkg.peerDependencies || {})
+ ]
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/src/commands.rs b/src-tauri/plugins/tauri-plugin-websearch/src/commands.rs
new file mode 100644
index 000000000..2123e22e3
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/src/commands.rs
@@ -0,0 +1,64 @@
+use crate::provider::{clamp_count, create_provider, FetchedPage, SearchResult};
+use serde::Serialize;
+
+#[derive(Debug, Clone, Serialize, thiserror::Error)]
+#[error("WebSearchError: {message}")]
+pub struct WebSearchError {
+ pub message: String,
+}
+
+impl WebSearchError {
+ fn new(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ }
+ }
+}
+
+impl From<String> for WebSearchError {
+ fn from(message: String) -> Self {
+ Self::new(message)
+ }
+}
+
+/// Search the web and return normalized results. `provider` selects the backend
+/// (defaults to Exa); `api_key` (keyed backends) and `endpoint` (self-hosted
+/// backends) are forwarded to the chosen backend.
+#[tauri::command]
+pub async fn web_search(
+ query: String,
+ count: Option<u64>,
+ provider: Option<String>,
+ api_key: Option<String>,
+ endpoint: Option<String>,
+) -> Result<Vec<SearchResult>, WebSearchError> {
+ let query = query.trim();
+ if query.is_empty() {
+ return Err(WebSearchError::new("web_search 'query' must not be empty."));
+ }
+ let backend = create_provider(provider.as_deref(), api_key, endpoint)?;
+ let results = backend.search(query, clamp_count(count)).await?;
+ Ok(results)
+}
+
+/// Fetch a web page by URL and return normalized, bounded readable content.
+#[tauri::command]
+pub async fn web_fetch(
+ url: String,
+ provider: Option<String>,
+ api_key: Option<String>,
+ endpoint: Option<String>,
+) -> Result<FetchedPage, WebSearchError> {
+ let url = url.trim();
+ if url.is_empty() {
+ return Err(WebSearchError::new("web_fetch 'url' must not be empty."));
+ }
+ if !(url.starts_with("http://") || url.starts_with("https://")) {
+ return Err(WebSearchError::new(format!(
+ "web_fetch 'url' must be an http(s) URL, got: {url}"
+ )));
+ }
+ let backend = create_provider(provider.as_deref(), api_key, endpoint)?;
+ let page = backend.fetch(url).await?;
+ Ok(page)
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs b/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs
new file mode 100644
index 000000000..a1bad8928
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs
@@ -0,0 +1,20 @@
+use tauri::{
+ plugin::{Builder, TauriPlugin},
+ Runtime,
+};
+
+mod commands;
+pub mod provider;
+
+pub use commands::{web_fetch, web_search, WebSearchError};
+pub use provider::{FetchedPage, SearchResult};
+
+/// Initializes the web search plugin.
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ Builder::new("websearch")
+ .invoke_handler(tauri::generate_handler![
+ commands::web_search,
+ commands::web_fetch
+ ])
+ .build()
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs b/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs
new file mode 100644
index 000000000..ebba7f560
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs
@@ -0,0 +1,945 @@
+//! Native, provider-neutral web search backend.
+//!
+//! The `web_search` / `web_fetch` capability is defined by the [`SearchProvider`]
+//! trait; concrete backends implement it and are selected at call time by
+//! [`create_provider`]. Adding a backend is a new impl plus one match arm - the
+//! plugin command contract and the whole frontend stay unchanged.
+//!
+//! The only backend shipped today is [`ExaProvider`] (the default). Exa is a
+//! backend, never a product-facing identity:
+//!
+//! * Keyless (default): Exa's hosted endpoint at `https://mcp.exa.ai/mcp`
+//! answers over JSON-RPC with no API key.
+//! * Keyed (opt-in): when an Exa API key is supplied the structured REST API
+//! (`https://api.exa.ai`) is used instead, for normalized JSON and higher
+//! rate limits.
+//!
+//! Every backend normalizes into [`SearchResult`] / [`FetchedPage`] and bounds
+//! output size so tool results can't blow up the model's context.
+
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+
+const FETCH_MAX_CHARS: usize = 40_000;
+pub const SEARCH_DEFAULT_COUNT: u32 = 5;
+pub const SEARCH_MAX_COUNT: u32 = 20;
+const REQUEST_TIMEOUT_SECS: u64 = 30;
+
+const EXA_HOSTED_URL: &str = "https://mcp.exa.ai/mcp";
+const EXA_REST_SEARCH_URL: &str = "https://api.exa.ai/search";
+const EXA_REST_CONTENTS_URL: &str = "https://api.exa.ai/contents";
+
+const TAVILY_SEARCH_URL: &str = "https://api.tavily.com/search";
+const TAVILY_EXTRACT_URL: &str = "https://api.tavily.com/extract";
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct SearchResult {
+ pub title: String,
+ pub url: String,
+ pub snippet: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub published_at: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct FetchedPage {
+ pub url: String,
+ pub title: String,
+ pub content: String,
+ pub truncated: bool,
+}
+
+/// A pluggable web search backend. Implementors turn a query into normalized
+/// [`SearchResult`]s and a URL into a bounded [`FetchedPage`].
+#[async_trait]
+pub trait SearchProvider: Send + Sync {
+ async fn search(&self, query: &str, count: u32) -> Result<Vec<SearchResult>, String>;
+ async fn fetch(&self, url: &str) -> Result<FetchedPage, String>;
+}
+
+/// 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).
+pub fn create_provider(
+ provider: Option<&str>,
+ api_key: Option<String>,
+ endpoint: Option<String>,
+) -> Result<Box<dyn SearchProvider>, String> {
+ match provider.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
+ None | Some("") | Some("exa") => Ok(Box::new(ExaProvider::new(api_key)?)),
+ Some("tavily") => Ok(Box::new(TavilyProvider::new(api_key)?)),
+ Some("searxng") => Ok(Box::new(SearxngProvider::new(endpoint)?)),
+ Some(other) => Err(format!("Unknown web search provider '{other}'")),
+ }
+}
+
+fn require_key(provider: &str, api_key: Option<String>) -> Result<String, String> {
+ normalize_key(api_key).ok_or_else(|| format!("{provider} requires an API key"))
+}
+
+fn build_http_client(provider: &str) -> Result<reqwest::Client, String> {
+ reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECS))
+ .build()
+ .map_err(|e| format!("failed to build HTTP client for {provider}: {e}"))
+}
+
+/// Which Exa transport the adapter uses.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum ExaMode {
+ Hosted,
+ Rest(String),
+}
+
+fn normalize_key(api_key: Option<String>) -> Option<String> {
+ api_key.and_then(|v| {
+ let v = v.trim().to_string();
+ if v.is_empty() || v == "YOUR_EXA_API_KEY_HERE" {
+ None
+ } else {
+ Some(v)
+ }
+ })
+}
+
+/// Exa backend. Defaults to the keyless hosted endpoint; upgrades to the
+/// structured REST API when a key is supplied.
+pub struct ExaProvider {
+ mode: ExaMode,
+ client: reqwest::Client,
+}
+
+impl ExaProvider {
+ pub fn new(api_key: Option<String>) -> Result<Self, String> {
+ let mode = match normalize_key(api_key) {
+ Some(key) => ExaMode::Rest(key),
+ None => ExaMode::Hosted,
+ };
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECS))
+ .build()
+ .map_err(|e| format!("failed to build HTTP client for Exa: {e}"))?;
+ Ok(Self { mode, client })
+ }
+
+ async fn hosted_call(&self, tool: &str, arguments: Value) -> Result<String, String> {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": tool, "arguments": arguments }
+ });
+ let resp = self
+ .client
+ .post(EXA_HOSTED_URL)
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| format!("Exa request failed: {e}"))?;
+ let status = resp.status();
+ let text = resp
+ .text()
+ .await
+ .map_err(|e| format!("Exa: failed to read response body: {e}"))?;
+ if !status.is_success() {
+ return Err(format!(
+ "Exa failed with HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(400).collect::<String>()
+ ));
+ }
+ parse_hosted_result_text(&text)
+ }
+}
+
+#[async_trait]
+impl SearchProvider for ExaProvider {
+ async fn search(&self, query: &str, count: u32) -> Result<Vec<SearchResult>, String> {
+ match &self.mode {
+ ExaMode::Hosted => {
+ let text = self
+ .hosted_call(
+ "web_search_exa",
+ json!({ "query": query, "numResults": count }),
+ )
+ .await?;
+ Ok(parse_hosted_search_text(&text))
+ }
+ ExaMode::Rest(key) => {
+ let body = json!({
+ "query": query,
+ "type": "auto",
+ "numResults": count,
+ "contents": {
+ "text": { "maxCharacters": 800 },
+ "highlights": { "numSentences": 3, "highlightsPerUrl": 1 }
+ }
+ });
+ let resp = self
+ .client
+ .post(EXA_REST_SEARCH_URL)
+ .header("x-api-key", key)
+ .header("content-type", "application/json")
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| format!("Exa search request failed: {e}"))?;
+ let status = resp.status();
+ let text = resp
+ .text()
+ .await
+ .map_err(|e| format!("Exa search: failed to read response body: {e}"))?;
+ if !status.is_success() {
+ return Err(format!(
+ "Exa search failed with HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(400).collect::<String>()
+ ));
+ }
+ let parsed: Value = serde_json::from_str(&text)
+ .map_err(|e| format!("Exa search: invalid JSON response: {e}"))?;
+ Ok(normalize_exa_rest_search(&parsed))
+ }
+ }
+ }
+
+ async fn fetch(&self, url: &str) -> Result<FetchedPage, String> {
+ match &self.mode {
+ ExaMode::Hosted => {
+ let text = self
+ .hosted_call(
+ "web_fetch_exa",
+ json!({ "urls": [url], "maxCharacters": FETCH_MAX_CHARS }),
+ )
+ .await?;
+ Ok(parse_hosted_fetch_text(&text, url))
+ }
+ ExaMode::Rest(key) => {
+ let body = json!({ "ids": [url], "text": true });
+ let resp = self
+ .client
+ .post(EXA_REST_CONTENTS_URL)
+ .header("x-api-key", key)
+ .header("content-type", "application/json")
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| format!("Exa fetch request failed: {e}"))?;
+ let status = resp.status();
+ let text = resp
+ .text()
+ .await
+ .map_err(|e| format!("Exa fetch: failed to read response body: {e}"))?;
+ if !status.is_success() {
+ return Err(format!(
+ "Exa fetch failed with HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(400).collect::<String>()
+ ));
+ }
+ let parsed: Value = serde_json::from_str(&text)
+ .map_err(|e| format!("Exa fetch: invalid JSON response: {e}"))?;
+ normalize_exa_rest_fetch(&parsed, url)
+ }
+ }
+ }
+}
+
+fn parse_hosted_result_text(body: &str) -> Result<String, String> {
+ let json_str = body
+ .lines()
+ .find_map(|l| l.strip_prefix("data:").map(str::trim))
+ .unwrap_or_else(|| body.trim());
+ let parsed: Value = serde_json::from_str(json_str)
+ .map_err(|e| format!("Exa: invalid response payload: {e}"))?;
+ if let Some(err) = parsed.get("error") {
+ return Err(format!("Exa returned an error: {err}"));
+ }
+ let result = parsed
+ .get("result")
+ .ok_or("Exa response missing 'result'")?;
+ if result.get("isError").and_then(|v| v.as_bool()) == Some(true) {
+ return Err(format!(
+ "Exa tool call failed: {}",
+ result
+ .get("content")
+ .and_then(|c| c.as_array())
+ .and_then(|a| a.first())
+ .and_then(|c| c.get("text"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown error")
+ ));
+ }
+ let text = result
+ .get("content")
+ .and_then(|c| c.as_array())
+ .and_then(|a| a.first())
+ .and_then(|c| c.get("text"))
+ .and_then(|v| v.as_str())
+ .ok_or("Exa response had no text content")?;
+ Ok(text.to_string())
+}
+
+fn parse_hosted_search_text(text: &str) -> Vec<SearchResult> {
+ let mut out = Vec::new();
+ for block in text.split("\n---\n") {
+ let block = block.trim();
+ if block.is_empty() {
+ continue;
+ }
+ let mut title = String::new();
+ let mut url = String::new();
+ let mut published: Option<String> = None;
+ let mut in_highlights = false;
+ let mut snippet_lines: Vec<String> = Vec::new();
+ for line in block.lines() {
+ let trimmed = line.trim();
+ if let Some(v) = trimmed.strip_prefix("Title:") {
+ title = v.trim().to_string();
+ } else if let Some(v) = trimmed.strip_prefix("URL:") {
+ url = v.trim().to_string();
+ } else if let Some(v) = trimmed.strip_prefix("Published:") {
+ let v = v.trim();
+ if !v.is_empty() && v != "N/A" {
+ published = Some(v.to_string());
+ }
+ } else if trimmed.starts_with("Author:") {
+ // Ignored in the normalized contract.
+ } else if trimmed.starts_with("Highlights:") {
+ in_highlights = true;
+ } else if in_highlights && trimmed != "..." && !trimmed.is_empty() {
+ snippet_lines.push(trimmed.to_string());
+ }
+ }
+ if url.is_empty() && title.is_empty() {
+ continue;
+ }
+ let snippet = clip_chars(&snippet_lines.join(" "), 500);
+ out.push(SearchResult {
+ title,
+ url,
+ snippet,
+ published_at: published,
+ });
+ }
+ out
+}
+
+fn parse_hosted_fetch_text(text: &str, requested_url: &str) -> FetchedPage {
+ let mut title = String::new();
+ let mut url = requested_url.to_string();
+ let mut body_start = 0usize;
+ for (i, line) in text.lines().enumerate() {
+ let trimmed = line.trim();
+ if i == 0 && trimmed.starts_with("# ") {
+ title = trimmed[2..].trim().to_string();
+ } else if let Some(v) = trimmed.strip_prefix("URL:") {
+ url = v.trim().to_string();
+ body_start = i + 1;
+ break;
+ } else if i > 2 {
+ break;
+ }
+ }
+ let body: String = text
+ .lines()
+ .skip(body_start)
+ .collect::<Vec<_>>()
+ .join("\n")
+ .trim()
+ .to_string();
+ let source = if body.is_empty() { text.trim() } else { &body };
+ let (content, truncated) = bound_text(source);
+ FetchedPage {
+ url,
+ title,
+ content,
+ truncated,
+ }
+}
+
+fn normalize_exa_rest_search(body: &Value) -> Vec<SearchResult> {
+ let Some(results) = body.get("results").and_then(|v| v.as_array()) else {
+ return Vec::new();
+ };
+ results
+ .iter()
+ .map(|r| {
+ let title = r
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let url = r
+ .get("url")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let snippet = r
+ .get("highlights")
+ .and_then(|v| v.as_array())
+ .and_then(|a| a.first())
+ .and_then(|v| v.as_str())
+ .map(str::to_string)
+ .or_else(|| {
+ r.get("text")
+ .and_then(|v| v.as_str())
+ .map(|t| clip_chars(t, 300))
+ })
+ .unwrap_or_default();
+ let published_at = r
+ .get("publishedDate")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ SearchResult {
+ title,
+ url,
+ snippet,
+ published_at,
+ }
+ })
+ .collect()
+}
+
+fn normalize_exa_rest_fetch(body: &Value, requested_url: &str) -> Result<FetchedPage, String> {
+ let first = body
+ .get("results")
+ .and_then(|v| v.as_array())
+ .and_then(|a| a.first())
+ .ok_or_else(|| format!("Exa fetch returned no content for {requested_url}"))?;
+ let url = first
+ .get("url")
+ .and_then(|v| v.as_str())
+ .unwrap_or(requested_url)
+ .to_string();
+ let title = first
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let raw = first.get("text").and_then(|v| v.as_str()).unwrap_or("");
+ let (content, truncated) = bound_text(raw);
+ Ok(FetchedPage {
+ url,
+ title,
+ content,
+ truncated,
+ })
+}
+
+/// Tavily backend (key-only). Uses the structured `/search` and `/extract`
+/// REST endpoints, authenticated with a bearer token.
+pub struct TavilyProvider {
+ api_key: String,
+ client: reqwest::Client,
+}
+
+impl TavilyProvider {
+ pub fn new(api_key: Option<String>) -> Result<Self, String> {
+ Ok(Self {
+ api_key: require_key("Tavily", api_key)?,
+ client: build_http_client("Tavily")?,
+ })
+ }
+
+ async fn post(&self, url: &str, body: Value) -> Result<Value, String> {
+ let resp = self
+ .client
+ .post(url)
+ .bearer_auth(&self.api_key)
+ .header("content-type", "application/json")
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| format!("Tavily request failed: {e}"))?;
+ let status = resp.status();
+ let text = resp
+ .text()
+ .await
+ .map_err(|e| format!("Tavily: failed to read response body: {e}"))?;
+ if !status.is_success() {
+ return Err(format!(
+ "Tavily failed with HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(400).collect::<String>()
+ ));
+ }
+ serde_json::from_str(&text).map_err(|e| format!("Tavily: invalid JSON response: {e}"))
+ }
+}
+
+#[async_trait]
+impl SearchProvider for TavilyProvider {
+ async fn search(&self, query: &str, count: u32) -> Result<Vec<SearchResult>, String> {
+ let parsed = self
+ .post(
+ TAVILY_SEARCH_URL,
+ json!({ "query": query, "max_results": count }),
+ )
+ .await?;
+ Ok(normalize_tavily_search(&parsed))
+ }
+
+ async fn fetch(&self, url: &str) -> Result<FetchedPage, String> {
+ let parsed = self
+ .post(TAVILY_EXTRACT_URL, json!({ "urls": [url] }))
+ .await?;
+ normalize_tavily_extract(&parsed, url)
+ }
+}
+
+fn normalize_tavily_search(body: &Value) -> Vec<SearchResult> {
+ let Some(results) = body.get("results").and_then(|v| v.as_array()) else {
+ return Vec::new();
+ };
+ results
+ .iter()
+ .map(|r| {
+ let title = r.get("title").and_then(|v| v.as_str()).unwrap_or("");
+ let url = r.get("url").and_then(|v| v.as_str()).unwrap_or("");
+ let snippet = r
+ .get("content")
+ .and_then(|v| v.as_str())
+ .map(|t| clip_chars(t, 500))
+ .unwrap_or_default();
+ let published_at = r
+ .get("published_date")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ SearchResult {
+ title: title.to_string(),
+ url: url.to_string(),
+ snippet,
+ published_at,
+ }
+ })
+ .collect()
+}
+
+fn normalize_tavily_extract(body: &Value, requested_url: &str) -> Result<FetchedPage, String> {
+ let first = body
+ .get("results")
+ .and_then(|v| v.as_array())
+ .and_then(|a| a.first())
+ .ok_or_else(|| format!("Tavily returned no content for {requested_url}"))?;
+ let url = first
+ .get("url")
+ .and_then(|v| v.as_str())
+ .unwrap_or(requested_url)
+ .to_string();
+ let raw = first
+ .get("raw_content")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let (content, truncated) = bound_text(raw);
+ Ok(FetchedPage {
+ url,
+ title: String::new(),
+ content,
+ truncated,
+ })
+}
+
+/// SearXNG backend (self-hosted, key-less). Queries a user-supplied instance's
+/// JSON search API. SearXNG has no content-extraction endpoint, so `fetch` does
+/// a plain HTTP GET of the URL and returns the bounded raw response body.
+pub struct SearxngProvider {
+ base_url: String,
+ client: reqwest::Client,
+}
+
+impl SearxngProvider {
+ pub fn new(endpoint: Option<String>) -> Result<Self, String> {
+ let base = endpoint
+ .map(|e| e.trim().trim_end_matches('/').to_string())
+ .filter(|e| !e.is_empty())
+ .ok_or("SearXNG requires an instance URL")?;
+ if !(base.starts_with("http://") || base.starts_with("https://")) {
+ return Err(format!(
+ "SearXNG instance URL must be an http(s) URL, got: {base}"
+ ));
+ }
+ Ok(Self {
+ base_url: base,
+ client: build_http_client("SearXNG")?,
+ })
+ }
+}
+
+#[async_trait]
+impl SearchProvider for SearxngProvider {
+ async fn search(&self, query: &str, count: u32) -> Result<Vec<SearchResult>, String> {
+ let resp = self
+ .client
+ .get(format!("{}/search", self.base_url))
+ .query(&[("q", query), ("format", "json")])
+ .send()
+ .await
+ .map_err(|e| format!("SearXNG request failed: {e}"))?;
+ let status = resp.status();
+ let text = resp
+ .text()
+ .await
+ .map_err(|e| format!("SearXNG: failed to read response body: {e}"))?;
+ if !status.is_success() {
+ return Err(format!(
+ "SearXNG failed with HTTP {}: {}",
+ status.as_u16(),
+ text.chars().take(400).collect::<String>()
+ ));
+ }
+ let parsed: Value = serde_json::from_str(&text).map_err(|e| {
+ format!("SearXNG: invalid JSON response (is the JSON API enabled?): {e}")
+ })?;
+ Ok(normalize_searxng_search(&parsed, count))
+ }
+
+ async fn fetch(&self, url: &str) -> Result<FetchedPage, String> {
+ let resp = self
+ .client
+ .get(url)
+ .send()
+ .await
+ .map_err(|e| format!("SearXNG fetch request failed: {e}"))?;
+ let status = resp.status();
+ let body = resp
+ .text()
+ .await
+ .map_err(|e| format!("SearXNG fetch: failed to read response body: {e}"))?;
+ if !status.is_success() {
+ return Err(format!(
+ "SearXNG fetch failed with HTTP {}",
+ status.as_u16()
+ ));
+ }
+ let title = extract_html_title(&body).unwrap_or_default();
+ let (content, truncated) = bound_text(&body);
+ Ok(FetchedPage {
+ url: url.to_string(),
+ title,
+ content,
+ truncated,
+ })
+ }
+}
+
+fn normalize_searxng_search(body: &Value, count: u32) -> Vec<SearchResult> {
+ let Some(results) = body.get("results").and_then(|v| v.as_array()) else {
+ return Vec::new();
+ };
+ results
+ .iter()
+ .take(count as usize)
+ .map(|r| {
+ let title = r.get("title").and_then(|v| v.as_str()).unwrap_or("");
+ let url = r.get("url").and_then(|v| v.as_str()).unwrap_or("");
+ let snippet = r
+ .get("content")
+ .and_then(|v| v.as_str())
+ .map(|t| clip_chars(t, 500))
+ .unwrap_or_default();
+ let published_at = r
+ .get("publishedDate")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ SearchResult {
+ title: title.to_string(),
+ url: url.to_string(),
+ snippet,
+ published_at,
+ }
+ })
+ .collect()
+}
+
+fn extract_html_title(html: &str) -> Option<String> {
+ let lower = html.to_ascii_lowercase();
+ let start = lower.find("<title")?;
+ let open_end = lower[start..].find('>')? + start + 1;
+ let close = lower[open_end..].find("</title>")? + open_end;
+ let title = html[open_end..close].trim();
+ if title.is_empty() {
+ None
+ } else {
+ Some(title.to_string())
+ }
+}
+
+fn clip_chars(s: &str, max: usize) -> String {
+ if s.chars().count() <= max {
+ s.to_string()
+ } else {
+ s.chars().take(max).collect()
+ }
+}
+
+fn bound_text(s: &str) -> (String, bool) {
+ if s.chars().count() <= FETCH_MAX_CHARS {
+ (s.to_string(), false)
+ } else {
+ (s.chars().take(FETCH_MAX_CHARS).collect(), true)
+ }
+}
+
+pub fn clamp_count(requested: Option<u64>) -> u32 {
+ match requested {
+ Some(0) | None => SEARCH_DEFAULT_COUNT,
+ Some(n) => (n as u32).min(SEARCH_MAX_COUNT),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn clamp_count_defaults_and_caps() {
+ assert_eq!(clamp_count(None), SEARCH_DEFAULT_COUNT);
+ assert_eq!(clamp_count(Some(0)), SEARCH_DEFAULT_COUNT);
+ assert_eq!(clamp_count(Some(3)), 3);
+ assert_eq!(clamp_count(Some(1000)), SEARCH_MAX_COUNT);
+ }
+
+ #[test]
+ fn empty_key_selects_hosted() {
+ let p = ExaProvider::new(None).unwrap();
+ assert_eq!(p.mode, ExaMode::Hosted);
+ let p = ExaProvider::new(Some(" ".into())).unwrap();
+ assert_eq!(p.mode, ExaMode::Hosted);
+ let p = ExaProvider::new(Some("YOUR_EXA_API_KEY_HERE".into())).unwrap();
+ assert_eq!(p.mode, ExaMode::Hosted);
+ }
+
+ #[test]
+ fn real_key_selects_rest() {
+ let p = ExaProvider::new(Some("abc123".into())).unwrap();
+ assert_eq!(p.mode, ExaMode::Rest("abc123".into()));
+ }
+
+ #[test]
+ fn create_provider_defaults_to_exa() {
+ assert!(create_provider(None, None, None).is_ok());
+ assert!(create_provider(Some(""), None, None).is_ok());
+ assert!(create_provider(Some("Exa"), None, None).is_ok());
+ }
+
+ #[test]
+ fn create_provider_rejects_unknown() {
+ match create_provider(Some("brave"), None, None) {
+ Ok(_) => panic!("expected unknown provider to error"),
+ Err(e) => assert!(e.contains("brave")),
+ }
+ }
+
+ #[test]
+ fn create_provider_tavily_requires_key() {
+ match create_provider(Some("tavily"), None, None) {
+ Ok(_) => panic!("expected Tavily to require a key"),
+ Err(e) => assert!(e.contains("Tavily")),
+ }
+ assert!(create_provider(Some("tavily"), Some("tvly-abc".into()), None).is_ok());
+ }
+
+ #[test]
+ fn create_provider_searxng_requires_valid_url() {
+ match create_provider(Some("searxng"), None, None) {
+ Ok(_) => panic!("expected SearXNG to require an instance URL"),
+ Err(e) => assert!(e.contains("SearXNG")),
+ }
+ match create_provider(Some("searxng"), None, Some("example.com".into())) {
+ Ok(_) => panic!("expected SearXNG to reject a scheme-less URL"),
+ Err(e) => assert!(e.contains("http")),
+ }
+ assert!(
+ create_provider(Some("searxng"), None, Some("https://searx.example/".into())).is_ok()
+ );
+ }
+
+ #[test]
+ fn normalize_searxng_search_maps_and_caps() {
+ let body = json!({
+ "results": [
+ { "title": "One", "url": "https://a.example", "content": "first", "publishedDate": "2024-01-01" },
+ { "title": "Two", "url": "https://b.example", "content": "second" },
+ { "title": "Three", "url": "https://c.example", "content": "third" }
+ ]
+ });
+ let results = normalize_searxng_search(&body, 2);
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].url, "https://a.example");
+ assert_eq!(results[0].published_at.as_deref(), Some("2024-01-01"));
+ assert!(results[1].published_at.is_none());
+ }
+
+ #[test]
+ fn extract_html_title_reads_title_tag() {
+ assert_eq!(
+ extract_html_title("<html><head><TITLE>Hello</TITLE></head>").as_deref(),
+ Some("Hello")
+ );
+ assert!(extract_html_title("<html>no title</html>").is_none());
+ }
+
+ #[test]
+ fn normalize_tavily_search_maps_contract() {
+ let body = json!({
+ "results": [
+ {
+ "title": "Example",
+ "url": "https://example.com",
+ "content": "A short excerpt.",
+ "published_date": "2024-05-01"
+ },
+ { "title": "No date", "url": "https://example.org", "content": "Body." }
+ ]
+ });
+ let results = normalize_tavily_search(&body);
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].url, "https://example.com");
+ assert_eq!(results[0].snippet, "A short excerpt.");
+ assert_eq!(results[0].published_at.as_deref(), Some("2024-05-01"));
+ assert!(results[1].published_at.is_none());
+ }
+
+ #[test]
+ fn normalize_tavily_search_empty_is_empty() {
+ assert!(normalize_tavily_search(&json!({})).is_empty());
+ assert!(normalize_tavily_search(&json!({"results": []})).is_empty());
+ }
+
+ #[test]
+ fn normalize_tavily_extract_reads_raw_content() {
+ let body = json!({
+ "results": [
+ { "url": "https://example.com", "raw_content": "hello world" }
+ ]
+ });
+ let page = normalize_tavily_extract(&body, "https://example.com").unwrap();
+ assert!(page.title.is_empty());
+ assert_eq!(page.content, "hello world");
+ assert!(!page.truncated);
+ }
+
+ #[test]
+ fn normalize_tavily_extract_no_results_errors() {
+ assert!(normalize_tavily_extract(&json!({"results": []}), "u").is_err());
+ }
+
+ #[test]
+ fn parse_hosted_result_text_reads_sse_frame() {
+ let sse = "event: message\ndata: {\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"hello\"}]}}\n\n";
+ assert_eq!(parse_hosted_result_text(sse).unwrap(), "hello");
+ }
+
+ #[test]
+ fn parse_hosted_result_text_reads_raw_json() {
+ let raw = "{\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"hi\"}]}}";
+ assert_eq!(parse_hosted_result_text(raw).unwrap(), "hi");
+ }
+
+ #[test]
+ fn parse_hosted_result_text_surfaces_errors() {
+ let err = "{\"error\":{\"code\":-32000,\"message\":\"boom\"}}";
+ assert!(parse_hosted_result_text(err).is_err());
+ let tool_err = "{\"result\":{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":\"bad\"}]}}";
+ assert!(parse_hosted_result_text(tool_err).unwrap_err().contains("bad"));
+ }
+
+ #[test]
+ fn parse_hosted_search_text_maps_contract() {
+ let text = "Title: Paris | Britannica\nURL: https://www.britannica.com/place/Paris\nPublished: 1998-07-20T00:00:00.000Z\nAuthor: N/A\nHighlights:\nParis is the capital of France.\n...\nSecond highlight.\n---\nTitle: Paris\nURL: https://en.wikipedia.org/wiki/Paris\nPublished: N/A\nAuthor: N/A\nHighlights:\nParis is the capital and largest city of France.";
+ let results = parse_hosted_search_text(text);
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].title, "Paris | Britannica");
+ assert_eq!(results[0].url, "https://www.britannica.com/place/Paris");
+ assert_eq!(
+ results[0].published_at.as_deref(),
+ Some("1998-07-20T00:00:00.000Z")
+ );
+ assert!(results[0].snippet.contains("capital of France"));
+ assert!(!results[0].snippet.contains("..."));
+ assert!(results[1].published_at.is_none());
+ assert_eq!(results[1].url, "https://en.wikipedia.org/wiki/Paris");
+ }
+
+ #[test]
+ fn parse_hosted_search_text_empty_is_empty() {
+ assert!(parse_hosted_search_text("").is_empty());
+ assert!(parse_hosted_search_text(" \n ").is_empty());
+ }
+
+ #[test]
+ fn parse_hosted_fetch_text_extracts_title_url_body() {
+ let text = "# Paris\nURL: https://en.wikipedia.org/wiki/Paris\n\nParis is the capital and largest city of France.";
+ let page = parse_hosted_fetch_text(text, "https://en.wikipedia.org/wiki/Paris");
+ assert_eq!(page.title, "Paris");
+ assert_eq!(page.url, "https://en.wikipedia.org/wiki/Paris");
+ assert!(page.content.starts_with("Paris is the capital"));
+ assert!(!page.truncated);
+ }
+
+ #[test]
+ fn parse_hosted_fetch_text_truncates_large_body() {
+ let big = "a".repeat(FETCH_MAX_CHARS + 100);
+ let text = format!("# T\nURL: https://x\n\n{big}");
+ let page = parse_hosted_fetch_text(&text, "https://x");
+ assert!(page.truncated);
+ assert_eq!(page.content.chars().count(), FETCH_MAX_CHARS);
+ }
+
+ #[test]
+ fn normalize_exa_rest_search_maps_contract() {
+ let body = json!({
+ "results": [
+ {
+ "title": "Example",
+ "url": "https://example.com",
+ "highlights": ["Short result excerpt"],
+ "publishedDate": "2024-01-02T00:00:00.000Z"
+ },
+ {
+ "title": "No highlight",
+ "url": "https://example.org",
+ "text": "Body text fallback used as snippet."
+ }
+ ]
+ });
+ let results = normalize_exa_rest_search(&body);
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].snippet, "Short result excerpt");
+ assert_eq!(
+ results[0].published_at.as_deref(),
+ Some("2024-01-02T00:00:00.000Z")
+ );
+ assert!(results[1].snippet.starts_with("Body text fallback"));
+ assert!(results[1].published_at.is_none());
+ }
+
+ #[test]
+ fn normalize_exa_rest_search_empty_is_empty() {
+ assert!(normalize_exa_rest_search(&json!({})).is_empty());
+ assert!(normalize_exa_rest_search(&json!({"results": []})).is_empty());
+ }
+
+ #[test]
+ fn normalize_exa_rest_fetch_bounds_and_titles() {
+ let body = json!({
+ "results": [ { "url": "https://example.com", "title": "T", "text": "hello world" } ]
+ });
+ let page = normalize_exa_rest_fetch(&body, "https://example.com").unwrap();
+ assert_eq!(page.title, "T");
+ assert_eq!(page.content, "hello world");
+ assert!(!page.truncated);
+ }
+
+ #[test]
+ fn normalize_exa_rest_fetch_no_results_errors() {
+ assert!(normalize_exa_rest_fetch(&json!({"results": []}), "u").is_err());
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-websearch/tsconfig.json b/src-tauri/plugins/tauri-plugin-websearch/tsconfig.json
new file mode 100644
index 000000000..059112270
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-websearch/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "compilerOptions": {
+ "target": "es2021",
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "skipLibCheck": true,
+ "strict": true,
+ "noUnusedLocals": true,
+ "noImplicitAny": true,
+ "noEmit": true
+ },
+ "include": ["guest-js/*.ts"],
+ "exclude": ["dist-js", "node_modules"]
+}
diff --git a/src-tauri/plugins/yarn.lock b/src-tauri/plugins/yarn.lock
index ec6cad55b..29b7f79d1 100644
--- a/src-tauri/plugins/yarn.lock
+++ b/src-tauri/plugins/yarn.lock
@@ -88,6 +88,18 @@ __metadata:
languageName: unknown
linkType: soft
+"@janhq/tauri-plugin-websearch-api@workspace:tauri-plugin-websearch":
+ version: 0.0.0-use.local
+ resolution: "@janhq/tauri-plugin-websearch-api@workspace:tauri-plugin-websearch"
+ dependencies:
+ "@rollup/plugin-typescript": "npm:^12.0.0"
+ "@tauri-apps/api": "npm:>=2.0.0-beta.6"
+ rollup: "npm:^4.9.6"
+ tslib: "npm:^2.6.2"
+ typescript: "npm:^5.3.3"
+ languageName: unknown
+ linkType: soft
+
"@npmcli/agent@npm:^3.0.0":
version: 3.0.0
resolution: "@npmcli/agent@npm:3.0.0"
diff --git a/src-tauri/src/core/mcp/constants.rs b/src-tauri/src/core/mcp/constants.rs
index f605d441b..55941f379 100644
--- a/src-tauri/src/core/mcp/constants.rs
+++ b/src-tauri/src/core/mcp/constants.rs
@@ -20,14 +20,6 @@ pub const DEFAULT_MCP_CONFIG: &str = r#"{
"active": false,
"official": true
},
- "exa": {
- "type": "http",
- "url": "https://mcp.exa.ai/mcp",
- "command": "",
- "args": [],
- "env": {},
- "active": true
- },
"browsermcp": {
"command": "npx",
"args": ["@browsermcp/mcp"],
diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rs
index 61f31c607..55762ff83 100644
--- a/src-tauri/src/core/mcp/tests.rs
+++ b/src-tauri/src/core/mcp/tests.rs
@@ -606,7 +606,6 @@ fn test_default_mcp_config_parses_as_valid_json() {
// Spot-check known servers
assert!(value["mcpServers"]["fetch"].is_object());
assert_eq!(value["mcpServers"]["fetch"]["command"], "uvx");
- assert_eq!(value["mcpServers"]["exa"]["type"], "http");
assert_eq!(
value["mcpSettings"]["toolCallTimeoutSeconds"],
super::constants::DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS
diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rs
index e6fdfcfa2..c5093aeec 100644
--- a/src-tauri/src/core/setup.rs
+++ b/src-tauri/src/core/setup.rs
@@ -61,11 +61,17 @@ pub fn migrate_mcp_servers(
}
if mcp_version < 3 {
log::info!("Migrating MCP schema version 3: Updating Exa to streamable HTTP");
- if let Err(e) = migrate_exa_to_http(app_handle) {
+ if let Err(e) = migrate_exa_to_http(app_handle.clone()) {
log::error!("Failed to migrate Exa to HTTP: {e}");
}
}
- store.set("mcp_version", 3);
+ if mcp_version < 4 {
+ log::info!("Migrating MCP schema version 4: Removing default Exa MCP (native web search cutover)");
+ if let Err(e) = remove_exa_server(app_handle) {
+ log::error!("Failed to remove Exa MCP server: {e}");
+ }
+ }
+ store.set("mcp_version", 4);
store.save().expect("Failed to save store");
Ok(())
}
@@ -103,6 +109,50 @@ fn migrate_exa_to_http(app_handle: tauri::AppHandle) -> Result<(), String> {
Ok(())
}
+/// One-time cutover to native web search: drop the default Exa MCP server so the
+/// built-in web_search/web_fetch tools own web search. Only removes the entry if
+/// it is still the inactive default (hosted HTTP endpoint, no API key); a user who
+/// activated it or supplied their own key keeps their configuration.
+fn remove_exa_server(app_handle: tauri::AppHandle) -> Result<(), String> {
+ let config_path = get_jan_data_folder_path(app_handle).join("mcp_config.json");
+ if !config_path.exists() {
+ return Ok(());
+ }
+ let config_str =
+ fs::read_to_string(&config_path).map_err(|e| format!("Failed to read MCP config: {e}"))?;
+ let mut config: serde_json::Value = serde_json::from_str(&config_str)
+ .map_err(|e| format!("Failed to parse MCP config: {e}"))?;
+
+ let Some(servers) = config.get_mut("mcpServers").and_then(|s| s.as_object_mut()) else {
+ return Ok(());
+ };
+
+ let is_default_exa = servers
+ .get("exa")
+ .and_then(|exa| exa.as_object())
+ .map(|exa| {
+ let inactive = exa.get("active").and_then(|v| v.as_bool()) != Some(true);
+ let no_key = exa
+ .get("env")
+ .and_then(|env| env.as_object())
+ .map(|env| env.is_empty())
+ .unwrap_or(true);
+ inactive && no_key
+ })
+ .unwrap_or(false);
+
+ if is_default_exa {
+ servers.remove("exa");
+ fs::write(
+ &config_path,
+ serde_json::to_string_pretty(&config)
+ .map_err(|e| format!("Failed to serialize MCP config: {e}"))?,
+ )
+ .map_err(|e| format!("Failed to write MCP config: {e}"))?;
+ }
+ Ok(())
+}
+
/// Install/update the bundled `jan` CLI binary.
///
/// - `version_changed`: pass `true` whenever the app version has changed (i.e. after an update).
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 4d272fce9..f841bb99e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -236,7 +236,8 @@ pub fn run() {
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_llamacpp::init())
.plugin(tauri_plugin_vector_db::init())
- .plugin(tauri_plugin_rag::init());
+ .plugin(tauri_plugin_rag::init())
+ .plugin(tauri_plugin_websearch::init());
#[cfg(feature = "deep-link")]
{
diff --git a/web-app/package.json b/web-app/package.json
index b7261b676..4ed1d76f2 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -25,6 +25,7 @@
"@janhq/core": "workspace:*",
"@janhq/interfaces": "0.0.2",
"@janhq/tauri-plugin-llamacpp-api": "link:../src-tauri/plugins/tauri-plugin-llamacpp",
+ "@janhq/tauri-plugin-websearch-api": "link:../src-tauri/plugins/tauri-plugin-websearch",
"@radix-ui/react-accordion": "1.2.11",
"@radix-ui/react-avatar": "1.1.10",
"@radix-ui/react-collapsible": "^1.1.12",
diff --git a/web-app/src/components/Citations.tsx b/web-app/src/components/Citations.tsx
index 71478f3c5..d5ff6bf9b 100644
--- a/web-app/src/components/Citations.tsx
+++ b/web-app/src/components/Citations.tsx
@@ -105,7 +105,11 @@ const WebCitationItem = memo(({ c }: { c: WebCitation }) => {
<li className="rounded-md border bg-card/40 px-3 py-2 text-xs">
<div className="flex items-center gap-2">
{c.favicon ? (
- <img src={c.favicon} alt="" className="size-3.5 rounded-sm" />
+ <img
+ src={c.favicon}
+ alt=""
+ className="size-4 shrink-0 rounded-full border border-border/50 bg-white object-contain"
+ />
) : (
<GlobeIcon className="size-3.5 shrink-0 text-muted-foreground" />
)}
diff --git a/web-app/src/components/WebCitationChip.tsx b/web-app/src/components/WebCitationChip.tsx
new file mode 100644
index 000000000..3af7b4671
--- /dev/null
+++ b/web-app/src/components/WebCitationChip.tsx
@@ -0,0 +1,76 @@
+import { memo } from 'react'
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from '@/components/ui/hover-card'
+import { useWebCitationStore } from '@/stores/web-citation-store'
+import { cn } from '@/lib/utils'
+
+const hostOf = (url: string) => {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '')
+ } catch {
+ return url
+ }
+}
+
+const faviconOf = (host: string) =>
+ `https://www.google.com/s2/favicons?domain=${host}&sz=64`
+
+export const WebCitationChip = memo(
+ ({ messageId, url }: { messageId?: string; url: string }) => {
+ const citation = useWebCitationStore((s) =>
+ messageId ? s.byMessageId[messageId]?.[url] : undefined
+ )
+ const host = hostOf(url)
+ const favicon = citation?.favicon || faviconOf(host)
+ return (
+ <HoverCard openDelay={80} closeDelay={120}>
+ <HoverCardTrigger asChild>
+ <a
+ href={url}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="mx-0.5 inline-flex translate-y-[-0.15em] align-baseline no-underline"
+ title={citation?.title || url}
+ >
+ <img
+ src={favicon}
+ alt=""
+ className="inline-block size-3.5 rounded-full border border-border/60 bg-white object-contain hover:ring-2 hover:ring-primary/40"
+ />
+ </a>
+ </HoverCardTrigger>
+ <HoverCardContent
+ align="start"
+ side="top"
+ className="w-72 space-y-2 p-3 text-xs"
+ >
+ <div className="flex items-center gap-2">
+ <img
+ src={favicon}
+ alt=""
+ className="size-4 shrink-0 rounded-full border border-border/60 bg-white object-contain"
+ />
+ <span className="truncate text-muted-foreground">{host}</span>
+ </div>
+ <a
+ href={url}
+ target="_blank"
+ rel="noreferrer noopener"
+ className={cn('block truncate font-medium hover:underline')}
+ >
+ {citation?.title || host}
+ </a>
+ {citation?.text && (
+ <p className="line-clamp-4 whitespace-pre-wrap leading-relaxed text-muted-foreground">
+ {citation.text}
+ </p>
+ )}
+ </HoverCardContent>
+ </HoverCard>
+ )
+ }
+)
+WebCitationChip.displayName = 'WebCitationChip'
diff --git a/web-app/src/components/WebSourcesRow.tsx b/web-app/src/components/WebSourcesRow.tsx
new file mode 100644
index 000000000..5537e9355
--- /dev/null
+++ b/web-app/src/components/WebSourcesRow.tsx
@@ -0,0 +1,73 @@
+import { memo, useMemo, useState } from 'react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { ChevronRightIcon } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { Citations, type WebCitation } from '@/components/Citations'
+
+const hostOf = (url: string) => {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '')
+ } catch {
+ return url
+ }
+}
+
+const faviconOf = (url: string) =>
+ `https://www.google.com/s2/favicons?domain=${hostOf(url)}&sz=64`
+
+export const WebSourcesRow = memo(
+ ({ citations }: { citations: WebCitation[] }) => {
+ const { t } = useTranslation()
+ const [expanded, setExpanded] = useState(false)
+
+ const unique = useMemo(() => {
+ const seen = new Set<string>()
+ const out: WebCitation[] = []
+ for (const c of citations) {
+ if (seen.has(c.url)) continue
+ seen.add(c.url)
+ out.push(c)
+ }
+ return out
+ }, [citations])
+
+ if (!unique.length) return null
+
+ const preview = unique.slice(0, 4)
+
+ return (
+ <div className="mt-3">
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="inline-flex items-center gap-2 rounded-full border bg-card/40 py-1 pl-1.5 pr-2.5 text-xs text-muted-foreground transition-colors hover:bg-card/70"
+ aria-expanded={expanded}
+ >
+ <span className="flex -space-x-1.5">
+ {preview.map((c) => (
+ <img
+ key={c.url}
+ src={c.favicon || faviconOf(c.url)}
+ alt=""
+ className="size-4 rounded-full border border-border/60 bg-white object-contain"
+ />
+ ))}
+ </span>
+ <span className="font-medium">
+ {t('chat:webSources', { count: unique.length })}
+ </span>
+ <ChevronRightIcon
+ className={cn(
+ 'size-3 shrink-0 transition-transform',
+ expanded && 'rotate-90'
+ )}
+ />
+ </button>
+ {expanded && (
+ <Citations payload={{ kind: 'web', citations: unique }} />
+ )}
+ </div>
+ )
+ }
+)
+WebSourcesRow.displayName = 'WebSourcesRow'
diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.ts
index 1573dbbb2..9fd9fd60e 100644
--- a/web-app/src/constants/localStorage.ts
+++ b/web-app/src/constants/localStorage.ts
@@ -10,6 +10,7 @@ export const localStorageKey = {
settingCodeBlock: 'setting-code-block',
settingLocalApiServer: 'setting-local-api-server',
settingProxyConfig: 'setting-proxy-config',
+ settingWebSearch: 'setting-web-search',
settingHardware: 'setting-hardware',
settingVulkan: 'setting-vulkan',
productAnalyticPrompt: 'productAnalyticPrompt',
diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.ts
index 9d22cd381..2e36dddb6 100644
--- a/web-app/src/constants/routes.ts
+++ b/web-app/src/constants/routes.ts
@@ -17,6 +17,7 @@ export const route = {
local_api_server: '/settings/local-api-server',
mcp_servers: '/settings/mcp-servers',
https_proxy: '/settings/https-proxy',
+ web_search: '/settings/web-search',
hardware: '/settings/hardware',
assistant: '/settings/assistant',
claude_code: '/settings/claude-code',
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 0d6faa789..3ce850e8d 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -31,7 +31,7 @@ import {
IconX,
IconPaperclip,
IconLoader2,
- IconWorld,
+ IconWorldSearch,
IconBrandChrome,
} from '@tabler/icons-react'
import { generateId } from 'ai'
@@ -100,6 +100,7 @@ import {
import JanBrowserExtensionDialog from '@/containers/dialogs/JanBrowserExtensionDialog'
import { useJanBrowserExtension } from '@/hooks/useJanBrowserExtension'
import { useAgentMode } from '@/hooks/useAgentMode'
+import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
type ChatInputProps = {
className?: string
@@ -183,6 +184,8 @@ const ChatInput = memo(function ChatInput({
// When projectId is present, treat as normal chat (disable agent mode UI)
const effectiveAgentMode = isAgentMode && !projectId
const toggleAgentMode = useAgentMode((state) => state.toggleAgentMode)
+ const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)
+ const setWebSearchEnabled = useWebSearchConfig((s) => s.setWebSearchEnabled)
const handleAgentToggle = useCallback(() => {
toggleAgentMode(agentModeKey)
@@ -2215,18 +2218,30 @@ const ChatInput = memo(function ChatInput({
</Tooltip>
)}
- {!effectiveAgentMode && selectedModel?.capabilities?.includes('web_search') && (
+ {!effectiveAgentMode && selectedModel?.capabilities?.includes('tools') && (
<Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <IconWorld
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className={cn(webSearchEnabled && 'text-primary')}
+ onClick={() => setWebSearchEnabled(!webSearchEnabled)}
+ >
+ <IconWorldSearch
size={18}
- className="text-muted-foreground"
+ className={cn(
+ 'text-muted-foreground',
+ webSearchEnabled && 'text-primary'
+ )}
/>
</Button>
</TooltipTrigger>
<TooltipContent>
- <p>Web Search</p>
+ <p>
+ {webSearchEnabled
+ ? t('common:web_search') + ' (Active)'
+ : t('common:web_search')}
+ </p>
</TooltipContent>
</Tooltip>
)}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 8230eecb7..7c27a72c9 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -43,8 +43,10 @@ import { PromptProgress } from '@/components/PromptProgress'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
import { parseCitationsFromToolOutput } from '@/lib/citation-parser'
-import type { RagCitation } from '@/components/Citations'
+import type { RagCitation, WebCitation } from '@/components/Citations'
import { useGroundingStore } from '@/stores/grounding-store'
+import { useWebCitationStore } from '@/stores/web-citation-store'
+import { WebSourcesRow } from '@/components/WebSourcesRow'
import { injectCitationMarkers } from '@/lib/grounding'
import {
ReasoningActiveStep,
@@ -63,6 +65,14 @@ const CONTENT_TYPE = {
REASONING: 'reasoning',
} as const
+// Turn a tool identifier (e.g. "web_search", "exa_search") into a readable
+// label for the streaming step header (e.g. "Web search").
+function humanizeToolName(name: string): string {
+ const spaced = name.replace(/[_-]+/g, ' ').trim()
+ if (!spaced) return 'tool'
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
+}
+
export type MessageItemProps = {
message: UIMessage
isFirstMessage: boolean
@@ -183,8 +193,9 @@ export const MessageItem = memo(
// Aggregate RAG citations in part order and record each rag tool part's
// base offset, so its card numbers/anchors continue the same global
// sequence the inline superscript markers use.
- const { ragCitations, citationOffsets } = useMemo(() => {
+ const { ragCitations, citationOffsets, webCitations } = useMemo(() => {
const out: RagCitation[] = []
+ const web: WebCitation[] = []
const offsets = new Map<number, number>()
if (message.role === 'assistant') {
const parts = message.parts as any[]
@@ -196,10 +207,12 @@ export const MessageItem = memo(
if (parsed?.kind === 'rag') {
offsets.set(i, out.length)
out.push(...parsed.citations)
+ } else if (parsed?.kind === 'web') {
+ web.push(...parsed.citations)
}
}
}
- return { ragCitations: out, citationOffsets: offsets }
+ return { ragCitations: out, citationOffsets: offsets, webCitations: web }
}, [message.parts, message.role])
const serviceHub = useServiceHub()
@@ -234,6 +247,12 @@ export const MessageItem = memo(
serviceHub,
])
+ const setWebCitations = useWebCitationStore((s) => s.setForMessage)
+ useEffect(() => {
+ if (!webCitations.length) return
+ setWebCitations(message.id, webCitations)
+ }, [webCitations, message.id, setWebCitations])
+
// Extract file metadata from message text (for user messages with attachments)
const attachedFiles = useMemo(() => {
if (message.role !== 'user') return []
@@ -520,6 +539,15 @@ export const MessageItem = memo(
meaningful.length > 0 &&
meaningful[meaningful.length - 1].part.type.startsWith('tool-')
+ const currentToolLabel = currentStepIsTool
+ ? humanizeToolName(
+ meaningful[meaningful.length - 1].part.type
+ .split('-')
+ .slice(1)
+ .join('-')
+ )
+ : ''
+
// Only reasoning text is worth expanding for — a tool-only step collapses
// to the header. While streaming that means the current step is a
// reasoning paragraph that has completed at least once (something for
@@ -610,7 +638,9 @@ export const MessageItem = memo(
defaultOpen={hasDisplayableContent && !hasFollowingContent}
>
<ChainOfThoughtHeader
- streamingLabel={currentStepIsTool ? 'Using tools...' : 'Thinking'}
+ streamingLabel={
+ currentStepIsTool ? `${currentToolLabel}...` : 'Thinking'
+ }
completedVerb={hasTools ? 'Worked' : 'Thought'}
/>
<ChainOfThoughtContent>
@@ -768,6 +798,10 @@ export const MessageItem = memo(
{/* Render message parts */}
{renderedParts}
+ {message.role === 'assistant' && !isStreaming && webCitations.length > 0 && (
+ <WebSourcesRow citations={webCitations} />
+ )}
+
{isLastMessage &&
message.role === 'assistant' &&
!awaitingApproval &&
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx
index 115e5aa59..0a6d95863 100644
--- a/web-app/src/containers/RenderMarkdown.tsx
+++ b/web-app/src/containers/RenderMarkdown.tsx
@@ -24,8 +24,27 @@ import rehypeKatex from 'rehype-katex'
import 'katex/dist/katex.min.css'
import { MermaidError } from '@/components/MermaidError'
import { CitationLink } from '@/components/CitationLink'
+import { WebCitationChip } from '@/components/WebCitationChip'
import { MarkdownTable } from '@/components/MarkdownTable'
+const WEB_CITE_MARKER = /\[\[cite:\s*([^\]\s]+?)\s*\]\]/g
+
+// Models sometimes drop the scheme (e.g. "example.com/x"); normalize to https.
+function normalizeCiteUrl(raw: string): string {
+ return /^https?:\/\//i.test(raw) ? raw : `https://${raw}`
+}
+
+// Convert model-emitted [[cite:URL]] markers into anchors the Anchor override
+// renders as circular favicon chips.
+function linkifyWebCitations(text: string): string {
+ if (!text.includes('[[cite:')) return text
+ return text.replace(
+ WEB_CITE_MARKER,
+ (_m, url: string) =>
+ `[cite](#webcite-${encodeURIComponent(normalizeCiteUrl(url))})`
+ )
+}
+
interface MarkdownProps {
content: string
className?: string
@@ -204,7 +223,10 @@ function RenderMarkdownComponent({
// normalizeLatex is O(n) over the full string and its cache misses every chunk;
// skip it while streaming (LaTeX can't render mid-token) to avoid O(n²) cost.
const normalizedContent = useMemo(
- () => (isStreaming ? effectiveContent : normalizeLatex(effectiveContent)),
+ () =>
+ linkifyWebCitations(
+ isStreaming ? effectiveContent : normalizeLatex(effectiveContent)
+ ),
[effectiveContent, isStreaming]
)
@@ -220,10 +242,14 @@ function RenderMarkdownComponent({
</CitationLink>
)
}
+ if (typeof href === 'string' && href.startsWith('#webcite-')) {
+ const url = decodeURIComponent(href.slice('#webcite-'.length))
+ return <WebCitationChip messageId={messageId} url={url} />
+ }
return <a {...props}>{children}</a>
}
return { a: Anchor, table: MarkdownTable, ...(components ?? {}) } as Components
- }, [components])
+ }, [components, messageId])
// Interactive HTML artifacts: only when the user opted in and the stream is
// complete (an incomplete fence must not be torn out mid-token). Splitting the
diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsx
index d9679b039..e0a0df5d4 100644
--- a/web-app/src/containers/SettingsMenu.tsx
+++ b/web-app/src/containers/SettingsMenu.tsx
@@ -15,6 +15,7 @@ import {
IconLock,
IconCpu,
IconWorld,
+ IconWorldSearch,
IconPaperclip,
} from '@tabler/icons-react'
import { useMatches, useNavigate } from '@tanstack/react-router'
@@ -192,6 +193,11 @@ const SettingsMenu = () => {
route: route.settings.https_proxy,
icon: IconWorld,
},
+ {
+ title: 'common:web_search',
+ route: route.settings.web_search,
+ icon: IconWorldSearch,
+ },
{
title: 'common:keyboardShortcuts',
route: route.settings.shortcuts,
diff --git a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
index 9ac979e9b..1b89c1917 100644
--- a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
+++ b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
@@ -488,5 +488,46 @@ describe('RenderMarkdown', () => {
await flush(container)
})
})
+
+ describe('web citation markers', () => {
+ it('renders a [[cite:URL]] marker as a favicon link to the source', () => {
+ const { container } = render(
+ <RenderMarkdown
+ content={'Paris is the capital of France.[[cite:https://en.wikipedia.org/wiki/Paris]]'}
+ messageId="m1"
+ />
+ )
+ const link = container.querySelector(
+ 'a[href="https://en.wikipedia.org/wiki/Paris"]'
+ )
+ expect(link).toBeTruthy()
+ expect(link?.querySelector('img')).toBeTruthy()
+ // The raw marker text must not leak into the rendered output.
+ expect(container.textContent).not.toContain('[[cite:')
+ })
+
+ it('normalizes a scheme-less marker URL to https', () => {
+ const { container } = render(
+ <RenderMarkdown
+ content={'The TPU is fast.[[cite:example.com/article/foo-bar]]'}
+ messageId="m3"
+ />
+ )
+ const link = container.querySelector(
+ 'a[href="https://example.com/article/foo-bar"]'
+ )
+ expect(link).toBeTruthy()
+ expect(link?.querySelector('img')).toBeTruthy()
+ expect(container.textContent).not.toContain('[[cite:')
+ })
+
+ it('leaves text without markers untouched', () => {
+ const { container } = render(
+ <RenderMarkdown content={'No citations here.'} messageId="m2" />
+ )
+ expect(container.querySelector('img')).toBeNull()
+ expect(container.textContent).toContain('No citations here.')
+ })
+ })
})
diff --git a/web-app/src/hooks/useWebSearchConfig.ts b/web-app/src/hooks/useWebSearchConfig.ts
new file mode 100644
index 000000000..dc777598e
--- /dev/null
+++ b/web-app/src/hooks/useWebSearchConfig.ts
@@ -0,0 +1,112 @@
+import { create } from 'zustand'
+import { persist, createJSONStorage } from 'zustand/middleware'
+import { localStorageKey } from '@/constants/localStorage'
+import { backendStorage } from '@/lib/backendStorage'
+import { getServiceHub } from '@/hooks/useServiceHub'
+
+export type WebSearchProviderMeta = {
+ id: string
+ label: string
+ keyless: boolean
+ secretKey: string
+ homepage: string
+ requiresEndpoint?: boolean
+}
+
+export const WEB_SEARCH_PROVIDERS: WebSearchProviderMeta[] = [
+ {
+ id: 'exa',
+ label: 'Exa',
+ keyless: true,
+ secretKey: 'exa-api-key',
+ homepage: 'exa.ai',
+ },
+ {
+ id: 'tavily',
+ label: 'Tavily',
+ keyless: false,
+ secretKey: 'tavily-api-key',
+ homepage: 'tavily.com',
+ },
+ {
+ id: 'searxng',
+ label: 'SearXNG',
+ keyless: true,
+ secretKey: '',
+ homepage: 'searxng.org',
+ requiresEndpoint: true,
+ },
+]
+
+export const DEFAULT_SEARCH_PROVIDER = 'exa'
+
+export const providerFavicon = (meta: WebSearchProviderMeta): string =>
+ `https://www.google.com/s2/favicons?domain=${meta.homepage}&sz=64`
+
+export const getProviderMeta = (id: string): WebSearchProviderMeta =>
+ WEB_SEARCH_PROVIDERS.find((p) => p.id === id) ?? WEB_SEARCH_PROVIDERS[0]
+
+type WebSearchConfigState = {
+ webSearchEnabled: boolean
+ searchProvider: string
+ apiKeys: Record<string, string>
+ endpoints: Record<string, string>
+ setWebSearchEnabled: (value: boolean) => void
+ setSearchProvider: (value: string) => void
+ setApiKey: (providerId: string, value: string) => void
+ setEndpoint: (providerId: string, value: string) => void
+}
+
+export const useWebSearchConfig = create<WebSearchConfigState>()(
+ persist(
+ (set, get) => ({
+ webSearchEnabled: true,
+ searchProvider: DEFAULT_SEARCH_PROVIDER,
+ apiKeys: {},
+ endpoints: {},
+ setWebSearchEnabled: (webSearchEnabled) => set({ webSearchEnabled }),
+ setSearchProvider: (searchProvider) => set({ searchProvider }),
+ setApiKey: (providerId, value) => {
+ set({ apiKeys: { ...get().apiKeys, [providerId]: value } })
+ const secretKey = getProviderMeta(providerId).secretKey
+ if (!secretKey) return
+ // Canonical secret store is the OS keyring, not settings.json.
+ getServiceHub()
+ .core()
+ .invoke('set_secret', { key: secretKey, value })
+ .catch((err) =>
+ console.warn('Failed to persist web search API key to keyring:', err)
+ )
+ },
+ // Instance URLs are not secrets; they persist in settings.json.
+ setEndpoint: (providerId, value) =>
+ set({ endpoints: { ...get().endpoints, [providerId]: value } }),
+ }),
+ {
+ name: localStorageKey.settingWebSearch,
+ storage: createJSONStorage(() => backendStorage),
+ skipHydration: true,
+ // Never write API keys to plaintext settings.json; they live in the keyring.
+ partialize: (state) => ({
+ webSearchEnabled: state.webSearchEnabled,
+ searchProvider: state.searchProvider,
+ endpoints: state.endpoints,
+ }),
+ onRehydrateStorage: () => (state) => {
+ if (!state) return
+ for (const provider of WEB_SEARCH_PROVIDERS) {
+ getServiceHub()
+ .core()
+ .invoke<string | null>('get_secret', { key: provider.secretKey })
+ .then((value) => {
+ if (!value) return
+ useWebSearchConfig.setState((s) => ({
+ apiKeys: { ...s.apiKeys, [provider.id]: value },
+ }))
+ })
+ .catch(() => {})
+ }
+ },
+ }
+ )
+)
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index e1f548f43..1320f414e 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -20,6 +20,13 @@ import { useAssistant } from '@/hooks/useAssistant'
import { useThreads } from '@/hooks/useThreads'
import { useAttachments } from '@/hooks/useAttachments'
import { useMCPServers } from '@/hooks/useMCPServers'
+import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
+import {
+ WEB_SEARCH_DESCRIPTION,
+ WEB_SEARCH_INPUT_SCHEMA,
+ WEB_FETCH_DESCRIPTION,
+ WEB_FETCH_INPUT_SCHEMA,
+} from '@/lib/webSearchTool'
import { useAppState } from '@/hooks/useAppState'
import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'
import { ExtensionManager } from '@/lib/extension'
@@ -949,6 +956,19 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
} catch (error) {
console.warn('Failed to load MCP tools:', error)
}
+
+ // Native web tools, provided by the websearch plugin (not an MCP server).
+ // Advertised whenever the user has web search enabled.
+ if (useWebSearchConfig.getState().webSearchEnabled) {
+ toolsRecord['web_search'] = {
+ description: WEB_SEARCH_DESCRIPTION,
+ inputSchema: jsonSchema(WEB_SEARCH_INPUT_SCHEMA as Record<string, unknown>),
+ } as Tool
+ toolsRecord['web_fetch'] = {
+ description: WEB_FETCH_DESCRIPTION,
+ inputSchema: jsonSchema(WEB_FETCH_INPUT_SCHEMA as Record<string, unknown>),
+ } as Tool
+ }
}
this.tools = toolsRecord
@@ -1203,11 +1223,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const selectedModel = useModelProvider.getState().selectedModel
const filesInstruction = this.buildFilesSystemInstruction(messagesToConvert)
- const rawSystem = filesInstruction
- ? this.systemMessage
- ? `${this.systemMessage}\n\n${filesInstruction}`
- : filesInstruction
- : this.systemMessage
+ const webSearchInstruction = this.buildWebSearchSystemInstruction()
+ const rawSystem =
+ [this.systemMessage, filesInstruction, webSearchInstruction]
+ .filter((s) => typeof s === 'string' && s.trim().length > 0)
+ .join('\n\n') || undefined
// Drop whitespace-only system prompts so we don't send a useless system
// turn that some chat templates still wrap into special tokens.
const effectiveSystem =
@@ -1588,6 +1608,27 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
].join(' ')
}
+ /**
+ * Static instruction teaching the model to use the native web tools and cite
+ * sources inline with [[cite:URL]] markers (rendered as favicon chips). Only
+ * added when web search is enabled so it doesn't affect prompt caching for
+ * users who keep it off.
+ */
+ buildWebSearchSystemInstruction(): string {
+ if (!useWebSearchConfig.getState().webSearchEnabled) return ''
+ return [
+ '# Web Access',
+ 'You can search the web with web_search and read pages with web_fetch.',
+ 'Use them whenever the request needs current, external, or verifiable',
+ 'information, then base your answer on what you find. When a statement',
+ 'relies on a web source, cite it inline immediately after that statement',
+ 'using the exact marker [[cite:URL]], where URL is the full source URL',
+ 'from a web_search result (for example: [[cite:https://example.com/page]]).',
+ 'Cite each distinct source you rely on; do not add a separate references',
+ 'or sources section.',
+ ].join(' ')
+ }
+
mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {
return messages.map((message) => {
if (message.role === 'user') {
diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.ts
index 68855b808..d4abd3dc1 100644
--- a/web-app/src/lib/hydrateStores.ts
+++ b/web-app/src/lib/hydrateStores.ts
@@ -19,6 +19,7 @@ import { useLatestJanModel } from '@/hooks/useLatestJanModel'
import { useJanModelPromptDismissed } from '@/hooks/useJanModelPrompt'
import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'
import { useAgentMode } from '@/hooks/useAgentMode'
+import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
/**
* Stores persisted through `backendStorage` set `skipHydration: true` so they
@@ -49,6 +50,7 @@ const secondaryStores = [
useJanModelPromptDismissed,
useDefaultEmbeddingModel,
useAgentMode,
+ useWebSearchConfig,
] as const
export async function hydrateBackendStores(): Promise<void> {
diff --git a/web-app/src/lib/webSearchTool.ts b/web-app/src/lib/webSearchTool.ts
new file mode 100644
index 000000000..6b440dd84
--- /dev/null
+++ b/web-app/src/lib/webSearchTool.ts
@@ -0,0 +1,90 @@
+import { webSearch, webFetch } from '@janhq/tauri-plugin-websearch-api'
+import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
+
+export const WEB_TOOL_NAMES = new Set(['web_search', 'web_fetch'])
+
+export const WEB_SEARCH_DESCRIPTION =
+ 'Search the web and return a ranked list of results (title, URL, snippet, and optional publish date). Use this to find current information, documentation, or sources you can then read with web_fetch. Cite the URLs you rely on.'
+
+export const WEB_SEARCH_INPUT_SCHEMA = {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'The search query.' },
+ count: {
+ type: 'integer',
+ description: 'Maximum number of results to return (default 5, max 20).',
+ },
+ },
+ required: ['query'],
+} as const
+
+export const WEB_FETCH_DESCRIPTION =
+ 'Fetch a web page by URL and return its readable text content along with the source URL and title. Output is bounded to avoid flooding the context. Use after web_search to read a specific result.'
+
+export const WEB_FETCH_INPUT_SCHEMA = {
+ type: 'object',
+ properties: {
+ url: { type: 'string', description: 'The http(s) URL to fetch.' },
+ },
+ required: ['url'],
+} as const
+
+function faviconFor(url: string): string | undefined {
+ try {
+ const host = new URL(url).hostname
+ return `https://www.google.com/s2/favicons?domain=${host}&sz=64`
+ } catch {
+ return undefined
+ }
+}
+
+type WebToolInput = { query?: unknown; count?: unknown; url?: unknown }
+type WebToolResult = { content?: unknown; error?: string }
+
+/**
+ * Execute a native web tool via the websearch plugin and shape web_search
+ * output into the web-citation payload consumed by parseCitationsFromToolOutput.
+ */
+export async function executeWebTool(
+ toolName: string,
+ input: WebToolInput
+): Promise<WebToolResult> {
+ const { apiKeys, endpoints, searchProvider } = useWebSearchConfig.getState()
+ const apiKey = apiKeys[searchProvider] || undefined
+ const endpoint = endpoints[searchProvider] || undefined
+ try {
+ if (toolName === 'web_search') {
+ const query = typeof input?.query === 'string' ? input.query : ''
+ const count = typeof input?.count === 'number' ? input.count : undefined
+ const results = await webSearch(query, count, apiKey, searchProvider, endpoint)
+ return {
+ content: {
+ kind: 'web',
+ query,
+ results: results.map((r) => ({
+ url: r.url,
+ title: r.title,
+ text: r.snippet,
+ published_date: r.published_at,
+ favicon: faviconFor(r.url),
+ })),
+ },
+ }
+ }
+ if (toolName === 'web_fetch') {
+ const url = typeof input?.url === 'string' ? input.url : ''
+ const page = await webFetch(url, apiKey, searchProvider, endpoint)
+ const text = `Title: ${page.title}\nURL: ${page.url}\n\n${page.content}${
+ page.truncated ? '\n\n[content truncated]' : ''
+ }`
+ return { content: text }
+ }
+ return { error: `Unknown web tool '${toolName}'` }
+ } catch (e) {
+ const message =
+ e && typeof e === 'object' && 'message' in e
+ ? String((e as { message: unknown }).message)
+ : String(e)
+ return { error: message }
+ }
+}
diff --git a/web-app/src/locales/en/chat.json b/web-app/src/locales/en/chat.json
index c1cbf882f..b367fab97 100644
--- a/web-app/src/locales/en/chat.json
+++ b/web-app/src/locales/en/chat.json
@@ -17,5 +17,6 @@
"regenerate": "Regenerate response",
"continue": "Continue generating"
},
- "done": "Done"
+ "done": "Done",
+ "webSources": "{{count}} source(s)"
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 723aaf260..8d9bd024b 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -13,6 +13,7 @@
"experimental": "Experimental",
"claude_code": "Claude Code",
"https_proxy": "HTTPS Proxy",
+ "web_search": "Web Search",
"extensions": "Extensions",
"attachments": "Attachments",
"general": "General",
diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.json
index 052454b98..74614c9b6 100644
--- a/web-app/src/locales/en/settings.json
+++ b/web-app/src/locales/en/settings.json
@@ -183,6 +183,21 @@
"hostSsl": "Host SSL",
"hostSslDesc": "Validate the SSL certificates of destination hosts."
},
+ "webSearch": {
+ "title": "Web Search",
+ "description": "Let models search and read the web using Jan's built-in tools.",
+ "enable": "Enable Web Search",
+ "enableDesc": "Advertise the web_search and web_fetch tools to models that support tool use. Works out of the box with no API key.",
+ "provider": "Search Provider",
+ "providerDesc": "Choose the backend that answers web_search and web_fetch.",
+ "apiKey": "{{provider}} API Key",
+ "apiKeyOptional": "Optional. Provide a {{provider}} API key for higher rate limits and structured results. Leave empty to use the free keyless endpoint.",
+ "apiKeyRequired": "Required. {{provider}} needs an API key to return results.",
+ "apiKeyPlaceholder": "Enter your {{provider}} API key",
+ "endpoint": "{{provider}} Instance URL",
+ "endpointDesc": "Required. The base URL of your {{provider}} instance, with the JSON API enabled.",
+ "endpointPlaceholder": "https://searx.example.com"
+ },
"localApiServer": {
"title": "Local API Server",
"description": "Run an OpenAI-compatible server locally.",
diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.ts
index eaf300218..a2a333a4c 100644
--- a/web-app/src/routeTree.gen.ts
+++ b/web-app/src/routeTree.gen.ts
@@ -14,6 +14,7 @@ import { Route as LogsRouteImport } from './routes/logs'
import { Route as IndexRouteImport } from './routes/index'
import { Route as HubIndexRouteImport } from './routes/hub/index'
import { Route as ThreadsThreadIdRouteImport } from './routes/threads/$threadId'
+import { Route as SettingsWebSearchRouteImport } from './routes/settings/web-search'
import { Route as SettingsShortcutsRouteImport } from './routes/settings/shortcuts'
import { Route as SettingsPrivacyRouteImport } from './routes/settings/privacy'
import { Route as SettingsMcpServersRouteImport } from './routes/settings/mcp-servers'
@@ -57,6 +58,11 @@ const ThreadsThreadIdRoute = ThreadsThreadIdRouteImport.update({
path: '/threads/$threadId',
getParentRoute: () => rootRouteImport,
} as any)
+const SettingsWebSearchRoute = SettingsWebSearchRouteImport.update({
+ id: '/settings/web-search',
+ path: '/settings/web-search',
+ getParentRoute: () => rootRouteImport,
+} as any)
const SettingsShortcutsRoute = SettingsShortcutsRouteImport.update({
id: '/settings/shortcuts',
path: '/settings/shortcuts',
@@ -163,6 +169,7 @@ export interface FileRoutesByFullPath {
'/settings/mcp-servers': typeof SettingsMcpServersRoute
'/settings/privacy': typeof SettingsPrivacyRoute
'/settings/shortcuts': typeof SettingsShortcutsRoute
+ '/settings/web-search': typeof SettingsWebSearchRoute
'/threads/$threadId': typeof ThreadsThreadIdRoute
'/hub/': typeof HubIndexRoute
'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute
@@ -187,6 +194,7 @@ export interface FileRoutesByTo {
'/settings/mcp-servers': typeof SettingsMcpServersRoute
'/settings/privacy': typeof SettingsPrivacyRoute
'/settings/shortcuts': typeof SettingsShortcutsRoute
+ '/settings/web-search': typeof SettingsWebSearchRoute
'/threads/$threadId': typeof ThreadsThreadIdRoute
'/hub': typeof HubIndexRoute
'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute
@@ -212,6 +220,7 @@ export interface FileRoutesById {
'/settings/mcp-servers': typeof SettingsMcpServersRoute
'/settings/privacy': typeof SettingsPrivacyRoute
'/settings/shortcuts': typeof SettingsShortcutsRoute
+ '/settings/web-search': typeof SettingsWebSearchRoute
'/threads/$threadId': typeof ThreadsThreadIdRoute
'/hub/': typeof HubIndexRoute
'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute
@@ -238,6 +247,7 @@ export interface FileRouteTypes {
| '/settings/mcp-servers'
| '/settings/privacy'
| '/settings/shortcuts'
+ | '/settings/web-search'
| '/threads/$threadId'
| '/hub/'
| '/settings/providers/$providerName'
@@ -262,6 +272,7 @@ export interface FileRouteTypes {
| '/settings/mcp-servers'
| '/settings/privacy'
| '/settings/shortcuts'
+ | '/settings/web-search'
| '/threads/$threadId'
| '/hub'
| '/settings/providers/$providerName'
@@ -286,6 +297,7 @@ export interface FileRouteTypes {
| '/settings/mcp-servers'
| '/settings/privacy'
| '/settings/shortcuts'
+ | '/settings/web-search'
| '/threads/$threadId'
| '/hub/'
| '/settings/providers/$providerName'
@@ -311,6 +323,7 @@ export interface RootRouteChildren {
SettingsMcpServersRoute: typeof SettingsMcpServersRoute
SettingsPrivacyRoute: typeof SettingsPrivacyRoute
SettingsShortcutsRoute: typeof SettingsShortcutsRoute
+ SettingsWebSearchRoute: typeof SettingsWebSearchRoute
ThreadsThreadIdRoute: typeof ThreadsThreadIdRoute
HubIndexRoute: typeof HubIndexRoute
SettingsProvidersProviderNameRoute: typeof SettingsProvidersProviderNameRoute
@@ -354,6 +367,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ThreadsThreadIdRouteImport
parentRoute: typeof rootRouteImport
}
+ '/settings/web-search': {
+ id: '/settings/web-search'
+ path: '/settings/web-search'
+ fullPath: '/settings/web-search'
+ preLoaderRoute: typeof SettingsWebSearchRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/settings/shortcuts': {
id: '/settings/shortcuts'
path: '/settings/shortcuts'
@@ -495,6 +515,7 @@ const rootRouteChildren: RootRouteChildren = {
SettingsMcpServersRoute: SettingsMcpServersRoute,
SettingsPrivacyRoute: SettingsPrivacyRoute,
SettingsShortcutsRoute: SettingsShortcutsRoute,
+ SettingsWebSearchRoute: SettingsWebSearchRoute,
ThreadsThreadIdRoute: ThreadsThreadIdRoute,
HubIndexRoute: HubIndexRoute,
SettingsProvidersProviderNameRoute: SettingsProvidersProviderNameRoute,
diff --git a/web-app/src/routes/settings/web-search.tsx b/web-app/src/routes/settings/web-search.tsx
new file mode 100644
index 000000000..e088ca1a2
--- /dev/null
+++ b/web-app/src/routes/settings/web-search.tsx
@@ -0,0 +1,198 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { route } from '@/constants/routes'
+import HeaderPage from '@/containers/HeaderPage'
+import SettingsMenu from '@/containers/SettingsMenu'
+import { Card, CardItem } from '@/containers/Card'
+import { Switch } from '@/components/ui/switch'
+import { Button } from '@/components/ui/button'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { Input } from '@/components/ui/input'
+import { EyeOff, Eye, ChevronsUpDown } from 'lucide-react'
+import { useState } from 'react'
+import { cn } from '@/lib/utils'
+import {
+ useWebSearchConfig,
+ WEB_SEARCH_PROVIDERS,
+ getProviderMeta,
+ providerFavicon,
+} from '@/hooks/useWebSearchConfig'
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export const Route = createFileRoute(route.settings.web_search as any)({
+ component: WebSearchContent,
+})
+
+const ProviderFavicon = ({ src }: { src: string }) => (
+ <img
+ src={src}
+ alt=""
+ className="size-4 shrink-0 rounded-full border border-border/50 bg-white object-contain"
+ />
+)
+
+function WebSearchContent() {
+ const { t } = useTranslation()
+ const [showKey, setShowKey] = useState(false)
+ const {
+ webSearchEnabled,
+ searchProvider,
+ apiKeys,
+ endpoints,
+ setWebSearchEnabled,
+ setSearchProvider,
+ setApiKey,
+ setEndpoint,
+ } = useWebSearchConfig()
+
+ const provider = getProviderMeta(searchProvider)
+ const apiKey = apiKeys[provider.id] ?? ''
+ const endpoint = endpoints[provider.id] ?? ''
+
+ return (
+ <div className="flex flex-col h-svh w-full">
+ <HeaderPage>
+ <div className="flex items-center gap-2 w-full">
+ <span className="font-medium text-base font-studio">
+ {t('common:settings')}
+ </span>
+ </div>
+ </HeaderPage>
+ <div className="flex h-[calc(100%-60px)]">
+ <SettingsMenu />
+ <div className="p-4 pt-0 w-full overflow-y-auto">
+ <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">
+ <Card
+ header={
+ <div className="flex items-center justify-between">
+ <h1 className="text-foreground font-studio font-medium text-base mb-2">
+ {t('settings:webSearch.title')}
+ </h1>
+ <Switch
+ checked={webSearchEnabled}
+ onCheckedChange={setWebSearchEnabled}
+ />
+ </div>
+ }
+ >
+ <CardItem
+ title={t('settings:webSearch.enable')}
+ description={t('settings:webSearch.enableDesc')}
+ />
+ <CardItem
+ title={t('settings:webSearch.provider')}
+ description={t('settings:webSearch.providerDesc')}
+ actions={
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="justify-between gap-2"
+ >
+ <ProviderFavicon src={providerFavicon(provider)} />
+ <span className="truncate">{provider.label}</span>
+ <ChevronsUpDown className="size-4 shrink-0 text-muted-foreground ml-2" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ {WEB_SEARCH_PROVIDERS.map((p) => (
+ <DropdownMenuItem
+ key={p.id}
+ className={cn(
+ 'cursor-pointer my-0.5 gap-2',
+ searchProvider === p.id && 'bg-secondary-foreground/8'
+ )}
+ onClick={() => setSearchProvider(p.id)}
+ >
+ <ProviderFavicon src={providerFavicon(p)} />
+ <span className="truncate">{p.label}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ }
+ />
+ {provider.requiresEndpoint ? (
+ <CardItem
+ title={t('settings:webSearch.endpoint', {
+ provider: provider.label,
+ })}
+ className="block"
+ description={
+ <div className="space-y-2">
+ <p>
+ {t('settings:webSearch.endpointDesc', {
+ provider: provider.label,
+ })}
+ </p>
+ <Input
+ type="text"
+ className="w-full"
+ placeholder={t('settings:webSearch.endpointPlaceholder')}
+ value={endpoint}
+ onChange={(e) =>
+ setEndpoint(provider.id, e.target.value)
+ }
+ />
+ </div>
+ }
+ />
+ ) : (
+ <CardItem
+ title={t('settings:webSearch.apiKey', {
+ provider: provider.label,
+ })}
+ className="block"
+ description={
+ <div className="space-y-2">
+ <p>
+ {t(
+ provider.keyless
+ ? 'settings:webSearch.apiKeyOptional'
+ : 'settings:webSearch.apiKeyRequired',
+ { provider: provider.label }
+ )}
+ </p>
+ <div className="relative">
+ <Input
+ type={showKey ? 'text' : 'password'}
+ className="w-full pr-16"
+ placeholder={t(
+ 'settings:webSearch.apiKeyPlaceholder',
+ { provider: provider.label }
+ )}
+ value={apiKey}
+ onChange={(e) =>
+ setApiKey(provider.id, e.target.value)
+ }
+ />
+ <div className="absolute right-2 top-1/2 transform -translate-y-1/2 flex items-center gap-1">
+ <button
+ onClick={() => setShowKey(!showKey)}
+ className="p-1 rounded hover:bg-foreground/5 text-foreground/70"
+ >
+ {showKey ? (
+ <EyeOff size={16} />
+ ) : (
+ <Eye size={16} />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ }
+ />
+ )}
+ </Card>
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 9b1ae6f8e..1aca7ab77 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -74,6 +74,7 @@ import { Button } from '@/components/ui/button'
import { IconAlertCircle, IconRefresh, IconLoader2 } from '@tabler/icons-react'
import { useToolApproval } from '@/hooks/useToolApproval'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
+import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'
import { ExtensionManager } from '@/lib/extension'
@@ -471,8 +472,9 @@ function ThreadDetail() {
try {
const toolName = toolCall.toolName
- // Built-in RAG tools are internal and should not require approval.
- const approved = ragToolNames.has(toolName)
+ // Built-in RAG and native web tools are internal and auto-allowed.
+ const approved = ragToolNames.has(toolName) ||
+ WEB_TOOL_NAMES.has(toolName)
? true
: await (toolApprovalPromises.current.get(toolCall.toolCallId) ??
useToolApprovalRequests
@@ -492,7 +494,9 @@ function ThreadDetail() {
let result
- if (ragToolNames.has(toolName)) {
+ if (WEB_TOOL_NAMES.has(toolName)) {
+ result = await executeWebTool(toolName, toolCall.input)
+ } else if (ragToolNames.has(toolName)) {
result = await serviceHub.rag().callTool({
toolName,
arguments: toolCall.input,
@@ -632,6 +636,7 @@ function ThreadDetail() {
const ragToolNames = useAppState.getState().ragToolNames
if (
!ragToolNames.has(toolCall.toolName) &&
+ !WEB_TOOL_NAMES.has(toolCall.toolName) &&
!toolApprovalPromises.current.has(toolCall.toolCallId)
) {
toolApprovalPromises.current.set(
diff --git a/web-app/src/stores/web-citation-store.ts b/web-app/src/stores/web-citation-store.ts
new file mode 100644
index 000000000..2d1b7855a
--- /dev/null
+++ b/web-app/src/stores/web-citation-store.ts
@@ -0,0 +1,24 @@
+import { create } from 'zustand'
+import type { WebCitation } from '@/components/Citations'
+
+type State = {
+ byMessageId: Record<string, Record<string, WebCitation>>
+ setForMessage: (messageId: string, citations: WebCitation[]) => void
+}
+
+const fingerprint = (map: Record<string, WebCitation>) =>
+ Object.keys(map).sort().join('|')
+
+export const useWebCitationStore = create<State>((set) => ({
+ byMessageId: {},
+ setForMessage: (messageId, citations) => {
+ if (!messageId || !citations.length) return
+ const map: Record<string, WebCitation> = {}
+ for (const c of citations) map[c.url] = c
+ set((s) => {
+ const prev = s.byMessageId[messageId]
+ if (prev && fingerprint(prev) === fingerprint(map)) return s
+ return { byMessageId: { ...s.byMessageId, [messageId]: map } }
+ })
+ },
+}))
diff --git a/yarn.lock b/yarn.lock
index 6a2307498..d89675ce8 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2943,6 +2943,12 @@ __metadata:
languageName: node
linkType: soft
+"@janhq/tauri-plugin-websearch-api@link:../src-tauri/plugins/tauri-plugin-websearch::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app":
+ version: 0.0.0-use.local
+ resolution: "@janhq/tauri-plugin-websearch-api@link:../src-tauri/plugins/tauri-plugin-websearch::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app"
+ languageName: node
+ linkType: soft
+
"@janhq/vector-db-extension@workspace:extensions/vector-db-extension":
version: 0.0.0-use.local
resolution: "@janhq/vector-db-extension@workspace:extensions/vector-db-extension"
@@ -2977,6 +2983,7 @@ __metadata:
"@janhq/core": "workspace:*"
"@janhq/interfaces": "npm:0.0.2"
"@janhq/tauri-plugin-llamacpp-api": "link:../src-tauri/plugins/tauri-plugin-llamacpp"
+ "@janhq/tauri-plugin-websearch-api": "link:../src-tauri/plugins/tauri-plugin-websearch"
"@radix-ui/react-accordion": "npm:1.2.11"
"@radix-ui/react-avatar": "npm:1.1.10"
"@radix-ui/react-collapsible": "npm:^1.1.12"