diff --git a/crates/tw-adopt/src/clients.rs b/crates/tw-adopt/src/clients.rs index ea456152..e1f9f6cc 100644 --- a/crates/tw-adopt/src/clients.rs +++ b/crates/tw-adopt/src/clients.rs @@ -47,8 +47,10 @@ impl TakesEffect { /// 接管提示和诊断结论里的那一句。 pub fn note(&self) -> &'static str { match self { - TakesEffect::Immediately => "下一个请求即使用新配置。", - TakesEffect::OnRestart => "重新打开终端后生效,在此之前网关不会收到该客户端的请求。", + TakesEffect::Immediately => "The next request uses the new configuration.", + TakesEffect::OnRestart => { + "It takes effect once the terminal is reopened; until then the gateway sees nothing from this client." + } } } /// 该不该设「还没收到请求」的超时提示。 @@ -81,8 +83,10 @@ impl Verified { /// 命令行里的说法。 pub fn note(&self) -> &'static str { match self { - Verified::Measured => "已在本机实际运行验证", - Verified::FieldsOnly => "字段名已查证,尚未在本机实际运行验证", + Verified::Measured => "checked by actually running it on this machine", + Verified::FieldsOnly => { + "the field names are verified; it has not been run on this machine" + } } } } @@ -189,9 +193,9 @@ pub fn adoptable() -> Vec { // **`settings.local.json` 优先级更高。**cc-switch #6828 栽在这里 shadowed_by: &[".claude/settings.local.json"], costs: &[ - "接口地址不是官方域名时,Remote Control 和语音输入不可用。", - "MCP tool search 将默认关闭。", - "Claude Code 可能会显示一次欢迎页,关闭即可。", + "Remote Control and voice input do not work when the endpoint is not an official domain.", + "MCP tool search is off by default.", + "Claude Code may show its welcome screen once; closing it is enough.", ], verified: Verified::FieldsOnly, marker: &[".claude"], @@ -216,8 +220,8 @@ pub fn adoptable() -> Vec { // 所以它不构成遮蔽 —— 但它确实存在,值得在诊断里提一句 shadowed_by: &[], costs: &[ - "Codex CLI 不从网关获取模型列表,自定义模型名无效,模型列表以本地的模型目录文件为准。", - "修改后需要重新打开终端。", + "Codex CLI does not read the model list from the gateway, so a custom model name has no effect; its local model catalogue decides.", + "The terminal has to be reopened afterwards.", ], verified: Verified::Measured, marker: &[".codex"], @@ -232,7 +236,7 @@ pub fn adoptable() -> Vec { format: Format::Json, takes_effect: TakesEffect::OnRestart, shadowed_by: &[], - costs: &["修改后需要重新启动 opencode。"], + costs: &["opencode has to be restarted afterwards."], verified: Verified::FieldsOnly, marker: &[".config/opencode", ".local/share/opencode"], process: &["opencode"], @@ -248,7 +252,9 @@ pub fn adoptable() -> Vec { shadowed_by: &[], // **只算部分接管**:Zed 的密钥走它自己的凭据存储,不在 // settings.json 里,我们写不进去。 - costs: &["Zed 的密钥不保存在配置文件中,需要在 Zed 的设置界面中手动填写一次。"], + costs: &[ + "Zed keeps its key outside the configuration file, so it has to be filled in once in Zed's settings.", + ], verified: Verified::FieldsOnly, marker: &[".config/zed"], process: &["Zed"], @@ -265,8 +271,8 @@ pub fn adoptable() -> Vec { // 我们只写 home 那一份,所以项目里的会盖住它 shadowed_by: &[], costs: &[ - "Aider 依次读取主目录、Git 项目根目录和当前目录中的配置,后读取的会覆盖先读取的,接管只修改主目录中的配置。", - "修改后需要重新启动 Aider。", + "Aider reads the home directory, then the Git project root, then the current directory, and each one overrides the last; only the home directory is changed here.", + "Aider has to be restarted afterwards.", ], verified: Verified::FieldsOnly, // 没接管过的用户本来就没有这个文件,所以它自己就是那个痕迹 @@ -304,25 +310,25 @@ pub fn manual_only() -> Vec { vec![ ManualOnly { name: "Cursor", - steps: "在 Cursor 的「Settings → Models」中开启 Override OpenAI Base URL,填写 {v1}。", - caveat: "Tab 补全与 inline edit 仍由 Cursor 自身的服务处理,不经过网关,因此只能部分接管。", + steps: "In Cursor, under Settings → Models, turn on Override OpenAI Base URL and enter {v1}.", + caveat: "Tab completion and inline edit still go to Cursor's own service rather than the gateway, so only part of Cursor is covered.", }, ManualOnly { name: "Continue", - steps: "在 ~/.continue/config.yaml 的 models 列表中添加一项,将 apiBase 设为 {v1}。", + steps: "Add an entry to the models list in ~/.continue/config.yaml with apiBase set to {v1}.", // **接管它要往一个 YAML 列表里插一个新条目**,那是结构性 // 改写,不是替换一个标量。我们的 YAML 补丁只做后者 // (见 crate::yaml 开头那段)。宁可少接管一个客户端,也不 // 要写一段我们自己没把握的结构。 - caveat: "接入需要在 models 列表中新增条目,不提供自动接管,请按上述步骤手动配置。", + caveat: "This needs a new entry in the models list, which is not written automatically; follow the steps above.", }, ManualOnly { name: "Gemini CLI", - steps: "在 shell 配置文件中添加 export GOOGLE_GEMINI_BASE_URL={base},然后重新打开终端。", + steps: "Add export GOOGLE_GEMINI_BASE_URL={base} to the shell configuration, then reopen the terminal.", // 它只认环境变量,没有可写的配置字段。改 .zshrc 超出了 // 「只改 endpoint 和 key 字段」的边界 —— // **报告是我们的职责,修改是他的权利。** - caveat: "Gemini CLI 只从环境变量读取接口地址。ThinkWatch 不修改 shell 配置文件,请手动添加。", + caveat: "Gemini CLI reads the endpoint only from the environment. ThinkWatch does not edit shell configuration files, so add it by hand.", }, ] } @@ -503,7 +509,7 @@ mod tests { c.id ); assert!( - c.takes_effect.note().contains("重新打开终端"), + c.takes_effect.note().contains("terminal is reopened"), "{} 没在接管那一刻说清要重开", c.id ); @@ -559,7 +565,11 @@ mod tests { // 我们这儿,而 Tab 补全根本不经过。 let m = manual_only(); let cursor = m.iter().find(|c| c.name == "Cursor").unwrap(); - assert!(cursor.caveat.contains("Tab 补全"), "{}", cursor.caveat); + assert!( + cursor.caveat.contains("Tab completion"), + "{}", + cursor.caveat + ); // 步骤里要有真实的地址,而不是一个让用户自己去找的说法 let gw = Gateway { base: "http://127.0.0.1:8788".into(), diff --git a/crates/tw-adopt/src/detect.rs b/crates/tw-adopt/src/detect.rs index 7b2043df..c0a64ac6 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!("{} is not running", c.name), + detail: "It reads the new configuration the next time it starts.".into(), fix: None, }); } else if !stale.is_empty() { out.push(Finding { level: Level::Blocking, - title: format!("{} 的进程启动于接管之前", c.name), + title: format!("{} was started before the change", c.name), detail: format!( - "有 {} 个进程在接管之前启动,仍在使用旧配置。{}", + "{} processes were started before the change and are still on the old configuration. {}", stale.len(), c.takes_effect.note() ), - fix: Some(format!("退出 {} 后重新打开", c.name)), + fix: Some(format!("Quit {} and open it again", c.name)), }); } else { out.push(Finding { level: Level::Clear, - title: format!("{} 在接管之后启动", c.name), - detail: "已读取新配置。".into(), + title: format!("{} was started after the change", c.name), + detail: "It has read the new configuration.".into(), fix: None, }); } } None => out.push(Finding { level: Level::Suspect, - title: "尚未接管该客户端".into(), - detail: format!("{} 中没有接管记录。", d.real.display()), + title: "This client has not been pointed at the gateway".into(), + detail: format!("{} carries no record.", d.real.display()), fix: None, }), } @@ -273,11 +273,11 @@ 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: "Nothing takes precedence over this file".into(), detail: if c.shadowed_by.is_empty() { - "该客户端没有优先级更高的配置文件。".into() + "This client has no configuration file that takes precedence.".into() } else { - format!("{} 不存在。", c.shadowed_by.join("、")) + format!("{} does not exist.", c.shadowed_by.join(", ")) }, fix: None, }); @@ -291,19 +291,22 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec } else { Level::Blocking }, - title: format!("{} 的优先级高于接管写入的配置", s.display()), + title: format!( + "{} takes precedence over what was written here", + s.display() + ), detail: if hits.is_empty() { - "该文件存在,但不包含相关字段。".into() + "The file exists, but carries none of the fields in question.".into() } else { format!( - "该文件中包含 {},会覆盖接管写入的设置。", + "The file carries {}, which overrides what was written here.", hits.iter() .map(|s| s.to_string()) .collect::>() - .join("、") + .join(", ") ) }, - fix: Some(format!("检查 {} 中的相关字段", s.display())), + fix: Some(format!("Look at those fields in {}", s.display())), }); } } @@ -314,9 +317,12 @@ 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.display())), + title: "This project has a configuration file of the same name".into(), + detail: format!( + "{} overrides the user-level configuration.", + local.display() + ), + fix: Some(format!("Look at {}", local.display())), }); } } @@ -332,15 +338,16 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec } else { Level::Blocking }, - title: "本机存在管理策略文件".into(), - detail: format!("{MANAGED} 的优先级高于其他所有配置,包括用户配置。"), + title: "This machine has a managed-policy file".into(), + detail: format!("{MANAGED} takes precedence over everything else, including the user's own configuration."), fix: None, }); } else { out.push(Finding { level: Level::Clear, - title: "本机没有管理策略文件".into(), - detail: "不存在优先级高于其他所有配置的管理策略文件。".into(), + title: "This machine has no managed-policy file".into(), + detail: "There is no managed-policy file taking precedence over everything else." + .into(), fix: None, }); } @@ -351,8 +358,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: "No shell file exports a variable of the same name".into(), + detail: "Checked .zshrc, .zprofile, .bashrc and the rest.".into(), fix: None, }); } else { @@ -363,19 +370,22 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec ( Level::Suspect, format!( - "不影响 {}(其配置文件优先级更高),但会影响读取环境变量的其他客户端。", + "It does not affect {}, whose configuration file takes precedence, but it does affect every client that reads the environment.", c.name ), ) } else { ( Level::Blocking, - format!("{} 读取环境变量,该行会覆盖接管写入的配置。", c.name), + format!( + "{} reads the environment, so this line overrides what was written here.", + c.name + ), ) }; out.push(Finding { level, - title: format!("{} 第 {line} 行导出了 {name}", f.display()), + title: format!("{} exports {name} on line {line}", f.display()), detail, // 命令给出来,执行与否是他的事 fix: Some(format!("sed -i '' '{line}d' {}", f.display())), @@ -387,17 +397,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: "The fields written here are no longer in the configuration".into(), detail: format!( - "{} 中未找到接管写入的接口地址,可能已被其他工具修改。", + "{} no longer carries the endpoint that was written here; something else may have changed it.", d.real.display() ), - fix: Some("重新接管该客户端".into()), + fix: Some("Point this client at the gateway again".into()), }), (Some(_), Some(ep)) => out.push(Finding { level: Level::Clear, - title: "配置中的接口地址与接管时一致".into(), - detail: format!("当前指向 {ep}。"), + title: "The endpoint in the configuration is the one written here".into(), + detail: format!("It points at {ep}."), fix: None, }), _ => {} @@ -407,8 +417,8 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec // 绿色的「查过了没问题」会让人以为已经确认过。 out.push(Finding { level: Level::Suspect, - title: "以上均为静态检查".into(), - detail: "静态检查无法确认配置已实际生效。收到该客户端的真实请求后,才能确认接管已生效。" + title: "Everything above is a static check".into(), + detail: "A static check cannot tell whether the configuration is actually in use. Only a real request from this client settles that." .into(), fix: None, }); @@ -480,7 +490,7 @@ mod tests { .find(|f| f.title.contains("ANTHROPIC_BASE_URL")) .unwrap(); assert_eq!(f.level, Level::Suspect, "{:?}", f); - assert!(f.detail.contains("优先级更高"), "{}", f.detail); + assert!(f.detail.contains("takes precedence"), "{}", f.detail); let cx = diagnose(&c("codex"), home, None); let f = cx @@ -505,7 +515,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("real request")), "结论里没留下这句话:{out:?}" ); } diff --git a/crates/tw-adopt/src/foreign.rs b/crates/tw-adopt/src/foreign.rs index a2243388..859ffbbc 100644 --- a/crates/tw-adopt/src/foreign.rs +++ b/crates/tw-adopt/src/foreign.rs @@ -25,23 +25,27 @@ use thiserror::Error; #[derive(Debug, Error)] pub enum ForeignError { - #[error("无法读取 {path}:{source}")] + #[error("{path} could not be read: {source}")] Read { path: PathBuf, source: std::io::Error, }, - #[error("无法写入 {path}:{source}")] + #[error("{path} could not be written: {source}")] Write { path: PathBuf, source: std::io::Error, }, - #[error("{path} 在确认之后又被修改,未写入。请重新查看改动")] + #[error( + "{path} changed after it was confirmed, so nothing was written. Look at the change again" + )] ChangedUnderUs { path: PathBuf }, - #[error("修改后的内容未通过校验,未写入({0})")] + #[error("the edited content did not pass its check, so nothing was written ({0})")] VerifyFailed(String), - #[error("写入后读回的内容与预期不一致,已从备份还原:{path}")] + #[error( + "what was read back after writing is not what was expected; restored from the backup: {path}" + )] Readback { path: PathBuf }, - #[error("符号链接层级过多:{path}")] + #[error("too many levels of symbolic link: {path}")] LinkLoop { path: PathBuf }, } @@ -240,7 +244,7 @@ pub fn apply( // 的是 ~/dotfiles/claude/settings.json —— 那是个会被 git 提交 // 的地方,而我们正要往里放一个密钥。 warnings.push(format!( - "{} 是符号链接,实际写入的文件为 {}。", + "{} is a symbolic link; the file actually written is {}.", ch.path.display(), real.display() )); @@ -277,7 +281,7 @@ pub fn apply( && m & 0o077 != 0 { warnings.push(format!( - "{} 的权限为 {:o},本机其他用户可以读取写入的密钥。可执行 chmod 600 {} 收紧权限。", + "{} is mode {:o}, so other users on this machine can read the key written into it. chmod 600 {} tightens it.", real.display(), m, real.display() @@ -358,7 +362,7 @@ mod tests { ); assert_eq!(std::fs::read_to_string(&real).unwrap(), "new"); assert!( - a.warnings.iter().any(|w| w.contains("符号链接")), + a.warnings.iter().any(|w| w.contains("symbolic link")), "{:?}", a.warnings ); diff --git a/crates/tw-adopt/src/json.rs b/crates/tw-adopt/src/json.rs index d36d976f..829f7633 100644 --- a/crates/tw-adopt/src/json.rs +++ b/crates/tw-adopt/src/json.rs @@ -21,11 +21,11 @@ use thiserror::Error; #[derive(Debug, Error, PartialEq)] pub enum JErr { - #[error("第 {at} 个字节处不是合法的 JSON:{msg}")] + #[error("byte {at} is not valid JSON: {msg}")] Syntax { at: usize, msg: String }, - #[error("{0} 不是对象,无法写入字段")] + #[error("{0} is not an object, so no field can be written into it")] NotObject(String), - #[error("文件为空")] + #[error("the file is empty")] 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, "a string was expected here")); } let mut out = String::new(); let mut j = i + 1; @@ -219,7 +219,9 @@ 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, "the escape sequence is incomplete"))?; j += 1; match c { b'"' => out.push('"'), @@ -232,10 +234,13 @@ 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 is followed by fewer than four digits") + })?; 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 is not followed by hexadecimal digits"))?; + u32::from_str_radix(s, 16) + .map_err(|_| err(p, "\\u is not followed by hexadecimal digits")) }; let hi = hex(b, j)?; j += 4; @@ -256,7 +261,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, "an escape sequence that is not recognized")), } } _ => { @@ -265,17 +270,17 @@ fn scan_str(b: &[u8], i: usize) -> Result<(String, usize), JErr> { j += 1; } out.push_str( - std::str::from_utf8(&b[start..j]).map_err(|_| err(start, "不是 UTF-8"))?, + std::str::from_utf8(&b[start..j]).map_err(|_| err(start, "not UTF-8"))?, ); } } } - Err(err(i, "字符串缺少结束引号")) + Err(err(i, "the string has no closing quote")) } 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, "a value is missing here"))?; match c { b'{' => { let mut j = skip_ws(b, i + 1); @@ -294,7 +299,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, "a colon was expected after the key")); } let (val, after_val) = parse_value(b, c + 1)?; ms.push(Member { @@ -316,7 +321,7 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { j + 1, )); } - return Err(err(j, "对象中缺少逗号或右花括号")); + return Err(err(j, "the object is missing a comma or a closing brace")); } } b'[' => { @@ -348,7 +353,7 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { j + 1, )); } - return Err(err(j, "数组中缺少逗号或右方括号")); + return Err(err(j, "the array is missing a comma or a closing bracket")); } } b'"' => { @@ -372,14 +377,19 @@ fn parse_value(b: &[u8], i: usize) -> Result<(Node, usize), JErr> { { j += 1; } - let lit = std::str::from_utf8(&b[start..j]).map_err(|_| err(start, "不是 UTF-8"))?; + let lit = std::str::from_utf8(&b[start..j]).map_err(|_| err(start, "not UTF-8"))?; let body = match lit { "true" => Body::Bool(true), "false" => Body::Bool(false), "null" => Body::Null, - "" => return Err(err(i, "此处缺少值")), + "" => return Err(err(i, "a value is missing here")), n if n.parse::().is_ok() => Body::Num(n.to_string()), - other => return Err(err(start, &format!("无法识别的字面量 {other}"))), + other => { + return Err(err( + start, + &format!("a literal that is not recognized: {other}"), + )); + } }; Ok(( Node { @@ -400,7 +410,10 @@ 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, + "there is extra content after the end of the document", + )); } Ok(n) } diff --git a/crates/tw-adopt/src/mcp.rs b/crates/tw-adopt/src/mcp.rs index 859ed9f7..e88e6ef0 100644 --- a/crates/tw-adopt/src/mcp.rs +++ b/crates/tw-adopt/src/mcp.rs @@ -16,15 +16,17 @@ use crate::json::Val; #[derive(Debug, thiserror::Error)] pub enum McpError { - #[error("未知的客户端 {0}")] + #[error("{0} is not a client we know")] UnknownClient(String), - #[error("无法解析 {client} 的 MCP 配置,未做任何修改:{msg}")] + #[error("the MCP configuration of {client} could not be parsed, so nothing was changed: {msg}")] Parse { client: String, msg: String }, #[error("{0}")] Write(#[from] ForeignError), - #[error("{client} 中没有名为「{name}」的 MCP server")] + #[error("{client} has no MCP server named `{name}`")] NotThere { client: String, name: String }, - #[error("{client} 的 MCP 配置格式未经验证,不支持写入({why})")] + #[error( + "the MCP configuration format of {client} is unverified, so it is not written to ({why})" + )] NotCopyable { client: String, why: String }, } @@ -98,7 +100,7 @@ pub fn targets() -> Vec { format: Format::Json, key: "mcp", copyable: false, - why_not: "该客户端的 MCP 配置格式尚未验证,写入可能导致客户端无法读取配置", + why_not: "this client's MCP configuration format is not verified yet, and writing to it could leave the client unable to read its own configuration", }, Target { client: "zed", @@ -107,7 +109,7 @@ pub fn targets() -> Vec { format: Format::Json, key: "context_servers", copyable: false, - why_not: "Zed 的 context server 使用不同的配置结构,不支持 command/args 形式", + why_not: "Zed's context servers use a different structure and do not take the command/args form", }, ] } @@ -146,7 +148,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 configuration is not YAML")), } } @@ -154,7 +156,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 configuration is not YAML")), } } @@ -162,7 +164,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 configuration is not YAML")), } } @@ -198,7 +200,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, "the root is not an object")); }; let servers = root.iter().find(|(k, _)| k == t.key).map(|(_, v)| v); match servers { @@ -295,13 +297,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 configuration is not YAML".into()), }; if strip(&got).normalized() != untouched { - return Err(format!("除 {key} 之外还有其他内容发生了变化")); + return Err(format!("something other than {key} changed")); } if got.normalized() != want.normalized() { - return Err("修改后的内容与预期不一致".into()); + return Err("the edited content is not what was expected".into()); } Ok(()) }, diff --git a/crates/tw-adopt/src/plan.rs b/crates/tw-adopt/src/plan.rs index 592e3cb5..dfa63f82 100644 --- a/crates/tw-adopt/src/plan.rs +++ b/crates/tw-adopt/src/plan.rs @@ -24,24 +24,28 @@ use crate::sentinel::{self, Original, SidecarRecord, Was}; #[derive(Debug, thiserror::Error)] pub enum PlanError { - #[error("无法读取 {client} 的配置:{source}")] + #[error("the configuration of {client} could not be read: {source}")] Read { client: String, source: ForeignError, }, - #[error("无法解析 {client} 的配置,未做任何修改:{msg}")] + #[error("the configuration of {client} could not be parsed, so nothing was changed: {msg}")] Parse { client: String, msg: String }, #[error("{0}")] Write(#[from] ForeignError), - #[error("{path} 旁的接管记录属于 {other},不属于 {client},未做任何修改")] + #[error("the record beside {path} belongs to {other}, not {client}, so nothing was changed")] ForeignSidecar { path: PathBuf, other: String, client: String, }, - #[error("未找到 {client} 的接管记录,无法确定还原内容。如需手动还原,请查看 {path}")] + #[error( + "there is no record for {client}, so there is nothing to restore from. To restore by hand, look at {path}" + )] NoRecord { client: String, path: PathBuf }, - #[error("{client} 的原值是密钥,仅保存在全文备份中,而备份 {backup} 已不存在")] + #[error( + "the original value for {client} is a secret kept only in the full backup, and the backup {backup} is gone" + )] SecretGone { client: String, backup: PathBuf }, } @@ -220,7 +224,7 @@ pub fn plan_adopt(c: &Client, home: &Path, gw: &Gateway) -> Result Result>() - .join("、") + .join(", ") )); } @@ -338,7 +342,7 @@ pub fn apply(c: &Client, plan: &Plan, backup_root: &Path) -> Result Result Result { after: String::new(), originals: Vec::new(), carries_secret: false, - notes: vec!["配置文件已不存在,仅删除接管记录。".into()], + notes: vec!["The configuration file is gone; only the record was removed.".into()], shadows: Vec::new(), targets: Vec::new(), drop_sidecar: Some(side), @@ -499,7 +506,7 @@ pub fn plan_restore(c: &Client, home: &Path) -> Result { // 更糟 —— 那等于卸载之后还在替他发着请求。 targets.push(Target::Remove(p.clone())); notes.push(format!( - "{} 的原值是密钥,仅保存在全文备份中,而 {} 已不存在。该字段已删除,需要手动重新填写。", + "The original value of {} is a secret kept only in the full backup, and {} is gone. The field was removed and has to be filled in again by hand.", f.field, backup.display() )); @@ -542,7 +549,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("This file was created here, restoring leaves it empty, and it was removed with the rest.".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 52d33b1a..280d8835 100644 --- a/crates/tw-adopt/src/sentinel.rs +++ b/crates/tw-adopt/src/sentinel.rs @@ -13,8 +13,8 @@ use serde::{Deserialize, Serialize}; -pub const BEGIN: &str = "=== ThinkWatch 接管开始 ==="; -pub const END: &str = "=== ThinkWatch 接管结束 ==="; +pub const BEGIN: &str = "=== ThinkWatch: begin ==="; +pub const END: &str = "=== ThinkWatch: end ==="; /// 这个字段原本是什么样。**三态,不是「有值/没值」两态。** /// @@ -47,9 +47,13 @@ impl Was { } fn note(&self) -> &'static str { match self { - Was::Missing => "原配置中没有该字段,还原时删除", - Was::Value(_) => "原配置中已有该字段,还原时写回「原值」", - Was::Secret(_) => "原值是密钥,未写入本文件,请从「全文备份」所指的文件中获取", + Was::Missing => "the original configuration had no such field; restoring removes it", + Was::Value(_) => { + "the original configuration had this field; restoring writes `was` back" + } + Was::Secret(_) => { + "the original value is a secret and is not in this file; take it from the full backup named above" + } } } } @@ -95,14 +99,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} no {} originally\n", o.field)), Was::Value(v) | Was::Secret(v) => { - out.push_str(&format!("{prefix} 原值 {}: {v}\n", o.field)) + out.push_str(&format!("{prefix} was {}: {v}\n", o.field)) } } } out.push_str(&format!( - "{prefix} 手动还原方法:将以上字段恢复为原值(原配置中没有的字段直接删除),然后删除本段注释\n" + "{prefix} to restore by hand: put the fields above back to what they were (delete the ones that had no value), then delete this block\n" )); out.push_str(&format!("{prefix} {END}\n")); out @@ -143,9 +147,9 @@ pub struct SidecarField { pub path: Vec, /// 机器读的标记:`missing` / `value` / `secret` pub was: String, - #[serde(rename = "原值", skip_serializing_if = "Option::is_none", default)] + #[serde(rename = "was_value", skip_serializing_if = "Option::is_none", default)] pub value: Option, - #[serde(rename = "说明")] + #[serde(rename = "note")] pub note: String, } @@ -157,21 +161,21 @@ pub struct SidecarField { pub struct SidecarRecord { /// 人话说明,**放在第一个字段** —— 用户打开这个文件,第一眼看到的 /// 应该是「这是什么」 - #[serde(rename = "这个文件是什么")] + #[serde(rename = "what_this_file_is")] pub what: String, - #[serde(rename = "怎么手动还原")] + #[serde(rename = "how_to_restore_by_hand")] pub how: String, pub client: String, pub adopted_at_ms: u64, /// 接管前那一刻的全文备份。密钥类原值只在这里,不在本文件里。 - #[serde(rename = "全文备份")] + #[serde(rename = "full_backup")] pub backup: String, /// 这个配置文件本来不存在,是接管时新建的。 /// /// 还原时要能把它**整个删掉** —— 否则「还原」之后会留下一个用户 /// 从来没有过的文件。但只在它还是空的时候删:用户可能在这期间往 /// 里加了自己的东西。 - #[serde(rename = "文件是我们建的", default)] + #[serde(rename = "file_created_by_us", default)] pub created_file: bool, pub originals: Vec, } @@ -203,9 +207,14 @@ impl SidecarRecord { ) -> Self { Self { what: format!( - "ThinkWatch Lite 接管 {client} 时生成的记录,记载了修改过的字段及其原值。" + "Written by ThinkWatch Lite when it pointed {client} at the gateway. It records \ + the fields that were changed and what they were before." ), - how: "将 originals 中的每个字段恢复为「原值」(was 为 missing 表示原配置中没有该字段,直接删除即可;was 为 secret 表示原值是密钥,请从「全文备份」所指的文件中获取),然后删除本文件。".to_string(), + how: "Put every field under `originals` back to its `was_value`. A `was` of \ + `missing` means the field was not there to begin with, so delete it; a `was` of \ + `secret` means the original is a secret, which is in the file named by \ + `full_backup`. Then delete this file." + .to_string(), client: client.to_string(), adopted_at_ms: at_ms, backup: backup.to_string(), @@ -247,7 +256,7 @@ mod tests { // 可能已经在废纸篓里了 —— 那段注释是他唯一的线索。 let b = comment_block("#", &originals()); assert!(b.contains("https://api.anthropic.com"), "原值没写进去:{b}"); - assert!(b.contains("手动还原方法"), "没告诉他能做什么:{b}"); + assert!(b.contains("to restore by hand"), "没告诉他能做什么:{b}"); assert!(b.contains(BEGIN) && b.contains(END), "{b}"); } @@ -258,11 +267,11 @@ mod tests { // 的字段。 let b = comment_block("#", &originals()); assert!( - b.contains("原配置中没有 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"), + b.contains("no env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY originally"), "{b}" ); assert!( - !b.contains("原值 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"), + !b.contains("was env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"), "{b}" ); } @@ -293,7 +302,7 @@ mod tests { .find(|f| f.field.ends_with("AUTH_TOKEN")) .unwrap(); assert_eq!(f.was, "secret"); - assert!(f.note.contains("备份"), "{}", f.note); + assert!(f.note.contains("full backup"), "{}", f.note); assert!(rec.backup.contains("backups"), "{}", rec.backup); } @@ -302,8 +311,8 @@ mod tests { let rec = SidecarRecord::new("claude-code", 1, "b", false, &originals()); let j = serde_json::to_string_pretty(&rec).unwrap(); let first = j.lines().nth(1).unwrap(); - assert!(first.contains("这个文件是什么"), "{first}"); - assert!(j.contains("怎么手动还原"), "{j}"); + assert!(first.contains("what_this_file_is"), "{first}"); + assert!(j.contains("how_to_restore_by_hand"), "{j}"); } #[test] diff --git a/crates/tw-adopt/src/toml.rs b/crates/tw-adopt/src/toml.rs index 61680f19..305cbab6 100644 --- a/crates/tw-adopt/src/toml.rs +++ b/crates/tw-adopt/src/toml.rs @@ -14,9 +14,9 @@ use crate::json::Val; #[derive(Debug, thiserror::Error, PartialEq)] pub enum TErr { - #[error("不是合法的 TOML:{0}")] + #[error("not valid TOML: {0}")] Syntax(String), - #[error("{0} 不是表,无法写入字段")] + #[error("{0} is not a table, so no field can be written into it")] 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("the table that was just inserted"); 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 79dbb46c..be8639eb 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("only top-level fields are supported, and {0} is nested")] TooDeep(String), } diff --git a/crates/tw-adopt/tests/roundtrip.rs b/crates/tw-adopt/tests/roundtrip.rs index cbe31ca5..c50bc49d 100644 --- a/crates/tw-adopt/tests/roundtrip.rs +++ b/crates/tw-adopt/tests/roundtrip.rs @@ -137,7 +137,7 @@ fn the_sidecar_never_holds_the_users_own_key() { "用户的密钥被抄进旁文件了:\n{side}" ); assert!(side.contains("secret"), "{side}"); - assert!(side.contains("全文备份"), "{side}"); + assert!(side.contains("full_backup"), "{side}"); } #[test] @@ -163,7 +163,9 @@ 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("filled in again by hand")), "没说清密钥拿不回来了:{:?}", r.notes ); @@ -268,8 +270,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("to restore by hand"), "{after}"); + assert!(after.contains("no model_provider originally"), "{after}"); } #[test] @@ -417,7 +419,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("there is no record"), "{e}"); assert_eq!(read(&b.home.join(".codex/config.toml")), CODEX); } @@ -485,7 +487,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("no model_provider originally"), "哨兵注释记成了我们自己的值:{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 7be58420..cfe56f39 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -83,7 +83,7 @@ impl Secret { /// 命令行和诊断包里的说法,**永远不含真实密钥**。 pub fn describe(&self) -> String { if self.0.contains("${") { - format!("环境变量 {}", self.0) + format!("environment variable {}", self.0) } else { tw_secret::mask_secret(&self.0) } @@ -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("a string, which may contain ${VAR}. An OAuth credential belongs in the upstream's oauth field") } 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("a mapping of header name to value") } fn visit_map>( self, @@ -252,45 +252,53 @@ pub fn auth_header(protocol: Option) -> (&'static str, &'static str) { /// 凭据写法上的问题。**每一条都指到具体的那一行**,而不是「凭据无效」。 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CredentialError { - #[error("API 密钥为空")] + #[error("the API key is empty")] EmptyKey, - #[error("key 和 oauth 只能填写其中一项")] + #[error("key and oauth are alternatives; fill in one of them")] KeyAndOauth, - #[error("oauth 的 refresh 和 endpoint 都不能为空")] + #[error("neither refresh nor endpoint of oauth can be empty")] EmptyOauth, - #[error("不支持接入 Claude 订阅账号的登录凭据,请改用 Anthropic API 密钥")] + #[error("a Claude subscription sign-in is not supported here; use an Anthropic API key")] ClaudeSubscription, - #[error("不支持接入 Gemini CLI 的 Google 登录凭据,请改用 Gemini API 密钥")] + #[error("the Google sign-in of Gemini CLI is not supported here; use a Gemini API key")] GoogleSubscription, - #[error("ChatGPT 账号上游只能使用登录获得的凭据")] + #[error("a ChatGPT account upstream takes only the credential obtained by signing in")] ChatgptWithoutLogin, - #[error("请求头「{0}」说明请求的来源,由网关如实发送,不能在配置中设置")] + #[error( + "the `{0}` header says where a request came from; the gateway sends it truthfully and it cannot be set in the configuration" + )] IdentityHeader(String), - #[error("请求头不能超过 {MAX_HEADERS} 个")] + #[error("there can be at most {MAX_HEADERS} headers")] TooManyHeaders, #[error( - "请求头名「{0}」不合法:只能由字母、数字和 - _ . ~ 组成,长度不超过 {MAX_HEADER_NAME} 个字符" + "the header name `{0}` is not valid: letters, digits and - _ . ~ only, and at most {MAX_HEADER_NAME} characters" )] BadHeaderName(String), - #[error("请求头「{0}」由网关管理,不能在配置中设置")] + #[error("the `{0}` header is the gateway's to manage and cannot be set in the configuration")] ReservedHeader(String), - #[error("请求头「{0}」重复(请求头名不区分大小写)")] + #[error("the `{0}` header appears twice (header names are case-insensitive)")] DuplicateHeader(String), - #[error("请求头「{0}」的值不能包含换行,长度不超过 {MAX_HEADER_VALUE} 个字符")] + #[error( + "the value of the `{0}` header cannot contain a newline and is at most {MAX_HEADER_VALUE} characters" + )] BadHeaderValue(String), #[error( - "请求头「{name}」中的 {placeholder} 无法识别,仅支持 {{{{access_token}}}} 和 {{{{client}}}}" + "{placeholder} in the `{name}` header is not recognized; only {{{{access_token}}}} and {{{{client}}}} are" )] UnknownPlaceholder { name: String, placeholder: String }, - #[error("请求头「{0}」使用了 {{{{access_token}}}},但该上游未配置 oauth")] + #[error( + "the `{0}` header uses {{{{access_token}}}}, and this upstream has no oauth configured" + )] TokenWithoutOauth(String), - #[error("已填写 key,API 密钥将通过请求头「{0}」发送,请求头中不能再设置「{0}」")] + #[error( + "a key is filled in, so the API key goes out in the `{0}` header; `{0}` cannot also be set among the headers" + )] KeyAndAuthHeader(String), #[error( - "配置 oauth 后,token 默认通过请求头「{0}」发送。如需自行设置该请求头,请在值中用 {{{{access_token}}}} 标明 token 的位置" + "with oauth configured, the token goes out in the `{0}` header by default. To set that header yourself, mark where the token goes with {{{{access_token}}}}" )] OauthAndAuthHeader(String), - #[error("无法获取 OAuth access token")] + #[error("an OAuth access token could not be obtained")] NoToken, /// 环境变量没设之类。存成文字:这个错误要能比较,而底下那个类型不能 #[error("{0}")] diff --git a/crates/tw-config/src/edit.rs b/crates/tw-config/src/edit.rs index 40717a54..663d0c59 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("there is already a {what} named `{name}`")] NameTaken { what: &'static str, name: String }, - #[error("未找到名为「{name}」的{what}")] + #[error("there is no {what} named `{name}`")] NotFound { what: &'static str, name: String }, #[error("{0}")] Yaml(#[from] tw_yaml::PatchError), - #[error("配置文件无法解析:{0}")] + #[error("the configuration file could not be parsed: {0}")] Parse(String), /// 渲染不出一个能安全写进去的值。 #[error("{0}")] Unwritable(String), - #[error("修改后的内容与预期不一致({0}),未写入文件")] + #[error("the edited content is not what was expected ({0}), so nothing was written")] SelfCheck(String), } @@ -46,23 +46,23 @@ pub struct Section { pub const PROVIDERS: Section = Section { path: &["providers"], - what: "上游", + what: "upstream", }; pub const PROXIES: Section = Section { path: &["proxies"], - what: "代理", + what: "proxy", }; pub const PRICE_SHEETS: Section = Section { path: &["pricing", "sheets"], - what: "价目表", + what: "price sheet", }; pub const ROUTES: Section = Section { path: &["routes"], - what: "路由", + what: "route", }; pub const GROUPS: Section = Section { path: &["groups"], - what: "策略组", + what: "group", }; impl Section { @@ -107,7 +107,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!("the {} has no name", section.what)))? .to_string(); let taken = section.index_of(&doc, &name); let steps = section.steps(); @@ -159,7 +159,7 @@ pub fn upsert( put_item(&mut expected, section, index, Value::Mapping(item.clone())); let got = parse(&out).map_err(|e| EditError::SelfCheck(e.to_string()))?; if got != expected { - return Err(EditError::SelfCheck(format!("{}「{name}」", section.what))); + return Err(EditError::SelfCheck(format!("{} `{name}`", section.what))); } Ok(out) } @@ -186,7 +186,7 @@ pub fn remove(text: &str, section: Section, name: &str) -> Result 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())) - } + Value::String(s) if s.contains('\n') || s.contains('\r') => Err(EditError::Unwritable( + "a value cannot contain a newline".to_string(), + )), Value::Mapping(m) => m.iter().try_for_each(|(k, v)| { reject_multiline(k)?; reject_multiline(v) @@ -269,7 +269,7 @@ fn sync_fields( let key_of = |k: &Value| -> Result { k.as_str() .map(str::to_string) - .ok_or_else(|| EditError::Unwritable(format!("键 {k:?} 不是字符串"))) + .ok_or_else(|| EditError::Unwritable(format!("the key {k:?} is not a string"))) }; for (k, _) in old.iter().filter(|(k, _)| !new.contains_key(*k)) { let mut p = path.to_vec(); diff --git a/crates/tw-config/src/history.rs b/crates/tw-config/src/history.rs index 613e0a31..df2b4c63 100644 --- a/crates/tw-config/src/history.rs +++ b/crates/tw-config/src/history.rs @@ -71,11 +71,11 @@ impl Origin { } pub fn label(&self) -> &'static str { match self { - Origin::Ui => "界面", - Origin::Cli => "命令行", - Origin::External => "外部编辑", - Origin::Rollback => "回滚", - Origin::Rotation => "凭据轮换", + Origin::Ui => "the interface", + Origin::Cli => "the command line", + Origin::External => "an outside edit", + Origin::Rollback => "a rollback", + Origin::Rotation => "a credential rotation", } } } @@ -231,7 +231,7 @@ pub fn read(v: &Version) -> Result { #[derive(Debug, thiserror::Error)] pub enum RollbackError { - #[error("版本历史中没有 {0}")] + #[error("the version history has no {0}")] NoSuchVersion(String), #[error(transparent)] Store(#[from] StoreError), @@ -378,7 +378,7 @@ mod tests { } let all = list(&p).unwrap(); assert_eq!(all.len(), 1, "历史里不该有轮换那几版:{all:?}"); - assert_eq!(all[0].origin.label(), "界面"); + assert_eq!(all[0].origin.label(), "the interface"); } #[test] diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 42e4eeb1..979ab69e 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -593,8 +593,8 @@ impl Trust { } pub fn label(&self) -> &'static str { match self { - Trust::Official => "官方端点", - Trust::Untrusted => "非官方端点", + Trust::Official => "official endpoint", + Trust::Untrusted => "unofficial endpoint", } } /// 命中高危时要不要真的切断。 @@ -629,10 +629,10 @@ pub enum Billing { impl Billing { pub fn label(&self) -> &'static str { match self { - Billing::PerToken => "按量计费", - Billing::Subscription => "订阅制", - Billing::Free => "不计费", - Billing::Unknown => "计费方式未知", + Billing::PerToken => "per token", + Billing::Subscription => "subscription", + Billing::Free => "free", + Billing::Unknown => "billing unknown", } } pub fn slug(&self) -> &'static str { @@ -861,7 +861,7 @@ pub fn patch_oauth_tokens( if !ok { return Err(RotateError::Broke { provider: provider.to_string(), - why: "写入后读回的 token 不是新值".into(), + why: "the token read back after writing is not the new one".into(), }); } Ok(out) @@ -875,23 +875,25 @@ fn provider_index(text: &str, provider: &str) -> Option { #[derive(Debug, thiserror::Error)] pub enum RotateError { - #[error("配置中已不存在上游「{provider}」")] + #[error("the configuration no longer has an upstream `{provider}`")] NoProvider { provider: String }, /// **说清「形状不对」而不是「写失败」。**用户可能把凭据写成了 /// 别的形状(锚点、块标量),那时正确的动作是他自己去改, /// 而不是让我们猜。 - #[error("无法定位上游「{provider}」的 oauth.refresh:{source}")] + #[error("oauth.refresh of upstream `{provider}` could not be located: {source}")] Shape { provider: String, source: tw_yaml::PatchError, }, - #[error("写入上游「{provider}」的新凭据后配置无法读取,未写入文件:{why}")] + #[error( + "after writing the new credential for upstream `{provider}` the configuration could not be read, so nothing was written: {why}" + )] Broke { provider: String, why: String }, } #[derive(Debug, thiserror::Error)] pub enum LoadError { - #[error("无法读取 {path}:{source}")] + #[error("{path} could not be read: {source}")] Io { path: PathBuf, source: std::io::Error, @@ -900,7 +902,7 @@ pub enum LoadError { /// 一份语法完美、只是把 `port` 写成 `prot` 的文件也会到这儿,而那句 /// 话会让用户去找一个根本不存在的语法错误。serde 自己的 /// 「unknown field `prot`, expected one of ...」比我们能补的任何话都准。 - #[error("无法解析 {path}:{source}")] + #[error("{path} could not be parsed: {source}")] Parse { path: PathBuf, source: serde_yaml_ng::Error, @@ -925,12 +927,12 @@ pub fn load(path: &Path) -> Result { #[derive(Debug, thiserror::Error)] pub enum WriteError { - #[error("无法写入 {path}:{source}")] + #[error("{path} could not be written: {source}")] Io { path: PathBuf, source: std::io::Error, }, - #[error("序列化失败:{0}")] + #[error("serialization failed: {0}")] Serialize(#[from] serde_yaml_ng::Error), } @@ -1104,7 +1106,10 @@ providers: #[test] fn describe_shows_the_env_var_name_not_its_value() { // 变量名不是秘密,而它恰恰是用户排查时要看的东西。 - assert_eq!(Secret::new("${MY_KEY}").describe(), "环境变量 ${MY_KEY}"); + assert_eq!( + Secret::new("${MY_KEY}").describe(), + "environment variable ${MY_KEY}" + ); } #[test] diff --git a/crates/tw-config/src/refs.rs b/crates/tw-config/src/refs.rs index ed67d1c6..677f46a2 100644 --- a/crates/tw-config/src/refs.rs +++ b/crates/tw-config/src/refs.rs @@ -228,12 +228,12 @@ pub fn client_refs(cfg: &Config, name: &str) -> Vec { for route in &cfg.routes { for rule in &route.rules { if rule.when.client.as_deref() == Some(name) { - out.push(format!("路由「{}」的规则「{}」", route.name, rule.name)); + out.push(format!("rule `{}` of route `{}`", rule.name, route.name)); } } } if cfg.default_key.as_deref() == Some(name) { - out.push("默认密钥".to_string()); + out.push("the default key".to_string()); } out } @@ -332,7 +332,7 @@ groups: type: fallback providers: [relay, 官方] routes: - - name: 默认 + - name: default rules: - name: 长上下文 when: { input_tokens: '>200k' } @@ -356,11 +356,11 @@ routes: refs, vec![ ProviderRef::RuleTarget { - route: "默认".into(), + route: "default".into(), rule: "长上下文".into() }, ProviderRef::RuleCondition { - route: "默认".into(), + route: "default".into(), rule: "中转脱敏".into() }, ProviderRef::Group { @@ -424,7 +424,7 @@ routes: assert_eq!( group_refs(&cfg(CFG), "pool"), vec![RuleRef { - route: "默认".into(), + route: "default".into(), rule: "兜底".into() }] ); @@ -453,14 +453,14 @@ routes: // 默认路由没写在配置里:改名之后要写进去,否则默认路由指向一条不存在的「默认」 let text = CFG.replace( " key: tw-k\n", - " key: tw-k\n - name: codex\n key: tw-x\n route: 默认\n", + " key: tw-k\n - name: codex\n key: tw-x\n route: default\n", ); let c = cfg(&text); - assert_eq!(route_users(&c, "默认"), ["codex"]); + assert_eq!(route_users(&c, "default"), ["codex"]); let renamed = edit::upsert( &text, edit::ROUTES, - Some("默认"), + Some("default"), &edit::parse(&text).unwrap()["routes"][0] .as_mapping() .map(|m| { @@ -471,7 +471,7 @@ routes: .unwrap(), ) .unwrap(); - let out = rename_route(&renamed, &c, "默认", "通用").unwrap(); + let out = rename_route(&renamed, &c, "default", "通用").unwrap(); let after = cfg(&out); assert_eq!(after.default_route.as_deref(), Some("通用")); assert_eq!(route_users(&after, "通用"), ["codex"]); @@ -486,7 +486,7 @@ routes: .unwrap(), ) .unwrap(); - let back = rename_route(&back, &after, "通用", "默认").unwrap(); + let back = rename_route(&back, &after, "通用", "default").unwrap(); assert!(!back.contains("default_route"), "{back}"); } diff --git a/crates/tw-config/src/reload.rs b/crates/tw-config/src/reload.rs index b781229f..ad200e43 100644 --- a/crates/tw-config/src/reload.rs +++ b/crates/tw-config/src/reload.rs @@ -40,9 +40,9 @@ impl Stage { /// 命令行和日志里的说法,后面接「错误」。 pub fn label(&self) -> &'static str { match self { - Stage::Syntax => "语法", - Stage::Schema => "字段", - Stage::Semantics => "语义", + Stage::Syntax => "syntax", + Stage::Schema => "schema", + Stage::Semantics => "semantics", } } } @@ -65,11 +65,11 @@ pub struct Rejected { impl std::fmt::Display for Rejected { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}错误", self.stage.label())?; + write!(f, "{} error", self.stage.label())?; if let Some(l) = self.line { - write!(f, "(第 {l} 行)")?; + write!(f, " (line {l})")?; } - write!(f, ":{}", self.message) + write!(f, ": {}", self.message) } } @@ -184,7 +184,7 @@ mod tests { // serde 的「missing field `clients`」说不出下一步做什么。 let r = try_parse("version: 1\n").unwrap_err(); assert_eq!(r.stage, Stage::Semantics, "{r:?}"); - assert!(r.message.contains("首次启动"), "{r:?}"); + assert!(r.message.contains("generated on first start"), "{r:?}"); } #[test] @@ -204,7 +204,7 @@ mod tests { let r = try_parse(bad).unwrap_err(); assert_eq!(r.stage, Stage::Semantics, "{r:?}"); assert!(r.line.is_none(), "语义错不该编行号:{r:?}"); - assert!(r.message.contains("重复"), "{r:?}"); + assert!(r.message.contains("appears twice"), "{r:?}"); } #[test] @@ -222,7 +222,7 @@ mod tests { let bad = "version: 999\nclients:\n - name: c\n key: tw-k\n"; let r = try_parse(bad).unwrap_err(); assert_eq!(r.stage, Stage::Schema); - assert!(r.message.contains("升级"), "{r:?}"); + assert!(r.message.contains("Upgrade the app"), "{r:?}"); assert!(!schema_supported(999)); assert!(schema_supported(1)); } @@ -254,6 +254,6 @@ mod tests { fn the_display_form_reads_like_a_sentence_a_person_can_act_on() { let bad = "version: 1\nclients:\n - name: c\n kye: tw-k\n"; let s = try_parse(bad).unwrap_err().to_string(); - assert!(s.starts_with("字段错误(第 4 行):"), "{s}"); + assert!(s.starts_with("schema error (line 4): "), "{s}"); } } diff --git a/crates/tw-config/src/security.rs b/crates/tw-config/src/security.rs index 3de887d6..0a8f35f3 100644 --- a/crates/tw-config/src/security.rs +++ b/crates/tw-config/src/security.rs @@ -34,9 +34,9 @@ impl Mode { } pub fn label(&self) -> &'static str { match self { - Mode::Off => "关闭", - Mode::Observe => "观察", - Mode::Enforce => "拦截", + Mode::Off => "off", + Mode::Observe => "observe", + Mode::Enforce => "enforce", } } @@ -128,10 +128,10 @@ impl Security { /// 很远,而用户点「切到拦截」时应该清楚知道会发生什么。 pub fn enforce_verb(line: &str) -> &'static str { match line { - "redact" => "替换", - "inspect_tools" => "切断", - "scan_configs" => "告警", - _ => "拦截", + "redact" => "replaces", + "inspect_tools" => "cuts off", + "scan_configs" => "reports", + _ => "enforces", } } } @@ -180,9 +180,9 @@ mod tests { #[test] fn each_line_of_defence_has_its_own_verb() { // 三件事差得很远,统一叫「拦截」会让用户不知道自己在开什么。 - assert_eq!(Security::enforce_verb("redact"), "替换"); - assert_eq!(Security::enforce_verb("inspect_tools"), "切断"); - assert_eq!(Security::enforce_verb("scan_configs"), "告警"); + assert_eq!(Security::enforce_verb("redact"), "replaces"); + assert_eq!(Security::enforce_verb("inspect_tools"), "cuts off"); + assert_eq!(Security::enforce_verb("scan_configs"), "reports"); } #[test] diff --git a/crates/tw-config/src/store.rs b/crates/tw-config/src/store.rs index 539e1471..73841a26 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} could not be read: {source}")] Io { path: PathBuf, source: std::io::Error, }, - #[error("{path} 不存在")] + #[error("{path} does not exist")] Missing { path: PathBuf }, /// **有人在我们读到和写下之间改了这个文件。** #[error( - "配置文件在此期间已被修改(当前版本为 {current},本次修改基于 {expected}),未覆盖该文件。请确认最新内容后重试" + "the configuration file changed in the meantime (it is now {current}, and this edit is based on {expected}), so it was not overwritten. Look at the current content and try again" )] 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("was not overwritten"), "{m}"); } #[test] diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index d69beaf5..e7afe411 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -5,53 +5,63 @@ use crate::{Config, SCHEMA_VERSION}; #[derive(Debug, thiserror::Error)] pub enum ValidationError { #[error( - "配置的 schema 版本为 {found},当前版本的 twcore 最高支持 {supported}。请升级应用,或将配置改回旧格式" + "the configuration is schema version {found}, and this twcore supports up to {supported}. Upgrade the app, or put the configuration back in the older form" )] SchemaTooNew { found: u32, supported: u32 }, #[error( - "配置中没有任何网关密钥(clients),所有请求都会被拒绝。首次启动时应已自动生成一个网关密钥" + "the configuration has no gateway key under `clients`, so every request is refused. One is generated on first start" )] NoClients, - #[error("上游名称重复:{0}。路由规则按名称引用上游,名称必须唯一")] + #[error( + "the upstream name {0} appears twice. Routing rules refer to an upstream by name, so names have to be unique" + )] DuplicateProvider(String), - #[error("网关密钥名称重复:{0}")] + #[error("the gateway key name {0} appears twice")] DuplicateClient(String), - #[error("网关密钥「{0}」与「{1}」的值相同。网关按密钥区分客户端,密钥值必须唯一")] + #[error( + "gateway keys `{0}` and `{1}` have the same value. The gateway tells clients apart by key, so the values have to be unique" + )] DuplicateKey(String, String), - #[error("default_key 指向的网关密钥「{0}」不存在")] + #[error("default_key points at gateway key `{0}`, which does not exist")] MissingDefaultKey(String), - #[error("默认网关密钥「{0}」处于停用状态。未接管的客户端均使用它,停用将使这些客户端一并失效")] + #[error( + "the default gateway key `{0}` is disabled. Every client that has not been pointed at the gateway explicitly uses it, and disabling it breaks all of them" + )] DisabledDefaultKey(String), - #[error("网关密钥「{0}」与「{1}」都写着为客户端「{2}」生成。一个客户端只能有一把")] + #[error( + "gateway keys `{0}` and `{1}` both say they were made for client `{2}`. A client has exactly one" + )] DuplicateClientKey(String, String, String), - #[error("上游「{name}」的接口地址不是 http 或 https 地址:{url}")] + #[error("the endpoint of upstream `{name}` is neither http nor https: {url}")] BadBaseUrl { name: String, url: String }, - #[error("网关密钥「{name}」的值为空")] + #[error("the value of gateway key `{name}` is empty")] EmptyKey { name: String }, - #[error("路由配置有误:{0}")] + #[error("the routing configuration is wrong: {0}")] Routing(#[from] tw_engine::RouteError), #[error( - "「{0}」既是上游名称又是策略组名称,规则中的 to 无法确定指向哪一个,请修改其中一个名称" + "`{0}` is the name of both an upstream and a group, so a rule's `to` cannot say which one it means. Rename one of them" )] NameCollision(String), - #[error("listen.gateway.allow_from 中的「{entry}」有误:{reason}")] + #[error("`{entry}` in listen.gateway.allow_from is wrong: {reason}")] BadCidr { entry: String, reason: String }, - #[error("上游「{name}」的凭据:{source}")] + #[error("the credential of upstream `{name}`: {source}")] Credential { name: String, source: crate::CredentialError, }, #[error("{0}")] Pricing(#[from] tw_pricing::SheetError), - #[error("上游「{provider}」使用的价目表「{sheet}」不存在")] + #[error("upstream `{provider}` uses price sheet `{sheet}`, which does not exist")] UnknownPriceSheet { provider: String, sheet: String }, #[error( - "上游「{name}」的启用范围(models_only)为空,该上游将不提供任何模型。如需暂停使用该上游,请将其停用(disabled: true)" + "the scope of upstream `{name}` (models_only) is empty, so it offers no model at all. To pause the upstream, disable it instead (disabled: true)" )] EmptyModelsOnly { name: String }, - #[error("上游「{name}」的启用范围(models_only)中存在空项")] + #[error("the scope of upstream `{name}` (models_only) has an empty entry")] BlankModelsOnly { name: String }, - #[error("{what}名称「{name}」以 __ 开头。以 __ 开头的名称留给内置项,请使用其他名称")] + #[error( + "the {what} name `{name}` starts with __, which is reserved for built-ins. Use a different name" + )] ReservedName { what: &'static str, name: String }, } @@ -163,9 +173,9 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { let named = cfg .providers .iter() - .map(|p| ("上游", &p.name)) - .chain(cfg.groups.iter().map(|g| ("策略组", &g.name))) - .chain(cfg.routes.iter().map(|r| ("路由", &r.name))); + .map(|p| ("upstream", &p.name)) + .chain(cfg.groups.iter().map(|g| ("group", &g.name))) + .chain(cfg.routes.iter().map(|r| ("route", &r.name))); for (what, name) in named { if reserved(name) { return Err(ValidationError::ReservedName { @@ -194,7 +204,8 @@ 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: "not a valid IP address or CIDR; it is written as 192.168.0.0/16" + .to_string(), }); } } @@ -300,7 +311,7 @@ mod tests { fn a_key_written_as_a_mapping_says_what_to_write_instead() { let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n key:\n whatever: 1\n"; let e = crate::try_parse(y).unwrap_err().message; - assert!(e.contains("字符串"), "没说该写成什么:{e}"); + assert!(e.contains("a string"), "没说该写成什么:{e}"); } #[test] @@ -326,7 +337,7 @@ mod tests { let e = validate(&cfg(vec![c("d", "tw-1")], vec![x])) .unwrap_err() .to_string(); - assert!(e.contains("「r」"), "{e}"); + assert!(e.contains("`r`"), "{e}"); } #[test] diff --git a/crates/tw-config/src/watch.rs b/crates/tw-config/src/watch.rs index 2d06d1d7..96d88a73 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("changes to {path} could not be watched: {source}")] Start { path: PathBuf, source: notify::Error, diff --git a/crates/tw-control/src/rotation.rs b/crates/tw-control/src/rotation.rs index 0364354e..988b14f4 100644 --- a/crates/tw-control/src/rotation.rs +++ b/crates/tw-control/src/rotation.rs @@ -213,14 +213,14 @@ providers: // 明文密钥的文件里猜结构是不能接受的 let e = tw_config::patch_oauth_tokens(CFG, "已经删掉了", renewal(Some("rt-NEW"), "at")) .unwrap_err(); - assert!(e.to_string().contains("已不存在上游"), "{e}"); + assert!(e.to_string().contains("no longer has an upstream"), "{e}"); } #[test] fn a_provider_without_oauth_is_refused_rather_than_rewritten() { let e = tw_config::patch_oauth_tokens(CFG, "官方", renewal(Some("rt-NEW"), "at")).unwrap_err(); - assert!(e.to_string().contains("无法定位"), "{e}"); + assert!(e.to_string().contains("could not be located"), "{e}"); } #[test] diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 261433c3..2f582ce6 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -360,7 +360,7 @@ async fn a_client_whose_mcp_shape_we_have_not_verified_refuses_and_explains() { ) .await; assert_eq!(st, StatusCode::NOT_IMPLEMENTED, "{out}"); - assert!(out.contains("未经验证"), "{out}"); + assert!(out.contains("is unverified"), "{out}"); } #[tokio::test] diff --git a/crates/tw-control/tests/dryrun.rs b/crates/tw-control/tests/dryrun.rs index b5164b15..3aa371ed 100644 --- a/crates/tw-control/tests/dryrun.rs +++ b/crates/tw-control/tests/dryrun.rs @@ -30,7 +30,7 @@ groups: session_affinity: false providers: [官方, 中转] routes: - - name: 默认 + - name: default rules: - name: 带缓存的必须走官方 when: { cache: true } @@ -102,7 +102,7 @@ async fn a_plain_request_falls_through_to_the_catch_all() { assert_eq!(r.rule.as_deref(), Some("其余都试试")); assert_eq!(r.via_group.as_deref(), Some("都试试")); assert_eq!(r.candidates.len(), 2); - assert_eq!(r.route, "默认"); + assert_eq!(r.route, "default"); // 开着会话粘滞(默认)的轮询不伤缓存:同一次对话始终落在同一家。 // 一律标成危险是假警报,而假警报会让人学会忽略这一栏 assert!(!r.hurts_cache, "粘滞的轮询不该报"); @@ -136,8 +136,8 @@ async fn without_a_key_or_a_route_it_refuses_instead_of_guessing() { #[tokio::test] async fn a_route_can_be_tried_by_name_and_a_draft_as_written() { let (_d, app) = app(); - let r = run(&app, r#"{"model":"claude-sonnet-4-5","route":"默认"}"#).await; - assert_eq!(r.route, "默认"); + let r = run(&app, r#"{"model":"claude-sonnet-4-5","route":"default"}"#).await; + assert_eq!(r.route, "default"); assert_eq!(r.rule.as_deref(), Some("其余都试试")); let r = run( diff --git a/crates/tw-control/tests/pricing.rs b/crates/tw-control/tests/pricing.rs index 0a8b1375..2afaae69 100644 --- a/crates/tw-control/tests/pricing.rs +++ b/crates/tw-control/tests/pricing.rs @@ -305,7 +305,7 @@ async fn a_sheet_with_a_half_written_override_is_refused_with_the_reason() { .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); assert!( - body["text"].as_str().unwrap().contains("长上下文"), + body["text"].as_str().unwrap().contains("long-context"), "{body}" ); assert_eq!(b.file(), BASE); @@ -486,7 +486,11 @@ async fn a_refresh_saves_the_new_table_and_prices_with_it_straight_away() { async fn a_failed_refresh_keeps_the_table_and_reports_why() { for (code, body, says) in [ (500, "internal error", "HTTP 500"), - (200, r#"{"error": "rate limited"}"#, "不是价格数据集"), + ( + 200, + r#"{"error": "rate limited"}"#, + "may not be a price data set", + ), ] { let (url, _) = price_source(code, body).await; let b = bed_with(BASE, Updater::new(url, Schedule::default())); diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index a234c998..5ecb833d 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -218,7 +218,10 @@ async fn a_duplicate_name_and_a_stale_version_are_both_conflicts() { ) .await; assert_eq!(st, StatusCode::CONFLICT, "{body}"); - assert!(body.contains("已存在名为「官方」的上游"), "{body}"); + assert!( + body.contains("there is already a upstream named `官方`"), + "{body}" + ); let (st, body) = call( &b.app, @@ -322,7 +325,7 @@ async fn a_claude_subscription_login_cannot_be_saved_as_oauth() { ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); - assert!(body.contains("Claude 订阅账号"), "{body}"); + assert!(body.contains("Claude subscription sign-in"), "{body}"); assert_eq!(b.parsed().providers.len(), 1); } diff --git a/crates/tw-control/tests/routes.rs b/crates/tw-control/tests/routes.rs index e190a4aa..76c16c44 100644 --- a/crates/tw-control/tests/routes.rs +++ b/crates/tw-control/tests/routes.rs @@ -159,11 +159,11 @@ fn enc(s: &str) -> String { async fn the_overview_says_what_is_synthesised_and_gives_every_rule_in_full() { let b = bed(BASE); let ov = b.overview().await; - let default = find(&ov["routes"], "默认"); + let default = find(&ov["routes"], "default"); assert_eq!(default["default"], true); assert_eq!(default["builtin"], true, "配置文件里没有它:{default}"); assert_eq!(default["has_catch_all"], true); - assert_eq!(default["rules"][0]["name"], "兜底"); + assert_eq!(default["rules"][0]["name"], "catch-all"); assert_eq!(default["rules"][0]["to"], "__all__"); assert_eq!(default["rules"][0]["catch_all"], true); @@ -191,8 +191,8 @@ async fn saving_the_synthesised_default_route_writes_it_into_the_file() { let (st, v) = call( &b.app, "PUT", - &format!("/routes/{}", enc("默认")), - json!({ "route": { "name": "默认", "rules": [ + &format!("/routes/{}", enc("default")), + json!({ "route": { "name": "default", "rules": [ rule("长上下文", json!([{ "field": "input_tokens", "values": [">200k"] }]), "中转"), catch_all("__all__"), ]}}), @@ -200,7 +200,7 @@ async fn saving_the_synthesised_default_route_writes_it_into_the_file() { .await; assert_eq!(st, StatusCode::OK, "{v}"); let cfg = b.parsed(); - let r = cfg.routes.iter().find(|r| r.name == "默认").unwrap(); + let r = cfg.routes.iter().find(|r| r.name == "default").unwrap(); assert_eq!( r.rules.iter().map(|x| x.name.as_str()).collect::>(), ["长上下文", "兜底"] @@ -211,7 +211,7 @@ async fn saving_the_synthesised_default_route_writes_it_into_the_file() { assert!(!file.contains("default_route"), "{file}"); assert!(file.contains("# 两家上游"), "{file}"); assert_eq!( - find(&b.overview().await["routes"], "默认")["builtin"], + find(&b.overview().await["routes"], "default")["builtin"], false ); } @@ -287,7 +287,7 @@ async fn the_name_of_the_synthesised_default_is_taken() { &b.app, "POST", "/routes", - json!({ "route": { "name": "默认", "rules": [catch_all("中转")] } }), + json!({ "route": { "name": "default", "rules": [catch_all("中转")] } }), ) .await; assert_eq!(st, StatusCode::CONFLICT); @@ -329,7 +329,7 @@ async fn a_broken_condition_is_refused_before_anything_is_written() { // 少了比较符:写进去的后果是这条规则永远不命中 ( json!([{ "field": "input_tokens", "values": ["200k"] }]), - "比较符", + "comparison operator", ), ( json!([{ "field": "dialect", "values": ["anthorpic"] }]), @@ -457,7 +457,7 @@ async fn the_default_route_cannot_be_deleted() { let (st, v) = call( &b.app, "DELETE", - &format!("/routes/{}", enc("默认")), + &format!("/routes/{}", enc("default")), json!(null), ) .await; @@ -474,12 +474,18 @@ async fn changing_the_default_keeps_the_synthesised_one_as_an_ordinary_route() { let kept = cfg .routes .iter() - .find(|r| r.name == "默认") + .find(|r| r.name == "default") .expect("「默认」留下来"); assert_eq!(kept.rules[0].to.as_deref(), Some("__all__")); // 换回来:默认值不写进文件 - let (st, v) = call(&b.app, "PUT", "/default_route", json!({ "name": "默认" })).await; + let (st, v) = call( + &b.app, + "PUT", + "/default_route", + json!({ "name": "default" }), + ) + .await; assert_eq!(st, StatusCode::OK, "{v}"); assert!(!b.file().contains("default_route"), "{}", b.file()); } diff --git a/crates/tw-dialect/src/anthropic/request.rs b/crates/tw-dialect/src/anthropic/request.rs index 8968f7c6..3421d2a0 100644 --- a/crates/tw-dialect/src/anthropic/request.rs +++ b/crates/tw-dialect/src/anthropic/request.rs @@ -13,7 +13,7 @@ const IMAGE_MIMES: &[&str] = &["image/jpeg", "image/png", "image/gif", "image/we /// 客户端发来的 Anthropic 请求 → 中间表示。 pub fn decode_request(v: &Value, dropped: &mut Dropped) -> Result { if !v.is_object() { - return Err(Rejection("请求体不是 JSON 对象。".into())); + return Err(Rejection("The request body is not a JSON object.".into())); } let mut r = Request { model: str_of(v, "model").unwrap_or_default().to_string(), diff --git a/crates/tw-dialect/src/chat/request.rs b/crates/tw-dialect/src/chat/request.rs index e0659856..7743d882 100644 --- a/crates/tw-dialect/src/chat/request.rs +++ b/crates/tw-dialect/src/chat/request.rs @@ -14,7 +14,7 @@ pub fn decode_request( shape: &mut ClientShape, ) -> Result { if !v.is_object() { - return Err(Rejection("请求体不是 JSON 对象。".into())); + return Err(Rejection("The request body is not a JSON object.".into())); } let mut r = Request { model: str_of(v, "model").unwrap_or_default().to_string(), diff --git a/crates/tw-dialect/src/convert.rs b/crates/tw-dialect/src/convert.rs index 732e3bbd..9c3ba8ba 100644 --- a/crates/tw-dialect/src/convert.rs +++ b/crates/tw-dialect/src/convert.rs @@ -61,7 +61,7 @@ pub fn decode( Dialect::Gemini => { let (model, stream) = gemini_path(path).ok_or_else(|| { Rejection(format!( - "无法从路径 {path} 中读出 Gemini 的模型和调用方式。" + "The path {path} does not say which Gemini model to call, or how." )) })?; shape.gemini_sse = query.is_some_and(|q| q.split('&').any(|kv| kv == "alt=sse")); @@ -132,8 +132,8 @@ pub fn prepare( query: Option<&str>, target: &Target, ) -> Result { - let v: Value = - serde_json::from_slice(body).map_err(|_| Rejection("请求体不是合法的 JSON。".into()))?; + let v: Value = serde_json::from_slice(body) + .map_err(|_| Rejection("The request body is not valid JSON.".into()))?; Ok(decode(client, &v, path, query)?.encode(target)) } @@ -265,7 +265,7 @@ impl Session { let text = String::from_utf8_lossy(body); let text = text.trim(); if text.is_empty() { - format!("上游返回 HTTP {status},没有附带说明。") + format!("The upstream answered HTTP {status} with nothing else.") } else { text.chars().take(2000).collect() } @@ -847,7 +847,7 @@ mod tests { &target(Dialect::Chat), ) .unwrap_err(); - assert_eq!(e.0, "请求体不是合法的 JSON。"); + assert_eq!(e.0, "The request body is not valid JSON."); } #[test] diff --git a/crates/tw-dialect/src/gemini/request.rs b/crates/tw-dialect/src/gemini/request.rs index b71eb821..24d0fb75 100644 --- a/crates/tw-dialect/src/gemini/request.rs +++ b/crates/tw-dialect/src/gemini/request.rs @@ -45,11 +45,11 @@ pub fn decode_request( dropped: &mut Dropped, ) -> Result { if !v.is_object() { - return Err(Rejection("请求体不是 JSON 对象。".into())); + return Err(Rejection("The request body is not a JSON object.".into())); } if field(v, "cachedContent").is_some_and(|c| !c.is_null()) { return Err(Rejection( - "请求使用了 cachedContent,缓存内容保存在 Google 服务端,无法转换到其他格式的上游。" + "The request uses cachedContent, which lives on Google's servers, so it cannot be converted for an upstream of another format." .into(), )); } diff --git a/crates/tw-dialect/src/gemini/stream.rs b/crates/tw-dialect/src/gemini/stream.rs index 2ddd8ca1..12bfa3d6 100644 --- a/crates/tw-dialect/src/gemini/stream.rs +++ b/crates/tw-dialect/src/gemini/stream.rs @@ -43,7 +43,9 @@ impl Parser { pub fn chunk(&mut self, v: &Value, out: &mut Vec) { if let Some(e) = v.get("error") { out.push(Event::Error { - message: str_of(e, "message").unwrap_or("上游返回错误").to_string(), + message: str_of(e, "message") + .unwrap_or("the upstream returned an error") + .to_string(), }); return; } diff --git a/crates/tw-dialect/src/responses/request.rs b/crates/tw-dialect/src/responses/request.rs index 3ac1918e..9284a609 100644 --- a/crates/tw-dialect/src/responses/request.rs +++ b/crates/tw-dialect/src/responses/request.rs @@ -18,22 +18,25 @@ pub fn decode_request( shape: &mut ClientShape, ) -> Result { if !v.is_object() { - return Err(Rejection("请求体不是 JSON 对象。".into())); + return Err(Rejection("The request body is not a JSON object.".into())); } for (key, what) in [ - ("previous_response_id", "对话内容保存在 OpenAI 服务端"), - ("conversation", "对话内容保存在 OpenAI 服务端"), - ("prompt", "提示模板保存在 OpenAI 服务端"), + ( + "previous_response_id", + "the conversation lives on OpenAI's servers", + ), + ("conversation", "the conversation lives on OpenAI's servers"), + ("prompt", "the prompt template lives on OpenAI's servers"), ] { if has(v, key) { return Err(Rejection(format!( - "请求使用了 {key},{what},无法转换到其他格式的上游。" + "The request uses {key}, and {what}, so it cannot be converted for an upstream of another format." ))); } } if v.get("background").and_then(Value::as_bool) == Some(true) { return Err(Rejection( - "请求使用了 background,后台运行只有 OpenAI 服务端支持,无法转换到其他格式的上游。" + "The request uses background, which only OpenAI's servers support, so it cannot be converted for an upstream of another format." .into(), )); } @@ -288,13 +291,13 @@ fn decode_item(item: &Value, dropped: &mut Dropped, r: &mut Request) -> Result<( } "item_reference" => { return Err(Rejection( - "input 中的 item_reference 引用了 OpenAI 服务端保存的内容,无法转换到其他格式的上游。" + "An item_reference in input points at something kept on OpenAI's servers, so the request cannot be converted for an upstream of another format." .into(), )); } "compaction" => { return Err(Rejection( - "input 中的 compaction 是 OpenAI 压缩后的加密对话,只有 OpenAI 能读取,无法转换到其他格式的上游。" + "A compaction in input is an encrypted, compacted conversation only OpenAI can read, so the request cannot be converted for an upstream of another format." .into(), )); } @@ -702,7 +705,7 @@ mod tests { r#"{"model":"m","background":true,"input":"hi"}"#, ] { let e = decode(body).unwrap_err(); - assert!(e.0.contains("无法转换"), "{body}: {e}"); + assert!(e.0.contains("cannot be converted"), "{body}: {e}"); } // null 不算用了 assert!(decode(r#"{"model":"m","previous_response_id":null,"input":"hi"}"#).is_ok()); diff --git a/crates/tw-dialect/src/responses/stream.rs b/crates/tw-dialect/src/responses/stream.rs index 86a7b2f9..0f380b7f 100644 --- a/crates/tw-dialect/src/responses/stream.rs +++ b/crates/tw-dialect/src/responses/stream.rs @@ -290,7 +290,7 @@ impl Parser { .get("response") .and_then(|r| r.get("error")) .and_then(|e| str_of(e, "message")) - .unwrap_or("上游返回 response.failed") + .unwrap_or("the upstream returned response.failed") .to_string(), }), "error" => out.push(Event::Error { diff --git a/crates/tw-engine/src/engine.rs b/crates/tw-engine/src/engine.rs index 2c7b9412..aaec0808 100644 --- a/crates/tw-engine/src/engine.rs +++ b/crates/tw-engine/src/engine.rs @@ -434,7 +434,7 @@ pub struct RouteSet { } /// 默认路由的名字。顶层没写 `default_route` 时用它。 -pub const DEFAULT_ROUTE: &str = "默认"; +pub const DEFAULT_ROUTE: &str = "default"; /// 内置策略组「全部上游」在配置里的名字:全部上游,按声明顺序故障转移。 /// @@ -446,7 +446,7 @@ pub const DEFAULT_ROUTE: &str = "默认"; pub const ALL_UPSTREAMS: &str = "__all__"; /// 合成的默认路由里那条兜底规则的名字。流量详情里「命中规则」显示的就是它。 -pub const CATCH_ALL_RULE: &str = "兜底"; +pub const CATCH_ALL_RULE: &str = "catch-all"; /// 以这个前缀开头的名字留给内置项。 pub const RESERVED_PREFIX: &str = "__"; @@ -506,25 +506,31 @@ pub enum Outcome2 { #[derive(Debug, thiserror::Error, PartialEq)] pub enum RouteError { - #[error("没有规则命中,且缺少兜底规则。请在末尾添加一条不带 when 的规则")] + #[error("no rule matched, and there is no catch-all. Add a rule without a `when` at the end")] NoMatch, #[error( - "规则「{0}」同时设置了 provider_would_be 和 to。provider_would_be 要在选定上游之后才能求值,这类规则只能使用 set 或 deny" + "rule `{0}` sets both provider_would_be and to. provider_would_be can only be evaluated once an upstream is chosen, so such a rule takes only set or deny" )] PhaseTwoWithTo(String), - #[error("规则「{0}」没有设置 to、deny、set 或 guard,命中后不产生任何效果")] + #[error("rule `{0}` sets none of to, deny, set or guard, so matching it does nothing")] NoAction(String), - #[error("规则「{rule}」指向的「{target}」既不是上游,也不是策略组")] + #[error("rule `{rule}` points at `{target}`, which is neither an upstream nor a group")] UnknownTarget { rule: String, target: String }, - #[error("策略组「{0}」中没有任何上游")] + #[error("group `{0}` has no upstream in it")] EmptyGroup(String), - #[error("存在多个名为「{0}」的策略组。规则按名称引用策略组,名称必须唯一")] + #[error( + "there is more than one group named `{0}`. Rules refer to a group by name, so names have to be unique" + )] DuplicateGroup(String), - #[error("存在多条名为「{0}」的路由。网关密钥按名称绑定路由,路由名称必须唯一")] + #[error( + "there is more than one route named `{0}`. A gateway key binds to a route by name, so names have to be unique" + )] DuplicateRoute(String), - #[error("default_route 指向的路由「{0}」不存在,未绑定路由的网关密钥将无法匹配任何规则")] + #[error( + "default_route points at route `{0}`, which does not exist, so a gateway key with no route of its own matches nothing" + )] UnknownDefaultRoute(String), - #[error("网关密钥「{client}」绑定的路由「{route}」不存在")] + #[error("gateway key `{client}` binds to route `{route}`, which does not exist")] UnknownRoute { client: String, route: String }, #[error(transparent)] Match(#[from] MatchError), @@ -1022,7 +1028,7 @@ mod tests { let e = Engine::new( vec!["a".into(), "b".into()], vec![], - vec![set_of("默认", "a"), set_of("codex 专用", "b")], + vec![set_of("default", "a"), set_of("codex 专用", "b")], None, bind(&[("codex", "codex 专用")]), ); @@ -1032,7 +1038,7 @@ mod tests { .map(|r| r.name.clone()) .collect::>() }; - assert_eq!(names("claude-code"), vec!["默认 的规则"]); + assert_eq!(names("claude-code"), vec!["default 的规则"]); // **绑了的只走它自己那条,默认那条的规则不会跟着来** assert_eq!(names("codex"), vec!["codex 专用 的规则"]); } @@ -1189,7 +1195,7 @@ mod tests { ); let err = e.route(&facts("claude-sonnet-4-5")).unwrap_err(); assert_eq!(err, RouteError::NoMatch); - assert!(err.to_string().contains("兜底")); + assert!(err.to_string().contains("catch-all")); } #[test] @@ -1497,7 +1503,7 @@ mod tests { ); let err = e.validate().unwrap_err(); assert!(matches!(err, RouteError::PhaseTwoWithTo(_))); - assert!(err.to_string().contains("只能使用 set 或 deny"), "{err}"); + assert!(err.to_string().contains("takes only set or deny"), "{err}"); } #[test] diff --git a/crates/tw-engine/src/num.rs b/crates/tw-engine/src/num.rs index 70e727c8..7fc5ffce 100644 --- a/crates/tw-engine/src/num.rs +++ b/crates/tw-engine/src/num.rs @@ -39,13 +39,15 @@ impl Compare { #[derive(Debug, thiserror::Error, PartialEq)] pub enum ParseError { - #[error("比较式为空")] + #[error("the comparison is empty")] Empty, - #[error("「{0}」缺少比较符,应以 > < >= <= = 之一开头,例如 \">200k\"")] + #[error("`{0}` has no comparison operator; it starts with one of > < >= <= =, as in \">200k\"")] NoOperator(String), - #[error("「{0}」中的数字无法解析")] + #[error("the number in `{0}` could not be parsed")] BadNumber(String), - #[error("「{0}」的单位无法识别。支持 k(千)和 m(百万),金额写成 $2.5 的形式")] + #[error( + "the unit in `{0}` is not recognized. k (thousand) and m (million) are; an amount is written as $2.5" + )] BadUnit(String), } diff --git a/crates/tw-engine/src/rule.rs b/crates/tw-engine/src/rule.rs index 83d0b37d..f302e6da 100644 --- a/crates/tw-engine/src/rule.rs +++ b/crates/tw-engine/src/rule.rs @@ -196,7 +196,7 @@ impl When { #[derive(Debug, thiserror::Error, PartialEq)] pub enum MatchError { - #[error("条件 {field} 的写法有误:{source}")] + #[error("condition {field} is written wrongly: {source}")] BadCompare { field: &'static str, source: crate::num::ParseError, diff --git a/crates/tw-pricing/src/lib.rs b/crates/tw-pricing/src/lib.rs index 5e3b10d8..d89c209c 100644 --- a/crates/tw-pricing/src/lib.rs +++ b/crates/tw-pricing/src/lib.rs @@ -92,9 +92,9 @@ pub fn to_micros(usd: f64) -> Micros { #[derive(Debug, thiserror::Error)] pub enum PricingError { - #[error("内置价目表无法解析:{0}")] + #[error("the built-in price sheet could not be parsed: {0}")] Snapshot(String), - #[error("价格数据无法解析:{0}")] + #[error("the price data could not be parsed: {0}")] Dataset(String), } diff --git a/crates/tw-pricing/src/sheet.rs b/crates/tw-pricing/src/sheet.rs index ff53452b..e8602bdb 100644 --- a/crates/tw-pricing/src/sheet.rs +++ b/crates/tw-pricing/src/sheet.rs @@ -102,24 +102,30 @@ pub struct PerMillion { #[derive(Debug, thiserror::Error, PartialEq)] pub enum SheetError { - #[error("存在未填写名称的价目表")] + #[error("a price sheet has no name")] EmptyName, - #[error("价目表名称「{0}」首尾不能包含空白")] + #[error("the price sheet name `{0}` cannot start or end with whitespace")] PaddedName(String), - #[error("价目表名称重复:{0}")] + #[error("the price sheet name {0} appears twice")] DuplicateName(String), - #[error("价目表「{sheet}」的倍率 {value} 无效,倍率必须大于 0")] + #[error( + "the multiplier {value} of price sheet `{sheet}` is not valid; a multiplier is greater than 0" + )] BadMultiplier { sheet: String, value: f64 }, - #[error("价目表「{sheet}」中存在未填写名称的模型")] + #[error("a model in price sheet `{sheet}` has no name")] EmptyModel { sheet: String }, - #[error("价目表「{sheet}」中模型 {model} 的{field}为 {value},单价不能为负数")] + #[error( + "the {field} of model {model} in price sheet `{sheet}` is {value}; a price cannot be negative" + )] BadPrice { sheet: String, model: String, field: &'static str, value: f64, }, - #[error("价目表「{sheet}」中模型 {model} 的长上下文输入单价与输出单价需要同时填写")] + #[error( + "model {model} in price sheet `{sheet}` needs both the long-context input price and the output price, or neither" + )] HalfLongContext { sheet: String, model: String }, } @@ -187,15 +193,15 @@ impl SheetDef { impl PerMillion { fn fields(&self) -> Vec<(&'static str, f64)> { let mut out = vec![ - ("输入单价", self.input), - ("输出单价", self.output), - ("缓存读取单价", self.cache_read), - ("缓存写入(5 分钟)单价", self.cache_write_5m), - ("缓存写入(1 小时)单价", self.cache_write_1h), + ("input price", self.input), + ("output price", self.output), + ("cache-read price", self.cache_read), + ("cache-write price (5 minutes)", self.cache_write_5m), + ("cache-write price (1 hour)", self.cache_write_1h), ]; for (name, v) in [ - ("长上下文输入单价", self.input_above_200k), - ("长上下文输出单价", self.output_above_200k), + ("long-context input price", self.input_above_200k), + ("long-context output price", self.output_above_200k), ] { if let Some(v) = v { out.push((name, v)); @@ -295,7 +301,7 @@ mod tests { matches!( e, SheetError::BadPrice { - field: "缓存读取单价", + field: "cache-read price", .. } ), diff --git a/crates/tw-pricing/src/table.rs b/crates/tw-pricing/src/table.rs index deda0b88..6f49411a 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(), + "it carries no model with a price, so it may not be a price data set".into(), )); } Ok(prices) diff --git a/crates/tw-redact/src/rules.rs b/crates/tw-redact/src/rules.rs index 4322e96f..50eca776 100644 --- a/crates/tw-redact/src/rules.rs +++ b/crates/tw-redact/src/rules.rs @@ -42,11 +42,11 @@ impl Kind { } pub fn label(&self) -> &'static str { match self { - Kind::ApiKeys => "API 密钥", - Kind::PrivateKeys => "私钥", + Kind::ApiKeys => "API keys", + Kind::PrivateKeys => "private keys", Kind::Jwt => "JWT", - Kind::ConnStrings => "连接串口令", - Kind::Internal => "内网标识", + Kind::ConnStrings => "connection-string passwords", + Kind::Internal => "internal addresses", } } pub fn all() -> &'static [Kind] { diff --git a/crates/tw-redact/src/stream.rs b/crates/tw-redact/src/stream.rs index d1e744d8..76bad304 100644 --- a/crates/tw-redact/src/stream.rs +++ b/crates/tw-redact/src/stream.rs @@ -175,8 +175,8 @@ impl ByteRestorer { }; // 尾巴上那半个字符留到下一块 self.partial = buf[valid..].to_vec(); - let text = - std::str::from_utf8(&buf[..valid]).expect("valid_up_to 之前的字节是合法的 UTF-8"); + let text = std::str::from_utf8(&buf[..valid]) + .expect("the bytes before valid_up_to are valid UTF-8"); self.inner.process(text).into_bytes() } diff --git a/crates/tw-scan/src/hidden.rs b/crates/tw-scan/src/hidden.rs index 783b9baa..d1a70ea3 100644 --- a/crates/tw-scan/src/hidden.rs +++ b/crates/tw-scan/src/hidden.rs @@ -42,15 +42,21 @@ impl Kind { /// 「U+200B ZWSP」对绝大多数人不构成信息。 pub fn why(&self) -> &'static str { match self { - Kind::ZeroWidth => "零宽字符:在编辑器中不可见,但会被模型读取。", + Kind::ZeroWidth => { + "Zero-width characters: invisible in an editor, and read by the model." + } Kind::Tag => { - "Unicode 标签字符:在编辑器中完全不可见,但会原样进入模型上下文,可用于隐藏整段指令。" + "Unicode tag characters: entirely invisible in an editor, carried into the model's context as they are, and able to hide a whole instruction." + } + Kind::Bidi => { + "Bidirectional controls: they make what is on screen read in a different order than the characters actually are." } - Kind::Bidi => "双向控制符:可使屏幕上的显示顺序与实际字符顺序不一致。", Kind::Homoglyph => { - "同形字符:外观与拉丁字母相同,实际是其他字符,常用于伪装命令和域名。" + "Homoglyphs: they look like Latin letters and are other characters, which is how a command or a domain gets disguised." + } + Kind::PrivateUse => { + "Private-use code points: they have no standard meaning, and an instruction file is no place for them." } - Kind::PrivateUse => "私用区码位:没有标准含义,出现在指令文件中即属可疑。", } } } @@ -296,7 +302,7 @@ mod tests { let hits = scan(&text); assert_eq!(hits.len(), 8, "藏了八个字符就该报八处"); assert!(hits.iter().all(|h| h.kind == Kind::Tag)); - assert!(hits[0].kind.why().contains("完全不可见")); + assert!(hits[0].kind.why().contains("entirely invisible")); } #[test] diff --git a/crates/tw-scan/src/report.rs b/crates/tw-scan/src/report.rs index 4f6b5267..22ddf098 100644 --- a/crates/tw-scan/src/report.rs +++ b/crates/tw-scan/src/report.rs @@ -87,7 +87,7 @@ impl McpServer { /// 判断「同名不同配置」用的指纹(矩阵上要标记号)。 pub fn shape(&self) -> String { match &self.url { - Some(u) => format!("远端 {u}"), + Some(u) => format!("remote {u}"), None => format!("{} {}", self.command, self.args.join(" ")), } } @@ -310,9 +310,13 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { path: src.path.clone(), line: h.line, title: format!( - "{} 中含有{}", + "{} contains {}", src.kind.label(), - h.kind.why().split(':').next().unwrap_or("隐藏字符") + h.kind + .why() + .split(':') + .next() + .unwrap_or("hidden characters") ), detail: format!("{}{}", h.kind.why(), src.kind.why()), excerpt: h.line_text, @@ -336,9 +340,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 `{}` is remote", m.name), detail: format!( - "该 server 的地址为 {},使用时相关上下文会发送到该服务器。", + "That server is at {}, and using it sends the surrounding context there.", m.url.as_deref().unwrap_or("") ), excerpt, @@ -372,9 +376,9 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { client: src.client.to_string(), path: src.path.clone(), line, - title: format!("skill「{name}」声明了 allowed-tools: [\"*\"]"), + title: format!("skill `{name}` declares allowed-tools: [\"*\"]"), detail: - "该 skill 可以使用任何工具。这可能是正常需要,建议确认是否确实需要此权限。" + "That skill may use any tool. It may well need to; it is worth confirming that it does." .into(), excerpt, }); @@ -424,8 +428,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!("{} matched rule `{}`", 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 52df5156..9156d2d5 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("the built-in rules file could not be parsed: {0}")] Builtin(String), } @@ -98,12 +98,15 @@ impl Rules { /// 命令行里的那一句。 pub fn summary(&self) -> String { let custom = self.custom(); - let mut s = format!("生效 {} 条", self.rules.len()); + let mut s = format!("{} active", self.rules.len()); if custom > 0 { - s.push_str(&format!(",其中自定义 {custom} 条")); + s.push_str(&format!(", {custom} of them custom")); } if !self.disabled.is_empty() { - s.push_str(&format!(",已停用内置规则 {} 条", self.disabled.len())); + s.push_str(&format!( + ", {} built-in rules disabled", + self.disabled.len() + )); } s } @@ -131,7 +134,7 @@ fn compile(spec: &RuleSpec, group: &'static str, custom: bool, out: &mut Rules) // 工作的安全功能等于没有。但它必须**大声**说出来 —— 静默失效 // 比没有更糟,因为用户以为它在 Err(e) => out.warnings.push(format!( - "规则「{}」的正则表达式有误,该规则未生效:{e}", + "the pattern of rule `{}` is wrong, so the rule is not in effect: {e}", spec.id )), } @@ -165,8 +168,9 @@ pub fn build(user: &tw_config::ScanRules) -> Result { // 「我明明停用了它,怎么还在报」 for id in &user.disable { if !out.disabled.contains(id) { - out.warnings - .push(format!("「{id}」不是内置规则的 id,停用未生效")); + out.warnings.push(format!( + "`{id}` is not the id of a built-in rule, so disabling it did nothing" + )); } } for spec in &user.add { @@ -443,8 +447,8 @@ mod tests { 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 of them custom"), "{s}"); + assert!(s.contains("1 built-in rules disabled"), "{s}"); // injection 组的规则永远不切断 assert!(!rs.rules.iter().find(|x| x.id == "我的").unwrap().high); } diff --git a/crates/tw-scan/src/sources.rs b/crates/tw-scan/src/sources.rs index 673f6c1e..96ff848a 100644 --- a/crates/tw-scan/src/sources.rs +++ b/crates/tw-scan/src/sources.rs @@ -58,20 +58,30 @@ impl Kind { Kind::Hooks => "hook", Kind::Mcp => "MCP server", Kind::Skill => "skill", - Kind::Command => "斜杠命令", + Kind::Command => "slash command", Kind::Agent => "subagent", - Kind::Instructions => "项目指令", + Kind::Instructions => "project instructions", } } /// 为什么它危险。**说清「它能干什么」**,别只说「它是什么」。 pub fn why(&self) -> &'static str { match self { - Kind::Hooks => "hook 在工具调用前后直接执行 shell 命令,无需模型参与即可获得执行权限。", - Kind::Mcp => "MCP server 配置指定了可执行程序及其参数,相当于直接运行该程序。", - Kind::Skill => "SKILL.md 的内容会被注入模型上下文,成为指令。", - Kind::Command => "斜杠命令的内容会被注入模型上下文,成为指令。", - Kind::Agent => "subagent 定义会被注入模型上下文,并可能声明宽松的工具权限。", - Kind::Instructions => "该文件会被自动读入模型上下文。", + Kind::Hooks => { + "A hook runs a shell command before or after a tool call, which is execution without the model taking part." + } + Kind::Mcp => { + "An MCP server entry names an executable and its arguments, which amounts to running that program." + } + Kind::Skill => { + "The content of SKILL.md goes into the model's context and becomes instruction." + } + Kind::Command => { + "The content of a slash command goes into the model's context and becomes instruction." + } + Kind::Agent => { + "A subagent definition goes into the model's context, and it may declare loose tool permissions." + } + Kind::Instructions => "This file is read into the model's context automatically.", } } } @@ -260,7 +270,7 @@ mod tests { // 危险度排序不是装饰:界面按它排,高危项发通知。 assert!(Kind::Hooks < Kind::Mcp); assert!(Kind::Mcp < Kind::Skill); - assert!(Kind::Hooks.why().contains("无需模型参与")); + assert!(Kind::Hooks.why().contains("without the model taking part")); } #[test] diff --git a/crates/tw-scan/src/watch.rs b/crates/tw-scan/src/watch.rs index d794b978..dcb978a4 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("changes to {path} could not be watched: {source}")] Start { path: PathBuf, source: notify::Error, diff --git a/crates/tw-scan/tests/scan.rs b/crates/tw-scan/tests/scan.rs index 2d35ac57..b022eb42 100644 --- a/crates/tw-scan/tests/scan.rs +++ b/crates/tw-scan/tests/scan.rs @@ -131,7 +131,11 @@ 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("without the model taking part"), + "{}", + f.detail + ); // 最高级的排在最前面 —— 界面直接按这个顺序画 assert_eq!(r.findings[0].rule, "curl-pipe-sh"); } @@ -189,7 +193,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("It may well need to"), "{}", f.detail); let sk = r.skills.iter().find(|s| s.name == "万能").unwrap(); assert_eq!(sk.allowed_tools, vec!["*".to_string()]); } @@ -278,7 +282,7 @@ fn a_remote_mcp_server_is_told_apart_from_one_that_runs_a_binary() { let remote = r.mcp.iter().find(|m| m.name == "远端的").unwrap(); assert!(remote.is_third_party()); assert!(remote.command.is_empty()); - assert_eq!(remote.shape(), "远端 https://mcp.example.com/mcp"); + assert_eq!(remote.shape(), "remote https://mcp.example.com/mcp"); let local = r.mcp.iter().find(|m| m.name == "本机的").unwrap(); assert!(!local.is_third_party(), "localhost 不算第三方"); @@ -291,7 +295,11 @@ 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("sends the surrounding context there"), + "{}", + f[0].detail + ); } #[test] diff --git a/crates/tw-secret/src/lib.rs b/crates/tw-secret/src/lib.rs index 3fee107a..d8426699 100644 --- a/crates/tw-secret/src/lib.rs +++ b/crates/tw-secret/src/lib.rs @@ -15,11 +15,11 @@ pub use mask::{ #[derive(Debug, thiserror::Error)] pub enum SecretError { - #[error("环境变量 {0} 未设置")] + #[error("the environment variable {0} is not set")] MissingEnv(String), - #[error("第 {pos} 个字符处的 ${{...}} 未闭合")] + #[error("the ${{...}} at character {pos} is not closed")] Unterminated { pos: usize }, - #[error("变量名为空:${{}}")] + #[error("the variable name is empty: ${{}}")] EmptyName, } diff --git a/crates/tw-secret/src/mask.rs b/crates/tw-secret/src/mask.rs index 9e9ca775..2b8598a9 100644 --- a/crates/tw-secret/src/mask.rs +++ b/crates/tw-secret/src/mask.rs @@ -23,7 +23,7 @@ pub fn mask_secret(s: &str) -> String { /// 「去掉 query」,是「只留 scheme://host:port」。 pub fn redact_url(url: &str) -> String { let Some(scheme_end) = url.find("://") else { - return "<非 URL>".to_string(); + return "".to_string(); }; let rest = &url[scheme_end + 3..]; // userinfo(user:pass@host)整段丢掉 @@ -524,7 +524,7 @@ mod tests { #[test] fn non_url_is_not_echoed_back() { - assert_eq!(redact_url("sk-this-is-actually-a-key"), "<非 URL>"); + assert_eq!(redact_url("sk-this-is-actually-a-key"), ""); } } diff --git a/crates/tw-store/src/blobs.rs b/crates/tw-store/src/blobs.rs index f191cfb3..b2828326 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(), "请求体写入失败:{e}"); + tracing::debug!(path = %p.display(), "the request body could not be written: {e}"); false } } diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index ebd8812b..03d02830 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -48,7 +48,7 @@ const SUBSCRIPTION: &str = "(billing = 'subscription')"; #[derive(Debug, thiserror::Error)] pub enum DbError { - #[error("无法打开 {path}:{source}")] + #[error("{path} could not be opened: {source}")] Open { path: String, source: rusqlite::Error, @@ -56,7 +56,7 @@ pub enum DbError { /// 库是更新版本的程序建的。**只能读不能写** —— 硬写会让那个版本的 /// 数据变成半新半旧,而用户回到新版本时已经修不回来了。 #[error( - "数据库的 schema 版本为 {found},当前版本的 twcore 最高支持 {supported}。请升级应用;如需继续使用当前版本,可将 {path} 移至其他位置,程序会新建空数据库,原有请求记录不会被删除" + "the database is schema version {found}, and this twcore supports up to {supported}. Upgrade the app; to stay on this version, move {path} elsewhere and an empty database is created, leaving the recorded requests where they are" )] TooNew { found: i64, @@ -1788,8 +1788,11 @@ mod tests { let e = Db::open(&p).unwrap_err(); assert!(matches!(e, DbError::TooNew { .. }), "{e:?}"); let m = e.to_string(); - assert!(m.contains("升级"), "{m}"); - assert!(m.contains("不会被删除"), "得说清历史记录的下场:{m}"); + assert!(m.contains("Upgrade the app"), "{m}"); + assert!( + m.contains("leaving the recorded requests where they are"), + "得说清历史记录的下场:{m}" + ); } #[test] diff --git a/crates/tw-store/src/disk.rs b/crates/tw-store/src/disk.rs index da463b88..981c821b 100644 --- a/crates/tw-store/src/disk.rs +++ b/crates/tw-store/src/disk.rs @@ -46,9 +46,13 @@ impl DiskLevel { /// 诊断包和日志里的说法。 pub fn label(&self) -> &'static str { match self { - DiskLevel::Ok => "正常", - DiskLevel::MetadataOnly => "磁盘空间不足,仅记录请求摘要,不保存请求体与响应体", - DiskLevel::Nothing => "磁盘空间严重不足,已停止记录,转发不受影响", + DiskLevel::Ok => "ok", + DiskLevel::MetadataOnly => { + "low disk space: only request summaries are recorded, and no request or response bodies" + } + DiskLevel::Nothing => { + "very low disk space: recording has stopped, and forwarding is unaffected" + } } } } @@ -112,7 +116,9 @@ mod tests { assert!(!l.slug().is_empty()); } assert!( - DiskLevel::Nothing.label().contains("转发不受影响"), + DiskLevel::Nothing + .label() + .contains("forwarding is unaffected"), "最坏的那一级也必须说清楚请求还是通的" ); } diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 461fbef4..1729ddc1 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -428,7 +428,7 @@ impl Recorder { kind: secret.clone(), masked: masked.clone(), }) { - tracing::debug!("泄漏记录写入失败:{e}"); + tracing::debug!("the leak record could not be written: {e}"); } } // 配置事件、额度事件、扫描告警都不是请求,不落这张表。 @@ -589,7 +589,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, "the request row could not be written: {e}"); } } @@ -619,7 +619,7 @@ impl Recorder { } tracing::warn!( free_mb = free / 1024 / 1024, - "磁盘状态已变化:{}", + "the disk state changed: {}", next.label() ); self.level = next; @@ -638,8 +638,8 @@ 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, "已清理过期的请求记录"), - Err(e) => tracing::debug!("清理请求记录失败:{e}"), + Ok(n) if n > 0 => tracing::info!(rows = n, "cleaned up expired request rows"), + Err(e) => tracing::debug!("the request rows could not be cleaned up: {e}"), _ => {} } freed diff --git a/crates/tw-store/src/task.rs b/crates/tw-store/src/task.rs index 5c382c01..e4e33ade 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!("recording fell behind; {n} requests were not recorded"); } 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, "reclaimed expired request bodies"); } } }); diff --git a/crates/tw-yaml/src/edit.rs b/crates/tw-yaml/src/edit.rs index 7639339e..e1cc5f65 100644 --- a/crates/tw-yaml/src/edit.rs +++ b/crates/tw-yaml/src/edit.rs @@ -48,11 +48,15 @@ pub fn put(text: &str, path: &[Step], value: Put<'_>) -> Result) -> Result replace_value(text, &before, n, value)?, None => add_key(text, &before, path, value)?, }; - let after = nodes(&out) - .map_err(|e| PatchError::SelfCheck(format!("写入 {} 后配置无法解析:{e}", show(path))))?; + let after = nodes(&out).map_err(|e| { + PatchError::SelfCheck(format!( + "the configuration could not be parsed after writing {}: {e}", + show(path) + )) + })?; untouched_outside(&before, &after, path)?; lands_as(&after, path, &frag)?; Ok(out) @@ -105,7 +113,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!( - "{}(行内映射中的键只能整体修改)", + "{} (a key of an inline mapping is changed as a whole)", show(path) ))); } @@ -121,7 +129,7 @@ pub fn remove_key(text: &str, path: &[Step]) -> Result { // 而不是一个空映射 —— 整项删是 `remove` 的事 Some(Step::Index(_)) => { return Err(PatchError::NotFound(format!( - "{}(该项只有这一个键,请删除整项)", + "{} (this is the entry's only key; delete the entry itself)", show(path) ))); } @@ -155,11 +163,15 @@ pub fn remove_key(text: &str, path: &[Step]) -> Result { out }; - let after = nodes(&out) - .map_err(|e| PatchError::SelfCheck(format!("删除 {} 后配置无法解析:{e}", show(path))))?; + let after = nodes(&out).map_err(|e| { + PatchError::SelfCheck(format!( + "the configuration could not be parsed after deleting {}: {e}", + show(path) + )) + })?; if after.iter().any(|n| n.path == path) { return Err(PatchError::SelfCheck(format!( - "删除后 {} 仍然存在", + "{} is still there after the delete", show(path) ))); } @@ -206,11 +218,15 @@ 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))))?; + let after = nodes(&out).map_err(|e| { + PatchError::SelfCheck(format!( + "the configuration could not be parsed after replacing {}: {e}", + show(&path) + )) + })?; if count_items(&after, seq_path) != count { return Err(PatchError::SelfCheck(format!( - "替换后 {} 的项数发生了变化", + "the number of entries under {} changed after the replace", show(seq_path) ))); } @@ -335,13 +351,17 @@ fn add_key(text: &str, all: &[Node], path: &[Step], value: Put<'_>) -> Result bool { fn value_end(text: &str, all: &[Node], n: &Node) -> Result { match &n.kind { 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)))), + 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!("{} (the inline form is not closed)", show(&n.path))) + }) + } NodeKind::Map | NodeKind::Seq => { block_end(text, all, &n.path).ok_or_else(|| PatchError::NotFound(show(&n.path))) } @@ -469,9 +491,9 @@ fn untouched_outside(before: &[Node], after: &[Node], path: &[Step]) -> Result<( .zip(a.iter()) .find(|(x, y)| x != y) .map(|(x, _)| show(x.0)) - .unwrap_or_else(|| format!("节点数 {} → {}", b.len(), a.len())); + .unwrap_or_else(|| format!("{} nodes → {}", b.len(), a.len())); return Err(PatchError::SelfCheck(format!( - "写入 {} 时修改了其他位置({diff})", + "writing {} changed something else as well ({diff})", show(path) ))); } @@ -491,7 +513,7 @@ fn lands_as(after: &[Node], path: &[Step], frag: &[Node]) -> Result<(), PatchErr .collect(); if got != want { return Err(PatchError::SelfCheck(format!( - "{} 写入后读回的值与预期不一致", + "the value read back after writing {} is not what was expected", show(path) ))); } diff --git a/crates/tw-yaml/src/lib.rs b/crates/tw-yaml/src/lib.rs index 995fba43..32c34be6 100644 --- a/crates/tw-yaml/src/lib.rs +++ b/crates/tw-yaml/src/lib.rs @@ -59,23 +59,29 @@ impl From for Step { #[derive(Debug, thiserror::Error, PartialEq)] pub enum PatchError { - #[error("YAML 无法解析:{0}")] + #[error("the YAML could not be parsed: {0}")] Parse(String), - #[error("无法在配置中定位 {0}")] + #[error("{0} could not be located in the configuration")] NotFound(String), - #[error("{0} 不是标量值,只有标量值可以直接修改")] + #[error("{0} is not a scalar, and only a scalar can be changed in place")] NotScalar(String), /// **写之前的最后一道闸。**改完在内存里重新解析一遍,对不上就拒绝 /// 写入。开销几百微秒,换来「永远不会写出一个自己都解析不了的文件」。 - #[error("配置修改自检未通过,未写入文件:{0}")] + #[error("the edit did not pass its own check, so nothing was written: {0}")] SelfCheck(String), /// 同一个 map 里出现了两个同名的键。 - #[error("{0} 在配置中重复出现,修改后可能不生效,请先手动删除重复的项")] + #[error( + "{0} appears more than once in the configuration, so a change to it may not take effect; remove the duplicates by hand first" + )] Duplicate(String), - #[error("{0} 是多行文本块(| 或 >),无法自动修改,请直接编辑配置文件")] + #[error( + "{0} is a multi-line block (| or >) and cannot be changed automatically; edit the configuration file directly" + )] BlockScalar(String), /// 锚点和别名让「改一处」不再是改一处。 - #[error("{0} 位于 YAML 锚点或别名(&x / *x)中,修改会影响所有引用处,请直接编辑配置文件")] + #[error( + "{0} sits inside a YAML anchor or alias (&x / *x), so a change reaches every use of it; edit the configuration file directly" + )] AnchorOrAlias(String), } @@ -464,12 +470,16 @@ pub fn set(text: &str, path: &[Step], value: &Scalar) -> Result Result Result let dash = text[line_start..] .find('-') .map(|i| line_start + i) - .ok_or_else(|| PatchError::NotFound(format!("{}(不是块式列表)", show(&want))))?; + .ok_or_else(|| PatchError::NotFound(format!("{} (not a block list)", show(&want))))?; let indent = dash - line_start; // 往后走到下一项的 `-`(同缩进)或者这一块结束 let mut at = text[line_start..] @@ -894,12 +906,15 @@ fn checked_structural( want: usize, ) -> Result { let after = nodes(&out).map_err(|e| { - PatchError::SelfCheck(format!("修改 {} 后配置无法解析:{e}", show(seq_path))) + PatchError::SelfCheck(format!( + "the configuration could not be parsed after changing {}: {e}", + show(seq_path) + )) })?; let got = count_items(&after, seq_path); if got != want { return Err(PatchError::SelfCheck(format!( - "修改后 {} 有 {got} 项,预期为 {want} 项", + "{} has {got} entries after the change, and {want} were expected", show(seq_path) ))); } diff --git a/crates/tw-yaml/tests/preserve.rs b/crates/tw-yaml/tests/preserve.rs index 5b48e7b8..66d8342a 100644 --- a/crates/tw-yaml/tests/preserve.rs +++ b/crates/tw-yaml/tests/preserve.rs @@ -152,7 +152,11 @@ fn a_block_scalar_is_refused_rather_than_reflowed() { let y = "script: |\n echo hi\nport: 1\n"; let e = set(y, &path!["script"], &Scalar::s("echo bye")).unwrap_err(); assert!(matches!(e, PatchError::BlockScalar(_)), "{e:?}"); - assert!(e.to_string().contains("直接编辑"), "{e}"); + assert!( + e.to_string() + .contains("edit the configuration file directly"), + "{e}" + ); } #[test] @@ -171,7 +175,7 @@ fn an_anchor_is_refused_instead_of_silently_changing_every_alias() { let y = "defaults: &d\n timeout: 30\na:\n <<: *d\nb:\n <<: *d\n"; let e = set(y, &path!["defaults"], &Scalar::s("x")).unwrap_err(); assert!(matches!(e, PatchError::AnchorOrAlias(_)), "{e:?}"); - assert!(e.to_string().contains("锚点"), "{e}"); + assert!(e.to_string().contains("anchor or alias"), "{e}"); } #[test] @@ -294,7 +298,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("appears more than once"), "{e}"); } #[test] diff --git a/crates/tw-yaml/tests/property.rs b/crates/tw-yaml/tests/property.rs index a05144d9..07171c68 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("the entry's only key") => continue, Err(PatchError::AnchorOrAlias(_)) | Err(PatchError::Duplicate(_)) => continue, Err(e) => panic!("seed {seed}:{} 删不掉:{e}\n{doc}", show(&target.path)), };