Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 39 additions & 10 deletions crates/tw-adopt/src/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,9 @@ impl Verified {
pub struct Client {
pub id: &'static str,
pub name: &'static str,
/// 配置文件
pub config: Loc,
/// 配置文件。**多数只有一个**;同一份配置能写在几个文件里的(opencode),
/// 按优先级从高到低列全,写哪一个见 [`Client::config_index`]。
pub config: &'static [Loc],
pub format: Format,
pub takes_effect: TakesEffect,
/// 优先级比主配置更高、会盖住我们的那些文件(诊断链)。
Expand Down Expand Up @@ -219,7 +220,7 @@ pub fn adoptable() -> Vec<Client> {
Client {
id: "claude-code",
name: "Claude Code",
config: Loc::Home(".claude/settings.json"),
config: &[Loc::Home(".claude/settings.json")],
format: Format::Json,
takes_effect: TakesEffect::Immediately,
// **`settings.local.json` 优先级更高。**cc-switch #6828 栽在这里
Expand Down Expand Up @@ -261,7 +262,7 @@ pub fn adoptable() -> Vec<Client> {
Client {
id: "codex",
name: "Codex",
config: Loc::Home(".codex/config.toml"),
config: &[Loc::Home(".codex/config.toml")],
format: Format::Toml,
// **读环境变量的,必须关掉终端重开**
takes_effect: TakesEffect::OnRestart,
Expand Down Expand Up @@ -289,7 +290,7 @@ pub fn adoptable() -> Vec<Client> {
Client {
id: "opencode",
name: "opencode",
config: crate::paths::OPENCODE_CONFIG,
config: crate::paths::OPENCODE_CONFIGS,
format: Format::Json,
takes_effect: TakesEffect::OnRestart,
shadowed_by: &[],
Expand All @@ -307,7 +308,7 @@ pub fn adoptable() -> Vec<Client> {
Client {
id: "zed",
name: "Zed",
config: crate::paths::ZED_SETTINGS,
config: &[crate::paths::ZED_SETTINGS],
format: Format::Json,
takes_effect: TakesEffect::Immediately,
shadowed_by: &[],
Expand All @@ -330,7 +331,7 @@ pub fn adoptable() -> Vec<Client> {
Client {
id: "aider",
name: "Aider",
config: Loc::Home(".aider.conf.yml"),
config: &[Loc::Home(".aider.conf.yml")],
format: Format::Yaml,
takes_effect: TakesEffect::OnRestart,
// **三层查找,后面的覆盖前面的**(home → 仓库根 → cwd)。
Expand Down Expand Up @@ -657,7 +658,8 @@ impl Client {
/// **没检测到它的时候也要给。**配置文件不在默认位置、或者装在别的
/// 用户目录下时,检测不到不等于用不了 —— 照着做一样能接上。
pub fn manual_steps(&self) -> Vec<Msg> {
let file = self.config.shown();
let i = crate::paths::env_home().map_or(0, |h| self.config_index(&h));
let file = self.config[i].shown();
let mut out = vec![msg!(
"adopt.manual.file", file = file =>
"Open {file} and set the fields below."
Expand All @@ -683,13 +685,40 @@ impl Client {
.unwrap_or_else(|| gw.base.clone())
}

/// [`Client::config`] 里写哪一个。
///
/// **接管过的那一个优先**:接管之后用户才建了一份优先级更高的文件时,
/// 我们的记录和能还原的原文都在原来那一个旁边 —— 换过去就既还原不了,
/// 也会把「被盖住了」报成「没接管过」。没接管过就挑在的里面优先级最高的,
/// 这正是客户端自己要写全局配置时挑的那一个(见 `paths::OPENCODE_CONFIGS`)。
pub fn config_index(&self, home: &std::path::Path) -> usize {
if self.config.len() > 1 {
let ours = |l: &Loc| {
let p = l.resolve(home);
let real = crate::foreign::resolve(&p).unwrap_or(p);
std::fs::read_to_string(crate::sentinel::sidecar_path(&real))
.ok()
.and_then(|t| serde_json::from_str::<crate::sentinel::SidecarRecord>(&t).ok())
.is_some_and(|r| r.client == self.id)
};
if let Some(i) = self.config.iter().position(ours) {
return i;
}
}
crate::paths::first_existing(self.config, home)
}

pub fn config_path(&self, home: &std::path::Path) -> PathBuf {
self.config.resolve(home)
self.config[self.config_index(home)].resolve(home)
}
/// 优先级比写的那一个更高的文件:固定的那几个(`settings.local.json`),
/// 加上同一份配置里排在它前面的文件名。
pub fn shadow_paths(&self, home: &std::path::Path) -> Vec<PathBuf> {
let above = &self.config[..self.config_index(home)];
self.shadowed_by
.iter()
.map(|p| crate::paths::under(home, p))
.chain(above.iter().map(|l| l.resolve(home)))
.collect()
}
/// 注释前缀。JSON 没有 —— 那时哨兵走旁文件。
Expand Down Expand Up @@ -871,7 +900,7 @@ mod tests {
for c in adoptable() {
let steps = c.manual_steps();
// 写法按平台(`~/…` 或 `%USERPROFILE%\…`),各自的样子见 paths 里那条测试
assert_eq!(steps[0].arg("file"), c.config.shown(), "{}", c.id);
assert_eq!(steps[0].arg("file"), c.config[0].shown(), "{}", c.id);
assert!(!edits(&c, &gw).is_empty(), "{}:没有要写的字段", c.id);
}
// Zed 的密钥不在配置文件里,多一步在它自己的设置里填
Expand Down
131 changes: 116 additions & 15 deletions crates/tw-adopt/src/detect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,29 @@ fn shell_exports(home: &Path, names: &[&str]) -> Vec<(PathBuf, usize, String)> {
out
}

/// 一份优先级更高的文件里,会盖住我们写的那些字段。
///
/// 多数客户端认的是环境变量那一块(Claude Code 的 `env` 块),出现变量名就
/// 算。opencode 逐层**深合并**:更高的那份文件只有写了 `provider.thinkwatch`
/// 才会盖住我们写的东西,别的键(`$schema`、别的 provider)和我们并存。
fn overriding_fields(c: &Client, text: &str) -> Vec<String> {
match c.id {
"opencode" => {
let path = ["provider", crate::clients::PROVIDER_ID];
match crate::json::get(text, &path) {
Ok(Some(_)) => vec![path.join(".")],
_ => Vec::new(),
}
}
_ => c
.env_vars
.iter()
.filter(|v| text.contains(**v))
.map(|v| v.to_string())
.collect(),
}
}

/// 走一遍优先级链。`project` 是当前项目目录(有的话)。
pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec<Finding> {
let d = detect_one(c, home);
Expand Down Expand Up @@ -648,7 +671,7 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec<Finding>
} else {
for s in &d.shadows {
let text = std::fs::read_to_string(s).unwrap_or_default();
let hits: Vec<_> = c.env_vars.iter().filter(|v| text.contains(**v)).collect();
let hits = overriding_fields(c, &text);
out.push(Finding {
level: if hits.is_empty() {
Level::Suspect
Expand All @@ -665,11 +688,7 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec<Finding>
} else {
msg!(
"adopt.diag.shadowed.fields",
fields = hits
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>()
.join(", ")
fields = hits.join(", ")
=> "The file carries {fields}, which overrides what was written here."
)
},
Expand All @@ -682,7 +701,7 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec<Finding>
if let Some(proj) = project {
// 只有跟着 home 走的那几种说得上「项目里有一份同名的」;XDG 目录下的
// 全局配置在项目里没有对应的位置
let local = c.config.home_rel().map(|r| crate::paths::under(proj, r));
let local = c.config[0].home_rel().map(|r| crate::paths::under(proj, r));
if let Some(local) = local.filter(|p| p.exists()) {
out.push(Finding {
level: Level::Suspect,
Expand All @@ -698,22 +717,41 @@ pub fn diagnose(c: &Client, home: &Path, project: Option<&Path>) -> Vec<Finding>
}

// 四、管理策略文件。**最高优先级,压过一切**
//
// `managed-settings.json` 和 `managed-settings.d/` 里的分片合起来是同一个
// 来源:先读前者,再按字母序合并分片,同一个键后读的赢。每个文件各报
// 一条 —— 用户要去改的是具体哪一个文件。
if c.id == "claude-code" {
let managed = crate::paths::managed_settings();
let dropins = crate::paths::managed_settings_dropins();
let level = |p: &Path| {
let text = std::fs::read_to_string(p).unwrap_or_default();
if overriding_fields(c, &text).is_empty() {
Level::Suspect
} else {
Level::Blocking
}
};
if managed.exists() {
let text = std::fs::read_to_string(&managed).unwrap_or_default();
let hits: Vec<_> = c.env_vars.iter().filter(|v| text.contains(**v)).collect();
out.push(Finding {
level: if hits.is_empty() {
Level::Suspect
} else {
Level::Blocking
},
level: level(&managed),
title: msg!("adopt.diag.managed" => "This machine has a managed-policy file"),
detail: msg!("adopt.diag.managed.detail", path = managed.display() => "{path} takes precedence over everything else, including the user's own configuration."),
fix: None,
});
} else {
}
for p in &dropins {
out.push(Finding {
level: level(p),
title: msg!("adopt.diag.managed_dropin" => "This machine has a managed-policy drop-in file"),
detail: msg!(
"adopt.diag.managed_dropin.detail", path = p.display()
=> "{path} is merged after managed-settings.json; like it, it takes precedence over everything else, including the user's own configuration."
),
fix: None,
});
}
if !managed.exists() && dropins.is_empty() {
out.push(Finding {
level: Level::Clear,
title: msg!("adopt.diag.no_managed" => "This machine has no managed-policy file"),
Expand Down Expand Up @@ -1072,6 +1110,69 @@ mod tests {
assert!(!has("opencode"));
}

fn adopt(id: &str, home: &Path, backups: &Path) {
let gw = crate::clients::Gateway {
base: "http://127.0.0.1:8080".into(),
key: None,
};
let p = crate::plan::plan_adopt(&c(id), home, &gw).unwrap();
crate::plan::apply(&c(id), &p, backups).unwrap();
}

/// 刚装好的 opencode 自己建的是 `opencode.jsonc`:写进它,而不是另起一份
/// 会被它盖住的 `opencode.json`,也不为那一行 `$schema` 报「被盖住」。
#[test]
fn opencode_is_written_where_opencode_itself_writes() {
let d = tempfile::tempdir().unwrap();
let home = d.path().join("home");
let jsonc = crate::paths::OPENCODE_CONFIGS[0].resolve(&home);
std::fs::create_dir_all(jsonc.parent().unwrap()).unwrap();
std::fs::write(
&jsonc,
"{\n \"$schema\": \"https://opencode.ai/config.json\"\n}",
)
.unwrap();
adopt("opencode", &home, &d.path().join("b"));

assert_eq!(c("opencode").config_path(&home), jsonc);
assert!(std::fs::read_to_string(&jsonc).unwrap().contains("baseURL"));
assert!(!crate::paths::OPENCODE_CONFIGS[1].resolve(&home).exists());
let got = detect_one(&c("opencode"), &home);
assert!(got.shadows.is_empty(), "{:?}", got.shadows);
assert!(got.adopted_at_ms.is_some());
}

/// 接管之后用户才建了 `opencode.jsonc`:仍然认原来那一份(记录和原文在
/// 它旁边),并且说出更高的那份盖住了什么。
#[test]
fn a_later_opencode_jsonc_is_reported_as_taking_precedence() {
let d = tempfile::tempdir().unwrap();
let home = d.path().join("home");
let json = crate::paths::OPENCODE_CONFIGS[1].resolve(&home);
let jsonc = crate::paths::OPENCODE_CONFIGS[0].resolve(&home);
std::fs::create_dir_all(json.parent().unwrap()).unwrap();
std::fs::write(&json, "{}\n").unwrap();
adopt("opencode", &home, &d.path().join("b"));
assert_eq!(c("opencode").config_path(&home), json);

let shadow = |jsonc_text: &str| {
std::fs::write(&jsonc, jsonc_text).unwrap();
assert_eq!(c("opencode").config_path(&home), json, "换了文件就还原不了");
diagnose(&c("opencode"), &home, None)
.into_iter()
.find(|f| f.title.code == "adopt.diag.shadowed")
.expect("没报被盖住")
};
// 别的键和我们并存,只是提一句
let f = shadow("{ // 我的\n \"theme\": \"x\" }");
assert_eq!(f.level, Level::Suspect);
assert_eq!(f.detail.code, "adopt.diag.shadowed.no_fields");
// 写了同名 provider 的,才真的盖住
let f = shadow("{ \"provider\": { \"thinkwatch\": { \"options\": {} } } }");
assert_eq!(f.level, Level::Blocking);
assert_eq!(f.detail.arg("fields"), "provider.thinkwatch");
}

#[test]
fn detection_reads_the_endpoint_from_the_file_not_from_our_own_record() {
// 「我们写过」和「现在还是那样」是两回事 —— 第六种原因就是
Expand Down
24 changes: 16 additions & 8 deletions crates/tw-adopt/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ impl McpError {
pub struct Target {
pub client: &'static str,
pub name: &'static str,
pub config: Loc,
/// 按优先级从高到低;读写的是在的里面最高的那一个,见
/// [`crate::paths::first_existing`]
pub config: &'static [Loc],
pub format: Format,
/// server 挂在哪个键下面
pub key: &'static str,
Expand Down Expand Up @@ -101,7 +103,7 @@ pub fn targets() -> Vec<Target> {
Target {
client: "claude-code",
name: "Claude Code",
config: Loc::Home(".claude.json"),
config: &[Loc::Home(".claude.json")],
format: Format::Json,
key: "mcpServers",
copyable: true,
Expand All @@ -110,7 +112,7 @@ pub fn targets() -> Vec<Target> {
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,
Expand All @@ -119,7 +121,7 @@ pub fn targets() -> Vec<Target> {
Target {
client: "cursor",
name: "Cursor",
config: Loc::Home(".cursor/mcp.json"),
config: &[Loc::Home(".cursor/mcp.json")],
format: Format::Json,
key: "mcpServers",
copyable: true,
Expand All @@ -128,7 +130,7 @@ pub fn targets() -> Vec<Target> {
Target {
client: "codex",
name: "Codex",
config: Loc::Home(".codex/config.toml"),
config: &[Loc::Home(".codex/config.toml")],
format: Format::Toml,
key: "mcp_servers",
copyable: true,
Expand All @@ -137,7 +139,7 @@ pub fn targets() -> Vec<Target> {
Target {
client: "opencode",
name: "opencode",
config: crate::paths::OPENCODE_CONFIG,
config: crate::paths::OPENCODE_CONFIGS,
format: Format::Json,
key: "mcp",
copyable: false,
Expand All @@ -149,7 +151,7 @@ pub fn targets() -> Vec<Target> {
Target {
client: "zed",
name: "Zed",
config: crate::paths::ZED_SETTINGS,
config: &[crate::paths::ZED_SETTINGS],
format: Format::Json,
key: "context_servers",
copyable: false,
Expand All @@ -170,7 +172,13 @@ pub fn target(client: &str) -> Result<Target, McpError> {

impl Target {
pub fn path(&self, home: &Path) -> PathBuf {
self.config.resolve(home)
self.config[crate::paths::first_existing(self.config, home)].resolve(home)
}
/// 给人看的路径。
pub fn shown(&self) -> String {
let i =
crate::paths::env_home().map_or(0, |h| crate::paths::first_existing(self.config, &h));
self.config[i].shown()
}
fn check(&self) -> Result<(), McpError> {
if self.copyable {
Expand Down
Loading
Loading