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

15.8 KB
Raw Blame
use cc_switch_lib::{
    qoder_config::QoderEdition, update_settings, AppSettings, AppType, McpServer, McpService,
    Prompt, PromptService, Provider, ProviderService,
};
use serde_json::{json, Value};
use std::{
    ffi::OsString,
    fs,
    path::{Path, PathBuf},
};

use crate::support::{create_test_state, reset_test_fs, test_mutex};

struct QoderHomes {
    directory: tempfile::TempDir,
    previous: [Option<OsString>; 2],
}
impl QoderHomes {
    fn new() -> Self {
        let directory = tempfile::tempdir().unwrap();
        let variables = ["QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR"];
        let previous = variables.map(std::env::var_os);
        for (variable, folder) in variables.into_iter().zip(["global", "cn"]) {
            let path = directory.path().join(folder);
            fs::create_dir_all(&path).unwrap();
            std::env::set_var(variable, path);
        }
        Self {
            directory,
            previous,
        }
    }
    fn root(&self, folder: &str) -> PathBuf {
        self.directory.path().join(folder)
    }
    fn settings(&self, folder: &str) -> PathBuf {
        self.root(folder).join("settings.json")
    }
}
impl Drop for QoderHomes {
    fn drop(&mut self) {
        for (variable, previous) in ["QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR"]
            .into_iter()
            .zip(&self.previous)
        {
            if let Some(previous) = previous {
                std::env::set_var(variable, previous);
            } else {
                std::env::remove_var(variable);
            }
        }
    }
}
fn read(path: &Path) -> Value {
    serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}
fn server() -> McpServer {
    serde_json::from_value(json!({"id":"managed","name":"Managed","server":{"command":"node","args":["server.js"]},"apps":{"qoder":true}})).unwrap()
}
/// Qoder 是一个应用,设置里选的版本决定 MCP / Skills / 提示词写进哪个目录。
fn select_edition(edition: QoderEdition) {
    update_settings(AppSettings {
        qoder_edition: Some(edition),
        ..AppSettings::default()
    })
    .unwrap();
}

#[test]
fn qoder_mcp_writes_only_the_selected_edition_and_keeps_native_settings() {
    let _guard = test_mutex().lock().unwrap();
    reset_test_fs();
    let homes = QoderHomes::new();
    let state = create_test_state().unwrap();
    select_edition(QoderEdition::Global);
    let native = json!({"model":{"name":"auto"},"mcpServers":{"native":{"type":"http","url":"https://example.test/mcp","disabled":true,"trust":false}}});
    for folder in ["global", "cn"] {
        fs::write(homes.settings(folder), native.to_string()).unwrap();
    }
    McpService::upsert_server(&state, server()).unwrap();
    let global = read(&homes.settings("global"));
    assert_eq!(global["model"], native["model"]);
    assert_eq!(
        global["mcpServers"]["native"],
        native["mcpServers"]["native"]
    );
    assert_eq!(global["mcpServers"]["managed"]["command"], "node");
    assert_eq!(read(&homes.settings("cn")), native);

    McpService::toggle_app(&state, "managed", AppType::Qoder, false).unwrap();
    assert!(read(&homes.settings("global"))["mcpServers"]
        .get("managed")
        .is_none());

    select_edition(QoderEdition::Cn);
    McpService::toggle_app(&state, "managed", AppType::Qoder, true).unwrap();
    assert_eq!(
        read(&homes.settings("cn"))["mcpServers"]["managed"]["command"],
        "node"
    );
    McpService::delete_server(&state, "managed").unwrap();
    for folder in ["global", "cn"] {
        assert_eq!(
            read(&homes.settings(folder))["mcpServers"],
            native["mcpServers"]
        );
    }
    assert!(state.db.get_all_mcp_servers().unwrap().is_empty());
}

