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): relay updater status to the web badge (#2895)
Maxfe69435720fb
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rsindex 44ca5ea4b..75bc19079 100644--- a/desktop/runtime-host/src/lib.rs+++ b/desktop/runtime-host/src/lib.rs@@ -85,3 +85,4 @@ pub fn bundled_runtime_host(}pub mod update;+pub mod update_status;diff --git a/desktop/runtime-host/src/update_status.rs b/desktop/runtime-host/src/update_status.rsnew file mode 100644index 000000000..8497cf2b5--- /dev/null+++ b/desktop/runtime-host/src/update_status.rs@@ -0,0 +1,265 @@+//! The desktop updater's last conclusion, published for the Runtime.+//!+//! Only the shell decides whether this computer can install a release: it owns+//! the update channel, skipped versions, signature checks, and updater+//! artifacts. After each completed check it records the result in+//! `update-status.json`, beside `computer-use.json`, and a desktop-managed+//! Runtime relays `latest` and `has_update` from that file to browsers+//! (`vibe/desktop_update_status.py`) without deciding anything itself.+//!+//! The Runtime ignores unknown fields, so a newer shell never breaks an older+//! Runtime. This module knows nothing about Tauri.++use std::fs::{self, OpenOptions};+use std::io::{self, Write};+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{SystemTime, UNIX_EPOCH};++use serde::Serialize;++use crate::update::Channel;++const UPDATE_STATUS_SCHEMA_VERSION: u32 = 1;+pub const UPDATE_STATUS_FILE: &str = "update-status.json";++static TEMP_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0);++/// A completed check. In-flight phases (checking, downloading, installing) are+/// never persisted, so a recheck cannot make the web forget a known update. The+/// install handoff is not a result either: the next launch's check publishes it.+#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum UpdateStatusPhase {+ Current,+ Available,+ Disabled,+ Error,+}++#[derive(Clone, Debug, Eq, PartialEq, Serialize)]+pub struct UpdateStatusRecord {+ pub schema_version: u32,+ pub phase: UpdateStatusPhase,+ /// The app's own SemVer, not the Runtime's PEP 440 version.+ pub current: String,+ pub latest: Option<String>,+ pub channel: Channel,+ /// The shell's conclusion; readers copy it and never infer it.+ pub has_update: bool,+ /// RFC 3339 UTC.+ pub checked_at: String,+}++impl UpdateStatusRecord {+ /// The record for one completed check.+ ///+ /// Only `Available` claims an update, and a skipped version is still+ /// available. `Disabled` and `Error` reached no conclusion, so they carry no+ /// version: a release the shell could not verify is not one it can install.+ pub fn new(+ phase: UpdateStatusPhase,+ current: impl Into<String>,+ latest: Option<String>,+ channel: Channel,+ checked_at: SystemTime,+ ) -> Self {+ let latest = match phase {+ UpdateStatusPhase::Disabled | UpdateStatusPhase::Error => None,+ _ => latest.filter(|version| !version.trim().is_empty()),+ };+ Self {+ schema_version: UPDATE_STATUS_SCHEMA_VERSION,+ phase,+ current: current.into(),+ latest,+ channel,+ has_update: phase == UpdateStatusPhase::Available,+ checked_at: rfc3339(checked_at),+ }+ }++ /// What the Runtime rejects (`vibe/desktop_update_status.py`), refused before writing.+ fn validate(&self) -> Result<(), String> {+ if self.schema_version != UPDATE_STATUS_SCHEMA_VERSION {+ return Err(format!("unsupported schema_version: {}", self.schema_version));+ }+ if self.has_update && self.latest.as_deref().is_none_or(|version| version.trim().is_empty()) {+ return Err("latest must be non-empty when has_update is true".to_owned());+ }+ Ok(())+ }+}++fn rfc3339(moment: SystemTime) -> String {+ let since_epoch = moment.duration_since(UNIX_EPOCH).unwrap_or_default();+ chrono::DateTime::from_timestamp(since_epoch.as_secs() as i64, 0)+ .map(|moment| moment.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))+ .unwrap_or_default()+}++#[derive(Clone, Debug)]+pub struct UpdateStatusStore {+ path: PathBuf,+}++impl UpdateStatusStore {+ pub fn new(path: PathBuf) -> Self {+ Self { path }+ }++ /// Replaces the file atomically: a reader sees the previous record or this+ /// one, never a partial write.+ pub fn write(&self, record: &UpdateStatusRecord) -> io::Result<()> {+ record+ .validate()+ .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;+ let parent = self+ .path+ .parent()+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "status path has no parent"))?;+ fs::create_dir_all(parent)?;+ let suffix = TEMP_FILE_SEQUENCE.fetch_add(1, Ordering::Relaxed);+ let temporary = parent.join(format!(".{UPDATE_STATUS_FILE}.{}.{}.tmp", std::process::id(), suffix));+ let mut file = OpenOptions::new().create_new(true).write(true).open(&temporary)?;+ let mut payload = serde_json::to_vec(record).map_err(io::Error::other)?;+ payload.push(b'\n');+ if let Err(error) = (|| {+ file.write_all(&payload)?;+ file.sync_all()?;+ drop(file);+ fs::rename(&temporary, &self.path)+ })() {+ let _ = fs::remove_file(&temporary);+ return Err(error);+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::AtomicBool;+ use std::sync::Arc;+ use std::time::Duration;++ fn scratch_dir(label: &str) -> PathBuf {+ static COUNTER: AtomicU64 = AtomicU64::new(0);+ let unique = COUNTER.fetch_add(1, Ordering::SeqCst);+ let dir = std::env::temp_dir().join(format!("avibe-update-status-{label}-{}-{unique}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).expect("scratch directory");+ dir+ }++ const AVAILABLE_FIXTURE: &str = include_str!("../../../tests/fixtures/desktop_update_status_available.json");++ fn at(seconds: u64) -> SystemTime {+ UNIX_EPOCH + Duration::from_secs(seconds)+ }++ fn available(latest: &str) -> UpdateStatusRecord {+ UpdateStatusRecord::new(+ UpdateStatusPhase::Available,+ "3.2.2-rc.13",+ Some(latest.to_owned()),+ Channel::Test,+ at(1_792_550_160),+ )+ }++ fn written(store_dir: &std::path::Path) -> serde_json::Value {+ serde_json::from_slice(&fs::read(store_dir.join(UPDATE_STATUS_FILE)).expect("read")).expect("json")+ }++ #[test]+ fn an_available_record_is_written_in_the_runtime_shape() {+ let dir = scratch_dir("shape");+ let store = UpdateStatusStore::new(dir.join(UPDATE_STATUS_FILE));+ store.write(&available("3.2.3")).expect("write");++ // The document the Runtime relays in `tests/test_version_identity.py`.+ let shared: serde_json::Value = serde_json::from_str(AVAILABLE_FIXTURE).expect("fixture");+ assert_eq!(written(&dir), shared);+ fs::remove_dir_all(dir).expect("cleanup");+ }++ #[test]+ fn only_available_claims_an_update_and_unconcluded_checks_carry_no_version() {+ for (phase, has_update, keeps_latest) in [+ (UpdateStatusPhase::Available, true, true),+ (UpdateStatusPhase::Current, false, true),+ (UpdateStatusPhase::Disabled, false, false),+ (UpdateStatusPhase::Error, false, false),+ ] {+ let record = UpdateStatusRecord::new(phase, "3.2.2", Some("3.2.3".to_owned()), Channel::Stable, at(0));+ assert_eq!(record.has_update, has_update, "{phase:?}");+ assert_eq!(record.latest.is_some(), keeps_latest, "{phase:?}");+ }+ }++ #[test]+ fn a_record_the_runtime_would_reject_is_never_written() {+ let dir = scratch_dir("reject");+ let store = UpdateStatusStore::new(dir.join(UPDATE_STATUS_FILE));+ store.write(&available("3.2.3")).expect("write");+ let before = written(&dir);+ for record in [+ UpdateStatusRecord {+ schema_version: 2,+ ..available("3.2.3")+ },+ UpdateStatusRecord {+ latest: None,+ ..available("3.2.3")+ },+ UpdateStatusRecord {+ latest: Some(" ".to_owned()),+ ..available("3.2.3")+ },+ ] {+ assert!(store.write(&record).is_err(), "{record:?}");+ assert_eq!(written(&dir), before, "a refused record leaves the last one");+ }+ fs::remove_dir_all(dir).expect("cleanup");+ }++ #[test]+ fn readers_never_observe_a_partial_replacement() {+ let dir = scratch_dir("atomic");+ let store = UpdateStatusStore::new(dir.join(UPDATE_STATUS_FILE));+ // Long enough that a non-atomic write would expose a torn prefix.+ let versions = ["3.2.3".to_owned(), format!("3.2.4-rc.{}", "9".repeat(4096))];+ store.write(&available(&versions[0])).expect("initial write");++ let done = Arc::new(AtomicBool::new(false));+ let reader = {+ let path = dir.join(UPDATE_STATUS_FILE);+ let versions = versions.clone();+ let done = Arc::clone(&done);+ std::thread::spawn(move || {+ let mut reads = 0;+ while !done.load(Ordering::SeqCst) || reads == 0 {+ let bytes = fs::read(&path).expect("the file is always present");+ let value: serde_json::Value = serde_json::from_slice(&bytes).expect("a complete record");+ assert!(versions.iter().any(|version| value["latest"] == version.as_str()));+ reads += 1;+ }+ })+ };+ for round in 0..200 {+ store.write(&available(&versions[round % 2])).expect("replace");+ }+ done.store(true, Ordering::SeqCst);+ reader.join().expect("reader thread");++ let leftovers: Vec<_> = fs::read_dir(&dir)+ .expect("list")+ .map(|entry| entry.expect("entry").file_name())+ .filter(|name| name != UPDATE_STATUS_FILE)+ .collect();+ assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}");+ fs::remove_dir_all(dir).expect("cleanup");+ }+}diff --git a/desktop/src-tauri/src/computer_use.rs b/desktop/src-tauri/src/computer_use.rsindex e9cf6741e..604d4249d 100644--- a/desktop/src-tauri/src/computer_use.rs+++ b/desktop/src-tauri/src/computer_use.rs@@ -211,9 +211,15 @@ struct Paths {snapshot: PathBuf,}+/// The directory the Runtime reads desktop state from (`desktop_computer_use_dir()`+/// in `core/computer_use.py`). The updater publishes `update-status.json` here too.+pub(crate) fn state_dir(app: &AppHandle) -> tauri::Result<PathBuf> {+ Ok(configured_path(app.path().app_data_dir()?, STATE_DIR_ENV))+}+impl Paths {fn resolve(app: &AppHandle) -> Result<Self, Box<dyn std::error::Error>> {- let state_dir = configured_path(app.path().app_data_dir()?, STATE_DIR_ENV);+ let state_dir = state_dir(app)?;std::fs::create_dir_all(&state_dir)?;let owner_uid = std::fs::metadata(&state_dir)?.uid();let socket = short_socket_path(&state_dir, owner_uid);diff --git a/desktop/src-tauri/src/updater.rs b/desktop/src-tauri/src/updater.rsindex e5e59a601..6fad4b0d2 100644--- a/desktop/src-tauri/src/updater.rs+++ b/desktop/src-tauri/src/updater.rs@@ -2,6 +2,7 @@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 std::{@@ -10,7 +11,7 @@ use std::{atomic::{AtomicBool, AtomicUsize, Ordering},Mutex,},- time::Duration,+ time::{Duration, SystemTime},};use tauri::{menu::{CheckMenuItem, MenuItem},@@ -88,9 +89,29 @@ pub struct Updater {source: AtomicUsize,channel_path: PathBuf,skipped_path: PathBuf,+ /// The last completed check, published for the Runtime to relay to browsers.+ status: UpdateStatusStore,pub menu: MenuItem<tauri::Wry>,pub channel_menu: CheckMenuItem<tauri::Wry>,}+/// The record a finished check publishes, or None while no check result is in+/// memory. `Error` here means the check failed: only `check()` publishes.+fn check_record(state: &State, current: &str, checked_at: SystemTime) -> Option<UpdateStatusRecord> {+ let phase = match state.phase {+ Phase::Current => UpdateStatusPhase::Current,+ Phase::Available => UpdateStatusPhase::Available,+ Phase::Disabled => UpdateStatusPhase::Disabled,+ Phase::Error => UpdateStatusPhase::Error,+ Phase::Idle | Phase::Checking | Phase::Downloading | Phase::Installing | Phase::Installed => return None,+ };+ Some(UpdateStatusRecord::new(+ phase,+ current,+ state.latest.clone(),+ state.channel,+ checked_at,+ ))+}fn label(phase: Phase, c: &Catalog) -> &str {match phase {Phase::Idle => &c.menu,@@ -111,6 +132,11 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {.ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_else(|| Channel::for_version(&app.package_info().version));+ // Beside `computer-use.json`, where the Runtime already finds desktop state.+ #[cfg(target_os = "macos")]+ let status_dir = super::computer_use::state_dir(app)?;+ #[cfg(not(target_os = "macos"))]+ let status_dir = app.path().app_data_dir()?;app.manage(Updater {state: Mutex::new(State {phase: Phase::Idle,@@ -121,6 +147,7 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {source: AtomicUsize::new(0),channel_path,skipped_path: app.path().app_local_data_dir()?.join("update-skipped.json"),+ status: UpdateStatusStore::new(status_dir.join(UPDATE_STATUS_FILE)),menu: MenuItem::with_id(app, MENU_ID, &c.menu, true, None::<&str>)?,channel_menu: CheckMenuItem::with_id(app,@@ -348,6 +375,23 @@ async fn find_update(app: &AppHandle, channel: Channel) -> Result<Option<Manifes}pub fn check(app: AppHandle, interactive: bool) {+ // Publishes the finished check in `update-status.json` for the Runtime to+ // relay. It is nested here so nothing but `check()` can publish. Install+ // progress and outcomes stay in memory: a failed install keeps the last+ // `Available` (the next check offers it again), and `Installed` only means+ // the installer took over — on Windows it runs after the shell exits and can+ // still restore this version — so the new app's startup check publishes+ // `Current`.+ fn publish(app: &AppHandle) {+ let updater = app.state::<Updater>();+ let state = updater.state.lock().expect("updater state");+ let Some(record) = check_record(&state, &app.package_info().version.to_string(), SystemTime::now()) else {+ return;+ };+ if let Err(error) = updater.status.write(&record) {+ eprintln!("desktop update status: {error}");+ }+ }let updater = app.state::<Updater>();if updater.busy.swap(true, Ordering::SeqCst) {if interactive {@@ -359,6 +403,7 @@ pub fn check(app: AppHandle, interactive: bool) {if KEY.trim().is_empty() || TARGET == "unsupported" {updater.busy.store(false, Ordering::SeqCst);set_state(&app, Phase::Disabled, None);+ publish(&app);if interactive {show(&app, &catalog().disabled_detail, None);}@@ -370,6 +415,7 @@ pub fn check(app: AppHandle, interactive: bool) {match find_update(&app, channel).await {Ok(Some(manifest)) => {set_state(&app, Phase::Available, Some(manifest.version.clone()));+ publish(&app);let skipped = skipped_version(&app.state::<Updater>());if !should_prompt(interactive, skipped.as_deref(), &manifest.version) {finish(&app);@@ -406,6 +452,7 @@ pub fn check(app: AppHandle, interactive: bool) {Ok(None) => {finish(&app);set_state(&app, Phase::Current, None);+ publish(&app);if interactive {let latest = app.state::<Updater>()@@ -421,6 +468,7 @@ pub fn check(app: AppHandle, interactive: bool) {eprintln!("desktop update check: {error}");finish(&app);set_state(&app, Phase::Error, None);+ publish(&app);if interactive {show(&app, &catalog().check_failed, None);}@@ -519,6 +567,39 @@ mod tests {assert!(should_prompt(true, Some("1.2.3"), "1.2.3"));}+ #[test]+ fn check_results_produce_their_record_and_other_phases_publish_nothing() {+ for phase in [+ Phase::Idle,+ Phase::Checking,+ Phase::Current,+ Phase::Available,+ Phase::Downloading,+ Phase::Installing,+ Phase::Installed,+ Phase::Disabled,+ Phase::Error,+ ] {+ let state = State {+ phase,+ latest: Some("3.2.3".to_owned()),+ channel: Channel::Test,+ };+ let expected = match phase {+ Phase::Current => Some(UpdateStatusPhase::Current),+ Phase::Available => Some(UpdateStatusPhase::Available),+ Phase::Disabled => Some(UpdateStatusPhase::Disabled),+ Phase::Error => Some(UpdateStatusPhase::Error),+ Phase::Idle | Phase::Checking | Phase::Downloading | Phase::Installing | Phase::Installed => None,+ };+ assert_eq!(+ check_record(&state, "3.2.2", SystemTime::now()).map(|record| record.phase),+ expected,+ "{phase:?}"+ );+ }+ }+#[test]fn every_native_update_state_has_localized_copy() {for locale in ["en", "zh"] {diff --git a/docs/desktop-test-installation.md b/docs/desktop-test-installation.mdindex d73996138..61a06f620 100644--- a/docs/desktop-test-installation.md+++ b/docs/desktop-test-installation.md@@ -43,6 +43,15 @@ 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.+A browser or phone connected to a Runtime that the desktop app manages shows the+app's last completed check in the version badge: the newer version it found, or+that it is up to date. The app owns that result and records it in+`update-status.json` in its application data directory; the browser only+displays it, offers no Upgrade button, and refreshing the badge rereads the+result without starting a new check. Install from the desktop app on the+computer running Avibe. Desktop apps that do not yet record the result keep+showing the general guidance to update from the desktop app.+To remove the private Runtime and Avibe-managed backend installations, choose**Uninstall Avibe…** in the application's first menu and confirm, then removethe macOS app or use the Windows system uninstaller. Removing only the app doesdiff --git a/tests/fixtures/desktop_update_status_available.json b/tests/fixtures/desktop_update_status_available.jsonnew file mode 100644index 000000000..5eac3877d--- /dev/null+++ b/tests/fixtures/desktop_update_status_available.json@@ -0,0 +1,9 @@+{+ "schema_version": 1,+ "phase": "available",+ "current": "3.2.2-rc.13",+ "latest": "3.2.3",+ "channel": "test",+ "has_update": true,+ "checked_at": "2026-10-21T02:36:00Z"+}diff --git a/tests/test_desktop_update_status.py b/tests/test_desktop_update_status.pynew file mode 100644index 000000000..0b242e93d--- /dev/null+++ b/tests/test_desktop_update_status.py@@ -0,0 +1,21 @@+from pathlib import Path++from core.computer_use import COMPUTER_USE_STATE_DIR_ENV+from vibe.desktop_update_status import desktop_update_status_path+++def test_desktop_update_status_path_ignores_avibe_home(tmp_path: Path) -> None:+ """A Runtime the shell adopted finds the shell's status under any AVIBE_HOME."""++ env = {"AVIBE_HOME": str(tmp_path / "runtime-home")}+ assert desktop_update_status_path(+ environ=env,+ home=tmp_path / "user",+ platform="darwin",+ ) == tmp_path / "user" / "Library" / "Application Support" / "bot.avibe.desktop" / "update-status.json"+ env[COMPUTER_USE_STATE_DIR_ENV] = str(tmp_path / "isolated-desktop")+ assert desktop_update_status_path(+ environ=env,+ home=tmp_path / "user",+ platform="darwin",+ ) == tmp_path / "isolated-desktop" / "update-status.json"diff --git a/tests/test_version_identity.py b/tests/test_version_identity.pyindex bedfb3e2c..9f42c7ee9 100644--- a/tests/test_version_identity.py+++ b/tests/test_version_identity.py@@ -1,8 +1,15 @@import json+from pathlib import Path++import pytestfrom core import update_checkerfrom vibe import api+# What the desktop updater writes for an available release; its own tests write+# the same document (desktop/runtime-host/src/update_status.rs).+DESKTOP_UPDATE_STATUS_FIXTURE = Path(__file__).parent / "fixtures" / "desktop_update_status_available.json"+def _write_metadata(path, *, commit: str, fingerprint: str = "same") -> None:path.write_text(@@ -88,24 +95,85 @@ def test_packaged_install_keeps_semantic_update_behavior(monkeypatch) -> None:assert api.get_version_info() == {**expected, "build": {"kind": "package"}}-def test_desktop_managed_runtime_skips_package_update_check(monkeypatch) -> None:+def _desktop_managed(monkeypatch, state_dir: Path) -> None:monkeypatch.delenv("VIBE_BUILD_METADATA_PATH", raising=False)monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")- monkeypatch.setattr("vibe.__version__", "3.0.6", raising=False)+ monkeypatch.setenv("AVIBE_COMPUTER_USE_STATE_DIR", str(state_dir))+ monkeypatch.setattr("vibe.__version__", "3.2.2rc13", raising=False)monkeypatch.setattr(api,"get_latest_version_info",lambda _current: (_ for _ in ()).throw(AssertionError("desktop Runtime must not query PyPI")),)- assert api.get_version_info() == {- "current": "3.0.6",- "latest": None,- "has_update": False,- "error": None,- "build": {"kind": "package"},- "managed_by": "desktop",- }++# A desktop app with no usable conclusion: the payload #2893 shipped.+DESKTOP_NO_CONCLUSION = {+ "current": "3.2.2rc13",+ "latest": None,+ "has_update": False,+ "error": None,+ "build": {"kind": "package"},+ "managed_by": "desktop",+}+++def test_desktop_managed_runtime_without_desktop_status_skips_package_update_check(monkeypatch, tmp_path) -> None:+ _desktop_managed(monkeypatch, tmp_path)++ assert api.get_version_info() == DESKTOP_NO_CONCLUSION+++def test_desktop_managed_runtime_relays_the_desktop_update_status(monkeypatch, tmp_path) -> None:+ _desktop_managed(monkeypatch, tmp_path)+ (tmp_path / "update-status.json").write_bytes(DESKTOP_UPDATE_STATUS_FIXTURE.read_bytes())++ assert api.get_version_info() == {**DESKTOP_NO_CONCLUSION, "latest": "3.2.3", "has_update": True}+++def test_desktop_managed_runtime_relays_an_up_to_date_desktop(monkeypatch, tmp_path) -> None:+ _desktop_managed(monkeypatch, tmp_path)+ status = json.loads(DESKTOP_UPDATE_STATUS_FIXTURE.read_text(encoding="utf-8"))+ # A newer desktop app may add fields this Runtime does not know.+ status.update(phase="current", latest="3.2.2-rc.13", has_update=False, written_by_a_newer_app=True)+ (tmp_path / "update-status.json").write_text(json.dumps(status), encoding="utf-8")++ assert api.get_version_info() == {**DESKTOP_NO_CONCLUSION, "latest": "3.2.2-rc.13"}+++def _fixture_with(**changes) -> str:+ status = json.loads(DESKTOP_UPDATE_STATUS_FIXTURE.read_text(encoding="utf-8"))+ status.update(changes)+ return json.dumps(status)+++ "content",+ [+ pytest.param('{"schema_version": 1, "phase": "avail', id="truncated"),+ pytest.param(b"\xff\xfe", id="not-utf8"),+ pytest.param("[]", id="not-an-object"),+ pytest.param(_fixture_with(schema_version=2), id="future-schema"),+ pytest.param(_fixture_with(schema_version=True), id="boolean-schema"),+ pytest.param(_fixture_with(latest=None), id="update-without-latest"),+ pytest.param(_fixture_with(latest=" "), id="update-with-blank-latest"),+ pytest.param(_fixture_with(latest=323), id="non-string-latest"),+ pytest.param(_fixture_with(has_update="true"), id="non-boolean-has-update"),+ pytest.param(None, id="unreadable"),+ ],+)+def test_desktop_managed_runtime_treats_an_unusable_desktop_status_as_missing(monkeypatch, tmp_path, content) -> None:+ _desktop_managed(monkeypatch, tmp_path)+ target = tmp_path / "update-status.json"+ if content is None:+ target.mkdir()+ elif isinstance(content, bytes):+ target.write_bytes(content)+ else:+ target.write_text(content, encoding="utf-8")++ # Never the PyPI failure path: an `error` would render "check failed".+ assert api.get_version_info() == DESKTOP_NO_CONCLUSIONdef test_configured_missing_metadata_stays_a_source_build(monkeypatch, tmp_path) -> None:diff --git a/ui/src/components/VersionBadge.test.tsx b/ui/src/components/VersionBadge.test.tsxindex 7c9c4c63a..97dc8c95e 100644--- a/ui/src/components/VersionBadge.test.tsx+++ b/ui/src/components/VersionBadge.test.tsx@@ -20,13 +20,27 @@ afterEach(() => {delete (window as { __AVIBE_DESKTOP_VERSION__?: string }).__AVIBE_DESKTOP_VERSION__;});-function renderInShell(appVersion: string, runtimeVersion: string) {+function renderInShell(appVersion: string, runtimeVersion: string, latest: string | null = null) {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: null, has_update: false, managed_by: 'desktop' });+ api.getVersion.mockResolvedValueOnce({ current: runtimeVersion, latest, has_update: latest !== null, managed_by: 'desktop' });render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);}+async function openBrowserPopup(title: string) {+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);+ const entry = await screen.findByTitle(title);+ fireEvent.click(entry);+ expect(await screen.findByRole('dialog')).toBeTruthy();+ return entry;+}++function expectNoUpdateControls() {+ expect(screen.queryByRole('button', { name: i18n.t('dashboard.upgradeNow') })).toBeNull();+ expect(screen.queryByText(i18n.t('dashboard.autoUpdate'))).toBeNull();+ expect(screen.queryByText(i18n.t('dashboard.checkFailed'))).toBeNull();+}+describe('desktop version ownership', () => {it('uses the stamped app version and never starts the Python updater', async () => {renderInShell('3.1.2-rc.15', '3.1.2rc15');@@ -37,6 +51,15 @@ 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 () => {+ 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();+ expect(screen.queryByRole('dialog')).toBeNull();+ });+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(@@ -47,15 +70,43 @@ describe('desktop version ownership', () => {expect(api.getConfig).not.toHaveBeenCalled();});- it('points a browser on a desktop Runtime to the desktop app without update controls', async () => {- render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);- const entry = await screen.findByTitle('v9.9.9');- fireEvent.click(entry);- expect(await screen.findByRole('dialog')).toBeTruthy();- expect(await screen.findByText(i18n.t('dashboard.desktopManagedUpdate'))).toBeTruthy();- expect(screen.queryByRole('button', { name: i18n.t('dashboard.upgradeNow') })).toBeNull();- expect(screen.queryByText(i18n.t('dashboard.autoUpdate'))).toBeNull();+ it('points a browser on a desktop Runtime to the update the desktop app found', async () => {+ api.getVersion.mockResolvedValueOnce({ current: '3.2.2rc13', latest: '3.2.3-rc.1', has_update: true, managed_by: 'desktop' });+ const entry = await openBrowserPopup('v3.2.2rc13');+ expect(await screen.findByText(i18n.t('dashboard.desktopManagedUpdateAvailable', { to: '3.2.3rc1' }))).toBeTruthy();+ expect(screen.getByText('3.2.3rc1')).toBeTruthy();+ expect(screen.queryByText(i18n.t('dashboard.desktopManagedUpdate'))).toBeNull();+ expectNoUpdateControls();expect(api.getVersion).toHaveBeenCalledOnce();+ expect(entry.querySelector('.animate-pulse')).toBeTruthy();+ });++ it('keeps neutral desktop guidance while the desktop app has published no conclusion', async () => {+ api.getVersion.mockResolvedValueOnce({ current: '3.2.2rc13', latest: null, has_update: false, error: null, managed_by: 'desktop' });+ const entry = await openBrowserPopup('v3.2.2rc13');+ expect(await screen.findByText(i18n.t('dashboard.desktopManagedUpdate'))).toBeTruthy();+ expect(screen.queryByText(i18n.t('dashboard.latestVersion'))).toBeNull();+ expect(screen.queryByText(i18n.t('dashboard.upToDate'))).toBeNull();+ expectNoUpdateControls();+ expect(entry.querySelector('.animate-pulse')).toBeNull();+ });++ it('rereads the version without the shared cache when the user refreshes', async () => {+ api.getVersion.mockResolvedValueOnce({ current: '3.2.2rc13', latest: null, has_update: false, error: null, managed_by: 'desktop' });+ api.getVersion.mockResolvedValueOnce({ current: '3.2.2rc13', latest: '3.2.3', has_update: true, error: null, managed_by: 'desktop' });+ await openBrowserPopup('v3.2.2rc13');+ expect(api.getVersion).toHaveBeenLastCalledWith(undefined);+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.checkUpdate') }));+ expect(await screen.findByText(i18n.t('dashboard.desktopManagedUpdateAvailable', { to: '3.2.3' }))).toBeTruthy();+ expect(api.getVersion).toHaveBeenLastCalledWith({ cache: false });+ });++ it('relays an up-to-date desktop app without update controls', async () => {+ api.getVersion.mockResolvedValueOnce({ current: '3.2.2rc13', latest: '3.2.2-rc.13', has_update: false, error: null, managed_by: 'desktop' });+ const entry = await openBrowserPopup('v3.2.2rc13');+ expect(await screen.findByText(i18n.t('dashboard.upToDate'))).toBeTruthy();+ expect(screen.queryByText(i18n.t('dashboard.desktopManagedUpdate'))).toBeNull();+ expectNoUpdateControls();expect(entry.querySelector('.animate-pulse')).toBeNull();});diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsxindex c8bd500b0..9117ccf11 100644--- a/ui/src/components/VersionBadge.tsx+++ b/ui/src/components/VersionBadge.tsx@@ -103,10 +103,12 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =}};- const checkVersion = async () => {+ // 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);try {- const info = await api.getVersion();+ const info = await api.getVersion(fresh ? { cache: false } : undefined);setVersionInfo(info);} catch (e) {console.error('Failed to check version:', e);@@ -138,8 +140,12 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =}};- const hasUpdate = !inDesktopShell && versionInfo?.managed_by !== 'desktop' && versionInfo?.has_update === true;+ // 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';+ // The desktop app reports SemVer; show it in the Runtime's PEP 440 form.+ const latestVersion = 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.@@ -220,7 +226,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =variant="ghost"size="icon"className="h-7 w-7 text-muted hover:text-foreground"- onClick={checkVersion}+ onClick={() => checkVersion(true)}disabled={checking || restarting}aria-label={refreshLabel}title={refreshLabel}@@ -260,15 +266,21 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =</div>{/* Latest Version */}- {!isSourceBuild && versionInfo?.latest && (+ {!isSourceBuild && latestVersion && (<div className="flex items-center justify-between text-sm"><span className="text-muted">{t('dashboard.latestVersion')}</span>- <span className="font-mono font-medium text-foreground">{versionInfo.latest}</span>+ <span className="font-mono font-medium text-foreground">{latestVersion}</span></div>)}{/* Update Status */}- {!isSourceBuild && (isDesktopManaged ? (+ {!isSourceBuild && (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>+ </div>+ ) : isDesktopManaged && !latestVersion ? (+ // The desktop app has not published a conclusion this Runtime can relay.<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"><Check size={16} className="shrink-0" /><span>{t('dashboard.desktopManagedUpdate')}</span>@@ -279,7 +291,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =<span>{t('dashboard.updateHint', {from: currentVersion,- to: versionInfo?.latest,+ to: latestVersion,})}</span></div>diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 78b21acf2..f58743968 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -699,7 +699,7 @@ export type ApiContextType = {backend: string,) => Promise<PickerAgentCatalog | null>;getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;- getVersion: () => Promise<VersionInfo>;+ getVersion: (options?: { cache?: boolean }) => Promise<VersionInfo>;doUpgrade: () => Promise<UpgradeResult>;browseDirectory: (path: string, showHidden?: boolean) => Promise<{ ok: boolean; path?: string; parent?: string | null; dirs?: { name: string; path: string }[]; error?: string }>;browseFavorites: () => Promise<{ ok: boolean; system?: string; favorites?: { key: string; path: string }[]; error?: string }>;@@ -3711,7 +3711,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}).catch(() => null),getLogs: (lines = 500, source) => postJson('/api/logs', source ? { lines, source } : { lines }),- getVersion: () => getCachedJson('/api/version', 10_000),+ getVersion: (options) => getCachedJson('/api/version', 10_000, options),doUpgrade: () => postJson('/api/upgrade', {}),browseDirectory: (path, showHidden) => postJson('/api/browse', { path, show_hidden: showHidden || false }),browseFavorites: () => getJson('/api/browse/favorites'),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 3dbd6d8cd..0db5c196e 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4088,6 +4088,7 @@"autoUpdate": "Auto Update","autoUpdateHint": "Auto-install when idle","desktopManagedUpdate": "Updates come from the Avibe desktop app on the computer running Avibe. Check for updates there.",+ "desktopManagedUpdateAvailable": "Version {{to}} is available. Update it with the Avibe desktop app on the computer running Avibe.","runtimeVersionSkew": "This app is v{{app}}, but it is connected to an Avibe Runtime at v{{runtime}}"},"doctor": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 70339b11a..a4683cece 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4088,6 +4088,7 @@"autoUpdate": "自动更新","autoUpdateHint": "空闲时自动安装","desktopManagedUpdate": "更新由运行 Avibe 的那台电脑上的桌面应用提供,请在那里检查更新。",+ "desktopManagedUpdateAvailable": "有新版本 {{to}},请在运行 Avibe 的那台电脑上通过 Avibe 桌面应用更新。","runtimeVersionSkew": "本应用为 v{{app}},但连接的 Avibe 运行时为 v{{runtime}}"},"doctor": {diff --git a/vibe/api.py b/vibe/api.pyindex 914b4e35c..65f509d74 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -71,6 +71,7 @@ from vibe.desktop_backends import (is_desktop_backend_path,)from vibe.desktop_runtime import is_private_desktop_runtime_path+from vibe.desktop_update_status import read_desktop_update_statusfrom vibe.cli_health import CliHealth, probe_cli, probe_cli_syncfrom vibe.cli_repair import REPAIR_PATH_CONFLICT, identify_repair_source, native_bootstrap_envfrom vibe.cli_paths import (@@ -6880,13 +6881,24 @@ def get_version_info() -> dict:"build": {"kind": "package" | "source", ...},"managed_by": "desktop" | None}++ A desktop-managed Runtime reports the desktop app's last completed check+ (``vibe/desktop_update_status.py``) and never queries PyPI."""from vibe import __version__build = get_build_identity()managed_by = "desktop" if is_desktop_managed_runtime() else Noneif managed_by:- result = {"current": __version__, "latest": None, "has_update": False, "error": None}+ # The desktop app alone decides what this computer can install; relay+ # its last conclusion, never PyPI's.+ status = read_desktop_update_status()+ result = {+ "current": __version__,+ "latest": status["latest"] if status else None,+ "has_update": status["has_update"] if status else False,+ "error": None,+ }elif build.kind == "source":result = {"current": __version__, "latest": None, "has_update": False, "error": None}else:diff --git a/vibe/desktop_update_status.py b/vibe/desktop_update_status.pynew file mode 100644index 000000000..b89193cdc--- /dev/null+++ b/vibe/desktop_update_status.py@@ -0,0 +1,71 @@+"""The Avibe desktop app's last update check, relayed to browsers.++Only the desktop app decides whether its computer can install a release: it+owns the update channel, skipped versions, signature checks, and updater+artifacts. After each completed check it writes ``update-status.json`` beside+``computer-use.json`` (``desktop/runtime-host/src/update_status.rs``). A+desktop-managed Runtime copies ``latest`` and ``has_update`` from that file and+never decides availability itself.++A file this module cannot use reads as no conclusion, so a desktop app that+predates the file keeps the neutral guidance. Unknown fields are ignored so a+newer app never breaks an older Runtime.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path+from typing import Any, TypedDict++from core.computer_use import desktop_computer_use_dir++logger = logging.getLogger(__name__)++UPDATE_STATUS_SCHEMA_VERSION = 1+UPDATE_STATUS_FILE = "update-status.json"+++class DesktopUpdateStatus(TypedDict):+ latest: str | None+ has_update: bool+++def desktop_update_status_path(**kwargs: Any) -> Path:+ """``update-status.json`` in the desktop app-data directory, independent of ``AVIBE_HOME``."""++ return desktop_computer_use_dir(**kwargs) / UPDATE_STATUS_FILE+++def parse_desktop_update_status(payload: object) -> DesktopUpdateStatus | None:+ if not isinstance(payload, dict):+ return None+ schema_version = payload.get("schema_version")+ if type(schema_version) is not int or schema_version != UPDATE_STATUS_SCHEMA_VERSION:+ return None+ has_update = payload.get("has_update")+ latest = payload.get("latest")+ if not isinstance(has_update, bool) or not (latest is None or isinstance(latest, str)):+ return None+ latest = (latest or "").strip() or None+ if has_update and latest is None:+ return None+ return {"latest": latest, "has_update": has_update}+++def read_desktop_update_status(path: Path | None = None) -> DesktopUpdateStatus | None:+ """The desktop app's last conclusion, or None when there is none to relay."""++ target = path or desktop_update_status_path()+ try:+ payload = json.loads(target.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, UnicodeError, ValueError, RecursionError) as exc:+ logger.debug("Ignoring unusable desktop update status %s: %s", target, exc)+ return None+ status = parse_desktop_update_status(payload)+ if status is None:+ logger.debug("Ignoring invalid desktop update status %s", target)+ return status