From a55200c56c5e09dc7148636f8c3452dbc98ba229 Mon Sep 17 00:00:00 2001 From: Ilya Shcherbak Date: Thu, 19 Nov 2026 22:13:34 +0300 Subject: [PATCH 1/2] Implement Wizard onboarding, agent management, and background downloads Keep navigation available after startup, consolidate agent connection forms, and show ongoing transfers in the sidebar. Add explicit install and cancel actions backed by Tauri, automatic release checks, and Hub balance actions. Remove the success checkmark from the top-up notice. Include native IPC tests for installer progress and update cancellation. --- README.md | 61 ++- .../src/agents/desktop_install/download.rs | 33 ++ .../src/agents/desktop_install/mod.rs | 4 +- crates/wizard-core/src/hub/mod.rs | 44 ++ crates/wizard-gui/Cargo.toml | 3 + crates/wizard-gui/build.rs | 21 +- crates/wizard-gui/src/desktop_install.rs | 217 +++++++-- crates/wizard-gui/src/hub_auth.rs | 48 +- crates/wizard-gui/src/ipc_test.rs | 37 ++ crates/wizard-gui/src/lib.rs | 7 +- crates/wizard-gui/src/updater.rs | 311 +++++++++++-- crates/wizard-gui/windows/app.manifest | 14 + crates/wizard-gui/wizard-ui/src/App.tsx | 108 +++-- .../wizard-gui/wizard-ui/src/AppSidebar.tsx | 85 +++- .../wizard-ui/src/SidebarDownloads.css | 1 + .../wizard-ui/src/SidebarDownloads.tsx | 58 +++ .../src/agents/AgentConfiguration.tsx | 367 +++++++++++---- .../src/agents/AgentConnectionPanel.tsx | 81 ++++ .../wizard-ui/src/agents/AgentPage.tsx | 383 ++++++++++----- .../wizard-ui/src/agents/BackupDialog.tsx | 103 +++-- .../wizard-ui/src/agents/DesktopInstall.tsx | 336 +++++--------- .../wizard-ui/src/agents/MissingAgent.tsx | 45 ++ .../src/agents/PreparedPlanDialog.tsx | 101 ++-- .../wizard-ui/src/agents/agents_state.ts | 7 + .../src/agents/desktop_install_state.ts | 97 ++++ .../wizard-ui/src/agents/navigation.ts | 14 +- .../wizard-ui/src/components/AppLogo.tsx | 4 +- .../wizard-ui/src/components/ErrorText.tsx | 2 +- .../src/components/StartupScreen.css | 11 + .../src/components/StartupScreen.tsx | 22 + .../src/components/catalyst/alert.tsx | 14 +- .../src/components/catalyst/badge.tsx | 2 +- .../src/components/catalyst/button.tsx | 8 +- .../src/components/catalyst/combobox.tsx | 10 +- .../components/catalyst/description-list.tsx | 2 +- .../src/components/catalyst/dialog.tsx | 8 +- .../src/components/catalyst/dropdown.tsx | 4 +- .../src/components/catalyst/fieldset.tsx | 10 +- .../src/components/catalyst/heading.tsx | 5 +- .../src/components/catalyst/input.tsx | 4 +- .../src/components/catalyst/listbox.tsx | 6 +- .../src/components/catalyst/radio.tsx | 4 +- .../src/components/catalyst/select.tsx | 2 +- .../components/catalyst/sidebar-layout.tsx | 141 ++++-- .../src/components/catalyst/text.tsx | 2 +- .../src/components/catalyst/textarea.tsx | 4 +- .../src/components/ui/DialogHeader.tsx | 40 ++ .../wizard-ui/src/components/ui/Identity.tsx | 29 ++ .../wizard-ui/src/components/ui/Layout.tsx | 100 ++++ .../src/components/ui/StateNotice.tsx | 67 +++ .../src/components/ui/TransferCard.css | 211 +++++++++ .../src/components/ui/TransferCard.tsx | 138 ++++++ .../wizard-ui/src/design-system/patterns.css | 334 ++++++++++++++ .../wizard-ui/src/design-system/tokens.css | 64 +++ .../wizard-ui/src/logs/LogWindow.tsx | 15 +- .../src/onboarding/AgentSelection.tsx | 137 +++--- .../wizard-ui/src/onboarding/InstallCard.tsx | 435 ++++++++++-------- .../src/onboarding/Installations.tsx | 224 +++++++++ .../wizard-ui/src/onboarding/SetupDialog.css | 69 +-- .../wizard-ui/src/onboarding/SetupDialog.tsx | 362 +++++++++++---- .../src/onboarding/installations_state.ts | 27 ++ .../wizard-ui/src/overview/Overview.css | 158 +++---- .../wizard-ui/src/overview/Overview.tsx | 390 ++++++++++++---- .../wizard-ui/src/overview/OverviewAgents.tsx | 94 ++++ .../src/overview/OverviewArtwork.tsx | 7 +- .../wizard-ui/src/overview/OverviewCard.tsx | 55 ++- .../src/overview/useOverviewTransition.ts | 90 ++++ .../wizard-ui/src/settings/HubAccount.tsx | 10 +- .../wizard-ui/src/settings/HubSignIn.css | 1 + .../wizard-ui/src/settings/HubSignIn.tsx | 10 +- .../wizard-ui/src/settings/SettingsPage.tsx | 234 +++++++--- .../src/settings/SystemProxyPrompt.tsx | 119 ++++- .../wizard-ui/src/settings/hub_account.ts | 2 +- .../wizard-ui/src/settings/hub_summary.ts | 63 +++ crates/wizard-gui/wizard-ui/src/styles.css | 6 + .../wizard-ui/src/updates/UpdateDialog.tsx | 65 +++ .../wizard-ui/src/updates/UpdateItem.tsx | 38 +- .../wizard-ui/src/updates/UpdateScreen.tsx | 18 - .../wizard-ui/src/updates/update.ts | 15 +- 79 files changed, 5027 insertions(+), 1451 deletions(-) create mode 100644 crates/wizard-gui/src/ipc_test.rs create mode 100644 crates/wizard-gui/windows/app.manifest create mode 100644 crates/wizard-gui/wizard-ui/src/SidebarDownloads.css create mode 100644 crates/wizard-gui/wizard-ui/src/SidebarDownloads.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/agents/MissingAgent.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/agents/desktop_install_state.ts create mode 100644 crates/wizard-gui/wizard-ui/src/components/StartupScreen.css create mode 100644 crates/wizard-gui/wizard-ui/src/components/StartupScreen.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/components/ui/DialogHeader.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/components/ui/Identity.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/components/ui/Layout.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/components/ui/StateNotice.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.css create mode 100644 crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/design-system/patterns.css create mode 100644 crates/wizard-gui/wizard-ui/src/design-system/tokens.css create mode 100644 crates/wizard-gui/wizard-ui/src/onboarding/Installations.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/onboarding/installations_state.ts create mode 100644 crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/overview/useOverviewTransition.ts create mode 100644 crates/wizard-gui/wizard-ui/src/settings/hub_summary.ts create mode 100644 crates/wizard-gui/wizard-ui/src/updates/UpdateDialog.tsx delete mode 100644 crates/wizard-gui/wizard-ui/src/updates/UpdateScreen.tsx diff --git a/README.md b/README.md index cb73ad0..1241b55 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,27 @@ The interface reference is the Hub in the neighboring `thinker` repository: `crates/ff-hub/hub-ui/src/modules/App.tsx` (agent order and divider) and `packages/coreinfra-ui/src/hub-sidebar-footer.tsx` (account menu and theme controls). +### UI design system + +Wizard uses neutral Catalyst surfaces, shared typography and spacing, and +restrained state colors. Startup, overview drawing, and download progress +animations remain part of the interface. Navigation and dialog transitions must +not reset ongoing operations. + +`src/design-system/tokens.css` owns surface, text, border, spacing, radius, and +motion values. `src/components/ui` owns page headings, panels, action bars, +identities, notices and transfer cards; accessible controls and focus trapping +continue to use Catalyst / Headless UI. Connection forms use unframed panels +inside dialogs. Version rows share column alignment; on narrow screens their +actions move below the version and stay together. + +Body/control text is 14/24 px, metadata 12/20 px, section titles 16/24 px and page +titles 22/32 px. Text inputs retain 16 px below 640 px to avoid mobile auto-zoom. +Do not use page-wide `!important` typography overrides or make a portal inherit +typography from the page behind it. Preserve heading order, keyboard focus, +contrast in both themes and reduced-motion support. Download progress uses a +labeled progressbar instead of announcing every percentage tick. + ### Overview and initial setup **Обзор** is the default full-window page, above **Агенты** in the sidebar. @@ -96,11 +117,13 @@ The three action cards use the live account and detection state: - **Установите агентов** becomes available after sign-in. - **Настройте агентов** requires sign-in and at least one detected agent. -On first launch, navigation is hidden. «Пропустить быструю настройку» beside -«Начало работы» reveals it and remembers the choice across launches. Overview -remains accessible from the sidebar. Configuration reuses the regular agent form -and plan confirmation; multiple installed agents always show a selection first. -The final action launches the configured desktop app or CLI. +First launch shows a brief Wizard logo animation, then automatically opens the +full interface with navigation, even before sign-in or setup. The animation is +remembered across launches and skipped for reduced motion or completed legacy +onboarding. Update checks run in the background without blocking navigation. +Configuration reuses the regular agent form 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. The default token is selected automatically: reuse the configured token if it belongs to the @@ -116,10 +139,30 @@ 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 -archive. Installed apps show their version and offer an update check. Completed -installs and checks close with «Готово». +Downloads run in the backend independently of the current page or dialog. The +action beside an agent's installed version is «Обновить» («Скачать» for a missing +desktop app). It only opens that agent's installation panel. Download, install +and cancel actions live in the expanded panel; the picker also only opens it. +The version row keeps the installed version until installation completes, then +animates the new number and removes the update action. Release checks run +automatically, without a manual check button or an up-to-date message. +Closing the dialog (outside click, Escape, or cross) keeps downloads running in +a stack of compact widgets in the left sidebar, directly above the Hub divider, +with a logo, percentage and downloaded/total MB. Clicking +a widget restores that operation. «Назад» appears only after choosing an app in +the picker and returns there without stopping downloads. Direct openings from +a version action or sidebar widget have no Back button. «Отменить» stops the selected +transfer and deletes its cached archive; downloading again starts from zero. +Network interruptions still retain resumable progress. Installation always needs +a separate confirmation, including notices about closing running applications. + +Wizard itself also checks for updates automatically, including at launch. Its +sidebar update action opens a dialog without changing the installed application. +«Скачать обновление» downloads and verifies the signed archive; «Установить» then +replaces Wizard and restarts it. Downloads survive closing the dialog and remain +visible in the sidebar. «Отменить» aborts the download and discards its bytes. +The main interface stays mounted throughout; only the explicit installation step +prepares the proxy service for replacement. Choosing a subscription offers to enable the system proxy if it is off. Only «Включить» changes OS settings; cancel keeps the selected mode. The prompt diff --git a/crates/wizard-core/src/agents/desktop_install/download.rs b/crates/wizard-core/src/agents/desktop_install/download.rs index 34f9d32..2ac0e03 100644 --- a/crates/wizard-core/src/agents/desktop_install/download.rs +++ b/crates/wizard-core/src/agents/desktop_install/download.rs @@ -66,6 +66,20 @@ pub fn saved_download(app: DesktopApp, release: Option<&Release>) -> Result Result<()> { + remove_download(&Slot::new(app)?.directory) +} + +fn remove_download(directory: &Path) -> Result<()> { + match fs::remove_dir_all(directory) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error).context("Не удалось удалить скачанную часть. Повторите отмену"), + } +} + /// Downloads and verifies the release archive, continuing a saved download of it. What was /// received stays saved when the download fails or is dropped; failed verification discards it. pub async fn download_release( @@ -864,4 +878,23 @@ mod tests { assert!(saved(&directory, None).is_none()); assert!(!directory.exists()); } + + #[test] + fn cancelled_download_restarts_without_a_range_request() { + let archive = archive(); + let server = serve(archive.clone(), vec![Plan::CutAfter(1_000_000)]); + let release = release(&server.url, &archive); + let root = tempfile::tempdir().unwrap(); + let directory = root.path().join("claude"); + assert!(run(&directory, &release, &[]).0.is_err()); + assert!(saved(&directory, Some(&release)).is_some()); + + remove_download(&directory).unwrap(); + assert!(!directory.exists()); + remove_download(&directory).unwrap(); // A second cancellation is harmless. + let (_, progress) = run(&directory, &release, &[]); + assert_eq!(progress.first().unwrap().received, 0); + assert!(server.requests().last().unwrap().range.is_none()); + assert_eq!(fs::read(directory.join(DOWNLOAD_NAME)).unwrap(), archive); + } } diff --git a/crates/wizard-core/src/agents/desktop_install/mod.rs b/crates/wizard-core/src/agents/desktop_install/mod.rs index 2abd613..a16ec2c 100644 --- a/crates/wizard-core/src/agents/desktop_install/mod.rs +++ b/crates/wizard-core/src/agents/desktop_install/mod.rs @@ -6,7 +6,9 @@ mod download; mod requests; mod running; -pub use download::{DownloadProgress, SavedDownload, download_release, saved_download}; +pub use download::{ + DownloadProgress, SavedDownload, discard_download, download_release, saved_download, +}; pub(crate) use running::with_closed; pub use running::{open_existing, open_first_install, running_apps}; diff --git a/crates/wizard-core/src/hub/mod.rs b/crates/wizard-core/src/hub/mod.rs index 05796db..4d977f1 100644 --- a/crates/wizard-core/src/hub/mod.rs +++ b/crates/wizard-core/src/hub/mod.rs @@ -217,6 +217,34 @@ impl HubProfile { } } +/// The selected hub's displayable balance and membership, without its agent tokens. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct HubSummary { + pub hub_id: String, + pub role_in_hub: String, + pub balance_rub: Option, +} + +pub async fn fetch_hub_summary( + client: &Client, + session: &str, + hub_id: &str, +) -> (SessionUpdate, Result) { + #[derive(Serialize)] + struct Request<'a> { + hub_id: &'a str, + } + let (update, summary) = + post::(client, session, HUB_INFO_PATH, &Request { hub_id }).await; + let summary = summary.and_then(|summary| { + if summary.hub_id != hub_id || summary.role_in_hub.is_empty() { + return Err(HubError::Response); + } + Ok(summary) + }); + (update, summary) +} + /// Agent token of a Hub hub. `token` is a secret: no `Debug`, never logged. #[derive(Clone, Serialize, Deserialize)] pub struct AgentToken { @@ -338,6 +366,22 @@ fn session_from_headers(headers: &HeaderMap) -> Result, ()> { mod tests { use super::*; + #[test] + fn summary_preserves_hidden_and_zero_balances_without_exposing_tokens() { + let hidden: HubSummary = serde_json::from_value(serde_json::json!({ + "hub_id": "team", "role_in_hub": "member", "agent_tokens": [{"token": "secret"}] + })) + .expect("valid hub response"); + assert_eq!(hidden.balance_rub, None); + let zero: HubSummary = serde_json::from_value(serde_json::json!({ + "hub_id": "personal", "role_in_hub": "owner", "balance_rub": 0 + })) + .expect("valid zero balance"); + assert_eq!(zero.balance_rub, Some(0.0)); + let exposed = serde_json::to_value(hidden).expect("serializable summary"); + assert!(exposed.get("agent_tokens").is_none()); + } + fn profile() -> HubProfile { HubProfile { personal_hub_id: "personal".into(), diff --git a/crates/wizard-gui/Cargo.toml b/crates/wizard-gui/Cargo.toml index ec90e00..e34a23b 100644 --- a/crates/wizard-gui/Cargo.toml +++ b/crates/wizard-gui/Cargo.toml @@ -39,6 +39,9 @@ wizard-proxy-daemon.workspace = true wizard-settings.workspace = true wizard-system-proxy.workspace = true +[dev-dependencies] +tauri = { workspace = true, features = ["test"] } + [target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies] tauri = { workspace = true, features = ["tray-icon"] } tauri-plugin-autostart.workspace = true diff --git a/crates/wizard-gui/build.rs b/crates/wizard-gui/build.rs index 261851f..21a2033 100644 --- a/crates/wizard-gui/build.rs +++ b/crates/wizard-gui/build.rs @@ -1,3 +1,22 @@ fn main() { - tauri_build::build(); + let mut attributes = tauri_build::Attributes::new(); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") + && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") + { + // Tauri's resource manifest is linked to binaries only. Library test executables + // also need Common Controls v6 once IPC tests retain Tauri's native menu code, + // otherwise the Windows loader exits with STATUS_ENTRYPOINT_NOT_FOUND. + let manifest = std::path::PathBuf::from( + std::env::var_os("CARGO_MANIFEST_DIR").expect("Cargo package directory"), + ) + .join("windows/app.manifest"); + println!("cargo:rerun-if-changed={}", manifest.display()); + println!("cargo:rustc-link-arg=/MANIFEST:EMBED"); + println!("cargo:rustc-link-arg=/MANIFESTINPUT:{}", manifest.display()); + // Embed the same manifest through the linker for every executable, without + // a second manifest in the application's icon/version resources. + attributes = attributes + .windows_attributes(tauri_build::WindowsAttributes::new_without_app_manifest()); + } + tauri_build::try_build(attributes).expect("failed to build Tauri resources"); } diff --git a/crates/wizard-gui/src/desktop_install.rs b/crates/wizard-gui/src/desktop_install.rs index 4bc667d..e3037d4 100644 --- a/crates/wizard-gui/src/desktop_install.rs +++ b/crates/wizard-gui/src/desktop_install.rs @@ -91,8 +91,8 @@ pub(crate) struct InstallManager { desktop: DesktopApp, signal: RevisionSignal, session: Arc>, - /// Pauses the running download. - pause: Mutex>>, + /// Cancels the running transfer; the command then discards its archive. + cancel: Mutex>>, unsupported: bool, } @@ -106,7 +106,7 @@ impl InstallManager { reason.map_or(State::Idle, |message| State::Unsupported { message }), ), session: Arc::new(tokio::sync::Mutex::new(Session::default())), - pause: Mutex::new(None), + cancel: Mutex::new(None), } } } @@ -258,26 +258,59 @@ pub(crate) fn download_desktop_release( ) } -/// Stops the download. What it received stays saved, and downloading again continues it. +/// Stops the transfer and discards its archive, including a completion racing the click. #[tauri::command] -#[expect( - clippy::needless_pass_by_value, - reason = "Tauri passes managed state by value" -)] -pub(crate) fn pause_desktop_download( +pub(crate) async fn cancel_desktop_download( desktop: DesktopApp, managers: tauri::State<'_, InstallManagers>, -) { - let pause = managers - .get(desktop) - .pause +) -> Result<(), String> { + let manager = managers.get(desktop); + if !matches!( + manager.signal.current().state, + State::Downloading { .. } + | State::ReadyToInstall { .. } + | State::Failed { + operation: Operation::Download, + .. + } + ) { + return Err("Нет скачивания, которое можно отменить".into()); + } + let cancel = manager + .cancel .lock() .unwrap_or_else(PoisonError::into_inner) .take(); - // Without a sender, or when sending fails, the download has already ended or been paused. - if let Some(pause) = pause { - pause.send(()).ok(); + if let Some(cancel) = cancel { + cancel.send(()).ok(); } + // Wait for the transfer future and its open archive handle to be dropped (Windows too). + let mut session = manager.session.lock().await; + let release = match &session.package { + Some(Package::Available(release)) => release.as_ref().clone(), + Some(Package::Downloaded(download)) => download.release.clone(), + None => return Ok(()), + }; + let discarded = + tauri::async_runtime::spawn_blocking(move || installer::discard_download(desktop)) + .await + .map_err(|_| "Не удалось удалить скачанный архив".to_owned()) + .and_then(|result| result.map_err(|error| format!("{error:#}"))); + if let Err(message) = discarded { + session.package = Some(Package::Available(Box::new(release))); + manager.signal.notify(State::Failed { + operation: Operation::Download, + message: message.clone(), + confirmation: None, + }); + return Err(message); + } + let notes = release.notes(); + manager + .signal + .notify(available_state(&release, notes, None)); + session.package = Some(Package::Available(Box::new(release))); + Ok(()) } /// Products that installing the downloaded release would close because they run now. Empty @@ -369,7 +402,7 @@ fn start( return Ok(()); } - let mut pause = None; + let mut cancel = None; match operation { Operation::Check => { // Checking again keeps a saved download only if the same release is found. @@ -382,8 +415,11 @@ fn start( return Err("Сначала проверьте доступную версию".into()); } let (sender, receiver) = oneshot::channel(); - *manager.pause.lock().unwrap_or_else(PoisonError::into_inner) = Some(sender); - pause = Some(receiver); + *manager + .cancel + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(sender); + cancel = Some(receiver); manager.signal.notify(State::Downloading { received: 0, total: 0, @@ -401,9 +437,9 @@ fn start( } tauri::async_runtime::spawn(async move { - let result = run(&app, &manager, &mut session, operation, install, pause).await; + let result = run(&app, &manager, &mut session, operation, install, cancel).await; manager - .pause + .cancel .lock() .unwrap_or_else(PoisonError::into_inner) .take(); @@ -475,7 +511,7 @@ async fn run( session: &mut Session, operation: Operation, install: InstallOptions, - pause: Option>, + cancel: Option>, ) -> Result<(), String> { let desktop = manager.desktop; let name = desktop.name(); @@ -536,27 +572,31 @@ async fn run( return Err("Сначала проверьте доступную версию".into()); }; let release = selected.as_ref().clone(); - let token = hub_tokens::proxy_token(app).await?.value; - let download = installer::download_release(release.clone(), &token, |progress| { - manager.signal.notify(State::Downloading { - received: progress.received, - total: progress.total, - reconnecting: progress.reconnecting, - }); - }); - // Without a pause request the sender is dropped, which disables that branch. - let pause = pause.unwrap_or_else(|| oneshot::channel().1); + let download = async { + let token = hub_tokens::proxy_token(app) + .await + .map_err(anyhow::Error::msg)? + .value; + installer::download_release(release.clone(), &token, |progress| { + manager.signal.notify(State::Downloading { + received: progress.received, + total: progress.total, + reconnecting: progress.reconnecting, + }); + }) + .await + }; + // Cancellation also interrupts token resolution and reconnect delays. + let cancel = cancel.unwrap_or_else(|| oneshot::channel().1); let result = tokio::select! { + biased; + Ok(()) = cancel => None, result = download => Some(result), - Ok(()) = pause => None, }; let Some(result) = result else { - log::info!("{} download paused", desktop.product()); - let saved = saved_download(desktop, Some(&release)).await; - let notes = release_notes(app, &release).await?; - manager - .signal - .notify(available_state(&release, notes, saved)); + log::info!("{} download cancelled", desktop.product()); + // The cancelling command owns cleanup and publishes the next state after + // this future releases the session lock and the archive file handle. return Ok(()); }; let download = match result { @@ -663,3 +703,102 @@ async fn run( Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::ipc_test; + use serde_json::json; + use tauri::test::{mock_builder, mock_context, noop_assets}; + + #[test] + fn ipc_install_snapshots_keep_each_desktops_progress_and_release_separate() { + let managers = InstallManagers::default(); + managers + .get(DesktopApp::Claude) + .signal + .notify(State::Downloading { + received: 1024, + total: 4096, + reconnecting: true, + }); + managers + .get(DesktopApp::ChatGpt) + .signal + .notify(State::ReadyToInstall { + version: "9.9.9".into(), + path: None, + notes: vec!["Сохраните текущую работу".into()], + confirmation: Some("Подтвердить замену".into()), + }); + let app = mock_builder() + .manage(managers) + .invoke_handler(tauri::generate_handler![get_desktop_install_state]) + .build(mock_context(noop_assets())) + .expect("test app"); + let window = ipc_test::window(&app); + assert_eq!( + ipc_test::invoke( + &window, + "get_desktop_install_state", + json!({ "desktop": "claude", "lastRevision": null }) + ), + Ok( + json!({ "revision": 1, "status": "downloading", "received": 1024, "total": 4096, "reconnecting": true }) + ) + ); + assert_eq!( + ipc_test::invoke( + &window, + "get_desktop_install_state", + json!({ "desktop": "chatgpt", "lastRevision": null }) + ), + Ok( + json!({ "revision": 1, "status": "ready_to_install", "version": "9.9.9", "path": null, + "notes": ["Сохраните текущую работу"], "confirmation": "Подтвердить замену" }) + ) + ); + assert!( + ipc_test::invoke( + &window, + "get_desktop_install_state", + json!({ "desktop": "unknown" }) + ) + .is_err() + ); + } + + #[test] + fn ipc_cancellation_cannot_discard_an_installation_in_progress() { + let managers = InstallManagers::default(); + managers + .get(DesktopApp::Claude) + .signal + .notify(State::Installing { close: true }); + let app = mock_builder() + .manage(managers) + .invoke_handler(tauri::generate_handler![ + cancel_desktop_download, + get_desktop_install_state + ]) + .build(mock_context(noop_assets())) + .expect("test app"); + let window = ipc_test::window(&app); + assert_eq!( + ipc_test::invoke( + &window, + "cancel_desktop_download", + json!({ "desktop": "claude" }) + ), + Err(json!("Нет скачивания, которое можно отменить")) + ); + assert_eq!( + ipc_test::invoke( + &window, + "get_desktop_install_state", + json!({ "desktop": "claude", "lastRevision": null }) + ), + Ok(json!({ "revision": 1, "status": "installing", "close": true })) + ); + } +} diff --git a/crates/wizard-gui/src/hub_auth.rs b/crates/wizard-gui/src/hub_auth.rs index f981565..6116087 100644 --- a/crates/wizard-gui/src/hub_auth.rs +++ b/crates/wizard-gui/src/hub_auth.rs @@ -9,7 +9,7 @@ use crate::{ }; use alloc::sync::Arc; use core::{future::Future, pin::pin, time::Duration}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use std::sync::{Mutex, MutexGuard, PoisonError}; use tauri::Manager as _; use tokio::time::Instant; @@ -252,10 +252,54 @@ pub(crate) async fn select_hub(app: tauri::AppHandle, hub_id: String) -> Result< Ok(()) } +/// Reads only non-secret summary fields for the selected, accessible hub. +#[tauri::command] +pub(crate) async fn get_hub_summary( + app: tauri::AppHandle, + hub_id: String, +) -> Result { + let profile = load_profile(&app) + .await + .map_err(|_| "Не удалось загрузить хаб")?; + if !profile.hubs.iter().any(|hub| hub.hub_id == hub_id) { + return Err("Хаб недоступен этому аккаунту".into()); + } + let (sent, summary) = hub_tokens::with_session(&app, |client, session| async move { + let (update, summary) = hub::fetch_hub_summary(&client, &session, &hub_id).await; + let current_session = match &update { + hub::SessionUpdate::Refreshed(refreshed) => refreshed.clone(), + _ => session, + }; + (update, summary.map(|summary| (current_session, summary))) + }) + .await + .map_err(|_| "Не удалось загрузить баланс хаба")?; + let settings = settings::get_state(&app).map_err(|_| "Настройки недоступны")?; + if settings.hub_session != sent + || profile.active_hub_id(&settings.active_hub_id) != summary.hub_id + { + return Err("Выбранный хаб изменился".into()); + } + Ok(summary) +} + +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum HubSection { + Payments, +} + /// Opens only the configured Hub origin in the system browser. #[tauri::command] -pub(crate) async fn open_hub(app: tauri::AppHandle, theme: String) -> Result<(), String> { +pub(crate) async fn open_hub( + app: tauri::AppHandle, + theme: String, + section: Option, +) -> Result<(), String> { let mut url = Url::parse(hub::HUB_ORIGIN).map_err(|_| "Некорректный адрес хаба")?; + if matches!(section, Some(HubSection::Payments)) { + url.set_path("/payments"); + } let account = HubAccount::saved(&app, false, None); if let Some(id) = account.active_hub_id { url.query_pairs_mut().append_pair("hub_id", &id); diff --git a/crates/wizard-gui/src/ipc_test.rs b/crates/wizard-gui/src/ipc_test.rs new file mode 100644 index 0000000..a5010d8 --- /dev/null +++ b/crates/wizard-gui/src/ipc_test.rs @@ -0,0 +1,37 @@ +//! Exercise Rust command argument decoding and responses through Tauri's IPC dispatcher. +//! The test runtime creates no native windows and never starts application services. + +use serde_json::Value; +use tauri::test::MockRuntime; + +pub(crate) fn window(app: &tauri::App) -> tauri::WebviewWindow { + tauri::WebviewWindowBuilder::new(app, "main", tauri::WebviewUrl::default()) + .build() + .expect("test webview") +} + +pub(crate) fn invoke( + window: &tauri::WebviewWindow, + command: &str, + arguments: Value, +) -> Result { + tauri::test::get_ipc_response( + window, + tauri::webview::InvokeRequest { + cmd: command.into(), + callback: tauri::ipc::CallbackFn(0), + error: tauri::ipc::CallbackFn(1), + url: if cfg!(windows) { + "http://tauri.localhost" + } else { + "tauri://localhost" + } + .parse() + .expect("local test origin"), + body: tauri::ipc::InvokeBody::Json(arguments), + headers: tauri::http::HeaderMap::default(), + invoke_key: tauri::test::INVOKE_KEY.into(), + }, + ) + .map(|body| body.deserialize().expect("JSON command response")) +} diff --git a/crates/wizard-gui/src/lib.rs b/crates/wizard-gui/src/lib.rs index 9812dd9..fce162d 100644 --- a/crates/wizard-gui/src/lib.rs +++ b/crates/wizard-gui/src/lib.rs @@ -13,6 +13,8 @@ mod autostart; mod desktop_install; mod hub_auth; mod hub_tokens; +#[cfg(test)] +mod ipc_test; mod logs; mod proxy; mod revision_signal; @@ -112,7 +114,7 @@ pub fn run_application() -> Result<()> { desktop_install::download_desktop_release, desktop_install::install_desktop_release, desktop_install::get_desktop_running_apps, - desktop_install::pause_desktop_download, + desktop_install::cancel_desktop_download, system_proxy::get_system_proxy_state, system_proxy::set_system_proxy, settings::get_application_settings, @@ -121,8 +123,11 @@ pub fn run_application() -> Result<()> { logs::read_logs, updater::get_update_state, updater::request_update, + updater::cancel_update, + updater::install_update, updater::retry_update_check, hub_auth::get_hub_account_state, + hub_auth::get_hub_summary, hub_auth::login_hub_account, hub_auth::logout_hub_account, hub_auth::select_hub, diff --git a/crates/wizard-gui/src/updater.rs b/crates/wizard-gui/src/updater.rs index 6acb06d..45a6df9 100644 --- a/crates/wizard-gui/src/updater.rs +++ b/crates/wizard-gui/src/updater.rs @@ -4,6 +4,7 @@ use anyhow::{Context as _, Result, anyhow}; use core::sync::atomic::{AtomicBool, Ordering}; use core::time::Duration; use serde::Serialize; +use std::sync::Mutex; use std::time::Instant; use tauri::Manager as _; use tauri::http::{HeaderValue, header::COOKIE}; @@ -18,18 +19,48 @@ const UPDATE_DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(2); #[serde(tag = "status", rename_all = "snake_case")] pub(crate) enum UpdateState { Checking, - Installing, + Downloading { + version: String, + received: u64, + total: Option, + }, + ReadyToInstall { + version: String, + }, + Installing { + version: String, + }, UpToDate, - Available { version: String }, - Failed { message: String }, + Available { + version: String, + }, + Failed { + message: String, + version: Option, + }, } impl UpdateState { fn is_in_progress(&self) -> bool { - matches!(self, Self::Checking | Self::Installing) + matches!( + self, + Self::Downloading { .. } | Self::ReadyToInstall { .. } | Self::Installing { .. } + ) } } +struct DownloadedUpdate { + update: Update, + bytes: Vec, +} + +#[derive(Default)] +struct UpdateJob { + generation: u64, + task: Option>, + ready: Option, +} + /// The updater's configured endpoints, tried in order. Hub's endpoint also receives the session /// and Wizard's usage parameters; the others are fallbacks that receive neither. struct UpdateSources { @@ -76,19 +107,18 @@ pub(crate) fn start(app: tauri::AppHandle, first_run: bool) -> Result<()> { let sources = UpdateSources::from_config(&app, first_run)?; let disabled = sources.endpoints.is_empty(); app.manage(sources); + app.manage(Mutex::new(UpdateJob::default())); if disabled { log::info!("application updates disabled: no endpoints configured"); app.state::>>() .notify(UpdateState::UpToDate); return Ok(()); } - start_update(app.clone()); - let state = Arc::clone(&app.state::>>()); tauri::async_runtime::spawn(async move { loop { - tokio::time::sleep(UPDATE_CHECK_INTERVAL).await; check_in_background(&app, &state).await; + tokio::time::sleep(UPDATE_CHECK_INTERVAL).await; } }); Ok(()) @@ -99,10 +129,6 @@ pub(crate) async fn get_update_state( last_revision: Option, state: tauri::State<'_, Arc>>, ) -> Result, String> { - // state.update(|current| { - // (!current.is_in_progress()).then(|| UpdateState::Failed { message: "test update error".to_owned() }) - // // (!current.is_in_progress()).then(|| UpdateState::Available { version: "0.0.0".to_owned() }) - // }); state .wait(last_revision) .await @@ -110,64 +136,168 @@ pub(crate) async fn get_update_state( } #[tauri::command] -pub(crate) fn request_update(app: tauri::AppHandle) { +#[expect( + clippy::needless_pass_by_value, + reason = "Tauri injects application handles by value" +)] +pub(crate) fn request_update(app: tauri::AppHandle) -> Result<(), String> { let state = Arc::clone(&app.state::>>()); - // Claim the next update atomically to prevent concurrent installations. - let Some(_) = state.update(|current| { - if current.is_in_progress() { - return None; - } - Some(UpdateState::Checking) - }) else { - return; + let manager = app.state::>(); + let mut job = manager.lock().map_err(|_| "Обновление недоступно")?; + let (UpdateState::Available { version } + | UpdateState::Failed { + version: Some(version), + .. + }) = state.current().state + else { + return Ok(()); }; - start_update(app); + job.generation = job.generation.wrapping_add(1); + let generation = job.generation; + state.notify(UpdateState::Downloading { + version: version.clone(), + received: 0, + total: None, + }); + let application = app.clone(); + job.task = Some(tauri::async_runtime::spawn(async move { + let result = download_update(&application, &state, generation).await; + let manager = application.state::>(); + let Ok(mut job) = manager.lock() else { + return; + }; + if job.generation != generation { + return; + } + job.task = None; + match result { + Ok(Some(download)) => { + let version = download.update.version.clone(); + job.ready = Some(download); + state.notify(UpdateState::ReadyToInstall { version }); + } + Ok(None) => { + state.notify(UpdateState::UpToDate); + } + Err(error) => { + log::error!("application update download failed: {error:#}"); + state.notify(UpdateState::Failed { + message: format!("{error:#}"), + version: Some(version), + }); + } + } + })); + Ok(()) } #[tauri::command] -pub(crate) fn retry_update_check(app: tauri::AppHandle) { - let state = Arc::clone(&app.state::>>()); - if !matches!(state.current().state, UpdateState::Failed { .. }) { - return; +#[expect( + clippy::needless_pass_by_value, + reason = "Tauri injects application handles by value" +)] +pub(crate) fn cancel_update(app: tauri::AppHandle) -> Result<(), String> { + let state = app.state::>>(); + let manager = app.state::>(); + let mut job = manager.lock().map_err(|_| "Обновление недоступно")?; + let (UpdateState::Downloading { version, .. } | UpdateState::ReadyToInstall { version }) = + state.current().state + else { + return Ok(()); + }; + job.generation = job.generation.wrapping_add(1); + if let Some(task) = job.task.take() { + task.abort(); } - tauri::async_runtime::spawn(async move { - check_in_background(&app, &state).await; - }); + job.ready = None; + state.notify(UpdateState::Available { version }); + Ok(()) } -fn start_update(app: tauri::AppHandle) { +#[tauri::command] +#[expect( + clippy::needless_pass_by_value, + reason = "Tauri injects application handles by value" +)] +pub(crate) fn install_update(app: tauri::AppHandle) -> Result<(), String> { let state = Arc::clone(&app.state::>>()); + let manager = app.state::>(); + let mut job = manager.lock().map_err(|_| "Обновление недоступно")?; + if !matches!(state.current().state, UpdateState::ReadyToInstall { .. }) { + return Ok(()); + } + let download = job.ready.take().ok_or("Сначала скачайте обновление")?; + let version = download.update.version.clone(); + state.notify(UpdateState::Installing { + version: version.clone(), + }); + let application = app.clone(); tauri::async_runtime::spawn(async move { - if let Err(error) = check_and_install_update(&app, &state).await { - log::error!("application update failed: {error:#}"); + if let Err(error) = install_downloaded_update(&application, download).await { + log::error!("application update installation failed: {error:#}"); state.notify(UpdateState::Failed { message: format!("{error:#}"), + version: Some(version), }); } }); + Ok(()) } -async fn check_and_install_update( +#[tauri::command] +pub(crate) fn retry_update_check(app: tauri::AppHandle) { + let state = Arc::clone(&app.state::>>()); + if !matches!( + state.current().state, + UpdateState::Failed { version: None, .. } + ) { + return; + } + tauri::async_runtime::spawn(async move { + check_in_background(&app, &state).await; + }); +} + +async fn download_update( app: &tauri::AppHandle, state: &RevisionSignal, -) -> Result<()> { - log::info!("checking for application updates"); - + generation: u64, +) -> Result> { let Some(mut update) = find_update(app).await? else { - log::info!("application is up to date"); - state.notify(UpdateState::UpToDate); - return Ok(()); + return Ok(None); }; update.timeout = Some(UPDATE_DOWNLOAD_TIMEOUT); log::info!("downloading application update {}", update.version); - state.notify(UpdateState::Installing); - + let mut received = 0; let bytes = update - .download(|_, _| {}, || {}) + .download( + |chunk, total| { + received += chunk as u64; + let manager = app.state::>(); + let Ok(job) = manager.lock() else { + return; + }; + if job.generation == generation { + state.notify(UpdateState::Downloading { + version: update.version.clone(), + received, + total, + }); + } + }, + || {}, + ) .await .context("Не удалось скачать обновление")?; + Ok(Some(DownloadedUpdate { update, bytes })) +} +async fn install_downloaded_update( + app: &tauri::AppHandle, + download: DownloadedUpdate, +) -> Result<()> { + let DownloadedUpdate { update, bytes } = download; // download() verifies the update signature before service removal begins. let update_guard = wizard_proxy_daemon::prepare_update() .await @@ -201,6 +331,9 @@ async fn check_and_install_update( } async fn check_in_background(app: &tauri::AppHandle, state: &RevisionSignal) { + if state.current().state.is_in_progress() { + return; + } log::info!("checking for application updates in background"); let next = match find_update(app).await { Ok(Some(update)) => { @@ -212,7 +345,10 @@ async fn check_in_background(app: &tauri::AppHandle, state: &RevisionSignal UpdateState::UpToDate, Err(error) => { log::error!("background update check failed: {error:#}"); - return; + UpdateState::Failed { + message: "Не удалось проверить обновления. Повторим автоматически.".into(), + version: None, + } } }; // Do not overwrite an installation request accepted during the network check. @@ -322,6 +458,97 @@ async fn check( #[cfg(test)] mod tests { use super::*; + use crate::ipc_test; + use serde_json::{Value, json}; + use tauri::test::{mock_builder, mock_context, noop_assets}; + + #[test] + fn ipc_cancel_stops_the_native_task_and_restores_the_available_version() { + struct OnDrop(Option>); + impl Drop for OnDrop { + fn drop(&mut self) { + if let Some(sender) = self.0.take() { + sender.send(()).ok(); + } + } + } + + let signal = Arc::new(RevisionSignal::new(UpdateState::Downloading { + version: "9.9.9".into(), + received: 1024, + total: Some(4096), + })); + let (started, started_rx) = tokio::sync::oneshot::channel(); + let (stopped, stopped_rx) = tokio::sync::oneshot::channel(); + let task = tauri::async_runtime::spawn(async move { + let _on_drop = OnDrop(Some(stopped)); + started.send(()).expect("task started"); + core::future::pending::<()>().await; + }); + tauri::async_runtime::block_on(started_rx).expect("download task running"); + let app = mock_builder() + .manage(Arc::clone(&signal)) + .manage(Mutex::new(UpdateJob { + generation: 7, + task: Some(task), + ready: None, + })) + .invoke_handler(tauri::generate_handler![get_update_state, cancel_update]) + .build(mock_context(noop_assets())) + .expect("test app"); + let window = ipc_test::window(&app); + assert_eq!( + ipc_test::invoke(&window, "cancel_update", json!({})), + Ok(Value::Null) + ); + assert_eq!( + ipc_test::invoke(&window, "get_update_state", json!({ "lastRevision": null })), + Ok(json!({ "revision": 1, "status": "available", "version": "9.9.9" })) + ); + tauri::async_runtime::block_on(async { + tokio::time::timeout(Duration::from_secs(1), stopped_rx) + .await + .expect("cancel drops the running download") + .expect("download dropped"); + }); + let manager = app.state::>(); + let job = manager.lock().expect("job lock"); + assert_eq!(job.generation, 8); + assert!(job.task.is_none()); + assert!(job.ready.is_none()); + } + + #[test] + fn ipc_observation_waits_for_a_new_revision_and_installation_cannot_be_cancelled() { + let signal = Arc::new(RevisionSignal::new(UpdateState::Checking)); + let app = mock_builder() + .manage(Arc::clone(&signal)) + .manage(Mutex::new(UpdateJob::default())) + .invoke_handler(tauri::generate_handler![get_update_state, cancel_update]) + .build(mock_context(noop_assets())) + .expect("test app"); + let window = ipc_test::window(&app); + let next = Arc::clone(&signal); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(Duration::from_millis(20)).await; + next.notify(UpdateState::Installing { + version: "9.9.9".into(), + }); + }); + assert_eq!( + ipc_test::invoke(&window, "get_update_state", json!({ "lastRevision": 0 })), + Ok(json!({ "revision": 1, "status": "installing", "version": "9.9.9" })) + ); + assert_eq!( + ipc_test::invoke(&window, "cancel_update", json!({})), + Ok(Value::Null) + ); + assert!(matches!( + signal.current().state, + UpdateState::Installing { .. } + )); + assert_eq!(signal.current().revision, 1); + } #[test] fn hub_endpoint_keeps_channel_and_adds_usage() { diff --git a/crates/wizard-gui/windows/app.manifest b/crates/wizard-gui/windows/app.manifest new file mode 100644 index 0000000..2d510ed --- /dev/null +++ b/crates/wizard-gui/windows/app.manifest @@ -0,0 +1,14 @@ + + + + + + + diff --git a/crates/wizard-gui/wizard-ui/src/App.tsx b/crates/wizard-gui/wizard-ui/src/App.tsx index 5090e00..53c674b 100644 --- a/crates/wizard-gui/wizard-ui/src/App.tsx +++ b/crates/wizard-gui/wizard-ui/src/App.tsx @@ -2,32 +2,36 @@ import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; import { AppSidebar } from "./AppSidebar"; import { AgentPage } from "./agents/AgentPage"; import { useAgentState } from "./agents/agents_state"; -import { pageFromHash } from "./agents/navigation"; +import { agentPageNames, pageFromHash } from "./agents/navigation"; import { useProxy } from "./agents/proxy"; -import { AuthLayout } from "./components/catalyst/auth-layout"; -import { Badge } from "./components/catalyst/badge"; import { SidebarLayout } from "./components/catalyst/sidebar-layout"; -import { ErrorText } from "./components/ErrorText"; -import { OpenLogsButton } from "./logs/OpenLogsButton"; +import { StateNotice } from "./components/ui/StateNotice"; +import { PageHeader } from "./components/ui/Layout"; import { useHubAccountControl } from "./settings/HubAccount"; import { HubSignIn } from "./settings/HubSignIn"; import { SettingsPage } from "./settings/SettingsPage"; import { useUpdateState } from "./updates/update"; -import { UpdateScreen } from "./updates/UpdateScreen"; +import { UpdateDialog } from "./updates/UpdateDialog"; import { Overview } from "./overview/Overview"; +import { InstallationsProvider } from "./onboarding/Installations"; +import { StartupScreen } from "./components/StartupScreen"; function subscribeNavigation(onChange: () => void) { window.addEventListener("hashchange", onChange); return () => window.removeEventListener("hashchange", onChange); } -const onboardingKey = "coreinfra.onboarding.completed"; +const startupKey = "coreinfra.startup.seen"; -function needsOnboarding() { - // A direct link to an agent or settings should still open that page normally. - if (pageFromHash(window.location.hash) !== "overview") return false; - try { return localStorage.getItem(onboardingKey) !== "true"; } - catch { return true; } +function needsStartup() { + try { + return ( + localStorage.getItem(startupKey) !== "true" && + localStorage.getItem("coreinfra.onboarding.completed") !== "true" + ); + } catch { + return true; + } } function App() { @@ -35,12 +39,18 @@ function App() { const agents = useAgentState(); const proxy = useProxy(); const account = useHubAccountControl(); - const page = useSyncExternalStore(subscribeNavigation, () => pageFromHash(window.location.hash)); - const state = update.state; - const [onboarding, setOnboarding] = useState(needsOnboarding); - const finishOnboarding = useCallback(() => { - try { localStorage.setItem(onboardingKey, "true"); } catch { /* The current session can still continue. */ } - setOnboarding(false); + const page = useSyncExternalStore(subscribeNavigation, () => + pageFromHash(window.location.hash), + ); + const [updateOpen, setUpdateOpen] = useState(false); + const [starting, setStarting] = useState(needsStartup); + const finishStartup = useCallback(() => { + try { + localStorage.setItem(startupKey, "true"); + } catch { + /* The current session can still continue. */ + } + setStarting(false); }, []); // Pages share the window scroll; start each one from the top. @@ -48,32 +58,46 @@ function App() { window.scrollTo(0, 0); }, [page]); - if (update.error === undefined && (!state || state.status === "checking" || state.status === "installing")) { - return ( - -
- - -
-
- ); - } + if (starting) return ; return ( - } - > - {page === "overview" ? : <> - - {page === "settings" && } - {page !== "settings" && agents.status === "loading" && Загрузка…} - {page !== "settings" && agents.status === "error" && Не удалось загрузить состояние агентов: {agents.message}} - {agents.status === "ready" && } - } - + + setUpdateOpen(true)} />} + > + {page === "overview" ? ( + + ) : ( + <> + + {page === "settings" && } + {page !== "settings" && agents.status !== "ready" && ( +
+ + + {agents.status === "loading" + ? "Ищем установленных агентов…" + : `Не удалось загрузить состояние агента: ${agents.message}`} + +
+ )} + {agents.status === "ready" && ( + + )} + + )} +
+ {updateOpen && setUpdateOpen(false)} />} +
); } diff --git a/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx b/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx index 34de81a..3289c96 100644 --- a/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx +++ b/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx @@ -1,26 +1,63 @@ import type { ComponentType, ComponentPropsWithoutRef } from "react"; import { useClose } from "@headlessui/react"; -import { Squares2X2Icon } from "@heroicons/react/20/solid"; -import { agentPaths, overviewPath, type AgentPageId, type AppPageId } from "./agents/navigation"; +import { Cog6ToothIcon, Squares2X2Icon } from "@heroicons/react/20/solid"; +import { + agentPaths, + overviewPath, + settingsPath, + type AgentPageId, + type AppPageId, +} from "./agents/navigation"; import { AppLogo } from "./components/AppLogo"; -import { ClaudeIcon, OpenAiIcon, OpenCodeIcon, PiIcon } from "./components/BrandIcons"; +import { + ClaudeIcon, + OpenAiIcon, + OpenCodeIcon, + PiIcon, +} from "./components/BrandIcons"; import { Button } from "./components/catalyst/button"; -import { Sidebar, SidebarBody, SidebarFooter, SidebarHeader, SidebarHeading, SidebarItem, SidebarLabel, SidebarSection, SidebarSpacer } from "./components/catalyst/sidebar"; +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"; import { UpdateItem } from "./updates/UpdateItem"; +import { SidebarDownloads } from "./SidebarDownloads"; -export function AppSidebar({ page, account, update }: { +export function AppSidebar({ + page, + account, + update, + onUpdate, +}: { page: AppPageId; account: HubAccountControl; update: UpdateObservation; + onUpdate: () => void; }) { // Closes the sidebar dialog on narrow windows; does nothing on the desktop layout. const close = useClose(); - function item(id: AgentPageId, label: string, Icon: ComponentType>) { + function item( + id: AgentPageId, + label: string, + Icon: ComponentType>, + ) { return ( - + {label} @@ -30,20 +67,41 @@ export function AppSidebar({ page, account, update }: { return ( - - + Обзор + + + Настройки + - Агенты + + Агенты + {item("claude_desktop", "Claude Desktop", ClaudeIcon)} {item("codex", "ChatGPT / Codex", OpenAiIcon)} {item("claude", "Claude Code", ClaudeIcon)} @@ -52,11 +110,12 @@ export function AppSidebar({ page, account, update }: { - + + - + ); diff --git a/crates/wizard-gui/wizard-ui/src/SidebarDownloads.css b/crates/wizard-gui/wizard-ui/src/SidebarDownloads.css new file mode 100644 index 0000000..8b608a4 --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/SidebarDownloads.css @@ -0,0 +1 @@ +.sidebar-downloads { display: flex; flex: none; flex-direction: column; gap: var(--ui-space-2); max-height: 40dvh; overflow-y: auto; padding: 0 var(--ui-space-4) var(--ui-space-4); } diff --git a/crates/wizard-gui/wizard-ui/src/SidebarDownloads.tsx b/crates/wizard-gui/wizard-ui/src/SidebarDownloads.tsx new file mode 100644 index 0000000..5c02672 --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/SidebarDownloads.tsx @@ -0,0 +1,58 @@ +import { megabytes } from "./agents/desktop_install_state"; +import { AgentIcon, choices } from "./onboarding/agents"; +import { + downloadProgress, + useInstallations, +} from "./onboarding/installations_state"; +import { TransferCard } from "./components/ui/TransferCard"; +import { useSidebarAction } from "./components/catalyst/sidebar-layout"; +import "./SidebarDownloads.css"; + +/** Downloads are part of the sidebar, directly above the account divider. */ +export function SidebarDownloads() { + const { jobs, observations, open } = useInstallations(); + const runSidebarAction = useSidebarAction(); + if (!jobs.length) return null; + return ( +
+ {jobs.map((desktop) => { + const choice = choices.find((choice) => choice.desktop === desktop)!; + const state = observations[desktop].state!; + const downloading = state.status === "downloading"; + const installed = state.status === "installed"; + const ready = state.status === "ready_to_install"; + const failed = state.status === "failed"; + return ( + } + status={ + downloading + ? `${megabytes(state.received)} / ${state.total > 0 ? megabytes(state.total) : "…"} МБ` + : ready + ? "Готово к установке" + : installed + ? "Установлено" + : failed + ? state.operation === "install" + ? "Не удалось установить" + : "Не удалось скачать" + : "Устанавливается…" + } + notice={ + downloading && state.reconnecting ? "Переподключение…" : undefined + } + progress={downloadProgress(state)} + downloading={downloading} + filled={ready || installed || state.status === "installing"} + tone={installed ? "success" : failed ? "error" : "default"} + onOpen={() => runSidebarAction(() => open(desktop))} + /> + ); + })} +
+ ); +} diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx index d85fecf..227e19f 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx @@ -1,36 +1,85 @@ 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, tokenPrefix } from "../settings/hub_tokens"; +import { + type AgentChange, + type AgentId, + type HubMode, + type RoutingMode, + type TokenChoice, +} from "./agents_state"; +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 { + Dropdown, + DropdownButton, + DropdownDescription, + DropdownItem, + DropdownLabel, + DropdownMenu, +} from "../components/catalyst/dropdown"; +import { + Description, + FieldGroup, + Fieldset, + Label, +} from "../components/catalyst/fieldset"; +import { ActionBar, Panel } from "../components/ui/Layout"; import { Radio, RadioField, RadioGroup } from "../components/catalyst/radio"; import { Text } from "../components/catalyst/text"; import { ErrorText } from "../components/ErrorText"; import { useSystemProxy } from "../settings/system_proxy"; import { SystemProxyPrompt } from "../settings/SystemProxyPrompt"; -type ModeOption = { mode: M; label: string }; +type ModeOption = { + mode: M; + label: string; + description: string; +}; export const currentModeLabels: Record = { - sub: "Подписка", - hub: "API-доступ", + sub: "CoreInfra AI Hub", + hub: "CoreInfra AI Hub", disabled: "Без CoreInfra", }; -export function routingModes(subscription: "Claude" | "Codex"): ModeOption[] { +export function routingModes( + subscription: "Claude" | "Codex", +): ModeOption[] { return [ - { mode: "hub", label: "CoreInfra AI Hub – API-доступ (оплата за использование)" }, - { mode: "sub", label: `CoreInfra AI Hub – своя подписка ${subscription}` }, - { mode: "disabled", label: "Без CoreInfra AI Hub" }, + { + mode: "hub", + label: "API-доступ", + description: "Через CoreInfra AI Hub, с оплатой за использование.", + }, + { + mode: "sub", + label: `Своя подписка ${subscription}`, + description: "Подключение через прокси CoreInfra AI Hub.", + }, + { + mode: "disabled", + label: "Без CoreInfra AI Hub", + description: "Использовать собственные настройки агента.", + }, ]; } export const hubModes: ModeOption[] = [ - { mode: "hub", label: "CoreInfra AI Hub – API-доступ (оплата за использование)" }, - { mode: "disabled", label: "Без CoreInfra AI Hub" }, + { + mode: "hub", + label: "API-доступ", + description: "Через CoreInfra AI Hub, с оплатой за использование.", + }, + { + mode: "disabled", + label: "Без CoreInfra AI Hub", + description: "Использовать собственные настройки агента.", + }, ]; // Hub access shared by all pages. Token values are secrets: never log them. @@ -48,75 +97,172 @@ const createdTokenNames: Record = { // Only reuse credentials listed in the selected Hub. Wait for its list before // offering creation; the backend creates on an explicit configuration action. -export function getAgentToken(agent: AgentId, agentToken: string | null, hub: Hub) { +export function getAgentToken( + agent: AgentId, + agentToken: string | null, + hub: Hub, +) { const createdName = createdTokenNames[agent]; const ready = hub.signedIn && hub.status === "ready"; - const existing = hub.tokens.find((token) => token.token === agentToken) - ?? hub.tokens.filter((token) => token.name === createdName).sort((a, b) => a.issued_at - b.issued_at)[0]; + const existing = + hub.tokens.find((token) => token.token === agentToken) ?? + hub.tokens + .filter((token) => token.name === createdName) + .sort((a, b) => a.issued_at - b.issued_at)[0]; let selected: TokenChoice | undefined; if (ready) { - selected = existing ? { kind: "existing", token: existing.token } : { kind: "create" }; + selected = existing + ? { kind: "existing", token: existing.token } + : { kind: "create" }; } - return { selected, ready, name: existing ? existing.name || "без названия" : createdName }; + return { + selected, + ready, + name: existing ? existing.name || "без названия" : createdName, + }; } // Keep a choice local to this agent's configuration form. 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 }>(); +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; + 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 }), + choose: (value: string | undefined) => + setDraft( + value === undefined ? undefined : { agent, agentToken, token: value }, + ), }; } -export function TokenNote({ token, hub, disabled }: { +export function TokenNote({ + token, + hub, + disabled, +}: { token: ReturnType; hub: Hub; disabled: boolean; }) { - if (!hub.signedIn) return Войдите в CoreInfra Hub, чтобы Wizard создал токен для агента.; - if (hub.status === "error") return
- {hub.error} - -
; + if (!hub.signedIn) + return ( + + Войдите в CoreInfra Hub, чтобы Wizard создал токен для агента. + + ); + if (hub.status === "error") + return ( +
+ {hub.error} + +
+ ); if (!token.ready) return Проверяем токен агента…; - 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}» - } - - - ; + 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, hub, note, disabled, error, onPrepare, initialMode, actions, actionsClassName = "", editing = false, needsApply = false }: { +export function RoutingFieldset({ + agent, + modes, + mode, + toChange, + agentToken, + hub, + note, + disabled, + error, + onPrepare, + initialMode, + actions, + actionsClassName = "", + editing = false, + needsApply = false, +}: { agent: AgentId; modes: ModeOption[]; mode: M; @@ -136,11 +282,16 @@ export function RoutingFieldset({ agent, modes, mode, toChange const [draft, setDraft] = useState(initialMode); const selected = draft ?? mode; const enabled = selected !== "disabled"; - const proxyOnly = agent === "claude_desktop" && selected === "sub"; + const proxyOnly = + agent === "claude_desktop" && selected === "sub"; const token = useAgentToken(agent, agentToken, hub); - const tokenChanged = !proxyOnly && (token.selected?.kind === "create" - || (token.selected?.kind === "existing" && token.selected.token !== agentToken)); - const changed = selected !== mode || (enabled && (needsApply || tokenChanged)); + 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); @@ -150,34 +301,70 @@ export function RoutingFieldset({ agent, modes, mode, toChange function chooseMode(value: M) { setDraft(value); - if (value === "sub" && systemProxy.state?.status !== "on") setProxyPrompt(true); + if (value === "sub" && systemProxy.state?.status !== "on") + setProxyPrompt(true); } - return <> -
- Подключение - {note && {note}} - - chooseMode(value as M)}> - {modes.map((option) => ( - - - - - ))} - - {proxyOnly ? Подключение через общий прокси Wizard. - : enabled && } -
- {actions} - -
- {error && {error}} -
-
- {proxyPrompt && setProxyPrompt(false)} />} - ; + return ( + <> + +
+ {note && {note}} + + chooseMode(value as M)} + > + {modes.map((option) => ( + + + + {option.description} + + ))} + + {proxyOnly ? ( + Подключение через общий прокси Wizard. + ) : ( + enabled && ( + + ) + )} + + + + {error && {error}} + +
+
+ {proxyPrompt && ( + setProxyPrompt(false)} + /> + )} + + ); } diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx new file mode 100644 index 0000000..ec44b3e --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConnectionPanel.tsx @@ -0,0 +1,81 @@ +import { useEffect, useRef, useState } from "react"; +import { type AgentChange, type AgentId, type AgentStates, type PreparedAgentChange, type RoutingMode, type TokenChoice, prepareAgentChange } from "./agents_state"; +import { RoutingFieldset, hubModes, routingModes, type Hub } from "./AgentConfiguration"; +import { PreparedPlanDialog } from "./PreparedPlanDialog"; +import { MissingAgent } from "./MissingAgent"; +import { useProxy } from "./proxy"; +import { agentPageNames } from "./navigation"; +import { AgentIcon, choices } from "../onboarding/agents"; +import { useHubTokens } from "../settings/hub_tokens"; +import type { HubAccountControl } from "../settings/HubAccount"; +import { Identity } from "../components/ui/Identity"; +import { ActionBar } from "../components/ui/Layout"; +import { Button } from "../components/catalyst/button"; +import { ErrorText } from "../components/ErrorText"; + +/** The control panel edits the same connection settings without leaving the overview. */ +export function AgentConnectionPanel({ agent, agents, account, onBack }: { + agent: AgentId; + agents: AgentStates; + account: HubAccountControl; + onBack: () => void; +}) { + const [prepared, setPrepared] = useState(); + const [preparing, setPreparing] = useState(false); + const [error, setError] = useState(); + const inFlight = useRef(false); + const busy = preparing || !!prepared; + const setAgentBusy = account.setAgentBusy; + useEffect(() => { + setAgentBusy(busy); + return () => setAgentBusy(false); + }, [busy, setAgentBusy]); + const hub: Hub = { ...useHubTokens(account.account?.active_hub_id), signedIn: account.signedIn }; + const proxy = useProxy(); + const detection = agents[agent]; + const choice = choices.find(choice => choice.id === agent)!; + const proxyAgent = agent === "claude_desktop" || (agent === "codex" && agents.codex.status === "found" && agents.codex.data.desktop.status === "found"); + const needsApply = detection.status === "found" && detection.data.routing_mode !== "disabled" && + (("proxy_needs_apply" in detection.data && detection.data.proxy_needs_apply) || (proxyAgent && proxy.proxy?.enabled === false)); + const errors = detection.status === "error" ? [detection.data] + : agent === "codex" && agents.codex.status === "found" ? [agents.codex.data.cli, agents.codex.data.desktop].flatMap(part => part.status === "error" ? [part.data] : []) : []; + + async function prepare(change: AgentChange, token: TokenChoice | null) { + if (inFlight.current || prepared) return; + inFlight.current = true; + setPreparing(true); + setError(undefined); + try { setPrepared(await prepareAgentChange(change, token)); } + catch (cause) { setError(typeof cause === "string" ? cause : "Не удалось подготовить изменения. Попробуйте ещё раз."); } + finally { inFlight.current = false; setPreparing(false); } + } + function toChange(mode: RoutingMode): AgentChange { + switch (agent) { + case "codex": return { CodexSetRouting: mode }; + case "claude": return { ClaudeSetRouting: mode }; + case "claude_desktop": return { ClaudeDesktopSetRouting: mode }; + case "opencode": return { SetOpenCodeHub: mode === "hub" ? "hub" : "disabled" }; + case "pi": return { SetPiHub: mode === "hub" ? "hub" : "disabled" }; + } + } + return <> + } title={agentPageNames[agent]} focusable /> + {errors.map(message =>
Не удалось обнаружить: {message}
)} + {detection.status === "found" ? Назад} + onPrepare={(change, token) => void prepare(change, token)} + /> : <> + {detection.status === "not_found" && agent !== "claude_desktop" && } + + } + {prepared && setPrepared(undefined)} onApplied={onBack} applyLabel="Применить" />} + ; +} diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx index be833b2..4c5aa6e 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx @@ -1,90 +1,115 @@ -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, RoutingFieldset, type Hub } from "./AgentConfiguration"; +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { + type AgentChange, + type AgentDetection, + type AgentId, + type AgentStates, + type BackupAgent, + type PreparedAgentChange, + type TokenChoice, + prepareAgentChange, +} from "./agents_state"; +import { + routingModes, + hubModes, + 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 { DesktopVersion } from "./DesktopInstall"; +import { MissingAgent } from "./MissingAgent"; +import { agentPageNames } from "./navigation"; +import { useHubTokens } from "../settings/hub_tokens"; import type { HubAccountControl } from "../settings/HubAccount"; import { useAgentProxyStartup, useProxy } from "./proxy"; import { reportError } from "../logs/log"; import { Badge } from "../components/catalyst/badge"; import { Button } from "../components/catalyst/button"; -import { DescriptionDetails, DescriptionList, DescriptionTerm } from "../components/catalyst/description-list"; -import { FieldGroup, Fieldset, Legend } from "../components/catalyst/fieldset"; -import { Heading } from "../components/catalyst/heading"; +import { + DescriptionDetails, + DescriptionList, + DescriptionTerm, +} from "../components/catalyst/description-list"; +import { PageHeader, ViewTransition } from "../components/ui/Layout"; import { ErrorText } from "../components/ErrorText"; -function PageHeading({ title, actions }: { title: string; actions?: ReactNode }) { - return ( -
- {title} - {actions} -
- ); -} - -function Version({ detection }: { detection: AgentDetection<{ version: string | null }> | { status: "not_found" } }) { - if (detection.status === "error") return Не удалось обнаружить: {detection.data}; - if (detection.status === "not_found") return <>Не найден; - return <>{detection.data.version ? `v${detection.data.version}` : "Версия неизвестна"}; -} - -// Saved routing of an agent: rows of the page's description list. -function RoutingRows({ mode, agentToken, hub }: { - mode: RoutingMode; - agentToken: string | null; - hub: Hub; +function Version({ + detection, +}: { + detection: + AgentDetection<{ version: string | null }> | { status: "not_found" }; }) { + if (detection.status === "error") + return Не удалось обнаружить: {detection.data}; + if (detection.status === "not_found") return <>Не найден; return ( <> - Режим - - - {currentModeLabels[mode]} - - - {mode !== "disabled" && agentToken !== null && ( - <> - Токен - {tokenLabel(agentToken, hub.tokens)} - - )} + {detection.data.version + ? `v${detection.data.version}` + : "Версия неизвестна"} ); } // Shared daemon state; each page decides what it means for its app. -function ProxyStatus({ proxy: { proxy, error }, startup }: { +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 (error === undefined && proxy?.enabled) + return Работает; if (startup.starting) return Запускается…; - if (startup.error) return
- {startup.error} - -
; - if (error !== undefined) return Состояние недоступно; + if (startup.error) + return ( +
+ {startup.error} + +
+ ); + if (error !== undefined) + return ( + + Состояние недоступно + + ); if (proxy === undefined) return Загрузка…; return Остановлен; } -function BackupButton({ agent, disabled }: { agent: BackupAgent; disabled: boolean }) { +function BackupButton({ + agent, + disabled, +}: { + agent: BackupAgent; + disabled: boolean; +}) { const [open, setOpen] = useState(false); return ( <> - + {open && setOpen(false)} />} ); } // The selected agent's page. Plan preparation and the plan dialog outlive page switches. -export function AgentPage({ agents, page, proxy, account }: { +export function AgentPage({ + agents, + page, + proxy, + account, +}: { agents: AgentStates; page: AgentId | null; proxy: ReturnType; @@ -92,20 +117,42 @@ export function AgentPage({ agents, page, proxy, account }: { }) { const [preparedChange, setPreparedChange] = useState(); const [isPreparingPlan, setIsPreparingPlan] = useState(false); + const [configurationRevision, setConfigurationRevision] = useState(0); + const pageContent = useRef(null); + useEffect(() => { + if (!configurationRevision) return; + const frame = requestAnimationFrame(() => { + pageContent.current?.querySelector('[role="radio"][aria-checked="true"]')?.focus({ preventScroll: true }); + }); + return () => cancelAnimationFrame(frame); + }, [configurationRevision]); // Tagged with the page that prepared the change, so it never shows on another agent's page. - const [error, setError] = useState<{ page: AgentId | null; message: string }>(); + const [error, setError] = useState<{ + page: AgentId | null; + message: string; + }>(); const pageError = error?.page === page ? error.message : undefined; const isChangeInProgress = isPreparingPlan || preparedChange !== undefined; const hub: Hub = { ...useHubTokens(account.account?.active_hub_id), signedIn: account.signedIn, }; - const claudeInstall = useDesktopInstall("claude"); - 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); + 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; @@ -118,7 +165,10 @@ export function AgentPage({ agents, page, proxy, account }: { } catch (cause: unknown) { const message = "Не удалось подготовить изменения"; reportError(message, cause); - setError({ page, message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}` }); + setError({ + page, + message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); } finally { setIsPreparingPlan(false); } @@ -132,42 +182,77 @@ export function AgentPage({ agents, page, proxy, account }: { break; case "codex": { const codex = agents.codex; - const chatGptFound = codex.status === "found" && codex.data.desktop.status === "found"; - const chatGptProxyStopped = !proxyStartup.starting && proxy.proxy?.enabled === false && chatGptFound - && codex.status === "found" && codex.data.routing_mode !== "disabled"; + const chatGptFound = + codex.status === "found" && codex.data.desktop.status === "found"; + const chatGptProxyStopped = + !proxyStartup.starting && + proxy.proxy?.enabled === false && + chatGptFound && + codex.status === "found" && + codex.data.routing_mode !== "disabled"; content = ( <> - } /> + + } + /> {codex.status === "error" ? ( -
Не удалось получить состояние ChatGPT / Codex: {codex.data}
+
+ + Не удалось получить состояние ChatGPT / Codex: {codex.data} + +
) : ( - + ChatGPT - + + + + + Codex CLI - + + + Прокси для ChatGPT - {codex.status === "found" && ( - - )} )} {codex.status === "found" && ( - ({ CodexSetRouting: mode })} agentToken={codex.data.token} hub={hub} - note="Настройка общая для ChatGPT и Codex." disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> + ({ CodexSetRouting: mode })} + agentToken={codex.data.token} + hub={hub} + note="Настройка общая для ChatGPT и Codex." + disabled={isChangeInProgress} + error={pageError} + onPrepare={prepare} + /> )} - {!chatGptInstall.hidden && ( -
- {chatGptFound ? "Обновление ChatGPT" : "Установка ChatGPT"} - - - -
+ {(codex.status === "not_found" || (codex.status === "found" && codex.data.cli.status === "not_found")) && ( + )} ); @@ -177,18 +262,32 @@ export function AgentPage({ agents, page, proxy, account }: { const claude = agents.claude; content = ( <> - } /> - + + } + /> + {claude.status === "not_found" ? : Версия - - {claude.status === "found" && ( - - )} - + + + + } {claude.status === "found" && ( - ({ ClaudeSetRouting: mode })} agentToken={claude.data.token} hub={hub} - disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> + ({ ClaudeSetRouting: mode })} + agentToken={claude.data.token} + hub={hub} + disabled={isChangeInProgress} + error={pageError} + onPrepare={prepare} + /> )} ); @@ -198,30 +297,57 @@ export function AgentPage({ agents, page, proxy, account }: { const desktop = agents.claude_desktop; content = ( <> - } /> - + + } + /> + Версия - + + + + + {desktop.status === "found" && ( <> Прокси - - + + + )} {desktop.status === "found" && ( - ({ ClaudeDesktopSetRouting: mode })} agentToken={desktop.data.token} hub={hub} - disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> + ({ ClaudeDesktopSetRouting: mode })} + agentToken={desktop.data.token} + hub={hub} + disabled={isChangeInProgress} + error={pageError} + onPrepare={prepare} + /> )} -
- {desktop.status === "found" ? "Обновление приложения" : "Установка приложения"} - - - -
); break; @@ -229,21 +355,34 @@ export function AgentPage({ agents, page, proxy, account }: { case "opencode": case "pi": { const detection = agents[page]; - const name = page === "opencode" ? "OpenCode" : "Pi"; + const name = agentPageNames[page]; content = ( <> - - + + {detection.status === "not_found" ? : Версия - - {detection.status === "found" && ( - - )} - + + + + } {detection.status === "found" && ( - (page === "opencode" ? { SetOpenCodeHub: mode } : { SetPiHub: mode })} - agentToken={detection.data.token} hub={hub} disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> + + page === "opencode" + ? { SetOpenCodeHub: mode } + : { SetPiHub: mode } + } + agentToken={detection.data.token} + hub={hub} + disabled={isChangeInProgress} + error={pageError} + onPrepare={prepare} + /> )} ); @@ -254,8 +393,16 @@ export function AgentPage({ agents, page, proxy, account }: { return ( <> {/* Keyed so that drafts of one agent's form never carry over to another agent. */} - {content} - {preparedChange && setPreparedChange(undefined)} applyLabel="Применить" />} +
{content}
+ {preparedChange && ( + setPreparedChange(undefined)} + onApplied={() => setConfigurationRevision((value) => value + 1)} + applyLabel="Применить" + /> + )} ); } diff --git a/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx b/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx index b102d90..7fc3a41 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/BackupDialog.tsx @@ -1,11 +1,20 @@ import { useEffect, useState } from "react"; -import { type Backup, type BackupAgent, getAgentBackups, applyDirectChange } from "./agents_state"; +import { + type Backup, + type BackupAgent, + getAgentBackups, + applyDirectChange, +} from "./agents_state"; import { Button } from "../components/catalyst/button"; -import { Dialog, DialogActions, DialogBody, DialogDescription, DialogTitle } from "../components/catalyst/dialog"; +import { + Dialog, + DialogActions, + DialogBody, +} from "../components/catalyst/dialog"; import { Label } from "../components/catalyst/fieldset"; import { Radio, RadioField, RadioGroup } from "../components/catalyst/radio"; -import { Text } from "../components/catalyst/text"; -import { ErrorText } from "../components/ErrorText"; +import { DialogHeader } from "../components/ui/DialogHeader"; +import { EmptyState, StateNotice } from "../components/ui/StateNotice"; function label(backup: Backup): string { return `${new Date(backup.time_created).toLocaleString("ru-RU", { @@ -17,7 +26,10 @@ function label(backup: Backup): string { })} · №${backup.id}`; } -export function BackupDialog({ agent, onClose }: { +export function BackupDialog({ + agent, + onClose, +}: { agent: BackupAgent; onClose: () => void; }) { @@ -30,12 +42,19 @@ export function BackupDialog({ agent, onClose }: { useEffect(() => { let stopped = false; - void getAgentBackups(agent).then((result) => { - if (!stopped) setBackups(result); - }).catch((cause: unknown) => { - if (!stopped) setError(`Не удалось загрузить резервные копии настроек: ${String(cause)}`); - }); - return () => { stopped = true; }; + void getAgentBackups(agent) + .then((result) => { + if (!stopped) setBackups(result); + }) + .catch((cause: unknown) => { + if (!stopped) + setError( + `Не удалось загрузить резервные копии настроек: ${String(cause)}`, + ); + }); + return () => { + stopped = true; + }; }, [agent]); async function restore() { @@ -50,43 +69,75 @@ export function BackupDialog({ agent, onClose }: { setRestored(backup.id); } catch (cause: unknown) { - setError(`Не удалось восстановить копию: ${String(cause)}. Часть файлов могла быть изменена.`); + setError( + `Не удалось восстановить копию: ${String(cause)}. Часть файлов могла быть изменена.`, + ); } finally { setPending(false); } } return ( - { if (!pending) onClose(); }}> - Резервные копии настроек {agent === "codex" ? "Codex" : agent === "claude_desktop" ? "Claude Desktop" : "Claude Code"} - - Сохранённые конфигурации перед изменениями Wizard. Это не история каждого переключения режима. - {agent === "claude_desktop" && " Восстановится весь сохранённый профиль, включая настройки MCP, выбор профиля и режим подключения. После восстановления перезапустите Claude Desktop."} - {agent === "codex" && " Если фоновая служба Codex запущена, Wizard перезапустит её после восстановления. Это может прервать текущую работу."} - + { + if (!pending) onClose(); + }} + > + + Сохранённые конфигурации перед изменениями Wizard. Это не история + каждого переключения режима. + {agent === "claude_desktop" && + " Восстановится весь сохранённый профиль, включая настройки MCP, выбор профиля и режим подключения. После восстановления перезапустите Claude Desktop."} + {agent === "codex" && + " Если фоновая служба Codex запущена, Wizard перезапустит её после восстановления. Это может прервать текущую работу."} + + } + /> {backups ? ( backups.length === 0 ? ( - Резервных копий настроек пока нет. + ) : ( - setSelected(Number(value))} aria-label="Резервная копия настроек" className="max-h-72 overflow-y-auto"> + setSelected(Number(value))} + aria-label="Резервная копия настроек" + className="ui-choice-group -m-1 max-h-72 overflow-y-auto p-1" + disabled={pending} + > {backups.map((item) => ( - + ))} ) - ) : !error && Загрузка…} - {restored !== undefined && Восстановлена резервная копия настроек №{restored}.} - {error && {error}} + ) : ( + !error && Загрузка… + )} + {restored !== undefined && ( + + Восстановлена резервная копия настроек №{restored}. + + )} + {error && {error}} - diff --git a/crates/wizard-gui/wizard-ui/src/agents/DesktopInstall.tsx b/crates/wizard-gui/wizard-ui/src/agents/DesktopInstall.tsx index 84161ca..6d4c62e 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/DesktopInstall.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/DesktopInstall.tsx @@ -1,249 +1,125 @@ -import { invoke } from "@tauri-apps/api/core"; -import { useEffect, useState } from "react"; +import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; import { Button } from "../components/catalyst/button"; -import { Checkbox, CheckboxField } from "../components/catalyst/checkbox"; -import { Label } from "../components/catalyst/fieldset"; -import { Text } from "../components/catalyst/text"; import { ErrorText } from "../components/ErrorText"; +import { + useInstallations, +} from "../onboarding/installations_state"; +import type { DesktopApp } from "./desktop_install_state"; -// Keep in sync with `DesktopApp` in `crates/wizard-core/src/agents/desktop_install/mod.rs`. -export type DesktopApp = "claude" | "chatgpt"; +export type { DesktopApp } from "./desktop_install_state"; -const names: Record = { - claude: { name: "Claude" }, - chatgpt: { name: "ChatGPT" }, -}; - -type Operation = "check" | "download" | "install"; -type Release = { version: string; path: string | null; notes: string[]; confirmation: string | null }; -/** Bytes that a paused or interrupted download saved; downloading again continues from them. */ -type Saved = { received: number; total: number }; -type Phase = - | { status: "idle" | "checking" | "up_to_date" } - // `close`: the user agreed to close the running applications, which open again afterwards. - | { status: "installing"; close: boolean } - | ({ status: "available"; saved: Saved | null } & Release) - | ({ status: "ready_to_install" } & Release) - // `total` is 0 until known. - | { status: "downloading"; received: number; total: number; reconnecting: boolean } - | { status: "installed"; version: string; notices: string[] } - | { status: "unsupported"; message: string } - | { status: "failed"; operation: Operation; message: string; confirmation: string | null }; -type Snapshot = Phase & { revision: number }; - -const megabytes = (bytes: number) => Math.floor(bytes / (1024 * 1024)).toLocaleString("ru-RU"); -const RUNNING_POLL_MS = 2000; - -/** Products that installation would close because they run now, polled while `active`. */ -function useRunningApps(desktop: DesktopApp, active: boolean) { - const [running, setRunning] = useState([]); - useEffect(() => { - setRunning([]); - if (!active) return; - let stopped = false; - let timer: ReturnType | undefined; - async function poll() { - try { - const next = await invoke("get_desktop_running_apps", { desktop }); - if (stopped) return; - setRunning((current) => current.join("\n") === next.join("\n") ? current : next); - } catch { - // Keep the last answer: installation checks again before it closes anything. - } - if (!stopped) timer = setTimeout(() => void poll(), RUNNING_POLL_MS); - } - void poll(); - return () => { - stopped = true; - clearTimeout(timer); - }; - }, [desktop, active]); - return running; -} - -export function useDesktopInstall(desktop: DesktopApp) { - const [state, setState] = useState(); - const [error, setError] = useState(); - useEffect(() => { - let stopped = false; - async function observe() { - let lastRevision: number | null = null; - while (!stopped) { +/** Archive cancellation is available only in the expanded installation panel. */ +export function CancelDownloadButton({ + desktop, + size = "md", + disabled = false, +}: { + desktop: DesktopApp; + size?: "sm" | "md"; + disabled?: boolean; +}) { + const controls = useInstallations(); + const requesting = Boolean(controls.requesting[desktop]); + const [cancelling, setCancelling] = useState(false); + return ( + + ); } -export function DesktopInstall({ observation, signedIn, disabled, installed }: { - observation: ReturnType; +/** A stable version column and action group, shared by both desktop agents. */ +export function DesktopVersion({ + desktop, + installed, + signedIn, + disabled, + version, + children, +}: { + desktop: DesktopApp; + installed: boolean; signedIn: boolean; disabled: boolean; - installed: boolean; + version: string | null; + children: ReactNode; }) { - const [error, setError] = useState(); - const [confirmed, setConfirmed] = useState(false); - const { desktop, state, busy } = observation; - const { name } = names[desktop]; - const confirmation = state?.status === "ready_to_install" || state?.status === "failed" ? state.confirmation : null; - // A confirmation applies only to the release it was given for. - useEffect(() => { - if (confirmation === null) setConfirmed(false); - }, [confirmation]); - const retryInstall = state?.status === "failed" && state.operation === "install"; - const installable = state?.status === "ready_to_install" || retryInstall; - const running = useRunningApps(desktop, installable && !busy); - if (!state) return observation.error ? {observation.error} : null; - if (state.status === "unsupported") return {state.message}; - - // Installation closes these and opens them again afterwards. - const closing = installable && running.length > 0 ? running.join(", ") : undefined; - const blocked = disabled || busy || observation.error !== undefined; - const networkBlocked = blocked || !signedIn; - const unconfirmed = confirmation !== null && !confirmed; - const progress = state.status === "downloading" && state.total > 0 - ? Math.min(100, Math.floor(state.received / state.total * 100)) : undefined; - - let operation: Operation = "check"; - let label = "Проверить обновления"; - switch (state.status) { - case "checking": - label = "Проверяем обновления…"; - break; - case "available": - operation = "download"; - label = state.saved - ? `Продолжить скачивание (${megabytes(state.saved.received)} из ${megabytes(state.saved.total)} МБ)` - : installed ? "Скачать обновление" : `Скачать ${name}`; - break; - case "ready_to_install": - operation = "install"; - label = closing ? `Закрыть ${closing} и установить` - : installed ? "Установить обновление" : `Установить ${name}`; - break; - case "installing": - operation = "install"; - label = state.close ? "Закрываем и устанавливаем…" : "Устанавливаем…"; - break; - case "failed": - operation = state.operation; - label = operation === "install" ? (closing ? `Закрыть ${closing} и повторить установку` : "Повторить установку") - : operation === "download" ? "Повторить скачивание" - : "Повторить проверку"; - break; - } - - async function request(operation: Operation) { - if (blocked || (operation !== "install" && !signedIn)) return; - if (operation === "install" && unconfirmed) return; - setError(undefined); - try { - if (operation === "install") { - await invoke("install_desktop_release", { - desktop, confirmed: confirmation !== null && confirmed, close: closing !== undefined, - }); - } else { - await invoke(operation === "check" ? "check_desktop_release" : "download_desktop_release", { desktop }); - } - } catch { - setError("Не удалось начать операцию. Проверьте её состояние и повторите попытку."); - } - } - - async function pause() { - setError(undefined); - try { - await invoke("pause_desktop_download", { desktop }); - } catch { - setError("Не удалось приостановить скачивание. Проверьте его состояние и повторите попытку."); - } - } - - const release = state.status === "available" || state.status === "ready_to_install" ? state : undefined; + const controls = useInstallations(); + const observation = controls.observations[desktop]; + const { state } = observation; + const displayedVersion = state?.status === "installed" ? state.version : version; + const previousVersion = useRef(displayedVersion); + const versionLabel = useRef(null); + useLayoutEffect(() => { + const previous = previousVersion.current; + previousVersion.current = displayedVersion; + if (!previous || !displayedVersion || previous === displayedVersion || + window.matchMedia("(prefers-reduced-motion: reduce)").matches || + document.documentElement.dataset.motion === "reduce") return; + const animation = versionLabel.current?.animate?.([ + { opacity: .25, transform: "translateY(6px)" }, + { opacity: 1, transform: "translateY(0)" }, + ], { duration: 280, easing: "ease-out" }); + return () => animation?.cancel(); + }, [displayedVersion]); + if (observation.hidden) return <>{children}; + if (!state) + return ( + <> + {children} + {observation.error} + + ); + const current = state.status === "up_to_date" || state.status === "installed"; + const checking = state.status === "idle" || state.status === "checking"; + const checkFailed = state.status === "failed" && state.operation === "check"; return ( -
- {!signedIn && Войдите в CoreInfra Hub, чтобы проверить обновления и скачать приложение.} -
- {state.status === "downloading" ? ( - <> - - - - - ) : ( - +
+
+ {displayedVersion ? `v${displayedVersion}` : children} +
+
+ {checking && signedIn && ( + + Проверяем версию… + )} - {!busy && operation !== "check" && ( - + {checkFailed && ( + + Не удалось проверить версию + )} + {!current && + !checkFailed && + (!checking || (!installed && !signedIn)) && ( + + )}
- {state.status === "downloading" && (state.reconnecting - ? Соединение прервано. Переподключаемся, скачанное сохранено… - : state.total > 0 && Скачано {megabytes(state.received)} из {megabytes(state.total)} МБ.)} - {state.status === "up_to_date" && Более новой доступной версии не найдено.} - {state.status === "available" && ( - Доступна версия {state.version}. - {state.path && <>
Путь установки: {state.path}.}
- )} - {state.status === "ready_to_install" && ( - Версия {state.version} скачана и готова к установке. - {state.path && <>
Путь установки: {state.path}.}
- )} - {release?.notes.map((note) => {note})} - {state.status === "available" && state.confirmation !== null && ( - {state.confirmation} — Wizard попросит подтвердить это перед установкой. - )} - {state.status === "ready_to_install" && state.path === null && ( - Система запросит права администратора для установки {name}. - )} - {confirmation !== null && (state.status === "ready_to_install" || retryInstall) && ( - - - - - )} - {closing && ( - Wizard закроет {closing} и откроет {running.length > 1 ? "их" : "его"} снова после установки. Текущие ответы и сессии будут прерваны. - )} - {state.status === "installing" && Не выходите из Wizard до завершения операции.} - {state.status === "installed" && ( - <> - Версия {state.version} установлена. - {state.notices.map((notice) => {notice})} - + {controls.errors[desktop] && ( +
+ {controls.errors[desktop]} +
)} - {state.status === "failed" && {state.message}} - {observation.error && {observation.error}} - {error && {error}}
); } diff --git a/crates/wizard-gui/wizard-ui/src/agents/MissingAgent.tsx b/crates/wizard-gui/wizard-ui/src/agents/MissingAgent.tsx new file mode 100644 index 0000000..0e7cfeb --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/agents/MissingAgent.tsx @@ -0,0 +1,45 @@ +import { useState } from "react"; +import { CheckIcon, ClipboardDocumentIcon, CommandLineIcon } from "@heroicons/react/20/solid"; +import { Button } from "../components/catalyst/button"; +import { Panel } from "../components/ui/Layout"; +import { EmptyState } from "../components/ui/StateNotice"; +import { ErrorText } from "../components/ErrorText"; + +const instructions = { + claude: { name: "Claude Code", command: "npm install -g @anthropic-ai/claude-code" }, + codex: { name: "Codex CLI", command: "npm install -g @openai/codex" }, + opencode: { name: "OpenCode", command: "npm install -g opencode-ai" }, + pi: { name: "Pi", command: "npm install -g @mariozechner/pi-coding-agent" }, +}; + +/** Give terminal agents an actionable empty state without running shell commands. */ +export function MissingAgent({ agent }: { agent: keyof typeof instructions }) { + const { name, command } = instructions[agent]; + const [copied, setCopied] = useState(false); + const [error, setError] = useState(); + async function copy() { + setError(undefined); + try { + await navigator.clipboard.writeText(command); + setCopied(true); + } catch { + setError("Не удалось скопировать. Выделите команду и скопируйте её вручную."); + } + } + return ( + + + Выполните команду в терминале с установленными Node.js и npm. + Wizard обнаружит агента автоматически. + +
+ {command} + +
+ {error &&
{error}
} +
+ ); +} diff --git a/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx b/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx index 2223936..39987be 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx @@ -1,20 +1,28 @@ import { useState } from "react"; -import { type AgentId, type PreparedAgentChange, applyAgentPlan, prepareAgentChange } from "./agents_state"; +import { + type PreparedAgentChange, + applyAgentPlan, + prepareAgentChange, +} from "./agents_state"; import { reportError } from "../logs/log"; import { ErrorText } from "../components/ErrorText"; import { Button } from "../components/catalyst/button"; -import { Dialog, DialogActions, DialogBody, DialogDescription, DialogTitle } from "../components/catalyst/dialog"; +import { + Dialog, + DialogActions, + DialogBody, +} from "../components/catalyst/dialog"; +import { DialogHeader } from "../components/ui/DialogHeader"; import { Text } from "../components/catalyst/text"; +import { agentPageNames } from "./navigation"; -const agentNames: Record = { - codex: "ChatGPT / Codex", - claude: "Claude Code", - pi: "Pi", - opencode: "OpenCode", - claude_desktop: "Claude Desktop", -}; - -export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied, applyLabel = "Завершить настройку" }: { +export function PreparedPlanDialog({ + prepared, + onReprepared, + onClose, + onApplied, + applyLabel = "Завершить настройку", +}: { prepared: PreparedAgentChange; onReprepared: (prepared: PreparedAgentChange) => void; onClose: () => void; @@ -34,14 +42,19 @@ export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied, setRepreparing(true); try { - const token = prepared.token === null ? null : { kind: "existing" as const, token: prepared.token }; + const token = + prepared.token === null + ? null + : { kind: "existing" as const, token: prepared.token }; const next = await prepareAgentChange(prepared.change, token); onReprepared(next); setError(undefined); } catch (cause: unknown) { const message = "Не удалось пересоздать план"; reportError(message, cause); - setError(`${message}: ${cause instanceof Error ? cause.message : String(cause)}. Показан прежний план. Часть изменений могла быть применена.`); + setError( + `${message}: ${cause instanceof Error ? cause.message : String(cause)}. Показан прежний план. Часть изменений могла быть применена.`, + ); } finally { setRepreparing(false); } @@ -60,22 +73,33 @@ export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied, } catch (cause: unknown) { const message = "Не удалось применить изменения"; reportError(message, cause); - setError(`${message}: ${cause instanceof Error ? cause.message : String(cause)}. Часть изменений могла быть применена.`); + setError( + `${message}: ${cause instanceof Error ? cause.message : String(cause)}. Часть изменений могла быть применена.`, + ); } finally { setApplying(false); } } return ( - { if (!busy) onClose(); }}> - План изменений: {agentNames[agent]} - {hasChanges && ( - - {prepared.restarts_desktop - ? "Завершите текущую работу. Wizard закроет приложение, если оно запущено, применит настройки и откроет его." - : "Завершите текущую работу и закройте агента перед применением. Wizard выполнит следующие действия."} - - )} + { + if (!busy) onClose(); + }} + > + {hasChanges ? (
    @@ -88,18 +112,33 @@ export function PreparedPlanDialog({ prepared, onReprepared, onClose, onApplied, ) : ( Изменения не требуются. )} - {error &&
    {error}
    } + {error && ( +
    + {error} +
    + )} - - {error && } - {hasChanges && } + {error && ( + + )} + {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 a949a7f..9c75c13 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/agents_state.ts @@ -119,6 +119,13 @@ export type AgentStates = { pi: AgentDetection; }; +// Codex can be found through its CLI while desktop detection fails, or vice versa. +export function hasAgentDetectionError(detection: AgentStates[AgentId]) { + return detection.status === "error" || + (detection.status === "found" && "desktop" in detection.data && + (detection.data.desktop.status === "error" || detection.data.cli.status === "error")); +} + type DetectionState = | { status: "loading" } | { status: "ready"; data: AgentStateSnapshot } diff --git a/crates/wizard-gui/wizard-ui/src/agents/desktop_install_state.ts b/crates/wizard-gui/wizard-ui/src/agents/desktop_install_state.ts new file mode 100644 index 0000000..6ebcade --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/agents/desktop_install_state.ts @@ -0,0 +1,97 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useEffect, useState } from "react"; + +// Keep in sync with `DesktopApp` in `crates/wizard-core/src/agents/desktop_install/mod.rs`. +export type DesktopApp = "claude" | "chatgpt"; + +const names: Record = { + claude: { name: "Claude" }, + chatgpt: { name: "ChatGPT" }, +}; + +export type Operation = "check" | "download" | "install"; +type Release = { version: string; path: string | null; notes: string[]; confirmation: string | null }; +/** Bytes retained after a network interruption; explicit cancellation discards them. */ +type Saved = { received: number; total: number }; +export type Phase = + | { status: "idle" | "checking" | "up_to_date" } + // `close`: the user agreed to close the running applications, which open again afterwards. + | { status: "installing"; close: boolean } + | ({ status: "available"; saved: Saved | null } & Release) + | ({ status: "ready_to_install" } & Release) + // `total` is 0 until known. + | { status: "downloading"; received: number; total: number; reconnecting: boolean } + | { status: "installed"; version: string; notices: string[] } + | { status: "unsupported"; message: string } + | { status: "failed"; operation: Operation; message: string; confirmation: string | null }; +export type Snapshot = Phase & { revision: number }; + +export const megabytes = (bytes: number) => Math.floor(bytes / (1024 * 1024)).toLocaleString("ru-RU"); +const RUNNING_POLL_MS = 2000; + +/** Products that installation would close because they run now, polled while `active`. */ +export function useRunningApps(desktop: DesktopApp, active: boolean) { + const [running, setRunning] = useState([]); + const [checked, setChecked] = useState(false); + const [error, setError] = useState(); + useEffect(() => { + setRunning([]); + setChecked(false); + setError(undefined); + if (!active) return; + let stopped = false; + let timer: ReturnType | undefined; + async function poll() { + try { + const next = await invoke("get_desktop_running_apps", { desktop }); + if (stopped) return; + setRunning((current) => current.join("\n") === next.join("\n") ? current : next); + setChecked(true); + setError(undefined); + } catch { + if (stopped) return; + setChecked(false); + setError("Не удалось проверить запущенные приложения. Повторяем проверку…"); + } + if (!stopped) timer = setTimeout(() => void poll(), RUNNING_POLL_MS); + } + void poll(); + return () => { + stopped = true; + clearTimeout(timer); + }; + }, [desktop, active]); + return { running, checked, error }; +} + +export function useDesktopInstall(desktop: DesktopApp) { + const [state, setState] = useState(); + const [error, setError] = useState(); + useEffect(() => { + let stopped = false; + async function observe() { + let lastRevision: number | null = null; + while (!stopped) { + try { + const next: Snapshot = await invoke("get_desktop_install_state", { desktop, lastRevision }); + if (stopped) return; + setState(next); + setError(undefined); + lastRevision = next.revision; + } catch { + if (stopped) return; + setError(`Не удалось получить состояние установки ${names[desktop].name}`); + lastRevision = null; + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + } + void observe(); + return () => { stopped = true; }; + }, [desktop]); + + const busy = state?.status === "checking" || state?.status === "downloading" || state?.status === "installing"; + // Hidden until the state loads, so that an unsupported application never flashes. + const hidden = state === undefined ? error === undefined : state.status === "unsupported"; + return { desktop, state, error, busy, hidden }; +} diff --git a/crates/wizard-gui/wizard-ui/src/agents/navigation.ts b/crates/wizard-gui/wizard-ui/src/agents/navigation.ts index 282d0e2..d7d5a27 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/navigation.ts +++ b/crates/wizard-gui/wizard-ui/src/agents/navigation.ts @@ -4,6 +4,13 @@ export type AgentPageId = AgentId; export type AppPageId = AgentPageId | "overview" | "settings"; export const overviewPath = "/overview"; export const settingsPath = "/settings"; +export const agentPageNames: Record = { + claude_desktop: "Claude Desktop", + claude: "Claude Code", + codex: "ChatGPT / Codex", + opencode: "OpenCode", + pi: "Pi", +}; export const agentPaths: Record = { claude_desktop: "/agents/claude-desktop", @@ -16,6 +23,9 @@ export const agentPaths: Record = { export function pageFromHash(hash: string): AppPageId { const path = hash.replace(/^#/, "").replace(/\/+$/, ""); if (path === settingsPath) return "settings"; - return (Object.keys(agentPaths) as AgentPageId[]) - .find((page) => agentPaths[page] === path) ?? "overview"; + return ( + (Object.keys(agentPaths) as AgentPageId[]).find( + (page) => agentPaths[page] === path, + ) ?? "overview" + ); } diff --git a/crates/wizard-gui/wizard-ui/src/components/AppLogo.tsx b/crates/wizard-gui/wizard-ui/src/components/AppLogo.tsx index f621c68..8bc7672 100644 --- a/crates/wizard-gui/wizard-ui/src/components/AppLogo.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/AppLogo.tsx @@ -1,12 +1,12 @@ import clsx from "clsx"; import wizardLogo from "../assets/logo-wizard.svg"; -export function AppLogo({ className }: { className?: string }) { +export function AppLogo({ className, markOnly = false }: { className?: string; markOnly?: boolean }) { return (
-
+
{children} @@ -67,7 +67,7 @@ export function AlertTitle({ {...props} className={clsx( className, - "text-center text-base/6 font-normal text-balance text-zinc-950 sm:text-left sm:text-sm/6 sm:text-wrap dark:text-white", + "text-left text-base/6 font-semibold text-balance text-zinc-950 dark:text-white", )} /> ); @@ -84,7 +84,7 @@ export function AlertDescription({ ); } @@ -105,7 +105,7 @@ export function AlertActions({ {...props} className={clsx( className, - "mt-6 flex flex-col-reverse items-center justify-end gap-3 *:w-full sm:mt-4 sm:flex-row sm:*:w-auto", + "mt-6 flex flex-wrap items-center justify-end gap-3", )} /> ); diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/badge.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/badge.tsx index 492d610..9e83d4a 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/badge.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/badge.tsx @@ -19,7 +19,7 @@ const colors = { "bg-yellow-400/20 text-yellow-700 group-data-hover:bg-yellow-400/30 dark:bg-yellow-400/10 dark:text-yellow-300 dark:group-data-hover:bg-yellow-400/15", lime: "bg-lime-400/20 text-lime-700 group-data-hover:bg-lime-400/30 dark:bg-lime-400/10 dark:text-lime-300 dark:group-data-hover:bg-lime-400/15", green: - "bg-green-500/15 text-green-700 group-data-hover:bg-green-500/25 dark:bg-green-500/10 dark:text-green-400 dark:group-data-hover:bg-green-500/20", + "bg-green-500/15 text-green-800 group-data-hover:bg-green-500/25 dark:bg-green-500/10 dark:text-green-400 dark:group-data-hover:bg-green-500/20", emerald: "bg-emerald-500/15 text-emerald-700 group-data-hover:bg-emerald-500/25 dark:bg-emerald-500/10 dark:text-emerald-400 dark:group-data-hover:bg-emerald-500/20", teal: "bg-teal-500/15 text-teal-700 group-data-hover:bg-teal-500/25 dark:bg-teal-500/10 dark:text-teal-300 dark:group-data-hover:bg-teal-500/20", diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/button.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/button.tsx index f631445..60d20f2 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/button.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/button.tsx @@ -11,9 +11,8 @@ import { Link } from "./link.js"; const styles = { base: [ // Base - "relative isolate inline-flex items-baseline justify-center gap-x-2 rounded-lg border text-base/6 font-semibold", + "relative isolate inline-flex items-center justify-center gap-x-2 rounded-lg border text-sm/6 font-semibold transition-colors duration-150 motion-reduce:transition-none", // Sizing - "px-[calc(--spacing(3.5)-1px)] py-[calc(--spacing(2.5)-1px)] sm:px-[calc(--spacing(3)-1px)] sm:py-[calc(--spacing(1.5)-1px)] sm:text-sm/6", // Focus "focus:not-data-focus:outline-hidden data-focus:outline-2 data-focus:outline-offset-2 data-focus:outline-blue-500", // Disabled @@ -167,7 +166,7 @@ type ButtonProps = ( | { color?: keyof typeof styles.colors; outline?: never; plain?: never } | { color?: never; outline: true; plain?: never } | { color?: never; outline?: never; plain: true } -) & { className?: string; children: React.ReactNode } & ( +) & { className?: string; children: React.ReactNode; size?: "sm" | "md" | "lg" } & ( | ({ href?: never } & Omit) | ({ href: string } & Omit< React.ComponentPropsWithoutRef, @@ -176,12 +175,13 @@ type ButtonProps = ( ); export const Button = forwardRef(function Button( - { color, outline, plain, className, children, ...props }: ButtonProps, + { color, outline, plain, className, children, size = "md", ...props }: ButtonProps, ref: React.ForwardedRef, ) { let classes = clsx( className, styles.base, + size === "sm" ? "min-h-8 px-2.5 py-0.5" : size === "lg" ? "min-h-11 px-4 py-2" : "min-h-10 px-3 py-1.5 sm:min-h-9 sm:py-1", outline ? styles.outline : plain diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/combobox.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/combobox.tsx index e5e0077..b28acd3 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/combobox.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/combobox.tsx @@ -61,7 +61,7 @@ export function Combobox({ // Background color is moved to control and shadow is removed in dark mode so hide `before` pseudo "dark:before:hidden", // Focus ring - "after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset sm:focus-within:after:ring-2 sm:focus-within:after:ring-blue-500", + "after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset focus-within:after:ring-2 focus-within:after:ring-blue-500", // Disabled state "has-data-disabled:opacity-50 has-data-disabled:before:bg-zinc-950/5 has-data-disabled:before:shadow-none", // Invalid state @@ -82,7 +82,7 @@ export function Combobox({ // Horizontal padding "pr-[calc(--spacing(10)-1px)] pl-[calc(--spacing(3.5)-1px)] sm:pr-[calc(--spacing(9)-1px)] sm:pl-[calc(--spacing(3)-1px)]", // Typography - "text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white", + "text-base/6 text-zinc-950 placeholder:text-zinc-500 dark:placeholder:text-zinc-400 sm:text-sm/6 dark:text-white", // Border "border border-zinc-950/10 data-hover:border-zinc-950/20 dark:border-white/10 dark:data-hover:border-white/20", // Background color @@ -97,7 +97,7 @@ export function Combobox({ "dark:scheme-dark", ])} /> - + ({ // Basic layout "group/option grid w-full cursor-default grid-cols-[1fr_--spacing(5)] items-baseline gap-x-2 rounded-lg py-2.5 pr-2 pl-3.5 sm:grid-cols-[1fr_--spacing(4)] sm:py-1.5 sm:pr-2 sm:pl-3", // Typography - "text-base/6 text-zinc-950 sm:text-sm/6 dark:text-white forced-colors:text-[CanvasText]", + "text-sm/6 text-zinc-950 dark:text-white forced-colors:text-[CanvasText]", // Focus - "outline-hidden data-focus:bg-blue-500 data-focus:text-white", + "outline-hidden data-focus:bg-blue-600 data-focus:text-white", // Forced colors mode "forced-color-adjust-none forced-colors:data-focus:bg-[Highlight] forced-colors:data-focus:text-[HighlightText]", // Disabled diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/description-list.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/description-list.tsx index 2d5be59..9ed071f 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/description-list.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/description-list.tsx @@ -13,7 +13,7 @@ export function DescriptionList({ {...props} className={clsx( className, - "grid grid-cols-1 text-base/6 sm:grid-cols-[min(50%,--spacing(80))_auto] sm:text-sm/6", + "grid grid-cols-1 text-sm/6 sm:grid-cols-[min(50%,--spacing(80))_auto]", )} /> ); diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/dialog.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/dialog.tsx index d492358..b12ffce 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/dialog.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/dialog.tsx @@ -43,8 +43,8 @@ export function Dialog({ className={clsx( className, sizes[size], - "row-start-2 w-full min-w-0 rounded-t-3xl bg-white p-(--gutter) shadow-lg ring-1 ring-zinc-950/10 [--gutter:--spacing(8)] sm:mb-auto sm:rounded-2xl dark:bg-zinc-900 dark:ring-white/10 forced-colors:outline", - "transition duration-100 will-change-transform data-closed:translate-y-12 data-closed:opacity-0 data-enter:ease-out data-leave:ease-in sm:data-closed:translate-y-0 sm:data-closed:data-enter:scale-95", + "row-start-2 w-full min-w-0 rounded-t-2xl bg-white p-(--gutter) shadow-lg ring-1 ring-zinc-950/10 [--gutter:var(--ui-panel-gutter)] sm:mb-auto sm:rounded-2xl dark:bg-zinc-900 dark:ring-white/10 forced-colors:outline", + "transition duration-150 motion-reduce:transition-none will-change-transform data-closed:translate-y-4 data-closed:opacity-0 data-enter:ease-out data-leave:ease-in sm:data-closed:translate-y-0 sm:data-closed:data-enter:scale-[.98] motion-reduce:data-closed:transform-none", )} > {children} @@ -67,7 +67,7 @@ export function DialogTitle({ {...props} className={clsx( className, - "text-lg/6 font-normal text-balance text-zinc-950 sm:text-base/6 dark:text-white", + "text-base/6 font-semibold text-balance text-zinc-950 dark:text-white focus:outline-none", )} /> ); @@ -105,7 +105,7 @@ export function DialogActions({ {...props} className={clsx( className, - "mt-8 flex flex-col-reverse items-center justify-end gap-3 *:w-full sm:flex-row sm:*:w-auto", + "mt-6 flex flex-wrap items-center justify-end gap-3", )} /> ); diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/dropdown.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/dropdown.tsx index 0904e11..cde349c 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/dropdown.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/dropdown.tsx @@ -71,9 +71,9 @@ export function DropdownItem({ // Base styles "group cursor-default rounded-lg px-3.5 py-2.5 focus:outline-hidden sm:px-3 sm:py-1.5", // Text styles - "text-left text-base/6 text-zinc-950 sm:text-sm/6 dark:text-white forced-colors:text-[CanvasText]", + "text-left text-sm/6 text-zinc-950 dark:text-white forced-colors:text-[CanvasText]", // Focus - "data-focus:bg-blue-500 data-focus:text-white", + "data-focus:bg-blue-600 data-focus:text-white", // Disabled state "data-disabled:opacity-50", // Forced colors mode diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/fieldset.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/fieldset.tsx index 2637995..ee83296 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/fieldset.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/fieldset.tsx @@ -31,7 +31,7 @@ export function Legend({ {...props} className={clsx( className, - "text-base/6 font-normal text-zinc-950 data-disabled:opacity-50 sm:text-sm/6 dark:text-white", + "text-sm/6 font-normal text-zinc-950 data-disabled:opacity-50 dark:text-white", )} /> ); @@ -45,7 +45,7 @@ export function FieldGroup({
); } @@ -80,7 +80,7 @@ export function Label({ {...props} className={clsx( className, - "text-base/6 text-zinc-950 select-none data-disabled:opacity-50 sm:text-sm/6 dark:text-white", + "text-sm/6 text-zinc-950 select-none data-disabled:opacity-50 dark:text-white", )} /> ); @@ -99,7 +99,7 @@ export function Description({ {...props} className={clsx( className, - "text-base/6 text-zinc-500 data-disabled:opacity-50 sm:text-sm/6 dark:text-zinc-400", + "text-sm/6 text-zinc-500 data-disabled:opacity-50 dark:text-zinc-400", )} /> ); @@ -118,7 +118,7 @@ export function ErrorMessage({ {...props} className={clsx( className, - "text-base/6 text-red-600 data-disabled:opacity-50 sm:text-sm/6 dark:text-red-500", + "text-sm/6 text-red-600 data-disabled:opacity-50 dark:text-red-500", )} /> ); diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/heading.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/heading.tsx index 30f240b..f4379ba 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/heading.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/heading.tsx @@ -16,7 +16,8 @@ export function Heading({ className, level = 1, ...props }: HeadingProps) { {...props} className={clsx( className, - "text-2xl/8 font-normal text-zinc-950 sm:text-xl/8 dark:text-white", + "font-semibold text-zinc-950 dark:text-white", + level === 1 ? "text-[22px]/8 tracking-tight" : level === 2 ? "text-base/6" : "text-sm/6", )} /> ); @@ -30,7 +31,7 @@ export function Subheading({ className, level = 2, ...props }: HeadingProps) { {...props} className={clsx( className, - "text-base/7 font-normal text-zinc-950 sm:text-sm/6 dark:text-white", + "text-sm/6 font-semibold text-zinc-950 dark:text-white", )} /> ); diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/input.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/input.tsx index 4ed8a84..4103f6b 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/input.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/input.tsx @@ -59,7 +59,7 @@ export const Input = forwardRef(function Input( // Background color is moved to control and shadow is removed in dark mode so hide `before` pseudo "dark:before:hidden", // Focus ring - "after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset sm:focus-within:after:ring-2 sm:focus-within:after:ring-blue-500", + "after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset focus-within:after:ring-2 focus-within:after:ring-blue-500", // Disabled state "has-data-disabled:opacity-50 has-data-disabled:before:bg-zinc-950/5 has-data-disabled:before:shadow-none", ])} @@ -87,7 +87,7 @@ export const Input = forwardRef(function Input( // Basic layout "relative block w-full appearance-none rounded-lg px-[calc(--spacing(3.5)-1px)] py-[calc(--spacing(2.5)-1px)] sm:px-[calc(--spacing(3)-1px)] sm:py-[calc(--spacing(1.5)-1px)]", // Typography - "text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white", + "text-base/6 text-zinc-950 placeholder:text-zinc-500 dark:placeholder:text-zinc-400 sm:text-sm/6 dark:text-white", // Border "border border-zinc-950/10 data-hover:border-zinc-950/20 dark:border-white/10 dark:data-hover:border-white/20", // Background color diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/listbox.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/listbox.tsx index e2391d9..19adda0 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/listbox.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/listbox.tsx @@ -63,7 +63,7 @@ export function Listbox({ // Horizontal padding "pr-[calc(--spacing(7)-1px)] pl-[calc(--spacing(3.5)-1px)] sm:pl-[calc(--spacing(3)-1px)]", // Typography - "text-left text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white forced-colors:text-[CanvasText]", + "text-left text-sm/6 text-zinc-950 placeholder:text-zinc-500 dark:placeholder:text-zinc-400 dark:text-white forced-colors:text-[CanvasText]", // Border "border border-zinc-950/10 group-data-active:border-zinc-950/20 group-data-hover:border-zinc-950/20 dark:border-white/10 dark:group-data-active:border-white/20 dark:group-data-hover:border-white/20", // Background color @@ -156,9 +156,9 @@ export function ListboxOption({ // Basic layout "group/option grid cursor-default grid-cols-[--spacing(5)_1fr] items-baseline gap-x-2 rounded-lg py-2.5 pr-3.5 pl-2 sm:grid-cols-[--spacing(4)_1fr] sm:py-1.5 sm:pr-3 sm:pl-1.5", // Typography - "text-base/6 text-zinc-950 sm:text-sm/6 dark:text-white forced-colors:text-[CanvasText]", + "text-sm/6 text-zinc-950 dark:text-white forced-colors:text-[CanvasText]", // Focus - "outline-hidden data-focus:bg-blue-500 data-focus:text-white", + "outline-hidden data-focus:bg-blue-600 data-focus:text-white", // Forced colors mode "forced-color-adjust-none forced-colors:data-focus:bg-[Highlight] forced-colors:data-focus:text-[HighlightText]", // Disabled diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/radio.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/radio.tsx index c3dab10..5509c12 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/radio.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/radio.tsx @@ -64,8 +64,8 @@ const base = [ // Background color applied to control in dark mode "dark:bg-white/5 dark:group-data-checked:bg-(--radio-checked-bg)", // Border - "border border-zinc-950/15 group-data-checked:border-transparent group-data-hover:group-data-checked:border-transparent group-data-hover:border-zinc-950/30 group-data-checked:bg-(--radio-checked-border)", - "dark:border-white/15 dark:group-data-checked:border-white/5 dark:group-data-hover:group-data-checked:border-white/5 dark:group-data-hover:border-white/30", + "border border-zinc-500/80 group-data-checked:border-transparent group-data-hover:group-data-checked:border-transparent group-data-hover:border-zinc-700 group-data-checked:bg-(--radio-checked-border)", + "dark:border-zinc-400/75 dark:group-data-checked:border-white/5 dark:group-data-hover:group-data-checked:border-white/5 dark:group-data-hover:border-zinc-300", // Inner highlight shadow "after:absolute after:inset-0 after:rounded-full after:shadow-[inset_0_1px_--theme(--color-white/15%)]", "dark:after:-inset-px dark:after:hidden dark:after:rounded-full dark:group-data-checked:after:block", diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/select.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/select.tsx index 4a986c9..7cd760d 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/select.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/select.tsx @@ -46,7 +46,7 @@ export const Select = forwardRef(function Select( // Options (multi-select) "[&_optgroup]:font-semibold", // Typography - "text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white dark:*:text-white", + "text-base/6 text-zinc-950 placeholder:text-zinc-500 dark:placeholder:text-zinc-400 sm:text-sm/6 dark:text-white dark:*:text-white", // Border "border border-zinc-950/10 data-hover:border-zinc-950/20 dark:border-white/10 dark:data-hover:border-white/20", // Background color diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/sidebar-layout.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/sidebar-layout.tsx index c9b8f3c..a8f7abf 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/sidebar-layout.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/sidebar-layout.tsx @@ -6,10 +6,19 @@ import * as Headless from "@headlessui/react"; import clsx from "clsx"; -import { useState } from "react"; +import { createContext, useContext, useEffect, useRef, useState } from "react"; import type * as React from "react"; import { NavbarItem } from "./navbar.js"; +const SidebarActionContext = createContext<(action: () => void) => void>( + (action) => action(), +); + +/** Open overlays only after mobile navigation has released its focus trap. */ +export function useSidebarAction() { + return useContext(SidebarActionContext); +} + function OpenMenuIcon() { return (
-
- - - + + +
+
+ + + +
+ {children}
- {children} -
- - + + + ); } @@ -69,6 +89,27 @@ export function SidebarLayout({ hideNavigation?: boolean; }>) { let [showSidebar, setShowSidebar] = useState(false); + const pendingAction = useRef<(() => void) | undefined>(undefined); + const actionFrame = useRef(undefined); + useEffect( + () => () => { + if (actionFrame.current !== undefined) + cancelAnimationFrame(actionFrame.current); + }, + [], + ); + + function runAfterClose(action: () => void) { + pendingAction.current = action; + setShowSidebar(false); + } + + function finishClosing() { + const action = pendingAction.current; + pendingAction.current = undefined; + // Let the previous dialog unmount and restore focus before mounting another. + if (action) actionFrame.current = requestAnimationFrame(action); + } return (
{/* Sidebar on desktop */} - {!hideNavigation &&
{sidebar}
} + {!hideNavigation && ( +
+ {sidebar} +
+ )} {/* Sidebar on mobile */} - {!hideNavigation && setShowSidebar(false)}> - {sidebar} - } + {!hideNavigation && ( + setShowSidebar(false)} + afterLeave={finishClosing} + > + + {sidebar} + + + )} {/* Navbar on mobile */} - {!hideNavigation &&
-
- setShowSidebar(true)} - aria-label="Открыть меню" - > - - -
-
{navbar}
-
} + {!hideNavigation && ( +
+
+ setShowSidebar(true)} + aria-label="Открыть меню" + > + + +
+
{navbar}
+
+ )} {/* Content */}
- {fill ? ( - children - ) : ( -
{children}
- )} + {fill ? children :
{children}
}
diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/text.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/text.tsx index 3381155..9286370 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/text.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/text.tsx @@ -15,7 +15,7 @@ export function Text({ {...props} className={clsx( className, - "text-base/6 text-zinc-500 sm:text-sm/6 dark:text-zinc-400", + "text-sm/6 text-zinc-500 dark:text-zinc-400", )} /> ); diff --git a/crates/wizard-gui/wizard-ui/src/components/catalyst/textarea.tsx b/crates/wizard-gui/wizard-ui/src/components/catalyst/textarea.tsx index 1ca6703..d90c9ed 100644 --- a/crates/wizard-gui/wizard-ui/src/components/catalyst/textarea.tsx +++ b/crates/wizard-gui/wizard-ui/src/components/catalyst/textarea.tsx @@ -30,7 +30,7 @@ export const Textarea = forwardRef(function Textarea( // Background color is moved to control and shadow is removed in dark mode so hide `before` pseudo "dark:before:hidden", // Focus ring - "after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset sm:focus-within:after:ring-2 sm:focus-within:after:ring-blue-500", + "after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset focus-within:after:ring-2 focus-within:after:ring-blue-500", // Disabled state "has-data-disabled:opacity-50 has-data-disabled:before:bg-zinc-950/5 has-data-disabled:before:shadow-none", ])} @@ -42,7 +42,7 @@ export const Textarea = forwardRef(function Textarea( // Basic layout "relative block h-full w-full appearance-none rounded-lg px-[calc(--spacing(3.5)-1px)] py-[calc(--spacing(2.5)-1px)] sm:px-[calc(--spacing(3)-1px)] sm:py-[calc(--spacing(1.5)-1px)]", // Typography - "text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white", + "text-base/6 text-zinc-950 placeholder:text-zinc-500 dark:placeholder:text-zinc-400 sm:text-sm/6 dark:text-white", // Border "border border-zinc-950/10 data-hover:border-zinc-950/20 dark:border-white/10 dark:data-hover:border-white/20", // Background color diff --git a/crates/wizard-gui/wizard-ui/src/components/ui/DialogHeader.tsx b/crates/wizard-gui/wizard-ui/src/components/ui/DialogHeader.tsx new file mode 100644 index 0000000..d95371c --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/components/ui/DialogHeader.tsx @@ -0,0 +1,40 @@ +import type { ReactNode } from "react"; +import { XMarkIcon } from "@heroicons/react/20/solid"; +import { Button } from "../catalyst/button"; +import { DialogDescription, DialogTitle } from "../catalyst/dialog"; + +export function DialogHeader({ + title, + description, + onClose, + closeLabel = "Закрыть", + disabled = false, +}: { + title: ReactNode; + description?: ReactNode; + onClose?: () => void; + closeLabel?: string; + disabled?: boolean; +}) { + return ( +
+
+ {title} + {description && {description}} +
+ {onClose && ( + + )} +
+ ); +} diff --git a/crates/wizard-gui/wizard-ui/src/components/ui/Identity.tsx b/crates/wizard-gui/wizard-ui/src/components/ui/Identity.tsx new file mode 100644 index 0000000..345f6cd --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/components/ui/Identity.tsx @@ -0,0 +1,29 @@ +import type { ReactNode } from "react"; +import { Heading } from "../catalyst/heading"; +import { Text } from "../catalyst/text"; + +export function Identity({ + icon, + title, + description, + focusable = false, +}: { + icon: ReactNode; + title: string; + description?: ReactNode; + focusable?: boolean; +}) { + return ( +
+ +
+ + {title} + + {description && {description}} +
+
+ ); +} diff --git a/crates/wizard-gui/wizard-ui/src/components/ui/Layout.tsx b/crates/wizard-gui/wizard-ui/src/components/ui/Layout.tsx new file mode 100644 index 0000000..6c53044 --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/components/ui/Layout.tsx @@ -0,0 +1,100 @@ +import { useId, type ComponentPropsWithoutRef, type ReactNode } from "react"; +import clsx from "clsx"; +import { Heading } from "../catalyst/heading"; +import { Text } from "../catalyst/text"; + +export function PageHeader({ + title, + description, + actions, +}: { + title: string; + description?: ReactNode; + actions?: ReactNode; +}) { + return ( +
+
+ {title} + {description && {description}} +
+ {actions &&
{actions}
} +
+ ); +} + +export function Panel({ + title, + description, + tone = "default", + framed = true, + children, + className, + ...props +}: { + title?: string; + description?: ReactNode; + tone?: "default" | "muted"; + framed?: boolean; +} & Omit, "title">) { + const id = useId(); + return ( +
+ {title && ( +
+ + {title} + + {description && {description}} +
+ )} + {children} +
+ ); +} + +export function ActionBar({ + children, + leading, + divider = false, + className, +}: { + children: ReactNode; + leading?: ReactNode; + divider?: boolean; + className?: string; +}) { + return ( +
+ {leading &&
{leading}
} +
{children}
+
+ ); +} + +/** Key only presentation; ongoing operations belong to their page/provider. */ +export function ViewTransition({ + children, + view, + className, +}: { + children: ReactNode; + view: string; + className?: string; +}) { + return ( +
+ {children} +
+ ); +} diff --git a/crates/wizard-gui/wizard-ui/src/components/ui/StateNotice.tsx b/crates/wizard-gui/wizard-ui/src/components/ui/StateNotice.tsx new file mode 100644 index 0000000..bb7921d --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/components/ui/StateNotice.tsx @@ -0,0 +1,67 @@ +import type { ComponentType, ReactNode, SVGProps } from "react"; +import { + ArrowPathIcon, + CheckCircleIcon, + ExclamationCircleIcon, + InformationCircleIcon, +} from "@heroicons/react/20/solid"; +import { Heading } from "../catalyst/heading"; +import { Text } from "../catalyst/text"; + +export function StateNotice({ + tone = "info", + children, + actions, +}: { + tone?: "info" | "loading" | "error" | "warning" | "success"; + children: ReactNode; + actions?: ReactNode; +}) { + const Icon = + tone === "loading" + ? ArrowPathIcon + : tone === "success" + ? CheckCircleIcon + : tone === "error" || tone === "warning" + ? ExclamationCircleIcon + : InformationCircleIcon; + return ( +
+
+ ); +} + +export function EmptyState({ + title, + headingLevel = 3, + children, + icon: Icon, + action, +}: { + title: string; + headingLevel?: 2 | 3; + children?: ReactNode; + icon?: ComponentType>; + action?: ReactNode; +}) { + return ( +
+ {Icon &&
+ ); +} diff --git a/crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.css b/crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.css new file mode 100644 index 0000000..0f3012b --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.css @@ -0,0 +1,211 @@ +.ui-transfer { + --transfer-brand: var(--brand-claude); + position: relative; + isolation: isolate; + display: flex; + flex: 1; + min-width: 0; + overflow: hidden; + border: 1px solid var(--ui-border); + border-radius: var(--ui-radius-panel); + background: var(--ui-surface-muted); + color: var(--ui-ink); + text-align: left; +} +.ui-transfer[data-brand="chatgpt"] { + --transfer-brand: var(--brand-openai); +} +.ui-transfer[data-brand="wizard"] { --transfer-brand: var(--brand-coreinfra); } +.ui-transfer[data-openable="true"] { + cursor: pointer; +} +.ui-transfer[data-openable="true"]:hover { + border-color: var(--ui-border-strong); +} +.ui-transfer[data-openable="true"]:active { + background: var(--ui-surface-hover); + border-color: var(--ui-border-strong); +} +.ui-transfer:focus-visible { + outline: 2px solid var(--ui-focus); + outline-offset: 2px; +} +.ui-transfer-fill { + position: absolute; + inset: 0 auto 0 0; + z-index: -1; + background: var(--ui-progress); + transition: width 600ms linear; + pointer-events: none; +} +.ui-transfer-body { + display: flex; + flex: 1; + min-width: 0; + min-height: 196px; + flex-direction: column; + gap: var(--ui-space-6); + padding: var(--ui-panel-gutter); +} +.ui-transfer-header { + position: relative; + display: flex; + min-width: 0; + align-items: flex-start; + gap: var(--ui-space-4); +} +.ui-transfer-content { + display: grid; + gap: var(--ui-space-3); +} +.ui-transfer-error { + color: var(--ui-danger); + font-size: 14px; + line-height: 24px; + overflow-wrap: anywhere; +} +.ui-transfer-copy { + flex: 1; + min-width: 0; + padding-right: 68px; +} +.ui-transfer-logo { + position: absolute; + right: 0; + top: var(--ui-space-2); + display: grid; + place-items: center; + width: 52px; + height: 52px; + color: var(--ui-ink-subtle); + transition: + transform var(--ui-duration), + color var(--ui-duration); +} +.ui-transfer-logo > svg { + width: 48px; + height: 48px; + color: inherit; +} +.ui-transfer-title { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: var(--ui-space-2); + font-size: 14px; + line-height: 24px; + font-weight: 600; +} +.ui-transfer-title > :first-child { + overflow-wrap: anywhere; +} +.ui-transfer-version, +.ui-transfer-status, +.ui-transfer-detail, +.ui-transfer-notice { + display: block; + margin-top: var(--ui-space-1); + font-size: 14px; + line-height: 24px; + color: var(--ui-ink-muted); + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; +} +.ui-transfer-notice { + color: var(--ui-warning); +} +.ui-transfer-actions { + margin-top: auto; +} +.ui-transfer-actions :is(button, a) { + max-width: 100%; +} +.ui-transfer-action-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--ui-space-2); +} +.ui-transfer[data-active="true"] .ui-transfer-logo { + color: var(--transfer-brand); +} +.ui-transfer[data-tone="success"] .ui-transfer-title > svg { + color: var(--ui-success); +} +.ui-transfer[data-tone="error"] .ui-transfer-title > svg { + color: var(--ui-danger); +} +.ui-transfer[data-variant="compact"] { + width: 100%; + flex: none; + border-radius: 10px; + background: var(--ui-surface); +} +.ui-transfer[data-variant="compact"] .ui-transfer-body { + min-height: 64px; + padding: 10px 12px; +} +.ui-transfer[data-variant="compact"] .ui-transfer-header { + gap: 10px; + align-items: center; +} +.ui-transfer[data-variant="compact"] .ui-transfer-logo { + position: static; + width: 24px; + height: 24px; + flex: none; + color: var(--transfer-brand); +} +.ui-transfer[data-variant="compact"] .ui-transfer-logo > svg { + width: 24px; + height: 24px; +} +.ui-transfer[data-variant="compact"] .ui-transfer-copy { + padding: 0; +} +.ui-transfer[data-variant="compact"] .ui-transfer-title { + font-size: 12px; + line-height: 20px; +} +.ui-transfer[data-variant="compact"] .ui-transfer-title > span:first-child { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ui-transfer[data-variant="compact"] .ui-transfer-title > svg { + flex: none; + width: 14px; + height: 14px; +} +.ui-transfer-percent { + flex: none; + font-size: 12px; + font-weight: 500; + color: var(--ui-ink-muted); + font-variant-numeric: tabular-nums; +} +.ui-transfer[data-variant="compact"] + :is(.ui-transfer-status, .ui-transfer-detail, .ui-transfer-notice) { + margin-top: 2px; + font-size: 12px; + line-height: 16px; +} +.onboarding-install-grid[data-focused="true"] .ui-transfer-body { + min-height: 0; +} +@media (hover: hover) { + .ui-transfer[data-variant="card"]:hover .ui-transfer-logo { + color: var(--transfer-brand); + transform: translateY(-2px); + } +} +@media (prefers-reduced-motion: reduce) { + .ui-transfer-fill, + .ui-transfer-logo { + transition: none; + } + .ui-transfer[data-variant="card"]:hover .ui-transfer-logo { + transform: none; + } +} diff --git a/crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.tsx b/crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.tsx new file mode 100644 index 0000000..9a7f3b9 --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/components/ui/TransferCard.tsx @@ -0,0 +1,138 @@ +import { useId, type CSSProperties, type ReactNode } from "react"; +import { CheckIcon, ExclamationCircleIcon } from "@heroicons/react/20/solid"; +import "./TransferCard.css"; + +type TransferCardProps = { + name: string; + icon: ReactNode; + brand: "claude" | "chatgpt" | "wizard"; + version?: string; + status: ReactNode; + detail?: ReactNode; + notice?: ReactNode; + error?: ReactNode; + progress?: number; + downloading?: boolean; + filled?: boolean; + tone?: "default" | "success" | "error"; + variant?: "card" | "compact"; + action?: ReactNode; + onOpen?: () => void; +}; + +/** One presentation for a selected installer, a picker card, and a sidebar job. */ +export function TransferCard({ + name, + icon, + brand, + version, + status, + detail, + notice, + error, + progress, + downloading = false, + filled = false, + tone = "default", + variant = "card", + action, + onOpen, +}: TransferCardProps) { + const descriptionId = useId(); + const fill = filled ? 100 : Math.min(100, Math.max(0, progress ?? 0)); + const compact = variant === "compact"; + const Container = compact ? "span" : "div"; + const Name = compact ? "span" : "h3"; + const contents = ( + <> +