diff --git a/crates/wizard-core/src/agents/claude_desktop.rs b/crates/wizard-core/src/agents/claude_desktop.rs index 1997ced..e2c961a 100644 --- a/crates/wizard-core/src/agents/claude_desktop.rs +++ b/crates/wizard-core/src/agents/claude_desktop.rs @@ -1,4 +1,6 @@ mod media; +mod models; +pub use models::Models; use super::{ AgentDetection, AgentToken, RoutingMode, @@ -21,7 +23,7 @@ use std::{ }; use wizard_settings::Settings; -const HUB_URL: &str = "https://hub.coreinfra.ai/anthropic/api"; +const HUB_URL: &str = "https://hub.coreinfra.ai/claude-desktop/api"; // Read-only compatibility with an unreleased configuration. Never bind this port. const RETIRED_PROXY_URL: &str = "http://127.0.0.1:33789"; pub(crate) static CONFIG_LOCK: Mutex<()> = Mutex::new(()); @@ -32,7 +34,7 @@ pub(crate) struct ClaudeDesktop { pub info: AgentInfo, pub routing_mode: RoutingMode, pub token: Option, - pub proxy_needs_apply: bool, + pub configuration_needs_apply: bool, pub media_needs_apply: bool, } @@ -49,19 +51,20 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { let configuration = || -> Result { let _guard = PreparedAgent::ClaudeDesktop.lock()?; let dir = config_library()?; - let (routing_mode, token, proxy_needs_apply) = read_profile(&dir)?; + let (routing_mode, token, configuration_needs_apply) = read_profile(&dir)?; let plan = prepare_with_media( &dir, &config_1p_path()?, None, settings.media.claude_desktop.is_some(), &media::Registration::for_wizard()?, + None, ); Ok(ClaudeDesktop { info, routing_mode, token, - proxy_needs_apply, + configuration_needs_apply, media_needs_apply: plan.map_or(true, |plan| !plan.info().is_empty()), }) }; @@ -154,7 +157,9 @@ fn has_hub_connection(config: &Value) -> bool { // 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" + HUB_URL + | "https://hub.coreinfra.ai/claude/api" + | "https://hub.coreinfra.ai/anthropic/api" ) }) } @@ -323,7 +328,13 @@ fn read_profile(dir: &Path) -> Result<(RoutingMode, Option, bool)> { let token = config["inferenceGatewayApiKey"] .as_str() .and_then(|s| AgentToken::new(s.to_owned())); - Ok((RoutingMode::Hub, token, proxy_needs_apply)) + let configuration_needs_apply = proxy_needs_apply + || config["inferenceGatewayBaseUrl"] + .as_str() + .map(|url| url.trim_end_matches('/')) + != Some(HUB_URL) + || Models::from_value(&config["inferenceModels"]).is_none(); + Ok((RoutingMode::Hub, token, configuration_needs_apply)) } else { Ok((RoutingMode::Disabled, None, false)) } @@ -332,18 +343,24 @@ fn read_profile(dir: &Path) -> Result<(RoutingMode, Option, bool)> { /// Prepare a local profile update without writing files or restarting Claude. Hub writes `token` /// to the profile; Hub and Sub enable local proxy demand; Disabled ignores it. /// `media`: whether Wizard holds a media grant for Claude Desktop. -pub fn prepare_routing(mode: RoutingMode, token: &str, media: bool) -> Result { - prepare_configuration(Some((mode, token)), media) +pub fn prepare_routing( + mode: RoutingMode, + token: &str, + media: bool, + models: Option<&Models>, +) -> Result { + prepare_configuration(Some((mode, token)), media, models) } /// Reconcile media in the current deployment without changing inference or proxy settings. pub fn prepare_media(enabled: bool) -> Result { - prepare_configuration(None, enabled) + prepare_configuration(None, enabled, None) } fn prepare_configuration( routing: Option<(RoutingMode, &str)>, media: bool, + models: Option<&Models>, ) -> Result { let _guard = PreparedAgent::ClaudeDesktop.lock()?; @@ -353,6 +370,7 @@ fn prepare_configuration( routing, media, &media::Registration::for_wizard()?, + models, ) } @@ -369,6 +387,7 @@ fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result, media_grant: bool, media: &media::Registration, + models: Option<&Models>, ) -> Result { let mut meta = FileChange::read(dir.join("_meta.json"))?; let metadata = json::parse(&meta.after)?; @@ -440,6 +460,12 @@ fn prepare_with_media( object.insert("inferenceGatewayBaseUrl".into(), json!(HUB_URL)); object.insert("inferenceGatewayApiKey".into(), json!(token)); object.insert("inferenceGatewayAuthScheme".into(), json!("x-api-key")); + object.insert( + "inferenceModels".into(), + models + .context("Каталог моделей Claude Desktop не загружен")? + .value()?, + ); } if mode == RoutingMode::Sub { @@ -502,6 +528,13 @@ mod tests { media::Registration::with_headers(dir.join("media-claude-desktop-headers.json")) } + pub(super) fn fixture_models() -> Models { + Models::from_value(&json!([ + {"name":"claude-sonnet-5", "labelOverride":"Claude Sonnet 5"}, + {"name":"claude-coreinfra-cn-3", "labelOverride":"GLM 5.3", "behavesAs":"claude-sonnet-4-6", "maxEffort":"max"} + ])).expect("valid model fixture") + } + #[test] fn first_launch_needs_only_precreated_configuration() -> Result<()> { for mode in [RoutingMode::Hub, RoutingMode::Sub] { @@ -528,6 +561,8 @@ mod tests { ); if mode == RoutingMode::Sub { assert!(profile.get("inferenceGatewayApiKey").is_none()); + } else { + assert_eq!(profile["inferenceModels"], fixture_models().value()?); } activated = true; Ok(()) @@ -579,6 +614,7 @@ mod tests { "inferenceGatewayAuthScheme": "bearer", "inferenceCredentialCommand": "old-command", "inferenceBedrockRegion": "us-east-1", + "inferenceModels": ["old-model"], "egressProxyUrl": "http://corp:3128", "egressProxyPacUrl": "https://corp/proxy.pac", "egressProxyAuth": "old-proxy-auth", @@ -649,6 +685,7 @@ mod tests { Some((mode, "token")), media, ®istration, + Some(&fixture_models()), ) }; let media_step = |plan: &PreparedPlan| { @@ -734,11 +771,12 @@ mod tests { Some((RoutingMode::Hub, "token")), grant, ®istration, + Some(&fixture_models()), ) }; let media_needs_apply = |grant| -> Result { Ok( - !prepare_with_media(&fixture.dir, &config_1p, None, grant, ®istration)? + !prepare_with_media(&fixture.dir, &config_1p, None, grant, ®istration, None)? .info() .is_empty(), ) @@ -853,6 +891,7 @@ mod tests { Some((mode, "token")), grant, ®istration, + Some(&fixture_models()), ) }; @@ -864,7 +903,7 @@ mod tests { )?; let media_needs_apply = |grant| -> Result { Ok( - !prepare_with_media(&fixture.dir, &config_1p, None, grant, ®istration)? + !prepare_with_media(&fixture.dir, &config_1p, None, grant, ®istration, None)? .info() .is_empty(), ) @@ -974,8 +1013,9 @@ mod tests { .root .path() .join("Claude/claude_desktop_config.json"); - let prepare = - |grant| prepare_with_media(&fixture.dir, &config_1p, None, grant, ®istration); + let prepare = |grant| { + prepare_with_media(&fixture.dir, &config_1p, None, grant, ®istration, None) + }; for enable in [true, false] { let plan = prepare(enable)?; assert!(!plan.info().is_empty()); @@ -1042,6 +1082,8 @@ mod tests { assert_eq!(config["inferenceGatewayBaseUrl"], HUB_URL); assert_eq!(config["inferenceCredentialKind"], "static"); assert_eq!(config["inferenceGatewayAuthScheme"], "x-api-key"); + assert_eq!(config["inferenceModels"], fixture_models().value()?); + assert!(!read_profile(&fixture.dir)?.2); } else { assert!( config @@ -1256,6 +1298,75 @@ mod tests { Ok(()) } + #[test] + fn invalid_model_catalog_requires_reapply() -> Result<()> { + let fixture = Fixture::new("gateway")?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, + true, + )?; + let baseline = json::read(&fixture.files[0])?; + assert!(!read_profile(&fixture.dir)?.2); + for models in [Value::Null, json!([]), json!(["invalid-model"])] { + let mut config = baseline.clone(); + config["inferenceModels"] = models; + std::fs::write(&fixture.files[0], config.to_string())?; + assert!(read_profile(&fixture.dir)?.2); + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, + true, + )?; + assert_eq!(json::read(&fixture.files[0])?, baseline); + assert!(!read_profile(&fixture.dir)?.2); + } + Ok(()) + } + + #[test] + fn catalog_refresh_preserves_mcp_and_a_missing_catalog_changes_no_files() -> Result<()> { + let fixture = Fixture::new("gateway")?; + let config_1p = fixture + .root + .path() + .join("Claude/claude_desktop_config.json"); + let registration = registration(&fixture.dir)?; + let prepare = |models: Option<&Models>| { + prepare_with_media( + &fixture.dir, + &config_1p, + Some((RoutingMode::Hub, "selected-token")), + true, + ®istration, + models, + ) + }; + let original = fixture.snapshots()?; + assert!(prepare(None).is_err()); + assert!(fixture.snapshots()? == original); + fixture.apply(prepare(Some(&fixture_models()))?, true)?; + let before = json::read(&fixture.files[0])?; + let updated_models = Models::from_value(&json!([ + {"name":"claude-coreinfra-cn-3", "labelOverride":"Updated GLM", "behavesAs":"claude-sonnet-4-6", "maxEffort":"high"} + ])).expect("updated catalog"); + fixture.apply(prepare(Some(&updated_models))?, true)?; + let after = json::read(&fixture.files[0])?; + assert_eq!(after["inferenceModels"], updated_models.value()?); + assert_eq!(after["inferenceGatewayApiKey"], "selected-token"); + assert_eq!(after["managedMcpServers"], before["managedMcpServers"]); + assert_eq!( + after["allowedPluginMarketplaces"], + before["allowedPluginMarketplaces"] + ); + assert_eq!(after["managedMcpServers"][1]["name"], "coreinfra_media"); + assert!(!read_profile(&fixture.dir)?.2); + let repeated = prepare(Some(&updated_models))?; + assert!(repeated.steps().iter().all(|step| match step { + PreparedStep::ChangeFile { change } => !change.is_changed(), + _ => true, + })); + Ok(()) + } + #[test] fn manually_configured_hub_supports_detection_and_mode_changes() -> Result<()> { let directory = tempfile::tempdir()?; @@ -1267,7 +1378,11 @@ mod tests { 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 url in [ + HUB_URL, + "https://hub.coreinfra.ai/claude/api", + "https://hub.coreinfra.ai/anthropic/api", + ] { for suffix in ["", "/"] { for mode in [RoutingMode::Hub, RoutingMode::Sub, RoutingMode::Disabled] { let original = json!({ @@ -1282,9 +1397,9 @@ mod tests { std::fs::write(&profile_path, original.to_string())?; std::fs::write(&preferences_path, r#"{"deploymentMode":"3p"}"#)?; - let (detected, token, proxy_needs_apply) = read_profile(&dir)?; + let (detected, token, configuration_needs_apply) = read_profile(&dir)?; assert_eq!(detected, RoutingMode::Hub); - assert!(!proxy_needs_apply); + assert!(configuration_needs_apply); assert_eq!( token.map(AgentToken::into_secret).as_deref(), Some("manual-token") @@ -1317,6 +1432,8 @@ mod tests { if mode == RoutingMode::Hub { assert_eq!(updated["inferenceGatewayBaseUrl"], HUB_URL); assert_eq!(updated["inferenceGatewayApiKey"], "wizard-token"); + assert_eq!(updated["inferenceModels"], fixture_models().value()?); + assert!(!read_profile(&dir)?.2); } else { assert!( updated diff --git a/crates/wizard-core/src/agents/claude_desktop/models.rs b/crates/wizard-core/src/agents/claude_desktop/models.rs new file mode 100644 index 0000000..73c053c --- /dev/null +++ b/crates/wizard-core/src/agents/claude_desktop/models.rs @@ -0,0 +1,164 @@ +//! Only model metadata is imported from Hub; connection settings and MCP stay local. +use anyhow::{Result, anyhow, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashSet; + +const MODELS_URL: &str = "https://hub.coreinfra.ai/claude-desktop/config"; + +#[derive(Deserialize, Serialize)] +#[serde(transparent)] +pub struct Models(Vec); + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct Model { + name: String, + #[serde(skip_serializing_if = "Option::is_none")] + label_override: Option, + #[serde(skip_serializing_if = "Option::is_none")] + behaves_as: Option, + #[serde(skip_serializing_if = "Option::is_none")] + max_effort: Option, + #[serde(rename = "supports1m", skip_serializing_if = "Option::is_none")] + supports_1m: Option, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "lowercase")] +enum Effort { + Low, + Medium, + High, + XHigh, + Max, +} + +impl Models { + pub async fn fetch(token: &str) -> Result { + let client = crate::hub::client() + .map_err(|_| anyhow!("Не удалось создать клиент каталога Claude Desktop"))?; + Self::fetch_from(&client, MODELS_URL, token).await + } + + async fn fetch_from(client: &reqwest::Client, url: &str, token: &str) -> Result { + let response = client + .get(url) + .header("x-api-key", token) + .send() + .await + .map_err(|_| { + anyhow!("Не удалось загрузить модели Claude Desktop. Попробуйте ещё раз.") + })?; + ensure!( + response.status().is_success(), + "Не удалось загрузить модели Claude Desktop (HTTP {})", + response.status() + ); + let bytes = response + .bytes() + .await + .map_err(|_| anyhow!("Не удалось прочитать каталог Claude Desktop"))?; + Self::parse(&bytes) + } + + fn parse(bytes: &[u8]) -> Result { + #[derive(Deserialize)] + struct Catalog { + #[serde(rename = "inferenceModels")] + models: Models, + } + let catalog: Catalog = serde_json::from_slice(bytes) + .map_err(|_| anyhow!("Hub вернул некорректный каталог Claude Desktop"))?; + ensure!( + catalog.models.valid(), + "Hub вернул пустой или некорректный каталог Claude Desktop" + ); + Ok(catalog.models) + } + + fn valid(&self) -> bool { + let mut ids = HashSet::new(); + !self.0.is_empty() + && self + .0 + .iter() + .all(|model| !model.name.trim().is_empty() && ids.insert(&model.name)) + } + + pub(super) fn from_value(value: &Value) -> Option { + serde_json::from_value::(value.clone()) + .ok() + .filter(Self::valid) + } + + pub(super) fn value(&self) -> Result { + ensure!(self.valid(), "Каталог моделей Claude Desktop не загружен"); + Ok(serde_json::to_value(self)?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + #[test] + fn imports_only_model_metadata_and_rejects_unusable_catalogs() -> Result<()> { + let models = Models::parse(&serde_json::to_vec(&json!({ + "inferenceModels": [{"name":"claude-coreinfra-cn-3", "labelOverride":"GLM", "behavesAs":"claude-sonnet-4-6", "maxEffort":"max", "command":"ignored"}], + "inferenceGatewayApiKey":"not-the-selected-key", "managedMcpServers":[{"command":"ignored"}] + }))?)?; + assert_eq!( + models.value()?, + json!([{"name":"claude-coreinfra-cn-3", "labelOverride":"GLM", "behavesAs":"claude-sonnet-4-6", "maxEffort":"max"}]) + ); + for invalid in [ + json!([]), + json!(["stale-model"]), + json!([{"name":""}]), + json!([{"name":"a"},{"name":"a"}]), + json!([{"name":"a","maxEffort":"unknown"}]), + ] { + assert!( + Models::parse(&serde_json::to_vec(&json!({"inferenceModels":invalid}))?).is_err() + ); + } + Ok(()) + } + + #[tokio::test] + async fn fetch_sends_the_agent_key_and_rejects_http_errors_and_redirects() -> Result<()> { + let _ = crate::hub::install_crypto_provider(); + let client = crate::hub::client().map_err(|_| anyhow!("test client"))?; + for status in [200, 401, 503, 302] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}/claude-desktop/config", listener.local_addr()?); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await?; + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + let mut byte = [0]; + stream.read_exact(&mut byte).await?; + request.push(byte[0]); + } + let body = r#"{"inferenceModels":[{"name":"claude-sonnet-5"}]}"#; + stream.write_all(format!("HTTP/1.1 {status} Test\r\nLocation: http://127.0.0.1:9/\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await?; + Ok::<_, anyhow::Error>(String::from_utf8(request)?) + }); + let result = Models::fetch_from(&client, &url, "fixture-key").await; + let request = server.await??; + assert!(request.starts_with("GET /claude-desktop/config ")); + assert!(request.contains("x-api-key: fixture-key\r\n")); + if status == 200 { + assert_eq!(result?.value()?, json!([{"name":"claude-sonnet-5"}])); + } else { + let error = result.err().expect("HTTP failure").to_string(); + assert!(error.contains(&status.to_string())); + assert!(!error.contains("fixture-key")); + } + } + Ok(()) + } +} diff --git a/crates/wizard-gui/src/agents.rs b/crates/wizard-gui/src/agents.rs index 57749e1..3662ed8 100644 --- a/crates/wizard-gui/src/agents.rs +++ b/crates/wizard-gui/src/agents.rs @@ -255,6 +255,20 @@ pub(crate) async fn prepare_agent_change( let reprepare_token = (!token.is_empty()).then(|| token.clone()); + // Fetch before taking the file lock or preparing changes. A failed fetch leaves the profile intact. + let desktop_models = if matches!( + change, + AgentChange::ClaudeDesktopSetRouting(RoutingMode::Hub) + ) { + Some( + claude_desktop::Models::fetch(&token) + .await + .map_err(|error| format!("{error:#}"))?, + ) + } else { + None + }; + // Plans contain credentials: never log the returned value. let plan = tauri::async_runtime::spawn_blocking(move || match change { AgentChange::CodexSetRouting(mode) => { @@ -267,7 +281,8 @@ pub(crate) async fn prepare_agent_change( ), AgentChange::ClaudeDesktopSetRouting(mode) => { let media = media.unwrap_or(settings.media.claude_desktop.is_some()); - let mut plan = claude_desktop::prepare_routing(mode, &token, media)?; + let mut plan = + claude_desktop::prepare_routing(mode, &token, media, desktop_models.as_ref())?; plan.restart_desktop( wizard_core::agents::desktop_install::DesktopApp::Claude, settings.last_paths.claude_desktop.as_deref(), diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx index f0d17ed..bfab5d2 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx @@ -36,7 +36,9 @@ export function AgentConnectionPanel({ agent, agents, account, onBack }: { const choice = choices.find(choice => choice.id === agent)!; const proxyAgent = agent === "claude_desktop" || (agent === "codex" && agents.codex.status === "found" && agents.codex.data.desktop.status === "found"); const needsApply = detection.status === "found" && detection.data.routing_mode !== "disabled" && - (("proxy_needs_apply" in detection.data && detection.data.proxy_needs_apply) || (proxyAgent && proxy.proxy?.enabled === false)); + (("proxy_needs_apply" in detection.data && detection.data.proxy_needs_apply) || + ("configuration_needs_apply" in detection.data && detection.data.configuration_needs_apply) || + (proxyAgent && proxy.proxy?.enabled === false)); const errors = detection.status === "error" ? [detection.data] : agent === "codex" && agents.codex.status === "found" ? [agents.codex.data.cli, agents.codex.data.desktop].flatMap(part => part.status === "error" ? [part.data] : []) : []; diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx index cedba45..84ad32f 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx @@ -341,7 +341,7 @@ export function AgentPage({ editing needsApply={ desktop.data.routing_mode !== "disabled" && - (desktop.data.proxy_needs_apply || + (desktop.data.configuration_needs_apply || (!proxyStartup.starting && proxy.proxy?.enabled === false)) } agent="claude_desktop" 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 6a7db8c..8eadb0d 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts @@ -118,7 +118,7 @@ export type ClaudeDesktop = { routing_mode: RoutingMode; // CoreInfra token from the agent's configuration. Secret: never log or persist it. token: string | null; - proxy_needs_apply: boolean; + configuration_needs_apply: boolean; media_needs_apply: boolean; }; diff --git a/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx b/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx index 0597307..5eb8bb0 100644 --- a/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx +++ b/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx @@ -49,6 +49,7 @@ export function OverviewAgents({ account, agents }: { const found = detection.status === "found"; const error = hasAgentDetectionError(detection); const needsApply = found && (("proxy_needs_apply" in detection.data && detection.data.proxy_needs_apply) || + ("configuration_needs_apply" in detection.data && detection.data.configuration_needs_apply) || ("media_needs_apply" in detection.data && detection.data.media_needs_apply)); const name = agentPageNames[id]; const status = error ? "Не удалось проверить" : !found ? "Не установлен" diff --git a/crates/wizard-gui/wizard-ui/src/preview/mocks.ts b/crates/wizard-gui/wizard-ui/src/preview/mocks.ts index 394bfc7..6da398f 100644 --- a/crates/wizard-gui/wizard-ui/src/preview/mocks.ts +++ b/crates/wizard-gui/wizard-ui/src/preview/mocks.ts @@ -113,6 +113,7 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo status: "found", data: { ...routing, + configuration_needs_apply: false, media_needs_apply: false, path: "/Applications/Claude.app", version: detectedVersion.claude, @@ -563,7 +564,7 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo next.claude_desktop = { status: "found", data: { - ...(next.claude_desktop.status === "found" ? next.claude_desktop.data : unconfigured), + ...(next.claude_desktop.status === "found" ? next.claude_desktop.data : { ...unconfigured, configuration_needs_apply: false }), media_needs_apply: false, path: release(desktop).path, version: versions[desktop], @@ -697,7 +698,7 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo ...agents.value, [plan.agent]: { ...detection, - data: { ...detection.data, routing_mode: plan.mode, token: plan.token, proxy_needs_apply: false, ...(plan.agent === "claude" && { media_needs_apply: false }) }, + data: { ...detection.data, routing_mode: plan.mode, token: plan.token, proxy_needs_apply: false, ...(plan.agent === "claude_desktop" && { configuration_needs_apply: false }), ...(plan.agent === "claude" && { media_needs_apply: false }) }, }, }); return; diff --git a/crates/wizard-gui/wizard-ui/src/test/flows.test.tsx b/crates/wizard-gui/wizard-ui/src/test/flows.test.tsx index cb55545..0f465d8 100644 --- a/crates/wizard-gui/wizard-ui/src/test/flows.test.tsx +++ b/crates/wizard-gui/wizard-ui/src/test/flows.test.tsx @@ -229,6 +229,26 @@ it("remembers declining the default media offer while switching Claude Desktop a expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled(); }); +it("migrates an outdated Claude Desktop configuration without changing the selected mode", async () => { + const user = userEvent.setup(); + launch("all_agents", "/agents/claude-desktop", ({ agents }) => { + const desktop = agents.value.claude_desktop; + if (desktop.status !== "found") throw new Error("Expected installed desktop"); + agents.publish({ ...agents.value, claude_desktop: { + ...desktop, data: { ...desktop.data, configuration_needs_apply: true }, + } }); + }); + const apply = await screen.findByRole("button", { name: "Применить" }); + expect(apply).toBeEnabled(); + await user.click(apply); + const plan = await screen.findByRole("dialog", { name: /План изменений/ }); + await user.click(within(plan).getByRole("button", { name: "Применить" })); + await finishSettings(user); + expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled(); + const desktop = environment.agents.value.claude_desktop; + expect(desktop.status === "found" && desktop.data.routing_mode).toBe("hub"); +}); + it("saves both media choices in Claude Desktop without a Hub connection", async () => { const user = userEvent.setup(); launch("offline", "/agents/claude-desktop", ({ agents }) => {