Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

121 KB
Raw Blame
use std::sync::Mutex as StdMutex;

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use serde_json::json;

use super::*;

#[derive(Default)]
struct MemoryLogin {
    value: StdMutex<Option<String>>,
    reads: StdMutex<usize>,
    writes: StdMutex<usize>,
    deletes: StdMutex<usize>,
    locked: StdMutex<bool>,
    post_write_read_failures: StdMutex<usize>,
}

impl AgyLoginStore for MemoryLogin {
    fn read(&self) -> Result<Option<String>, AppError> {
        *self.reads.lock().unwrap() += 1;
        if *self.locked.lock().unwrap() {
            return Err(AppError::Config("test keychain is locked".into()));
        }
        let mut failures = self.post_write_read_failures.lock().unwrap();
        if *failures > 0 && *self.writes.lock().unwrap() > 0 {
            *failures -= 1;
            return Err(AppError::Config("test keychain readback failed".into()));
        }
        Ok(self.value.lock().unwrap().clone())
    }
    fn read_for_switch(&self) -> Result<Option<String>, AppError> {
        *self.locked.lock().unwrap() = false;
        self.read()
    }
    fn write(&self, value: &str) -> Result<(), AppError> {
        *self.value.lock().unwrap() = Some(value.to_string());
        *self.writes.lock().unwrap() += 1;
        Ok(())
    }
    fn delete(&self) -> Result<(), AppError> {
        *self.value.lock().unwrap() = None;
        *self.deletes.lock().unwrap() += 1;
        Ok(())
    }
}

fn id_token(sub: &str, email: &str) -> String {
    format!(
        "e30.{}.sig",
        URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"sub": sub, "email": email})).unwrap())
    )
}

fn credential(sub: &str, access: &str) -> Value {
    json!({
        "token": {"access_token": access, "token_type": "Bearer", "refresh_token": format!("refresh-{sub}"),
                  "expiry": "2026-10-21T13:41:43.657824+08:00", "expires_in": 3599},
        "auth_method": "consumer",
        "id_token": id_token(sub, &format!("{sub}@example.com")),
    })
}

fn set_live(login: &MemoryLogin, credential: &Value) {
    *login.value.lock().unwrap() = Some(keychain::encode(credential).unwrap());
}

fn live_sub(login: &MemoryLogin) -> Option<String> {
    let raw = login.value.lock().unwrap().clone()?;
    let credential = keychain::decode(&raw).ok()?;
    identity::identity(credential["id_token"].as_str()?)?.sub
}

fn manager() -> (tempfile::TempDir, Arc<MemoryLogin>, AgyAccountManager) {
    let dir = tempfile::tempdir().unwrap();
    let login = Arc::new(MemoryLogin::default());
    let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login.clone());
    (dir, login, manager)
}

async fn add(manager: &AgyAccountManager, sub: &str) {
    let mut store = manager.store.lock().await;
    let credential = credential(sub, "fresh");
    let claims = identity::identity(credential["id_token"].as_str().unwrap()).unwrap();
    upsert(&mut store, credential, &claims);
    manager.persist(&store).unwrap();
}

// 以下测试只在支持切号的平台上有意义。
#[cfg(any(target_os = "macos", windows, target_os = "linux"))]
mod switching {
    use super::*;

    use crate::app_config::AppType;
    use crate::database::Database;
    use crate::provider::{AuthBinding, AuthBindingSource, Provider, ProviderMeta};
    use crate::services::provider::agy_direct::{save_from_editor, switch_account};
    use crate::store::AppState;
    use crate::test_support::TestHome;
    use serial_test::serial;

    fn official_card(account: &str) -> Provider {
        let mut provider =
            Provider::with_id("official".into(), "Antigravity".into(), json!({}), None);
        provider.category = Some("official".into());
        provider.meta = Some(ProviderMeta {
            auth_binding: Some(AuthBinding {
                source: AuthBindingSource::ManagedAccount,
                auth_provider: Some("agy_oauth".into()),
                account_id: Some(account.into()),
            }),
            ..Default::default()
        });
        provider
    }

