A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
fix(claude-account): stash the displaced default login instead of adopting it (#10153)
Jason Young92d69a079f26
diff --git a/src-tauri/src/services/claude_account/layout.rs b/src-tauri/src/services/claude_account/layout.rsindex 75705b218..c2a2e1ae9 100644--- a/src-tauri/src/services/claude_account/layout.rs+++ b/src-tauri/src/services/claude_account/layout.rs@@ -7,6 +7,10 @@//! - `.no-browser`(Windows,不存在的文件)是授权中心关了「登录时自动打开浏览器」时交给//! Claude Code 的 `BROWSER`:让它打不开浏览器,只打印链接。//!+//! 切卡时默认槽位里原来的登录不是 CC Switch 的账号时,收进暂存目录+//! `<app_config_dir>/claude-login-stash/<key 的 sha256 前 16 位>/config/`([`stash_dir`]):+//! 只为不丢掉这份登录、切换失败时能换回去,不进账号表,界面上也不显示。+//!//! macOS 上 Claude Code 把登录存在钥匙串 `Claude Code-credentials-<后缀>`,后缀是//! `CLAUDE_CONFIG_DIR` 原字符串(NFC)的 sha256 前 8 位。删账号时按同样的算法找到它。@@ -17,6 +21,7 @@ use sha2::{Digest, Sha256};use crate::error::AppError;const ROOT_DIRNAME: &str = "claude-accounts";+const STASH_DIRNAME: &str = "claude-login-stash";const CONFIG_DIRNAME: &str = "config";#[cfg(unix)]pub const OPENER_FILENAME: &str = ".open-url";@@ -39,6 +44,41 @@ pub fn config_dir(data_dir: &Path, local_id: &str) -> PathBuf {account_home(data_dir, local_id).join(CONFIG_DIRNAME)}+/// 暂存登录的根目录。+pub fn stash_root(data_dir: &Path) -> PathBuf {+ data_dir.join(STASH_DIRNAME)+}++/// 没收录的登录(账号 key 是 `account_key`)的暂存槽位:`<暂存根>/<key 的 sha256 前 16 位>/config`。+/// 位置由 key 算出,不另记索引;同一个号再被换下来时用同一个目录。+pub fn stash_dir(data_dir: &Path, account_key: &str) -> PathBuf {+ let digest = Sha256::digest(account_key.as_bytes());+ let name: String = digest+ .iter()+ .take(8)+ .map(|byte| format!("{byte:02x}"))+ .collect();+ stash_root(data_dir).join(name).join(CONFIG_DIRNAME)+}++/// `dir` 是不是某个暂存槽位([`stash_dir`] 的样子)。+pub fn is_stash_dir(data_dir: &Path, dir: &Path) -> bool {+ let Ok(rest) = dir.strip_prefix(stash_root(data_dir)) else {+ return false;+ };+ let mut parts = rest.components();+ matches!(+ (parts.next(), parts.next(), parts.next()),+ (Some(std::path::Component::Normal(name)), Some(config), None)+ if name.len() == 16+ && name+ .to_string_lossy()+ .bytes()+ .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))+ && config.as_os_str() == CONFIG_DIRNAME+ )+}+/// 新账号的本机 id:32 位小写 hex,只用作目录名。pub fn new_local_id() -> String {uuid::Uuid::new_v4().simple().to_string()@@ -206,6 +246,29 @@ mod tests {));}+ #[test]+ fn stash_dir_is_stable_per_account_and_recognized() {+ let data = Path::new("/data/.cc-switch");+ let dir = stash_dir(data, "acc:org");+ assert_eq!(dir, stash_dir(data, "acc:org"));+ assert_ne!(dir, stash_dir(data, "other:org"));+ assert!(dir.starts_with(stash_root(data)));+ assert!(is_stash_dir(data, &dir));+ // 账号目录、暂存根本身、嵌套目录、别的数据目录都不算+ assert!(!is_stash_dir(+ data,+ &config_dir(data, "0123456789abcdef0123456789abcdef")+ ));+ assert!(!is_stash_dir(data, &stash_root(data)));+ assert!(!is_stash_dir(data, dir.parent().unwrap()));+ assert!(!is_stash_dir(data, &dir.join("nested")));+ assert!(!is_stash_dir(Path::new("/elsewhere"), &dir));+ assert!(!is_stash_dir(+ data,+ &stash_root(data).join("..").join("config")+ ));+ }+#[test]fn rejects_unsafe_config_dirs() {let data = std::env::temp_dir().join("cc-switch-layout-test");diff --git a/src-tauri/src/services/claude_account/mod.rs b/src-tauri/src/services/claude_account/mod.rsindex 66f32d957..2f2961ee8 100644--- a/src-tauri/src/services/claude_account/mod.rs+++ b/src-tauri/src/services/claude_account/mod.rs@@ -137,7 +137,7 @@ pub struct ClaudeAccountManager {ended: std::sync::Mutex<HashMap<String, FlowEnd>>,}-/// 账号表文件的进程内互斥:管理器和切换(收录默认槽位里原来的登录)都会改它。+/// 账号表文件的进程内互斥:管理器和记套餐([`note_plan`])都会改它。/// 改之前先从磁盘重读,改完立刻落盘,中间不跨 await。static STORE_FILE: std::sync::Mutex<()> = std::sync::Mutex::new(());@@ -395,6 +395,8 @@ impl ClaudeAccountManager {if let Some(plan) = snapshot::dir_plan(&config_dir) {note_plan(&data_dir, &key, &plan);}+ // 切卡时暂存过这个号的登录(当时还没收录):现在有正式的账号目录了,暂存的删掉+ snapshot::discard_stash_of(&data_dir, &key);}).await;}@@ -457,7 +459,7 @@ impl ClaudeAccountManager {pub async fn list(&self) -> Vec<ClaudeAccount> {let accounts: Vec<(String, AccountData)> = {let mut store = self.store.lock().await;- // 切换时可能收录了新账号(默认槽位里原来的登录)+ // 别处(记套餐等)可能直接改过磁盘上的账号表*store = load_store(&self.data_dir);store.accounts@@ -577,7 +579,7 @@ fn create_private_dir(dir: &Path) -> Result<(), AppError> {Ok(())}-/// 按磁盘上的账号表找账号目录、收录新账号:切换路径上用(拿不到 Tauri 状态)。+/// 按磁盘上的账号表找账号目录:切换路径上用(拿不到 Tauri 状态)。pub struct DiskAccounts {pub data_dir: PathBuf,}@@ -588,45 +590,6 @@ impl snapshot::Accounts for DiskAccounts {}}-impl snapshot::Adopter for DiskAccounts {- /// 给默认槽位里原来的登录建一个账号目录:只写资料(`oauthAccount`),凭据由切换随后放进去。- fn adopt(- &self,- found: &identity::Identity,- profile: &serde_json::Value,- ) -> Result<PathBuf, AppError> {- let local_id = layout::new_local_id();- let config_dir = layout::config_dir(&self.data_dir, &local_id);- layout::assert_config_dir(&self.data_dir, &config_dir)?;- create_private_dir(&config_dir)?;- let doc = serde_json::json!({- "oauthAccount": profile,- "hasCompletedOnboarding": true,- });- let bytes =- serde_json::to_vec_pretty(&doc).map_err(|source| AppError::JsonSerialize { source })?;- crate::config::atomic_write_private(&config_dir.join(".claude.json"), &bytes)?;- sync_shared(&config_dir);-- let _file = store_file_guard();- let mut store = load_store(&self.data_dir);- store.accounts.insert(- found.key.clone(),- AccountData {- local_id,- email: found.email.clone(),- org_name: found.org_name.clone(),- plan: None,- rate_limit_tier: None,- added_at: chrono::Utc::now().timestamp(),- },- );- persist_store(&self.data_dir, &store)?;- log::info!("[ClaudeAccount] 已把默认登录收录为账号");- Ok(config_dir)- }-}-/// 删掉一个账号的目录和它在钥匙串里的条目。`remove_dir_all` 不跟随符号链接(共享层链到/// 默认目录的那些只删链接本身)。fn remove_account_files(home: &Path, config_dir: &Path) {diff --git a/src-tauri/src/services/claude_account/snapshot/mod.rs b/src-tauri/src/services/claude_account/snapshot/mod.rsindex e542f9cb1..1722073c9 100644--- a/src-tauri/src/services/claude_account/snapshot/mod.rs+++ b/src-tauri/src/services/claude_account/snapshot/mod.rs@@ -6,7 +6,8 @@//!//! 一次切换([`check_out`])://! 1. 收回:默认槽位里现在是谁(O),就把它的账号键写回 O 的账号槽位;O 还不是 CC Switch-//! 管的账号时,先给它建一个账号目录([`Adopter`])。+//! 管的账号时,写进 O 的暂存槽位([`layout::stash_dir`])。不收录成账号:用户没要求就不进+//! 账号表,暂存只为不丢掉这份登录、切换失败时能换回去(换回后删掉)。//! 2. 放入:默认槽位 = 原来的共享键(MCP 的 OAuth 等,属于这台电脑)+ T 的账号键。这一步//! 是提交点,在 Claude Code 的写锁里先比对再写(期间被 Claude Code 改过就放弃)。//! 3. 默认的 `.claude.json`:`oauthAccount` 换成 T 的,删掉跟账号走的缓存。@@ -33,16 +34,15 @@ use std::path::{Path, PathBuf};use std::sync::Mutex;use std::time::Duration;-use serde_json::Value;--use super::identity;+use super::{identity, layout};use crate::error::AppError;+use crate::sync_utils::MutexExt;use store::{CredentialStore, Slot};pub use files::backup_dir;pub use recover::recover;pub use state::{confirm, load_state, update_state, Journal, State, Step};-pub use switch::{check_out, replace_live, vacate};+pub use switch::{check_back, check_out, replace_live, vacate};#[cfg(test)]use creds::{account_fingerprint, login_expiry, merge};@@ -197,12 +197,6 @@ pub fn note_login_expiry(data_dir: &Path, account: &str, config_dir: &Path) {});}-/// 默认槽位里的登录属于一个还没收录的账号时,给它建账号目录并收录,返回目录。-/// `profile` 是默认 `.claude.json` 里的 `oauthAccount`。-pub trait Adopter {- fn adopt(&self, identity: &identity::Identity, profile: &Value) -> Result<PathBuf, AppError>;-}-/// 账号 key → 本机账号目录(已收录的)。pub trait Accounts {fn dir_of(&self, account: &str) -> Option<PathBuf>;@@ -214,7 +208,6 @@ pub struct Ctx<'a> {pub default: Slot,pub store: &'a dyn CredentialStore,pub accounts: &'a dyn Accounts,- pub adopter: &'a dyn Adopter,}/// 切换的结果。@@ -223,12 +216,54 @@ pub enum Outcome {/// 默认槽位里本来就是 TAlreadyLive,Switched {- /// 原来默认槽位里的号刚被收录成新账号(第一次切换时常见)- adopted: Option<String>,- /// 原来默认槽位里的号和它被收回到的目录:后面的步骤失败时用它切回去+ /// 原来默认槽位里的号和它被收回到的目录(账号目录或暂存槽位):后面的步骤失败时用它切回去previous: Option<(String, PathBuf)>,},}+/// 账号 `account`(没收录的)暂存着的登录目录:目录在、资料认得出是它时才有。+pub fn stashed_dir(data_dir: &Path, account: &str) -> Option<PathBuf> {+ let dir = layout::stash_dir(data_dir, account);+ let profile = files::read_profile(&Slot::Account(dir.clone()).global_config())?;+ let found = identity::identity_from_profile(&profile)?;+ (found.key == account).then_some(dir)+}++/// 删掉一个暂存槽位:凭据(含它的备份槽位)和整个暂存目录。切换失败换回原来的号之后用。+/// `dir` 不是暂存槽位时什么都不做。+fn discard_stash(ctx: &Ctx<'_>, dir: &Path) -> Result<(), AppError> {+ let _serial = SWITCH.lock_recover();+ remove_stash(ctx.store, ctx.data_dir, dir)+}++/// 账号 `account` 正式收录成账号之后:它要是还有暂存着的登录,删掉(尽力而为,失败只记日志)。+pub fn discard_stash_of(data_dir: &Path, account: &str) {+ let dir = layout::stash_dir(data_dir, account);+ if !dir.is_dir() {+ return;+ }+ let _serial = SWITCH.lock_recover();+ if let Err(error) = remove_stash(store::platform_store().as_ref(), data_dir, &dir) {+ log::warn!("[ClaudeAccount] 删除暂存的登录失败: {error}");+ } else {+ log::info!("[ClaudeAccount] 账号已收录,删掉它暂存的登录");+ }+}++fn remove_stash(store: &dyn CredentialStore, data_dir: &Path, dir: &Path) -> Result<(), AppError> {+ if !layout::is_stash_dir(data_dir, dir) {+ return Ok(());+ }+ store.delete(&Slot::Account(files::backup_dir(dir)))?;+ store.delete(&Slot::Account(dir.to_path_buf()))?;+ // 外层是 `<暂存根>/<hash>`,里面只有这个槽位和它的备份+ let home = dir.parent().unwrap_or(dir);+ match std::fs::remove_dir_all(home) {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(source) => Err(AppError::io(home, source)),+ }+}+#[cfg(test)]mod tests;diff --git a/src-tauri/src/services/claude_account/snapshot/switch.rs b/src-tauri/src/services/claude_account/snapshot/switch.rsindex 19d8d187d..0a74e851f 100644--- a/src-tauri/src/services/claude_account/snapshot/switch.rs+++ b/src-tauri/src/services/claude_account/snapshot/switch.rs@@ -19,6 +19,7 @@ use super::{default_owner, identity, update_state, Ctx, Journal, Outcome, Step, COMMIT_DEADLINE, SWITCH,};use crate::error::AppError;+use crate::services::claude_account::{create_private_dir, layout};/// 一次切换要用到的、在刷新锁里读好的东西。struct Plan {@@ -45,6 +46,19 @@ pub fn check_out(ctx: &Ctx<'_>, target: &str, target_dir: &Path) -> Result<Outcorun(ctx, target, target_dir, Mode::Switch)}+/// 切换的后续步骤失败时换回原来的号 `previous`(收回在 `dir`,[`Outcome::Switched`] 的+/// `previous`)。`dir` 是暂存槽位(原来的号不是账号)时,换回后删掉暂存。+pub fn check_back(ctx: &Ctx<'_>, previous: &str, dir: &Path) -> Result<(), AppError> {+ check_out(ctx, previous, dir)?;+ if layout::is_stash_dir(ctx.data_dir, dir) {+ if let Err(error) = super::discard_stash(ctx, dir) {+ // 登录已经换回来了,暂存删不掉只是多留一份+ log::warn!("[ClaudeAccount] 换回后删除暂存的登录失败: {error}");+ }+ }+ Ok(())+}+/// 账号 `target` 刚重新登录(新登录在 `target_dir`)、默认槽位里又正是它:用新登录换掉默认槽位/// 里的旧登录(旧的可能已经过期或被吊销)。默认槽位不是它时不动。返回换了没有。pub fn replace_live(ctx: &Ctx<'_>, target: &str, target_dir: &Path) -> Result<bool, AppError> {@@ -148,34 +162,23 @@ fn plan(}))}-/// 把默认槽位里原来的号收回它的账号槽位;还没收录的先收录。原来就是 T(重新登录)时不收回:-/// 旧登录由新登录顶替。+/// 把默认槽位里原来的号收回它的账号槽位;还没收录的号收进它的暂存槽位(不收录成账号)。+/// 原来就是 T(重新登录)时不收回:旧登录由新登录顶替。fn park_previous(ctx: &Ctx<'_>, plan: &Plan) -> Result<Outcome, AppError> {let (Some(live), Some(owner)) = (plan.live.as_ref(), plan.live_owner.as_ref()) else {- return Ok(Outcome::Switched {- adopted: None,- previous: None,- });+ return Ok(Outcome::Switched { previous: None });};if owner.key == plan.journal.target {- return Ok(Outcome::Switched {- adopted: None,- previous: None,- });+ return Ok(Outcome::Switched { previous: None });}- let mut adopted = None;- let park_dir = match ctx.accounts.dir_of(&owner.key) {- Some(dir) => dir,+ let (park_dir, stashed) = match ctx.accounts.dir_of(&owner.key) {+ Some(dir) => (dir, false),None => {- let profile = plan- .live_profile- .as_ref()- .and_then(|doc| doc.get("oauthAccount"))- .cloned()- .unwrap_or(Value::Null);- let dir = ctx.adopter.adopt(owner, &profile)?;- adopted = Some(owner.key.clone());- dir+ // 资料(`oauthAccount`)由下面的 park 写进去,之后切回时靠它认人+ let dir = layout::stash_dir(ctx.data_dir, &owner.key);+ create_private_dir(&dir)?;+ log::info!("[ClaudeAccount] 原来的登录不是 CC Switch 的账号,暂存起来,不收录");+ (dir, true)}};park(@@ -185,9 +188,11 @@ fn park_previous(ctx: &Ctx<'_>, plan: &Plan) -> Result<Outcome, AppError> {&owner.key,&Slot::Account(park_dir.clone()),)?;- update_state(ctx.data_dir, |state| note_expiry(state, &owner.key, live))?;+ // 暂存的号不在账号列表里,不用记过期时间+ if !stashed {+ update_state(ctx.data_dir, |state| note_expiry(state, &owner.key, live))?;+ }Ok(Outcome::Switched {- adopted,previous: Some((owner.key.clone(), park_dir)),})}diff --git a/src-tauri/src/services/claude_account/snapshot/tests.rs b/src-tauri/src/services/claude_account/snapshot/tests.rsindex c42ef2536..bb5932319 100644--- a/src-tauri/src/services/claude_account/snapshot/tests.rs+++ b/src-tauri/src/services/claude_account/snapshot/tests.rs@@ -2,7 +2,7 @@ use std::cell::RefCell;use std::collections::HashMap;use std::sync::atomic::{AtomicUsize, Ordering};-use serde_json::json;+use serde_json::{json, Value};use super::store::memory::MemoryStore;use super::*;@@ -27,7 +27,6 @@ struct Fixture {data: PathBuf,store: MemoryStore,accounts: FakeAccounts,- adopter: FakeAdopter,}#[derive(Default)]@@ -39,27 +38,6 @@ impl Accounts for FakeAccounts {}}-struct FakeAdopter {- root: PathBuf,- adopted: RefCell<Vec<String>>,-}--impl Adopter for FakeAdopter {- fn adopt(&self, found: &identity::Identity, profile: &Value) -> Result<PathBuf, AppError> {- let dir = self- .root- .join(format!("adopted-{}", self.adopted.borrow().len()));- std::fs::create_dir_all(&dir).unwrap();- std::fs::write(- dir.join(".claude.json"),- serde_json::to_vec(&json!({ "oauthAccount": profile })).unwrap(),- )- .unwrap();- self.adopted.borrow_mut().push(found.key.clone());- Ok(dir)- }-}-fn secret(org: &str, refresh: &str) -> Secret {let Value::Object(map) = json!({"claudeAiOauth": {"accessToken": format!("at-{refresh}"), "refreshToken": refresh, "expiresAt": 1},@@ -82,16 +60,11 @@ impl Fixture {let data = tmp.path().join("data");std::fs::create_dir_all(home.join(".claude")).unwrap();std::fs::create_dir_all(&data).unwrap();- let adopter = FakeAdopter {- root: tmp.path().join("accounts"),- adopted: RefCell::default(),- };Fixture {home,data,store: MemoryStore::default(),accounts: FakeAccounts::default(),- adopter,_tmp: tmp,}}@@ -108,7 +81,6 @@ impl Fixture {default: self.default(),store: &self.store,accounts: &self.accounts,- adopter: &self.adopter,}}@@ -146,6 +118,10 @@ impl Fixture {.unwrap();}+ fn stash_root(&self) -> PathBuf {+ layout::stash_root(&self.data)+ }+fn default_profile(&self) -> Value {serde_json::from_slice(&std::fs::read(self.default().global_config()).unwrap()).unwrap()}@@ -162,18 +138,17 @@ impl Fixture {}#[test]-fn first_switch_adopts_the_default_login_and_moves_the_target_in() {+fn first_switch_stashes_the_default_login_and_moves_the_target_in() {let fx = Fixture::new();fx.sign_in_default("me", "org-me", "rt-me");let (work, work_dir) = fx.account("work", "org-work", "rt-work");let outcome = check_out(&fx.ctx(), &work, &work_dir).unwrap();- let adopted_dir = fx.adopter.root.join("adopted-0");+ let stash = layout::stash_dir(&fx.data, "me:org-me");assert_eq!(outcome,Outcome::Switched {- adopted: Some("me:org-me".into()),- previous: Some(("me:org-me".into(), adopted_dir.clone())),+ previous: Some(("me:org-me".into(), stash.clone())),});@@ -186,11 +161,13 @@ fn first_switch_adopts_the_default_login_and_moves_the_target_in() {let left = fx.store.get(&Slot::Account(work_dir)).unwrap();assert!(left.0.get("claudeAiOauth").is_none());assert_eq!(left.0["mcpOAuth"], json!({"server": "kept-per-slot"}));- // 原来的号收进了新账号目录- assert_eq!(- fx.refresh_of(&Slot::Account(adopted_dir)).as_deref(),- Some("rt-me")- );+ // 原来的号进了暂存槽位:只有账号键,资料认得出是它,没有收录成账号、也不记过期时间+ let stashed = fx.store.get(&Slot::Account(stash.clone())).unwrap();+ assert_eq!(stashed.0["claudeAiOauth"]["refreshToken"], json!("rt-me"));+ assert!(stashed.0.get("mcpOAuth").is_none());+ assert_eq!(stashed_dir(&fx.data, "me:org-me"), Some(stash));+ assert!(fx.accounts.dir_of("me:org-me").is_none());+ assert!(!load_state(&fx.data).login_expiry.contains_key("me:org-me"));// 资料换成 work 的,账号缓存删掉,其他键不碰let doc = fx.default_profile();assert_eq!(doc["oauthAccount"]["accountUuid"], "work");@@ -203,6 +180,120 @@ fn first_switch_adopts_the_default_login_and_moves_the_target_in() {assert_eq!(default_owner(&fx.default()).as_deref(), Some(work.as_str()));}+#[test]+fn checking_back_restores_the_stashed_login_and_removes_the_stash() {+ let fx = Fixture::new();+ fx.sign_in_default("me", "org-me", "rt-me");+ let (work, work_dir) = fx.account("work", "org-work", "rt-work");+ let Outcome::Switched {+ previous: Some((me, stash)),+ } = check_out(&fx.ctx(), &work, &work_dir).unwrap()+ else {+ panic!("should have switched");+ };++ // 写卡片失败:换回原来的号+ check_back(&fx.ctx(), &me, &stash).unwrap();+ assert_eq!(fx.refresh_of(&fx.default()).as_deref(), Some("rt-me"));+ assert_eq!(default_owner(&fx.default()).as_deref(), Some(me.as_str()));+ // work 回到它自己的槽位+ assert_eq!(+ fx.refresh_of(&Slot::Account(work_dir)).as_deref(),+ Some("rt-work")+ );+ // 暂存删干净:凭据、备份槽位和整个暂存目录+ assert!(fx.store.get(&Slot::Account(stash.clone())).is_none());+ assert!(fx.store.get(&Slot::Account(backup_dir(&stash))).is_none());+ assert!(!stash.parent().unwrap().exists());+ assert_eq!(stashed_dir(&fx.data, &me), None);+}++#[test]+fn checking_back_to_an_account_dir_keeps_it() {+ let fx = Fixture::new();+ fx.sign_in_default("me", "org-me", "rt-me");+ let (me, me_dir) = fx.account("me", "org-me", "rt-me-old");+ let (work, work_dir) = fx.account("work", "org-work", "rt-work");+ check_out(&fx.ctx(), &work, &work_dir).unwrap();++ check_back(&fx.ctx(), &me, &me_dir).unwrap();+ assert_eq!(fx.refresh_of(&fx.default()).as_deref(), Some("rt-me"));+ // 账号目录不是暂存槽位,不删+ assert!(me_dir.join(".claude.json").is_file());+ assert!(!fx.stash_root().exists());+}++#[test]+fn recovery_can_find_the_previous_login_in_the_stash() {+ let fx = Fixture::new();+ fx.sign_in_default("me", "org-me", "rt-me");+ let (work, work_dir) = fx.account("work", "org-work", "rt-work");+ check_out(&fx.ctx(), &work, &work_dir).unwrap();++ // 启动时按切换日志找原来的号:它不在账号表里,在暂存槽位+ let journal = done(&fx.data).unwrap();+ let before = journal.before_owner.unwrap();+ assert_eq!(before, "me:org-me");+ assert!(fx.accounts.dir_of(&before).is_none());+ let dir = stashed_dir(&fx.data, &before).unwrap();+ check_back(&fx.ctx(), &before, &dir).unwrap();+ assert_eq!(fx.refresh_of(&fx.default()).as_deref(), Some("rt-me"));+ assert!(!dir.exists());++ // 资料认不出是这个号时不算+ let other = layout::stash_dir(&fx.data, "ghost:org");+ std::fs::create_dir_all(&other).unwrap();+ std::fs::write(+ other.join(".claude.json"),+ serde_json::to_vec(&json!({"oauthAccount": profile("me", "org-me")})).unwrap(),+ )+ .unwrap();+ assert_eq!(stashed_dir(&fx.data, "ghost:org"), None);+}++#[test]+fn stashing_the_same_login_twice_reuses_the_stash_and_backs_up_the_older_one() {+ let fx = Fixture::new();+ fx.sign_in_default("me", "org-me", "rt-me-1");+ let (work, work_dir) = fx.account("work", "org-work", "rt-work");+ let (other, other_dir) = fx.account("other", "org-other", "rt-other");+ check_out(&fx.ctx(), &work, &work_dir).unwrap();+ let stash = layout::stash_dir(&fx.data, "me:org-me");++ // 之后用户在 Claude Code 里又登了 me(另一次登录),再切卡+ fx.sign_in_default("me", "org-me", "rt-me-2");+ let outcome = check_out(&fx.ctx(), &other, &other_dir).unwrap();+ assert_eq!(+ outcome,+ Outcome::Switched {+ previous: Some(("me:org-me".into(), stash.clone())),+ }+ );+ // 同一个暂存目录:新的那份在槽位里,旧的挪进备份槽位+ assert_eq!(+ fx.refresh_of(&Slot::Account(stash.clone())).as_deref(),+ Some("rt-me-2")+ );+ assert_eq!(+ fx.refresh_of(&Slot::Account(backup_dir(&stash))).as_deref(),+ Some("rt-me-1")+ );+ assert_eq!(std::fs::read_dir(fx.stash_root()).unwrap().count(), 1);+ assert!(fx.accounts.dir_of("me:org-me").is_none());+}++#[test]+fn discarding_a_non_stash_dir_does_nothing() {+ let fx = Fixture::new();+ let (_, work_dir) = fx.account("work", "org-work", "rt-work");+ discard_stash(&fx.ctx(), &work_dir).unwrap();+ assert_eq!(+ fx.refresh_of(&Slot::Account(work_dir.clone())).as_deref(),+ Some("rt-work")+ );+ assert!(work_dir.join(".claude.json").is_file());+}+#[test]fn switching_back_parks_the_live_account_in_its_own_slot() {let fx = Fixture::new();@@ -225,7 +316,6 @@ fn switching_back_parks_the_live_account_in_its_own_slot() {assert_eq!(outcome,Outcome::Switched {- adopted: None,previous: Some((work.clone(), work_dir.clone())),});@@ -236,7 +326,7 @@ fn switching_back_parks_the_live_account_in_its_own_slot() {Some("rt-work-2"));assert!(fx.refresh_of(&Slot::Account(me_dir.clone())).is_none());- assert!(fx.adopter.adopted.borrow().is_empty());+ assert!(!fx.stash_root().exists());// 第一次收回时 me 槽位里那份另外的登录没被覆盖掉,留在备份里(只有账号键)let backup = fx.store.get(&Slot::Account(backup_dir(&me_dir))).unwrap();assert_eq!(@@ -294,7 +384,7 @@ fn expired_target_is_refused_without_changes() {);assert!(check_out(&fx.ctx(), &work, &work_dir).is_err());assert_eq!(fx.refresh_of(&fx.default()).as_deref(), Some("rt-me"));- assert!(fx.adopter.adopted.borrow().is_empty());+ assert!(!fx.stash_root().exists());}#[test]@@ -348,7 +438,7 @@ fn signed_out_target_is_refused_without_changes() {fx.store.delete(&Slot::Account(work_dir.clone())).unwrap();assert!(check_out(&fx.ctx(), &work, &work_dir).is_err());assert_eq!(fx.refresh_of(&fx.default()).as_deref(), Some("rt-me"));- assert!(fx.adopter.adopted.borrow().is_empty());+ assert!(!fx.stash_root().exists());}#[test]@@ -371,13 +461,7 @@ fn empty_default_slot_just_receives_the_target() {let fx = Fixture::new();let (work, work_dir) = fx.account("work", "org-work", "rt-work");let outcome = check_out(&fx.ctx(), &work, &work_dir).unwrap();- assert_eq!(- outcome,- Outcome::Switched {- adopted: None,- previous: None,- }- );+ assert_eq!(outcome, Outcome::Switched { previous: None });assert_eq!(fx.refresh_of(&fx.default()).as_deref(), Some("rt-work"));assert_eq!(fx.default_profile()["oauthAccount"]["accountUuid"], "work");}@@ -662,7 +746,6 @@ fn failure_after_the_commit_still_counts_as_switched() {assert_eq!(outcome,Outcome::Switched {- adopted: None,previous: Some((me, me_dir)),});@@ -856,13 +939,7 @@ fn vacate_moves_the_login_back_out_of_an_empty_default() {),);let outcome = check_out(&fx.ctx(), &work, &work_dir).unwrap();- assert_eq!(- outcome,- Outcome::Switched {- adopted: None,- previous: None,- }- );+ assert_eq!(outcome, Outcome::Switched { previous: None });assert!(done(&fx.data).unwrap().before_owner.is_none());vacate(&fx.ctx(), &work, &work_dir).unwrap();diff --git a/src-tauri/src/services/provider/claude_official.rs b/src-tauri/src/services/provider/claude_official.rsindex 02a06d201..6025913eb 100644--- a/src-tauri/src/services/provider/claude_official.rs+++ b/src-tauri/src/services/provider/claude_official.rs@@ -78,7 +78,7 @@ pub fn with_login_switch<R>(/// 换掉登录之前默认槽位里是什么:切换的后续步骤失败时用来换回去。enum PreviousLogin {- /// 原来的号和它被收回到的目录+ /// 原来的号和它被收回到的目录(账号目录,或没收录的号的暂存槽位)Account {account: String,dir: std::path::PathBuf,@@ -146,9 +146,7 @@ fn restore_login(previous: PreviousLogin) -> bool {}let data_dir = crate::config::get_app_config_dir();let result = with_snapshot_ctx(&data_dir, |ctx| match &previous {- PreviousLogin::Account { account, dir } => {- snapshot::check_out(ctx, account, dir).map(|_| ())- }+ PreviousLogin::Account { account, dir } => snapshot::check_back(ctx, account, dir),PreviousLogin::Empty { target, dir } => snapshot::vacate(ctx, target, dir),});match result {@@ -188,7 +186,9 @@ pub fn recover_login_switch(db: &Database) {if !pointer_matches && snapshot::is_live(&journal.target) {log::info!("[ClaudeAccount] 上次切换没来得及更新卡片,把登录换回原来的号");let previous = match journal.before_owner {+ // 原来的号不是账号时在它的暂存槽位里Some(account) => claude_account::config_dir_on_disk(&data_dir, &account)+ .or_else(|| snapshot::stashed_dir(&data_dir, &account)).map(|dir| PreviousLogin::Account { account, dir }),None => Some(PreviousLogin::Empty {target: journal.target,@@ -265,7 +265,6 @@ fn with_snapshot_ctx<R>(default: snapshot::store::Slot::default_slot(),store: store.as_ref(),accounts: &accounts,- adopter: &accounts,})}