From 083cfe0086cd167e3fa5665435655c0a5aa5e953 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:56:09 +0800 Subject: [PATCH 1/4] feat(routing): configure Core web tools with system locale defaults --- scripts/shots/mock/core.ts | 6 ++ scripts/shots/scenes.ts | 29 ++++++ src-tauri/Cargo.lock | 14 +-- src-tauri/Cargo.toml | 14 +-- src-tauri/src/call.rs | 3 + src/control.ts | 3 + src/generated/tw-api.ts | 58 ++++++++++- src/i18n/core.zh.json | 4 +- src/routing/ProbesTab.i18n.ts | 4 +- src/routing/ProbesTab.tsx | 2 + src/routing/WebTools.i18n.ts | 28 +++++ src/routing/WebTools.tsx | 145 ++++++++++++++++++++++++++ src/routing/webToolsForm.test.ts | 24 +++++ src/routing/webToolsForm.ts | 18 ++++ src/routing/webToolsLocale.test.ts | 29 ++++++ src/routing/webToolsLocale.ts | 26 +++++ src/traffic/drawer/Content.tsx | 2 + src/traffic/drawer/WebToolSummary.tsx | 25 +++++ 18 files changed, 417 insertions(+), 17 deletions(-) create mode 100644 src/routing/WebTools.i18n.ts create mode 100644 src/routing/WebTools.tsx create mode 100644 src/routing/webToolsForm.test.ts create mode 100644 src/routing/webToolsForm.ts create mode 100644 src/routing/webToolsLocale.test.ts create mode 100644 src/routing/webToolsLocale.ts create mode 100644 src/traffic/drawer/WebToolSummary.tsx diff --git a/scripts/shots/mock/core.ts b/scripts/shots/mock/core.ts index ba77b5bd..6506ee30 100644 --- a/scripts/shots/mock/core.ts +++ b/scripts/shots/mock/core.ts @@ -88,6 +88,12 @@ 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: { + 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, + } }), + SaveWebTools: refuse, + TestWebTool: refuse, // 导入导出与备份:只读的列一份当前版本,写的拒绝 ConfigItems: () => overview(lastSeen()).providers.map((p) => ({ item: { kind: "provider", name: p.name }, refs: [] })), ExportConfig: refuse, diff --git a/scripts/shots/scenes.ts b/scripts/shots/scenes.ts index e1be482e..fec02b9e 100644 --- a/scripts/shots/scenes.ts +++ b/scripts/shots/scenes.ts @@ -7,6 +7,8 @@ // i18n 表里取,所以中英两种界面走的是同一段代码。 import { textOf } from "@/i18n"; import { connText } from "@/connection/connection.i18n"; +import { webToolsText } from "@/routing/WebTools.i18n"; +import { routingPageText } from "@/routing/RoutingPage.i18n"; import { routingText } from "@/routing/routing.i18n"; import { byText, choose, click, idle, type, waitFor } from "./drive"; @@ -41,6 +43,33 @@ export const SCENES: Scene[] = [ { id: "keys", page: "keys" }, { id: "upstreams", page: "upstreams" }, { id: "routing", page: "routing" }, + { + id: "web-tools", page: "routing", + setup: async () => { + click(await waitFor(() => byText(textOf(routingPageText).probes))); + const title = await waitFor(() => byText(textOf(webToolsText).title, "section div")); + title.scrollIntoView({ block: "center" }); + }, + }, + { + id: "web-tools-config", page: "routing", remote: true, + setup: async () => { + click(await waitFor(() => byText(textOf(routingPageText).probes))); + click(await waitFor(() => byText(textOf(webToolsText).configure))); + await waitFor("[role=dialog]"); + }, + }, + { + id: "web-tools-language", page: "routing", remote: true, + setup: async () => { + click(await waitFor(() => byText(textOf(routingPageText).probes))); + click(await waitFor(() => byText(textOf(webToolsText).configure))); + const input = await waitFor("[role=dialog] input[id$='-language']"); + click(input); + type(input, textOf(webToolsText) === webToolsText.zh ? "中文" : "Chinese"); + await waitFor("[role=listbox]"); + }, + }, { id: "security", page: "security" }, { id: "mcp", page: "mcp" }, { id: "settings", page: "settings" }, diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index a51a5ffe..18da2bad 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5460,7 +5460,7 @@ dependencies = [ [[package]] name = "tw-api" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "serde", "serde_json", @@ -5472,7 +5472,7 @@ dependencies = [ [[package]] name = "tw-dialect" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "memchr", "serde", @@ -5482,7 +5482,7 @@ dependencies = [ [[package]] name = "tw-guard" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -5504,7 +5504,7 @@ dependencies = [ [[package]] name = "tw-link" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "serde", "serde_json", @@ -5531,7 +5531,7 @@ dependencies = [ [[package]] name = "tw-types" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "serde", "ts-rs", @@ -5540,7 +5540,7 @@ dependencies = [ [[package]] name = "tw-watch" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "libc", "notify", @@ -5551,7 +5551,7 @@ dependencies = [ [[package]] name = "tw-yaml" version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.96.0#a49d0a84dafe01f12081116e74929e1a9bc71be8" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" dependencies = [ "saphyr-parser", "thiserror 2.0.21", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f1b9403b..6caea1db 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -25,13 +25,15 @@ license = "MIT" # 走意味着同一份源码今天和明天编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 # twcore 二进制必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是 # 从 tw-api 锁到的 tag 去取二进制的(见 scripts/fetch-core.sh)。 +# Pending the hosted-web-tools Core release; switch this immutable development +# revision to its release tag before bundling. See the linked Core pull request. [workspace.dependencies] -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.96.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.96.0" } -tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.96.0" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.96.0" } -tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.96.0" } -tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.96.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } +tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } +tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } +tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } [lib] name = "thinkwatch_lite_lib" diff --git a/src-tauri/src/call.rs b/src-tauri/src/call.rs index 7624c96d..708e0aec 100644 --- a/src-tauri/src/call.rs +++ b/src-tauri/src/call.rs @@ -72,6 +72,9 @@ webview_endpoints![ ConfigRepairPlan, RepairConfig, SaveListen, + WebTools, + SaveWebTools, + TestWebTool, // 记录。搜索翻的是整个库,界面自己发起、自己翻页 History, HistorySearch, diff --git a/src/control.ts b/src/control.ts index eb21614d..c2271434 100644 --- a/src/control.ts +++ b/src/control.ts @@ -40,6 +40,9 @@ export const WEBVIEW_ENDPOINTS = [ "ConfigRepairPlan", "RepairConfig", "SaveListen", + "WebTools", + "SaveWebTools", + "TestWebTool", "History", "HistorySearch", "RequestDetail", diff --git a/src/generated/tw-api.ts b/src/generated/tw-api.ts index 29d07cf4..1e1e872c 100644 --- a/src/generated/tw-api.ts +++ b/src/generated/tw-api.ts @@ -1,6 +1,6 @@ // Generated by tw-api (`tw_api::ts::export_all`). Do not edit by hand. -export const CONTROL_API_VERSION = 60; +export const CONTROL_API_VERSION = 61; /** * 手动中止(`POST /request/{id}/abort`、`POST /sessions/{id}/abort`)叫停了哪几个请求。 @@ -5118,6 +5118,8 @@ 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"; + /** * 一页搜索停在哪儿的原因。 */ @@ -6588,6 +6590,54 @@ export type UsageView = { input: number, output: number, cache_read: number, cac */ cache_1h?: boolean, }; +export type WebSearchLocale = { language: string, region: string, }; + +export type WebSource = { url: string, title: string, text: string, engine: SearchEngine | null, published_at: string | null, }; + +export type WebToolRequest = { "action": "search", query: string, allowed_domains: Array, blocked_domains: Array, } | { "action": "open_page", url: string, offset: number, } | { "action": "find_in_page", url: string, pattern: string, }; + +export type WebToolResult = { sources: Array, cached: boolean, elapsed_ms: number, +/** + * Partial-source failures, distinct from a successful search with zero results. + */ +warnings: Array, truncated: boolean, }; + +export type WebToolsConfig = { mode: WebToolsMode, +/** + * Empty chooses healthy engines automatically; otherwise tried in this order. + */ +engines: Array, +/** + * An existing proxy name, "system", or "direct". + */ +proxy: string, +/** + * Empty follows the system language on the host running Core. + */ +language: string, +/** + * Empty follows the region in that host's system locale, when available. + */ +region: string, allowed_domains: Array, blocked_domains: Array, max_results: number, +/** + * Number of search result pages to read when snippets are insufficient. Zero disables it. + */ +read_pages: number, max_page_chars: number, timeout_secs: number, max_concurrent: number, interval_ms: number, cache_secs: number, max_tool_calls: number, +/** + * Only before any search result is used; never silently switches paid services on. + */ +fallback_to_upstream: boolean, }; + +export type WebToolsMode = "upstream" | "core"; + +export type WebToolsSave = { base_version: string, config: WebToolsConfig, }; + +export type WebToolsView = { config: WebToolsConfig, config_version: string, +/** + * Detected on the Core host, which may be remote. Empty fields mean unavailable. + */ +system_locale: WebSearchLocale, }; + /** * 聚合类端点的时间窗(`GET /summary`、`/latency`)。**缺省是「今天」而不是 * 「最近 24 小时」** —— 用户问的是「今天花了多少」,那是个从零点算起的问题。 @@ -6702,6 +6752,9 @@ export const ENDPOINTS = { PinKeys: { method: "PUT", path: "/pinned-keys", params: [], format: "json" }, ConfigRepairPlan: { method: "GET", path: "/config/repair", params: [], format: "json" }, RepairConfig: { method: "POST", path: "/config/repair", params: [], format: "json" }, + WebTools: { method: "GET", path: "/web-tools", params: [], format: "json" }, + SaveWebTools: { method: "PUT", path: "/web-tools", params: [], format: "json" }, + TestWebTool: { method: "POST", path: "/web-tools/test", params: [], format: "json" }, SaveListen: { method: "PUT", path: "/listen", params: [], format: "json" }, Summary: { method: "GET", path: "/summary", params: [], format: "json" }, CostBuckets: { method: "GET", path: "/summary/buckets", params: [], format: "json" }, @@ -6860,6 +6913,9 @@ export type Endpoints = { PinKeys: { req: PinnedKeys; res: null }; ConfigRepairPlan: { req: null; res: ConfigRepair }; RepairConfig: { req: ConfigRepairRequest; res: ConfigWritten }; + WebTools: { req: null; res: WebToolsView }; + SaveWebTools: { req: WebToolsSave; res: ConfigWritten }; + TestWebTool: { req: WebToolRequest; res: WebToolResult }; SaveListen: { req: ListenSave; res: ConfigWritten }; Summary: { req: Window; res: Summary }; CostBuckets: { req: BucketQuery; res: Array }; diff --git a/src/i18n/core.zh.json b/src/i18n/core.zh.json index be7bcca0..d6b47e65 100644 --- a/src/i18n/core.zh.json +++ b/src/i18n/core.zh.json @@ -1183,6 +1183,8 @@ "wsl.listener_restore": "同时移除 Lite 添加且已无客户端需要的监听和来源规则;独立修改过的设置会保留。", "wsl.rollback_failed": "WSL 接管失败,且因设置已变化或控制面不可用,无法回退监听:{detail}。请检查网关监听设置;接管记录已保留。", "wsl.stopped": "WSL · {distro} 已停止。启动发行版后才能检查网关连通性。", - "wsl.listener_cleanup_failed": "客户端配置已还原,但未能移除闲置的 WSL 监听或来源规则:{detail}。请检查网关监听设置;清理记录已保留。" + "wsl.listener_cleanup_failed": "客户端配置已还原,但未能移除闲置的 WSL 监听或来源规则:{detail}。请检查网关监听设置;清理记录已保留。", + "gw.web_tools.failed": "联网工具:{detail}", + "config.web_tools.invalid": "联网工具配置无效:{detail}" } } diff --git a/src/routing/ProbesTab.i18n.ts b/src/routing/ProbesTab.i18n.ts index 5b748465..86139e18 100644 --- a/src/routing/ProbesTab.i18n.ts +++ b/src/routing/ProbesTab.i18n.ts @@ -3,7 +3,7 @@ import { messages } from "@/i18n"; export const probesTabText = messages( { intro: - "客户端自动发起的辅助请求,不由用户操作触发,同样产生费用。这一层先过,剩下的才轮到规则。", + "配置客户端辅助请求及联网工具的执行方式。设为转发的请求继续按路由规则选择上游。", intercept: "本地应答", interceptWhat: "由网关直接应答,不发送到上游,不产生费用。", forward: "转发", @@ -12,7 +12,7 @@ export const probesTabText = messages( }, { intro: - "Auxiliary requests that clients send on their own, without any user action. They incur costs as well, and they pass through here before any rule is evaluated.", + "Choose how client auxiliary requests and web tools are handled. Forwarded requests continue through routing rules.", intercept: "Answer locally", interceptWhat: "The gateway answers directly. Nothing is sent upstream and no cost is incurred.", forward: "Forward", diff --git a/src/routing/ProbesTab.tsx b/src/routing/ProbesTab.tsx index 388f9908..d383c8eb 100644 --- a/src/routing/ProbesTab.tsx +++ b/src/routing/ProbesTab.tsx @@ -7,6 +7,7 @@ import { useText } from "@/i18n"; import { PROBES, probeLabel } from "@/labels"; import { patchConfig } from "@/patch"; import type { Overview, ProbeMode } from "@/types"; +import { WebTools } from "./WebTools"; import { probesTabText } from "./ProbesTab.i18n"; /** @@ -94,6 +95,7 @@ export function ProbesTab({ ov }: { ov: Overview }) { })}

