From 3fb60aa79040a924665ad07c5b4c8cedf6d01abc Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:22:58 +0800 Subject: [PATCH] adopt: Linux paths, process names and shell exports - Claude Code managed policy: /etc/claude-code on Linux; Windows moves to %ProgramFiles%\ClaudeCode (the docs say ProgramData is no longer read). - Config locations become `paths::Loc` (home-relative or XDG-relative). opencode (every platform), Zed and Claude Desktop (Linux) honour $XDG_CONFIG_HOME / $XDG_DATA_HOME, but only when the home passed in is the process's own, so tests with a temp home stay isolated. - Claude Desktop on Linux (beta) lives at $XDG_CONFIG_HOME/Claude. - Process detection: parse `ps` lines in one place, match by name prefix (Linux truncates comm to 15 bytes), and give Zed its per-platform process name (`zed-editor` on Linux, `zed` on macOS, `Zed` on Windows). - Shell exports: add .bash_login; match exact variable names on real export statements; parse fish `set` flags (-x/-gx/-Ux/--export, not -e) only in config.fish, so bash's `set -x` is no longer read as an export. - The "delete this line" fix uses GNU sed syntax off macOS (new code adopt.diag.delete_line_gnu). Co-Authored-By: Claude Opus 5.5 --- crates/tw-adopt/src/clients.rs | 71 +++--- crates/tw-adopt/src/detect.rs | 358 ++++++++++++++++++++++++----- crates/tw-adopt/src/mcp.rs | 18 +- crates/tw-adopt/src/paths.rs | 275 +++++++++++++++++----- crates/tw-adopt/tests/roundtrip.rs | 8 +- crates/tw-api/msg-codes.txt | 1 + crates/tw-control/src/clients.rs | 2 +- crates/tw-control/tests/adopt.rs | 2 +- crates/tw-scan/src/sources.rs | 8 +- 9 files changed, 588 insertions(+), 155 deletions(-) diff --git a/crates/tw-adopt/src/clients.rs b/crates/tw-adopt/src/clients.rs index 0263f2ed..d27255bb 100644 --- a/crates/tw-adopt/src/clients.rs +++ b/crates/tw-adopt/src/clients.rs @@ -14,6 +14,7 @@ use serde::{Deserialize, Serialize}; use tw_types::{Msg, msg}; use crate::json::Val; +use crate::paths::Loc; /// 配置文件是什么格式。**决定了怎么做字段级合并,以及哨兵往哪儿放。** #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -103,8 +104,8 @@ impl Verified { pub struct Client { pub id: &'static str, pub name: &'static str, - /// 配置文件,相对 `$HOME` - pub config: &'static str, + /// 配置文件 + pub config: Loc, pub format: Format, pub takes_effect: TakesEffect, /// 优先级比主配置更高、会盖住我们的那些文件(诊断链)。 @@ -120,12 +121,15 @@ pub struct Client { /// 不认识这个码的客户端。 pub costs: &'static [(&'static str, &'static str)], pub verified: Verified, - /// 判断「这台机器上装了它吗」的痕迹,相对 `$HOME`。 + /// 判断「这台机器上装了它吗」的痕迹。 /// /// 不能只看配置文件在不在:`.aider.conf.yml` 这种,没接管过的用户 /// 本来就没有;而 `~/.claude/` 这种,装了就一定有。 - pub marker: &'static [&'static str], - /// 进程名里认得出它的片段。诊断「客户端没重启」要用。 + pub marker: &'static [Loc], + /// 认得出它的进程名开头。诊断「客户端没重启」要用。 + /// + /// **是开头,不是全名**:Linux 的进程名截到 15 个字节,带目标三元组的 + /// 二进制名(`codex-x86_64-unknown-linux-musl`)截完只剩前面一段。 pub process: &'static [&'static str], /// 它会读的环境变量。扫 shell 配置时找这些名字。 pub env_vars: &'static [&'static str], @@ -192,6 +196,21 @@ fn secret(path: &[&str], value: Val) -> Edit { /// Codex 的 `openai` / `ollama` / `lmstudio` 是保留 id,不能撞。 pub const PROVIDER_ID: &str = "thinkwatch"; +/// Zed 的进程名。 +/// +/// 三个平台各是各的,照 Zed 自己的打包脚本:macOS 上是 +/// `Zed.app/Contents/MacOS/zed`(`ps` 给的是路径,取最后一段就是小写的 +/// `zed`);Linux 的包把编辑器放在 `libexec/zed-editor`,`bin/zed` 只是个 +/// 命令行前端 —— 认前者,否则一个挂着 `--wait` 的命令行会被当成编辑器; +/// Windows 上是 `Zed.exe`。 +const ZED_PROCESS: &str = if cfg!(windows) { + "Zed" +} else if cfg!(target_os = "macos") { + "zed" +} else { + "zed-editor" +}; + /// 表一:能接管 API 端点的。 /// /// 字段名都对应上游当前文档,不是猜的。 @@ -200,7 +219,7 @@ pub fn adoptable() -> Vec { Client { id: "claude-code", name: "Claude Code", - config: ".claude/settings.json", + config: Loc::Home(".claude/settings.json"), format: Format::Json, takes_effect: TakesEffect::Immediately, // **`settings.local.json` 优先级更高。**cc-switch #6828 栽在这里 @@ -220,7 +239,7 @@ pub fn adoptable() -> Vec { ), ], verified: Verified::FieldsOnly, - marker: &[".claude"], + marker: &[Loc::Home(".claude")], process: &["claude"], env_vars: &[ "ANTHROPIC_BASE_URL", @@ -234,14 +253,15 @@ pub fn adoptable() -> Vec { }, // **不叫「Codex CLI」。**`~/.codex/config.toml` 是一份配置、两个 // 前端:命令行的 codex,和 ChatGPT 桌面版内置的那一个 - // (`ChatGPT.app/Contents/Resources/codex`,同一个二进制)。桌面版 + // (macOS 上是 `ChatGPT.app/Contents/Resources/codex`,同一个二进制; + // Windows 和 Linux 上也有这个桌面版)。桌面版 // 启动 app-server 时不带任何 provider 覆盖,`model_provider` 完全 // 由这个文件决定 —— 只装了桌面版的用户看到「Codex CLI」,会以为 // 在说一个他没装的东西。 Client { id: "codex", name: "Codex", - config: ".codex/config.toml", + config: Loc::Home(".codex/config.toml"), format: Format::Toml, // **读环境变量的,必须关掉终端重开** takes_effect: TakesEffect::OnRestart, @@ -260,7 +280,7 @@ pub fn adoptable() -> Vec { ), ], verified: Verified::Measured, - marker: &[".codex"], + marker: &[Loc::Home(".codex")], process: &["codex"], env_vars: &["OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_HOME"], key_elsewhere: None, @@ -269,7 +289,7 @@ pub fn adoptable() -> Vec { Client { id: "opencode", name: "opencode", - config: ".config/opencode/opencode.json", + config: crate::paths::OPENCODE_CONFIG, format: Format::Json, takes_effect: TakesEffect::OnRestart, shadowed_by: &[], @@ -278,7 +298,7 @@ pub fn adoptable() -> Vec { "opencode has to be restarted afterwards.", )], verified: Verified::FieldsOnly, - marker: &[".config/opencode", ".local/share/opencode"], + marker: &[Loc::XdgConfig("opencode"), Loc::XdgData("opencode")], process: &["opencode"], env_vars: &["OPENAI_API_KEY", "OPENAI_BASE_URL"], key_elsewhere: None, @@ -287,7 +307,7 @@ pub fn adoptable() -> Vec { Client { id: "zed", name: "Zed", - config: crate::paths::zed_settings(), + config: crate::paths::ZED_SETTINGS, format: Format::Json, takes_effect: TakesEffect::Immediately, shadowed_by: &[], @@ -299,7 +319,7 @@ pub fn adoptable() -> Vec { )], verified: Verified::FieldsOnly, marker: &[crate::paths::ZED_DIR], - process: &["Zed"], + process: &[ZED_PROCESS], env_vars: &[], key_elsewhere: Some(( code!("adopt.manual.zed.key"), @@ -310,7 +330,7 @@ pub fn adoptable() -> Vec { Client { id: "aider", name: "Aider", - config: ".aider.conf.yml", + config: Loc::Home(".aider.conf.yml"), format: Format::Yaml, takes_effect: TakesEffect::OnRestart, // **三层查找,后面的覆盖前面的**(home → 仓库根 → cwd)。 @@ -328,7 +348,10 @@ pub fn adoptable() -> Vec { ], verified: Verified::FieldsOnly, // 没接管过的用户本来就没有这个文件,所以它自己就是那个痕迹 - marker: &[".aider.conf.yml", ".aider.model.settings.yml"], + marker: &[ + Loc::Home(".aider.conf.yml"), + Loc::Home(".aider.model.settings.yml"), + ], process: &["aider"], env_vars: &["OPENAI_API_BASE", "OPENAI_API_KEY"], key_elsewhere: None, @@ -634,7 +657,7 @@ impl Client { /// **没检测到它的时候也要给。**配置文件不在默认位置、或者装在别的 /// 用户目录下时,检测不到不等于用不了 —— 照着做一样能接上。 pub fn manual_steps(&self) -> Vec { - let file = crate::paths::shown(self.config); + let file = self.config.shown(); let mut out = vec![msg!( "adopt.manual.file", file = file => "Open {file} and set the fields below." @@ -661,7 +684,7 @@ impl Client { } pub fn config_path(&self, home: &std::path::Path) -> PathBuf { - crate::paths::under(home, self.config) + self.config.resolve(home) } pub fn shadow_paths(&self, home: &std::path::Path) -> Vec { self.shadowed_by @@ -691,9 +714,10 @@ mod tests { ids.dedup(); assert_eq!(ids.len(), n, "有重复的 id"); for c in &cs { + let home = std::path::Path::new("/h"); assert!( - !c.config.starts_with('/'), - "{} 的路径该是相对 home 的", + c.config_path(home).starts_with(home), + "{} 的路径该在 home 底下", c.id ); assert!(!c.name.is_empty()); @@ -847,12 +871,7 @@ mod tests { for c in adoptable() { let steps = c.manual_steps(); // 写法按平台(`~/…` 或 `%USERPROFILE%\…`),各自的样子见 paths 里那条测试 - assert_eq!( - steps[0].arg("file"), - crate::paths::shown(c.config), - "{}", - c.id - ); + assert_eq!(steps[0].arg("file"), c.config.shown(), "{}", c.id); assert!(!edits(&c, &gw).is_empty(), "{}:没有要写的字段", c.id); } // Zed 的密钥不在配置文件里,多一步在它自己的设置里填 diff --git a/crates/tw-adopt/src/detect.rs b/crates/tw-adopt/src/detect.rs index 88c06318..52687f4d 100644 --- a/crates/tw-adopt/src/detect.rs +++ b/crates/tw-adopt/src/detect.rs @@ -86,11 +86,7 @@ pub fn detect_one(c: &Client, home: &Path) -> Detected { Detected { id: c.id, name: c.name, - installed: c - .marker - .iter() - .any(|m| crate::paths::under(home, m).exists()) - || text.is_some(), + installed: c.marker.iter().any(|m| m.resolve(home).exists()) || text.is_some(), has_config: text.is_some(), adopted_at_ms: rec .filter(|r: &SidecarRecord| r.client == c.id) @@ -179,11 +175,47 @@ fn parse_etime(s: &str) -> Option { Some(days * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2]) } -/// 正在跑的进程里,匹配这些片段的那些各自启动于什么时候(毫秒时间戳)。 +/// `ps -Ao pid=,etime=,comm=` 的一行:跑了多少秒、进程名。 +/// +/// 两个平台给的 `comm` 不是一回事:macOS 上是可执行文件的**完整路径** +/// (可以带空格,`Claude Helper (Renderer).app/…`),Linux 上是内核记的 +/// 进程名,最多 15 个字节、不带路径。取最后一个 `/` 之后那段,两边就都是 +/// 名字了。 +#[cfg(not(windows))] +fn parse_ps_line(line: &str) -> Option<(u64, &str)> { + let line = line.trim_start(); + let (_pid, rest) = line.split_once(char::is_whitespace)?; + let rest = rest.trim_start(); + let (etime, comm) = rest.split_once(char::is_whitespace)?; + let comm = comm.trim(); + let name = comm.rsplit('/').next().unwrap_or(comm); + Some((parse_etime(etime)?, name)) +} + +/// 进程名是不是这些标记之一开头的。 +/// +/// **比开头,不比包含**:包含的话 `zed` 会认下任何名字里带这三个字母的 +/// 进程。也不比全名:Linux 把进程名截到 15 个字节,带目标三元组的二进制 +/// 名截完只剩前一段,而那一段仍然以标记开头。 +#[cfg(not(windows))] +fn is_one_of(name: &str, markers: &[&str]) -> bool { + markers.iter().any(|m| name.starts_with(m)) +} + +/// 正在跑的进程里,匹配这些标记的那些各自启动于什么时候(毫秒时间戳)。 +/// +/// **npm 装的客户端认的是真正干活的那个原生进程**:Codex 的 npm 包是个 +/// node 包装层(进程名 `node`),它再起 `vendor/…/codex`;Claude Code 和 +/// opencode 的 npm 包直接装原生二进制。认 `node` 等于认下这台机器上所有 +/// node 程序,所以不认。 #[cfg(not(windows))] fn running_since(markers: &[&str]) -> Vec { // 写死绝对路径:按 PATH 找的话,谁往 PATH 前面塞一个同名程序,它就跟着 - // core 一起跑起来了。macOS 和常见 Linux 发行版上都在这里 + // core 一起跑起来了。macOS 和常见 Linux 发行版上都在这里(/bin 在 + // Fedora、Arch、新的 Debian/Ubuntu 上是指向 /usr/bin 的链接)。 + // + // 极简发行版可能根本没装 procps:那时起不来,当成「没在跑」 —— 这一条 + // 本来就是个提示,不值得为它报错。 let Ok(out) = std::process::Command::new("/bin/ps") .args(["-Ao", "pid=,etime=,comm="]) .output() @@ -193,17 +225,9 @@ fn running_since(markers: &[&str]) -> Vec { let now = now_ms(); String::from_utf8_lossy(&out.stdout) .lines() - .filter_map(|line| { - let mut it = line.split_whitespace(); - let _pid = it.next()?; - let etime = it.next()?; - let cmd = line.split_once(etime).map(|(_, r)| r).unwrap_or(""); - let name = cmd.rsplit('/').next().unwrap_or(cmd); - if !markers.iter().any(|m| name.contains(m)) { - return None; - } - Some(now.saturating_sub(parse_etime(etime)? * 1000)) - }) + .filter_map(parse_ps_line) + .filter(|(_, name)| is_one_of(name, markers)) + .map(|(secs, _)| now.saturating_sub(secs * 1000)) .collect() } @@ -345,12 +369,7 @@ fn env_conflicts(home: &Path, names: &[&str]) -> Vec { => "{path} exports {name} on line {line}" ), // 命令给出来,执行与否是他的事 - fix: msg!( - "adopt.diag.delete_line", - path = f.display(), - line = line - => "sed -i '' '{line}d' {path}" - ), + fix: delete_line(&f, line), overrides: |client| { msg!( "adopt.diag.shell_export.overrides", @@ -444,37 +463,119 @@ fn env_conflicts(_home: &Path, names: &[&str]) -> Vec { out } +/// 删掉某个文件第几行的那条命令。 +/// +/// **两个平台的 sed 不是一个 sed。**macOS 的 BSD sed 里 `-i` 必须跟一个备份 +/// 后缀(空串就是不备份);GNU sed 的后缀是贴在 `-i` 上的,`-i ''` 会把 `''` +/// 当成脚本、把 `'3d'` 当成文件名 —— 照抄过去只会报「找不到文件 3d」。两句 +/// 不同的命令,各用各的码。 +#[cfg(target_os = "macos")] +fn delete_line(path: &Path, line: usize) -> Msg { + msg!( + "adopt.diag.delete_line", + path = path.display(), + line = line + => "sed -i '' '{line}d' {path}" + ) +} +#[cfg(all(not(windows), not(target_os = "macos")))] +fn delete_line(path: &Path, line: usize) -> Msg { + msg!( + "adopt.diag.delete_line_gnu", + path = path.display(), + line = line + => "sed -i '{line}d' {path}" + ) +} + +/// 要看的 shell 配置文件,相对 home,以及它是不是 fish 的。 +/// +/// bash 登录时读 `.bash_profile`、`.bash_login`、`.profile` 里先找到的那一个, +/// 交互时读 `.bashrc`;Linux 上多数人用的是 bash,这几个都得在。 +#[cfg(not(windows))] +const SHELL_FILES: &[(&str, bool)] = &[ + (".zshrc", false), + (".zprofile", false), + (".zshenv", false), + (".bashrc", false), + (".bash_profile", false), + (".bash_login", false), + (".profile", false), + (".config/fish/config.fish", true), +]; + +/// 这一行导出了哪些变量。 +/// +/// **只认真的导出语句,而且按变量名整个比**,不看「这一行里有没有这串字」: +/// `export ANTHROPIC_BASE_URL_OLD=…` 不是在设 `ANTHROPIC_BASE_URL`,而 +/// `echo $OPENAI_BASE_URL` 什么也没设。 +/// +/// - sh 系:`export A=1 B=2`、`export A`(把已有的变量导出去,一样算)。 +/// - fish:`set` 带上导出标志才算 —— `-x`、`-gx`、`-Ux`、`--export`,标志 +/// 可以分开写。`set -e` 是删掉它,不算。**`set -x` 在 bash 里是另一回事** +/// (打开命令回显),所以这一套只用在 fish 的文件上。 +/// +/// 注释掉的不算。**这个判断很便宜,但漏掉它就会天天误报** —— 而误报几次 +/// 之后,真正该看的那一次也不会被看。 +#[cfg(not(windows))] +fn exported_names(line: &str, fish: bool) -> Vec<&str> { + let t = line.trim_start(); + if t.starts_with('#') { + return Vec::new(); + } + let mut words = t.split_whitespace(); + let is_name = |w: &str| { + !w.is_empty() + && !w.starts_with(|c: char| c.is_ascii_digit()) + && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + }; + if fish { + if words.next() != Some("set") { + return Vec::new(); + } + let (mut export, mut erase) = (false, false); + for w in words { + if let Some(long) = w.strip_prefix("--") { + export |= long == "export"; + erase |= long == "erase"; + } else if let Some(short) = w.strip_prefix('-') { + export |= short.contains('x'); + erase |= short.contains('e'); + } else { + // 标志之后第一个词就是变量名 + return if export && !erase && is_name(w) { + vec![w] + } else { + Vec::new() + }; + } + } + Vec::new() + } else { + if words.next() != Some("export") { + return Vec::new(); + } + words + .take_while(|w| !w.starts_with('#')) + .map(|w| w.split_once('=').map_or(w, |(n, _)| n)) + .filter(|n| is_name(n)) + .collect() + } +} + /// shell 配置里 export 了同名变量的那些行。 #[cfg(not(windows))] fn shell_exports(home: &Path, names: &[&str]) -> Vec<(PathBuf, usize, String)> { - let files = [ - ".zshrc", - ".zprofile", - ".zshenv", - ".bashrc", - ".bash_profile", - ".profile", - ".config/fish/config.fish", - ]; let mut out = Vec::new(); - for f in files { - let p = home.join(f); + for &(f, fish) in SHELL_FILES { + let p = crate::paths::under(home, f); let Ok(text) = std::fs::read_to_string(&p) else { continue; }; for (i, line) in text.lines().enumerate() { - let t = line.trim_start(); - // 注释掉的不算。**这个判断很便宜,但漏掉它就会天天误报** —— - // 而误报几次之后,真正该看的那一次也不会被看。 - if t.starts_with('#') { - continue; - } + let set = exported_names(line, fish); for n in names { - if (t.starts_with("export ") - || t.starts_with("set -x ") - || t.starts_with("setenv ")) - && t.contains(n) - { + if set.contains(n) { out.push((p.clone(), i + 1, n.to_string())); } } @@ -579,8 +680,10 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec // 三、项目级配置盖住了用户级 if let Some(proj) = project { - let local = crate::paths::under(proj, c.config); - if local.exists() { + // 只有跟着 home 走的那几种说得上「项目里有一份同名的」;XDG 目录下的 + // 全局配置在项目里没有对应的位置 + let local = c.config.home_rel().map(|r| crate::paths::under(proj, r)); + if let Some(local) = local.filter(|p| p.exists()) { out.push(Finding { level: Level::Suspect, title: msg!("adopt.diag.project_config" => "This project has a configuration file of the same name"), @@ -806,11 +909,13 @@ mod tests { .iter() .find(|f| f.title.text.contains("OPENAI_BASE_URL")) .unwrap(); - assert!( - f.fix.as_ref().unwrap().text.contains("sed -i ''"), - "{:?}", - f.fix - ); + let fix = &f.fix.as_ref().unwrap().text; + // 各平台自己那个 sed 的写法,见 `delete_line` + if cfg!(target_os = "macos") { + assert!(fix.starts_with("sed -i '' '1d' "), "{fix}"); + } else { + assert!(fix.starts_with("sed -i '1d' "), "{fix}"); + } // 文件还在,我们没动它 assert!(d.path().join(".zshrc").exists()); assert!( @@ -820,6 +925,153 @@ mod tests { ); } + /// Linux 上 `ps` 真实吐出来的样子:右对齐的 pid、`etime`、15 字节以内的 + /// 进程名(不带路径)。 + #[test] + #[cfg(not(windows))] + fn linux_ps_lines_are_read_as_names() { + let lines = [ + " 1 12-03:04:05 systemd", + " 2141 01:02:03 zed-editor", + " 2230 05:12 claude", + " 2301 00:09 node", + " 2302 00:09 codex", + " 2400 00:30 codex-x86_64-un", + " 2500 00:30 opencode", + " 2600 00:30 aider", + " 2700 00:30 zeitgeist-daemon", + ]; + let parsed: Vec<_> = lines.iter().filter_map(|l| parse_ps_line(l)).collect(); + assert_eq!(parsed.len(), lines.len()); + assert_eq!(parsed[0], (12 * 86400 + 3 * 3600 + 4 * 60 + 5, "systemd")); + assert_eq!(parsed[1], (3600 + 2 * 60 + 3, "zed-editor")); + let hits = |m: &[&str]| { + parsed + .iter() + .filter(|(_, n)| is_one_of(n, m)) + .map(|(_, n)| *n) + .collect::>() + }; + let by = |id: &str| adoptable().into_iter().find(|c| c.id == id).unwrap(); + assert_eq!(hits(by("claude-code").process), ["claude"]); + // npm 装的 codex:node 包装层不算,它起的原生进程算;截断的三元组名也算 + assert_eq!(hits(by("codex").process), ["codex", "codex-x86_64-un"]); + assert_eq!(hits(by("opencode").process), ["opencode"]); + assert_eq!(hits(by("aider").process), ["aider"]); + if cfg!(target_os = "linux") { + // 「Zed」大写认不出 Linux 上的编辑器,「zed」包含又会认下 zeitgeist + assert_eq!(hits(by("zed").process), ["zed-editor"]); + } + } + + /// macOS 的 `comm` 是完整路径,可以带空格。 + #[test] + #[cfg(not(windows))] + fn macos_ps_lines_are_read_as_names() { + let l = "11315 19:42:58 /Users/u/Library/Application Support/Claude/claude-code/2.1.280/claude.app/Contents/MacOS/claude"; + assert_eq!(parse_ps_line(l), Some((19 * 3600 + 42 * 60 + 58, "claude"))); + let l = "48711 06:13:11 /Applications/Claude.app/Contents/Frameworks/Claude Helper (Renderer).app/Contents/MacOS/Claude Helper (Renderer)"; + assert_eq!(parse_ps_line(l).unwrap().1, "Claude Helper (Renderer)"); + let l = " 900 1-00:00:00 /Applications/Zed.app/Contents/MacOS/zed"; + let (_, name) = parse_ps_line(l).unwrap(); + if cfg!(target_os = "macos") { + let zed = adoptable().into_iter().find(|c| c.id == "zed").unwrap(); + assert!(is_one_of(name, zed.process), "{name}"); + } + assert_eq!(parse_ps_line("垃圾"), None); + assert_eq!(parse_ps_line(""), None); + } + + /// bash 用户:`.bashrc`、`.bash_profile`、`.profile` 都在看的范围里。 + #[test] + #[cfg(not(windows))] + fn bash_files_are_checked() { + for f in [".bashrc", ".bash_profile", ".bash_login", ".profile"] { + let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join(f), "export OPENAI_BASE_URL=https://old\n").unwrap(); + let hits = shell_exports(d.path(), &["OPENAI_BASE_URL"]); + assert_eq!(hits.len(), 1, "{f}"); + } + } + + /// 按变量名整个比:名字相近的、只是被引用的,都不算。 + #[test] + #[cfg(not(windows))] + fn only_a_real_export_of_that_exact_name_counts() { + assert_eq!(exported_names("export A=1 B=2", false), ["A", "B"]); + assert_eq!( + exported_names(" export OPENAI_API_KEY", false), + ["OPENAI_API_KEY"] + ); + assert_eq!( + exported_names("export OPENAI_BASE_URL_OLD=x", false), + ["OPENAI_BASE_URL_OLD"] + ); + assert!(exported_names("echo $OPENAI_BASE_URL", false).is_empty()); + assert!(exported_names("OPENAI_BASE_URL=x", false).is_empty()); + assert!(exported_names("# export OPENAI_BASE_URL=x", false).is_empty()); + // bash 里的 `set -x` 是打开命令回显,不是导出 + assert!(exported_names("set -x OPENAI_BASE_URL x", false).is_empty()); + let d = tempfile::tempdir().unwrap(); + std::fs::write( + d.path().join(".bashrc"), + "export OPENAI_BASE_URL_OLD=x\necho $OPENAI_BASE_URL\n", + ) + .unwrap(); + assert!(shell_exports(d.path(), &["OPENAI_BASE_URL"]).is_empty()); + } + + /// fish 的导出是 `set` 加导出标志;没有导出标志的、删掉变量的都不算。 + #[test] + #[cfg(not(windows))] + fn fish_set_is_read_by_its_flags() { + for l in [ + "set -x OPENAI_BASE_URL https://old", + "set -gx OPENAI_BASE_URL https://old", + "set -Ux OPENAI_BASE_URL https://old", + "set --export OPENAI_BASE_URL https://old", + "set -g -x OPENAI_BASE_URL https://old", + ] { + assert_eq!(exported_names(l, true), ["OPENAI_BASE_URL"], "{l}"); + } + for l in [ + "set -g OPENAI_BASE_URL https://old", + "set OPENAI_BASE_URL https://old", + "set -e OPENAI_BASE_URL", + "set -ex OPENAI_BASE_URL", + "# set -gx OPENAI_BASE_URL https://old", + "export OPENAI_BASE_URL=https://old", + ] { + assert!(exported_names(l, true).is_empty(), "{l}"); + } + let d = tempfile::tempdir().unwrap(); + let f = d.path().join(".config/fish/config.fish"); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + std::fs::write(&f, "set -g X 1\nset -gx OPENAI_BASE_URL https://old\n").unwrap(); + let hits = shell_exports(d.path(), &["OPENAI_BASE_URL"]); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].1, 2); + } + + /// 项目里的同名配置只对跟着 home 走的客户端说得通。 + #[test] + fn a_project_copy_is_only_looked_for_where_it_means_something() { + let d = tempfile::tempdir().unwrap(); + let home = d.path().join("home"); + let proj = d.path().join("proj"); + std::fs::create_dir_all(proj.join(".config/opencode")).unwrap(); + std::fs::write(proj.join(".config/opencode/opencode.json"), "{}").unwrap(); + std::fs::create_dir_all(proj.join(".codex")).unwrap(); + std::fs::write(proj.join(".codex/config.toml"), "").unwrap(); + let has = |id: &str| { + diagnose(&c(id), &home, Some(&proj)) + .iter() + .any(|f| f.title.code == "adopt.diag.project_config") + }; + assert!(has("codex")); + assert!(!has("opencode")); + } + #[test] fn detection_reads_the_endpoint_from_the_file_not_from_our_own_record() { // 「我们写过」和「现在还是那样」是两回事 —— 第六种原因就是 diff --git a/crates/tw-adopt/src/mcp.rs b/crates/tw-adopt/src/mcp.rs index bdf8a1b2..7ad55817 100644 --- a/crates/tw-adopt/src/mcp.rs +++ b/crates/tw-adopt/src/mcp.rs @@ -16,6 +16,7 @@ use tw_types::{Msg, msg}; use crate::clients::Format; use crate::foreign::{self, Applied, Change, ForeignError}; use crate::json::Val; +use crate::paths::Loc; /// 搬 MCP server 时的失败。 /// @@ -65,8 +66,7 @@ impl McpError { pub struct Target { pub client: &'static str, pub name: &'static str, - /// 相对 `$HOME` - pub config: &'static str, + pub config: Loc, pub format: Format, /// server 挂在哪个键下面 pub key: &'static str, @@ -101,7 +101,7 @@ pub fn targets() -> Vec { Target { client: "claude-code", name: "Claude Code", - config: ".claude.json", + config: Loc::Home(".claude.json"), format: Format::Json, key: "mcpServers", copyable: true, @@ -110,7 +110,7 @@ pub fn targets() -> Vec { Target { client: "claude-desktop", name: "Claude Desktop", - config: crate::paths::claude_desktop_config(), + config: crate::paths::CLAUDE_DESKTOP_CONFIG, format: Format::Json, key: "mcpServers", copyable: true, @@ -119,7 +119,7 @@ pub fn targets() -> Vec { Target { client: "cursor", name: "Cursor", - config: ".cursor/mcp.json", + config: Loc::Home(".cursor/mcp.json"), format: Format::Json, key: "mcpServers", copyable: true, @@ -128,7 +128,7 @@ pub fn targets() -> Vec { Target { client: "codex", name: "Codex", - config: ".codex/config.toml", + config: Loc::Home(".codex/config.toml"), format: Format::Toml, key: "mcp_servers", copyable: true, @@ -137,7 +137,7 @@ pub fn targets() -> Vec { Target { client: "opencode", name: "opencode", - config: ".config/opencode/opencode.json", + config: crate::paths::OPENCODE_CONFIG, format: Format::Json, key: "mcp", copyable: false, @@ -149,7 +149,7 @@ pub fn targets() -> Vec { Target { client: "zed", name: "Zed", - config: crate::paths::zed_settings(), + config: crate::paths::ZED_SETTINGS, format: Format::Json, key: "context_servers", copyable: false, @@ -170,7 +170,7 @@ pub fn target(client: &str) -> Result { impl Target { pub fn path(&self, home: &Path) -> PathBuf { - crate::paths::under(home, self.config) + self.config.resolve(home) } fn check(&self) -> Result<(), McpError> { if self.copyable { diff --git a/crates/tw-adopt/src/paths.rs b/crates/tw-adopt/src/paths.rs index 776cf3d4..216cedd2 100644 --- a/crates/tw-adopt/src/paths.rs +++ b/crates/tw-adopt/src/paths.rs @@ -15,7 +15,11 @@ //! 配置。默认位置就在 home 底下,这是绝大多数;而「没发现」比「改错文件」 //! 便宜得多。 //! -//! 机器级的那一个(管理策略)没有 home 可言,它读环境变量。 +//! XDG 目录是个例外:那几个客户端**自己**认 `$XDG_CONFIG_HOME`,设了它的 +//! 用户,`~/.config` 下那份就不是在用的那份 —— 照默认位置去改,改的正是一份 +//! 错文件。所以它们要读变量,而隔离靠 [`Loc::resolve`] 里那条规矩守住。 +//! +//! 机器级的那一个(管理策略)没有 home 可言,它是个固定路径。 use std::path::{Path, PathBuf}; @@ -32,77 +36,171 @@ pub fn under(base: &Path, rel: &str) -> PathBuf { .fold(base.to_path_buf(), |p, c| p.join(c)) } -/// 给人看的写法:「打开 … 」那一步里的路径。 +/// 一条配置路径从哪儿算起。 /// -/// macOS 上是 `~/.claude/settings.json`;Windows 上没有 `~`,写成资源管理器 -/// 地址栏里能直接粘贴的 `%USERPROFILE%\.claude\settings.json`。 -pub fn shown(rel: &str) -> String { - #[cfg(windows)] - { - format!(r"%USERPROFILE%\{}", rel.replace('/', r"\")) +/// 大多数客户端的配置在 home 底下一个固定的相对位置;有几个跟着 XDG 走 +/// (opencode 在每个平台上,Zed 和 Claude Desktop 在 Linux 上)。**要能在 +/// 常量里构造**:它们放在 `marker: &[…]` 那种静态切片里。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Loc { + /// 相对 home + Home(&'static str), + /// 相对 XDG 配置目录:`$XDG_CONFIG_HOME`,没设就是 `~/.config` + XdgConfig(&'static str), + /// 相对 XDG 数据目录:`$XDG_DATA_HOME`,没设就是 `~/.local/share` + XdgData(&'static str), +} + +impl Loc { + /// 在 `home` 这个用户底下,它落在哪儿。 + pub fn resolve(&self, home: &Path) -> PathBuf { + self.resolve_with(home, env_home().as_deref(), |v| std::env::var_os(v)) } - #[cfg(not(windows))] - { - format!("~/{rel}") + + /// [`Loc::resolve`] 去掉进程环境的那一半,测试直接喂。 + /// + /// **XDG 变量只在 `home` 就是这个进程自己的 home 时才认。**变量描述的是 + /// 跑着这个进程的那个用户;调用方传来别的 home(测试传的临时目录就是) + /// 时,拿开发者自己的 `$XDG_CONFIG_HOME` 去套它,测试改到的就是真的配置 + /// —— 这正是本文件开头那条隔离要挡的事。 + /// + /// 相对路径的值不认:XDG 规范要求这类值是绝对路径,相对的当没设(Zed + /// 用的 `dirs` 也是这么做的)。 + fn resolve_with( + &self, + home: &Path, + proc_home: Option<&Path>, + var: impl Fn(&str) -> Option, + ) -> PathBuf { + let xdg = |name: &str, default: &str, rel: &str| { + let base = var(name) + .map(PathBuf::from) + .filter(|p| p.is_absolute() && proc_home == Some(home)) + .unwrap_or_else(|| under(home, default)); + under(&base, rel) + }; + match *self { + Loc::Home(rel) => under(home, rel), + Loc::XdgConfig(rel) => xdg("XDG_CONFIG_HOME", ".config", rel), + Loc::XdgData(rel) => xdg("XDG_DATA_HOME", ".local/share", rel), + } + } + + /// 相对 home 的那一段。XDG 那两种没有固定的一段,所以是 `None` —— + /// 「项目里有一份同名配置」(`<项目>/.claude/settings.json` 那种)只对 + /// 前者说得通。 + pub fn home_rel(&self) -> Option<&'static str> { + match *self { + Loc::Home(rel) => Some(rel), + Loc::XdgConfig(_) | Loc::XdgData(_) => None, + } + } + + /// 给人看的写法:「打开 … 」那一步里的路径。 + /// + /// macOS 和 Linux 上是 `~/.claude/settings.json`;Windows 上没有 `~`, + /// 写成资源管理器地址栏里能直接粘贴的 `%USERPROFILE%\.claude\settings.json`。 + /// XDG 目录被挪到 home 外面的,给完整路径。 + pub fn shown(&self) -> String { + let home = env_home().unwrap_or_default(); + let p = self.resolve(&home); + let rel = match p.strip_prefix(&home) { + Ok(rel) if !home.as_os_str().is_empty() => rel, + _ => return p.display().to_string(), + }; + let parts: Vec<_> = rel + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect(); + #[cfg(windows)] + { + format!(r"%USERPROFILE%\{}", parts.join(r"\")) + } + #[cfg(not(windows))] + { + format!("~/{}", parts.join("/")) + } } } -/// Zed 的设置文件,相对 home。 -/// -/// Windows 上的 Zed 按那个平台的习惯放在漫游的 AppData 下,不是 `~/.config`。 -pub fn zed_settings() -> &'static str { +/// 这个进程自己的 home。和 tw-control 的 `home_dir` 读的是同一个变量。 +fn env_home() -> Option { #[cfg(windows)] - { - "AppData/Roaming/Zed/settings.json" - } + const VAR: &str = "USERPROFILE"; #[cfg(not(windows))] - { - ".config/zed/settings.json" - } + const VAR: &str = "HOME"; + std::env::var_os(VAR) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) } -/// Zed 装过的痕迹:它的设置目录。**是常量不是函数**:它要放进 -/// `marker: &[…]` 那个静态切片里,函数的返回值进不去。 -pub const ZED_DIR: &str = if cfg!(windows) { - "AppData/Roaming/Zed" +/// Zed 的设置文件。 +/// +/// 三个平台三个地方,都照 Zed 自己的 `paths::config_dir()`:Windows 上在漫游 +/// 的 AppData 下;Linux 上是 `$XDG_CONFIG_HOME/zed`(经 `dirs::config_dir`); +/// macOS 上**写死** `~/.config/zed`,不看 XDG。 +pub const ZED_SETTINGS: Loc = if cfg!(windows) { + Loc::Home("AppData/Roaming/Zed/settings.json") +} else if cfg!(target_os = "macos") { + Loc::Home(".config/zed/settings.json") } else { - ".config/zed" + Loc::XdgConfig("zed/settings.json") }; -/// Claude Desktop 的配置,相对 home。 +/// Zed 装过的痕迹:它的设置目录。 +pub const ZED_DIR: Loc = if cfg!(windows) { + Loc::Home("AppData/Roaming/Zed") +} else if cfg!(target_os = "macos") { + Loc::Home(".config/zed") +} else { + Loc::XdgConfig("zed") +}; + +/// opencode 的全局配置。它用 `xdg-basedir`,**每个平台都**认 +/// `$XDG_CONFIG_HOME`,没设才是 `~/.config/opencode`。 +pub const OPENCODE_CONFIG: Loc = Loc::XdgConfig("opencode/opencode.json"); + +/// Claude Desktop 的配置。 /// -/// macOS 上在 `Library/Application Support/` 下,Windows 上在漫游的 AppData 下 -/// —— 两边都是各自平台放这类东西的地方,不是我们挑的。 -pub fn claude_desktop_config() -> &'static str { - #[cfg(windows)] - { - "AppData/Roaming/Claude/claude_desktop_config.json" - } - #[cfg(not(windows))] - { - "Library/Application Support/Claude/claude_desktop_config.json" - } -} +/// 它是 Electron 应用,这个文件在 `userData` 下,也就是 Electron 的 `appData` +/// 加应用名:macOS 上是 `Library/Application Support/Claude/`,Windows 上是 +/// 漫游的 AppData,Linux(beta,只出 Debian 系的包)上是 +/// `$XDG_CONFIG_HOME/Claude`,没设就是 `~/.config/Claude`。 +pub const CLAUDE_DESKTOP_CONFIG: Loc = if cfg!(windows) { + Loc::Home("AppData/Roaming/Claude/claude_desktop_config.json") +} else if cfg!(target_os = "macos") { + Loc::Home("Library/Application Support/Claude/claude_desktop_config.json") +} else { + Loc::XdgConfig("Claude/claude_desktop_config.json") +}; /// 机器级的管理策略文件。**优先级压过一切**,包括用户自己的配置。 /// -/// 机器级,所以这一个不相对 home。 +/// 机器级,所以这一个不相对 home。位置照 Claude Code 文档「Deploy managed +/// settings」:macOS `/Library/Application Support/ClaudeCode/`,Linux(和 +/// WSL)`/etc/claude-code/`,Windows `C:\Program Files\ClaudeCode\`。Windows +/// 上旧的 `C:\ProgramData\ClaudeCode\` 文档明说**不再读**,看它等于看一个 +/// 已经不起作用的文件。 pub fn managed_settings() -> PathBuf { #[cfg(windows)] { // **不写死 `C:\`** —— 系统盘不一定是 C,而写死的后果是在那些机器上 // 报「这台机器没有管理策略」,也就是对一个真的压过用户配置的东西 // 视而不见。 - std::env::var_os("PROGRAMDATA") + std::env::var_os("ProgramFiles") .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")) + .unwrap_or_else(|| PathBuf::from(r"C:\Program Files")) .join("ClaudeCode") .join("managed-settings.json") } - #[cfg(not(windows))] + #[cfg(target_os = "macos")] { PathBuf::from("/Library/Application Support/ClaudeCode/managed-settings.json") } + #[cfg(not(any(windows, target_os = "macos")))] + { + PathBuf::from("/etc/claude-code/managed-settings.json") + } } #[cfg(test)] @@ -111,17 +209,11 @@ mod tests { /// 相对 home,不是绝对路径 —— 否则 `home.join(…)` 会把 home 整个丢掉。 #[test] - fn the_desktop_config_is_relative_to_home() { - let p = claude_desktop_config(); - assert!( - !PathBuf::from(p).is_absolute(), - "绝对路径会让 home.join() 忽略 home:{p}" - ); + fn the_desktop_config_is_under_home() { + let h = Path::new("/tmp/h"); + let p = CLAUDE_DESKTOP_CONFIG.resolve_with(h, None, |_| None); + assert!(p.starts_with(h), "{}", p.display()); assert!(p.ends_with("claude_desktop_config.json")); - assert_eq!( - std::path::Path::new("/tmp/h").join(p), - std::path::Path::new("/tmp/h").join(p), - ); } /// 接出来的每一段都是一个组件:没有哪一段里还夹着 `/`。 @@ -144,7 +236,7 @@ mod tests { #[test] fn the_shown_path_is_written_the_platform_way() { - let s = shown(".claude/settings.json"); + let s = Loc::Home(".claude/settings.json").shown(); if cfg!(windows) { assert_eq!(s, r"%USERPROFILE%\.claude\settings.json"); } else { @@ -157,16 +249,85 @@ mod tests { fn the_managed_policy_is_machine_wide() { assert!(managed_settings().is_absolute()); assert!(managed_settings().ends_with("managed-settings.json")); + if cfg!(target_os = "linux") { + assert_eq!( + managed_settings(), + Path::new("/etc/claude-code/managed-settings.json") + ); + } } /// 每个平台指向自己那套习惯的位置。 #[test] fn each_platform_points_at_its_own_convention() { - let p = claude_desktop_config(); + let h = Path::new("/h"); + let p = CLAUDE_DESKTOP_CONFIG.resolve_with(h, None, |_| None); + let z = ZED_SETTINGS.resolve_with(h, None, |_| None); if cfg!(windows) { - assert!(p.starts_with("AppData/"), "{p}"); + assert!(p.starts_with(h.join("AppData")), "{}", p.display()); + } else if cfg!(target_os = "macos") { + assert!(p.starts_with(h.join("Library")), "{}", p.display()); + assert_eq!(z, under(h, ".config/zed/settings.json")); } else { - assert!(p.starts_with("Library/"), "{p}"); + assert_eq!(p, under(h, ".config/Claude/claude_desktop_config.json")); + assert_eq!(z, under(h, ".config/zed/settings.json")); } } + + /// 设了 `$XDG_CONFIG_HOME` 的用户,认它的客户端就不在 `~/.config` 了。 + /// + /// Windows 上 `/home/u` 不是绝对路径,这条只在 unix 上跑。 + #[test] + #[cfg(not(windows))] + fn xdg_config_home_is_honoured_for_the_process_own_home() { + let h = Path::new("/home/u"); + let var = |n: &str| (n == "XDG_CONFIG_HOME").then(|| "/home/u/.cfg".into()); + assert_eq!( + OPENCODE_CONFIG.resolve_with(h, Some(h), var), + Path::new("/home/u/.cfg/opencode/opencode.json") + ); + // 没设就是默认位置 + assert_eq!( + OPENCODE_CONFIG.resolve_with(h, Some(h), |_| None), + Path::new("/home/u/.config/opencode/opencode.json") + ); + // 数据目录走它自己的变量 + let data = |n: &str| (n == "XDG_DATA_HOME").then(|| "/data/u".into()); + assert_eq!( + Loc::XdgData("opencode").resolve_with(h, Some(h), data), + Path::new("/data/u/opencode") + ); + // 跟 home 走的那些不看它 + assert_eq!( + Loc::Home(".codex/config.toml").resolve_with(h, Some(h), var), + Path::new("/home/u/.codex/config.toml") + ); + } + + /// **隔离。**传进来的不是这个进程的 home(测试的临时目录就是),变量 + /// 描述的就不是它 —— 认了的话,测试改的是开发者真的配置。 + #[test] + fn xdg_config_home_is_ignored_for_any_other_home() { + let var = |_: &str| Some("/home/me/.config".into()); + let tmp = Path::new("/tmp/test-home"); + assert_eq!( + OPENCODE_CONFIG.resolve_with(tmp, Some(Path::new("/home/me")), var), + Path::new("/tmp/test-home/.config/opencode/opencode.json") + ); + assert_eq!( + OPENCODE_CONFIG.resolve_with(tmp, None, var), + Path::new("/tmp/test-home/.config/opencode/opencode.json") + ); + } + + /// 相对路径的值当没设,这是 XDG 规范的要求。 + #[test] + fn a_relative_xdg_value_is_ignored() { + let h = Path::new("/home/u"); + let var = |_: &str| Some("cfg".into()); + assert_eq!( + OPENCODE_CONFIG.resolve_with(h, Some(h), var), + Path::new("/home/u/.config/opencode/opencode.json") + ); + } } diff --git a/crates/tw-adopt/tests/roundtrip.rs b/crates/tw-adopt/tests/roundtrip.rs index 600af06f..4c3b78ac 100644 --- a/crates/tw-adopt/tests/roundtrip.rs +++ b/crates/tw-adopt/tests/roundtrip.rs @@ -26,7 +26,7 @@ fn bed(client: &str, contents: &str) -> Bed { let dir = tempfile::tempdir().unwrap(); let home = dir.path().join("home"); let c = adoptable().into_iter().find(|c| c.id == client).unwrap(); - let p = home.join(c.config); + let p = c.config_path(&home); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); if !contents.is_empty() { std::fs::write(&p, contents).unwrap(); @@ -338,7 +338,7 @@ fn every_adoptable_client_survives_a_round_trip() { let b = bed(c.id, seed); let p = plan_adopt(&c, &b.home, &gw()).unwrap(); apply(&c, &p, &b.backups).unwrap(); - let after = read(&b.home.join(c.config)); + let after = read(&c.config_path(&b.home)); assert!( after.contains("别动"), "{} 把用户原有的字段弄丢了:\n{after}", @@ -348,7 +348,7 @@ fn every_adoptable_client_survives_a_round_trip() { let r = plan_restore(&c, &b.home).unwrap(); apply_restore(&c, &r, &b.backups).unwrap(); assert_eq!( - read(&b.home.join(c.config)), + read(&c.config_path(&b.home)), seed, "{} 还原之后对不上", c.id @@ -373,7 +373,7 @@ fn a_gateway_without_a_key_writes_no_key_field() { let p = plan_adopt(&c, &b.home, &g).unwrap(); assert!(!p.carries_secret, "{} 说自己要写密钥,可是没有密钥", c.id); apply(&c, &p, &b.backups).unwrap(); - let after = read(&b.home.join(c.config)); + let after = read(&c.config_path(&b.home)); assert!( !after.contains("\"apiKey\": \"\""), "{} 写了一个空密钥:{after}", diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index cad19d6a..ecdfedec 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -14,6 +14,7 @@ adopt.cost.opencode.restart adopt.cost.zed.key_store adopt.diag.adopt_again adopt.diag.delete_line +adopt.diag.delete_line_gnu adopt.diag.endpoint_ok adopt.diag.endpoint_ok.detail adopt.diag.fields_gone diff --git a/crates/tw-control/src/clients.rs b/crates/tw-control/src/clients.rs index f0b936b9..abed5985 100644 --- a/crates/tw-control/src/clients.rs +++ b/crates/tw-control/src/clients.rs @@ -507,7 +507,7 @@ pub async fn mcp_targets(State(_s): State) -> Json Vec { f( "claude-desktop", Kind::Mcp, - under(home, tw_adopt::paths::claude_desktop_config()), + tw_adopt::paths::CLAUDE_DESKTOP_CONFIG.resolve(home), ), f("cursor", Kind::Mcp, under(home, ".cursor/mcp.json")), f("codex", Kind::Mcp, under(home, ".codex/config.toml")), f( "opencode", Kind::Mcp, - under(home, ".config/opencode/opencode.json"), + tw_adopt::paths::OPENCODE_CONFIG.resolve(home), ), f( "zed", Kind::Mcp, - under(home, tw_adopt::paths::zed_settings()), + tw_adopt::paths::ZED_SETTINGS.resolve(home), ), // 指令类 f( @@ -257,7 +257,7 @@ mod tests { let d = tempfile::tempdir().unwrap(); // 路径按平台走 —— 写死 macOS 那一条的话,这个测试在 Windows 上 // 会造一个没人找的文件,然后报告扫描漏了它。 - touch(&d.path().join(tw_adopt::paths::claude_desktop_config())); + touch(&tw_adopt::paths::CLAUDE_DESKTOP_CONFIG.resolve(d.path())); let got = user_level(d.path()); assert_eq!(got.len(), 1); assert_eq!(got[0].client, "claude-desktop");