diff --git a/README.md b/README.md index 12d7726..cc6f445 100644 --- a/README.md +++ b/README.md @@ -72,10 +72,13 @@ node crates/wizard-gui/wizard-ui/node_modules/@tauri-apps/cli/tauri.js dev For a standalone local application (a faster debug build, signed ad hoc): ```sh -node crates/wizard-gui/wizard-ui/node_modules/@tauri-apps/cli/tauri.js build --debug --bundles app +node crates/wizard-gui/wizard-ui/node_modules/@tauri-apps/cli/tauri.js build --debug --bundles app --config '{"plugins":{"updater":{"endpoints":[]}}}' open "target/debug/bundle/macos/CoreInfra Wizard.app" ``` +The empty updater endpoint list disables update checks in this local bundle, so a +published release cannot replace the code you are testing. + Omit `--debug` for the release build described above. Neither command installs the bundle into `/Applications`. Local builds use the same saved account and proxy settings as the installed Wizard. Quit and reopen the bundle after rebuilding it. diff --git a/crates/wizard-core/src/agents/claude.rs b/crates/wizard-core/src/agents/claude.rs index 26c9cc0..3abfebc 100644 --- a/crates/wizard-core/src/agents/claude.rs +++ b/crates/wizard-core/src/agents/claude.rs @@ -105,12 +105,12 @@ fn mode_from_config(settings: &Value) -> RoutingMode { } pub fn get_backups() -> Result> { - BackupManager::get_backups(AgentKind::Claude) + BackupManager::new(AgentKind::Claude)?.get_backups() } pub fn restore_backup(id: u32) -> Result<()> { let _guard = PreparedAgent::Claude.lock()?; - BackupManager::load_backup(AgentKind::Claude, id) + BackupManager::new(AgentKind::Claude)?.load_backup(id) } /// `token` is ignored when disabled. diff --git a/crates/wizard-core/src/agents/claude_desktop.rs b/crates/wizard-core/src/agents/claude_desktop.rs index 3bcc22c..6a6d357 100644 --- a/crates/wizard-core/src/agents/claude_desktop.rs +++ b/crates/wizard-core/src/agents/claude_desktop.rs @@ -3,23 +3,23 @@ use super::{ detection::{self, AgentInfo, DesktopAgent}, }; use crate::{ - config_files::{changes::FileChange, json}, + config_files::{ + backups::{AgentKind, BackupManager}, + changes::FileChange, + json, + }, prepared_plan::{PreparedAgent, PreparedPlan, PreparedStep}, }; use anyhow::{Context as _, Result, ensure}; use serde::Serialize; use serde_json::{Value, json}; -use std::{path::PathBuf, sync::Mutex}; +use std::{ + path::{Path, PathBuf}, + sync::Mutex, +}; use wizard_settings::Settings; const HUB_URL: &str = "https://hub.coreinfra.ai/anthropic/api"; -const CONNECTION_KEYS: [&str; 5] = [ - "inferenceProvider", - "inferenceCredentialKind", - "inferenceGatewayBaseUrl", - "inferenceGatewayApiKey", - "inferenceGatewayAuthScheme", -]; pub(crate) static CONFIG_LOCK: Mutex<()> = Mutex::new(()); #[derive(Clone, Debug, Serialize, PartialEq, Eq)] @@ -89,30 +89,13 @@ fn has_hub_connection(config: &Value) -> bool { config["inferenceProvider"] == "gateway" && config["inferenceGatewayBaseUrl"] .as_str() - .is_some_and(|url| url.trim_end_matches('/') == HUB_URL) -} - -/// Profiles are not backed up, so a mode must not replace the user's own proxy or connection. -fn ensure_no_foreign_settings(config: &Value, mode: RoutingMode, proxy_url: &str) -> Result<()> { - if mode == RoutingMode::Disabled { - return Ok(()); - } - let set = |key: &str| config.get(key).is_some_and(|value| !value.is_null()); - ensure!( - !set("egressProxyPacUrl") - && (!set("egressProxyUrl") || config["egressProxyUrl"] == proxy_url), - "Remove the egress proxy from the selected Claude Desktop profile or select another profile: CoreInfra routing would replace it" - ); - // Claude selects its own account with the "anthropic" provider, which Hub may replace. - let own_connection = !has_hub_connection(config) - && CONNECTION_KEYS - .iter() - .any(|key| set(key) && !(*key == "inferenceProvider" && config[key] == "anthropic")); - ensure!( - mode != RoutingMode::Hub || !own_connection, - "Remove the inference provider from the selected Claude Desktop profile or select another profile: CoreInfra Hub would replace it" - ); - Ok(()) + .is_some_and(|url| { + // Manual setup also uses the Claude API alias for the same Hub gateway. + matches!( + url.trim_end_matches('/'), + HUB_URL | "https://hub.coreinfra.ai/claude/api" + ) + }) } /// Reads the token owned by the active routing mode without exposing the full profile. @@ -120,11 +103,72 @@ pub fn configured_token() -> Result> { Ok(read_routing()?.1.map(AgentToken::into_secret)) } +pub fn get_backups() -> Result> { + BackupManager::new(AgentKind::ClaudeDesktop)?.get_backups() +} + +pub fn prepare_restore_backup(id: u32) -> Result { + let _guard = PreparedAgent::ClaudeDesktop.lock()?; + prepare_restore_at( + &config_library()?, + &BackupManager::new(AgentKind::ClaudeDesktop)?, + id, + ) +} + +fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result { + let mut changes = manager.restore_changes(id)?; + // A restore also backs up the state it replaces. If the user has selected another + // profile since this backup, include that profile so the new backup is restorable. + let meta_path = dir.join("_meta.json"); + let current_meta = changes + .iter() + .find(|change| change.path() == &meta_path) + .context("Claude Desktop backup is missing profile metadata")?; + // Corrupt current metadata must not prevent recovery from a valid backup. + if let Ok(current_meta) = json::parse(current_meta.before()) + && let Ok(Some(current_id)) = applied_id(¤t_meta) + { + let current_path = dir.join(format!("{current_id}.json")); + if !changes.iter().any(|change| change.path() == ¤t_path) { + changes.push(FileChange::read(current_path)?); + } + } + let restored = |path: &Path| -> Result { + let change = changes + .iter() + .find(|change| change.path() == path) + .context("Claude Desktop backup is missing a configuration file")?; + json::parse(&change.after) + }; + let meta = restored(&dir.join("_meta.json"))?; + let proxy_enabled = if meta.get("hybridPointer").is_none_or(Value::is_null) + && let Some(id) = applied_id(&meta)? + { + let profile = restored(&dir.join(format!("{id}.json")))?; + profile["egressProxyUrl"] == format!("http://{}", wizard_proxy::ADDRESS) + && profile.get("egressProxyPacUrl").is_none_or(Value::is_null) + } else { + false + }; + let mut steps: Vec<_> = changes + .into_iter() + .map(|change| PreparedStep::ChangeFile { change }) + .collect(); + steps.push(PreparedStep::SetClaudeProxyEnabled { + enabled: proxy_enabled, + }); + Ok(PreparedPlan::new(PreparedAgent::ClaudeDesktop, steps)) +} + /// Hub reads the profile's key. Sub has no agent key; Wizard owns proxy credentials. fn read_routing() -> Result<(RoutingMode, Option)> { let _guard = PreparedAgent::ClaudeDesktop.lock()?; - let dir = config_library()?; + read_routing_at(&config_library()?) +} + +fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option)> { let meta = json::read(&dir.join("_meta.json"))?; let Some(id) = applied_id(&meta)? else { return Ok((RoutingMode::Disabled, None)); @@ -160,7 +204,10 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { ); let _guard = PreparedAgent::ClaudeDesktop.lock()?; - let dir = config_library()?; + prepare_routing_at(&config_library()?, mode, token) +} + +fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result { let mut meta = FileChange::read(dir.join("_meta.json"))?; let metadata = json::parse(&meta.after)?; let selected = applied_id(&metadata)?; @@ -170,8 +217,6 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { let mut preferences = FileChange::read(dir.with_file_name("claude_desktop_config.json"))?; let proxy_url = format!("http://{}", wizard_proxy::ADDRESS); - let current = json::parse(&config.after)?; - ensure_no_foreign_settings(¤t, mode, &proxy_url)?; ensure!( selected.is_some() || config.before().content().is_none(), "new Claude Desktop profile already exists; prepare again" @@ -197,54 +242,43 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { })?; } - // Wizard points every profile it configures at its proxy. - let managed = current["egressProxyUrl"] == proxy_url; - json::update(&mut config.after, |config| { - // Remove only CoreInfra's connection; another gateway belongs to the user and is not - // backed up. Claude ignores inference settings in the 1p mode that Sub selects. - let remove = mode != RoutingMode::Hub && has_hub_connection(config); - - let object = config - .as_object_mut() - .context("Claude Desktop configuration must be an object")?; - - if mode == RoutingMode::Hub { - object.insert("inferenceProvider".into(), json!("gateway")); - object.insert("inferenceCredentialKind".into(), json!("static")); - object.insert("inferenceGatewayBaseUrl".into(), json!(HUB_URL)); - object.insert("inferenceGatewayApiKey".into(), json!(token)); - object.insert("inferenceGatewayAuthScheme".into(), json!("x-api-key")); - } else if remove { - for key in CONNECTION_KEYS { - object.shift_remove(key); + if selected.is_some() || mode != RoutingMode::Disabled { + json::update(&mut config.after, |config| { + let object = config + .as_object_mut() + .context("Claude Desktop configuration must be an object")?; + + // The complete previous profile is backed up before applying this plan. + // Clear provider-specific credentials and proxy overrides before setting the mode. + object + .retain(|key, _| !key.starts_with("inference") && !key.starts_with("egressProxy")); + if mode == RoutingMode::Hub { + object.insert("inferenceProvider".into(), json!("gateway")); + object.insert("inferenceCredentialKind".into(), json!("static")); + object.insert("inferenceGatewayBaseUrl".into(), json!(HUB_URL)); + object.insert("inferenceGatewayApiKey".into(), json!(token)); + object.insert("inferenceGatewayAuthScheme".into(), json!("x-api-key")); } - } - - if mode == RoutingMode::Sub { - object.insert("disableAutoUpdates".into(), json!(true)); - } else if managed { - // Undo Sub's override only in a profile Wizard configured. - object.shift_remove("disableAutoUpdates"); - } - if mode != RoutingMode::Disabled { - object.insert("egressProxyUrl".into(), json!(proxy_url)); - object.shift_remove("egressProxyPacUrl"); - } else if managed { - object.shift_remove("egressProxyUrl"); - } - Ok(()) - })?; + if mode == RoutingMode::Sub { + object.insert("disableAutoUpdates".into(), json!(true)); + } else { + object.shift_remove("disableAutoUpdates"); + } - // Disabled returns a Wizard profile to the Claude account (1p), where sign-in works. - if mode != RoutingMode::Disabled || managed { - json::update(&mut preferences.after, |preferences| { - preferences["deploymentMode"] = - json!(if mode == RoutingMode::Hub { "3p" } else { "1p" }); + if mode != RoutingMode::Disabled { + object.insert("egressProxyUrl".into(), json!(proxy_url)); + } Ok(()) })?; } + // Disabled returns to the Claude account (1p), where sign-in works. + json::update(&mut preferences.after, |preferences| { + preferences["deploymentMode"] = json!(if mode == RoutingMode::Hub { "3p" } else { "1p" }); + Ok(()) + })?; + // Publish a newly created profile before selecting it. Keep unchanged steps too. Ok(PreparedPlan::new( PreparedAgent::ClaudeDesktop, @@ -264,29 +298,353 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { #[cfg(test)] mod tests { use super::*; + use crate::config_files::changes::FileSnapshot; + + struct Fixture { + root: tempfile::TempDir, + dir: PathBuf, + files: Vec, + } + + impl Fixture { + fn new(provider: &str) -> Result { + let root = tempfile::tempdir()?; + let dir = root.path().join("Claude-3p/configLibrary"); + std::fs::create_dir_all(&dir)?; + let id = uuid::Uuid::new_v4().to_string(); + let files = vec![ + dir.join(format!("{id}.json")), + dir.join("_meta.json"), + dir.with_file_name("claude_desktop_config.json"), + ]; + let contents = [ + json!({ + "inferenceProvider": provider, + "inferenceCredentialKind": "command", + "inferenceGatewayBaseUrl": "https://gateway.example/api", + "inferenceGatewayApiKey": "old-key", + "inferenceGatewayAuthScheme": "bearer", + "inferenceCredentialCommand": "old-command", + "inferenceBedrockRegion": "us-east-1", + "egressProxyUrl": "http://corp:3128", + "egressProxyPacUrl": "https://corp/proxy.pac", + "egressProxyAuth": "old-proxy-auth", + "disableAutoUpdates": true, + "managedMcpServers": {"example": {"url": "https://mcp.example"}}, + "autoModeEnabled": true, + }), + json!({"appliedId": id, "entries": [{"id": id, "name": "Manual"}]}), + json!({"deploymentMode": "3p", "unrelated": true}), + ]; + for (path, value) in files.iter().zip(contents) { + std::fs::write(path, serde_json::to_string_pretty(&value)?)?; + } + Ok(Self { root, dir, files }) + } + + fn manager(&self) -> BackupManager { + BackupManager::in_directory(AgentKind::ClaudeDesktop, self.root.path().join("backups")) + } + + fn snapshots(&self) -> Result> { + self.files + .iter() + .map(|path| FileSnapshot::read(path)) + .collect() + } + + fn apply(&self, plan: PreparedPlan, expected_proxy: bool) -> Result<()> { + let mut called = false; + plan.apply_with_backup( + Some(self.manager()), + |enabled| { + called = true; + assert_eq!(enabled, expected_proxy); + assert!(!self.manager().get_backups()?.is_empty()); + Ok(()) + }, + |_| panic!("unexpected Codex proxy change"), + )?; + assert!(called); + Ok(()) + } + } + + #[test] + fn foreign_connections_are_replaced_and_full_configuration_can_be_restored() -> Result<()> { + for provider in ["gateway", "bedrock", "vertex"] { + for mode in [RoutingMode::Hub, RoutingMode::Sub, RoutingMode::Disabled] { + let fixture = Fixture::new(provider)?; + let original = fixture.snapshots()?; + let plan = prepare_routing_at(&fixture.dir, mode, "new-token")?; + assert!(fixture.snapshots()? == original); + assert!(fixture.manager().get_backups()?.is_empty()); + fixture.apply(plan, mode != RoutingMode::Disabled)?; + assert_eq!(fixture.manager().get_backups()?.len(), 1); + let restored = fixture.manager().restore_changes(1)?; + // Include unchanged selection and preferences, not just the changed profile. + assert_eq!(restored.len(), 3); + for (path, snapshot) in fixture.files.iter().zip(&original) { + assert!( + restored + .iter() + .any(|change| change.path() == path && change.after == *snapshot) + ); + } + let config = json::read(&fixture.files[0])?; + assert_eq!( + config["managedMcpServers"], + json!({"example": {"url": "https://mcp.example"}}) + ); + assert_eq!(config["autoModeEnabled"], true); + assert!(config.get("inferenceCredentialCommand").is_none()); + assert!(config.get("inferenceBedrockRegion").is_none()); + assert!(config.get("egressProxyPacUrl").is_none()); + assert!(config.get("egressProxyAuth").is_none()); + assert_eq!(read_routing_at(&fixture.dir)?.0, mode); + if mode == RoutingMode::Hub { + assert_eq!(config["inferenceGatewayApiKey"], "new-token"); + assert_eq!(config["inferenceGatewayBaseUrl"], HUB_URL); + assert_eq!(config["inferenceCredentialKind"], "static"); + assert_eq!(config["inferenceGatewayAuthScheme"], "x-api-key"); + } else { + assert!( + config + .as_object() + .expect("test profile must be present") + .keys() + .all(|key| !key.starts_with("inference")) + ); + } + if mode == RoutingMode::Disabled { + assert!(config.get("egressProxyUrl").is_none()); + } else { + assert_eq!( + config["egressProxyUrl"], + format!("http://{}", wizard_proxy::ADDRESS) + ); + } + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 1)?, + false, + )?; + assert!(fixture.snapshots()? == original); + } + } + Ok(()) + } + + #[test] + fn backup_failure_prevents_configuration_and_proxy_changes() -> Result<()> { + let fixture = Fixture::new("gateway")?; + let original = fixture.snapshots()?; + // A file where the backup directory should be makes saving impossible. + std::fs::write(fixture.root.path().join("backups"), "blocked")?; + let plan = prepare_routing_at(&fixture.dir, RoutingMode::Hub, "new-token")?; + let result = plan.apply_with_backup( + Some(fixture.manager()), + |_| panic!("proxy must not change before the backup is saved"), + |_| panic!("unexpected Codex proxy change"), + ); + assert!(result.is_err()); + assert!(fixture.snapshots()? == original); + Ok(()) + } #[test] - fn user_proxy_and_connection_are_not_replaced() { - let proxy = "http://127.0.0.1:33787"; - let check = |config: Value, mode| ensure_no_foreign_settings(&config, mode, proxy); - let modes = [RoutingMode::Hub, RoutingMode::Sub]; - - for mode in modes { - assert!(check(json!({}), mode).is_ok()); - assert!(check(json!({"egressProxyUrl": proxy}), mode).is_ok()); - assert!(check(json!({"egressProxyUrl": "http://corp:3128"}), mode).is_err()); - assert!(check(json!({"egressProxyPacUrl": "http://corp/pac"}), mode).is_err()); - // Claude's own account and CoreInfra's gateway may be replaced. - assert!(check(json!({"inferenceProvider": "anthropic"}), mode).is_ok()); - let hub = json!({"inferenceProvider": "gateway", "inferenceGatewayBaseUrl": HUB_URL}); - assert!(check(hub, mode).is_ok()); + fn new_profile_can_be_removed_by_restoring_its_backup() -> Result<()> { + let fixture = Fixture::new("gateway")?; + for path in &fixture.files { + std::fs::remove_file(path)?; } - let gateway = json!({"inferenceProvider": "gateway", "inferenceGatewayApiKey": "user"}); - assert!(check(gateway.clone(), RoutingMode::Hub).is_err()); - // Sub leaves inference settings unchanged. - assert!(check(gateway, RoutingMode::Sub).is_ok()); - assert!(check(json!({"inferenceProvider": "bedrock"}), RoutingMode::Hub).is_err()); - let corp = json!({"egressProxyUrl": "http://corp:3128"}); - assert!(check(corp, RoutingMode::Disabled).is_ok()); + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, + true, + )?; + let meta = json::read(&fixture.files[1])?; + let created = fixture.dir.join(format!( + "{}.json", + applied_id(&meta)?.expect("test profile must be present") + )); + assert!(created.exists()); + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 1)?, + false, + )?; + assert!(!created.exists()); + assert!(fixture.files.iter().all(|path| !path.exists())); + assert_eq!(read_routing_at(&fixture.dir)?.0, RoutingMode::Disabled); + Ok(()) + } + + #[test] + fn restoring_after_selecting_another_profile_keeps_a_restorable_backup() -> Result<()> { + let fixture = Fixture::new("gateway")?; + let original = fixture.snapshots()?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, + true, + )?; + + let second_id = uuid::Uuid::new_v4().to_string(); + let second_path = fixture.dir.join(format!("{second_id}.json")); + let second_config = json!({"inferenceProvider": "bedrock"}); + std::fs::write(&second_path, second_config.to_string())?; + let mut meta = json::read(&fixture.files[1])?; + meta["appliedId"] = json!(second_id); + meta["entries"] + .as_array_mut() + .expect("profile entries") + .push(json!({"id": second_id, "name": "Second"})); + std::fs::write(&fixture.files[1], meta.to_string())?; + let before_restore = fixture.snapshots()?; + + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 1)?, + false, + )?; + assert!(fixture.snapshots()? == original); + assert_eq!(fixture.manager().get_backups()?.len(), 2); + + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 2)?, + false, + )?; + assert!(fixture.snapshots()? == before_restore); + assert_eq!(json::read(&second_path)?, second_config); + Ok(()) + } + + #[test] + fn restoring_recovers_corrupt_metadata_and_preserves_organization_selection() -> Result<()> { + for current_meta in [ + "{broken", + r#"{"hybridPointer":{"url":"https://org.example/config"}}"#, + ] { + let fixture = Fixture::new("gateway")?; + let original = fixture.snapshots()?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, + true, + )?; + std::fs::write(&fixture.files[1], current_meta)?; + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 1)?, + false, + )?; + assert!(fixture.snapshots()? == original); + let saved = fixture.manager().restore_changes(2)?; + assert!(saved.iter().any(|change| change.path() == &fixture.files[1] + && change.after.content() == Some(current_meta))); + if current_meta.starts_with("{\"hybridPointer\"") { + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 2)?, + false, + )?; + assert_eq!(std::fs::read_to_string(&fixture.files[1])?, current_meta); + } + } + Ok(()) + } + + #[test] + fn manual_edits_get_a_new_backup_and_restoring_local_proxy_enables_it() -> Result<()> { + let fixture = Fixture::new("gateway")?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, + true, + )?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Sub, "")?, + true, + )?; + assert_eq!(fixture.manager().get_backups()?.len(), 1); + let mut config = json::read(&fixture.files[0])?; + config["autoModeEnabled"] = json!(false); + std::fs::write(&fixture.files[0], config.to_string())?; + let edited = fixture.snapshots()?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Disabled, "")?, + false, + )?; + assert_eq!(fixture.manager().get_backups()?.len(), 2); + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 2)?, + true, + )?; + assert!(fixture.snapshots()? == edited); + Ok(()) + } + + #[test] + fn manually_configured_hub_supports_detection_and_mode_changes() -> Result<()> { + let directory = tempfile::tempdir()?; + let dir = directory.path().join("configLibrary"); + std::fs::create_dir(&dir)?; + let id = uuid::Uuid::new_v4().to_string(); + let meta = json!({"appliedId": id, "entries": [{"id": id, "name": "Manual"}]}); + std::fs::write(dir.join("_meta.json"), meta.to_string())?; + let preferences_path = dir.with_file_name("claude_desktop_config.json"); + let profile_path = dir.join(format!("{id}.json")); + + for url in [HUB_URL, "https://hub.coreinfra.ai/claude/api"] { + for suffix in ["", "/"] { + for mode in [RoutingMode::Hub, RoutingMode::Sub, RoutingMode::Disabled] { + let original = json!({ + "inferenceProvider": "gateway", + "inferenceCredentialKind": "static", + "inferenceGatewayBaseUrl": format!("{url}{suffix}"), + "inferenceGatewayApiKey": "manual-token", + "inferenceGatewayAuthScheme": "x-api-key", + "managedMcpServers": {"example": {"url": "https://mcp.example"}}, + "autoModeEnabled": true, + }); + std::fs::write(&profile_path, original.to_string())?; + std::fs::write(&preferences_path, r#"{"deploymentMode":"3p"}"#)?; + + let (detected, token) = read_routing_at(&dir)?; + assert_eq!(detected, RoutingMode::Hub); + assert_eq!( + token.map(AgentToken::into_secret).as_deref(), + Some("manual-token") + ); + + let plan = prepare_routing_at(&dir, mode, "wizard-token")?; + assert_eq!(json::read(&profile_path)?, original); + let changes: Vec<_> = plan + .steps + .into_iter() + .filter_map(|step| match step { + PreparedStep::ChangeFile { change } => Some(change), + PreparedStep::SetClaudeProxyEnabled { enabled } => { + assert_eq!(enabled, mode != RoutingMode::Disabled); + None + } + _ => panic!("unexpected Claude Desktop routing step"), + }) + .collect(); + FileChange::apply_all(&changes)?; + + let updated = json::read(&profile_path)?; + assert_eq!(updated["managedMcpServers"], original["managedMcpServers"]); + assert_eq!(updated["autoModeEnabled"], true); + assert_eq!(json::read(&dir.join("_meta.json"))?, meta); + assert_eq!(read_routing_at(&dir)?.0, mode); + if mode == RoutingMode::Hub { + assert_eq!(updated["inferenceGatewayBaseUrl"], HUB_URL); + assert_eq!(updated["inferenceGatewayApiKey"], "wizard-token"); + } else { + assert!( + updated + .as_object() + .expect("test profile must be present") + .keys() + .all(|key| !key.starts_with("inference")) + ); + } + } + } + } + Ok(()) } } diff --git a/crates/wizard-core/src/agents/codex.rs b/crates/wizard-core/src/agents/codex.rs index d72dce2..68355f9 100644 --- a/crates/wizard-core/src/agents/codex.rs +++ b/crates/wizard-core/src/agents/codex.rs @@ -100,14 +100,14 @@ fn mode_from_config(doc: &DocumentMut) -> RoutingMode { } pub fn get_backups() -> Result> { - BackupManager::get_backups(AgentKind::Codex) + BackupManager::new(AgentKind::Codex)?.get_backups() } /// Call from a Tokio blocking worker. Like a plan, restarts a running managed daemon, /// which may interrupt work. pub fn restore_backup(id: u32, settings: &Settings) -> Result<()> { let _guard = PreparedAgent::Codex.lock()?; - BackupManager::load_backup(AgentKind::Codex, id)?; + BackupManager::new(AgentKind::Codex)?.load_backup(id)?; let path = std::path::absolute(config_path()?)?; // Backups hold files only; the restored mode decides whether ChatGPT updates itself. #[cfg(target_os = "macos")] diff --git a/crates/wizard-core/src/config_files/backups.rs b/crates/wizard-core/src/config_files/backups.rs index 7cfe10e..c4f20f8 100644 --- a/crates/wizard-core/src/config_files/backups.rs +++ b/crates/wizard-core/src/config_files/backups.rs @@ -21,6 +21,7 @@ const STATE_VERSION: u32 = 1; pub enum AgentKind { Codex, Claude, + ClaudeDesktop, } impl AgentKind { @@ -28,9 +29,32 @@ impl AgentKind { /// (`~/.claude.json`, `ChatGPT`'s Preferences): their apps rewrite it constantly, and a /// restore would roll back unrelated state such as MCP servers or a proxy Wizard removed. pub(crate) fn backs_up(self, path: &Path) -> bool { + if self == Self::ClaudeDesktop { + let Some(parent) = path.parent() else { + return false; + }; + let name = path.file_name().and_then(|name| name.to_str()); + if parent.file_name().is_some_and(|name| name == "Claude-3p") { + return name == Some("claude_desktop_config.json"); + } + return parent + .file_name() + .is_some_and(|name| name == "configLibrary") + && parent + .parent() + .and_then(Path::file_name) + .is_some_and(|name| name == "Claude-3p") + && name.is_some_and(|name| { + name == "_meta.json" + || name.strip_suffix(".json").is_some_and(|id| { + uuid::Uuid::parse_str(id).is_ok_and(|uuid| uuid.to_string() == id) + }) + }); + } let names: &[&str] = match self { Self::Codex => &["config.toml", ".env"], Self::Claude => &["settings.json", "no-proxy.sh"], + Self::ClaudeDesktop => unreachable!(), }; path.file_name() .and_then(|name| name.to_str()) @@ -41,28 +65,43 @@ impl AgentKind { let name = match self { Self::Codex => "codex", Self::Claude => "claude", + Self::ClaudeDesktop => "claude_desktop", }; Ok(wizard_settings::paths::config_dir()? .join("backups") .join(name)) } - - fn ensure_directory(self) -> Result { - let directory = self.directory()?; - fs::create_dir_all(&directory)?; - #[cfg(unix)] - fs::set_permissions(&directory, Permissions::from_mode(0o700))?; - Ok(directory) - } } -pub struct BackupManager; +pub struct BackupManager { + agent: AgentKind, + directory: PathBuf, +} impl BackupManager { - pub fn get_backups(agent: AgentKind) -> Result> { - let directory = agent.directory()?; - let entries = match fs::read_dir(&directory) { + pub fn new(agent: AgentKind) -> Result { + Ok(Self { + agent, + directory: agent.directory()?, + }) + } + + #[cfg(test)] + pub(crate) fn in_directory(agent: AgentKind, directory: PathBuf) -> Self { + Self { agent, directory } + } + + fn ensure_directory(&self) -> Result<&Path> { + fs::create_dir_all(&self.directory)?; + #[cfg(unix)] + fs::set_permissions(&self.directory, Permissions::from_mode(0o700))?; + Ok(&self.directory) + } + + pub fn get_backups(&self) -> Result> { + let directory = &self.directory; + let entries = match fs::read_dir(directory) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(error) => return Err(error).context("failed to list backups"), @@ -84,7 +123,7 @@ impl BackupManager { if name != format!("{id}.json") { continue; } - let Ok(backup) = Backup::load(agent, id) else { + let Ok(backup) = Backup::load(&self.directory, id) else { continue; }; backups.push(backup); @@ -94,52 +133,64 @@ impl BackupManager { Ok(backups) } - pub fn apply_changes(agent: AgentKind, changes: &[FileChange]) -> Result<()> { - Self::create_backup_if_needed(agent, changes)?; + pub fn apply_changes(&self, changes: &[FileChange]) -> Result<()> { + self.create_backup_if_needed(changes)?; FileChange::apply_all(changes)?; - Self::save_last_written(agent, changes) + self.save_last_written(changes) } - pub fn create_backup_if_needed(agent: AgentKind, changes: &[FileChange]) -> Result<()> { + pub fn create_backup_if_needed(&self, changes: &[FileChange]) -> Result<()> { if changes.iter().all(|change| !change.is_changed()) { return Ok(()); } - State::load(agent)?.create_backup_if_needed(changes) + State::load(self)?.create_backup_if_needed(self, changes) } - pub fn save_last_written(agent: AgentKind, changes: &[FileChange]) -> Result<()> { + pub fn save_last_written(&self, changes: &[FileChange]) -> Result<()> { if changes.iter().all(|change| !change.is_changed()) { return Ok(()); } - let mut state = State::load(agent)?; + let mut state = State::load(self)?; state.last_written = Some( changes .iter() .map(|change| (change.path().clone(), change.after.clone())) .collect(), ); - state.save() + state.save(self) } - pub fn load_backup(agent: AgentKind, id: u32) -> Result<()> { - let backup = Backup::load(agent, id)?; + pub fn load_backup(&self, id: u32) -> Result<()> { + self.apply_changes(&self.restore_changes(id)?) + .context("failed to restore backup") + } + + pub(crate) fn restore_changes(&self, id: u32) -> Result> { + let backup = Backup::load(&self.directory, id)?; let mut changes = Vec::with_capacity(backup.files.len()); // Older backups may also hold app-owned state files. - for (path, snapshot) in backup.files.iter().filter(|(path, _)| agent.backs_up(path)) { + for (path, snapshot) in backup + .files + .iter() + .filter(|(path, _)| self.agent.backs_up(path)) + { let mut change = FileChange::read(path.clone())?; change.after = snapshot.clone(); changes.push(change); } - // Like a plan, back up only what the restore changes. - changes.retain(FileChange::is_changed); + // Desktop restores keep the profile, selection and deployment mode together. + // Other agents back up only what the restore changes. + if self.agent != AgentKind::ClaudeDesktop { + changes.retain(FileChange::is_changed); + } // Restore existing files first; delete files absent from the backup last. changes.sort_by_key(|change| matches!(change.after, FileSnapshot::Missing)); - Self::apply_changes(agent, &changes).context("failed to restore backup") + Ok(changes) } } @@ -161,13 +212,13 @@ impl State { last_written: None, } } - fn load(agent: AgentKind) -> Result { - let path = agent.directory()?.join("state.json"); + fn load(manager: &BackupManager) -> Result { + let path = manager.directory.join("state.json"); let snapshot = FileSnapshot::read(&path) .with_context(|| format!("failed to read backup state {}", path.display()))?; let Some(content) = snapshot.content() else { - return Ok(Self::default(agent)); + return Ok(Self::default(manager.agent)); }; let state: Self = serde_json::from_str(content) @@ -177,17 +228,17 @@ impl State { "unsupported backup state version" ); ensure!( - state.agent == agent, + state.agent == manager.agent, "backup state belongs to a different agent" ); Ok(state) } - fn save(&self) -> Result<()> { + fn save(&self, manager: &BackupManager) -> Result<()> { let mut content = serde_json::to_string_pretty(self) .map_err(|_| anyhow::anyhow!("failed to serialize backup state"))?; content.push('\n'); - let path = self.agent.ensure_directory()?.join("state.json"); + let path = manager.ensure_directory()?.join("state.json"); let mut change = FileChange::read(path)?; change.after = FileSnapshot::new(content, 0o600); @@ -198,7 +249,11 @@ impl State { self.next_backup_id = self.next_backup_id.strict_add(1); backup_id } - fn create_backup_if_needed(&mut self, changes: &[FileChange]) -> Result<()> { + fn create_backup_if_needed( + &mut self, + manager: &BackupManager, + changes: &[FileChange], + ) -> Result<()> { // A path may occur in multiple steps; keep its first original snapshot. let current_state: BTreeMap<&PathBuf, &FileSnapshot> = changes .iter() @@ -212,8 +267,8 @@ impl State { // Save the next ID first, so a failed state save can never reuse an existing backup's ID. let id = self.get_next_backup_id(); - self.save()?; - Backup::from_changes(id, changes).save(self.agent) + self.save(manager)?; + Backup::from_changes(id, changes).save(manager) } } @@ -239,9 +294,7 @@ impl Backup { .collect(), } } - fn load(agent: AgentKind, id: u32) -> Result { - let directory = agent.directory()?; - + fn load(directory: &Path, id: u32) -> Result { let path = directory.join(format!("{id}.json")); let snapshot = FileSnapshot::read(&path) .with_context(|| format!("failed to read backup {}", path.display()))?; @@ -260,12 +313,12 @@ impl Backup { Ok(backup) } - fn save(&self, agent: AgentKind) -> Result<()> { + fn save(&self, manager: &BackupManager) -> Result<()> { let mut content = serde_json::to_string_pretty(self) .map_err(|_| anyhow::anyhow!("failed to serialize backup"))?; content.push('\n'); - let directory = agent.ensure_directory()?; + let directory = manager.ensure_directory()?; let mut change = FileChange::read(directory.join(format!("{}.json", self.id)))?; // Another Wizard process may have used this ID; never replace its backup. diff --git a/crates/wizard-core/src/prepared_plan.rs b/crates/wizard-core/src/prepared_plan.rs index eaa528e..0d32cfe 100644 --- a/crates/wizard-core/src/prepared_plan.rs +++ b/crates/wizard-core/src/prepared_plan.rs @@ -134,7 +134,7 @@ impl PreparedPlan { } /// Call from a Tokio blocking worker. Adjacent file changes are applied as a group. - /// Codex/Claude backups cover the entire plan; there is no rollback on failure. + /// Agent backups cover the entire plan; there is no rollback on failure. pub fn apply(self) -> Result<()> { anyhow::ensure!( !self.steps.iter().any(|step| matches!( @@ -156,6 +156,25 @@ impl PreparedPlan { /// returns. Proxy callbacks receive only demand. pub fn apply_with_proxies( self, + set_claude_enabled: impl FnMut(bool) -> Result<()>, + set_codex_enabled: impl FnMut(bool) -> Result<()>, + ) -> Result<()> { + let backup = self.backup_agent().map(BackupManager::new).transpose()?; + self.apply_with_backup(backup, set_claude_enabled, set_codex_enabled) + } + + fn backup_agent(&self) -> Option { + match self.agent { + PreparedAgent::Codex => Some(AgentKind::Codex), + PreparedAgent::Claude => Some(AgentKind::Claude), + PreparedAgent::ClaudeDesktop => Some(AgentKind::ClaudeDesktop), + PreparedAgent::Pi | PreparedAgent::OpenCode => None, + } + } + + pub(crate) fn apply_with_backup( + self, + manager: Option, mut set_claude_enabled: impl FnMut(bool) -> Result<()>, mut set_codex_enabled: impl FnMut(bool) -> Result<()>, ) -> Result<()> { @@ -166,36 +185,34 @@ impl PreparedPlan { for step in &self.steps { if let PreparedStep::ChangeFile { change } | PreparedStep::PiApplyAuth { change, .. } = step - && change.is_changed() + && (change.is_changed() || matches!(self.agent, PreparedAgent::ClaudeDesktop)) { change.verify_before()?; } } - let backup_agent = match self.agent { - PreparedAgent::Codex => Some(AgentKind::Codex), - PreparedAgent::Claude => Some(AgentKind::Claude), - PreparedAgent::ClaudeDesktop | PreparedAgent::Pi | PreparedAgent::OpenCode => None, - }; - let backup = backup_agent.map(|agent| { + let backup = self.backup_agent().zip(manager).map(|(agent, manager)| { let changes: Vec<_> = self .steps .iter() - // Only changed files: restoring an untouched file would roll back unrelated edits. + // Desktop needs the profile, selection and deployment mode together, even + // when only its token changes. Other agents back up only changed files. .filter_map(|step| match step { PreparedStep::ChangeFile { change } - if change.is_changed() && agent.backs_up(change.path()) => + if (change.is_changed() || agent == AgentKind::ClaudeDesktop) + && agent.backs_up(change.path()) => { Some(change.clone()) } _ => None, }) .collect(); - (agent, changes) + (manager, changes) }); - if let Some((agent, changes)) = &backup { - BackupManager::create_backup_if_needed(*agent, changes) + if let Some((manager, changes)) = &backup { + manager + .create_backup_if_needed(changes) .context("failed to save backup before applying plan")?; } @@ -227,8 +244,9 @@ impl PreparedPlan { } } - if let Some((agent, changes)) = &backup { - BackupManager::save_last_written(*agent, changes) + if let Some((manager, changes)) = &backup { + manager + .save_last_written(changes) .context("plan applied, but saving backup state failed")?; } Ok(()) diff --git a/crates/wizard-gui/src/agents.rs b/crates/wizard-gui/src/agents.rs index 7b56cce..1ad0a86 100644 --- a/crates/wizard-gui/src/agents.rs +++ b/crates/wizard-gui/src/agents.rs @@ -64,6 +64,7 @@ pub(crate) async fn get_agent_backups(agent: BackupAgent) -> Result, tauri::async_runtime::spawn_blocking(move || match agent { BackupAgent::Codex => codex::get_backups(), BackupAgent::Claude => claude::get_backups(), + BackupAgent::ClaudeDesktop => claude_desktop::get_backups(), }) .await .context("backup listing task failed") @@ -284,11 +285,25 @@ pub(crate) async fn apply_direct_change( log::info!("received direct change: {name}"); let result = match change { + DirectChange::RestoreBackup { + agent: BackupAgent::ClaudeDesktop, + id, + } => { + let plan = tauri::async_runtime::spawn_blocking(move || { + claude_desktop::prepare_restore_backup(id) + }) + .await + .context("backup restore preparation task failed") + .flatten() + .map_err(|error| format!("{error:#}"))?; + return apply_agent_plan(plan, app).await; + } DirectChange::RestoreBackup { agent, id } => { let settings = settings::get_state(&app).map_err(|error| format!("{error:#}"))?; let result = tauri::async_runtime::spawn_blocking(move || match agent { BackupAgent::Codex => codex::restore_backup(id, &settings), BackupAgent::Claude => claude::restore_backup(id), + BackupAgent::ClaudeDesktop => unreachable!(), }) .await .context("backup restore task failed") diff --git a/crates/wizard-gui/src/updater.rs b/crates/wizard-gui/src/updater.rs index dcbd5cd..3e4615d 100644 --- a/crates/wizard-gui/src/updater.rs +++ b/crates/wizard-gui/src/updater.rs @@ -73,7 +73,15 @@ impl UpdateSources { } pub(crate) fn start(app: tauri::AppHandle, first_run: bool) -> Result<()> { - app.manage(UpdateSources::from_config(&app, first_run)?); + let sources = UpdateSources::from_config(&app, first_run)?; + let disabled = sources.endpoints.is_empty(); + app.manage(sources); + if disabled { + log::info!("application updates disabled: no endpoints configured"); + app.state::>>() + .notify(UpdateState::UpToDate); + return Ok(()); + } start_update(app.clone()); let state = Arc::clone(&app.state::>>()); @@ -218,6 +226,10 @@ async fn check_in_background(app: &tauri::AppHandle, state: &RevisionSignal Result> { let sources = app.state::(); + // An empty endpoint list explicitly disables updates for local test bundles. + if sources.endpoints.is_empty() { + return Ok(None); + } let mut last_error = None; for endpoint in &sources.endpoints { let result = if endpoint.hub { diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx index 18b8437..f9b5f51 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx @@ -371,7 +371,7 @@ export function AgentPage({ agents, page, proxy, account }: { const desktop = agents.claude_desktop; content = ( <> - + } /> Версия diff --git a/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx b/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx index fb80f51..b102d90 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx @@ -58,9 +58,10 @@ export function BackupDialog({ agent, onClose }: { return ( { if (!pending) onClose(); }}> - Резервные копии настроек {agent === "codex" ? "Codex" : "Claude Code"} + Резервные копии настроек {agent === "codex" ? "Codex" : agent === "claude_desktop" ? "Claude Desktop" : "Claude Code"} Сохранённые конфигурации перед изменениями Wizard. Это не история каждого переключения режима. + {agent === "claude_desktop" && " Восстановится весь сохранённый профиль, включая настройки MCP, выбор профиля и режим подключения. После восстановления перезапустите Claude Desktop."} {agent === "codex" && " Если фоновая служба Codex запущена, Wizard перезапустит её после восстановления. Это может прервать текущую работу."} diff --git a/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts b/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts index 7a8a28e..af42282 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts @@ -39,7 +39,7 @@ export function applyAgentPlan(plan: PreparedPlan): Promise { return invoke("apply_agent_plan", { plan }); } -export type BackupAgent = "codex" | "claude"; +export type BackupAgent = "codex" | "claude" | "claude_desktop"; export type Backup = { id: number;