diff --git a/package.json b/package.json index 37f4c5e1..372a8597 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "thinkwatch-lite", "private": true, "description": "Desktop app for a local AI API gateway on macOS, Windows and Linux", - "version": "2026.11.16", + "version": "2026.11.17", "type": "module", "packageManager": "pnpm@11.13.1", "scripts": { diff --git a/release-notes/2026.11.17.md b/release-notes/2026.11.17.md new file mode 100644 index 00000000..d2d97c08 --- /dev/null +++ b/release-notes/2026.11.17.md @@ -0,0 +1,8 @@ +This release bundles ThinkWatch Core 0.98.0 with improved free web search. Core connects directly to Google (Docs), DuckDuckGo and Bing, without API keys or a browser runtime. + +- Automatic search follows Core's recommended order: Google (Docs), DuckDuckGo, then Bing. Cached results, shared concurrent searches, per-engine pacing and cooldowns reduce repeated requests and allow another source to take over when one fails. +- The search engine picker reads the connected Core's capabilities. Google (Docs) can be selected and saved alongside other sources, with readable engine names in test results. Connections to older Core versions retain their existing choices. +- Google (Docs) searches public web pages through a legacy Google endpoint, with at least six seconds between requests and no regional preference support. It depends on the endpoint and eligible public document contexts remaining available. +- The native bridge preserves new search engine identifiers while Core continues to validate configuration and search requests. Other control-plane routes keep their existing validation. + +Configure and test these sources under **Routing → Auxiliary → Web search and page reading**. Existing upstream execution settings remain unchanged until Core execution is enabled. diff --git a/scripts/shots/mock/core.ts b/scripts/shots/mock/core.ts index 6506ee30..736b1dd2 100644 --- a/scripts/shots/mock/core.ts +++ b/scripts/shots/mock/core.ts @@ -88,7 +88,7 @@ export const CORE: { [N in WebviewEndpoint]: Handler } = { ConfigRepairPlan: () => ({ base_version: configVersion(), fixes: [] }), RepairConfig: refuse, SaveListen: refuse, - WebTools: () => ({ config_version: configVersion(), system_locale: { language: "zh-Hans", region: "CN" }, config: { + WebTools: () => ({ available_engines: [{ id: "google_docs", name: "Google (Docs)", min_interval_ms: 6000 }, { id: "duckduckgo", name: "DuckDuckGo", min_interval_ms: 0 }, { id: "bing", name: "Bing", min_interval_ms: 0 }], config_version: configVersion(), system_locale: { language: "zh-Hans", region: "CN" }, config: { mode: "upstream", engines: [], proxy: "system", language: "", region: "", allowed_domains: [], blocked_domains: [], max_results: 8, read_pages: 2, max_page_chars: 12000, timeout_secs: 30, max_concurrent: 4, interval_ms: 1000, cache_secs: 600, max_tool_calls: 8, fallback_to_upstream: false, } }), diff --git a/scripts/ui/web-tools.pw.ts b/scripts/ui/web-tools.pw.ts index 6999c23c..124d0d19 100644 --- a/scripts/ui/web-tools.pw.ts +++ b/scripts/ui/web-tools.pw.ts @@ -43,7 +43,7 @@ test("locale menus scroll and select in the real config dialog; drafts survive S await expect(region).toHaveValue("日本"); const engine = dialog.getByRole("combobox", { name: "搜索引擎", exact: true }); await engine.click(); - await expect(page.getByRole("option")).toHaveCount(3); + await expect(page.getByRole("option")).toHaveCount(4); await page.getByRole("option", { name: "Bing", exact: true }).click(); await expect(page.getByRole("listbox")).toBeVisible(); await page.keyboard.press("Escape"); @@ -143,6 +143,56 @@ test("engine choices support keyboard search and return to Automatic when the la await expect.poll(() => page.evaluate(() => (window as unknown as { savedWebConfig?: unknown }).savedWebConfig)).toMatchObject({ engines: [] }); }); +test("Core-advertised Google search survives saving and reopening", async ({ page }) => { + await open(page); + await acceptSaves(page); + const dialog = page.getByRole("dialog"); + const engine = dialog.getByRole("combobox", { name: "搜索引擎", exact: true }); + await expect(dialog).toContainText("请求间隔至少 6 秒"); + await engine.click(); + await page.getByRole("option", { name: "Google (Docs)", exact: true }).click(); + await page.keyboard.press("Escape"); + await dialog.getByRole("button", { name: "保存", exact: true }).click(); + await expect(dialog).toBeHidden(); + await expect.poll(() => page.evaluate(() => (window as unknown as { savedWebConfig?: unknown }).savedWebConfig)).toMatchObject({ engines: ["google_docs"] }); + await page.getByRole("button", { name: "配置", exact: true }).click(); + await expect(engine).toHaveText("Google (Docs)"); + await engine.click(); + await expect(page.getByRole("option", { name: "Google (Docs)", exact: true })).toHaveAttribute("aria-selected", "true"); +}); + +test("older Core without capabilities retains its two engines", async ({ page }) => { + await page.addInitScript(() => { + type Invoke = (command: string, args?: Record, options?: unknown) => Promise; + const context = window as unknown as { __TAURI_INTERNALS__: Record }; + const internals: Record = {}; + let invoke: Invoke; + Object.defineProperty(internals, "invoke", { + configurable: true, + get: () => invoke, + set: (original: Invoke) => { + invoke = async (command, args, options) => { + const result = await original(command, args, options); + if (command === "call" && args?.endpoint === "WebTools") { + const view = { ...result as Record }; + delete view.available_engines; + return view; + } + return result; + }; + }, + }); + context.__TAURI_INTERNALS__ = internals; + }); + await open(page); + const dialog = page.getByRole("dialog"); + await expect(dialog).not.toContainText("Google (Docs)"); + await dialog.getByRole("combobox", { name: "搜索引擎", exact: true }).click(); + await expect(page.getByRole("option")).toHaveCount(3); + await expect(page.getByRole("option", { name: "Bing", exact: true })).toBeVisible(); + await expect(page.getByRole("option", { name: "DuckDuckGo", exact: true })).toBeVisible(); +}); + test("invalid domains block saving; failed save retains edits; Escape closes the menu first", async ({ page }) => { await open(page); const dialog = page.getByRole("dialog"); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 5c00a76e..7ec07066 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4950,7 +4950,7 @@ dependencies = [ [[package]] name = "thinkwatch-lite" -version = "2026.11.16" +version = "2026.11.17" dependencies = [ "anyhow", "base64 0.22.1", @@ -5459,8 +5459,8 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "serde", "serde_json", @@ -5471,8 +5471,8 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "memchr", "serde", @@ -5481,8 +5481,8 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -5503,8 +5503,8 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "serde", "serde_json", @@ -5530,8 +5530,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "serde", "ts-rs", @@ -5539,8 +5539,8 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "libc", "notify", @@ -5550,8 +5550,8 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.97.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" +version = "0.98.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.98.0#8572a2e32f21f18038a40da7545ac58fb49ac6a2" dependencies = [ "saphyr-parser", "thiserror 2.0.21", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 481c5033..6d2e13bc 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "thinkwatch-lite" -version = "2026.11.16" +version = "2026.11.17" edition = "2024" # **这个数决定依赖能升到哪一版。**edition 2024 的解析器只挑声明的 Rust # 版本编得动的依赖:写 1.85 的时候,`cargo update` 一直停在旧的 time 和 @@ -26,12 +26,12 @@ license = "MIT" # twcore 二进制必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是 # 从 tw-api 锁到的 tag 去取二进制的(见 scripts/fetch-core.sh)。 [workspace.dependencies] -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.97.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.97.0" } -tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.97.0" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.97.0" } -tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.97.0" } -tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.97.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.98.0" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.98.0" } +tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.98.0" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.98.0" } +tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.98.0" } +tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.98.0" } [lib] name = "thinkwatch_lite_lib" diff --git a/src-tauri/src/call.rs b/src-tauri/src/call.rs index 708e0aec..db062738 100644 --- a/src-tauri/src/call.rs +++ b/src-tauri/src/call.rs @@ -3,7 +3,8 @@ //! **只是转发的端点不再各有一个命令。**以前一个端点在这一层要写一个命令, //! 参数名、路径、请求类型各写一遍,前端再按命令名和参数名调一遍 —— 参数名 //! 拼错是运行时才知道的事。现在界面按端点名调(类型来自生成的 `tw-api.ts`), -//! 这里按名字找到 `tw_api::ep` 里那一个端点,把请求按它的类型读一遍再发出去。 +//! 这里按名字找到 `tw_api::ep` 里那一个端点。搜索能力可随 Core 扩展,三个搜索 +//! 端点直接转发 JSON 交给 Core 校验;其余端点先按钉住的协议类型校验。 //! //! **界面够得着的端点只有 [`ALLOWED`] 里这些。**不在里面的有意不给:密钥明文 //! (`KeyValue`,复制走 Rust 这边直接写剪贴板)、让 core 退出、诊断包的正文、 @@ -207,9 +208,14 @@ webview_endpoints![ SyncRepublish, ]; -/// 请求按这个端点的类型读一遍再发:**界面发来的形状不对,在这里就停下**, -/// 不把一个 core 读不了的请求送过去。 +/// 搜索端点保留 Core 的可扩展能力字段,其余请求先按端点类型校验。 async fn relay(c: &ControlClient, params: &[&str], req: Value) -> Out { + // Search capabilities evolve on Core independently of the bundled API. + // Only these already-allowlisted routes accept extensible JSON. Core still + // validates every request, with the same authenticated transport and paths. + if matches!(E::NAME, "WebTools" | "SaveWebTools" | "TestWebTool") { + return Ok(c.call::>(params, &req).await?); + } let req: E::Req = serde_json::from_value(req).map_err(|e| { CmdError::plain(format!( "The request for `{}` has the wrong shape: {e}", @@ -220,10 +226,191 @@ async fn relay(c: &ControlClient, params: &[&str], req: Value) -> O serde_json::to_value(res).map_err(|e| CmdError::plain(e.to_string())) } +struct SearchEndpoint(std::marker::PhantomData); + +impl Endpoint for SearchEndpoint { + const METHOD: tw_api::Method = E::METHOD; + const PATH: &'static str = E::PATH; + const PARAMS: &'static [&'static str] = E::PARAMS; + const FORMAT: tw_api::Format = E::FORMAT; + const NAME: &'static str = E::NAME; + type Req = Value; + type Res = Value; +} + #[cfg(test)] mod tests { use super::*; + /// Use the real authenticated transport to catch enum decoding in either + /// direction, including adapters added after this Lite version was built. + async fn search_roundtrip(req: Value, reply: Value) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("config.yaml"); + std::fs::write( + &config, + format!("listen:\n control:\n key: \"{}\"\n", "ab".repeat(32)), + ) + .unwrap(); + let key = tw_link::read_key(&config).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port_file = dir.path().join("control.port"); + std::fs::write( + &port_file, + listener.local_addr().unwrap().port().to_string(), + ) + .unwrap(); + let expected_req = req.clone(); + let expected_reply = reply.clone(); + let server = tokio::spawn(async move { + let (tcp, _) = listener.accept().await.unwrap(); + let acceptor = tw_link::Acceptor::new(move || Some(key.clone()), "test"); + let mut stream = acceptor.accept(tcp).await.unwrap().stream; + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + head.push(stream.read_u8().await.unwrap()); + } + let head = String::from_utf8(head).unwrap(); + assert!(head.starts_with(&format!("{} {} HTTP/1.1", E::METHOD.as_str(), E::PATH))); + let len = head + .lines() + .find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + if len > 0 { + let mut body = vec![0; len]; + stream.read_exact(&mut body).await.unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap(), + expected_req + ); + } else { + assert!(expected_req.is_null()); + } + let body = reply.to_string(); + stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap(); + stream.flush().await.unwrap(); + }); + let client = ControlClient::new(tw_api::control::Address::Loopback { port_file }, config); + assert_eq!(relay::(&client, &[], req).await.unwrap(), expected_reply); + server.await.unwrap(); + } + + #[tokio::test] + async fn search_capabilities_cross_the_pinned_native_bridge() { + use serde_json::json; + search_roundtrip::(Value::Null, json!({ + "config": {"engines": ["google_docs", "future_engine"]}, + "available_engines": [{"id": "future_engine", "name": "Future", "min_interval_ms": 6000}] + })).await; + search_roundtrip::( + json!({ + "base_version": "test", "config": {"engines": ["google_docs", "future_engine"]} + }), + json!({"version": "saved"}), + ) + .await; + search_roundtrip::( + json!({"action": "search", "query": "Rust"}), + json!({ + "sources": [{"engine": "future_engine", "url": "https://www.rust-lang.org/"}] + }), + ) + .await; + } + + #[tokio::test] + #[ignore = "requires a Google Docs-capable resources/twcore and live Google access"] + async fn live_search_through_native_relay_and_isolated_core() { + use serde_json::json; + use std::time::Duration; + struct Process(std::process::Child); + impl Drop for Process { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let home = tempfile::Builder::new() + .prefix("tw-search-") + .tempdir() + .unwrap(); + let config_path = home.path().join("config.yaml"); + let _process = Process( + std::process::Command::new( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("resources") + .join(crate::gateway::CORE_EXE), + ) + .args(["serve", "--config"]) + .arg(&config_path) + .args(["--port", "0"]) + .env("THINKWATCH_HOME", home.path()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(), + ); + let client = ControlClient::new(tw_api::control::Address::in_dir(home.path()), config_path); + tokio::time::timeout(Duration::from_secs(30), async { + while client.ping(Duration::from_millis(500)).await.is_err() { + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .unwrap(); + let view = relay::(&client, &[], Value::Null) + .await + .unwrap(); + assert!( + view["available_engines"] + .as_array() + .unwrap() + .iter() + .any(|e| e["id"] == "google_docs") + ); + let mut config = view["config"].clone(); + config["engines"] = json!(["google_docs"]); + config["read_pages"] = json!(0); + relay::( + &client, + &[], + json!({"base_version": view["config_version"], "config": config}), + ) + .await + .unwrap(); + let saved = relay::(&client, &[], Value::Null) + .await + .unwrap(); + assert_eq!(saved["config"]["engines"], json!(["google_docs"])); + let request = json!({"action": "search", "query": "Python asyncio TaskGroup documentation", "allowed_domains": ["python.org"], "blocked_domains": []}); + let result = relay::(&client, &[], request.clone()) + .await + .unwrap(); + assert!( + result["sources"] + .as_array() + .unwrap() + .iter() + .any(|s| s["engine"] == "google_docs" + && s["url"] + .as_str() + .unwrap() + .contains("docs.python.org/3/library/asyncio-task.html")), + "{result}" + ); + let cached = relay::(&client, &[], request) + .await + .unwrap(); + assert_eq!(cached["cached"], true); + let invalid = relay::(&client, &[], json!({"base_version": saved["config_version"], "config": {"engines": ["unsupported_engine"]}})).await; + assert!(invalid.is_err(), "Core must still reject unknown engines"); + } + /// 这些是有意不给界面的,见模块说明。 #[test] fn what_the_webview_cannot_reach() { diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 70513ef6..7b3500e1 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "ThinkWatch Lite", - "version": "2026.11.16", + "version": "2026.11.17", "identifier": "app.thinkwatch.lite", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/control.ts b/src/control.ts index c2271434..e7d7e951 100644 --- a/src/control.ts +++ b/src/control.ts @@ -13,7 +13,8 @@ * 失败时抛出的是一条 `Msg` 形状的对象,交给 `errorText`。 */ import { invoke } from "@tauri-apps/api/core"; -import type { ENDPOINTS, Endpoints } from "./generated/tw-api"; +import type { ENDPOINTS } from "./generated/tw-api"; +import type { Endpoints } from "./webToolsCompat"; /** * 界面能直接调的端点。**和 `src-tauri/src/call.rs` 的 `ALLOWED` 是同一份** diff --git a/src/generated/tw-api.ts b/src/generated/tw-api.ts index 1e1e872c..21fa3844 100644 --- a/src/generated/tw-api.ts +++ b/src/generated/tw-api.ts @@ -5118,7 +5118,7 @@ export type SavedSource = { kind: SavedSourceKind, name: string, }; */ export type SavedSourceKind = "upstream-key" | "upstream-header" | "access-key" | "proxy-password" | "control-key" | "sync-credential"; -export type SearchEngine = "bing" | "duckduckgo"; +export type SearchEngine = "bing" | "duckduckgo" | "google_docs"; /** * 一页搜索停在哪儿的原因。 @@ -6590,6 +6590,12 @@ export type UsageView = { input: number, output: number, cache_read: number, cac */ cache_1h?: boolean, }; +export type WebSearchEngine = { id: SearchEngine, name: string, +/** + * The engine's minimum applies even if the user's configured interval is lower. + */ +min_interval_ms: number, }; + export type WebSearchLocale = { language: string, region: string, }; export type WebSource = { url: string, title: string, text: string, engine: SearchEngine | null, published_at: string | null, }; @@ -6636,7 +6642,11 @@ export type WebToolsView = { config: WebToolsConfig, config_version: string, /** * Detected on the Core host, which may be remote. Empty fields mean unavailable. */ -system_locale: WebSearchLocale, }; +system_locale: WebSearchLocale, +/** + * Engine capabilities advertised by the connected Core. + */ +available_engines: Array, }; /** * 聚合类端点的时间窗(`GET /summary`、`/latency`)。**缺省是「今天」而不是 diff --git a/src/i18n/core.zh.json b/src/i18n/core.zh.json index d6b47e65..22037141 100644 --- a/src/i18n/core.zh.json +++ b/src/i18n/core.zh.json @@ -1185,6 +1185,7 @@ "wsl.stopped": "WSL · {distro} 已停止。启动发行版后才能检查网关连通性。", "wsl.listener_cleanup_failed": "客户端配置已还原,但未能移除闲置的 WSL 监听或来源规则:{detail}。请检查网关监听设置;清理记录已保留。", "gw.web_tools.failed": "联网工具:{detail}", + "gw.web_tools.query_mismatch": "搜索引擎返回的结果与查询内容不匹配。", "config.web_tools.invalid": "联网工具配置无效:{detail}" } } diff --git a/src/routing/EnginePicker.tsx b/src/routing/EnginePicker.tsx index f02be835..c27d6c9a 100644 --- a/src/routing/EnginePicker.tsx +++ b/src/routing/EnginePicker.tsx @@ -1,24 +1,24 @@ import { useRef } from "react"; import { useText } from "@/i18n"; -import type { SearchEngine } from "@/types"; +import type { SearchEngine, WebSearchEngine } from "@/types"; +import { engineName, legacyEngines } from "@/webToolsCompat"; import { Button } from "@/ui/button"; import { Combobox, ComboboxTrigger, ComboboxInput, ComboboxContent, ComboboxList, ComboboxItem, ComboboxEmpty, ComboboxSeparator } from "@/ui/combobox"; import { webToolsText } from "./WebTools.i18n"; import { selectedEngines, type EngineChoice } from "./webToolsForm"; -const engines: Record = { bing: "Bing", duckduckgo: "DuckDuckGo" }; -const choices: EngineChoice[] = ["auto", ...Object.keys(engines) as SearchEngine[]]; - /** Automatic is exclusive; an empty saved list continues to follow Core defaults. */ -export function EnginePicker({ id, value, disabled, onChange }: { +export function EnginePicker({ id, value, available = legacyEngines, disabled, onChange }: { id: string; value: SearchEngine[]; + available?: WebSearchEngine[]; disabled: boolean; onChange: (value: SearchEngine[]) => void; }) { const t = useText(webToolsText); const trigger = useRef(null); - const label = (choice: EngineChoice) => choice === "auto" ? t.auto : engines[choice]; + const choices: EngineChoice[] = ["auto", ...new Set([...available.map((engine) => engine.id), ...value])]; + const label = (choice: EngineChoice) => choice === "auto" ? t.auto : engineName(choice, available); const names = value.map(label).join(", "); const summary = value.length > 2 ? t.engineCount(value.length) : names || t.auto; return multiple items={choices} value={value.length ? value : ["auto"]} disabled={disabled} diff --git a/src/routing/WebTools.i18n.ts b/src/routing/WebTools.i18n.ts index ad1395fc..4df7922c 100644 --- a/src/routing/WebTools.i18n.ts +++ b/src/routing/WebTools.i18n.ts @@ -6,9 +6,10 @@ export const webToolsText = messages( core: "Core 执行", upstream: "上游执行", coreHelp: "独立搜索直接返回结果;对话中的联网操作执行后交回模型。主模型仍按实际用量计费。", upstreamHelp: "保留客户端原有请求,按路由规则交给上游。", configure: "配置", test: "测试", save: "保存", cancel: "取消", retry: "重试", loading: "正在读取搜索配置…", unavailable: "无法读取联网工具配置。请确认连接正常,且 Core 已支持联网工具。", local: "执行位置:本机 Core", remote: (name: string) => `执行位置:${name}`, + googleDocsHelp: "Google (Docs) 搜索公开网页,请求间隔至少 6 秒,不支持地区偏好。", engines: "搜索引擎", auto: "自动", findEngine: "查找引擎", noEngineMatch: "没有匹配的引擎", engineCount: (n: number) => `已选 ${n} 个引擎`, proxy: "网络出口", system: "跟随系统", direct: "直连", language: "搜索语言", region: "国家或地区", automatic: (name: string) => `跟随系统(${name})`, automaticUnknown: "跟随系统(由搜索引擎决定)", unknownLocale: "当前设置", noLocaleMatch: "没有匹配的语言或地区", - localeLocal: "自动使用本机 Core 的系统设置。", localeRemote: (name: string) => `自动使用远程 Core「${name}」的系统设置。`, localeHelp: "可按名称搜索并单独修改语言或地区;搜索引擎会尽量按此偏好返回结果。", allowed: "允许的域名", blocked: "排除的域名", domainsHelp: "支持粘贴多行域名,规则包含子域名并同时约束网页读取。排除优先。", allowedHelp: "留空时不限制域名。", blockedHelp: "留空时不排除域名。", add: "添加", remove: "删除", removeDomain: (domain: string) => `删除 ${domain}`, domainPlaceholder: "添加域名,例如 sqlite.org", invalidDomains: (names: string) => `域名格式不正确:${names}`, tooManyDomains: "每份列表最多 100 个域名。", domainConflict: (names: string) => `以下域名同时出现在两份列表中,将被排除:${names}`, engineHelp: "自动使用可用引擎,或多选指定引擎;结果不足时继续补充。", + localeLocal: "自动使用本机 Core 的系统设置。", localeRemote: (name: string) => `自动使用远程 Core「${name}」的系统设置。`, localeHelp: "可按名称搜索并单独修改语言或地区;搜索引擎会尽量按此偏好返回结果。", allowed: "允许的域名", blocked: "排除的域名", domainsHelp: "支持粘贴多行域名,规则包含子域名并同时约束网页读取。排除优先。", allowedHelp: "留空时不限制域名。", blockedHelp: "留空时不排除域名。", add: "添加", remove: "删除", removeDomain: (domain: string) => `删除 ${domain}`, domainPlaceholder: "添加域名,例如 sqlite.org", invalidDomains: (names: string) => `域名格式不正确:${names}`, tooManyDomains: "每份列表最多 100 个域名。", domainConflict: (names: string) => `以下域名同时出现在两份列表中,将被排除:${names}`, engineHelp: "自动按 Core 推荐顺序搜索,失败或无可用结果时切换引擎;也可多选指定优先顺序。", maxResults: "搜索结果数", readPages: "摘要不足时读取网页数", pageChars: "每页最多返回字符", timeout: "每次操作超时(秒)", concurrent: "最大并发", interval: "同一引擎请求间隔(毫秒)", cache: "缓存有效期(秒)", toolCalls: "每个请求最多执行工具次数", fallback: "独立搜索失败时允许回退上游", fallbackHelp: "回退可能产生上游模型和搜索费用;已交回模型的工具结果不重放。", advanced: "限额与缓存", readHelp: "设为 0 时搜索只返回摘要;模型仍可明确请求读取网页。", search: "搜索", open: "读取网页", find: "页内查找", query: "查询词", url: "网页 URL", pattern: "查找文本", run: "执行测试", testing: "正在执行…", testHelp: "使用已保存的配置,由当前连接的 Core 实际联网执行。", noResults: "没有匹配的结果。", cached: "命中缓存", fetched: "实际获取", elapsed: (ms: number) => `${ms} 毫秒`, partial: "部分来源未成功", truncated: "内容已按配置截断", invalid: "请检查数值范围和域名格式。", @@ -18,9 +19,10 @@ export const webToolsText = messages( core: "Run in Core", upstream: "Run upstream", coreHelp: "Standalone searches return results directly. Web operations within a conversation return to the model. Main-model usage is still billed.", upstreamHelp: "Forward the client's original requests through routing rules.", configure: "Configure", test: "Test", save: "Save", cancel: "Cancel", retry: "Retry", loading: "Loading web-tool configuration…", unavailable: "Web-tool configuration is unavailable. Check the connection and that Core supports web tools.", local: "Runs on: local Core", remote: (name: string) => `Runs on: ${name}`, + googleDocsHelp: "Google (Docs) searches the web, with at least 6 seconds between requests. Regional preferences are not supported.", engines: "Search engines", auto: "Automatic", findEngine: "Find an engine", noEngineMatch: "No matching engines", engineCount: (n: number) => `${n} engines selected`, proxy: "Network", system: "System proxy", direct: "Direct", language: "Search language", region: "Country or region", automatic: (name: string) => `System (${name})`, automaticUnknown: "System (search engine default)", unknownLocale: "Current selection", noLocaleMatch: "No matching language or region", - localeLocal: "Automatic uses the local Core’s system settings.", localeRemote: (name: string) => `Automatic uses the system settings of remote Core “${name}”.`, localeHelp: "Search by name to override either preference. Search engines apply these preferences where supported.", allowed: "Allowed domains", blocked: "Blocked domains", domainsHelp: "Paste multiple hostnames on separate lines. Rules include subdomains and apply to page reading. Blocked domains take priority.", allowedHelp: "Empty allows all domains.", blockedHelp: "Empty blocks no domains.", add: "Add", remove: "Delete", removeDomain: (domain: string) => `Delete ${domain}`, domainPlaceholder: "Add a hostname, e.g. sqlite.org", invalidDomains: (names: string) => `Invalid hostnames: ${names}`, tooManyDomains: "Each list supports up to 100 hostnames.", domainConflict: (names: string) => `These domains appear in both lists and will be blocked: ${names}`, engineHelp: "Use available engines automatically, or select specific engines. Additional engines fill remaining results.", + localeLocal: "Automatic uses the local Core’s system settings.", localeRemote: (name: string) => `Automatic uses the system settings of remote Core “${name}”.`, localeHelp: "Search by name to override either preference. Search engines apply these preferences where supported.", allowed: "Allowed domains", blocked: "Blocked domains", domainsHelp: "Paste multiple hostnames on separate lines. Rules include subdomains and apply to page reading. Blocked domains take priority.", allowedHelp: "Empty allows all domains.", blockedHelp: "Empty blocks no domains.", add: "Add", remove: "Delete", removeDomain: (domain: string) => `Delete ${domain}`, domainPlaceholder: "Add a hostname, e.g. sqlite.org", invalidDomains: (names: string) => `Invalid hostnames: ${names}`, tooManyDomains: "Each list supports up to 100 hostnames.", domainConflict: (names: string) => `These domains appear in both lists and will be blocked: ${names}`, engineHelp: "Automatic follows Core’s recommended order and switches engines on failure or no usable results. Select engines to set your own priority.", maxResults: "Search results", readPages: "Read pages when snippets are insufficient", pageChars: "Maximum characters per page", timeout: "Operation timeout (seconds)", concurrent: "Concurrent operations", interval: "Interval per engine (milliseconds)", cache: "Cache lifetime (seconds)", toolCalls: "Maximum tool calls per request", fallback: "Allow upstream fallback if a standalone search fails", fallbackHelp: "Fallback may incur upstream model and search fees. Tool results already given to the model are not replayed.", advanced: "Limits and cache", readHelp: "Zero returns snippets only from searches. The model can still explicitly request a page.", search: "Search", open: "Read page", find: "Find in page", query: "Query", url: "Page URL", pattern: "Find text", run: "Run test", testing: "Running…", testHelp: "Uses the saved configuration and makes real network requests from the connected Core.", noResults: "No matching results.", cached: "Cache hit", fetched: "Fetched", elapsed: (ms: number) => `${ms} ms`, partial: "Some sources failed", truncated: "Content was truncated to the configured limit", invalid: "Check the numeric ranges and domain names.", diff --git a/src/routing/WebTools.tsx b/src/routing/WebTools.tsx index feaf6971..f8c8f78b 100644 --- a/src/routing/WebTools.tsx +++ b/src/routing/WebTools.tsx @@ -11,6 +11,7 @@ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/ui/collap import { TableRow, TableCell } from "@/ui/table"; import { DomainList } from "./DomainList"; import { EnginePicker } from "./EnginePicker"; +import { engineName } from "@/webToolsCompat"; import { Segmented } from "@/ui/segmented"; import { SelectField, SelectOption } from "@/ui/select-field"; import { Combobox, ComboboxInput, ComboboxContent, ComboboxList, ComboboxItem, ComboboxEmpty } from "@/ui/combobox"; @@ -62,7 +63,7 @@ export function WebTools({ overview }: { overview: Overview }) { { if (!open && !busy) setDialog(null); }}> e.preventDefault()}> {view && dialog === "config" && setDialog(null)} />} - {view && dialog === "test" && } + {view && dialog === "test" && } ; @@ -86,9 +87,10 @@ function Configuration({ view, overview, busy, error, save, close }: { view: Web return <> {t.title}{t.intro}
- set("engines", value)} /> + set("engines", value)} /> set("proxy", nextValue)}>{t.system}{t.direct}{overview.proxies.map((p) => {p.name})}

{t.engineHelp}

+ {view.available_engines?.some((engine) => engine.id === "google_docs") && (!config.engines.length || config.engines.includes("google_docs")) &&

{t.googleDocsHelp}

} set("language", value)} /> set("region", value)} />

{remote ? t.localeRemote(remote.name) : t.localeLocal} {t.localeHelp}

@@ -123,7 +125,7 @@ function LocalePicker({ id, kind, value, detected, disabled, onChange }: { id: s ; } -function Tester() { +function Tester({ view }: { view: WebToolsView }) { const id = useId(); const t = useText(webToolsText); const [action, setAction] = useState("search"); @@ -148,7 +150,7 @@ function Tester() {

{result.cached ? t.cached : t.fetched} · {t.elapsed(result.elapsed_ms)}{result.truncated ? ` · ${t.truncated}` : ""}

{result.warnings.map((warning, i) =>

{t.partial}: {errorText(warning)}

)} {!result.sources.length &&

{t.noResults}

} - {result.sources.map((source, i) => )} + {result.sources.map((source, i) => )}
} ; diff --git a/src/types.ts b/src/types.ts index 803e0a79..4d4e5b2d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,7 +2,8 @@ // // **控制面契约的类型不在这里写。**它们由钉着的那版 tw-api 生成,提交在 // `./generated/tw-api.ts`(`src-tauri/tests/ts_bindings.rs` 核对它和钉着的 -// core 一致),这里原样转出去。以前这里是手抄的镜像,和 Rust 那边对不对得 +// core 一致),这里转出去。搜索引擎 ID 经 webToolsCompat 扩展,跟随连接的 Core。 +// 以前这里是手抄的镜像,和 Rust 那边对不对得 // 上全靠人记得改两遍。**不经过 core 的那几样**(客户端接管、MCP、扫描、这台 // 机器上的事件)同样是生成的:`./generated/lite-api.ts`,源头是 `src-tauri/src/wire.rs`。 // @@ -29,6 +30,8 @@ import type { LocalEvent } from "./generated/lite-api"; export type * from "./generated/tw-api"; export type * from "./generated/lite-api"; +// Engine IDs and capabilities are supplied by the connected Core. +export type { SearchEngine, WebSearchEngine, WebToolsConfig, WebToolsSave, WebSource, WebToolResult, WebToolsView, Endpoints } from "./webToolsCompat"; /** core 的事件流上的一条 */ export type CoreEvent = Event; diff --git a/src/webToolsCompat.ts b/src/webToolsCompat.ts new file mode 100644 index 00000000..70c63f02 --- /dev/null +++ b/src/webToolsCompat.ts @@ -0,0 +1,28 @@ +import type * as Api from "./generated/tw-api"; + +// Search adapters belong to the connected Core. Keep the pinned generated API +// intact while allowing these capability IDs to grow independently of Lite. +export type SearchEngine = string; +export type WebSearchEngine = { id: SearchEngine; name: string; min_interval_ms: number }; +export type WebToolsConfig = Omit & { engines: SearchEngine[] }; +export type WebToolsSave = Omit & { config: WebToolsConfig }; +export type WebSource = Omit & { engine: SearchEngine | null }; +export type WebToolResult = Omit & { sources: WebSource[] }; +export type WebToolsView = Omit & { + config: WebToolsConfig; + available_engines?: WebSearchEngine[]; +}; +export type Endpoints = Omit & { + WebTools: Omit & { res: WebToolsView }; + SaveWebTools: Omit & { req: WebToolsSave }; + TestWebTool: Omit & { res: WebToolResult }; +}; + +export const legacyEngines: WebSearchEngine[] = [ + { id: "bing", name: "Bing", min_interval_ms: 0 }, + { id: "duckduckgo", name: "DuckDuckGo", min_interval_ms: 0 }, +]; + +export function engineName(id: string, available = legacyEngines): string { + return available.find((engine) => engine.id === id)?.name ?? id; +}