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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(desktop): use the Workbench update popover (#3013)
Maxf225b7a0b3ab
diff --git a/desktop/README.md b/desktop/README.mdindex e010e01c1..33d99ebf5 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -557,11 +557,23 @@ from unit/contract tests.## Signed desktop updates (G2)-The native **Check for Desktop Updates…** entry is the sole update owner. The-Workbench version badge in a desktop window opens that same entry and shows the-build-injected desktop version. Startup only checks; a native **Download and-Install** confirmation authorizes download and replacement. The tray/menu shows-checking, current, available, downloading, installing, disabled, and error states.+The native updater remains the sole update owner, while the Workbench version+badge is its user interface. In a desktop window the badge turns yellow when a+signed release is available and opens the Workbench popover. The native+**Check for Desktop Updates…** menu item and `avibe://updates` deep link open the+same popover and start an explicit check. The popover asks for confirmation+before download and replacement, and offers **Skip this version**. Startup+checks silently and lets the badge provide the prompt. A native dialog is used+only when there is no reachable Workbench window or the fixed popover event+cannot be dispatched, such as a check that finishes before the webview loads.+Native state changes are pushed to the Workbench, including checks started by+the **Use TEST Updates** menu item. The state marks whether an available release+came from an explicit check, so an automatic check honors **Skip this version**+while an explicit check can offer the same release again. If a newer Workbench+runs under an older shell that rejects `desktop_update_state`, the Workbench+uses Runtime version reads and the legacy `avibe://updates` native path until+the shell is upgraded. The tray/menu shows checking, current, available,+downloading, installing, disabled, and error states.The **Use TEST Updates** toggle persists beside the private Runtime, defaults onfor prerelease app versions and off for stable versions, and never downgrades.Browsers and Python installations retain their existing update behavior.diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rsindex b69547b3d..dbb97b664 100644--- a/desktop/src-tauri/build.rs+++ b/desktop/src-tauri/build.rs@@ -14,6 +14,10 @@ fn main() {"open_install_docs","computer_use_enable","computer_use_open_permission",+ "desktop_update_state",+ "desktop_update_check",+ "desktop_update_install",+ "desktop_update_skip","pet_ready","pet_set_expanded","pet_drag",diff --git a/desktop/src-tauri/capabilities/main-desktop-update.json b/desktop/src-tauri/capabilities/main-desktop-update.jsonnew file mode 100644index 000000000..c83968081--- /dev/null+++ b/desktop/src-tauri/capabilities/main-desktop-update.json@@ -0,0 +1,17 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "main-desktop-update",+ "description": "The Workbench's desktop update popover: read the shell updater state, check for updates, and start the signed install or skip flow. Granted to the main window for the loopback Runtime origin only, never to the bundled bootstrap page.",+ "local": false,+ "windows": ["main"],+ "remote": {+ "urls": ["http://127.0.0.1:*/*", "http://[\\:\\:1]:*/*"]+ },+ "permissions": [+ "core:event:default",+ "allow-desktop-update-state",+ "allow-desktop-update-check",+ "allow-desktop-update-install",+ "allow-desktop-update-skip"+ ]+}diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_update_check.toml b/desktop/src-tauri/permissions/autogenerated/desktop_update_check.tomlnew file mode 100644index 000000000..15b39c872--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/desktop_update_check.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-desktop-update-check"+description = "Enables the desktop_update_check command without any pre-configured scope."+commands.allow = ["desktop_update_check"]++[[permission]]+identifier = "deny-desktop-update-check"+description = "Denies the desktop_update_check command without any pre-configured scope."+commands.deny = ["desktop_update_check"]diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_update_install.toml b/desktop/src-tauri/permissions/autogenerated/desktop_update_install.tomlnew file mode 100644index 000000000..24457aa02--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/desktop_update_install.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-desktop-update-install"+description = "Enables the desktop_update_install command without any pre-configured scope."+commands.allow = ["desktop_update_install"]++[[permission]]+identifier = "deny-desktop-update-install"+description = "Denies the desktop_update_install command without any pre-configured scope."+commands.deny = ["desktop_update_install"]diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_update_skip.toml b/desktop/src-tauri/permissions/autogenerated/desktop_update_skip.tomlnew file mode 100644index 000000000..e2e7a1761--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/desktop_update_skip.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-desktop-update-skip"+description = "Enables the desktop_update_skip command without any pre-configured scope."+commands.allow = ["desktop_update_skip"]++[[permission]]+identifier = "deny-desktop-update-skip"+description = "Denies the desktop_update_skip command without any pre-configured scope."+commands.deny = ["desktop_update_skip"]diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_update_state.toml b/desktop/src-tauri/permissions/autogenerated/desktop_update_state.tomlnew file mode 100644index 000000000..94bef4fee--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/desktop_update_state.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-desktop-update-state"+description = "Enables the desktop_update_state command without any pre-configured scope."+commands.allow = ["desktop_update_state"]++[[permission]]+identifier = "deny-desktop-update-state"+description = "Denies the desktop_update_state command without any pre-configured scope."+commands.deny = ["desktop_update_state"]diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 6a24c9bd8..a6632ea03 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -96,6 +96,13 @@ const SETTINGS_DEEP_LINK: &str = "avibe://settings";/// A Workbench that handles it cancels it; an uncancelled one falls back to/// loading the deep link's destination.const OPEN_SETTINGS_EVENT: &str = "avibe:desktop-open-settings";+/// The in-page request to open the Version popover, read by+/// `ui/src/lib/desktopShell.ts`. An uncancelled request falls back to the+/// native updater dialog when the Workbench cannot receive it.+const OPEN_UPDATES_EVENT: &str = "avibe:desktop-open-updates";+/// Internal shell-only target used when an adopted Workbench has no listener+/// for `OPEN_UPDATES_EVENT`. It is intercepted before any page can navigate.+pub(crate) const OPEN_UPDATES_FALLBACK_URL: &str = "avibe://updates-fallback";/// Where a relaunch after a guide-driven Screen Recording grant returns.#[cfg(target_os = "macos")]const COMPUTER_USE_SETUP_DEEP_LINK: &str = "avibe://settings/computer-use";@@ -108,6 +115,9 @@ const UNINSTALL_MENU_ID: &str = "uninstall-private-runtime";const EN_PRODUCT_CATALOG: &str = include_str!("../../../ui/src/i18n/en.json");const ZH_PRODUCT_CATALOG: &str = include_str!("../../../ui/src/i18n/zh.json");+#[derive(Default)]+struct PendingDesktopUpdateOpen(AtomicBool);+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct ProductCatalog {@@ -590,6 +600,36 @@ fn open_settings_script() -> String {)}+fn open_updates_script() -> String {+ format!(+ "window.__AVIBE_DESKTOP_UPDATES_HANDLED__ = false; \+ window.dispatchEvent(new Event('{OPEN_UPDATES_EVENT}', {{ cancelable: true }})); \+ if (!window.__AVIBE_DESKTOP_UPDATES_HANDLED__) window.location.assign('{OPEN_UPDATES_FALLBACK_URL}');"+ )+}++/// Ask the current Workbench to open its desktop update popover. Returning+/// `false` is the documented fallback boundary: the shell has no reachable+/// Workbench window, or the page rejected the script.+fn open_desktop_updates(app: &AppHandle) -> bool {+ let Some(window) = app.get_webview_window(MAIN_WINDOW) else {+ return false;+ };+ if !pet::is_workbench(&window) {+ return false;+ }+ focus_or_restore_main_window(app);+ window.eval(open_updates_script()).is_ok()+}++fn request_desktop_updates(app: &AppHandle) {+ app.state::<PendingDesktopUpdateOpen>().0.store(true, Ordering::SeqCst);+}++fn take_desktop_update_request(app: &AppHandle) -> bool {+ app.state::<PendingDesktopUpdateOpen>().0.swap(false, Ordering::SeqCst)+}+fn refresh_runtime_tray(app: &AppHandle, state: TrayRuntimeState) {refresh_native_controls(app, Some(state));}@@ -1717,13 +1757,29 @@ fn focus_or_restore_main_window(app: &AppHandle) {}fn receive_native_deep_link(app: &AppHandle, arguments: impl IntoIterator<Item = impl AsRef<str>>) {+ let mut updates_requested = false;+ let mut workbench_arguments = Vec::new();+ for argument in arguments {+ let argument = argument.as_ref();+ if argument == updater::OPEN_URL {+ updates_requested = true;+ } else {+ workbench_arguments.push(argument.to_owned());+ }+ }+ if updates_requested {+ request_desktop_updates(app);+ }if let Ok(mut links) = app.state::<Mutex<DeepLinks>>().lock() {- links.receive(arguments);+ links.receive(workbench_arguments);}if app.try_state::<Shell>().is_none() {return;}focus_or_restore_main_window(app);+ if updates_requested && open_desktop_updates(app) {+ let _ = take_desktop_update_request(app);+ }apply_pending_deep_link(app);}@@ -2069,6 +2125,7 @@ fn request_private_runtime_removal(app: AppHandle) {pub fn run() {let builder = tauri::Builder::default().manage(Mutex::new(DeepLinks::default()))+ .manage(PendingDesktopUpdateOpen::default())// Registered first, as the plugin documents: a second launch is handed to// the running shell instead of starting a competing Runtime..plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {@@ -2109,7 +2166,11 @@ pub fn run() {match event.id().as_ref() {OPEN_MENU_ID => focus_or_restore_main_window(app),SETTINGS_MENU_ID => open_workbench_settings(app),- updater::MENU_ID => updater::check(app.clone(), true),+ updater::MENU_ID => {+ if !open_desktop_updates(app) {+ updater::check(app.clone(), true);+ }+ }updater::CHANNEL_ID => updater::toggle_channel(app),LOGIN_MENU_ID => toggle_start_at_login(app),notifications::MENU_ID => {@@ -2144,6 +2205,11 @@ pub fn run() {#[cfg(target_os = "macos")]macos_title_bar::sync(webview);apply_pending_deep_link(webview.app_handle());+ if take_desktop_update_request(webview.app_handle())+ && !open_desktop_updates(webview.app_handle())+ {+ updater::check(webview.app_handle().clone(), true);+ }// Settings become available the moment a Workbench is on// screen, not at the monitor's first tick. The shared// rule still decides, so a bootstrap page enables nothing.@@ -2155,6 +2221,12 @@ pub fn run() {return pet::navigation_allowed(webview.app_handle(), url);}if webview.label() == MAIN_WINDOW && url.as_str() == updater::OPEN_URL {+ if !open_desktop_updates(webview.app_handle()) {+ updater::check(webview.app_handle().clone(), true);+ }+ return false;+ }+ if webview.label() == MAIN_WINDOW && url.as_str() == OPEN_UPDATES_FALLBACK_URL {updater::check(webview.app_handle().clone(), true);return false;}@@ -2228,6 +2300,10 @@ pub fn run() {open_install_docs,computer_use_enable,computer_use_open_permission,+ updater::desktop_update_state,+ updater::desktop_update_check,+ updater::desktop_update_install,+ updater::desktop_update_skip,pet::pet_ready,pet::pet_set_expanded,pet::pet_drag,@@ -2282,11 +2358,14 @@ pub fn run() {if computer_use::take_setup_resume(app.handle()) {links.receive([COMPUTER_USE_SETUP_DEEP_LINK]);}- links.receive(- std::env::args_os()- .skip(1)- .filter_map(|argument| argument.into_string().ok()),- );+ let arguments: Vec<String> = std::env::args_os()+ .skip(1)+ .filter_map(|argument| argument.into_string().ok())+ .collect();+ if arguments.iter().any(|argument| argument == updater::OPEN_URL) {+ request_desktop_updates(app.handle());+ }+ links.receive(arguments.into_iter().filter(|argument| argument != updater::OPEN_URL));}updater::init(app.handle())?;install_native_tray(app.handle())?;@@ -2329,6 +2408,16 @@ mod tests {);}+ #[test]+ fn the_updates_request_is_a_cancelable_workbench_event() {+ assert_eq!(+ open_updates_script(),+ "window.__AVIBE_DESKTOP_UPDATES_HANDLED__ = false; \+ window.dispatchEvent(new Event('avibe:desktop-open-updates', { cancelable: true })); \+ if (!window.__AVIBE_DESKTOP_UPDATES_HANDLED__) window.location.assign('avibe://updates-fallback');"+ );+ }+#[test]fn a_control_refresh_without_a_status_keeps_the_status_already_shown() {let unreachable = TrayRuntimeState::Unreachable;diff --git a/desktop/src-tauri/src/pet.rs b/desktop/src-tauri/src/pet.rsindex 9b72ffd79..17560a516 100644--- a/desktop/src-tauri/src/pet.rs+++ b/desktop/src-tauri/src/pet.rs@@ -1110,7 +1110,7 @@ pub fn pet_unbind(window: WebviewWindow, session_id: String) -> Result<PetBindin#[tauri::command]pub fn pet_open(window: WebviewWindow, link: String) -> Result<(), String> {ensure_pet_page(&window)?;- if parse_deep_link(&link).is_none() {+ if link != crate::updater::OPEN_URL && parse_deep_link(&link).is_none() {return Err("Not an Avibe link.".to_owned());}let app = window.app_handle().clone();diff --git a/desktop/src-tauri/src/updater.rs b/desktop/src-tauri/src/updater.rsindex 6fad4b0d2..7bd80cc35 100644--- a/desktop/src-tauri/src/updater.rs+++ b/desktop/src-tauri/src/updater.rs@@ -1,12 +1,12 @@-//! Native-only desktop updater. Remote WebViews never receive updater commands.+//! Desktop updater owned by the native shell and controlled by its Workbench popover.use avibe_runtime_host::{download::{self, Length},update::{self, Channel, Manifest, Release, REPOSITORY},update_status::{UpdateStatusPhase, UpdateStatusRecord, UpdateStatusStore, UPDATE_STATUS_FILE},};-use serde::Deserialize;+use serde::{Deserialize, Serialize};use std::{- path::PathBuf,+ path::{Path, PathBuf},sync::{atomic::{AtomicBool, AtomicUsize, Ordering},Mutex,@@ -15,13 +15,14 @@ use std::{};use tauri::{menu::{CheckMenuItem, MenuItem},- AppHandle, Manager,+ AppHandle, Emitter, Manager, WebviewWindow,};use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};pub const MENU_ID: &str = "desktop-update";pub const CHANNEL_ID: &str = "desktop-update-test";pub const OPEN_URL: &str = "avibe://updates";+pub const STATE_EVENT: &str = "avibe:desktop-update-state";const KEY: &str = match option_env!("AVIBE_DESKTOP_UPDATER_PUBLIC_KEY") {Some(key) => key,None => "",@@ -64,7 +65,8 @@ fn catalog() -> Catalog {super::native_catalog_for_locales(sys_locale::get_locales()).updater}-#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]enum Phase {Idle,Checking,@@ -80,6 +82,18 @@ struct State {phase: Phase,latest: Option<String>,channel: Channel,+ manifest: Option<Manifest>,+ availability_interactive: bool,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DesktopUpdateState {+ phase: Phase,+ latest: Option<String>,+ channel: Channel,+ skipped_version: Option<String>,+ interactive: bool,}pub struct Updater {state: Mutex<State>,@@ -142,6 +156,8 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {phase: Phase::Idle,latest: None,channel,+ manifest: None,+ availability_interactive: false,}),busy: AtomicBool::new(false),source: AtomicUsize::new(0),@@ -162,15 +178,63 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {}fn set_state(app: &AppHandle, phase: Phase, latest: Option<String>) {let updater = app.state::<Updater>();- let mut state = updater.state.lock().expect("updater state");- state.phase = phase;- if latest.is_some() || phase == Phase::Checking {- state.latest = latest;+ {+ let mut state = updater.state.lock().expect("updater state");+ state.phase = phase;+ if matches!(phase, Phase::Checking | Phase::Current | Phase::Disabled | Phase::Error) {+ state.manifest = None;+ }+ if !matches!(+ phase,+ Phase::Available | Phase::Checking | Phase::Downloading | Phase::Installing+ ) {+ state.availability_interactive = false;+ }+ if latest.is_some() || phase == Phase::Checking {+ state.latest = latest;+ }}let _ = updater.menu.set_text(format!("{} — {}", label(phase, &catalog()), app.package_info().version));let _ = updater.channel_menu.set_enabled(!updater.busy.load(Ordering::SeqCst));+ emit_state(app);+}++fn state_snapshot(app: &AppHandle) -> DesktopUpdateState {+ let updater = app.state::<Updater>();+ let state = updater.state.lock().expect("updater state");+ DesktopUpdateState {+ phase: state.phase,+ latest: state.latest.clone(),+ channel: state.channel,+ skipped_version: skipped_version(&updater),+ interactive: state.availability_interactive,+ }+}++fn emit_state(app: &AppHandle) {+ let _ = app.emit_to(super::MAIN_WINDOW, STATE_EVENT, state_snapshot(app));+}++fn ensure_workbench(window: &WebviewWindow) -> Result<(), String> {+ if super::pet::is_workbench(window) {+ Ok(())+ } else {+ Err("This command is only available to the Avibe Workbench.".to_owned())+ }+}++fn workbench_ready(app: &AppHandle) -> bool {+ app.get_webview_window("main")+ .is_some_and(|window| super::pet::is_workbench(&window))+}++fn set_available(app: &AppHandle, manifest: Manifest) {+ let latest = manifest.version.clone();+ set_state(app, Phase::Available, Some(latest));+ app.state::<Updater>().state.lock().expect("updater state").manifest = Some(manifest);+ emit_state(app);}pub fn toggle_channel(app: &AppHandle) {let updater = app.state::<Updater>();@@ -195,6 +259,7 @@ pub fn toggle_channel(app: &AppHandle) {show(app, &catalog().check_failed, None);return;}+ emit_state(app);check(app.clone(), true);}fn show(app: &AppHandle, message: &str, latest: Option<&str>) {@@ -232,16 +297,19 @@ fn skipped_version(updater: &Updater) -> Option<String> {}fn skip_version(app: &AppHandle, version: &str) {let path = &app.state::<Updater>().skipped_path;- let result = path- .parent()- .ok_or_else(|| std::io::Error::other("missing config directory"))- .and_then(std::fs::create_dir_all)- .and_then(|()| std::fs::write(path, serde_json::to_vec(version).expect("version JSON")));+ let result = persist_skipped_version(path, version);if let Err(error) = result {eprintln!("desktop update skip: {error}");}}+fn persist_skipped_version(path: &Path, version: &str) -> std::io::Result<()> {+ path.parent()+ .ok_or_else(|| std::io::Error::other("missing config directory"))+ .and_then(std::fs::create_dir_all)+ .and_then(|()| std::fs::write(path, serde_json::to_vec(version).expect("version JSON")))+}+#[derive(Deserialize)]struct GithubRelease {tag_name: String,@@ -410,17 +478,25 @@ pub fn check(app: AppHandle, interactive: bool) {return;}let channel = updater.state.lock().expect("updater state").channel;+ updater.state.lock().expect("updater state").availability_interactive = interactive;set_state(&app, Phase::Checking, None);tauri::async_runtime::spawn(async move {match find_update(&app, channel).await {Ok(Some(manifest)) => {- set_state(&app, Phase::Available, Some(manifest.version.clone()));+ set_available(&app, manifest.clone());publish(&app);let skipped = skipped_version(&app.state::<Updater>());if !should_prompt(interactive, skipped.as_deref(), &manifest.version) {finish(&app);return;}+ if workbench_ready(&app) {+ // The Workbench owns the confirmation UI. Keep the signed+ // manifest in native state, but release the check lock so+ // closing the popover cannot strand the updater as busy.+ finish(&app);+ return;+ }let c = catalog();let confirmation = app.clone();app.dialog()@@ -476,10 +552,70 @@ pub fn check(app: AppHandle, interactive: bool) {}});}++#[tauri::command]+pub fn desktop_update_state(window: WebviewWindow, app: AppHandle) -> Result<DesktopUpdateState, String> {+ ensure_workbench(&window)?;+ Ok(state_snapshot(&app))+}++#[tauri::command]+pub fn desktop_update_check(window: WebviewWindow, app: AppHandle) -> Result<(), String> {+ ensure_workbench(&window)?;+ check(app, true);+ Ok(())+}++#[tauri::command]+pub fn desktop_update_install(window: WebviewWindow, app: AppHandle) -> Result<(), String> {+ ensure_workbench(&window)?;+ let updater = app.state::<Updater>();+ let manifest = {+ let state = updater+ .state+ .lock()+ .map_err(|_| "Desktop updater state is unavailable.".to_owned())?;+ if state.phase != Phase::Available {+ return Err("No desktop update is ready to install.".to_owned());+ }+ state+ .manifest+ .clone()+ .ok_or_else(|| "No desktop update is ready to install.".to_owned())?+ };+ if updater.busy.swap(true, Ordering::SeqCst) {+ return Err("A desktop update is already in progress.".to_owned());+ }+ install(app, manifest);+ Ok(())+}++#[tauri::command]+pub fn desktop_update_skip(window: WebviewWindow, app: AppHandle) -> Result<(), String> {+ ensure_workbench(&window)?;+ let version = {+ let updater = app.state::<Updater>();+ let state = updater+ .state+ .lock()+ .map_err(|_| "Desktop updater state is unavailable.".to_owned())?;+ if state.phase != Phase::Available {+ return Err("No desktop update is available to skip.".to_owned());+ }+ state+ .latest+ .clone()+ .ok_or_else(|| "The available desktop update has no version.".to_owned())?+ };+ skip_version(&app, &version);+ finish(&app);+ Ok(())+}fn finish(app: &AppHandle) {let updater = app.state::<Updater>();updater.busy.store(false, Ordering::SeqCst);let _ = updater.channel_menu.set_enabled(true);+ emit_state(app);}fn install(app: AppHandle, manifest: Manifest) {set_state(&app, Phase::Downloading, None);@@ -516,11 +652,13 @@ fn install(app: AppHandle, manifest: Manifest) {Err(error) => {eprintln!("desktop update install: {error}");set_state(&app, Phase::Error, None);- app.dialog()- .message(catalog().install_failed)- .title(catalog().title)- .kind(MessageDialogKind::Error)- .show(|_| {});+ if !workbench_ready(&app) {+ app.dialog()+ .message(catalog().install_failed)+ .title(catalog().title)+ .kind(MessageDialogKind::Error)+ .show(|_| {});+ }}}});@@ -567,6 +705,38 @@ mod tests {assert!(should_prompt(true, Some("1.2.3"), "1.2.3"));}+ #[test]+ fn skipped_version_is_persisted_as_the_release_string() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("update-skipped.json");+ persist_skipped_version(&path, "3.2.3").unwrap();+ assert_eq!(+ serde_json::from_slice::<String>(&std::fs::read(path).unwrap()).unwrap(),+ "3.2.3"+ );+ }++ #[test]+ fn desktop_update_state_serializes_the_interactive_check_contract() {+ let state = DesktopUpdateState {+ phase: Phase::Available,+ latest: Some("3.2.3".to_owned()),+ channel: Channel::Test,+ skipped_version: Some("3.2.3".to_owned()),+ interactive: true,+ };+ assert_eq!(+ serde_json::to_value(state).unwrap(),+ serde_json::json!({+ "phase": "available",+ "latest": "3.2.3",+ "channel": "test",+ "skippedVersion": "3.2.3",+ "interactive": true,+ })+ );+ }+#[test]fn check_results_produce_their_record_and_other_phases_publish_nothing() {for phase in [@@ -584,6 +754,8 @@ mod tests {phase,latest: Some("3.2.3".to_owned()),channel: Channel::Test,+ manifest: None,+ availability_interactive: false,};let expected = match phase {Phase::Current => Some(UpdateStatusPhase::Current),diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.jsonindex ad8541713..f1bb68115 100644--- a/desktop/src-tauri/tauri.conf.json+++ b/desktop/src-tauri/tauri.conf.json@@ -34,7 +34,8 @@"window-drag","pet","main-pet-bind",- "main-computer-use"+ "main-computer-use",+ "main-desktop-update"],"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost"}diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rsindex d20511a19..7969f56a7 100644--- a/desktop/src-tauri/tests/shell_boundaries.rs+++ b/desktop/src-tauri/tests/shell_boundaries.rs@@ -100,13 +100,47 @@ fn the_bootstrap_capability_grants_only_the_three_shell_commands() {}#[test]-fn the_shell_enables_only_its_five_capabilities() {+fn the_shell_enables_only_its_declared_capabilities() {assert_eq!(config()["app"]["security"]["capabilities"],- serde_json::json!(["bootstrap", "window-drag", "pet", "main-pet-bind", "main-computer-use"])+ serde_json::json!([+ "bootstrap",+ "window-drag",+ "pet",+ "main-pet-bind",+ "main-computer-use",+ "main-desktop-update"+ ]));}+#[test]+fn desktop_update_commands_are_workbench_scoped() {+ let capability = read_json(crate_dir().join("capabilities/main-desktop-update.json"));+ assert_eq!(capability["windows"], serde_json::json!([MAIN_WINDOW]));+ assert_eq!(capability["local"], Value::Bool(false));+ assert_eq!(+ capability["permissions"],+ serde_json::json!([+ "core:event:default",+ "allow-desktop-update-state",+ "allow-desktop-update-check",+ "allow-desktop-update-install",+ "allow-desktop-update-skip"+ ])+ );+ let source = shipping_source("src/lib.rs");+ for command in [+ "updater::desktop_update_state",+ "updater::desktop_update_check",+ "updater::desktop_update_install",+ "updater::desktop_update_skip",+ ] {+ assert!(source.contains(command), "missing Workbench updater command {command}");+ }+ assert!(shipping_source("src/updater.rs").contains("This command is only available to the Avibe Workbench."));+}+#[test]fn notifications_are_native_only_without_workbench_callable_commands() {let source = shipping_source("src/lib.rs");@@ -209,7 +243,7 @@ fn notification_lifecycle_follows_runtime_ownership_not_webview_visibility_or_ss}#[test]-fn deep_links_have_native_entry_points_without_a_workbench_callable_command() {+fn deep_links_have_native_entry_points_and_the_updates_popover_route() {let source = shipping_source("src/lib.rs");let build = shipping_source("build.rs");for required in [@@ -226,10 +260,18 @@ fn deep_links_have_native_entry_points_without_a_workbench_callable_command() {}assert!(!build.contains("deep_link") && !build.contains("window_state"));assert!(!source.contains("on_open_url"));- // The one script the shell runs in the Workbench is its constant Settings- // request; nothing page-supplied is ever evaluated.- assert_eq!(source.matches(".eval(").count(), 1);+ // The shell evaluates only its fixed Settings and Updates event scripts;+ // nothing page-supplied is ever evaluated.+ assert_eq!(source.matches(".eval(").count(), 2);assert!(source.contains("window.eval(open_settings_script())"));+ assert!(source.contains("window.eval(open_updates_script())"));+ assert!(source.contains("avibe:desktop-open-updates"));+ assert!(source.contains("request_desktop_updates(app)"));+ assert!(source.contains("take_desktop_update_request(webview.app_handle())"));+ assert!(source.contains("if !open_desktop_updates(webview.app_handle())"));+ assert!(source.contains("avibe://updates-fallback"));+ assert!(source.contains("OPEN_UPDATES_FALLBACK_URL"));+ assert!(shipping_source("src/pet.rs").contains("link != crate::updater::OPEN_URL"));assert!(!source.contains("RunEvent::Opened"));let receiver = source.split("fn receive_native_deep_link(")@@ -402,6 +444,10 @@ fn every_shell_command_is_declared_so_its_permission_exists() {"open_install_docs","computer_use_enable","computer_use_open_permission",+ "desktop_update_state",+ "desktop_update_check",+ "desktop_update_install",+ "desktop_update_skip","pet_ready","pet_set_expanded","pet_drag",@@ -1052,19 +1098,19 @@ fn explicit_stop_does_not_schedule_automatic_recovery() {}#[test]-fn updates_have_one_native_owner_and_no_remote_install_permission() {+fn updates_have_one_native_owner_and_one_scoped_workbench_control_path() {let source = include_str!("../src/lib.rs");let updater = include_str!("../src/updater.rs");- // The shell downloads and verifies updates itself; no plugin exposes a- // second update 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::MENU_ID => updater::check(app.clone(), true)"));+ assert!(source.contains("updater::MENU_ID =>"));assert!(source.contains("url.as_str() == updater::OPEN_URL"));assert!(updater.contains("MessageDialogButtons::YesNoCancelCustom"));assert!(updater.contains("update::install_verified(download, &artifact, KEY"));assert!(!include_str!("../capabilities/bootstrap.json").contains("updater:"));- assert!(!include_str!("../build.rs").contains("update_install"));+ assert!(include_str!("../build.rs").contains("desktop_update_install"));}#[test]diff --git a/docs/desktop-test-installation.md b/docs/desktop-test-installation.mdindex a30aef4cb..8f0693be2 100644--- a/docs/desktop-test-installation.md+++ b/docs/desktop-test-installation.md@@ -45,13 +45,18 @@ Agent backends are detected or installed when selected in Avibe.To upgrade, use the desktop updater when your installed release published signedupdate metadata (`desktop-update-<target>.json` assets; the first was-`gh-v3.1.2rc2`). The app checks at startup, and **Check for Desktop Updates…** in-the tray menu or the Workbench version badge checks on demand. A newer signed-release asks before doing anything: choose **Download and Install**, **Skip This-Version**, or **Later**. Prerelease builds follow TEST releases while **Use TEST-Updates** is on, and updates never downgrade. Releases without that metadata,-including builds that report **Desktop updates disabled**, upgrade manually: quit-the shell and replace the app (macOS) or run the replacement installer (Windows).+`gh-v3.1.2rc2`). The app checks at startup and turns the Workbench version badge+yellow when a newer release is available. **Check for Desktop Updates…** in the+tray menu, the Workbench version badge, and the `avibe://updates` deep link all+open the same popover and run a check. A newer signed release asks before doing+anything: choose **Download and Install**, **Skip This Version**, or **Later**.+Startup checks do not show a native dialog after the Workbench is reachable. A+native fallback is reserved for the period before the webview is ready or when+the fixed popover event cannot be dispatched. Prerelease builds follow TEST+releases while **Use TEST Updates** is on, and updates never downgrade. Releases+without that metadata, including builds that report **Desktop updates disabled**,+upgrade manually: quit the shell and replace the app (macOS) or run the+replacement installer (Windows).Either path keeps user data under `~/.avibe`; the replacement app verifies andactivates its private Runtime when it opens.diff --git a/docs/plans/desktop-auto-update.md b/docs/plans/desktop-auto-update.mdindex 3c1c56390..2ca827d76 100644--- a/docs/plans/desktop-auto-update.md+++ b/docs/plans/desktop-auto-update.md@@ -3,8 +3,10 @@## Outcome and boundariesFrom baseline `2a8ce221283f81cdd37cf375c92a977669a3b540`, add one native desktop-update owner. Startup checks only; installation requires a native confirmation.-The Web version entry routes to that owner without receiving updater IPC powers.+update owner. Startup checks only; installation requires confirmation in the+Workbench popover once it is reachable, with a native fallback during startup+or when the popover event cannot be dispatched. The Web version entry routes to+that owner without receiving updater IPC powers.Current version comes from Tauri package metadata stamped by the release build.Stable builds default to stable; prerelease builds default to TEST. Channel choiceis local to the shell. No downgrade, Python in-place upgrade, backend update, or@@ -15,8 +17,8 @@ mutation of `~/.avibe` / private Runtime slots is part of application replacemenThe update prompt offers Install, Skip This Version, and Later. Skip records onlythat exact version in the shell's local data directory; the automatic startupcheck stays silent for it, while an explicit menu check and any newer release-prompt again. Dismissing the dialog (Esc or close) always means Later. There is-no silent auto-install option: installation keeps its native confirmation.+prompt again. Closing the popover without choosing an action means Later. There+is no silent auto-install option: installation keeps its confirmation step.## Distribution contractdiff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonindex b6018f39f..6aa24af8f 100644--- a/ui/eslint-baseline.json+++ b/ui/eslint-baseline.json@@ -47,10 +47,6 @@"src/components/ThemeToggle.tsx": {"avibe/localized-user-text": 1},- "src/components/VersionBadge.tsx": {- "avibe/localized-user-text": 4,- "react-hooks/immutability": 2- },"src/components/Wizard.tsx": {"@typescript-eslint/no-explicit-any": 1,"react-hooks/set-state-in-effect": 1@@ -595,6 +591,9 @@"src/App.tsx": {"react-hooks/refs": 1},+ "src/components/VersionBadge.tsx": {+ "react-hooks/exhaustive-deps": 2+ },"src/components/apps/AppWindow.tsx": {"react-hooks/exhaustive-deps": 2},diff --git a/ui/src/components/VersionBadge.test.tsx b/ui/src/components/VersionBadge.test.tsxindex 97dc8c95e..f3e7630b1 100644--- a/ui/src/components/VersionBadge.test.tsx+++ b/ui/src/components/VersionBadge.test.tsx@@ -4,26 +4,67 @@ import { I18nextProvider } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { VersionBadge } from './VersionBadge';+import {+ DESKTOP_OPEN_UPDATES_EVENT,+ DESKTOP_UPDATE_STATE_EVENT,+} from '../lib/desktopShell';const api = vi.hoisted(() => ({getVersion: vi.fn(async () => ({ current: '9.9.9', latest: '10.0.0', has_update: true, managed_by: 'desktop' })),getConfig: vi.fn(async () => ({ update: { auto_update: true } })),doUpgrade: vi.fn(async () => ({ ok: true, message: 'Upgrade successful', output: null, restarting: false })),}));+const defaultDesktopInvoke = vi.hoisted(() => async (command: string) => {+ if (command === 'desktop_update_state') {+ return { phase: 'available', latest: '10.0.0', channel: 'stable', skippedVersion: null, interactive: true };+ }+ if (command === 'plugin:event|listen') return 1;+ return undefined;+});+const desktopInvoke = vi.hoisted(() => vi.fn(defaultDesktopInvoke));vi.mock('../context/ApiContext', () => ({ useApi: () => api }));vi.mock('../lib/useIsDesktop', () => ({ useIsDesktop: () => true }));afterEach(() => {cleanup();vi.clearAllMocks();+ desktopInvoke.mockImplementation(defaultDesktopInvoke);delete (window as { __AVIBE_DESKTOP_SHELL__?: true }).__AVIBE_DESKTOP_SHELL__;delete (window as { __AVIBE_DESKTOP_VERSION__?: string }).__AVIBE_DESKTOP_VERSION__;+ delete (window as { __AVIBE_DESKTOP_UPDATES_HANDLED__?: boolean }).__AVIBE_DESKTOP_UPDATES_HANDLED__;+ delete (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;});-function renderInShell(appVersion: string, runtimeVersion: string, latest: string | null = null) {+function renderInShell(+ appVersion: string,+ runtimeVersion: string,+ latest: string | null = null,+ withUpdater = false,+ versionOverride?: {+ current: string;+ latest: string | null;+ has_update: boolean;+ error?: string | null;+ managed_by?: 'desktop';+ },+) {Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });Object.defineProperty(window, '__AVIBE_DESKTOP_VERSION__', { value: appVersion, configurable: true });- api.getVersion.mockResolvedValueOnce({ current: runtimeVersion, latest, has_update: latest !== null, managed_by: 'desktop' });+ if (withUpdater) {+ Object.defineProperty(window, '__TAURI_INTERNALS__', {+ value: {+ invoke: desktopInvoke,+ transformCallback: () => 1,+ },+ configurable: true,+ });+ }+ api.getVersion.mockResolvedValueOnce(versionOverride ?? {+ current: runtimeVersion,+ latest,+ has_update: latest !== null,+ managed_by: 'desktop',+ });render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);}@@ -51,15 +92,204 @@ describe('desktop version ownership', () => {expect(screen.queryByRole('dialog')).toBeNull();});- it('leaves the desktop window to its own menu even when the app reported an update', async () => {+ it('shows the yellow badge in the desktop shell when the app reports an update', async () => {renderInShell('3.2.2-rc.13', '3.2.2rc13', '3.2.3');await vi.waitFor(() => expect(api.getVersion).toHaveBeenCalledOnce());- const entry = screen.getByTitle('v3.2.2-rc.13');- expect(entry.className).not.toContain('text-gold-ink');- expect(entry.querySelector('.animate-pulse')).toBeNull();+ const entry = await screen.findByTitle('v3.2.2-rc.13');+ expect(entry.className).toContain('text-gold-ink');+ expect(entry.querySelector('.animate-pulse')).toBeTruthy();expect(screen.queryByRole('dialog')).toBeNull();});+ it('prefers native available state over a Runtime version error', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: null,+ has_update: false,+ error: 'PyPI unavailable',+ managed_by: 'desktop',+ });+ fireEvent.click(await screen.findByTitle('v3.2.2-rc.13'));+ expect(await screen.findByText(+ i18n.t('dashboard.desktopManagedUpdateAvailable', { to: '10.0.0' }),+ )).toBeTruthy();+ expect(screen.queryByText(i18n.t('dashboard.checkFailed'))).toBeNull();+ });++ it('prefers native current state over a Runtime version error', async () => {+ desktopInvoke.mockImplementation(async (command: string) => {+ if (command === 'desktop_update_state') {+ return { phase: 'current', latest: '3.2.2', channel: 'stable', skippedVersion: null, interactive: false };+ }+ if (command === 'plugin:event|listen') return 1;+ return undefined;+ });+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: null,+ has_update: false,+ error: 'PyPI unavailable',+ managed_by: 'desktop',+ });+ fireEvent.click(await screen.findByTitle('v3.2.2-rc.13'));+ expect(await screen.findByText(i18n.t('dashboard.upToDate'))).toBeTruthy();+ expect(screen.queryByText(i18n.t('dashboard.checkFailed'))).toBeNull();+ });++ it('opens the Web popover in the desktop shell instead of navigating to the update deep link', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', '3.2.3');+ const entry = await screen.findByTitle('v3.2.2-rc.13');+ const currentUrl = window.location.href;+ fireEvent.click(entry);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ expect(window.location.href).toBe(currentUrl);+ });++ it('acknowledges the native open request when the desktop updater IPC is available', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', '3.2.3', true);+ await screen.findByTitle('v3.2.2-rc.13');+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith('desktop_update_state'));+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith(+ 'plugin:event|listen',+ expect.objectContaining({+ event: DESKTOP_UPDATE_STATE_EVENT,+ target: { kind: 'Any' },+ handler: 1,+ }),+ ));+ const event = new Event(DESKTOP_OPEN_UPDATES_EVENT, { cancelable: true });+ expect(window.dispatchEvent(event)).toBe(false);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ expect(window.__AVIBE_DESKTOP_UPDATES_HANDLED__).toBe(true);+ });++ it('registers the native updater state listener for every event target', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', '3.2.3', true);+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith(+ 'plugin:event|listen',+ expect.objectContaining({+ event: DESKTOP_UPDATE_STATE_EVENT,+ target: { kind: 'Any' },+ handler: 1,+ }),+ ));+ });++ it('uses the desktop updater IPC for install and never calls the Runtime upgrade API', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', '3.2.3', true);+ fireEvent.click(await screen.findByTitle('v3.2.2-rc.13'));+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith('desktop_update_install'));+ expect(api.doUpgrade).not.toHaveBeenCalled();+ });++ it('persists Skip this version through the desktop updater IPC', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', '3.2.3', true);+ fireEvent.click(await screen.findByTitle('v3.2.2-rc.13'));+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.skipUpdate') }));+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith('desktop_update_skip'));+ expect(api.doUpgrade).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ });++ it('suppresses a skipped release for automatic checks but offers it after an explicit refresh', async () => {+ let state = {+ phase: 'available',+ latest: '3.2.3',+ channel: 'stable',+ skippedVersion: '3.2.3',+ interactive: false,+ };+ desktopInvoke.mockImplementation(async (command: string) => {+ if (command === 'desktop_update_state') return state;+ if (command === 'desktop_update_check') {+ state = { ...state, interactive: true };+ }+ return undefined;+ });+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: null,+ has_update: false,+ managed_by: 'desktop',+ });++ const entry = await screen.findByTitle('v3.2.2-rc.13');+ expect(entry.className).not.toContain('text-gold-ink');++ fireEvent.click(entry);+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.checkUpdate') }));+ expect(await screen.findByText(i18n.t('dashboard.desktopManagedUpdateAvailable', { to: '3.2.3' }))).toBeTruthy();+ expect(entry.className).toContain('text-gold-ink');+ });++ it('falls back to Runtime version reads when an older shell lacks the updater command', async () => {+ desktopInvoke.mockImplementation(async (command: string) => {+ if (command === 'desktop_update_state') throw new Error('unknown command');+ return undefined;+ });+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: '3.2.3',+ has_update: true,+ managed_by: 'desktop',+ });++ const entry = await screen.findByTitle('v3.2.2-rc.13');+ await vi.waitFor(() => expect(entry.className).toContain('text-gold-ink'));+ expect(api.getVersion).toHaveBeenCalledWith({ cache: false });+ });++ it('uses shell updater ownership even when the adopted Runtime omits managed_by', async () => {+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: null,+ has_update: false,+ });+ const entry = await screen.findByTitle('v3.2.2-rc.13');+ await vi.waitFor(() => expect(entry.className).toContain('text-gold-ink'));+ fireEvent.click(entry);+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith('desktop_update_install'));+ expect(api.doUpgrade).not.toHaveBeenCalled();+ });++ it('renders the desktop updater error state in the popover', async () => {+ desktopInvoke.mockImplementation(async (command: string) => {+ if (command === 'desktop_update_state') {+ return { phase: 'error', latest: null, channel: 'stable', skippedVersion: null, interactive: false };+ }+ return undefined;+ });+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: null,+ has_update: false,+ error: 'check failed',+ managed_by: 'desktop',+ });+ fireEvent.click(await screen.findByTitle('v3.2.2-rc.13'));+ expect(await screen.findByText(i18n.t('dashboard.checkFailed'))).toBeTruthy();+ });++ it('renders the desktop updater disabled state in the popover', async () => {+ desktopInvoke.mockImplementation(async (command: string) => {+ if (command === 'desktop_update_state') {+ return { phase: 'disabled', latest: null, channel: 'stable', skippedVersion: null, interactive: false };+ }+ return undefined;+ });+ renderInShell('3.2.2-rc.13', '3.2.2rc13', null, true, {+ current: '3.2.2rc13',+ latest: null,+ has_update: false,+ error: null,+ managed_by: 'desktop',+ });+ fireEvent.click(await screen.findByTitle('v3.2.2-rc.13'));+ expect(await screen.findByText(i18n.t('dashboard.checkFailed'))).toBeTruthy();+ });+it('shows and flags the Runtime version when the shell serves another one', async () => {renderInShell('3.1.2-rc.3', '3.1.2rc2');const entry = await screen.findByTitle(diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsxindex 9117ccf11..131492964 100644--- a/ui/src/components/VersionBadge.tsx+++ b/ui/src/components/VersionBadge.tsx@@ -13,7 +13,14 @@ import {import { cn } from '@/lib/utils';import { setConfigField } from '@/lib/configMutations';import { scheduleUpgradeReload } from '../lib/upgradeReload';-import { isDesktopShell } from '../lib/desktopShell';+import {+ DESKTOP_OPEN_UPDATES_EVENT,+ desktopUpdateShellActions,+ isDesktopShell,+ listenDesktopUpdateState,+ type DesktopUpdateShellActions,+ type DesktopUpdateState,+} from '../lib/desktopShell';import { useIsDesktop } from '../lib/useIsDesktop';import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';@@ -52,7 +59,13 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =const api = useApi();const inDesktopShell = isDesktopShell();const isDesktop = useIsDesktop();+ const shellActions = React.useMemo(() => desktopUpdateShellActions(), []);+ const [desktopActions, setDesktopActions] = React.useState<DesktopUpdateShellActions | null>(shellActions);+ const [desktopUpdaterStatus, setDesktopUpdaterStatus] = React.useState<'pending' | 'available' | 'unavailable'>(+ shellActions ? 'pending' : 'unavailable',+ );const [versionInfo, setVersionInfo] = React.useState<VersionInfo | null>(null);+ const [desktopUpdateState, setDesktopUpdateState] = React.useState<DesktopUpdateState | null>(null);const [isPopupOpen, setIsPopupOpen] = React.useState(false);const [checking, setChecking] = React.useState(false);const [upgrading, setUpgrading] = React.useState(false);@@ -63,13 +76,6 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =const popupRef = React.useRef<HTMLDivElement>(null);const popupId = React.useId();- React.useEffect(() => {- checkVersion();- // The shell owns updates; it reads the Runtime's version only to show skew.- if (inDesktopShell) return;- loadAutoUpdateSetting();- }, []);-React.useEffect(() => {const handleClickOutside = (event: MouseEvent) => {if (popupRef.current && !popupRef.current.contains(event.target as Node)) {@@ -103,12 +109,63 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =}};+ const readDesktopUpdateState = async (): Promise<DesktopUpdateState | null> => {+ const actions = desktopActions;+ if (!actions) return null;+ try {+ const state = await actions.getState();+ setDesktopUpdateState(state);+ setDesktopUpdaterStatus('available');+ return state;+ } catch (error) {+ // A newer Workbench can be adopted by an older shell whose generic+ // Tauri IPC exists but does not know the desktop updater commands.+ // Treat the command rejection as the compatibility boundary and fall+ // back to the legacy deep link plus Runtime version reads.+ setDesktopActions(null);+ setDesktopUpdaterStatus('unavailable');+ setDesktopUpdateState(null);+ throw error;+ }+ };++ const waitForDesktopUpdate = async (): Promise<DesktopUpdateState | null> => {+ if (!desktopActions) return null;+ while (true) {+ const state = await readDesktopUpdateState();+ if (!state || !['checking', 'downloading', 'installing'].includes(state.phase)) {+ return state;+ }+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ return readDesktopUpdateState();+ };+// An explicit refresh skips the shared read cache, so a check the desktop app// just finished shows at once.const checkVersion = async (fresh = false) => {setChecking(true);+ const actions = desktopActions;+ const rereadVersion = fresh || Boolean(actions);+ let nativeStateAvailable = false;try {- const info = await api.getVersion(fresh ? { cache: false } : undefined);+ if (actions) {+ if (fresh) {+ await actions.check();+ await waitForDesktopUpdate();+ } else {+ const state = await readDesktopUpdateState();+ if (state && ['checking', 'downloading', 'installing'].includes(state.phase)) {+ await waitForDesktopUpdate();+ }+ }+ nativeStateAvailable = true;+ }+ } catch (e) {+ console.error('Failed to check desktop update state:', e);+ }+ try {+ const info = await api.getVersion(rereadVersion || nativeStateAvailable ? { cache: false } : undefined);setVersionInfo(info);} catch (e) {console.error('Failed to check version:', e);@@ -117,10 +174,69 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =}};+ React.useEffect(() => {+ if (!inDesktopShell) return;+ const handleOpenUpdates = (event: Event) => {+ if (!desktopActions || desktopUpdaterStatus !== 'available') return;+ window.__AVIBE_DESKTOP_UPDATES_HANDLED__ = true;+ event.preventDefault();+ setIsPopupOpen(true);+ void checkVersion(true);+ };+ window.addEventListener(DESKTOP_OPEN_UPDATES_EVENT, handleOpenUpdates);+ return () => window.removeEventListener(DESKTOP_OPEN_UPDATES_EVENT, handleOpenUpdates);+ // The updater actions and API are stable for the lifetime of the Workbench.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [desktopUpdaterStatus, inDesktopShell]);++ React.useEffect(() => {+ if (!inDesktopShell || desktopUpdaterStatus !== 'available') return;+ let active = true;+ let unlisten: (() => Promise<void>) | null = null;+ void listenDesktopUpdateState((state) => {+ if (!active) return;+ setDesktopUpdateState(state);+ setChecking(state.phase === 'checking');+ setUpgrading(['downloading', 'installing'].includes(state.phase));+ }).then((cleanup) => {+ if (!active) {+ void cleanup?.();+ } else {+ unlisten = cleanup;+ }+ }).catch((error) => {+ // State snapshots remain the compatibility fallback when the shell has+ // updater IPC but lacks the event plugin permission.+ console.error('Failed to subscribe to desktop update state:', error);+ });+ return () => {+ active = false;+ void unlisten?.();+ };+ }, [desktopUpdaterStatus, inDesktopShell]);++ React.useEffect(() => {+ const timer = window.setTimeout(() => {+ void checkVersion();+ // The shell owns updates; it reads the Runtime's version only to show skew.+ if (!inDesktopShell) void loadAutoUpdateSetting();+ }, 0);+ return () => window.clearTimeout(timer);+ // This runs once per mounted badge. The desktop path waits one task so the+ // shell's startup updater can publish its result.+ // The API and updater actions are stable for the lifetime of the Workbench.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+const handleUpgrade = async () => {setUpgrading(true);setUpgradeResult(null);try {+ if (isDesktopManaged && desktopActions) {+ await desktopActions.install();+ await waitForDesktopUpdate();+ return;+ }const result = await api.doUpgrade();setUpgradeResult(result);if (result.ok) {@@ -140,12 +256,21 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =}};- // A desktop-managed Runtime relays the desktop app's own conclusion, so the- // dot may light, but only that app installs: it never gets an Upgrade button.- const hasUpdate = !inDesktopShell && versionInfo?.has_update === true;- const isDesktopManaged = versionInfo?.managed_by === 'desktop';+ const isDesktopManaged = inDesktopShell || versionInfo?.managed_by === 'desktop';+ const nativeUpdateStateAvailable = Boolean(desktopActions && desktopUpdateState);+ // A desktop-managed Runtime relays the desktop app's own conclusion. The+ // shell also exposes its in-memory state so a fresh native check lights the+ // badge before the Runtime's status file has been reread.+ const hasUpdate = desktopActions+ ? desktopUpdateState?.phase === 'available'+ && (desktopUpdateState.interactive || desktopUpdateState.skippedVersion !== desktopUpdateState.latest)+ : versionInfo?.has_update === true;// The desktop app reports SemVer; show it in the Runtime's PEP 440 form.- const latestVersion = versionInfo?.latest ? normalizeVersion(versionInfo.latest) : null;+ const latestVersion = isDesktopManaged && desktopUpdateState?.latest+ ? normalizeVersion(desktopUpdateState.latest)+ : versionInfo?.latest+ ? normalizeVersion(versionInfo.latest)+ : null;const shellVersion = inDesktopShell ? window.__AVIBE_DESKTOP_VERSION__ : undefined;const runtimeVersion = versionInfo?.current;// A shell can serve a Runtime it did not start, such as one it adopted.@@ -163,19 +288,39 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =const badgeTitle = hasVersionSkew? t('dashboard.runtimeVersionSkew', { app: shellVersion, runtime: runtimeVersion }): isSourceBuild- ? `${t('dashboard.sourceRevision')}: ${sourceRevision || t('dashboard.unknownRevision')}${versionInfo?.build?.dirty ? ` (${t('dashboard.dirtySource')})` : ''}`- : `v${currentVersion}`;+ ? t(versionInfo?.build?.dirty ? 'dashboard.sourceRevisionTitleDirty' : 'dashboard.sourceRevisionTitle', {+ revision: sourceRevision || t('dashboard.unknownRevision'),+ })+ : t('dashboard.versionTitle', { version: currentVersion });// Desktop details belong in the shared floating layer, outside the sidebar.// Phones retain their fixed panel below the header.const Popup = isDesktop ? PopoverContent : 'div';+ const handleSkipDesktopUpdate = async () => {+ if (!desktopActions) return;+ try {+ await desktopActions.skip();+ await readDesktopUpdateState();+ setIsPopupOpen(false);+ } catch (e) {+ console.error('Failed to skip desktop update:', e);+ }+ };++ const handleBadgeClick = () => {+ if (inDesktopShell && desktopUpdaterStatus !== 'available') {+ window.location.href = 'avibe://updates';+ }+ };+return (- <Popover open={!inDesktopShell && isPopupOpen} onOpenChange={setIsPopupOpen}>+ <Popover open={isPopupOpen} onOpenChange={setIsPopupOpen}><div className="relative" ref={popupRef}>{/* Version Badge trigger */}<PopoverTrigger asChild><buttontype="button"+ onClick={handleBadgeClick}className={cn(badgeVariants({ variant: hasUpdate || hasVersionSkew ? 'warning' : 'secondary' }),interactiveBadgeTriggerClassName,@@ -183,13 +328,9 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =)}title={badgeTitle}aria-controls={popupId}- onClick={inDesktopShell ? (event) => {- event.preventDefault();- window.location.href = 'avibe://updates';- } : undefined}>{hasVersionSkew && <AlertCircle size={12} aria-hidden="true" />}- {isSourceBuild ? <GitCommitHorizontal size={12} /> : 'v'}+ {isSourceBuild ? <GitCommitHorizontal size={12} /> : t('dashboard.versionPrefix')}{displayVersion}{hasUpdate && (<span className="absolute -top-1 -right-1 size-2.5 rounded-full border-2 border-background bg-gold animate-pulse" />@@ -251,8 +392,11 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =<div className="flex items-start justify-between gap-3 text-sm"><span className="shrink-0 text-muted">{t('dashboard.sourceRevision')}</span><span className="max-w-[10rem] break-all text-right font-mono font-medium text-foreground">- {sourceRevision || t('dashboard.unknownRevision')}- {versionInfo?.build?.dirty ? ` (${t('dashboard.dirtySource')})` : ''}+ {versionInfo?.build?.dirty+ ? t('dashboard.sourceRevisionDirty', {+ revision: sourceRevision || t('dashboard.unknownRevision'),+ })+ : sourceRevision || t('dashboard.unknownRevision')}</span></div>)}@@ -262,7 +406,9 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =<span className="text-muted">{t(isSourceBuild ? 'dashboard.packageVersion' : 'dashboard.currentVersion')}</span>- <span className="max-w-[10rem] break-all text-right font-mono font-medium text-foreground">{currentVersion}</span>+ <span className="max-w-[10rem] break-all text-right font-mono font-medium text-foreground">+ {t('dashboard.versionValue', { version: currentVersion })}+ </span></div>{/* Latest Version */}@@ -274,7 +420,35 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =)}{/* Update Status */}- {!isSourceBuild && (isDesktopManaged && hasUpdate ? (+ {!isSourceBuild && (isDesktopManaged && desktopUpdateState?.phase === 'checking' ? (+ <div className="flex items-center gap-2 rounded-md border border-cyan/30 bg-cyan/10 px-3 py-2 text-sm text-cyan-ink">+ <RefreshCw size={16} className="shrink-0 animate-spin" />+ <span>{t('dashboard.checking')}</span>+ </div>+ ) : isDesktopManaged && ['downloading', 'installing'].includes(desktopUpdateState?.phase ?? '') ? (+ <div className="flex items-center gap-2 rounded-md border border-cyan/30 bg-cyan/10 px-3 py-2 text-sm text-cyan-ink">+ <RefreshCw size={16} className="shrink-0 animate-spin" />+ <span>{t('dashboard.upgrading')}</span>+ </div>+ ) : isDesktopManaged && desktopUpdateState?.phase === 'installed' ? (+ <div className="flex items-center gap-2 rounded-md border border-mint/25 bg-mint/10 px-3 py-2 text-sm text-mint-ink">+ <Check size={16} className="shrink-0" />+ <span>{t('dashboard.upgradeSuccess')}</span>+ </div>+ ) : isDesktopManaged && desktopUpdateState?.phase === 'disabled' ? (+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm text-muted">+ <AlertCircle size={16} className="shrink-0" />+ <span>{t('dashboard.checkFailed')}</span>+ </div>+ ) : isDesktopManaged && (+ desktopUpdateState?.phase === 'error'+ || (!nativeUpdateStateAvailable && versionInfo?.error)+ ) ? (+ <div className="flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink">+ <AlertCircle size={16} className="shrink-0" />+ <span>{t('dashboard.checkFailed')}</span>+ </div>+ ) : isDesktopManaged && hasUpdate ? (<div className="flex items-center gap-2 rounded-md border border-gold/30 bg-gold/10 px-3 py-2 text-sm text-gold-ink"><AlertCircle size={16} className="shrink-0" /><span>{t('dashboard.desktopManagedUpdateAvailable', { to: latestVersion })}</span>@@ -295,12 +469,12 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =})}</span></div>- ) : versionInfo && !versionInfo.error ? (+ ) : versionInfo && (!versionInfo.error || desktopUpdateState?.phase === 'current') ? (<div className="flex items-center gap-2 rounded-md border border-mint/25 bg-mint/10 px-3 py-2 text-sm text-mint-ink"><Check size={16} className="shrink-0" /><span>{t('dashboard.upToDate')}</span></div>- ) : versionInfo?.error ? (+ ) : versionInfo?.error && !nativeUpdateStateAvailable ? (<div className="flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink"><AlertCircle size={16} className="shrink-0" /><span>{t('dashboard.checkFailed')}</span>@@ -355,12 +529,24 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =</div>{/* Actions */}- {hasUpdate && !isDesktopManaged && !restarting && (+ {hasUpdate && !restarting && (<div className="flex justify-end border-t border-border px-4 py-3">- <Button variant="brand" size="xs" onClick={handleUpgrade} disabled={upgrading}>- <Download size={14} className={upgrading ? 'animate-bounce' : ''} />- {upgrading ? t('dashboard.upgrading') : t('dashboard.upgradeNow')}- </Button>+ {isDesktopManaged && desktopActions && desktopUpdateState?.phase === 'available' ? (+ <div className="flex items-center gap-2">+ <Button variant="ghost" size="xs" onClick={handleSkipDesktopUpdate} disabled={upgrading}>+ {t('dashboard.skipUpdate')}+ </Button>+ <Button variant="brand" size="xs" onClick={handleUpgrade} disabled={upgrading}>+ <Download size={14} className={upgrading ? 'animate-bounce' : ''} />+ {upgrading ? t('dashboard.upgrading') : t('dashboard.upgradeNow')}+ </Button>+ </div>+ ) : !isDesktopManaged ? (+ <Button variant="brand" size="xs" onClick={handleUpgrade} disabled={upgrading}>+ <Download size={14} className={upgrading ? 'animate-bounce' : ''} />+ {upgrading ? t('dashboard.upgrading') : t('dashboard.upgradeNow')}+ </Button>+ ) : null}</div>)}</Popup>diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsxindex 7c960edb5..1d4c10348 100644--- a/ui/src/components/settings/SettingsLayout.test.tsx+++ b/ui/src/components/settings/SettingsLayout.test.tsx@@ -703,7 +703,7 @@ describe('SettingsLayout', () => {const user = userEvent.setup();renderLayout('/settings');- const version = await screen.findByTitle('v3.1.4');+ const version = await screen.findByTitle('dashboard.versionTitle');expect(version.parentElement?.parentElement?.className).toContain('md:hidden');await user.click(version);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9ce48563b..a3f077847 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4132,8 +4132,14 @@"versionAndUpdate": "Version & Update","buildAndVersion": "Build & Version","currentVersion": "Current Version",+ "versionPrefix": "v",+ "versionTitle": "v{{version}}",+ "versionValue": "{{version}}","packageVersion": "Package Version","sourceRevision": "Source Revision",+ "sourceRevisionTitle": "Source Revision: {{revision}}",+ "sourceRevisionTitleDirty": "Source Revision: {{revision}} (dirty)",+ "sourceRevisionDirty": "{{revision}} (dirty)","refreshBuildInfo": "Refresh Build Information","unknownRevision": "unknown","dirtySource": "dirty",@@ -4143,6 +4149,7 @@"updateAvailable": "Update Available","upgradeNow": "Upgrade Now","upgrading": "Upgrading...",+ "skipUpdate": "Skip this version","upToDate": "You're up to date","checkFailed": "Check failed","upgradeSuccess": "Upgrade successful!",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 57d85a07d..02bf54e37 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4132,8 +4132,14 @@"versionAndUpdate": "版本与更新","buildAndVersion": "构建与版本","currentVersion": "当前版本",+ "versionPrefix": "v",+ "versionTitle": "v{{version}}",+ "versionValue": "{{version}}","packageVersion": "包版本","sourceRevision": "源码修订",+ "sourceRevisionTitle": "源码修订: {{revision}}",+ "sourceRevisionTitleDirty": "源码修订: {{revision}} (有未提交改动)",+ "sourceRevisionDirty": "{{revision}} (有未提交改动)","refreshBuildInfo": "刷新构建信息","unknownRevision": "未知","dirtySource": "有未提交改动",@@ -4143,6 +4149,7 @@"updateAvailable": "有新版本","upgradeNow": "立即更新","upgrading": "更新中...",+ "skipUpdate": "跳过此版本","upToDate": "已是最新版本","checkFailed": "检查失败","upgradeSuccess": "更新成功!",diff --git a/ui/src/lib/desktopShell.ts b/ui/src/lib/desktopShell.tsindex 463c7c1f2..b4d918dc8 100644--- a/ui/src/lib/desktopShell.ts+++ b/ui/src/lib/desktopShell.ts@@ -9,6 +9,8 @@ declare global {readonly __AVIBE_DESKTOP_PET__?: true;/** The macOS shell answers the Computer Use guide's actions. */readonly __AVIBE_DESKTOP_COMPUTER_USE__?: true;+ /** The current Workbench handled the shell's update-popover request. */+ __AVIBE_DESKTOP_UPDATES_HANDLED__?: boolean;}}@@ -48,6 +50,7 @@ export function canShowInDesktopPet(): boolean {}type ShellInvoke = (command: string, args?: Record<string, unknown>) => Promise<unknown>;+type ShellTransformCallback = (callback: (event: unknown) => void, once?: boolean) => number;const computerUseInvoke = (): ShellInvoke | null => {if (!isDesktopShell() || window.__AVIBE_DESKTOP_COMPUTER_USE__ !== true) return null;@@ -55,6 +58,99 @@ const computerUseInvoke = (): ShellInvoke | null => {return internals?.invoke ? internals.invoke.bind(internals) : null;};+export type DesktopUpdatePhase =+ | 'idle'+ | 'checking'+ | 'current'+ | 'available'+ | 'downloading'+ | 'installing'+ | 'installed'+ | 'disabled'+ | 'error';++export type DesktopUpdateState = {+ phase: DesktopUpdatePhase;+ latest: string | null;+ channel: 'stable' | 'test';+ skippedVersion: string | null;+ interactive: boolean;+};++const desktopUpdateInvoke = (): ShellInvoke | null => {+ if (!isDesktopShell()) return null;+ const internals = (window as unknown as { __TAURI_INTERNALS__?: { invoke?: ShellInvoke } }).__TAURI_INTERNALS__;+ return internals?.invoke ? internals.invoke.bind(internals) : null;+};++export const DESKTOP_OPEN_UPDATES_EVENT = 'avibe:desktop-open-updates';+export const DESKTOP_UPDATE_STATE_EVENT = 'avibe:desktop-update-state';++type DesktopUpdateStateEvent = {+ payload: unknown;+};++type DesktopUpdateStateListener = (state: DesktopUpdateState) => void;++/** The desktop updater controls available to the Workbench's version popover. */+export type DesktopUpdateShellActions = {+ getState: () => Promise<DesktopUpdateState>;+ check: () => Promise<void>;+ install: () => Promise<void>;+ skip: () => Promise<void>;+};++export function desktopUpdateShellActions(): DesktopUpdateShellActions | null {+ const invoke = desktopUpdateInvoke();+ if (!invoke) return null;+ return {+ getState: async () => (await invoke('desktop_update_state')) as DesktopUpdateState,+ check: async () => { await invoke('desktop_update_check'); },+ install: async () => { await invoke('desktop_update_install'); },+ skip: async () => { await invoke('desktop_update_skip'); },+ };+}++/**+ * Listen to native updater state changes without making the Web UI depend on+ * the desktop package. The desktop shell grants the core event permission to+ * the Workbench capability; a browser or an older shell simply has no+ * listener bridge and keeps using snapshot reads.+ */+export async function listenDesktopUpdateState(+ handler: DesktopUpdateStateListener,+): Promise<(() => Promise<void>) | null> {+ const invoke = desktopUpdateInvoke();+ const internals = (window as unknown as {+ __TAURI_INTERNALS__?: {+ transformCallback?: ShellTransformCallback;+ };+ }).__TAURI_INTERNALS__;+ if (!invoke || !internals?.transformCallback) return null;++ const eventId = await invoke('plugin:event|listen', {+ event: DESKTOP_UPDATE_STATE_EVENT,+ target: { kind: 'Any' },+ handler: internals.transformCallback((event: unknown) => {+ const payload = (event as DesktopUpdateStateEvent).payload as DesktopUpdateState;+ handler(payload);+ }),+ }) as number;++ return async () => {+ const eventPlugin = (window as unknown as {+ __TAURI_EVENT_PLUGIN_INTERNALS__?: {+ unregisterListener?: (event: string, eventId: number) => void;+ };+ }).__TAURI_EVENT_PLUGIN_INTERNALS__;+ eventPlugin?.unregisterListener?.(DESKTOP_UPDATE_STATE_EVENT, eventId);+ await invoke('plugin:event|unlisten', {+ event: DESKTOP_UPDATE_STATE_EVENT,+ eventId,+ });+ };+}+/** A System Settings privacy pane the Computer Use guide can open. */export type ComputerUsePermissionPane = 'accessibility' | 'screen_recording';