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" ? : } + + {isLogWindow ? : } , ); diff --git a/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx b/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx index 116b8dc..d843d51 100644 --- a/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx +++ b/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx @@ -1,27 +1,29 @@ -import { useState } from "react"; +import { useRef, useState, useSyncExternalStore, type MouseEvent } from "react"; import { MenuButton } from "@headlessui/react"; -import { ArrowRightEndOnRectangleIcon, ArrowRightStartOnRectangleIcon, ChevronUpIcon } from "@heroicons/react/16/solid"; -import { loginHubAccount, logoutHubAccount, useHubAccount } from "./hub_account"; -import { Avatar } from "../components/catalyst/avatar"; -import { Dropdown, DropdownDescription, DropdownItem, DropdownLabel, DropdownMenu } from "../components/catalyst/dropdown"; -import { SidebarItem } from "../components/catalyst/sidebar"; +import { ComputerDesktopIcon, EllipsisHorizontalIcon, MoonIcon, SunIcon } from "@heroicons/react/20/solid"; +import { loginHubAccount, logoutHubAccount, openHub, selectHub, useHubAccount } from "./hub_account"; +import { getTheme, setTheme, subscribeTheme } from "./theme"; +import { Dropdown, DropdownDescription, DropdownDivider, DropdownHeader, DropdownHeading, DropdownItem, DropdownLabel, DropdownMenu, DropdownSection } from "../components/catalyst/dropdown"; +import { SidebarItem, SidebarLabel } from "../components/catalyst/sidebar"; +import { Text } from "../components/catalyst/text"; import { ErrorText } from "../components/ErrorText"; +import { useOpenLogs } from "../logs/OpenLogsButton"; -// Account state and the sign-in/out action, shared by the sidebar and agent pages. +// Account state and actions are shared by the sidebar and agent pages. export function useHubAccountControl() { const { account, error: stateError } = useHubAccount(); const [submitting, setSubmitting] = useState(false); + const [agentBusy, setAgentBusy] = useState(false); const [error, setError] = useState(); - async function change() { - if (!account || submitting) return; + async function run(action: () => Promise) { + if (submitting) return; setSubmitting(true); setError(undefined); try { - // While pending, login reopens the Hub page and extends the wait. - await (account.signed_in ? logoutHubAccount() : loginHubAccount()); + await action(); } catch (cause) { - setError(typeof cause === "string" ? cause : "Не удалось изменить состояние входа. Попробуйте снова."); + setError(typeof cause === "string" ? cause : "Не удалось выполнить действие. Попробуйте снова."); } finally { setSubmitting(false); } @@ -31,57 +33,126 @@ export function useHubAccountControl() { account, signedIn: account?.signed_in === true, submitting, + agentBusy, + setAgentBusy, error: stateError || error || account?.error || undefined, - change: () => void change(), + change: () => { + if (account && !agentBusy) void run(account.signed_in ? logoutHubAccount : loginHubAccount); + }, + select: (hubId: string) => { + if (!agentBusy) void run(() => selectHub(hubId)); + }, + open: () => void run(() => openHub(getTheme())), }; } export type HubAccountControl = ReturnType; -// Sidebar footer: the signed-in hub with a menu, or the sign-in item. +const themes = [ + { value: "light", label: "Светлая тема", Icon: SunIcon }, + { value: "dark", label: "Темная тема", Icon: MoonIcon }, + { value: "system", label: "Системная тема", Icon: ComputerDesktopIcon }, +] as const; + export function HubAccountMenu({ hub }: { hub: HubAccountControl }) { const { account } = hub; - const hubName = account?.profile?.personal_hub_name; + const logs = useOpenLogs(); + const typeaheadUntil = useRef(0); + const theme = useSyncExternalStore(subscribeTheme, getTheme); + const activeHub = account?.profile?.hubs.find((item) => item.hub_id === account.active_hub_id); + const activeName = activeHub?.display_name?.trim() || activeHub?.hub_name || "CoreInfra AI Hub"; + const disabled = hub.submitting || hub.agentBusy; return ( <> - {account?.signed_in ? ( + - - - - - {hubName ?? "CoreInfra AI Hub"} - - {hubName ? "CoreInfra AI Hub" : "Вход выполнен"} - - - - + { typeaheadUntil.current = 0; }}> + + {account?.signed_in ? activeName : "CoreInfra AI Hub"} + + - - - - Выйти - Выход из аккаунта не изменяет настройки агентов. + { + // Keep theme and hub selection open for keyboard activation, preserving typeahead. + if (event.key.length === 1 && event.key !== " ") { + typeaheadUntil.current = Date.now() + 350; + return; + } + if (event.key === " " && Date.now() < typeaheadUntil.current) { + typeaheadUntil.current = Infinity; + return; + } + typeaheadUntil.current = 0; + if (event.key !== "Enter" && event.key !== " ") return; + const id = event.currentTarget.getAttribute("aria-activedescendant"); + const item = id ? document.getElementById(id) : null; + if (!item?.hasAttribute("data-keep-open")) return; + event.preventDefault(); + event.stopPropagation(); + item.click(); + }}> + + {themes.map(({ value, label, Icon }) => ( + ) => { event.preventDefault(); setTheme(value); }}> + + + ))} + + {account?.profile?.username && ( + + {account.profile.username} + {account.profile.verified_email && {account.profile.verified_email}} + + )} + {account?.signed_in && ( + + Хабы + {account.profile?.hubs.map((item) => { + const active = item.hub_id === account.active_hub_id; + const name = item.display_name?.trim() || item.hub_name; + return ( + { typeaheadUntil.current = 0; }} + onPointerMove={(event) => { + if (!event.currentTarget.hasAttribute("data-focus")) typeaheadUntil.current = 0; + }} + onClick={(event: MouseEvent) => { + event.preventDefault(); + event.currentTarget.closest('[role="menu"]')?.focus({ preventScroll: true }); + if (!active) hub.select(item.hub_id); + }}> + {name} + {item.is_personal && Личный хаб} + {active && Активный} + + ); + })} + {!account.profile && Загрузка хабов…} + + )} + + + Перейти в хаб + + + Журнал + + + + {account?.signed_in ? "Выйти" : account?.pending ? "Продолжить вход" : "Войти"} - ) : ( - - - - - - {!account ? (hub.error ? "Хаб недоступен" : "Загрузка…") : account.pending ? "Ожидание входа…" : "Войти"} - - CoreInfra AI Hub - - - - - )} + {hub.error && {hub.error}} + {logs.error && {logs.error}} > ); } diff --git a/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx b/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx new file mode 100644 index 0000000..1202753 --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/settings/SettingsPage.tsx @@ -0,0 +1,67 @@ +import { useRef, useState } from "react"; +import { Badge } from "../components/catalyst/badge"; +import { Button } from "../components/catalyst/button"; +import { Description, Fieldset, Label } from "../components/catalyst/fieldset"; +import { Heading } from "../components/catalyst/heading"; +import { Switch, SwitchField, SwitchGroup } from "../components/catalyst/switch"; +import { Text } from "../components/catalyst/text"; +import { ErrorText } from "../components/ErrorText"; +import { type ApplicationSetting, setApplicationSetting, useApplicationSettings } from "./application_settings"; + +export function SettingsPage() { + const { settings, error: loadError } = useApplicationSettings(); + const inFlight = useRef(false); + const [saving, setSaving] = useState(false); + const [failure, setFailure] = useState<{ setting: ApplicationSetting; enabled: boolean; message: string }>(); + const disabled = saving || !settings?.supported || Boolean(loadError); + + async function change(setting: ApplicationSetting, enabled: boolean) { + if (inFlight.current) return; + inFlight.current = true; + setSaving(true); + setFailure(undefined); + try { + await setApplicationSetting(setting, enabled); + } catch (cause: unknown) { + setFailure({ setting, enabled, message: typeof cause === "string" ? cause : "Не удалось изменить настройку приложения" }); + } finally { + inFlight.current = false; + setSaving(false); + } + } + + return ( + <> + Настройки + + {!settings && !loadError && Загрузка…} + {settings && !settings.supported && ( + Работа в трее и автозапуск пока доступны только на macOS и Windows. + )} + + + Работать в трее + При закрытии окна Wizard продолжает работать в фоне. + { void change("tray_enabled", enabled); }} /> + + + Запускать при входе в систему + При включённой работе в трее Wizard запускается без окна. + { void change("autostart_enabled", enabled); }} /> + + + + + {saving && Применение…} + {loadError && {loadError}} + {failure && ( + <> + {failure.message} + { void change(failure.setting, failure.enabled); }}>Повторить + > + )} + + > + ); +} diff --git a/crates/wizard-gui/wizard-ui/src/settings/application_settings.ts b/crates/wizard-gui/wizard-ui/src/settings/application_settings.ts new file mode 100644 index 0000000..379ed6a --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/settings/application_settings.ts @@ -0,0 +1,45 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useEffect, useState } from "react"; + +export type ApplicationSetting = "tray_enabled" | "autostart_enabled"; +type ApplicationSettings = { + tray_enabled: boolean; + autostart_enabled: boolean; + supported: boolean; +}; +type ApplicationSettingsSnapshot = ApplicationSettings & { revision: number }; + +// The backend owns saved preferences; this hook only observes its safe IPC projection. +export function useApplicationSettings() { + const [settings, setSettings] = useState(); + const [error, setError] = useState(); + + useEffect(() => { + let stopped = false; + async function observe() { + let lastRevision: number | null = null; + while (!stopped) { + try { + const next: ApplicationSettingsSnapshot = await invoke("get_application_settings", { lastRevision }); + if (stopped) return; + setSettings(next); + setError(undefined); + lastRevision = next.revision; + } catch { + if (stopped) return; + setError("Не удалось получить настройки приложения"); + lastRevision = null; + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + } + void observe(); + return () => { stopped = true; }; + }, []); + + return { settings, error }; +} + +export function setApplicationSetting(setting: ApplicationSetting, enabled: boolean): Promise { + return invoke("set_application_setting", { setting, enabled }); +} diff --git a/crates/wizard-gui/wizard-ui/src/settings/hub_account.ts b/crates/wizard-gui/wizard-ui/src/settings/hub_account.ts index ec3a4d3..8b8019c 100644 --- a/crates/wizard-gui/wizard-ui/src/settings/hub_account.ts +++ b/crates/wizard-gui/wizard-ui/src/settings/hub_account.ts @@ -1,8 +1,9 @@ import { invoke } from "@tauri-apps/api/core"; import { useEffect, useState } from "react"; -type HubProfile = { personal_hub_name: string }; -type HubAccount = { signed_in: boolean; profile: HubProfile | null; pending: boolean; error: string | null }; +type ProfileHub = { hub_id: string; hub_name: string; display_name: string | null; is_personal: boolean }; +type HubProfile = { personal_hub_id: string; personal_hub_name: string; username: string; verified_email: string | null; hubs: ProfileHub[] }; +type HubAccount = { signed_in: boolean; profile: HubProfile | null; active_hub_id: string | null; pending: boolean; error: string | null }; type HubAccountSnapshot = HubAccount & { revision: number }; export function useHubAccount() { @@ -38,3 +39,5 @@ export function useHubAccount() { export const loginHubAccount = () => invoke("login_hub_account"); export const logoutHubAccount = () => invoke("logout_hub_account"); +export const selectHub = (hubId: string) => invoke("select_hub", { hubId }); +export const openHub = (theme: string) => invoke("open_hub", { theme }); diff --git a/crates/wizard-gui/wizard-ui/src/settings/hub_tokens.ts b/crates/wizard-gui/wizard-ui/src/settings/hub_tokens.ts index 65611b0..812f718 100644 --- a/crates/wizard-gui/wizard-ui/src/settings/hub_tokens.ts +++ b/crates/wizard-gui/wizard-ui/src/settings/hub_tokens.ts @@ -3,7 +3,7 @@ import { useEffect, useState } from "react"; // `token` values are secrets: never log or persist them. export type HubToken = { token: string; name: string; issued_at: number }; -type HubTokens = { tokens: HubToken[]; loading: boolean; error: string | null }; +type HubTokens = { hub_id: string | null; tokens: HubToken[]; loading: boolean; error: string | null }; type HubTokensSnapshot = HubTokens & { revision: number }; // Only `ready` means the list is known; `tokens` keeps the last known list for labels. @@ -17,8 +17,8 @@ export function refreshHubTokens(): Promise { return invoke("refresh_hub_tokens"); } -export function useHubTokens(): HubTokensState { - const [state, setState] = useState({ status: "loading", tokens: [] }); +export function useHubTokens(activeHubId: string | null | undefined): HubTokensState { + const [state, setState] = useState(); useEffect(() => { let stopped = false; @@ -28,13 +28,11 @@ export function useHubTokens(): HubTokensState { try { const next: HubTokensSnapshot = await invoke("get_hub_tokens_state", { lastRevision }); if (stopped) return; - setState(next.loading ? { status: "loading", tokens: next.tokens } - : next.error !== null ? { status: "error", tokens: next.tokens, error: next.error } - : { status: "ready", tokens: next.tokens }); + setState(next); lastRevision = next.revision; } catch { if (stopped) return; - setState({ status: "error", tokens: [], error: "Не удалось получить токены CoreInfra Hub" }); + setState({ hub_id: null, loading: false, tokens: [], error: "Не удалось получить токены CoreInfra Hub" }); lastRevision = null; await new Promise((resolve) => setTimeout(resolve, 1000)); } @@ -44,7 +42,12 @@ export function useHubTokens(): HubTokensState { return () => { stopped = true; }; }, []); - return state; + if (!state || (state.hub_id !== activeHubId && !(state.hub_id === null && state.error))) { + return { status: "loading", tokens: [] }; + } + if (state.loading) return { status: "loading", tokens: state.tokens }; + if (state.error !== null) return { status: "error", tokens: state.tokens, error: state.error }; + return { status: "ready", tokens: state.tokens }; } // Shown instead of the whole secret value. @@ -57,3 +60,45 @@ export function tokenLabel(token: string, tokens: HubToken[]): string { const name = tokens.find((candidate) => candidate.token === token)?.name; return name ? name : tokenPrefix(token); } + +type ConfiguredTokenInfo = { name: string; hub_id: string }; +type ConfiguredTokens = { details: (ConfiguredTokenInfo | null)[]; error: string | null }; +type ConfiguredTokensSnapshot = ConfiguredTokens & { revision: number }; + +// Only metadata is returned. Keys stay in memory and are never logged or persisted here. +export function useConfiguredTokens(tokens: string[], accountId: string | undefined) { + const [result, setResult] = useState(); + + useEffect(() => { + if (!accountId || tokens.length === 0) return; + let stopped = false; + async function observe(currentAccountId: string) { + let lastRevision: number | null = null; + while (!stopped) { + try { + const next: ConfiguredTokensSnapshot = await invoke("get_configured_token_info", { tokens, lastRevision }); + if (stopped) return; + setResult({ tokens, accountId: currentAccountId, ...next }); + lastRevision = next.revision; + } catch { + if (stopped) return; + setResult({ tokens, accountId: currentAccountId, details: [], error: "Не удалось получить сведения о ключах" }); + lastRevision = null; + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + } + void observe(accountId); + return () => { stopped = true; }; + }, [tokens, accountId]); + + const current = result?.tokens === tokens && result.accountId === accountId ? result : undefined; + return { + loading: Boolean(accountId && tokens.length > 0 && !current), + error: current?.error, + get: (token: string) => current?.details[tokens.indexOf(token)] ?? undefined, + }; +} diff --git a/crates/wizard-gui/wizard-ui/src/settings/theme.ts b/crates/wizard-gui/wizard-ui/src/settings/theme.ts new file mode 100644 index 0000000..57a0fba --- /dev/null +++ b/crates/wizard-gui/wizard-ui/src/settings/theme.ts @@ -0,0 +1,50 @@ +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { reportError } from "../logs/log"; + +export type Theme = "light" | "dark" | "system"; + +const key = "coreinfra.theme"; +const listeners = new Set<() => void>(); +let theme: Theme = "system"; +let initialized = false; +const isTheme = (value: unknown): value is Theme => + value === "light" || value === "dark" || value === "system"; + +export const getTheme = () => theme; +export function subscribeTheme(listener: () => void) { + listeners.add(listener); + return () => { listeners.delete(listener); }; +} + +function applyTheme() { + document.documentElement.dataset.theme = theme === "system" + ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" + : theme; + void getCurrentWindow().setTheme(theme === "system" ? null : theme) + .catch((cause) => reportError("Не удалось изменить тему окна", cause)); + listeners.forEach((listener) => listener()); +} + +export function setTheme(value: Theme) { + theme = value; + try { localStorage.setItem(key, value); } catch { /* Apply even without storage. */ } + applyTheme(); +} + +export function initializeTheme() { + if (initialized) return; + initialized = true; + try { + const saved = localStorage.getItem(key); + if (isTheme(saved)) theme = saved; + } catch { /* Use the system theme when storage is unavailable. */ } + applyTheme(); + window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => { + if (theme === "system") applyTheme(); + }); + window.addEventListener("storage", (event) => { + if (event.key !== key && event.key !== null) return; + theme = isTheme(event.newValue) ? event.newValue : "system"; + applyTheme(); + }); +} diff --git a/crates/wizard-gui/wizard-ui/src/styles.css b/crates/wizard-gui/wizard-ui/src/styles.css index af47602..7ef9b1e 100644 --- a/crates/wizard-gui/wizard-ui/src/styles.css +++ b/crates/wizard-gui/wizard-ui/src/styles.css @@ -1,4 +1,6 @@ @import "tailwindcss"; +@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)); +@custom-variant mac-window (&:where([data-mac-window], [data-mac-window] *)); /* Hub fonts (hub-ui/src/styles/style.css), variable upright only. */ @font-face { @@ -24,7 +26,11 @@ @layer base { :root { - color-scheme: light dark; + color-scheme: light; + } + + :root[data-theme="dark"] { + color-scheme: dark; } html { diff --git a/crates/wizard-settings/src/lib.rs b/crates/wizard-settings/src/lib.rs index 4686bc8..ddda85e 100644 --- a/crates/wizard-settings/src/lib.rs +++ b/crates/wizard-settings/src/lib.rs @@ -21,10 +21,31 @@ pub struct Settings { /// Account session, independent of agent tokens. Never expose through IPC. #[serde(skip_serializing_if = "String::is_empty")] pub hub_session: String, + /// Selected Hub for listing and creating agent tokens; empty uses the personal hub. + #[serde(skip_serializing_if = "String::is_empty")] + pub active_hub_id: String, + /// Application lifecycle preferences, independent of proxy demand. + pub application: ApplicationSettings, /// Kept last: it serializes as a TOML table, written after plain keys. pub last_paths: LastPaths, } +#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct ApplicationSettings { + pub tray_enabled: bool, + pub autostart_enabled: bool, +} + +impl Default for ApplicationSettings { + fn default() -> Self { + Self { + tray_enabled: true, + autostart_enabled: true, + } + } +} + /// Last found agent paths: first search candidates, not cached detection results. #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] @@ -104,3 +125,69 @@ pub fn update_file(edit: impl FnOnce(&mut Settings)) -> Result<()> { } save_to_file(&settings) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn application_defaults_and_partial_tables() { + for text in ["", "[last_paths]\n", "[application]\n"] { + let settings: Settings = toml_edit::de::from_str(text).expect("valid settings"); + assert!(settings.application.tray_enabled); + assert!(settings.application.autostart_enabled); + } + let settings: Settings = toml_edit::de::from_str("[application]\ntray_enabled = false\n") + .expect("partial application settings"); + assert!(!settings.application.tray_enabled); + assert!(settings.application.autostart_enabled); + assert!(Settings::default().application.tray_enabled); + assert!(Settings::default().application.autostart_enabled); + } + + #[test] + fn application_preferences_round_trip_independently_of_proxy_demand() { + for tray_enabled in [false, true] { + for autostart_enabled in [false, true] { + let settings = Settings { + application: ApplicationSettings { + tray_enabled, + autostart_enabled, + }, + claude_proxy_enabled: Some("fixture".into()), + ..Settings::default() + }; + let text = toml_edit::ser::to_string_pretty(&settings).expect("serialize settings"); + let restored: Settings = toml_edit::de::from_str(&text).expect("read settings"); + assert_eq!(restored.application.tray_enabled, tray_enabled); + assert_eq!(restored.application.autostart_enabled, autostart_enabled); + assert!(restored.local_proxy_enabled()); + } + } + } + + #[test] + fn existing_settings_default_to_personal_hub() { + let settings: Settings = toml_edit::de::from_str("hub_session = 'session'\n[last_paths]\n") + .expect("settings without a selected hub should deserialize"); + assert!(settings.active_hub_id.is_empty()); + } + + #[test] + fn selected_hub_round_trips_with_discovered_paths() { + let settings = Settings { + active_hub_id: "team".into(), + last_paths: LastPaths { + codex: Some(PathBuf::from("/usr/local/bin/codex")), + ..LastPaths::default() + }, + ..Settings::default() + }; + let text = toml_edit::ser::to_string_pretty(&settings) + .expect("settings with a selected hub and paths should serialize"); + let restored: Settings = + toml_edit::de::from_str(&text).expect("serialized settings should deserialize"); + assert_eq!(restored.active_hub_id, "team"); + assert_eq!(restored.last_paths.codex, settings.last_paths.codex); + } +}