#[test]
fn qoder_mcp_failure_rolls_back_and_native_models_stay_in_cli() {
    let _guard = test_mutex().lock().unwrap();
    reset_test_fs();
    let homes = QoderHomes::new();
    let state = create_test_state().unwrap();
    select_edition(QoderEdition::Global);
    fs::write(homes.settings("global"), "broken JSON").unwrap();
    assert!(McpService::upsert_server(&state, server()).is_err());
    assert_eq!(
        fs::read_to_string(homes.settings("global")).unwrap(),
        "broken JSON"
    );
    assert!(state.db.get_all_mcp_servers().unwrap().is_empty());
    let app = AppType::Qoder;
    assert!(ProviderService::list(&state, app.clone())
        .unwrap()
        .is_empty());
    assert!(!ProviderService::should_import_default_config_on_startup(&state, &app).unwrap());
    assert!(!ProviderService::import_default_config(&state, app.clone()).unwrap());
    let provider = Provider::with_id(
        "custom".into(),
        "Custom".into(),
        json!({"apiKey":"test"}),
        None,
    );
    assert!(ProviderService::add(&state, app, provider, true).is_err());
}

#[test]
fn qoder_prompt_follows_the_selected_editions_directory() {
    let _guard = test_mutex().lock().unwrap();
    reset_test_fs();
    let homes = QoderHomes::new();
    let state = create_test_state().unwrap();
    select_edition(QoderEdition::Global);
    let prompt: Prompt = serde_json::from_value(
        json!({"id":"global","name":"Global","content":"Shared instructions","enabled":false}),
    )
    .unwrap();
    PromptService::upsert_prompt(&state, AppType::Qoder, "global", prompt).unwrap();
    PromptService::enable_prompt(&state, AppType::Qoder, "global").unwrap();
    assert_eq!(
        fs::read_to_string(homes.root("global").join("AGENTS.md")).unwrap(),
        "Shared instructions"
    );
    assert!(!homes.root("cn").join("AGENTS.md").exists());
    // 换版本后重新投影,写进新版本的目录。
    select_edition(QoderEdition::Cn);
    PromptService::sync_to_live(&state, AppType::Qoder).unwrap();
    assert_eq!(
        fs::read_to_string(homes.root("cn").join("AGENTS.md")).unwrap(),
        "Shared instructions"
    );
}