    #[test]
    #[serial]
    fn saving_a_new_provider_binding_changes_the_live_login() {
        // 保存会写 config.json 和设备状态,都在进程共用的测试 home 下;用自己的 home。
        let _home = TestHome::new();
        let (_dir, login, manager) = manager();
        let state = AppState::new(Arc::new(Database::memory().unwrap()));
        set_live(&login, &credential("alice", "a1"));
        tauri::async_runtime::block_on(manager.import_current()).unwrap();
        tauri::async_runtime::block_on(add(&manager, "bob"));
        state
            .db
            .save_provider(&AppType::Agy, &official_card("alice"))
            .unwrap();

        let mut card = official_card("bob");
        save_from_editor(&state, &manager, card.clone(), None).unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        let status = tauri::async_runtime::block_on(manager.status()).unwrap();
        assert_eq!(status.current_account_id.as_deref(), Some("bob"));

        tauri::async_runtime::block_on(manager.switch_to("alice")).unwrap();
        card.name = "Renamed card".into();
        save_from_editor(&state, &manager, card.clone(), None).unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));

        card.meta = None;
        save_from_editor(&state, &manager, card, None).unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
    }

    #[test]
    #[serial]
    fn switching_accounts_enables_the_matching_direct_provider() {
        let _home = TestHome::new();
        let (_dir, login, manager) = manager();
        let state = AppState::new(Arc::new(Database::memory().unwrap()));
        set_live(&login, &credential("alice", "a1"));
        tauri::async_runtime::block_on(manager.import_current()).unwrap();
        tauri::async_runtime::block_on(add(&manager, "bob"));
        tauri::async_runtime::block_on(add(&manager, "carol"));

        let alice = official_card("alice");
        save_from_editor(&state, &manager, alice.clone(), None).unwrap();
        let mut bob = official_card("bob");
        bob.id = "official-bob".into();
        state.db.save_provider(&AppType::Agy, &bob).unwrap();

        assert!(switch_account(&state, &manager, "bob").unwrap());
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        let current_provider = || {
            crate::mode::current::direct_provider(&state.db, &AppType::Agy)
                .unwrap()
                .unwrap()
                .id
        };
        assert_eq!(current_provider(), bob.id);

        assert!(!switch_account(&state, &manager, "carol").unwrap());
        assert_eq!(live_sub(&login).as_deref(), Some("carol"));
        assert_eq!(current_provider(), bob.id);

        assert!(switch_account(&state, &manager, "alice").unwrap());
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert_eq!(current_provider(), alice.id);
    }

    #[test]
    #[serial]
    fn a_missing_bound_account_leaves_the_login_and_provider_unchanged() {
        // A failed save rolls the row back only when no agy operation is pending in the
        // device store, which lives under the process-wide test home. Serial tests swap
        // that home and may hold a pending agy operation, so use a home of our own.
        let _home = TestHome::new();
        let (_dir, login, manager) = manager();
        let state = AppState::new(Arc::new(Database::memory().unwrap()));
        set_live(&login, &credential("alice", "a1"));
        let previous = official_card("alice");
        state.db.save_provider(&AppType::Agy, &previous).unwrap();

        let card = official_card("missing");
        assert!(save_from_editor(&state, &manager, card.clone(), None).is_err());
        let saved = state
            .db
            .get_provider_by_id(&card.id, &AppType::Agy)
            .unwrap()
            .unwrap();
        assert_eq!(
            saved
                .meta
                .unwrap()
                .managed_account_id_for("agy_oauth")
                .as_deref(),
            Some("alice")
        );
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));

        let mut new_card = card;
        new_card.id = "new".into();
        assert!(save_from_editor(&state, &manager, new_card, None).is_err());
        assert!(state
            .db
            .get_provider_by_id("new", &AppType::Agy)
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn status_reports_an_uncollected_login_and_import_collects_it() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        // 查看状态不收录没见过的号,只报出它的名字
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id, None);
        assert!(status.accounts.is_empty());
        assert_eq!(
            status.uncollected_login.as_deref(),
            Some("[email protected]")
        );
        assert_eq!(manager.current_account_id().await, None);
        // 用户点「收录」才收进来
        let account = manager.import_current().await.unwrap();
        assert_eq!(account.id, "alice");
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id.as_deref(), Some("alice"));
        assert_eq!(status.accounts.len(), 1);
        assert_eq!(status.uncollected_login, None);
        assert_eq!(*login.writes.lock().unwrap(), 0, "查看、收录都不写钥匙串");
    }

    #[tokio::test]
    async fn status_refreshes_the_copy_of_a_collected_login() {
        let (_dir, login, manager) = manager();
        add(&manager, "alice").await;
        // agy 续期后写回新的 access token:已收录的号照样跟上
        set_live(&login, &credential("alice", "renewed"));
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id.as_deref(), Some("alice"));
        assert_eq!(status.uncollected_login, None);
        let store = manager.store.lock().await;
        assert_eq!(
            store.accounts["alice"].credential["token"]["access_token"],
            "renewed"
        );
    }

    #[test]
    #[serial]
    fn cloud_snapshot_waits_for_a_failed_binding_save_to_roll_back() {
        use crate::services::sync_protocol::sync_mutex;

        // Own test home, as in the test above.
        let _home = TestHome::new();

        struct CancelUnlock;

        impl AgyLoginStore for CancelUnlock {
            fn read(&self) -> Result<Option<String>, AppError> {
                assert!(sync_mutex().try_lock().is_err());
                Err(AppError::Message("keychain unlock cancelled".into()))
            }

            fn write(&self, _: &str) -> Result<(), AppError> {
                unreachable!("a cancelled unlock must not write")
            }

            fn delete(&self) -> Result<(), AppError> {
                unreachable!("a cancelled unlock must not delete")
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let manager =
            AgyAccountManager::with_login_store(dir.path().to_path_buf(), Arc::new(CancelUnlock));
        tauri::async_runtime::block_on(add(&manager, "bob"));
        let state = AppState::new(Arc::new(Database::memory().unwrap()));
        state
            .db
            .save_provider(&AppType::Agy, &official_card("alice"))
            .unwrap();
        // The dump header carries a per-second timestamp; drop it so two snapshots
        // taken across a second boundary still compare equal.
        let snapshot = || {
            state
                .db
                .export_sql_string_for_sync()
                .unwrap()
                .lines()
                .filter(|line| !line.starts_with("-- 生成时间:"))
                .collect::<Vec<_>>()
                .join("\n")
        };
        let before = snapshot();

        let error = save_from_editor(&state, &manager, official_card("bob"), None).unwrap_err();
        assert_eq!(error.to_string(), "keychain unlock cancelled");

        let _sync_guard = sync_mutex().blocking_lock();
        assert_eq!(snapshot(), before);
    }

    #[tokio::test]
    async fn status_leaves_a_locked_keychain_alone_but_switch_can_unlock_it() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        add(&manager, "bob").await;
        *login.locked.lock().unwrap() = true;

        let status = manager.status().await.unwrap();
        assert!(status.current_account_id.is_none());
        assert_eq!(status.accounts.len(), 1);
        assert!(*login.locked.lock().unwrap());

        manager.switch_to("bob").await.unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        // 没收录过的 alice 只暂存,不进账号表
        assert!(!manager
            .list()
            .await
            .iter()
            .any(|account| account.id == "alice"));
    }

    #[tokio::test]
    async fn switching_stashes_an_uncollected_displaced_login_without_collecting_it() {
        let (dir, login, manager) = manager();
        add(&manager, "bob").await;
        // agy 登着一个 CC Switch 还没见过的号
        set_live(&login, &credential("alice", "a1"));
        let original = login.value.lock().unwrap().clone().unwrap();

        manager.switch_to("bob").await.unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));

        // 被顶掉的 alice 没收进账号表,原文整条进了暂存,不会弄丢
        let reopened = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login.clone());
        let ids: Vec<_> = reopened.list().await.into_iter().map(|a| a.id).collect();
        assert_eq!(ids, vec!["bob".to_string()]);
        let stash_path = dir.path().join(STASH_FILENAME);
        assert_eq!(stash::raw_of(&stash_path, "alice"), Some(original.clone()));

        // 之后用户在 agy 里登回 alice 并收录:暂存里那份用不上了,删掉
        *login.value.lock().unwrap() = Some(original);
        reopened.import_current().await.unwrap();
        assert_eq!(stash::raw_of(&stash_path, "alice"), None);
    }

    #[tokio::test]
    async fn stash_keeps_one_entry_per_account_and_reads_the_legacy_format() {
        let (dir, login, manager) = manager();
        let stash_path = dir.path().join(STASH_FILENAME);
        // 旧版的单条格式:读出来当作认不出格式的那一条,不丢
        std::fs::write(
            &stash_path,
            serde_json::to_vec(&json!({"raw": "legacy", "saved_at": 1})).unwrap(),
        )
        .unwrap();
        add(&manager, "bob").await;
        set_live(&login, &credential("alice", "a1"));
        manager.switch_to("bob").await.unwrap();
        set_live(&login, &credential("carol", "c1"));
        manager.switch_to("bob").await.unwrap();

        assert_eq!(
            stash::raw_of(&stash_path, stash::UNRECOGNIZED_KEY).as_deref(),
            Some("legacy")
        );
        assert!(stash::raw_of(&stash_path, "alice").is_some());
        assert!(stash::raw_of(&stash_path, "carol").is_some());
        assert_eq!(manager.list().await.len(), 1);
    }

    #[tokio::test]
    async fn an_unreadable_stash_stops_the_switch_and_is_kept() {
        let (dir, login, manager) = manager();
        let stash_path = dir.path().join(STASH_FILENAME);
        std::fs::write(&stash_path, b"{ not json").unwrap();
        add(&manager, "bob").await;
        set_live(&login, &credential("alice", "a1"));

        let error = manager.switch_to("bob").await.unwrap_err();
        assert!(matches!(
            error,
            AppError::Localized { key, .. } if key == "agy.account.login_stash_unreadable"
        ));
        // 钥匙串没被覆盖,暂存文件原样留着
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert_eq!(*login.writes.lock().unwrap(), 0);
        assert_eq!(std::fs::read(&stash_path).unwrap(), b"{ not json");
    }

    #[tokio::test]
    async fn switching_away_adopts_tokens_agy_refreshed() {
        let (_dir, login, manager) = manager();
        add(&manager, "alice").await;
        add(&manager, "bob").await;
        manager.switch_to("alice").await.unwrap();
        // agy 续期后把新的 access token 写回钥匙串
        set_live(&login, &credential("alice", "renewed"));
        manager.switch_to("bob").await.unwrap();
        let store = manager.store.lock().await;
        assert_eq!(
            store.accounts["alice"].credential["token"]["access_token"],
            "renewed"
        );
    }

    #[tokio::test]
    async fn switching_to_the_current_login_writes_nothing() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        manager.import_current().await.unwrap();
        manager.switch_to("alice").await.unwrap();
        assert_eq!(*login.writes.lock().unwrap(), 0);
    }

    #[test]
    #[serial]
    fn saving_a_binding_recovers_from_a_transient_readback_failure() {
        // 保存会写 config.json 和设备状态,都在进程共用的测试 home 下;用自己的 home。
        let _home = TestHome::new();
        let (_dir, login, manager) = manager();
        let state = AppState::new(Arc::new(Database::memory().unwrap()));
        set_live(&login, &credential("alice", "a1"));
        tauri::async_runtime::block_on(add(&manager, "bob"));
        *login.post_write_read_failures.lock().unwrap() = 1;

        let card = official_card("bob");
        save_from_editor(&state, &manager, card.clone(), None).unwrap();

        let saved = state
            .db
            .get_provider_by_id(&card.id, &AppType::Agy)
            .unwrap()
            .unwrap();
        assert_eq!(
            saved
                .meta
                .unwrap()
                .managed_account_id_for("agy_oauth")
                .as_deref(),
            Some("bob")
        );
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        assert_eq!(*login.writes.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn persistent_readback_failure_reports_that_the_login_is_unverified() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        add(&manager, "bob").await;
        *login.post_write_read_failures.lock().unwrap() = 2;

        let error = manager.switch_to("bob").await.unwrap_err();
        assert!(matches!(
            error,
            AppError::Localized { key, .. } if key == "agy.account.write_verify_failed"
        ));
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        assert_eq!(*login.writes.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn removing_the_live_account_keeps_it_out_and_stashes_it_on_switch() {
        let (dir, login, manager) = manager();
        add(&manager, "bob").await;
        set_live(&login, &credential("alice", "a1"));
        manager.import_current().await.unwrap();
        manager.remove("alice").await.unwrap();
        // 删掉后查看状态不会又收回来,钥匙串也没动
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id, None);
        assert_eq!(status.accounts.len(), 1);
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        // 切走时不复活,登录暂存起来不丢
        manager.switch_to("bob").await.unwrap();
        assert_eq!(manager.list().await.len(), 1);
        assert!(stash::raw_of(&dir.path().join(STASH_FILENAME), "alice").is_some());
    }

    #[tokio::test]
    async fn unrecognized_login_is_stashed_before_overwrite() {
        let (dir, login, manager) = manager();
        add(&manager, "bob").await;
        *login.value.lock().unwrap() = Some("something-else".into());
        manager.switch_to("bob").await.unwrap();
        assert_eq!(
            stash::raw_of(&dir.path().join(STASH_FILENAME), stash::UNRECOGNIZED_KEY).as_deref(),
            Some("something-else")
        );
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
    }

    #[tokio::test]
    async fn accounts_needing_reauth_cannot_be_switched_to() {
        let (_dir, _login, manager) = manager();
        add(&manager, "bob").await;
        manager
            .store
            .lock()
            .await
            .accounts
            .get_mut("bob")
            .unwrap()
            .requires_reauth = true;
        assert!(manager.switch_to("bob").await.is_err());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn account_file_is_private() {
        use std::os::unix::fs::PermissionsExt;
        let (dir, _login, manager) = manager();
        add(&manager, "bob").await;
        let mode = std::fs::metadata(dir.path().join(STORE_FILENAME))
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600);
    }

    #[tokio::test]
    async fn following_cards_query_the_account_agy_is_signed_in_with() {
        let (_dir, login, manager) = manager();
        assert_eq!(manager.current_account_id().await, None, "agy 没登录");

        add(&manager, "alice").await;
        set_live(&login, &credential("bob", "b1"));
        // 还没收录的号不收进来,跟随卡查不到它
        assert_eq!(manager.current_account_id().await, None);
        assert_eq!(manager.list().await.len(), 1);
        // 收录之后就能查到
        manager.import_current().await.unwrap();
        assert_eq!(manager.current_account_id().await.as_deref(), Some("bob"));

        // 在 CC Switch 里删掉的号不再收回来
        manager.remove("bob").await.unwrap();
        assert_eq!(manager.current_account_id().await, None);
        assert_eq!(*login.writes.lock().unwrap(), 0);
    }

    #[tokio::test]
    async fn adding_an_account_waits_for_a_new_login_in_agy() {
        let (dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        // agy 原来登着的号没收录过:只暂存不收录,并暂时清掉钥匙串让终端直接进登录流程
        assert!(manager.list().await.is_empty());
        assert!(stash::raw_of(&dir.path().join(STASH_FILENAME), "alice").is_some());
        assert_eq!(*login.deletes.lock().unwrap(), 1);
        assert!(login.value.lock().unwrap().is_none());
        // 钥匙串为空:继续等
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());

        // 在 agy 里登录了新号:收录,这次登录结束
        set_live(&login, &agy15_credential("bob", "b1"));
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "email:[email protected]");
        assert_eq!(account.email.as_deref(), Some("[email protected]"));
        assert_eq!(manager.list().await.len(), 1);
        assert!(manager.poll_login(&start.flow_id).await.is_err());
        assert_eq!(*login.writes.lock().unwrap(), 0, "加号不写钥匙串");
    }

    #[tokio::test]
    async fn signing_in_again_with_the_same_account_replaces_its_copy() {
        let (_dir, login, manager) = manager();
        add(&manager, "alice").await;
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        let mut again = agy15_credential("alice", "a2");
        again["token"]["refresh_token"] = json!("new-refresh");
        set_live(&login, &again);
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "alice", "按邮箱对回原来的号");
        let store = manager.store.lock().await;
        assert_eq!(store.accounts.len(), 1);
        assert_eq!(
            store.accounts["alice"].credential["token"]["refresh_token"],
            "new-refresh"
        );
    }

    #[tokio::test]
    async fn desktop_login_imports_an_untracked_keychain_login_right_away() {
        let (_dir, login, manager) = manager();
        // 桌面端已经登录(钥匙串里有、CC Switch 还没收录):这次「添加账号」要的就是它,
        // 第一次轮询直接收录,不用重新登录
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login_desktop().await.unwrap();
        assert!(start.already_signed_in);
        // 桌面端模式不动钥匙串:原登录一直有效,不暂存也不写回
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert_eq!(*login.deletes.lock().unwrap(), 0);
        assert_eq!(*login.writes.lock().unwrap(), 0);
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "alice");
        assert_eq!(manager.list().await.len(), 1);
        assert!(manager.poll_login(&start.flow_id).await.is_err());
    }

    #[tokio::test]
    async fn desktop_login_keeps_the_keychain_until_the_new_sign_in() {
        let (_dir, login, manager) = manager();
        // 当前登录已经是收录过的号:桌面端模式只等新的登录(用户要加的是另一个号)
        add(&manager, "alice").await;
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login_desktop().await.unwrap();
        assert!(!start.already_signed_in);
        // 桌面端模式不动钥匙串:原登录一直有效,不暂存也不写回
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert_eq!(*login.deletes.lock().unwrap(), 0);
        assert_eq!(*login.writes.lock().unwrap(), 0);
        // 现有登录已收进账号表,当前登录不变
        assert_eq!(manager.list().await.len(), 1);
        assert_eq!(
            manager
                .status()
                .await
                .unwrap()
                .current_account_id
                .as_deref(),
            Some("alice")
        );
        // 钥匙串没换(refresh token 与开始时相同):继续等
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());

        // 用户在 Antigravity 桌面端登录了新号:收录,这次登录结束
        set_live(&login, &agy15_credential("bob", "b1"));
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "email:[email protected]");
        assert_eq!(manager.list().await.len(), 2);
        assert!(manager.poll_login(&start.flow_id).await.is_err());
    }

    #[tokio::test]
    async fn desktop_login_on_a_fresh_keychain_completes_on_first_sign_in() {
        let (_dir, login, manager) = manager();
        let start = manager.start_login_desktop().await.unwrap();
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());

        // 桌面端首次登录:钥匙串从无到有就收录
        set_live(&login, &credential("bob", "b1"));
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "bob");
        assert_eq!(*login.writes.lock().unwrap(), 0, "加号不写钥匙串");
    }

    #[tokio::test]
    async fn desktop_login_cancel_does_not_touch_the_keychain() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login_desktop().await.unwrap();
        assert!(manager.cancel_login(&start.flow_id).await);
        // 没清过钥匙串,取消也不写回,原登录不受影响
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert_eq!(*login.writes.lock().unwrap(), 0);
        assert!(!manager.has_pending_login().await);
    }

    #[tokio::test]
    async fn desktop_login_reimports_a_dismissed_account_on_explicit_add() {
        let (_dir, login, manager) = manager();
        // 用户删过这个号(授权中心里不显示),桌面端还登着它:点「添加账号」就是要把它收回来
        add(&manager, "alice").await;
        set_live(&login, &credential("alice", "a1"));
        manager.remove("alice").await.unwrap();
        assert_eq!(manager.list().await.len(), 0);

        let start = manager.start_login_desktop().await.unwrap();
        assert!(start.already_signed_in);
        // 钥匙串不动;账号表也先不复活(等第一次轮询收录,dismissed 只防 status 的静默复活)
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert_eq!(manager.list().await.len(), 0);

        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "alice");
        assert_eq!(manager.list().await.len(), 1);
        assert!(manager.poll_login(&start.flow_id).await.is_err());
    }

    #[tokio::test]
    async fn quota_is_remembered_per_account() {
        let dir = tempfile::tempdir().unwrap();
        let login = Arc::new(MemoryLogin::default());
        let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login.clone());
        add(&manager, "alice").await;
        assert!(manager.last_quota("alice").await.is_none());
        let quota = SubscriptionQuota::not_found("agy");
        manager.record_quota("alice", &quota).await;
        manager.record_quota("nobody", &quota).await;
        // 存在账号文件里,重启后还在
        let reopened = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login);
        assert_eq!(
            reopened
                .last_quota("alice")
                .await
                .map(|q| q.tool)
                .as_deref(),
            Some("agy")
        );
        assert_eq!(reopened.list().await.len(), 1);
    }

    /// agy 1.5 自己写回钥匙串的格式:没有 id_token,只有 id_token_email 和 writer_id。
    pub(super) fn agy15_credential(sub: &str, access: &str) -> Value {
        let mut credential = credential(sub, access);
        let object = credential.as_object_mut().unwrap();
        object.remove("id_token");
        object.insert("id_token_email".into(), json!(format!("{sub}@example.com")));
        object.insert("writer_id".into(), json!("w1"));
        credential
    }

    #[tokio::test]
    async fn agy15_login_is_recognized_by_its_refresh_token() {
        let (_dir, login, manager) = manager();
        add(&manager, "alice").await;
        add(&manager, "bob").await;
        let mut live = agy15_credential("alice", "renewed-by-agy15");
        live["token"]["expiry"] = json!(in_an_hour());
        set_live(&login, &live);

        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id.as_deref(), Some("alice"));
        assert_eq!(status.accounts.len(), 2, "不会多出一个认不出的号");
        // agy 续过的令牌照样收回来
        let store = manager.store.lock().await;
        assert_eq!(
            store.accounts["alice"].credential["token"]["access_token"],
            "renewed-by-agy15"
        );
        drop(store);
        assert_eq!(*login.writes.lock().unwrap(), 0);
    }

    #[tokio::test]
    async fn agy15_login_falls_back_to_the_email() {
        let (_dir, login, manager) = manager();
        add(&manager, "alice").await;
        // 在 agy 里重新登录过:refresh token 换了,邮箱没变(大小写不同也认)
        let mut live = agy15_credential("alice", "a2");
        live["token"]["refresh_token"] = json!("another-refresh");
        live["id_token_email"] = json!("[email protected]");
        set_live(&login, &live);
        assert_eq!(manager.current_account_id().await.as_deref(), Some("alice"));
        let store = manager.store.lock().await;
        assert_eq!(
            store.accounts["alice"].credential["token"]["refresh_token"],
            "another-refresh"
        );
    }

    #[tokio::test]
    async fn switching_away_from_an_agy15_login_does_not_stash_it() {
        let (dir, login, manager) = manager();
        add(&manager, "alice").await;
        add(&manager, "bob").await;
        set_live(&login, &agy15_credential("alice", "a2"));
        manager.switch_to("bob").await.unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        assert!(!dir.path().join(STASH_FILENAME).exists());
        // 切回 alice 时写的是 agy 写回的那份(新格式),核对照样通过
        manager.switch_to("alice").await.unwrap();
        let raw = login.value.lock().unwrap().clone().unwrap();
        assert_eq!(
            keychain::decode(&raw).unwrap()["id_token_email"],
            "[email protected]"
        );
    }

    #[tokio::test]
    async fn removing_an_agy15_live_account_keeps_it_out_and_recovers_it_on_switch() {
        let (dir, login, manager) = manager();
        add(&manager, "alice").await;
        add(&manager, "bob").await;
        set_live(&login, &agy15_credential("alice", "a2"));

        manager.remove("alice").await.unwrap();
        assert_eq!(*login.writes.lock().unwrap(), 0, "删账号不动钥匙串");
        // agy 1.5 的钥匙串条目没有 id_token,删掉后依然靠 dismissed_emails 本地识别,
        // 不会发网请求,也不会重新塞回列表
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id, None);
        assert_eq!(status.accounts.len(), 1);
        assert_eq!(manager.current_account_id().await, None);

        // 切走时不复活,按识别出的账号 id 暂存(不当成认不出格式的那条)
        manager.switch_to("bob").await.unwrap();
        assert_eq!(manager.list().await.len(), 1);
        let stash_path = dir.path().join(STASH_FILENAME);
        assert!(stash::raw_of(&stash_path, "alice").is_some());
        assert_eq!(stash::raw_of(&stash_path, stash::UNRECOGNIZED_KEY), None);
    }

    #[tokio::test]
    async fn legacy_dismissed_account_backfills_dismissed_email_once_recognized() {
        let (_dir, login, manager) = manager();
        // 模拟旧版删过的账号:只有 dismissed 里的 sub,没有 dismissed_emails
        {
            let mut store = manager.store.lock().await;
            store.dismissed.push("alice".into());
            manager.persist(&store).unwrap();
        }
        // 第一次经带 id_token 的旧格式认出是谁时,顺手把邮箱补进 dismissed_emails
        set_live(&login, &credential("alice", "a1"));
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id, None);
        assert!(status.accounts.is_empty());
        {
            let store = manager.store.lock().await;
            assert_eq!(
                store.dismissed_emails.get("alice").map(String::as_str),
                Some("[email protected]")
            );
        }
        // 之后 agy 1.5 改写成不带 id_token 的新格式,直接靠补齐的 dismissed_emails 本地识别
        set_live(&login, &agy15_credential("alice", "a2"));
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id, None);
        assert!(status.accounts.is_empty());
    }

    #[tokio::test]
    async fn read_live_treats_agy15_logged_out_metadata_as_none_without_stashing() {
        let (dir, login, manager) = manager();
        for metadata in [
            json!({"writer_id": "w1", "auth_method": "consumer"}),
            json!({"token": null, "writer_id": "w1"}),
            json!({"token": {}, "id_token_email": "[email protected]"}),
        ] {
            set_live(&login, &metadata);
            let status = manager.status().await.unwrap();
            assert_eq!(status.current_account_id, None);
            // 登出残留不算原登录:不暂存、不清钥匙串,取消也不写回
            let start = manager.start_login().await.unwrap();
            assert!(!dir.path().join(STASH_FILENAME).exists());
            assert_eq!(*login.deletes.lock().unwrap(), 0);
            assert!(manager.cancel_login(&start.flow_id).await);
            assert_eq!(*login.writes.lock().unwrap(), 0);
        }

        // token 里带 access_token 但缺 refresh_token 仍视为认不出的格式并暂存
        set_live(&login, &json!({"token": {"access_token": "only-access"}}));
        let start = manager.start_login().await.unwrap();
        assert!(dir.path().join(STASH_FILENAME).exists());
        assert!(manager.cancel_login(&start.flow_id).await);
    }

    #[tokio::test]
    async fn poll_login_ends_on_terminal_exit_and_restores_the_cleared_login() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));

        let start = manager.start_login().await.unwrap();
        let exit_file = start
            .exit_status_file
            .clone()
            .expect("终端模式带退出码文件");
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());
        // agy 异常退出:立刻结束,钥匙串还空着就写回原登录,文件随流程删掉
        std::fs::write(&exit_file, "127\n").unwrap();
        let err = manager.poll_login(&start.flow_id).await.unwrap_err();
        assert!(matches!(
            err,
            AppError::Localized { key, .. } if key == "agy.account.login_command_failed"
        ));
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert!(!exit_file.exists());
        assert!(manager.poll_login(&start.flow_id).await.is_err());

        // 正常退出但没登录:同样立刻结束
        let start = manager.start_login().await.unwrap();
        let exit_file = start.exit_status_file.clone().unwrap();
        std::fs::write(&exit_file, "0\n").unwrap();
        let err = manager.poll_login(&start.flow_id).await.unwrap_err();
        assert!(matches!(
            err,
            AppError::Localized { key, .. } if key == "agy.account.login_not_completed"
        ));
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert!(!exit_file.exists());

        // Windows 终端直接点 X 关闭(管道 EOF 写入 `closed`):同样立刻结束并恢复原登录
        let start = manager.start_login().await.unwrap();
        let exit_file = start.exit_status_file.clone().unwrap();
        std::fs::write(&exit_file, "closed\n").unwrap();
        let err = manager.poll_login(&start.flow_id).await.unwrap_err();
        assert!(matches!(
            err,
            AppError::Localized { key, .. } if key == "agy.account.login_not_completed"
        ));
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert!(!exit_file.exists());

        // 登录完成后才退出:先看钥匙串,照常收录
        let start = manager.start_login().await.unwrap();
        let exit_file = start.exit_status_file.clone().unwrap();
        set_live(&login, &credential("bob", "b1"));
        std::fs::write(&exit_file, "0\n").unwrap();
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "bob");
        assert!(!exit_file.exists());

        // 取消也删文件
        let start = manager.start_login().await.unwrap();
        let exit_file = start.exit_status_file.clone().unwrap();
        std::fs::write(&exit_file, "0\n").unwrap();
        assert!(manager.cancel_login(&start.flow_id).await);
        assert!(!exit_file.exists());
    }

    #[tokio::test]
    async fn reopening_the_terminal_ignores_the_old_terminal_exit() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        let old = start.exit_status_file.clone().unwrap();

        let renewed = manager.renew_login_exit_file().await.unwrap();
        assert_ne!(renewed, old);
        // 旧终端里的 agy 之后退出:只写旧文件,这次登录照常等待
        std::fs::write(&old, "0\n").unwrap();
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());
        let _ = std::fs::remove_file(&old);
        std::fs::write(&renewed, "1\n").unwrap();
        assert!(manager.poll_login(&start.flow_id).await.is_err());
        assert!(!renewed.exists());
    }

    #[tokio::test]
    async fn desktop_login_has_no_exit_status_file() {
        let (_dir, _login, manager) = manager();
        let start = manager.start_login_desktop().await.unwrap();
        assert!(start.exit_status_file.is_none());
        assert!(manager.renew_login_exit_file().await.is_none());
    }

    #[tokio::test]
    async fn switch_to_ends_the_pending_login_and_removes_its_exit_file() {
        let (_dir, login, manager) = manager();
        set_live(&login, &credential("alice", "a1"));
        add(&manager, "bob").await;

        let start = manager.start_login().await.unwrap();
        let exit_file = start.exit_status_file.clone().unwrap();
        std::fs::write(&exit_file, "0\n").unwrap();
        // 等待中切号:钥匙串换成 bob,这次登录作废(否则轮询会把切过去的号当成新登录)
        manager.switch_to("bob").await.unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        assert!(!exit_file.exists());
        let err = manager.poll_login(&start.flow_id).await.unwrap_err();
        assert!(matches!(
            err,
            AppError::Localized { key, .. } if key == "agy.account.login_expired"
        ));
    }

    /// 真机钥匙串冒烟:读写一条测试专用的条目(不是 agy 那条),确认写入(macOS 经 `security -i`,
    /// Windows 经凭据管理器)、原地更新、读回都正常。默认不跑:`cargo test agy_account -- --ignored`。
    #[test]
    #[ignore]
    #[cfg(any(target_os = "macos", windows))]
    fn real_keychain_round_trip_on_a_test_item() {
        let store = keychain::SystemKeychain::named("cc-switch-agy-selftest", "probe");
        let first = keychain::encode(&credential("probe", "one")).unwrap();
        store.write(&first).unwrap();
        assert_eq!(store.read().unwrap().as_deref(), Some(first.as_str()));
        let second = keychain::encode(&credential("probe", "two")).unwrap();
        store.write(&second).unwrap();
        assert_eq!(store.read().unwrap().as_deref(), Some(second.as_str()));
        #[cfg(target_os = "macos")]
        let _ = std::process::Command::new("/usr/bin/security")
            .args([
                "delete-generic-password",
                "-s",
                "cc-switch-agy-selftest",
                "-a",
                "probe",
            ])
            .output();
        #[cfg(windows)]
        let _ = std::process::Command::new("cmdkey")
            .arg("/delete:cc-switch-agy-selftest:probe")
            .output();
    }
}

