Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 <https://mozilla.org/MPL/2.0/>.
Expand Down
104 changes: 92 additions & 12 deletions crates/wizard-core/src/hub/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
}
}
}
}
Expand Down Expand Up @@ -103,13 +106,9 @@ pub async fn fetch_profile(
struct ProfileResponse {
personal_hub_id: String,
hubs: Vec<ProfileHub>,
}

#[derive(Deserialize)]
struct ProfileHub {
hub_id: String,
hub_name: String,
display_name: Option<String>,
#[serde(default)]
username: String,
verified_email: Option<String>,
}

let (update, response) =
Expand All @@ -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)
Expand Down Expand Up @@ -185,10 +188,33 @@ async fn request<T: DeserializeOwned>(
/// 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<ProfileHub>,
pub username: String,
pub verified_email: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProfileHub {
pub hub_id: String,
pub hub_name: String,
pub display_name: Option<String>,
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.
Expand Down Expand Up @@ -291,3 +317,57 @@ fn session_from_headers(headers: &HeaderMap) -> Result<Option<String>, ()> {
}
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");
}
}
2 changes: 2 additions & 0 deletions crates/wizard-gui/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"windows": ["main", "logs"],
"permissions": [
"core:default",
"core:window:allow-set-theme",
"core:window:allow-start-dragging",
"log:allow-log"
]
}
84 changes: 73 additions & 11 deletions crates/wizard-gui/src/hub_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,19 +95,27 @@ pub(crate) struct HubAccount {
signed_in: bool,
/// Absent until loaded from Hub, or when loading failed.
profile: Option<HubProfile>,
active_hub_id: Option<String>,
pending: bool,
error: Option<String>,
}

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<String>) -> 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::<HubProfileState>().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::<HubProfileState>().lock().clone())
.flatten(),
profile,
active_hub_id,
pending,
error,
}
Expand All @@ -130,7 +138,11 @@ pub(crate) async fn load_profile(app: &tauri::AppHandle) -> Result<HubProfile, H

let (sent, profile) = hub_tokens::with_session(app, |client, session| async move {
let (update, profile) = hub::fetch_profile(&client, &session).await;
(update, profile.map(|profile| (session, profile)))
let current_session = match &update {
hub::SessionUpdate::Refreshed(refreshed) => refreshed.clone(),
_ => session,
};
(update, profile.map(|profile| (current_session, profile)))
})
.await?;
let current = settings::get_state(app).map(|s| s.hub_session);
Expand Down Expand Up @@ -199,16 +211,63 @@ pub(crate) async fn logout_hub_account(app: tauri::AppHandle) -> Result<(), Stri
if !matches!(*app.state::<HubAuth>().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);
publish(&app, false, None);
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::<RevisionSignal<HubAccount>>().update(|account| {
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading