diff --git a/README.md b/README.md index 2aa456e..86c130c 100644 --- a/README.md +++ b/README.md @@ -103,11 +103,16 @@ 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 API configuration and downloads. Claude Desktop's +subscription uses Wizard's shared proxy token and needs no separate agent token. +The local proxy has exactly two listeners: `127.0.0.1:33787` for Claude Desktop and +the system proxy, and `127.0.0.1:33788` for ChatGPT. Both use the same Wizard token; +changing an agent's API token does not change either listener's credential. +«Завершить настройку» 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..b9028e6 100644 --- a/crates/wizard-core/src/agents/claude_desktop.rs +++ b/crates/wizard-core/src/agents/claude_desktop.rs @@ -20,6 +20,8 @@ use std::{ use wizard_settings::Settings; const HUB_URL: &str = "https://hub.coreinfra.ai/anthropic/api"; +// Read-only compatibility with an unreleased configuration. Never bind this port. +const RETIRED_PROXY_URL: &str = "http://127.0.0.1:33789"; pub(crate) static CONFIG_LOCK: Mutex<()> = Mutex::new(()); #[derive(Clone, Debug, Serialize, PartialEq, Eq)] @@ -28,6 +30,7 @@ pub(crate) struct ClaudeDesktop { pub info: AgentInfo, pub routing_mode: RoutingMode, pub token: Option, + pub proxy_needs_apply: bool, } pub(super) fn detect(settings: &Settings) -> AgentDetection { @@ -40,7 +43,7 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { AgentDetection::Error(error) => return AgentDetection::Error(error), }; - let (routing_mode, token) = match read_routing() { + let (routing_mode, token, proxy_needs_apply) = match read_routing() { Ok(routing) => routing, Err(error) => return AgentDetection::Error(format!("{error:#}")), }; @@ -48,6 +51,7 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { info, routing_mode, token, + proxy_needs_apply, }) } @@ -118,6 +122,18 @@ 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)?; + // An old backup must not point Claude at a listener that no longer exists. + for change in &mut changes { + if change.path().parent() == Some(dir) + && let Ok(profile) = json::parse(&change.after) + && profile["egressProxyUrl"] == RETIRED_PROXY_URL + { + json::update(&mut change.after, |profile| { + profile["egressProxyUrl"] = json!(format!("http://{}", wizard_proxy::ADDRESS)); + Ok(()) + })?; + } + } // 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"); @@ -162,34 +178,35 @@ fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result Result<(RoutingMode, Option)> { +fn read_routing() -> Result<(RoutingMode, Option, bool)> { let _guard = PreparedAgent::ClaudeDesktop.lock()?; read_routing_at(&config_library()?) } -fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option)> { +fn read_routing_at(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)); + return Ok((RoutingMode::Disabled, None, false)); }; 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_needs_apply = config["egressProxyUrl"] == RETIRED_PROXY_URL; if preferences["deploymentMode"] == "1p" - && config["egressProxyUrl"] == proxy_url + && (config["egressProxyUrl"] == proxy_url || proxy_needs_apply) && config.get("egressProxyPacUrl").is_none() { - Ok((RoutingMode::Sub, None)) + Ok((RoutingMode::Sub, None, proxy_needs_apply)) } else if preferences["deploymentMode"] != "1p" && has_hub_connection(&config) { let token = config["inferenceGatewayApiKey"] .as_str() .and_then(|token| AgentToken::new(token.to_owned())); - Ok((RoutingMode::Hub, token)) + Ok((RoutingMode::Hub, token, proxy_needs_apply)) } else { - Ok((RoutingMode::Disabled, None)) + Ok((RoutingMode::Disabled, None, false)) } } @@ -300,6 +317,57 @@ mod tests { use super::*; use crate::config_files::changes::FileSnapshot; + #[test] + fn first_launch_needs_only_precreated_configuration() -> Result<()> { + for mode in [RoutingMode::Hub, RoutingMode::Sub] { + let root = tempfile::tempdir()?; + let dir = root.path().join("Claude-3p/configLibrary"); + let plan = prepare_routing_at(&dir, mode, "test-agent-token")?; + assert!(!dir.parent().expect("profile directory").exists()); + let mut activated = false; + plan.apply_with_backup( + None, + |enabled| { + assert!(enabled); + // All files must be present before starting the proxy or the desktop app. + let meta = json::read(&dir.join("_meta.json"))?; + let id = applied_id(&meta)?.expect("selected profile"); + assert_eq!(meta["entries"], json!([{ "id": id, "name": "CoreInfra" }])); + let profile = json::read(&dir.join(format!("{id}.json")))?; + assert_eq!(profile["egressProxyUrl"], "http://127.0.0.1:33787"); + let preferences = + json::read(&dir.with_file_name("claude_desktop_config.json"))?; + assert_eq!( + preferences["deploymentMode"], + if mode == RoutingMode::Hub { "3p" } else { "1p" } + ); + if mode == RoutingMode::Sub { + assert!(profile.get("inferenceGatewayApiKey").is_none()); + } + activated = true; + Ok(()) + }, + |_| panic!("unexpected ChatGPT proxy"), + )?; + assert!(activated); + let (detected, token, needs_apply) = read_routing_at(&dir)?; + assert_eq!(detected, mode); + assert!(!needs_apply); + assert_eq!( + token.map(AgentToken::into_secret).as_deref(), + (mode == RoutingMode::Hub).then_some("test-agent-token") + ); + + let repeated = prepare_routing_at(&dir, mode, "test-agent-token")?; + assert!(repeated.steps().iter().all(|step| match step { + PreparedStep::ChangeFile { change } => !change.is_changed(), + _ => true, + })); + assert_eq!(std::fs::read_dir(&dir)?.count(), 2); + } + Ok(()) + } + struct Fixture { root: tempfile::TempDir, dir: PathBuf, @@ -434,6 +502,51 @@ mod tests { Ok(()) } + #[test] + fn retired_proxy_configuration_is_repaired_on_apply_and_backup_restore() -> Result<()> { + for mode in [RoutingMode::Hub, RoutingMode::Sub] { + let fixture = Fixture::new("gateway")?; + let token = if mode == RoutingMode::Hub { + "api-token" + } else { + "" + }; + fixture.apply(prepare_routing_at(&fixture.dir, mode, token)?, true)?; + + 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_routing_at(&fixture.dir)?; + assert_eq!(detected, mode); + assert!(needs_apply); + assert_eq!(agent_token.is_some(), mode == RoutingMode::Hub); + // Detection leaves the user's profile unchanged; Apply confirms the repair. + assert_eq!(json::read(&fixture.files[0])?, profile); + + fixture.apply(prepare_routing_at(&fixture.dir, mode, token)?, true)?; + assert_eq!(fixture.manager().get_backups()?.len(), 2); + assert!(!read_routing_at(&fixture.dir)?.2); + + // Restoring the backup of the retired configuration keeps the two-port layout. + fixture.apply( + prepare_restore_at(&fixture.dir, &fixture.manager(), 2)?, + true, + )?; + assert_eq!( + json::read(&fixture.files[0])?["egressProxyUrl"], + "http://127.0.0.1:33787" + ); + let (restored_mode, restored_token, needs_apply) = read_routing_at(&fixture.dir)?; + assert_eq!(restored_mode, mode); + assert!(!needs_apply); + assert_eq!( + restored_token.map(AgentToken::into_secret).as_deref(), + (mode == RoutingMode::Hub).then_some("api-token") + ); + } + Ok(()) + } + #[test] fn backup_failure_prevents_configuration_and_proxy_changes() -> Result<()> { let fixture = Fixture::new("gateway")?; @@ -602,8 +715,9 @@ mod tests { std::fs::write(&profile_path, original.to_string())?; std::fs::write(&preferences_path, r#"{"deploymentMode":"3p"}"#)?; - let (detected, token) = read_routing_at(&dir)?; + let (detected, token, proxy_needs_apply) = read_routing_at(&dir)?; assert_eq!(detected, RoutingMode::Hub); + assert!(!proxy_needs_apply); assert_eq!( token.map(AgentToken::into_secret).as_deref(), Some("manual-token") diff --git a/crates/wizard-core/src/agents/codex.rs b/crates/wizard-core/src/agents/codex.rs index 68355f9..3a128cd 100644 --- a/crates/wizard-core/src/agents/codex.rs +++ b/crates/wizard-core/src/agents/codex.rs @@ -33,6 +33,7 @@ pub(crate) struct Codex { pub desktop: AgentDetection, pub routing_mode: RoutingMode, pub token: Option, + pub proxy_needs_apply: bool, } pub(super) fn detect(settings: &Settings) -> AgentDetection { @@ -59,11 +60,16 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { Ok(routing) => routing, Err(error) => return AgentDetection::Error(format!("{error:#}")), }; + let proxy_needs_apply = !cfg!(target_os = "linux") + && routing_mode != RoutingMode::Disabled + && matches!(desktop, AgentDetection::Found(_)) + && (!settings.codex_proxy_enabled || desktop_proxy_needs_apply()); AgentDetection::Found(Codex { cli, desktop, routing_mode, token, + proxy_needs_apply, }) } @@ -258,26 +264,34 @@ pub fn prepare_routing_for_gui( ) -> Result { let mut plan = prepare_routing(mode, token, settings)?; // Linux cannot start the local proxy yet: route only the CLI there. - let enabled = if mode == RoutingMode::Disabled || cfg!(target_os = "linux") { - false + let desktop = if cfg!(target_os = "linux") { + AgentDetection::NotFound } else { - match detection::detect_desktop( + detection::detect_desktop( DesktopAgent::Codex, settings.last_paths.codex_desktop.as_deref(), - ) { - AgentDetection::Found(_) => true, - // Clean up a configuration left from before ChatGPT was removed. - AgentDetection::NotFound => false, - AgentDetection::Error(error) => { - anyhow::bail!("failed to detect ChatGPT for local proxy: {error}") - } - } + ) }; + if mode != RoutingMode::Disabled + && let AgentDetection::Error(error) = &desktop + { + anyhow::bail!("failed to detect ChatGPT for local proxy: {error}"); + } + let installed = matches!(desktop, AgentDetection::Found(_)); + let enabled = mode != RoutingMode::Disabled && installed; + if let AgentDetection::Found(info) = desktop { + plan.restart_desktop( + super::desktop_install::DesktopApp::ChatGpt, + Some(&info.path), + ); + } // Without ChatGPT installed (Windows), there is no profile to clean up when disabling. match desktop_preferences_path()? { Some(path) => { - let change = prepare_desktop_proxy(path, enabled)?; - plan.steps.insert(0, PreparedStep::ChangeFile { change }); + // Read after shutdown to preserve the app's final writes. A first installation + // needs only the proxy preference; Chromium initializes the rest on first launch. + plan.steps + .insert(0, PreparedStep::SetChatGptProxy { path, enabled }); } None => ensure!(!enabled, "ChatGPT profile location is unavailable"), } @@ -329,30 +343,41 @@ Join-Path $root 'LocalCache\Roaming\Codex\web\Codex\Default\Preferences' | Conve } } -fn prepare_desktop_proxy(path: PathBuf, enabled: bool) -> Result { +fn desktop_proxy_needs_apply() -> bool { + let current = desktop_preferences_path().and_then(|path| { + let path = path.context("ChatGPT profile location is unavailable")?; + desktop_proxy_needs_apply_at(path) + }); + current.unwrap_or_else(|error| { + // A desktop profile problem must not hide an otherwise usable Codex CLI. + log::warn!("ChatGPT proxy configuration needs checking: {error:#}"); + true + }) +} + +fn desktop_proxy_needs_apply_at(path: PathBuf) -> Result { + Ok(prepare_desktop_proxy(path, true)?.is_changed()) +} + +pub(crate) fn prepare_desktop_proxy(path: PathBuf, enabled: bool) -> Result { use crate::config_files::{changes::FileSnapshot, json}; use serde_json::json; let mut change = FileChange::read(std::path::absolute(path)?)?; - // ChatGPT creates its profile on first launch; until then there is nothing to clean up. - if matches!(change.after, FileSnapshot::Missing) { - // Linux detection accepts any `chatgpt` executable, which may be another program. - ensure!( - !enabled || cfg!(target_os = "linux"), - "ChatGPT ещё не запускался: откройте его один раз и повторите." - ); - log::info!("ChatGPT proxy configuration skipped: profile Preferences file is missing"); + // Disabling an absent profile is a no-op. Enabling creates only the standard Chromium + // proxy preference; no cookies, database, Local State or first-run markers are needed. + if !enabled && matches!(change.after, FileSnapshot::Missing) { return Ok(change); } let proxy = json!({ "mode": "fixed_servers", - "server": format!("http://{}", wizard_proxy::ADDRESS), + "server": format!("http://{}", wizard_proxy::CHATGPT_ADDRESS), }); // Continue recognizing the previous ChatGPT endpoint as Wizard's configuration. let previous_proxy = json!({ "mode": "fixed_servers", - "server": format!("http://{}", wizard_proxy::OLD_ADDRESS), + "server": format!("http://{}", wizard_proxy::ADDRESS), }); json::update(&mut change.after, |config| { let current = config.get("proxy"); @@ -602,10 +627,81 @@ mod tests { use serde_json::json; #[test] - fn chatgpt_uses_lower_port_and_recognizes_both_wizard_endpoints() -> Result<()> { + fn chatgpt_can_be_configured_before_its_first_launch() -> Result<()> { + let directory = tempfile::tempdir()?; + let path = directory.path().join("Codex/Default/Preferences"); + let change = prepare_desktop_proxy(path.clone(), true)?; + assert!( + !directory.path().join("Codex").exists(), + "preparation must not write" + ); + FileChange::apply_all(&[change])?; + assert_eq!( + config_files::json::read(&path)?, + json!({ + "proxy": { "mode": "fixed_servers", "server": "http://127.0.0.1:33788" }, + }) + ); + assert!(!prepare_desktop_proxy(path, true)?.is_changed()); + Ok(()) + } + + #[test] + fn chatgpt_disabling_before_first_launch_creates_nothing() -> Result<()> { + let directory = tempfile::tempdir()?; + let path = directory.path().join("Codex/Default/Preferences"); + let change = prepare_desktop_proxy(path, false)?; + assert!(!change.is_changed()); + FileChange::apply_all(&[change])?; + assert!(!directory.path().join("Codex").exists()); + Ok(()) + } + + #[test] + fn chatgpt_first_launch_cannot_be_overwritten_by_a_stale_plan() -> Result<()> { + let directory = tempfile::tempdir()?; + let path = directory.path().join("Preferences"); + let change = prepare_desktop_proxy(path.clone(), true)?; + let initialized = r#"{"profile":{"name":"First launch"},"unrelated":true}"#; + std::fs::write(&path, initialized)?; + assert!(FileChange::apply_all(&[change]).is_err()); + assert_eq!(std::fs::read_to_string(&path)?, initialized); + FileChange::apply_all(&[prepare_desktop_proxy(path.clone(), true)?])?; + let config = config_files::json::read(&path)?; + assert_eq!(config["profile"]["name"], "First launch"); + assert_eq!(config["unrelated"], true); + assert_eq!(config["proxy"]["server"], "http://127.0.0.1:33788"); + Ok(()) + } + + #[test] + fn chatgpt_proxy_pending_tracks_profile_not_shared_daemon() -> Result<()> { + let directory = tempfile::tempdir()?; + let path = directory.path().join("Preferences"); + assert!(desktop_proxy_needs_apply_at(path.clone())?); + assert!(!path.exists()); + for (proxy, pending) in [ + (serde_json::Value::Null, true), + ( + json!({ "mode": "fixed_servers", "server": "http://127.0.0.1:33787" }), + true, + ), + ( + json!({ "mode": "fixed_servers", "server": "http://127.0.0.1:33788" }), + false, + ), + ] { + std::fs::write(&path, json!({ "proxy": proxy }).to_string())?; + assert_eq!(desktop_proxy_needs_apply_at(path.clone())?, pending); + } + Ok(()) + } + + #[test] + fn chatgpt_uses_its_port_and_recognizes_both_wizard_endpoints() -> Result<()> { let directory = tempfile::tempdir()?; let path = directory.path().join("Preferences"); - for address in [wizard_proxy::ADDRESS, wizard_proxy::OLD_ADDRESS] { + for address in [wizard_proxy::ADDRESS, wizard_proxy::CHATGPT_ADDRESS] { let before = json!({ "unrelated": true, "proxy": { "mode": "fixed_servers", "server": format!("http://{address}") }, @@ -618,7 +714,7 @@ mod tests { assert_eq!( config["proxy"], json!({ - "mode": "fixed_servers", "server": "http://127.0.0.1:33787", + "mode": "fixed_servers", "server": "http://127.0.0.1:33788", }) ); assert_eq!(config["unrelated"], true); 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..5f8efb9 100644 --- a/crates/wizard-core/src/agents/desktop_install/mod.rs +++ b/crates/wizard-core/src/agents/desktop_install/mod.rs @@ -3,9 +3,11 @@ mod chatgpt; mod claude; mod download; +mod requests; mod running; pub use download::{DownloadProgress, SavedDownload, download_release, saved_download}; +pub(crate) use running::with_closed; pub use running::{open_existing, open_first_install, running_apps}; use super::TokenAgent; @@ -298,14 +300,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 {}", @@ -1062,9 +1057,9 @@ fn install_release_inner( } #[cfg(target_os = "macos")] - let mut notices = install_macos(download, confirmed, close, reopen)?; + let notices = install_macos(download, confirmed, close, reopen)?; #[cfg(not(target_os = "macos"))] - let mut notices = { + let notices = { ensure!( download.release.target.rename.is_none() || confirmed, "Подтвердите переименование приложения" @@ -1097,15 +1092,6 @@ fn install_release_inner( download.release.target.app.product() ); - let target = &download.release.target; - // A new ChatGPT creates its profile on first launch; routing can be applied only then. It is - // applied with ChatGPT closed: a running ChatGPT may write its profile back over the change. - if target.app == DesktopApp::ChatGpt && target.first_install() { - notices.push( - "Чтобы подключить ChatGPT к CoreInfra, после его первого запуска закройте ChatGPT, нажмите «Применить» в разделе «Подключение» и откройте его снова." - .to_owned(), - ); - } Ok(Installed { notices }) } 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/agents/desktop_install/running.rs b/crates/wizard-core/src/agents/desktop_install/running.rs index 66cadb7..329a5d2 100644 --- a/crates/wizard-core/src/agents/desktop_install/running.rs +++ b/crates/wizard-core/src/agents/desktop_install/running.rs @@ -10,19 +10,160 @@ use super::{DesktopApp, Target}; use crate::agents::{AgentDetection, detection}; #[cfg(target_os = "macos")] use crate::platform::macos::{app_is_running, read_app_info, request_app_quit, running_app_paths}; +use anyhow::Result; +#[cfg(target_os = "macos")] +use anyhow::ensure; #[cfg(target_os = "macos")] use core::time::Duration; use std::path::Path; #[cfg(any(target_os = "macos", target_os = "linux"))] use std::path::PathBuf; #[cfg(target_os = "macos")] -use std::{process::Command, time::Instant}; +use std::process::Command; +#[cfg(target_os = "macos")] +use std::time::Instant; /// How long an application may take to quit, including a confirmation it asks the user for. /// The Windows and Linux installation scripts use the same limit. #[cfg(target_os = "macos")] const QUIT_TIMEOUT: Duration = Duration::from_secs(30); +/// Configuration owns the full close/write/open cycle. Never force-quit an application. +/// A fresh installation opens only after its configuration has been saved successfully. +pub(crate) fn with_closed( + app: DesktopApp, + last_path: Option<&Path>, + apply: impl FnOnce() -> Result<()>, +) -> Result<()> { + run_closed( + || close_existing(app), + apply, + || open_existing(app, last_path), + ) +} + +fn run_closed( + close: impl FnOnce() -> Result, + apply: impl FnOnce() -> Result<()>, + open: impl FnOnce() -> Result<()>, +) -> Result<()> { + let was_running = close()?; + let applied = apply(); + // Restore an already running app after an error, but never launch a first installation + // with incomplete settings. Preserve the configuration error if reopening also fails. + if !was_running && applied.is_err() { + return applied; + } + let opened = open(); + match (applied, opened) { + (Ok(()), Ok(())) => Ok(()), + (Err(error), Ok(())) => Err(error), + (Ok(()), Err(error)) => { + Err(error.context("Настройки сохранены, но не удалось открыть приложение")) + } + (Err(error), Err(open_error)) => Err(error.context(format!( + "Не удалось снова открыть приложение: {open_error:#}" + ))), + } +} + +fn close_existing(app: DesktopApp) -> Result { + #[cfg(target_os = "macos")] + { + let id = app.spec().bundle.id; + let was_running = app_is_running(id); + request_app_quit(id); + let deadline = Instant::now() + QUIT_TIMEOUT; + while app_is_running(id) { + ensure!( + Instant::now() < deadline, + "{} не закрылся. Завершите текущую работу и повторите настройку.", + app.product() + ); + std::thread::sleep(Duration::from_millis(250)); + } + Ok(was_running) + } + #[cfg(target_os = "windows")] + { + windows::close_package(&app.spec().package) + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + anyhow::bail!( + "Перезапуск {} на этой платформе не поддерживается", + app.product() + ) + } +} + +#[cfg(test)] +mod configuration_tests { + use super::run_closed; + use core::cell::RefCell; + + #[test] + fn configuration_is_saved_before_first_launch_or_restart() -> anyhow::Result<()> { + for was_running in [false, true] { + let steps = RefCell::new(Vec::new()); + run_closed( + || { + steps.borrow_mut().push("closed"); + Ok(was_running) + }, + || { + steps.borrow_mut().push("configured"); + Ok(()) + }, + || { + steps.borrow_mut().push("opened"); + Ok(()) + }, + )?; + assert_eq!(*steps.borrow(), ["closed", "configured", "opened"]); + } + Ok(()) + } + + #[test] + fn refused_shutdown_prevents_configuration_and_launch() { + let result = run_closed( + || anyhow::bail!("quit refused"), + || panic!("must not change a running app's profile"), + || panic!("must not open another instance"), + ); + assert_eq!(result.expect_err("must fail").to_string(), "quit refused"); + } + + #[test] + fn failed_configuration_only_reopens_a_previously_running_app() { + for was_running in [false, true] { + let mut opened = false; + let result = run_closed( + || Ok(was_running), + || anyhow::bail!("configuration failed"), + || { + opened = true; + Ok(()) + }, + ); + assert_eq!(opened, was_running); + assert_eq!( + result.expect_err("must fail").to_string(), + "configuration failed" + ); + } + } + + #[test] + fn launch_failure_does_not_claim_setup_completed() { + let result = run_closed(|| Ok(false), || Ok(()), || anyhow::bail!("launch failed")); + let message = format!("{:#}", result.expect_err("must fail")); + assert!(message.contains("Настройки сохранены")); + assert!(message.contains("launch failed")); + } +} + /// Products that installing `target` would close because they run in this user session now. #[must_use] pub fn running_apps(target: &Target) -> Vec<&'static str> { @@ -272,6 +413,46 @@ mod windows { use super::super::{WindowsPackage, command_output, powershell}; use anyhow::Result; + pub(super) fn close_package(package: &WindowsPackage) -> Result { + let script = super::super::windows_install_script( + "$package = $env:WIZARD_DESKTOP_PACKAGE | ConvertFrom-Json", + &format!( + "{}\n{}", + super::super::WINDOWS_CLOSE, + r" +$running = @(Get-PackageProcesses) +if (@($running | Where-Object { $_.SessionId -ne [Diagnostics.Process]::GetCurrentProcess().SessionId }).Count -gt 0) { exit 25 } +if ($running.Count -gt 0) { Close-PackageProcesses $running } +if ($running.Count -gt 0) { 'running' } else { 'stopped' } +exit 0 +" + ), + ); + let parameters = serde_json::json!({ + "name": package.name, + "publisher": package.publisher, + "process": package.process, + "process_in_package": package.process_in_package, + }); + let mut command = powershell(&script); + command.env("WIZARD_DESKTOP_PACKAGE", parameters.to_string()); + let mut command = tokio::process::Command::from(command); + command + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + let output = crate::platform::command_output(command, core::time::Duration::from_secs(45))?; + anyhow::ensure!( + output.status.success(), + "Приложение не закрылось. Завершите текущую работу и повторите настройку." + ); + match output.stdout.trim_ascii() { + b"running" => Ok(true), + b"stopped" => Ok(false), + _ => anyhow::bail!("Не удалось проверить закрытие приложения"), + } + } + /// Whether the package's process runs in this user session. The installation script repeats /// the check with the package's exact location. #[expect(unsafe_code, reason = "Win32 process enumeration")] diff --git a/crates/wizard-core/src/prepared_plan.rs b/crates/wizard-core/src/prepared_plan.rs index 0d32cfe..069d195 100644 --- a/crates/wizard-core/src/prepared_plan.rs +++ b/crates/wizard-core/src/prepared_plan.rs @@ -4,7 +4,11 @@ //! External commands have no rollback; `@latest` does not pin a package version. use crate::{ - agents::{claude, claude_desktop, codex, opencode, pi}, + agents::{ + claude, claude_desktop, codex, + desktop_install::{self, DesktopApp}, + opencode, pi, + }, config_files::{ backups::{AgentKind, BackupManager}, changes::{FileChange, FileSnapshot}, @@ -12,7 +16,10 @@ use crate::{ }; use anyhow::{Context as _, Result}; use serde::{Deserialize, Serialize}; -use std::{path::PathBuf, sync::MutexGuard}; +use std::{ + path::{Path, PathBuf}, + sync::MutexGuard, +}; #[derive(Clone, Copy, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -39,17 +46,43 @@ impl PreparedAgent { } } +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct DesktopRestart { + app: DesktopApp, + last_path: Option, +} + // No Debug: the original and prepared contents may contain credentials. #[derive(Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PreparedPlan { agent: PreparedAgent, pub(crate) steps: Vec, + #[serde(default)] + desktop: Option, } impl PreparedPlan { pub(crate) fn new(agent: PreparedAgent, steps: Vec) -> Self { - Self { agent, steps } + Self { + agent, + steps, + desktop: None, + } + } + + /// GUI configuration closes the desktop app before writing and opens it afterwards. + pub fn restart_desktop(&mut self, app: DesktopApp, last_path: Option<&Path>) { + self.desktop = Some(DesktopRestart { + app, + last_path: last_path.map(Path::to_owned), + }); + } + + #[must_use] + pub fn restarts_desktop(&self) -> bool { + self.desktop.is_some() } #[must_use] @@ -62,6 +95,14 @@ impl PreparedPlan { #[must_use] pub fn info(&self) -> Vec { let mut info = Vec::new(); + if let Some(desktop) = &self.desktop { + info.push(PreparedStepInfo { + description: format!( + "Применит настройки при закрытом {} и откроет приложение.", + desktop.app.product() + ), + }); + } for step in &self.steps { let item = match step { @@ -103,6 +144,13 @@ impl PreparedPlan { PreparedStep::OpenCodeRemoveCredential { .. } => PreparedStepInfo { description: "Удалит ключ CoreInfra от Wizard из OpenCode. Другие ключи CoreInfra сохранятся.".to_owned(), }, + PreparedStep::SetChatGptProxy { enabled, .. } => PreparedStepInfo { + description: if *enabled { + "Настроит подключение ChatGPT через локальный прокси Wizard." + } else { + "Удалит настройки прокси Wizard из ChatGPT." + }.to_owned(), + }, PreparedStep::SetCodexProxyEnabled { enabled } => PreparedStepInfo { description: if *enabled { "Включит локальный прокси ChatGPT в Wizard." @@ -137,11 +185,13 @@ impl PreparedPlan { /// Agent backups cover the entire plan; there is no rollback on failure. pub fn apply(self) -> Result<()> { anyhow::ensure!( - !self.steps.iter().any(|step| matches!( - step, - PreparedStep::SetClaudeProxyEnabled { .. } - | PreparedStep::SetCodexProxyEnabled { .. } - )), + self.desktop.is_none() + && !self.steps.iter().any(|step| matches!( + step, + PreparedStep::SetClaudeProxyEnabled { .. } + | PreparedStep::SetCodexProxyEnabled { .. } + | PreparedStep::SetChatGptProxy { .. } + )), "Desktop proxy plans can only be applied in the GUI" ); self.apply_with_proxies( @@ -173,12 +223,37 @@ impl PreparedPlan { } pub(crate) fn apply_with_backup( - self, + mut self, + manager: Option, + set_claude_enabled: impl FnMut(bool) -> Result<()>, + set_codex_enabled: impl FnMut(bool) -> Result<()>, + ) -> Result<()> { + let _guard = self.agent.lock()?; + + if let Some(desktop) = self.desktop.take() { + desktop_install::with_closed(desktop.app, desktop.last_path.as_deref(), || { + self.apply_closed(manager, set_claude_enabled, set_codex_enabled) + }) + } else { + self.apply_closed(manager, set_claude_enabled, set_codex_enabled) + } + } + + fn apply_closed( + mut self, manager: Option, mut set_claude_enabled: impl FnMut(bool) -> Result<()>, mut set_codex_enabled: impl FnMut(bool) -> Result<()>, ) -> Result<()> { - let _guard = self.agent.lock()?; + // Only ChatGPT's app-owned Preferences are read after shutdown. CLI configuration + // and Claude profiles retain their original snapshots and conflict checks. + for step in &mut self.steps { + if let PreparedStep::SetChatGptProxy { path, enabled } = step { + *step = PreparedStep::ChangeFile { + change: codex::prepare_desktop_proxy(path.clone(), *enabled)?, + }; + } + } // Refuse a write (symlink, file changed since preparation) before an install step runs. // Each write checks again. @@ -257,6 +332,12 @@ impl PreparedPlan { #[derive(Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum PreparedStep { + /// Read the application-owned Preferences after shutdown; preserve unrelated fields. + #[serde(rename = "set_chatgpt_proxy")] + SetChatGptProxy { + path: PathBuf, + enabled: bool, + }, /// Saves `ChatGPT`'s demand for the local proxy, without an agent credential. SetCodexProxyEnabled { enabled: bool, @@ -328,6 +409,9 @@ impl PreparedStep { // Use PreparedPlan::apply to retain grouped file writes and the agent mutex. fn apply(self) -> Result<()> { match self { + Self::SetChatGptProxy { .. } => { + anyhow::bail!("ChatGPT Preferences must be prepared after closing the app") + } Self::SetClaudeProxyEnabled { .. } | Self::SetCodexProxyEnabled { .. } => { anyhow::bail!("Desktop proxy requires the GUI") } @@ -372,3 +456,88 @@ impl PreparedStep { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::config_files::json; + + #[test] + fn chatgpt_profile_is_created_or_merged_after_shutdown_before_proxy_start() -> Result<()> { + for initialized_during_shutdown in [false, true] { + let directory = tempfile::tempdir()?; + let path = directory.path().join("Default/Preferences"); + let plan = PreparedPlan::new( + PreparedAgent::Codex, + vec![ + PreparedStep::SetChatGptProxy { + path: path.clone(), + enabled: true, + }, + PreparedStep::SetCodexProxyEnabled { enabled: true }, + ], + ); + assert!(!plan.info().is_empty()); + assert!(!path.parent().expect("profile directory").exists()); + if initialized_during_shutdown { + std::fs::create_dir_all(path.parent().expect("profile directory"))?; + std::fs::write(&path, r#"{"profile":{"name":"saved during shutdown"}}"#)?; + } + let mut activated = false; + plan.apply_with_backup( + None, + |_| panic!("unexpected Claude proxy"), + |enabled| { + assert!(enabled); + let config = json::read(&path)?; + assert_eq!(config["proxy"]["server"], "http://127.0.0.1:33788"); + if initialized_during_shutdown { + assert_eq!(config["profile"]["name"], "saved during shutdown"); + } else { + assert_eq!(config.as_object().expect("preferences object").len(), 1); + } + activated = true; + Ok(()) + }, + )?; + assert!(activated); + } + Ok(()) + } + + #[test] + fn desktop_profile_does_not_bypass_existing_configuration_conflict_checks() -> Result<()> { + let directory = tempfile::tempdir()?; + let config = directory.path().join("config.toml"); + std::fs::write(&config, "original")?; + let mut change = FileChange::read(config.clone())?; + change.after = FileSnapshot::new("prepared".into(), 0o600); + let preferences = directory.path().join("Default/Preferences"); + let plan = PreparedPlan::new( + PreparedAgent::Codex, + vec![ + PreparedStep::SetChatGptProxy { + path: preferences.clone(), + enabled: true, + }, + PreparedStep::ChangeFile { change }, + PreparedStep::SetCodexProxyEnabled { enabled: true }, + ], + ); + std::fs::write(&config, "user change after preparation")?; + assert!( + plan.apply_with_backup( + None, + |_| panic!("unexpected Claude proxy"), + |_| panic!("proxy must not start after failed preflight"), + ) + .is_err() + ); + assert!(!preferences.exists()); + assert_eq!( + std::fs::read_to_string(config)?, + "user change after preparation" + ); + Ok(()) + } +} diff --git a/crates/wizard-gui/src/agents.rs b/crates/wizard-gui/src/agents.rs index 83fbed2..4a405cf 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,77 @@ 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 => settings.codex_proxy_enabled, + LaunchAgent::Claude | LaunchAgent::Codex | LaunchAgent::OpenCode | LaunchAgent::Pi => false, + } +} + +#[cfg(test)] +mod tests { + use super::needs_proxy; + use wizard_core::agents::launch::LaunchAgent; + + #[test] + fn cli_launch_does_not_require_the_desktop_proxy() { + for enabled in [false, true] { + let settings = wizard_settings::Settings { + claude_proxy_enabled: enabled, + codex_proxy_enabled: enabled, + ..Default::default() + }; + assert_eq!(needs_proxy(LaunchAgent::ChatGpt, &settings), enabled); + assert_eq!(needs_proxy(LaunchAgent::ClaudeDesktop, &settings), enabled); + for cli in [ + LaunchAgent::Codex, + LaunchAgent::Claude, + LaunchAgent::OpenCode, + LaunchAgent::Pi, + ] { + assert!(!needs_proxy(cli, &settings)); + } + } + } +} + +/// 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. @@ -114,6 +186,7 @@ pub(crate) struct PreparedAgentChange { token: Option, plan: PreparedPlan, info: Vec, + restarts_desktop: bool, } impl AgentChange { @@ -137,9 +210,9 @@ impl AgentChange { } } -/// Enabled modes require `token`; it is not validated. Never log it. `Create` issues the Hub -/// token before preparation and is not part of the plan: cancelling or a failed preparation -/// keeps the token, already published in the Hub token list. +/// Enabled modes require `token`, except Claude Desktop subscription which uses +/// Wizard's shared proxy credential. Never log tokens. `Create` issues the Hub token +/// before preparation: cancelling or failed preparation keeps it in the Hub list. #[tauri::command] pub(crate) async fn prepare_agent_change( change: AgentChange, @@ -157,8 +230,6 @@ 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, @@ -183,7 +254,16 @@ pub(crate) async fn prepare_agent_change( codex::prepare_routing_for_gui(mode, &token, &settings) } AgentChange::ClaudeSetRouting(mode) => claude::prepare_routing(mode, &token), - AgentChange::ClaudeDesktopSetRouting(mode) => claude_desktop::prepare_routing(mode, &token), + AgentChange::ClaudeDesktopSetRouting(mode) => { + let mut plan = claude_desktop::prepare_routing(mode, &token)?; + if cfg!(any(target_os = "macos", target_os = "windows")) { + 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), }) @@ -196,6 +276,7 @@ pub(crate) async fn prepare_agent_change( })?; let info = plan.info(); + let restarts_desktop = plan.restarts_desktop(); log::info!("agent change prepared: {name}"); Ok(PreparedAgentChange { @@ -204,6 +285,7 @@ pub(crate) async fn prepare_agent_change( token: reprepare_token, plan, info, + restarts_desktop, }) } diff --git a/crates/wizard-gui/src/desktop_install.rs b/crates/wizard-gui/src/desktop_install.rs index 29bd5c7..34cea98 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); @@ -307,8 +308,8 @@ pub(crate) async fn get_desktop_running_apps( } /// `confirmed` approves the change that the selected release asks to confirm. `close` approves -/// closing the applications that the user was told run now. Onboarding defers the first -/// launch until configuration; other callers retain the default immediate first launch. +/// closing the applications that the user was told run now. Onboarding configures a first +/// installation before opening it; other callers retain immediate first launch. #[tauri::command] pub(crate) fn install_desktop_release( app: tauri::AppHandle, @@ -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..20e9270 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,18 @@ 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 tokenChanged = !proxyOnly && (token.selected?.kind === "create" + || (token.selected?.kind === "existing" && token.selected.token !== agentToken)); + const changed = selected !== mode || (enabled && (needsApply || tokenChanged)); const systemProxy = useSystemProxy(); const [proxyPrompt, setProxyPrompt] = useState(false); @@ -121,13 +168,13 @@ export function RoutingFieldset({ agent, modes, mode, toChange ))} - {proxyOnly ? Для аутентификации будет использован токен «coreinfra-ai-wizard» из личного хаба. Если его ещё нет, Wizard создаст его автоматически. + {proxyOnly ? Подключение через общий прокси Wizard. : (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..80c2f2d 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,15 @@ 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" && agents.codex.status === "found" && agents.codex.data.desktop.status === "found" + ? "chatgpt" : page === "claude_desktop" ? "claude_desktop" : null; + const proxyDetection = page === "codex" || page === "claude_desktop" ? agents[page] : 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 +136,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 +151,7 @@ export function AgentPage({ agents, page, proxy, account }: { Прокси для ChatGPT - - {chatGptProxyStopped && Прокси для ChatGPT не запущен, нажмите «Завершить настройку».} + {codex.status === "found" && ( @@ -147,7 +159,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 +190,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,20 +209,20 @@ 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} /> )}
{desktop.status === "found" ? "Обновление приложения" : "Установка приложения"} - {desktop.status !== "found" && } + {(desktop.status !== "found" || desktop.data.routing_mode === "sub") && } @@ -234,7 +246,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 +260,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..2223936 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; @@ -70,7 +71,9 @@ export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied План изменений: {agentNames[agent]} {hasChanges && ( - Завершите текущую работу и закройте агента перед применением. Wizard выполнит следующие действия. + {prepared.restarts_desktop + ? "Завершите текущую работу. Wizard закроет приложение, если оно запущено, применит настройки и откроет его." + : "Завершите текущую работу и закройте агента перед применением. Wizard выполнит следующие действия."} )} @@ -95,7 +98,7 @@ export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied {repreparing ? "Пересоздание…" : "Пересоздать"} } {hasChanges && } 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 af42282..a949a7f 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts @@ -25,10 +25,12 @@ export type PreparedAgentChange = { token: string | null; plan: PreparedPlan; info: PreparedStepInfo[]; + restarts_desktop: boolean; }; -// Required for enabled modes. `create` makes the backend issue a Hub token named after the agent -// before preparing; the token stays in Hub even if the plan is cancelled. Values are secrets. +// Required for enabled modes except Claude Desktop subscription (shared Wizard proxy token). +// `create` issues a Hub token before preparing; it stays in Hub if the plan is cancelled. +// Values are secrets. export type TokenChoice = { kind: "existing"; token: string } | { kind: "create" }; export function prepareAgentChange(change: AgentChange, token: TokenChoice | null): Promise { @@ -71,6 +73,7 @@ export type Codex = { cli: AgentDetection<{ path: string; version: string | null }>; desktop: AgentDetection<{ path: string; version: string | null }>; routing_mode: RoutingMode; + proxy_needs_apply: boolean; // CoreInfra token from the agent's configuration. Secret: never log or persist it. token: string | null; }; @@ -89,6 +92,7 @@ export type ClaudeDesktop = { routing_mode: RoutingMode; // CoreInfra token from the agent's configuration. Secret: never log or persist it. token: string | null; + proxy_needs_apply: boolean; }; export type OpenCode = { diff --git a/crates/wizard-gui/wizard-ui/src/agents/proxy.ts b/crates/wizard-gui/wizard-ui/src/agents/proxy.ts index 10d2d0e..664f741 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/proxy.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/proxy.ts @@ -5,6 +5,29 @@ import { reportError } from "../logs/log"; export type Proxy = { enabled: boolean }; type ProxySnapshot = Proxy & { revision: number }; +type ProxyAgent = "chatgpt" | "claude_desktop"; + +export function useAgentProxyStartup(agent: ProxyAgent | null) { + const [attempt, setAttempt] = useState(0); + const [result, setResult] = useState<{ agent: ProxyAgent; 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 ; @@ -124,6 +124,7 @@ export function SetupDialog({ initialStage, account, agents, onClose, onFinished const installed = agents.status === "ready" ? choices.filter((choice) => isFound(choice, agents.data)) : []; const [selected, setSelected] = useState(); const [stage, setStage] = useState(initialStage === "select" ? "entry" : initialStage); + const [restarted, setRestarted] = useState(false); // Resolve the entry screen from live detection, not the first (possibly partial) snapshot. const viewStage = stage === "entry" ? installed.length === 1 ? "configure" : "select" : stage; const [installView, setInstallView] = useState("choose"); @@ -157,8 +158,8 @@ export function SetupDialog({ initialStage, account, agents, onClose, onFinished
{(viewStage === "install" || viewStage === "select") && } - {viewStage === "configure" && selectedChoice && { setSelected(selectedChoice.id); changeBusy(false); setStage("complete"); }} onBack={() => setStage("select")} />} - {viewStage === "complete" && selectedChoice && setStage("select")} />} + {viewStage === "configure" && selectedChoice && { setSelected(selectedChoice.id); setRestarted(restarted && Boolean(selectedChoice.desktop)); changeBusy(false); setStage("complete"); }} onBack={() => setStage("select")} />} + {viewStage === "complete" && selectedChoice && setStage("select")} />}
; } diff --git a/crates/wizard-gui/wizard-ui/src/overview/Overview.css b/crates/wizard-gui/wizard-ui/src/overview/Overview.css index 279e244..4251040 100644 --- a/crates/wizard-gui/wizard-ui/src/overview/Overview.css +++ b/crates/wizard-gui/wizard-ui/src/overview/Overview.css @@ -56,7 +56,7 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button, flex-shrink: 0; width: calc(100% - var(--hero-gutter) * 2); max-width: 330px; - margin: 8px var(--hero-gutter); + margin: 8px 8px 8px var(--hero-gutter); border: 0; border-radius: 12px; background: transparent; @@ -196,7 +196,7 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button, } @container overview (max-width: 470px) { .overview-hero { min-height: 220px; } - .overview-video { max-width: 290px; margin-block: 8px 12px; } + .overview-video { max-width: 290px; } .overview-actions { margin-top: 20px; } .overview-actions-header { align-items: flex-start; flex-direction: column; gap: 0; } .overview-skip { margin-left: -8px; margin-right: 0; } diff --git a/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx b/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx index 6fb6090..cf41506 100644 --- a/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx @@ -74,11 +74,9 @@ function SystemProxySettings() { const [submitting, setSubmitting] = useState(false); const [commandError, setCommandError] = useState(); const hasOurs = state?.status === "on" || state?.status === "partial"; - const requested = state?.requested === true; - const checked = requested || hasOurs; const busy = submitting || state?.busy === true; const disabled = busy || Boolean(loadError) || !state || state.status === "unsupported" - || (!checked && (state.status !== "off" || state.conflict)); + || (!hasOurs && (state.status !== "off" || state.conflict)); const forceDisabled = busy || Boolean(loadError) || !(hasOurs || state?.status === "off"); @@ -101,8 +99,8 @@ function SystemProxySettings() {
- Wizard будет проксировать сайты OpenAI и Claude, остальной интернет будет работать как раньше. - { void change(enabled); }} /> + Запросы к OpenAI и Anthropic идут через выходные узлы CoreInfra AI Hub. Все остальные ресурсы доступны напрямую. + { void change(enabled); }} />
{busy && Применение системных настроек… На macOS может потребоваться авторизация.} @@ -116,11 +114,10 @@ function SystemProxySettings() { {(state?.conflict || state?.status === "partial") && ( )} - {requested && state?.status === "off" && Спрос на локальный прокси сохранён, но в ОС он выключен. Выключите переключатель, чтобы снять спрос.} {hasOurs && !state?.listener_running && ( ОС использует Wizard, но локальный прокси недоступен. Приложения могут потерять доступ к сети. )} - {checked && Прокси продолжит работать после выхода из GUI Wizard.} + {hasOurs && Прокси продолжит работать после выхода из GUI Wizard.} {loadError && {loadError}} {state?.read_error && {state.read_error}} {(state?.operation_error || commandError) && {state?.operation_error || commandError}} diff --git a/crates/wizard-gui/wizard-ui/src/settings/SystemProxyPrompt.tsx b/crates/wizard-gui/wizard-ui/src/settings/SystemProxyPrompt.tsx index 22ab71b..357ba2e 100644 --- a/crates/wizard-gui/wizard-ui/src/settings/SystemProxyPrompt.tsx +++ b/crates/wizard-gui/wizard-ui/src/settings/SystemProxyPrompt.tsx @@ -42,7 +42,7 @@ export function SystemProxyPrompt({ observation: { state, error: loadError }, on return { if (!busy) onClose(); }} className="system-proxy-prompt [&_:is(h2,p,span,button,a)]:text-sm/6!"> Включить системный прокси? - Системный прокси направляет запросы к Anthropic и OpenAI через Wizard для входа и работы со своей подпиской. Остальные сайты работают как обычно. + Системный прокси направляет запросы к OpenAI и Anthropic через выходные узлы CoreInfra AI Hub для входа и работы со своей подпиской. Все остальные ресурсы доступны напрямую. Прокси работает и после закрытия окна. Отключить его можно в Wizard: «Настройки» → «Системный прокси». {busy && Включаем системный прокси… На macOS может потребоваться подтверждение администратора.} {!busy && (!state || state.status === "unknown") && !failure && Проверяем состояние системного прокси…} diff --git a/crates/wizard-gui/wizard-ui/src/settings/system_proxy.ts b/crates/wizard-gui/wizard-ui/src/settings/system_proxy.ts index e5ae74a..0dbbd16 100644 --- a/crates/wizard-gui/wizard-ui/src/settings/system_proxy.ts +++ b/crates/wizard-gui/wizard-ui/src/settings/system_proxy.ts @@ -6,13 +6,12 @@ type SystemProxyState = { busy: boolean; conflict: boolean; listener_running: boolean; - requested: boolean; read_error: string | null; operation_error: string | null; }; type SystemProxySnapshot = SystemProxyState & { revision: number }; -// Observes persisted demand and OS state without automatically changing either. +// Observes OS state without automatically changing it. // Tray actions remain visible after reopening the window. export function useSystemProxy() { const [state, setState] = useState(); diff --git a/crates/wizard-proxy-daemon/src/lib.rs b/crates/wizard-proxy-daemon/src/lib.rs index a30a6a6..90777f3 100644 --- a/crates/wizard-proxy-daemon/src/lib.rs +++ b/crates/wizard-proxy-daemon/src/lib.rs @@ -31,8 +31,8 @@ mod linux; use linux as platform; /// Prepare the service once at GUI startup, before synchronizing settings. -/// In release builds, a running daemon with the same workspace crate version is -/// left untouched. Debug builds ignore version matches to pick up local rebuilds. +/// In release builds, a running daemon with the same application version and proxy +/// revision is left untouched. Debug builds always pick up local rebuilds. /// Otherwise a valid Status or refused connection triggers platform registration. /// Other HTTP errors leave registration unchanged. /// Await this operation to completion: cancellation can leave native registration @@ -40,7 +40,10 @@ use linux as platform; pub async fn create_daemon() -> io::Result<()> { let _guard = SYNC_LOCK.lock().await; match wizard_proxy::control::status().await { - Ok(status) if !cfg!(debug_assertions) && status.version == env!("CARGO_PKG_VERSION") => { + Ok(status) + if !cfg!(debug_assertions) + && status.version == wizard_proxy::control::DAEMON_VERSION => + { log::info!("proxy daemon version matches; keeping current service"); return Ok(()); } @@ -140,7 +143,7 @@ impl UpdateGuard { /// Only a refused connection permits starting a process: a timeout or failed /// Reload may already have applied changes and must not trigger a second launch. /// A single platform start request is followed by bounded Status polling. -/// This never registers the service; call `create_daemon` at GUI startup first. +/// If a needed daemon is absent, repair its registration before requesting a start. /// Neither a launch nor a mutating Reload is automatically retried. pub async fn sync_proxy() -> io::Result<()> { let _guard = SYNC_LOCK.lock().await; @@ -170,6 +173,11 @@ async fn sync_with_settings() -> io::Result<()> { .map_err(|_| io::Error::other("failed to load Wizard settings"))? .local_proxy_enabled(); if enabled { + // Startup may have failed before registration (for example, while + // obtaining a token offline). A later explicit operation must recover. + platform::ensure_daemon() + .await + .inspect_err(|error| diagnostics::error("proxy service registration", error))?; log::info!("requesting proxy service start"); platform::start_daemon() .await diff --git a/crates/wizard-proxy-daemon/src/linux.rs b/crates/wizard-proxy-daemon/src/linux.rs index cb14eed..d47fda0 100644 --- a/crates/wizard-proxy-daemon/src/linux.rs +++ b/crates/wizard-proxy-daemon/src/linux.rs @@ -6,6 +6,7 @@ use std::io; pub(super) use super::unix::shutdown_signal; +pub(super) use create_daemon as ensure_daemon; // No platform service is installed on Linux yet. Cleanup is a successful no-op. pub(super) async fn uninstall() -> io::Result { diff --git a/crates/wizard-proxy-daemon/src/macos.rs b/crates/wizard-proxy-daemon/src/macos.rs index e49fd87..8a695a1 100644 --- a/crates/wizard-proxy-daemon/src/macos.rs +++ b/crates/wizard-proxy-daemon/src/macos.rs @@ -171,7 +171,15 @@ fn unregister_service(service: &SMAppService) -> io::Result<()> { } pub async fn create_daemon() -> io::Result<()> { - tokio::task::spawn_blocking(register_daemon) + tokio::task::spawn_blocking(|| register_daemon(true)) + .await + .inspect_err(|error| wizard_proxy::diagnostics::error("proxy registration worker", error)) + .map_err(|_| io::Error::other("proxy service registration worker failed"))? +} + +/// Preserve an existing registration and any process it is still starting. +pub async fn ensure_daemon() -> io::Result<()> { + tokio::task::spawn_blocking(|| register_daemon(false)) .await .inspect_err(|error| wizard_proxy::diagnostics::error("proxy registration worker", error)) .map_err(|_| io::Error::other("proxy service registration worker failed"))? @@ -181,7 +189,7 @@ pub async fn create_daemon() -> io::Result<()> { unsafe_code, reason = "SMAppService bindings require checked native calls" )] -fn register_daemon() -> io::Result<()> { +fn register_daemon(replace_existing: bool) -> io::Result<()> { if !objc2::available!(macos = 13.0) { return Err(io::Error::new( io::ErrorKind::Unsupported, @@ -198,7 +206,7 @@ fn register_daemon() -> io::Result<()> { // SAFETY: service is a live SMAppService on a supported OS. let mut status = unsafe { service.status() }; log::info!("proxy service status before registration: {}", status.0); - if status == SMAppServiceStatus::Enabled { + if status == SMAppServiceStatus::Enabled && replace_existing { // Never register before successful completion, including on timeout: // the native unregistration may still finish after we return an error. unregister_service(&service)?; diff --git a/crates/wizard-proxy-daemon/src/windows-task-exists.ps1 b/crates/wizard-proxy-daemon/src/windows-task-exists.ps1 new file mode 100644 index 0000000..e7403f7 --- /dev/null +++ b/crates/wizard-proxy-daemon/src/windows-task-exists.ps1 @@ -0,0 +1,20 @@ +# Read-only lookup. Exit 10 means missing; other failures must not trigger registration. +$ErrorActionPreference = 'Stop' +try { + $scheduler = New-Object -ComObject Schedule.Service + $scheduler.Connect() + $folder = $scheduler.GetFolder('\') + try { + $null = $folder.GetTask($env:WIZARD_PROXY_TASK) + } catch { + # HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), not access denied. + if ($_.Exception.HResult -eq -2147024894 -or + $_.Exception.InnerException.HResult -eq -2147024894) { + exit 10 + } + throw + } + exit 0 +} catch { + exit 1 +} diff --git a/crates/wizard-proxy-daemon/src/windows.rs b/crates/wizard-proxy-daemon/src/windows.rs index 19b62fa..6373462 100644 --- a/crates/wizard-proxy-daemon/src/windows.rs +++ b/crates/wizard-proxy-daemon/src/windows.rs @@ -18,6 +18,35 @@ use windows_sys::Win32::{ }, }; +/// Keep an existing task, including its disabled state, when restoring a stopped proxy. +pub(super) async fn ensure_daemon() -> io::Result<()> { + let sid = current_user_sid().await?; + // schtasks uses the same failure code for a missing task and access errors. + // Only a confirmed missing task permits registration; never replace one + // after a timeout, access denial, or Task Scheduler failure. + let status = tokio::time::timeout( + Duration::from_secs(15), + Command::new(system_executable(r"WindowsPowerShell\v1.0\powershell.exe")?) + .args(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]) + .arg(include_str!("windows-task-exists.ps1")) + .env_remove("PSModulePath") + .env("WIZARD_PROXY_TASK", task_name(&sid)) + .creation_flags(CREATE_NO_WINDOW) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .status(), + ) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy task lookup timed out"))??; + match status.code() { + Some(0) => Ok(()), + Some(10) => create_daemon().await, + _ => Err(io::Error::other("proxy task lookup failed")), + } +} + pub(super) async fn create_daemon() -> io::Result<()> { log::info!("requesting graceful proxy shutdown before task update"); match wizard_proxy::control::shutdown().await { diff --git a/crates/wizard-proxy/src/control.rs b/crates/wizard-proxy/src/control.rs index 96e1d0b..b25f0ca 100644 --- a/crates/wizard-proxy/src/control.rs +++ b/crates/wizard-proxy/src/control.rs @@ -13,6 +13,10 @@ pub(crate) const TIMEOUT: Duration = Duration::from_secs(2); const REQUEST_TIMEOUT: Duration = Duration::from_secs(3); const MAX_RESPONSE: usize = 1024; +/// Include the proxy revision so incompatible development builds with the same +/// application version are replaced once instead of keeping an old daemon alive. +pub const DAEMON_VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "+proxy.2"); + /// Current runtime permission to proxy, not upstream health or token validity. /// Both ports remain bound while the managed server is running. #[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/wizard-proxy/src/lib.rs b/crates/wizard-proxy/src/lib.rs index 057bed3..2873c7e 100644 --- a/crates/wizard-proxy/src/lib.rs +++ b/crates/wizard-proxy/src/lib.rs @@ -30,10 +30,10 @@ mod server_tests; pub use upstream::{HOST as UPSTREAM_HOST, PORT as UPSTREAM_PORT, USERNAME as UPSTREAM_USERNAME}; -/// Listener used by Claude Desktop; shares configuration with the other managed port. +/// Listener used by Claude Desktop and the system proxy; uses Wizard's shared token. pub const ADDRESS: &str = "127.0.0.1:33787"; -/// Listener used by `ChatGPT`; shares configuration with the other managed port. -pub const OLD_ADDRESS: &str = "127.0.0.1:33788"; +/// Listener used by `ChatGPT`; uses the same Wizard token and configuration. +pub const CHATGPT_ADDRESS: &str = "127.0.0.1:33788"; // Idle WebSocket and streaming connections remain valid; detect vanished peers // with TCP keepalive instead of applying an application-level idle timeout. @@ -96,7 +96,7 @@ impl ServerState { // Called with reload_lock held, after any previous generation has drained. async fn current_status(&self) -> control::Status { control::Status { - version: env!("CARGO_PKG_VERSION").to_owned(), + version: control::DAEMON_VERSION.to_owned(), enabled: self.slot.current.read().await.is_some(), } } @@ -291,10 +291,12 @@ pub async fn run_managed(shutdown: impl Future) -> io::Result<()> { let listener = TcpListener::bind(ADDRESS).await.inspect_err(|error| { diagnostics::error("Claude Desktop listener bind", error); })?; - let listener_old = TcpListener::bind(OLD_ADDRESS).await.inspect_err(|error| { - diagnostics::error("ChatGPT listener bind", error); - })?; - log::info!("proxy listeners bound: claude_desktop={ADDRESS}, chatgpt={OLD_ADDRESS}"); + let listener_old = TcpListener::bind(CHATGPT_ADDRESS) + .await + .inspect_err(|error| { + diagnostics::error("ChatGPT listener bind", error); + })?; + log::info!("proxy listeners bound: claude_desktop={ADDRESS}, chatgpt={CHATGPT_ADDRESS}"); run_listeners(state, listener, listener_old, shutdown).await } diff --git a/crates/wizard-proxy/src/server_test.rs b/crates/wizard-proxy/src/server_test.rs index 7320c20..8315c5b 100644 --- a/crates/wizard-proxy/src/server_test.rs +++ b/crates/wizard-proxy/src/server_test.rs @@ -164,14 +164,14 @@ async fn disabling_reload_replies_before_exit() -> io::Result<()> { let status: control::Status = control::request(&address.to_string(), control::Command::Status).await?; - assert_eq!(status.version, env!("CARGO_PKG_VERSION")); + assert_eq!(status.version, control::DAEMON_VERSION); assert!(status.enabled); settings(None, false, false); let response: control::ReloadResponse = control::request(&address.to_string(), control::Command::Reload).await?; assert!(response.error.is_none()); - assert_eq!(response.status.version, env!("CARGO_PKG_VERSION")); + assert_eq!(response.status.version, control::DAEMON_VERSION); assert!(!response.status.enabled); task.await.map_err(io::Error::other)??; Ok(())