#[tokio::test]
async fn removing_from_cc_switch_never_touches_the_keychain() {
    let (_dir, login, manager) = manager();
    add(&manager, "bob").await;
    set_live(&login, &credential("bob", "b1"));
    manager.remove("bob").await.unwrap();
    assert!(manager.list().await.is_empty());
    assert_eq!(*login.writes.lock().unwrap(), 0);
    assert_eq!(live_sub(&login).as_deref(), Some("bob"));
}

#[tokio::test]
async fn unknown_login_flow_reports_an_error() {
    let (_dir, _login, manager) = manager();
    assert!(manager.poll_login("nope").await.is_err());
    assert!(!manager.cancel_login("nope").await);
}

fn in_an_hour() -> String {
    (chrono::Local::now() + chrono::Duration::hours(1))
        .to_rfc3339_opts(chrono::SecondsFormat::Micros, false)
}

#[tokio::test]
async fn an_unreadable_account_file_is_kept_instead_of_overwritten() {
    let (dir, login, manager) = manager();
    add(&manager, "alice").await;
    add(&manager, "bob").await;
    let store_path = dir.path().join(STORE_FILENAME);
    let mut unreadable = std::fs::read(&store_path).unwrap();
    unreadable.extend_from_slice(b"\n}");
    std::fs::write(&store_path, &unreadable).unwrap();
    set_live(&login, &credential("carol", "c1"));

    let reopened = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login.clone());
    reopened.status().await.unwrap();

    assert!(
        crate::test_support::dir_holds_file_with(dir.path(), &unreadable),
        "the unreadable account file was overwritten"
    );
}

#[tokio::test]
async fn last_quota_reads_stored_snapshot_without_touching_keychain() {
    use crate::services::subscription::{CredentialStatus, QuotaTier};

    let (_dir, login, manager) = manager();
    add(&manager, "alice").await;
    add(&manager, "bob").await;
    *login.locked.lock().unwrap() = true;

    let saved = SubscriptionQuota {
        tool: "agy".into(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers: vec![QuotaTier {
            name: "agy_gemini_five_hour".into(),
            utilization: 35.0,
            resets_at: Some("2026-10-21T04:16:37Z".into()),
            used_value_usd: None,
            max_value_usd: None,
        }],
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(1_700_000_000_000),
    };
    manager.record_quota("alice", &saved).await;

    let alice = manager.last_quota("alice").await.expect("stored snapshot");
    assert!(alice.success);
    assert_eq!(alice.queried_at, Some(1_700_000_000_000));
    assert_eq!(alice.tiers.len(), 1);
    assert!(manager.last_quota("bob").await.is_none());
    assert!(manager.last_quota("missing").await.is_none());
    assert_eq!(
        *login.reads.lock().unwrap(),
        0,
        "读取本地快照不应触发钥匙串读取"
    );
    assert_eq!(*login.writes.lock().unwrap(), 0);
}

#[tokio::test]
async fn legacy_account_file_ignores_removed_picture_field() {
    let dir = tempfile::tempdir().unwrap();
    let store_path = dir.path().join(STORE_FILENAME);
    let legacy = json!({
        "version": 1,
        "accounts": {
            "alice": {
                "sub": "alice",
                "email": "[email protected]",
                "picture": "https://lh3.googleusercontent.com/a/legacy",
                "credential": credential("alice", "a1"),
                "authenticated_at": 100
            },
            "bob": {
                "sub": "bob",
                "email": "[email protected]",
                "picture": null,
                "credential": credential("bob", "b1"),
                "authenticated_at": 200
            }
        }
    });
    std::fs::write(&store_path, serde_json::to_vec_pretty(&legacy).unwrap()).unwrap();

    let login = Arc::new(MemoryLogin::default());
    let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login);
    let accounts = manager.list().await;
    assert_eq!(accounts.len(), 2);
    assert_eq!(accounts[0].id, "alice");
    assert_eq!(accounts[0].email.as_deref(), Some("[email protected]"));
    assert_eq!(accounts[1].id, "bob");

    // 再次写盘后旧的 picture 键不再保留
    manager
        .record_quota("alice", &SubscriptionQuota::not_found("agy"))
        .await;
    let saved: Value = serde_json::from_slice(&std::fs::read(&store_path).unwrap()).unwrap();
    assert!(saved["accounts"]["alice"].get("picture").is_none());
    assert!(saved["accounts"]["bob"].get("picture").is_none());
}

