From a5b7a0de4eefeb668854f9388fb0705b19bc6b54 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 19:43:49 +0800 Subject: [PATCH 1/2] feat(api): slugs for every closed set, so the UI owns the words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The desktop app decided behaviour by comparing the Chinese text core sent: `GroupView.kind == "手动选"` and `"轮流"` in four places plus the tray menu, a table mapping 按顺序 back to `fallback`, `StorageStatus.level !== "正常"` and `AttemptView.outcome === "成功"`. Rewording any of those in core broke the app with no compile error, and the wording is exactly what the app is now rewriting into a formal register. A field whose value comes from a fixed set core defines now carries an identifier, as `trust` and `billing` already did, and the app maps it to its own label: - `GroupView.kind`, `DryRunResult.strategy`: the config word (`fallback` / `select` / `load-balance` / `url-test` / `cheapest`) - `StorageStatus.level`: `ok` / `metadata_only` / `stopped` / `unavailable` - `ConfigReloaded.origin`, `ConfigVersion.origin`: `ui` / `cli` / `external` / `rollback` / `rotation` - `ConfigRejected.stage`: `syntax` / `schema` / `semantics` - `LocallyAnswered.probe`: the probe id - `QuotaWindow.label` becomes `window`: `5h` / `7d` / `weekly` - `AttemptView.outcome`: `served` / `status` / `error`, with `status` and `error` beside it - `LeakSeen.secret`, `LeakGroup.secret` (was `kind`) and `RedactedItem.secret` (was `what`): the secret type, such as `anthropic-api-key` - `L1Segment` carries a `stage` (`step` + `peer`); `L1Result.notes` becomes `skipped` with a reason, and `failed` names the stage an error happened at - `AdoptResponse.takes_effect_note` becomes `takes_effect` Labels that only restated a slug next to them are gone: `ProbeView.label` / `what`, `DriftView.label`, `ScanFinding.kind_label`, `DetectedClient.takes_effect_note` / `verified_note`, `SpeedEstimate.note`, `ReplayQuote.note`. The scan rule summary (`rules_origin`) becomes `rules_active` / `rules_custom` / `rules_disabled`. Lists that mixed fixed labels into data are structured: `RuleView.to` is optional with a `deny` flag instead of 拒绝 or (只改参数), and `RuleView.conditions`, `DryRunResult.set`, `RuleTrace.mismatch` and `PlanView.fields` carry keys and values instead of sentences such as 带缓存 or 删掉 env.X. `Translated.dropped` lists the dropped fields by position. `SecretView.display` no longer prefixes 环境变量. `ManualClient.how` now contains the gateway address. The app replaced a 网关地址 placeholder that core never sent, so the steps said 填我们的地址. Sentences that carry runtime detail (errors, hints, diagnosis findings) stay in core; the CLI and the diagnostics bundle keep their own labels. The workspace goes to 0.4.0 for the app to pin. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 40 +-- Cargo.toml | 2 +- bin/twcore/src/main.rs | 21 +- crates/tw-adopt/src/clients.rs | 66 +++- crates/tw-adopt/src/mcp.rs | 12 +- crates/tw-api/src/lib.rs | 209 +++++++++--- crates/tw-config/src/credential.rs | 12 +- crates/tw-config/src/history.rs | 16 +- crates/tw-config/src/probes.rs | 42 +-- crates/tw-config/src/reload.rs | 9 + crates/tw-control/src/clients.rs | 55 ++-- crates/tw-control/src/config.rs | 6 +- crates/tw-control/src/dryrun.rs | 100 +++--- crates/tw-control/src/lib.rs | 134 ++++---- crates/tw-control/src/replay.rs | 1 - crates/tw-control/src/scan.rs | 9 +- crates/tw-control/tests/adopt.rs | 18 +- crates/tw-control/tests/dryrun.rs | 28 +- crates/tw-control/tests/models.rs | 6 +- crates/tw-control/tests/sync.rs | 8 +- crates/tw-dialect/src/req.rs | 31 +- crates/tw-engine/src/engine.rs | 30 +- crates/tw-gateway/src/clientprobe.rs | 13 +- crates/tw-gateway/src/l1.rs | 429 +++++++++++++++++-------- crates/tw-gateway/src/l3.rs | 4 +- crates/tw-gateway/src/leak.rs | 10 +- crates/tw-gateway/src/lib.rs | 5 +- crates/tw-gateway/src/quota.rs | 18 +- crates/tw-gateway/src/quote.rs | 49 +-- crates/tw-gateway/src/server.rs | 55 +++- crates/tw-gateway/src/ws.rs | 4 +- crates/tw-gateway/tests/l1_real.rs | 15 +- crates/tw-gateway/tests/passthrough.rs | 17 +- crates/tw-gateway/tests/replay.rs | 2 +- crates/tw-redact/src/redact.rs | 12 +- crates/tw-redact/src/rules.rs | 74 +++-- crates/tw-scan/src/rules.rs | 26 +- crates/tw-store/src/db.rs | 1 + crates/tw-store/src/disk.rs | 15 +- crates/tw-store/src/drift.rs | 7 +- crates/tw-store/src/recorder.rs | 35 +- 41 files changed, 1024 insertions(+), 622 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ce240f5b..05566b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2775,7 +2775,7 @@ dependencies = [ [[package]] name = "tw-adopt" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde", "serde_json", @@ -2789,7 +2789,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde", "serde_json", @@ -2797,7 +2797,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.3.0" +version = "0.4.0" dependencies = [ "blake3", "notify", @@ -2817,7 +2817,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.3.0" +version = "0.4.0" dependencies = [ "axum", "bytes", @@ -2852,7 +2852,7 @@ dependencies = [ [[package]] name = "tw-crypto" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aes-gcm", "anyhow", @@ -2864,7 +2864,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde", "serde_json", @@ -2872,7 +2872,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde", "serde_json", @@ -2884,7 +2884,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.3.0" +version = "0.4.0" dependencies = [ "arc-swap", "async-stream", @@ -2924,7 +2924,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.3.0" +version = "0.4.0" dependencies = [ "tokio", "tracing", @@ -2933,7 +2933,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.3.0" +version = "0.4.0" dependencies = [ "arc-swap", "flate2", @@ -2945,7 +2945,7 @@ dependencies = [ [[package]] name = "tw-protocol" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bytes", "futures", @@ -2957,7 +2957,7 @@ dependencies = [ [[package]] name = "tw-provider" -version = "0.3.0" +version = "0.4.0" dependencies = [ "async-stream", "aws-credential-types", @@ -2982,7 +2982,7 @@ dependencies = [ [[package]] name = "tw-redact" -version = "0.3.0" +version = "0.4.0" dependencies = [ "base64", "serde", @@ -2992,7 +2992,7 @@ dependencies = [ [[package]] name = "tw-resil" -version = "0.3.0" +version = "0.4.0" dependencies = [ "futures", "metrics", @@ -3005,7 +3005,7 @@ dependencies = [ [[package]] name = "tw-scan" -version = "0.3.0" +version = "0.4.0" dependencies = [ "notify", "regex", @@ -3022,14 +3022,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.3.0" +version = "0.4.0" dependencies = [ "thiserror", ] [[package]] name = "tw-store" -version = "0.3.0" +version = "0.4.0" dependencies = [ "bytes", "libc", @@ -3047,7 +3047,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde", "serde_json", @@ -3056,7 +3056,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.3.0" +version = "0.4.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -3065,7 +3065,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.3.0" +version = "0.4.0" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index d706e808..d0038dbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ repository = "https://github.com/ThinkWatchProject/ThinkWatch-Core" # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.3.0" +version = "0.4.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 43c943a8..5babb09a 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -252,10 +252,18 @@ fn cmd_clients(path: &Path, what: ClientsCmd) -> Result<()> { println!(" ⓘ {}", d.verified.note()); } } + // 配置读不了时照样列出步骤,地址按默认端口给 + let port = tw_config::load(path) + .map(|c| c.listen.gateway.port) + .unwrap_or(tw_config::DEFAULT_GATEWAY_PORT); + let gw = Gateway { + base: format!("http://127.0.0.1:{port}"), + key: None, + }; println!(); println!("接管不了、只能给指引的:"); for m in manual_only() { - println!(" {:<12} {}", m.name, m.how); + println!(" {:<12} {}", m.name, m.how(&gw)); println!(" {}", m.caveat); } Ok(()) @@ -496,16 +504,19 @@ fn print_l1(target: &str, via: Option<&str>, r: &tw_gateway::L1Result) { }; println!("{} {}", if r.ok { "✅" } else { "❌" }, head); for seg in &r.segments { - println!(" {:<18} {:>6} ms", seg.name, seg.ms); + println!(" {:<18} {:>6} ms", seg.stage.label(), seg.ms); } if r.ok { println!(" {:<18} {:>6} ms", "建连总计", r.total_ms); } if let Some(e) = &r.error { - println!(" {e}"); + match r.failed { + Some(stage) => println!(" {}:{e}", stage.label()), + None => println!(" {e}"), + } } - for n in &r.notes { - println!(" · {n}"); + for s in &r.skipped { + println!(" · {}", s.reason.label()); } println!(); } diff --git a/crates/tw-adopt/src/clients.rs b/crates/tw-adopt/src/clients.rs index 531ee6b9..e645b775 100644 --- a/crates/tw-adopt/src/clients.rs +++ b/crates/tw-adopt/src/clients.rs @@ -36,11 +36,19 @@ pub enum TakesEffect { } impl TakesEffect { - /// 接管完成那一屏要说的话。**在那一刻说,不是等五分钟后再说。** + /// 控制面发给界面的值。接管完成那一屏由界面按它说明什么时候生效 —— + /// **在那一刻说,不是等五分钟后再说。** + pub fn slug(&self) -> &'static str { + match self { + TakesEffect::Immediately => "immediately", + TakesEffect::OnRestart => "on_restart", + } + } + /// 接管提示和诊断结论里的那一句。 pub fn note(&self) -> &'static str { match self { - TakesEffect::Immediately => "下一个请求就会走新配置。", - TakesEffect::OnRestart => "需要关掉终端重开才生效 —— 在那之前收不到请求是正常的。", + TakesEffect::Immediately => "下一个请求即使用新配置。", + TakesEffect::OnRestart => "重新打开终端后生效,在此之前网关收不到该客户端的请求。", } } /// 该不该设「还没收到请求」的超时提示。 @@ -63,10 +71,18 @@ pub enum Verified { } impl Verified { + /// 控制面发给界面的值。 + pub fn slug(&self) -> &'static str { + match self { + Verified::Measured => "measured", + Verified::FieldsOnly => "fields_only", + } + } + /// 命令行里的说法。 pub fn note(&self) -> &'static str { match self { - Verified::Measured => "本机实测过", - Verified::FieldsOnly => "字段查证过,但没有在本机实跑验证", + Verified::Measured => "已在本机实际运行验证", + Verified::FieldsOnly => "字段名已查证,尚未在本机实际运行验证", } } } @@ -269,33 +285,44 @@ pub fn adoptable() -> Vec { /// 用户以为所有流量都在我们这儿。 pub struct ManualOnly { pub name: &'static str, - pub how: &'static str, + /// 手动配置的步骤。`{v1}` 是带 `/v1` 的网关地址,`{base}` 是不带的 + steps: &'static str, pub caveat: &'static str, } +impl ManualOnly { + /// 手动配置的步骤,**网关地址已经填好**。以前这里写的是「填我们的 + /// 地址」,用户还得自己去找那个地址是什么。 + pub fn how(&self, gw: &Gateway) -> String { + self.steps + .replace("{v1}", &gw.v1()) + .replace("{base}", gw.base.trim_end_matches('/')) + } +} + pub fn manual_only() -> Vec { vec![ ManualOnly { name: "Cursor", - how: "设置 → Models → Override OpenAI Base URL,填我们的地址。", - caveat: "即使改了,Tab 补全和 inline edit 仍然走 Cursor 自己的后端,不会经过我们。所以它只能算「部分接管」。", + steps: "在 Cursor 的「Settings → Models」中开启 Override OpenAI Base URL,填写 {v1}。", + caveat: "Tab 补全与 inline edit 仍由 Cursor 自身的服务处理,不经过网关,因此只能部分接管。", }, ManualOnly { name: "Continue", - how: "在 ~/.continue/config.yaml 的 models: 列表里加一条,把 apiBase 指向我们的地址。", + steps: "在 ~/.continue/config.yaml 的 models 列表中添加一项,将 apiBase 设为 {v1}。", // **接管它要往一个 YAML 列表里插一个新条目**,那是结构性 // 改写,不是替换一个标量。我们的 YAML 补丁只做后者 // (见 crate::yaml 开头那段)。宁可少接管一个客户端,也不 // 要写一段我们自己没把握的结构。 - caveat: "它的接管要往一个 YAML 列表里插新条目,属于结构性改写 —— 我们的增量写入只做「替换一个已有的值」,所以这一条给指引不代劳。", + caveat: "接入需要在 models 列表中新增条目,不提供自动接管,请按上述步骤手动配置。", }, ManualOnly { name: "Gemini CLI", - how: "在你的 shell 配置里 export GOOGLE_GEMINI_BASE_URL=<我们的地址>。", + steps: "在 shell 配置文件中添加 export GOOGLE_GEMINI_BASE_URL={base},然后重新打开终端。", // 它只认环境变量,没有可写的配置字段。改 .zshrc 超出了 // 「只改 endpoint 和 key 字段」的边界 —— // **报告是我们的职责,修改是他的权利。** - caveat: "它只读环境变量,没有可写的配置字段。改 shell 配置文件超出了我们该动的范围,所以这一条只给命令,不代劳。", + caveat: "Gemini CLI 只从环境变量读取接口地址。ThinkWatch 不修改 shell 配置文件,请手动添加。", }, ] } @@ -476,7 +503,7 @@ mod tests { c.id ); assert!( - c.takes_effect.note().contains("重开"), + c.takes_effect.note().contains("重新打开终端"), "{} 没在接管那一刻说清要重开", c.id ); @@ -533,6 +560,19 @@ mod tests { let m = manual_only(); let cursor = m.iter().find(|c| c.name == "Cursor").unwrap(); assert!(cursor.caveat.contains("Tab 补全"), "{}", cursor.caveat); + // 步骤里要有真实的地址,而不是一个让用户自己去找的说法 + let gw = Gateway { + base: "http://127.0.0.1:8788".into(), + key: None, + }; + assert!( + cursor.how(&gw).contains("http://127.0.0.1:8788/v1"), + "{}", + cursor.how(&gw) + ); + for c in &m { + assert!(!c.how(&gw).contains('{'), "{}:{}", c.name, c.how(&gw)); + } assert!( !adoptable().iter().any(|c| c.name == "Cursor"), "Cursor 不该在接管表里" diff --git a/crates/tw-adopt/src/mcp.rs b/crates/tw-adopt/src/mcp.rs index 9df8296d..155f8fe3 100644 --- a/crates/tw-adopt/src/mcp.rs +++ b/crates/tw-adopt/src/mcp.rs @@ -181,8 +181,10 @@ pub struct Plan { pub before: Option, pub after: String, pub noop: bool, - /// 人话的一句「这次干了什么」 - pub summary: String, + /// 这次改的是哪个键,按层级(`mcpServers`、server 名) + pub field: Vec, + /// 删掉这个键。否则是写入 + pub remove: bool, } /// 读一个 server 的配置原样。 @@ -226,7 +228,8 @@ pub fn plan_copy(t: &Target, home: &Path, name: &str, value: &Val) -> Result Result, at_ms: u64, }, @@ -313,7 +321,7 @@ pub enum Event { id: u64, /// 内容版本号,和 `PATCH /config` 的 `base_version` 是同一个 version: String, - /// 「界面」「命令行」「外部编辑」「回滚」 + /// `ui` / `cli` / `external` / `rollback` / `rotation` origin: String, at_ms: u64, }, @@ -323,7 +331,8 @@ pub enum Event { /// 人看的信息 —— 托盘变黄、界面标红、定位到那一行。 ConfigRejected { id: u64, - /// 「语法」「字段」「语义」 + /// `syntax`(YAML 写坏了)/ `schema`(字段名或取值不对)/ + /// `semantics`(单看每个字段都对,合起来不成立) stage: String, message: String, /// 1 起。语义错误没有,那时硬指一行只会误导 @@ -340,21 +349,31 @@ pub enum Event { LocallyAnswered { id: u64, client: String, - /// 「连通性检查」这类人话标签。字段叫 `probe` 而不是 `kind` —— - /// 那个名字已经被枚举的 tag 占了 + /// 哪一类辅助请求,和 `ProbeView.id` 同一个词表。字段叫 `probe` 而 + /// 不是 `kind` —— 那个名字已经被枚举的 tag 占了 probe: String, at_ms: u64, }, } /// 尝试链里的一跳。 +/// +/// **失败的原因要留着** —— 一条说「试过 A → B → C」的链,和一条还说清 +/// 每一跳为什么失败的链,排查价值差得远。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AttemptView { pub provider: String, - /// 「成功」「429 限流」「连不上上游」这类人话。**失败的原因要留着** - /// —— 一条说「试过 A → B → C」的链,和一条还说清每一跳为什么失败的 - /// 链,排查价值差得远 + /// - `served`:这一跳接下了请求,尝试链到此为止。上游回的是 4xx 也算 + /// —— 请求本身有问题,换一个上游也一样被拒。 + /// - `status`:上游返回 5xx 或 429,换下一个上游。 + /// - `error`:没有收到响应(超时、无法连接)。 pub outcome: String, + /// 上游返回的状态码。`error` 时没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, + /// `error` 时的说明 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, pub ms: u64, } @@ -373,7 +392,8 @@ pub struct RoutingView { /// 「我们猜的」,而混在一个类型里就区分不了了。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct QuotaWindow { - pub label: String, + /// `5h` / `7d`(Anthropic)/ `weekly`(Codex) + pub window: String, pub used_percent: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub reset_in_secs: Option, @@ -495,10 +515,6 @@ pub struct ProxyView { pub struct ProbeView { /// `health_check` / `warmup` / `titling` / `topic_detect` / `suggestion` pub id: String, - /// 中文名 - pub label: String, - /// 这一类是什么请求,一句话 - pub what: String, /// `intercept` / `route` / `passthrough` pub mode: String, } @@ -601,7 +617,7 @@ pub struct ProviderView { /// 一个可能是密钥的值给界面看的样子。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct SecretView { - /// 打过码的值,或者 `环境变量 ${NAME}` + /// 打过码的值。带 `${NAME}` 的值原样给 —— 它写的是从哪个环境变量读 pub display: String, /// 整个值恰好是一个 `${NAME}` 时的变量名。变量名不是秘密,编辑时要回填 #[serde(default, skip_serializing_if = "Option::is_none")] @@ -642,9 +658,26 @@ pub enum ReferenceView { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RuleView { pub name: String, - pub to: String, - /// `when` 的人话摘要。空 = 兜底 - pub conditions: Vec, + /// 去向:上游名或组名。拒绝的规则和只改参数的规则没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to: Option, + /// 命中就拒绝 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub deny: bool, + /// `when` 里写了的条件,按固定顺序。空 = 兜底 + pub conditions: Vec, +} + +/// 规则里的一个条件。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ConditionView { + /// `when` 里的键:`model` / `client` / `dialect` / `input_tokens` / + /// `max_tokens` / `tool_count` / `intent` / `provider_would_be` / + /// `cache` / `tools` / `image` / `thinking` / `stream` + pub field: String, + /// 写的值。`intent` 和 `provider_would_be` 可以写多个,满足其一即可; + /// 布尔条件是 `true` / `false`;数量条件是比较式(`>200k`) + pub values: Vec, } /// 一条路由 —— 一组规则,加上它分给了谁。 @@ -663,6 +696,8 @@ pub struct RouteView { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GroupView { pub name: String, + /// 配置里写的 `type`:`fallback` / `select` / `load-balance` / + /// `url-test` / `cheapest` pub kind: String, /// 同一次会话固定走同一家。**这一项直接决定账单** #[serde(default)] @@ -754,17 +789,36 @@ pub struct L1Request { pub provider: Option, } +/// 建连的哪一步、对着谁。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct L1Stage { + /// `config`(地址或代理配置用不了,没有开始建连)/ `dns` / `tcp` / + /// `tls` / `handshake`(代理协议的握手,含认证) + pub step: String, + /// `upstream` / `proxy` + pub peer: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct L1Segment { - pub name: String, + pub stage: L1Stage, pub ms: u64, } +/// 没有出现在分段里的那一步,和原因。**不说的话,缺一段看起来就像 bug。** +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct L1Skip { + pub stage: L1Stage, + /// `plain_http`(`http://` 地址没有 TLS)/ `ip_address`(地址已经是 IP, + /// 不需要解析)/ `proxy_resolves`(`socks5h` 和 HTTP CONNECT 由代理解析域名) + pub reason: String, +} + /// **分段是个列表而不是固定的 DNS/TCP/TLS 三段**,因为走代理时的形状本来 -/// 就不同:多出「代理握手」,而 `socks5h` 下根本没有本地 DNS 那一段。 +/// 就不同:多出代理握手,而 `socks5h` 下根本没有本地 DNS 那一段。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct L1Result { - /// 实际测的是什么 —— 回显出来,别让用户猜点的那一下测了谁 + /// 测的是哪个上游或代理的名字 —— 回显出来,别让用户猜点的那一下测了谁 pub target: String, /// 经过哪个代理,直连是 None #[serde(default, skip_serializing_if = "Option::is_none")] @@ -772,9 +826,12 @@ pub struct L1Result { pub ok: bool, pub segments: Vec, pub total_ms: u64, - /// 解释为什么某一段不在上面。**没有这句话,缺一段看起来就像 bug。** #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub notes: Vec, + pub skipped: Vec, + /// 失败在哪一步 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failed: Option, + /// 失败的原因 #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, } @@ -1294,7 +1351,7 @@ pub struct BaseVersion { pub struct ConfigVersion { pub version: String, pub at_ms: u64, - /// 「界面」「命令行」「外部编辑」「回滚」 + /// `ui` / `cli` / `external` / `rollback` / `rotation` pub origin: String, pub bytes: u64, /// 这一版是现在跑着的那一版吗。 @@ -1537,8 +1594,6 @@ pub struct SpeedEstimate { /// 这家的计费方式:`per-token` / `subscription` / `free` / `unknown`。 /// **订阅制那几项没有金额,但不让合计变成空** pub billing: String, - /// 给人看的那一句 - pub note: String, /// 这家服务不了这个模型:`out_of_scope`(不在启用范围里)/ /// `not_offered`(模型清单里没有)。有值时不进合计,也不会被测 #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1593,7 +1648,8 @@ pub struct SpeedResult { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LeakGroup { pub provider: String, - pub kind: String, + /// 哪种凭据,和 `Event::LeakSeen.secret` 同一个词表 + pub secret: String, pub requests: i64, pub last_at_ms: i64, /// 涉及哪几把,**都已打码** @@ -1603,7 +1659,10 @@ pub struct LeakGroup { /// 观测这一层现在能不能写。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StorageStatus { - /// 「正常」/「磁盘快满了…」/「磁盘几乎满了…」 + /// - `ok`:正常记录 + /// - `metadata_only`:磁盘空间不足,只记请求摘要,不保存请求体和响应体 + /// - `stopped`:磁盘空间严重不足,停止记录 + /// - `unavailable`:请求记录没有启动(数据库打不开之类) pub level: String, /// 记了多少条 pub rows: i64, @@ -1616,10 +1675,10 @@ pub struct StorageStatus { /// 换掉了哪一类、几处。**只有类别和计数,没有原值。** #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RedactedItem { - /// `api-keys` 这类机器读的标记 + /// 类别:`api-keys` / `private-keys` / `jwt` / `conn-strings` / `internal` pub kind: String, - /// 「Anthropic API key」这类人话 - pub what: String, + /// 具体是哪种,和 `Event::LeakSeen.secret` 同一个词表 + pub secret: String, pub count: u64, } @@ -1711,7 +1770,6 @@ pub struct ReplayQuote { pub cost_micros: Option, /// 要重放到的那家的计费方式:`per-token` / `subscription` / `free` / `unknown` pub billing: String, - pub note: String, /// 发出去之前会不会脱敏。用户有权在按下去之前知道 pub will_redact: bool, pub pricing_date: String, @@ -1744,9 +1802,9 @@ pub struct ReplayResult { /// 一个上游最近是不是变了(防线三)。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DriftView { - /// `tool_calls` / `flagged` / `errors` + /// `flagged`(命中高危规则的响应)/ `tool_calls`(带工具调用的响应)/ + /// `errors`(失败的请求) pub metric: String, - pub label: String, /// 比率,0..1 pub recent: f64, pub baseline: f64, @@ -1793,7 +1851,6 @@ pub struct ScanFinding { pub rule: String, /// `hooks` | `mcp` | `skill` | `command` | `agent` | `instructions` pub kind: String, - pub kind_label: String, pub client: String, pub path: String, /// 第几行,从 1 开始 @@ -1850,9 +1907,13 @@ pub struct ScanResponse { /// 读不动的文件。**要显示** —— 悄悄跳过会给人「查过了」的错觉 pub unreadable: Vec, pub scanned: usize, - /// 规则从哪儿来的 - pub rules_origin: String, - /// 用户的规则文件有问题时的那句话 + /// 这次生效的规则数,内置的加上用户加的 + pub rules_active: usize, + /// 其中用户加的 + pub rules_custom: usize, + /// 停用了几条内置规则 + pub rules_disabled: usize, + /// 有规则没能生效时的说明(正则写错、停用了不存在的 id) pub rules_warning: Option, /// 这次连哪些项目目录一起扫了 pub projects: Vec, @@ -1932,32 +1993,59 @@ fn default_true() -> bool { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RuleTrace { pub name: String, - /// `matched` | `skipped` | `phase_two` + /// `matched` | `skipped` | `phase_two`(条件要等选定上游之后才能求值, + /// 静态试算给不了结论) pub verdict: String, - /// 没命中时,是哪个条件没对上 - pub why: Option, + /// 没命中时,第一个没对上的条件 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mismatch: Option, + /// 条件本身写错了、没法求值时的说明 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// 一个没对上的条件。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MismatchView { + /// 和 `ConditionView.field` 同一个词表 + pub field: String, + /// 规则里写的值。`intent` 写了多个时逐个列出 + pub want: Vec, + /// 这个请求实际的值。`intent` 为空表示真实的用户请求 + pub got: String, +} + +/// 一项参数改写。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SetView { + /// `model`(换模型,整个 prompt cache 作废)/ `max_tokens` / `thinking` / + /// `only_at_session_start`(以上改写只在新会话开始时应用,值是 `true`) + pub field: String, + pub value: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DryRunResult { - /// 这个组按什么挑(`按顺序` / `选最快` / `选最便宜` …)。 + /// 经过的组按什么排候选:`fallback` / `select` / `load-balance` / + /// `url-test` / `cheapest`。 /// /// **不说的话,用户看不懂候选为什么是这个顺序** —— 「我明明把官方 /// 写在第一个」。直指 provider 时是 None。 #[serde(default, skip_serializing_if = "Option::is_none")] pub strategy: Option, - /// `route` | `deny` | `no_match` | `unavailable`(选中的上游都服务不了) + /// `route` | `deny` | `no_match` | `unavailable`(选中的上游都服务不了, + /// 见 `skipped`) pub outcome: String, /// 命中的规则名 pub rule: Option, - /// 拒绝的理由(`deny` 时) + /// `deny` 时规则里写的拒绝理由 pub reason: Option, /// 候选链,第一个是首选,后面是故障转移的备选 pub candidates: Vec, /// 经过了哪个组 pub via_group: Option, - /// 累积起来的参数改写,人话形式 - pub set: Vec, + /// 累积起来的参数改写 + pub set: Vec, pub trace: Vec, /// 这条路会不会伤到 prompt cache。**要直说 —— 它决定账单** pub hurts_cache: bool, @@ -1999,17 +2087,18 @@ pub struct DetectedClient { /// 配置里此刻的端点。**读出来的**,不是拿我们自己的记录充数 pub endpoint: Option, pub shadows: Vec, - /// `immediately` | `on_restart` + /// `immediately`(下一个请求就使用新配置)| `on_restart`(客户端重新 + /// 启动后才生效,读环境变量的要重开终端) pub takes_effect: String, - pub takes_effect_note: String, /// 接管之后要不要在「一直没收到请求」时提示。 /// /// **需要重开终端的客户端不提示** —— 用户可能一整天都没重开过,那时 /// 弹「是不是没生效」是狼来了 pub warns_when_silent: bool, - /// `measured` | `fields_only` + /// `measured`(在本机实际运行验证过)| `fields_only`(字段名查证过, + /// 没有在本机实际运行验证) pub verified: String, - pub verified_note: String, + /// 接管之后会失去或改变的功能 pub costs: Vec, /// 最后一次收到这个客户端的请求。**接管有没有真的生效,只有它能证明** pub last_seen_ms: Option, @@ -2019,6 +2108,7 @@ pub struct DetectedClient { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ManualClient { pub name: String, + /// 手动配置的步骤,网关地址已经填在里面 pub how: String, pub caveat: String, } @@ -2058,8 +2148,20 @@ pub struct PlanView { /// 已经是这样了,什么都不用改 pub noop: bool, pub carries_secret: bool, - /// 这次会把哪些字段改成什么,人话形式。diff 之外再给一份摘要 - pub fields: Vec, + /// 这次会改哪些字段。diff 之外再给一份摘要 + pub fields: Vec, +} + +/// 配置文件里的一处改动。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FieldChange { + /// `set` | `remove` + pub op: String, + /// 字段路径,按层级用 `.` 连起来:`env.ANTHROPIC_BASE_URL` + pub path: String, + /// 要写入的值。写的是网关密钥或者一整段结构时不给 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -2069,7 +2171,8 @@ pub struct AdoptResponse { pub created: bool, /// 不至于失败、但用户该知道的事(符号链接、权限太松……) pub warnings: Vec, - pub takes_effect_note: String, + /// 改动什么时候生效,和 `DetectedClient.takes_effect` 同一个词表 + pub takes_effect: String, } /// 一条诊断发现。 diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index 0a8134b1..c874e3a0 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -70,7 +70,17 @@ impl Secret { Ok(tw_secret::expand_from_env(&self.0)?) } - /// 给人看的形态,**永远不含真实密钥**。 + /// 给界面的形态,**永远不含真实密钥**:带 `${NAME}` 的原样给(写的是 + /// 从哪个环境变量读),其余打码。怎么称呼它由界面决定。 + pub fn shown(&self) -> String { + if self.0.contains("${") { + self.0.clone() + } else { + tw_secret::mask_secret(&self.0) + } + } + + /// 命令行和诊断包里的说法,**永远不含真实密钥**。 pub fn describe(&self) -> String { if self.0.contains("${") { format!("环境变量 {}", self.0) diff --git a/crates/tw-config/src/history.rs b/crates/tw-config/src/history.rs index 72514c86..0909a70b 100644 --- a/crates/tw-config/src/history.rs +++ b/crates/tw-config/src/history.rs @@ -39,7 +39,9 @@ pub enum Origin { } impl Origin { - fn slug(&self) -> &'static str { + /// 历史文件名里的那一段。**文件名是存盘格式**,和控制面发的 `slug()` + /// 分开:外部编辑在文件名里一直叫 `ext`,改掉它就读不懂已有的历史。 + fn file_tag(&self) -> &'static str { match self { Origin::Ui => "ui", Origin::Cli => "cli", @@ -48,6 +50,16 @@ impl Origin { Origin::Rotation => "rotation", } } + /// 控制面发给界面的值。 + pub fn slug(&self) -> &'static str { + match self { + Origin::Ui => "ui", + Origin::Cli => "cli", + Origin::External => "external", + Origin::Rollback => "rollback", + Origin::Rotation => "rotation", + } + } fn parse(s: &str) -> Origin { match s { "ui" => Origin::Ui, @@ -143,7 +155,7 @@ pub fn snapshot( // 名字里带上时间、来源和版本号 —— 光看文件名就能读懂这一版是什么。 let file = dir.join(format!( "{at_ms}-{}-{}.yaml", - origin.slug(), + origin.file_tag(), &version["blake3:".len()..] )); store::write_atomic(&file, text)?; diff --git a/crates/tw-config/src/probes.rs b/crates/tw-config/src/probes.rs index 9ad238e5..a43e2041 100644 --- a/crates/tw-config/src/probes.rs +++ b/crates/tw-config/src/probes.rs @@ -40,42 +40,18 @@ impl ProbeAction { } impl ClientProbes { - /// 五类,按「界面上从上到下」的顺序,每类带一句人话。 + /// 五类,按「界面上从上到下」的顺序。 /// /// **这份清单住在这里而不是界面里**:增删一类是这个结构体的事, - /// 而一个只在前端硬编码的清单会在加了第六类的那天悄悄少一行。 - pub fn all(&self) -> [(&'static str, &'static str, &'static str, ProbeAction); 5] { + /// 而一个只在前端硬编码的清单会在加了第六类的那天悄悄少一行。每一类 + /// 叫什么、是什么请求,由界面按 id 自己写。 + pub fn all(&self) -> [(&'static str, ProbeAction); 5] { [ - ( - "health_check", - "连通性检查", - "客户端启动时打的一发空请求,只为看网关通不通。默认本地应答。", - self.health_check, - ), - ( - "warmup", - "预热", - "正文恰好是 Warmup 的那一发,用来把连接和缓存捂热。默认本地应答。", - self.warmup, - ), - ( - "titling", - "起标题", - "给会话起个名字。**默认放行** —— 拦了的话每个会话都叫同一个名字。", - self.titling, - ), - ( - "topic_detect", - "话题识别", - "客户端判断这轮聊的是什么,用来决定要不要换上下文。默认放行。", - self.topic_detect, - ), - ( - "suggestion", - "补全建议", - "输入框里那些灰色的建议。默认放行。", - self.suggestion, - ), + ("health_check", self.health_check), + ("warmup", self.warmup), + ("titling", self.titling), + ("topic_detect", self.topic_detect), + ("suggestion", self.suggestion), ] } } diff --git a/crates/tw-config/src/reload.rs b/crates/tw-config/src/reload.rs index 645378e3..b781229f 100644 --- a/crates/tw-config/src/reload.rs +++ b/crates/tw-config/src/reload.rs @@ -29,6 +29,15 @@ pub enum Stage { } impl Stage { + /// 控制面发给界面的值。 + pub fn slug(&self) -> &'static str { + match self { + Stage::Syntax => "syntax", + Stage::Schema => "schema", + Stage::Semantics => "semantics", + } + } + /// 命令行和日志里的说法,后面接「错误」。 pub fn label(&self) -> &'static str { match self { Stage::Syntax => "语法", diff --git a/crates/tw-control/src/clients.rs b/crates/tw-control/src/clients.rs index 96cd3c92..c4ec0f6e 100644 --- a/crates/tw-control/src/clients.rs +++ b/crates/tw-control/src/clients.rs @@ -78,17 +78,9 @@ pub async fn list(State(s): State) -> Result "immediately".into(), - tw_adopt::clients::TakesEffect::OnRestart => "on_restart".into(), - }, - takes_effect_note: d.takes_effect.note().to_string(), + takes_effect: d.takes_effect.slug().to_string(), warns_when_silent: d.takes_effect.warns_when_silent(), - verified: match d.verified { - tw_adopt::clients::Verified::Measured => "measured".into(), - tw_adopt::clients::Verified::FieldsOnly => "fields_only".into(), - }, - verified_note: d.verified.note().to_string(), + verified: d.verified.slug().to_string(), costs: d.costs, }) .collect(); @@ -98,7 +90,10 @@ pub async fn list(State(s): State) -> Result) -> String { } } -fn view(p: &plan::Plan, fields: Vec, key: Option<&str>) -> tw_api::PlanView { +fn view(p: &plan::Plan, fields: Vec, key: Option<&str>) -> tw_api::PlanView { tw_api::PlanView { client: p.client.clone(), path: p.path.display().to_string(), @@ -148,19 +143,21 @@ pub async fn plan_adopt( .targets .iter() .map(|t| match t { - plan::Target::Set(path, v) => { + plan::Target::Set(path, v) => tw_api::FieldChange { + op: "set".into(), + path: path.join("."), // **密钥不回显**,哪怕是打码的 - let shown = if path.iter().any(|k| { + value: (!path.iter().any(|k| { let k = k.to_ascii_lowercase(); k.contains("token") || k.contains("key") - }) { - "(那把网关密钥)".to_string() - } else { - v.to_line() - }; - format!("{} = {shown}", path.join(".")) - } - plan::Target::Remove(path) => format!("删掉 {}", path.join(".")), + })) + .then(|| v.to_line()), + }, + plan::Target::Remove(path) => tw_api::FieldChange { + op: "remove".into(), + path: path.join("."), + value: None, + }, }) .collect(); Ok(Json(view(&p, fields, gw.key.as_deref()))) @@ -208,7 +205,7 @@ pub async fn adopt( created: a.created, warnings: a.warnings, // **在接管完成那一屏说,不是等五分钟后再说** - takes_effect_note: c.takes_effect.note().to_string(), + takes_effect: c.takes_effect.slug().to_string(), })) } @@ -229,7 +226,7 @@ pub async fn restore( backup: a.backup.display().to_string(), created: false, warnings: p.notes, - takes_effect_note: c.takes_effect.note().to_string(), + takes_effect: c.takes_effect.slug().to_string(), })) } @@ -296,7 +293,12 @@ pub async fn mcp_plan_op( noop: p.noop, // MCP 的 env 里可能有密钥,而我们正把它抄进另一个文件 carries_secret: true, - fields: vec![p.summary], + fields: vec![tw_api::FieldChange { + op: if p.remove { "remove" } else { "set" }.to_string(), + path: p.field.join("."), + // 值是一整段 server 配置,里面可能有密钥,diff 里已经能看到打过码的样子 + value: None, + }], })) } @@ -312,7 +314,8 @@ pub async fn mcp_apply( backup: a.backup.display().to_string(), created: a.created, warnings: a.warnings, - takes_effect_note: "客户端下次启动时会读到它。".into(), + // 客户端只在启动时读 MCP 配置 + takes_effect: tw_adopt::clients::TakesEffect::OnRestart.slug().to_string(), })) } diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 8ea20696..4c5ed37c 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -97,7 +97,7 @@ impl ConfigManager { // 写错一个字,界面上什么都不会发生。 self.bus.emit(tw_api::Event::ConfigRejected { id: self.bus.next_id(), - stage: r.stage.label().to_string(), + stage: r.stage.slug().to_string(), message: r.message.clone(), line: r.line, excerpt: r.excerpt.clone(), @@ -114,11 +114,11 @@ impl ConfigManager { // 着的 —— 于是「回到上一版」在列表上就是第二条,不用数。 let _ = tw_config::history::snapshot(&self.path, text, origin); let version = store::version_of(text); - tracing::info!(%version, origin = origin.label(), "配置已生效"); + tracing::info!(%version, origin = origin.slug(), "配置已生效"); self.bus.emit(tw_api::Event::ConfigReloaded { id: self.bus.next_id(), version: version.clone(), - origin: origin.label().to_string(), + origin: origin.slug().to_string(), at_ms: now_ms(), }); Ok(version) diff --git a/crates/tw-control/src/dryrun.rs b/crates/tw-control/src/dryrun.rs index 29928212..c2621967 100644 --- a/crates/tw-control/src/dryrun.rs +++ b/crates/tw-control/src/dryrun.rs @@ -93,9 +93,10 @@ pub async fn dry_run( if r.when.is_phase_two() { trace.push(tw_api::RuleTrace { name: r.name.clone(), - verdict: "phase_two".into(), // 阶段二的条件要等路由决定完才知道,静态试算给不了结论 - why: Some("它的条件要等选完上游才知道,这一轮先跳过".into()), + verdict: "phase_two".into(), + mismatch: None, + error: None, }); continue; } @@ -103,17 +104,20 @@ pub async fn dry_run( Ok(true) => trace.push(tw_api::RuleTrace { name: r.name.clone(), verdict: "matched".into(), - why: None, + mismatch: None, + error: None, }), Ok(false) => trace.push(tw_api::RuleTrace { name: r.name.clone(), verdict: "skipped".into(), - why: Some(unmatched(&r.when, &f)), + mismatch: unmatched(&r.when, &f), + error: None, }), Err(e) => trace.push(tw_api::RuleTrace { name: r.name.clone(), verdict: "skipped".into(), - why: Some(e.to_string()), + mismatch: None, + error: Some(e.to_string()), }), } } @@ -148,7 +152,7 @@ pub async fn dry_run( .via_group .as_deref() .and_then(|g| engine.groups().iter().find(|x| x.name == g)) - .map(|g| g.kind.label().to_string()); + .map(|g| g.kind.slug().to_string()); // 和数据面同一步:去掉服务不了这个请求的候选(停用的、范围外的、 // 清单里没有这个模型的)。**被跳过的要列出来** —— 「规则明明写的 // 是 A」正是用户会来试算的原因 @@ -166,9 +170,9 @@ pub async fn dry_run( reason: why.slug().to_string(), }) .collect(); + // 服务不了的原因都在 `skipped` 里,不再另说一遍 if serving.usable.is_empty() { out.outcome = "unavailable".into(); - out.reason = Some(serving.explain(&f.model).message); return Ok(Json(out)); } d.candidates = serving.usable; @@ -198,28 +202,33 @@ pub async fn dry_run( } Err(RouteError::NoMatch) => { out.outcome = "no_match".into(); - out.reason = Some(RouteError::NoMatch.to_string()); } Err(e) => return Err((StatusCode::BAD_REQUEST, e.to_string())), } Ok(Json(out)) } -fn describe(set: &tw_engine::SetAction) -> Vec { +fn describe(set: &tw_engine::SetAction) -> Vec { let mut v = Vec::new(); + let mut push = |field: &str, value: String| { + v.push(tw_api::SetView { + field: field.to_string(), + value, + }) + }; + // 换模型会作废整个 prompt cache,而这件事在长会话里可能比不换还贵 —— + // 界面上要说出来,所以它单独是一项,不和别的参数混在一起 if let Some(m) = &set.model { - // 换模型会作废整个 prompt cache,而这件事在长会话里可能比不换 - // 还贵 —— 试算里就要说出来 - v.push(format!("换模型 → {m}(会作废整个 prompt cache)")); + push("model", m.clone()); } if let Some(t) = set.max_tokens { - v.push(format!("max_tokens → {t}")); + push("max_tokens", t.to_string()); } if let Some(t) = set.thinking { - v.push(format!("thinking → {t}")); + push("thinking", t.to_string()); } if set.only_at_session_start { - v.push("只在新会话开始时应用".into()); + push("only_at_session_start", "true".to_string()); } v } @@ -228,54 +237,49 @@ fn describe(set: &tw_engine::SetAction) -> Vec { /// /// **逐条试,报第一个不满足的。**报「不匹配」等于什么都没说 —— 用户看 /// 试算就是为了知道差在哪儿。 -fn unmatched(when: &tw_engine::rule::When, f: &RequestFacts) -> String { - let eq = |want: &Option, got: &str| -> Option { - match want { - Some(w) if w != got => Some(format!("要求 `{w}`,实际是 `{got}`")), - _ => None, - } - }; - let b = |want: Option, got: bool, name: &str| -> Option { - match want { - Some(w) if w != got => Some(format!("要求 {name}={w},实际是 {got}")), - _ => None, - } +fn unmatched(when: &tw_engine::rule::When, f: &RequestFacts) -> Option { + let miss = |field: &str, want: Vec, got: String| { + Some(tw_api::MismatchView { + field: field.to_string(), + want, + got, + }) }; if let Some(w) = &when.model && !tw_engine::rule::glob_match(w, &f.model) { - return format!("model 要匹配 `{w}`,实际是 `{}`", f.model); - } - if let Some(m) = eq(&when.client, &f.client) { - return format!("client {m}"); + return miss("model", vec![w.clone()], f.model.clone()); } - if let Some(m) = eq(&when.dialect, &f.dialect) { - return format!("dialect {m}"); + for (field, want, got) in [ + ("client", &when.client, &f.client), + ("dialect", &when.dialect, &f.dialect), + ] { + if let Some(w) = want + && w != got + { + return miss(field, vec![w.clone()], got.clone()); + } } if let Some(w) = &when.intent && !w.contains(&f.intent) { - return format!( - "intent 要在 {w:?} 里,实际是 `{}`", - if f.intent.is_empty() { - "(真实用户请求)" - } else { - &f.intent - } - ); + // 实际值为空表示真实的用户请求,由界面说明 + return miss("intent", crate::one_or_many(w), f.intent.clone()); } - for (want, got, name) in [ + for (want, got, field) in [ (when.cache, f.cache, "cache"), (when.tools, f.tools, "tools"), (when.image, f.image, "image"), (when.thinking, f.thinking, "thinking"), (when.stream, f.stream, "stream"), ] { - if let Some(m) = b(want, got, name) { - return m; + if let Some(w) = want + && w != got + { + return miss(field, vec![w.to_string()], got.to_string()); } } - for (want, got, name) in [ + for (want, got, field) in [ (&when.input_tokens, f.input_tokens as f64, "input_tokens"), (&when.tool_count, f.tool_count as f64, "tool_count"), ( @@ -285,10 +289,10 @@ fn unmatched(when: &tw_engine::rule::When, f: &RequestFacts) -> String { ), ] { if let Some(w) = want { - return format!("{name} 要满足 `{w}`,实际是 {got}"); + return miss(field, vec![w.clone()], got.to_string()); } } // **阶段二的条件不在这里**:它们在上面就被单独归类了。走到这儿说明 - // 有个条件我们没覆盖到 —— 与其编一句,不如承认。 - "有条件没对上(这条 ThinkWatch 还没能给出更具体的解释)".to_string() + // 有个条件没覆盖到 —— 与其编一句,不如承认说不出来。 + None } diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index c0b1292c..1901b0d2 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -261,13 +261,8 @@ async fn overview(State(s): State) -> Json { .map(|r| tw_api::RuleView { name: r.name.clone(), // 阶段二的规则没有去向 —— 它们只改参数或拒绝 - to: r.to.clone().unwrap_or_else(|| { - if r.deny.is_some() { - "拒绝".into() - } else { - "(只改参数)".into() - } - }), + to: r.to.clone(), + deny: r.deny.is_some(), conditions: describe_when(&r.when), }) .collect(), @@ -278,7 +273,7 @@ async fn overview(State(s): State) -> Json { .iter() .map(|g| tw_api::GroupView { name: g.name.clone(), - kind: g.kind.label().to_string(), + kind: g.kind.slug().to_string(), session_affinity: g.session_affinity, selected: g.selected.clone(), providers: g.providers.clone(), @@ -308,10 +303,8 @@ async fn overview(State(s): State) -> Json { .client_probes .all() .into_iter() - .map(|(id, label, what, mode)| tw_api::ProbeView { + .map(|(id, mode)| tw_api::ProbeView { id: id.to_string(), - label: label.to_string(), - what: what.to_string(), mode: mode.slug().to_string(), }) .collect(), @@ -366,7 +359,7 @@ fn provider_view( base_url_masked: base_url != p.base_url, base_url, key: p.key.as_ref().map(|k| tw_api::SecretView { - display: k.describe(), + display: k.shown(), env: k.env_var().map(str::to_string), }), auth_header: p.auth_header().0.to_string(), @@ -410,60 +403,57 @@ fn provider_view( } } -/// 把 `when` 写成人话。 +/// `when` 里写了的条件,按固定顺序。 /// /// **规则列表上必须能直接读懂条件** —— 让用户去对着 YAML 猜「这条为什么 -/// 没命中」,正是那类「我明明配了」问题的来源。 -fn describe_when(w: &tw_engine::rule::When) -> Vec { +/// 没命中」,正是那类「我明明配了」问题的来源。这里给键和值,每个条件 +/// 怎么称呼由界面决定。 +fn describe_when(w: &tw_engine::rule::When) -> Vec { let mut out = Vec::new(); - if let Some(m) = &w.model { - out.push(format!("模型 {m}")); - } - if let Some(c) = &w.client { - out.push(format!("客户端 {c}")); - } - if let Some(d) = &w.dialect { - out.push(format!("方言 {d}")); - } - for (label, v) in [ - ("输入 token", &w.input_tokens), + let mut push = |field: &str, values: Vec| { + out.push(tw_api::ConditionView { + field: field.to_string(), + values, + }) + }; + for (field, v) in [ + ("model", &w.model), + ("client", &w.client), + ("dialect", &w.dialect), + ("input_tokens", &w.input_tokens), ("max_tokens", &w.max_tokens), - ("工具数", &w.tool_count), + ("tool_count", &w.tool_count), ] { if let Some(x) = v { - out.push(format!("{label} {x}")); + push(field, vec![x.clone()]); } } if let Some(i) = &w.intent { - out.push(format!("客户端辅助请求 {}", join_one_or_many(i))); + push("intent", one_or_many(i)); } // **不写出来的话,一条只有 provider_would_be 的规则在界面上会显示成 // 「兜底」**(条件为空就是兜底的标记)—— 那是个会让人查半天的假象。 if let Some(p) = &w.provider_would_be { - out.push(format!("将要走 {}", join_one_or_many(p))); + push("provider_would_be", one_or_many(p)); } - for (label, v) in [ - ("带缓存", w.cache), - ("带工具", w.tools), - ("带图片", w.image), - ("扩展思考", w.thinking), - ("流式", w.stream), + for (field, v) in [ + ("cache", w.cache), + ("tools", w.tools), + ("image", w.image), + ("thinking", w.thinking), + ("stream", w.stream), ] { if let Some(b) = v { - out.push(if b { - label.to_string() - } else { - format!("不{label}") - }); + push(field, vec![b.to_string()]); } } out } -fn join_one_or_many(v: &tw_engine::rule::OneOrMany) -> String { +fn one_or_many(v: &tw_engine::rule::OneOrMany) -> Vec { match v { - tw_engine::rule::OneOrMany::One(s) => s.clone(), - tw_engine::rule::OneOrMany::Many(xs) => xs.join(" 或 "), + tw_engine::rule::OneOrMany::One(s) => vec![s.clone()], + tw_engine::rule::OneOrMany::Many(xs) => xs.clone(), } } @@ -515,7 +505,11 @@ async fn l1( ok: false, segments: Vec::new(), total_ms: 0, - notes: Vec::new(), + skipped: Vec::new(), + failed: Some(l1_stage(tw_gateway::Stage { + step: tw_gateway::Step::Config, + peer: tw_gateway::Peer::Proxy, + })), error: Some(e), }); continue; @@ -541,16 +535,31 @@ pub(crate) fn l1_view( .segments .into_iter() .map(|x| tw_api::L1Segment { - name: x.name, + stage: l1_stage(x.stage), ms: x.ms, }) .collect(), total_ms: r.total_ms, - notes: r.notes, + skipped: r + .skipped + .into_iter() + .map(|x| tw_api::L1Skip { + stage: l1_stage(x.stage), + reason: x.reason.slug().to_string(), + }) + .collect(), + failed: r.failed.map(l1_stage), error: r.error, } } +fn l1_stage(s: tw_gateway::Stage) -> tw_api::L1Stage { + tw_api::L1Stage { + step: s.step.slug().to_string(), + peer: s.peer.slug().to_string(), + } +} + /// 按时间分桶的花费与请求数(概览的趋势图)。 /// /// 桶宽由调用方给:同一段数据,「今天每小时」和「最近 30 天每天」要的 @@ -791,7 +800,6 @@ fn quote_item( max_output_tokens: e.max_output_tokens, cost_micros: e.quote.cost_micros, billing: e.quote.billing.slug().to_string(), - note: e.quote.note, skipped: skip.map(|s| s.slug().to_string()), } } @@ -833,7 +841,7 @@ async fn leaks( xs.into_iter() .map(|l| tw_api::LeakGroup { provider: l.provider, - kind: l.kind, + secret: l.kind, requests: l.requests, last_at_ms: l.last_at_ms, masked: l.masked, @@ -899,7 +907,7 @@ async fn quota(State(s): State) -> Json .windows .into_iter() .map(|w| tw_api::QuotaWindow { - label: w.label, + window: w.window, used_percent: w.used_percent, reset_in_secs: w.reset_in_secs, status: w.status, @@ -940,7 +948,7 @@ async fn latency_by_provider( async fn storage(State(s): State) -> Json { let Some(store) = &s.store else { return Json(tw_api::StorageStatus { - level: "没有起来(历史记录不可用,转发不受影响)".into(), + level: "unavailable".into(), rows: 0, blob_bytes: 0, forwarding_affected: false, @@ -948,7 +956,7 @@ async fn storage(State(s): State) -> Json { }; let g = store.lock().await; Json(tw_api::StorageStatus { - level: g.level().label().to_string(), + level: g.level().slug().to_string(), rows: g.db().count().unwrap_or(0), blob_bytes: g.blobs().total_bytes(), // **永远是 false。**观测挂了,代理照跑。哪天有人想改成 @@ -961,7 +969,7 @@ fn need_store(s: &ControlState) -> Result<&Arc) -> Json m.len(), + serde_json::Value::Object(m) => m, other => panic!("{other:?}"), }; let lines = describe_when(&full); - assert_eq!( - lines.len(), - fields, - "有 when 字段没被翻成人话。已翻的:{lines:?}" - ); + assert_eq!(lines.len(), fields.len(), "有 when 字段没列出来:{lines:?}"); + // 界面按 `field` 取名称,所以它必须就是配置里的那个键 + for l in &lines { + assert!(fields.contains_key(&l.field), "{l:?}"); + } } #[test] @@ -1521,6 +1528,7 @@ mod describe_tests { serde_yaml_ng::from_str("{ provider_would_be: relay }").unwrap(); let lines = describe_when(&w); assert!(!lines.is_empty(), "空的条件列表在界面上就是「兜底」"); - assert!(lines[0].contains("relay"), "{lines:?}"); + assert_eq!(lines[0].field, "provider_would_be", "{lines:?}"); + assert_eq!(lines[0].values, ["relay"], "{lines:?}"); } } diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index 5829e7a2..1e387cda 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -128,7 +128,6 @@ pub async fn quote( input_tokens: input as i64, cost_micros: quote.cost_micros, billing: quote.billing.slug().to_string(), - note: quote.note, // 脱敏在重放里照做,但用户有权在按下去之前知道 will_redact: !tw_gateway::guard::effective_kinds(provider, &tw_engine::Guard::default()) .is_empty(), diff --git a/crates/tw-control/src/scan.rs b/crates/tw-control/src/scan.rs index d03c8aee..fb8e8c1c 100644 --- a/crates/tw-control/src/scan.rs +++ b/crates/tw-control/src/scan.rs @@ -30,7 +30,6 @@ pub fn finding_view(f: &tw_scan::report::Finding) -> tw_api::ScanFinding { level: f.level.slug().to_string(), rule: f.rule.clone(), kind: f.kind.slug().to_string(), - kind_label: f.kind.label().to_string(), client: f.client.clone(), path: f.path.display().to_string(), line: f.line, @@ -66,7 +65,9 @@ pub async fn scan( conflicting: Vec::new(), unreadable: Vec::new(), scanned: 0, - rules_origin: e.to_string(), + rules_active: 0, + rules_custom: 0, + rules_disabled: 0, rules_warning: Some(e.to_string()), projects: p.project, }); @@ -120,7 +121,9 @@ pub async fn scan( .collect(), unreadable: r.unreadable, scanned, - rules_origin: rules.summary(), + rules_active: rules.rules.len(), + rules_custom: rules.custom(), + rules_disabled: rules.disabled.len(), // **写坏的那几条要说出来** —— 一条静默失效的安全规则,比没有那条 // 规则更糟,因为用户以为它在 rules_warning: (!rules.warnings.is_empty()).then(|| rules.warnings.join(";")), diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 81625280..c840fc7e 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -110,7 +110,6 @@ async fn a_client_that_needs_a_restart_says_so_and_gets_no_silence_warning() { let codex = v.clients.iter().find(|c| c.id == "codex").unwrap(); assert_eq!(codex.takes_effect, "on_restart"); assert!(!codex.warns_when_silent); - assert!(codex.takes_effect_note.contains("重开")); } #[tokio::test] @@ -141,13 +140,18 @@ async fn the_plan_summary_never_echoes_the_key() { let v: tw_api::PlanView = serde_json::from_str(&body).unwrap(); assert!(v.carries_secret); for f in &v.fields { - assert!(!f.contains("tw-一把钥匙就够"), "字段摘要里回显了密钥:{f}"); + assert!( + !f.value.as_deref().unwrap_or("").contains("tw-一把钥匙就够"), + "字段摘要里回显了密钥:{f:?}" + ); } - assert!( - v.fields.iter().any(|f| f.contains("网关密钥")), - "{:?}", - v.fields - ); + let key = v + .fields + .iter() + .find(|f| f.path == "env.ANTHROPIC_AUTH_TOKEN") + .expect("写密钥的那一项要列出来"); + assert_eq!(key.op, "set"); + assert_eq!(key.value, None, "{key:?}"); } #[tokio::test] diff --git a/crates/tw-control/tests/dryrun.rs b/crates/tw-control/tests/dryrun.rs index d260d373..5c5abcd3 100644 --- a/crates/tw-control/tests/dryrun.rs +++ b/crates/tw-control/tests/dryrun.rs @@ -111,16 +111,20 @@ async fn every_rule_that_did_not_match_says_what_it_wanted() { .find(|t| t.name == "带缓存的必须走官方") .unwrap(); assert_eq!(cache_rule.verdict, "skipped"); - let why = cache_rule.why.as_deref().unwrap(); - assert!(why.contains("cache"), "{why}"); - assert!( - why.contains("true") && why.contains("false"), - "要说清要什么、实际是什么:{why}" + // 要说清要什么、实际是什么 + assert_eq!( + cache_rule.mismatch, + Some(tw_api::MismatchView { + field: "cache".into(), + want: vec!["true".into()], + got: "false".into(), + }) ); let long = r.trace.iter().find(|t| t.name == "超长上下文降级").unwrap(); - assert!( - long.why.as_deref().unwrap().contains("input_tokens"), + assert_eq!( + long.mismatch.as_ref().map(|m| m.field.as_str()), + Some("input_tokens"), "{long:?}" ); } @@ -153,14 +157,12 @@ async fn a_set_only_rule_still_shows_up_as_matched_and_says_what_it_changes() { "{:?}", r.trace ); + // 换模型会作废整个缓存,而那在长会话里可能比不换还贵 —— 所以它单独 + // 是一项,界面才能在这一项旁边说出来 assert!( - r.set.iter().any(|s| s.contains("claude-haiku-4-5")), - "{:?}", r.set - ); - // 换模型会作废整个缓存,而那在长会话里可能比不换还贵 - assert!( - r.set.iter().any(|s| s.contains("prompt cache")), + .iter() + .any(|s| s.field == "model" && s.value == "claude-haiku-4-5"), "{:?}", r.set ); diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index c6306aac..2f9aa8f9 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -273,10 +273,8 @@ routes: assert_eq!(v["outcome"], "unavailable", "{v}"); assert_eq!(v["candidates"], serde_json::json!([])); assert_eq!(v["skipped"][1]["reason"], "out_of_scope", "{v}"); - assert!( - v["reason"].as_str().unwrap().contains("claude-opus-4-1"), - "{v}" - ); + // 原因都在 `skipped` 里,不再另写一句 + assert!(v["reason"].is_null(), "{v}"); } #[tokio::test] diff --git a/crates/tw-control/tests/sync.rs b/crates/tw-control/tests/sync.rs index 0066bfc4..864cd552 100644 --- a/crates/tw-control/tests/sync.rs +++ b/crates/tw-control/tests/sync.rs @@ -49,7 +49,7 @@ async fn an_external_edit_is_picked_up_and_takes_effect() { std::fs::write(mgr.path(), &next).unwrap(); match next_config_event(&mut rx).await { - tw_api::Event::ConfigReloaded { origin, .. } => assert_eq!(origin, "外部编辑"), + tw_api::Event::ConfigReloaded { origin, .. } => assert_eq!(origin, "external"), other => panic!("{other:?}"), } } @@ -67,14 +67,14 @@ async fn our_own_write_does_not_come_back_as_an_external_edit() { // 第一个事件是我们自己那次写 match next_config_event(&mut rx).await { - tw_api::Event::ConfigReloaded { origin, .. } => assert_eq!(origin, "界面"), + tw_api::Event::ConfigReloaded { origin, .. } => assert_eq!(origin, "ui"), other => panic!("{other:?}"), } // 之后不该再冒出一个「外部编辑」 let stray = tokio::time::timeout(Duration::from_millis(1200), async { loop { if let Ok(tw_api::Event::ConfigReloaded { origin, .. }) = rx.recv().await - && origin == "外部编辑" + && origin == "external" { return; } @@ -103,7 +103,7 @@ async fn a_broken_file_keeps_the_old_config_serving_and_says_where() { message, .. } => { - assert_eq!(stage, "字段"); + assert_eq!(stage, "schema"); assert_eq!(line, Some(4), "得指到那一行"); assert!(message.contains("kye"), "{message}"); } diff --git a/crates/tw-dialect/src/req.rs b/crates/tw-dialect/src/req.rs index 0b6908e5..8a9305df 100644 --- a/crates/tw-dialect/src/req.rs +++ b/crates/tw-dialect/src/req.rs @@ -24,6 +24,10 @@ use serde_json::{Map, Value, json}; pub struct Converted { pub body: Value, /// 转不过去、只能丢掉的东西。**必须交出去给用户看** + /// + /// 写的是它在请求体里的位置(`thinking`、`top_k`、 + /// `messages.content.thinking`),不是一句解释 —— 「目标协议没有这个 + /// 字段」对每一项都成立,由界面说一次就够了。 pub dropped: Vec, } @@ -70,18 +74,21 @@ fn content_part(block: &Value, dropped: &mut Vec) -> Option { "image_url": { "url": src.get("url").and_then(|u| u.as_str()).unwrap_or_default() }, })), other => { - dropped.push(format!("一个 image 块的 source 类型是 {other:?},转不过去")); + dropped.push(format!( + "messages.content.image.source.{}", + other.unwrap_or("unknown") + )); None } } } // 扩展思考在 OpenAI chat 里没有对应物 - Some("thinking") | Some("redacted_thinking") => { - dropped.push("消息里的 thinking 块(OpenAI chat 方言没有它)".into()); + Some(t @ ("thinking" | "redacted_thinking")) => { + dropped.push(format!("messages.content.{t}")); None } Some(other) => { - dropped.push(format!("不认识的 content 块类型 `{other}`")); + dropped.push(format!("messages.content.{other}")); None } None => None, @@ -244,11 +251,11 @@ pub fn to_openai(v: &Value) -> Converted { out.insert("stream_options".into(), json!({ "include_usage": true })); } if v.get("thinking").is_some_and(|t| !t.is_null()) { - dropped.push("thinking(扩展思考):OpenAI chat 方言没有对应字段".into()); + dropped.push("thinking".into()); } for k in ["top_k", "metadata"] { if v.get(k).is_some() { - dropped.push(format!("{k}:OpenAI chat 方言没有对应字段")); + dropped.push(k.to_string()); } } Converted { @@ -357,17 +364,7 @@ mod tests { let c = conv( r#"{"model":"m","messages":[],"thinking":{"type":"enabled","budget_tokens":1024},"top_k":40}"#, ); - assert_eq!(c.dropped.len(), 2, "{:?}", c.dropped); - assert!( - c.dropped.iter().any(|d| d.contains("thinking")), - "{:?}", - c.dropped - ); - assert!( - c.dropped.iter().any(|d| d.contains("top_k")), - "{:?}", - c.dropped - ); + assert_eq!(c.dropped, ["thinking", "top_k"]); // 而且请求本身不该带上它们 assert!(c.body.get("thinking").is_none()); assert!(c.body.get("top_k").is_none()); diff --git a/crates/tw-engine/src/engine.rs b/crates/tw-engine/src/engine.rs index 8f1ab575..d658534a 100644 --- a/crates/tw-engine/src/engine.rs +++ b/crates/tw-engine/src/engine.rs @@ -60,13 +60,15 @@ impl GroupType { !matches!(self, GroupType::Fallback | GroupType::Select) } - pub fn label(&self) -> &'static str { + /// 配置里 `type` 写的那个词,也是控制面发给界面的值。**界面按它判断、 + /// 按它取自己的名称**,不拿显示文字去比较。 + pub fn slug(&self) -> &'static str { match self { - GroupType::Fallback => "按顺序", - GroupType::Select => "手动选", - GroupType::LoadBalance => "轮流", - GroupType::UrlTest => "选最快", - GroupType::Cheapest => "选最便宜", + GroupType::Fallback => "fallback", + GroupType::Select => "select", + GroupType::LoadBalance => "load-balance", + GroupType::UrlTest => "url-test", + GroupType::Cheapest => "cheapest", } } } @@ -778,6 +780,22 @@ impl Engine { mod tests { use super::*; + /// 界面拿 `slug()` 去判断、去写回配置,所以它必须就是配置里的那个词。 + #[test] + fn the_slug_is_the_word_written_in_the_config() { + for t in [ + GroupType::Fallback, + GroupType::Select, + GroupType::LoadBalance, + GroupType::UrlTest, + GroupType::Cheapest, + ] { + let back: GroupType = + serde_json::from_value(serde_json::Value::String(t.slug().into())).unwrap(); + assert_eq!(back, t); + } + } + fn facts(model: &str) -> RequestFacts { RequestFacts { model: model.into(), diff --git a/crates/tw-gateway/src/clientprobe.rs b/crates/tw-gateway/src/clientprobe.rs index eb125c75..39243304 100644 --- a/crates/tw-gateway/src/clientprobe.rs +++ b/crates/tw-gateway/src/clientprobe.rs @@ -24,17 +24,8 @@ pub enum ProbeKind { } impl ProbeKind { - pub fn label(&self) -> &'static str { - match self { - ProbeKind::HealthCheck => "连通性检查", - ProbeKind::Warmup => "预热", - ProbeKind::Titling => "会话标题", - ProbeKind::TopicDetect => "话题检测", - ProbeKind::Suggestion => "建议模式", - } - } - - /// 规则里 `when: { intent: ... }` 写的那个词。 + /// 规则里 `when: { intent: ... }` 写的那个词,也是 `LocallyAnswered.probe` + /// 和 `ProbeView.id` 发的值。 pub fn slug(&self) -> &'static str { match self { ProbeKind::HealthCheck => "health_check", diff --git a/crates/tw-gateway/src/l1.rs b/crates/tw-gateway/src/l1.rs index ea5fa44c..ab81c902 100644 --- a/crates/tw-gateway/src/l1.rs +++ b/crates/tw-gateway/src/l1.rs @@ -23,24 +23,135 @@ use tokio::net::TcpStream; /// 一句「8 秒超时」和「TLS 握手 8 秒没完成」的可修复性差得远。 const PHASE_TIMEOUT: Duration = Duration::from_secs(8); +/// 建连的哪一步。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Step { + /// 地址或代理配置用不了,还没有开始建连 + Config, + Dns, + Tcp, + Tls, + /// 代理协议的握手,含认证 + Handshake, +} + +impl Step { + pub fn slug(&self) -> &'static str { + match self { + Step::Config => "config", + Step::Dns => "dns", + Step::Tcp => "tcp", + Step::Tls => "tls", + Step::Handshake => "handshake", + } + } +} + +/// 这一步对着谁。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Peer { + Upstream, + Proxy, +} + +impl Peer { + pub fn slug(&self) -> &'static str { + match self { + Peer::Upstream => "upstream", + Peer::Proxy => "proxy", + } + } +} + +/// 建连的一步,连同它对着谁。**失败时报的就是它**:「卡在到代理的 TCP +/// 握手」和「卡在上游的 TLS 握手」该去修的地方完全不同。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Stage { + pub step: Step, + pub peer: Peer, +} + +impl Stage { + const fn new(step: Step, peer: Peer) -> Self { + Self { step, peer } + } + + /// 命令行里的说法。**界面不用它**,界面按 `step` / `peer` 自己说。 + pub fn label(&self) -> String { + let step = match self.step { + Step::Config => "配置", + Step::Dns => "DNS 解析", + Step::Tcp => "TCP 握手", + Step::Tls => "TLS 握手", + Step::Handshake => "代理握手", + }; + match (self.step, self.peer) { + (Step::Handshake, _) | (_, Peer::Upstream) => step.to_string(), + (_, Peer::Proxy) => format!("{step} · 代理"), + } + } +} + +/// 某一步为什么没有出现在分段里。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SkipReason { + /// `http://` 地址没有 TLS + PlainHttp, + /// 地址已经是 IP,不需要解析 + IpAddress, + /// `socks5h` 和 HTTP CONNECT 把域名交给代理解析 + ProxyResolves, +} + +impl SkipReason { + pub fn slug(&self) -> &'static str { + match self { + SkipReason::PlainHttp => "plain_http", + SkipReason::IpAddress => "ip_address", + SkipReason::ProxyResolves => "proxy_resolves", + } + } + + /// 命令行里的说法。 + pub fn label(&self) -> &'static str { + match self { + SkipReason::PlainHttp => "http:// 地址不进行 TLS 握手", + SkipReason::IpAddress => "地址已是 IP,无需 DNS 解析", + SkipReason::ProxyResolves => "域名由代理解析,本机不进行 DNS 解析", + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Segment { - pub name: String, + pub stage: Stage, pub ms: u64, } +/// 没出现在分段里的一步。**不说的话,缺一段看起来就像 bug。** +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Skip { + pub stage: Stage, + pub reason: SkipReason, +} + /// **分段是个列表而不是固定的三个字段**,因为走代理时的形状本来就不同: -/// 多出「代理握手」,而 `socks5h` 下根本没有本地 DNS 这一段。用 +/// 多出代理握手,而 `socks5h` 下根本没有本地 DNS 这一段。用 /// `Option` 表达会把「测不到」和「0 毫秒」混成一件事。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct L1Result { pub ok: bool, pub segments: Vec, pub total_ms: u64, - /// 解释为什么某一段不在上面。**没有这句话,缺一段看起来就像 bug。** #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub notes: Vec, - /// 失败时说清楚卡在哪一段、下一步做什么 + pub skipped: Vec, + /// 失败在哪一步 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failed: Option, + /// 失败的原因和下一步 #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, } @@ -70,7 +181,7 @@ pub fn hop_for( match p.proxy.as_str() { tw_config::DIRECT => Ok(None), tw_config::SYSTEM => Err( - "这家走的是系统代理,而系统代理的地址要到建连时才由环境决定 —— L1 测不到它。想量这条线的话,把代理显式配成一个命名条目。" + "该上游使用系统代理,代理地址在建立连接时才能确定,链路测速无法测量。如需测速,请将代理配置为命名代理。" .into(), ), name => { @@ -78,7 +189,7 @@ pub fn hop_for( .proxies .iter() .find(|x| x.name == name) - .ok_or_else(|| format!("provider `{}` 要走代理 `{name}`,但 proxies 段里没有这个名字。", p.name))?; + .ok_or_else(|| format!("上游「{}」使用的代理「{name}」未在 proxies 中定义。", p.name))?; hop_of(px).map(Some) } } @@ -93,7 +204,7 @@ pub fn hop_of(px: &tw_config::Proxy) -> Result { a.user.clone(), a.pass .resolve() - .map_err(|e| format!("代理 `{}` 的密码取不出来:{e}", px.name))?, + .map_err(|e| format!("无法读取代理「{}」的密码:{e}", px.name))?, )), }; Ok(ProxyHop { @@ -122,7 +233,7 @@ impl Io for T {} struct Timer { segments: Vec, - notes: Vec, + skipped: Vec, started: Instant, last: Instant, } @@ -132,29 +243,33 @@ impl Timer { let now = Instant::now(); Self { segments: Vec::new(), - notes: Vec::new(), + skipped: Vec::new(), started: now, last: now, } } - fn mark(&mut self, name: impl Into) { + fn mark(&mut self, stage: Stage) { let now = Instant::now(); self.segments.push(Segment { - name: name.into(), + stage, ms: now.duration_since(self.last).as_millis() as u64, }); self.last = now; } + fn skip(&mut self, stage: Stage, reason: SkipReason) { + self.skipped.push(Skip { stage, reason }); + } fn total(&self) -> u64 { self.started.elapsed().as_millis() as u64 } - fn fail(self, phase: &str, msg: impl std::fmt::Display) -> L1Result { + fn fail(self, stage: Stage, msg: impl std::fmt::Display) -> L1Result { L1Result { ok: false, total_ms: self.total(), segments: self.segments, - notes: self.notes, - error: Some(format!("{phase}:{msg}")), + skipped: self.skipped, + failed: Some(stage), + error: Some(msg.to_string()), } } fn ok(self) -> L1Result { @@ -162,35 +277,41 @@ impl Timer { ok: true, total_ms: self.total(), segments: self.segments, - notes: self.notes, + skipped: self.skipped, + failed: None, error: None, } } } -async fn phase( - what: &str, - f: impl std::future::Future>, -) -> Result { +/// 某一步超时的说法。**它同时是判据**:解析超时和解析失败要说成两句话。 +fn timed_out() -> String { + format!("{} 秒内未完成", PHASE_TIMEOUT.as_secs()) +} + +async fn phase(f: impl std::future::Future>) -> Result { match tokio::time::timeout(PHASE_TIMEOUT, f).await { Ok(Ok(v)) => Ok(v), Ok(Err(e)) => Err(e.to_string()), - Err(_) => Err(format!("{PHASE_TIMEOUT:?} 内没完成({what})")), + Err(_) => Err(timed_out()), } } /// 拆出 host / port / 要不要 TLS。 fn target_of(base_url: &str) -> Result<(String, u16, bool), String> { - let u = - reqwest::Url::parse(base_url).map_err(|e| format!("base_url 不是一个合法的 URL:{e}"))?; + let u = reqwest::Url::parse(base_url).map_err(|e| format!("接口地址不是合法的 URL:{e}"))?; let tls = match u.scheme() { "https" => true, "http" => false, - other => return Err(format!("不支持的 scheme `{other}`,只能是 http 或 https")), + other => { + return Err(format!( + "接口地址的协议 {other} 不受支持,仅支持 http 和 https" + )); + } }; let host = u .host_str() - .ok_or("base_url 里没有主机名")? + .ok_or("接口地址中缺少主机名")? .trim_matches(['[', ']']) .to_string(); Ok((host, u.port_or_known_default().unwrap_or(443), tls)) @@ -201,7 +322,7 @@ pub async fn l1(base_url: &str, proxy: Option<&ProxyHop>) -> L1Result { let mut t = Timer::new(); let (host, port, tls) = match target_of(base_url) { Ok(v) => v, - Err(e) => return t.fail("配置", e), + Err(e) => return t.fail(Stage::new(Step::Config, Peer::Upstream), e), }; let stream: Box = match proxy { @@ -215,15 +336,15 @@ pub async fn l1(base_url: &str, proxy: Option<&ProxyHop>) -> L1Result { }, }; + let tls_stage = Stage::new(Step::Tls, Peer::Upstream); if !tls { - t.notes - .push("这是一个 http:// 地址,没有 TLS 这一段。".into()); + t.skip(tls_stage, SkipReason::PlainHttp); return t.ok(); } if let Err(e) = tls_handshake(stream, &host).await { - return t.fail("TLS 握手", e); + return t.fail(tls_stage, e); } - t.mark("TLS 握手"); + t.mark(tls_stage); t.ok() } @@ -244,45 +365,49 @@ pub async fn l1_proxy(p: &ProxyHop, host: &str, port: u16) -> L1Result { } async fn connect_direct(t: &mut Timer, host: &str, port: u16) -> Result { - let addr = match resolve(t, host, port, "DNS 解析").await { + let dns = Stage::new(Step::Dns, Peer::Upstream); + let addr = match resolve(t, host, port, dns).await { Ok(a) => a, - Err(e) => return Err(std::mem::replace(t, Timer::new()).fail("DNS 解析", e)), + Err(e) => return Err(std::mem::replace(t, Timer::new()).fail(dns, e)), }; - match phase("TCP 握手", TcpStream::connect(addr)).await { + let tcp = Stage::new(Step::Tcp, Peer::Upstream); + match phase(TcpStream::connect(addr)).await { Ok(s) => { let _ = s.set_nodelay(true); - t.mark("TCP 握手"); + t.mark(tcp); Ok(s) } - Err(e) => Err(std::mem::replace(t, Timer::new()).fail("TCP 握手", tcp_message(&e, addr))), + Err(e) => Err(std::mem::replace(t, Timer::new()).fail(tcp, tcp_message(&e, addr))), } } /// 解析一个 `host:port`。**已经是 IP 时不记这一段** —— 记一个 0ms 的 -/// 「DNS 解析」会让人以为解析快得离谱,而实际是根本没发生。 -async fn resolve(t: &mut Timer, host: &str, port: u16, label: &str) -> Result { +/// DNS 解析会让人以为解析快得离谱,而实际是根本没发生。 +async fn resolve(t: &mut Timer, host: &str, port: u16, stage: Stage) -> Result { if let Ok(ip) = host.parse::() { - t.notes - .push(format!("{host} 已经是 IP,没有 {label} 这一段。")); + t.skip(stage, SkipReason::IpAddress); t.last = Instant::now(); return Ok(SocketAddr::new(ip, port)); } // **解析失败的系统原话是英文的、而且没提到域名。**「nodename nor // servname provided」对着一个中文界面出现,用户既不知道它在说谁, // 也不知道该改哪里。 - let mut it = phase(label, tokio::net::lookup_host((host, port))) + let mut it = phase(tokio::net::lookup_host((host, port))) .await .map_err(|e| { - if e.contains("内没完成") { - format!("{host} 的解析{e}。DNS 服务器可能不通。") + if e == timed_out() { + format!( + "解析 {host} 超过 {} 秒未完成,DNS 服务器可能无法访问。", + PHASE_TIMEOUT.as_secs() + ) } else { - format!("解析不出 `{host}`。检查域名拼写;如果这家上游本来就要走代理,先配好代理。") + format!("无法解析 {host}。请检查域名拼写;如果该地址需要经代理访问,请先配置代理。") } })?; let addr = it .next() - .ok_or_else(|| format!("`{host}` 解析成功但一个地址都没有"))?; - t.mark(label); + .ok_or_else(|| format!("{host} 的解析结果中没有地址"))?; + t.mark(stage); Ok(addr) } @@ -296,51 +421,52 @@ async fn connect_via_proxy( let (phost, pport) = match split_hostport(&p.addr) { Ok(v) => v, - Err(e) => return Err(std::mem::replace(t, Timer::new()).fail("代理地址", e)), + Err(e) => { + let stage = Stage::new(Step::Config, Peer::Proxy); + return Err(std::mem::replace(t, Timer::new()).fail(stage, e)); + } }; // socks5(不带 h)在本地解析目标域名 —— **这一段正是会被污染的那一段**, // 所以它值得单独计时。socks5h 和 CONNECT 都把域名原样交给代理。 + let upstream_dns = Stage::new(Step::Dns, Peer::Upstream); let target_ip = if p.kind == Socks5 { - match resolve(t, host, port, "DNS 解析 · 上游").await { + match resolve(t, host, port, upstream_dns).await { Ok(a) => Some(a), - Err(e) => return Err(std::mem::replace(t, Timer::new()).fail("DNS 解析 · 上游", e)), + Err(e) => return Err(std::mem::replace(t, Timer::new()).fail(upstream_dns, e)), } } else { - if p.kind == Socks5h { - t.notes - .push("socks5h 把域名原样交给代理解析,本地没有 DNS 这一段(这正是它比 socks5 抗污染的地方)。".into()); - } else { - t.notes - .push("HTTP CONNECT 把域名原样交给代理解析,本地没有 DNS 这一段。".into()); - } + t.skip(upstream_dns, SkipReason::ProxyResolves); None }; - let paddr = match resolve(t, &phost, pport, "DNS 解析 · 代理").await { + let proxy_dns = Stage::new(Step::Dns, Peer::Proxy); + let paddr = match resolve(t, &phost, pport, proxy_dns).await { Ok(a) => a, - Err(e) => return Err(std::mem::replace(t, Timer::new()).fail("DNS 解析 · 代理", e)), + Err(e) => return Err(std::mem::replace(t, Timer::new()).fail(proxy_dns, e)), }; - let tcp = match phase("TCP 握手 · 代理", TcpStream::connect(paddr)).await { + let proxy_tcp = Stage::new(Step::Tcp, Peer::Proxy); + let tcp = match phase(TcpStream::connect(paddr)).await { Ok(s) => { let _ = s.set_nodelay(true); - t.mark("TCP 握手 · 代理"); + t.mark(proxy_tcp); s } Err(e) => { let msg = tcp_message(&e, paddr); - return Err(std::mem::replace(t, Timer::new()).fail("TCP 握手 · 代理", msg)); + return Err(std::mem::replace(t, Timer::new()).fail(proxy_tcp, msg)); } }; // https 代理:到代理这一跳本身也是 TLS,CONNECT 走在里面。 + let proxy_tls = Stage::new(Step::Tls, Peer::Proxy); let mut io: Box = if p.kind == Https { match tls_handshake_boxed(Box::new(tcp), &phost).await { Ok(s) => { - t.mark("TLS 握手 · 代理"); + t.mark(proxy_tls); s } - Err(e) => return Err(std::mem::replace(t, Timer::new()).fail("TLS 握手 · 代理", e)), + Err(e) => return Err(std::mem::replace(t, Timer::new()).fail(proxy_tls, e)), } } else { Box::new(tcp) @@ -350,12 +476,13 @@ async fn connect_via_proxy( Socks5 | Socks5h => socks5_connect(&mut io, p, host, port, target_ip).await, Http | Https => http_connect(&mut io, p, host, port).await, }; + let handshake = Stage::new(Step::Handshake, Peer::Proxy); match r { Ok(()) => { - t.mark("代理握手"); + t.mark(handshake); Ok(io) } - Err(e) => Err(std::mem::replace(t, Timer::new()).fail("代理握手", e)), + Err(e) => Err(std::mem::replace(t, Timer::new()).fail(handshake, e)), } } @@ -365,13 +492,13 @@ async fn connect_via_proxy( fn tcp_message(e: &str, addr: SocketAddr) -> String { let l = e.to_ascii_lowercase(); if l.contains("refused") { - format!("{addr} 拒绝了连接 —— 那个端口上没有东西在听。检查地址和端口。") - } else if l.contains("内没完成") || l.contains("timed out") { - format!("连 {addr} 一直没有回应。多半是被丢包了:检查网络,或者这家上游需要走代理。") + format!("{addr} 拒绝连接,该端口上没有服务在监听。请检查地址和端口。") + } else if e == timed_out() || l.contains("timed out") { + format!("连接 {addr} 没有响应。请检查网络,或确认该地址是否需要经代理访问。") } else if l.contains("unreachable") { - format!("到 {addr} 的网络不可达。检查本机网络。") + format!("无法访问 {addr} 所在的网络,请检查本机网络。") } else { - format!("连不上 {addr}:{e}") + format!("无法连接 {addr}:{e}") } } @@ -380,19 +507,21 @@ fn split_hostport(s: &str) -> Result<(String, u16), String> { if let Some(rest) = s.strip_prefix('[') { let (h, p) = rest .split_once("]:") - .ok_or("IPv6 代理地址要写成 [::1]:1080")?; - return Ok((h.to_string(), p.parse().map_err(|_| "端口不是数字")?)); + .ok_or("IPv6 代理地址应写成 [::1]:1080 的形式")?; + return Ok((h.to_string(), p.parse().map_err(|_| "端口必须是数字")?)); } - let (h, p) = s.rsplit_once(':').ok_or("代理地址要写成 host:port")?; + let (h, p) = s + .rsplit_once(':') + .ok_or("代理地址应写成 主机:端口 的形式")?; // **裸的 IPv6 要报错,不能猜。**`fe80::1` 会被切成主机 `fe80:` 加 // 端口 `1` —— 一个语法上完全合法、语义上彻底错掉的结果,而它的表现 // 是「代理连不上」,没有任何线索指向这里。 if h.contains(':') { - return Err(format!("`{s}` 里的 IPv6 地址要加方括号,写成 [{h}]:{p}")); + return Err(format!("{s} 中的 IPv6 地址需要加方括号,应写成 [{h}]:{p}")); } Ok(( h.to_string(), - p.parse().map_err(|_| format!("端口 `{p}` 不是数字"))?, + p.parse().map_err(|_| format!("端口 {p} 不是数字"))?, )) } @@ -415,7 +544,7 @@ async fn socks5_connect( read_exact(io, &mut m).await?; if m[0] != 0x05 { return Err(format!( - "对面回的不是 SOCKS5(版本字节 0x{:02x})。这个端口上跑的可能是 HTTP 代理。", + "代理的响应不是 SOCKS5 协议(版本字节 0x{:02x}),该端口上可能是 HTTP 代理。", m[0] )); } @@ -423,10 +552,10 @@ async fn socks5_connect( 0x00 => {} 0x02 => { let Some((u, pw)) = &p.auth else { - return Err("代理要求用户名密码,但这个代理没有配 auth".into()); + return Err("代理要求用户名和密码认证,但该代理未配置认证信息".into()); }; if u.len() > 255 || pw.len() > 255 { - return Err("SOCKS5 的用户名和密码都不能超过 255 字节".into()); + return Err("SOCKS5 的用户名和密码均不能超过 255 字节".into()); } let mut buf = vec![0x01, u.len() as u8]; buf.extend_from_slice(u.as_bytes()); @@ -436,11 +565,11 @@ async fn socks5_connect( let mut r = [0u8; 2]; read_exact(io, &mut r).await?; if r[1] != 0x00 { - return Err("代理拒绝了用户名密码".into()); + return Err("代理拒绝了用户名和密码".into()); } } - 0xFF => return Err("代理不接受我们提供的认证方式".into()), - other => return Err(format!("代理选了一个我们不支持的认证方式 0x{other:02x}")), + 0xFF => return Err("代理不接受所提供的认证方式".into()), + other => return Err(format!("代理要求的认证方式 0x{other:02x} 不受支持")), } // CONNECT @@ -456,7 +585,7 @@ async fn socks5_connect( } None => { if host.len() > 255 { - return Err("域名超过 255 字节,SOCKS5 发不出去".into()); + return Err("域名超过 255 字节,无法通过 SOCKS5 发送".into()); } req.push(0x03); req.push(host.len() as u8); @@ -480,7 +609,7 @@ async fn socks5_connect( read_exact(io, &mut l).await?; l[0] as usize } - other => return Err(format!("代理回了一个看不懂的地址类型 0x{other:02x}")), + other => return Err(format!("代理返回了无法识别的地址类型 0x{other:02x}")), }; let mut rest = vec![0u8; n + 2]; read_exact(io, &mut rest).await?; @@ -490,13 +619,13 @@ async fn socks5_connect( fn socks5_reply(code: u8) -> &'static str { match code { 0x01 => "代理内部错误", - 0x02 => "代理的规则不允许连这个地址", + 0x02 => "代理规则不允许连接该地址", 0x03 => "网络不可达", 0x04 => "主机不可达", 0x05 => "目标拒绝连接", - 0x06 => "TTL 过期", + 0x06 => "TTL 已过期", 0x07 => "代理不支持 CONNECT", - 0x08 => "代理不支持这个地址类型", + 0x08 => "代理不支持该地址类型", _ => "代理拒绝了连接", } } @@ -532,7 +661,7 @@ async fn http_connect( break; } if buf.len() > 8192 { - return Err("代理的响应头超过 8KB,不像是一个 HTTP 代理".into()); + return Err("代理的响应头超过 8 KB,该端口上可能不是 HTTP 代理".into()); } } let head = String::from_utf8_lossy(&buf); @@ -540,21 +669,18 @@ async fn http_connect( let code = line.split_whitespace().nth(1).unwrap_or(""); match code { "200" => Ok(()), - "407" => Err("代理要求认证(407)。检查用户名密码。".into()), - "" => Err(format!("代理回了一句看不懂的话:{line}")), - c => Err(format!("代理拒绝了 CONNECT(HTTP {c}):{line}")), + "407" => Err("代理要求认证(HTTP 407),请检查用户名和密码。".into()), + "" => Err(format!("代理返回了无法识别的响应:{line}")), + c => Err(format!("代理拒绝了 CONNECT 请求(HTTP {c}):{line}")), } } async fn write_all(io: &mut Box, buf: &[u8]) -> Result<(), String> { - phase("写给代理", io.write_all(buf)).await + phase(io.write_all(buf)).await } async fn read_exact(io: &mut Box, buf: &mut [u8]) -> Result<(), String> { - phase("等代理回话", async { - io.read_exact(buf).await.map(|_| ()) - }) - .await + phase(async { io.read_exact(buf).await.map(|_| ()) }).await } /// TLS 配置。**用平台的信任根**,和数据面走的是同一套验证 —— 否则 L1 @@ -569,7 +695,7 @@ pub(crate) fn tls_config() -> Arc { use rustls_platform_verifier::BuilderVerifierExt; let c = rustls::ClientConfig::builder() .with_platform_verifier() - .expect("装不出平台证书验证器") + .expect("无法创建平台证书验证器") .with_no_client_auth(); Arc::new(c) }) @@ -582,12 +708,12 @@ async fn tls_handshake(stream: Box, host: &str) -> Result<(), String> { async fn tls_handshake_boxed(stream: Box, host: &str) -> Result, String> { let name = rustls::pki_types::ServerName::try_from(host.to_string()) - .map_err(|_| format!("`{host}` 不是一个能放进 SNI 的主机名"))?; + .map_err(|_| format!("{host} 不是有效的 TLS 主机名"))?; let conn = tokio_rustls::TlsConnector::from(tls_config()); match tokio::time::timeout(PHASE_TIMEOUT, conn.connect(name, stream)).await { Ok(Ok(s)) => Ok(Box::new(s)), Ok(Err(e)) => Err(tls_message(&e)), - Err(_) => Err(format!("{PHASE_TIMEOUT:?} 内没完成")), + Err(_) => Err(timed_out()), } } @@ -611,20 +737,22 @@ fn tls_message(e: &std::io::Error) -> String { // 塞进 `Other`,那些结构化变体在这个平台上永远不会出现 —— 按枚举 // 匹配的结果是每一种失败都拿到那句最泛的提示,包括证书只是过期时。 let d = detail.to_ascii_lowercase(); - let hint = - if d.contains("expired") || d.contains("not valid yet") || d.contains("not yet valid") { - "过期有两种可能:证书真的过期了,或者本机时钟不对 —— 先看一眼系统时间。" - } else if d.contains("issuer") - || d.contains("self-signed") - || d.contains("self signed") - || d.contains("untrusted") - || d.contains("not trusted") - { - "签发者不在系统信任列表里。本机装了抓包工具或公司根证书的话,这条链就是被换过的。" - } else { - "如果这条线上有东西在劫持 TLS(抓包工具、企业代理),看到的就是这个。" - }; - format!("证书验证没过:{detail}。{hint}") + let hint = if d.contains("expired") + || d.contains("not valid yet") + || d.contains("not yet valid") + { + "证书已过期或尚未生效,也可能是本机时间不准确,请先核对系统时间。" + } else if d.contains("issuer") + || d.contains("self-signed") + || d.contains("self signed") + || d.contains("untrusted") + || d.contains("not trusted") + { + "证书的签发者不在系统信任列表中。如果本机安装了抓包工具或企业根证书,证书链可能已被替换。" + } else { + "如果网络中有抓包工具或企业代理拦截 TLS 连接,也会出现此错误。" + }; + format!("证书验证未通过:{detail}。{hint}") } #[cfg(test)] @@ -632,8 +760,15 @@ mod tests { use super::*; use tokio::net::TcpListener; - fn names(r: &L1Result) -> Vec<&str> { - r.segments.iter().map(|s| s.name.as_str()).collect() + fn stages(r: &L1Result) -> Vec { + r.segments.iter().map(|s| s.stage).collect() + } + + fn skipped(r: &L1Result, step: Step, peer: Peer, reason: SkipReason) -> bool { + r.skipped.contains(&Skip { + stage: Stage::new(step, peer), + reason, + }) } /// 起一个只接受连接、什么都不说的 TCP 端口。 @@ -656,10 +791,18 @@ mod tests { let a = dead_ear().await; let r = l1(&format!("http://{a}"), None).await; assert!(r.ok, "{r:?}"); - assert_eq!(names(&r), ["TCP 握手"]); - // 缺一段必须有话说,否则看起来像 bug - assert!(r.notes.iter().any(|n| n.contains("TLS")), "{:?}", r.notes); - assert!(r.notes.iter().any(|n| n.contains("IP")), "{:?}", r.notes); + assert_eq!(stages(&r), [Stage::new(Step::Tcp, Peer::Upstream)]); + // 缺一段必须有交代,否则看起来像 bug + assert!( + skipped(&r, Step::Tls, Peer::Upstream, SkipReason::PlainHttp), + "{:?}", + r.skipped + ); + assert!( + skipped(&r, Step::Dns, Peer::Upstream, SkipReason::IpAddress), + "{:?}", + r.skipped + ); } #[tokio::test] @@ -670,14 +813,23 @@ mod tests { drop(l); let r = l1(&format!("http://{a}"), None).await; assert!(!r.ok); - assert!(r.error.as_ref().unwrap().starts_with("TCP 握手:"), "{r:?}"); + assert_eq!( + r.failed, + Some(Stage::new(Step::Tcp, Peer::Upstream)), + "{r:?}" + ); + assert!(r.error.is_some()); } #[tokio::test] async fn a_hostname_that_does_not_resolve_fails_at_dns() { let r = l1("https://no-such-host.invalid", None).await; assert!(!r.ok); - assert!(r.error.as_ref().unwrap().starts_with("DNS 解析:"), "{r:?}"); + assert_eq!( + r.failed, + Some(Stage::new(Step::Dns, Peer::Upstream)), + "{r:?}" + ); assert!(r.segments.is_empty(), "还没走到 TCP 就不该有 TCP 这一段"); } @@ -686,7 +838,11 @@ mod tests { for bad in ["ftp://x", "not a url", "https://"] { let r = l1(bad, None).await; assert!(!r.ok, "{bad} 该被拒"); - assert!(r.error.as_ref().unwrap().starts_with("配置:"), "{r:?}"); + assert_eq!( + r.failed, + Some(Stage::new(Step::Config, Peer::Upstream)), + "{r:?}" + ); } } @@ -950,7 +1106,7 @@ mod tests { let mut io = dial(a).await; let p = hop(tw_config::ProxyKind::Http, a, None); let e = http_connect(&mut io, &p, "x.com", 443).await.unwrap_err(); - assert!(e.contains("用户名密码"), "{e}"); + assert!(e.contains("用户名和密码"), "{e}"); } #[tokio::test] @@ -966,16 +1122,22 @@ mod tests { let r = l1("http://example.com:80", Some(&p)).await; assert!(r.ok, "{r:?}"); // 代理地址就是个 IP,所以没有解析这一段 —— 而这件事有话交代。 - assert_eq!(names(&r), ["TCP 握手 · 代理", "代理握手"]); + assert_eq!( + stages(&r), + [ + Stage::new(Step::Tcp, Peer::Proxy), + Stage::new(Step::Handshake, Peer::Proxy) + ] + ); assert!( - r.notes.iter().any(|n| n.contains("已经是 IP")), + skipped(&r, Step::Dns, Peer::Proxy, SkipReason::IpAddress), "{:?}", - r.notes + r.skipped ); assert!( - r.notes.iter().any(|n| n.contains("socks5h")), + skipped(&r, Step::Dns, Peer::Upstream, SkipReason::ProxyResolves), "socks5h 没有本地 DNS 这件事要说出来:{:?}", - r.notes + r.skipped ); } @@ -990,7 +1152,7 @@ mod tests { let r = l1_proxy(&p, "api.anthropic.com", 443).await; assert!(!r.ok); let e = r.error.unwrap(); - assert!(e.contains("没有东西在听"), "{e}"); + assert!(e.contains("没有服务在监听"), "{e}"); assert!(!e.contains("os error"), "{e}"); } @@ -1005,7 +1167,13 @@ mod tests { let p = hop(tw_config::ProxyKind::Socks5h, a, Some(("svc", "p@ss"))); let r = l1_proxy(&p, "api.anthropic.com", 443).await; assert!(r.ok, "{r:?}"); - assert_eq!(names(&r), ["TCP 握手 · 代理", "代理握手"]); + assert_eq!( + stages(&r), + [ + Stage::new(Step::Tcp, Peer::Proxy), + Stage::new(Step::Handshake, Peer::Proxy) + ] + ); assert_eq!(creds.await.unwrap(), "svc:p@ss"); } @@ -1034,9 +1202,6 @@ mod tests { let p = hop(tw_config::ProxyKind::Socks5h, a, None); let r = l1("https://api.anthropic.com", Some(&p)).await; assert!(!r.ok); - assert!( - r.error.as_ref().unwrap().starts_with("TCP 握手 · 代理:"), - "{r:?}" - ); + assert_eq!(r.failed, Some(Stage::new(Step::Tcp, Peer::Proxy)), "{r:?}"); } } diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index c6cbab72..0e4ad295 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -297,14 +297,14 @@ mod tests { assert_eq!(e.input_tokens, probe_input_tokens()); assert_eq!(e.max_output_tokens, MAX_TOKENS); assert!(e.quote.cost_micros.is_some()); - let tokens = (probe_input_tokens() + MAX_TOKENS).to_string(); let e = estimate( &prices(), "订阅", "claude-sonnet-4-5", tw_config::Billing::Subscription, ); - assert!(e.quote.note.contains(&tokens), "{}", e.quote.note); + assert_eq!(e.quote.cost_micros, None); + assert_eq!(e.input_tokens, probe_input_tokens()); } #[test] diff --git a/crates/tw-gateway/src/leak.rs b/crates/tw-gateway/src/leak.rs index dd9b278a..96d660cf 100644 --- a/crates/tw-gateway/src/leak.rs +++ b/crates/tw-gateway/src/leak.rs @@ -23,7 +23,7 @@ use serde::{Deserialize, Serialize}; /// 一次发现。 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Finding { - /// 「Anthropic API key」这类人话 + /// 哪种凭据,见 [`tw_redact::rules::Hit::secret`] pub kind: String, /// **已打码**的样子,比如 `sk-an…7f9c` pub masked: String, @@ -42,7 +42,7 @@ pub fn scan(body: &[u8]) -> Vec { // 决定看什么 for h in tw_redact::rules::scan(&text, tw_redact::rules::Kind::all()) { let f = Finding { - kind: h.what.to_string(), + kind: h.secret.to_string(), // **打码之后才记。**「发现了 sk-ant-xxx」这句话本身就是一次 // 泄漏 —— 它会进日志、进界面、被复制到 issue 里 masked: tw_secret::mask_secret(&text[h.bytes]), @@ -64,7 +64,7 @@ mod tests { #[test] fn a_pasted_anthropic_key_is_found() { let body = r#"{"messages":[{"role":"user","content":"我的 key 是 sk-ant-api03-abcdefghijklmnopqrstuvwxyz1234"}]}"#; - assert_eq!(kinds(body), vec!["Anthropic API key"]); + assert_eq!(kinds(body), vec!["anthropic-api-key"]); } #[test] @@ -82,8 +82,8 @@ mod tests { let body = "sk-ant-api03-aaaaaaaaaaaaaaaaaaaaaaaa 还有 ghp_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; let ks = kinds(body); - assert!(ks.contains(&"Anthropic API key".to_string()), "{ks:?}"); - assert!(ks.contains(&"GitHub personal token".to_string()), "{ks:?}"); + assert!(ks.contains(&"anthropic-api-key".to_string()), "{ks:?}"); + assert!(ks.contains(&"github-personal-token".to_string()), "{ks:?}"); } #[test] diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 1154f2ad..48fbcf25 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -40,7 +40,10 @@ pub use bodies::{BodyKind, BodyRecord, BodySender}; pub use clientprobe::{ProbeKind, classify}; pub use error::GatewayError; pub use health::Health; -pub use l1::{L1Result, ProxyHop, Segment, hop_of, l1, l1_proxy, proxy_target}; +pub use l1::{ + L1Result, Peer, ProxyHop, Segment, Skip, SkipReason, Stage, Step, hop_of, l1, l1_proxy, + proxy_target, +}; pub use l3::{Estimate, L3Result}; pub use limits::{Gate, LimitError, Limits}; pub use probe::{ModelList, ProbeResult, probe}; diff --git a/crates/tw-gateway/src/quota.rs b/crates/tw-gateway/src/quota.rs index 8cbd902e..0dad2817 100644 --- a/crates/tw-gateway/src/quota.rs +++ b/crates/tw-gateway/src/quota.rs @@ -22,8 +22,8 @@ use serde::{Deserialize, Serialize}; /// 一个额度窗口的状态。**每个字段都直接来自响应头,没有一个是推算的。** #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Window { - /// 「5h」「7d」「周」这类人话标签 - pub label: String, + /// 哪个窗口:`5h` / `7d`(Anthropic)/ `weekly`(Codex) + pub window: String, /// 用了百分之多少。0–100 pub used_percent: f64, /// 还有多少秒重置。**上游没给就是 None** —— 那时界面上只能说 @@ -84,14 +84,14 @@ pub fn from_headers(h: &HeaderMap) -> Quota { let get = |k: &str| h.get(k).and_then(|v| v.to_str().ok()); // ── Anthropic ──────────────────────────────────────────────── - for (key, label) in [("5h", "5 小时"), ("7d", "7 天")] { + for key in ["5h", "7d"] { let Some(u) = get(&format!("anthropic-ratelimit-unified-{key}-utilization")) .and_then(|v| v.parse::().ok()) else { continue; }; windows.push(Window { - label: label.to_string(), + window: key.to_string(), // 上游给的是 0–100 还是 0–1,各家不一样。**大于 1 就当成 // 百分比**:一个真实的 0.62 和一个真实的 62 都要能读对,而 // 「用了 0.62%」这种值在订阅场景下没有意义。 @@ -104,20 +104,20 @@ pub fn from_headers(h: &HeaderMap) -> Quota { } // 7 天窗口的越线标记是个独立的头 if get("anthropic-ratelimit-unified-7d-surpassed-threshold") == Some("true") - && let Some(w) = windows.iter_mut().find(|w| w.label == "7 天") + && let Some(w) = windows.iter_mut().find(|w| w.window == "7d") && w.status.is_none() { w.status = Some("allowed_warning".to_string()); } // ── Codex ──────────────────────────────────────────────────── - for (prefix, label) in [("primary", "周"), ("secondary", "5 小时")] { + for (prefix, window) in [("primary", "weekly"), ("secondary", "5h")] { let Some(u) = get(&format!("x-codex-{prefix}-used-percent")).and_then(|v| v.parse().ok()) else { continue; }; windows.push(Window { - label: label.to_string(), + window: window.to_string(), used_percent: normalize_percent(u), reset_in_secs: get(&format!("x-codex-{prefix}-reset-after-seconds")) .and_then(|v| v.parse().ok()), @@ -188,7 +188,7 @@ mod tests { ])); assert_eq!(q.windows.len(), 2); let five = &q.windows[0]; - assert_eq!(five.label, "5 小时"); + assert_eq!(five.window, "5h"); assert_eq!(five.used_percent, 62.0); assert_eq!(five.reset_in_secs, Some(7200)); assert_eq!(five.status.as_deref(), Some("allowed")); @@ -232,7 +232,7 @@ mod tests { ("anthropic-ratelimit-unified-5h-utilization", "20"), ("anthropic-ratelimit-unified-7d-utilization", "91"), ])); - assert_eq!(q.tightest().unwrap().label, "7 天"); + assert_eq!(q.tightest().unwrap().window, "7d"); } #[test] diff --git a/crates/tw-gateway/src/quote.rs b/crates/tw-gateway/src/quote.rs index a1569cef..0bbfffad 100644 --- a/crates/tw-gateway/src/quote.rs +++ b/crates/tw-gateway/src/quote.rs @@ -1,7 +1,8 @@ -//! 发出一个会花钱的请求之前的报价。推理测速和回放共用。 +//! 发出一个会产生费用的请求之前的报价。推理测速和回放共用。 //! -//! **四种计费方式各说各的**,而都要给出 token 数 —— 那是唯一一个我们确定 -//! 知道的量。 +//! **四种计费方式的金额各不相同**:订阅制和计费方式未知的没有金额,不计费 +//! 的是 0。怎么向用户说明由界面按计费方式决定,token 数由调用方一起给出 +//! —— 那是唯一一个确定知道的量。 use tw_config::Billing; @@ -11,9 +12,6 @@ pub struct Quote { /// 未知、无法计价时是空** —— 不是 0 pub cost_micros: Option, pub billing: Billing, - /// 给人看的那一句。**金额再小也要显示** —— 用户按下按钮时有权知道自己在 - /// 花什么 - pub note: String, } /// 这家上游跑这个模型、用这么多 token,报一个价。 @@ -24,31 +22,18 @@ pub fn quote( usage: &tw_pricing::Usage, billing: Billing, ) -> Quote { - let tokens = usage.input + usage.output; - let (cost_micros, note) = match billing { - // **订阅制不是免费**:它不按 token 收钱,消耗的是额度 - Billing::Subscription => (None, format!("计入订阅额度,约 {tokens} tokens")), - Billing::Free => (Some(0), format!("不计费,约 {tokens} tokens")), - Billing::Unknown => ( - None, - format!("计费方式未知,无法预估费用,约 {tokens} tokens"), - ), + let cost_micros = match billing { + // **订阅制不是免费**:它不按 token 收费,消耗的是额度 + Billing::Subscription | Billing::Unknown => None, + Billing::Free => Some(0), Billing::PerToken => match book.cost_for(provider, model, usage, false) { - tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => { - // 五位小数:一次测速是几百微分的量级,两位小数会显示成 - // $0.00,而那等于告诉用户「这不花钱」 - (Some(m), format!("约 ${:.5}", m as f64 / 1e6)) - } - tw_pricing::Cost::Unpriced { .. } => ( - None, - format!("无法计价:`{model}` 不在价目表中,约 {tokens} tokens"), - ), + tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => Some(m), + tw_pricing::Cost::Unpriced { .. } => None, }, }; Quote { cost_micros, billing, - note, } } @@ -85,27 +70,16 @@ mod tests { } #[test] - fn each_billing_mode_says_what_it_costs_and_how_many_tokens() { + fn each_billing_mode_has_its_own_amount() { let q = |b| quote(&book(), "p", "claude-sonnet-4-5", &usage(), b); let per_token = q(Billing::PerToken); assert!(per_token.cost_micros.unwrap() > 0); - assert!( - per_token.note.starts_with("约 $0.000"), - "{}", - per_token.note - ); let sub = q(Billing::Subscription); assert_eq!(sub.cost_micros, None); - assert!( - sub.note.contains("额度") && sub.note.contains("18"), - "{}", - sub.note - ); let free = q(Billing::Free); assert_eq!(free.cost_micros, Some(0)); let unknown = q(Billing::Unknown); assert_eq!(unknown.cost_micros, None); - assert!(unknown.note.contains("18"), "{}", unknown.note); let unpriced = quote( &book(), "p", @@ -114,7 +88,6 @@ mod tests { Billing::PerToken, ); assert_eq!(unpriced.cost_micros, None); - assert!(unpriced.note.contains("无法计价"), "{}", unpriced.note); } #[test] diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 9633d9cf..f222370b 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -1060,10 +1060,10 @@ async fn pipeline( state.bus.emit(tw_api::Event::LocallyAnswered { id, client: client_name.clone(), - probe: kind.label().to_string(), + probe: kind.slug().to_string(), at_ms: now_ms(), }); - tracing::debug!(client = %client_name, kind = kind.label(), "本地应答"); + tracing::debug!(client = %client_name, kind = kind.slug(), "本地应答"); return Ok(local_answer(kind, &body)); } // `route` 交给规则处理:打一个标记让 `when: { intent: ... }` @@ -1367,9 +1367,9 @@ async fn pipeline( items: ledger .counts .iter() - .map(|(k, what, n)| tw_api::RedactedItem { + .map(|(k, secret, n)| tw_api::RedactedItem { kind: k.slug().to_string(), - what: what.to_string(), + secret: secret.to_string(), count: *n as u64, }) .collect(), @@ -1392,7 +1392,11 @@ async fn pipeline( &provider.name, state.health.record_failure(&provider.name), ); - chain.push(hop(&provider.name, format!("凭据取不到:{e}"), hop_started)); + chain.push(hop_failed( + &provider.name, + format!("无法取得凭据:{e}"), + hop_started, + )); last_err = Some(GatewayError::config(format!( "provider `{}` 的凭据取不到:{e}", provider.name @@ -1453,7 +1457,12 @@ async fn pipeline( &provider.name, state.health.record_failure(&provider.name), ); - chain.push(hop(&provider.name, format!("{}", r.status()), hop_started)); + chain.push(hop( + &provider.name, + "status", + r.status().as_u16(), + hop_started, + )); // **429 要保住 429。**塌成 502 的话,客户端会当成「服务器 // 坏了」而不是「该退避了」,而它们该做的事完全不同。 last_err = Some(if r.status() == 429 { @@ -1470,7 +1479,12 @@ async fn pipeline( &provider.name, state.health.record_success(&provider.name), ); - chain.push(hop(&provider.name, "成功".to_string(), hop_started)); + chain.push(hop( + &provider.name, + "served", + r.status().as_u16(), + hop_started, + )); upstream = Some(r); used = Some(provider); used_ledger = ledger; @@ -1485,7 +1499,7 @@ async fn pipeline( state.health.record_failure(&provider.name), ); let err = forward::map_reqwest_error(e); - chain.push(hop(&provider.name, err.message.clone(), hop_started)); + chain.push(hop_failed(&provider.name, err.message.clone(), hop_started)); last_err = Some(err); continue; } @@ -1562,7 +1576,7 @@ async fn pipeline( .windows .iter() .map(|w| tw_api::QuotaWindow { - label: w.label.clone(), + window: w.window.clone(), used_percent: w.used_percent, reset_in_secs: w.reset_in_secs, status: w.status.clone(), @@ -1897,10 +1911,29 @@ async fn serve_once( .await } -fn hop(provider: &str, outcome: String, started: std::time::Instant) -> tw_api::AttemptView { +/// 上游回了话的一跳:`served` 或者 `status`。 +fn hop( + provider: &str, + outcome: &str, + status: u16, + started: std::time::Instant, +) -> tw_api::AttemptView { + tw_api::AttemptView { + provider: provider.to_string(), + outcome: outcome.to_string(), + status: Some(status), + error: None, + ms: started.elapsed().as_millis() as u64, + } +} + +/// 没有收到响应的一跳。 +fn hop_failed(provider: &str, error: String, started: std::time::Instant) -> tw_api::AttemptView { tw_api::AttemptView { provider: provider.to_string(), - outcome, + outcome: "error".to_string(), + status: None, + error: Some(error), ms: started.elapsed().as_millis() as u64, } } diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index fd3ae335..5b8ac827 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -266,9 +266,9 @@ async fn pump( .ledger .counts .iter() - .map(|(k, what, n)| tw_api::RedactedItem { + .map(|(k, secret, n)| tw_api::RedactedItem { kind: k.slug().to_string(), - what: what.to_string(), + secret: secret.to_string(), count: *n as u64, }) .collect(), diff --git a/crates/tw-gateway/tests/l1_real.rs b/crates/tw-gateway/tests/l1_real.rs index e957083c..6a506ca3 100644 --- a/crates/tw-gateway/tests/l1_real.rs +++ b/crates/tw-gateway/tests/l1_real.rs @@ -1,11 +1,16 @@ +use tw_gateway::{L1Result, Step}; + +fn steps(r: &L1Result) -> Vec { + r.segments.iter().map(|s| s.stage.step).collect() +} + #[tokio::test] #[ignore = "打真实网络,手动跑:cargo test -p tw-gateway --test l1_real -- --ignored --nocapture"] async fn a_real_https_endpoint_completes_all_three_segments() { let r = tw_gateway::l1("https://api.anthropic.com", None).await; println!("{r:#?}"); assert!(r.ok, "{r:?}"); - let names: Vec<_> = r.segments.iter().map(|s| s.name.as_str()).collect(); - assert_eq!(names, ["DNS 解析", "TCP 握手", "TLS 握手"]); + assert_eq!(steps(&r), [Step::Dns, Step::Tcp, Step::Tls]); } #[tokio::test] @@ -15,9 +20,7 @@ async fn an_expired_certificate_fails_at_tls_not_at_tcp() { let r = tw_gateway::l1("https://expired.badssl.com", None).await; println!("{r:#?}"); assert!(!r.ok); - let e = r.error.unwrap(); - assert!(e.starts_with("TLS 握手:"), "{e}"); + assert_eq!(r.failed.map(|s| s.step), Some(Step::Tls), "{r:?}"); // TCP 是通的 —— 段列表要能证明这一点 - let names: Vec<_> = r.segments.iter().map(|s| s.name.as_str()).collect(); - assert_eq!(names, ["DNS 解析", "TCP 握手"]); + assert_eq!(steps(&r), [Step::Dns, Step::Tcp]); } diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 2b7fc574..778bd76b 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -1411,7 +1411,7 @@ async fn intercepting_a_probe_emits_its_own_event_not_a_request_pair() { .expect("2 秒内没等到事件") .unwrap(); match ev { - tw_api::Event::LocallyAnswered { probe, .. } => assert_eq!(probe, "连通性检查"), + tw_api::Event::LocallyAnswered { probe, .. } => assert_eq!(probe, "health_check"), other => panic!("该是本地应答,实际 {other:?}"), } // 后面不该再跟着一对 started/finished @@ -2003,7 +2003,7 @@ async fn a_key_pasted_into_a_prompt_is_noticed_but_the_request_goes_through_unto } } let (secret, masked, provider) = found.expect("请求体里有 key,却没有发现"); - assert_eq!(secret, "Anthropic API key"); + assert_eq!(secret, "anthropic-api-key"); assert_eq!(provider, "中转", "得知道发给了谁 —— 那才是这条防线的意义"); // 报出来的东西一律打码:「发现了 sk-ant-xxx」本身就是一次泄漏 assert!(!masked.contains("abcdefghijklmnop"), "{masked}"); @@ -2124,11 +2124,13 @@ async fn the_attempt_chain_records_every_hop_and_why_each_one_failed() { assert_eq!(group.as_deref(), Some("全部")); assert_eq!(attempts.len(), 3, "{attempts:?}"); assert_eq!(attempts[0].provider, "挂了的"); - assert!(attempts[0].outcome.contains("503"), "{:?}", attempts[0]); + assert_eq!(attempts[0].outcome, "status", "{:?}", attempts[0]); + assert_eq!(attempts[0].status, Some(503), "{:?}", attempts[0]); assert_eq!(attempts[1].provider, "限流的"); - assert!(attempts[1].outcome.contains("429"), "{:?}", attempts[1]); + assert_eq!(attempts[1].status, Some(429), "{:?}", attempts[1]); assert_eq!(attempts[2].provider, "好的"); - assert_eq!(attempts[2].outcome, "成功"); + assert_eq!(attempts[2].outcome, "served"); + assert_eq!(attempts[2].status, Some(200)); } #[tokio::test] @@ -2160,7 +2162,7 @@ async fn a_request_that_succeeds_first_try_still_has_a_chain_of_one() { tokio::time::timeout(Duration::from_secs(2), rx.recv()).await { assert_eq!(attempts.len(), 1); - assert_eq!(attempts[0].outcome, "成功"); + assert_eq!(attempts[0].outcome, "served"); return; } } @@ -2196,7 +2198,8 @@ async fn a_request_that_fails_everywhere_still_reports_the_chain() { tokio::time::timeout(Duration::from_secs(2), rx.recv()).await { assert_eq!(attempts.len(), 1); - assert!(attempts[0].outcome.contains("503"), "{:?}", attempts[0]); + assert_eq!(attempts[0].outcome, "status", "{:?}", attempts[0]); + assert_eq!(attempts[0].status, Some(503), "{:?}", attempts[0]); return; } } diff --git a/crates/tw-gateway/tests/replay.rs b/crates/tw-gateway/tests/replay.rs index 1c20b637..b33019aa 100644 --- a/crates/tw-gateway/tests/replay.rs +++ b/crates/tw-gateway/tests/replay.rs @@ -56,7 +56,7 @@ fn no_fixture_carries_a_credential() { let real: Vec<_> = hits .iter() .filter(|h| h.kind != tw_redact::rules::Kind::Internal) - .map(|h| format!("{}({})", h.what, &dump[h.bytes.clone()])) + .map(|h| format!("{}({})", h.secret, &dump[h.bytes.clone()])) .collect(); assert!(real.is_empty(), "{name} 里有凭据:{real:?}"); } diff --git a/crates/tw-redact/src/redact.rs b/crates/tw-redact/src/redact.rs index 06b1110c..b8e66561 100644 --- a/crates/tw-redact/src/redact.rs +++ b/crates/tw-redact/src/redact.rs @@ -42,14 +42,14 @@ impl Ledger { pub fn table(&self) -> &HashMap { &self.back } - fn note(&mut self, kind: Kind, what: &'static str) { + fn note(&mut self, kind: Kind, secret: &'static str) { match self .counts .iter_mut() - .find(|(k, w, _)| *k == kind && *w == what) + .find(|(k, w, _)| *k == kind && *w == secret) { Some((_, _, n)) => *n += 1, - None => self.counts.push((kind, what, 1)), + None => self.counts.push((kind, secret, 1)), } } } @@ -100,7 +100,7 @@ pub fn apply_into(text: &str, hits: &[Hit], mut ledger: Ledger) -> Redacted { p } }; - ledger.note(h.kind, h.what); + ledger.note(h.kind, h.secret); out.replace_range(h.bytes.clone(), &ph); } ledger.counts.sort_by_key(|(k, w, _)| (*k, *w)); @@ -213,8 +213,8 @@ mod tests { let t = format!("{KEY} 和 10.0.0.1 和 10.0.0.2"); let r = redact(&t, &all()); let summary = format!("{:?}", r.ledger.counts); - assert!(summary.contains("Anthropic API key"), "{summary}"); - assert!(summary.contains("内网地址"), "{summary}"); + assert!(summary.contains("anthropic-api-key"), "{summary}"); + assert!(summary.contains("internal-ip"), "{summary}"); assert!( !summary.contains("sk-ant-api03-AAAA"), "计数里带出了原值:{summary}" diff --git a/crates/tw-redact/src/rules.rs b/crates/tw-redact/src/rules.rs index dca4d58b..4322e96f 100644 --- a/crates/tw-redact/src/rules.rs +++ b/crates/tw-redact/src/rules.rs @@ -66,8 +66,12 @@ pub struct Hit { pub kind: Kind, /// 在原文里的字节区间 pub bytes: Range, - /// 「Anthropic API key」这类人话 - pub what: &'static str, + /// 具体是哪种凭据:`anthropic-api-key` / `private-key` / `jwt` … + /// + /// **给的是 slug,不是名称。**界面拿它查自己的名称表;以前这里是 + /// 「Anthropic API key」「连接串里的口令」这样的显示文字,一路原样进了 + /// 事件、数据库和界面。 + pub secret: &'static str, } // ---------------------------------------------------------------- API 密钥 @@ -77,27 +81,27 @@ pub struct Hit { /// **只收前缀明确的。**代码里的 hash、base64 的图片、UUID 全都长得像 /// 「一长串随机字符」,按那个判据匹配会疯狂误报。 const PREFIXED: &[(&str, &str, usize)] = &[ - // (前缀, 人话, 前缀之后至少还要有多少个字符) - ("sk-ant-", "Anthropic API key", 20), - ("sk-proj-", "OpenAI project key", 20), - ("ghp_", "GitHub personal token", 30), - ("gho_", "GitHub OAuth token", 30), - ("ghs_", "GitHub server token", 30), - ("ghu_", "GitHub user token", 30), - ("github_pat_", "GitHub fine-grained token", 30), - ("xoxb-", "Slack bot token", 20), - ("xoxp-", "Slack user token", 20), - ("xoxa-", "Slack app token", 20), - ("AKIA", "AWS access key id", 12), - ("ASIA", "AWS temporary key id", 12), - ("AIza", "Google API key", 30), - ("ya29.", "Google OAuth token", 20), - ("glpat-", "GitLab token", 15), - ("sk_live_", "Stripe live key", 20), - ("rk_live_", "Stripe restricted key", 20), - ("npm_", "npm token", 30), - ("dop_v1_", "DigitalOcean token", 30), - ("SG.", "SendGrid key", 30), + // (前缀, 哪种凭据, 前缀之后至少还要有多少个字符) + ("sk-ant-", "anthropic-api-key", 20), + ("sk-proj-", "openai-project-key", 20), + ("ghp_", "github-personal-token", 30), + ("gho_", "github-oauth-token", 30), + ("ghs_", "github-server-token", 30), + ("ghu_", "github-user-token", 30), + ("github_pat_", "github-fine-grained-token", 30), + ("xoxb-", "slack-bot-token", 20), + ("xoxp-", "slack-user-token", 20), + ("xoxa-", "slack-app-token", 20), + ("AKIA", "aws-access-key-id", 12), + ("ASIA", "aws-temporary-key-id", 12), + ("AIza", "google-api-key", 30), + ("ya29.", "google-oauth-token", 20), + ("glpat-", "gitlab-token", 15), + ("sk_live_", "stripe-live-key", 20), + ("rk_live_", "stripe-restricted-key", 20), + ("npm_", "npm-token", 30), + ("dop_v1_", "digitalocean-token", 30), + ("SG.", "sendgrid-key", 30), ]; /// `sk-` 开头的 OpenAI 老式 key。 @@ -110,11 +114,11 @@ fn is_tok(c: char) -> bool { } fn classify_token(tok: &str) -> Option<&'static str> { - for (prefix, what, min_tail) in PREFIXED { + for (prefix, secret, min_tail) in PREFIXED { if let Some(tail) = tok.strip_prefix(prefix) && tail.len() >= *min_tail { - return Some(what); + return Some(secret); } } if let Some(tail) = tok.strip_prefix("sk-") @@ -127,7 +131,7 @@ fn classify_token(tok: &str) -> Option<&'static str> { && tail.chars().any(|c| c.is_ascii_digit()) && tail.chars().any(|c| c.is_ascii_alphabetic()) { - return Some("OpenAI API key"); + return Some("openai-api-key"); } None } @@ -194,7 +198,7 @@ fn private_keys(text: &str, out: &mut Vec) { out.push(Hit { kind: Kind::PrivateKeys, bytes: begin..end, - what: "私钥", + secret: "private-key", }); from = end; } @@ -265,7 +269,7 @@ fn conn_strings(text: &str, out: &mut Vec) { out.push(Hit { kind: Kind::ConnStrings, bytes: c + 1..j, - what: "连接串里的口令", + secret: "conn-string-password", }); } from = after; @@ -301,14 +305,14 @@ fn is_rfc1918(tok: &str) -> bool { /// 本身藏起来了。何况我们的网关自己就住在那儿。 fn internal_token(tok: &str) -> Option<&'static str> { if is_rfc1918(tok) { - return Some("内网地址"); + return Some("internal-ip"); } let lower = tok.to_ascii_lowercase(); if (lower.ends_with(".local") || lower.ends_with(".internal") || lower.ends_with(".lan")) && lower.len() > 7 && lower.contains('.') { - return Some("内部域名"); + return Some("internal-domain"); } None } @@ -332,11 +336,11 @@ pub fn scan(text: &str, kinds: &[Kind]) -> Vec { let want_int = kinds.contains(&Kind::Internal); if want_api || want_jwt || want_int { for_each_token(text, |tok, span| { - if want_api && let Some(what) = classify_token(tok) { + if want_api && let Some(secret) = classify_token(tok) { out.push(Hit { kind: Kind::ApiKeys, bytes: span, - what, + secret, }); return; } @@ -344,15 +348,15 @@ pub fn scan(text: &str, kinds: &[Kind]) -> Vec { out.push(Hit { kind: Kind::Jwt, bytes: span, - what: "JWT", + secret: "jwt", }); return; } - if want_int && let Some(what) = internal_token(tok) { + if want_int && let Some(secret) = internal_token(tok) { out.push(Hit { kind: Kind::Internal, bytes: span, - what, + secret, }); } }); diff --git a/crates/tw-scan/src/rules.rs b/crates/tw-scan/src/rules.rs index 170b29ab..511f9948 100644 --- a/crates/tw-scan/src/rules.rs +++ b/crates/tw-scan/src/rules.rs @@ -86,18 +86,24 @@ pub struct Rules { } impl Rules { - /// 一句给界面看的话:现在到底有多少条在生效。 + /// 其中用户自己加的有几条。 /// - /// 这句话是「加法加停用」能成立的前提 —— 用户不必抄一份规则集, - /// 也能知道自己这台机器上跑的是什么。 + /// 「现在到底有多少条在生效、几条是加的、停用了几条」是「加法加停用」 + /// 能成立的前提 —— 用户不必抄一份规则集,也能知道自己这台机器上跑的 + /// 是什么。界面拿这三个数自己说。 + pub fn custom(&self) -> usize { + self.rules.iter().filter(|r| r.custom).count() + } + + /// 命令行里的那一句。 pub fn summary(&self) -> String { - let custom = self.rules.iter().filter(|r| r.custom).count(); - let mut s = format!("{} 条生效", self.rules.len()); + let custom = self.custom(); + let mut s = format!("生效 {} 条", self.rules.len()); if custom > 0 { - s.push_str(&format!("(其中 {custom} 条是你加的)")); + s.push_str(&format!(",其中自定义 {custom} 条")); } if !self.disabled.is_empty() { - s.push_str(&format!(",停用了 {} 条内置", self.disabled.len())); + s.push_str(&format!(",已停用内置规则 {} 条", self.disabled.len())); } s } @@ -434,9 +440,11 @@ mod tests { disable: vec!["chmod-777".into()], }) .unwrap(); + assert_eq!(rs.custom(), 1); + assert_eq!(rs.disabled.len(), 1); let s = rs.summary(); - assert!(s.contains("1 条是你加的"), "{s}"); - assert!(s.contains("停用了 1 条"), "{s}"); + assert!(s.contains("其中自定义 1 条"), "{s}"); + assert!(s.contains("已停用内置规则 1 条"), "{s}"); // injection 组的规则永远不切断 assert!(!rs.rules.iter().find(|x| x.id == "我的").unwrap().high); } diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 61100eb4..6aa60646 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -1122,6 +1122,7 @@ pub struct Leak { pub at_ms: i64, pub request_id: i64, pub provider: String, + /// 哪种凭据的 slug(`anthropic-api-key` …)。列名沿用 `kind` pub kind: String, /// **已打码。**存原文等于把泄漏搬了个家 pub masked: String, diff --git a/crates/tw-store/src/disk.rs b/crates/tw-store/src/disk.rs index 8a86c9cc..da463b88 100644 --- a/crates/tw-store/src/disk.rs +++ b/crates/tw-store/src/disk.rs @@ -34,11 +34,21 @@ impl DiskLevel { pub fn writes_anything(&self) -> bool { !matches!(self, DiskLevel::Nothing) } + /// 控制面发给界面的值。**界面按它判断、按它取自己的文案**,不拿 + /// 显示文字去比较。 + pub fn slug(&self) -> &'static str { + match self { + DiskLevel::Ok => "ok", + DiskLevel::MetadataOnly => "metadata_only", + DiskLevel::Nothing => "stopped", + } + } + /// 诊断包和日志里的说法。 pub fn label(&self) -> &'static str { match self { DiskLevel::Ok => "正常", - DiskLevel::MetadataOnly => "磁盘快满了,只记摘要不存请求体", - DiskLevel::Nothing => "磁盘几乎满了,已停止记录(转发不受影响)", + DiskLevel::MetadataOnly => "磁盘空间不足,仅记录请求摘要,不保存请求体与响应体", + DiskLevel::Nothing => "磁盘空间严重不足,已停止记录,转发不受影响", } } } @@ -99,6 +109,7 @@ mod tests { // 哪天有人往 DiskLevel 上加一个「停止转发」,它会立刻响。 for l in [DiskLevel::Ok, DiskLevel::MetadataOnly, DiskLevel::Nothing] { assert!(l.label().len() > 1, "每一级都要有一句给人看的话"); + assert!(!l.slug().is_empty()); } assert!( DiskLevel::Nothing.label().contains("转发不受影响"), diff --git a/crates/tw-store/src/drift.rs b/crates/tw-store/src/drift.rs index 58a079e8..1b2d72dc 100644 --- a/crates/tw-store/src/drift.rs +++ b/crates/tw-store/src/drift.rs @@ -28,9 +28,9 @@ const MIN_SAMPLE: i64 = 20; /// 一处变化。 #[derive(Debug, Clone, PartialEq)] pub struct Drift { - /// `tool_calls` / `flagged` / `errors` + /// `flagged`(命中高危规则的响应)/ `tool_calls`(带工具调用的响应)/ + /// `errors`(失败的请求) pub metric: &'static str, - pub label: &'static str, pub recent: f64, pub baseline: f64, /// 两边各自的样本量。**必须一起显示** —— 没有它,比率是个没法判断 @@ -62,7 +62,6 @@ pub fn compare(recent: &Shape, base: &Shape) -> Vec { if recent.with_flags > 0 && (b == 0.0 || jumped(r, b)) { out.push(Drift { metric: "flagged", - label: "命中危险规则的响应", recent: r, baseline: b, recent_n: recent.inspected, @@ -79,7 +78,6 @@ pub fn compare(recent: &Shape, base: &Shape) -> Vec { if jumped(r, b) { out.push(Drift { metric: "tool_calls", - label: "带工具调用的响应", recent: r, baseline: b, recent_n: recent.inspected, @@ -98,7 +96,6 @@ pub fn compare(recent: &Shape, base: &Shape) -> Vec { if jumped(r, b) { out.push(Drift { metric: "errors", - label: "失败的请求", recent: r, baseline: b, recent_n: recent.total, diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 7c48192f..afcb429f 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -232,11 +232,11 @@ impl Recorder { // 那一跳的延迟算给超时的那一家 —— 两个数字都指向错的 // 上游,而且没有任何东西会提示它们错了。 // - // 判据是「链的最后一跳」,不是按 outcome 的字符串匹配 - // 「成功」:转移在第一次成功时就 break,所以最后一跳 + // 判据是「链的最后一跳」,不是看哪一跳的 outcome 是 + // `served`:转移在第一次成功时就 break,所以最后一跳 // 要么是服务的那家,要么是放弃前试的最后一家。两种都 - // 是这一行该归的对象,而这条性质是结构性的 —— 改了 - // outcome 的措辞不会让它失效。 + // 是这一行该归的对象,而这条性质是结构性的,不依赖 + // outcome 的取值。 if let Some(last) = attempts.last() { p.provider = last.provider.clone(); } @@ -657,12 +657,16 @@ mod tests { attempts: vec![ tw_api::AttemptView { provider: "官方".into(), - outcome: "上游超时".into(), + outcome: "error".into(), + status: None, + error: Some("上游响应超时".into()), ms: 10_003, }, tw_api::AttemptView { provider: "中转".into(), - outcome: "成功".into(), + outcome: "served".into(), + status: Some(200), + error: None, ms: 5_042, }, ], @@ -681,7 +685,8 @@ mod tests { serde_json::from_str(row.routing.as_deref().unwrap()).unwrap(); assert_eq!(routing.attempts.len(), 2); assert_eq!(routing.attempts[0].provider, "官方"); - assert_eq!(routing.attempts[0].outcome, "上游超时"); + assert_eq!(routing.attempts[0].outcome, "error"); + assert_eq!(routing.attempts[0].error.as_deref(), Some("上游响应超时")); } /// 一次就成的请求不该被这条规则改坏:链长度为 1,最后一跳就是它自己。 @@ -695,7 +700,9 @@ mod tests { group: None, attempts: vec![tw_api::AttemptView { provider: "官方".into(), - outcome: "成功".into(), + outcome: "served".into(), + status: Some(200), + error: None, ms: 300, }], billing: "per-token".into(), @@ -964,7 +971,9 @@ mod billing_tests { group: None, attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), - outcome: "成功".into(), + outcome: "served".into(), + status: Some(200), + error: None, ms: 5, }], billing: billing.into(), @@ -1134,13 +1143,13 @@ mod redaction_tests { provider: "relay".into(), items: vec![ tw_api::RedactedItem { - kind: "api_key".into(), - what: "sk-…".into(), + kind: "api-keys".into(), + secret: "anthropic-api-key".into(), count: 2, }, tw_api::RedactedItem { - kind: "token".into(), - what: "ghp_…".into(), + kind: "api-keys".into(), + secret: "github-personal-token".into(), count: 1, }, ], From bc9057253fb97a95d2d352e4c0863bc553a0c1ef Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 20:16:33 +0800 Subject: [PATCH 2/2] fix(copy): write every message core shows in a formal register MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The desktop app now follows a written register: statements rather than asides or questions, no first or second person, 费用 for amounts, and no explanations of internal mechanics. Much of what it displays is written here, and read like someone talking: 连不上上游。检查 base_url…, 密钥要你自己在 Zed 的界面里填一次 —— 我们够不着, 补丁自检没过 … 这是个 bug, 请把配置文件贴到 issue 里. The same sentences reach AI clients as gateway errors and people reading the CLI, the logs and the diagnostics bundle. Rewritten: control-plane and gateway errors, configuration validation, link test results, client adoption notes and diagnosis findings, scan findings and the built-in rule reasons, the diagnostics bundle, the notes written into adopted client configs, twcore's output and help text, and logs. Terms follow the app: 上游, 接口地址, 网关密钥, 请求记录, 非官方端点, 按量计费. Names are quoted as 「name」 instead of in backticks, which the UI shows literally. Errors carry no trailing 。, so the UI can place them in a sentence. The adoption file formats stay as they are: the comment block markers and the Chinese keys of `*.thinkwatch.json` are read back on restore, so changing them would strand clients adopted by an earlier version. Only the prose inside them changed. `bin/twcore/tests/copy.rs` reads the string literals in product code and the rule reasons in `rules.yaml`, and fails on the spoken forms the app's `copy.test.ts` rejects plus the ones removed here. The app's test only sees its own `.tsx` files, so without this nothing checks what core sends. Co-Authored-By: Claude Opus 5 --- bin/twcore/src/main.rs | 188 +++++++-------- bin/twcore/tests/copy.rs | 278 +++++++++++++++++++++++ crates/tw-adopt/src/clients.rs | 20 +- crates/tw-adopt/src/detect.rs | 73 +++--- crates/tw-adopt/src/foreign.rs | 16 +- crates/tw-adopt/src/json.rs | 32 +-- crates/tw-adopt/src/mcp.rs | 26 +-- crates/tw-adopt/src/plan.rs | 24 +- crates/tw-adopt/src/sentinel.rs | 18 +- crates/tw-adopt/src/toml.rs | 4 +- crates/tw-adopt/src/yaml.rs | 2 +- crates/tw-adopt/tests/roundtrip.rs | 10 +- crates/tw-config/src/credential.rs | 32 +-- crates/tw-config/src/edit.rs | 12 +- crates/tw-config/src/history.rs | 2 +- crates/tw-config/src/lib.rs | 28 +-- crates/tw-config/src/store.rs | 8 +- crates/tw-config/src/validate.rs | 30 +-- crates/tw-config/src/watch.rs | 2 +- crates/tw-control/src/clients.rs | 11 +- crates/tw-control/src/config.rs | 28 +-- crates/tw-control/src/diagnostics.rs | 46 ++-- crates/tw-control/src/lib.rs | 22 +- crates/tw-control/src/pricing.rs | 28 +-- crates/tw-control/src/replay.rs | 26 +-- crates/tw-control/src/resources.rs | 32 +-- crates/tw-control/src/rotation.rs | 8 +- crates/tw-control/src/scan.rs | 6 +- crates/tw-control/tests/adopt.rs | 14 +- crates/tw-control/tests/resources.rs | 2 +- crates/tw-engine/src/engine.rs | 20 +- crates/tw-engine/src/num.rs | 8 +- crates/tw-engine/src/rule.rs | 2 +- crates/tw-gateway/src/access.rs | 6 +- crates/tw-gateway/src/ending.rs | 4 +- crates/tw-gateway/src/fixture.rs | 8 +- crates/tw-gateway/src/forward.rs | 8 +- crates/tw-gateway/src/l1.rs | 46 ++-- crates/tw-gateway/src/l3.rs | 4 +- crates/tw-gateway/src/latency.rs | 8 +- crates/tw-gateway/src/limits.rs | 4 +- crates/tw-gateway/src/live.rs | 2 +- crates/tw-gateway/src/models.rs | 16 +- crates/tw-gateway/src/oauth.rs | 18 +- crates/tw-gateway/src/probe.rs | 11 +- crates/tw-gateway/src/server.rs | 104 ++++----- crates/tw-gateway/src/toolwall.rs | 6 +- crates/tw-gateway/src/ws.rs | 16 +- crates/tw-gateway/tests/hotreload.rs | 7 +- crates/tw-gateway/tests/m1_acceptance.rs | 2 +- crates/tw-gateway/tests/models.rs | 2 +- crates/tw-gateway/tests/oauth.rs | 2 +- crates/tw-gateway/tests/passthrough.rs | 4 +- crates/tw-pricing/src/lib.rs | 4 +- crates/tw-pricing/src/sheet.rs | 14 +- crates/tw-pricing/src/table.rs | 2 +- crates/tw-redact/src/stream.rs | 3 +- crates/tw-scan/data/rules.yaml | 36 +-- crates/tw-scan/src/hidden.rs | 12 +- crates/tw-scan/src/report.rs | 18 +- crates/tw-scan/src/rules.rs | 6 +- crates/tw-scan/src/sources.rs | 14 +- crates/tw-scan/src/watch.rs | 2 +- crates/tw-scan/tests/scan.rs | 6 +- crates/tw-secret/src/lib.rs | 4 +- crates/tw-store/src/blobs.rs | 2 +- crates/tw-store/src/db.rs | 6 +- crates/tw-store/src/recorder.rs | 8 +- crates/tw-store/src/task.rs | 4 +- crates/tw-yaml/src/edit.rs | 28 +-- crates/tw-yaml/src/lib.rs | 30 +-- crates/tw-yaml/tests/preserve.rs | 2 +- crates/tw-yaml/tests/property.rs | 2 +- 73 files changed, 911 insertions(+), 628 deletions(-) create mode 100644 bin/twcore/tests/copy.rs diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 5babb09a..63949918 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -16,7 +16,7 @@ use lockfile::{LockFile, LockOutcome}; #[derive(Parser)] #[command(name = "twcore", version, about = "ThinkWatch Lite 的本地 AI 网关引擎")] struct Cli { - /// 配置文件路径。默认 ~/.thinkwatch/config.yaml + /// 配置文件路径,默认为 ~/.thinkwatch/config.yaml #[arg(long, global = true)] config: Option, #[command(subcommand)] @@ -25,50 +25,56 @@ struct Cli { #[derive(Subcommand)] enum Command { - /// 起网关 + /// 启动网关 Serve { - /// 覆盖配置里的端口。写 0 让系统挑一个(测试用) + /// 覆盖配置中的端口。设为 0 时由系统分配(用于测试) #[arg(long)] port: Option, - /// 只起控制面,不起数据面。守护连续失败后进这个模式 —— - /// 网关挂了的时候,用户最需要的恰恰是能改配置 + /// 仅启动控制面,不启动数据面 + // + // 守护连续失败后进这个模式 —— 网关挂了的时候,用户最需要的恰恰是 + // 能改配置 #[arg(long)] safe: bool, - /// 父进程 pid。它没了我们跟着退 —— 「让用户认为他俩就是一个程序」 + /// 父进程 pid。父进程退出后本进程随之退出 + // + // 「让用户认为他俩就是一个程序」 #[arg(long)] parent: Option, }, - /// 生成一份初始配置 + /// 生成初始配置 Init { - /// 已存在时也覆盖 + /// 配置文件已存在时仍然覆盖 #[arg(long)] force: bool, }, - /// 校验配置并把结论说清楚 + /// 校验配置并输出结果 Check, - /// 改配置。**和界面走同一套代码** —— 两套实现就是两套行为 + /// 修改配置 + // + // **和界面走同一套代码** —— 两套实现就是两套行为 Config { #[command(subcommand)] what: ConfigCmd, }, - /// 量一条线通不通、每一段花了多久。**零成本**,不发任何业务请求 + /// 测试链路连通性及各阶段耗时。不发送业务请求,不产生费用 Speed { - /// 只测这一家。不写就全测 + /// 只测试该上游。不指定时测试全部上游 provider: Option, - /// 只测某个代理本身 + /// 只测试指定的代理 #[arg(long)] proxy: Option, }, - /// 扫一遍本机的客户端配置面:hooks、MCP、skill、指令文件。**只读** + /// 扫描本机客户端配置面:hooks、MCP、skill 与指令文件。只读取,不修改 Scan { - /// 额外扫一个项目目录。我们不去全盘找项目,只看你指的 + /// 额外扫描的项目目录。不会自动查找项目 #[arg(long)] project: Vec, - /// 连清单一起打印,不只是问题 + /// 同时输出完整清单,而不仅是发现的问题 #[arg(long)] inventory: bool, }, - /// 看看这台机器上有哪些 AI 客户端,以及它们指向哪儿 + /// 列出本机的 AI 客户端及其指向的地址 Clients { #[command(subcommand)] what: ClientsCmd, @@ -77,30 +83,32 @@ enum Command { #[derive(Subcommand)] enum ClientsCmd { - /// 扫一遍。**只读** + /// 扫描本机客户端。只读取,不修改 List, - /// 「我明明配了,为什么没生效」—— 走一遍优先级链 + /// 诊断配置未生效的原因,逐层检查配置的优先级 Why { - /// 客户端 id,比如 claude-code + /// 客户端 id,例如 claude-code client: String, - /// 当前项目目录,用来查项目级配置是不是盖住了用户级 + /// 当前项目目录,用于检查项目级配置是否覆盖了用户级配置 #[arg(long)] project: Option, }, - /// 算一份接管改动**并打印出来**,不落盘 + /// 计算接管改动并输出,不写入文件 Plan { client: String }, } #[derive(Subcommand)] enum ConfigCmd { - /// 打印当前配置的原文和版本号 + /// 输出当前配置的原文和版本号 Show, - /// 改一个字段。路径写成 `/providers/官方/base_url` + /// 修改一个字段,路径写成 /providers/官方/base_url 的形式 Set { - /// **按名字定位,不是下标** —— 下标会在重排之后指向另一个东西 + /// 按名称定位,而不是按下标 + // + // 下标会在重排之后指向另一个东西 path: String, value: String, - /// 明确写成数字而不是字符串。`--int 8788` 和 `8788` 是两回事 + /// 按整数写入,而不是字符串。--int 8788 与 8788 不同 #[arg(long, conflicts_with_all = ["bool_value", "null"])] int: bool, #[arg(long = "bool", conflicts_with_all = ["int", "null"])] @@ -108,9 +116,9 @@ enum ConfigCmd { #[arg(long, conflicts_with_all = ["int", "bool_value"])] null: bool, }, - /// 历史版本 + /// 列出历史版本 History, - /// 回到某一版 + /// 回滚到指定版本 Rollback { version: String }, } @@ -156,7 +164,7 @@ fn cmd_scan(config: &Path, projects: Vec, inventory: bool) -> Result<() for p in &projects { srcs.extend(tw_scan::sources::in_project(p)); } - println!("扫了 {} 份文件(规则 {})", srcs.len(), rules.summary()); + println!("已扫描 {} 个文件(规则:{})", srcs.len(), rules.summary()); let r = tw_scan::report::scan(&srcs, &rules); if inventory { @@ -164,11 +172,11 @@ fn cmd_scan(config: &Path, projects: Vec, inventory: bool) -> Result<() println!("\nMCP server({}):", r.mcp.len()); for m in &r.mcp { let mark = if conflicting.contains(&m.name) { - " ⚠同名不同配置" + " ⚠ 同名但配置不同" } else { "" }; - let off = if m.enabled { "" } else { "(已关闭)" }; + let off = if m.enabled { "" } else { "(已停用)" }; let what = match &m.url { Some(u) => format!("远端 {u}"), None => format!("{} {}", m.command, m.args.join(" ")), @@ -176,7 +184,7 @@ fn cmd_scan(config: &Path, projects: Vec, inventory: bool) -> Result<() println!(" {:<20} {:<14} {what}{off}{mark}", m.name, m.client); if !m.env_keys.is_empty() { println!( - " {:<20} {:<14} 读环境变量 {}", + " {:<20} {:<14} 读取环境变量 {}", "", "", m.env_keys.join("、") @@ -194,14 +202,14 @@ fn cmd_scan(config: &Path, projects: Vec, inventory: bool) -> Result<() } for u in &r.unreadable { - println!("⚠ 读不动:{u}"); + println!("⚠ 无法读取:{u}"); } if r.findings.is_empty() { // 没风险的时候要说「安全」,而不是什么都不显示 - println!("\n✓ 没发现问题。"); + println!("\n✓ 未发现问题。"); return Ok(()); } - println!("\n发现 {} 处:", r.findings.len()); + println!("\n发现 {} 处问题:", r.findings.len()); for f in &r.findings { let mark = match f.level { tw_scan::report::Level::High => "✗ 高危", @@ -213,7 +221,7 @@ fn cmd_scan(config: &Path, projects: Vec, inventory: bool) -> Result<() println!(" {}", f.excerpt.trim()); println!(" {}", f.detail); } - println!("\n只报告,不会替你删任何东西 —— 删不删你自己定。"); + println!("\n扫描只报告问题,不会删除任何内容。"); Ok(()) } @@ -231,19 +239,19 @@ fn cmd_clients(path: &Path, what: ClientsCmd) -> Result<()> { ClientsCmd::List => { for d in detect::detect(&home()) { let state = match (d.installed, d.adopted_at_ms, &d.endpoint) { - (false, _, _) => "没装".to_string(), + (false, _, _) => "未安装".to_string(), (true, Some(at), Some(ep)) => format!("已接管 {} → {ep}", fmt_time(at)), // **「我们写过」和「现在还是那样」是两回事。** (true, Some(at), None) => { - format!("接管过({}),但配置里已经没有我们写的字段了", fmt_time(at)) + format!("曾于 {} 接管,但配置中已不包含接管写入的字段", fmt_time(at)) } - (true, None, Some(ep)) => format!("没接管,自己指向 {ep}"), - (true, None, None) => "装了,没接管".to_string(), + (true, None, Some(ep)) => format!("未接管,当前指向 {ep}"), + (true, None, None) => "已安装,未接管".to_string(), }; println!("{:<14} {:<12} {state}", d.id, d.name); println!(" {}", d.real.display()); if d.real != d.path { - println!(" ({} 是个符号链接)", d.path.display()); + println!(" ({} 是符号链接)", d.path.display()); } for s in &d.shadows { println!(" ⚠ {} 优先级更高", s.display()); @@ -261,7 +269,7 @@ fn cmd_clients(path: &Path, what: ClientsCmd) -> Result<()> { key: None, }; println!(); - println!("接管不了、只能给指引的:"); + println!("不支持自动接管、需要手动配置的客户端:"); for m in manual_only() { println!(" {:<12} {}", m.name, m.how(&gw)); println!(" {}", m.caveat); @@ -272,7 +280,7 @@ fn cmd_clients(path: &Path, what: ClientsCmd) -> Result<()> { let c = adoptable() .into_iter() .find(|c| c.id == client) - .ok_or_else(|| anyhow::anyhow!("没有叫 `{client}` 的客户端"))?; + .ok_or_else(|| anyhow::anyhow!("未知的客户端 {client}"))?; for f in detect::diagnose(&c, &home(), project.as_deref()) { let mark = match f.level { detect::Level::Blocking => "✗", @@ -291,7 +299,7 @@ fn cmd_clients(path: &Path, what: ClientsCmd) -> Result<()> { let c = adoptable() .into_iter() .find(|c| c.id == client) - .ok_or_else(|| anyhow::anyhow!("没有叫 `{client}` 的客户端"))?; + .ok_or_else(|| anyhow::anyhow!("未知的客户端 {client}"))?; let cfg = tw_config::load(path)?; // 0.0.0.0 是监听地址,不是能填进客户端配置的地址 —— 客户端 // 得知道往哪儿连,那永远是 127.0.0.1 @@ -300,17 +308,17 @@ fn cmd_clients(path: &Path, what: ClientsCmd) -> Result<()> { key: None, }; let plan = tw_adopt::plan::plan_adopt(&c, &home(), &gw)?; - println!("要改:{}", plan.path.display()); + println!("将修改:{}", plan.path.display()); if plan.is_noop() { - println!("(已经是这样了,什么都不用改)"); + println!("(配置已是目标状态,无需修改)"); return Ok(()); } for n in &plan.notes { println!(" · {n}"); } - println!("\n--- 改完之后 ---"); + println!("\n--- 修改后 ---"); println!("{}", plan.after); - println!("--- 以上只是算出来的,没有写盘 ---"); + println!("--- 以上为预览,未写入文件 ---"); Ok(()) } } @@ -335,14 +343,14 @@ fn cmd_config(path: &Path, what: ConfigCmd) -> Result<()> { ConfigCmd::History => { let all = tw_config::history::list(path)?; if all.is_empty() { - println!("还没有历史版本。第一次改配置之后就有了。"); + println!("尚无历史版本,首次修改配置后会生成。"); return Ok(()); } let now = tw_config::store::read(path).map(|c| c.version()).ok(); // 新的在前 —— 要找的几乎总是最近那几版 for v in all.iter().rev() { let mark = if Some(&v.version) == now.as_ref() { - "← 现在" + "← 当前" } else { " " }; @@ -355,13 +363,13 @@ fn cmd_config(path: &Path, what: ConfigCmd) -> Result<()> { ); } println!(); - println!("回到某一版:twcore config rollback <版本号>(前几位就够)"); + println!("回滚到指定版本:twcore config rollback <版本号>(输入前几位即可)"); Ok(()) } ConfigCmd::Rollback { version } => { let text = tw_config::history::rollback(path, &version)?; - println!("已回到 {}", tw_config::store::version_of(&text)); - eprintln!("(core 在跑的话,它会在一秒内自己发现)"); + println!("已回滚到 {}", tw_config::store::version_of(&text)); + eprintln!("(core 正在运行时,会在一秒内自动加载)"); Ok(()) } ConfigCmd::Set { @@ -378,13 +386,13 @@ fn cmd_config(path: &Path, what: ConfigCmd) -> Result<()> { tw_yaml::Scalar::Int( value .parse() - .with_context(|| format!("`{value}` 不是一个整数"))?, + .with_context(|| format!("「{value}」不是整数"))?, ) } else if bool_value { tw_yaml::Scalar::Bool( value .parse() - .with_context(|| format!("`{value}` 不是 true 或 false"))?, + .with_context(|| format!("「{value}」不是 true 或 false"))?, ) } else { tw_yaml::Scalar::Str(value) @@ -398,8 +406,8 @@ fn cmd_config(path: &Path, what: ConfigCmd) -> Result<()> { let _ = tw_config::history::snapshot(path, &cur.text, tw_config::history::Origin::Cli); tw_config::store::write_if_unchanged(path, &cur.fingerprint, &next)?; let _ = tw_config::history::snapshot(path, &next, tw_config::history::Origin::Cli); - println!("已改。新版本 {}", tw_config::store::version_of(&next)); - eprintln!("(core 在跑的话,它会在一秒内自己发现)"); + println!("已修改,新版本为 {}", tw_config::store::version_of(&next)); + eprintln!("(core 正在运行时,会在一秒内自动加载)"); Ok(()) } } @@ -421,7 +429,7 @@ fn fmt_time(ms: u64) -> String { /// 握手时间不是任何一条线的真实值,而这一层存在的全部意义就是那几个 /// 数字准不准。 fn cmd_speed(path: &Path, provider: Option, proxy: Option) -> Result<()> { - let cfg = tw_config::load(path).with_context(|| format!("读 {}", path.display()))?; + let cfg = tw_config::load(path).with_context(|| format!("读取 {}", path.display()))?; let rt = tokio::runtime::Runtime::new()?; rt.block_on(async move { if let Some(name) = proxy { @@ -429,12 +437,12 @@ fn cmd_speed(path: &Path, provider: Option, proxy: Option) -> Re .proxies .iter() .find(|x| x.name == name) - .with_context(|| format!("没有叫 `{name}` 的代理"))?; + .with_context(|| format!("未找到名为「{name}」的代理"))?; let hop = tw_gateway::hop_of(px).map_err(anyhow::Error::msg)?; let (host, port) = tw_gateway::proxy_target(&cfg, &px.name); let r = tw_gateway::l1_proxy(&hop, &host, port).await; print_l1( - &format!("代理 {}(经它连 {host}:{port})", px.name), + &format!("代理「{}」(经其连接 {host}:{port})", px.name), None, &r, ); @@ -445,12 +453,12 @@ fn cmd_speed(path: &Path, provider: Option, proxy: Option) -> Re cfg.providers .iter() .find(|p| p.name == *n) - .with_context(|| format!("没有叫 `{n}` 的上游"))?, + .with_context(|| format!("未找到名为「{n}」的上游"))?, ], None => cfg.providers.iter().collect(), }; if targets.is_empty() { - println!("还没有配置任何上游 —— 先往 providers 段里加一个。"); + println!("尚未配置任何上游,请先在 providers 中添加上游。"); return Ok(()); } for p in targets { @@ -476,14 +484,14 @@ fn hop_for( // 跟随系统代理的地址要到建连时才由环境决定,我们没有那份地址 // 可以去握手。说出来,而不是假装直连测一遍给个漂亮数字。 tw_config::SYSTEM => anyhow::bail!( - "走的是系统代理,地址要到建连时才由环境决定 —— L1 测不到它。把代理显式配成一个命名条目就能测。" + "该上游使用系统代理,代理地址在建立连接时才能确定,链路测速无法测量。将代理配置为命名代理后即可测速" ), name => { let px = cfg .proxies .iter() .find(|x| x.name == name) - .with_context(|| format!("proxies 段里没有 `{name}`"))?; + .with_context(|| format!("proxies 中未定义「{name}」"))?; let auth = match &px.auth { None => None, Some(a) => Some((a.user.clone(), a.pass.resolve()?)), @@ -499,7 +507,7 @@ fn hop_for( fn print_l1(target: &str, via: Option<&str>, r: &tw_gateway::L1Result) { let head = match via { - Some(v) => format!("{target}(经 {v})"), + Some(v) => format!("{target}(经由 {v})"), None => target.to_string(), }; println!("{} {}", if r.ok { "✅" } else { "❌" }, head); @@ -507,7 +515,7 @@ fn print_l1(target: &str, via: Option<&str>, r: &tw_gateway::L1Result) { println!(" {:<18} {:>6} ms", seg.stage.label(), seg.ms); } if r.ok { - println!(" {:<18} {:>6} ms", "建连总计", r.total_ms); + println!(" {:<18} {:>6} ms", "建立连接合计", r.total_ms); } if let Some(e) = &r.error { match r.failed { @@ -524,8 +532,8 @@ fn print_l1(target: &str, via: Option<&str>, r: &tw_gateway::L1Result) { fn cmd_init(path: &Path, force: bool) -> Result<()> { if path.exists() && !force { anyhow::bail!( - "{} 已经存在。要重新生成请加 --force —— 但那会覆盖你现在的配置,\n\ - 里面的密钥也会一起没。", + "{} 已存在。如需重新生成,请添加 --force。\n\ + 这会覆盖当前配置,其中的密钥也将丢失", path.display() ); } @@ -535,9 +543,9 @@ fn cmd_init(path: &Path, force: bool) -> Result<()> { println!("已生成 {}", path.display()); println!(); println!("网关密钥:{key}"); - println!("(把它配到客户端上。tw- 前缀是刻意的 —— 一眼看出这不是上游的真 key)"); + println!("(请在客户端中配置该密钥。tw- 前缀用于区分网关密钥与上游的 API 密钥)"); println!(); - println!("下一步:往 providers 段里加第一个上游,然后 twcore serve。"); + println!("下一步:在 providers 中添加上游,然后运行 twcore serve。"); Ok(()) } @@ -550,9 +558,9 @@ fn write_config(path: &Path, cfg: &tw_config::Config) -> Result<()> { fn cmd_check(path: &Path) -> Result<()> { match tw_config::load(path) { Ok(cfg) => { - println!("✅ {} 没问题", path.display()); + println!("✅ {} 校验通过", path.display()); println!( - " {} 个客户端,{} 个上游", + " {} 个网关密钥,{} 个上游", cfg.clients.len(), cfg.providers.len() ); @@ -560,11 +568,11 @@ fn cmd_check(path: &Path) -> Result<()> { let proto = match p.effective_protocol() { Some(x) => format!("{x:?}"), // 猜不出来不是错误,但值得说一句 —— M0 按 Anthropic 走。 - None => "未知(按 Anthropic 转发)".to_string(), + None => "未识别(按 Anthropic 格式转发)".to_string(), }; // 说来源而不是值。 let credential = match (&p.key, &p.oauth) { - (Some(k), _) => format!("密钥 {}({})", k.describe(), p.auth_header().0), + (Some(k), _) => format!("API 密钥 {}({})", k.describe(), p.auth_header().0), (None, Some(_)) => "OAuth".to_string(), (None, None) if !p.headers.is_empty() => "请求头".to_string(), (None, None) => "无凭据".to_string(), @@ -591,7 +599,7 @@ fn cmd_check(path: &Path) -> Result<()> { // 这几样写错了,症状全是网关起来之后一片 401。 if let Some(o) = &p.oauth { if o.refresh.trim().is_empty() { - println!(" ⚠ refresh token 是空的 —— 这家换不出 token"); + println!(" ⚠ refresh token 为空,无法获取 access token"); } // **本机的 http 不算明文过网。**报它是个假警报,而 // 假警报的代价是用户学会忽略这一栏的所有话( @@ -604,7 +612,7 @@ fn cmd_check(path: &Path) -> Result<()> { // refresh token 换得出无数个 access token。 // 它走明文 = 整个凭据走明文 println!( - " ⚠ token 端点不是 https:{} —— refresh token 会明文过网", + " ⚠ token 端点不是 https 地址:{},refresh token 将以明文传输", tw_secret::redact_url(&o.endpoint) ); } @@ -614,12 +622,12 @@ fn cmd_check(path: &Path) -> Result<()> { // 静默走默认值是对的(一个写错的提前量不该让上游 // 整个不可用),但**不说出来就没人会发现自己写错了** println!( - " ⚠ refresh_before: `{raw}` 看不懂(要 `30s`/`5m`/`1h`),按 300 秒算" + " ⚠ refresh_before 的值「{raw}」无法识别(应为 30s、5m、1h 的形式),按 300 秒处理" ); } - println!(" · OAuth 凭据:换 token 要联网,网关起来之后才做"); + println!(" · OAuth 凭据:获取 token 需要联网,将在网关启动后进行"); } else if let Err(e) = p.outbound_headers(None, None) { - println!(" ⚠ 凭据取不到:{e}"); + println!(" ⚠ 无法获取凭据:{e}"); } } Ok(()) @@ -640,9 +648,9 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> LockOutcome::Acquired(l) => l, LockOutcome::AlreadyRunning { pid } => { anyhow::bail!( - "已经有一个 twcore 在跑(pid {pid})。\n\ - 网关端口是固定的,两个实例抢不了同一个 —— 先停掉那个再起。\n\ - 如果那个进程其实已经不在了,删掉 {} 再试。", + "已有 twcore 实例正在运行(pid {pid})。\n\ + 两个实例无法共用同一个网关端口,请先停止该实例。\n\ + 如果该进程实际已退出,请删除 {} 后重试", dir.join("twcore.lock").display() ); } @@ -711,7 +719,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> let _watch = match tw_control::spawn_watcher(manager.clone()) { Ok(w) => Some(w), Err(e) => { - tracing::warn!("盯不住配置文件,手改文件不会自动生效:{e}"); + tracing::warn!("无法监听配置文件,手动修改的配置不会自动生效:{e}"); None } }; @@ -740,7 +748,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> let _scan_watch = match tw_control::scan::spawn_watcher(control.clone()) { Ok(w) => Some(w), Err(e) => { - tracing::warn!("盯不住客户端配置面,变更时不会告警:{e}"); + tracing::warn!("无法监控客户端配置面,发生变更时不会告警:{e}"); None } }; @@ -771,7 +779,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> loop { tokio::time::sleep(std::time::Duration::from_secs(2)).await; if !parent_alive(ppid) { - tracing::info!(ppid, "父进程没了,跟着退"); + tracing::info!(ppid, "父进程已退出,随之退出"); std::process::exit(0); } } @@ -781,10 +789,10 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> if safe { // 安全模式:只起控制面。数据面不动,让用户还能改配置、回滚。 // **这时候控制面就是全部** —— 它没了,这个进程一件事都干不了。 - tracing::warn!("安全模式:只起控制面,数据面不启动"); + tracing::warn!("安全模式:仅启动控制面,不启动数据面"); tokio::select! { msg = control_dead => { - anyhow::bail!("{}", msg.unwrap_or_else(|_| "控制面没了".into())) + anyhow::bail!("{}", msg.unwrap_or_else(|_| "控制面已停止".into())) } _ = shutdown_signal() => {} } @@ -804,10 +812,10 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> tw_gateway::serve_following_config(state, addr).await } } => { - r.with_context(|| format!("监听 {addr} 失败。端口被占用的话,先看看是不是上一个实例没退干净。")) + r.with_context(|| format!("监听 {addr} 失败。如果端口被占用,请检查上一个实例是否已完全退出")) } msg = control_dead => { - anyhow::bail!("{}", msg.unwrap_or_else(|_| "控制面没了".into())) + anyhow::bail!("{}", msg.unwrap_or_else(|_| "控制面已停止".into())) } _ = shutdown_signal() => { tracing::info!("收到退出信号"); @@ -835,7 +843,7 @@ fn build_store( let db = match tw_store::Db::open(&dir.join("data.db")) { Ok(db) => db, Err(e) => { - tracing::warn!("请求历史起不来,这次不记录(转发不受影响):{e}"); + tracing::warn!("请求记录无法启动,本次运行不记录请求,转发不受影响:{e}"); return None; } }; diff --git a/bin/twcore/tests/copy.rs b/bin/twcore/tests/copy.rs new file mode 100644 index 00000000..56930bed --- /dev/null +++ b/bin/twcore/tests/copy.rs @@ -0,0 +1,278 @@ +//! 产品代码里给人看的文字是书面语。 +//! +//! 错误、提示、诊断结论、日志、命令行输出,最后都会被人读到:界面把 +//! 控制面返回的句子原样显示,AI 客户端把网关的错误打印在终端里。桌面端 +//! 的文案规则是书面语、不用第一和第二人称、不解释内部机制,它自己的 +//! `copy.test.ts` 只查得到界面代码 —— core 发过去的句子由这里查。 +//! +//! 查的是**字符串字面量**,不是注释:注释是写给读代码的人的,不受这条 +//! 规则管。测试代码也不查,那里的中文是假装用户写的内容。 + +use std::path::{Path, PathBuf}; + +/// 桌面端 `copy.test.ts` 拒绝的说法,加上 core 里出现过的那些。 +const SPOKEN: &[&str] = &[ + // 桌面端同一份清单 + "就好", + "就行", + "怎么", + "哪家", + "哪儿", + "啥", + "扫一眼", + "攒着", + "别的设备", + "这么多秒", + "条子", + "亏钱", + "回本", + "送上去", + "白跑", + "花钱", + "随便点", + "稍等", + "要是", + "马上", + "多半", + "还没", + "没法", + "看看", + "接下来", + "为什么", + "连不上", + "起不来", + "读不动", + "写好了", + "什么都不用", + "拿到", + "删掉", + "发出去", + "换回来", + "在听", + "只看", + "只计到", + "那一刻", + "一分钱", + "一字节", + "打码", + "这家", + "那家", + "一家", + "每家", + "知道了", + "吗?", + // 人称 + "你", + "您", + "我们", + // 同一个概念只有一个叫法 + "关掉", + "测一下", + "算账", + "花费", + "成本", + // 开发流程的词 + "仓库", + "编译", + "调试", + "堆栈", + // core 里改掉过的说法 + "读不懂", + "读不通", + "读不了", + "写不了", + "取不到", + "盯不住", + "不认识", + "对不上", + "那把", + "这把", + "——", + "**", +]; + +/// 不是给人读的句子,而是存盘格式的一部分。 +/// +/// 接管时写在客户端配置旁边的 `*.thinkwatch.json` 用这几个中文键,还原时 +/// 按键名读回来。改掉它们,已经接管的客户端就还原不了。 +const FORMAT: &[&str] = &["怎么手动还原", "文件是我们建的"]; + +fn workspace() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn rust_files(dir: &Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + rust_files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } +} + +/// 一段源码里的字符串字面量,连同所在行。**跳过注释和字符字面量**, +/// 原始字符串(`r#"…"#`)按原样取。 +fn literals(src: &str) -> Vec<(usize, String)> { + let c: Vec = src.chars().collect(); + let mut out = Vec::new(); + let (mut i, mut line) = (0, 1); + let ident = |ch: char| ch.is_alphanumeric() || ch == '_'; + while i < c.len() { + match c[i] { + '\n' => { + line += 1; + i += 1; + } + '/' if c.get(i + 1) == Some(&'/') => { + while i < c.len() && c[i] != '\n' { + i += 1; + } + } + '/' if c.get(i + 1) == Some(&'*') => { + let mut depth = 0; + while i < c.len() { + if c[i] == '/' && c.get(i + 1) == Some(&'*') { + depth += 1; + i += 2; + } else if c[i] == '*' && c.get(i + 1) == Some(&'/') { + depth -= 1; + i += 2; + if depth == 0 { + break; + } + } else { + if c[i] == '\n' { + line += 1; + } + i += 1; + } + } + } + '\'' => { + // 字符字面量('x'、'\n'、'中')整个跳过;否则是生命周期 + if c.get(i + 1) == Some(&'\\') { + i += 2; + while i < c.len() && c[i] != '\'' { + i += 1; + } + i += 1; + } else if c.get(i + 2) == Some(&'\'') { + i += 3; + } else { + i += 1; + } + } + 'r' if (i == 0 || !ident(c[i - 1])) + && matches!(c.get(i + 1), Some('"') | Some('#')) => + { + let mut j = i + 1; + let mut hashes = 0; + while c.get(j) == Some(&'#') { + hashes += 1; + j += 1; + } + if c.get(j) != Some(&'"') { + i += 1; + continue; + } + let start = j + 1; + let mut k = start; + let end = loop { + if k >= c.len() { + break c.len(); + } + if c[k] == '"' && (1..=hashes).all(|h| c.get(k + h) == Some(&'#')) { + break k; + } + k += 1; + }; + let lit: String = c[start..end].iter().collect(); + out.push((line, lit.clone())); + line += lit.matches('\n').count(); + i = end + 1 + hashes; + } + '"' => { + let start = i + 1; + let mut k = start; + while k < c.len() && c[k] != '"' { + k += if c[k] == '\\' { 2 } else { 1 }; + } + let end = k.min(c.len()); + let lit: String = c[start..end].iter().collect(); + out.push((line, lit.clone())); + line += lit.matches('\n').count(); + i = end + 1; + } + _ => i += 1, + } + } + out +} + +#[test] +fn product_text_is_written_not_spoken() { + let root = workspace(); + let mut files = Vec::new(); + rust_files(&root.join("crates"), &mut files); + rust_files(&root.join("bin"), &mut files); + files.sort(); + + let mut found = Vec::new(); + for f in &files { + let rel = f.strip_prefix(&root).unwrap_or(f).display().to_string(); + // 集成测试和这个文件自己都不查 + if rel.contains("/tests/") { + continue; + } + let src = std::fs::read_to_string(f).unwrap(); + // 看的是产品代码那一半(测试模块在文件末尾) + let product = src.split("#[cfg(test)]").next().unwrap(); + for (line, lit) in literals(product) { + // SQL 语句里的注释不是给人读的文字 + if FORMAT.contains(&lit.as_str()) || lit.contains("CREATE TABLE") { + continue; + } + for w in SPOKEN.iter().filter(|w| lit.contains(**w)) { + found.push(format!("{rel}:{line} 「{w}」 {lit}")); + } + } + } + + // 内置扫描规则的说明会原样出现在发现和工具调用告警里 + let rules = root.join("crates/tw-scan/data/rules.yaml"); + for (n, l) in std::fs::read_to_string(&rules).unwrap().lines().enumerate() { + let Some(why) = l.trim().strip_prefix("why:") else { + continue; + }; + for w in SPOKEN.iter().filter(|w| why.contains(**w)) { + found.push(format!( + "crates/tw-scan/data/rules.yaml:{} 「{w}」 {why}", + n + 1 + )); + } + } + + assert!( + found.is_empty(), + "这些文字用了口语或人称:\n{}", + found.join("\n") + ); +} + +#[test] +fn the_literal_reader_skips_comments_and_keeps_strings() { + let src = r####" +// "你好" 在注释里 +let a = "上游响应超时"; /* "我们" */ +let b = r#"原始 "字符串""#; +let c = '中'; +fn f<'a>(x: &'a str) {} +"####; + let got: Vec = literals(src).into_iter().map(|(_, s)| s).collect(); + assert_eq!(got, ["上游响应超时", "原始 \"字符串\""]); +} diff --git a/crates/tw-adopt/src/clients.rs b/crates/tw-adopt/src/clients.rs index e645b775..ea456152 100644 --- a/crates/tw-adopt/src/clients.rs +++ b/crates/tw-adopt/src/clients.rs @@ -48,7 +48,7 @@ impl TakesEffect { pub fn note(&self) -> &'static str { match self { TakesEffect::Immediately => "下一个请求即使用新配置。", - TakesEffect::OnRestart => "重新打开终端后生效,在此之前网关收不到该客户端的请求。", + TakesEffect::OnRestart => "重新打开终端后生效,在此之前网关不会收到该客户端的请求。", } } /// 该不该设「还没收到请求」的超时提示。 @@ -189,9 +189,9 @@ pub fn adoptable() -> Vec { // **`settings.local.json` 优先级更高。**cc-switch #6828 栽在这里 shadowed_by: &[".claude/settings.local.json"], costs: &[ - "Remote Control 和语音输入会被禁用 —— 只要 base URL 不是官方域名就会。", - "MCP tool search 默认关闭。", - "它可能会弹一次自己的欢迎页,点掉就行。", + "接口地址不是官方域名时,Remote Control 和语音输入不可用。", + "MCP tool search 将默认关闭。", + "Claude Code 可能会显示一次欢迎页,关闭即可。", ], verified: Verified::FieldsOnly, marker: &[".claude"], @@ -216,8 +216,8 @@ pub fn adoptable() -> Vec { // 所以它不构成遮蔽 —— 但它确实存在,值得在诊断里提一句 shadowed_by: &[], costs: &[ - "它不问我们要模型列表,所以自定义模型名对它无效 —— 那个清单来自本地的模型目录文件。", - "改完要关掉终端重开。", + "Codex CLI 不从网关获取模型列表,自定义模型名无效,模型列表以本地的模型目录文件为准。", + "修改后需要重新打开终端。", ], verified: Verified::Measured, marker: &[".codex"], @@ -232,7 +232,7 @@ pub fn adoptable() -> Vec { format: Format::Json, takes_effect: TakesEffect::OnRestart, shadowed_by: &[], - costs: &["改完要重开。"], + costs: &["修改后需要重新启动 opencode。"], verified: Verified::FieldsOnly, marker: &[".config/opencode", ".local/share/opencode"], process: &["opencode"], @@ -248,7 +248,7 @@ pub fn adoptable() -> Vec { shadowed_by: &[], // **只算部分接管**:Zed 的密钥走它自己的凭据存储,不在 // settings.json 里,我们写不进去。 - costs: &["密钥要你自己在 Zed 的界面里填一次 —— 它不放在配置文件里,我们够不着。"], + costs: &["Zed 的密钥不保存在配置文件中,需要在 Zed 的设置界面中手动填写一次。"], verified: Verified::FieldsOnly, marker: &[".config/zed"], process: &["Zed"], @@ -265,8 +265,8 @@ pub fn adoptable() -> Vec { // 我们只写 home 那一份,所以项目里的会盖住它 shadowed_by: &[], costs: &[ - "它按 home → 仓库根 → 当前目录的顺序找配置,后面的会盖住前面的 —— 我们只写 home 那一份。", - "改完要重开。", + "Aider 依次读取主目录、Git 项目根目录和当前目录中的配置,后读取的会覆盖先读取的,接管只修改主目录中的配置。", + "修改后需要重新启动 Aider。", ], verified: Verified::FieldsOnly, // 没接管过的用户本来就没有这个文件,所以它自己就是那个痕迹 diff --git a/crates/tw-adopt/src/detect.rs b/crates/tw-adopt/src/detect.rs index d80efb90..7b2043df 100644 --- a/crates/tw-adopt/src/detect.rs +++ b/crates/tw-adopt/src/detect.rs @@ -237,34 +237,34 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec if started.is_empty() { out.push(Finding { level: Level::Clear, - title: format!("{} 现在没在跑", c.name), - detail: "下次启动时它会读到新配置。".into(), + title: format!("{} 当前未运行", c.name), + detail: "下次启动时将读取新配置。".into(), fix: None, }); } else if !stale.is_empty() { out.push(Finding { level: Level::Blocking, - title: format!("{} 的进程比我们改配置的时间还早", c.name), + title: format!("{} 的进程启动于接管之前", c.name), detail: format!( - "有 {} 个进程是在接管之前启动的,它们读的还是旧配置。{}", + "有 {} 个进程在接管之前启动,仍在使用旧配置。{}", stale.len(), c.takes_effect.note() ), - fix: Some(format!("关掉 {} 再打开", c.name)), + fix: Some(format!("退出 {} 后重新打开", c.name)), }); } else { out.push(Finding { level: Level::Clear, - title: format!("{} 是接管之后启动的", c.name), - detail: "它读到的是新配置。".into(), + title: format!("{} 在接管之后启动", c.name), + detail: "已读取新配置。".into(), fix: None, }); } } None => out.push(Finding { level: Level::Suspect, - title: "还没有接管过它".into(), - detail: format!("{} 上没有我们留下的接管记录。", d.real.display()), + title: "尚未接管该客户端".into(), + detail: format!("{} 中没有接管记录。", d.real.display()), fix: None, }), } @@ -273,9 +273,9 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec if d.shadows.is_empty() { out.push(Finding { level: Level::Clear, - title: "没有优先级更高的文件盖住它".into(), + title: "没有优先级更高的配置文件".into(), detail: if c.shadowed_by.is_empty() { - "这个客户端没有这类文件。".into() + "该客户端没有优先级更高的配置文件。".into() } else { format!("{} 不存在。", c.shadowed_by.join("、")) }, @@ -291,19 +291,19 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec } else { Level::Blocking }, - title: format!("{} 的优先级比我们写的那份高", s.display()), + title: format!("{} 的优先级高于接管写入的配置", s.display()), detail: if hits.is_empty() { - "它存在,但里面没有我们关心的字段。".into() + "该文件存在,但不包含相关字段。".into() } else { format!( - "它里面有 {} —— 会盖掉我们写的。", + "该文件中包含 {},会覆盖接管写入的设置。", hits.iter() .map(|s| s.to_string()) .collect::>() .join("、") ) }, - fix: Some(format!("打开 {} 看看那几行", s.display())), + fix: Some(format!("检查 {} 中的相关字段", s.display())), }); } } @@ -314,9 +314,9 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec if local.exists() { out.push(Finding { level: Level::Suspect, - title: "这个项目里有一份同名配置".into(), - detail: format!("{} 会覆盖用户级的那份。", local.display()), - fix: Some(format!("打开 {local:?} 看看")), + title: "当前项目中有同名配置文件".into(), + detail: format!("{} 会覆盖用户级配置。", local.display()), + fix: Some(format!("检查 {}", local.display())), }); } } @@ -332,15 +332,15 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec } else { Level::Blocking }, - title: "这台机器上有管理策略文件".into(), - detail: format!("{MANAGED} 的优先级压过一切,包括你自己的配置。"), + title: "本机存在管理策略文件".into(), + detail: format!("{MANAGED} 的优先级高于其他所有配置,包括用户配置。"), fix: None, }); } else { out.push(Finding { level: Level::Clear, - title: "没有管理策略文件".into(), - detail: "这台机器上没有会压过一切的那份。".into(), + title: "本机没有管理策略文件".into(), + detail: "不存在优先级高于其他所有配置的管理策略文件。".into(), fix: None, }); } @@ -351,8 +351,8 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec if exports.is_empty() { out.push(Finding { level: Level::Clear, - title: "shell 配置里没有同名的环境变量".into(), - detail: "扫过了 .zshrc / .zprofile / .bashrc 这些。".into(), + title: "shell 配置中没有同名环境变量".into(), + detail: "已检查 .zshrc、.zprofile、.bashrc 等文件。".into(), fix: None, }); } else { @@ -363,14 +363,14 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec ( Level::Suspect, format!( - "这不影响 {}(它的配置文件优先级更高),但会影响读环境变量的其他客户端。", + "不影响 {}(其配置文件优先级更高),但会影响读取环境变量的其他客户端。", c.name ), ) } else { ( Level::Blocking, - format!("{} 读环境变量,这一行会盖掉我们写的配置。", c.name), + format!("{} 读取环境变量,该行会覆盖接管写入的配置。", c.name), ) }; out.push(Finding { @@ -378,7 +378,7 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec title: format!("{} 第 {line} 行导出了 {name}", f.display()), detail, // 命令给出来,执行与否是他的事 - fix: Some(format!("要移除的话:sed -i '' '{line}d' {}", f.display())), + fix: Some(format!("sed -i '' '{line}d' {}", f.display())), }); } } @@ -387,17 +387,17 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec match (&d.adopted_at_ms, &d.endpoint) { (Some(_), None) => out.push(Finding { level: Level::Blocking, - title: "我们写的字段已经不在配置里了".into(), + title: "接管写入的字段已不在配置中".into(), detail: format!( - "{} 里找不到我们写的端点 —— 被别的工具改回去了。", + "{} 中未找到接管写入的接口地址,可能已被其他工具修改。", d.real.display() ), - fix: Some("重新接管一次".into()), + fix: Some("重新接管该客户端".into()), }), (Some(_), Some(ep)) => out.push(Finding { level: Level::Clear, - title: "配置里的端点还是我们写的".into(), - detail: format!("现在指向 {ep}。"), + title: "配置中的接口地址与接管时一致".into(), + detail: format!("当前指向 {ep}。"), fix: None, }), _ => {} @@ -407,10 +407,9 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec // 绿色的「查过了没问题」会让人以为已经确认过。 out.push(Finding { level: Level::Suspect, - title: "以上都是静态检查".into(), - detail: - "优先级链有五层,静态检查证明不了「真的生效了」。唯一可靠的验证是等一个真实请求过来。" - .into(), + title: "以上均为静态检查".into(), + detail: "静态检查无法确认配置已实际生效。收到该客户端的真实请求后,才能确认接管已生效。" + .into(), fix: None, }); out @@ -506,7 +505,7 @@ mod tests { let d = tempfile::tempdir().unwrap(); let out = diagnose(&c("claude-code"), d.path(), None); assert!( - out.iter().any(|f| f.detail.contains("等一个真实请求")), + out.iter().any(|f| f.detail.contains("真实请求")), "结论里没留下这句话:{out:?}" ); } diff --git a/crates/tw-adopt/src/foreign.rs b/crates/tw-adopt/src/foreign.rs index 9e2426ef..a2243388 100644 --- a/crates/tw-adopt/src/foreign.rs +++ b/crates/tw-adopt/src/foreign.rs @@ -25,23 +25,23 @@ use thiserror::Error; #[derive(Debug, Error)] pub enum ForeignError { - #[error("读不了 {path}:{source}")] + #[error("无法读取 {path}:{source}")] Read { path: PathBuf, source: std::io::Error, }, - #[error("写不了 {path}:{source}")] + #[error("无法写入 {path}:{source}")] Write { path: PathBuf, source: std::io::Error, }, - #[error("{path} 在你确认之后又被改过了 —— 没有写入,请重新看一遍改动")] + #[error("{path} 在确认之后又被修改,未写入。请重新查看改动")] ChangedUnderUs { path: PathBuf }, - #[error("改完之后的内容自己校验不过,已经放弃写入({0})")] + #[error("修改后的内容未通过校验,未写入({0})")] VerifyFailed(String), - #[error("写完读回来和预期不一致,已经从备份还原:{path}")] + #[error("写入后读回的内容与预期不一致,已从备份还原:{path}")] Readback { path: PathBuf }, - #[error("符号链接绕了太多层:{path}")] + #[error("符号链接层级过多:{path}")] LinkLoop { path: PathBuf }, } @@ -240,7 +240,7 @@ pub fn apply( // 的是 ~/dotfiles/claude/settings.json —— 那是个会被 git 提交 // 的地方,而我们正要往里放一个密钥。 warnings.push(format!( - "{} 是一个符号链接,实际写入的是 {}。", + "{} 是符号链接,实际写入的文件为 {}。", ch.path.display(), real.display() )); @@ -277,7 +277,7 @@ pub fn apply( && m & 0o077 != 0 { warnings.push(format!( - "{} 的权限是 {:o},同机器上的其他用户能读到刚写进去的密钥。要收紧的话:chmod 600 {}", + "{} 的权限为 {:o},本机其他用户可以读取写入的密钥。可执行 chmod 600 {} 收紧权限。", real.display(), m, real.display() diff --git a/crates/tw-adopt/src/json.rs b/crates/tw-adopt/src/json.rs index ac76adf9..d36d976f 100644 --- a/crates/tw-adopt/src/json.rs +++ b/crates/tw-adopt/src/json.rs @@ -23,9 +23,9 @@ use thiserror::Error; pub enum JErr { #[error("第 {at} 个字节处不是合法的 JSON:{msg}")] Syntax { at: usize, msg: String }, - #[error("`{0}` 不是一个对象,没法往里写字段")] + #[error("{0} 不是对象,无法写入字段")] NotObject(String), - #[error("文件是空的")] + #[error("文件为空")] Empty, } @@ -210,7 +210,7 @@ fn err(at: usize, msg: &str) -> JErr { /// 三次,所以这句话必须写下来,不能靠「应该没问题」。 fn scan_str(b: &[u8], i: usize) -> Result<(String, usize), JErr> { if b.get(i) != Some(&b'"') { - return Err(err(i, "这里应该是一个字符串")); + return Err(err(i, "此处应为字符串")); } let mut out = String::new(); let mut j = i + 1; @@ -219,7 +219,7 @@ fn scan_str(b: &[u8], i: usize) -> Result<(String, usize), JErr> { b'"' => return Ok((out, j + 1)), b'\\' => { j += 1; - let c = *b.get(j).ok_or_else(|| err(j, "转义没写完"))?; + let c = *b.get(j).ok_or_else(|| err(j, "转义序列不完整"))?; j += 1; match c { b'"' => out.push('"'), @@ -232,10 +232,10 @@ fn scan_str(b: &[u8], i: usize) -> Result<(String, usize), JErr> { b't' => out.push('\t'), b'u' => { let hex = |b: &[u8], p: usize| -> Result { - let s = b.get(p..p + 4).ok_or_else(|| err(p, "\\u 后面不足四位"))?; + let s = b.get(p..p + 4).ok_or_else(|| err(p, "\\u 后不足四位"))?; let s = std::str::from_utf8(s) - .map_err(|_| err(p, "\\u 后面不是十六进制"))?; - u32::from_str_radix(s, 16).map_err(|_| err(p, "\\u 后面不是十六进制")) + .map_err(|_| err(p, "\\u 后不是十六进制数字"))?; + u32::from_str_radix(s, 16).map_err(|_| err(p, "\\u 后不是十六进制数字")) }; let hi = hex(b, j)?; j += 4; @@ -256,7 +256,7 @@ fn scan_str(b: &[u8], i: usize) -> Result<(String, usize), JErr> { }; out.push(ch); } - _ => return Err(err(j - 1, "不认识的转义")), + _ => return Err(err(j - 1, "无法识别的转义序列")), } } _ => { @@ -270,12 +270,12 @@ fn scan_str(b: &[u8], i: usize) -> Result<(String, usize), JErr> { } } } - Err(err(i, "字符串没有收尾的引号")) + Err(err(i, "字符串缺少结束引号")) } fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { let i = skip_ws(b, i); - let c = *b.get(i).ok_or_else(|| err(i, "这里应该有一个值"))?; + let c = *b.get(i).ok_or_else(|| err(i, "此处缺少值"))?; match c { b'{' => { let mut j = skip_ws(b, i + 1); @@ -294,7 +294,7 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { let kstart = j; let c = skip_ws(b, after_key); if b.get(c) != Some(&b':') { - return Err(err(c, "键后面应该是冒号")); + return Err(err(c, "键之后应为冒号")); } let (val, after_val) = parse_value(b, c + 1)?; ms.push(Member { @@ -316,7 +316,7 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { j + 1, )); } - return Err(err(j, "对象里缺一个逗号或者右花括号")); + return Err(err(j, "对象中缺少逗号或右花括号")); } } b'[' => { @@ -348,7 +348,7 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { j + 1, )); } - return Err(err(j, "数组里缺一个逗号或者右方括号")); + return Err(err(j, "数组中缺少逗号或右方括号")); } } b'"' => { @@ -377,9 +377,9 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { "true" => Body::Bool(true), "false" => Body::Bool(false), "null" => Body::Null, - "" => return Err(err(i, "这里应该有一个值")), + "" => return Err(err(i, "此处缺少值")), n if n.parse::().is_ok() => Body::Num(n.to_string()), - other => return Err(err(start, &format!("不认识的字面量 `{other}`"))), + other => return Err(err(start, &format!("无法识别的字面量 {other}"))), }; Ok(( Node { @@ -400,7 +400,7 @@ fn parse(text: &str) -> Result { let (n, after) = parse_value(b, 0)?; let rest = skip_ws(b, after); if rest < b.len() { - return Err(err(rest, "文件末尾还有多出来的东西")); + return Err(err(rest, "文件末尾有多余内容")); } Ok(n) } diff --git a/crates/tw-adopt/src/mcp.rs b/crates/tw-adopt/src/mcp.rs index 155f8fe3..859ed9f7 100644 --- a/crates/tw-adopt/src/mcp.rs +++ b/crates/tw-adopt/src/mcp.rs @@ -16,15 +16,15 @@ use crate::json::Val; #[derive(Debug, thiserror::Error)] pub enum McpError { - #[error("不认识的客户端 `{0}`")] + #[error("未知的客户端 {0}")] UnknownClient(String), - #[error("{client} 的 MCP 配置解析不了,没有动它:{msg}")] + #[error("无法解析 {client} 的 MCP 配置,未做任何修改:{msg}")] Parse { client: String, msg: String }, #[error("{0}")] Write(#[from] ForeignError), - #[error("{client} 里没有叫 `{name}` 的 MCP server")] + #[error("{client} 中没有名为「{name}」的 MCP server")] NotThere { client: String, name: String }, - #[error("{client} 的 MCP 配置格式我们没有验证过,不往里写({why})")] + #[error("{client} 的 MCP 配置格式未经验证,不支持写入({why})")] NotCopyable { client: String, why: String }, } @@ -98,7 +98,7 @@ pub fn targets() -> Vec { format: Format::Json, key: "mcp", copyable: false, - why_not: "它的 MCP 段格式我们没有实际样本,照着猜写进去可能生成一份它读不懂的配置", + why_not: "该客户端的 MCP 配置格式尚未验证,写入可能导致客户端无法读取配置", }, Target { client: "zed", @@ -107,7 +107,7 @@ pub fn targets() -> Vec { format: Format::Json, key: "context_servers", copyable: false, - why_not: "Zed 的 context server 用的是另一套结构,不是 command/args 那一套", + why_not: "Zed 的 context server 使用不同的配置结构,不支持 command/args 形式", }, ] } @@ -146,7 +146,7 @@ fn semantic(t: &Target, text: &str) -> Result { match t.format { Format::Json => crate::json::value(text).map_err(|e| parse_err(t.client, e)), Format::Toml => crate::toml::value(text).map_err(|e| parse_err(t.client, e)), - Format::Yaml => Err(parse_err(t.client, "MCP 不走 YAML")), + Format::Yaml => Err(parse_err(t.client, "MCP 配置不使用 YAML 格式")), } } @@ -154,7 +154,7 @@ fn put(t: &Target, text: &str, path: &[&str], v: &Val) -> Result crate::json::set(text, path, v).map_err(|e| parse_err(t.client, e)), Format::Toml => crate::toml::set(text, path, v).map_err(|e| parse_err(t.client, e)), - Format::Yaml => Err(parse_err(t.client, "MCP 不走 YAML")), + Format::Yaml => Err(parse_err(t.client, "MCP 配置不使用 YAML 格式")), } } @@ -162,7 +162,7 @@ fn drop_(t: &Target, text: &str, path: &[&str]) -> Result { match t.format { Format::Json => crate::json::remove(text, path).map_err(|e| parse_err(t.client, e)), Format::Toml => crate::toml::remove(text, path).map_err(|e| parse_err(t.client, e)), - Format::Yaml => Err(parse_err(t.client, "MCP 不走 YAML")), + Format::Yaml => Err(parse_err(t.client, "MCP 配置不使用 YAML 格式")), } } @@ -198,7 +198,7 @@ pub fn read_server(t: &Target, home: &Path, name: &str) -> Result } let v = semantic(t, &text)?; let Val::Obj(root) = &v else { - return Err(parse_err(t.client, "根不是一个对象")); + return Err(parse_err(t.client, "根节点不是对象")); }; let servers = root.iter().find(|(k, _)| k == t.key).map(|(_, v)| v); match servers { @@ -295,13 +295,13 @@ pub fn apply(t: &Target, plan: &Plan, backup_root: &Path) -> Result crate::json::value(text).map_err(|e| e.to_string())?, Format::Toml => crate::toml::value(text).map_err(|e| e.to_string())?, - Format::Yaml => return Err("MCP 不走 YAML".into()), + Format::Yaml => return Err("MCP 配置不使用 YAML 格式".into()), }; if strip(&got).normalized() != untouched { - return Err(format!("除了 {key} 之外还有别的东西变了")); + return Err(format!("除 {key} 之外还有其他内容发生了变化")); } if got.normalized() != want.normalized() { - return Err("改完的内容和预期对不上".into()); + return Err("修改后的内容与预期不一致".into()); } Ok(()) }, diff --git a/crates/tw-adopt/src/plan.rs b/crates/tw-adopt/src/plan.rs index 0f3202dd..592e3cb5 100644 --- a/crates/tw-adopt/src/plan.rs +++ b/crates/tw-adopt/src/plan.rs @@ -24,24 +24,24 @@ use crate::sentinel::{self, Original, SidecarRecord, Was}; #[derive(Debug, thiserror::Error)] pub enum PlanError { - #[error("{client} 的配置读不动:{source}")] + #[error("无法读取 {client} 的配置:{source}")] Read { client: String, source: ForeignError, }, - #[error("{client} 的配置解析不了,没有动它:{msg}")] + #[error("无法解析 {client} 的配置,未做任何修改:{msg}")] Parse { client: String, msg: String }, #[error("{0}")] Write(#[from] ForeignError), - #[error("{path} 旁边那份接管记录写的是 `{other}`,不是 `{client}` —— 没有动任何东西")] + #[error("{path} 旁的接管记录属于 {other},不属于 {client},未做任何修改")] ForeignSidecar { path: PathBuf, other: String, client: String, }, - #[error("没有找到 {client} 的接管记录,不知道该还原成什么。手动还原的话看 {path}")] + #[error("未找到 {client} 的接管记录,无法确定还原内容。如需手动还原,请查看 {path}")] NoRecord { client: String, path: PathBuf }, - #[error("{client} 的原值是一个密钥,只在全文备份里;备份 {backup} 已经不在了")] + #[error("{client} 的原值是密钥,仅保存在全文备份中,而备份 {backup} 已不存在")] SecretGone { client: String, backup: PathBuf }, } @@ -220,7 +220,7 @@ pub fn plan_adopt(c: &Client, home: &Path, gw: &Gateway) -> Result Result Result Result Result { after: String::new(), originals: Vec::new(), carries_secret: false, - notes: vec!["这个配置文件已经不在了,只清掉我们留下的接管记录。".into()], + notes: vec!["配置文件已不存在,仅删除接管记录。".into()], shadows: Vec::new(), targets: Vec::new(), drop_sidecar: Some(side), @@ -499,7 +499,7 @@ pub fn plan_restore(c: &Client, home: &Path) -> Result { // 更糟 —— 那等于卸载之后还在替他发着请求。 targets.push(Target::Remove(p.clone())); notes.push(format!( - "{} 原来是一个密钥,它只在全文备份里,而 {} 已经不在了 —— 我们把这个字段删掉了,你需要自己重新填一次。", + "{} 的原值是密钥,仅保存在全文备份中,而 {} 已不存在。该字段已删除,需要手动重新填写。", f.field, backup.display() )); @@ -542,7 +542,7 @@ pub fn plan_restore(c: &Client, home: &Path) -> Result { let delete_file = rec.created_file && matches!(semantic(c.format, &text, c.id)?, Val::Obj(ms) if ms.is_empty()); if delete_file { - notes.push("这个文件当初是接管时新建的,还原后它是空的,所以一并删掉了。".into()); + notes.push("该文件在接管时新建,还原后内容为空,已一并删除。".into()); } notes.insert(0, c.takes_effect.note().to_string()); diff --git a/crates/tw-adopt/src/sentinel.rs b/crates/tw-adopt/src/sentinel.rs index f77feca6..52d33b1a 100644 --- a/crates/tw-adopt/src/sentinel.rs +++ b/crates/tw-adopt/src/sentinel.rs @@ -47,9 +47,9 @@ impl Was { } fn note(&self) -> &'static str { match self { - Was::Missing => "原本没有这个字段,还原时删掉它", - Was::Value(_) => "原本就有值,还原时写回「原值」", - Was::Secret(_) => "原值是密钥,没有抄到这个文件里;去「全文备份」那份文件里取", + Was::Missing => "原配置中没有该字段,还原时删除", + Was::Value(_) => "原配置中已有该字段,还原时写回「原值」", + Was::Secret(_) => "原值是密钥,未写入本文件,请从「全文备份」所指的文件中获取", } } } @@ -95,14 +95,14 @@ pub fn comment_block(prefix: &str, originals: &[Original]) -> String { out.push_str(&format!("{prefix} {BEGIN}\n")); for o in originals { match &o.was { - Was::Missing => out.push_str(&format!("{prefix} 原本没有 {}\n", o.field)), + Was::Missing => out.push_str(&format!("{prefix} 原配置中没有 {}\n", o.field)), Was::Value(v) | Was::Secret(v) => { out.push_str(&format!("{prefix} 原值 {}: {v}\n", o.field)) } } } out.push_str(&format!( - "{prefix} 要手动还原:把上面这些值改回去(原本没有的就删掉),再删掉本段注释\n" + "{prefix} 手动还原方法:将以上字段恢复为原值(原配置中没有的字段直接删除),然后删除本段注释\n" )); out.push_str(&format!("{prefix} {END}\n")); out @@ -203,9 +203,9 @@ impl SidecarRecord { ) -> Self { Self { what: format!( - "ThinkWatch Lite 接管 {client} 时留下的记录。它记着我们改了哪些字段、原来是什么值。" + "ThinkWatch Lite 接管 {client} 时生成的记录,记载了修改过的字段及其原值。" ), - how: "把下面 originals 里的每个字段改回它的「原值」(was 是 missing 表示原本没有这个字段,删掉即可;was 是 secret 表示原值是密钥、请去「全文备份」那份文件里取),然后删掉这个文件。".to_string(), + how: "将 originals 中的每个字段恢复为「原值」(was 为 missing 表示原配置中没有该字段,直接删除即可;was 为 secret 表示原值是密钥,请从「全文备份」所指的文件中获取),然后删除本文件。".to_string(), client: client.to_string(), adopted_at_ms: at_ms, backup: backup.to_string(), @@ -247,7 +247,7 @@ mod tests { // 可能已经在废纸篓里了 —— 那段注释是他唯一的线索。 let b = comment_block("#", &originals()); assert!(b.contains("https://api.anthropic.com"), "原值没写进去:{b}"); - assert!(b.contains("要手动还原"), "没告诉他能做什么:{b}"); + assert!(b.contains("手动还原方法"), "没告诉他能做什么:{b}"); assert!(b.contains(BEGIN) && b.contains(END), "{b}"); } @@ -258,7 +258,7 @@ mod tests { // 的字段。 let b = comment_block("#", &originals()); assert!( - b.contains("原本没有 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"), + b.contains("原配置中没有 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"), "{b}" ); assert!( diff --git a/crates/tw-adopt/src/toml.rs b/crates/tw-adopt/src/toml.rs index 535b021e..61680f19 100644 --- a/crates/tw-adopt/src/toml.rs +++ b/crates/tw-adopt/src/toml.rs @@ -16,7 +16,7 @@ use crate::json::Val; pub enum TErr { #[error("不是合法的 TOML:{0}")] Syntax(String), - #[error("`{0}` 不是一张表,没法往里写字段")] + #[error("{0} 不是表,无法写入字段")] NotTable(String), } @@ -147,7 +147,7 @@ pub fn set(text: &str, path: &[&str], v: &Val) -> Result { let next = item .as_table_like_mut() .and_then(|t| t.get_mut(k)) - .expect("刚插进去的"); + .expect("刚插入的表"); if next.as_table_like().is_none() { return Err(TErr::NotTable(parents[..=i].join("."))); } diff --git a/crates/tw-adopt/src/yaml.rs b/crates/tw-adopt/src/yaml.rs index 9c8c0325..79dbb46c 100644 --- a/crates/tw-adopt/src/yaml.rs +++ b/crates/tw-adopt/src/yaml.rs @@ -16,7 +16,7 @@ use tw_yaml::{PatchError, Scalar, Step}; pub enum YErr { #[error("{0}")] Patch(#[from] PatchError), - #[error("只支持顶层的扁平字段,`{0}` 是嵌套的")] + #[error("仅支持顶层字段,{0} 是嵌套字段")] TooDeep(String), } diff --git a/crates/tw-adopt/tests/roundtrip.rs b/crates/tw-adopt/tests/roundtrip.rs index fdcb42e0..cbe31ca5 100644 --- a/crates/tw-adopt/tests/roundtrip.rs +++ b/crates/tw-adopt/tests/roundtrip.rs @@ -163,7 +163,7 @@ fn losing_the_backup_removes_our_key_and_says_so_out_loud() { let r = plan_restore(&c, &b.home).unwrap(); assert!( - r.notes.iter().any(|n| n.contains("你需要自己重新填一次")), + r.notes.iter().any(|n| n.contains("需要手动重新填写")), "没说清密钥拿不回来了:{:?}", r.notes ); @@ -268,8 +268,8 @@ fn codex_gets_a_sentinel_comment_because_toml_can_hold_one() { apply(&c, &p, &b.backups).unwrap(); let after = read(&b.home.join(".codex/config.toml")); assert!(after.contains(tw_adopt::sentinel::BEGIN), "{after}"); - assert!(after.contains("要手动还原"), "{after}"); - assert!(after.contains("原本没有 model_provider"), "{after}"); + assert!(after.contains("手动还原方法"), "{after}"); + assert!(after.contains("原配置中没有 model_provider"), "{after}"); } #[test] @@ -417,7 +417,7 @@ fn a_restore_without_a_record_refuses_instead_of_guessing() { let b = bed("codex", CODEX); let c = client("codex"); let e = plan_restore(&c, &b.home).unwrap_err(); - assert!(e.to_string().contains("没有找到"), "{e}"); + assert!(e.to_string().contains("未找到"), "{e}"); assert_eq!(read(&b.home.join(".codex/config.toml")), CODEX); } @@ -485,7 +485,7 @@ fn re_adopting_codex_also_keeps_the_first_record() { } let after = read(&b.home.join(".codex/config.toml")); assert!( - after.contains("原本没有 model_provider"), + after.contains("原配置中没有 model_provider"), "哨兵注释记成了我们自己的值:{after}" ); let r = plan_restore(&c, &b.home).unwrap(); diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index c874e3a0..e5a12e92 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -129,7 +129,7 @@ impl<'de> Deserialize<'de> for Secret { // **说清楚该怎么写。**serde 默认只会说「expected a string」,而写错成 // `key: { oauth: ... }` 的人要知道的是 OAuth 放在哪儿 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("一个字符串(可以带 ${VAR})。OAuth 凭据写在上游的 `oauth` 字段里") + f.write_str("字符串(可以包含 ${VAR})。OAuth 凭据应写在上游的 oauth 字段中") } fn visit_str(self, v: &str) -> Result { Ok(Secret(v.to_string())) @@ -217,7 +217,7 @@ impl<'de> Deserialize<'de> for Headers { impl<'de> serde::de::Visitor<'de> for V { type Value = Headers; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("一组「请求头名: 值」") + f.write_str("由「请求头名: 值」组成的映射") } fn visit_map>( self, @@ -252,41 +252,41 @@ pub fn auth_header(protocol: Option) -> (&'static str, &'static str) { /// 凭据写法上的问题。**每一条都指到具体的那一行**,而不是「凭据无效」。 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CredentialError { - #[error("密钥是空的")] + #[error("API 密钥为空")] EmptyKey, - #[error("`key` 和 `oauth` 只能写一个")] + #[error("key 和 oauth 只能填写其中一项")] KeyAndOauth, #[error("oauth 的 refresh 和 endpoint 都不能为空")] EmptyOauth, - #[error("Claude 订阅账号的登录凭据不能接入,请改用 Anthropic API 密钥")] + #[error("不支持接入 Claude 订阅账号的登录凭据,请改用 Anthropic API 密钥")] ClaudeSubscription, - #[error("Gemini CLI 的 Google 登录凭据不能接入,请改用 Gemini API 密钥")] + #[error("不支持接入 Gemini CLI 的 Google 登录凭据,请改用 Gemini API 密钥")] GoogleSubscription, - #[error("请求头最多 {MAX_HEADERS} 个")] + #[error("请求头不能超过 {MAX_HEADERS} 个")] TooManyHeaders, #[error( - "请求头名「{0}」不合法:只能由字母、数字和 - _ . ~ 组成,最长 {MAX_HEADER_NAME} 个字符" + "请求头名「{0}」不合法:只能由字母、数字和 - _ . ~ 组成,长度不超过 {MAX_HEADER_NAME} 个字符" )] BadHeaderName(String), - #[error("请求头「{0}」由网关管理,不能在配置里设置")] + #[error("请求头「{0}」由网关管理,不能在配置中设置")] ReservedHeader(String), - #[error("请求头「{0}」写了两次(请求头名不分大小写)")] + #[error("请求头「{0}」重复(请求头名不区分大小写)")] DuplicateHeader(String), - #[error("请求头「{0}」的值不能包含换行,最长 {MAX_HEADER_VALUE} 个字符")] + #[error("请求头「{0}」的值不能包含换行,长度不超过 {MAX_HEADER_VALUE} 个字符")] BadHeaderValue(String), #[error( - "请求头「{name}」里的 {placeholder} 认不出来。能用的只有 {{{{access_token}}}} 和 {{{{client}}}}" + "请求头「{name}」中的 {placeholder} 无法识别,仅支持 {{{{access_token}}}} 和 {{{{client}}}}" )] UnknownPlaceholder { name: String, placeholder: String }, - #[error("请求头「{0}」用了 {{{{access_token}}}},但这个上游没有配置 oauth")] + #[error("请求头「{0}」使用了 {{{{access_token}}}},但该上游未配置 oauth")] TokenWithoutOauth(String), - #[error("已经写了 `key`,请求头里不能再写「{0}」—— 密钥就是放在这个头里发的")] + #[error("已填写 key,API 密钥将通过请求头「{0}」发送,请求头中不能再设置「{0}」")] KeyAndAuthHeader(String), #[error( - "配置了 oauth 时 token 默认放在「{0}」里。要自己写这个头,请在值里用 {{{{access_token}}}} 指定 token 的位置" + "配置 oauth 后,token 默认通过请求头「{0}」发送。如需自行设置该请求头,请在值中用 {{{{access_token}}}} 标明 token 的位置" )] OauthAndAuthHeader(String), - #[error("取不到 OAuth access token")] + #[error("无法获取 OAuth access token")] NoToken, /// 环境变量没设之类。存成文字:这个错误要能比较,而底下那个类型不能 #[error("{0}")] diff --git a/crates/tw-config/src/edit.rs b/crates/tw-config/src/edit.rs index 54cbe34e..b9f4ffe4 100644 --- a/crates/tw-config/src/edit.rs +++ b/crates/tw-config/src/edit.rs @@ -22,18 +22,18 @@ use tw_yaml::{Put, Step}; #[derive(Debug, thiserror::Error)] pub enum EditError { - #[error("已经有叫「{name}」的{what}了")] + #[error("已存在名为「{name}」的{what}")] NameTaken { what: &'static str, name: String }, - #[error("没有叫「{name}」的{what}")] + #[error("未找到名为「{name}」的{what}")] NotFound { what: &'static str, name: String }, #[error("{0}")] Yaml(#[from] tw_yaml::PatchError), - #[error("配置文件读不通:{0}")] + #[error("配置文件无法解析:{0}")] Parse(String), /// 渲染不出一个能安全写进去的值。 #[error("{0}")] Unwritable(String), - #[error("写完之后读回来和预期不一样:{0}。没有写盘。")] + #[error("修改后的内容与预期不一致({0}),未写入文件")] SelfCheck(String), } @@ -99,7 +99,7 @@ pub fn upsert( let name = item .get("name") .and_then(Value::as_str) - .ok_or_else(|| EditError::Unwritable(format!("{}没有名字", section.what)))? + .ok_or_else(|| EditError::Unwritable(format!("{}缺少名称", section.what)))? .to_string(); let taken = section.index_of(&doc, &name); let steps = section.steps(); @@ -238,7 +238,7 @@ fn render_block(v: &Value) -> Result { fn reject_multiline(v: &Value) -> Result<(), EditError> { match v { Value::String(s) if s.contains('\n') || s.contains('\r') => { - Err(EditError::Unwritable("值里不能有换行".to_string())) + Err(EditError::Unwritable("值中不能包含换行".to_string())) } Value::Mapping(m) => m.iter().try_for_each(|(k, v)| { reject_multiline(k)?; diff --git a/crates/tw-config/src/history.rs b/crates/tw-config/src/history.rs index 0909a70b..613e0a31 100644 --- a/crates/tw-config/src/history.rs +++ b/crates/tw-config/src/history.rs @@ -231,7 +231,7 @@ pub fn read(v: &Version) -> Result { #[derive(Debug, thiserror::Error)] pub enum RollbackError { - #[error("历史里没有 {0} 这一版")] + #[error("版本历史中没有 {0}")] NoSuchVersion(String), #[error(transparent)] Store(#[from] StoreError), diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 7754bf71..f665d9f3 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -309,8 +309,8 @@ impl<'de> Deserialize<'de> for Bind { // 手写配置文件的人什么都没说,而这个字段写错的后果是 // 整份配置加载失败、网关起不来。 serde::de::Error::custom(format!( - "`bind` 只能是 `loopback`、`all`,或者一张网卡的 IP(比如 192.168.1.5)。\ - 收到的是 `{other}`" + "bind 只能是 loopback、all 或某个网卡的 IP 地址(例如 192.168.1.5),\ + 当前值为 {other}" )) }), } @@ -524,8 +524,8 @@ impl Trust { } pub fn label(&self) -> &'static str { match self { - Trust::Official => "官方", - Trust::Untrusted => "不受信任", + Trust::Official => "官方端点", + Trust::Untrusted => "非官方端点", } } /// 命中高危时要不要真的切断。 @@ -560,10 +560,10 @@ pub enum Billing { impl Billing { pub fn label(&self) -> &'static str { match self { - Billing::PerToken => "按量", - Billing::Subscription => "订阅", + Billing::PerToken => "按量计费", + Billing::Subscription => "订阅制", Billing::Free => "不计费", - Billing::Unknown => "未知", + Billing::Unknown => "计费方式未知", } } pub fn slug(&self) -> &'static str { @@ -758,7 +758,7 @@ pub fn patch_oauth_refresh( if !ok { return Err(RotateError::Broke { provider: provider.to_string(), - why: "补丁写完之后读回来,那个字段不是新值".into(), + why: "写入后读回的 refresh token 不是新值".into(), }); } Ok(out) @@ -772,23 +772,23 @@ fn provider_index(text: &str, provider: &str) -> Option { #[derive(Debug, thiserror::Error)] pub enum RotateError { - #[error("配置里没有叫 `{provider}` 的上游了")] + #[error("配置中已不存在上游「{provider}」")] NoProvider { provider: String }, /// **说清「形状不对」而不是「写失败」。**用户可能把凭据写成了 /// 别的形状(锚点、块标量),那时正确的动作是他自己去改, /// 而不是让我们猜。 - #[error("`{provider}` 的 oauth.refresh 不在预期的位置上:{source}")] + #[error("无法定位上游「{provider}」的 oauth.refresh:{source}")] Shape { provider: String, source: tw_yaml::PatchError, }, - #[error("给 `{provider}` 打完补丁之后配置读不回来了,没有写盘:{why}")] + #[error("写入上游「{provider}」的新凭据后配置无法读取,未写入文件:{why}")] Broke { provider: String, why: String }, } #[derive(Debug, thiserror::Error)] pub enum LoadError { - #[error("读 {path} 失败:{source}")] + #[error("无法读取 {path}:{source}")] Io { path: PathBuf, source: std::io::Error, @@ -797,7 +797,7 @@ pub enum LoadError { /// 一份语法完美、只是把 `port` 写成 `prot` 的文件也会到这儿,而那句 /// 话会让用户去找一个根本不存在的语法错误。serde 自己的 /// 「unknown field `prot`, expected one of ...」比我们能补的任何话都准。 - #[error("{path} 读不通:{source}")] + #[error("无法解析 {path}:{source}")] Parse { path: PathBuf, source: serde_yaml_ng::Error, @@ -822,7 +822,7 @@ pub fn load(path: &Path) -> Result { #[derive(Debug, thiserror::Error)] pub enum WriteError { - #[error("写 {path} 失败:{source}")] + #[error("无法写入 {path}:{source}")] Io { path: PathBuf, source: std::io::Error, diff --git a/crates/tw-config/src/store.rs b/crates/tw-config/src/store.rs index 662f2122..539e1471 100644 --- a/crates/tw-config/src/store.rs +++ b/crates/tw-config/src/store.rs @@ -75,16 +75,16 @@ pub fn version_of(text: &str) -> String { #[derive(Debug, thiserror::Error)] pub enum StoreError { - #[error("读 {path} 失败:{source}")] + #[error("无法读取 {path}:{source}")] Io { path: PathBuf, source: std::io::Error, }, - #[error("{path} 还不存在")] + #[error("{path} 不存在")] Missing { path: PathBuf }, /// **有人在我们读到和写下之间改了这个文件。** #[error( - "配置文件在这期间被改过了(现在是 {current},我们看到的是 {expected})。**没有覆盖它。**先看一眼外面改了什么,再决定要不要重来。" + "配置文件在此期间已被修改(当前版本为 {current},本次修改基于 {expected}),未覆盖该文件。请确认最新内容后重试" )] Conflict { expected: String, current: String }, } @@ -267,7 +267,7 @@ mod tests { let m = e.to_string(); assert!(m.contains(&version_of("a: 1\n")[..18]), "{m}"); assert!(m.contains(&version_of("a: 2\n")[..18]), "{m}"); - assert!(m.contains("没有覆盖"), "{m}"); + assert!(m.contains("未覆盖"), "{m}"); } #[test] diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index b0d8f1f1..59c32a28 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -5,28 +5,30 @@ use crate::{Config, SCHEMA_VERSION}; #[derive(Debug, thiserror::Error)] pub enum ValidationError { #[error( - "配置 schema 版本是 {found},这个版本的 twcore 只认到 {supported}。\n请升级应用,或把配置改回旧格式。" + "配置的 schema 版本为 {found},当前版本的 twcore 最高支持 {supported}。请升级应用,或将配置改回旧格式" )] SchemaTooNew { found: u32, supported: u32 }, #[error( - "配置里一个 client 都没有。没有网关密钥的话,任何请求都会被拒绝 —— 首次启动本应自动生成一把。" + "配置中没有任何网关密钥(clients),所有请求都会被拒绝。首次启动时应已自动生成一个网关密钥" )] NoClients, - #[error("provider 名字重复:{0}。名字是路由规则里引用它的方式,必须唯一。")] + #[error("上游名称重复:{0}。路由规则按名称引用上游,名称必须唯一")] DuplicateProvider(String), - #[error("client 名字重复:{0}")] + #[error("网关密钥名称重复:{0}")] DuplicateClient(String), - #[error("两个 client 用了同一把密钥({0} 和 {1})。密钥就是身份,重复等于这两个客户端分不开。")] + #[error("网关密钥「{0}」与「{1}」的值相同。网关按密钥区分客户端,密钥值必须唯一")] DuplicateKey(String, String), - #[error("provider `{name}` 的 base_url 不是 http/https:{url}")] + #[error("上游「{name}」的接口地址不是 http 或 https 地址:{url}")] BadBaseUrl { name: String, url: String }, - #[error("client `{name}` 的密钥是空的")] + #[error("网关密钥「{name}」的值为空")] EmptyKey { name: String }, - #[error("路由配置有问题:{0}")] + #[error("路由配置有误:{0}")] Routing(#[from] tw_engine::RouteError), - #[error("`{0}` 既是 provider 名又是组名。规则里的 `to` 会指向哪个是不确定的,改掉其中一个。")] + #[error( + "「{0}」既是上游名称又是策略组名称,规则中的 to 无法确定指向哪一个,请修改其中一个名称" + )] NameCollision(String), - #[error("listen.gateway.allow_from 里的 `{entry}` 写错了:{reason}")] + #[error("listen.gateway.allow_from 中的「{entry}」有误:{reason}")] BadCidr { entry: String, reason: String }, #[error("上游「{name}」的凭据:{source}")] Credential { @@ -35,13 +37,13 @@ pub enum ValidationError { }, #[error("{0}")] Pricing(#[from] tw_pricing::SheetError), - #[error("上游「{provider}」选的价目表「{sheet}」不存在")] + #[error("上游「{provider}」使用的价目表「{sheet}」不存在")] UnknownPriceSheet { provider: String, sheet: String }, #[error( - "上游「{name}」的启用范围(models_only)是空的,这样它一个模型都不服务。暂时不用这家上游的话,请停用它(disabled: true)" + "上游「{name}」的启用范围(models_only)为空,该上游将不提供任何模型。如需暂停使用该上游,请将其停用(disabled: true)" )] EmptyModelsOnly { name: String }, - #[error("上游「{name}」的启用范围(models_only)里有一项是空的")] + #[error("上游「{name}」的启用范围(models_only)中存在空项")] BlankModelsOnly { name: String }, } @@ -137,7 +139,7 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { let _ = e; return Err(ValidationError::BadCidr { entry: entry.clone(), - reason: "不是合法的 IP 或 CIDR,写法是 `192.168.0.0/16`".to_string(), + reason: "不是合法的 IP 地址或 CIDR,应写成 192.168.0.0/16 的形式".to_string(), }); } } diff --git a/crates/tw-config/src/watch.rs b/crates/tw-config/src/watch.rs index 6149717d..2d06d1d7 100644 --- a/crates/tw-config/src/watch.rs +++ b/crates/tw-config/src/watch.rs @@ -19,7 +19,7 @@ pub const DEBOUNCE: Duration = Duration::from_millis(200); #[derive(Debug, thiserror::Error)] pub enum WatchError { - #[error("盯不住 {path}:{source}")] + #[error("无法监听 {path} 的变化:{source}")] Start { path: PathBuf, source: notify::Error, diff --git a/crates/tw-control/src/clients.rs b/crates/tw-control/src/clients.rs index c4ec0f6e..9ec6e7e0 100644 --- a/crates/tw-control/src/clients.rs +++ b/crates/tw-control/src/clients.rs @@ -20,7 +20,7 @@ fn find(id: &str) -> Result { adoptable() .into_iter() .find(|c| c.id == id) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有叫 `{id}` 的客户端"))) + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未知的客户端 {id}"))) } /// 客户端该连的地址。 @@ -38,14 +38,13 @@ fn gateway_for(s: &ControlState, key_name: Option<&str>) -> Result cfg.clients.iter().find(|c| c.name == n).ok_or_else(|| { ( StatusCode::NOT_FOUND, - format!("config.yaml 里没有叫 `{n}` 的网关密钥"), + format!("config.yaml 中没有名为「{n}」的网关密钥"), ) })?, None => cfg.clients.first().ok_or_else(|| { ( StatusCode::CONFLICT, - "config.yaml 里还没有任何网关密钥 —— 先在配置页加一个,再来接管客户端。" - .to_string(), + "config.yaml 中尚无网关密钥,请先创建网关密钥,再接管客户端".to_string(), ) })?, }; @@ -107,7 +106,7 @@ pub async fn list(State(s): State) -> Result) -> String { match key { @@ -273,7 +272,7 @@ fn mcp_plan(s: &ControlState, req: &tw_api::McpOpRequest) -> Result Err((StatusCode::BAD_REQUEST, format!("不认识的操作 `{other}`"))), + other => Err((StatusCode::BAD_REQUEST, format!("不支持的操作 {other}"))), } } diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 4c5ed37c..0ad26470 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -31,13 +31,13 @@ pub enum ApplyError { #[error("{0}")] Rejected(tw_config::Rejected), /// 校验过了但运行时对象建不起来 —— 同样保持旧的。 - #[error("配置能读,但用不起来:{0}")] + #[error("配置可以解析,但无法应用:{0}")] Build(String), /// patch 指的那个位置有问题。**和 Build 分开**:那句「配置能读但 /// 用不起来」会让人去查配置,而该查的是这次请求写的路径。 #[error("{0}")] BadPath(String), - #[error("版本对不上:你基于 {base},而现在是 {current}。刷新一下再改。")] + #[error("配置版本不一致:本次修改基于 {base},当前版本为 {current}。请刷新后重新修改")] Stale { base: String, current: String }, /// 按资源改(上游、代理、价目表)时的失败:名字撞了、找不到、值写不进去。 #[error(transparent)] @@ -103,7 +103,7 @@ impl ConfigManager { excerpt: r.excerpt.clone(), at_ms: now_ms(), }); - tracing::warn!("配置没通过校验,继续用旧的:{r}"); + tracing::warn!("配置未通过校验,继续使用上一版本:{r}"); ApplyError::Rejected(r) })?; self.gateway @@ -192,7 +192,7 @@ impl ConfigManager { .iter() .rev() .find(|v| v.version == version || v.version.ends_with(version)) - .ok_or_else(|| ApplyError::BadPath(format!("历史里没有 {version} 这一版")))?; + .ok_or_else(|| ApplyError::BadPath(format!("版本历史中没有 {version}")))?; let text = tw_config::history::read(target)?; let cur = self.current().ok(); // 回滚也走同一条写入路径,所以它同样会:校验、存历史、防回环。 @@ -228,10 +228,10 @@ pub fn spawn_watcher( tokio::spawn(async move { while rx.recv().await.is_some() { match mgr.reload_from_disk().await { - Ok(Some(v)) => tracing::debug!(version = %v, "文件被改过,已重载"), - Ok(None) => tracing::trace!("文件事件是我们自己写的,忽略"), + Ok(Some(v)) => tracing::debug!(version = %v, "配置文件已被修改,已重新加载"), + Ok(None) => tracing::trace!("文件变更由本进程写入,忽略"), // 错误已经在 apply_text 里发过事件了,这里只记一行 - Err(e) => tracing::debug!("重载没成功:{e}"), + Err(e) => tracing::debug!("重新加载失败:{e}"), } } }); @@ -321,7 +321,7 @@ pub fn resolve_path(text: &str, pointer: &str) -> Result, Str Some(i) => out.push(tw_yaml::Step::Index(i)), None => { return Err(format!( - "`{pointer}` 里没有叫 `{seg}` 的那一项。列表里的东西按 `name` 找,写下标也行。" + "{pointer} 中没有名为「{seg}」的项。列表项按 name 查找,也可以使用下标" )); } } @@ -368,12 +368,12 @@ impl ConfigManager { // 默认不写的,只能改「用户碰巧写过」的字段,等于表单模式在 // 他最需要的时候是死的。已经写过的走 `set`,那是它的第一步。 tw_yaml::insert(&text, &steps, &scalar) - .map_err(|e| ApplyError::BadPath(format!("改 `{path}` 失败:{e}")))? + .map_err(|e| ApplyError::BadPath(format!("修改 {path} 失败:{e}")))? } tw_api::PatchOp::Append { path, item } => { let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; tw_yaml::append(&text, &steps, item) - .map_err(|e| ApplyError::BadPath(format!("往 `{path}` 加一项失败:{e}")))? + .map_err(|e| ApplyError::BadPath(format!("向 {path} 添加项失败:{e}")))? } tw_api::PatchOp::Remove { path } => { let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; @@ -381,15 +381,15 @@ impl ConfigManager { // **按名字解析、按下标删** —— 名字是用户写的,下标是 // 我们刚刚算出来的,中间没有任何一次用户可见的重排。 let (last, parent) = steps.split_last().ok_or_else(|| { - ApplyError::BadPath(format!("`{path}` 不指向列表里的某一项")) + ApplyError::BadPath(format!("{path} 没有指向列表中的某一项")) })?; let tw_yaml::Step::Index(i) = last else { return Err(ApplyError::BadPath(format!( - "`{path}` 指的不是列表里的一项 —— 删除要指到具体那一条,比如 /clients/codex" + "{path} 没有指向列表中的某一项。删除时需要指定具体的项,例如 /clients/codex" ))); }; tw_yaml::remove(&text, parent, *i) - .map_err(|e| ApplyError::BadPath(format!("删 `{path}` 失败:{e}")))? + .map_err(|e| ApplyError::BadPath(format!("删除 {path} 失败:{e}")))? } tw_api::PatchOp::Clear { path } => { // 要清的列表可能根本还没写进文件 —— 「一个都不给」 @@ -397,7 +397,7 @@ impl ConfigManager { // 对没写过的键会原样留成 Key,走得通。 let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; tw_yaml::clear_seq(&text, &steps) - .map_err(|e| ApplyError::BadPath(format!("清空 `{path}` 失败:{e}")))? + .map_err(|e| ApplyError::BadPath(format!("清空 {path} 失败:{e}")))? } }; } diff --git a/crates/tw-control/src/diagnostics.rs b/crates/tw-control/src/diagnostics.rs index 08437668..6c542165 100644 --- a/crates/tw-control/src/diagnostics.rs +++ b/crates/tw-control/src/diagnostics.rs @@ -35,8 +35,8 @@ pub async fn bundle(State(s): State) -> String { let _ = writeln!(out, "# ThinkWatch 诊断包\n"); let _ = writeln!( out, - "> 这份内容里的密钥、地址、请求正文都已经打码。交出去之前请自己扫一眼 —— \ - **我们是一个看得见所有 API key 的网关**,这一步值得多花十秒。\n" + "> 本文件中的密钥、地址和请求正文均已脱敏。ThinkWatch 作为网关可以接触到所有 API \ + 密钥,发送本文件之前,请再次检查其中是否含有敏感信息。\n" ); // ---- 版本和平台 @@ -51,7 +51,7 @@ pub async fn bundle(State(s): State) -> String { let t = book.table(); let source = match t.source { tw_pricing::TableSource::Builtin => "内置", - tw_pricing::TableSource::Fetched => "联网刷新", + tw_pricing::TableSource::Fetched => "联网更新", tw_pricing::TableSource::Empty => "未加载", }; line( @@ -65,7 +65,7 @@ pub async fn bundle(State(s): State) -> String { line(&mut out, "架构", std::env::consts::ARCH); line( &mut out, - "已运行", + "运行时长", format!("{} 秒", s.started.elapsed().as_secs()), ); @@ -74,7 +74,7 @@ pub async fn bundle(State(s): State) -> String { line( &mut out, "网关", - s.gateway_addr.as_deref().unwrap_or("没起(安全模式)"), + s.gateway_addr.as_deref().unwrap_or("未启动(安全模式)"), ); line(&mut out, "绑定", format!("{:?}", cfg.listen.gateway.bind)); line(&mut out, "端口", cfg.listen.gateway.port); @@ -90,7 +90,7 @@ pub async fn bundle(State(s): State) -> String { // ---- 上游 let _ = writeln!( out, - "\n## 上游({} 个)\n\n| 名字 | 地址 | 协议 | 代理 | 状态 | 模型 | 脱敏 | 信任 | 价目表 |\n|---|---|---|---|---|---|---|---|---|", + "\n## 上游({} 个)\n\n| 名称 | 接口地址 | 协议 | 代理 | 状态 | 模型 | 脱敏 | 信任级别 | 价目表 |\n|---|---|---|---|---|---|---|---|---|", cfg.providers.len() ); for p in &cfg.providers { @@ -102,27 +102,27 @@ pub async fn bundle(State(s): State) -> String { tw_secret::redact_url(&p.base_url), p.effective_protocol() .map(|x| format!("{x:?}")) - .unwrap_or_else(|| "猜不出".into()), + .unwrap_or_else(|| "未识别".into()), p.proxy, if p.disabled { "已停用" } else if s.health().is_available(&p.name) { "正常" } else { - "**熔断中**" + "熔断中" }, { // 「这家为什么收不到某个模型的请求」多半答在这一栏 let l = s.gateway.models.listing(p); let served = s.gateway.catalog.load().count_for(&p.name); let scope = if p.models_only.is_some() { - ",限定范围" + ",已限定启用范围" } else { "" }; match l.source { tw_gateway::models::Source::Discovered => { - format!("{served}(上游列出 {}{scope})", l.models.len()) + format!("{served}(上游提供 {}{scope})", l.models.len()) } tw_gateway::models::Source::Manual => { format!("{served}(手动清单 {}{scope})", l.models.len()) @@ -136,20 +136,20 @@ pub async fn bundle(State(s): State) -> String { { let k = p.effective_redact(); if k.is_empty() { - "不脱".to_string() + "不脱敏".to_string() } else { k.iter().map(|x| x.slug()).collect::>().join(" ") } }, p.effective_trust().label(), - p.pricing.as_deref().unwrap_or("默认"), + p.pricing.as_deref().unwrap_or("默认价目表"), ); } // ---- 客户端条目(**只有名字和脱敏后的 key**) let _ = writeln!( out, - "\n## 网关密钥({} 把)\n\n| 名字 | key |\n|---|---|", + "\n## 网关密钥({} 个)\n\n| 名称 | 密钥 |\n|---|---|", cfg.clients.len() ); for c in &cfg.clients { @@ -159,22 +159,22 @@ pub async fn bundle(State(s): State) -> String { // ---- 安全三态 let _ = writeln!(out, "\n## 安全\n\n| | |\n|---|---|"); line(&mut out, "出站脱敏", cfg.security.redact.label()); - line(&mut out, "入站审查", cfg.security.inspect_tools.label()); - line(&mut out, "配置扫描", cfg.security.scan_configs.label()); + line(&mut out, "工具调用审查", cfg.security.inspect_tools.label()); + line(&mut out, "配置面扫描", cfg.security.scan_configs.label()); // ---- 存储和最近的失败 match &s.store { None => { - let _ = writeln!(out, "\n## 观测\n\n**没有启动。**这段时间的请求没有被记录。"); + let _ = writeln!(out, "\n## 请求记录\n\n未启动,此期间的请求未被记录。"); } Some(store) => { let g = store.lock().await; - let _ = writeln!(out, "\n## 观测\n\n| | |\n|---|---|"); - line(&mut out, "磁盘状态", format!("{:?}", g.level())); + let _ = writeln!(out, "\n## 请求记录\n\n| | |\n|---|---|"); + line(&mut out, "磁盘状态", g.level().label()); line(&mut out, "请求条数", g.db().count().unwrap_or(0)); line( &mut out, - "留档大小", + "请求体存储大小", format!("{} 字节", g.blobs().total_bytes()), ); @@ -186,12 +186,12 @@ pub async fn bundle(State(s): State) -> String { .collect(); let _ = writeln!( out, - "\n### 最近的失败({} 条,取自最近 {} 条请求)\n", + "\n### 最近失败的请求({} 条,取自最近 {} 条请求)\n", failed.len(), recent.len() ); if failed.is_empty() { - let _ = writeln!(out, "没有。"); + let _ = writeln!(out, "无。"); } else { let _ = writeln!(out, "| 时间 | 上游 | 状态 | 错误 |\n|---|---|---|---|"); for r in failed { @@ -225,14 +225,14 @@ pub async fn bundle(State(s): State) -> String { let _ = writeln!(out, "{}", tw_secret::mask_config_yaml(&text)); } Err(e) => { - let _ = writeln!(out, "# 读不了:{e}"); + let _ = writeln!(out, "# 无法读取:{e}"); } } let _ = writeln!(out, "```"); let _ = writeln!( out, - "\n---\n\n**不含请求体和响应体。**它们最有用也最危险 —— 需要的话在请求详情页里单独看。" + "\n---\n\n本文件不包含请求体和响应体,如有需要,请在请求详情中查看。" ); out } diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 1901b0d2..c2591e5b 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -206,7 +206,7 @@ fn async_stream_from( // 订阅者跟不上时 broadcast 会丢最老的。**继续收而不是断开** —— // UI 少几行实时日志无所谓,断掉重连才是真的难受。 Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::warn!(dropped = n, "控制面订阅者跟不上,丢了一些事件"); + tracing::warn!(dropped = n, "控制面订阅者处理不及,部分事件已丢弃"); continue; } Err(broadcast::error::RecvError::Closed) => return None, @@ -491,7 +491,7 @@ async fn l1( cfg.providers .iter() .find(|p| p.name == *n) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有叫 `{n}` 的上游")))?, + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到名为「{n}」的上游")))?, ], None => cfg.providers.iter().collect(), }; @@ -758,7 +758,7 @@ async fn speed_run( total_ms: 0, input_tokens: None, output_tokens: None, - error: Some(format!("取不到凭据:{e}")), + error: Some(format!("无法获取凭据:{e}")), }); continue; } @@ -818,7 +818,7 @@ fn targets<'a>( cfg.providers .iter() .find(|p| &p.name == n) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有叫「{n}」的上游"))) + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到名为「{n}」的上游"))) }) .collect() } @@ -869,7 +869,7 @@ async fn request_detail( .db() .get(id) .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))? - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有第 {id} 号请求")))?; + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到第 {id} 号请求")))?; let at = row.at_ms; let body = |which| { let raw = g.blobs().get(at, id, which)?; @@ -969,7 +969,7 @@ fn need_store(s: &ControlState) -> Result<&Arc, ) -> Result, (StatusCode, String)> { let Some(store) = &s.store else { - return Err((StatusCode::SERVICE_UNAVAILABLE, "观测层没有启动".into())); + return Err((StatusCode::SERVICE_UNAVAILABLE, "请求记录未启动".into())); }; let g = store.lock().await; let session = g @@ -1344,7 +1344,7 @@ async fn session_detail( .iter() .find(|x| x.id == id) .map(session_view) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有叫 `{id}` 的会话")))?; + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到会话 {id}")))?; let turns = g .db() .turns(&id) @@ -1357,7 +1357,7 @@ async fn session_detail( #[derive(Debug, thiserror::Error)] pub enum ControlError { - #[error("控制面 socket {path} 起不来:{source}")] + #[error("无法启动控制面 socket {path}:{source}")] Bind { path: PathBuf, source: std::io::Error, @@ -1367,7 +1367,7 @@ pub enum ControlError { /// 给的原话是「path must be shorter than SUN_LEN」,看不出上限是多少、 /// 也看不出自己超了多少。 #[error( - "控制面 socket 的路径太长:{len} 字节,系统上限是 {max}。\n{path}\n把配置放到一个短一点的目录下(默认的 ~/.thinkwatch 不会有这个问题)。" + "控制面 socket 的路径过长:{len} 字节,系统上限为 {max}。\n{path}\n请将配置放在路径较短的目录中(默认的 ~/.thinkwatch 不受此限制)" )] PathTooLong { path: PathBuf, @@ -1416,7 +1416,7 @@ pub async fn serve_unix(state: ControlState, path: &Path) -> Result<(), ControlE // 0700:只有当前用户能连。这就是不需要 token 的原因。 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); } - tracing::info!(path = %path.display(), "控制面已监听"); + tracing::info!(path = %path.display(), "控制面已开始监听"); let app = router(state); loop { diff --git a/crates/tw-control/src/pricing.rs b/crates/tw-control/src/pricing.rs index 87b6107f..3178a35d 100644 --- a/crates/tw-control/src/pricing.rs +++ b/crates/tw-control/src/pricing.rs @@ -88,7 +88,7 @@ fn read_saved(path: &Path) -> Option { Ok(raw) => raw, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, Err(e) => { - tracing::warn!("{} 读不了,按内置价目表计价:{e}", path.display()); + tracing::warn!("无法读取 {},改用内置价目表计价:{e}", path.display()); return None; } }; @@ -97,7 +97,7 @@ fn read_saved(path: &Path) -> Option { match tw_pricing::Table::fetched(&raw, local_date(saved_at)) { Ok(t) => Some(t), Err(e) => { - tracing::warn!("{} 读不通,按内置价目表计价:{e}", path.display()); + tracing::warn!("无法解析 {},改用内置价目表计价:{e}", path.display()); None } } @@ -167,7 +167,7 @@ struct Attempt { pub enum RefreshError { #[error("{0}")] Fetch(String), - #[error("下载到的内容不是价格数据集:{0}")] + #[error("下载的内容不是价格数据集:{0}")] Dataset(String), #[error("价目表无法保存:{0}")] Save(String), @@ -237,7 +237,7 @@ pub fn spawn(s: ControlState) { && u.due(s.config_path(), SystemTime::now()) && let Err(e) = refresh(&s).await { - tracing::info!("默认价目表刷新失败,稍后重试:{e}"); + tracing::info!("默认价目表更新失败,稍后重试:{e}"); } u.pause(u.schedule.tick).await; } @@ -271,7 +271,7 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshErro .timeout(FETCH_TIMEOUT) .send() .await - .map_err(|e| RefreshError::Fetch(format!("连接价格数据源失败:{}", chain(&e))))?; + .map_err(|e| RefreshError::Fetch(format!("无法连接价格数据源:{}", chain(&e))))?; if !resp.status().is_success() { return Err(RefreshError::Fetch(format!( "价格数据源返回 HTTP {}", @@ -286,7 +286,7 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshErro { if raw.len() + chunk.len() > MAX_DATASET { return Err(RefreshError::Dataset(format!( - "大小超过 {} MB", + "文件大小超过 {} MB", MAX_DATASET / 1024 / 1024 ))); } @@ -333,7 +333,7 @@ async fn pricing_status(s: &ControlState) -> tw_api::PricingStatus { // **拿不到存储就是 0** —— 观测层起不来时网关照常转发,这一页也该照常打开 let (unpriced_recent, unpriced_models) = match &s.store { Some(st) => st.lock().await.db().unpriced_recent(7).unwrap_or_else(|e| { - tracing::debug!("无法计价的请求统计取不到:{e}"); + tracing::debug!("未能获取无法计价请求的统计:{e}"); (0, Vec::new()) }), None => (0, Vec::new()), @@ -407,7 +407,7 @@ async fn query( if loaded.config().sheet(&name).is_none() { return Err(fail( StatusCode::NOT_FOUND, - format!("没有叫「{name}」的价目表"), + format!("未找到名为「{name}」的价目表"), )); } (loaded, Some(name)) @@ -485,10 +485,12 @@ async fn sheet( UrlPath(name): UrlPath, ) -> Result, Fail> { let cfg = s.config(); - let def = cfg - .pricing - .sheet(&name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的价目表")))?; + let def = cfg.pricing.sheet(&name).ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + format!("未找到名为「{name}」的价目表"), + ) + })?; Ok(Json(tw_api::PriceSheetInput { name: def.name.clone(), multiplier: def.multiplier, @@ -555,7 +557,7 @@ async fn delete_sheet( let users = refs::sheet_users(cfg, &name); if !users.is_empty() { return Err(ApplyError::InUse(format!( - "价目表「{name}」仍被上游{}使用,解除后才能删除", + "价目表「{name}」仍被上游{}使用,请先解除关联再删除", quoted(&users) ))); } diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index 1e387cda..75371f2b 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -45,14 +45,14 @@ fn stored_body( .db() .get(id) .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))? - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有第 {id} 号请求")))?; + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到第 {id} 号请求")))?; let raw = g .blobs() .get(row.at_ms, id, tw_store::Which::Request) .ok_or_else(|| { ( StatusCode::NOT_FOUND, - format!("第 {id} 号请求的请求体已经不在了(可能被清理了,见存储设置)"), + format!("第 {id} 号请求的请求体已不存在,可能已被清理"), ) })?; let original = g @@ -65,7 +65,7 @@ fn stored_body( return Err(( StatusCode::CONFLICT, format!( - "第 {id} 号请求的体有 {original} 字节,我们只存了 {},重放它等于发一个不一样的请求。", + "第 {id} 号请求的请求体有 {original} 字节,仅保存了 {} 字节,无法原样重放", raw.len() ), )); @@ -81,7 +81,7 @@ pub async fn quote( let store = s.store.as_ref().ok_or_else(|| { ( StatusCode::SERVICE_UNAVAILABLE, - "观测层没有启动".to_string(), + "请求记录未启动".to_string(), ) })?; let (row, raw) = { @@ -96,7 +96,7 @@ pub async fn quote( .ok_or_else(|| { ( StatusCode::NOT_FOUND, - format!("没有叫 `{}` 的上游", req.provider), + format!("未找到名为「{}」的上游", req.provider), ) })?; @@ -143,7 +143,7 @@ pub async fn run( let store = s.store.as_ref().ok_or_else(|| { ( StatusCode::SERVICE_UNAVAILABLE, - "观测层没有启动".to_string(), + "请求记录未启动".to_string(), ) })?; let (row, raw) = { @@ -158,7 +158,7 @@ pub async fn run( .ok_or_else(|| { ( StatusCode::NOT_FOUND, - format!("没有叫 `{}` 的上游", req.provider), + format!("未找到名为「{}」的上游", req.provider), ) })?; // OAuth 要联网换 token。重放不经过数据面,但**凭据这一层 @@ -171,7 +171,7 @@ pub async fn run( .map_err(|e| { fail( StatusCode::BAD_REQUEST, - format!("`{}` 的凭据取不到:{e}", provider.name), + format!("无法获取上游「{}」的凭据:{e}", provider.name), ) })?; @@ -236,7 +236,7 @@ pub async fn fixture( let store = s.store.as_ref().ok_or_else(|| { ( StatusCode::SERVICE_UNAVAILABLE, - "观测层没有启动".to_string(), + "请求记录未启动".to_string(), ) })?; let g = store.lock().await; @@ -244,7 +244,7 @@ pub async fn fixture( .db() .get(id) .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))? - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("没有第 {id} 号请求")))?; + .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到第 {id} 号请求")))?; let body = |which| -> String { g.blobs() .get(row.at_ms, id, which) @@ -256,7 +256,7 @@ pub async fn fixture( if req.is_empty() && resp.is_empty() { return Err(( StatusCode::NOT_FOUND, - format!("第 {id} 号请求的正文已经不在了(可能被清理了,见存储设置)"), + format!("第 {id} 号请求的响应体已不存在,可能已被清理"), )); } // 截断过的照样能当用例用 —— 它验的是「我们怎么理解这段字节」, @@ -266,11 +266,11 @@ pub async fn fixture( .original_len(row.at_ms, id, tw_store::Which::Response) .is_some_and(|o| o > resp.len()); let note = format!( - "实录:{} 于 {}{}", + "录制自上游「{}」,时间戳 {}{}", row.provider, row.at_ms, if truncated { - "。响应体在存储时被截断过,只取了开头一段。" + "。响应体在存储时已被截断,仅包含开头部分" } else { "" } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 7617f5c7..38eb1243 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -96,7 +96,7 @@ async fn delete_provider( let used = refs::provider_refs(cfg, &name); if !used.is_empty() { return Err(ApplyError::InUse(format!( - "上游「{name}」仍被{}引用,解除引用后才能删除", + "上游「{name}」仍被{}引用,请先解除引用再删除", describe(&used) ))); } @@ -154,7 +154,7 @@ async fn test_provider( cfg.providers .iter() .find(|p| p.name == n) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{n}」的上游")))?, + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{n}」的上游")))?, ), None => None, }; @@ -183,7 +183,7 @@ async fn test_provider( Some(a) => Some(a.to_string()), None => { return Ok(Json(failed( - "OAuth 凭据需要保存后才能检测。要现在检测,请同时填写 access token。" + "OAuth 凭据需要保存后才能检测。如需立即检测,请同时填写 access token" .to_string(), ))); } @@ -223,7 +223,7 @@ async fn provider_models( .providers .iter() .find(|p| p.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的上游")))?; + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{name}」的上游")))?; Ok(Json(models_view(&s, p, s.gateway.models.listing(p)))) } @@ -234,13 +234,13 @@ async fn refresh_models( ) -> Result, Fail> { let listing = tw_gateway::models::refresh_one(&s.gateway, &name) .await - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的上游")))?; + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{name}」的上游")))?; let cfg = s.config(); let p = cfg .providers .iter() .find(|p| p.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的上游")))?; + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{name}」的上游")))?; Ok(Json(models_view(&s, p, listing))) } @@ -292,7 +292,7 @@ fn to_provider( (tw_api::SecretChange::Set { value }, _) => { let v = value.trim(); if v.is_empty() { - return Err("密钥不能为空".to_string()); + return Err("API 密钥不能为空".to_string()); } Some(tw_config::Secret::new(v)) } @@ -449,7 +449,7 @@ async fn delete_proxy( let users = refs::proxy_users(cfg, &name); if !users.is_empty() { return Err(ApplyError::InUse(format!( - "代理「{name}」仍被上游{}使用,解除后才能删除", + "代理「{name}」仍被上游{}使用,请先解除关联再删除", quoted(&users) ))); } @@ -471,7 +471,7 @@ async fn test_proxy( cfg.proxies .iter() .find(|p| p.name == n) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{n}」的代理")))?, + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{n}」的代理")))?, ), None => None, }; @@ -480,7 +480,7 @@ async fn test_proxy( // 握手的目标:正在编辑的那个代理原来服务的上游 let (host, port) = tw_gateway::proxy_target(&cfg, req.current.as_deref().unwrap_or(&px.name)); let r = tw_gateway::l1_proxy(&hop, &host, port).await; - Ok(Json(crate::l1_view(format!("代理 {}", px.name), None, r))) + Ok(Json(crate::l1_view(px.name.clone(), None, r))) } fn to_proxy( @@ -489,14 +489,14 @@ fn to_proxy( ) -> Result { let name = checked_name(&input.name, "代理")?; if matches!(name.as_str(), tw_config::DIRECT | tw_config::SYSTEM) { - return Err(format!("「{name}」是内置选项的名字,请换一个")); + return Err(format!("「{name}」是内置选项的名称,请使用其他名称")); } let addr = input.addr.trim().to_string(); let port_ok = addr .rsplit_once(':') .is_some_and(|(h, p)| !h.is_empty() && p.parse::().is_ok_and(|p| p > 0)); if !port_ok { - return Err(format!("代理地址「{addr}」要写成 主机:端口")); + return Err(format!("代理地址「{addr}」应写成 主机:端口 的形式")); } let auth = match &input.auth { // 没动认证:沿用原来那一份,**原值不经过界面** @@ -509,7 +509,7 @@ fn to_proxy( } // `${` 在配置里表示「从环境变量读」 if pass.contains("${") { - return Err("密码里不能出现 `${`".to_string()); + return Err("密码中不能包含 ${".to_string()); } Some(tw_config::proxy::ProxyAuth { user: user.to_string(), @@ -532,7 +532,7 @@ pub(crate) fn checked_name(raw: &str, what: &str) -> Result { return Err(format!("{what}名称不能为空")); } if raw.trim() != raw { - return Err(format!("{what}名称首尾不能有空白")); + return Err(format!("{what}名称首尾不能包含空白")); } Ok(raw.to_string()) } @@ -540,13 +540,13 @@ pub(crate) fn checked_name(raw: &str, what: &str) -> Result { /// 界面上的一个选项值 → 配置里的枚举。**和 YAML 里写的词是同一套**。 fn slug(what: &str, v: &str) -> Result { serde_yaml_ng::from_value(Value::String(v.to_string())) - .map_err(|_| format!("{what}「{v}」不认识")) + .map_err(|_| format!("{what}「{v}」不受支持")) } pub(crate) fn mapping(v: &T) -> Result { match serde_yaml_ng::to_value(v) { Ok(Value::Mapping(m)) => Ok(m), - Ok(_) => Err(invalid("写不成一个映射".to_string())), + Ok(_) => Err(invalid("无法序列化为映射".to_string())), Err(e) => Err(invalid(e.to_string())), } } diff --git a/crates/tw-control/src/rotation.rs b/crates/tw-control/src/rotation.rs index 07d5a8ff..6b61c171 100644 --- a/crates/tw-control/src/rotation.rs +++ b/crates/tw-control/src/rotation.rs @@ -72,7 +72,7 @@ async fn persist(state: &crate::ControlState, r: &Rotated) -> (bool, String) { ( false, format!( - "{last}。重启之前请处理:修好这个文件(多半是权限或者它正被别的程序占着),修好之后下一次轮换会自动写进去;实在不行就重新走一次授权换一份新凭据" + "{last}。请在重启前处理:检查该文件的权限,以及是否被其他程序占用。问题解决后,下一次轮换会自动写回;如仍无法写回,请重新授权以获取新凭据" ), ) } @@ -81,7 +81,7 @@ async fn once(state: &crate::ControlState, r: &Rotated) -> Result200k\" 这样,前面得有 > < >= <= = 之一")] + #[error("「{0}」缺少比较符,应以 > < >= <= = 之一开头,例如 \">200k\"")] NoOperator(String), - #[error("`{0}` 里的数字读不出来")] + #[error("「{0}」中的数字无法解析")] BadNumber(String), - #[error("`{0}` 的单位不认识。支持 k / m(千 / 百万),钱写成 $2.5")] + #[error("「{0}」的单位无法识别。支持 k(千)和 m(百万),金额写成 $2.5 的形式")] BadUnit(String), } diff --git a/crates/tw-engine/src/rule.rs b/crates/tw-engine/src/rule.rs index 3eb4c1b4..74cc43ff 100644 --- a/crates/tw-engine/src/rule.rs +++ b/crates/tw-engine/src/rule.rs @@ -195,7 +195,7 @@ impl When { #[derive(Debug, thiserror::Error, PartialEq)] pub enum MatchError { - #[error("条件 `{field}` 写错了:{source}")] + #[error("条件 {field} 的写法有误:{source}")] BadCompare { field: &'static str, source: crate::num::ParseError, diff --git a/crates/tw-gateway/src/access.rs b/crates/tw-gateway/src/access.rs index 435eb2d4..eec8bb69 100644 --- a/crates/tw-gateway/src/access.rs +++ b/crates/tw-gateway/src/access.rs @@ -18,9 +18,9 @@ pub struct Cidr { #[derive(Debug, thiserror::Error, PartialEq)] pub enum CidrError { - #[error("`{0}` 不是合法的 CIDR。写法是 `192.168.0.0/16` 这样。")] + #[error("「{0}」不是合法的 CIDR,应写成 192.168.0.0/16 的形式")] Malformed(String), - #[error("`{cidr}` 的前缀长度 {prefix} 超出范围(IPv4 最大 32,IPv6 最大 128)")] + #[error("「{cidr}」的前缀长度 {prefix} 超出范围(IPv4 最大为 32,IPv6 最大为 128)")] BadPrefix { cidr: String, prefix: u8 }, } @@ -122,7 +122,7 @@ impl AllowList { .map(|s| s.to_string()) .collect::>(), ) - .expect("内置的私网段一定是合法 CIDR") + .expect("内置私网段是合法的 CIDR") } pub fn allows(&self, ip: IpAddr) -> bool { diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index 34046c33..1e12f5c8 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -30,7 +30,7 @@ use crate::usage::{Sniffer, Usage}; /// **到目前为止对响应知道的一切都在它身上**:状态码、收到多少字节、嗅到 /// 多少用量、攒下的响应体。放在一处是因为结局要用的正是这些 —— 不管这个 /// 结局是显式报的,还是在 Drop 里报的。 -#[must_use = "丢掉它就等于报告客户端已经走了"] +#[must_use = "丢弃它等同于报告客户端已断开"] pub struct Ending { bus: tw_observe::EventBus, id: u64, @@ -169,7 +169,7 @@ impl Drop for Ending { self.bus.emit(tw_api::Event::RequestFailed { id: self.id, source: "internal".to_string(), - message: "请求中断:网关内部出错".to_string(), + message: "请求中断:网关内部错误".to_string(), bytes: self.received(), duration_ms: Some(self.duration_ms()), usage, diff --git a/crates/tw-gateway/src/fixture.rs b/crates/tw-gateway/src/fixture.rs index 0d58c57c..8b6aef4d 100644 --- a/crates/tw-gateway/src/fixture.rs +++ b/crates/tw-gateway/src/fixture.rs @@ -236,7 +236,7 @@ pub fn replay(f: &Fixture) -> Vec { ($field:ident, $label:expr) => { if got.$field != f.expect.$field { diffs.push(format!( - "{}:录的是 {:?},现在是 {:?}", + "{}:录制时为 {:?},当前为 {:?}", $label, f.expect.$field, got.$field )); } @@ -250,7 +250,7 @@ pub fn replay(f: &Fixture) -> Vec { cmp!(image, "带图片"); cmp!(thinking, "扩展思考"); cmp!(stream, "流式"); - cmp!(usage, "usage 四维"); + cmp!(usage, "用量四项"); cmp!(stop_reason, "stop_reason"); cmp!(tool_calls, "工具调用"); cmp!(error_kind, "错误分类"); @@ -328,11 +328,11 @@ mod tests { .replace("\"usage\":{\"output_tokens\":30}", "\"usage\":{}"); let d = replay(&f); assert_eq!(d.len(), 1, "{d:?}"); - assert!(d[0].contains("usage 四维"), "{d:?}"); + assert!(d[0].contains("用量四项"), "{d:?}"); // **差异要说清「录的是什么、现在是什么」** —— 只说「不一致」 // 的话,看的人还得自己去翻 assert!( - d[0].contains("录的是") && d[0].contains("现在是"), + d[0].contains("录制时为") && d[0].contains("当前为"), "{}", d[0] ); diff --git a/crates/tw-gateway/src/forward.rs b/crates/tw-gateway/src/forward.rs index f76168d1..ac8436d2 100644 --- a/crates/tw-gateway/src/forward.rs +++ b/crates/tw-gateway/src/forward.rs @@ -164,7 +164,7 @@ pub fn apply_set(body: &Bytes, set: &tw_engine::SetAction) -> Bytes { Ok(b) => Bytes::from(b), // 序列化不该失败,但真失败了宁可发原文也不要发半个 body Err(e) => { - tracing::error!("改写后的请求体序列化失败,发原文:{e}"); + tracing::error!("改写后的请求体序列化失败,改为发送原始请求体:{e}"); body.clone() } } @@ -173,10 +173,10 @@ pub fn apply_set(body: &Bytes, set: &tw_engine::SetAction) -> Bytes { pub fn map_reqwest_error(e: reqwest::Error) -> GatewayError { // 分类要能让人看出该去哪儿修。 if e.is_timeout() { - GatewayError::upstream("上游超时") + GatewayError::upstream("上游响应超时") } else if e.is_connect() { GatewayError::upstream(format!( - "连不上上游。检查 base_url 和网络,如果配了代理也检查代理:{}", + "无法连接上游,请检查接口地址、网络和代理设置:{}", tw_secret::redact_url(e.url().map(|u| u.as_str()).unwrap_or("")) )) } else { @@ -188,7 +188,7 @@ pub fn map_reqwest_error(e: reqwest::Error) -> GatewayError { pub fn check_body_size(body: &Bytes, max: usize) -> Result<(), GatewayError> { if body.len() > max { return Err(GatewayError::request(format!( - "请求体 {} 字节,超过上限 {} 字节", + "请求体大小为 {} 字节,超过上限 {} 字节", body.len(), max ))); diff --git a/crates/tw-gateway/src/l1.rs b/crates/tw-gateway/src/l1.rs index ab81c902..1f4dff27 100644 --- a/crates/tw-gateway/src/l1.rs +++ b/crates/tw-gateway/src/l1.rs @@ -181,7 +181,7 @@ pub fn hop_for( match p.proxy.as_str() { tw_config::DIRECT => Ok(None), tw_config::SYSTEM => Err( - "该上游使用系统代理,代理地址在建立连接时才能确定,链路测速无法测量。如需测速,请将代理配置为命名代理。" + "该上游使用系统代理,代理地址在建立连接时才能确定,链路测速无法测量。如需测速,请将代理配置为命名代理" .into(), ), name => { @@ -189,7 +189,7 @@ pub fn hop_for( .proxies .iter() .find(|x| x.name == name) - .ok_or_else(|| format!("上游「{}」使用的代理「{name}」未在 proxies 中定义。", p.name))?; + .ok_or_else(|| format!("上游「{}」使用的代理「{name}」未在 proxies 中定义", p.name))?; hop_of(px).map(Some) } } @@ -397,11 +397,11 @@ async fn resolve(t: &mut Timer, host: &str, port: u16, stage: Stage) -> Result String { let l = e.to_ascii_lowercase(); if l.contains("refused") { - format!("{addr} 拒绝连接,该端口上没有服务在监听。请检查地址和端口。") + format!("{addr} 拒绝连接,该端口上没有服务在监听。请检查地址和端口") } else if e == timed_out() || l.contains("timed out") { - format!("连接 {addr} 没有响应。请检查网络,或确认该地址是否需要经代理访问。") + format!("连接 {addr} 没有响应。请检查网络,或确认该地址是否需要经代理访问") } else if l.contains("unreachable") { - format!("无法访问 {addr} 所在的网络,请检查本机网络。") + format!("无法访问 {addr} 所在的网络,请检查本机网络") } else { format!("无法连接 {addr}:{e}") } @@ -544,7 +544,7 @@ async fn socks5_connect( read_exact(io, &mut m).await?; if m[0] != 0x05 { return Err(format!( - "代理的响应不是 SOCKS5 协议(版本字节 0x{:02x}),该端口上可能是 HTTP 代理。", + "代理的响应不是 SOCKS5 协议(版本字节 0x{:02x}),该端口上可能是 HTTP 代理", m[0] )); } @@ -669,7 +669,7 @@ async fn http_connect( let code = line.split_whitespace().nth(1).unwrap_or(""); match code { "200" => Ok(()), - "407" => Err("代理要求认证(HTTP 407),请检查用户名和密码。".into()), + "407" => Err("代理要求认证(HTTP 407),请检查用户名和密码".into()), "" => Err(format!("代理返回了无法识别的响应:{line}")), c => Err(format!("代理拒绝了 CONNECT 请求(HTTP {c}):{line}")), } @@ -737,21 +737,19 @@ fn tls_message(e: &std::io::Error) -> String { // 塞进 `Other`,那些结构化变体在这个平台上永远不会出现 —— 按枚举 // 匹配的结果是每一种失败都拿到那句最泛的提示,包括证书只是过期时。 let d = detail.to_ascii_lowercase(); - let hint = if d.contains("expired") - || d.contains("not valid yet") - || d.contains("not yet valid") - { - "证书已过期或尚未生效,也可能是本机时间不准确,请先核对系统时间。" - } else if d.contains("issuer") - || d.contains("self-signed") - || d.contains("self signed") - || d.contains("untrusted") - || d.contains("not trusted") - { - "证书的签发者不在系统信任列表中。如果本机安装了抓包工具或企业根证书,证书链可能已被替换。" - } else { - "如果网络中有抓包工具或企业代理拦截 TLS 连接,也会出现此错误。" - }; + let hint = + if d.contains("expired") || d.contains("not valid yet") || d.contains("not yet valid") { + "证书已过期或尚未生效,也可能是本机时间不准确,请先核对系统时间" + } else if d.contains("issuer") + || d.contains("self-signed") + || d.contains("self signed") + || d.contains("untrusted") + || d.contains("not trusted") + { + "证书的签发者不在系统信任列表中。如果本机安装了抓包工具或企业根证书,证书链可能已被替换" + } else { + "如果网络中有抓包工具或企业代理拦截 TLS 连接,也会出现此错误" + }; format!("证书验证未通过:{detail}。{hint}") } diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index 0e4ad295..1a7d180b 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -154,7 +154,7 @@ pub async fn run( output_tokens: None, input_tokens: None, error: Some(format!( - "推理测速暂不支持 {} 协议的上游,没有发出请求", + "推理测速暂不支持 {} 协议的上游,未发送请求", protocol.map(|p| format!("{p:?}")).unwrap_or_default() )), }; @@ -345,7 +345,7 @@ mod tests { assert!(!r.ok); let e = r.error.unwrap(); assert!(e.contains("暂不支持"), "{e}"); - assert!(e.contains("没有发出请求"), "{e}"); + assert!(e.contains("未发送请求"), "{e}"); } #[test] diff --git a/crates/tw-gateway/src/latency.rs b/crates/tw-gateway/src/latency.rs index f67fba91..124f199a 100644 --- a/crates/tw-gateway/src/latency.rs +++ b/crates/tw-gateway/src/latency.rs @@ -44,7 +44,7 @@ impl Latency { /// 记一次。**转发路径上调,所以必须便宜**:一次哈希加一次 push。 pub fn record(&self, provider: &str, ttfb_ms: u32) { - let mut g = self.inner.lock().expect("锁没毒"); + let mut g = self.inner.lock().expect("锁未中毒"); let w = g.entry(provider.to_string()).or_default(); if w.len() == WINDOW { w.pop_front(); @@ -57,7 +57,7 @@ impl Latency { /// **只在完全没有真实样本时垫**。真实流量一到就该由它说了算 —— /// L1 量的是建连,不含上游排队和推理,天生偏乐观。 pub fn seed(&self, provider: &str, ttfb_ms: u32) { - let mut g = self.inner.lock().expect("锁没毒"); + let mut g = self.inner.lock().expect("锁未中毒"); let w = g.entry(provider.to_string()).or_default(); if w.is_empty() { // 垫满 `MIN_SAMPLES` 才算数 —— 否则它自己也是「样本不够」 @@ -69,7 +69,7 @@ impl Latency { /// 这家的典型 TTFB。`None` = 样本不够,**不是「很快」**。 pub fn typical(&self, provider: &str) -> Option { - let g = self.inner.lock().expect("锁没毒"); + let g = self.inner.lock().expect("锁未中毒"); let w = g.get(provider)?; if w.len() < MIN_SAMPLES { return None; @@ -81,7 +81,7 @@ impl Latency { /// 一次取一批 —— 排序时要用到,逐个取会连着锁好几次。 pub fn snapshot(&self, names: &[String]) -> HashMap { - let g = self.inner.lock().expect("锁没毒"); + let g = self.inner.lock().expect("锁未中毒"); let mut out = HashMap::new(); for n in names { if let Some(w) = g.get(n) diff --git a/crates/tw-gateway/src/limits.rs b/crates/tw-gateway/src/limits.rs index f5e9fe38..b7623a0b 100644 --- a/crates/tw-gateway/src/limits.rs +++ b/crates/tw-gateway/src/limits.rs @@ -21,9 +21,9 @@ pub use tw_types::Limits; #[derive(Debug, thiserror::Error)] pub enum LimitError { - #[error("排队超过 {0:?} 还没轮到。上游可能全都卡住了,或者并发上限设得太低。")] + #[error("排队超过 {0:?} 仍未获得处理。上游可能均无响应,或并发上限设置过低")] Timeout(Duration), - #[error("等待队列已满({0} 个)。有东西在疯狂发请求 —— 检查一下是不是有脚本失控了。")] + #[error("等待队列已满({0} 个),请求量异常,请检查是否有脚本在大量发送请求")] QueueFull(usize), } diff --git a/crates/tw-gateway/src/live.rs b/crates/tw-gateway/src/live.rs index da0f6070..8f026933 100644 --- a/crates/tw-gateway/src/live.rs +++ b/crates/tw-gateway/src/live.rs @@ -23,7 +23,7 @@ pub struct Live(Arc); /// 一个请求的通行证。**Drop 时自动减一** —— 手工减的话,迟早有一条错误 /// 路径会漏掉,而漏掉的表现是这个数只增不减,等它归零的人永远等不到。 -#[must_use = "丢掉通行证就等于这个请求已经结束"] +#[must_use = "丢弃通行证等同于请求已结束"] pub struct Pass(Arc); impl Live { diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index 0cdb90d2..f136cce6 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -256,7 +256,7 @@ async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer let http = rt.clients.get(&p.name).unwrap_or(&state.http); let headers = match state.headers_for(p, http, None).await { Ok(h) => h, - Err(e) => return Answer::Failed(format!("取不到凭据:{e}")), + Err(e) => return Answer::Failed(format!("无法获取凭据:{e}")), }; let r = crate::probe::probe(http, &p.base_url, &headers, p.effective_protocol()).await; if !r.ok { @@ -265,7 +265,7 @@ async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer match r.models { ModelList::Listed { models } => Answer::Listed(models), ModelList::NotImplemented { status } => { - Answer::NoList(format!("上游没有提供模型列表接口(HTTP {status})")) + Answer::NoList(format!("上游未提供模型列表接口(HTTP {status})")) } ModelList::Unrecognized { .. } => { Answer::NoList("上游返回的模型列表格式无法识别".to_string()) @@ -287,10 +287,10 @@ async fn refresh(state: &AppState, names: &[String]) { for (p, id, answer) in futures::future::join_all(asks).await { match &answer { Answer::Listed(models) => { - tracing::debug!(provider = %p.name, models = models.len(), "模型清单已获取") + tracing::debug!(provider = %p.name, models = models.len(), "已获取模型列表") } Answer::NoList(why) | Answer::Failed(why) => { - tracing::info!(provider = %p.name, "没有获取到模型清单:{why}") + tracing::info!(provider = %p.name, "未能获取模型列表:{why}") } Answer::Pending => {} } @@ -365,8 +365,8 @@ impl Skip { pub fn label(&self) -> &'static str { match self { Skip::Disabled => "已停用", - Skip::OutOfScope => "该模型不在启用范围内", - Skip::NotOffered => "不提供该模型", + Skip::OutOfScope => "不在启用范围内", + Skip::NotOffered => "未提供此模型", } } } @@ -389,11 +389,11 @@ impl Serving { .join(";"); // 全是停用:请求没问题,是配置里能用的上游都关掉了 if self.skipped.iter().all(|(_, s)| *s == Skip::Disabled) { - crate::GatewayError::config(format!("路由选中的上游都已停用:{why}")) + crate::GatewayError::config(format!("路由选中的上游均已停用:{why}")) } else { crate::GatewayError::new( crate::error::Source::Request, - format!("没有可用的上游提供模型 `{model}`:{why}"), + format!("没有可用的上游提供模型 {model}:{why}"), ) } } diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index 286f7f3b..37823642 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -34,13 +34,13 @@ const BACKOFF: Duration = Duration::from_secs(30); #[derive(Debug, thiserror::Error)] pub enum OauthError { - #[error("换 token 时连不上 {endpoint}:{why}")] + #[error("刷新 token 时无法连接 {endpoint}:{why}")] Http { endpoint: String, why: String }, #[error("token 端点返回 {status}:{body}")] Status { status: u16, body: String }, - #[error("token 端点的响应里没有 access_token")] + #[error("token 端点的响应中没有 access_token")] NoToken, - #[error("上一次换 token 失败了({why}),{secs} 秒之后再试")] + #[error("上次刷新 token 失败({why}),将在 {secs} 秒后重试")] Backoff { why: String, secs: u64 }, } @@ -140,7 +140,7 @@ impl Cache { ) -> Result<(String, Option), OauthError> { // 先看手里有没有能用的 { - let g = self.inner.lock().expect("锁没毒"); + let g = self.inner.lock().expect("锁未中毒"); if let Some(live) = g.get(provider).filter(|l| l.usable_for(cfg)) { if let Some((why, until)) = &live.failed && Instant::now() < *until @@ -176,7 +176,7 @@ impl Cache { http: &reqwest::Client, ) -> Result<(String, Option), OauthError> { { - let mut g = self.inner.lock().expect("锁没毒"); + let mut g = self.inner.lock().expect("锁未中毒"); if let Some(live) = g.get_mut(provider).filter(|l| l.usable_for(cfg)) { live.renew_at = Some(Instant::now()); // 强制刷新时把退避清掉 —— 这是调用方明确要求的一次 @@ -194,7 +194,7 @@ impl Cache { ) -> Result<(String, Option), OauthError> { // 用手里那个 refresh(可能是服务器换过的),没有就用配置里的 let refresh = { - let g = self.inner.lock().expect("锁没毒"); + let g = self.inner.lock().expect("锁未中毒"); g.get(provider) // 认不出来 = 用户改了配置,缓存里那个(哪怕是服务器 // 换发的)一律不算,用配置里的重新开始 @@ -207,7 +207,7 @@ impl Cache { Err(e) => { // **记下失败并退避。**没有它,一个坏掉的 token 端点会被 // 每个请求敲一次 - let mut g = self.inner.lock().expect("锁没毒"); + let mut g = self.inner.lock().expect("锁未中毒"); let why = e.to_string(); let fp = fingerprint(cfg); let entry = g.entry(provider.to_string()).or_insert_with(|| Live { @@ -241,7 +241,7 @@ impl Cache { let life = secs.saturating_sub(lead).max(1); Instant::now() + Duration::from_secs(life) }); - let mut g = self.inner.lock().expect("锁没毒"); + let mut g = self.inner.lock().expect("锁未中毒"); g.insert( provider.to_string(), Live { @@ -390,7 +390,7 @@ mod tests { let second = rt.block_on(c.token("p", &o, &http)).unwrap_err(); // 第二次直接被退避挡住,没有再去连 assert!(matches!(second, OauthError::Backoff { .. }), "{second}"); - assert!(second.to_string().contains("秒之后再试"), "{second}"); + assert!(second.to_string().contains("秒后重试"), "{second}"); } #[test] diff --git a/crates/tw-gateway/src/probe.rs b/crates/tw-gateway/src/probe.rs index 39205160..2e78cfc1 100644 --- a/crates/tw-gateway/src/probe.rs +++ b/crates/tw-gateway/src/probe.rs @@ -96,9 +96,12 @@ pub async fn probe( Err(e) => { let ms = started.elapsed().as_millis() as u64; let msg = if e.is_timeout() { - format!("{PROBE_TIMEOUT:?} 内没有响应。检查 base_url,或者这家上游是不是需要代理。") + format!( + "{PROBE_TIMEOUT:?} 内没有响应。请检查接口地址,或确认该上游是否需要经代理访问" + ) } else if e.is_connect() { - "连不上。检查 base_url 拼写和网络;如果这家上游要走代理,先配好代理。".to_string() + "无法连接。请检查接口地址拼写和网络;如果该上游需要经代理访问,请先配置代理" + .to_string() } else { format!("请求失败:{e}") }; @@ -116,7 +119,7 @@ pub async fn probe( ms, proto_name, format!( - "上游拒绝了这把密钥(HTTP {})。检查 key 有没有多余的空格,以及它是不是这家的。", + "上游拒绝了该密钥(HTTP {})。请检查密钥是否包含多余的空格,以及是否属于该上游", status.as_u16() ), ); @@ -128,7 +131,7 @@ pub async fn probe( // 拿到了 2xx 但读 body 失败 —— 归到「没认出」而不是「不提供」, // 因为它确实有这个接口。 Err(e) => ModelList::Unrecognized { - sample: format!("读响应体失败:{e}"), + sample: format!("读取响应体失败:{e}"), }, } } else { diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index f222370b..43861b44 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -63,15 +63,15 @@ pub fn client_for_provider( // 今天已经犯过一次了(还没有配置任何上游那条)。 GatewayError::config(format!( concat!( - "provider `{}` 要走代理 `{}`,但 proxies 段里没有这个名字。\n", - "内置的名字只有 `direct` 和 `system`。" + "上游「{}」使用的代理「{}」未在 proxies 中定义,", + "内置选项只有 direct 和 system" ), p.name, name )) })?; let url = proxy .url() - .map_err(|e| GatewayError::config(format!("代理 `{name}` 的密码取不到:{e}")))?; + .map_err(|e| GatewayError::config(format!("无法读取代理「{name}」的密码:{e}")))?; match reqwest::Proxy::all(&url) { Ok(px) => b = b.proxy(px), Err(e) => { @@ -81,12 +81,12 @@ pub fn client_for_provider( if p.on_proxy_fail == tw_config::OnProxyFail::Direct { tracing::warn!( provider = %p.name, proxy = %name, - "代理配不起来,按 on_proxy_fail 降级直连:{e}" + "代理不可用,按 on_proxy_fail 设置改为直连:{e}" ); b = b.no_proxy(); } else { return Err(GatewayError::config(format!( - "provider `{}` 的代理 `{name}` 配不起来:{e}", + "上游「{}」的代理「{name}」不可用:{e}", p.name ))); } @@ -95,7 +95,7 @@ pub fn client_for_provider( } } b.build() - .map_err(|e| GatewayError::config(format!("HTTP 客户端建不起来:{e}"))) + .map_err(|e| GatewayError::config(format!("无法创建 HTTP 客户端:{e}"))) } /// 一次配置换入时**整块换掉**的那部分。 @@ -269,7 +269,7 @@ impl AppState { pub fn new(config: tw_config::Config) -> Result { let http = base_client_builder() .build() - .map_err(|e| GatewayError::config(format!("HTTP 客户端建不起来:{e}")))?; + .map_err(|e| GatewayError::config(format!("无法创建 HTTP 客户端:{e}")))?; let limits = config.limits.clone(); let pricing_config = config.pricing.clone(); let price_assign = config.price_assign(); @@ -295,7 +295,7 @@ impl AppState { Arc::new(tw_pricing::Table::builtin().unwrap_or_else(|e| { // **加载不了不能挡住启动**:那时成本显示「未知」, // 而转发照常 - tracing::warn!("内置价目表加载失败,成本一律标未知:{e}"); + tracing::warn!("内置价目表加载失败,所有请求的费用记为未知:{e}"); tw_pricing::Table::empty() })), pricing_config, @@ -348,7 +348,7 @@ impl AppState { let o = p .oauth .as_ref() - .ok_or_else(|| format!("上游「{}」没有配置 OAuth", p.name))?; + .ok_or_else(|| format!("上游「{}」未配置 OAuth", p.name))?; self.oauth_token(p, o, http).await } @@ -380,15 +380,13 @@ impl AppState { // 通道满 = 前一次还没写完。**这条要说** —— 和 body // 那条路不一样,丢掉的不是一条观测记录,是一份 // 还没落盘的凭据 - self.report_rotation(&p.name, false, "写回的队列满了,这一次没排上"); + self.report_rotation(&p.name, false, "写回队列已满,本次未能写回"); } } // 控制面没起来:**只报不写**,而且要说清没写 - None => self.report_rotation( - &p.name, - false, - "没有配置管理器(网关是单独跑的),写不回去", - ), + None => { + self.report_rotation(&p.name, false, "网关独立运行,没有配置管理器,无法写回") + } } } Ok(token) @@ -401,11 +399,11 @@ impl AppState { /// 而那时他应该已经知道原因。 pub fn report_rotation(&self, provider: &str, persisted: bool, detail: &str) { { - let mut told = self.rotation_told.lock().expect("锁没毒"); + let mut told = self.rotation_told.lock().expect("锁未中毒"); if persisted { if !told.insert(provider.to_string()) { // 这家的「已经帮你写回去了」说过了 - tracing::debug!(provider, "又一次轮换,已写回,不再重复说"); + tracing::debug!(provider, "凭据再次轮换,已写回"); return; } } else { @@ -423,7 +421,7 @@ impl AppState { tracing::warn!( provider, detail, - "token 端点换发了新的 refresh token,但没能写回 config.yaml —— 重启之前必须处理,否则这家上游会全是 401" + "token 端点换发了新的 refresh token,但未能写回 config.yaml。重启前必须处理,否则该上游的请求将全部返回 401" ); } self.bus.emit(tw_api::Event::CredentialRotated { @@ -592,7 +590,7 @@ impl AppState { ) -> Result<(String, crate::auth::KeyPosition), GatewayError> { let Some((key, position)) = crate::auth::extract_key_with_position(headers, query) else { return Err(GatewayError::auth( - "请求没带网关密钥。把 config.yaml 里 clients 段的那把 key 配到客户端上。", + "请求未携带网关密钥。请将 config.yaml 的 clients 中的网关密钥配置到客户端", )); }; self.rt @@ -605,9 +603,7 @@ impl AppState { .ok_or_else(|| { // 不回显收到的 key,哪怕是打码的 —— 回显会让「猜密钥」 // 这件事有了反馈信号。 - GatewayError::auth( - "网关密钥不认识。检查客户端配置里的 key 和 config.yaml 是否一致。", - ) + GatewayError::auth("网关密钥无效。请检查客户端配置中的密钥与 config.yaml 是否一致") }) } } @@ -669,7 +665,7 @@ async fn ws_upgrade( { tw_engine::Outcome::Route(d) => d, tw_engine::Outcome::Deny { rule, reason } => { - tracing::info!(%rule, "按规则拒绝一次 WS 升级"); + tracing::info!(%rule, "按规则拒绝 WebSocket 升级"); return Err(GatewayError::denied(reason)); } }; @@ -678,13 +674,13 @@ async fn ws_upgrade( return Err(GatewayError::config("没有可用的上游".to_string())); }; let Some(provider) = rt.config.providers.iter().find(|p| p.name == name) else { - return Err(GatewayError::config(format!("配置里没有 `{name}`"))); + return Err(GatewayError::config(format!("配置中不存在「{name}」"))); }; // **走代理的上游不代理 WS**,而且要明说。悄悄绕过用户配的代理, // 等于把他以为在代理后面的流量直接发出去 if provider.proxy != tw_config::DIRECT { return Err(GatewayError::config(format!( - "`{name}` 配了出站代理({}),而 WebSocket 升级这条路还不会走代理 —— 与其悄悄绕过它,不如在这里停下。这条链路暂时只支持 direct 的上游。", + "上游「{name}」配置了代理({}),WebSocket 连接暂不支持经代理转发,仅支持直连的上游", provider.proxy ))); } @@ -692,7 +688,7 @@ async fn ws_upgrade( let upstream_headers = state .headers_for(provider, http, Some(&client_name)) .await - .map_err(|e| GatewayError::config(format!("`{name}` 的凭据取不到:{e}")))?; + .map_err(|e| GatewayError::config(format!("无法获取上游「{name}」的凭据:{e}")))?; let url = crate::ws::upstream_url(&provider.base_url, uri.path(), query.as_deref()); let id = state.bus.next_id(); state.bus.emit(tw_api::Event::RequestStarted { @@ -792,7 +788,7 @@ async fn list_models( let rt = state.runtime(); if !rt.allow.allows(peer.ip()) { return Err(GatewayError::auth(format!( - "{} 不在允许的来源里。", + "{} 不在允许的来源地址中", peer.ip() ))); } @@ -843,7 +839,7 @@ async fn get_model( let rt = state.runtime(); if !rt.allow.allows(peer.ip()) { return Err(GatewayError::auth(format!( - "{} 不在允许的来源里。", + "{} 不在允许的来源地址中", peer.ip() ))); } @@ -861,7 +857,7 @@ async fn get_model( if !catalog.is_empty() && !catalog.admits(&model, Some(&shape.protocols()), allow.as_deref()) { return Err(GatewayError::new( crate::error::Source::Request, - format!("没有叫 `{model}` 的模型。能用的见 GET /v1/models。"), + format!("不存在模型 {model},可用模型请参见 GET /v1/models"), )); } let now = now_ms() / 1000; @@ -899,7 +895,7 @@ async fn passthrough( return Err(GatewayError::new( crate::error::Source::Auth, format!( - "{} 不在允许的来源里。改 listen.gateway.allow_from,或者把 bind 改回 loopback。", + "{} 不在允许的来源地址中。请修改 listen.gateway.allow_from,或将 bind 改为 loopback", peer.ip() ), )); @@ -1082,8 +1078,8 @@ async fn pipeline( // 说不清下一步。 if rt.config.providers.is_empty() { return Err(GatewayError::config(concat!( - "还没有配置任何上游。打开 ThinkWatch Lite 添加第一个 provider,", - "或者往 config.yaml 的 providers 段里写一个。" + "尚未配置任何上游。请在 ThinkWatch Lite 中添加上游,", + "或在 config.yaml 的 providers 中添加" ))); } @@ -1125,12 +1121,12 @@ async fn pipeline( // 该去改的地方不一样 let msg = if catalog.providers_for(&facts.model).is_empty() { format!( - "没有上游提供模型 {}。能用的模型见 GET /v1/models。", + "没有上游提供模型 {},可用模型请参见 GET /v1/models", facts.model ) } else { format!( - "客户端 `{client_name}` 不允许使用 {}。它能用的模型见 GET /v1/models。", + "网关密钥「{client_name}」无权使用模型 {},可用模型请参见 GET /v1/models", facts.model ) }; @@ -1167,7 +1163,7 @@ async fn pipeline( return Err(serving.explain(&facts.model)); } if !serving.skipped.is_empty() { - tracing::debug!(skipped = ?serving.skipped, model = %facts.model, "跳过服务不了的候选"); + tracing::debug!(skipped = ?serving.skipped, model = %facts.model, "跳过无法服务该请求的候选上游"); } decision.candidates = serving.usable; // 策略组排序。**引擎给的是集合,顺序在这儿定** —— @@ -1236,7 +1232,7 @@ async fn pipeline( if fail_open { tracing::warn!( candidates = ?decision.candidates, - "全部候选都在熔断中,仍然照常尝试(fail-open)" + "所有候选上游均处于熔断状态,仍照常尝试(fail-open)" ); } @@ -1325,7 +1321,7 @@ async fn pipeline( let Some(provider) = rt.config.providers.iter().find(|p| &p.name == *name) else { // 校验时挡过一次,能到这儿说明配置在运行中被换过。 last_err = Some(GatewayError::config(format!( - "规则 `{}` 选中了 `{name}`,但配置里没有这个 provider", + "规则「{}」选中的上游「{name}」在配置中不存在", decision.matched_rule ))); continue; @@ -1348,7 +1344,7 @@ async fn pipeline( tracing::info!(%rule, provider = %provider.name, "阶段二拒绝"); return Err(GatewayError::denied(reason)); } - Err(e) => return Err(GatewayError::config(format!("阶段二求值失败:{e}"))), + Err(e) => return Err(GatewayError::config(format!("规则求值失败:{e}"))), }; // 参数改写。**只在这里动 body,而且只动被点名的那几个字段** —— // 出站直通说过任何 body 改写都可能是缓存杀手,所以这是 @@ -1394,11 +1390,11 @@ async fn pipeline( ); chain.push(hop_failed( &provider.name, - format!("无法取得凭据:{e}"), + format!("无法获取凭据:{e}"), hop_started, )); last_err = Some(GatewayError::config(format!( - "provider `{}` 的凭据取不到:{e}", + "无法获取上游「{}」的凭据:{e}", provider.name ))); continue; @@ -1466,9 +1462,9 @@ async fn pipeline( // **429 要保住 429。**塌成 502 的话,客户端会当成「服务器 // 坏了」而不是「该退避了」,而它们该做的事完全不同。 last_err = Some(if r.status() == 429 { - GatewayError::rate_limited(format!("`{}` 限流了", provider.name)) + GatewayError::rate_limited(format!("上游「{}」触发限流", provider.name)) } else { - GatewayError::upstream(format!("`{}` 返回 {}", provider.name, r.status())) + GatewayError::upstream(format!("上游「{}」返回 {}", provider.name, r.status())) }); continue; } @@ -1528,7 +1524,7 @@ async fn pipeline( // 的错误,和一条只说「503」的错误,是两种产品:前者说明我们替 // 他做了工作,后者让他以为我们什么都没干。 if attempts.len() > 1 { - err.message = format!("{}(试过:{})", err.message, attempts.join(" → ")); + err.message = format!("{}(已尝试:{})", err.message, attempts.join(" → ")); } // 失败也必须有结局。少了它,UI 上那一行会永远停在「进行中」—— // 而「一直转圈」比「明确失败」更让人怀疑是我们卡住了。它由 @@ -1539,7 +1535,7 @@ async fn pipeline( if attempts.len() > 1 { tracing::info!( chain = %attempts.join(" → "), - "故障转移:最终由 {} 服务", + "故障转移:最终由 {} 响应", provider.name ); } @@ -1603,7 +1599,7 @@ async fn pipeline( // // **结局跟着流走,而不是只写在流的末尾。**客户端中途走掉时,末尾的 // 代码一行都不会执行,而上游已经为这次请求计了费(见 `crate::ending`)。 - let mut ending = ending.take().expect("发出开始事件时就放进去了"); + let mut ending = ending.take().expect("发出开始事件时已写入"); ending.responded(status.as_u16()); let chunks = upstream.bytes_stream(); // **中途断掉不能只是让流消失。**首字节已经发出去了,状态码和响应头 @@ -1700,11 +1696,11 @@ async fn pipeline( if blocked { tracing::warn!( provider = %wall_provider, tool = %v.tool, rule = %v.rule, - "切断响应流:上游返回了一个高危工具调用" + "已切断响应流:上游返回了高危工具调用" ); cut = Some(( GatewayError::denied(format!( - "`{}` 返回的 `{}` 调用命中「{}」({}),已切断。这个上游标记为不受信任。", + "上游「{}」(非官方端点)返回的 {} 调用命中规则「{}」({}),已切断响应", wall_provider, v.tool, v.rule, v.why )), v.safe_prefix, @@ -1783,7 +1779,7 @@ async fn pipeline( // // `source` 用这个错误自己的:上游断了是 `upstream`,被 // 防火墙切断是 `denied` —— 后者不是上游坏了,是策略拦的。 - ending.failed(err.source.slug(), format!("流中断:{}", err.message)); + ending.failed(err.source.slug(), format!("响应流中断:{}", err.message)); if is_sse { yield Ok(Bytes::from(err.sse_frame())); } @@ -1833,20 +1829,20 @@ pub async fn seed_latency(state: &AppState) { let hop = match crate::l1::hop_for(&rt.config, p) { Ok(h) => h, Err(why) => { - tracing::debug!(provider = %name, %why, "L1 垫不了底"); + tracing::debug!(provider = %name, %why, "该上游无法进行链路测速,不补充延迟样本"); continue; } }; let r = crate::l1::l1(&p.base_url, hop.as_ref()).await; if r.ok { - tracing::debug!(provider = %name, ms = r.total_ms, "L1 垫底"); + tracing::debug!(provider = %name, ms = r.total_ms, "以链路测速结果补充延迟样本"); state .latency .seed(&name, r.total_ms.min(u32::MAX as u64) as u32); } else { // **连都连不上的那家不垫。**它会因为「没样本」排在最后, // 而那正是对的 - tracing::debug!(provider = %name, "L1 连不上,不垫底"); + tracing::debug!(provider = %name, "链路测速无法连接,不补充延迟样本"); } } } @@ -1882,7 +1878,7 @@ pub async fn serve_following_config( // 通知来了但地址没变(比如又改回去了)—— 原样重来 continue; } - tracing::info!(from = %next, to = %want, "监听地址变了,重建监听器"); + tracing::info!(from = %next, to = %want, "监听地址已变化,重建监听器"); next = want; } } @@ -1897,9 +1893,9 @@ async fn serve_once( let listener = tokio::net::TcpListener::bind(addr).await?; let actual = listener.local_addr()?; if !state.runtime().allow.is_empty() { - tracing::info!(%actual, "网关已监听(有来源白名单)"); + tracing::info!(%actual, "网关已开始监听(启用来源地址白名单)"); } else { - tracing::info!(%actual, "网关已监听"); + tracing::info!(%actual, "网关已开始监听"); } // `into_make_service_with_connect_info` 是拿到对端地址的唯一办法 —— // 少了它,来源白名单收到的永远是 unwrap 出来的默认值。 diff --git a/crates/tw-gateway/src/toolwall.rs b/crates/tw-gateway/src/toolwall.rs index 5d81c206..5820f74d 100644 --- a/crates/tw-gateway/src/toolwall.rs +++ b/crates/tw-gateway/src/toolwall.rs @@ -99,7 +99,7 @@ fn complete_tool_calls(v: &Value) -> Vec<(String, String)> { let name = v .get("name") .and_then(|x| x.as_str()) - .unwrap_or("(没名字)") + .unwrap_or("(未命名)") .to_string(); out.push((name, input.to_string())); } @@ -200,7 +200,7 @@ impl Wall { let name = cb .get("name") .and_then(|x| x.as_str()) - .unwrap_or("(没名字)") + .unwrap_or("(未命名)") .to_string(); self.blocks.insert(index, (name, String::new())); self.tool_calls += 1; @@ -275,7 +275,7 @@ impl Wall { self.fired.push(r.id.clone()); out.push(Verdict { rule: r.id.clone(), - why: format!("{}。这段文字会进入下一轮的上下文。", r.why), + why: format!("{}。这段文字会进入下一轮对话的上下文", r.why), high: false, tool: "(响应正文)".into(), excerpt: excerpt(m.as_str()), diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index 5b8ac827..4fffa7f2 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -127,7 +127,7 @@ pub async fn proxy( ) { Ok(r) => r, Err(e) => { - let why = format!("上游地址不是合法的 WS 地址:{e}"); + let why = format!("上游地址不是合法的 WebSocket 地址:{e}"); ending.failed("config", why.clone()); close_with(client, &why).await; return; @@ -143,7 +143,7 @@ pub async fn proxy( req.headers_mut().insert(n, v); } _ => { - let why = format!("这家的请求头「{name}」里有不能放进请求头的字符"); + let why = format!("上游的请求头「{name}」包含请求头中不允许的字符"); ending.failed("config", why.clone()); close_with(client, &why).await; return; @@ -153,7 +153,7 @@ pub async fn proxy( let up = match dial(&upstream_url, req).await { Ok(x) => x, Err(e) => { - let why = format!("连不上上游的 WebSocket:{e}"); + let why = format!("无法连接上游的 WebSocket:{e}"); ending.failed("upstream", why.clone()); close_with(client, &why).await; return; @@ -206,10 +206,10 @@ async fn dial( }; let tcp = tokio::net::TcpStream::connect((host.as_str(), port)) .await - .map_err(|e| format!("连不上 {host}:{port}:{e}"))?; + .map_err(|e| format!("无法连接 {host}:{port}:{e}"))?; let io: Box = if tls { let name = rustls::pki_types::ServerName::try_from(host.clone()) - .map_err(|_| format!("`{host}` 不是一个能放进 SNI 的主机名"))?; + .map_err(|_| format!("{host} 不是有效的 TLS 主机名"))?; let conn = tokio_rustls::TlsConnector::from(crate::l1::tls_config()); Box::new(conn.connect(name, tcp).await.map_err(|e| e.to_string())?) } else { @@ -286,7 +286,7 @@ async fn pump( Message::Close(_) => break End::Closed, }; if let Err(e) = u_tx.send(out).await { - break End::Broke(format!("写给上游失败:{e}")); + break End::Broke(format!("向上游发送数据失败:{e}")); } } // 上游 → 客户端:先还原占位符,再过工具墙 @@ -306,7 +306,7 @@ async fn pump( for h in &hits { if h.high && p.cut && !deadly { why = format!( - "`{}` 返回的 `{}` 调用命中「{}」({}),已切断连接。这个上游标记为不受信任。", + "上游「{}」(非官方端点)返回的 {} 调用命中规则「{}」({}),已切断连接", p.provider, h.tool, h.rule, h.why ); } @@ -327,7 +327,7 @@ async fn pump( // **命中那一帧不发。**和 SSE 那条路同一条纪律: // 先判断再转发,而不是发完再说 let _ = c_tx.send(Message::Text( - "[ThinkWatch] 上游返回了一个高危工具调用,这条连接已切断。".into(), + "[ThinkWatch] 上游返回了高危工具调用,连接已切断".into(), )).await; break End::Cut(why); } diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index 70256628..5fc16a53 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -488,7 +488,7 @@ async fn reloading_from_zero_providers_to_one_starts_working_without_a_restart() let state = tw_gateway::AppState::new(cfg(vec![], vec![])).unwrap(); let gw = serve(state.clone()).await; let first = ask(gw).await; - assert!(first.contains("还没有配置任何上游"), "{first}"); + assert!(first.contains("尚未配置任何上游"), "{first}"); state.reload(cfg(vec![provider("a", a)], vec![])).unwrap(); assert!(ask(gw).await.contains("\"a\""), "加完上游还是不通"); @@ -508,7 +508,10 @@ async fn the_allow_list_is_reloaded_too() { c.listen.gateway.allow_from = vec!["10.0.0.0/8".into()]; state.reload(c).unwrap(); let after = ask(gw).await; - assert!(after.contains("不在允许的来源里"), "白名单没生效:{after}"); + assert!( + after.contains("不在允许的来源地址中"), + "白名单没生效:{after}" + ); } #[tokio::test] diff --git a/crates/tw-gateway/tests/m1_acceptance.rs b/crates/tw-gateway/tests/m1_acceptance.rs index 67781755..89473629 100644 --- a/crates/tw-gateway/tests/m1_acceptance.rs +++ b/crates/tw-gateway/tests/m1_acceptance.rs @@ -353,5 +353,5 @@ async fn a_single_model_lookup_obeys_the_same_allow_list_as_the_list() { let r = get("/v1/models/claude-opus-4".into()).await; assert_ne!(r.status(), 200, "**限制了的模型单点还是查得到**"); let body = r.text().await.unwrap(); - assert!(body.contains("没有叫"), "{body}"); + assert!(body.contains("不存在模型"), "{body}"); } diff --git a/crates/tw-gateway/tests/models.rs b/crates/tw-gateway/tests/models.rs index 9310aa98..15f2b9ce 100644 --- a/crates/tw-gateway/tests/models.rs +++ b/crates/tw-gateway/tests/models.rs @@ -279,7 +279,7 @@ async fn when_no_candidate_serves_the_model_the_error_names_each_one_and_why() { assert_eq!(status, 400, "{body}"); let msg = body["error"]["message"].as_str().unwrap(); assert!( - msg.contains("official-only") && msg.contains("relay 不提供该模型"), + msg.contains("official-only") && msg.contains("relay 未提供此模型"), "{msg}" ); diff --git a/crates/tw-gateway/tests/oauth.rs b/crates/tw-gateway/tests/oauth.rs index dc248785..493a3026 100644 --- a/crates/tw-gateway/tests/oauth.rs +++ b/crates/tw-gateway/tests/oauth.rs @@ -415,7 +415,7 @@ async fn without_a_config_manager_the_rotation_is_reported_as_not_persisted() { for one in &seen { assert_eq!(one.0, "p"); assert!(!one.1, "没写却说写了:{seen:?}"); - assert!(one.2.contains("写不回去"), "{seen:?}"); + assert!(one.2.contains("无法写回"), "{seen:?}"); } // 事件里一个 token 都不能有 assert!(!seen.iter().any(|s| s.2.contains("rt-")), "{seen:?}"); diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 778bd76b..7cbe32ba 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -755,7 +755,7 @@ async fn everything_broken_still_tries_rather_than_refusing() { let msg = body["error"]["message"].as_str().unwrap(); // 错误里要能看出「试过谁」—— 用户能看见故障转移在替他工作, // 这是信任的来源。 - assert!(msg.contains("试过"), "{msg}"); + assert!(msg.contains("已尝试"), "{msg}"); } /// 一个慢上游:每个请求要 `delay`,用来观察并发行为。 @@ -1596,7 +1596,7 @@ async fn a_health_check_works_before_any_upstream_is_configured() { .await .unwrap(); assert_ne!(real.status(), 200); - assert!(real.text().await.unwrap().contains("还没有配置任何上游")); + assert!(real.text().await.unwrap().contains("尚未配置任何上游")); } /// **错误必须用入站方言的原生格式返回。**一个 Anthropic 客户端 diff --git a/crates/tw-pricing/src/lib.rs b/crates/tw-pricing/src/lib.rs index 9911058c..d0c5402b 100644 --- a/crates/tw-pricing/src/lib.rs +++ b/crates/tw-pricing/src/lib.rs @@ -88,9 +88,9 @@ pub fn to_micros(usd: f64) -> Micros { #[derive(Debug, thiserror::Error)] pub enum PricingError { - #[error("内置价目表解不开,这是个打包错误:{0}")] + #[error("内置价目表无法解析:{0}")] Snapshot(String), - #[error("价格数据读不通:{0}")] + #[error("价格数据无法解析:{0}")] Dataset(String), } diff --git a/crates/tw-pricing/src/sheet.rs b/crates/tw-pricing/src/sheet.rs index 692bae04..55b49dfe 100644 --- a/crates/tw-pricing/src/sheet.rs +++ b/crates/tw-pricing/src/sheet.rs @@ -102,24 +102,24 @@ pub struct PerMillion { #[derive(Debug, thiserror::Error, PartialEq)] pub enum SheetError { - #[error("有一张价目表没有名字")] + #[error("存在未填写名称的价目表")] EmptyName, - #[error("价目表名称「{0}」首尾不能有空白")] + #[error("价目表名称「{0}」首尾不能包含空白")] PaddedName(String), - #[error("价目表名字重复:{0}")] + #[error("价目表名称重复:{0}")] DuplicateName(String), - #[error("价目表「{sheet}」的倍率 {value} 不对:要是一个大于 0 的数")] + #[error("价目表「{sheet}」的倍率 {value} 无效,倍率必须大于 0")] BadMultiplier { sheet: String, value: f64 }, - #[error("价目表「{sheet}」里有一个模型没写名字")] + #[error("价目表「{sheet}」中存在未填写名称的模型")] EmptyModel { sheet: String }, - #[error("价目表「{sheet}」里 `{model}` 的{field}是 {value}:单价不能是负数")] + #[error("价目表「{sheet}」中模型 {model} 的{field}为 {value},单价不能为负数")] BadPrice { sheet: String, model: String, field: &'static str, value: f64, }, - #[error("价目表「{sheet}」里 `{model}` 的长上下文单价要输入、输出一起写")] + #[error("价目表「{sheet}」中模型 {model} 的长上下文输入单价与输出单价需要同时填写")] HalfLongContext { sheet: String, model: String }, } diff --git a/crates/tw-pricing/src/table.rs b/crates/tw-pricing/src/table.rs index 21fd48e7..d5e4b4a5 100644 --- a/crates/tw-pricing/src/table.rs +++ b/crates/tw-pricing/src/table.rs @@ -144,7 +144,7 @@ fn parse_dataset(raw: &[u8]) -> Result, PricingError .collect(); if prices.is_empty() { return Err(PricingError::Dataset( - "里面一个带价格的模型都没有 —— 多半不是那份数据集".into(), + "其中没有任何带价格的模型,可能不是价格数据集".into(), )); } Ok(prices) diff --git a/crates/tw-redact/src/stream.rs b/crates/tw-redact/src/stream.rs index 4e121c05..d1e744d8 100644 --- a/crates/tw-redact/src/stream.rs +++ b/crates/tw-redact/src/stream.rs @@ -175,7 +175,8 @@ impl ByteRestorer { }; // 尾巴上那半个字符留到下一块 self.partial = buf[valid..].to_vec(); - let text = std::str::from_utf8(&buf[..valid]).expect("valid_up_to 保证这一段是合法的"); + let text = + std::str::from_utf8(&buf[..valid]).expect("valid_up_to 之前的字节是合法的 UTF-8"); self.inner.process(text).into_bytes() } diff --git a/crates/tw-scan/data/rules.yaml b/crates/tw-scan/data/rules.yaml index 9d84c95f..2812c2a4 100644 --- a/crates/tw-scan/data/rules.yaml +++ b/crates/tw-scan/data/rules.yaml @@ -16,28 +16,28 @@ version: 1 injection: - id: ignore-previous pattern: '(?i)ignore\s+(all\s+)?(previous|above|prior)[^\n]{0,20}instructions' - why: 提示注入最经典的开头 + why: 典型的提示注入开头 - id: disregard pattern: '(?i)disregard\s+(the\s+)?(system|above|previous)' - why: 同上,换了个动词 + why: 典型的提示注入开头,使用 disregard 一类的动词 - id: you-are-now pattern: '(?i)you\s+are\s+now\s+(a|an)\s' - why: 试图重设模型的身份 + why: 试图重新设定模型的身份 - id: 忽略指令 pattern: '忽略(以上|之前|上面|前面)(的)?(所有)?(指令|要求|规则)' - why: 中文的提示注入 + why: 中文提示注入,要求忽略先前的指令 - id: 新指令 pattern: '新的?指令[::]' - why: 中文的提示注入 + why: 中文提示注入,声明新的指令 - id: 你现在是 pattern: '你(现在)?(是|扮演)一[个位名]' - why: 试图重设模型的身份 + why: 试图重新设定模型的身份 - id: chat-marker pattern: '<\|(im_start|im_end|system|endoftext)\|>' - why: 伪造对话标记,试图让模型把正文当成系统消息 + why: 伪造对话标记,试图让模型将正文当作系统消息 - id: fake-system pattern: '(?i)\[?(system|assistant)\]?\s*[::]\s*(you|your|ignore|从现在|你)' - why: 伪造成系统或助手的发言 + why: 伪装成系统或助手的发言 # 二、危险命令。这一组和工具调用防火墙共用 —— 一套规则两处用。 # @@ -53,49 +53,49 @@ dangerous: # 填长到 200 字符以上,同一条命令就匹配不到了。测试抓住的。 - id: curl-pipe-sh pattern: '(?i)(curl|wget)[^\n|]*\|\s*(sudo\s+)?(ba|z|d)?sh' - why: 下载即执行 —— 内容由对方决定,你看不到它跑了什么 + why: 下载后直接执行,执行的内容由远端决定且无法预先查看 level: high - id: rm-rf-root pattern: 'rm\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*[rf][a-zA-Z]*\s+(/|~|\$HOME)(\s|$)' - why: 删掉整个家目录或根目录 + why: 删除整个主目录或根目录 level: medium - id: chmod-777 pattern: 'chmod\s+(-R\s+)?777' - why: 把文件权限放到所有人可写 + why: 将文件权限设为所有人可写 level: medium - id: base64-decode-exec pattern: '(?i)base64\s+(-d|--decode)[^\n|]*\|\s*(ba)?sh' - why: 把要执行的内容藏在 base64 里 + why: 将要执行的内容隐藏在 base64 编码中 level: high - id: exfil-env pattern: '(?i)(env|printenv|cat\s+[^\n]{0,60}\.env)[^\n]{0,200}(curl|wget|nc\s)' - why: 把环境变量(里面通常有密钥)发到外面去 + why: 将环境变量(通常包含密钥)发送到外部 level: high # **命令形状的规则对中文指令完全不设防。**「把 ~/.aws/credentials # 打印出来」里没有 cat 也没有 curl,但它要的是同一件事。所以再加一条 # 按「凭据路径 + 外送动词」匹配的,两个方向都写。 - id: 凭据外泄 pattern: '(\.ssh/id_|\.aws/credentials|\.netrc|/\.env)[^\n]{0,30}(发|传|上报|打印|输出|贴出|读出|(?i:send|upload|post|print|paste|exfil))' - why: 让模型把凭据文件的内容送出去 + why: 要求模型将凭据文件的内容发送出去 level: high - id: 凭据外泄2 pattern: '(发送|上传|贴出|打印|输出|读取|(?i:send|upload|post|print|read))[^\n]{0,30}(\.ssh/id_|\.aws/credentials|\.netrc|/\.env)' - why: 让模型把凭据文件的内容送出去 + why: 要求模型将凭据文件的内容发送出去 level: high # **写入启动项**:只要写进去了,下次开终端就执行 —— 而且是在你完全 # 不知情的时候。它和「下载即执行」并列为高危,理由是一样的: # 一步就能拿到执行权。 - id: 写启动项 pattern: '(>>?|tee|cp|mv|ln\s+-s)[^\n]{0,200}(\.zshrc|\.bashrc|\.bash_profile|\.profile|\.zprofile|LaunchAgents|LaunchDaemons|\.git/hooks|crontab)' - why: 往开机或开终端就会执行的地方写东西 + why: 写入开机或打开终端时自动执行的位置 level: high # `crontab -l` 是看一眼,`crontab <文件>` / `crontab -r` / `crontab -` # 才是动手。分不开的话,这条规则会在每次「帮我看看定时任务」时误报。 - id: crontab-install pattern: 'crontab\s+(-r\b|-\s*$|[^\s-][^\n]{0,40})' - why: 装一个定时执行的任务,或者把现有的全删掉 + why: 安装定时任务,或删除全部现有定时任务 level: high - id: ssh-key-read pattern: '(?i)(cat|cp|scp|curl)[^\n]{0,200}(\.ssh/id_|\.aws/credentials|\.netrc)' - why: 读私钥或云凭据 + why: 读取私钥或云服务凭据 level: high diff --git a/crates/tw-scan/src/hidden.rs b/crates/tw-scan/src/hidden.rs index 9fd9af9a..783b9baa 100644 --- a/crates/tw-scan/src/hidden.rs +++ b/crates/tw-scan/src/hidden.rs @@ -42,13 +42,15 @@ impl Kind { /// 「U+200B ZWSP」对绝大多数人不构成信息。 pub fn why(&self) -> &'static str { match self { - Kind::ZeroWidth => "零宽字符:你看不见它,模型看得见。", + Kind::ZeroWidth => "零宽字符:在编辑器中不可见,但会被模型读取。", Kind::Tag => { - "Unicode 标签字符:在任何编辑器里都完全不可见,但会原样进入模型的上下文。一整段指令可以藏在这里。" + "Unicode 标签字符:在编辑器中完全不可见,但会原样进入模型上下文,可用于隐藏整段指令。" } - Kind::Bidi => "双向控制符:能让屏幕上的显示顺序和实际字节顺序不一致。", - Kind::Homoglyph => "同形异义字:长得像拉丁字母,其实不是。常用来伪装命令和域名。", - Kind::PrivateUse => "私用区码位:没有标准含义,出现在指令文件里本身就可疑。", + Kind::Bidi => "双向控制符:可使屏幕上的显示顺序与实际字符顺序不一致。", + Kind::Homoglyph => { + "同形字符:外观与拉丁字母相同,实际是其他字符,常用于伪装命令和域名。" + } + Kind::PrivateUse => "私用区码位:没有标准含义,出现在指令文件中即属可疑。", } } } diff --git a/crates/tw-scan/src/report.rs b/crates/tw-scan/src/report.rs index d85d5499..4f6b5267 100644 --- a/crates/tw-scan/src/report.rs +++ b/crates/tw-scan/src/report.rs @@ -310,11 +310,11 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { path: src.path.clone(), line: h.line, title: format!( - "{} 里有{}", + "{} 中含有{}", src.kind.label(), h.kind.why().split(':').next().unwrap_or("隐藏字符") ), - detail: format!("{} {}", h.kind.why(), src.kind.why()), + detail: format!("{}{}", h.kind.why(), src.kind.why()), excerpt: h.line_text, }); } @@ -336,9 +336,9 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { client: src.client.to_string(), path: src.path.clone(), line, - title: format!("MCP server `{}` 在远端", m.name), + title: format!("MCP server「{}」位于远端", m.name), detail: format!( - "它指向 {}。用到它的时候,相关上下文会发到那台服务器上。", + "该 server 的地址为 {},使用时相关上下文会发送到该服务器。", m.url.as_deref().unwrap_or("") ), excerpt, @@ -372,8 +372,10 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { client: src.client.to_string(), path: src.path.clone(), line, - title: format!("skill `{name}` 声明了 allowed-tools: [\"*\"]"), - detail: "它能用任何工具。这可能完全正当,但值得你看一眼是不是真的需要。".into(), + title: format!("skill「{name}」声明了 allowed-tools: [\"*\"]"), + detail: + "该 skill 可以使用任何工具。这可能是正常需要,建议确认是否确实需要此权限。" + .into(), excerpt, }); } @@ -422,8 +424,8 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { client: src.client.to_string(), path: src.path.clone(), line, - title: format!("{} 里命中「{}」", src.kind.label(), rule.id), - detail: format!("{} {}", rule.why, src.kind.why()), + title: format!("{} 中命中规则「{}」", src.kind.label(), rule.id), + detail: format!("{}。{}", rule.why, src.kind.why()), excerpt, }); } diff --git a/crates/tw-scan/src/rules.rs b/crates/tw-scan/src/rules.rs index 511f9948..52df5156 100644 --- a/crates/tw-scan/src/rules.rs +++ b/crates/tw-scan/src/rules.rs @@ -57,7 +57,7 @@ pub struct RuleFile { #[derive(Debug, thiserror::Error)] pub enum RuleError { - #[error("内置规则文件坏了:{0}")] + #[error("内置规则文件无法解析:{0}")] Builtin(String), } @@ -131,7 +131,7 @@ fn compile(spec: &RuleSpec, group: &'static str, custom: bool, out: &mut Rules) // 工作的安全功能等于没有。但它必须**大声**说出来 —— 静默失效 // 比没有更糟,因为用户以为它在 Err(e) => out.warnings.push(format!( - "规则 `{}` 的正则写不通,这一条没有生效:{e}", + "规则「{}」的正则表达式有误,该规则未生效:{e}", spec.id )), } @@ -166,7 +166,7 @@ pub fn build(user: &tw_config::ScanRules) -> Result { for id in &user.disable { if !out.disabled.contains(id) { out.warnings - .push(format!("`{id}` 不是内置规则的 id,这一条停用没有生效")); + .push(format!("「{id}」不是内置规则的 id,停用未生效")); } } for spec in &user.add { diff --git a/crates/tw-scan/src/sources.rs b/crates/tw-scan/src/sources.rs index 94e108ca..673f6c1e 100644 --- a/crates/tw-scan/src/sources.rs +++ b/crates/tw-scan/src/sources.rs @@ -66,16 +66,12 @@ impl Kind { /// 为什么它危险。**说清「它能干什么」**,别只说「它是什么」。 pub fn why(&self) -> &'static str { match self { - Kind::Hooks => { - "hook 在工具调用前后直接执行 shell 命令 —— 不需要模型参与就能拿到执行权。" - } - Kind::Mcp => { - "MCP server 配置指定的是一个可执行程序和它的参数,等同于「运行这个二进制」。" - } + Kind::Hooks => "hook 在工具调用前后直接执行 shell 命令,无需模型参与即可获得执行权限。", + Kind::Mcp => "MCP server 配置指定了可执行程序及其参数,相当于直接运行该程序。", Kind::Skill => "SKILL.md 的内容会被注入模型上下文,成为指令。", Kind::Command => "斜杠命令的内容会被注入模型上下文,成为指令。", - Kind::Agent => "subagent 定义会被注入上下文,而且可能声明宽松的工具权限。", - Kind::Instructions => "这个文件会被自动读入上下文。", + Kind::Agent => "subagent 定义会被注入模型上下文,并可能声明宽松的工具权限。", + Kind::Instructions => "该文件会被自动读入模型上下文。", } } } @@ -264,7 +260,7 @@ mod tests { // 危险度排序不是装饰:界面按它排,高危项发通知。 assert!(Kind::Hooks < Kind::Mcp); assert!(Kind::Mcp < Kind::Skill); - assert!(Kind::Hooks.why().contains("不需要模型参与")); + assert!(Kind::Hooks.why().contains("无需模型参与")); } #[test] diff --git a/crates/tw-scan/src/watch.rs b/crates/tw-scan/src/watch.rs index 5590cceb..d794b978 100644 --- a/crates/tw-scan/src/watch.rs +++ b/crates/tw-scan/src/watch.rs @@ -29,7 +29,7 @@ pub const DEBOUNCE: Duration = Duration::from_millis(300); #[derive(Debug, thiserror::Error)] pub enum WatchError { - #[error("盯不住 {path}:{source}")] + #[error("无法监听 {path} 的变化:{source}")] Start { path: PathBuf, source: notify::Error, diff --git a/crates/tw-scan/tests/scan.rs b/crates/tw-scan/tests/scan.rs index 3366ed8b..2d35ac57 100644 --- a/crates/tw-scan/tests/scan.rs +++ b/crates/tw-scan/tests/scan.rs @@ -131,7 +131,7 @@ fn a_hook_that_downloads_and_executes_is_the_highest_level() { .find(|f| f.rule == "curl-pipe-sh") .unwrap_or_else(|| panic!("{:#?}", r.findings)); assert_eq!(f.level, Level::High); - assert!(f.detail.contains("不需要模型参与"), "{}", f.detail); + assert!(f.detail.contains("无需模型参与"), "{}", f.detail); // 最高级的排在最前面 —— 界面直接按这个顺序画 assert_eq!(r.findings[0].rule, "curl-pipe-sh"); } @@ -189,7 +189,7 @@ fn a_skill_claiming_every_tool_is_reported_without_being_called_malicious() { .find(|f| f.rule == "over-broad-tools") .unwrap(); assert_eq!(f.level, Level::Medium); - assert!(f.detail.contains("可能完全正当"), "{}", f.detail); + assert!(f.detail.contains("这可能是正常需要"), "{}", f.detail); let sk = r.skills.iter().find(|s| s.name == "万能").unwrap(); assert_eq!(sk.allowed_tools, vec!["*".to_string()]); } @@ -291,7 +291,7 @@ fn a_remote_mcp_server_is_told_apart_from_one_that_runs_a_binary() { assert_eq!(f.len(), 1, "只有第三方那个该报:{:#?}", r.findings); // **级别是提示,不是高危。**它多半是用户自己有意加的 assert_eq!(f[0].level, Level::Low); - assert!(f[0].detail.contains("会发到那台服务器"), "{}", f[0].detail); + assert!(f[0].detail.contains("会发送到该服务器"), "{}", f[0].detail); } #[test] diff --git a/crates/tw-secret/src/lib.rs b/crates/tw-secret/src/lib.rs index 10722dcb..3fee107a 100644 --- a/crates/tw-secret/src/lib.rs +++ b/crates/tw-secret/src/lib.rs @@ -17,9 +17,9 @@ pub use mask::{ pub enum SecretError { #[error("环境变量 {0} 未设置")] MissingEnv(String), - #[error("第 {pos} 个字符处的 ${{...}} 没有闭合")] + #[error("第 {pos} 个字符处的 ${{...}} 未闭合")] Unterminated { pos: usize }, - #[error("空的变量名:${{}}")] + #[error("变量名为空:${{}}")] EmptyName, } diff --git a/crates/tw-store/src/blobs.rs b/crates/tw-store/src/blobs.rs index f0b78470..f191cfb3 100644 --- a/crates/tw-store/src/blobs.rs +++ b/crates/tw-store/src/blobs.rs @@ -89,7 +89,7 @@ impl Blobs { true } Err(e) => { - tracing::debug!(path = %p.display(), "body 写不下:{e}"); + tracing::debug!(path = %p.display(), "请求体写入失败:{e}"); false } } diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 6aa60646..35bdbb45 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -41,7 +41,7 @@ const NO_USAGE: &str = "(cost_micros IS NULL AND input_tokens IS NULL AND error #[derive(Debug, thiserror::Error)] pub enum DbError { - #[error("打不开 {path}:{source}")] + #[error("无法打开 {path}:{source}")] Open { path: String, source: rusqlite::Error, @@ -49,7 +49,7 @@ pub enum DbError { /// 库是更新版本的程序建的。**只能读不能写** —— 硬写会让那个版本的 /// 数据变成半新半旧,而用户回到新版本时已经修不回来了。 #[error( - "数据库的 schema 版本是 {found},这个版本的 twcore 只认到 {supported}。请升级应用;实在要用旧版的话,把 {path} 挪走会重新建一个空库(历史记录会看不见,但不会丢)。" + "数据库的 schema 版本为 {found},当前版本的 twcore 最高支持 {supported}。请升级应用;如需继续使用当前版本,可将 {path} 移至其他位置,程序会新建空数据库,原有请求记录不会被删除" )] TooNew { found: i64, @@ -1737,7 +1737,7 @@ mod tests { assert!(matches!(e, DbError::TooNew { .. }), "{e:?}"); let m = e.to_string(); assert!(m.contains("升级"), "{m}"); - assert!(m.contains("不会丢"), "得说清历史记录的下场:{m}"); + assert!(m.contains("不会被删除"), "得说清历史记录的下场:{m}"); } #[test] diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index afcb429f..57b2cf0d 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -393,7 +393,7 @@ impl Recorder { kind: secret.clone(), masked: masked.clone(), }) { - tracing::debug!("发现记不下来:{e}"); + tracing::debug!("泄漏记录写入失败:{e}"); } } // 配置事件、额度事件、扫描告警都不是请求,不落这张表。 @@ -547,7 +547,7 @@ impl Recorder { fn write(&self, r: RequestRow) { if let Err(e) = self.db.insert(&r) { // **不往回抛。**观测挂了,代理照跑。 - tracing::debug!(id = r.id, "请求记不下来:{e}"); + tracing::debug!(id = r.id, "请求记录写入失败:{e}"); } } @@ -572,7 +572,7 @@ impl Recorder { // 得知道那不是 bug。 tracing::warn!( free_mb = free / 1024 / 1024, - "磁盘级别变了:{}", + "磁盘状态已变化:{}", next.label() ); self.level = next; @@ -584,7 +584,7 @@ impl Recorder { let freed = self.blobs.gc(now_ms, keep_days, max_bytes); let cutoff = now_ms - (metadata_keep_days as i64) * 86_400_000; match self.db.prune_before(cutoff) { - Ok(n) if n > 0 => tracing::info!(rows = n, "清掉了过期的请求记录"), + Ok(n) if n > 0 => tracing::info!(rows = n, "已清理过期的请求记录"), Err(e) => tracing::debug!("清理请求记录失败:{e}"), _ => {} } diff --git a/crates/tw-store/src/task.rs b/crates/tw-store/src/task.rs index 8be4e873..5c382c01 100644 --- a/crates/tw-store/src/task.rs +++ b/crates/tw-store/src/task.rs @@ -61,7 +61,7 @@ pub fn spawn( // **落后了就跳过,不要退出。**广播通道满的时候丢的是 // 观测记录,而退出会让之后的记录全部丢失。 Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => { - tracing::warn!("观测落后了 {n} 条,这些请求不会出现在历史里"); + tracing::warn!("请求记录处理不及,{n} 条请求未能记录"); } Err(tokio::sync::broadcast::error::RecvError::Closed) => return, } @@ -81,7 +81,7 @@ pub fn spawn( crate::blobs::MAX_BYTES, ); if freed > 0 { - tracing::info!(mb = freed / 1024 / 1024, "回收了过期的请求体"); + tracing::info!(mb = freed / 1024 / 1024, "已回收过期的请求体"); } } }); diff --git a/crates/tw-yaml/src/edit.rs b/crates/tw-yaml/src/edit.rs index c7e4ed4f..7639339e 100644 --- a/crates/tw-yaml/src/edit.rs +++ b/crates/tw-yaml/src/edit.rs @@ -49,10 +49,10 @@ pub fn put(text: &str, path: &[Step], value: Put<'_>) -> Result) -> Result add_key(text, &before, path, value)?, }; let after = nodes(&out) - .map_err(|e| PatchError::SelfCheck(format!("写完 `{}` 之后解析不了:{e}", show(path))))?; + .map_err(|e| PatchError::SelfCheck(format!("写入 {} 后配置无法解析:{e}", show(path))))?; untouched_outside(&before, &after, path)?; lands_as(&after, path, &frag)?; Ok(out) @@ -105,7 +105,7 @@ pub fn remove_key(text: &str, path: &[Step]) -> Result { } if !matches!(parent_node.kind, NodeKind::Map) || is_flow(text, parent_node) { return Err(PatchError::NotFound(format!( - "{}(行内映射里的键只能整段改写)", + "{}(行内映射中的键只能整体修改)", show(path) ))); } @@ -121,7 +121,7 @@ pub fn remove_key(text: &str, path: &[Step]) -> Result { // 而不是一个空映射 —— 整项删是 `remove` 的事 Some(Step::Index(_)) => { return Err(PatchError::NotFound(format!( - "{}(这是那一项里唯一的键,要删就删整项)", + "{}(该项只有这一个键,请删除整项)", show(path) ))); } @@ -156,10 +156,10 @@ pub fn remove_key(text: &str, path: &[Step]) -> Result { }; let after = nodes(&out) - .map_err(|e| PatchError::SelfCheck(format!("删掉 `{}` 之后解析不了:{e}", show(path))))?; + .map_err(|e| PatchError::SelfCheck(format!("删除 {} 后配置无法解析:{e}", show(path))))?; if after.iter().any(|n| n.path == path) { return Err(PatchError::SelfCheck(format!( - "删完之后 `{}` 还在", + "删除后 {} 仍然存在", show(path) ))); } @@ -207,10 +207,10 @@ pub fn replace_item( let mut path = seq_path.to_vec(); path.push(Step::Index(index)); let after = nodes(&out) - .map_err(|e| PatchError::SelfCheck(format!("换掉 `{}` 之后解析不了:{e}", show(&path))))?; + .map_err(|e| PatchError::SelfCheck(format!("替换 {} 后配置无法解析:{e}", show(&path))))?; if count_items(&after, seq_path) != count { return Err(PatchError::SelfCheck(format!( - "换完之后 `{}` 的项数变了", + "替换后 {} 的项数发生了变化", show(seq_path) ))); } @@ -335,13 +335,13 @@ fn add_key(text: &str, all: &[Node], path: &[Step], value: Put<'_>) -> Result Result { NodeKind::Scalar { .. } | NodeKind::Alias => Ok(n.bytes.end.min(text.len())), NodeKind::Map | NodeKind::Seq if is_flow(text, n) => flow_end(text, n.bytes.start) .map(|i| i + 1) - .ok_or_else(|| PatchError::NotFound(format!("{}(行内写法没收尾)", show(&n.path)))), + .ok_or_else(|| PatchError::NotFound(format!("{}(行内写法未闭合)", show(&n.path)))), NodeKind::Map | NodeKind::Seq => { block_end(text, all, &n.path).ok_or_else(|| PatchError::NotFound(show(&n.path))) } @@ -471,7 +471,7 @@ fn untouched_outside(before: &[Node], after: &[Node], path: &[Step]) -> Result<( .map(|(x, _)| show(x.0)) .unwrap_or_else(|| format!("节点数 {} → {}", b.len(), a.len())); return Err(PatchError::SelfCheck(format!( - "写 `{}` 的时候动到了别处({diff})", + "写入 {} 时修改了其他位置({diff})", show(path) ))); } @@ -491,7 +491,7 @@ fn lands_as(after: &[Node], path: &[Step], frag: &[Node]) -> Result<(), PatchErr .collect(); if got != want { return Err(PatchError::SelfCheck(format!( - "`{}` 写完读回来和要写的不一样", + "{} 写入后读回的值与预期不一致", show(path) ))); } diff --git a/crates/tw-yaml/src/lib.rs b/crates/tw-yaml/src/lib.rs index 3dd74bca..995fba43 100644 --- a/crates/tw-yaml/src/lib.rs +++ b/crates/tw-yaml/src/lib.rs @@ -59,29 +59,23 @@ impl From for Step { #[derive(Debug, thiserror::Error, PartialEq)] pub enum PatchError { - #[error("这份 YAML 解析不了:{0}")] + #[error("YAML 无法解析:{0}")] Parse(String), - #[error("配置里没有 `{0}` 这个位置")] + #[error("无法在配置中定位 {0}")] NotFound(String), - #[error("`{0}` 不是一个标量 —— 只有标量能这样改;结构性的增删走另一条路")] + #[error("{0} 不是标量值,只有标量值可以直接修改")] NotScalar(String), /// **写之前的最后一道闸。**改完在内存里重新解析一遍,对不上就拒绝 /// 写入。开销几百微秒,换来「永远不会写出一个自己都解析不了的文件」。 - #[error("补丁自检没过:{0}。**没有写盘。**这是个 bug,请把配置文件贴到 issue 里")] + #[error("配置修改自检未通过,未写入文件:{0}")] SelfCheck(String), /// 同一个 map 里出现了两个同名的键。 - #[error( - "`{0}` 在配置里出现了不止一次。同名的键谁生效各家解析器并不一致,改错一个的表现是「改了却没生效」—— 请先手动删掉重复的那个" - )] + #[error("{0} 在配置中重复出现,修改后可能不生效,请先手动删除重复的项")] Duplicate(String), - #[error( - "`{0}` 是一个多行块标量(`|` / `>`)。缩进在这里是内容的一部分,改错一格就改了值 —— 请直接编辑配置文件" - )] + #[error("{0} 是多行文本块(| 或 >),无法自动修改,请直接编辑配置文件")] BlockScalar(String), /// 锚点和别名让「改一处」不再是改一处。 - #[error( - "`{0}` 落在 YAML 的锚点/别名(`&x` / `*x`)里。改它会同时改掉引用它的每一处,所以这里不动它 —— 请直接编辑配置文件" - )] + #[error("{0} 位于 YAML 锚点或别名(&x / *x)中,修改会影响所有引用处,请直接编辑配置文件")] AnchorOrAlias(String), } @@ -471,11 +465,11 @@ pub fn set(text: &str, path: &[Step], value: &Scalar) -> Result Result Result { let after = nodes(&out).map_err(|e| { - PatchError::SelfCheck(format!("改完 `{}` 之后解析不了:{e}", show(seq_path))) + PatchError::SelfCheck(format!("修改 {} 后配置无法解析:{e}", show(seq_path))) })?; let got = count_items(&after, seq_path); if got != want { return Err(PatchError::SelfCheck(format!( - "改完之后 `{}` 有 {got} 项,应该是 {want} 项", + "修改后 {} 有 {got} 项,预期为 {want} 项", show(seq_path) ))); } diff --git a/crates/tw-yaml/tests/preserve.rs b/crates/tw-yaml/tests/preserve.rs index 363f9a56..5b48e7b8 100644 --- a/crates/tw-yaml/tests/preserve.rs +++ b/crates/tw-yaml/tests/preserve.rs @@ -294,7 +294,7 @@ fn a_duplicate_key_is_refused_rather_than_guessed() { let y = "a:\n k: 1\n k: 2\n"; let e = set(y, &path!["a", "k"], &Scalar::Int(9)).unwrap_err(); assert!(matches!(e, PatchError::Duplicate(_)), "{e:?}"); - assert!(e.to_string().contains("不止一次"), "{e}"); + assert!(e.to_string().contains("重复出现"), "{e}"); } #[test] diff --git a/crates/tw-yaml/tests/property.rs b/crates/tw-yaml/tests/property.rs index e37afe5e..a05144d9 100644 --- a/crates/tw-yaml/tests/property.rs +++ b/crates/tw-yaml/tests/property.rs @@ -443,7 +443,7 @@ fn removing_a_key_removes_that_entry_and_nothing_else() { let out = match remove_key(&doc, &target.path) { Ok(o) => o, // 列表项里唯一的键:明确拒绝,不是失败 - Err(PatchError::NotFound(m)) if m.contains("唯一的键") => continue, + Err(PatchError::NotFound(m)) if m.contains("只有这一个键") => continue, Err(PatchError::AnchorOrAlias(_)) | Err(PatchError::Duplicate(_)) => continue, Err(e) => panic!("seed {seed}:{} 删不掉:{e}\n{doc}", show(&target.path)), };