A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
feat(agy): switch providers through the Enterprise Gateway block in config.json
Jason37ddb1531976
diff --git a/src-tauri/src/agy_config.rs b/src-tauri/src/agy_config.rsindex b2a43daf3..04f7baf05 100644--- a/src-tauri/src/agy_config.rs+++ b/src-tauri/src/agy_config.rs@@ -45,6 +45,12 @@ pub fn customizations_dir() -> PathBuf {get_home_dir().join(".gemini").join("config")}+/// `~/.gemini/config/config.json`:CLI 和桌面版都从这里读 Enterprise Gateway 的+/// `gateway` / `models`(切换式写入的唯一文件,见 `live::project::agy`)。+pub fn gateway_config_path() -> PathBuf {+ customizations_dir().join("config.json")+}+pub fn settings_path() -> PathBuf {agy_dir().join("settings.json")}@@ -558,8 +564,13 @@ fn fnv1a(bytes: &[u8]) -> u64 {})}-/// 从 live 读回编辑器用的 `{ env, config }`。Key 不在任何文件里,所以 `env` 恒为空。+/// 从 live 读回供应商行的形状。`config.json` 里开着网关(带 Key)时读成第三方卡+/// (`env` 放 Key 和地址,其余网关选项放 `gateway`,见 `live::project::agy`);否则是+/// agy 自己的登录,只读 `settings.json` 里的模型。pub fn read_live_settings() -> Result<Value, AppError> {+ if let Some(settings) = read_gateway_settings()? {+ return Ok(settings);+ }let settings_file = settings_path();if !settings_file.exists() {return Err(AppError::localized(@@ -580,6 +591,100 @@ pub fn read_live_settings() -> Result<Value, AppError> {}))}+/// `config.json` 里开着的网关读回成行;没有文件、没开网关或没有 Key 时为 `None`。+/// 投影时自动补的 `x-goog-api-key`(值就是 Key)不读回,下次投影会再补上。+fn read_gateway_settings() -> Result<Option<Value>, AppError> {+ let path = gateway_config_path();+ let raw = match fs::read(&path) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(AppError::io(&path, error)),+ };+ let doc: Value = serde_json::from_slice(&raw)+ .map_err(|e| AppError::Config(format!("Invalid agy config.json: {e}")))?;+ let Some(gateway) = doc.get("gateway").and_then(Value::as_object) else {+ return Ok(None);+ };+ let text = |value: Option<&Value>| {+ value+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|text| !text.is_empty())+ .map(str::to_string)+ };+ let Some(key) = text(gateway.get("apiKey")) else {+ return Ok(None);+ };+ if gateway.get("enabled").and_then(Value::as_bool) != Some(true) {+ return Ok(None);+ }+ let mut env = serde_json::Map::new();+ env.insert("GEMINI_API_KEY".into(), json!(key));+ if let Some(url) = text(gateway.get("url")) {+ env.insert("GOOGLE_GEMINI_BASE_URL".into(), json!(url));+ }+ let mut options = serde_json::Map::new();+ let protocol = text(gateway.get("wireProtocol"));+ // 投影只在 genai 协议下自动补 x-goog-api-key,所以也只在 genai 下不读回它。+ let auto_goog_header = protocol+ .as_deref()+ .is_none_or(|protocol| protocol == crate::live::project::agy::WIRE_GENAI);+ if let Some(protocol) = protocol {+ options.insert("wireProtocol".into(), json!(protocol));+ }+ let headers: serde_json::Map<String, Value> = gateway+ .get("customHeaders")+ .and_then(Value::as_object)+ .into_iter()+ .flatten()+ .filter(|(name, value)| {+ !(auto_goog_header+ && name.eq_ignore_ascii_case("x-goog-api-key")+ && value.as_str() == Some(&key))+ })+ .map(|(name, value)| (name.clone(), value.clone()))+ .collect();+ if !headers.is_empty() {+ options.insert("customHeaders".into(), Value::Object(headers));+ }+ let models = doc.get("models");+ let ids: Vec<Value> = models+ .and_then(|models| models.get("list"))+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|entry| text(entry.get("modelId")).map(Value::String))+ .collect();+ if !ids.is_empty() {+ options.insert("models".into(), Value::Array(ids));+ if let Some(default) = text(models.and_then(|models| models.get("defaultModelId"))) {+ options.insert("defaultModel".into(), json!(default));+ }+ }+ if let Some(ca) = text(doc.get("caCertPath")) {+ options.insert("caCertPath".into(), json!(ca));+ }+ let mut settings = json!({ "env": env, "config": {} });+ if !options.is_empty() {+ settings["gateway"] = Value::Object(options);+ }+ Ok(Some(settings))+}++/// `config.json` 现在开着网关(启用的是第三方卡):这时直接跑 `agy` 走的是网关,不是官方登录。+pub(crate) fn live_gateway_enabled() -> bool {+ fs::read(gateway_config_path())+ .ok()+ .and_then(|raw| serde_json::from_slice::<Value>(&raw).ok())+ .and_then(|doc| doc.pointer("/gateway/enabled").and_then(Value::as_bool))+ .unwrap_or(false)+}++/// 行里有 Key:第三方网关卡(从 live 导入时据此定分类)。+pub(crate) fn has_gateway_key(settings: &Value) -> bool {+ AgyProjection::of(settings).is_key_mode()+}+#[derive(Debug, Clone, PartialEq, Eq)]struct AgyProjection {api_key: Option<String>,@@ -626,18 +731,13 @@ pub(crate) fn has_managed_content(settings: &Value) -> bool {projection.api_key.is_some() || projection.base_url.is_some() || projection.model.is_some()}-/// 私有目录里 `settings.json` 的补丁:Key 模式加上卡上的模型。-fn key_profile_patch(projection: &AgyProjection) -> JsonPatch {- let mut patch = JsonPatch::default();- patch- .set- .push((KeyPath::new(&["modelProvider"]), json!("gemini")));- let model = KeyPath::new(&["model"]);- match &projection.model {- Some(name) => patch.set.push((model, json!(name))),- None => patch.remove.push(model),+/// 私有目录里 `settings.json` 的补丁:撤掉旧版写的 `modelProvider: gemini` 和显示名模型。+/// 网关模式下模型来自网关(`config.json` 的 `models` 或网关自己的模型列表)。+fn key_profile_patch() -> JsonPatch {+ JsonPatch {+ remove: vec![KeyPath::new(&["modelProvider"]), KeyPath::new(&["model"])],+ ..JsonPatch::default()}- patch}/// 撤掉 #8268 测试版写进真实 `settings.json` 的 `modelProvider`,模型和其余键不动。@@ -679,7 +779,21 @@ pub(crate) struct AgyLaunch {pub env: Vec<(&'static str, Option<String>)>,}-/// 准备在终端里启动某张卡:Key 卡会建好(或更新)它的私有目录。+/// 打开 Key 卡的终端时要清掉的变量:用户 rc 里 export 的会按字段盖过私有目录里的网关+/// (实测请求头还会逐个合并进来),旧版的 Key 变量在网关模式下也没用了。+const LAUNCH_CLEARED_ENV: &[&str] = &[+ "GEMINI_API_KEY",+ "GOOGLE_GEMINI_BASE_URL",+ "AGY_LLM_GATEWAY_URL",+ "AGY_LLM_GATEWAY_API_KEY",+ "AGY_LLM_GATEWAY_WIRE_PROTOCOL",+ "AGY_LLM_GATEWAY_MODELS",+ "AGY_LLM_GATEWAY_HEADERS",+ "AGY_LLM_GATEWAY_CA_CERT",+];++/// 准备在终端里启动某张卡:Key 卡会建好(或更新)它的私有目录,网关写在私有目录自己的+/// `config/config.json` 里,不管现在启用的是哪张卡都只用这张卡的网关。pub(crate) fn prepare_launch(provider_id: &str, settings: &Value) -> Result<AgyLaunch, AppError> {let projection = AgyProjection::of(settings);if !projection.is_key_mode() {@@ -690,57 +804,143 @@ pub(crate) fn prepare_launch(provider_id: &str, settings: &Value) -> Result<AgyL});}let dir = key_profile_dir(provider_id);- prepare_key_profile(&dir, &projection)?;+ let gateway = crate::live::project::agy::AgyProjection::of(settings, false);+ prepare_key_profile(&dir, &gateway)?;Ok(AgyLaunch {gemini_dir: Some(dir),model: None,- env: vec![- ("GEMINI_API_KEY", projection.api_key.clone()),- ("GOOGLE_GEMINI_BASE_URL", projection.base_url.clone()),- ],+ env: LAUNCH_CLEARED_ENV+ .iter()+ .map(|name| (*name, None))+ .collect(),})}-fn prepare_key_profile(dir: &Path, projection: &AgyProjection) -> Result<(), AppError> {+fn prepare_key_profile(+ dir: &Path,+ gateway: &crate::live::project::agy::AgyProjection,+) -> Result<(), AppError> {let settings = dir.join("antigravity-cli").join("settings.json");- let pre = if settings.exists() {- Some(fs::read(&settings).map_err(|e| AppError::io(&settings, e))?)- } else {- None+ write_patched(&settings, &key_profile_patch())?;+ prepare_private_config(&dir.join("config"), &customizations_dir(), gateway)+}++/// 读 `path`、打补丁,内容变了才写(0600)。+fn write_patched(path: &Path, patch: &JsonPatch) -> Result<(), AppError> {+ let pre = match fs::read(path) {+ Ok(bytes) => Some(bytes),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(error) => return Err(AppError::io(path, error)),};- let bytes = key_profile_patch(projection)- .apply(&settings, pre.as_deref())- .map_err(AppError::from)?;+ let bytes = patch.apply(path, pre.as_deref()).map_err(AppError::from)?;if pre.as_deref() != Some(bytes.as_slice()) {- if let Some(parent) = settings.parent() {+ if let Some(parent) = path.parent() {fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;}- atomic_write_private(&settings, &bytes)?;+ atomic_write_private(path, &bytes)?;}- link_shared_config(&dir.join("config"), &customizations_dir())+ Ok(())}-/// `<私有目录>/config` 指向共享的 `~/.gemini/config`。已经是别的真实目录时不动它:-/// 那是 agy 自己建的,里面可能有用户的东西。-fn link_shared_config(link: &Path, target: &Path) -> Result<(), AppError> {- fs::create_dir_all(target).map_err(|e| AppError::io(target, e))?;- match fs::symlink_metadata(link) {- Ok(meta) if meta.file_type().is_symlink() => {- if fs::read_link(link).ok().as_deref() == Some(target) {- return Ok(());+/// 私有目录的 `config`:共享 `~/.gemini/config` 里的每一项都链回去(MCP、Skills、插件、+/// 提示词照常共享),只有 `config.json` 是私有的一份:共享那份的内容,网关块换成这张卡的。+/// 旧版这里是整个目录的链接,第一次启动时换成真实目录。agy 自己在私有目录里建的东西不动。+fn prepare_private_config(+ private: &Path,+ shared: &Path,+ gateway: &crate::live::project::agy::AgyProjection,+) -> Result<(), AppError> {+ fs::create_dir_all(shared).map_err(|e| AppError::io(shared, e))?;+ if fs::symlink_metadata(private).is_ok_and(|meta| meta.file_type().is_symlink()) {+ remove_link(private)?;+ }+ fs::create_dir_all(private).map_err(|e| AppError::io(private, e))?;++ let mut names = std::collections::HashSet::new();+ for entry in fs::read_dir(shared).map_err(|e| AppError::io(shared, e))? {+ let entry = entry.map_err(|e| AppError::io(shared, e))?;+ let name = entry.file_name();+ if name == "config.json" {+ continue;+ }+ let target = entry.path();+ let link = private.join(&name);+ names.insert(name);+ match fs::symlink_metadata(&link) {+ Ok(meta) if meta.file_type().is_symlink() || is_junction(&link) => {+ if fs::read_link(&link).ok().as_deref() == Some(target.as_path()) {+ continue;+ }+ remove_link(&link)?;}- remove_link(link)?;+ Ok(_) => {+ log::warn!(+ "agy key profile has its own {}, leaving it as is",+ link.display()+ );+ continue;+ }+ Err(_) => {}}- Ok(_) => {- log::warn!(- "agy key profile config is a real directory, leaving it as is: {}",- link.display()- );- return Ok(());+ if target.is_dir() {+ create_dir_link(&target, &link)?;+ } else {+ create_file_link(&target, &link)?;}- Err(_) => {}}- create_dir_link(target, link)+ // 共享目录里已经没有的项,删掉指向它的旧链接。+ for entry in fs::read_dir(private)+ .map_err(|e| AppError::io(private, e))?+ .flatten()+ {+ let link = entry.path();+ let is_link = fs::symlink_metadata(&link)+ .is_ok_and(|meta| meta.file_type().is_symlink() || is_junction(&link));+ if is_link && !names.contains(&entry.file_name()) {+ remove_link(&link)?;+ }+ }++ let shared_config = shared.join("config.json");+ let base = match fs::read(&shared_config) {+ Ok(bytes) => Some(bytes),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(error) => return Err(AppError::io(&shared_config, error)),+ };+ let own = private.join("config.json");+ let patch = crate::live::project::agy::direct_patch(None, gateway);+ let bytes = patch.apply(&own, base.as_deref()).map_err(AppError::from)?;+ if fs::read(&own).ok().as_deref() != Some(bytes.as_slice()) {+ atomic_write_private(&own, &bytes)?;+ }+ Ok(())+}++#[cfg(windows)]+fn is_junction(path: &Path) -> bool {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;+ fs::symlink_metadata(path)+ .is_ok_and(|meta| meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0)+}++#[cfg(not(windows))]+fn is_junction(_path: &Path) -> bool {+ false+}++#[cfg(unix)]+fn create_file_link(target: &Path, link: &Path) -> Result<(), AppError> {+ std::os::unix::fs::symlink(target, link).map_err(|e| AppError::io(link, e))+}++/// Windows 建文件符号链接要开发者模式,失败时退回硬链接(同一个盘,普通用户也能建)。+#[cfg(windows)]+fn create_file_link(target: &Path, link: &Path) -> Result<(), AppError> {+ if std::os::windows::fs::symlink_file(target, link).is_ok() {+ return Ok(());+ }+ fs::hard_link(target, link).map_err(|e| AppError::io(link, e))}#[cfg(unix)]@@ -1035,10 +1235,6 @@ mod legacy {mod tests {use super::*;- fn projection(settings: Value) -> AgyProjection {- AgyProjection::of(&settings)- }-fn patched(patch: &JsonPatch, before: &str) -> Value {let bytes = patch.apply(Path::new("settings.json"), Some(before.as_bytes()))@@ -1047,16 +1243,12 @@ mod tests {}#[test]- fn key_profile_patch_sets_key_mode_and_the_card_model() {- let p = projection(json!({- "env":{"GEMINI_API_KEY":"fixture","GOOGLE_GEMINI_BASE_URL":"https://example.test"},- "config":{"model":{"name":"Gemini 3.1 Pro (High)"}}- }));- let doc = patched(&key_profile_patch(&p), r#"{"theme":"dark"}"#);- assert_eq!(doc["modelProvider"], "gemini");- assert_eq!(doc["model"], "Gemini 3.1 Pro (High)");- assert_eq!(doc["theme"], "dark");- assert!(!serde_json::to_string(&doc).unwrap().contains("fixture"));+ fn key_profile_patch_drops_the_legacy_key_mode_and_display_model() {+ let doc = patched(+ &key_profile_patch(),+ r#"{"theme":"dark","modelProvider":"gemini","model":"Gemini 3.1 Pro (High)"}"#,+ );+ assert_eq!(doc, json!({"theme": "dark"}));}#[test]@@ -1389,7 +1581,7 @@ mod integration_tests {#[test]#[serial]- fn cards_never_write_the_real_settings_credentials_or_shell_files() {+ fn cards_switch_only_the_gateway_block() {use crate::services::ProviderService;let home = HomeGuard::new();fs::create_dir_all(agy_dir()).unwrap();@@ -1398,6 +1590,13 @@ mod integration_tests {// Sibling Gemini files are never targets either.let sibling = home.path().join(".gemini/settings.json");fs::write(&sibling, "{\"keep\":true}").unwrap();+ // The desktop app and the plugin system share config.json.+ fs::create_dir_all(customizations_dir()).unwrap();+ fs::write(+ gateway_config_path(),+ r#"{"plugins":{"a":1},"userSettings":{"enableAdc":true}}"#,+ )+ .unwrap();let db = Arc::new(Database::memory().unwrap());let state = AppState::new(db.clone());let login = provider(@@ -1406,28 +1605,53 @@ mod integration_tests {true,);let relay = relay("relay");- for row in [&login, &relay] {- assert!(ProviderService::add(&state, AppType::Agy, row.clone(), true).unwrap());- let error = ProviderService::switch(&state, AppType::Agy, &row.id).unwrap_err();- assert!(error.to_string().contains("Open terminal"), "{error}");- }+ // The first card becomes current; later cards are only saved.+ assert!(ProviderService::add(&state, AppType::Agy, login.clone(), true).unwrap());+ assert!(ProviderService::add(&state, AppType::Agy, relay.clone(), true).unwrap());assert_eq!(provider_for(&db, &AppType::Agy, Purpose::Direct).unwrap(),- None+ Some("login".into())+ );+ assert!(read_json(&gateway_config_path()).get("gateway").is_none());++ ProviderService::switch(&state, AppType::Agy, "relay").unwrap();+ let live = read_json(&gateway_config_path());+ assert_eq!(live["plugins"], json!({"a": 1}));+ assert_eq!(live["userSettings"], json!({"enableAdc": true}));+ assert_eq!(live["gateway"]["url"], "https://example.test");+ assert_eq!(live["gateway"]["apiKey"], "fixture");+ assert_eq!(+ provider_for(&db, &AppType::Agy, Purpose::Direct).unwrap(),+ Some("relay".into()));+ assert!(live_gateway_enabled());+ // The current card can't be deleted.+ assert!(ProviderService::delete(&state, AppType::Agy, "relay").is_err());- // A pointer left by an older version is neither re-applied by a full- // sync nor a reason to refuse deleting the card.- db.set_current_provider(&AppType::Agy, "login").unwrap();- if let Err(error) = ProviderService::sync_current_to_live(&state) {- assert!(!error.to_string().contains("provider/agy"), "{error}");- }- ProviderService::delete(&state, AppType::Agy, "login").unwrap();+ ProviderService::switch(&state, AppType::Agy, "login").unwrap();+ assert_eq!(+ read_json(&gateway_config_path()),+ json!({"plugins":{"a":1},"userSettings":{"enableAdc":true}})+ );+ assert!(!live_gateway_enabled());+ ProviderService::delete(&state, AppType::Agy, "relay").unwrap();- prepare_launch(&relay.id, &relay.settings_config).unwrap();+ // Neither agy's own settings nor the Gemini CLI files are touched, and the key+ // only ever lived in config.json (0600) and the database.assert_eq!(fs::read_to_string(settings_path()).unwrap(), original);assert_eq!(fs::read_to_string(&sibling).unwrap(), "{\"keep\":true}");+ assert_eq!(+ fs::metadata(gateway_config_path())+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );for file in walk(home.path()) {+ if file.starts_with(crate::config::get_home_dir().join(".cc-switch")) {+ continue;+ }let text = fs::read(&file).unwrap_or_default();assert!(!String::from_utf8_lossy(&text).contains("fixture"),@@ -1444,62 +1668,88 @@ mod integration_tests {#[test]#[serial]- fn key_launch_prepares_a_private_profile_linked_to_shared_config() {+ fn key_launch_prepares_a_private_profile_with_its_own_gateway() {let _home = HomeGuard::new();let shared = customizations_dir();- fs::create_dir_all(&shared).unwrap();+ fs::create_dir_all(shared.join("skills")).unwrap();fs::write(shared.join("mcp_config.json"), "{}").unwrap();+ // The live file points at another card; the terminal must not inherit it.+ fs::write(+ shared.join("config.json"),+ r#"{"plugins":{"a":1},"gateway":{"enabled":true,"url":"https://other.test","apiKey":"other","customHeaders":{"x-goog-api-key":"other"}},"models":{"list":[{"modelId":"o"}]}}"#,+ )+ .unwrap();let row = relay("relay");+ let dir = key_profile_dir("relay");+ // An older version linked the whole config directory.+ fs::create_dir_all(&dir).unwrap();+ create_dir_link(&shared, &dir.join("config")).unwrap();+ fs::create_dir_all(dir.join("antigravity-cli")).unwrap();+ fs::write(+ dir.join("antigravity-cli/settings.json"),+ r#"{"modelProvider":"gemini","model":"Gemini 3.1 Pro (High)","trustedWorkspaces":["/w"]}"#,+ )+ .unwrap();let launch = prepare_launch(&row.id, &row.settings_config).unwrap();- let dir = key_profile_dir("relay");assert_eq!(launch.gemini_dir.as_deref(), Some(dir.as_path()));+ // Keys never travel in the environment; exported gateway variables are cleared.+ assert!(launch.env.iter().all(|(_, value)| value.is_none()));+ assert!(launch+ .env+ .iter()+ .any(|(name, _)| *name == "AGY_LLM_GATEWAY_HEADERS"));++ let settings = read_json(&dir.join("antigravity-cli/settings.json"));+ assert_eq!(settings, json!({"trustedWorkspaces": ["/w"]}));+ let config = dir.join("config");+ assert!(!fs::symlink_metadata(&config)+ .unwrap()+ .file_type()+ .is_symlink());assert_eq!(- launch.env,- vec![- ("GEMINI_API_KEY", Some("fixture".to_string())),- (- "GOOGLE_GEMINI_BASE_URL",- Some("https://example.test".to_string())- ),- ]+ fs::read_link(config.join("mcp_config.json")).unwrap(),+ shared.join("mcp_config.json"));- let private = dir.join("antigravity-cli/settings.json");- let doc = read_json(&private);- assert_eq!(doc["modelProvider"], "gemini");- assert_eq!(doc["model"], "Gemini 3.1 Pro (High)");assert_eq!(- fs::metadata(&private).unwrap().permissions().mode() & 0o777,+ fs::read_link(config.join("skills")).unwrap(),+ shared.join("skills")+ );+ let own = read_json(&config.join("config.json"));+ assert_eq!(own["plugins"], json!({"a": 1}));+ assert_eq!(own["gateway"]["url"], "https://example.test");+ assert_eq!(own["gateway"]["apiKey"], "fixture");+ assert_eq!(+ own["gateway"]["customHeaders"],+ json!({"x-goog-api-key": "fixture"})+ );+ assert!(own.get("models").is_none());+ assert_eq!(+ fs::metadata(config.join("config.json"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,0o600);- assert!(!String::from_utf8_lossy(&fs::read(&private).unwrap()).contains("fixture"));- assert_eq!(fs::read_link(dir.join("config")).unwrap(), shared);- assert!(dir.join("config/mcp_config.json").is_file());+ // The shared file still belongs to the other card.+ assert_eq!(+ read_json(&shared.join("config.json"))["gateway"]["apiKey"],+ "other"+ );+// The global prompt lives in the shared customization root, so the- // private profile loads it too.+ // private profile loads it too (linked on the next launch).let prompt = crate::prompt_files::prompt_file_path(&AppType::Agy).unwrap();assert_eq!(prompt, shared.join("AGENTS.md"));fs::write(&prompt, "rules").unwrap();+ fs::remove_file(shared.join("mcp_config.json")).unwrap();+ prepare_launch(&row.id, &row.settings_config).unwrap();assert_eq!(- fs::read_to_string(dir.join("config/AGENTS.md")).unwrap(),+ fs::read_to_string(config.join("AGENTS.md")).unwrap(),"rules");-- // agy's own keys in the private settings survive later launches; a key- // without an endpoint must clear any endpoint the user's shell exported.- let mut doc = read_json(&private);- doc["trustedWorkspaces"] = json!(["/w"]);- fs::write(&private, serde_json::to_vec(&doc).unwrap()).unwrap();- let google = provider(- "relay",- json!({"env":{"GEMINI_API_KEY":"fixture"},"config":{}}),- false,- );- let launch = prepare_launch(&google.id, &google.settings_config).unwrap();- assert_eq!(launch.env[1], ("GOOGLE_GEMINI_BASE_URL", None));- let doc = read_json(&private);- assert_eq!(doc["trustedWorkspaces"][0], "/w");- assert!(doc.get("model").is_none());+ assert!(fs::symlink_metadata(config.join("mcp_config.json")).is_err());}#[test]@@ -1559,6 +1809,49 @@ mod integration_tests {assert!(!settings_path().exists());}+ #[test]+ #[serial]+ fn live_gateway_is_imported_as_the_current_key_card() {+ let _home = HomeGuard::new();+ fs::create_dir_all(customizations_dir()).unwrap();+ fs::write(+ gateway_config_path(),+ r#"{"gateway":{"enabled":true,"url":"https://relay.test","apiKey":"fixture","wireProtocol":"openai","customHeaders":{"x-goog-api-key":"fixture","X-Team":"dev"}},"models":{"defaultModelId":"b","list":[{"modelId":"a"},{"modelId":"b"}]},"caCertPath":"/ca.pem"}"#,+ )+ .unwrap();+ let db = Arc::new(Database::memory().unwrap());+ let state = AppState::new(db.clone());+ assert!(+ crate::services::ProviderService::import_default_config(&state, AppType::Agy).unwrap()+ );+ let row = db+ .get_provider_by_id("default", &AppType::Agy)+ .unwrap()+ .unwrap();+ assert_eq!(row.category.as_deref(), Some("custom"));+ assert_eq!(+ row.settings_config,+ json!({+ "env": {"GEMINI_API_KEY": "fixture", "GOOGLE_GEMINI_BASE_URL": "https://relay.test"},+ "config": {},+ "gateway": {+ "wireProtocol": "openai",+ "customHeaders": {"x-goog-api-key": "fixture", "X-Team": "dev"},+ "models": ["a", "b"],+ "defaultModel": "b",+ "caCertPath": "/ca.pem",+ },+ })+ );+ // Re-projecting the imported card leaves the file as it was.+ let before = fs::read(gateway_config_path()).unwrap();+ crate::services::ProviderService::sync_current_to_live(&state).unwrap();+ assert_eq!(+ read_json(&gateway_config_path()),+ serde_json::from_slice::<Value>(&before).unwrap()+ );+ }+#[test]#[serial]fn existing_empty_agy_settings_are_not_imported() {diff --git a/src-tauri/src/commands/provider.rs b/src-tauri/src/commands/provider.rsindex 605da4cbd..2b13b04dd 100644--- a/src-tauri/src/commands/provider.rs+++ b/src-tauri/src/commands/provider.rs@@ -251,6 +251,14 @@ pub async fn switch_provider(let state = handle.try_state::<AppState>().ok_or_else(|| "应用状态不可用".to_string())?;+ if app_type == AppType::Agy {+ return agy_direct::switch_with_login(+ state.inner(),+ &handle.state::<AgyAccountState>().0,+ &id,+ )+ .map_err(|e| e.to_string());+ }switch_provider_internal(state.inner(), app_type, &id).map_err(|e| e.to_string())}).awaitdiff --git a/src-tauri/src/deeplink/provider.rs b/src-tauri/src/deeplink/provider.rsindex 497fe2c25..874866cd3 100644--- a/src-tauri/src/deeplink/provider.rs+++ b/src-tauri/src/deeplink/provider.rs@@ -179,8 +179,8 @@ pub fn import_provider_from_deeplink(}}- // If enabled=true, set as current provider. Antigravity 没有「启用」,只导入。- if !additive && activate && !matches!(app_type, AppType::Agy) {+ // If enabled=true, set as current provider.+ if !additive && activate {ProviderService::switch(state, app_type.clone(), &provider_id)?;log::info!("Provider '{provider_id}' set as current for {app_type:?}");}diff --git a/src-tauri/src/deeplink/tests.rs b/src-tauri/src/deeplink/tests.rsindex edd78b2ab..a8dbb5a91 100644--- a/src-tauri/src/deeplink/tests.rs+++ b/src-tauri/src/deeplink/tests.rs@@ -1550,21 +1550,25 @@ fn agy_deeplink_prompt_import_respects_activation() {#[test]#[cfg(unix)]#[serial_test::serial]-fn agy_deeplink_enabled_key_provider_stays_out_of_live_files() {+fn agy_deeplink_enabled_key_provider_becomes_the_gateway() {let _home = TempUserHome::new();let state = AppState::new(Arc::new(Database::memory().unwrap()));let request = parse_deeplink_url("ccswitch://v1/import?resource=provider&app=agy&name=Agy&endpoint=https://relay.example&apiKey=fixture&model=link-model&enabled=true").unwrap();let id = super::provider::import_provider_from_deeplink(&state, request).unwrap();- // Antigravity cards have no "enable": enabled=true only imports the card.let current = crate::mode::current::provider_for(&state.db,&AppType::Agy,crate::mode::current::Purpose::Direct,).unwrap();- assert_eq!(current, None);- // A key card never creates or changes the native settings: it only applies- // to agy started from "Open Terminal" with its private profile.+ assert_eq!(current.as_deref(), Some(id.as_str()));+ // Enabling writes only the gateway block of config.json; agy's own settings and+ // the Gemini CLI files are untouched.+ let live: serde_json::Value =+ serde_json::from_slice(&std::fs::read(crate::agy_config::gateway_config_path()).unwrap())+ .unwrap();+ assert_eq!(live["gateway"]["url"], "https://relay.example");+ assert_eq!(live["gateway"]["apiKey"], "fixture");assert!(!crate::agy_config::settings_path().exists());assert!(!crate::config::get_home_dir().join(".gemini/.env").exists());let row = state@@ -1573,22 +1577,11 @@ fn agy_deeplink_enabled_key_provider_stays_out_of_live_files() {.unwrap().unwrap();let launch = crate::services::provider::agy_direct::terminal_launch(&row).unwrap();- assert_eq!(- launch.env[0],- ("GEMINI_API_KEY", Some("fixture".to_string()))- );- let private: serde_json::Value = serde_json::from_slice(- &std::fs::read(- launch- .gemini_dir- .unwrap()- .join("antigravity-cli/settings.json"),- )- .unwrap(),+ let own: serde_json::Value = serde_json::from_slice(+ &std::fs::read(launch.gemini_dir.unwrap().join("config/config.json")).unwrap(),).unwrap();- assert_eq!(private["model"], "link-model");- assert_eq!(private["modelProvider"], "gemini");+ assert_eq!(own["gateway"]["apiKey"], "fixture");}#[test]diff --git a/src-tauri/src/live/floor.rs b/src-tauri/src/live/floor.rsindex e3dd28fb3..31ce124b7 100644--- a/src-tauri/src/live/floor.rs+++ b/src-tauri/src/live/floor.rs@@ -208,6 +208,22 @@ pub fn desktop_profile_floor(key: &str) -> bool {pub const DESKTOP_PROFILE_SEED: &[&str] =&["disableDeploymentModeChooser", "coworkEgressAllowedHosts"];+/// Antigravity `~/.gemini/config/config.json` 顶层的关键字段:Enterprise Gateway 的网关块+/// (地址、凭据、协议、请求头)和模型清单,各自整块属于供应商。同一个文件里的 `plugins`、+/// `sidecars`、`userSettings` 归 Antigravity 和用户,CC Switch 不碰。+///+/// agy CLI 1.5.20 和桌面版 2.36.0 都读这个位置(实测);官方文档写的+/// `~/.antigravity/settings.json` 两者都不读。+pub const AGY_FLOOR_TOP: &[&str] = &["gateway", "models"];++pub fn agy_floor_top(key: &str) -> bool {+ AGY_FLOOR_TOP.contains(&key)+}++/// Antigravity 的供应商独有字段(`config.json` 顶层):自签证书网关要的 CA 文件路径,+/// 用户也可能把它设成全局,所以切走时只删上一家带进来、值没被改过的。+pub const AGY_EXCLUSIVE_TOP: &[&str] = &["caCertPath"];+#[cfg(test)]mod tests {use super::*;diff --git a/src-tauri/src/live/project/agy.rs b/src-tauri/src/live/project/agy.rsnew file mode 100644index 000000000..048b3cc24--- /dev/null+++ b/src-tauri/src/live/project/agy.rs@@ -0,0 +1,323 @@+//! Antigravity 的直连投影:供应商行 → `~/.gemini/config/config.json` 的关键字段和独有字段。+//!+//! 第三方卡投影成 Enterprise Gateway:`gateway` 写地址、Key、协议和请求头,`models` 写这张卡+//! 限定的模型(没填就不写,agy 会向网关的 `/v1beta/models` 或 `/v1/models` 自己取列表)。+//! 官方登录卡什么都不投影:网关和 Google 登录互斥,清掉网关块,agy 就回到自己的登录。+//!+//! 行的形状沿用旧版(`env.GEMINI_API_KEY`、`env.GOOGLE_GEMINI_BASE_URL`),旧版同步过来照样+//! 能打开终端;网关独有的选项放在行的 `gateway` 对象里:+//!+//! ```json+//! { "env": { "GEMINI_API_KEY": "…", "GOOGLE_GEMINI_BASE_URL": "https://relay.example" },+//! "gateway": { "wireProtocol": "genai", "models": ["gemini-3.8-flash"],+//! "defaultModel": "gemini-3.8-flash", "customHeaders": {}, "caCertPath": "" } }+//! ```+//!+//! 旧卡 `config.model.name` 里的是显示名(`Gemini 3.1 Pro (High)`),网关只认模型 ID,不投影。++use serde_json::{json, Map, Value};++use crate::live::floor;+use crate::live::patch::json::{ClearScope, JsonPatch};+use crate::live::patch::KeyPath;++/// 没填地址的 Key 卡走 Google 自己的 Gemini API。+pub const GOOGLE_GEMINI_API_URL: &str = "https://generativelanguage.googleapis.com";++/// 网关协议:`genai`(Gemini 原生,agy 的默认)或 `openai`(Chat Completions)。+pub const WIRE_GENAI: &str = "genai";+pub const WIRE_OPENAI: &str = "openai";++/// agy 在网关模式下一律发 `Authorization: Bearer`;只认 `x-goog-api-key` 的 Gemini 中转+/// (包括 Google 自己的 API)靠这个头兜底。实测 agy 原样转发,不当作保留头丢掉。+const GOOG_API_KEY_HEADER: &str = "x-goog-api-key";++/// 一个供应商在 `config.json` 里拥有的键。+#[derive(Debug, Clone, Default, PartialEq)]+pub struct AgyProjection {+ /// 顶层关键字段(`gateway`、`models`)。官方登录卡为空。+ pub top: Map<String, Value>,+ /// 顶层独有字段(`caCertPath`)。+ pub exclusive: Map<String, Value>,+}++impl AgyProjection {+ /// 从供应商行取出网关设置。`official` 为真(官方登录卡)或者没有 Key 时投影为空。+ /// 行要先经 `agy_direct` 校验(字符串、单行)。+ pub fn of(settings: &Value, official: bool) -> Self {+ let env = settings.get("env");+ let Some(key) = env_text(env, "GEMINI_API_KEY").filter(|_| !official) else {+ return Self::default();+ };+ let options = settings.get("gateway").and_then(Value::as_object);+ let protocol = wire_protocol(options);+ let url = gateway_url(+ env_text(env, "GOOGLE_GEMINI_BASE_URL")+ .as_deref()+ .unwrap_or(GOOGLE_GEMINI_API_URL),+ );++ let mut gateway = Map::new();+ gateway.insert("enabled".into(), json!(true));+ gateway.insert("url".into(), json!(url));+ gateway.insert("apiKey".into(), json!(key));+ gateway.insert("wireProtocol".into(), json!(protocol));+ let headers = custom_headers(options, protocol, &key);+ if !headers.is_empty() {+ gateway.insert("customHeaders".into(), Value::Object(headers));+ }++ let mut top = Map::new();+ top.insert("gateway".into(), Value::Object(gateway));+ if let Some(models) = models_block(options) {+ top.insert("models".into(), models);+ }++ let mut exclusive = Map::new();+ if let Some(path) = option_text(options, "caCertPath") {+ exclusive.insert("caCertPath".into(), json!(path));+ }+ Self { top, exclusive }+ }++ /// 官方登录:不写网关。+ pub fn is_login(&self) -> bool {+ self.top.is_empty()+ }++ fn set_entries(&self) -> Vec<(KeyPath, Value)> {+ self.top+ .iter()+ .chain(&self.exclusive)+ .map(|(key, value)| (KeyPath::new(&[key]), value.clone()))+ .collect()+ }+}++/// 直连切换的补丁:清掉 live 里的关键字段、写目标的,再删掉 `prev`(live 现在对应的那家)+/// 带进来、值没被改过的独有字段。+pub fn direct_patch(prev: Option<&AgyProjection>, target: &AgyProjection) -> JsonPatch {+ let outgoing = prev+ .into_iter()+ .flat_map(|prev| &prev.exclusive)+ .map(|(key, value)| (KeyPath::new(&[key]), vec![value.clone()]));+ JsonPatch {+ clear: vec![ClearScope {+ parent: KeyPath::root(),+ is_floor: floor::agy_floor_top,+ }],+ set: target.set_entries(),+ remove_if: outgoing.collect(),+ ..JsonPatch::default()+ }+}++fn env_text(env: Option<&Value>, key: &str) -> Option<String> {+ trimmed(env?.get(key)?)+}++fn option_text(options: Option<&Map<String, Value>>, key: &str) -> Option<String> {+ trimmed(options?.get(key)?)+}++fn trimmed(value: &Value) -> Option<String> {+ value+ .as_str()+ .map(str::trim)+ .filter(|text| !text.is_empty())+ .map(str::to_string)+}++fn wire_protocol(options: Option<&Map<String, Value>>) -> &'static str {+ match option_text(options, "wireProtocol").as_deref() {+ Some(WIRE_OPENAI) => WIRE_OPENAI,+ _ => WIRE_GENAI,+ }+}++/// agy 自己在地址后面拼 `/v1/chat/completions` 或 `/v1beta/models/...`:用户照中转文档+/// 填了带版本的地址时去掉版本段,否则会拼成 `/v1/v1/...`。+pub fn gateway_url(raw: &str) -> String {+ let mut url = raw.trim().trim_end_matches('/').to_string();+ for suffix in ["/v1beta", "/v1"] {+ if let Some(stripped) = url.strip_suffix(suffix) {+ url = stripped.trim_end_matches('/').to_string();+ break;+ }+ }+ url+}++fn custom_headers(+ options: Option<&Map<String, Value>>,+ protocol: &str,+ key: &str,+) -> Map<String, Value> {+ let mut headers: Map<String, Value> = options+ .and_then(|options| options.get("customHeaders"))+ .and_then(Value::as_object)+ .into_iter()+ .flatten()+ .filter_map(|(name, value)| {+ let name = name.trim();+ let value = trimmed(value)?;+ (!name.is_empty()).then(|| (name.to_string(), json!(value)))+ })+ .collect();+ let has_goog_key = headers+ .keys()+ .any(|name| name.eq_ignore_ascii_case(GOOG_API_KEY_HEADER));+ if protocol == WIRE_GENAI && !has_goog_key {+ headers.insert(GOOG_API_KEY_HEADER.into(), json!(key));+ }+ headers+}++fn models_block(options: Option<&Map<String, Value>>) -> Option<Value> {+ let mut ids: Vec<String> = Vec::new();+ for id in options?+ .get("models")?+ .as_array()?+ .iter()+ .filter_map(trimmed)+ {+ if !ids.contains(&id) {+ ids.push(id);+ }+ }+ let first = ids.first()?.clone();+ let default = option_text(options, "defaultModel")+ .filter(|id| ids.contains(id))+ .unwrap_or(first);+ let list: Vec<Value> = ids.iter().map(|id| json!({ "modelId": id })).collect();+ Some(json!({ "defaultModelId": default, "list": list }))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::Path;++ fn relay(gateway: Value) -> Value {+ json!({+ "env": {"GEMINI_API_KEY": "fixture", "GOOGLE_GEMINI_BASE_URL": "https://relay.test/v1beta/"},+ "config": {"model": {"name": "Gemini 4 Argon (Medium)"}},+ "gateway": gateway,+ })+ }++ fn apply(patch: &JsonPatch, doc: Value) -> Value {+ let mut doc = doc;+ patch.apply_to(Path::new("config.json"), &mut doc).unwrap();+ doc+ }++ #[test]+ fn relay_projects_a_genai_gateway_with_goog_key_header() {+ let projection = AgyProjection::of(&relay(json!({})), false);+ assert_eq!(+ projection.top["gateway"],+ json!({+ "enabled": true,+ "url": "https://relay.test",+ "apiKey": "fixture",+ "wireProtocol": "genai",+ "customHeaders": {"x-goog-api-key": "fixture"},+ })+ );+ // 没限定模型就不写 models,让 agy 自己去网关取列表;显示名不投影。+ assert!(!projection.top.contains_key("models"));+ assert!(projection.exclusive.is_empty());+ }++ #[test]+ fn openai_protocol_keeps_user_headers_and_lists_models() {+ let projection = AgyProjection::of(+ &relay(json!({+ "wireProtocol": "openai",+ "models": [" a ", "b", "a", ""],+ "defaultModel": "b",+ "customHeaders": {"X-Team": "dev", "Empty": " "},+ "caCertPath": "/etc/ca.pem",+ })),+ false,+ );+ let gateway = &projection.top["gateway"];+ assert_eq!(gateway["wireProtocol"], "openai");+ assert_eq!(gateway["customHeaders"], json!({"X-Team": "dev"}));+ assert_eq!(+ projection.top["models"],+ json!({"defaultModelId": "b", "list": [{"modelId": "a"}, {"modelId": "b"}]})+ );+ assert_eq!(projection.exclusive["caCertPath"], "/etc/ca.pem");+ }++ #[test]+ fn default_model_falls_back_to_the_first_listed() {+ let projection = AgyProjection::of(+ &relay(json!({"models": ["x", "y"], "defaultModel": "z"})),+ false,+ );+ assert_eq!(projection.top["models"]["defaultModelId"], "x");+ }++ #[test]+ fn key_without_endpoint_uses_google_and_user_goog_header_wins() {+ let settings = json!({+ "env": {"GEMINI_API_KEY": "fixture"},+ "gateway": {"customHeaders": {"X-Goog-Api-Key": "other"}},+ });+ let gateway = &AgyProjection::of(&settings, false).top["gateway"];+ assert_eq!(gateway["url"], GOOGLE_GEMINI_API_URL);+ assert_eq!(gateway["customHeaders"], json!({"X-Goog-Api-Key": "other"}));+ }++ #[test]+ fn official_and_keyless_rows_project_to_login() {+ assert!(AgyProjection::of(&relay(json!({})), true).is_login());+ assert!(AgyProjection::of(&json!({"env": {}}), false).is_login());+ }++ #[test]+ fn gateway_url_strips_version_segments_once() {+ assert_eq!(gateway_url("https://a.test/v1/"), "https://a.test");+ assert_eq!(gateway_url("https://a.test/v1beta"), "https://a.test");+ assert_eq!(gateway_url("https://a.test/api/v1"), "https://a.test/api");+ assert_eq!(gateway_url("https://a.test/v1/v1"), "https://a.test/v1");+ }++ #[test]+ fn switching_replaces_only_gateway_models_and_owned_ca() {+ let live = json!({+ "plugins": {"p": 1},+ "gateway": {"enabled": true, "url": "https://old.test"},+ "models": {"list": []},+ "caCertPath": "/old/ca.pem",+ "userSettings": {"enableAdc": true},+ });+ let prev = AgyProjection::of(&relay(json!({"caCertPath": "/old/ca.pem"})), false);+ let target = AgyProjection::of(&relay(json!({"models": ["m"]})), false);+ let out = apply(&direct_patch(Some(&prev), &target), live);+ assert_eq!(out["plugins"], json!({"p": 1}));+ assert_eq!(out["userSettings"], json!({"enableAdc": true}));+ assert_eq!(out["gateway"]["url"], "https://relay.test");+ assert_eq!(out["models"]["list"], json!([{"modelId": "m"}]));+ assert!(out.get("caCertPath").is_none());+ // 关键字段原位改值,其余键顺序不变。+ let keys: Vec<&str> = out+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect();+ assert_eq!(keys, ["plugins", "gateway", "models", "userSettings"]);+ }++ #[test]+ fn switching_to_login_clears_gateway_but_keeps_a_user_changed_ca() {+ let live = json!({"gateway": {"enabled": true}, "models": {}, "caCertPath": "/mine.pem"});+ let prev = AgyProjection::of(&relay(json!({"caCertPath": "/old.pem"})), false);+ let out = apply(&direct_patch(Some(&prev), &AgyProjection::default()), live);+ assert_eq!(out, json!({"caCertPath": "/mine.pem"}));+ }+}diff --git a/src-tauri/src/live/project/mod.rs b/src-tauri/src/live/project/mod.rsindex 4f16ad739..21a0ffcc1 100644--- a/src-tauri/src/live/project/mod.rs+++ b/src-tauri/src/live/project/mod.rs@@ -3,6 +3,7 @@//! 投影器不读盘也不写盘,只给出「这个供应商要求哪些键是什么值」,再转成对应格式的//! 补丁交给引擎,以现有文件为底改写。+pub mod agy;pub mod claude;pub mod codex;pub mod gemini;diff --git a/src-tauri/src/services/provider/agy_direct.rs b/src-tauri/src/services/provider/agy_direct.rsindex 964be718d..be9db43dd 100644--- a/src-tauri/src/services/provider/agy_direct.rs+++ b/src-tauri/src/services/provider/agy_direct.rs@@ -1,5 +1,9 @@-//! Antigravity CLI 的卡片只用来打开终端,没有「启用」:官方卡按会话传 `--model`,第三方-//! Key 不进任何文件,只在 CC Switch 打开的终端里经环境变量传给 agy(见 `agy_config` 模块说明)。+//! Antigravity 的切换:第三方卡写成 Enterprise Gateway(`~/.gemini/config/config.json` 顶层的+//! `gateway` / `models`),官方卡清掉网关块回到 agy 自己的 Google 登录。CLI 和桌面版读同一个+//! 文件,桌面版只在启动时读,切换后要重启。规则同 Claude Code:只替换关键字段和独有字段,+//! 文件里其余内容(插件、sidecars、用户设置)不碰,不回填(见 `live::project::agy`)。+//!+//! 「打开终端」仍然可用:当前卡直接跟随文件,非当前的 Key 卡经环境变量按字段覆盖文件。use serde_json::{json, Value};@@ -7,12 +11,26 @@ use crate::agy_config;use crate::app_config::AppType;use crate::database::Database;use crate::error::AppError;+use crate::live::engine::LiveFile;+use crate::live::patch::json::JsonPatch;+use crate::live::project::agy::{direct_patch, AgyProjection, WIRE_GENAI, WIRE_OPENAI};+use crate::mode::operation::{AppWrite, FileChange, OperationReport};+use crate::mode::state::{op, PendingTarget};use crate::provider::Provider;use crate::services::agy_account::{keychain, AgyAccountManager};use crate::services::sync_protocol::sync_mutex;use crate::store::AppState;-use super::{lock_native_provider_operations, ProviderService};+use super::{lock_native_provider_operations, ProviderService, SwitchResult};++fn app() -> &'static str {+ AppType::Agy.as_str()+}++/// `~/.gemini/config/config.json`。网关块里有 Key,按 0600 写(agy 自己也是 0600)。+pub(crate) fn config_file() -> LiveFile {+ LiveFile::private(agy_config::gateway_config_path())+}pub(crate) fn is_official(provider: &Provider) -> bool {// Provider names are user editable and must never silently select OAuth.@@ -35,7 +53,9 @@ fn bound_account_id(provider: &Provider) -> Option<String> {.filter(|id| !id.trim().is_empty())}-/// 保存官方卡的新账号绑定时,同步 agy 的全局登录。只改模型等字段时保留当前登录。+/// 保存卡片。存的是当前卡时按新行重新投影 `config.json`(官方卡换了绑定账号时先换登录);+/// 还没有当前卡时(第一张卡)把它设成当前,和 Claude Code 新增第一个供应商一样。非当前卡+/// 只存行,不碰文件和登录。pub(crate) fn save_from_editor(state: &AppState,accounts: &AgyAccountManager,@@ -49,18 +69,146 @@ pub(crate) fn save_from_editor((binding.is_some() && keychain::supported()).then(|| sync_mutex().blocking_lock());let _guard = lock_native_provider_operations(state, &app);ProviderService::prepare_new_provider(&app, &mut provider)?;+ // 写文件前先校验,不合法的行连库都不进。+ projection(&provider)?;let previous = state.db.get_provider_by_id(&provider.id, &app)?;let binding_changed = binding != previous.as_ref().and_then(bound_account_id);-- state.db.save_provider(&app, &provider)?;- if !binding_changed {+ let current =+ crate::mode::current::provider_for(&state.db, &app, crate::mode::current::Purpose::Direct)?;+ let is_current = current.as_deref() == Some(provider.id.as_str());+ if !is_current && current.is_some() {+ state.db.save_provider(&app, &provider)?;return Ok(true);}- let written = tauri::async_runtime::block_on(switch_to_bound_account(accounts, &provider));+ state.db.save_provider(&app, &provider)?;+ let written = (|| {+ if binding_changed {+ tauri::async_runtime::block_on(switch_to_bound_account(accounts, &provider))?;+ }+ if is_current {+ reapply(&state.db, previous.as_ref(), &provider)?;+ } else {+ switch_to(&state.db, None, &provider)?;+ }+ Ok(())+ })();ProviderService::keep_row_if_written(state, &app, &provider.id, previous.as_ref(), written)}+/// 切到 `id`(供应商列表的「启用」)。官方卡绑了授权中心账号时,先换 agy 的登录(`accounts`+/// 为 `None` 的调用方只换文件):登录换不过去就整个不切,指针和文件都不动。+pub(crate) fn switch(+ state: &AppState,+ accounts: Option<&AgyAccountManager>,+ id: &str,+) -> Result<SwitchResult, AppError> {+ let app = AppType::Agy;+ let target = state+ .db+ .get_provider_by_id(id, &app)?+ .ok_or_else(|| AppError::Message(format!("供应商 {id} 不存在")))?;+ projection(&target)?;+ if let Some(accounts) = accounts {+ tauri::async_runtime::block_on(switch_to_bound_account(accounts, &target))?;+ }+ let previous =+ crate::mode::current::provider_for(&state.db, &app, crate::mode::current::Purpose::Direct)?+ .filter(|current| current != id)+ .map(|current| state.db.get_provider_by_id(¤t, &app))+ .transpose()+ .unwrap_or_else(|error| {+ // 上一家读不出来就和它不在库里一样处理:只少删它带进来的独有字段。+ log::warn!("读取 Antigravity 当前供应商失败,按没有上一家处理: {error}");+ None+ })+ .flatten();+ log::info!(+ "[SWITCH] agy 直连:{} → {id},写 config.json",+ previous.as_ref().map_or("(无)", |row| row.id.as_str())+ );+ switch_to(&state.db, previous.as_ref().or(Some(&target)), &target)?;+ Ok(SwitchResult::default())+}++/// 命令层的切换:拿着 agy 的切换锁,官方卡先换授权中心绑定的账号。+pub(crate) fn switch_with_login(+ state: &AppState,+ accounts: &AgyAccountManager,+ id: &str,+) -> Result<SwitchResult, AppError> {+ let _guard = lock_native_provider_operations(state, &AppType::Agy);+ switch(state, Some(accounts), id)+}++/// 供应商行投影成要写的网关设置。写之前校验,校验不过什么都不写。+pub(crate) fn projection(provider: &Provider) -> Result<AgyProjection, AppError> {+ let settings = live_settings(provider)?;+ Ok(AgyProjection::of(&settings, is_official(provider)))+}++/// 切到 `target`:同一个操作里写 `config.json`、改指针。`prev` 是 live 现在对应的那家+/// (直连指针那家),用来删它带进来的独有字段。+pub(crate) fn switch_to(+ db: &Database,+ prev: Option<&Provider>,+ target: &Provider,+) -> Result<OperationReport, AppError> {+ write(db, prev, target, Some(&target.id))+}++/// 把当前供应商重新投影到 `config.json`,不改指针。`prev` 是编辑前的那一版行。+pub(crate) fn reapply(+ db: &Database,+ prev: Option<&Provider>,+ target: &Provider,+) -> Result<OperationReport, AppError> {+ write(db, prev, target, None)+}++fn write(+ db: &Database,+ prev: Option<&Provider>,+ target: &Provider,+ pointer: Option<&str>,+) -> Result<OperationReport, AppError> {+ let target = projection(target)?;+ let prev = prev.and_then(|prev| projection(prev).ok());+ let patch = direct_patch(prev.as_ref(), &target);+ // 官方登录又没有文件时(没装过桌面版、没配过 MCP)不为了「什么都不写」建一个空文件。+ let untouched =+ target.is_login() && target.exclusive.is_empty() && !config_file().path.exists();+ run(+ db,+ if pointer.is_some() {+ op::SWITCH+ } else {+ op::APPLY+ },+ (!untouched).then_some(&patch),+ PendingTarget::pointer(pointer.map(str::to_string)),+ )+}++/// 用 `patch` 改写 `config.json`,和 `target` 在同一个操作里提交;`patch` 为空时只落定+/// 状态、不读也不写文件。+pub(crate) fn run(+ db: &Database,+ op: &str,+ patch: Option<&JsonPatch>,+ target: PendingTarget,+) -> Result<OperationReport, AppError> {+ let write = AppWrite::begin(db, app())?;+ let changes: Vec<FileChange<'_>> = patch+ .into_iter()+ .map(|patch| FileChange {+ file: config_file(),+ patch,+ })+ .collect();+ write.run(op, &changes, target)+}+/// 用授权中心的同一套切换逻辑,写入并核对 agy 的实际登录。pub(crate) async fn switch_to_bound_account(accounts: &AgyAccountManager,@@ -142,13 +290,95 @@ fn live_settings(provider: &Provider) -> Result<Value, AppError> {"Gemini config missing required field: GEMINI_API_KEY",));}+ validate_gateway_options(settings.get("gateway"), has_endpoint)?;Ok(settings)}-/// 在终端里启动这张卡要用的参数;Key 卡会先建好它的私有目录。+/// 行里 `gateway` 选项的形状:都是单行字符串(模型是字符串数组,请求头是字符串到字符串的+/// 对象)。agy 只认 `genai` / `openai`;OpenAI 协议必须填地址,Google 的默认地址不是+/// Chat Completions。+fn validate_gateway_options(options: Option<&Value>, has_endpoint: bool) -> Result<(), AppError> {+ let invalid = |what: &str| {+ AppError::localized(+ "agy.gateway.invalid",+ format!("Antigravity 网关设置无效:{what}"),+ format!("Invalid Antigravity gateway settings: {what}"),+ )+ };+ let Some(options) = options.filter(|value| !value.is_null()) else {+ return Ok(());+ };+ let options = options+ .as_object()+ .ok_or_else(|| invalid("gateway must be an object"))?;+ let single_line = |value: &Value, what: &str| match value {+ Value::Null => Ok(()),+ Value::String(text) if !text.chars().any(char::is_control) => Ok(()),+ _ => Err(invalid(what)),+ };+ for key in ["wireProtocol", "defaultModel", "caCertPath"] {+ if let Some(value) = options.get(key) {+ single_line(value, key)?;+ }+ }+ match options+ .get("wireProtocol")+ .and_then(Value::as_str)+ .map(str::trim)+ {+ None | Some("") | Some(WIRE_GENAI) => {}+ Some(WIRE_OPENAI) if has_endpoint => {}+ Some(WIRE_OPENAI) => return Err(invalid("the OpenAI protocol needs an endpoint URL")),+ Some(_) => return Err(invalid("wireProtocol must be genai or openai")),+ }+ match options.get("models") {+ None | Some(Value::Null) => {}+ Some(Value::Array(models)) => {+ for model in models {+ if !model.is_string() {+ return Err(invalid("models must be strings"));+ }+ single_line(model, "models")?;+ }+ }+ Some(_) => return Err(invalid("models must be a list")),+ }+ match options.get("customHeaders") {+ None | Some(Value::Null) => {}+ Some(Value::Object(headers)) => {+ for (name, value) in headers {+ if name.chars().any(|c| c.is_control() || c == ':') || !value.is_string() {+ return Err(invalid("customHeaders"));+ }+ single_line(value, "customHeaders")?;+ }+ }+ Some(_) => return Err(invalid("customHeaders must be an object")),+ }+ Ok(())+}++/// 在终端里启动这张卡要用的参数;Key 卡会先建好它的私有目录(带它自己的网关)。+///+/// 官方卡跑原生 `agy`:启用的是第三方卡时 `config.json` 开着网关,原生 `agy` 走的是网关,+/// 网关和 Google 登录又互斥,没法只给这一个终端关掉网关,所以要先启用这张官方卡。pub(crate) fn terminal_launch(provider: &Provider) -> Result<agy_config::AgyLaunch, AppError> {let settings = live_settings(provider)?;- agy_config::prepare_launch(&provider.id, &settings)+ let launch = agy_config::prepare_launch(&provider.id, &settings)?;+ if launch.gemini_dir.is_none() && agy_config::live_gateway_enabled() {+ return Err(AppError::localized(+ "agy.terminal.gateway_active",+ format!(+ "现在启用的是第三方卡,直接运行 agy 会走它的网关:要用官方登录,请先启用「{}」",+ provider.name+ ),+ format!(+ "A third-party card is in use, so agy runs through its gateway. Use \"{}\" first to run agy with your Google sign-in.",+ provider.name+ ),+ ));+ }+ Ok(launch)}/// 会话页的恢复命令如果指向某张 Key 卡的私有目录,返回那张卡和会话 ID,好按「打开终端」diff --git a/src-tauri/src/services/provider/live.rs b/src-tauri/src/services/provider/live.rsindex 7bbcb6649..9290ddacb 100644--- a/src-tauri/src/services/provider/live.rs+++ b/src-tauri/src/services/provider/live.rs@@ -484,10 +484,14 @@ pub(crate) fn write_live_for_state(super::grok_direct::reapply(state, Some(provider), provider)?;return Ok(());}- if matches!(app_type, AppType::Agy | AppType::Copilot) {- // Antigravity 的卡只作用于它打开的终端,全量同步不写真实 settings.json。Copilot 自带- // 模型卡只经「添加 / 编辑」写进 providers.json(文件里的条目归 Copilot,列表从文件读回),- // 全量同步不重写它;官方卡从不写文件。+ if matches!(app_type, AppType::Agy) {+ // Antigravity 同理:只替换 config.json 的网关块,不换登录。+ super::agy_direct::reapply(db, Some(provider), provider)?;+ return Ok(());+ }+ if matches!(app_type, AppType::Copilot) {+ // Copilot 自带模型卡只经「添加 / 编辑」写进 providers.json(文件里的条目归 Copilot,+ // 列表从文件读回),全量同步不重写它;官方卡从不写文件。return Ok(());}@@ -1374,8 +1378,15 @@ pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool} else {"custom"}- } else if matches!(app_type, AppType::Agy | AppType::Copilot) {- // Key 只在进程环境里,从不落盘:从 live 导入的一定是客户端自己的登录。+ } else if matches!(app_type, AppType::Agy) {+ // config.json 里有网关(带 Key)的导入成第三方卡,否则是 agy 自己的登录。+ if crate::agy_config::has_gateway_key(&provider.settings_config) {+ "custom"+ } else {+ "official"+ }+ } else if matches!(app_type, AppType::Copilot) {+ // 从 live 导入的一定是 Copilot 自己的登录。"official"} else {"custom"diff --git a/src-tauri/src/services/provider/mod.rs b/src-tauri/src/services/provider/mod.rsindex b3b67a36e..6a6f56554 100644--- a/src-tauri/src/services/provider/mod.rs+++ b/src-tauri/src/services/provider/mod.rs@@ -6322,8 +6322,10 @@ impl ProviderService {gemini_direct::switch_to(state.db.as_ref(), &provider)?;return Ok(true);}- // Antigravity 的卡只用来打开终端,添加不写任何文件。- AppType::Agy => return Ok(true),+ AppType::Agy => {+ agy_direct::switch_to(state.db.as_ref(), None, &provider)?;+ return Ok(true);+ }AppType::GrokBuild => {grok_direct::switch_to(state, None, &provider)?;return Ok(true);@@ -7232,11 +7234,8 @@ impl ProviderService {return Ok(());}- // For other apps: 本地记录、DB、代理路由任何一处指着它都不能删。Antigravity 没有- // 「启用」,旧版留下的直连指针不拦删除。- if !matches!(app_type, AppType::Agy)- && crate::mode::current::is_referenced(&state.db, &app_type, id)?- {+ // For other apps: 本地记录、DB、代理路由任何一处指着它都不能删。+ if crate::mode::current::is_referenced(&state.db, &app_type, id)? {return Err(AppError::Message("无法删除当前正在使用的供应商".to_string(),));@@ -7259,7 +7258,6 @@ impl ProviderService {/// 正被使用的照样不能删。fn delete_unreadable(state: &AppState, app_type: &AppType, id: &str) -> Result<(), AppError> {if !app_type.spec().additive- && !matches!(app_type, AppType::Agy)&& crate::mode::current::is_referenced(&state.db, app_type, id)?{return Err(AppError::Message(@@ -7499,13 +7497,10 @@ impl ProviderService {if app_type == AppType::Pi {return pi::enable(state, id);}- // Antigravity 的卡只作用于它打开的终端,没有「启用」(见 agy_config 模块说明)。+ // Antigravity:写 config.json 的网关块(见 agy_direct)。这条路径不换登录,官方卡的+ // 账号切换由命令层带着授权中心走 `agy_direct::switch_with_login`。if app_type == AppType::Agy {- return Err(AppError::localized(- "agy.switch.unsupported",- "Antigravity 的卡片不需要启用,用「打开终端」启动即可",- "Antigravity cards are not enabled; use Open terminal to start one",- ));+ return agy_direct::switch(state, None, id);}// Copilot CLI:官方卡只用来打开终端;自带模型卡的「切换」就是添加进 providers.json,// 不改 Copilot 自己的默认模型(见 copilot_config 模块说明)。