Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(desktop): wait for bundled bootstrap URL (#3092)

Max562f5b6b55f4
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
index 75bc19079..68ad77815 100644
--- a/desktop/runtime-host/src/lib.rs
+++ b/desktop/runtime-host/src/lib.rs
@@ -49,7 +49,10 @@ pub use launcher::{
LaunchWatch, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher, DESKTOP_BACKENDS_ROOT_ENV,
DESKTOP_NPM_CLI_ENV, DESKTOP_RUNTIME_ROOT_ENV, UV_TOOL_BIN_DIR_ENV, VIBE_PATH_ENV,
};
-pub use origin::{is_shell_ui_url, LoopbackOrigin, OriginError, DEV_SERVER_PORT};
+pub use origin::{
+ is_shell_ui_url, wait_for_shell_ui_url, LoopbackOrigin, OriginError, ShellUiUrlWaitError, DEV_SERVER_PORT,
+ SHELL_UI_URL_TIMEOUT,
+};
pub use private_runtime::{PrivateRuntimeBundle, PrivateRuntimeError, RuntimeBundleManifest};
pub use status::{BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus};
diff --git a/desktop/runtime-host/src/origin.rs b/desktop/runtime-host/src/origin.rs
index cae3c67ea..e9012969f 100644
--- a/desktop/runtime-host/src/origin.rs
+++ b/desktop/runtime-host/src/origin.rs
@@ -13,6 +13,8 @@
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
+use std::thread;
+use std::time::{Duration, Instant};
use url::{Host, Url};
@@ -20,6 +22,12 @@ use url::{Host, Url};
/// Must match `desktop/vite.config.ts` and `build.devUrl` in `tauri.conf.json`.
pub const DEV_SERVER_PORT: u16 = 1420;
+/// The bundled WebView may report its initial document before Tauri's local
+/// asset URL has committed. Keep setup bounded while allowing that transition
+/// to complete.
+pub const SHELL_UI_URL_TIMEOUT: Duration = Duration::from_secs(5);
+const SHELL_UI_URL_POLL_INTERVAL: Duration = Duration::from_millis(10);
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum OriginError {
#[error("The desktop origin is empty.")]
@@ -171,6 +179,48 @@ pub fn is_shell_ui_url(url: &Url) -> bool {
}
}
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum ShellUiUrlWaitError {
+ #[error("failed to read the desktop window URL: {0}")]
+ Read(String),
+ #[error("the Avibe desktop window did not load its bundled bootstrap page before timeout; last URL: {last_url}")]
+ TimedOut { last_url: String },
+}
+
+/// Returns the first shell URL reported by a WebView, allowing transient
+/// non-shell URLs while its bundled document commits.
+///
+/// The URL reader is injected so the timing contract can be tested without a
+/// native WebView. A timeout still performs one final read, making the error
+/// name the URL observed at the end of the bounded wait.
+pub fn wait_for_shell_ui_url<F>(mut read_url: F, timeout: Duration) -> Result<Url, ShellUiUrlWaitError>
+where
+ F: FnMut() -> Result<Url, String>,
+{
+ let deadline = Instant::now() + timeout;
+
+ loop {
+ let url = read_url().map_err(ShellUiUrlWaitError::Read)?;
+ if is_shell_ui_url(&url) {
+ return Ok(url);
+ }
+ let last_url = display_url(&url);
+
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return Err(ShellUiUrlWaitError::TimedOut { last_url });
+ }
+ thread::sleep(SHELL_UI_URL_POLL_INTERVAL.min(remaining));
+ }
+}
+
+fn display_url(url: &Url) -> String {
+ let mut display = url.clone();
+ display.set_query(None);
+ display.set_fragment(None);
+ display.to_string()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -336,6 +386,59 @@ mod tests {
assert!(!is_shell_ui_url(&other));
}
+ #[test]
+ fn an_already_committed_shell_url_proceeds_without_polling() {
+ let shell = Url::parse("http://tauri.localhost/index.html").expect("test URL parses");
+ let mut reads = 0;
+
+ let result = wait_for_shell_ui_url(
+ || {
+ reads += 1;
+ Ok(shell.clone())
+ },
+ Duration::from_secs(1),
+ );
+
+ assert_eq!(result, Ok(shell));
+ assert_eq!(reads, 1);
+ }
+
+ #[test]
+ fn a_transient_non_shell_url_is_rechecked_until_the_shell_commits() {
+ let mut urls = [
+ "about:blank",
+ "http://127.0.0.1:5123/",
+ "http://tauri.localhost/index.html",
+ ]
+ .into_iter()
+ .map(|raw| Url::parse(raw).expect("test URL parses"));
+
+ let result = wait_for_shell_ui_url(
+ || Ok(urls.next().expect("the reader is called only until success")),
+ Duration::from_secs(1),
+ );
+
+ assert_eq!(
+ result,
+ Ok(Url::parse("http://tauri.localhost/index.html").expect("test URL parses"))
+ );
+ }
+
+ #[test]
+ fn a_timeout_reports_the_last_url_without_query_or_fragment() {
+ let last = Url::parse("http://127.0.0.1:5123/loading?token=secret#fragment").expect("test URL parses");
+
+ let error = wait_for_shell_ui_url(|| Ok(last.clone()), Duration::from_millis(25))
+ .expect_err("a non-shell URL must time out");
+
+ assert_eq!(
+ error,
+ ShellUiUrlWaitError::TimedOut {
+ last_url: "http://127.0.0.1:5123/loading".to_owned(),
+ }
+ );
+ }
+
/// The port the shell's own UI is served from is the one loopback port a
/// Runtime must never be reached at: a page there would be classified as
/// *local* by Tauri and would keep the bootstrap commands after navigation.
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 7daa6ee8f..89f44aaa8 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -45,8 +45,8 @@ use avibe_runtime_host::default_runtime_host;
#[cfg(feature = "bundled-runtime")]
use avibe_runtime_host::{bundled_runtime_host, BootstrapLog, RemovalOutcome, BOOTSTRAP_LOG_NAME};
use avibe_runtime_host::{
- is_shell_ui_url, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, BootstrapTrigger,
- CliOutcome, LoopbackOrigin, RuntimeHost, StatusSink,
+ is_shell_ui_url, wait_for_shell_ui_url, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus,
+ BootstrapTrigger, CliOutcome, LoopbackOrigin, RuntimeHost, StatusSink, SHELL_UI_URL_TIMEOUT,
};
use serde::Deserialize;
use tauri::menu::{CheckMenuItem, Menu, MenuItem, MenuItemKind, PredefinedMenuItem, Submenu};
@@ -323,11 +323,11 @@ struct Shell {
dialog_pending: AtomicBool,
exit_authorized: AtomicBool,
exit_cleanup_started: AtomicBool,
- bootstrap_url: Url,
+ bootstrap_url: Arc<Mutex<Option<Url>>>,
}
impl Shell {
- fn new(host: RuntimeHost, bootstrap_url: Url) -> Self {
+ fn new(host: RuntimeHost) -> Self {
Self {
host: Arc::new(host),
latest: Arc::new(Mutex::new(None)),
@@ -338,9 +338,25 @@ impl Shell {
dialog_pending: AtomicBool::new(false),
exit_authorized: AtomicBool::new(false),
exit_cleanup_started: AtomicBool::new(false),
- bootstrap_url,
+ bootstrap_url: Arc::new(Mutex::new(None)),
}
}
+
+ fn set_bootstrap_url(&self, bootstrap_url: Url) -> bool {
+ self.bootstrap_url
+ .lock()
+ .map(|mut current| {
+ *current = Some(bootstrap_url);
+ })
+ .is_ok()
+ }
+
+ fn is_bootstrap_ready(&self) -> bool {
+ self.bootstrap_url
+ .lock()
+ .map(|current| current.is_some())
+ .unwrap_or(false)
+ }
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -859,6 +875,14 @@ fn exit_shell(app: &AppHandle) {
app.exit(0);
}
+fn exit_shell_with_code(app: &AppHandle, code: i32) {
+ if !claim_exit_cleanup(app) {
+ return;
+ }
+ authorize_exit(app);
+ app.exit(code);
+}
+
fn claim_exit_cleanup(app: &AppHandle) -> bool {
claim_exit_cleanup_flag(&app.state::<Shell>().exit_cleanup_started)
}
@@ -1344,6 +1368,9 @@ fn computer_use_guide_controller(window: &WebviewWindow) -> Result<tauri::State<
/// The return value is part of the retry contract: the bootstrap page must not
/// hide its Retry action when another run still owns the activity.
fn spawn_bootstrap(app: AppHandle, trigger: BootstrapTrigger) -> bool {
+ if !app.state::<Shell>().is_bootstrap_ready() {
+ return false;
+ }
let activity = app.state::<Shell>().activity.clone();
if activity
.compare_exchange(ACTIVITY_IDLE, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
@@ -1596,9 +1623,14 @@ fn return_to_bootstrap(app: &AppHandle) -> bool {
/// Restores the exact bootstrap URL captured before the first navigation. It is
/// a bundled Tauri page in production and the fixed Vite dev URL in development.
fn restore_bootstrap_view(app: &AppHandle) -> bool {
- let (bootstrap_url, latest) = {
+ let (Some(bootstrap_url), latest) = ({
let shell = app.state::<Shell>();
- (shell.bootstrap_url.clone(), shell.latest.clone())
+ (
+ shell.bootstrap_url.lock().ok().and_then(|url| url.clone()),
+ shell.latest.clone(),
+ )
+ }) else {
+ return false;
};
if !is_shell_ui_url(&bootstrap_url) {
return false;
@@ -1678,6 +1710,33 @@ fn ensure_main_window(app: &AppHandle) -> Option<WebviewWindow> {
Some(window)
}
+fn start_bootstrap_when_shell_url_ready(
+ app: AppHandle,
+ window: WebviewWindow,
+ #[cfg(feature = "bundled-runtime")] bootstrap_log: BootstrapLog,
+) {
+ tauri::async_runtime::spawn_blocking(move || {
+ let result = wait_for_shell_ui_url(|| window.url().map_err(|error| error.to_string()), SHELL_UI_URL_TIMEOUT);
+ match result {
+ Ok(bootstrap_url) => {
+ if !app.state::<Shell>().set_bootstrap_url(bootstrap_url) {
+ eprintln!("the Avibe desktop shell could not store its bundled bootstrap URL");
+ exit_shell_with_code(&app, 101);
+ return;
+ }
+ updater::check(app.clone(), false);
+ let _ = spawn_bootstrap(app, BootstrapTrigger::Launch);
+ }
+ Err(error) => {
+ #[cfg(feature = "bundled-runtime")]
+ bootstrap_log.record("shell.bootstrap_url", &[("error", error.to_string())]);
+ eprintln!("{error}");
+ exit_shell_with_code(&app, 101);
+ }
+ }
+ });
+}
+
/// Tells the Workbench, before any of its scripts run, that it is rendered by
/// this shell rather than a browser tab or a PWA: it hides what the shell cannot
/// do (a pre-opened `about:blank` tab never exists here). Top-level document only;
@@ -2374,14 +2433,8 @@ pub fn run() {
let window = ensure_main_window(app.handle()).ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::NotFound, "the Avibe desktop window is missing")
})?;
- let bootstrap_url = window.url()?;
- if !is_shell_ui_url(&bootstrap_url) {
- return Err(std::io::Error::new(
- std::io::ErrorKind::PermissionDenied,
- "the Avibe desktop window did not load its bundled bootstrap page",
- )
- .into());
- }
+ #[cfg(feature = "bundled-runtime")]
+ let bootstrap_log = BootstrapLog::at(app.path().app_local_data_dir()?.join(BOOTSTRAP_LOG_NAME));
let host = {
#[cfg(feature = "bundled-runtime")]
{
@@ -2389,9 +2442,7 @@ pub fn run() {
app.path().resource_dir()?.join("runtime"),
app.path().app_local_data_dir()?.join("runtime"),
app.path().app_local_data_dir()?.join("backends"),
- // Beside the Runtime it describes, so a user asked for
- // "the log next to your Avibe runtime folder" finds it.
- BootstrapLog::at(app.path().app_local_data_dir()?.join(BOOTSTRAP_LOG_NAME)),
+ bootstrap_log.clone(),
)?
}
#[cfg(not(feature = "bundled-runtime"))]
@@ -2399,7 +2450,7 @@ pub fn run() {
default_runtime_host()?
}
};
- app.manage(Shell::new(host, bootstrap_url));
+ app.manage(Shell::new(host));
#[cfg(target_os = "macos")]
app.manage(computer_use::Controller::start(app.handle()));
app.manage(notifications::Notifications::new(
@@ -2428,8 +2479,10 @@ pub fn run() {
pet::apply_shortcuts(app.handle());
#[cfg(target_os = "macos")]
refresh_computer_use_control(app.handle());
- updater::check(app.handle().clone(), false);
- let _ = spawn_bootstrap(app.handle().clone(), BootstrapTrigger::Launch);
+ #[cfg(feature = "bundled-runtime")]
+ start_bootstrap_when_shell_url_ready(app.handle().clone(), window, bootstrap_log);
+ #[cfg(not(feature = "bundled-runtime"))]
+ start_bootstrap_when_shell_url_ready(app.handle().clone(), window);
Ok(())
})
.run(tauri::generate_context!())
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index ab1ee570b..b76d50176 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -605,7 +605,8 @@ fn post_navigation_recovery_stays_in_the_unprivileged_rust_shell() {
// Handing a predecessor's Runtime over stops it, so only the app launch and
// the user's Try again may ask for it; every recovery path must not.
assert_eq!(source.matches("BootstrapTrigger::Launch").count(), 1);
- assert!(source.contains("spawn_bootstrap(app.handle().clone(), BootstrapTrigger::Launch)"));
+ assert!(source.contains("start_bootstrap_when_shell_url_ready"));
+ assert!(source.contains("spawn_bootstrap(app, BootstrapTrigger::Launch)"));
assert_eq!(source.matches("BootstrapTrigger::Retry").count(), 1);
assert!(source.contains("Ok(spawn_bootstrap(app, BootstrapTrigger::Retry))"));
assert!(
@@ -959,6 +960,31 @@ fn every_quit_boundary_reuses_one_bounded_computer_use_cleanup() {
);
}
+#[test]
+fn fatal_startup_exit_authorizes_tauri_exit_code() {
+ let source = shipping_source("src/lib.rs");
+ let fatal_exit = source
+ .split("fn exit_shell_with_code(")
+ .nth(1)
+ .expect("fatal shell exit helper")
+ .split("fn claim_exit_cleanup(")
+ .next()
+ .expect("fatal shell exit body");
+ assert!(fatal_exit.contains("if !claim_exit_cleanup(app)"));
+ assert!(fatal_exit.contains("authorize_exit(app)"));
+ assert!(fatal_exit.contains("app.exit(code)"));
+
+ let bootstrap = source
+ .split("fn start_bootstrap_when_shell_url_ready(")
+ .nth(1)
+ .expect("startup bootstrap handoff")
+ .split("/// Tells the Workbench")
+ .next()
+ .expect("startup bootstrap body");
+ assert_eq!(bootstrap.matches("exit_shell_with_code(&app, 101)").count(), 2);
+ assert!(!bootstrap.contains("app.exit(101)"));
+}
+
#[test]
fn native_tray_copy_has_locale_and_placeholder_parity() {
let root = crate_dir().join("../../ui/src/i18n");
@@ -1146,7 +1172,7 @@ fn updates_have_one_native_owner_and_one_scoped_workbench_control_path() {
// The shell downloads and verifies updates itself; the Workbench only
// invokes the shell's existing state machine.
assert!(!source.contains("tauri_plugin_updater"));
- assert!(source.contains("updater::check(app.handle().clone(), false)"));
+ assert!(source.contains("updater::check(app.clone(), false)"));
assert!(source.contains("updater::MENU_ID =>"));
assert!(source.contains("url.as_str() == updater::OPEN_URL"));
assert!(updater.contains("MessageDialogButtons::YesNoCancelCustom"));