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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
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,也就决定了那份明文密钥同机的其他用户读不读得到。
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-adopt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-adopt/src/foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

/// 同一毫秒里最多几份备份。补零宽度跟着它走,超了排序就不对了。
Expand Down
164 changes: 164 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::ffi::OsString>,
home: Option<std::ffi::OsString>,
appdata: Option<std::ffi::OsString>,
) -> 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<OsString> {
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 在这儿听,桌面端到这儿连
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
155 changes: 1 addition & 154 deletions crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::ffi::OsString>,
home: Option<std::ffi::OsString>,
appdata: Option<std::ffi::OsString>,
) -> 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)]
Expand Down Expand Up @@ -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<OsString> {
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);
}
}
Loading
Loading