#[test]
fn qoder_usage_metadata_stays_out_of_native_credentials() {
    use std::{
        io::{Read, Write},
        net::TcpListener,
        time::{Duration, Instant},
    };
    let _guard = test_mutex().lock().unwrap();
    reset_test_fs();
    let homes = QoderHomes::new();
    let state = create_test_state().unwrap();
    select_edition(QoderEdition::Cn);
    let native = json!({"providers":{"native":{"baseUrl":"https://example.test/v1","apiKey":"native-key","model":"model"}},"model":{"name":"native/model"}});
    for folder in ["global", "cn"] {
        fs::write(homes.settings(folder), native.to_string()).unwrap();
    }
    let before = fs::read(homes.settings("cn")).unwrap();
    let script = serde_json::from_value(json!({"enabled":true,"language":"javascript","code":"({request:{url:'{{baseUrl}}/usage',method:'GET',headers:{Authorization:'Bearer {{apiKey}}'}},extractor:function(r){return r}})","autoQueryInterval":15})).unwrap();
    // 打开列表时把 settings.json 里已有的供应商导入成卡片
    let mut card = ProviderService::list(&state, AppType::Qoder).unwrap()["native"].clone();
    card.meta.get_or_insert_with(Default::default).usage_script = Some(script);
    ProviderService::update(&state, AppType::Qoder, None, card).unwrap();
    // 只存用量脚本不碰 Qoder 的文件
    assert_eq!(fs::read(homes.settings("cn")).unwrap(), before);
    let stored = state
        .db
        .get_provider_by_id("native", &AppType::Qoder)
        .unwrap()
        .unwrap();
    assert!(stored.meta.unwrap().usage_script.unwrap().enabled);
    assert_eq!(stored.settings_config, native["providers"]["native"]);
    assert_eq!(read(&homes.settings("global")), native);
    // Query against a local fixture after credentials change outside CC Switch.
    let listener = TcpListener::bind("localhost:0").unwrap();
    let address = listener.local_addr().unwrap();
    listener.set_nonblocking(true).unwrap();
    let handle = std::thread::spawn(move || {
        let start = Instant::now();
        loop {
            match listener.accept() {
                Ok((mut stream, _)) => {
                    // Windows inherits the listener's nonblocking mode on accept.
                    // Wait for the request bytes instead of racing the HTTP client.
                    stream.set_nonblocking(false).unwrap();
                    stream
                        .set_read_timeout(Some(Duration::from_secs(5)))
                        .unwrap();
                    let mut buffer = [0u8; 8192];
                    let mut count = 0;
                    while !buffer[..count].windows(4).any(|part| part == b"\r\n\r\n") {
                        assert!(count < buffer.len(), "Usage request headers are too large");
                        let received = stream
                            .read(&mut buffer[count..])
                            .expect("Usage request headers should arrive before the read timeout");
                        assert!(
                            received > 0,
                            "Usage connection closed before request headers"
                        );
                        count += received;
                    }
                    let request = String::from_utf8_lossy(&buffer[..count]).to_ascii_lowercase();
                    assert!(request.starts_with("get /usage "), "{request}");
                    assert!(request.contains("authorization: bearer changed-key"));
                    let body = r#"{"remaining":42,"unit":"USD"}"#;
                    write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()).unwrap();
                    break;
                }
                Err(error)
                    if error.kind() == std::io::ErrorKind::WouldBlock
                        && start.elapsed() < Duration::from_secs(10) =>
                {
                    std::thread::sleep(Duration::from_millis(10))
                }
                Err(error) => panic!("Usage fixture was not reached: {error}"),
            }
        }
    });
    let mut changed = native.clone();
    changed["providers"]["native"]["apiKey"] = json!("changed-key");
    changed["providers"]["native"]["baseUrl"] =
        json!(format!("http://localhost:{}", address.port()));
    fs::write(homes.settings("cn"), changed.to_string()).unwrap();
    let result = tokio::runtime::Runtime::new()
        .unwrap()
        .block_on(ProviderService::query_usage(
            &state,
            AppType::Qoder,
            "native",
        ))
        .unwrap();
    assert!(result.success, "{:?}", result.error);
    assert_eq!(result.data.unwrap()[0].remaining, Some(42.0));
    handle.join().unwrap();
}

#[test]
fn qoder_skills_follow_the_selected_edition_and_preserve_native_skills() {
    use cc_switch_lib::SkillService;
    let _guard = test_mutex().lock().unwrap();
    reset_test_fs();
    let homes = QoderHomes::new();
    let state = create_test_state().unwrap();
    select_edition(QoderEdition::Global);
    let directory = "qoder-managed-skill";
    let ssot = SkillService::get_ssot_dir().unwrap().join(directory);
    fs::create_dir_all(&ssot).unwrap();
    fs::write(
        ssot.join("SKILL.md"),
        "---\nname: managed\ndescription: fixture\n---\nManaged skill",
    )
    .unwrap();
    let skill = serde_json::from_value(json!({"id":"qoder-skill","name":"Managed","description":"fixture","directory":directory,"apps":{},"installedAt":0})).unwrap();
    state.db.save_skill(&skill).unwrap();
    fs::write(homes.settings("global"), json!({"skills":{"disabled":[directory,"unrelated"]},"skillOverrides":{directory:"off","unrelated":"off"},"model":{"name":"auto"}}).to_string()).unwrap();
    SkillService::toggle_app(&state.db, "qoder-skill", &AppType::Qoder, true).unwrap();
    assert_eq!(
        read(&homes.settings("global"))["skills"]["disabled"],
        json!(["unrelated"])
    );
    assert_eq!(
        read(&homes.settings("global"))["skillOverrides"],
        json!({"unrelated":"off"})
    );
    assert!(homes
        .root("global")
        .join("skills")
        .join(directory)
        .join("SKILL.md")
        .exists());
    assert!(!homes.root("cn").join("skills").join(directory).exists());

    // 换版本后重新投影,技能写进新版本的目录。
    select_edition(QoderEdition::Cn);
    SkillService::sync_to_app(&state.db, &AppType::Qoder).unwrap();
    assert!(homes
        .root("cn")
        .join("skills")
        .join(directory)
        .join("SKILL.md")
        .exists());

    // An unrelated native skill is never removed by managed Skill synchronization.
    let native = homes.root("cn").join("skills/native-skill");
    fs::create_dir_all(&native).unwrap();
    fs::write(native.join("SKILL.md"), "Native user skill").unwrap();
    assert!(SkillService::resync_all_apps(&state.db)
        .iter()
        .filter(|outcome| outcome.app == "qoder")
        .all(|outcome| outcome.ok));
    assert_eq!(
        fs::read_to_string(native.join("SKILL.md")).unwrap(),
        "Native user skill"
    );
    let stored = state
        .db
        .get_installed_skill("qoder-skill")
        .unwrap()
        .unwrap();
    assert!(stored.apps.qoder);
}

