From 3ee751f76a897f5f89a6163674596d9b199fee62 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 20:27:33 +0800 Subject: [PATCH] fix: the data directory is part of the contract The desktop app resolved the data directory on its own, from HOME only. On Windows HOME is normally unset, so it fell back to `.thinkwatch` in the current directory while core used %APPDATA%\ThinkWatch. The port file and the token live in that directory: the app would look for a running gateway in the wrong place and never find it. The resolver moves from tw-config into tw-api as `tw_api::data::dir()`, next to `control::Endpoint`, which moved there for the same reason. The desktop app can then ask the same function instead of keeping a copy. tw-config's `default_dir` is gone; its callers use the new one. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + bin/twcore/src/main.rs | 2 +- crates/tw-adopt/Cargo.toml | 2 + crates/tw-adopt/src/foreign.rs | 2 +- crates/tw-api/src/lib.rs | 164 +++++++++++++++++++++++++++++++++ crates/tw-config/Cargo.toml | 2 + crates/tw-config/src/lib.rs | 155 +------------------------------ crates/tw-control/src/lib.rs | 4 +- 8 files changed, 175 insertions(+), 158 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e39feb3e..5604ecf2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2783,6 +2783,7 @@ dependencies = [ "thiserror", "toml_edit", "tracing", + "tw-api", "tw-config", "tw-types", "tw-yaml", @@ -2812,6 +2813,7 @@ dependencies = [ "tempfile", "thiserror", "tokio", + "tw-api", "tw-engine", "tw-pricing", "tw-redact", diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index b2807b61..7b07b56c 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -671,7 +671,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> let dir = path .parent() .map(PathBuf::from) - .unwrap_or_else(tw_config::default_dir); + .unwrap_or_else(tw_api::data::dir); // **数据目录在这儿建,而且只在这儿。**后面每一步(锁、控制面的 socket、 // 凭据文件)都会顺手 `create_dir_all`,谁先到谁建 —— 而 Windows 上「谁 // 建的」决定了它的 ACL,也就决定了那份明文密钥同机的其他用户读不读得到。 diff --git a/crates/tw-adopt/Cargo.toml b/crates/tw-adopt/Cargo.toml index 55450ad9..3f0153aa 100644 --- a/crates/tw-adopt/Cargo.toml +++ b/crates/tw-adopt/Cargo.toml @@ -11,6 +11,8 @@ description = "Detect local AI clients, take over their configuration, and resto serde = { workspace = true } tw-config = { path = "../tw-config" } tw-types = { workspace = true } +# 数据目录在哪由契约层回答,见 `tw_api::data` +tw-api = { workspace = true } tw-yaml = { path = "../tw-yaml" } serde_json = { workspace = true } toml_edit = { workspace = true } diff --git a/crates/tw-adopt/src/foreign.rs b/crates/tw-adopt/src/foreign.rs index ca287442..935446ae 100644 --- a/crates/tw-adopt/src/foreign.rs +++ b/crates/tw-adopt/src/foreign.rs @@ -218,7 +218,7 @@ fn replace(tmp: &Path, real: &Path) -> std::io::Result<()> { /// 工具会把 mtime 全改成同一天)。序号补零到固定宽度,同一毫秒里的 /// 几份也按先后排。 pub fn backup_root() -> PathBuf { - tw_config::default_dir().join("backups") + tw_api::data::dir().join("backups") } /// 同一毫秒里最多几份备份。补零宽度跟着它走,超了排序就不对了。 diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 1b2846b2..afacfd1e 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -3224,6 +3224,170 @@ mod tests { } } +/// 数据目录在哪。 +/// +/// **在契约层,不在 tw-config。**core 和桌面端必须落到同一个目录 —— 端口文件、 +/// 凭据文件、配置都在里面,两边各算一遍、算得不一样的话,界面找不到一个正在 +/// 跑的网关。以前桌面端自己只看 `HOME`,Windows 上那个变量默认不存在,于是它 +/// 落到当前目录下的 `.thinkwatch`,而 core 在 `%APPDATA%\ThinkWatch`。控制面 +/// 的地址(`control::Endpoint`)因为同样的理由搬到了这里。 +pub mod data { + use std::path::PathBuf; + + /// 按哪套习惯去放数据目录。 + /// + /// **是个参数,不是就地一个 `cfg!`。**这样两边的判断在同一台机器上都测得到 + /// —— 写错的那一支往往是本机没在跑的那一支。 + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum Convention { + /// `$HOME/.thinkwatch` + Unix, + /// `%APPDATA%\ThinkWatch` + Windows, + } + + impl Convention { + /// 这台机器用哪一套。 + pub const HERE: Self = if cfg!(windows) { + Self::Windows + } else { + Self::Unix + }; + } + + /// 数据目录:配置、请求库、锁、控制面的端口和凭据文件都在这里。 + /// + /// `THINKWATCH_HOME` 最优先 —— 测试靠它隔离,用户靠它换地方。 + /// + /// 没有它就按平台的习惯:unix 上是 `~/.thinkwatch`;Windows 上是 + /// `%APPDATA%\ThinkWatch`,**不是 `%USERPROFILE%\.thinkwatch`** —— 点开头的 + /// 目录是 unix 的习惯,而在 Windows 上,用户要去找一个程序存了什么的时候 + /// 是去 APPDATA 找的。 + /// + /// **和「用户的 home」不是一回事**,后者用来顺着去找各家客户端的配置 + /// (`~/.claude`、`~/.codex` 这些点开头的目录在 Windows 上确实躺在 + /// `%USERPROFILE%` 下),见 tw-control 的 `home_dir`。 + pub fn dir() -> PathBuf { + pick( + Convention::HERE, + std::env::var_os("THINKWATCH_HOME"), + std::env::var_os("HOME"), + std::env::var_os("APPDATA"), + ) + } + + fn pick( + conv: Convention, + explicit: Option, + home: Option, + appdata: Option, + ) -> PathBuf { + // 设成空串当作没设。`PathBuf::from("")` 是一个谁都解释不了的路径,而它 + // 会一路走到「打不开这个文件」才暴露出来。 + if let Some(e) = explicit.filter(|v| !v.is_empty()) { + return PathBuf::from(e); + } + let base = match conv { + Convention::Unix => home.filter(|v| !v.is_empty()).map(|h| (h, ".thinkwatch")), + Convention::Windows => appdata.filter(|v| !v.is_empty()).map(|a| (a, "ThinkWatch")), + }; + match base { + Some((dir, leaf)) => PathBuf::from(dir).join(leaf), + // 环境里什么都问不出来:退到当前目录下的一个相对路径。**不退到根目录** + // —— 那会让我们往系统盘里写东西。 + None => PathBuf::from(".thinkwatch"), + } + } + + #[cfg(test)] + mod tests { + use super::*; + use std::ffi::OsString; + + fn os(s: &str) -> Option { + Some(OsString::from(s)) + } + + /// 显式指定的那个谁也推不翻它 —— 测试靠它隔离,推翻了测试就会去写 + /// 真正的 `~/.thinkwatch`。 + #[test] + fn thinkwatch_home_wins_on_either_platform() { + for conv in [Convention::Unix, Convention::Windows] { + assert_eq!( + pick( + conv, + os("/somewhere/else"), + os("/home/x"), + os("C:\\AppData") + ), + PathBuf::from("/somewhere/else"), + "{conv:?}" + ); + } + } + + #[test] + fn unix_puts_it_under_home_and_windows_under_appdata() { + assert_eq!( + pick(Convention::Unix, None, os("/home/x"), os("C:\\AppData")), + PathBuf::from("/home/x/.thinkwatch") + ); + assert_eq!( + pick(Convention::Windows, None, os("/home/x"), os("C:\\AppData")), + PathBuf::from("C:\\AppData").join("ThinkWatch") + ); + } + + /// 两边各看各的变量。**Windows 上的 `HOME` 通常根本不存在**,而在装了 + /// Git Bash 的机器上它又存在 —— 两种情况都不该影响数据目录去哪儿。 + #[test] + fn neither_platform_reads_the_other_ones_variable() { + assert_eq!( + pick(Convention::Unix, None, os("/home/x"), None), + PathBuf::from("/home/x/.thinkwatch"), + "unix 不需要 APPDATA" + ); + assert_eq!( + pick(Convention::Windows, None, os("/home/x"), None), + PathBuf::from(".thinkwatch"), + "Windows 上有 HOME 也不能拿它当 APPDATA 使" + ); + } + + /// 设成空串等于没设。`PathBuf::from("")` 要到「打不开这个文件」才暴露。 + #[test] + fn an_empty_variable_counts_as_unset() { + assert_eq!( + pick(Convention::Unix, os(""), os("/home/x"), None), + PathBuf::from("/home/x/.thinkwatch") + ); + assert_eq!( + pick(Convention::Unix, None, os(""), None), + PathBuf::from(".thinkwatch") + ); + } + + /// 什么都问不出来时退到相对路径,**不是根目录**。 + #[test] + fn with_nothing_to_go_on_it_stays_relative() { + for conv in [Convention::Unix, Convention::Windows] { + let got = pick(conv, None, None, None); + assert_eq!(got, PathBuf::from(".thinkwatch"), "{conv:?}"); + assert!(!got.is_absolute(), "{conv:?} 落到了绝对路径:{got:?}"); + } + } + + /// 这台机器上那一套是哪一套。 + #[test] + fn here_follows_the_platform_it_was_compiled_for() { + #[cfg(windows)] + assert_eq!(Convention::HERE, Convention::Windows); + #[cfg(not(windows))] + assert_eq!(Convention::HERE, Convention::Unix); + } + } +} + /// 控制面在哪儿、拿什么进门。 /// /// **这是契约的一部分,不是两边各自的约定。**core 在这儿听,桌面端到这儿连 diff --git a/crates/tw-config/Cargo.toml b/crates/tw-config/Cargo.toml index afa103ec..ac6f2509 100644 --- a/crates/tw-config/Cargo.toml +++ b/crates/tw-config/Cargo.toml @@ -10,6 +10,8 @@ description = "YAML config schema, loading, and validation" [dependencies] tw-engine = { workspace = true } tw-types = { workspace = true } +# 数据目录在哪由契约层回答,见 `tw_api::data` +tw-api = { workspace = true } tw-secret = { workspace = true } # 校验要认得出配置里写到的内置脱敏规则 id tw-redact = { workspace = true } diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index e8ac817b..32f854fb 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -961,73 +961,8 @@ pub use security::{ pub use store::{Fingerprint, Loaded, StoreError, version_of}; pub use validate::validate; -/// 按哪套习惯去放数据目录。 -/// -/// **是个参数,不是就地一个 `cfg!`。**这样两边的判断在同一台机器上都测得到 -/// ——我们现在只有 macOS 的 CI,而写错的那一支恰恰是没人跑的那一支。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Convention { - /// `$HOME/.thinkwatch` - Unix, - /// `%APPDATA%\ThinkWatch` - Windows, -} - -impl Convention { - /// 这台机器用哪一套。 - pub const HERE: Self = if cfg!(windows) { - Self::Windows - } else { - Self::Unix - }; -} - -/// 默认配置目录。 -/// -/// `THINKWATCH_HOME` 最优先 —— 测试靠它隔离,用户靠它换地方。 -/// -/// 没有它就按平台的习惯:unix 上是 `~/.thinkwatch`;Windows 上是 -/// `%APPDATA%\ThinkWatch`,**不是 `%USERPROFILE%\.thinkwatch`** —— 点开头的 -/// 目录是 unix 的习惯,而在 Windows 上,用户要去找一个程序存了什么的时候 -/// 是去 APPDATA 找的。 -/// -/// **和「用户的 home」不是一回事**,后者用来顺着去找各家客户端的配置 -/// (`~/.claude`、`~/.codex` 这些点开头的目录在 Windows 上确实躺在 -/// `%USERPROFILE%` 下),见 `tw_control::home_dir`。 -pub fn default_dir() -> PathBuf { - pick_dir( - Convention::HERE, - std::env::var_os("THINKWATCH_HOME"), - std::env::var_os("HOME"), - std::env::var_os("APPDATA"), - ) -} - -fn pick_dir( - conv: Convention, - explicit: Option, - home: Option, - appdata: Option, -) -> PathBuf { - // 设成空串当作没设。`PathBuf::from("")` 是一个谁都解释不了的路径,而它 - // 会一路走到「打不开这个文件」才暴露出来。 - if let Some(e) = explicit.filter(|v| !v.is_empty()) { - return PathBuf::from(e); - } - let base = match conv { - Convention::Unix => home.filter(|v| !v.is_empty()).map(|h| (h, ".thinkwatch")), - Convention::Windows => appdata.filter(|v| !v.is_empty()).map(|a| (a, "ThinkWatch")), - }; - match base { - Some((dir, leaf)) => PathBuf::from(dir).join(leaf), - // 环境里什么都问不出来:退到当前目录下的一个相对路径。**不退到根目录** - // —— 那会让我们往系统盘里写东西。 - None => PathBuf::from(".thinkwatch"), - } -} - pub fn default_path() -> PathBuf { - default_dir().join("config.yaml") + tw_api::data::dir().join("config.yaml") } #[cfg(test)] @@ -1384,91 +1319,3 @@ mod strictness_tests { assert!(!p("x", "https://api.anthropic.com@evil.com/v1").is_official_endpoint()); } } - -#[cfg(test)] -mod dir_tests { - use super::*; - use std::ffi::OsString; - - fn os(s: &str) -> Option { - Some(OsString::from(s)) - } - - /// 显式指定的那个谁也推不翻它 —— 测试靠它隔离,推翻了测试就会去写 - /// 真正的 `~/.thinkwatch`。 - #[test] - fn thinkwatch_home_wins_on_either_platform() { - for conv in [Convention::Unix, Convention::Windows] { - assert_eq!( - pick_dir( - conv, - os("/somewhere/else"), - os("/home/x"), - os("C:\\AppData") - ), - PathBuf::from("/somewhere/else"), - "{conv:?}" - ); - } - } - - #[test] - fn unix_puts_it_under_home_and_windows_under_appdata() { - assert_eq!( - pick_dir(Convention::Unix, None, os("/home/x"), os("C:\\AppData")), - PathBuf::from("/home/x/.thinkwatch") - ); - assert_eq!( - pick_dir(Convention::Windows, None, os("/home/x"), os("C:\\AppData")), - PathBuf::from("C:\\AppData").join("ThinkWatch") - ); - } - - /// 两边各看各的变量。**Windows 上的 `HOME` 通常根本不存在**,而在装了 - /// Git Bash 的机器上它又存在 —— 两种情况都不该影响数据目录去哪儿。 - #[test] - fn neither_platform_reads_the_other_ones_variable() { - assert_eq!( - pick_dir(Convention::Unix, None, os("/home/x"), None), - PathBuf::from("/home/x/.thinkwatch"), - "unix 不需要 APPDATA" - ); - assert_eq!( - pick_dir(Convention::Windows, None, os("/home/x"), None), - PathBuf::from(".thinkwatch"), - "Windows 上有 HOME 也不能拿它当 APPDATA 使" - ); - } - - /// 设成空串等于没设。`PathBuf::from("")` 要到「打不开这个文件」才暴露。 - #[test] - fn an_empty_variable_counts_as_unset() { - assert_eq!( - pick_dir(Convention::Unix, os(""), os("/home/x"), None), - PathBuf::from("/home/x/.thinkwatch") - ); - assert_eq!( - pick_dir(Convention::Unix, None, os(""), None), - PathBuf::from(".thinkwatch") - ); - } - - /// 什么都问不出来时退到相对路径,**不是根目录**。 - #[test] - fn with_nothing_to_go_on_it_stays_relative() { - for conv in [Convention::Unix, Convention::Windows] { - let got = pick_dir(conv, None, None, None); - assert_eq!(got, PathBuf::from(".thinkwatch"), "{conv:?}"); - assert!(!got.is_absolute(), "{conv:?} 落到了绝对路径:{got:?}"); - } - } - - /// 这台机器上那一套是哪一套。 - #[test] - fn here_follows_the_platform_it_was_compiled_for() { - #[cfg(windows)] - assert_eq!(Convention::HERE, Convention::Windows); - #[cfg(not(windows))] - assert_eq!(Convention::HERE, Convention::Unix); - } -} diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 46de149e..343f49b4 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -72,7 +72,7 @@ pub struct ControlState { /// 用户的 home。 /// -/// **不是数据目录**(那个是 `tw_config::default_dir`)。这里只用来顺着它去找 +/// **不是数据目录**(那个是 `tw_api::data::dir`)。这里只用来顺着它去找 /// 各家客户端的配置 —— `~/.claude`、`~/.codex`、`~/.cursor`,而这些点开头的 /// 目录在 Windows 上同样躺在 `%USERPROFILE%` 下。 /// @@ -1665,7 +1665,7 @@ mod socket_path_tests { #[test] fn the_default_path_fits_with_room_to_spare() { // 这条不是形式主义:如果哪天默认目录变深了,它会立刻响。 - let p = tw_config::default_dir().join("twcore.sock"); + let p = tw_api::data::dir().join("twcore.sock"); socket_path_fits(&p).unwrap(); }