{t.ruleHint}

+ ); } diff --git a/src/routing/WebTools.i18n.ts b/src/routing/WebTools.i18n.ts new file mode 100644 index 00000000..185cfe69 --- /dev/null +++ b/src/routing/WebTools.i18n.ts @@ -0,0 +1,28 @@ +import { messages } from "@/i18n"; + +export const webToolsText = messages( + { + title: "联网搜索与网页读取", intro: "选择搜索、读取网页和页内查找由谁执行。普通对话继续按路由规则选择模型。", + core: "Core 执行", upstream: "上游执行", coreHelp: "独立搜索直接返回结果;对话中的联网操作执行后交回模型。主模型仍按实际用量计费。", + upstreamHelp: "保留客户端原有请求,按路由规则交给上游。", configure: "配置", test: "测试", save: "保存", cancel: "取消", retry: "重试", loading: "正在读取搜索配置…", + unavailable: "无法读取联网工具配置。请确认连接正常,且 Core 已支持联网工具。", local: "执行位置:本机 Core", remote: (name: string) => `执行位置:${name}`, + engines: "搜索引擎", auto: "自动选择可用引擎", bingFirst: "Bing → DuckDuckGo", duckFirst: "DuckDuckGo → Bing", proxy: "网络出口", system: "跟随系统", direct: "直连", + language: "搜索语言", region: "国家或地区", automatic: (name: string) => `跟随系统(${name})`, automaticUnknown: "跟随系统(由搜索引擎决定)", unknownLocale: "当前设置", noLocaleMatch: "没有匹配的语言或地区", + localeLocal: "自动使用本机 Core 的系统设置。", localeRemote: (name: string) => `自动使用远程 Core「${name}」的系统设置。`, localeHelp: "可按名称搜索并单独修改语言或地区;搜索引擎会尽量按此偏好返回结果。", allowed: "仅搜索这些域名", blocked: "排除这些域名", domainsHelp: "用逗号或换行分隔域名,例如 sqlite.org。规则也约束网页读取。", + 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: "请检查数值范围和域名格式。", + }, + { + title: "Web search and page reading", intro: "Choose who runs search, page reading, and find-in-page. Model requests continue to follow routing rules.", + 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}`, + engines: "Search engines", auto: "Choose available engines automatically", bingFirst: "Bing → DuckDuckGo", duckFirst: "DuckDuckGo → Bing", 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: "Separate hostnames with commas or newlines, for example sqlite.org. Rules also apply to page reading.", + 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 new file mode 100644 index 00000000..42c0050d --- /dev/null +++ b/src/routing/WebTools.tsx @@ -0,0 +1,145 @@ +import { useId, useRef, useEffect, useState } from "react"; +import { call } from "@/control"; +import { useResource } from "@/lib/resource"; +import { useLang, useText } from "@/i18n"; +import { useRemote } from "@/connection/useRemote"; +import { Button } from "@/ui/button"; +import { Input } from "@/ui/input"; +import { Checkbox } from "@/ui/checkbox"; +import { Segmented } from "@/ui/segmented"; +import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; +import { Combobox, ComboboxInput, ComboboxContent, ComboboxList, ComboboxItem, ComboboxEmpty } from "@/ui/combobox"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/ui/dialog"; +import { DialogError, FormItem } from "@/upstreams/parts"; +import { errorText } from "@/upstreams/labels"; +import type { Overview, WebToolsConfig, WebToolsView, WebToolResult, WebToolRequest, SearchEngine } from "@/types"; +import { webToolsText } from "./WebTools.i18n"; +import { domains, validWebConfig, WEB_LIMITS } from "./webToolsForm"; +import { localeName, localeOptions, type LocaleKind, type LocaleOption } from "./webToolsLocale"; + +export function WebTools({ overview }: { overview: Overview }) { + const t = useText(webToolsText); + const active = useRef(true); + useEffect(() => { active.current = true; return () => { active.current = false; }; }, []); + const remote = useRemote(); + const resource = useResource("web-tools", () => call("WebTools", null), { deps: [overview.config_version] }); + const [dialog, setDialog] = useState<"config" | "test" | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const view = resource.data; + async function save(config: WebToolsConfig, base = view?.config_version) { + if (!base || !view) return; + setBusy(true); setError(null); + try { + const result = await call("SaveWebTools", { base_version: base, config }); + if (!active.current) return; + resource.mutate({ ...view, config, config_version: result.version }); + setDialog(null); + } catch (e) { setError(errorText(e)); } + finally { setBusy(false); } + } + return
+
+
{t.title}

{t.intro}

+ {view && void save({ ...view.config, mode })} />} +
+

{remote ? t.remote(remote.name) : t.local}

+ {view ? <> +

{view.config.mode === "core" ? t.coreHelp : t.upstreamHelp}

+
+ :
{resource.error ? <>{t.unavailable} : t.loading}
} + + { if (!open && !busy) setDialog(null); }}> + e.preventDefault()}> + {view && dialog === "config" && setDialog(null)} />} + {view && dialog === "test" && } + + +
; +} + +function Configuration({ view, overview, busy, error, save, close }: { view: WebToolsView; overview: Overview; busy: boolean; error: string | null; save: (config: WebToolsConfig, base: string) => Promise; close: () => void }) { + const t = useText(webToolsText); + const remote = useRemote(); + const id = useId(); + const [baseVersion] = useState(view.config_version); + const [config, setConfig] = useState(view.config); + const [allowed, setAllowed] = useState(config.allowed_domains.join(", ")); + const [blocked, setBlocked] = useState(config.blocked_domains.join(", ")); + const set = (key: K, value: WebToolsConfig[K]) => setConfig((c) => ({ ...c, [key]: value })); + const draft = { ...config, allowed_domains: domains(allowed), blocked_domains: domains(blocked) }; + const valid = validWebConfig(draft); + const numeric = [ + ["max_results", t.maxResults], ["read_pages", t.readPages], ["max_page_chars", t.pageChars], ["timeout_secs", t.timeout], + ["max_concurrent", t.concurrent], ["interval_ms", t.interval], ["cache_secs", t.cache], ["max_tool_calls", t.toolCalls], + ] as const; + return <> + {t.title}{t.intro} +
+ set("engines", e.target.value ? e.target.value.split(",") as SearchEngine[] : [])}> + {t.auto}{t.bingFirst}{t.duckFirst}BingDuckDuckGo + + set("proxy", e.target.value)}>{t.system}{t.direct}{overview.proxies.map((p) => {p.name})} + set("language", value)} /> + set("region", value)} /> +

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

+ setAllowed(e.target.value)} /> + setBlocked(e.target.value)} /> +

{t.domainsHelp}

+ {numeric.slice(0, 2).map(([key, label]) => set(key, Number(e.target.value))} />)} +
{t.advanced}
+ {numeric.slice(2).map(([key, label]) => set(key, Number(e.target.value))} />)} +
+

{t.readHelp}

+ +

{t.fallbackHelp}

+
+ + + ; +} + +function LocalePicker({ id, kind, value, detected, disabled, onChange }: { id: string; kind: LocaleKind; value: string; detected: string; disabled: boolean; onChange: (value: string) => void }) { + const t = useText(webToolsText); + const lang = useLang(); + const detectedName = localeName(kind, detected, lang); + const automatic = detectedName ? t.automatic(detectedName) : t.automaticUnknown; + const options = localeOptions(kind, lang, value, automatic, t.unknownLocale); + return + option.value === value)} disabled={disabled} itemToStringLabel={(option: LocaleOption) => option.label} onValueChange={(option) => { if (option) onChange(option.value); }}> + + {t.noLocaleMatch}{(option: LocaleOption) => {option.label}} + + ; +} + +function Tester() { + const id = useId(); + const t = useText(webToolsText); + const [action, setAction] = useState("search"); + const [input, setInput] = useState(""); + const [pattern, setPattern] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [result, setResult] = useState(null); + async function run() { + const request: WebToolRequest = action === "search" ? { action, query: input, allowed_domains: [], blocked_domains: [] } + : action === "open_page" ? { action, url: input, offset: 0 } : { action, url: input, pattern }; + setBusy(true); setError(null); setResult(null); + try { setResult(await call("TestWebTool", request)); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } + } + return <> + {t.test} · {t.title}{t.testHelp} + { setAction(value); setResult(null); setError(null); }} /> + setInput(e.target.value)} /> + {action === "find_in_page" && setPattern(e.target.value)} />} + + {result &&
+

{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) => )} +
} + + ; +} diff --git a/src/routing/webToolsForm.test.ts b/src/routing/webToolsForm.test.ts new file mode 100644 index 00000000..eec1690b --- /dev/null +++ b/src/routing/webToolsForm.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { domains, validWebConfig } from "./webToolsForm"; +import type { WebToolsConfig } from "@/types"; + +const config: WebToolsConfig = { + mode: "core", 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, +}; + +describe("web tool configuration", () => { + it("accepts hostnames and rejects URLs and wildcard filters", () => { + expect(domains(" SQLite.org, docs.example.org\nsqlite.org ")).toEqual(["sqlite.org", "docs.example.org"]); + expect(validWebConfig({ ...config, allowed_domains: ["sqlite.org"] })).toBe(true); + for (const domain of ["https://sqlite.org", "*.sqlite.org", "sqlite.org:443", "-sqlite.org"]) { + expect(validWebConfig({ ...config, allowed_domains: [domain] })).toBe(false); + } + }); + it("accepts zero cache/page-prefetch and rejects invalid resource limits", () => { + expect(validWebConfig({ ...config, cache_secs: 0, read_pages: 0 })).toBe(true); + expect(validWebConfig({ ...config, max_concurrent: 0 })).toBe(false); + expect(validWebConfig({ ...config, timeout_secs: NaN })).toBe(false); + expect(validWebConfig({ ...config, max_tool_calls: 1.5 })).toBe(false); + }); +}); diff --git a/src/routing/webToolsForm.ts b/src/routing/webToolsForm.ts new file mode 100644 index 00000000..cc9c5c5d --- /dev/null +++ b/src/routing/webToolsForm.ts @@ -0,0 +1,18 @@ +import type { WebToolsConfig } from "@/types"; + +export const WEB_LIMITS = { + max_results: [1, 20], read_pages: [0, 5], max_page_chars: [1000, 50000], timeout_secs: [1, 120], + max_concurrent: [1, 16], interval_ms: [250, 60000], cache_secs: [0, 86400], max_tool_calls: [1, 32], +} as const; + +export function domains(text: string): string[] { + return [...new Set(text.split(/[\s,,]+/).map((s) => s.trim().toLowerCase()).filter(Boolean))]; +} + +export function validWebConfig(c: WebToolsConfig): boolean { + return Object.entries(WEB_LIMITS).every(([key, [min, max]]) => { + const n = c[key as keyof typeof WEB_LIMITS]; + return Number.isInteger(n) && n >= min && n <= max; + }) && c.allowed_domains.length <= 100 && c.blocked_domains.length <= 100 && [...c.allowed_domains, ...c.blocked_domains].every((s) => s.length <= 253 && s.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))) + && [c.language, c.region].every((s) => s.length <= 35 && /^[a-z0-9-]*$/i.test(s)); +} diff --git a/src/routing/webToolsLocale.test.ts b/src/routing/webToolsLocale.test.ts new file mode 100644 index 00000000..f0c45474 --- /dev/null +++ b/src/routing/webToolsLocale.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { localeName, localeOptions } from "./webToolsLocale"; + +describe("search locale choices", () => { + it("shows translated names and distinguishes writing systems", () => { + expect(localeName("language", "zh-Hans", "zh")).toContain("简体"); + expect(localeName("language", "zh-Hant", "en")).toContain("Traditional"); + expect(localeName("region", "US", "zh")).toBe("美国"); + expect(localeName("region", "GB", "en")).toBe("United Kingdom"); + }); + + it("keeps auto empty and preserves a valid tag set outside the picker", () => { + const options = localeOptions("language", "en", "pt-BR", "System (English)", "Current selection"); + expect(options[0]).toEqual({ value: "", label: "System (English)" }); + expect(options.find((o) => o.value === "pt-BR")?.label).toContain("Brazil"); + expect(options.some((o) => o.value === "zh-Hans")).toBe(true); + expect(options.some((o) => o.value === "zh-Hant")).toBe(true); + expect(new Set(options.map((o) => o.value)).size).toBe(options.length); + }); + + it("offers named countries and handles an unknown system locale without inventing one", () => { + const options = localeOptions("region", "zh", "", "跟随系统", "当前设置"); + expect(options).toContainEqual({ value: "CN", label: "中国" }); + expect(options).toContainEqual({ value: "JP", label: "日本" }); + expect(options.every((o) => !o.value || o.label !== o.value)).toBe(true); + expect(localeName("language", "", "en")).toBeUndefined(); + expect(localeName("language", "malformed_tag", "en")).toBeUndefined(); + }); +}); diff --git a/src/routing/webToolsLocale.ts b/src/routing/webToolsLocale.ts new file mode 100644 index 00000000..61113c0a --- /dev/null +++ b/src/routing/webToolsLocale.ts @@ -0,0 +1,26 @@ +import type { Lang } from "@/i18n"; + +// ISO 639-1 and ISO 3166-1 identifiers are storage values only. DisplayNames +// supplies readable names in the UI language; the combobox searches those names. +const LANGUAGES = "aa ab ae af ak am an ar as av ay az ba be bg bh bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zh-Hans zh-Hant zu".split(" "); +const REGIONS = "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(" "); + +export type LocaleOption = { value: string; label: string }; +export type LocaleKind = "language" | "region"; + +export function localeName(kind: LocaleKind, code: string, lang: Lang): string | undefined { + if (!code) return undefined; + try { + return new Intl.DisplayNames([lang], { type: kind, fallback: "none" }).of(code); + } catch { return undefined; } +} + +export function localeOptions(kind: LocaleKind, lang: Lang, current: string, automatic: string, unknown: string): LocaleOption[] { + const codes = kind === "language" ? LANGUAGES : REGIONS; + const options = [...new Set([...codes, ...(current ? [current] : [])])] + .map((value) => ({ value, label: localeName(kind, value, lang) })) + .filter((item): item is LocaleOption => !!item.label || item.value === current) + .map((item) => ({ ...item, label: item.label || unknown })) + .sort((a, b) => a.label.localeCompare(b.label, lang)); + return [{ value: "", label: automatic }, ...options]; +} diff --git a/src/traffic/drawer/Content.tsx b/src/traffic/drawer/Content.tsx index 9429984e..23f5f370 100644 --- a/src/traffic/drawer/Content.tsx +++ b/src/traffic/drawer/Content.tsx @@ -11,6 +11,7 @@ import { Pill } from "../Conversation"; import { contentText } from "./Content.i18n"; import { dialectOf } from "./dialect"; import type { LiveContent } from "./live"; +import { WebToolSummary } from "./WebToolSummary"; import { Parsed } from "./Parsed"; import { Raw } from "./Raw"; import { requestDrawerText } from "./RequestDrawer.i18n"; @@ -118,6 +119,7 @@ export function Content({ return (
+
label={t.viewsLabel} diff --git a/src/traffic/drawer/WebToolSummary.tsx b/src/traffic/drawer/WebToolSummary.tsx new file mode 100644 index 00000000..29cd8060 --- /dev/null +++ b/src/traffic/drawer/WebToolSummary.tsx @@ -0,0 +1,25 @@ +import { useText } from "@/i18n"; +import type { HeadView } from "@/types"; +import { webToolsText } from "@/routing/WebTools.i18n"; + +/** The gateway records these headers with the response, including cached requests. */ +export function WebToolSummary({ head }: { head: HeadView | null }) { + const t = useText(webToolsText); + const header = (name: string) => head?.headers.find(([key]) => key.toLowerCase() === name)?.[1]; + const executor = header("x-thinkwatch-web-tools"); + if (!executor) return null; + let trace: unknown; + try { trace = JSON.parse(header("x-thinkwatch-web-trace") ?? "[]"); } catch { trace = []; } + return
+ {t.title} · {executor === "core" ? t.core : t.upstream} + {header("x-thinkwatch-web-fallback") === "1" &&

{t.fallbackHelp}

} + {Array.isArray(trace) && trace.map((step: unknown, index) => { + if (!step || typeof step !== "object") return null; + const v = step as Record; + const action = v.action === "search" ? t.search : v.action === "open_page" ? t.open : v.action === "find_in_page" ? t.find : null; + if (!action || typeof v.elapsed_ms !== "number") return null; + const engines = Array.isArray(v.engines) ? v.engines.filter((s) => s === "bing" || s === "duckduckgo").join(", ") : ""; + return

{action} · {v.cached ? t.cached : t.fetched} · {t.elapsed(v.elapsed_ms)}{engines && ` · ${engines}`}{typeof v.warnings === "number" && v.warnings > 0 && ` · ${t.partial}`}

; + })} +
; +} From 845d959b19562508cbe5d849b3b33125566291c2 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:48:48 +0800 Subject: [PATCH 2/4] fix(menubar): use a dedicated macOS accessory process for fullscreen menus --- ...macos-fullscreen-status-menu-2026-11-14.md | 58 ++++ src-tauri/examples/menubar_helper_smoke.rs | 99 ++++++ src-tauri/src/main.rs | 5 + src-tauri/src/menubar/helper.rs | 294 ++++++++++++++++++ src-tauri/src/menubar/helper/tests.rs | 163 ++++++++++ src-tauri/src/menubar/linux/tests.rs | 2 +- src-tauri/src/menubar/macos/info.rs | 2 +- src-tauri/src/menubar/mod.rs | 44 +-- src-tauri/src/menubar/model.rs | 38 +-- src-tauri/src/menubar/model/tests.rs | 6 +- src-tauri/src/theme.rs | 2 + 11 files changed, 668 insertions(+), 45 deletions(-) create mode 100644 docs/research/macos-fullscreen-status-menu-2026-11-14.md create mode 100644 src-tauri/examples/menubar_helper_smoke.rs create mode 100644 src-tauri/src/menubar/helper.rs create mode 100644 src-tauri/src/menubar/helper/tests.rs diff --git a/docs/research/macos-fullscreen-status-menu-2026-11-14.md b/docs/research/macos-fullscreen-status-menu-2026-11-14.md new file mode 100644 index 00000000..20ef0b41 --- /dev/null +++ b/docs/research/macos-fullscreen-status-menu-2026-11-14.md @@ -0,0 +1,58 @@ +# macOS 全屏应用中菜单栏下拉菜单不可见 + +排查日期:2026-11-14;修复与验收:2026-11-15。 + +## 结论 + +用户确认普通桌面能打开菜单,全屏应用中只能看到菜单栏按钮高亮。2026-11-15 通过 `sw_vers` 核对,本机实际是 **macOS 27.2.1(26B131)**;上一轮将系统行为归因到 macOS 26 不准确。正在运行的安装版为 ThinkWatch Lite 2026.11.10。 + +证据指向 macOS 27 的原生菜单与全屏 Space、应用 activation policy 的兼容问题。Lite 主窗口打开后使用 Regular 模式;菜单可以开始跟踪,但其显示窗口未进入其他应用的全屏空间。主窗口关闭后切回 Accessory,在本机测试中能绕过问题。 + +## 选择与验证 + +| 方案 | 本机结果 | +| --- | --- | +| 修改菜单窗口及显示子窗口的空间属性 | 不稳定,未采用 | +| 在鼠标松开后,按屏幕坐标以 `inView: nil` 弹出菜单 | 用户实际点击确认仍不显示,未采用 | +| 独立 Accessory 进程持有原生菜单 | 用户确认测试探针能显示;随后确认编译后的真实 Rust 辅助进程菜单正常 | + +公开的同类案例:[Codex #59930](https://github.com/openai/codex/issues/59930)、[Crossbow #346](https://github.com/Richard-Zhang1019/Crossbow/pull/346)。[macshot #511](https://github.com/sw33tLie/macshot/pull/511) 的屏幕坐标方案有其报告者的成功验证,但在本机未通过用户验收,因此没有采用。 + +## 已实现的修复 + +- `src-tauri/src/main.rs` 在初始化 Tauri、用户数据和 core 之前分流 `--menubar-helper`。 +- `src-tauri/src/menubar/helper.rs` 在所有受支持的 macOS 上启动同一可执行文件的辅助模式。子进程保持 Accessory,复用现有 `macos.rs` 原生菜单实现,不启动 WebView 或 core。 +- 主程序用匿名 stdin 管道传递状态快照、显示样式、语言和主题;子进程经 stdout 回传菜单开合与类型化动作。动作仍在主程序主线程上执行。 +- 发送端与主队列接收端均只保留最新待处理快照,避免积压过期读数;主题只在变化时重新设置。 +- 父进程退出或崩溃时,输入管道 EOF 立即结束辅助进程,即使菜单正在展开。辅助进程异常退出后,主程序等待 3 秒重新启动并重发最新快照。 +- 按用户于 2026-11-15 的明确要求,移除系统版本判断及主应用中的进程内菜单分支,所有受支持的 macOS 统一走辅助进程。安装、刷新和隐藏使用同一路径。主窗口的 Dock 行为不变,不随菜单开合切换 activation policy。 + +`Action::Open` 的页面名使用 `Cow<'static, str>`:本地构建菜单仍可借用常量,管道解码时持有字符串,不泄漏内存。状态模型添加序列化支持,菜单渲染规则保持原样。 + +## 验收证据 + +- `cargo clippy --locked --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings`:通过。 +- `cargo test --locked --manifest-path src-tauri/Cargo.toml --lib menubar::`:71 项通过,包括新增的快照等价、动作往返、消息边界、异常数据和更新合并检查。 +- `cargo build --locked --manifest-path src-tauri/Cargo.toml --bin thinkwatch-lite`:通过。 +- `cargo fmt --manifest-path src-tauri/Cargo.toml --all --check` 与 `git diff --check`:通过。 +- 真实辅助模式进程检查:启动、EOF 退出、错误输入退出,以及语言、主题、隐藏/显示样式切换通过。 +- 用户在全屏应用中实际点击真实 Rust 辅助进程的“12.3K”测试菜单,确认菜单正常并点击了“打开主界面”。测试不操作正在运行的网关。 +- 保留原生回归检查 `src-tauri/examples/menubar_helper_smoke.rs`。它在真正的辅助模式进程中打开 NSMenu 并触发第一项,收到 `Open(true)`、`Open(false)`、`Action(OpenMain)`,然后验证 EOF 退出;另一个场景验证菜单跟踪期间 EOF 也能退出。两项通过。 + +原生回归命令: + +```sh +CARGO_INCREMENTAL=0 cargo run --locked --manifest-path src-tauri/Cargo.toml --example menubar_helper_smoke +``` + +程序触发的点击不能替代真实全屏鼠标验收,因此两种证据分别保留。按用户要求不安排旧系统测试;外接屏及完整安装包升级尚未验收。Debug 辅助进程在测试数据持续刷新时约 82 MiB RSS,发布构建内存未测量。 + +统一 macOS 路径后,在当前 macOS 27.2.1 上再次通过 `cargo clippy --all-targets -- -D warnings`、格式和差异检查。没有安排旧系统测试;上面的原生交互验收针对同一辅助进程实现。 + +## 交付与清理 + +修复保留在工作区源码,尚未提交或替换 `/Applications` 中的安装版;需重新打包安装后才会影响正在使用的版本。安装版 Lite(PID 2384)和 core(PID 2411)全程保持运行。 + +本轮临时目录为 `/tmp/twlite-fullscreen-fix.KdFsAv`,含探针、构建缓存、二进制、测试驱动和日志,验证完成后已删除。`du` 统计清理约 4.90 GiB 临时产物;清理前后 `df` 可用空间净增约 4.45 GiB(同盘有其他活动)。保留修复源码、回归检查和本文;活动工作区不移除,因此无需制作工作区归档。 + +统一 macOS 路径后的验证目录 `/tmp/twlite-unified-menubar.2PWIAb` 也已清理,包含构建缓存和 Clippy 日志;清理前确认验证已结束且无辅助测试进程占用。`du` 统计删除 1,196,624 KiB(约 1.14 GiB),前后 `df` 可用空间净增 981,976 KiB(约 0.94 GiB)。源码、本文和既有活动工作区依赖继续保留。 diff --git a/src-tauri/examples/menubar_helper_smoke.rs b/src-tauri/examples/menubar_helper_smoke.rs new file mode 100644 index 00000000..bc41277f --- /dev/null +++ b/src-tauri/examples/menubar_helper_smoke.rs @@ -0,0 +1,99 @@ +//! macOS 菜单辅助进程的原生往返检查,不启动 Tauri 或 core。 +//! +//! `cargo run --manifest-path src-tauri/Cargo.toml --example menubar_helper_smoke` +//! 临时打开菜单、触发第一项,断言动作通过管道返回,关闭输入后子进程退出。 +//! 全屏空间仍须实际鼠标点击验收,不能用这条程序触发的点击代替。 + +#[cfg(all(target_os = "macos", debug_assertions))] +fn main() { + use std::io::{BufRead, BufReader, Write}; + use std::process::{Command, Stdio}; + use std::time::Duration; + + use objc2::rc::Retained; + use objc2_app_kit::{NSApplication, NSMenu, NSView}; + use thinkwatch_lite_lib::menubar::{helper, macos, model}; + + fn containing_menu(view: &NSView) -> Option> { + if let Some(item) = view.enclosingMenuItem() { + // 菜单仍由 menubar::macos 持有。 + if let Some(menu) = unsafe { item.menu() } { + return Some(menu); + } + } + view.subviews().iter().find_map(|v| containing_menu(&v)) + } + + if std::env::args().any(|arg| arg == "--menubar-helper") { + std::thread::spawn(|| { + std::thread::sleep(Duration::from_secs(1)); + macos::on_main(|mtm| macos::preview::open_menu_later(mtm, 0.1)); + std::thread::sleep(Duration::from_secs(1)); + macos::on_main(|mtm| { + assert!(macos::preview::is_open(), "原生菜单没有打开"); + let menu = NSApplication::sharedApplication(mtm) + .windows() + .iter() + .filter_map(|window| window.contentView()) + .find_map(|view| containing_menu(&view)) + .expect("菜单没有挂出自定义行"); + menu.cancelTrackingWithoutAnimation(); + menu.performActionForItemAtIndex(0); + }); + // 父端断管道应结束进程;失败时不让测试无限等待。 + std::thread::sleep(Duration::from_secs(15)); + std::process::exit(4); + }); + assert!(helper::run_if_requested()); + return; + } + + for drop_while_open in [false, true] { + let mut child = Command::new(std::env::current_exe().unwrap()) + .arg("--menubar-helper") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + let frame = serde_json::json!({ + "snapshot": model::Snapshot::default(), + "style": "full", "lang": "zh", "theme": null, + }); + writeln!(input, "{frame}").unwrap(); + input.flush().unwrap(); + let mut opened = false; + let mut closed = false; + let mut action = false; + for line in BufReader::new(child.stdout.take().unwrap()).lines() { + let event: serde_json::Value = serde_json::from_str(&line.unwrap()).unwrap(); + println!("{event}"); + opened |= event == serde_json::json!({"Open": true}); + closed |= event == serde_json::json!({"Open": false}); + if drop_while_open && opened { + break; + } + if event == serde_json::json!({"Action": "OpenMain"}) { + action = true; + break; + } + } + drop(input); + assert!( + child.wait().unwrap().success(), + "辅助进程没有随管道关闭退出" + ); + if drop_while_open { + assert!(opened, "菜单没有打开"); + println!("PASS: EOF closes helper while its menu is tracking"); + } else { + assert!(opened && closed && action, "菜单开合或动作没有完整回传"); + println!("PASS: native menu action and helper EOF cleanup"); + } + } +} + +#[cfg(not(all(target_os = "macos", debug_assertions)))] +fn main() { + eprintln!("This check requires a macOS debug build and an active desktop session."); +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index af7ff45d..811c2223 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -2,6 +2,11 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { + // 菜单栏子进程只跑 AppKit,必须在 Tauri、数据目录和 core 初始化之前分流。 + #[cfg(target_os = "macos")] + if thinkwatch_lite_lib::menubar::helper::run_if_requested() { + return; + } tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::try_from_env("TWLITE_LOG") diff --git a/src-tauri/src/menubar/helper.rs b/src-tauri/src/menubar/helper.rs new file mode 100644 index 00000000..72d6d754 --- /dev/null +++ b/src-tauri/src/menubar/helper.rs @@ -0,0 +1,294 @@ +//! macOS 的菜单统一由一个始终保持 Accessory 的进程持有。 +//! +//! 主应用开窗后变成 Regular;27.2 上它的原生菜单能收到点击,却可能不能显示在别的 +//! 应用的全屏 Space 中。子进程复用 `macos` 的画法,只收快照、回传动作,不启动 Tauri、 +//! 不读取用户数据、不连接 core。两根匿名管道随主进程关闭,EOF 直接结束子进程。 + +use std::io::{self, BufRead, Write}; +use std::process::Stdio; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use anyhow::Context; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::sync::watch; + +use super::{macos, model}; +use crate::{i18n, theme}; + +const ARG: &str = "--menubar-helper"; +const MAX_PACKET: usize = 4 * 1024 * 1024; +const RETRY: Duration = Duration::from_secs(3); + +static FRAMES: OnceLock>> = OnceLock::new(); +static THEME: Mutex> = Mutex::new(None); + +/// 只传模型的输入,子进程按同一份代码产生菜单,图标和静态文案不用另造一套协议。 +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Frame { + snapshot: model::Snapshot, + style: model::Style, + lang: i18n::Lang, + theme: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +enum Event { + Open(bool), + Action(model::Action), +} + +pub fn install(app: &tauri::AppHandle) -> anyhow::Result<()> { + let exe = std::env::current_exe().context("找不到菜单栏子进程的程序路径")?; + let (tx, mut rx) = watch::channel(None); + FRAMES + .set(tx) + .map_err(|_| anyhow::anyhow!("菜单栏子进程已经启动"))?; + let app = app.clone(); + tauri::async_runtime::spawn(async move { + loop { + if let Err(error) = session(&exe, &app, &mut rx).await { + tracing::warn!(%error, "菜单栏子进程退出,稍后重建"); + } + super::set_open(&app, false); + // 重建时重发最新快照;菜单没开、没有请求时也能恢复,不依赖下一个业务事件。 + tokio::time::sleep(RETRY).await; + } + }); + Ok(()) +} + +pub fn present(snapshot: &model::Snapshot, style: model::Style) { + if let Some(tx) = FRAMES.get() { + tx.send_replace(Some(Frame { + snapshot: snapshot.clone(), + style, + lang: i18n::current(), + theme: *THEME.lock().expect("锁未中毒"), + })); + } +} + +pub fn hide() { + if let Some(tx) = FRAMES.get() { + tx.send_modify(|frame| { + if let Some(frame) = frame { + frame.style = model::Style::Hidden; + } + }); + } +} + +/// 初始化外观发生在 install 之前;先记住,以后的修改也立即推送,空闲时同样生效。 +pub fn set_theme(theme: Option) { + *THEME.lock().expect("锁未中毒") = theme; + if let Some(tx) = FRAMES.get() { + tx.send_modify(|frame| { + if let Some(frame) = frame { + frame.theme = theme; + } + }); + } +} + +async fn session( + exe: &std::path::Path, + app: &tauri::AppHandle, + frames: &mut watch::Receiver>, +) -> anyhow::Result<()> { + let mut child = tokio::process::Command::new(exe) + .arg(ARG) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn()?; + let mut input = child.stdin.take().expect("已请求 stdin 管道"); + let mut output = BufReader::new(child.stdout.take().expect("已请求 stdout 管道")); + let write = async { + loop { + // 只保留最新一帧。管道暂时堵塞时不堆积过期的速度、额度和请求列表。 + let frame = frames.borrow_and_update().clone(); + if let Some(frame) = frame { + input.write_all(&packet(&frame)?).await?; + input.flush().await?; + } + if frames.changed().await.is_err() { + return Ok::<(), anyhow::Error>(()); + } + } + }; + let read = async { + while let Some(event) = read_async::(&mut output).await? { + match event { + Event::Open(open) => super::set_open(app, open), + Event::Action(action) => { + let app = app.clone(); + macos::on_main(move |_| super::handle(&app, action)); + } + } + } + anyhow::bail!("菜单栏输出管道已关闭") + }; + let result = tokio::select! { + result = write => result, + result = read => result, + status = child.wait() => Err(anyhow::anyhow!("菜单栏进程结束:{:?}", status?)), + }; + // 先回收这一份,才能起下一份,避免重复图标;取消任务时 kill_on_drop 兜底。 + let _ = child.kill().await; + let _ = child.wait().await; + result +} + +fn packet(value: &impl Serialize) -> io::Result> { + let mut bytes = serde_json::to_vec(value)?; + bytes.push(b'\n'); + if bytes.len() > MAX_PACKET { + return Err(io::Error::other("菜单栏消息过大")); + } + Ok(bytes) +} + +fn decode(bytes: &[u8]) -> io::Result> { + if bytes.is_empty() { + return Ok(None); + } + if bytes.len() > MAX_PACKET || bytes.last() != Some(&b'\n') { + return Err(io::Error::other("菜单栏消息过大或不完整")); + } + serde_json::from_slice(bytes) + .map(Some) + .map_err(io::Error::other) +} + +fn read_sync(reader: &mut impl BufRead) -> io::Result> { + let mut bytes = Vec::new(); + std::io::Read::take(reader, (MAX_PACKET + 1) as u64).read_until(b'\n', &mut bytes)?; + decode(&bytes) +} + +async fn read_async( + reader: &mut (impl AsyncBufRead + Unpin), +) -> io::Result> { + let mut bytes = Vec::new(); + reader + .take((MAX_PACKET + 1) as u64) + .read_until(b'\n', &mut bytes) + .await?; + decode(&bytes) +} + +/// 在 main 的最前面调用。只有这个参数进入辅助模式,不初始化主应用的任何服务。 +pub fn run_if_requested() -> bool { + if std::env::args_os().nth(1).as_deref() != Some(std::ffi::OsStr::new(ARG)) { + return false; + } + run_child(); + true +} + +fn send(event: &Event) { + let result = packet(event).and_then(|bytes| { + let mut out = io::stdout().lock(); + out.write_all(&bytes)?; + out.flush() + }); + if result.is_err() { + std::process::exit(0); + } +} + +/// AppKit 暂时忙时,只留最新一帧,最多往主队列投递一个任务。 +#[derive(Default)] +struct Inbox { + latest: Option, + queued: bool, +} + +impl Inbox { + fn replace(&mut self, frame: Frame) -> bool { + self.latest = Some(frame); + !std::mem::replace(&mut self.queued, true) + } + + fn take(&mut self) -> Option { + self.queued = false; + self.latest.take() + } +} + +fn run_child() { + use objc2::MainThreadMarker; + use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy}; + + let mtm = MainThreadMarker::new().expect("菜单栏子进程在主线程启动"); + let app = NSApplication::sharedApplication(mtm); + app.setActivationPolicy(NSApplicationActivationPolicy::Accessory); + macos::install( + mtm, + |action| send(&Event::Action(action)), + |open| send(&Event::Open(open)), + ); + + static INBOX: Mutex = Mutex::new(Inbox { + latest: None, + queued: false, + }); + std::thread::spawn(|| { + let mut input = io::stdin().lock(); + loop { + match read_sync::(&mut input) { + Ok(Some(frame)) => { + let schedule = INBOX.lock().expect("锁未中毒").replace(frame); + if schedule { + macos::on_main(|mtm| { + let frame = INBOX.lock().expect("锁未中毒").take(); + if let Some(frame) = frame { + apply_frame(mtm, frame); + } + }); + } + } + // 父进程正常退出、崩溃或被杀都会关闭管道;即使菜单正在跟踪也立即退出。 + Ok(None) => std::process::exit(0), + Err(error) => { + eprintln!("菜单栏输入失败:{error}"); + std::process::exit(1); + } + } + } + }); + app.run(); +} + +fn apply_frame(mtm: objc2::MainThreadMarker, frame: Frame) { + use objc2_app_kit::{ + NSAppearance, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSApplication, + }; + i18n::set(frame.lang); + thread_local! { + // 第一帧也要设;之后只在设置变动时改外观,不随速度每秒重复设置。 + static APPLIED: std::cell::Cell>> = const { std::cell::Cell::new(None) }; + } + let changed = APPLIED.with(|applied| applied.replace(Some(frame.theme)) != Some(frame.theme)); + if changed { + let appearance = frame.theme.and_then(|theme| { + // AppKit 导出的只读名称;None 继续跟随系统外观。 + let name = unsafe { + match theme { + theme::Theme::Light => NSAppearanceNameAqua, + theme::Theme::Dark => NSAppearanceNameDarkAqua, + } + }; + NSAppearance::appearanceNamed(name) + }); + NSApplication::sharedApplication(mtm).setAppearance(appearance.as_deref()); + } + let (bar, rows) = model::build(&frame.snapshot, frame.style); + macos::apply(mtm, &bar, &rows); +} + +#[cfg(test)] +mod tests; diff --git a/src-tauri/src/menubar/helper/tests.rs b/src-tauri/src/menubar/helper/tests.rs new file mode 100644 index 00000000..109e6d7f --- /dev/null +++ b/src-tauri/src/menubar/helper/tests.rs @@ -0,0 +1,163 @@ +use super::*; +use model::*; + +fn frame() -> Frame { + Frame { + snapshot: Snapshot { + gateway: Gateway::Running, + addr: Some("127.0.0.1:18790".into()), + today: Some(Today { + tokens: 31_900_000, + requests: 42, + ..Default::default() + }), + hourly: Some(Hourly { + from_ms: 0, + tokens: vec![100; 24], + }), + quotas: vec![Quota { + provider: "chatgpt".into(), + windows: vec![Window { + window: "5h".into(), + used_percent: 87.5, + ..Default::default() + }], + ..Default::default() + }], + live: vec![Live { + id: 123, + model: "test-model".into(), + rate: Some(53), + ..Default::default() + }], + notices: vec![NoticeLine { + key: "test".into(), + level: Level::Warning, + title: "注意\n第二行".into(), + body: "detail".into(), + }], + groups: vec![Group { + name: "primary".into(), + members: vec!["one".into()], + selected: Some("one".into()), + }], + connections: vec![Connection { + id: "local".into(), + name: "本机".into(), + current: true, + }], + hotkey: Some(crate::hotkey::default_combo()), + rate: Some(53), + now_ms: 3_600_000, + ..Default::default() + }, + style: Style::Numbers, + lang: i18n::Lang::Zh, + theme: Some(theme::Theme::Dark), + } +} + +#[test] +fn helper_renders_the_same_menu_after_a_snapshot_crosses_the_pipe() { + for lang in [i18n::Lang::Zh, i18n::Lang::En] { + let mut original = frame(); + original.lang = lang; + let copy: Frame = decode(&packet(&original).unwrap()).unwrap().unwrap(); + assert_eq!(copy.lang, lang); + assert_eq!(copy.theme, original.theme); + i18n::with_lang(lang, || { + assert_eq!( + build(©.snapshot, copy.style), + build(&original.snapshot, original.style) + ); + }); + } +} + +#[test] +fn every_menu_action_round_trips_without_losing_its_target() { + let actions = [ + Action::OpenMain, + Action::Open("dashboard".into()), + Action::Open("upstreams".into()), + Action::Open("requests".into()), + Action::OpenRequest(123), + Action::OpenNotice("notice\nkey".into()), + Action::AllNotices, + Action::Settings, + Action::CopyAddress, + Action::CopyKey, + Action::SelectGroup { + group: "primary".into(), + provider: "one".into(), + }, + Action::RestartGateway, + Action::RetryConnection, + Action::SwitchConnection("remote".into()), + Action::CheckUpdates, + Action::InstallUpdate, + Action::Quit, + ]; + for action in actions { + let original = Event::Action(action); + assert_eq!( + decode::(&packet(&original).unwrap()).unwrap(), + Some(original) + ); + } +} + +#[tokio::test] +async fn both_readers_preserve_message_boundaries_and_report_eof() { + let events = [ + Event::Open(true), + Event::Action(Action::OpenMain), + Event::Open(false), + ]; + let bytes: Vec = events + .iter() + .flat_map(|event| packet(event).unwrap()) + .collect(); + let (mut sync, mut asynchronous) = (bytes.as_slice(), bytes.as_slice()); + for expected in events { + assert_eq!( + read_sync::(&mut sync).unwrap(), + Some(expected.clone()) + ); + assert_eq!( + read_async::(&mut asynchronous).await.unwrap(), + Some(expected) + ); + } + assert_eq!(read_sync::(&mut sync).unwrap(), None); + assert_eq!(read_async::(&mut asynchronous).await.unwrap(), None); +} + +#[tokio::test] +async fn oversized_malformed_and_partial_packets_are_rejected() { + for bytes in [ + vec![b' '; MAX_PACKET + 1], + b"not json\n".to_vec(), + b"{\"Open\":true}".to_vec(), + ] { + assert!(read_sync::(&mut bytes.as_slice()).is_err()); + assert!(read_async::(&mut bytes.as_slice()).await.is_err()); + } +} + +#[test] +fn a_busy_ui_keeps_only_the_latest_frame_and_can_schedule_again() { + let mut inbox = Inbox::default(); + assert!(inbox.replace(frame())); + let mut newer = frame(); + newer.style = Style::Hidden; + newer.theme = None; + newer.snapshot.rate = Some(100); + assert!(!inbox.replace(newer)); + let latest = inbox.take().unwrap(); + assert_eq!(latest.style, Style::Hidden); + assert_eq!(latest.theme, None); + assert_eq!(latest.snapshot.rate, Some(100)); + assert!(inbox.take().is_none()); + assert!(inbox.replace(frame())); +} diff --git a/src-tauri/src/menubar/linux/tests.rs b/src-tauri/src/menubar/linux/tests.rs index 83409c73..eb456b27 100644 --- a/src-tauri/src/menubar/linux/tests.rs +++ b/src-tauri/src/menubar/linux/tests.rs @@ -43,7 +43,7 @@ fn tray(rows: Vec) -> (LinuxTray, Clicks) { fn activation_follows_the_window_opened_by_the_action() { for action in [ Action::OpenMain, - Action::Open("overview"), + Action::Open("overview".into()), Action::OpenRequest(42), Action::OpenNotice("gateway:failed".into()), Action::AllNotices, diff --git a/src-tauri/src/menubar/macos/info.rs b/src-tauri/src/menubar/macos/info.rs index a7b8fb1c..bd01b3fc 100644 --- a/src-tauri/src/menubar/macos/info.rs +++ b/src-tauri/src/menubar/macos/info.rs @@ -1029,7 +1029,7 @@ mod tests { tone: Tone::Normal, detail: detail.map(str::to_string), }, - action: model::Action::Open("upstreams"), + action: model::Action::Open("upstreams".into()), }; let plain = row_height(&row(None)); assert_eq!(plain, QUOTA_BAR_Y + QUOTA_BAR_H + QUOTA_BOTTOM); diff --git a/src-tauri/src/menubar/mod.rs b/src-tauri/src/menubar/mod.rs index 25500025..04704f8a 100644 --- a/src-tauri/src/menubar/mod.rs +++ b/src-tauri/src/menubar/mod.rs @@ -9,6 +9,8 @@ pub mod model; +#[cfg(target_os = "macos")] +pub mod helper; #[cfg(any(target_os = "linux", test))] mod linux; #[cfg(target_os = "macos")] @@ -111,22 +113,9 @@ pub fn install(app: &tauri::AppHandle) -> anyhow::Result<()> { set_style(crate::prefs::load(&crate::data_dir()).menubar); #[cfg(target_os = "macos")] { - let mtm = objc2::MainThreadMarker::new() - .ok_or_else(|| anyhow::anyhow!("菜单栏要在主线程上建"))?; - let (a, b) = (app.clone(), app.clone()); - macos::install( - mtm, - move |action| handle(&a, action), - move |open| { - OPEN.store(open, Ordering::Relaxed); - if open && let Some(st) = b.try_state::() { - st.menubar_now.notify_one(); - } - }, - ); + helper::install(app)?; // 第一帧:还没收到任何数,但菜单栏上不能是空的 - let (bar, rows) = model::build(&Snapshot::default(), drawn_style()); - macos::apply(mtm, &bar, &rows); + present(&Snapshot::default()); } #[cfg(target_os = "linux")] linux::install(app)?; @@ -138,6 +127,14 @@ pub fn install(app: &tauri::AppHandle) -> anyhow::Result<()> { Ok(()) } +#[cfg(target_os = "macos")] +fn set_open(app: &tauri::AppHandle, open: bool) { + OPEN.store(open, Ordering::Relaxed); + if open && let Some(st) = app.try_state::() { + st.menubar_now.notify_one(); + } +} + /// 收数、画、等下一个理由。**被事件叫醒,不是定时醒**:空闲时一次都不醒 async fn run(app: tauri::AppHandle) { let Some(st) = app.try_state::() else { @@ -161,7 +158,7 @@ async fn run(app: tauri::AppHandle) { // `menubar_now` 叫醒这里,收一次、画出来 if drawn_style() == Style::Hidden { #[cfg(target_os = "macos")] - macos::on_main(macos::hide); + helper::hide(); now.notified().await; continue; } @@ -258,13 +255,16 @@ fn sleep_until(at: Option) -> tokio::time::Sleep { /// 把快照交给画的那一层 fn present(snap: &Snapshot) { - let (bar, rows) = model::build(snap, drawn_style()); #[cfg(target_os = "macos")] - macos::on_main(move |mtm| macos::apply(mtm, &bar, &rows)); - #[cfg(target_os = "linux")] - linux::apply(&bar, &rows); - #[cfg(not(any(target_os = "macos", target_os = "linux")))] - tray::apply(&bar, &rows); + helper::present(snap, drawn_style()); + #[cfg(not(target_os = "macos"))] + { + let (bar, rows) = model::build(snap, drawn_style()); + #[cfg(target_os = "linux")] + linux::apply(&bar, &rows); + #[cfg(not(target_os = "linux"))] + tray::apply(&bar, &rows); + } } /// 只更新随时间走的那几样:现在几点、谁在跑、速率。**问 core 要**(`/live`): diff --git a/src-tauri/src/menubar/model.rs b/src-tauri/src/menubar/model.rs index be288f7d..64fc58be 100644 --- a/src-tauri/src/menubar/model.rs +++ b/src-tauri/src/menubar/model.rs @@ -18,7 +18,7 @@ pub enum Style { } /// 网关此刻的状态。守护进程的几种状态按「用户该知道什么」归成这几类 -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Gateway { /// 正在起来,或者崩了之后正在重启 #[default] @@ -41,7 +41,7 @@ impl Gateway { } /// 收一次数得到的全部事实。**都是已经发生的事**,怎么说由 [`build`] 决定 -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct Snapshot { pub gateway: Gateway, /// 客户端该连的网关地址(主机:端口,`127.0.0.1:18790`),和「复制网关地址」复制的是同一个。 @@ -88,14 +88,14 @@ impl Snapshot { } } -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Connection { pub id: String, pub name: String, pub current: bool, } -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Today { pub requests: i64, pub failed: i64, @@ -148,7 +148,7 @@ pub const HOUR_MS: i64 = 3_600_000; /// 今天按本地小时分的 token:第 k 格是 `[零点 + k 小时, 零点 + k + 1 小时)`,和 core 分格的 /// 算法一样(从起点数,一格一个桶宽) -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Hourly { /// 今天的本地零点,Unix 毫秒 pub from_ms: i64, @@ -202,7 +202,7 @@ fn spark(h: &Hourly, now_ms: u64) -> Vec { .collect() } -#[derive(Debug, Clone, Default, PartialEq)] +#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Quota { pub provider: String, pub windows: Vec, @@ -210,7 +210,7 @@ pub struct Quota { pub reset_credits: Option, } -#[derive(Debug, Clone, Default, PartialEq)] +#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Window { /// 上游给的窗口名:`5h` / `weekly` / `30d`…,写法见 [`window_label`] pub window: String, @@ -224,14 +224,14 @@ pub struct Window { /// 积分制套餐一个额度窗口的总额、已用、剩余,**都是上游给的原数**:剩余不是总额减已用 /// 算出来的,三个数不一定对得上,显示剩余就显示它说的剩余 -#[derive(Debug, Clone, Copy, Default, PartialEq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)] pub struct QuotaCredits { pub total: f64, pub used: f64, pub remaining: f64, } -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Live { pub id: u64, /// 请求头认出来的应用(`claude-code`)。认不出来是 None @@ -247,14 +247,16 @@ pub struct Live { pub rate: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, +)] pub enum Level { Info, Warning, Critical, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NoticeLine { pub key: String, pub level: Level, @@ -262,7 +264,7 @@ pub struct NoticeLine { pub body: String, } -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Group { pub name: String, pub members: Vec, @@ -270,11 +272,11 @@ pub struct Group { } /// 点了之后做什么 -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Action { OpenMain, /// 打开主界面并落到这一页(`upstreams`、`dashboard`…) - Open(&'static str), + Open(std::borrow::Cow<'static, str>), /// 打开流量页并展开这一条 OpenRequest(u64), /// 落到能处理这条提醒的那一页,并标为已读 @@ -880,7 +882,7 @@ fn rows(s: &Snapshot) -> Vec { out.push(Row::Quota { provider: q.provider.clone(), window: window_row(w, s.now_ms), - action: Action::Open("upstreams"), + action: Action::Open("upstreams".into()), }); } let used_up = q @@ -893,7 +895,7 @@ fn rows(s: &Snapshot) -> Vec { &format!("resets:{}", q.provider), "arrow.counterclockwise.circle", tr!("额度重置卡…", "Quota Reset Credits…"), - Action::Open("upstreams"), + Action::Open("upstreams".into()), ) .right(tr!(format!("可用 {n} 张"), format!("{n} available"))), )); @@ -930,7 +932,7 @@ fn rows(s: &Snapshot) -> Vec { "live-more", "", tr!(format!("另有 {more} 个"), format!("{more} more")), - Action::Open("requests"), + Action::Open("requests".into()), ) })); } @@ -1091,7 +1093,7 @@ fn dash(s: &Snapshot) -> Dash { } tip }), - action: Action::Open("dashboard"), + action: Action::Open("dashboard".into()), } } diff --git a/src-tauri/src/menubar/model/tests.rs b/src-tauri/src/menubar/model/tests.rs index cd217406..d6e85157 100644 --- a/src-tauri/src/menubar/model/tests.rs +++ b/src-tauri/src/menubar/model/tests.rs @@ -244,7 +244,7 @@ fn today_leads_with_tokens_and_puts_the_cost_last_in_the_small_line() { d.meta.iter().map(|m| m.failed).collect::>(), [false, true, false] ); - assert_eq!(d.action, Action::Open("dashboard")); + assert_eq!(d.action, Action::Open("dashboard".into())); assert_eq!(d.line(), "今日 1.2M token · 128 次 · 失败 2 · $3.47"); // 大字是取整过的:悬停提示里写准数 assert_eq!( @@ -632,7 +632,7 @@ fn a_used_up_quota_offers_the_reset_credits_only_when_there_are_some() { assert_eq!(credits.right.as_deref(), Some("可用 2 张")); assert_eq!( credits.action, - Some(Action::Open("upstreams")), + Some(Action::Open("upstreams".into())), "菜单里不直接用卡" ); s.quotas[0].reset_credits = Some(0); @@ -677,7 +677,7 @@ fn each_quota_window_reported_gets_its_own_row() { assert_eq!(w[0].1.line("ChatGPT"), "ChatGPT 每周 31% · 4 天后重置"); assert!(rows.iter().any(|r| matches!( r, - Row::Quota { action, .. } if *action == Action::Open("upstreams") + Row::Quota { action, .. } if *action == Action::Open("upstreams".into()) ))); // 紧跟在「今日」后面,之后一条分隔线 let at = rows diff --git a/src-tauri/src/theme.rs b/src-tauri/src/theme.rs index 092778c5..d6ec3de6 100644 --- a/src-tauri/src/theme.rs +++ b/src-tauri/src/theme.rs @@ -123,6 +123,8 @@ pub fn effective(setting: Option) -> Theme { /// Linux 例外:那里 `None` 的意思是「不偏好深色」,也就是浅色。跟随系统得把 /// 系统现在的答案写进去,之后由 [`linux`] 盯着系统再改。 pub fn apply(app: &tauri::AppHandle, setting: Option) { + #[cfg(target_os = "macos")] + crate::menubar::helper::set_theme(setting); #[cfg(target_os = "linux")] { linux::remember(setting); From 9c56ef25dc2173c42762d00a9e9fb9b9c4189f41 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:48:48 +0800 Subject: [PATCH 3/4] chore(release): prepare Lite 2026.11.15 --- package.json | 2 +- release-notes/2026.11.15.md | 5 +++++ src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 5 files changed, 9 insertions(+), 4 deletions(-) create mode 100644 release-notes/2026.11.15.md diff --git a/package.json b/package.json index 29e6a0ee..1310bf21 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.14", + "version": "2026.11.15", "type": "module", "packageManager": "pnpm@11.13.1", "scripts": { diff --git a/release-notes/2026.11.15.md b/release-notes/2026.11.15.md new file mode 100644 index 00000000..e8bc108e --- /dev/null +++ b/release-notes/2026.11.15.md @@ -0,0 +1,5 @@ +Web search and page reading can now run in Core. Configure the execution mode under **Routing → Auxiliary**, choose automatic search engines or set your own preferences, and test search, page reads, and find-in-page directly from the app. Language and country/region follow the connected Core host by default, with searchable choices by name instead of code inputs. + +On macOS, the menu-bar menu now runs in a dedicated accessory process, allowing it to open over other applications’ full-screen spaces while the main app keeps its normal Dock behavior. The same implementation is used on all supported macOS versions. Menu updates, actions, language, and theme stay synchronized, and the helper exits with the main app or restarts after an unexpected exit. + +This release includes ThinkWatch Core 0.97.0. Recognized Claude Code standalone WebSearch requests can avoid an auxiliary model call; web tools in ordinary conversations still return results to the main model, whose normal usage remains billed. Core execution is opt-in and does not require MCP or a search API key. diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 18da2bad..2e511524 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4950,7 +4950,7 @@ dependencies = [ [[package]] name = "thinkwatch-lite" -version = "2026.11.14" +version = "2026.11.15" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6caea1db..57868e4f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "thinkwatch-lite" -version = "2026.11.14" +version = "2026.11.15" edition = "2024" # **这个数决定依赖能升到哪一版。**edition 2024 的解析器只挑声明的 Rust # 版本编得动的依赖:写 1.85 的时候,`cargo update` 一直停在旧的 time 和 diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index cb3ab4d9..88ce159b 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.14", + "version": "2026.11.15", "identifier": "app.thinkwatch.lite", "build": { "beforeDevCommand": "pnpm dev", From 6a125a3ef5182283b085b2673696ec1465f7a0ce Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:17:57 +0800 Subject: [PATCH 4/4] chore(core): pin release v0.97.0 --- src-tauri/Cargo.lock | 28 ++++++++++++++-------------- src-tauri/Cargo.toml | 14 ++++++-------- 2 files changed, 20 insertions(+), 22 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 2e511524..01794080 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5459,8 +5459,8 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "serde", "serde_json", @@ -5471,8 +5471,8 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "memchr", "serde", @@ -5481,8 +5481,8 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -5503,8 +5503,8 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "serde", "serde_json", @@ -5530,8 +5530,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "serde", "ts-rs", @@ -5539,8 +5539,8 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "libc", "notify", @@ -5550,8 +5550,8 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.96.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?rev=54a51512fe51ff855a9ebafd161e9a7520fbafb1#54a51512fe51ff855a9ebafd161e9a7520fbafb1" +version = "0.97.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.97.0#a61afa7053f08438163ca640c1321b3a2c9b0c24" dependencies = [ "saphyr-parser", "thiserror 2.0.21", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 57868e4f..555bb09d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -25,15 +25,13 @@ license = "MIT" # 走意味着同一份源码今天和明天编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 # twcore 二进制必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是 # 从 tw-api 锁到的 tag 去取二进制的(见 scripts/fetch-core.sh)。 -# Pending the hosted-web-tools Core release; switch this immutable development -# revision to its release tag before bundling. See the linked Core pull request. [workspace.dependencies] -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } -tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } -tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } -tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", rev = "54a51512fe51ff855a9ebafd161e9a7520fbafb1" } +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" } [lib] name = "thinkwatch_lite_lib"