#[test]
fn qoder_provider_cards_add_per_edition_and_leave_privacy_alone() {
    let _guard = test_mutex().lock().unwrap();
    reset_test_fs();
    let homes = QoderHomes::new();
    let state = create_test_state().unwrap();
    select_edition(QoderEdition::Global);
    let config = json!({"displayName":"Custom","baseUrl":"https://example.test/v1","apiKey":"test-key","protocol":"anthropic","authType":"api-key","models":[{"model":"custom-model","contextWindow":200000,"maxOutputTokens":8192},{"model":"second"}],"model":"custom-model"});
    let provider = Provider::with_id("custom".into(), "Custom".into(), config.clone(), None);
    assert!(ProviderService::list(&state, AppType::Qoder)
        .unwrap()
        .is_empty());
    assert!(
        !homes.settings("global").exists(),
        "reading must not create settings"
    );
    // 「添加」写进国际版,不改默认模型;用户在 Qoder 里的隐私选择不动
    ProviderService::add(&state, AppType::Qoder, provider, true).unwrap();
    let global = read(&homes.settings("global"));
    assert_eq!(global["providers"]["custom"], config);
    assert!(global.get("model").is_none());
    assert!(global.get("privacy").is_none());
    assert_eq!(
        ProviderService::current(&state, AppType::Qoder).unwrap(),
        ""
    );

    // 设为默认:连模型一起选
    ProviderService::set_qoder_default(&state, "custom", Some("second")).unwrap();
    assert_eq!(
        read(&homes.settings("global"))["model"]["name"],
        "custom/second"
    );
    assert_eq!(
        ProviderService::current(&state, AppType::Qoder).unwrap(),
        "custom"
    );
    // 默认那家不能移除
    assert!(ProviderService::remove_from_live_config(&state, AppType::Qoder, "custom").is_err());

    // 国内版共用同一批卡片:切过去后这张在「可添加」,文件里什么都没有
    select_edition(QoderEdition::Cn);
    let cards = ProviderService::list(&state, AppType::Qoder).unwrap();
    assert_eq!(
        cards["custom"].meta.as_ref().unwrap().live_config_managed,
        Some(false)
    );
    assert!(!homes.settings("cn").exists());
    ProviderService::add_to_live_config(&state, AppType::Qoder, "custom").unwrap();
    let mut settings = read(&homes.settings("cn"));
    assert_eq!(settings["providers"]["custom"], config);
    settings["privacy"]["usageStatisticsEnabled"] = json!(true);
    fs::write(homes.settings("cn"), settings.to_string()).unwrap();
    ProviderService::remove_from_live_config(&state, AppType::Qoder, "custom").unwrap();
    let settings = read(&homes.settings("cn"));
    assert!(settings["providers"].get("custom").is_none());
    assert_eq!(settings["privacy"]["usageStatisticsEnabled"], true);
    // 卡片留着,国际版的配置也没动
    assert!(ProviderService::list(&state, AppType::Qoder)
        .unwrap()
        .contains_key("custom"));
    assert_eq!(
        read(&homes.settings("global"))["providers"]["custom"],
        config
    );
}