#[cfg(any(target_os = "macos", windows, target_os = "linux"))]
mod running_guard_and_scope {
    use super::*;

    fn test_env() -> (
        tempfile::TempDir,
        tempfile::TempDir,
        Arc<MemoryLogin>,
        AgyAccountManager,
    ) {
        let dir = tempfile::tempdir().unwrap();
        let desktop_dir = tempfile::tempdir().unwrap();
        let login = Arc::new(MemoryLogin::default());
        let manager = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login.clone(),
            Some(desktop_dir.path().to_path_buf()),
        );
        (dir, desktop_dir, login, manager)
    }

    #[tokio::test]
    async fn switch_succeeds_and_clears_desktop_scope() {
        let (_dir, desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        add(&manager, "bob").await;
        let scope_file = desktop_dir
            .path()
            .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
        std::fs::write(&scope_file, "scope-alice").unwrap();

        manager.switch_to("bob").await.unwrap();
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        assert!(!scope_file.exists());

        // No-op switch to already-active account succeeds cleanly.
        manager.switch_to("bob").await.unwrap();
    }

    #[tokio::test]
    async fn start_login_stashes_an_uncollected_current_login_and_records_pending_flow() {
        let (dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));

        let start = manager.start_login().await.unwrap();
        assert!(!start.flow_id.is_empty());
        assert!(manager.has_pending_login().await);
        // 钥匙串马上要清空:没收录的 alice 只暂存,不收进账号表
        assert!(manager.list().await.is_empty());
        assert!(stash::raw_of(&dir.path().join(STASH_FILENAME), "alice").is_some());
    }

    #[tokio::test]
    async fn start_login_refreshes_a_collected_current_login_without_stashing_it() {
        let (dir, _desktop_dir, login, manager) = test_env();
        add(&manager, "alice").await;
        set_live(&login, &credential("alice", "renewed"));

        manager.start_login().await.unwrap();
        assert!(!dir.path().join(STASH_FILENAME).exists());
        let store = manager.store.lock().await;
        assert_eq!(
            store.accounts["alice"].credential["token"]["access_token"],
            "renewed"
        );
    }

    #[tokio::test]
    async fn switch_clears_desktop_scope_and_syncs_fallback_only_after_verified_write() {
        let dir = tempfile::tempdir().unwrap();
        let desktop_dir = tempfile::tempdir().unwrap();
        let fallback_file = dir.path().join(keychain::STANDALONE_TOKEN_FILENAME);
        let raw_keychain = Arc::new(MemoryLogin::default());
        let login = Arc::new(keychain::AgyLogin::with_keychain(
            fallback_file.clone(),
            raw_keychain.clone(),
        ));
        let manager = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login,
            Some(desktop_dir.path().to_path_buf()),
        );

        let alice_cred = credential("alice", "a1");
        let bob_cred = credential("bob", "fresh");
        set_live(&raw_keychain, &alice_cred);
        std::fs::write(&fallback_file, serde_json::to_vec(&alice_cred).unwrap()).unwrap();
        add(&manager, "bob").await;
        let scope_file = desktop_dir
            .path()
            .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
        std::fs::write(&scope_file, "scope-alice").unwrap();

        // If post-write verification fails, scope file and fallback file stay untouched.
        *raw_keychain.post_write_read_failures.lock().unwrap() = 2;
        assert!(manager.switch_to("bob").await.is_err());
        assert!(scope_file.exists());
        assert_eq!(
            keychain::decode(&std::fs::read_to_string(&fallback_file).unwrap()).unwrap(),
            alice_cred
        );

        // Reset back to alice and perform a clean verified switch to bob -> scope cleared & fallback synced.
        set_live(&raw_keychain, &alice_cred);
        manager.switch_to("bob").await.unwrap();
        assert_eq!(live_sub(&raw_keychain).as_deref(), Some("bob"));
        assert!(!scope_file.exists());
        assert_eq!(
            keychain::decode(&std::fs::read_to_string(&fallback_file).unwrap()).unwrap(),
            bob_cred
        );
    }

    fn fallback_env() -> (
        tempfile::TempDir,
        std::path::PathBuf,
        Arc<MemoryLogin>,
        AgyAccountManager,
    ) {
        let dir = tempfile::tempdir().unwrap();
        let fallback_file = dir.path().join(keychain::STANDALONE_TOKEN_FILENAME);
        let raw_keychain = Arc::new(MemoryLogin::default());
        let login = Arc::new(keychain::AgyLogin::with_keychain(
            fallback_file.clone(),
            raw_keychain.clone(),
        ));
        let manager = AgyAccountManager::with_test_env(dir.path().join("data"), login, None);
        (dir, fallback_file, raw_keychain, manager)
    }

    /// agy 里 `/logout` 后钥匙串空了,回退文件还留着 alice:不能把 alice 当成「已是当前号」
    /// 跳过写钥匙串,否则打开 alice 的终端 agy 仍要求登录。
    #[tokio::test]
    async fn switch_writes_keychain_when_only_a_stale_fallback_file_holds_the_account() {
        let (_dir, fallback_file, raw_keychain, manager) = fallback_env();
        add(&manager, "alice").await;
        std::fs::write(
            &fallback_file,
            serde_json::to_vec(&credential("alice", "old")).unwrap(),
        )
        .unwrap();

        assert_eq!(manager.status().await.unwrap().current_account_id, None);
        manager.switch_to("alice").await.unwrap();
        assert_eq!(live_sub(&raw_keychain).as_deref(), Some("alice"));
        assert_eq!(*raw_keychain.writes.lock().unwrap(), 1);
    }

    /// 钥匙串是 alice、回退文件残留 bob 时添加账号:用户在 agy 里 `/logout` 后,
    /// 不能把文件里的 bob 当成新登录提前收进来。
    #[tokio::test]
    async fn add_account_ignores_a_stale_fallback_file_after_logout() {
        let (_dir, fallback_file, raw_keychain, manager) = fallback_env();
        add(&manager, "bob").await;
        set_live(&raw_keychain, &credential("alice", "a1"));
        std::fs::write(
            &fallback_file,
            serde_json::to_vec(&credential("bob", "old")).unwrap(),
        )
        .unwrap();

        let start = manager.start_login().await.unwrap();
        *raw_keychain.value.lock().unwrap() = None;
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());

        set_live(&raw_keychain, &credential("carol", "c1"));
        let added = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(added.id, "carol");
    }

    #[tokio::test]
    async fn poll_login_same_account_with_same_refresh_token_completes_after_seeing_logged_out() {
        let (_dir, desktop_dir, login, manager) = test_env();
        let scope_file = desktop_dir
            .path()
            .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
        std::fs::write(&scope_file, "scope-alice").unwrap();

        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        assert!(manager.has_pending_login().await);
        assert!(login.value.lock().unwrap().is_none());

        // Keychain is empty while user signs in -> keep polling.
        assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());

        // User signs back into the same Google account returning the same refresh_token -> completes!
        set_live(&login, &credential("alice", "a2"));
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "alice");
        assert!(!scope_file.exists());
        assert!(!manager.has_pending_login().await);
    }

    #[tokio::test]
    async fn start_login_clears_keychain_and_cancel_restores_previous_login() {
        let (_dir, _desktop_dir, login, manager) = test_env();
        let alice = credential("alice", "a1");
        set_live(&login, &alice);

        let start = manager.start_login().await.unwrap();
        assert!(login.value.lock().unwrap().is_none());
        // 读 manager 自己的状态,不读进程级的 last_known_status:同进程里并发的测试会改写它
        assert_eq!(
            manager.status().await.unwrap().current_account_id,
            None,
            "clearing keychain clears active sign-in status while pending"
        );

        assert!(manager.cancel_login(&start.flow_id).await);
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        // 还原的是没收录的号:照样只提示,不收录
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id, None);
        assert_eq!(
            status.uncollected_login.as_deref(),
            Some("[email protected]")
        );
    }

    #[tokio::test]
    async fn cancel_login_does_not_overwrite_a_new_login() {
        let (_dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        assert!(login.value.lock().unwrap().is_none());

        set_live(&login, &credential("bob", "b1"));
        assert!(manager.cancel_login(&start.flow_id).await);
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
    }

    #[tokio::test]
    async fn quitting_mid_login_restores_the_cleared_login() {
        let (_dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        assert!(login.value.lock().unwrap().is_none());

        manager.abandon_pending_logins().await;
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
        assert!(!manager.has_pending_login().await);
        assert!(manager.poll_login(&start.flow_id).await.is_err());
    }

    #[tokio::test]
    async fn quitting_after_signing_in_keeps_the_new_login() {
        let (_dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        manager.start_login().await.unwrap();

        set_live(&login, &credential("bob", "b1"));
        manager.abandon_pending_logins().await;
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
    }

    #[tokio::test]
    async fn restarting_login_preserves_original_restore_credential() {
        let (_dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        let first = manager.start_login().await.unwrap();
        assert!(login.value.lock().unwrap().is_none());

        let second = manager.start_login().await.unwrap();
        assert!(!manager.cancel_login(&first.flow_id).await);
        assert!(manager.cancel_login(&second.flow_id).await);
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
    }

    #[tokio::test]
    async fn expired_login_restores_previous_login_when_keychain_is_empty() {
        let (_dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        assert!(login.value.lock().unwrap().is_none());

        {
            let mut pending = manager.pending.lock().await;
            pending.get_mut(&start.flow_id).unwrap().deadline =
                Instant::now() - Duration::from_secs(1);
        }

        assert!(manager.poll_login(&start.flow_id).await.is_err());
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
    }

    #[tokio::test]
    async fn identify_prefers_exact_sub_match_and_falls_back_to_id_token_email_without_duplicates()
    {
        let (_dir, _desktop_dir, login, manager) = test_env();

        // Existing account stored by email:<address> (e.g. from agy 1.5 without id_token).
        set_live(&login, &switching::agy15_credential("alice", "a1"));
        manager.import_current().await.unwrap();
        let status = manager.status().await.unwrap();
        assert_eq!(
            status.current_account_id.as_deref(),
            Some("email:[email protected]")
        );

        // Re-signing in with a credential that has id_token (sub + email) matches existing email account
        // via id_token.email fallback without creating a duplicate account.
        let mut with_id_token = credential("alice-sub", "a2");
        with_id_token["id_token"] = json!(id_token("alice-sub", "[email protected]"));
        set_live(&login, &with_id_token);
        let status = manager.status().await.unwrap();
        assert_eq!(status.accounts.len(), 1);
        assert_eq!(
            status.current_account_id.as_deref(),
            Some("email:[email protected]")
        );

        // Conversely, when an account is stored under its `sub` key and another account shares email
        // or no email match is needed, exact `sub` match takes priority over `email:` heuristic.
        let mut store = manager.store.lock().await;
        let sub_cred = credential("bob-sub", "b1");
        let bob_claims = identity::identity(sub_cred["id_token"].as_str().unwrap()).unwrap();
        upsert(&mut store, sub_cred, &bob_claims);
        // Simulate an email-keyed entry with the same email inserted earlier.
        let mut dup_email_cred = switching::agy15_credential("bob-sub", "b0");
        dup_email_cred["token"]["refresh_token"] = json!("refresh-bob-old");
        let dup_claims = identity::IdentityClaims {
            sub: Some(identity::email_account_id("[email protected]")),
            email: Some("[email protected]".into()),
            name: None,
        };
        upsert(&mut store, dup_email_cred, &dup_claims);
        drop(store);

        let mut fresh_bob = credential("bob-sub", "b2");
        fresh_bob["token"]["refresh_token"] = json!("refresh-bob-old");
        set_live(&login, &fresh_bob);
        let status = manager.status().await.unwrap();
        assert_eq!(status.current_account_id.as_deref(), Some("bob-sub"));
    }

    #[tokio::test]
    async fn poll_login_reports_scope_cleanup_failure_and_can_retry() {
        let (_dir, desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        let start = manager.start_login().await.unwrap();
        set_live(&login, &credential("bob", "fresh"));
        let scope = desktop_dir
            .path()
            .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
        std::fs::create_dir(&scope).unwrap();

        assert!(matches!(
            manager.poll_login(&start.flow_id).await.unwrap_err(),
            AppError::Localized { key, .. } if key == "agy.account.desktop_scope_cleanup_failed"
        ));
        assert!(manager.has_pending_login().await);
        std::fs::remove_dir(&scope).unwrap();
        std::fs::write(&scope, "scope-alice").unwrap();
        let writes_before = *login.writes.lock().unwrap();
        let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
        assert_eq!(account.id, "bob");
        assert!(!scope.exists());
        assert!(!manager.has_pending_login().await);
        assert_eq!(*login.writes.lock().unwrap(), writes_before);
    }

    #[tokio::test]
    async fn poll_login_reports_fallback_failure_and_can_retry_after_restart() {
        let (dir, desktop_dir, keychain, _manager) = test_env();
        let file = dir.path().join(keychain::STANDALONE_TOKEN_FILENAME);
        set_live(&keychain, &credential("alice", "a1"));
        let login = Arc::new(keychain::AgyLogin::with_keychain(
            file.clone(),
            keychain.clone(),
        ));
        let manager = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login.clone(),
            Some(desktop_dir.path().to_path_buf()),
        );
        let start = manager.start_login().await.unwrap();
        set_live(&keychain, &credential("bob", "fresh"));
        std::fs::create_dir(&file).unwrap();
        assert!(matches!(
            manager.poll_login(&start.flow_id).await.unwrap_err(),
            AppError::Localized { key, .. } if key == "agy.account.fallback_sync_failed"
        ));
        assert!(manager.has_pending_login().await);

        let reopened = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login,
            Some(desktop_dir.path().to_path_buf()),
        );
        std::fs::remove_dir(&file).unwrap();
        std::fs::write(
            &file,
            serde_json::to_vec(&credential("alice", "a1")).unwrap(),
        )
        .unwrap();
        set_live(&keychain, &credential("bob", "refreshed"));
        let writes_before = *keychain.writes.lock().unwrap();
        reopened.switch_to("bob").await.unwrap();
        assert_eq!(*keychain.writes.lock().unwrap(), writes_before);
        assert_eq!(
            keychain::decode(&std::fs::read_to_string(&file).unwrap()).unwrap(),
            credential("bob", "refreshed")
        );
    }

    #[tokio::test]
    async fn failed_scope_cleanup_is_reported_and_retried_after_restart() {
        let (dir, desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        add(&manager, "bob").await;
        let scope = desktop_dir
            .path()
            .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
        // A directory at the file path deterministically makes remove_file fail.
        std::fs::create_dir(&scope).unwrap();

        assert!(manager.switch_to("bob").await.is_err());
        assert_eq!(live_sub(&login).as_deref(), Some("bob"));
        assert!(scope.exists());

        let reopened = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login.clone(),
            Some(desktop_dir.path().to_path_buf()),
        );
        assert!(reopened.switch_to("bob").await.is_err());
        std::fs::remove_dir(&scope).unwrap();
        std::fs::write(&scope, "scope-alice").unwrap();
        // Keep a token refreshed by agy since the partial switch.
        set_live(&login, &credential("bob", "refreshed"));
        let writes_before = *login.writes.lock().unwrap();
        reopened.switch_to("bob").await.unwrap();
        assert!(!scope.exists());
        assert_eq!(*login.writes.lock().unwrap(), writes_before);
        assert_eq!(
            keychain::decode(&login.read().unwrap().unwrap()).unwrap()["token"]["access_token"],
            "refreshed"
        );
    }

    #[tokio::test]
    async fn failed_fallback_sync_is_reported_and_retried_after_restart() {
        let (dir, desktop_dir, keychain, _manager) = test_env();
        let fallback_dir = tempfile::tempdir().unwrap();
        let file = fallback_dir
            .path()
            .join(keychain::STANDALONE_TOKEN_FILENAME);
        std::fs::create_dir(&file).unwrap();
        set_live(&keychain, &credential("alice", "a1"));
        let login = Arc::new(keychain::AgyLogin::with_keychain(
            file.clone(),
            keychain.clone(),
        ));
        let manager = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login.clone(),
            Some(desktop_dir.path().to_path_buf()),
        );
        add(&manager, "bob").await;
        let scope = desktop_dir
            .path()
            .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
        std::fs::write(&scope, "scope-alice").unwrap();

        assert!(manager.switch_to("bob").await.is_err());
        assert_eq!(live_sub(&keychain).as_deref(), Some("bob"));
        assert_eq!(std::fs::read_to_string(&scope).unwrap(), "scope-alice");

        let reopened = AgyAccountManager::with_test_env(
            dir.path().to_path_buf(),
            login,
            Some(desktop_dir.path().to_path_buf()),
        );
        // A partially completed switch must not take the current-account no-op path.
        assert!(reopened.switch_to("bob").await.is_err());
        assert!(file.is_dir());

        std::fs::remove_dir(&file).unwrap();
        std::fs::write(
            &file,
            serde_json::to_vec(&credential("alice", "a1")).unwrap(),
        )
        .unwrap();
        set_live(&keychain, &credential("bob", "refreshed"));
        let writes_before = *keychain.writes.lock().unwrap();
        reopened.switch_to("bob").await.unwrap();
        assert_eq!(
            keychain::decode(&std::fs::read_to_string(&file).unwrap()).unwrap(),
            credential("bob", "refreshed")
        );
        assert!(!scope.exists());
        assert_eq!(*keychain.writes.lock().unwrap(), writes_before);
        // Completed switches are once again no-ops.
        reopened.switch_to("bob").await.unwrap();
    }

    #[test]
    #[serial_test::serial]
    fn saving_new_provider_binding_rolls_back_db_when_switch_fails() {
        use crate::app_config::AppType;
        use crate::database::Database;
        use crate::provider::{AuthBinding, AuthBindingSource, Provider, ProviderMeta};
        use crate::services::provider::agy_direct::save_from_editor;
        use crate::store::AppState;

        // 保存会写 config.json 和设备状态,都在进程共用的测试 home 下;用自己的 home。
        let _home = crate::test_support::TestHome::new();
        let (_dir, _desktop_dir, login, manager) = test_env();
        set_live(&login, &credential("alice", "a1"));
        tauri::async_runtime::block_on(add(&manager, "bob"));
        tauri::async_runtime::block_on(async {
            manager
                .store
                .lock()
                .await
                .accounts
                .get_mut("bob")
                .unwrap()
                .requires_reauth = true;
        });

        let state = AppState::new(Arc::new(Database::memory().unwrap()));
        let mut alice_card =
            Provider::with_id("official".into(), "Antigravity".into(), json!({}), None);
        alice_card.category = Some("official".into());
        alice_card.meta = Some(ProviderMeta {
            auth_binding: Some(AuthBinding {
                source: AuthBindingSource::ManagedAccount,
                auth_provider: Some("agy_oauth".into()),
                account_id: Some("alice".into()),
            }),
            ..Default::default()
        });
        state.db.save_provider(&AppType::Agy, &alice_card).unwrap();

        let mut bob_card = alice_card.clone();
        bob_card
            .meta
            .as_mut()
            .unwrap()
            .auth_binding
            .as_mut()
            .unwrap()
            .account_id = Some("bob".into());
        assert!(save_from_editor(&state, &manager, bob_card, None).is_err());

        // DB row must remain bound to alice and keychain must stay on alice.
        let persisted = state
            .db
            .get_provider_by_id("official", &AppType::Agy)
            .unwrap()
            .unwrap();
        assert_eq!(
            persisted
                .meta
                .as_ref()
                .and_then(|m| m.managed_account_id_for("agy_oauth"))
                .as_deref(),
            Some("alice")
        );
        assert_eq!(live_sub(&login).as_deref(), Some("alice"));
    }
}

mod acp {
    use crate::services::agy_account::acp_login::{
        is_windows_native_exe, parse_authorization_url, validate_login_response,
    };

    const VALID_URL: &str = "https://accounts.google.com/o/oauth2/auth?client_id=cid&response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=state-abc-123";

    #[test]
    fn windows_native_exe_check_only_matches_exe() {
        use std::path::Path;
        assert!(is_windows_native_exe(Path::new("agy.exe")));
        assert!(is_windows_native_exe(Path::new(
            r"C:\Users\me\.local\bin\AGY.EXE"
        )));
        assert!(!is_windows_native_exe(Path::new("agy.cmd")));
        assert!(!is_windows_native_exe(Path::new("agy.CMD")));
        assert!(!is_windows_native_exe(Path::new("agy.bat")));
        assert!(!is_windows_native_exe(Path::new("agy")));
    }

    #[cfg(windows)]
    #[test]
    fn windows_browser_suppression_clears_path_only_for_native_exe() {
        use crate::services::agy_account::acp_login::apply_browser_suppression;
        use std::ffi::OsStr;
        use std::path::Path;

        let mut exe_cmd = tokio::process::Command::new(r"C:\agy\agy.exe");
        apply_browser_suppression(
            &mut exe_cmd,
            Path::new(r"C:\agy\agy.exe"),
            Path::new(r"C:\data"),
        );
        let exe_envs: Vec<(&OsStr, Option<&OsStr>)> = exe_cmd.as_std().get_envs().collect();
        assert!(exe_envs.contains(&(
            OsStr::new("NoDefaultCurrentDirectoryInExePath"),
            Some(OsStr::new("1"))
        )));
        assert!(exe_envs.contains(&(OsStr::new("PATH"), Some(OsStr::new("")))));

        let mut cmd_wrapper = tokio::process::Command::new(r"C:\agy\agy.cmd");
        apply_browser_suppression(
            &mut cmd_wrapper,
            Path::new(r"C:\agy\agy.cmd"),
            Path::new(r"C:\data"),
        );
        let cmd_envs: Vec<(&OsStr, Option<&OsStr>)> = cmd_wrapper.as_std().get_envs().collect();
        assert!(cmd_envs.contains(&(
            OsStr::new("NoDefaultCurrentDirectoryInExePath"),
            Some(OsStr::new("1"))
        )));
        assert!(!cmd_envs
            .iter()
            .any(|(k, _)| k.to_str().is_some_and(|s| s.eq_ignore_ascii_case("PATH"))));
    }

    #[test]
    fn url_parser_validates_google_oauth_params() {
        let parsed = parse_authorization_url(&format!("  {VALID_URL}\r\n")).expect("valid url");
        assert_eq!(parsed.authorization_url, VALID_URL);
        assert_eq!(
            parsed.redirect_uri,
            "https://antigravity.google/oauth-callback"
        );
        assert_eq!(parsed.state, "state-abc-123");

        // 非 Google 域名 / 错误路径 / 端口 / 凭据 / fragment / 空白
        assert!(parse_authorization_url("http://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=s").is_none());
        assert!(parse_authorization_url("https://evil.example/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=s").is_none());
        assert!(parse_authorization_url("https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=s").is_none());
        assert!(parse_authorization_url("https://accounts.google.com:8443/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=s").is_none());
        assert!(parse_authorization_url("https://[email protected]/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=s").is_none());
        assert!(parse_authorization_url(&format!("{VALID_URL}#frag")).is_none());
        assert!(parse_authorization_url(&format!("prefix {VALID_URL}")).is_none());

        // response_type / redirect_uri / state 约束
        assert!(parse_authorization_url("https://accounts.google.com/o/oauth2/auth?response_type=token&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=s").is_none());
        assert!(parse_authorization_url(&format!("{VALID_URL}&response_type=code")).is_none());
        assert!(parse_authorization_url("https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2F&state=s").is_none());
        assert!(parse_authorization_url(&format!(
            "{VALID_URL}&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback"
        ))
        .is_none());
        assert!(parse_authorization_url("https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=").is_none());
        assert!(parse_authorization_url("https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=a%20b").is_none());
        assert!(parse_authorization_url(&format!("{VALID_URL}&state=dup")).is_none());

        let too_long_state = "a".repeat(513);
        assert!(parse_authorization_url(&format!(
            "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state={too_long_state}"
        ))
        .is_none());
    }

    #[test]
    fn login_response_validator_accepts_code_or_matching_callback_url() {
        let pending = parse_authorization_url(VALID_URL).unwrap();

        // 干净代码
        assert_eq!(
            validate_login_response(&pending, "  4/0AeanS0_abc.def~-  ").as_deref(),
            Some("4/0AeanS0_abc.def~-")
        );
        assert!(validate_login_response(&pending, "").is_none());
        assert!(validate_login_response(&pending, "has space").is_none());
        assert!(validate_login_response(&pending, "has\nnewline").is_none());
        assert!(validate_login_response(&pending, "abc#def").is_none());
        assert!(validate_login_response(&pending, &"x".repeat(2049)).is_none());

        // 完整回调 URL
        let callback =
            "https://antigravity.google/oauth-callback?state=state-abc-123&code=4/0AeanS0&scope=email";
        assert_eq!(
            validate_login_response(&pending, &format!("  {callback}  ")).as_deref(),
            Some(callback)
        );
        assert!(validate_login_response(
            &pending,
            "https://antigravity.google/oauth-callback?state=wrong&code=4/0AeanS0"
        )
        .is_none());
        assert!(validate_login_response(
            &pending,
            "https://antigravity.google/oauth-callback?state=state-abc-123&code="
        )
        .is_none());
        assert!(validate_login_response(
            &pending,
            "https://antigravity.google/oauth-callback?state=state-abc-123"
        )
        .is_none());
        assert!(validate_login_response(
            &pending,
            "https://antigravity.google/other?state=state-abc-123&code=abc"
        )
        .is_none());
        assert!(validate_login_response(
            &pending,
            "https://evil.example/oauth-callback?state=state-abc-123&code=abc"
        )
        .is_none());
        assert!(validate_login_response(
            &pending,
            "https://antigravity.google/oauth-callback?state=state-abc-123&state=state-abc-123&code=abc"
        )
        .is_none());
    }

    #[cfg(windows)]
    #[test]
    fn windows_wrap_acp_command_preserves_create_no_window_with_job_object() {
        use crate::services::agy_account::acp_login::wrap_acp_command;

        let cmd = tokio::process::Command::new(r"C:\agy\agy.exe");
        let wrapped = wrap_acp_command(cmd);
        let flags = wrapped
            .get_wrap::<process_wrap::tokio::CreationFlags>()
            .expect("CreationFlags wrapper must be present");
        assert_eq!(flags.0 .0, 0x0800_0000);
        assert!(wrapped.has_wrap::<process_wrap::tokio::JobObject>());
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn windows_supports_acp_login_caches_probe_result_by_file_metadata() {
        use crate::services::agy_account::acp_login::supports_acp_login;

        let dir = tempfile::tempdir().unwrap();
        let probe_cmd = dir.path().join("agy-probe.cmd");
        let count_file = dir.path().join("calls.txt");
        let body = format!(
            "@echo off\r\necho call>>\"{}\"\r\necho   --login  Log in\r\nexit /b 0\r\n",
            count_file.display()
        );
        std::fs::write(&probe_cmd, body).unwrap();

        assert!(supports_acp_login(&probe_cmd).await);
        assert!(supports_acp_login(&probe_cmd).await);
        let calls = std::fs::read_to_string(&count_file).unwrap();
        assert_eq!(calls.lines().count(), 1, "second probe should hit cache");
    }

    #[tokio::test]
    async fn acp_login_stashes_uncollected_login_without_importing_and_clears_stash_on_finalize() {
        use super::*;

        let (dir, login, manager) = manager();
        set_live(&login, &credential("alice", "r-alice"));

        {
            let mut store = manager.store.lock().await;
            let (raw, live) = manager.read_live_with_raw(&store, true).await.unwrap();
            manager
                .stash_live_before_acp_login(&mut store, raw, live)
                .unwrap();
            assert!(
                !store.accounts.contains_key("alice"),
                "start_login_acp must not auto-import an uncollected login"
            );
        }
        let stash_path = dir.path().join(STASH_FILENAME);
        assert!(
            stash::raw_of(&stash_path, "alice").is_some(),
            "uncollected login must be stashed before ACP overwrites the keychain"
        );

        {
            let mut store = manager.store.lock().await;
            let live = manager.read_live(&store, true).await.unwrap();
            let account = manager
                .finalize_live_login(&mut store, live)
                .await
                .unwrap()
                .expect("finalized account");
            assert_eq!(account.id, "alice");
            assert!(store.accounts.contains_key("alice"));
        }
        assert!(
            stash::raw_of(&stash_path, "alice").is_none(),
            "collecting the account must remove its stash entry"
        );
    }

    #[cfg(unix)]
    mod unix_mock {
        use super::super::*;
        use super::VALID_URL;
        use crate::services::agy_account::acp_login::{
            supports_acp_login, unix_browser_shim, RunningAcpLogin,
        };
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        use std::path::Path;

        fn write_script(dir: &Path, name: &str, body: &str) -> PathBuf {
            let path = dir.join(name);
            std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        }

        fn mock_agy_named(
            dir: &Path,
            name: &str,
            acp_login_body: &str,
            has_login_flag: bool,
        ) -> PathBuf {
            let help_line = if has_login_flag {
                "echo '  --login  Print OAuth URL'"
            } else {
                "echo '  --port   Listen port'"
            };
            write_script(
                dir,
                name,
                &format!(
                    r#"
if [ "$1" = "acp" ] && [ "$2" = "--help" ]; then
  {help_line}
  exit 0
fi
if [ "$1" = "acp" ] && [ "$2" = "--login" ]; then
  {acp_login_body}
fi
exit 2
"#
                ),
            )
        }

        fn mock_agy(dir: &Path, acp_login_body: &str, has_login_flag: bool) -> PathBuf {
            mock_agy_named(dir, "mock-agy", acp_login_body, has_login_flag)
        }

        async fn wait_poll(
            manager: &AgyAccountManager,
            flow_id: &str,
        ) -> Result<Option<AgyAccount>, AppError> {
            let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
            loop {
                match manager.poll_login(flow_id).await {
                    Ok(None) if tokio::time::Instant::now() < deadline => {
                        tokio::time::sleep(Duration::from_millis(25)).await;
                    }
                    other => return other,
                }
            }
        }

        async fn wait_pid(pid_file: &Path) -> i32 {
            for _ in 0..40 {
                if pid_file.exists() {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
            std::fs::read_to_string(pid_file)
                .unwrap()
                .trim()
                .parse()
                .unwrap()
        }

        async fn assert_process_exited(pid: i32, context: &str) {
            let mut still_alive = true;
            for _ in 0..40 {
                if unsafe { libc::kill(pid, 0) } != 0 {
                    still_alive = false;
                    break;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
            if still_alive {
                unsafe { libc::kill(pid, libc::SIGKILL) };
            }
            assert!(!still_alive, "{context}: descendant {pid} still alive");
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn detects_acp_login_capability_from_help() {
            let dir = tempfile::tempdir().unwrap();
            let supported = mock_agy_named(dir.path(), "agy-supported", "exit 0", true);
            let unsupported = mock_agy_named(dir.path(), "agy-unsupported", "exit 0", false);
            let stderr_help = write_script(
                dir.path(),
                "stderr-agy",
                "echo 'Usage: agy acp --login' >&2\nexit 0",
            );
            let failing = write_script(dir.path(), "failing-agy", "echo '--login'\nexit 1");

            assert!(supports_acp_login(&supported).await);
            assert!(supports_acp_login(&stderr_help).await);
            assert!(!supports_acp_login(&unsupported).await);
            assert!(!supports_acp_login(&failing).await);
            assert!(!supports_acp_login(&dir.path().join("missing-agy")).await);
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn happy_path_submit_paste_writes_stdin_absorbs_account_and_syncs_desktop() {
            let dir = tempfile::tempdir().unwrap();
            let desktop_dir = tempfile::tempdir().unwrap();
            let fallback_dir = tempfile::tempdir().unwrap();
            let fallback_file = fallback_dir
                .path()
                .join(keychain::STANDALONE_TOKEN_FILENAME);
            std::fs::write(
                &fallback_file,
                serde_json::to_vec(&credential("alice", "a1")).unwrap(),
            )
            .unwrap();
            let scope_file = desktop_dir
                .path()
                .join(keychain::DESKTOP_CREDENTIAL_SCOPE_FILENAME);
            std::fs::write(&scope_file, "scope-alice").unwrap();

            let paste_out = dir.path().join("pasted.txt");
            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
printf '%s\n' '{VALID_URL}'
IFS= read -r line
printf '%s' "$line" > '{}'
exit 0
"#,
                    paste_out.display()
                ),
                true,
            );
            let mem_keychain = Arc::new(MemoryLogin::default());
            let login = Arc::new(keychain::AgyLogin::with_keychain(
                fallback_file.clone(),
                mem_keychain.clone(),
            ));
            let manager = AgyAccountManager::with_test_env(
                dir.path().to_path_buf(),
                login,
                Some(desktop_dir.path().to_path_buf()),
            );
            // 先收录并删除一个旧号,验证 start_login_acp 不会把刚删掉的号重新拉回来,也不清空钥匙串
            set_live(&mem_keychain, &credential("alice", "a1"));
            manager.import_current().await.unwrap();
            manager.remove("alice").await.unwrap();
            assert!(manager.list().await.is_empty());

            let start = manager.start_login_acp(&bin).await.unwrap();
            assert_eq!(start.auth_url.as_deref(), Some(VALID_URL));
            assert!(start.exit_status_file.is_none());
            assert!(!start.already_signed_in);
            assert!(manager.list().await.is_empty());
            assert!(manager.renew_login_exit_file().await.is_none());

            // 仍在等待退出时 poll 返回 Ok(None)
            assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());

            // 非法输入被拒绝,不关闭流程
            assert!(manager
                .submit_paste(&start.flow_id, "invalid paste with space")
                .await
                .is_err());

            // 模拟 agy 完成授权写入钥匙串并收到回调地址后 exit 0
            let callback =
                "https://antigravity.google/oauth-callback?state=state-abc-123&code=code-ok";
            let bob_cred = super::super::switching::agy15_credential("bob", "b1");
            set_live(&mem_keychain, &bob_cred);
            manager
                .submit_paste(&start.flow_id, callback)
                .await
                .unwrap();

            let account = wait_poll(&manager, &start.flow_id)
                .await
                .unwrap()
                .expect("account added");
            assert_eq!(account.email.as_deref(), Some("[email protected]"));
            assert_eq!(std::fs::read_to_string(&paste_out).unwrap(), callback);
            assert_eq!(
                keychain::decode(&std::fs::read_to_string(&fallback_file).unwrap()).unwrap(),
                bob_cred
            );
            assert!(!scope_file.exists());
            assert!(manager.poll_login(&start.flow_id).await.is_err());
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn exit_zero_without_known_keychain_login_returns_localized_error() {
            let dir = tempfile::tempdir().unwrap();
            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
printf '%s\n' '{VALID_URL}'
IFS= read -r _line
exit 0
"#
                ),
                true,
            );
            let login = Arc::new(MemoryLogin::default());
            let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login);

            let start = manager.start_login_acp(&bin).await.unwrap();
            manager
                .submit_paste(&start.flow_id, "clean-auth-code")
                .await
                .unwrap();
            let err = wait_poll(&manager, &start.flow_id).await.unwrap_err();
            assert!(matches!(
                err,
                AppError::Localized { key, .. } if key == "agy.account.acp_keyring_missing"
            ));
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn nonzero_exit_fails_without_leaking_raw_output() {
            let dir = tempfile::tempdir().unwrap();
            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
printf '%s\n' '{VALID_URL}'
echo 'SECRET_STDOUT_TOKEN'
echo 'SECRET_STDERR_TOKEN' >&2
exit 1
"#
                ),
                true,
            );
            let login = Arc::new(MemoryLogin::default());
            let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login);

            let start = manager.start_login_acp(&bin).await.unwrap();
            let err = wait_poll(&manager, &start.flow_id).await.unwrap_err();
            let msg = err.to_string();
            assert!(!msg.contains("SECRET_STDOUT_TOKEN"));
            assert!(!msg.contains("SECRET_STDERR_TOKEN"));
            assert!(manager.poll_login(&start.flow_id).await.is_err());
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn early_exit_before_url_fails_fast_without_leaking_output() {
            let dir = tempfile::tempdir().unwrap();
            let bin = mock_agy(
                dir.path(),
                "echo 'SECRET_EARLY_OUT'\necho 'SECRET_EARLY_ERR' >&2\nexit 1",
                true,
            );
            let login = Arc::new(MemoryLogin::default());
            let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login);

            let err = match manager.start_login_acp(&bin).await {
                Ok(_) => panic!("expected early exit to fail"),
                Err(err) => err,
            };
            assert!(matches!(
                err,
                AppError::Localized { key, .. } if key == "agy.account.acp_no_auth_url"
            ));
            let msg = err.to_string();
            assert!(!msg.contains("SECRET_EARLY_OUT"));
            assert!(!msg.contains("SECRET_EARLY_ERR"));
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn cancel_switch_to_and_abandon_kill_child_process_tree() {
            let dir = tempfile::tempdir().unwrap();
            let pid_file = dir.path().join("child.pid");
            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
printf '%s\n' '{VALID_URL}'
sleep 30 &
echo $! > '{}'
wait
"#,
                    pid_file.display()
                ),
                true,
            );

            // 直接验证 RunningAcpLogin::cancel 杀掉占着管道的后代进程并结束 done
            let mut running = RunningAcpLogin::start(&bin, dir.path(), Duration::from_secs(60))
                .await
                .unwrap();
            let bg_pid = wait_pid(&pid_file).await;
            running.cancel();
            let exit = tokio::time::timeout(Duration::from_secs(5), &mut running.done)
                .await
                .expect("cancel finishes promptly")
                .unwrap();
            assert!(!exit.success);
            assert_process_exited(bg_pid, "RunningAcpLogin::cancel").await;

            // 验证 manager.cancel_login、manager.switch_to、manager.abandon_pending_logins 均清理 pending 并杀子进程
            let login = Arc::new(MemoryLogin::default());
            let manager =
                AgyAccountManager::with_login_store(dir.path().to_path_buf(), login.clone());
            add(&manager, "alice").await;
            set_live(&login, &credential("bob", "b1"));

            let _ = std::fs::remove_file(&pid_file);
            let start1 = manager.start_login_acp(&bin).await.unwrap();
            let bg_pid1 = wait_pid(&pid_file).await;
            assert!(manager.cancel_login(&start1.flow_id).await);
            assert!(!manager.cancel_login(&start1.flow_id).await);
            assert!(manager.poll_login(&start1.flow_id).await.is_err());
            assert_process_exited(bg_pid1, "cancel_login").await;

            let _ = std::fs::remove_file(&pid_file);
            let start2 = manager.start_login_acp(&bin).await.unwrap();
            let bg_pid2 = wait_pid(&pid_file).await;
            manager.switch_to("alice").await.unwrap();
            assert!(manager.poll_login(&start2.flow_id).await.is_err());
            assert_process_exited(bg_pid2, "switch_to").await;

            let _ = std::fs::remove_file(&pid_file);
            let start3 = manager.start_login_acp(&bin).await.unwrap();
            let bg_pid3 = wait_pid(&pid_file).await;
            manager.abandon_pending_logins().await;
            assert!(manager.poll_login(&start3.flow_id).await.is_err());
            assert_process_exited(bg_pid3, "abandon_pending_logins").await;
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn running_acp_submit_paste_accepts_clean_code() {
            let dir = tempfile::tempdir().unwrap();
            let paste_out = dir.path().join("code.txt");
            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
printf '%s\n' '{VALID_URL}'
IFS= read -r line
printf '%s' "$line" > '{}'
exit 0
"#,
                    paste_out.display()
                ),
                true,
            );
            let mut running = RunningAcpLogin::start(&bin, dir.path(), Duration::from_secs(30))
                .await
                .unwrap();
            running
                .paste_target()
                .submit("4/0AeanS0_clean-code")
                .await
                .unwrap();
            let exit = tokio::time::timeout(Duration::from_secs(5), &mut running.done)
                .await
                .unwrap()
                .unwrap();
            assert!(exit.success);
            assert_eq!(
                std::fs::read_to_string(&paste_out).unwrap(),
                "4/0AeanS0_clean-code"
            );
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn closed_or_invalid_stdout_before_url_terminates_the_process() {
            for output in ["exec 1>&-", "printf '\\377\\n'"] {
                let dir = tempfile::tempdir().unwrap();
                let pid_file = dir.path().join("parent.pid");
                let bin = write_script(
                    dir.path(),
                    "agy-closed-output",
                    &format!(
                        "echo $$ > '{}'\n{output}\nexec sleep 30",
                        pid_file.display()
                    ),
                );
                let result = tokio::time::timeout(
                    Duration::from_secs(2),
                    RunningAcpLogin::start(&bin, dir.path(), Duration::from_secs(60)),
                )
                .await
                .expect("stdout failure must not wait for the still-running parent");
                assert!(matches!(
                    result,
                    Err(AppError::Localized { key, .. }) if key == "agy.account.acp_no_auth_url"
                ));
                assert_process_exited(wait_pid(&pid_file).await, "startup output failure").await;
            }
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn parent_exit_cleans_descendants_and_preserves_exit_status() {
            for code in [0, 1] {
                let dir = tempfile::tempdir().unwrap();
                let pid_file = dir.path().join("child.pid");
                let bin = mock_agy(
                    dir.path(),
                    &format!(
                        "sleep 30 &\necho $! > '{}'\nprintf '%s\\n' '{VALID_URL}'\nexit {code}",
                        pid_file.display()
                    ),
                    true,
                );
                let mut running = RunningAcpLogin::start(&bin, dir.path(), Duration::from_secs(60))
                    .await
                    .unwrap();
                let exit = tokio::time::timeout(Duration::from_secs(2), &mut running.done)
                    .await
                    .expect("parent exit must complete even when descendants keep pipes open")
                    .unwrap();
                assert_eq!(exit.success, code == 0);
                assert_process_exited(wait_pid(&pid_file).await, "parent exit").await;
            }
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn help_probe_cleans_descendants_holding_output_pipes() {
            let dir = tempfile::tempdir().unwrap();
            let pid_file = dir.path().join("child.pid");
            let bin = write_script(
                dir.path(),
                "agy-help-child",
                &format!(
                    "sleep 30 &\necho $! > '{}'\necho '  --login  Log in'\nexit 0",
                    pid_file.display()
                ),
            );
            assert!(
                tokio::time::timeout(Duration::from_secs(2), supports_acp_login(&bin))
                    .await
                    .expect("an exited help command must not wait for inherited pipes")
            );
            assert_process_exited(wait_pid(&pid_file).await, "help probe").await;
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn cancel_and_wait_finishes_cleanup_and_can_be_repeated() {
            let dir = tempfile::tempdir().unwrap();
            let pid_file = dir.path().join("parent.pid");
            let bin = mock_agy(
                dir.path(),
                &format!(
                    "echo $$ > '{}'\nprintf '%s\\n' '{VALID_URL}'\nexec sleep 30",
                    pid_file.display()
                ),
                true,
            );
            let mut running = RunningAcpLogin::start(&bin, dir.path(), Duration::from_secs(60))
                .await
                .unwrap();
            let target = running.paste_target();
            running.cancel_and_wait().await;
            assert!(
                !running
                    .done
                    .try_recv()
                    .expect("cleanup already finished")
                    .success
            );
            assert_process_exited(wait_pid(&pid_file).await, "awaited cancellation").await;
            assert!(target.submit("code-after-cancel").await.is_err());
            tokio::time::timeout(Duration::from_secs(2), running.cancel_and_wait())
                .await
                .expect("cancellation stays awaitable after the result was consumed");
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn switch_stops_acp_before_it_can_overwrite_the_target_login() {
            struct FileLogin {
                live: PathBuf,
                gate: PathBuf,
                completed: PathBuf,
                pid_file: PathBuf,
            }

            impl AgyLoginStore for FileLogin {
                fn read(&self) -> Result<Option<String>, AppError> {
                    std::fs::read_to_string(&self.live)
                        .map(Some)
                        .map_err(|e| AppError::io(&self.live, e))
                }

                fn write(&self, value: &str) -> Result<(), AppError> {
                    std::fs::write(&self.live, value).map_err(|e| AppError::io(&self.live, e))
                }

                fn delete(&self) -> Result<(), AppError> {
                    unreachable!("ACP does not clear the keychain")
                }

                fn sync_fallback(&self, _: &Value) -> Result<(), AppError> {
                    // 模拟官方登录在切号核验之后、回退凭据同步期间写入新账号。
                    // 只有切号前已等 ACP 退出,才能保证目标账号不被覆盖。
                    std::fs::write(&self.gate, "ready").unwrap();
                    let pid: i32 = std::fs::read_to_string(&self.pid_file)
                        .unwrap()
                        .trim()
                        .parse()
                        .unwrap();
                    let deadline = Instant::now() + Duration::from_secs(2);
                    while !self.completed.exists()
                        && unsafe { libc::kill(pid, 0) } == 0
                        && Instant::now() < deadline
                    {
                        std::thread::sleep(Duration::from_millis(5));
                    }
                    Ok(())
                }
            }

            let dir = tempfile::tempdir().unwrap();
            let login = Arc::new(FileLogin {
                live: dir.path().join("keychain.json"),
                gate: dir.path().join("switch-verified"),
                completed: dir.path().join("oauth-finished"),
                pid_file: dir.path().join("parent.pid"),
            });
            login
                .write(&keychain::encode(&credential("bob", "old-bob")).unwrap())
                .unwrap();
            let manager =
                AgyAccountManager::with_login_store(dir.path().to_path_buf(), login.clone());
            add(&manager, "alice").await;
            let replacement = dir.path().join("new-login.json");
            std::fs::write(
                &replacement,
                keychain::encode(&credential("charlie", "new-charlie")).unwrap(),
            )
            .unwrap();
            let bin = mock_agy(
                dir.path(),
                &format!(
                    "echo $$ > '{}'\nprintf '%s\\n' '{VALID_URL}'\nIFS= read -r code\nwhile [ ! -f '{}' ]; do sleep 0.01; done\ncp '{}' '{}'\nprintf done > '{}'\nexit 0",
                    login.pid_file.display(), login.gate.display(), replacement.display(), login.live.display(), login.completed.display()
                ),
                true,
            );
            let flow = manager.start_login_acp(&bin).await.unwrap();
            manager
                .submit_paste(&flow.flow_id, "fake-code")
                .await
                .unwrap();
            manager.switch_to("alice").await.unwrap();
            assert_eq!(manager.current_account_id().await.as_deref(), Some("alice"));
            assert!(
                !login.completed.exists(),
                "the old login must not overwrite the selected account"
            );
            assert!(manager.poll_login(&flow.flow_id).await.is_err());
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn switch_during_acp_startup_waits_and_cancels_the_registered_flow() {
            let (dir, login, manager) = manager();
            let manager = Arc::new(manager);
            set_live(&login, &credential("bob", "b1"));
            add(&manager, "alice").await;
            let pid_file = dir.path().join("parent.pid");
            let release = dir.path().join("release-url");
            let bin = mock_agy(
                dir.path(),
                &format!(
                    "echo $$ > '{}'\nwhile [ ! -f '{}' ]; do sleep 0.01; done\nprintf '%s\\n' '{VALID_URL}'\nexec sleep 30",
                    pid_file.display(), release.display()
                ),
                true,
            );
            let starter = Arc::clone(&manager);
            let starting = tokio::spawn(async move { starter.start_login_acp(&bin).await });
            let pid = wait_pid(&pid_file).await;
            let mut switching = Box::pin(manager.switch_to("alice"));
            tokio::select! {
                result = &mut switching => panic!("switch overtook ACP startup: {result:?}"),
                _ = tokio::time::sleep(Duration::from_millis(25)) => {}
            }
            std::fs::write(release, "ready").unwrap();
            let flow = starting.await.unwrap().unwrap();
            switching.await.unwrap();
            assert_eq!(live_sub(&login).as_deref(), Some("alice"));
            assert!(!manager.has_pending_login().await);
            assert!(manager.poll_login(&flow.flow_id).await.is_err());
            assert_process_exited(pid, "switch during startup").await;
        }

        const OPENER_BIN: &str = if cfg!(target_os = "macos") {
            "open"
        } else {
            "xdg-open"
        };

        #[tokio::test]
        #[serial_test::serial]
        async fn suppresses_browser_opener_via_private_shim_while_keeping_other_path_bins() {
            let dir = tempfile::tempdir().unwrap();
            let data_dir = dir.path().join("app-data");
            let fake_bin = dir.path().join("fake-bin");
            std::fs::create_dir_all(&fake_bin).unwrap();

            let spy_marker = dir.path().join("spy-opened.txt");
            let opener_rc = dir.path().join("opener-rc.txt");
            let other_out = dir.path().join("other-out.txt");
            let env_out = dir.path().join("env-out.txt");

            write_script(
                &fake_bin,
                OPENER_BIN,
                &format!(
                    "printf 'OPENED:%s' \"$1\" > '{}'\nexit 0",
                    spy_marker.display()
                ),
            );
            write_script(&fake_bin, "cc-switch-other-tool", "printf 'OTHER_TOOL_OK'");

            let mut path_entries = vec![fake_bin.clone()];
            if let Some(existing) = std::env::var_os("PATH") {
                path_entries.extend(std::env::split_paths(&existing));
            }
            let _env = crate::test_support::EnvVars::new()
                .set("PATH", std::env::join_paths(path_entries).unwrap())
                .set("SSH_CONNECTION", "1.2.3.4 12345 5.6.7.8 22")
                .set("SSH_CLIENT", "1.2.3.4 12345 22")
                .set("SSH_TTY", "/dev/pts/0")
                .set("AGY_CLI_FORCE_FILE_TOKEN_STORAGE", "1")
                .set("GEMINI_API_KEY", "should-be-removed")
                .set("GOOGLE_GEMINI_BASE_URL", "https://should-be-removed.test");

            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
{OPENER_BIN} '{VALID_URL}'
printf '%s' "$?" > '{}'
cc-switch-other-tool > '{}'
printf '%s|%s|%s|%s|%s|%s' \
  "${{SSH_CONNECTION:-}}" \
  "${{SSH_CLIENT:-}}" \
  "${{SSH_TTY:-}}" \
  "${{AGY_CLI_FORCE_FILE_TOKEN_STORAGE:-}}" \
  "${{GEMINI_API_KEY:-}}" \
  "${{GOOGLE_GEMINI_BASE_URL:-}}" > '{}'
printf '%s\n' '{VALID_URL}'
IFS= read -r _line
exit 0
"#,
                    opener_rc.display(),
                    other_out.display(),
                    env_out.display(),
                ),
                true,
            );

            let mut running = RunningAcpLogin::start(&bin, &data_dir, Duration::from_secs(30))
                .await
                .unwrap();
            running
                .paste_target()
                .submit("4/0AeanS0_clean-code")
                .await
                .unwrap();
            let exit = tokio::time::timeout(Duration::from_secs(5), &mut running.done)
                .await
                .unwrap()
                .unwrap();
            assert!(exit.success);

            assert!(
                !spy_marker.exists(),
                "real/spy browser opener in PATH must never be executed"
            );
            assert_eq!(std::fs::read_to_string(&opener_rc).unwrap(), "0");
            assert_eq!(
                std::fs::read_to_string(&other_out).unwrap(),
                "OTHER_TOOL_OK"
            );
            assert_eq!(std::fs::read_to_string(&env_out).unwrap(), "|||||");

            let shim_dir = data_dir.join("agy-no-browser");
            let shim_script = shim_dir.join(OPENER_BIN);
            assert_eq!(
                std::fs::symlink_metadata(&shim_dir)
                    .unwrap()
                    .permissions()
                    .mode()
                    & 0o777,
                0o700
            );
            assert_eq!(
                std::fs::symlink_metadata(&shim_script)
                    .unwrap()
                    .permissions()
                    .mode()
                    & 0o777,
                0o700
            );
            assert_eq!(
                std::fs::read_to_string(&shim_script).unwrap(),
                "#!/bin/sh\nexit 0\n"
            );
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn browser_suppression_falls_back_to_filtering_path_when_shim_creation_fails() {
            let dir = tempfile::tempdir().unwrap();
            let blocked_data_dir = dir.path().join("not-a-directory");
            std::fs::write(&blocked_data_dir, b"file").unwrap();

            let opener_dir = dir.path().join("dir-with-opener");
            let other_dir = dir.path().join("dir-with-other");
            std::fs::create_dir_all(&opener_dir).unwrap();
            std::fs::create_dir_all(&other_dir).unwrap();

            let spy_marker = dir.path().join("spy-opened.txt");
            let opener_rc = dir.path().join("opener-rc.txt");
            let other_out = dir.path().join("other-out.txt");

            write_script(
                &opener_dir,
                OPENER_BIN,
                &format!(
                    "printf 'OPENED:%s' \"$1\" > '{}'\nexit 0",
                    spy_marker.display()
                ),
            );
            write_script(
                &other_dir,
                "cc-switch-other-tool",
                "printf 'FALLBACK_OTHER_OK'",
            );

            let mut path_entries = vec![opener_dir.clone(), other_dir.clone()];
            if let Some(existing) = std::env::var_os("PATH") {
                path_entries.extend(std::env::split_paths(&existing));
            }
            let _env = crate::test_support::EnvVars::new()
                .set("PATH", std::env::join_paths(path_entries).unwrap());

            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
{OPENER_BIN} '{VALID_URL}' 2>/dev/null
printf '%s' "$?" > '{}'
cc-switch-other-tool > '{}'
printf '%s\n' '{VALID_URL}'
IFS= read -r _line
exit 0
"#,
                    opener_rc.display(),
                    other_out.display(),
                ),
                true,
            );

            let mut running =
                RunningAcpLogin::start(&bin, &blocked_data_dir, Duration::from_secs(30))
                    .await
                    .unwrap();
            running
                .paste_target()
                .submit("4/0AeanS0_clean-code")
                .await
                .unwrap();
            let exit = tokio::time::timeout(Duration::from_secs(5), &mut running.done)
                .await
                .unwrap()
                .unwrap();
            assert!(exit.success);

            assert!(
                !spy_marker.exists(),
                "fallback must filter out PATH entries containing the browser opener"
            );
            assert_ne!(std::fs::read_to_string(&opener_rc).unwrap(), "0");
            assert_eq!(
                std::fs::read_to_string(&other_out).unwrap(),
                "FALLBACK_OTHER_OK"
            );
        }

        #[tokio::test]
        #[serial_test::serial]
        async fn shim_refuses_symlink_dir_and_replaces_tampered_script_atomically() {
            let dir = tempfile::tempdir().unwrap();
            let opener_dir = dir.path().join("spy-bin");
            std::fs::create_dir_all(&opener_dir).unwrap();
            let spy_marker = dir.path().join("spy-opened.txt");
            write_script(
                &opener_dir,
                OPENER_BIN,
                &format!(
                    "printf 'OPENED:%s' \"$1\" > '{}'\nexit 0",
                    spy_marker.display()
                ),
            );

            let mut path_entries = vec![opener_dir.clone()];
            if let Some(existing) = std::env::var_os("PATH") {
                path_entries.extend(std::env::split_paths(&existing));
            }
            let _env = crate::test_support::EnvVars::new()
                .set("PATH", std::env::join_paths(path_entries).unwrap());

            let bin = mock_agy(
                dir.path(),
                &format!(
                    r#"
{OPENER_BIN} '{VALID_URL}' 2>/dev/null
printf '%s\n' '{VALID_URL}'
IFS= read -r _line
exit 0
"#
                ),
                true,
            );

            // 1. 符号链接 shim 目录不会被跟随,自动退回过滤 PATH,且目标目录保持原样
            let symlink_data_dir = dir.path().join("symlink-data");
            let outside_target = dir.path().join("outside-target");
            std::fs::create_dir_all(&symlink_data_dir).unwrap();
            std::fs::create_dir_all(&outside_target).unwrap();
            std::os::unix::fs::symlink(&outside_target, symlink_data_dir.join("agy-no-browser"))
                .unwrap();

            let mut running =
                RunningAcpLogin::start(&bin, &symlink_data_dir, Duration::from_secs(30))
                    .await
                    .unwrap();
            running
                .paste_target()
                .submit("4/0AeanS0_clean-code")
                .await
                .unwrap();
            let exit = tokio::time::timeout(Duration::from_secs(5), &mut running.done)
                .await
                .unwrap()
                .unwrap();
            assert!(exit.success);
            assert!(!spy_marker.exists());
            assert!(!outside_target.join(OPENER_BIN).exists());

            // 2. 符号链接拦截脚本会被原子替换为 0700 真实文件,不改写原符号链接目标
            let tampered_data_dir = dir.path().join("tampered-data");
            let shim_dir = tampered_data_dir.join("agy-no-browser");
            std::fs::create_dir_all(&shim_dir).unwrap();
            std::fs::set_permissions(&shim_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
            let sentinel = dir.path().join("sentinel.txt");
            std::fs::write(&sentinel, "DO_NOT_TOUCH").unwrap();
            std::os::unix::fs::symlink(&sentinel, shim_dir.join(OPENER_BIN)).unwrap();

            let mut running2 =
                RunningAcpLogin::start(&bin, &tampered_data_dir, Duration::from_secs(30))
                    .await
                    .unwrap();
            running2
                .paste_target()
                .submit("4/0AeanS0_clean-code")
                .await
                .unwrap();
            let exit2 = tokio::time::timeout(Duration::from_secs(5), &mut running2.done)
                .await
                .unwrap()
                .unwrap();
            assert!(exit2.success);
            assert!(!spy_marker.exists());
            assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "DO_NOT_TOUCH");

            let script_meta = std::fs::symlink_metadata(shim_dir.join(OPENER_BIN)).unwrap();
            assert!(script_meta.file_type().is_file());
            assert_eq!(script_meta.permissions().mode() & 0o777, 0o700);
            assert_eq!(
                std::fs::symlink_metadata(&shim_dir)
                    .unwrap()
                    .permissions()
                    .mode()
                    & 0o777,
                0o700
            );
            assert_eq!(
                std::fs::read_to_string(shim_dir.join(OPENER_BIN)).unwrap(),
                "#!/bin/sh\nexit 0\n"
            );
        }

        #[test]
        #[serial_test::serial]
        fn suppressed_path_falls_back_on_noexec_colon_dir_and_directory_collision() {
            let dir = tempfile::tempdir().unwrap();
            let opener_dir = dir.path().join("has-opener");
            let other_dir = dir.path().join("other-bin");
            std::fs::create_dir_all(&opener_dir).unwrap();
            std::fs::create_dir_all(&other_dir).unwrap();
            write_script(&opener_dir, OPENER_BIN, "exit 0");

            let raw_path = std::env::join_paths([
                PathBuf::from("."),
                PathBuf::from("relative/bin"),
                opener_dir.clone(),
                other_dir.clone(),
            ])
            .unwrap();

            // 1. 模拟 noexec 挂载(access(X_OK) 返回 EACCES):不可保留原 PATH 中的 opener_dir,
            //    必须回退到过滤 PATH,去掉 opener_dir 和相对路径,仅保留 other_dir。
            let noexec_data_dir = dir.path().join("noexec-data");
            let noexec_path = unix_browser_shim::suppressed_path_with(
                &noexec_data_dir,
                Some(raw_path.as_os_str()),
                |_script| {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::PermissionDenied,
                        "simulated noexec mount",
                    ))
                },
            );
            let noexec_entries: Vec<PathBuf> = std::env::split_paths(&noexec_path).collect();
            assert_eq!(noexec_entries, vec![other_dir.clone()]);

            // 2. data_dir 路径包含 `:` 导致 join_paths 失败时,同样回退到过滤 PATH。
            let colon_data_dir = dir.path().join("with:colon");
            let colon_path = unix_browser_shim::suppressed_path_with(
                &colon_data_dir,
                Some(raw_path.as_os_str()),
                |_| Ok(()),
            );
            let colon_entries: Vec<PathBuf> = std::env::split_paths(&colon_path).collect();
            assert_eq!(colon_entries, vec![other_dir.clone()]);

            // 3. 原 PATH 为 None 时:成功返回 [shim_dir],失败返回空 PATH(避免 unset 触发默认 /usr/bin)。
            let ok_data_dir = dir.path().join("none-path-data");
            let none_ok = unix_browser_shim::suppressed_path_with(&ok_data_dir, None, |_| Ok(()));
            assert_eq!(
                std::env::split_paths(&none_ok).collect::<Vec<_>>(),
                vec![ok_data_dir.join("agy-no-browser")]
            );
            let none_fallback = unix_browser_shim::suppressed_path_with(&ok_data_dir, None, |_| {
                Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "simulated noexec",
                ))
            });
            assert!(none_fallback.is_empty());

            // 4. 合法脚本再次调用直接复用同一 inode(不重写,避免并发 ETXTBSY);
            //    权限被放宽(0755)或带上特殊权限位(如 01700)时则原子替换回干净 0700。
            let script_path = ok_data_dir.join("agy-no-browser").join(OPENER_BIN);
            let first_ino = std::fs::symlink_metadata(&script_path).unwrap().ino();
            let _ = unix_browser_shim::suppressed_path_with(&ok_data_dir, None, |_| Ok(()));
            let second_ino = std::fs::symlink_metadata(&script_path).unwrap().ino();
            assert_eq!(
                first_ino, second_ino,
                "valid shim should be reused in place"
            );

            std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();
            let _ = unix_browser_shim::suppressed_path_with(&ok_data_dir, None, |_| Ok(()));
            let mode_refreshed = std::fs::symlink_metadata(&script_path).unwrap();
            assert_eq!(mode_refreshed.permissions().mode() & 0o7777, 0o700);
            assert_ne!(
                mode_refreshed.ino(),
                first_ino,
                "broadened mode must trigger atomic replacement"
            );

            if std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o1700))
                .is_ok()
            {
                let before_special_ino = std::fs::symlink_metadata(&script_path).unwrap().ino();
                let _ = unix_browser_shim::suppressed_path_with(&ok_data_dir, None, |_| Ok(()));
                let refreshed_meta = std::fs::symlink_metadata(&script_path).unwrap();
                assert_eq!(refreshed_meta.permissions().mode() & 0o7777, 0o700);
                assert_ne!(
                    refreshed_meta.ino(),
                    before_special_ino,
                    "special mode bits must trigger atomic replacement"
                );
            }

            // 5. apply_browser_suppression 实际为 Command 注入包含 shim_dir 的 PATH。
            let mut cmd = tokio::process::Command::new("/bin/true");
            crate::services::agy_account::acp_login::apply_browser_suppression(
                &mut cmd,
                Path::new("/bin/true"),
                &ok_data_dir,
            );
            let cmd_path = cmd
                .as_std()
                .get_envs()
                .find_map(|(k, v)| (k == std::ffi::OsStr::new("PATH")).then_some(v))
                .flatten()
                .expect("PATH should be set on unix command");
            assert_eq!(
                std::env::split_paths(cmd_path).next(),
                Some(ok_data_dir.join("agy-no-browser"))
            );

            // 6. script_path 被目录占据时 rename 失败(EISDIR):回退过滤 PATH 且不残留 .tmp 文件。
            let dir_collision_data = dir.path().join("dir-collision");
            let collision_shim_dir = dir_collision_data.join("agy-no-browser");
            std::fs::create_dir_all(collision_shim_dir.join(OPENER_BIN)).unwrap();
            let collision_path = unix_browser_shim::suppressed_path_with(
                &dir_collision_data,
                Some(raw_path.as_os_str()),
                |_| Ok(()),
            );
            assert_eq!(
                std::env::split_paths(&collision_path).collect::<Vec<_>>(),
                vec![other_dir]
            );
            let leftover_tmps: Vec<_> = std::fs::read_dir(&collision_shim_dir)
                .unwrap()
                .filter_map(Result::ok)
                .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
                .collect();
            assert!(
                leftover_tmps.is_empty(),
                "failed rename must clean up temp file"
            );
        }
    }
}