From 4779ded4813d5ebede310c45764b3caf13cc1dc1 Mon Sep 17 00:00:00 2001 From: Ilya Shcherbak Date: Mon, 16 Nov 2026 19:51:29 +0300 Subject: [PATCH 1/3] Fix agent tokens, proxy recovery, and update checks Share explicit Hub token selection between configuration and downloads. Give Claude Desktop a separate backed-up proxy credential and listener, while preserving legacy profiles until they are configured again. Restore configured proxies when opening or launching an agent. Repair missing service registration, preserve existing Windows tasks on lookup errors, and replace older same-version daemons lacking the Claude listener. Report feed failures safely and retry transient update-check failures. Enable Apply for pending changes, reflect observed system proxy state, and refine installer alignment, video spacing, and sidebar presentation. Validation: cargo x ci (115 tests, TypeScript, formatting, Clippy) and isolated browser checks for proxy startup, retries, and recovered status. --- README.md | 12 +- .../wizard-core/src/agents/claude_desktop.rs | 171 ++++++++++++--- .../src/agents/desktop_install/claude.rs | 9 +- .../src/agents/desktop_install/download.rs | 25 +-- .../src/agents/desktop_install/mod.rs | 10 +- .../src/agents/desktop_install/requests.rs | 203 ++++++++++++++++++ .../wizard-core/src/config_files/backups.rs | 5 +- crates/wizard-gui/src/agents.rs | 53 ++++- crates/wizard-gui/src/desktop_install.rs | 24 +-- crates/wizard-gui/src/lib.rs | 1 + crates/wizard-gui/src/system_proxy.rs | 28 +-- crates/wizard-gui/src/system_proxy/tests.rs | 20 +- crates/wizard-gui/src/tray.rs | 3 - .../wizard-gui/wizard-ui/src/AppSidebar.tsx | 4 - .../src/agents/AgentConfiguration.tsx | 68 ++++-- .../wizard-ui/src/agents/AgentPage.tsx | 43 ++-- .../src/agents/PreparedPlanDialog.tsx | 5 +- .../wizard-gui/wizard-ui/src/agents/proxy.ts | 22 ++ .../wizard-ui/src/onboarding/InstallCard.tsx | 22 +- .../wizard-ui/src/onboarding/SetupDialog.css | 14 +- .../wizard-ui/src/overview/Overview.css | 4 +- .../wizard-ui/src/settings/SettingsPage.tsx | 11 +- .../src/settings/SystemProxyPrompt.tsx | 2 +- .../wizard-ui/src/settings/system_proxy.ts | 3 +- crates/wizard-proxy-daemon/src/lib.rs | 31 ++- crates/wizard-proxy-daemon/src/linux.rs | 1 + crates/wizard-proxy-daemon/src/macos.rs | 14 +- .../src/windows-task-exists.ps1 | 20 ++ crates/wizard-proxy-daemon/src/windows.rs | 29 +++ crates/wizard-proxy/src/control.rs | 8 +- crates/wizard-proxy/src/lib.rs | 61 +++++- crates/wizard-proxy/src/server_test.rs | 142 +++++++++++- crates/wizard-settings/src/lib.rs | 11 + crates/wizard-settings/src/paths.rs | 22 +- 34 files changed, 903 insertions(+), 198 deletions(-) create mode 100644 crates/wizard-core/src/agents/desktop_install/requests.rs create mode 100644 crates/wizard-proxy-daemon/src/windows-task-exists.ps1 diff --git a/README.md b/README.md index 2aa456e..6e07310 100644 --- a/README.md +++ b/README.md @@ -103,11 +103,15 @@ and plan confirmation; multiple installed agents always show a selection first. The final action launches the configured desktop app or CLI. Connection options are ordered API access, subscription, then without CoreInfra. -Token selection is automatic: reuse the configured token if it belongs to the +The default token is selected automatically: reuse the configured token if it belongs to the selected Hub, otherwise reuse the oldest token named for the agent, or create one -on confirmation. A note shows its name instead of a selector. Claude Desktop's -subscription uses the existing Wizard proxy-token flow. «Завершить настройку» -opens the change plan and confirms it before the launch step. +on confirmation. The note's «Изменить» link opens a menu of tokens in the selected +Hub. The choice is shared by configuration and downloads. Claude Desktop also uses +its own token in subscription mode, through a dedicated local listener; its +credential is stored with mode 0600 and backed up alongside the agent profile. +Legacy profiles keep working through the shared listener until configured again. +«Завершить настройку» opens the change plan before the launch step. Regular agent +pages use «Применить», enabled for pending mode/token changes or a stopped proxy. Downloads run in the backend and preserve explicit pauses across dialog closes. Installing requires a separate «Установить» confirmation; «Отмена» retains the diff --git a/crates/wizard-core/src/agents/claude_desktop.rs b/crates/wizard-core/src/agents/claude_desktop.rs index 6a6d357..acc942c 100644 --- a/crates/wizard-core/src/agents/claude_desktop.rs +++ b/crates/wizard-core/src/agents/claude_desktop.rs @@ -5,7 +5,7 @@ use super::{ use crate::{ config_files::{ backups::{AgentKind, BackupManager}, - changes::FileChange, + changes::{FileChange, FileSnapshot}, json, }, prepared_plan::{PreparedAgent, PreparedPlan, PreparedStep}, @@ -52,19 +52,7 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { } fn config_library() -> Result { - #[cfg(target_os = "macos")] - let directory = dirs::home_dir().map(|home| home.join("Library/Application Support")); - #[cfg(target_os = "windows")] - let directory = dirs::data_local_dir(); - #[cfg(target_os = "linux")] - let directory = dirs::config_dir(); - - std::path::absolute( - directory - .context("failed to resolve Claude Desktop configuration directory")? - .join("Claude-3p/configLibrary"), - ) - .context("failed to resolve Claude Desktop configuration path") + Ok(wizard_settings::paths::claude_config_dir()?.join("configLibrary")) } fn applied_id(meta: &Value) -> Result> { @@ -118,6 +106,14 @@ pub fn prepare_restore_backup(id: u32) -> Result { fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result { let mut changes = manager.restore_changes(id)?; + let token_path = dir.with_file_name("coreinfra-proxy-token"); + // Backups from before per-agent proxy credentials restore the shared listener. + // Include the current credential in the backup made before this restore too. + if !changes.iter().any(|change| change.path() == &token_path) { + let mut token = FileChange::read(token_path.clone())?; + token.after = FileSnapshot::Missing; + changes.push(token); + } // 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"); @@ -146,7 +142,19 @@ fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result Result Result<(RoutingMode, Option)> { let _guard = PreparedAgent::ClaudeDesktop.lock()?; @@ -176,13 +184,21 @@ fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option)> { let config = json::read(&dir.join(format!("{id}.json")))?; let preferences = json::read(&dir.with_file_name("claude_desktop_config.json"))?; - let proxy_url = format!("http://{}", wizard_proxy::ADDRESS); + let proxy_url = format!("http://{}", wizard_proxy::CLAUDE_ADDRESS); + let legacy_proxy_url = format!("http://{}", wizard_proxy::ADDRESS); if preferences["deploymentMode"] == "1p" - && config["egressProxyUrl"] == proxy_url + && (config["egressProxyUrl"] == proxy_url || config["egressProxyUrl"] == legacy_proxy_url) && config.get("egressProxyPacUrl").is_none() { - Ok((RoutingMode::Sub, None)) + let token = if config["egressProxyUrl"] == proxy_url { + FileSnapshot::read(&dir.with_file_name("coreinfra-proxy-token"))? + .content() + .and_then(|token| AgentToken::new(token.to_owned())) + } else { + None + }; + Ok((RoutingMode::Sub, token)) } else if preferences["deploymentMode"] != "1p" && has_hub_connection(&config) { let token = config["inferenceGatewayApiKey"] .as_str() @@ -194,7 +210,7 @@ fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option)> { } /// 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. +/// to the profile; Hub and Sub save the agent's proxy credential; Disabled removes it. pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { // Hub and Sub point Claude at the local proxy, which Linux cannot start yet. #[cfg(target_os = "linux")] @@ -208,6 +224,10 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { } fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result { + ensure!( + mode == RoutingMode::Disabled || !token.is_empty(), + "CoreInfra token is not set" + ); let mut meta = FileChange::read(dir.join("_meta.json"))?; let metadata = json::parse(&meta.after)?; let selected = applied_id(&metadata)?; @@ -215,8 +235,14 @@ fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result Result Result<()> { + let fixture = Fixture::new("gateway")?; + let token_path = fixture.dir.with_file_name("coreinfra-proxy-token"); + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Sub, "selected-token")?, + true, + )?; + let (mode, token) = read_routing_at(&fixture.dir)?; + assert_eq!(mode, RoutingMode::Sub); + assert_eq!( + token.map(AgentToken::into_secret).as_deref(), + Some("selected-token") + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + assert_eq!( + std::fs::metadata(&token_path)?.permissions().mode() & 0o777, + 0o600 + ); + } + + // A manual credential change is backed up together with the active profile. + std::fs::write(&token_path, "manual-token")?; + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Sub, "replacement-token")?, + true, + )?; + assert_eq!(fixture.manager().get_backups()?.len(), 2); + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 2)?, + true, + )?; + assert_eq!( + read_routing_at(&fixture.dir)? + .1 + .map(AgentToken::into_secret) + .as_deref(), + Some("manual-token") + ); + + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Disabled, "")?, + false, + )?; + assert!(!token_path.exists()); + assert!(prepare_routing_at(&fixture.dir, RoutingMode::Sub, "").is_err()); + Ok(()) + } + + #[test] + fn legacy_subscription_moves_to_its_own_listener_on_apply() -> Result<()> { + let fixture = Fixture::new("gateway")?; + std::fs::write( + &fixture.files[0], + json!({"egressProxyUrl": format!("http://{}", wizard_proxy::ADDRESS)}).to_string(), + )?; + std::fs::write(&fixture.files[2], r#"{"deploymentMode":"1p"}"#)?; + let (mode, token) = read_routing_at(&fixture.dir)?; + assert_eq!(mode, RoutingMode::Sub); + assert!(token.is_none()); + fixture.apply( + prepare_routing_at(&fixture.dir, RoutingMode::Sub, "agent-token")?, + true, + )?; + assert_eq!( + json::read(&fixture.files[0])?["egressProxyUrl"], + format!("http://{}", wizard_proxy::CLAUDE_ADDRESS) + ); + assert_eq!( + read_routing_at(&fixture.dir)? + .1 + .map(AgentToken::into_secret) + .as_deref(), + Some("agent-token") + ); + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 1)?, + true, + )?; + assert_eq!( + json::read(&fixture.files[0])?["egressProxyUrl"], + format!("http://{}", wizard_proxy::ADDRESS) + ); + assert!(read_routing_at(&fixture.dir)?.1.is_none()); + Ok(()) + } + #[test] fn backup_failure_prevents_configuration_and_proxy_changes() -> Result<()> { let fixture = Fixture::new("gateway")?; @@ -455,7 +574,9 @@ mod tests { 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)?; + if path.exists() { + std::fs::remove_file(path)?; + } } fixture.apply( prepare_routing_at(&fixture.dir, RoutingMode::Hub, "token")?, @@ -555,7 +676,7 @@ mod tests { true, )?; fixture.apply( - prepare_routing_at(&fixture.dir, RoutingMode::Sub, "")?, + prepare_routing_at(&fixture.dir, RoutingMode::Sub, "token")?, true, )?; assert_eq!(fixture.manager().get_backups()?.len(), 1); diff --git a/crates/wizard-core/src/agents/desktop_install/claude.rs b/crates/wizard-core/src/agents/desktop_install/claude.rs index bf9b6a1..11c85af 100644 --- a/crates/wizard-core/src/agents/desktop_install/claude.rs +++ b/crates/wizard-core/src/agents/desktop_install/claude.rs @@ -212,14 +212,7 @@ pub(super) async fn check_release(token: &str, target: Target) -> Result { } } let mut response = request.send().await.map_err(|error| { - let message = - format!("Не удалось скачать {name} через прокси; проверьте токен и соединение"); if proxy_rejected_token(&error) { - anyhow!(message) + anyhow!(super::requests::TOKEN_REJECTED) } else { - interrupted(message) + wizard_proxy::diagnostics::error("desktop archive request", &error); + interrupted(format!( + "Не удалось скачать {name}: соединение с CoreInfra AI Hub прервано" + )) } })?; @@ -480,16 +482,6 @@ impl Transfer<'_> { } } -/// Whether the proxy refused the token, which reconnecting cannot fix. hyper-util's error type is -/// private, so only its message identifies the refusal. -fn proxy_rejected_token(error: &reqwest::Error) -> bool { - core::iter::successors( - Some(error as &(dyn core::error::Error + 'static)), - |error| error.source(), - ) - .any(|error| error.to_string() == "tunnel error: proxy authorization required") -} - /// The archive's `ETag`, if it can validate a range request. fn strong_etag(response: &Response) -> Option { response @@ -801,10 +793,7 @@ mod tests { ); let error = result.err().unwrap(); assert!(!error.is::()); - assert_eq!( - error.to_string(), - "Не удалось скачать Claude через прокси; проверьте токен и соединение" - ); + assert_eq!(error.to_string(), super::super::requests::TOKEN_REJECTED); assert_eq!(proxy.requests().len(), 1); } diff --git a/crates/wizard-core/src/agents/desktop_install/mod.rs b/crates/wizard-core/src/agents/desktop_install/mod.rs index d8c5674..f0bc382 100644 --- a/crates/wizard-core/src/agents/desktop_install/mod.rs +++ b/crates/wizard-core/src/agents/desktop_install/mod.rs @@ -3,6 +3,7 @@ mod chatgpt; mod claude; mod download; +mod requests; mod running; pub use download::{DownloadProgress, SavedDownload, download_release, saved_download}; @@ -298,14 +299,7 @@ fn client(token: &str) -> Result { /// Fetches a small update feed, refusing responses over `limit` bytes. async fn fetch_feed(client: &Client, url: &str, limit: usize) -> Result> { - let mut response = client - .get(url) - .timeout(Duration::from_secs(30)) - .send() - .await - .map_err(|_| { - anyhow!("Не удалось проверить обновления через прокси; проверьте токен и соединение") - })?; + let mut response = requests::feed_response(client, url).await?; ensure!( response.status().is_success(), "Сервер проверки обновлений вернул HTTP {}", diff --git a/crates/wizard-core/src/agents/desktop_install/requests.rs b/crates/wizard-core/src/agents/desktop_install/requests.rs new file mode 100644 index 0000000..5859ac0 --- /dev/null +++ b/crates/wizard-core/src/agents/desktop_install/requests.rs @@ -0,0 +1,203 @@ +//! Feed requests go directly through the Hub proxy, independently of the local daemon. + +use anyhow::{Result, anyhow, bail}; +use core::{error::Error, time::Duration}; +use reqwest::{Client, Response, StatusCode}; + +pub(super) const TOKEN_REJECTED: &str = + "Прокси CoreInfra AI Hub отклонил токен. Выберите действующий токен агента."; + +/// CONNECT failures have no HTTP response in reqwest. The dependency's tunnel error +/// is private; compare its fixed message without exposing arbitrary error contents. +pub(super) fn proxy_rejected_token(error: &reqwest::Error) -> bool { + causes(error).any(|error| error.to_string() == "tunnel error: proxy authorization required") +} + +fn causes<'a>(error: &'a (dyn Error + 'static)) -> impl Iterator { + core::iter::successors(Some(error), |error| (*error).source()).take(32) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Failure { + Token, + Tls, + Timeout, + Connection, + Other, +} + +impl Failure { + fn from_request(error: &reqwest::Error) -> Self { + if proxy_rejected_token(error) { + Self::Token + } else if causes(error).any(::is::) { + Self::Tls + } else if error.is_timeout() { + Self::Timeout + } else if error.is_connect() || error.is_request() { + Self::Connection + } else { + Self::Other + } + } + + const fn message(self) -> &'static str { + match self { + Self::Token => TOKEN_REJECTED, + Self::Tls => { + "Не удалось установить защищённое соединение через CoreInfra AI Hub. Проверьте дату и время, VPN и сертификаты системы." + } + Self::Timeout => { + "Проверка обновлений через CoreInfra AI Hub не дождалась ответа. Проверьте соединение и повторите попытку." + } + Self::Connection => { + "Не удалось подключиться к серверу обновлений через CoreInfra AI Hub. Проверьте интернет-соединение и VPN." + } + Self::Other => { + "Не удалось выполнить запрос обновлений через CoreInfra AI Hub. Повторите попытку." + } + } + } + + const fn retryable(self) -> bool { + matches!(self, Self::Timeout | Self::Connection) + } +} + +/// Retry an idempotent feed request once after a transient connection/server failure. +/// Keep vendor-specific statuses (including Claude's 204/404) for the caller to interpret. +pub(super) async fn feed_response(client: &Client, url: &str) -> Result { + let mut retried = false; + loop { + match client + .get(url) + .timeout(Duration::from_secs(30)) + .send() + .await + { + Ok(response) if response.status() == StatusCode::PROXY_AUTHENTICATION_REQUIRED => { + bail!(TOKEN_REJECTED); + } + Ok(response) + if !retried + && (response.status().is_server_error() + || response.status() == StatusCode::REQUEST_TIMEOUT) => + { + log::warn!( + "desktop feed request will retry: status={}", + response.status().as_u16() + ); + } + Ok(response) => return Ok(response), + Err(error) => { + let failure = Failure::from_request(&error); + log::warn!( + "desktop feed request failed: category={failure:?};{}", + wizard_proxy::diagnostics::summary(&error) + ); + if retried || !failure.retryable() { + return Err(anyhow!(failure.message())); + } + } + } + retried = true; + tokio::time::sleep(Duration::from_millis(500)).await; + } +} + +#[cfg(test)] +mod tests { + #![expect(clippy::unwrap_used, reason = "local HTTP fixtures")] + + extern crate alloc; + + use super::*; + use alloc::sync::Arc; + use core::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + async fn serve( + responses: Vec<&'static str>, + ) -> (String, Arc, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&requests); + let task = tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") && request.len() < 8192 { + if socket.read_exact(&mut byte).await.is_err() { + break; + } + request.push(byte[0]); + } + let index = count + .fetch_add(1, Ordering::SeqCst) + .min(responses.len() - 1); + let _ = socket.write_all(responses[index].as_bytes()).await; + } + }); + (format!("http://{address}"), requests, task) + } + + #[tokio::test] + async fn rejected_proxy_token_is_reported_without_retry_or_credentials() { + let (url, count, server) = serve(vec![ + "HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 0\r\n\r\n", + ]) + .await; + let client = Client::builder() + .no_proxy() + .proxy( + reqwest::Proxy::all(url) + .unwrap() + .basic_auth("fixture", "secret-token"), + ) + .build() + .unwrap(); + let error = feed_response(&client, "https://feed.invalid/update?secret=fixture") + .await + .unwrap_err(); + assert_eq!(error.to_string(), TOKEN_REJECTED); + assert_eq!(count.load(Ordering::SeqCst), 1); + assert!(!format!("{error:#}").contains("secret")); + server.abort(); + } + + #[tokio::test] + async fn temporary_server_failure_recovers_but_client_and_empty_responses_are_preserved() { + let client = Client::builder().no_proxy().build().unwrap(); + let (url, count, server) = serve(vec![ + "HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nnew", + ]) + .await; + let response = feed_response(&client, &url).await.unwrap(); + assert_eq!(response.text().await.unwrap(), "new"); + assert_eq!(count.load(Ordering::SeqCst), 2); + server.abort(); + for response in [ + "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 204 No Content\r\n\r\n", + "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n", + ] { + let (url, count, server) = serve(vec![response]).await; + let result = feed_response(&client, &url).await.unwrap(); + assert_eq!(result.status().as_u16().to_string(), &response[9..12]); + assert_eq!(count.load(Ordering::SeqCst), 1); + server.abort(); + } + } + + #[tokio::test] + async fn disconnected_feed_retries_once_and_does_not_blame_the_token() { + let (url, count, server) = serve(vec![""]).await; + let client = Client::builder().no_proxy().build().unwrap(); + let error = feed_response(&client, &url).await.unwrap_err(); + assert_eq!(error.to_string(), Failure::Connection.message()); + assert_eq!(count.load(Ordering::SeqCst), 2); + server.abort(); + } +} diff --git a/crates/wizard-core/src/config_files/backups.rs b/crates/wizard-core/src/config_files/backups.rs index c4f20f8..82ba4bd 100644 --- a/crates/wizard-core/src/config_files/backups.rs +++ b/crates/wizard-core/src/config_files/backups.rs @@ -35,7 +35,10 @@ impl AgentKind { }; 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 matches!( + name, + Some("claude_desktop_config.json" | "coreinfra-proxy-token") + ); } return parent .file_name() diff --git a/crates/wizard-gui/src/agents.rs b/crates/wizard-gui/src/agents.rs index 83fbed2..a1bb189 100644 --- a/crates/wizard-gui/src/agents.rs +++ b/crates/wizard-gui/src/agents.rs @@ -61,6 +61,7 @@ pub(crate) async fn launch_agent( app: tauri::AppHandle, agent: wizard_core::agents::launch::LaunchAgent, ) -> Result<(), String> { + ensure_agent_proxy(app.clone(), agent).await?; let settings = settings::get_state(&app).map_err(|error| format!("{error:#}"))?; tauri::async_runtime::spawn_blocking(move || { wizard_core::agents::launch::launch(agent, &settings) @@ -71,6 +72,50 @@ pub(crate) async fn launch_agent( .map_err(|error| format!("{error:#}")) } +fn needs_proxy( + agent: wizard_core::agents::launch::LaunchAgent, + settings: &wizard_settings::Settings, +) -> bool { + use wizard_core::agents::launch::LaunchAgent; + match agent { + LaunchAgent::ClaudeDesktop => settings.claude_proxy_enabled, + LaunchAgent::ChatGpt | LaunchAgent::Codex => settings.codex_proxy_enabled, + LaunchAgent::Claude | LaunchAgent::OpenCode | LaunchAgent::Pi => false, + } +} + +/// Opening an agent restores only its saved proxy configuration, never its routing mode. +#[tauri::command] +pub(crate) async fn ensure_agent_proxy( + app: tauri::AppHandle, + agent: wizard_core::agents::launch::LaunchAgent, +) -> Result<(), String> { + let settings = + settings::get_state(&app).map_err(|_| "Не удалось прочитать настройки Wizard")?; + if !needs_proxy(agent, &settings) { + return Ok(()); + } + proxy::observe(&app).await; + if proxy::running(&app) { + return Ok(()); + } + let result = async { + proxy::prepare_token(&app).await?; + proxy::sync(&app).await?; + let settings = settings::get_state(&app)?; + anyhow::ensure!( + !needs_proxy(agent, &settings) || proxy::running(&app), + "Локальный прокси не подтвердил готовность" + ); + Ok::<(), anyhow::Error>(()) + } + .await; + result.map_err(|error| { + log::error!("proxy startup on agent open failed: {error:#}"); + format!("Не удалось запустить локальный прокси: {error:#}") + }) +} + #[tauri::command] pub(crate) async fn get_agent_backups(agent: BackupAgent) -> Result, String> { // TODO: files can make this response large and include credentials. @@ -157,13 +202,7 @@ pub(crate) async fn prepare_agent_change( let settings = settings::get_state(&app).map_err(|error| format!("{error:#}"))?; - // Claude Desktop Sub needs only Wizard's upstream token, obtained on apply. - // Hub mode and the other agents still need their own direct API credential. - let token = if change.enabled() - && !matches!( - change, - AgentChange::ClaudeDesktopSetRouting(RoutingMode::Sub) - ) { + let token = if change.enabled() { match token { Some(TokenChoice::Existing { token }) if !token.is_empty() => token, Some(TokenChoice::Create) => { diff --git a/crates/wizard-gui/src/desktop_install.rs b/crates/wizard-gui/src/desktop_install.rs index 29bd5c7..f0bf417 100644 --- a/crates/wizard-gui/src/desktop_install.rs +++ b/crates/wizard-gui/src/desktop_install.rs @@ -79,11 +79,12 @@ enum Package { } const CHECK_INTERVAL: Duration = Duration::from_hours(24); +const FAILED_CHECK_INTERVAL: Duration = Duration::from_mins(5); #[derive(Default)] struct Session { package: Option, - last_check: Option, + next_check: Option, } pub(crate) struct InstallManager { @@ -183,7 +184,7 @@ pub(crate) fn start_background_checks(app: tauri::AppHandle) { let tokens = app.state::>(); // The timer's immediate first tick covers startup; wake only on later token changes. let mut revision = Some(tokens.current().revision); - // Only inspect the deadline here; network checks are limited by last_check. + // Only inspect the deadline here; network checks are limited by next_check. // This also retries a due check skipped while another operation held the lock. let mut timer = tokio::time::interval(Duration::from_mins(5)); timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); @@ -369,9 +370,7 @@ fn start( }; if automatic && (matches!(session.package, Some(Package::Downloaded(_))) - || session - .last_check - .is_some_and(|last| last.elapsed() < CHECK_INTERVAL)) + || session.next_check.is_some_and(|next| Instant::now() < next)) { return Ok(()); } @@ -382,8 +381,7 @@ fn start( Operation::Check => { // Checking again keeps a saved download only if the same release is found. session.package = None; - // Failed checks also count, so a bad token or offline network cannot cause a retry loop. - session.last_check = Some(Instant::now()); + session.next_check = Some(Instant::now() + CHECK_INTERVAL); manager.signal.notify(State::Checking); } Operation::Download => { @@ -432,8 +430,10 @@ fn start( .notify(AgentRevisionState); } if let Err(message) = result { - if automatic { - session.last_check = Some(Instant::now()); + if matches!(operation, Operation::Check) { + // A startup network failure must not hide updates for the next day. + // Keep a cooldown so rejected credentials cannot cause a retry loop. + session.next_check = Some(Instant::now() + FAILED_CHECK_INTERVAL); } match operation { Operation::Install => { @@ -479,7 +479,7 @@ async fn resolve_token( } /// The token in the application's routing configuration, else the Hub token Wizard created -/// for it, else Wizard's proxy token (Sub mode configures no agent token). +/// for it, else Wizard's proxy token for legacy configurations. async fn background_token( app: &tauri::AppHandle, desktop: DesktopApp, @@ -555,7 +555,7 @@ async fn run( }; log::info!("Starting {} background check", desktop.product()); session.package = None; - session.last_check = Some(Instant::now()); + session.next_check = Some(Instant::now() + CHECK_INTERVAL); manager.signal.notify(State::Checking); token } else { @@ -689,7 +689,7 @@ async fn run( })?; session.package = None; // Count the installation as the day's check, so its notices stay visible. - session.last_check = Some(Instant::now()); + session.next_check = Some(Instant::now() + CHECK_INTERVAL); if desktop == DesktopApp::ChatGpt { // A daemon started from the replaced bundle keeps running the old executable. diff --git a/crates/wizard-gui/src/lib.rs b/crates/wizard-gui/src/lib.rs index defcd32..9812dd9 100644 --- a/crates/wizard-gui/src/lib.rs +++ b/crates/wizard-gui/src/lib.rs @@ -134,6 +134,7 @@ pub fn run_application() -> Result<()> { proxy::get_proxy_state, agents::get_agent_state, agents::launch_agent, + agents::ensure_agent_proxy, agents::get_agent_backups, agents::prepare_agent_change, agents::apply_agent_plan, diff --git a/crates/wizard-gui/src/system_proxy.rs b/crates/wizard-gui/src/system_proxy.rs index ac2fa72..38e6b18 100644 --- a/crates/wizard-gui/src/system_proxy.rs +++ b/crates/wizard-gui/src/system_proxy.rs @@ -1,4 +1,4 @@ -//! Persisted daemon demand and independently observed OS state, shared by settings and tray. +//! Observed OS state, shared by settings and tray. //! Only explicit user operations change OS settings; observers never reconcile them. use crate::revision_signal::{RevisionSignal, RevisionSnapshot}; @@ -24,16 +24,11 @@ pub(crate) enum Status { } #[derive(Clone, Default, PartialEq, Eq, Serialize)] -#[expect( - clippy::struct_excessive_bools, - reason = "independent observed facts and persisted demand, not mutually exclusive states" -)] pub(crate) struct State { pub(crate) status: Status, pub(crate) busy: bool, pub(crate) conflict: bool, pub(crate) listener_running: bool, - pub(crate) requested: bool, read_error: Option, operation_error: Option, } @@ -50,7 +45,7 @@ impl State { pub(crate) fn can_toggle(&self) -> bool { !self.busy && self.status != Status::Unsupported - && (self.requested || self.has_ours() || (self.status == Status::Off && !self.conflict)) + && (self.has_ours() || (self.status == Status::Off && !self.conflict)) } } @@ -129,14 +124,12 @@ fn sync_tray(app: &tauri::AppHandle) { let _ = app; } -fn observe_current(app: &tauri::AppHandle) -> Result { - let requested = crate::settings::get_state(app)?.system_proxy_enabled; +fn observe_current(app: &tauri::AppHandle) -> State { let status = os::status(); update(&app.state::>(), |state| { - state.requested = requested; observe(state, status, crate::proxy::running(app)); }); - Ok(current(app)) + current(app) } fn os_errors(write: Result<()>, observed: &State, enabled: bool) -> Vec { @@ -202,7 +195,7 @@ fn apply(app: &tauri::AppHandle, enabled: bool, forced: bool) -> Result<()> { if let Err(error) = started { // Startup can time out after taking effect. Restore demand, but never // shut down a listener that the OS may already be using. - let observed = observe_current(app)?; + let observed = observe_current(app); let keep = previous.system_proxy_enabled || observed.status != Status::Off; crate::settings::update_state_locked(app, &guard, |settings| { settings.system_proxy_enabled = keep; @@ -225,7 +218,7 @@ fn apply(app: &tauri::AppHandle, enabled: bool, forced: bool) -> Result<()> { } else { os::disable() }; - let observed = observe_current(app)?; // Also after partial writes or failed verification. + let observed = observe_current(app); // Also after partial writes or failed verification. let mut errors = os_errors(write, &observed, enabled); let demand = if observed.status == Status::Off { enabled && previous.system_proxy_enabled @@ -290,7 +283,7 @@ async fn run(app: tauri::AppHandle, enabled: Option, forced: bool) -> Resu if let Some(enabled) = enabled { apply(&worker_app, enabled, forced).map_err(|error| format!("{error:#}")) } else { - let state = observe_current(&worker_app).map_err(|error| format!("{error:#}"))?; + let state = observe_current(&worker_app); state.read_error.map_or(Ok(()), Err) } })(); @@ -300,9 +293,6 @@ async fn run(app: tauri::AppHandle, enabled: Option, forced: bool) -> Resu update(&signal, |state| { state.busy = false; state.listener_running = crate::proxy::running(&worker_app); - if let Ok(settings) = crate::settings::get_state(&worker_app) { - state.requested = settings.system_proxy_enabled; - } if let Err(error) = &result { state.operation_error = Some(error.clone()); } @@ -371,7 +361,7 @@ pub(crate) async fn get_system_proxy_state( "Операции системного прокси недоступны; перезапустите Wizard".to_owned() })?; tauri::async_runtime::block_on(crate::proxy::observe(&app)); - observe_current(&app).map_err(|error| format!("{error:#}"))?; + observe_current(&app); sync_tray(&app); Ok::<(), String>(()) }) @@ -404,7 +394,7 @@ pub(crate) fn toggle_from_tray(app: &tauri::AppHandle) { } let app = app.clone(); tauri::async_runtime::spawn(async move { - if set_system_proxy(app.clone(), !(state.requested || state.has_ours()), false) + if set_system_proxy(app.clone(), !state.has_ours(), false) .await .is_err() { diff --git a/crates/wizard-gui/src/system_proxy/tests.rs b/crates/wizard-gui/src/system_proxy/tests.rs index 86314d7..acf334a 100644 --- a/crates/wizard-gui/src/system_proxy/tests.rs +++ b/crates/wizard-gui/src/system_proxy/tests.rs @@ -40,13 +40,25 @@ fn aggregates_os_settings_without_treating_a_stopped_listener_as_a_conflict() { observe(&mut state, Ok(SystemProxyStatus { services: vec![] }), true); assert_eq!(state.status, Status::Unavailable); assert!(!state.can_toggle()); +} + +#[test] +fn external_disable_allows_enabling_again_while_the_listener_keeps_running() { + use ProxyState::{Disabled, Foreign, Wizard}; + let mut state = State::default(); + observe(&mut state, Ok(snapshot(Wizard, Wizard, false)), true); + assert!(state.has_ours()); - // External OS changes must not erase saved demand or prevent cancelling it. - state.requested = true; - observe(&mut state, Ok(snapshot(Foreign, Foreign, true)), false); + observe(&mut state, Ok(snapshot(Disabled, Disabled, false)), true); assert_eq!(state.status, Status::Off); - assert!(state.requested); + assert!(!state.has_ours()); + assert!(state.listener_running); assert!(state.can_toggle()); + + observe(&mut state, Ok(snapshot(Foreign, Foreign, true)), true); + assert_eq!(state.status, Status::Off); + assert!(!state.has_ours()); + assert!(!state.can_toggle()); } #[test] diff --git a/crates/wizard-gui/src/tray.rs b/crates/wizard-gui/src/tray.rs index daecd33..27dbbea 100644 --- a/crates/wizard-gui/src/tray.rs +++ b/crates/wizard-gui/src/tray.rs @@ -105,9 +105,6 @@ fn system_proxy_label(state: &crate::system_proxy::State) -> &'static str { if state.busy { return "Системный прокси — применение…"; } - if state.requested { - return "Выключить системный прокси"; - } match state.status { Status::Unknown => "Системный прокси — состояние неизвестно", Status::Unavailable => "Системный прокси — нет сетевых сервисов", diff --git a/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx b/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx index 8acc0bb..34de81a 100644 --- a/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx +++ b/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx @@ -5,7 +5,6 @@ import { agentPaths, overviewPath, type AgentPageId, type AppPageId } from "./ag import { AppLogo } from "./components/AppLogo"; import { ClaudeIcon, OpenAiIcon, OpenCodeIcon, PiIcon } from "./components/BrandIcons"; import { Button } from "./components/catalyst/button"; -import { Divider } from "./components/catalyst/divider"; import { Sidebar, SidebarBody, SidebarFooter, SidebarHeader, SidebarHeading, SidebarItem, SidebarLabel, SidebarSection, SidebarSpacer } from "./components/catalyst/sidebar"; import { type HubAccountControl, HubAccountMenu } from "./settings/HubAccount"; import type { UpdateObservation } from "./updates/update"; @@ -47,9 +46,6 @@ export function AppSidebar({ page, account, update }: { Агенты {item("claude_desktop", "Claude Desktop", ClaudeIcon)} {item("codex", "ChatGPT / Codex", OpenAiIcon)} -
- -
{item("claude", "Claude Code", ClaudeIcon)} {item("opencode", "OpenCode", OpenCodeIcon)} {item("pi", "Pi", PiIcon)} diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx index 73150b1..c3890a8 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx @@ -1,8 +1,10 @@ import { type ReactNode, useEffect, useState } from "react"; +import { CheckIcon } from "@heroicons/react/20/solid"; import { type AgentChange, type AgentId, type HubMode, type RoutingMode, type TokenChoice } from "./agents_state"; -import { type HubTokensState, refreshHubTokens } from "../settings/hub_tokens"; +import { type HubTokensState, refreshHubTokens, tokenPrefix } from "../settings/hub_tokens"; import { reportError } from "../logs/log"; import { Button } from "../components/catalyst/button"; +import { Dropdown, DropdownButton, DropdownDescription, DropdownItem, DropdownLabel, DropdownMenu } from "../components/catalyst/dropdown"; import { FieldGroup, Fieldset, Label, Legend } from "../components/catalyst/fieldset"; import { Radio, RadioField, RadioGroup } from "../components/catalyst/radio"; import { Text } from "../components/catalyst/text"; @@ -58,8 +60,25 @@ export function getAgentToken(agent: AgentId, agentToken: string | null, hub: Hu return { selected, ready, name: existing ? existing.name || "без названия" : createdName }; } +// Keep a choice local to this agent's form and reuse it for downloads. A token +// must still be listed in the active Hub; saved configuration changes reset it. +export function useAgentToken(agent: AgentId, agentToken: string | null, hub: Hub) { + const [draft, setDraft] = useState<{ agent: AgentId; agentToken: string | null; token: string }>(); + const automatic = getAgentToken(agent, agentToken, hub); + const chosen = draft?.agent === agent && draft.agentToken === agentToken + ? hub.tokens.find((item) => item.token === draft.token) : undefined; + const token = automatic.ready && chosen + ? { ...automatic, selected: { kind: "existing" as const, token: chosen.token }, name: chosen.name || "без названия" } + : automatic; + return { + ...token, + automatic, + choose: (value: string | undefined) => setDraft(value === undefined ? undefined : { agent, agentToken, token: value }), + }; +} + export function TokenNote({ token, hub, disabled }: { - token: ReturnType; + token: ReturnType; hub: Hub; disabled: boolean; }) { @@ -71,13 +90,35 @@ export function TokenNote({ token, hub, disabled }: { }}>Повторить ; if (!token.ready) return Проверяем токен агента…; - return {token.selected?.kind === "create" ? "Будет создан и использован" : "Будет использован"} токен «{token.name}» для аутентификации в хабе.; + return + {token.selected?.kind === "create" ? "Будет создан и использован" : "Будет использован"} токен «{token.name}» для аутентификации в хабе.{" "} + + + Изменить + + + {hub.tokens.map((item) => { + const selected = token.selected?.kind === "existing" && token.selected.token === item.token; + return token.choose(item.token)}> + {selected && } + {item.name || "Без названия"} + {tokenPrefix(item.token)} + ; + })} + {token.automatic.selected?.kind === "create" && token.choose(undefined)}> + {token.selected?.kind === "create" && } + Создать «{token.automatic.name}» + } + + + ; } // The same connection form is used by the agent page and initial setup. -export function RoutingFieldset({ agent, modes, mode, toChange, agentToken, token: tokenOverride, hub, note, disabled, error, onPrepare, initialMode, actions, actionsClassName = "" }: { +export function RoutingFieldset({ agent, modes, mode, toChange, agentToken, token: tokenOverride, hub, note, disabled, error, onPrepare, initialMode, actions, actionsClassName = "", editing = false, needsApply = false }: { agent: AgentId; - token?: ReturnType; + token?: ReturnType; modes: ModeOption[]; mode: M; toChange: (mode: M) => AgentChange; @@ -90,12 +131,16 @@ export function RoutingFieldset({ agent, modes, mode, toChange initialMode?: M; actions?: ReactNode; actionsClassName?: string; + editing?: boolean; + needsApply?: boolean; }) { const [draft, setDraft] = useState(initialMode); const selected = draft ?? mode; const enabled = selected !== "disabled"; - const proxyOnly = agent === "claude_desktop" && selected === "sub"; - const token = tokenOverride ?? getAgentToken(agent, agentToken, hub); + const localToken = useAgentToken(agent, agentToken, hub); + const token = tokenOverride ?? localToken; + const changed = selected !== mode || (enabled && (needsApply || token.selected?.kind === "create" + || (token.selected?.kind === "existing" && token.selected.token !== agentToken))); const systemProxy = useSystemProxy(); const [proxyPrompt, setProxyPrompt] = useState(false); @@ -121,13 +166,12 @@ export function RoutingFieldset({ agent, modes, mode, toChange ))} - {proxyOnly ? Для аутентификации будет использован токен «coreinfra-ai-wizard» из личного хаба. Если его ещё нет, Wizard создаст его автоматически. - : (enabled || tokenOverride !== undefined) && } + {(enabled || tokenOverride !== undefined) && }
{actions} -
{error && {error}} diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx index 233f605..8bae633 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx @@ -1,12 +1,12 @@ import { Fragment, type ReactNode, useState } from "react"; import { type AgentChange, type AgentDetection, type AgentId, type AgentStates, type BackupAgent, type PreparedAgentChange, type RoutingMode, type TokenChoice, prepareAgentChange } from "./agents_state"; -import { currentModeLabels, routingModes, hubModes, getAgentToken, TokenNote, RoutingFieldset, type Hub } from "./AgentConfiguration"; +import { currentModeLabels, routingModes, hubModes, useAgentToken, TokenNote, RoutingFieldset, type Hub } from "./AgentConfiguration"; import { PreparedPlanDialog } from "./PreparedPlanDialog"; import { BackupDialog } from "./BackupDialog"; import { DesktopInstall, useDesktopInstall } from "./DesktopInstall"; import { tokenLabel, useHubTokens } from "../settings/hub_tokens"; import type { HubAccountControl } from "../settings/HubAccount"; -import { useProxy } from "./proxy"; +import { useAgentProxyStartup, useProxy } from "./proxy"; import { reportError } from "../logs/log"; import { Badge } from "../components/catalyst/badge"; import { Button } from "../components/catalyst/button"; @@ -55,12 +55,21 @@ function RoutingRows({ mode, agentToken, hub }: { } // Shared daemon state; each page decides what it means for its app. -function ProxyStatus({ proxy: { proxy, error } }: { proxy: ReturnType }) { +function ProxyStatus({ proxy: { proxy, error }, startup }: { + proxy: ReturnType; + startup: ReturnType; +}) { + // Apply or the system-proxy action can recover after an earlier startup failure. + if (error === undefined && proxy?.enabled) return Работает; + if (startup.starting) return Запускается…; + if (startup.error) return
+ {startup.error} + +
; if (error !== undefined) return Состояние недоступно; if (proxy === undefined) return Загрузка…; - const running = proxy.enabled; - return {running ? "Работает" : "Остановлен"}; + return Остановлен; } function BackupButton({ agent, disabled }: { agent: BackupAgent; disabled: boolean }) { @@ -91,11 +100,14 @@ export function AgentPage({ agents, page, proxy, account }: { ...useHubTokens(account.account?.active_hub_id), signedIn: account.signedIn, }; - const claudeDesktopToken = getAgentToken("claude_desktop", agents.claude_desktop.status === "found" ? agents.claude_desktop.data.token : null, hub); + const claudeDesktopToken = useAgentToken("claude_desktop", agents.claude_desktop.status === "found" ? agents.claude_desktop.data.token : null, hub); const claudeInstall = useDesktopInstall("claude"); // ChatGPT downloads use the token of the shared ChatGPT / Codex routing. - const codexToken = getAgentToken("codex", agents.codex.status === "found" ? agents.codex.data.token : null, hub); + const codexToken = useAgentToken("codex", agents.codex.status === "found" ? agents.codex.data.token : null, hub); const chatGptInstall = useDesktopInstall("chatgpt"); + const proxyAgent = page === "codex" || page === "claude_desktop" ? page : null; + const proxyDetection = proxyAgent ? agents[proxyAgent] : undefined; + const proxyStartup = useAgentProxyStartup(proxyDetection?.status === "found" && proxyDetection.data.routing_mode !== "disabled" ? proxyAgent : null); async function prepare(change: AgentChange, token: TokenChoice | null) { if (isChangeInProgress) return; @@ -123,7 +135,7 @@ export function AgentPage({ agents, page, proxy, account }: { case "codex": { const codex = agents.codex; const chatGptFound = codex.status === "found" && codex.data.desktop.status === "found"; - const chatGptProxyStopped = proxy.proxy?.enabled === false && chatGptFound + const chatGptProxyStopped = !proxyStartup.starting && proxy.proxy?.enabled === false && chatGptFound && codex.status === "found" && codex.data.routing_mode !== "disabled"; content = ( <> @@ -138,8 +150,7 @@ export function AgentPage({ agents, page, proxy, account }: { Прокси для ChatGPT - - {chatGptProxyStopped && Прокси для ChatGPT не запущен, нажмите «Завершить настройку».} + {codex.status === "found" && ( @@ -147,7 +158,7 @@ export function AgentPage({ agents, page, proxy, account }: { )} {codex.status === "found" && ( - ({ CodexSetRouting: mode })} agentToken={codex.data.token} hub={hub} note="Настройка общая для ChatGPT и Codex." disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> )} @@ -178,7 +189,7 @@ export function AgentPage({ agents, page, proxy, account }: { )} {claude.status === "found" && ( - ({ ClaudeSetRouting: mode })} agentToken={claude.data.token} hub={hub} disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> )} @@ -197,13 +208,13 @@ export function AgentPage({ agents, page, proxy, account }: { {desktop.status === "found" && ( <> Прокси - + )} {desktop.status === "found" && ( - ({ ClaudeDesktopSetRouting: mode })} agentToken={desktop.data.token} hub={hub} disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> )} @@ -234,7 +245,7 @@ export function AgentPage({ agents, page, proxy, account }: { )} {detection.status === "found" && ( - (page === "opencode" ? { SetOpenCodeHub: mode } : { SetPiHub: mode })} agentToken={detection.data.token} hub={hub} disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> )} @@ -248,7 +259,7 @@ export function AgentPage({ agents, page, proxy, account }: { <> {/* Keyed so that drafts of one agent's form never carry over to another agent. */} {content} - {preparedChange && setPreparedChange(undefined)} />} + {preparedChange && setPreparedChange(undefined)} applyLabel="Применить" />} ); } diff --git a/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx b/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx index fa3abc1..e3d7e8b 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx @@ -14,11 +14,12 @@ const agentNames: Record = { claude_desktop: "Claude Desktop", }; -export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied }: { +export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied, applyLabel = "Завершить настройку" }: { prepared: PreparedAgentChange; onReprepared: (prepared: PreparedAgentChange) => void; onClose: () => void; onApplied?: () => void; + applyLabel?: "Применить" | "Завершить настройку"; }) { const { agent, info } = prepared; const hasChanges = info.length > 0; @@ -95,7 +96,7 @@ export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied {repreparing ? "Пересоздание…" : "Пересоздать"} } {hasChanges && } diff --git a/crates/wizard-gui/wizard-ui/src/agents/proxy.ts b/crates/wizard-gui/wizard-ui/src/agents/proxy.ts index 10d2d0e..4427f65 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/proxy.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/proxy.ts @@ -1,10 +1,32 @@ import { invoke } from "@tauri-apps/api/core"; import { useEffect, useState } from "react"; import { reportError } from "../logs/log"; +import type { AgentId } from "./agents_state"; export type Proxy = { enabled: boolean }; type ProxySnapshot = Proxy & { revision: number }; +export function useAgentProxyStartup(agent: AgentId | null) { + const [attempt, setAttempt] = useState(0); + const [result, setResult] = useState<{ agent: AgentId; attempt: number; error?: string }>(); + useEffect(() => { + setResult(undefined); + if (!agent) return; + let stopped = false; + void invoke("ensure_agent_proxy", { agent }).then(() => { + if (!stopped) setResult({ agent, attempt }); + }).catch((cause: unknown) => { + if (stopped) return; + const error = typeof cause === "string" ? cause : "Не удалось запустить локальный прокси"; + reportError("Не удалось запустить прокси при открытии агента", cause); + setResult({ agent, attempt, error }); + }); + return () => { stopped = true; }; + }, [agent, attempt]); + const current = result?.agent === agent && result?.attempt === attempt ? result : undefined; + return { starting: Boolean(agent) && !current, error: current?.error, retry: () => setAttempt(value => value + 1) }; +} + export function useProxy(): { proxy: Proxy | undefined; error: string | undefined } { const [proxy, setProxy] = useState(); const [error, setError] = useState(); diff --git a/crates/wizard-gui/wizard-ui/src/onboarding/InstallCard.tsx b/crates/wizard-gui/wizard-ui/src/onboarding/InstallCard.tsx index 90901db..565ace1 100644 --- a/crates/wizard-gui/wizard-ui/src/onboarding/InstallCard.tsx +++ b/crates/wizard-gui/wizard-ui/src/onboarding/InstallCard.tsx @@ -130,8 +130,8 @@ export function InstallCard({ choice, observation, token, tokenReady, found, ver } if (active && downloaded) return