From 16642043c24163401020439f5fd91c1874fb4ea9 Mon Sep 17 00:00:00 2001 From: Ilya Shcherbak Date: Fri, 30 Oct 2026 01:57:39 +0300 Subject: [PATCH] Align Wizard agent navigation and account menu with Hub --- README.md | 28 ++- crates/wizard-core/src/hub/mod.rs | 104 ++++++++- crates/wizard-gui/capabilities/default.json | 2 + crates/wizard-gui/src/hub_auth.rs | 84 ++++++- crates/wizard-gui/src/hub_tokens.rs | 211 +++++++++++++++++- crates/wizard-gui/src/lib.rs | 12 +- crates/wizard-gui/src/settings.rs | 163 ++++++++++++-- crates/wizard-gui/src/tray.rs | 7 +- crates/wizard-gui/tauri.conf.json | 2 + crates/wizard-gui/wizard-ui/src/App.tsx | 23 +- .../wizard-gui/wizard-ui/src/AppSidebar.tsx | 53 ++--- .../wizard-ui/src/agents/AgentPage.tsx | 22 +- .../wizard-ui/src/agents/navigation.ts | 20 ++ .../components/catalyst/sidebar-layout.tsx | 4 +- .../wizard-ui/src/logs/OpenLogsButton.tsx | 18 +- crates/wizard-gui/wizard-ui/src/main.tsx | 10 +- .../wizard-ui/src/settings/HubAccount.tsx | 163 ++++++++++---- .../wizard-ui/src/settings/SettingsPage.tsx | 67 ++++++ .../src/settings/application_settings.ts | 45 ++++ .../wizard-ui/src/settings/hub_account.ts | 7 +- .../wizard-ui/src/settings/hub_tokens.ts | 61 ++++- .../wizard-ui/src/settings/theme.ts | 50 +++++ crates/wizard-gui/wizard-ui/src/styles.css | 8 +- crates/wizard-settings/src/lib.rs | 87 ++++++++ 24 files changed, 1069 insertions(+), 182 deletions(-) create mode 100644 crates/wizard-gui/wizard-ui/src/agents/navigation.ts create mode 100644 crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx create mode 100644 crates/wizard-gui/wizard-ui/src/settings/application_settings.ts create mode 100644 crates/wizard-gui/wizard-ui/src/settings/theme.ts diff --git a/README.md b/README.md index ada51be..12d7726 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ An application for configuring agents to use CoreInfra. 4. Install dependencies: ```sh - npm ci --prefix crates/wizard-gui/wizard-ui + npm ci --include=dev --prefix crates/wizard-gui/wizard-ui ``` 5. Choose a bundle format for your system: @@ -58,6 +58,32 @@ The generated files are located at these paths relative to the repository root: `*` represents the filename, which depends on the application version and architecture. +### Working on the interface on macOS + +Run these commands from the repository root. Quit any running Wizard first: the +application allows only one instance, including development builds. + +For UI development with Vite hot reload and Rust file watching: + +```sh +node crates/wizard-gui/wizard-ui/node_modules/@tauri-apps/cli/tauri.js dev +``` + +For a standalone local application (a faster debug build, signed ad hoc): + +```sh +node crates/wizard-gui/wizard-ui/node_modules/@tauri-apps/cli/tauri.js build --debug --bundles app +open "target/debug/bundle/macos/CoreInfra Wizard.app" +``` + +Omit `--debug` for the release build described above. Neither command installs the +bundle into `/Applications`. Local builds use the same saved account and proxy +settings as the installed Wizard. Quit and reopen the bundle after rebuilding it. + +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). + ## License Except where separately noted, CoreInfra Wizard's original source code is licensed under the [Mozilla Public License, v. 2.0](LICENSE). If a copy of the MPL was not distributed with this project, you can obtain one at . diff --git a/crates/wizard-core/src/hub/mod.rs b/crates/wizard-core/src/hub/mod.rs index 19919d2..e1c773d 100644 --- a/crates/wizard-core/src/hub/mod.rs +++ b/crates/wizard-core/src/hub/mod.rs @@ -16,7 +16,7 @@ use reqwest::{ use serde::{Deserialize, Serialize, de::DeserializeOwned}; use wizard_settings::Settings; -const HUB_ORIGIN: &str = "https://hub.coreinfra.ai"; +pub const HUB_ORIGIN: &str = "https://hub.coreinfra.ai"; const PROFILE_PATH: &str = "/hub/api/profile"; const HUB_INFO_PATH: &str = "/hub/api/hub/info"; const ISSUE_TOKEN_PATH: &str = "/hub/api/agent-token/issue"; @@ -68,7 +68,10 @@ impl SessionUpdate { match self { Self::Unchanged => {} Self::Refreshed(session) => settings.hub_session = session, - Self::Rejected => settings.hub_session.clear(), + Self::Rejected => { + settings.hub_session.clear(); + settings.active_hub_id.clear(); + } } } } @@ -103,13 +106,9 @@ pub async fn fetch_profile( struct ProfileResponse { personal_hub_id: String, hubs: Vec, - } - - #[derive(Deserialize)] - struct ProfileHub { - hub_id: String, - hub_name: String, - display_name: Option, + #[serde(default)] + username: String, + verified_email: Option, } let (update, response) = @@ -120,17 +119,21 @@ pub async fn fetch_profile( } let hub = response .hubs - .into_iter() + .iter() .find(|hub| hub.hub_id == response.personal_hub_id) .ok_or(HubError::Response)?; let personal_hub_name = hub .display_name + .as_ref() .map(|name| name.trim().to_owned()) .filter(|name| !name.is_empty()) - .unwrap_or(hub.hub_name); + .unwrap_or_else(|| hub.hub_name.clone()); Ok(HubProfile { personal_hub_id: response.personal_hub_id, personal_hub_name, + hubs: response.hubs, + username: response.username, + verified_email: response.verified_email, }) }); (update, profile) @@ -185,10 +188,33 @@ async fn request( /// Non-secret Hub account details, constructed explicitly by `fetch_profile`. #[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)] pub struct HubProfile { - /// Hub whose agent tokens Wizard lists and creates. + /// Default hub when no accessible hub has been selected. #[serde(skip_serializing_if = "String::is_empty")] pub personal_hub_id: String, pub personal_hub_name: String, + pub hubs: Vec, + pub username: String, + pub verified_email: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct ProfileHub { + pub hub_id: String, + pub hub_name: String, + pub display_name: Option, + pub is_personal: bool, +} + +impl HubProfile { + /// Ignore a saved hub that is no longer in this account's memberships. + #[must_use] + pub fn active_hub_id<'a>(&'a self, selected: &'a str) -> &'a str { + if self.hubs.iter().any(|hub| hub.hub_id == selected) { + selected + } else { + &self.personal_hub_id + } + } } /// Agent token of a Hub hub. `token` is a secret: no `Debug`, never logged. @@ -291,3 +317,57 @@ fn session_from_headers(headers: &HeaderMap) -> Result, ()> { } Ok(session) } + +#[cfg(test)] +mod tests { + use super::*; + + fn profile() -> HubProfile { + HubProfile { + personal_hub_id: "personal".into(), + hubs: vec![ProfileHub { + hub_id: "team".into(), + hub_name: "Team".into(), + display_name: None, + is_personal: false, + }], + ..HubProfile::default() + } + } + + #[test] + fn selected_hub_must_belong_to_profile() { + let profile = profile(); + assert_eq!(profile.active_hub_id("team"), "team"); + assert_eq!(profile.active_hub_id(""), "personal"); + assert_eq!(profile.active_hub_id("removed-membership"), "personal"); + } + + #[test] + fn rejected_session_forgets_hub_without_changing_agent_routing() { + let mut settings = Settings { + hub_session: "old-session".into(), + active_hub_id: "team".into(), + codex_proxy_enabled: Some("test-token".into()), + ..Settings::default() + }; + SessionUpdate::Rejected.apply(&mut settings, "old-session"); + assert!(settings.hub_session.is_empty()); + assert!(settings.active_hub_id.is_empty()); + assert_eq!(settings.codex_proxy_enabled.as_deref(), Some("test-token")); + } + + #[test] + fn stale_rejection_does_not_clear_new_account_or_hub() { + let mut settings = Settings { + hub_session: "new-session".into(), + active_hub_id: "team".into(), + ..Settings::default() + }; + SessionUpdate::Rejected.apply(&mut settings, "old-session"); + assert_eq!(settings.hub_session, "new-session"); + assert_eq!(settings.active_hub_id, "team"); + SessionUpdate::Refreshed("refreshed-session".into()).apply(&mut settings, "new-session"); + assert_eq!(settings.active_hub_id, "team"); + } +} diff --git a/crates/wizard-gui/capabilities/default.json b/crates/wizard-gui/capabilities/default.json index ef2a056..deef492 100644 --- a/crates/wizard-gui/capabilities/default.json +++ b/crates/wizard-gui/capabilities/default.json @@ -4,6 +4,8 @@ "windows": ["main", "logs"], "permissions": [ "core:default", + "core:window:allow-set-theme", + "core:window:allow-start-dragging", "log:allow-log" ] } diff --git a/crates/wizard-gui/src/hub_auth.rs b/crates/wizard-gui/src/hub_auth.rs index c66f1e6..e893977 100644 --- a/crates/wizard-gui/src/hub_auth.rs +++ b/crates/wizard-gui/src/hub_auth.rs @@ -95,6 +95,7 @@ pub(crate) struct HubAccount { signed_in: bool, /// Absent until loaded from Hub, or when loading failed. profile: Option, + active_hub_id: Option, pending: bool, error: Option, } @@ -102,12 +103,19 @@ pub(crate) struct HubAccount { impl HubAccount { /// `signed_in` comes from saved settings (a read failure is signed out), `profile` from memory. fn saved(app: &tauri::AppHandle, pending: bool, error: Option) -> Self { - let signed_in = settings::get_state(app).is_ok_and(|s| !s.hub_session.is_empty()); + let settings = settings::get_state(app).ok(); + let signed_in = settings.as_ref().is_some_and(|s| !s.hub_session.is_empty()); + let profile = signed_in + .then(|| app.state::().lock().clone()) + .flatten(); + let active_hub_id = profile + .as_ref() + .zip(settings.as_ref()) + .map(|(profile, settings)| profile.active_hub_id(&settings.active_hub_id).to_owned()); Self { signed_in, - profile: signed_in - .then(|| app.state::().lock().clone()) - .flatten(), + profile, + active_hub_id, pending, error, } @@ -130,7 +138,11 @@ pub(crate) async fn load_profile(app: &tauri::AppHandle) -> Result refreshed.clone(), + _ => session, + }; + (update, profile.map(|profile| (current_session, profile))) }) .await?; let current = settings::get_state(app).map(|s| s.hub_session); @@ -199,9 +211,12 @@ pub(crate) async fn logout_hub_account(app: tauri::AppHandle) -> Result<(), Stri if !matches!(*app.state::().attempt(), Attempt::Idle) { return Err("Дождитесь завершения попытки входа".into()); } - settings::update_state(&app, |s| s.hub_session.clear()) - .await - .map_err(|_| "Не удалось удалить сессию Wizard")?; + settings::update_state(&app, |s| { + s.hub_session.clear(); + s.active_hub_id.clear(); + }) + .await + .map_err(|_| "Не удалось удалить сессию Wizard")?; log::info!("hub logout"); clear_profile(&app); HubTokensManager::clear(&app); @@ -209,6 +224,50 @@ pub(crate) async fn logout_hub_account(app: tauri::AppHandle) -> Result<(), Stri Ok(()) } +/// Selects an accessible hub without changing any agent configuration. +#[tauri::command] +pub(crate) async fn select_hub(app: tauri::AppHandle, hub_id: String) -> Result<(), String> { + let profile = load_profile(&app) + .await + .map_err(|_| "Не удалось загрузить хабы")?; + let session = settings::get_state(&app) + .map_err(|_| "Настройки недоступны")? + .hub_session; + if session.is_empty() { + return Err("Войдите в CoreInfra Hub".into()); + } + if !profile.hubs.iter().any(|hub| hub.hub_id == hub_id) { + return Err("Хаб недоступен этому аккаунту".into()); + } + settings::update_state(&app, move |s| { + if s.hub_session == session { + s.active_hub_id = hub_id; + } + }) + .await + .map_err(|_| "Не удалось сохранить выбранный хаб")?; + HubTokensManager::clear(&app); + republish(&app); + HubTokensManager::refresh(&app).await; + Ok(()) +} + +/// 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> { + let mut url = Url::parse(hub::HUB_ORIGIN).map_err(|_| "Некорректный адрес хаба")?; + let account = HubAccount::saved(&app, false, None); + if let Some(id) = account.active_hub_id { + url.query_pairs_mut().append_pair("hub_id", &id); + } + if matches!(theme.as_str(), "light" | "dark" | "system") { + url.query_pairs_mut().append_pair("app_theme", &theme); + } + login::open_browser(&url) + .await + .map_err(|error| error.message().to_owned()) +} + /// Republishes the saved account after a session change, keeping `pending` and `error`. pub(crate) fn republish(app: &tauri::AppHandle) { app.state::>().update(|account| { @@ -272,9 +331,12 @@ async fn run_login(app: &tauri::AppHandle) -> Result<(), LoginError> { return Err(error); } }; - if settings::update_state(app, move |s| s.hub_session = session) - .await - .is_err() + if settings::update_state(app, move |s| { + s.hub_session = session; + s.active_hub_id.clear(); + }) + .await + .is_err() { callback.reply(Reply::Failed).await; return Err(LoginError::Save); diff --git a/crates/wizard-gui/src/hub_tokens.rs b/crates/wizard-gui/src/hub_tokens.rs index de92236..f85dc47 100644 --- a/crates/wizard-gui/src/hub_tokens.rs +++ b/crates/wizard-gui/src/hub_tokens.rs @@ -1,4 +1,4 @@ -//! In-memory list of agent tokens in the user's personal Hub hub. Token values are secrets: +//! In-memory list of agent tokens in the selected Hub. Token values are secrets: //! they are never persisted or logged and leave the backend only through IPC. use crate::{ @@ -13,6 +13,7 @@ use wizard_core::hub::{self, AgentTokens, Client, HubError, SessionUpdate}; #[derive(Clone, Default, Serialize)] pub(crate) struct HubTokens { + hub_id: Option, tokens: AgentTokens, loading: bool, error: Option, @@ -65,6 +66,108 @@ pub(crate) async fn refresh_hub_tokens(app: tauri::AppHandle) { HubTokensManager::refresh(&app).await; } +#[derive(Clone, Serialize)] +pub(crate) struct ConfiguredTokenInfo { + name: String, + hub_id: String, +} + +#[derive(Clone, Serialize)] +pub(crate) struct ConfiguredTokens { + details: Vec>, + error: Option, +} + +/// Resolve already configured keys across the account's hubs, independently of the selected +/// hub. Refresh with the token list; network errors are state, IPC errors reject the command. +/// Return only names and hub IDs, in request order; never log the input keys. +#[tauri::command] +pub(crate) async fn get_configured_token_info( + app: tauri::AppHandle, + tokens: Vec, + last_revision: Option, +) -> Result, String> { + let signal = app.state::>(); + let mut snapshot = signal + .wait(last_revision) + .await + .map_err(|_| "Не удалось получить сведения о ключах")?; + // Wait for a completed refresh rather than querying every hub twice per refresh. + while snapshot.state.loading { + snapshot = signal + .wait(Some(snapshot.revision)) + .await + .map_err(|_| "Не удалось получить сведения о ключах")?; + } + let state = match hub_auth::load_profile(&app).await { + Ok(profile) => { + resolve_configured_tokens( + &tokens, + profile.hubs.into_iter().map(|hub| hub.hub_id), + |hub_id| { + with_session(&app, |client, session| async move { + hub::list_agent_tokens(&client, &session, &hub_id).await + }) + }, + ) + .await + } + Err(_) => ConfiguredTokens { + details: vec![None; tokens.len()], + error: Some("Не удалось загрузить сведения о хабах настроенных агентов".into()), + }, + }; + Ok(RevisionSnapshot { + revision: snapshot.revision, + state, + }) +} + +async fn resolve_configured_tokens( + tokens: &[String], + hubs: impl IntoIterator, + mut fetch: F, +) -> ConfiguredTokens +where + F: FnMut(String) -> Fut, + Fut: Future>, +{ + let mut result = ConfiguredTokens { + details: vec![None; tokens.len()], + error: None, + }; + for hub_id in hubs { + if result.details.iter().all(Option::is_some) { + break; + } + let list = match fetch(hub_id.clone()).await { + Ok(list) => list, + Err(HubError::SignedOut) => { + result.error = Some("Войдите в CoreInfra Hub".into()); + break; + } + Err(_) => { + result.error = + Some("Не удалось загрузить сведения о ключах из CoreInfra Hub".into()); + continue; + } + }; + for (token, info) in tokens.iter().zip(&mut result.details) { + if let Some(found) = list.get(token) { + *info = Some(ConfiguredTokenInfo { + name: found.name.clone(), + hub_id: hub_id.clone(), + }); + } + } + } + // A failure in an unrelated hub does not invalidate keys resolved in other hubs. + if result.details.iter().all(Option::is_some) { + result.error = None; + } + result +} + /// Loads, publishes and clears the token list, and runs authenticated Hub requests. pub(crate) struct HubTokensManager; @@ -102,7 +205,8 @@ impl HubTokensManager { return None; } Some(match result { - Ok(list) => HubTokens { + Ok((hub_id, list)) => HubTokens { + hub_id: Some(hub_id), tokens: list, loading: false, error: None, @@ -133,13 +237,13 @@ impl HubTokensManager { } } -/// Creates a token named `name` in the personal hub, then reloads the list so the token shows +/// Creates a token named `name` in the selected hub, then reloads the list so the token shows /// with Hub's own data before its value is returned. A failed reload is published as the list /// error and does not fail the result. Never log the value. pub(crate) async fn issue(app: &tauri::AppHandle, name: &str) -> Result { let signal = app.state::>(); let generation = signal.current().state.generation; - let hub_id = personal_hub_id(app).await.map_err(|error| match error { + let hub_id = active_hub_id(app).await.map_err(|error| match error { TokensError::NoHub => error.message().to_owned(), TokensError::Request(_) => "Не удалось создать токен CoreInfra Hub".to_owned(), })?; @@ -164,19 +268,23 @@ pub(crate) async fn issue(app: &tauri::AppHandle, name: &str) -> Result Result { +async fn active_hub_id(app: &tauri::AppHandle) -> Result { let profile = hub_auth::load_profile(app) .await .map_err(TokensError::Request)?; - Some(profile.personal_hub_id) + let selected = settings::get_state(app) + .map_err(|_| TokensError::Request(HubError::Request))? + .active_hub_id; + Some(profile.active_hub_id(&selected).to_owned()) .filter(|id| !id.is_empty()) .ok_or(TokensError::NoHub) } -async fn fetch(app: &tauri::AppHandle) -> Result { - let hub_id = personal_hub_id(app).await?; +async fn fetch(app: &tauri::AppHandle) -> Result<(String, AgentTokens), TokensError> { + let hub_id = active_hub_id(app).await?; with_session(app, |client, session| async move { - hub::list_agent_tokens(&client, &session, &hub_id).await + let (update, tokens) = hub::list_agent_tokens(&client, &session, &hub_id).await; + (update, tokens.map(|tokens| (hub_id, tokens))) }) .await .map_err(TokensError::Request) @@ -222,3 +330,88 @@ where } result } + +#[cfg(test)] +mod tests { + use super::*; + use core::future::ready; + + fn token_list(token: &str) -> AgentTokens { + serde_json::from_value(serde_json::json!([ + { "token": token, "name": "Agent", "issued_at": 1 } + ])) + .expect("test token list should deserialize") + } + + #[test] + fn missing_key_is_not_a_network_error() { + let result = tauri::async_runtime::block_on(resolve_configured_tokens( + &["missing-key".into()], + ["personal".into()], + |_| ready(Ok(AgentTokens::default())), + )); + assert!(result.details[0].is_none()); + assert!(result.error.is_none()); + } + + #[test] + fn partial_failure_keeps_known_keys_and_refresh_recovers() { + let keys = ["personal-key".into(), "team-key".into()]; + let failed = tauri::async_runtime::block_on(resolve_configured_tokens( + &keys, + ["personal".into(), "team".into()], + |id| { + ready(if id == "personal" { + Ok(token_list("personal-key")) + } else { + Err(HubError::Request) + }) + }, + )); + assert_eq!( + failed.details[0].as_ref().map(|info| info.hub_id.as_str()), + Some("personal") + ); + assert!(failed.details[1].is_none()); + assert!(failed.error.is_some()); + + let refreshed = tauri::async_runtime::block_on(resolve_configured_tokens( + &keys, + ["personal".into(), "team".into()], + |id| { + ready(Ok(token_list(if id == "personal" { + "personal-key" + } else { + "team-key" + }))) + }, + )); + assert!(refreshed.error.is_none()); + assert_eq!( + refreshed.details[1] + .as_ref() + .map(|info| info.hub_id.as_str()), + Some("team") + ); + } + + #[test] + fn unrelated_hub_failure_does_not_hide_resolved_key() { + let result = tauri::async_runtime::block_on(resolve_configured_tokens( + &["team-key".into()], + ["unavailable".into(), "team".into()], + |id| { + ready(if id == "team" { + Ok(token_list("team-key")) + } else { + Err(HubError::Request) + }) + }, + )); + assert!(result.error.is_none()); + assert_eq!( + result.details[0].as_ref().map(|info| info.name.as_str()), + Some("Agent") + ); + } +} diff --git a/crates/wizard-gui/src/lib.rs b/crates/wizard-gui/src/lib.rs index 30f2912..c305465 100644 --- a/crates/wizard-gui/src/lib.rs +++ b/crates/wizard-gui/src/lib.rs @@ -87,12 +87,13 @@ pub fn run_application() -> Result<()> { hub_tokens::HubTokensManager::initialize(app.handle())?; #[cfg(any(target_os = "macos", target_os = "windows"))] let tray_enabled = { - let proxy_enabled = settings::get_state(app.handle())?.local_proxy_enabled(); + let preferences = settings::get_state(app.handle())?.application; autostart::initialize(app.handle())?; - autostart::set_enabled(app.handle(), proxy_enabled)?; + let autostart = autostart::set_enabled(app.handle(), preferences.autostart_enabled); app.on_menu_event(|app, event| tray::on_menu_event(app, &event)); - tray::set_enabled(app.handle(), proxy_enabled)?; + let tray = tray::set_enabled(app.handle(), preferences.tray_enabled); + autostart.and(tray)?; tray::is_enabled(app.handle()) }; #[cfg(target_os = "linux")] @@ -116,6 +117,8 @@ pub fn run_application() -> Result<()> { claude_desktop_install::check_claude_desktop_release, claude_desktop_install::download_claude_desktop_release, claude_desktop_install::install_claude_desktop_release, + settings::get_application_settings, + settings::set_application_setting, logs::open_logs, logs::read_logs, updater::get_update_state, @@ -124,7 +127,10 @@ pub fn run_application() -> Result<()> { hub_auth::get_hub_account_state, hub_auth::login_hub_account, hub_auth::logout_hub_account, + hub_auth::select_hub, + hub_auth::open_hub, hub_tokens::get_hub_tokens_state, + hub_tokens::get_configured_token_info, hub_tokens::refresh_hub_tokens, proxy::get_proxy_state, agents::get_agent_state, diff --git a/crates/wizard-gui/src/settings.rs b/crates/wizard-gui/src/settings.rs index a0e1eb6..cc725a4 100644 --- a/crates/wizard-gui/src/settings.rs +++ b/crates/wizard-gui/src/settings.rs @@ -1,8 +1,9 @@ -use crate::revision_signal::RevisionSignal; +use crate::revision_signal::{RevisionSignal, RevisionSnapshot}; use anyhow::{Context as _, Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; use std::sync::Mutex; use tauri::Manager as _; -use wizard_settings::{self as settings, Settings}; +use wizard_settings::{self as settings, ApplicationSettings, Settings}; static SETTINGS_WRITE_LOCK: Mutex<()> = Mutex::new(()); @@ -28,6 +29,14 @@ pub(crate) fn get_state(app: &tauri::AppHandle) -> Result { pub(crate) async fn update_state( app: &tauri::AppHandle, edit: impl FnOnce(&mut Settings) + Send + 'static, +) -> Result<()> { + update_state_with_application_sync(app, edit, false).await +} + +async fn update_state_with_application_sync( + app: &tauri::AppHandle, + edit: impl FnOnce(&mut Settings) + Send + 'static, + sync_application: bool, ) -> Result<()> { let app = app.clone(); tauri::async_runtime::spawn_blocking(move || { @@ -40,23 +49,149 @@ pub(crate) async fn update_state( let current = signal.current().state; let mut next = current.clone(); edit(&mut next); - if next == current { - return Ok(()); + let application = next.application; + let sync_application = sync_application || application != current.application; + if next != current { + settings::save_to_file(&next) + .context("Не удалось сохранить настройки; изменения не применены")?; + signal.notify(next); } - #[cfg(any(target_os = "macos", target_os = "windows"))] - let proxy_enabled = next.local_proxy_enabled(); - settings::save_to_file(&next)?; - signal.notify(next); - - // Listeners are synced by the caller that changes a proxy setting. - #[cfg(any(target_os = "macos", target_os = "windows"))] - if proxy_enabled != current.local_proxy_enabled() { - crate::tray::set_enabled(&app, proxy_enabled)?; - crate::autostart::set_enabled(&app, proxy_enabled)?; + // Proxy changes never control the application's lifecycle. Explicit + // retries synchronize OS effects even when the saved values are unchanged. + if sync_application { + sync_application_settings(&app, application) + .context("Настройки сохранены, но не удалось применить их в системе")?; } Ok(()) }) .await .context("settings save task failed")? } + +fn sync_application_settings(app: &tauri::AppHandle, settings: ApplicationSettings) -> Result<()> { + #[cfg(any(target_os = "macos", target_os = "windows"))] + { + let tray = crate::tray::set_enabled(app, settings.tray_enabled); + let autostart = crate::autostart::set_enabled(app, settings.autostart_enabled); + // Finish both effects before exiting if the last window closed while + // disabling the tray. Explicit Exit remains unaffected. + if !crate::tray::is_enabled(app) && app.webview_windows().is_empty() { + app.exit(0); + } + tray.and(autostart) + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + let _ = (app, settings); + bail!("Работа в трее и автозапуск пока доступны только на macOS и Windows") + } +} + +#[derive(Clone, Serialize)] +pub(crate) struct ApplicationSettingsState { + #[serde(flatten)] + preferences: ApplicationSettings, + supported: bool, +} + +fn application_snapshot( + snapshot: &RevisionSnapshot, +) -> RevisionSnapshot { + RevisionSnapshot { + revision: snapshot.revision, + state: ApplicationSettingsState { + preferences: snapshot.state.application, + supported: cfg!(any(target_os = "macos", target_os = "windows")), + }, + } +} + +/// Project only non-secret preferences from the single settings owner. +#[tauri::command] +pub(crate) async fn get_application_settings( + last_revision: Option, + signal: tauri::State<'_, RevisionSignal>, +) -> Result, String> { + signal + .wait(last_revision) + .await + .map(|snapshot| application_snapshot(&snapshot)) + .map_err(|_| "Не удалось получить настройки приложения".into()) +} + +#[derive(Clone, Copy, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum ApplicationSetting { + TrayEnabled, + AutostartEnabled, +} + +fn set_preference(settings: &mut Settings, setting: ApplicationSetting, enabled: bool) { + match setting { + ApplicationSetting::TrayEnabled => settings.application.tray_enabled = enabled, + ApplicationSetting::AutostartEnabled => settings.application.autostart_enabled = enabled, + } +} + +#[tauri::command] +pub(crate) async fn set_application_setting( + app: tauri::AppHandle, + setting: ApplicationSetting, + enabled: bool, +) -> Result<(), String> { + if !cfg!(any(target_os = "macos", target_os = "windows")) { + return Err("Работа в трее и автозапуск пока доступны только на macOS и Windows".into()); + } + update_state_with_application_sync( + &app, + move |settings| set_preference(settings, setting, enabled), + true, + ) + .await + .map_err(|error| format!("{error:#}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ipc_exposes_only_application_preferences() { + let settings = Settings { + hub_session: "fixture-session".into(), + claude_proxy_enabled: Some("fixture-token".into()), + ..Settings::default() + }; + let snapshot = application_snapshot(&RevisionSnapshot { + revision: 7, + state: settings, + }); + let json = serde_json::to_value(snapshot).expect("serialize safe snapshot"); + assert_eq!(json.as_object().expect("object").len(), 4); + assert_eq!(json["revision"], 7); + assert_eq!(json["tray_enabled"], true); + assert_eq!(json["autostart_enabled"], true); + assert!(json.get("supported").is_some()); + } + + #[test] + fn preference_updates_preserve_other_settings() { + let mut settings = Settings { + hub_session: "fixture-session".into(), + codex_proxy_enabled: Some("fixture-token".into()), + ..Settings::default() + }; + set_preference(&mut settings, ApplicationSetting::TrayEnabled, false); + assert!(!settings.application.tray_enabled); + assert!(settings.application.autostart_enabled); + set_preference(&mut settings, ApplicationSetting::AutostartEnabled, false); + assert!(!settings.application.tray_enabled); + assert!(!settings.application.autostart_enabled); + assert_eq!(settings.hub_session, "fixture-session"); + assert_eq!( + settings.codex_proxy_enabled.as_deref(), + Some("fixture-token") + ); + } +} diff --git a/crates/wizard-gui/src/tray.rs b/crates/wizard-gui/src/tray.rs index 168f9e9..3d668cc 100644 --- a/crates/wizard-gui/src/tray.rs +++ b/crates/wizard-gui/src/tray.rs @@ -1,5 +1,4 @@ use anyhow::{Context as _, Result}; -use tauri::Manager as _; use tauri::menu::{Menu, MenuEvent, MenuItem}; use tauri::tray::TrayIconBuilder; @@ -33,10 +32,8 @@ pub(crate) fn set_enabled(app: &tauri::AppHandle, enabled: bool) -> Result<()> { fn set_enabled_on_main_thread(app: &tauri::AppHandle, enabled: bool) -> Result<()> { // Removing the registry entry drops the native icon; AppKit requires the main thread. if !enabled { - let removed = app.remove_tray_by_id(TRAY_ID).is_some(); - if removed && app.webview_windows().is_empty() { - app.exit(0); - } + // The settings writer decides whether to exit after all OS effects finish. + app.remove_tray_by_id(TRAY_ID); return Ok(()); } if is_enabled(app) { diff --git a/crates/wizard-gui/tauri.conf.json b/crates/wizard-gui/tauri.conf.json index 6be2f72..4331e67 100644 --- a/crates/wizard-gui/tauri.conf.json +++ b/crates/wizard-gui/tauri.conf.json @@ -18,6 +18,8 @@ "windows": [ { "title": "CoreInfra Wizard", + "titleBarStyle": "Overlay", + "hiddenTitle": true, "create": false, "width": 1100, "height": 720 diff --git a/crates/wizard-gui/wizard-ui/src/App.tsx b/crates/wizard-gui/wizard-ui/src/App.tsx index 4ad7035..a95f408 100644 --- a/crates/wizard-gui/wizard-ui/src/App.tsx +++ b/crates/wizard-gui/wizard-ui/src/App.tsx @@ -1,7 +1,8 @@ -import { useEffect, useState } from "react"; +import { useEffect, useSyncExternalStore } from "react"; import { AppSidebar } from "./AppSidebar"; import { AgentPage } from "./agents/AgentPage"; -import { type AgentId, useAgentState } from "./agents/agents_state"; +import { useAgentState } from "./agents/agents_state"; +import { pageFromHash } from "./agents/navigation"; import { useProxy } from "./agents/proxy"; import { AuthLayout } from "./components/catalyst/auth-layout"; import { Badge } from "./components/catalyst/badge"; @@ -9,15 +10,21 @@ import { SidebarLayout } from "./components/catalyst/sidebar-layout"; import { ErrorText } from "./components/ErrorText"; import { OpenLogsButton } from "./logs/OpenLogsButton"; import { useHubAccountControl } from "./settings/HubAccount"; +import { SettingsPage } from "./settings/SettingsPage"; import { useUpdateState } from "./updates/update"; import { UpdateScreen } from "./updates/UpdateScreen"; +function subscribeNavigation(onChange: () => void) { + window.addEventListener("hashchange", onChange); + return () => window.removeEventListener("hashchange", onChange); +} + function App() { const update = useUpdateState(); const agents = useAgentState(); const proxy = useProxy(); const account = useHubAccountControl(); - const [page, setPage] = useState("claude_desktop"); + const page = useSyncExternalStore(subscribeNavigation, () => pageFromHash(window.location.hash)); const state = update.state; // Pages share the window scroll; start each one from the top. @@ -39,12 +46,12 @@ function App() { return ( } + sidebar={} > - {agents.status === "loading" && Загрузка…} - {agents.status === "error" && Не удалось загрузить состояние агентов: {agents.message}} - {agents.status === "ready" && } + {page === "settings" && } + {page !== "settings" && agents.status === "loading" && Загрузка…} + {page !== "settings" && agents.status === "error" && Не удалось загрузить состояние агентов: {agents.message}} + {agents.status === "ready" && } ); } diff --git a/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx b/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx index 96e5949..e14dca1 100644 --- a/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx +++ b/crates/wizard-gui/wizard-ui/src/AppSidebar.tsx @@ -1,74 +1,61 @@ import type { ComponentType, ComponentPropsWithoutRef } from "react"; import { useClose } from "@headlessui/react"; -import type { AgentId, AgentStates } from "./agents/agents_state"; -import type { useProxy } from "./agents/proxy"; +import { agentPaths, settingsPath, type AgentPageId, type AppPageId } from "./agents/navigation"; import { AppLogo } from "./components/AppLogo"; import { ClaudeIcon, OpenAiIcon, OpenCodeIcon, PiIcon } from "./components/BrandIcons"; -import { Badge } from "./components/catalyst/badge"; +import { Button } from "./components/catalyst/button"; +import { Divider } from "./components/catalyst/divider"; import { Sidebar, SidebarBody, SidebarFooter, SidebarHeader, SidebarHeading, SidebarItem, SidebarLabel, SidebarSection, SidebarSpacer } from "./components/catalyst/sidebar"; -import { OpenLogsItem } from "./logs/OpenLogsButton"; import { type HubAccountControl, HubAccountMenu } from "./settings/HubAccount"; import type { UpdateObservation } from "./updates/update"; import { UpdateItem } from "./updates/UpdateItem"; -// Short routing state of an agent, if it is worth showing next to its name. -function AgentBadge({ agents, id, proxy }: { agents: AgentStates; id: AgentId; proxy: ReturnType }) { - const agent = agents[id]; - if (agent.status === "error") return Ошибка; - if (agent.status === "not_found") return null; - - const mode = agent.data.routing_mode; - const chatGptProxyStopped = agents.codex.status === "found" && agents.codex.data.desktop.status === "found" - && proxy.proxy?.chatgpt === false; - if (mode === "disabled") return null; - if (id === "codex" && chatGptProxyStopped) return Прокси; - return {mode === "sub" ? "Подписка" : "Hub"}; -} - -export function AppSidebar({ page, onSelect, agents, proxy, account, update }: { - page: AgentId; - onSelect: (page: AgentId) => void; - agents: AgentStates | undefined; - proxy: ReturnType; +export function AppSidebar({ page, account, update }: { + page: AppPageId; account: HubAccountControl; update: UpdateObservation; }) { // Closes the sidebar dialog on narrow windows; does nothing on the desktop layout. const close = useClose(); - function item(id: AgentId, label: string, Icon: ComponentType>) { + function item(id: AgentPageId, label: string, Icon: ComponentType>) { return ( - { onSelect(id); close(); }}> + {label} - {agents && } ); } return ( - - -
+ + +
+
Агенты {item("claude_desktop", "Claude Desktop", ClaudeIcon)} + {item("codex", "ChatGPT / Codex", OpenAiIcon)} +
+ +
{item("claude", "Claude Code", ClaudeIcon)} - {item("codex", "Codex", OpenAiIcon)} {item("opencode", "OpenCode", OpenCodeIcon)} {item("pi", "Pi", PiIcon)}
-
- + + + Настройки +
diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx index 2858add..ae1311b 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx @@ -121,7 +121,7 @@ function TokenField({ token, hub, disabled }: { ))} - {!hub.signedIn && Войдите в CoreInfra Hub для выбора токена.} + {!hub.signedIn && Войдите в CoreInfra Hub для выбора ключа.} {hub.status === "error" && ( {hub.error}{" "} @@ -250,17 +250,17 @@ function BackupButton({ agent, disabled }: { agent: BackupAgent; disabled: boole // The selected agent's page. Plan preparation and the plan dialog outlive page switches. export function AgentPage({ agents, page, proxy, account }: { agents: AgentStates; - page: AgentId; + page: AgentId | null; proxy: ReturnType; account: HubAccountControl; }) { const [preparedChange, setPreparedChange] = useState(); const [isPreparingPlan, setIsPreparingPlan] = useState(false); // Tagged with the page that prepared the change, so it never shows on another agent's page. - const [error, setError] = useState<{ page: AgentId; 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(), signedIn: account.signedIn }; + const hub: Hub = { ...useHubTokens(account.account?.active_hub_id), signedIn: account.signedIn }; const claudeDesktopToken = useTokenMenu("claude_desktop", agents.claude_desktop.status === "found" ? agents.claude_desktop.data.token : null, hub); const claudeInstall = useClaudeDesktopInstall(); @@ -299,21 +299,25 @@ export function AgentPage({ agents, page, proxy, account }: { let content: ReactNode; switch (page) { + // Keep a prepared plan alive while the settings page is selected. + case null: + content = null; + break; case "codex": { const codex = agents.codex; const chatGptProxyStopped = proxy.proxy?.chatgpt === false && codex.status === "found" && codex.data.desktop.status === "found" && codex.data.routing_mode !== "disabled"; content = ( <> - } /> + } /> {codex.status === "error" ? ( -
Не удалось получить состояние Codex / ChatGPT: {codex.data}
+
Не удалось получить состояние ChatGPT / Codex: {codex.data}
) : ( - Codex CLI - ChatGPT + Codex CLI + Прокси для ChatGPT @@ -328,7 +332,7 @@ export function AgentPage({ agents, page, proxy, account }: { {codex.status === "found" && ( ({ CodexSetRouting: mode })} agentToken={codex.data.token} hub={hub} - note="Настройка общая для Codex и ChatGPT." disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> + note="Настройка общая для ChatGPT и Codex." disabled={isChangeInProgress} error={pageError} onPrepare={prepare} /> )} ); diff --git a/crates/wizard-gui/wizard-ui/src/agents/navigation.ts b/crates/wizard-gui/wizard-ui/src/agents/navigation.ts new file mode 100644 index 0000000..9e43e67 --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/agents/navigation.ts @@ -0,0 +1,20 @@ +import type { AgentId } from "./agents_state"; + +export type AgentPageId = AgentId; +export type AppPageId = AgentPageId | "settings"; +export const settingsPath = "/settings"; + +export const agentPaths: Record = { + claude_desktop: "/agents/claude-desktop", + claude: "/agents/claude", + codex: "/agents/codex", + opencode: "/agents/opencode", + pi: "/agents/pi", +}; + +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) ?? "claude_desktop"; +} 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 0c1f016..8b7ab16 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 @@ -39,7 +39,7 @@ function MobileSidebar({ />
@@ -84,7 +84,7 @@ export function SidebarLayout({ {/* Navbar on mobile */}
(); @@ -36,17 +34,3 @@ export function OpenLogsButton() {
); } - -export function OpenLogsItem() { - const { pending, error, open } = useOpenLogs(); - - return ( - <> - - - Журнал - - {error &&
{error}
} - - ); -} diff --git a/crates/wizard-gui/wizard-ui/src/main.tsx b/crates/wizard-gui/wizard-ui/src/main.tsx index ba11549..8f18fe3 100644 --- a/crates/wizard-gui/wizard-ui/src/main.tsx +++ b/crates/wizard-gui/wizard-ui/src/main.tsx @@ -3,9 +3,17 @@ import ReactDOM from "react-dom/client"; import App from "./App"; import { LogWindow } from "./logs/LogWindow"; import "./styles.css"; +import { initializeTheme } from "./settings/theme"; + +initializeTheme(); +const isLogWindow = window.location.hash === "#logs"; +if (navigator.platform.startsWith("Mac") && !isLogWindow) { + document.documentElement.dataset.macWindow = ""; +} ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - {window.location.hash === "#logs" ? : } +