From b6c54bef028c8624ef4949f8dfd73e772b3fb253 Mon Sep 17 00:00:00 2001 From: Ilya Shcherbak Date: Sat, 21 Nov 2026 01:43:30 +0300 Subject: [PATCH] Reconcile Claude Desktop video registration and persist opt-outs --- .../wizard-core/src/agents/claude_desktop.rs | 305 ++++++++++++------ .../src/agents/claude_desktop/video.rs | 74 ++--- crates/wizard-core/src/prepared_plan.rs | 4 +- crates/wizard-gui/src/agents.rs | 32 +- crates/wizard-gui/src/video.rs | 6 +- .../src/agents/AgentConfiguration.tsx | 17 +- .../src/agents/AgentConnectionPanel.tsx | 3 +- .../wizard-ui/src/agents/AgentPage.tsx | 3 +- .../src/agents/PreparedPlanDialog.tsx | 13 +- .../wizard-ui/src/agents/VideoConnection.tsx | 3 +- .../wizard-ui/src/agents/agents_state.ts | 9 +- .../wizard-ui/src/onboarding/SetupDialog.tsx | 3 +- .../wizard-gui/wizard-ui/src/preview/mocks.ts | 25 +- .../wizard-ui/src/test/flows.test.tsx | 65 +++- 14 files changed, 366 insertions(+), 196 deletions(-) diff --git a/crates/wizard-core/src/agents/claude_desktop.rs b/crates/wizard-core/src/agents/claude_desktop.rs index c75fcc0..548f508 100644 --- a/crates/wizard-core/src/agents/claude_desktop.rs +++ b/crates/wizard-core/src/agents/claude_desktop.rs @@ -33,6 +33,7 @@ pub(crate) struct ClaudeDesktop { pub routing_mode: RoutingMode, pub token: Option, pub proxy_needs_apply: bool, + pub video_needs_apply: bool, } pub(super) fn detect(settings: &Settings) -> AgentDetection { @@ -45,17 +46,29 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { AgentDetection::Error(error) => return AgentDetection::Error(error), }; - let video = settings.video.claude_desktop.is_some(); - let (routing_mode, token, proxy_needs_apply) = match read_routing(video) { - Ok(routing) => routing, - Err(error) => return AgentDetection::Error(format!("{error:#}")), + let configuration = || -> Result { + let _guard = PreparedAgent::ClaudeDesktop.lock()?; + let dir = config_library()?; + let (routing_mode, token, proxy_needs_apply) = read_profile(&dir)?; + let plan = prepare_with_video( + &dir, + &config_1p_path()?, + None, + settings.video.claude_desktop.is_some(), + &video::Registration::for_wizard()?, + ); + Ok(ClaudeDesktop { + info, + routing_mode, + token, + proxy_needs_apply, + video_needs_apply: plan.map_or(true, |plan| !plan.info().is_empty()), + }) }; - AgentDetection::Found(ClaudeDesktop { - info, - routing_mode, - token, - proxy_needs_apply, - }) + match configuration() { + Ok(desktop) => AgentDetection::Found(desktop), + Err(error) => AgentDetection::Error(format!("{error:#}")), + } } /// The 1p configuration, where Claude Desktop in 1p mode reads local MCP servers. @@ -212,20 +225,11 @@ fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result Result<(RoutingMode, Option, bool)> { - let (mode, token, needs_apply) = read_profile(&config_library()?, Some(video))?; - let config_1p_needs_apply = - prepare_1p_video(config_1p_path()?, video && mode == RoutingMode::Sub) - .map_or(true, |change| change.is_changed()); - Ok((mode, token, needs_apply || config_1p_needs_apply)) -} - /// The key for paid video calls: the profile's key in Hub; in Sub, which has no agent key, /// Wizard's own proxy key from its personal Hub. Never log it. pub(crate) fn video_token() -> Result> { - let (mode, token, _) = read_profile(&config_library()?, None)?; + let _guard = PreparedAgent::ClaudeDesktop.lock()?; + let (mode, token, _) = read_profile(&config_library()?)?; Ok(match mode { RoutingMode::Hub => token.map(AgentToken::into_secret), RoutingMode::Sub => wizard_settings::load_from_file()? @@ -235,12 +239,7 @@ pub(crate) fn video_token() -> Result> { }) } -/// `video_grant`: `Some` also checks the Hub video registration against the grant. -fn read_profile( - dir: &Path, - video_grant: Option, -) -> Result<(RoutingMode, Option, bool)> { - let _guard = PreparedAgent::ClaudeDesktop.lock()?; +fn read_profile(dir: &Path) -> Result<(RoutingMode, Option, bool)> { let meta = json::read(&dir.join("_meta.json"))?; let Some(id) = applied_id(&meta)? else { return Ok((RoutingMode::Disabled, None, false)); @@ -260,21 +259,7 @@ fn read_profile( let token = config["inferenceGatewayApiKey"] .as_str() .and_then(|s| AgentToken::new(s.to_owned())); - let Some(video_grant) = video_grant else { - return Ok((RoutingMode::Hub, token, proxy_needs_apply)); - }; - let mut updated = config.clone(); - let registration = video::Registration::for_wizard()?; - let needs_video = registration - .update_3p_profile( - updated - .as_object_mut() - .context("Invalid Claude Desktop profile")?, - video_grant, - ) - .is_err() - || updated != config; - Ok((RoutingMode::Hub, token, proxy_needs_apply || needs_video)) + Ok((RoutingMode::Hub, token, proxy_needs_apply)) } else { Ok((RoutingMode::Disabled, None, false)) } @@ -284,13 +269,24 @@ fn read_profile( /// to the profile; Hub and Sub enable local proxy demand; Disabled ignores it. /// `video`: whether Wizard holds a video grant for Claude Desktop. pub fn prepare_routing(mode: RoutingMode, token: &str, video: bool) -> Result { + prepare_configuration(Some((mode, token)), video) +} + +/// Reconcile video in the current deployment without changing inference or proxy settings. +pub fn prepare_video(enabled: bool) -> Result { + prepare_configuration(None, enabled) +} + +fn prepare_configuration( + routing: Option<(RoutingMode, &str)>, + video: bool, +) -> Result { let _guard = PreparedAgent::ClaudeDesktop.lock()?; prepare_with_video( &config_library()?, &config_1p_path()?, - mode, - token, + routing, video, &video::Registration::for_wizard()?, ) @@ -306,8 +302,7 @@ fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result Result, video_grant: bool, video: &video::Registration, ) -> Result { @@ -325,17 +319,14 @@ fn prepare_with_video( let metadata = json::parse(&meta.after)?; let selected = applied_id(&metadata)?; - let id = selected.map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_owned); - let mut config = FileChange::read(dir.join(format!("{id}.json")))?; let mut preferences = FileChange::read(dir.with_file_name("claude_desktop_config.json"))?; - - let proxy_url = format!("http://{}", wizard_proxy::ADDRESS); - ensure!( - selected.is_some() || config.before().content().is_none(), - "new Claude Desktop profile already exists; prepare again" - ); - - if selected.is_none() && mode != RoutingMode::Disabled { + let use_3p = match routing { + Some((mode, _)) => mode == RoutingMode::Hub, + None => selected.is_some() && json::parse(&preferences.after)?["deploymentMode"] != "1p", + }; + let mut id = selected.map(str::to_owned); + if id.is_none() && routing.is_some_and(|(mode, _)| mode != RoutingMode::Disabled) { + let new_id = uuid::Uuid::new_v4().to_string(); json::update(&mut meta.after, |meta| { let entries = meta .as_object_mut() @@ -345,23 +336,33 @@ fn prepare_with_video( .as_array_mut() .context("Claude Desktop profile entries must be an array")?; ensure!( - !entries.iter().any(|entry| entry["id"] == id), + !entries.iter().any(|entry| entry["id"] == new_id), "new Claude Desktop profile identifier already exists; prepare again" ); - entries.push(json!({"id": id, "name": "CoreInfra"})); - meta["appliedId"] = json!(id); + entries.push(json!({"id": new_id, "name": "CoreInfra"})); + meta["appliedId"] = json!(new_id); Ok(()) })?; + id = Some(new_id); } - if selected.is_some() || mode != RoutingMode::Disabled { + let mut steps = Vec::new(); + if let Some(id) = id { + let mut config = FileChange::read(dir.join(format!("{id}.json")))?; + ensure!( + selected.is_some() || config.before().content().is_none(), + "new Claude Desktop profile already exists; prepare again" + ); json::update(&mut config.after, |config| { let object = config .as_object_mut() .context("Claude Desktop configuration must be an object")?; - video.update_3p_profile(object, video_grant && mode == RoutingMode::Hub)?; + video.update_3p_profile(object, video_grant && use_3p)?; + let Some((mode, token)) = routing else { + return Ok(()); + }; // The complete previous profile is backed up before applying this plan. // Clear provider-specific credentials and proxy overrides before setting the mode. object @@ -381,38 +382,45 @@ fn prepare_with_video( } if mode != RoutingMode::Disabled { - object.insert("egressProxyUrl".into(), json!(proxy_url)); + object.insert( + "egressProxyUrl".into(), + json!(format!("http://{}", wizard_proxy::ADDRESS)), + ); } Ok(()) })?; + steps.push(PreparedStep::ChangeFile { change: config }); } // 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(()) - })?; + if routing.is_some() { + json::update(&mut preferences.after, |preferences| { + preferences["deploymentMode"] = json!(if use_3p { "3p" } else { "1p" }); + Ok(()) + })?; + } // Publish a newly created profile before selecting it. Keep unchanged steps too. - let mut steps = vec![ - PreparedStep::ChangeFile { change: config }, + steps.extend([ PreparedStep::ChangeFile { change: meta }, PreparedStep::ChangeFile { change: preferences, }, - ]; + ]); // Claude Desktop rewrites its 1p configuration while running: read it again after - // closing the app. Preparing here only rejects a foreign entry and skips a no-op. - let enabled = video_grant && mode == RoutingMode::Sub; + // closing the app if the registration needs to change. + let enabled = video_grant && !use_3p; if video_1p_change(config_1p.to_owned(), enabled, video)?.is_changed() { steps.push(PreparedStep::SetClaudeDesktop1pVideo { path: config_1p.to_owned(), enabled, }); } - steps.push(PreparedStep::SetClaudeProxyEnabled { - enabled: mode != RoutingMode::Disabled, - }); + if let Some((mode, _)) = routing { + steps.push(PreparedStep::SetClaudeProxyEnabled { + enabled: mode != RoutingMode::Disabled, + }); + } Ok(PreparedPlan::new(PreparedAgent::ClaudeDesktop, steps)) } @@ -454,7 +462,7 @@ mod tests { |_| panic!("unexpected ChatGPT proxy"), )?; assert!(activated); - let (detected, token, needs_apply) = read_profile(&dir, Some(false))?; + let (detected, token, needs_apply) = read_profile(&dir)?; assert_eq!(detected, mode); assert!(!needs_apply); assert_eq!( @@ -565,8 +573,7 @@ mod tests { prepare_with_video( &fixture.dir, &config_1p, - mode, - "token", + Some((mode, "token")), video, ®istration, ) @@ -587,7 +594,9 @@ mod tests { // Claude Desktop rewrites its 1p configuration while it runs. std::fs::write( &config_1p, - json!({"preferences": {"sidebarMode": "b"}, "mcpServers": {"other": other}}) + json!({"preferences": {"sidebarMode": "b"}, "mcpServers": { + "other": other, "coreinfra_video": {"command":"previous-wizard", "args":[], "env":{}} + }}) .to_string(), )?; fixture.apply(plan, true)?; @@ -607,14 +616,21 @@ mod tests { assert_eq!(read_config_1p()?["mcpServers"], json!({"other": other})); assert_eq!(read_config_1p()?["preferences"]["sidebarMode"], "b"); - let foreign = json!({"command": "user-video", "args": []}); + let stale = json!({"command": "previous-wizard", "args": []}); std::fs::write( &config_1p, - json!({"mcpServers": {"coreinfra_video": foreign}}).to_string(), + json!({"mcpServers": {"coreinfra_video": stale}}).to_string(), )?; - assert!(prepare(RoutingMode::Sub, true).is_err()); - assert_eq!(video_step(&prepare(RoutingMode::Disabled, false)?), None); - assert_eq!(read_config_1p()?["mcpServers"]["coreinfra_video"], foreign); + let plan = prepare(RoutingMode::Disabled, true)?; + assert_eq!(video_step(&plan), Some(true)); + fixture.apply(plan, false)?; + assert_eq!( + read_config_1p()?, + json!({"mcpServers": {"coreinfra_video": ours}}) + ); + assert_eq!(video_step(&prepare(RoutingMode::Disabled, true)?), None); + fixture.apply(prepare(RoutingMode::Disabled, false)?, false)?; + assert_eq!(read_config_1p()?, json!({})); std::fs::remove_file(&config_1p)?; assert_eq!(video_step(&prepare(RoutingMode::Hub, true)?), None); @@ -634,12 +650,18 @@ mod tests { prepare_with_video( &fixture.dir, &config_1p, - RoutingMode::Hub, - "token", + Some((RoutingMode::Hub, "token")), grant, ®istration, ) }; + let video_needs_apply = |grant| -> Result { + Ok( + !prepare_with_video(&fixture.dir, &config_1p, None, grant, ®istration)? + .info() + .is_empty(), + ) + }; let example = json!({"name":"example", "transport":"http", "url":"https://mcp.example"}); // (MCP servers named coreinfra_video, Wizard marketplaces) in the profile. let video_entries = || -> Result<(usize, usize)> { @@ -663,20 +685,100 @@ mod tests { // Hub without a grant registers nothing, and detection agrees. fixture.apply(prepare(false)?, true)?; assert_eq!(video_entries()?, (0, 0)); - assert!(!read_profile(&fixture.dir, Some(false))?.2); - assert!(read_profile(&fixture.dir, Some(true))?.2); + assert!(!video_needs_apply(false)?); + assert!(video_needs_apply(true)?); fixture.apply(prepare(true)?, true)?; assert_eq!(video_entries()?, (1, 1)); - assert!(!read_profile(&fixture.dir, Some(true))?.2); - assert!(read_profile(&fixture.dir, Some(false))?.2); + assert!(!video_needs_apply(true)?); + assert!(video_needs_apply(false)?); + + let current = json::read(&fixture.files[0])?; + let mut stale = current.clone(); + stale["managedMcpServers"][1]["args"][2] = json!( + registration + .headers + .with_file_name("video-mcp-headers.json") + ); + std::fs::write(&fixture.files[0], stale.to_string())?; + assert!(video_needs_apply(true)?); + fixture.apply(prepare(true)?, true)?; + assert_eq!(json::read(&fixture.files[0])?, current); + + stale["managedMcpServers"] = json!([ + {"name":"coreinfra_video", "transport":"http"}, example, stale["managedMcpServers"][1] + ]); + stale["allowedPluginMarketplaces"] = json!([ + {"repo":"coreinfraai/WIZARD", "path":"old"}, + {"expectedName":"coreinfra-wizard", "ref":"old"} + ]); + std::fs::write(&fixture.files[0], stale.to_string())?; + fixture.apply(prepare(true)?, true)?; + let repaired = json::read(&fixture.files[0])?; + assert_eq!( + repaired["managedMcpServers"], + json!([current["managedMcpServers"][1], example]) + ); + assert_eq!( + repaired["allowedPluginMarketplaces"], + current["allowedPluginMarketplaces"] + ); + assert!(!video_needs_apply(true)?); // Revoking the grant removes only Wizard's entries. + std::fs::write(&fixture.files[0], stale.to_string())?; fixture.apply(prepare(false)?, true)?; assert_eq!(video_entries()?, (0, 0)); Ok(()) } + #[test] + fn video_only_follows_the_active_deployment_without_configuring_routing() -> Result<()> { + let registration = video::Registration::for_wizard()?; + for has_profile in [false, true] { + let fixture = Fixture::new("bedrock")?; + if !has_profile { + for path in &fixture.files { + std::fs::remove_file(path)?; + } + } + let original = json::read(&fixture.files[0])?; + let selection = fixture.snapshots()?; + let config_1p = fixture + .root + .path() + .join("Claude/claude_desktop_config.json"); + let prepare = + |grant| prepare_with_video(&fixture.dir, &config_1p, None, grant, ®istration); + for enable in [true, false] { + let plan = prepare(enable)?; + assert!(!plan.info().is_empty()); + plan.apply_with_backup( + Some(fixture.manager()), + |_| panic!("a video-only change must preserve the Claude proxy"), + |_| panic!("unexpected Codex proxy change"), + )?; + assert!(prepare(enable)?.info().is_empty()); + assert_eq!(read_profile(&fixture.dir)?.0, RoutingMode::Disabled); + assert!(fixture.snapshots()?[1..] == selection[1..]); + let local = json::read(&config_1p)?; + assert_eq!( + local["mcpServers"].get("coreinfra_video").is_some(), + enable && !has_profile + ); + if has_profile && enable { + let profile = json::read(&fixture.files[0])?; + assert_eq!(profile["managedMcpServers"][1]["name"], "coreinfra_video"); + assert_eq!(profile["inferenceProvider"], original["inferenceProvider"]); + assert_eq!(profile["egressProxyUrl"], original["egressProxyUrl"]); + } else { + assert_eq!(json::read(&fixture.files[0])?, original); + } + } + } + Ok(()) + } + #[test] fn foreign_connections_are_replaced_and_full_configuration_can_be_restored() -> Result<()> { for provider in ["gateway", "bedrock", "vertex"] { @@ -708,7 +810,7 @@ mod tests { assert!(config.get("inferenceBedrockRegion").is_none()); assert!(config.get("egressProxyPacUrl").is_none()); assert!(config.get("egressProxyAuth").is_none()); - assert_eq!(read_profile(&fixture.dir, Some(false))?.0, mode); + assert_eq!(read_profile(&fixture.dir)?.0, mode); if mode == RoutingMode::Hub { assert_eq!(config["inferenceGatewayApiKey"], "new-token"); assert_eq!(config["inferenceGatewayBaseUrl"], HUB_URL); @@ -755,7 +857,7 @@ mod tests { let mut profile = json::read(&fixture.files[0])?; profile["egressProxyUrl"] = json!(RETIRED_PROXY_URL); std::fs::write(&fixture.files[0], profile.to_string())?; - let (detected, agent_token, needs_apply) = read_profile(&fixture.dir, Some(false))?; + let (detected, agent_token, needs_apply) = read_profile(&fixture.dir)?; assert_eq!(detected, mode); assert!(needs_apply); assert_eq!(agent_token.is_some(), mode == RoutingMode::Hub); @@ -764,7 +866,7 @@ mod tests { fixture.apply(prepare_routing_at(&fixture.dir, mode, token)?, true)?; assert_eq!(fixture.manager().get_backups()?.len(), 2); - assert!(!read_profile(&fixture.dir, Some(false))?.2); + assert!(!read_profile(&fixture.dir)?.2); // Restoring the backup of the retired configuration keeps the two-port layout. fixture.apply( @@ -775,8 +877,7 @@ mod tests { json::read(&fixture.files[0])?["egressProxyUrl"], "http://127.0.0.1:33787" ); - let (restored_mode, restored_token, needs_apply) = - read_profile(&fixture.dir, Some(false))?; + let (restored_mode, restored_token, needs_apply) = read_profile(&fixture.dir)?; assert_eq!(restored_mode, mode); assert!(!needs_apply); assert_eq!( @@ -826,10 +927,7 @@ mod tests { )?; assert!(!created.exists()); assert!(fixture.files.iter().all(|path| !path.exists())); - assert_eq!( - read_profile(&fixture.dir, Some(false))?.0, - RoutingMode::Disabled - ); + assert_eq!(read_profile(&fixture.dir)?.0, RoutingMode::Disabled); Ok(()) } @@ -958,10 +1056,9 @@ mod tests { std::fs::write(&profile_path, original.to_string())?; std::fs::write(&preferences_path, r#"{"deploymentMode":"3p"}"#)?; - // With a video grant, a manual Hub profile also lacks Wizard's registration. - let (detected, token, proxy_needs_apply) = read_profile(&dir, Some(true))?; + let (detected, token, proxy_needs_apply) = read_profile(&dir)?; assert_eq!(detected, RoutingMode::Hub); - assert!(proxy_needs_apply); + assert!(!proxy_needs_apply); assert_eq!( token.map(AgentToken::into_secret).as_deref(), Some("manual-token") @@ -990,7 +1087,7 @@ mod tests { ); assert_eq!(updated["autoModeEnabled"], true); assert_eq!(json::read(&dir.join("_meta.json"))?, meta); - assert_eq!(read_profile(&dir, Some(false))?.0, mode); + assert_eq!(read_profile(&dir)?.0, mode); if mode == RoutingMode::Hub { assert_eq!(updated["inferenceGatewayBaseUrl"], HUB_URL); assert_eq!(updated["inferenceGatewayApiKey"], "wizard-token"); diff --git a/crates/wizard-core/src/agents/claude_desktop/video.rs b/crates/wizard-core/src/agents/claude_desktop/video.rs index 61cd83f..887102d 100644 --- a/crates/wizard-core/src/agents/claude_desktop/video.rs +++ b/crates/wizard-core/src/agents/claude_desktop/video.rs @@ -1,6 +1,6 @@ //! Claude Desktop's local 3P profile uses native arrays for both managed extensions. use crate::video::stdio; -use anyhow::{Context as _, Result, ensure}; +use anyhow::{Context as _, Result}; use serde_json::{Map, Value, json}; use std::path::PathBuf; @@ -54,49 +54,34 @@ impl Registration { .as_str() .is_some_and(|repo| repo.eq_ignore_ascii_case(REPO)) }, - |entry| { - entry["source"] == "github" - && entry["repo"] == REPO - && entry["expectedName"] == MARKET - && entry["credentialKind"] == "anonymous" - && entry["installationPreference"] == "auto_install" - && entry.get("path").is_none() - }, - "ref", )?; - let args = json!([stdio::ARG, self.port.to_string(), self.headers]); reconcile( profile, "managedMcpServers", enable, json!({ - "name":SERVER, "transport":"stdio", "command":self.command, "args":args, + "name":SERVER, "transport":"stdio", "command":self.command, "args":self.args(), "toolTimeoutSec":240, "toolPolicy":{"video_models":"allow"} }), |entry| entry["name"] == SERVER, - |entry| entry["transport"] == "stdio" && entry["args"] == args, - "command", ) } - /// Subscription (1p) mode: Claude Desktop reads local servers from `mcpServers` in - /// `Claude/claude_desktop_config.json`. There is no plugin marketplace or tool policy here. + fn args(&self) -> Value { + json!([stdio::ARG, self.port.to_string(), self.headers]) + } + + /// Claude Desktop reads local servers from `mcpServers` in its 1p configuration. pub(super) fn update_1p_config( &self, config: &mut Map, enable: bool, ) -> Result<()> { - let args = json!([stdio::ARG, self.port.to_string(), self.headers]); - let owned = |entry: &Value| entry["args"] == args; if !enable { - let now_empty = match config.get_mut("mcpServers").and_then(Value::as_object_mut) { - Some(servers) if servers.get(SERVER).is_some_and(owned) => { - servers.shift_remove(SERVER); - servers.is_empty() - } - _ => false, - }; - if now_empty { + if let Some(servers) = config.get_mut("mcpServers").and_then(Value::as_object_mut) + && servers.shift_remove(SERVER).is_some() + && servers.is_empty() + { config.shift_remove("mcpServers"); } return Ok(()); @@ -106,38 +91,26 @@ impl Registration { .or_insert_with(|| json!({})) .as_object_mut() .context("В настройках Claude Desktop поле mcpServers должно быть объектом")?; - if let Some(entry) = servers.get_mut(SERVER) { - ensure!( - owned(entry), - "В Claude Desktop уже зарегистрирован другой MCP-сервер coreinfra_video" - ); - // Refresh only the executable, which moves when Wizard is reinstalled elsewhere. - entry["command"] = json!(self.command); - } else { - servers.insert( - SERVER.into(), - json!({"command": self.command, "args": args}), - ); - } + servers.insert( + SERVER.into(), + json!({"command": self.command, "args": self.args()}), + ); Ok(()) } } -// Only refresh the pin or executable when a registration already belongs to Wizard. -// In particular, keep a user's stricter tool policies and other servers in place. +// Replace all versions of the registration at its first position in the profile. fn reconcile( profile: &mut Map, key: &str, enable: bool, desired: Value, matches: impl Fn(&Value) -> bool, - owned: impl Fn(&Value) -> bool, - refresh: &str, ) -> Result<()> { if !enable { if let Some(entries) = profile.get_mut(key).and_then(Value::as_array_mut) { let previous_len = entries.len(); - entries.retain(|entry| !(matches(entry) && owned(entry))); + entries.retain(|entry| !matches(entry)); if previous_len != 0 && entries.is_empty() { profile.shift_remove(key); } @@ -150,15 +123,8 @@ fn reconcile( .or_insert_with(|| json!([])) .as_array_mut() .with_context(|| format!("В профиле Claude Desktop поле {key} должно быть массивом"))?; - let mut existing = entries.iter_mut().filter(|entry| matches(entry)); - if let Some(entry) = existing.next() { - ensure!( - owned(entry) && existing.next().is_none(), - "Конфликт регистрации CoreInfra Video в поле {key} профиля Claude Desktop" - ); - entry[refresh] = desired[refresh].clone(); - } else { - entries.push(desired); - } + let index = entries.iter().position(&matches).unwrap_or(entries.len()); + entries.retain(|entry| !matches(entry)); + entries.insert(index, desired); Ok(()) } diff --git a/crates/wizard-core/src/prepared_plan.rs b/crates/wizard-core/src/prepared_plan.rs index 93c5dda..7fc354e 100644 --- a/crates/wizard-core/src/prepared_plan.rs +++ b/crates/wizard-core/src/prepared_plan.rs @@ -153,9 +153,9 @@ impl PreparedPlan { }, PreparedStep::SetClaudeDesktop1pVideo { enabled, .. } => PreparedStepInfo { description: if *enabled { - "Зарегистрирует MCP-сервер coreinfra_video в Claude Desktop для подписки Claude." + "Зарегистрирует локальный MCP-сервер coreinfra_video в Claude Desktop." } else { - "Удалит MCP-сервер coreinfra_video, добавленный Wizard, из настроек Claude Desktop для подписки." + "Удалит локальный MCP-сервер coreinfra_video из настроек Claude Desktop." }.to_owned(), }, PreparedStep::SetCodexProxyEnabled { enabled } => PreparedStepInfo { diff --git a/crates/wizard-gui/src/agents.rs b/crates/wizard-gui/src/agents.rs index 0a4542d..206044b 100644 --- a/crates/wizard-gui/src/agents.rs +++ b/crates/wizard-gui/src/agents.rs @@ -173,6 +173,7 @@ pub(crate) enum AgentChange { CodexSetRouting(RoutingMode), ClaudeSetRouting(RoutingMode), ClaudeDesktopSetRouting(RoutingMode), + ClaudeDesktopSetVideo(bool), SetPiHub(HubMode), SetOpenCodeHub(HubMode), } @@ -190,11 +191,13 @@ pub(crate) struct PreparedAgentChange { } impl AgentChange { - const fn enabled(self) -> bool { + const fn needs_agent_token(self) -> bool { match self { - Self::CodexSetRouting(mode) - | Self::ClaudeSetRouting(mode) - | Self::ClaudeDesktopSetRouting(mode) => !matches!(mode, RoutingMode::Disabled), + Self::CodexSetRouting(mode) | Self::ClaudeSetRouting(mode) => { + !matches!(mode, RoutingMode::Disabled) + } + Self::ClaudeDesktopSetRouting(mode) => matches!(mode, RoutingMode::Hub), + Self::ClaudeDesktopSetVideo(_) => false, Self::SetPiHub(mode) | Self::SetOpenCodeHub(mode) => !matches!(mode, HubMode::Disabled), } } @@ -203,7 +206,9 @@ impl AgentChange { match self { Self::CodexSetRouting(_) => TokenAgent::Codex, Self::ClaudeSetRouting(_) => TokenAgent::Claude, - Self::ClaudeDesktopSetRouting(_) => TokenAgent::ClaudeDesktop, + Self::ClaudeDesktopSetRouting(_) | Self::ClaudeDesktopSetVideo(_) => { + TokenAgent::ClaudeDesktop + } Self::SetPiHub(_) => TokenAgent::Pi, Self::SetOpenCodeHub(_) => TokenAgent::OpenCode, } @@ -225,6 +230,7 @@ pub(crate) async fn prepare_agent_change( AgentChange::CodexSetRouting(_) => ("CodexSetRouting", "codex"), AgentChange::ClaudeSetRouting(_) => ("ClaudeSetRouting", "claude"), AgentChange::ClaudeDesktopSetRouting(_) => ("ClaudeDesktopSetRouting", "claude_desktop"), + AgentChange::ClaudeDesktopSetVideo(_) => ("ClaudeDesktopSetVideo", "claude_desktop"), AgentChange::SetPiHub(_) => ("SetPiHub", "pi"), AgentChange::SetOpenCodeHub(_) => ("SetOpenCodeHub", "opencode"), }; @@ -232,11 +238,7 @@ pub(crate) async fn prepare_agent_change( let settings = settings::get_state(&app).map_err(|error| format!("{error:#}"))?; - let token = if change.enabled() - && !matches!( - change, - AgentChange::ClaudeDesktopSetRouting(RoutingMode::Sub) - ) { + let token = if change.needs_agent_token() { match token { Some(TokenChoice::Existing { token }) if !token.is_empty() => token, Some(TokenChoice::Create) if matches!(change, AgentChange::CodexSetRouting(_)) => { @@ -272,6 +274,16 @@ pub(crate) async fn prepare_agent_change( ); Ok(plan) } + AgentChange::ClaudeDesktopSetVideo(enabled) => { + let mut plan = claude_desktop::prepare_video(enabled)?; + if !plan.info().is_empty() { + plan.restart_desktop( + wizard_core::agents::desktop_install::DesktopApp::Claude, + settings.last_paths.claude_desktop.as_deref(), + ); + } + Ok(plan) + } AgentChange::SetPiHub(mode) => pi::prepare_hub(mode, &token, &settings), AgentChange::SetOpenCodeHub(mode) => opencode::prepare_hub(mode, &token, &settings), }) diff --git a/crates/wizard-gui/src/video.rs b/crates/wizard-gui/src/video.rs index 6e0e411..2adb22f 100644 --- a/crates/wizard-gui/src/video.rs +++ b/crates/wizard-gui/src/video.rs @@ -1,4 +1,4 @@ -use crate::settings; +use crate::{agents::AgentRevisionState, revision_signal::RevisionSignal, settings}; use anyhow::{Context as _, Result}; use serde::Serialize; use tauri::Manager as _; @@ -72,5 +72,9 @@ pub(crate) async fn set_video_connection( .await .map_err(|_| "Не удалось настроить видео")? .map_err(|e| format!("{e:#}"))?; + // Detection compares registrations with the saved grant. A preceding routing plan + // may already have triggered a read against the previous grant. + app.state::>() + .notify(AgentRevisionState); crate::proxy::sync(&app).await.map_err(|e| format!("{e:#}")) } diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx index 9bee68b..382ecf9 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx @@ -265,6 +265,7 @@ export function RoutingFieldset({ actionsClassName = "", editing = false, needsApply = false, + videoNeedsApply = false, }: { agent: AgentId; modes: ModeOption[]; @@ -281,6 +282,7 @@ export function RoutingFieldset({ actionsClassName?: string; editing?: boolean; needsApply?: boolean; + videoNeedsApply?: boolean; }) { const [draft, setDraft] = useState(initialMode); const subscriptionTokenPreview = useContext(SubscriptionTokenPreviewContext); @@ -294,15 +296,12 @@ export function RoutingFieldset({ (token.selected?.kind === "create" || (token.selected?.kind === "existing" && token.selected.token !== agentToken)); - const showVideo = agent === "codex" || agent === "claude" || (agent === "claude_desktop" && selected !== "disabled"); + const showVideo = agent === "codex" || agent === "claude" || agent === "claude_desktop"; const video = useVideoConnection(agent, showVideo); - const videoChanged = showVideo && video.needsApply; - // Claude Desktop registers video in its configuration only through a plan that restarts it. - const desktopVideoChanged = - agent === "claude_desktop" && showVideo && !!video.status && video.enabled !== video.status.enabled; + const videoChanged = showVideo && !!video.status && (video.needsApply || videoNeedsApply); const routingChanged = - selected !== mode || (enabled && (needsApply || tokenChanged)) || desktopVideoChanged; - const prepareRouting = !editing || routingChanged; + selected !== mode || (enabled && (needsApply || tokenChanged)); + const prepareRouting = routingChanged || (!editing && (enabled || agent !== "claude_desktop")); const systemProxy = useSystemProxy(); const [proxyPrompt, setProxyPrompt] = useState(false); @@ -317,7 +316,7 @@ export function RoutingFieldset({ } function prepare() { - const includeVideo = showVideo && (video.needsApply || (prepareRouting && video.enabled)); + const includeVideo = videoChanged || (showVideo && prepareRouting && video.enabled); onPrepare({ agent, routing: prepareRouting ? { @@ -369,7 +368,7 @@ export function RoutingFieldset({ disabled || (prepareRouting && enabled && (proxyOnly ? !hub.signedIn : !token.ready)) || (showVideo && !video.status && !video.error) || - (!prepareRouting && !videoChanged) + (editing && !prepareRouting && !videoChanged) } onClick={prepare} > diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx index 03638c7..c7bf07f 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx @@ -36,7 +36,7 @@ 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" && - (("video_needs_apply" in detection.data && detection.data.video_needs_apply) || ("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) || (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] : []) : []; @@ -68,6 +68,7 @@ export function AgentConnectionPanel({ agent, agents, account, onBack }: { modes={agent === "pi" || agent === "opencode" ? hubModes : routingModes(agent === "codex" ? "Codex" : "Claude")} toChange={toChange} agentToken={detection.data.token} hub={hub} needsApply={needsApply} disabled={busy || account.submitting} error={error} + videoNeedsApply={"video_needs_apply" in detection.data && detection.data.video_needs_apply} note={agent === "codex" ? "Настройка общая для ChatGPT и Codex." : undefined} actions={} onPrepare={prepare} diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx index a1819f3..a69fba4 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx @@ -284,7 +284,7 @@ export function AgentPage({ key={configurationRevision} editing agent="claude" - needsApply={claude.data.video_needs_apply} + videoNeedsApply={claude.data.video_needs_apply} modes={routingModes("Claude")} mode={claude.data.routing_mode} toChange={(mode) => ({ ClaudeSetRouting: mode })} @@ -344,6 +344,7 @@ export function AgentPage({ (!proxyStartup.starting && proxy.proxy?.enabled === false)) } agent="claude_desktop" + videoNeedsApply={desktop.data.video_needs_apply} modes={routingModes("Claude")} mode={desktop.data.routing_mode} toChange={(mode) => ({ ClaudeDesktopSetRouting: mode })} diff --git a/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx b/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx index 80b4c68..386547f 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx @@ -28,9 +28,16 @@ function PlanSteps({ plan }: { plan: ConnectionPlan }) { const steps: ReactNode[] = (plan.routing?.info ?? []).map(step => step.description); // Keep the choice from the form visible alongside the first routing action. if (plan.videoEnabled !== undefined) { - steps.unshift(plan.videoEnabled - ? <>Установит скилл coreinfra-video для видео-моделей. - : <>Отключит видео-модели и удалит скилл coreinfra-video, установленный Wizard.); + const video = coreinfra-video; + if (plan.agent === "claude_desktop") { + steps.unshift(plan.videoEnabled + ? <>Подключит инструменты {video} в Claude Desktop. + : <>Отключит видео-модели {video} в Claude Desktop.); + } else { + steps.unshift(plan.videoEnabled + ? <>Установит скилл {video} для видео-моделей. + : <>Отключит видео-модели и удалит скилл {video}, установленный Wizard.); + } } const rows = steps.map((step, index) =>
  • {step}
  • ); return ( diff --git a/crates/wizard-gui/wizard-ui/src/agents/VideoConnection.tsx b/crates/wizard-gui/wizard-ui/src/agents/VideoConnection.tsx index be6db5d..dc50800 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/VideoConnection.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/VideoConnection.tsx @@ -34,7 +34,8 @@ export function useVideoConnection(agent: AgentId, available: boolean) { }, [agent, available, revision]); const enabled = draft ?? (status && (status.enabled || status.suggested)); - const needsApply = !!status && (enabled !== status.enabled || (enabled && !status.running) || !!status.error); + // The first Apply also saves an explicit decline of the default suggestion. + const needsApply = !!status && (status.suggested || enabled !== status.enabled || (enabled && !status.running) || !!status.error); function retry() { setError(undefined); setRevision(value => value + 1); 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 e8faaf2..b5b89db 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts @@ -6,6 +6,7 @@ export type AgentChange = | { CodexSetRouting: RoutingMode } | { ClaudeSetRouting: RoutingMode } | { ClaudeDesktopSetRouting: RoutingMode } + | { ClaudeDesktopSetVideo: boolean } | { SetPiHub: HubMode } | { SetOpenCodeHub: HubMode }; @@ -46,8 +47,11 @@ export type ConnectionPlan = { }; export async function prepareAgentChange({ agent, routing, videoEnabled }: ConnectionDraft): Promise { - const prepared = routing - ? await invoke("prepare_agent_change", { ...routing, video: videoEnabled }) + const request = routing ?? (agent === "claude_desktop" && videoEnabled !== undefined + ? { change: { ClaudeDesktopSetVideo: videoEnabled }, token: null } + : undefined); + const prepared = request + ? await invoke("prepare_agent_change", { ...request, video: videoEnabled }) : undefined; return { agent, routing: prepared, videoEnabled }; } @@ -113,6 +117,7 @@ export type ClaudeDesktop = { // CoreInfra token from the agent's configuration. Secret: never log or persist it. token: string | null; proxy_needs_apply: boolean; + video_needs_apply: boolean; }; export type OpenCode = { diff --git a/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx b/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx index 69dbe33..b46fb7f 100644 --- a/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx @@ -113,8 +113,9 @@ function Configure({ : routingModes(choice.agent === "codex" ? "Codex" : "Claude") } mode={agent.data.routing_mode} + videoNeedsApply={"video_needs_apply" in agent.data && agent.data.video_needs_apply} initialMode={ - agent.data.routing_mode === "disabled" ? "hub" : undefined + hub.signedIn && agent.data.routing_mode === "disabled" ? "hub" : undefined } agentToken={agent.data.token} hub={hub} diff --git a/crates/wizard-gui/wizard-ui/src/preview/mocks.ts b/crates/wizard-gui/wizard-ui/src/preview/mocks.ts index a707382..82411d0 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, + video_needs_apply: false, path: "/Applications/Claude.app", version: detectedVersion.claude, }, @@ -497,7 +498,7 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo const enabled = videoEnabled.has(String(args.agent)); return { enabled, suggested: !enabled && !videoDeclined.has(String(args.agent)), running: enabled, error: null }; } - case "set_video_connection": + case "set_video_connection": { if (args.enabled) { videoEnabled.add(String(args.agent)); videoDeclined.delete(String(args.agent)); @@ -505,7 +506,15 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo videoEnabled.delete(String(args.agent)); videoDeclined.add(String(args.agent)); } + const agent = args.agent as AgentId; + const detection = agents.value[agent]; + if (detection.status === "found" && "video_needs_apply" in detection.data) { + agents.publish({ ...agents.value, [agent]: { + ...detection, data: { ...detection.data, video_needs_apply: false }, + } }); + } return; + } case "get_update_state": return update.read(revision); case "get_application_settings": @@ -554,6 +563,7 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo status: "found", data: { ...(next.claude_desktop.status === "found" ? next.claude_desktop.data : unconfigured), + video_needs_apply: false, path: release(desktop).path, version: versions[desktop], }, @@ -610,6 +620,17 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo return; case "prepare_agent_change": { const change = args.change as AgentChange; + if ("ClaudeDesktopSetVideo" in change) { + const agent = "claude_desktop"; + const desktop = agents.value.claude_desktop; + const changed = videoEnabled.has(agent) !== change.ClaudeDesktopSetVideo || + (desktop.status === "found" && desktop.data.video_needs_apply); + return { + agent, change, token: null, plan: { preview: true, agent, videoOnly: true }, + info: changed ? [{ description: "Обновит регистрацию CoreInfra Video в Claude Desktop." }] : [], + restarts_desktop: changed, + } satisfies PreparedAgentChange; + } const operation = Object.keys(change)[0] as keyof typeof change; const agent = ( { @@ -663,9 +684,11 @@ export function createMockEnvironment(scenario: Scenario = "update", options: Mo agent: AgentId; mode: RoutingMode; token: string | null; + videoOnly?: boolean; }; if (!plan.preview) throw "Превью принимает только демонстрационные планы"; + if (plan.videoOnly) return; const detection = agents.value[plan.agent]; if (detection.status === "found") agents.publish({ 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 53940e7..f7655bb 100644 --- a/crates/wizard-gui/wizard-ui/src/test/flows.test.tsx +++ b/crates/wizard-gui/wizard-ui/src/test/flows.test.tsx @@ -168,10 +168,10 @@ it("applies a Claude Desktop video change through a plan that restarts Desktop, await user.click(toggle); await user.click(screen.getByRole("button", { name: "Применить" })); const plan = await screen.findByRole("dialog", { name: /План изменений/ }); - // The mode is unchanged, but Desktop still gets a routing plan with the draft's video choice. + // A video-only plan can close Desktop without reconfiguring its gateway or agent token. expect(prepare).toHaveBeenLastCalledWith(expect.objectContaining({ agent: "claude_desktop", - routing: expect.objectContaining({ change: { ClaudeDesktopSetRouting: "hub" } }), + routing: undefined, videoEnabled: true, })); await user.click(within(plan).getByRole("button", { name: "Применить" })); @@ -179,19 +179,22 @@ it("applies a Claude Desktop video change through a plan that restarts Desktop, const applied = environment.calls.indexOf("apply_agent_plan"); expect(applied).toBeGreaterThanOrEqual(0); expect(environment.calls.indexOf("set_video_connection")).toBeGreaterThan(applied); + await finishSettings(user); + expect(await screen.findByRole("switch", { name: /coreinfra-video/ })).toBeChecked(); + expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled(); } finally { prepare.mockRestore(); } }); -it("offers Claude Desktop video on a subscription and hides it without CoreInfra", async () => { +it("keeps the Claude Desktop video choice across routing modes", async () => { const user = userEvent.setup(); const prepare = vi.spyOn(agentCommands, "prepareAgentChange"); try { launch("all_agents", "/agents/claude-desktop"); await screen.findByRole("switch", { name: /coreinfra-video/ }); await user.click(screen.getByRole("radio", { name: "Без CoreInfra AI Hub" })); - expect(screen.queryByRole("switch", { name: /coreinfra-video/ })).not.toBeInTheDocument(); + expect(screen.getByRole("switch", { name: /coreinfra-video/ })).toBeVisible(); await user.click(screen.getByRole("radio", { name: "Своя подписка Claude" })); await user.click(await screen.findByRole("button", { name: "Пропустить" })); await user.click(await screen.findByRole("switch", { name: /coreinfra-video/ })); @@ -207,6 +210,50 @@ it("offers Claude Desktop video on a subscription and hides it without CoreInfra } }); +it("remembers declining the default video offer while switching Claude Desktop away from Hub", async () => { + const user = userEvent.setup(); + launch("all_agents", "/agents/claude-desktop", undefined, { videoSuggested: true }); + const toggle = await screen.findByRole("switch", { name: /coreinfra-video/ }); + expect(toggle).toBeChecked(); + await user.click(toggle); + await user.click(screen.getByRole("radio", { name: "Без CoreInfra AI Hub" })); + await user.click(screen.getByRole("button", { name: "Применить" })); + const plan = await screen.findByRole("dialog", { name: /План изменений/ }); + expect(within(plan).getByText(/Отключит видео-модели/)).toBeVisible(); + await user.click(within(plan).getByRole("button", { name: "Применить" })); + await finishSettings(user); + await user.click(screen.getByRole("link", { name: "Claude Code" })); + await user.click(screen.getByRole("link", { name: "Claude Desktop" })); + expect(await screen.findByRole("switch", { name: /coreinfra-video/ })).not.toBeChecked(); + expect(screen.getByRole("radio", { name: "Без CoreInfra AI Hub" })).toBeChecked(); + expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled(); +}); + +it("saves both video choices in Claude Desktop without a Hub connection", async () => { + const user = userEvent.setup(); + launch("offline", "/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, routing_mode: "disabled", token: null }, + } }); + }, { videoSuggested: true }); + for (const enabled of [false, true]) { + const toggle = await screen.findByRole("switch", { name: /coreinfra-video/ }); + expect(toggle).toHaveAttribute("aria-checked", String(!enabled)); + await user.click(toggle); + const apply = screen.getByRole("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(await screen.findByRole("switch", { name: /coreinfra-video/ })).toHaveAttribute("aria-checked", String(enabled)); + expect(screen.getByRole("radio", { name: "Без CoreInfra AI Hub" })).toBeChecked(); + expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled(); + } +}); + it("offers video by default to configured agents until the user turns it off", async () => { const user = userEvent.setup(); launch("all_agents", "/agents/claude", undefined, { videoSuggested: true }); @@ -215,7 +262,7 @@ it("offers video by default to configured agents until the user turns it off", a const apply = screen.getByRole("button", { name: "Применить" }); expect(apply).toBeEnabled(); await user.click(toggle); - expect(apply).toBeDisabled(); + expect(apply).toBeEnabled(); await user.click(toggle); await user.click(apply); let plan = await screen.findByRole("dialog", { name: "План изменений: Claude Code" }); @@ -521,13 +568,16 @@ describe("application transitions", () => { it("replaces getting started with the overview after the first connection is configured", async () => { const user = userEvent.setup(); - launch("onboarding_merge", "/overview"); + launch("onboarding_merge", "/overview", undefined, { videoSuggested: true }); await screen.findByRole("heading", { name: "Начало работы" }); expect(screen.queryByRole("button", { name: "Пополнить" })).not.toBeInTheDocument(); await user.click(screen.getByRole("button", { name: "Настроить агента" })); const dialog = await screen.findByRole("dialog", { name: "Настройка агентов" }); await user.click(within(dialog).getByRole("radio", { name: "Claude Desktop" })); await user.click(within(dialog).getByRole("button", { name: "Настроить агента" })); + const video = await within(dialog).findByRole("switch", { name: /coreinfra-video/ }); + expect(video).toBeChecked(); + await user.click(video); await user.click(await within(dialog).findByRole("button", { name: "Завершить настройку" })); const plan = await screen.findByRole("dialog", { name: "План изменений: Claude Desktop" }); await user.click(within(plan).getByRole("button", { name: "Завершить настройку" })); @@ -541,6 +591,9 @@ describe("application transitions", () => { expect(within(dashboard).getByText("Приложения, обновления и настройки подключения.")).toBeInTheDocument(); await screen.findByRole("heading", { name: "Агент готов!" }); expect(screen.queryByRole("heading", { name: "Начало работы" })).not.toBeInTheDocument(); + await user.click(screen.getByRole("link", { name: "Claude Desktop" })); + expect(await screen.findByRole("switch", { name: /coreinfra-video/ })).not.toBeChecked(); + await waitFor(() => expect(screen.getByRole("button", { name: "Применить" })).toBeDisabled()); }); it("does not mistake a detection failure for missing applications on the overview", async () => {