Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(desktop): support remote desktop updates (#3058)

Max68fd6a2151a4
diff --git a/desktop/runtime-host/src/download.rs b/desktop/runtime-host/src/download.rs
index 6465f1b7b..b5a6451ed 100644
--- a/desktop/runtime-host/src/download.rs
+++ b/desktop/runtime-host/src/download.rs
@@ -34,6 +34,19 @@ pub async fn fetch(
sources: &[String],
start: usize,
length: Length,
+) -> Result<(Vec<u8>, usize), String> {
+ fetch_with_progress(client, sources, start, length, |_received, _total| {}).await
+}
+
+/// Fetches with streamed byte progress. `received` includes bytes retained
+/// across source retries; `total` is exact for `Length::Exact` and the best
+/// response-derived estimate for `Length::AtMost`.
+pub async fn fetch_with_progress(
+ client: &reqwest::Client,
+ sources: &[String],
+ start: usize,
+ length: Length,
+ mut progress: impl FnMut(u64, u64) + Send,
) -> Result<(Vec<u8>, usize), String> {
if sources.is_empty() {
return Err("no download source".into());
@@ -42,7 +55,7 @@ pub async fn fetch(
let mut last = String::new();
for attempt in 0..sources.len() * 2 {
let index = (start + attempt) % sources.len();
- match continue_from(client, &sources[index], &mut data, length).await {
+ match continue_from(client, &sources[index], &mut data, length, &mut progress).await {
Ok(()) => return Ok((data, index)),
Err(Failure::Retry(error)) => last = error,
Err(Failure::Discard(error)) => {
@@ -54,7 +67,13 @@ pub async fn fetch(
Err(last)
}
-async fn continue_from(client: &reqwest::Client, url: &str, data: &mut Vec<u8>, length: Length) -> Result<(), Failure> {
+async fn continue_from(
+ client: &reqwest::Client,
+ url: &str,
+ data: &mut Vec<u8>,
+ length: Length,
+ progress: &mut impl FnMut(u64, u64),
+) -> Result<(), Failure> {
let retry = |error: reqwest::Error| Failure::Retry(format!("download failed: {error}"));
let mut request = client.get(url);
if !data.is_empty() {
@@ -81,11 +100,20 @@ async fn continue_from(client: &reqwest::Client, url: &str, data: &mut Vec<u8>,
let limit = match length {
Length::Exact(size) | Length::AtMost(size) => size,
};
+ let total = match length {
+ Length::Exact(size) => size,
+ Length::AtMost(_) => response
+ .content_length()
+ .map(|remaining| data.len() as u64 + remaining)
+ .unwrap_or(limit),
+ };
+ progress(data.len() as u64, total);
while let Some(chunk) = response.chunk().await.map_err(retry)? {
if (data.len() + chunk.len()) as u64 > limit {
return Err(Failure::Discard("download exceeds its expected size".into()));
}
data.extend_from_slice(&chunk);
+ progress(data.len() as u64, total);
}
if matches!(length, Length::Exact(size) if data.len() as u64 != size) {
return Err(Failure::Retry("download ended early".into()));
diff --git a/desktop/runtime-host/src/notifications.rs b/desktop/runtime-host/src/notifications.rs
index ca66fe5b5..647e0b00c 100644
--- a/desktop/runtime-host/src/notifications.rs
+++ b/desktop/runtime-host/src/notifications.rs
@@ -140,6 +140,9 @@ pub trait NotificationSink: Send + Sync {
/// The Runtime's unread total, for the app icon badge. It is state rather
/// than an interruption, so neither the toggle nor focus gates it.
fn show_unread(&self, total: u64);
+ /// A remote desktop update event is only a nudge. The shell must re-read
+ /// and validate its request file; the SSE payload never reaches this API.
+ fn desktop_update_requested(&self) {}
}
#[derive(Default)]
@@ -548,6 +551,10 @@ pub async fn run_notifications(
let allowed_at_receipt = sink.gate().allows();
for frame in decoder.push(&chunk) {
unread_changed.notify_one();
+ if frame.event == "desktop.update.requested" {
+ sink.desktop_update_requested();
+ continue;
+ }
let candidate = filter
.lock()
.ok()
diff --git a/desktop/runtime-host/src/update_status.rs b/desktop/runtime-host/src/update_status.rs
index 8497cf2b5..3946f5aa5 100644
--- a/desktop/runtime-host/src/update_status.rs
+++ b/desktop/runtime-host/src/update_status.rs
@@ -16,19 +16,22 @@ use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
-use serde::Serialize;
+use semver::Version;
+use serde::{Deserialize, Serialize};
use crate::update::Channel;
const UPDATE_STATUS_SCHEMA_VERSION: u32 = 1;
pub const UPDATE_STATUS_FILE: &str = "update-status.json";
+pub const DESKTOP_UPDATE_REQUEST_FILE: &str = "desktop-update-request.json";
+pub const REMOTE_REQUEST_MAX_AGE: chrono::Duration = chrono::Duration::minutes(30);
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)]
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum UpdateStatusPhase {
Current,
@@ -37,7 +40,82 @@ pub enum UpdateStatusPhase {
Error,
}
-#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RemoteRequestPhase {
+ Requested,
+ Acknowledged,
+ Checking,
+ AwaitingHost,
+ Downloading,
+ Installing,
+ Restarting,
+ Completed,
+ Failed,
+ Declined,
+ Expired,
+}
+
+impl RemoteRequestPhase {
+ pub fn is_terminal(self) -> bool {
+ matches!(self, Self::Completed | Self::Failed | Self::Declined | Self::Expired)
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct RemoteRequestStatus {
+ pub request_id: String,
+ pub target: String,
+ pub phase: RemoteRequestPhase,
+ pub progress: Option<u8>,
+ pub error_code: Option<String>,
+ pub updated_at: String,
+}
+
+impl RemoteRequestStatus {
+ pub fn new(
+ request_id: impl Into<String>,
+ target: impl Into<String>,
+ phase: RemoteRequestPhase,
+ progress: Option<u8>,
+ error_code: Option<String>,
+ updated_at: SystemTime,
+ ) -> Self {
+ let progress = (phase == RemoteRequestPhase::Downloading).then_some(progress.unwrap_or(0));
+ Self {
+ request_id: request_id.into(),
+ target: target.into(),
+ phase,
+ progress,
+ error_code: error_code.filter(|error| !error.trim().is_empty()),
+ updated_at: rfc3339(updated_at),
+ }
+ }
+
+ fn valid(&self) -> bool {
+ !self.request_id.trim().is_empty()
+ && !self.target.trim().is_empty()
+ && self.updated_at.parse::<chrono::DateTime<chrono::FixedOffset>>().is_ok()
+ && self.progress.is_none_or(|progress| progress <= 100)
+ && (self.phase == RemoteRequestPhase::Downloading || self.progress.is_none())
+ && self.error_code.as_deref().is_none_or(|error| !error.trim().is_empty())
+ }
+}
+
+fn deserialize_remote_request<'de, D>(deserializer: D) -> Result<Option<RemoteRequestStatus>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ let value = Option::<serde_json::Value>::deserialize(deserializer)?;
+ Ok(value.and_then(|value| {
+ serde_json::from_value::<RemoteRequestStatus>(value)
+ .ok()
+ .filter(RemoteRequestStatus::valid)
+ }))
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct UpdateStatusRecord {
pub schema_version: u32,
pub phase: UpdateStatusPhase,
@@ -49,6 +127,12 @@ pub struct UpdateStatusRecord {
pub has_update: bool,
/// RFC 3339 UTC.
pub checked_at: String,
+ /// Whether a local Workbench has opted into unattended remote installs.
+ #[serde(default)]
+ pub remote_install_allowed: bool,
+ /// The last remote request, including terminal outcomes.
+ #[serde(default, deserialize_with = "deserialize_remote_request")]
+ pub remote_request: Option<RemoteRequestStatus>,
}
impl UpdateStatusRecord {
@@ -76,9 +160,17 @@ impl UpdateStatusRecord {
channel,
has_update: phase == UpdateStatusPhase::Available,
checked_at: rfc3339(checked_at),
+ remote_install_allowed: false,
+ remote_request: None,
}
}
+ pub fn with_remote(mut self, remote_install_allowed: bool, remote_request: Option<RemoteRequestStatus>) -> Self {
+ self.remote_install_allowed = remote_install_allowed;
+ self.remote_request = remote_request;
+ self
+ }
+
/// 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 {
@@ -91,6 +183,130 @@ impl UpdateStatusRecord {
}
}
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
+#[serde(rename_all = "lowercase")]
+enum DesktopUpdateRequestState {
+ Pending,
+ Expired,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
+#[serde(deny_unknown_fields)]
+pub struct DesktopUpdateRequest {
+ pub schema_version: u32,
+ pub request_id: String,
+ pub target: String,
+ state: DesktopUpdateRequestState,
+ pub created_at: String,
+ pub expires_at: String,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum DesktopUpdateRequestError {
+ Invalid(String),
+ Expired(DesktopUpdateRequest),
+}
+
+impl std::fmt::Display for DesktopUpdateRequestError {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Invalid(error) => formatter.write_str(error),
+ Self::Expired(_) => formatter.write_str("desktop update request expired"),
+ }
+ }
+}
+
+impl std::error::Error for DesktopUpdateRequestError {}
+
+fn uuid_shaped(value: &str) -> bool {
+ let bytes = value.as_bytes();
+ bytes.len() == 36
+ && [8, 13, 18, 23].into_iter().all(|index| bytes[index] == b'-')
+ && bytes.iter().enumerate().all(|(index, byte)| {
+ index == 8
+ || index == 13
+ || index == 18
+ || index == 23
+ || (byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
+ })
+}
+
+fn parse_timestamp(value: &str) -> Option<chrono::DateTime<chrono::Utc>> {
+ value
+ .parse::<chrono::DateTime<chrono::FixedOffset>>()
+ .ok()
+ .map(|moment| moment.with_timezone(&chrono::Utc))
+}
+
+impl DesktopUpdateRequest {
+ pub fn is_pending(&self) -> bool {
+ self.state == DesktopUpdateRequestState::Pending
+ }
+
+ pub fn parse(bytes: &[u8], now: SystemTime) -> Result<Self, DesktopUpdateRequestError> {
+ let request: Self = serde_json::from_slice(bytes)
+ .map_err(|_| DesktopUpdateRequestError::Invalid("invalid desktop update request".to_owned()))?;
+ let parsed_target = Version::parse(&request.target);
+ if request.schema_version != UPDATE_STATUS_SCHEMA_VERSION
+ || !uuid_shaped(&request.request_id)
+ || request.target.len() > 96
+ || request.target.trim() != request.target
+ || parsed_target.is_err()
+ || parsed_target.is_ok_and(|version| version.to_string() != request.target)
+ {
+ return Err(DesktopUpdateRequestError::Invalid(
+ "invalid desktop update request".to_owned(),
+ ));
+ }
+ let now = chrono::DateTime::<chrono::Utc>::from(now);
+ let Some(created_at) = parse_timestamp(&request.created_at) else {
+ return Err(DesktopUpdateRequestError::Invalid(
+ "invalid desktop update request timestamps".to_owned(),
+ ));
+ };
+ let Some(expires_at) = parse_timestamp(&request.expires_at) else {
+ return Err(DesktopUpdateRequestError::Invalid(
+ "invalid desktop update request timestamps".to_owned(),
+ ));
+ };
+ if created_at > now || expires_at <= created_at || expires_at - created_at > REMOTE_REQUEST_MAX_AGE {
+ return Err(DesktopUpdateRequestError::Invalid(
+ "invalid desktop update request timestamps".to_owned(),
+ ));
+ }
+ if !request.is_pending() || expires_at <= now {
+ return Err(DesktopUpdateRequestError::Expired(request));
+ }
+ Ok(request)
+ }
+
+ pub fn expires_at(&self) -> chrono::DateTime<chrono::Utc> {
+ parse_timestamp(&self.expires_at).expect("validated desktop update request timestamp")
+ }
+
+ pub fn expires_in(&self, now: SystemTime) -> std::time::Duration {
+ (self.expires_at() - chrono::DateTime::<chrono::Utc>::from(now))
+ .to_std()
+ .unwrap_or_default()
+ }
+}
+
+pub fn parse_desktop_update_request(
+ bytes: &[u8],
+ now: SystemTime,
+) -> Result<DesktopUpdateRequest, DesktopUpdateRequestError> {
+ DesktopUpdateRequest::parse(bytes, now)
+}
+
+pub fn read_desktop_update_request(
+ path: &std::path::Path,
+ now: SystemTime,
+) -> Result<DesktopUpdateRequest, DesktopUpdateRequestError> {
+ let bytes = fs::read(path)
+ .map_err(|_| DesktopUpdateRequestError::Invalid("desktop update request unavailable".to_owned()))?;
+ parse_desktop_update_request(&bytes, now)
+}
+
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)
@@ -108,6 +324,20 @@ impl UpdateStatusStore {
Self { path }
}
+ pub fn read(&self) -> io::Result<Option<UpdateStatusRecord>> {
+ match fs::read(&self.path) {
+ Ok(bytes) => {
+ let record: UpdateStatusRecord = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
+ record
+ .validate()
+ .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
+ Ok(Some(record))
+ }
+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(error),
+ }
+ }
+
/// 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<()> {
@@ -181,7 +411,20 @@ mod tests {
// 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);
+ let actual = written(&dir);
+ for key in [
+ "schema_version",
+ "phase",
+ "current",
+ "latest",
+ "channel",
+ "has_update",
+ "checked_at",
+ ] {
+ assert_eq!(actual[key], shared[key], "{key}");
+ }
+ assert_eq!(actual["remote_install_allowed"], false);
+ assert_eq!(actual["remote_request"], serde_json::Value::Null);
fs::remove_dir_all(dir).expect("cleanup");
}
@@ -225,6 +468,162 @@ mod tests {
fs::remove_dir_all(dir).expect("cleanup");
}
+ fn request_json(request_id: &str, target: &str, state: &str, created_at: &str, expires_at: &str) -> Vec<u8> {
+ serde_json::to_vec(&serde_json::json!({
+ "schema_version": 1,
+ "request_id": request_id,
+ "target": target,
+ "state": state,
+ "created_at": created_at,
+ "expires_at": expires_at,
+ }))
+ .expect("request JSON")
+ }
+
+ fn request_now(value: &str) -> SystemTime {
+ chrono::DateTime::parse_from_rfc3339(value).expect("timestamp").into()
+ }
+
+ #[test]
+ fn request_parser_rejects_malformed_forged_state_stale_and_expired_input() {
+ let valid = request_json(
+ "123e4567-e89b-12d3-a456-426614174000",
+ "3.2.4-rc.1",
+ "pending",
+ "2026-10-29T02:00:00Z",
+ "2026-10-29T02:30:00Z",
+ );
+ let request = parse_desktop_update_request(&valid, request_now("2026-10-29T02:05:00Z")).unwrap();
+ assert_eq!(request.request_id, "123e4567-e89b-12d3-a456-426614174000");
+
+ for malformed in [
+ request_json(
+ "not-a-uuid",
+ "3.2.4",
+ "pending",
+ "2026-10-29T02:00:00Z",
+ "2026-10-29T02:30:00Z",
+ ),
+ request_json(
+ "123E4567-e89b-12d3-a456-426614174000",
+ "3.2.4",
+ "pending",
+ "2026-10-29T02:00:00Z",
+ "2026-10-29T02:30:00Z",
+ ),
+ request_json(
+ "123e4567-e89b-12d3-a456-426614174000",
+ "v3.2.4",
+ "pending",
+ "2026-10-29T02:00:00Z",
+ "2026-10-29T02:30:00Z",
+ ),
+ request_json(
+ "123e4567-e89b-12d3-a456-426614174000",
+ "3.2.4",
+ "acknowledged",
+ "2026-10-29T02:00:00Z",
+ "2026-10-29T02:30:00Z",
+ ),
+ request_json(
+ "123e4567-e89b-12d3-a456-426614174000",
+ "3.2.4",
+ "pending",
+ "2026-10-29T02:30:00Z",
+ "2026-10-29T02:00:00Z",
+ ),
+ ] {
+ assert!(parse_desktop_update_request(&malformed, request_now("2026-10-29T02:05:00Z")).is_err());
+ }
+
+ let expired = request_json(
+ "123e4567-e89b-12d3-a456-426614174000",
+ "3.2.4",
+ "pending",
+ "2026-10-29T01:00:00Z",
+ "2026-10-29T01:30:00Z",
+ );
+ assert!(matches!(
+ parse_desktop_update_request(&expired, request_now("2026-10-29T02:05:00Z")),
+ Err(DesktopUpdateRequestError::Expired(_))
+ ));
+
+ let explicitly_expired = request_json(
+ "123e4567-e89b-12d3-a456-426614174000",
+ "3.2.4",
+ "expired",
+ "2026-10-29T02:00:00Z",
+ "2026-10-29T02:30:00Z",
+ );
+ assert!(matches!(
+ parse_desktop_update_request(&explicitly_expired, request_now("2026-10-29T02:05:00Z")),
+ Err(DesktopUpdateRequestError::Expired(_))
+ ));
+ }
+
+ #[test]
+ fn every_remote_status_field_degrades_without_losing_the_ordinary_result() {
+ let cases = [
+ ("request_id", "list", serde_json::json!([]), false),
+ ("request_id", "object", serde_json::json!({}), false),
+ ("request_id", "number", serde_json::json!(7), false),
+ ("request_id", "null", serde_json::Value::Null, false),
+ ("request_id", "opaque-string", serde_json::json!("opaque-request"), true),
+ ("target", "list", serde_json::json!([]), false),
+ ("target", "object", serde_json::json!({}), false),
+ ("target", "number", serde_json::json!(7), false),
+ ("target", "null", serde_json::Value::Null, false),
+ ("target", "opaque-string", serde_json::json!("opaque-target"), true),
+ ("phase", "list", serde_json::json!([]), false),
+ ("phase", "object", serde_json::json!({}), false),
+ ("phase", "number", serde_json::json!(7), false),
+ ("phase", "null", serde_json::Value::Null, false),
+ ("phase", "unknown-string", serde_json::json!("unknown"), false),
+ ("progress", "list", serde_json::json!([]), false),
+ ("progress", "object", serde_json::json!({}), false),
+ ("progress", "out-of-range-number", serde_json::json!(101), false),
+ ("progress", "null", serde_json::Value::Null, true),
+ ("progress", "unknown-string", serde_json::json!("unknown"), false),
+ ("error_code", "list", serde_json::json!([]), false),
+ ("error_code", "object", serde_json::json!({}), false),
+ ("error_code", "number", serde_json::json!(7), false),
+ ("error_code", "null", serde_json::Value::Null, true),
+ ("error_code", "opaque-string", serde_json::json!("unknown"), true),
+ ("updated_at", "list", serde_json::json!([]), false),
+ ("updated_at", "object", serde_json::json!({}), false),
+ ("updated_at", "number", serde_json::json!(7), false),
+ ("updated_at", "null", serde_json::Value::Null, false),
+ ("updated_at", "unknown-string", serde_json::json!("unknown"), false),
+ ];
+
+ for (field, shape, field_value, kept) in cases {
+ let mut value = serde_json::json!({
+ "schema_version": 1,
+ "phase": "available",
+ "current": "3.2.3",
+ "latest": "3.2.4",
+ "channel": "test",
+ "has_update": true,
+ "checked_at": "2026-10-29T02:00:00Z",
+ "remote_install_allowed": true,
+ "remote_request": {
+ "request_id": "request-1",
+ "target": "3.2.4",
+ "phase": "downloading",
+ "progress": 42,
+ "error_code": null,
+ "updated_at": "2026-10-29T02:00:00Z"
+ }
+ });
+ value["remote_request"][field] = field_value;
+ let record: UpdateStatusRecord = serde_json::from_value(value).expect("ordinary status remains readable");
+
+ assert_eq!(record.phase, UpdateStatusPhase::Available, "{field}-{shape}");
+ assert_eq!(record.remote_request.is_some(), kept, "{field}-{shape}");
+ assert!(record.remote_install_allowed, "{field}-{shape}");
+ }
+ }
+
#[test]
fn readers_never_observe_a_partial_replacement() {
let dir = scratch_dir("atomic");
diff --git a/desktop/runtime-host/tests/download.rs b/desktop/runtime-host/tests/download.rs
index ae229ff17..0e4eea485 100644
--- a/desktop/runtime-host/tests/download.rs
+++ b/desktop/runtime-host/tests/download.rs
@@ -1,4 +1,4 @@
-use avibe_runtime_host::download::{fetch, Length};
+use avibe_runtime_host::download::{fetch, fetch_with_progress, Length};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
@@ -216,3 +216,26 @@ async fn bytes_beyond_the_expected_size_are_discarded_with_their_source() {
Err("download exceeds its expected size".into())
);
}
+
+#[tokio::test]
+async fn streamed_progress_is_monotonic_across_source_resumption_and_reaches_the_exact_length() {
+ let mirror = source([Reply::Cut(9)]);
+ let github = source([Reply::Serve]);
+ let urls = vec![mirror.url.clone(), github.url.clone()];
+ let progress = Arc::new(Mutex::new(Vec::new()));
+ let observed = progress.clone();
+
+ let result = fetch_with_progress(&client(), &urls, 0, EXACT, move |received, total| {
+ observed.lock().unwrap().push((received, total));
+ })
+ .await;
+
+ assert_eq!(result, Ok((PAYLOAD.to_vec(), 1)));
+ let progress = progress.lock().unwrap();
+ assert_eq!(progress.first(), Some(&(0, PAYLOAD.len() as u64)));
+ assert_eq!(progress.last(), Some(&(PAYLOAD.len() as u64, PAYLOAD.len() as u64)));
+ assert!(
+ progress.windows(2).all(|pair| pair[0].0 <= pair[1].0),
+ "progress regressed across source retry: {progress:?}"
+ );
+}
diff --git a/desktop/runtime-host/tests/notifications.rs b/desktop/runtime-host/tests/notifications.rs
index f96761181..51144409a 100644
--- a/desktop/runtime-host/tests/notifications.rs
+++ b/desktop/runtime-host/tests/notifications.rs
@@ -1,5 +1,5 @@
use std::collections::{HashMap, VecDeque};
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -89,6 +89,7 @@ struct FakeSink {
delivered: Mutex<Vec<NotificationIntent>>,
sources: Mutex<Vec<Option<String>>>,
unread: Mutex<Vec<u64>>,
+ desktop_update_nudges: AtomicUsize,
}
impl Default for FakeSink {
@@ -100,6 +101,7 @@ impl Default for FakeSink {
delivered: Mutex::new(Vec::new()),
sources: Mutex::new(Vec::new()),
unread: Mutex::new(Vec::new()),
+ desktop_update_nudges: AtomicUsize::new(0),
}
}
}
@@ -121,6 +123,10 @@ impl NotificationSink for FakeSink {
fn show_unread(&self, total: u64) {
self.unread.lock().unwrap().push(total);
}
+
+ fn desktop_update_requested(&self) {
+ self.desktop_update_nudges.fetch_add(1, Ordering::SeqCst);
+ }
}
fn stamps_only(stamps: RunTimestamps) -> RunDetail {
@@ -196,6 +202,30 @@ async fn global_sse_is_an_allow_list_not_a_second_event_bus() {
task.abort();
}
+#[tokio::test(start_paused = true)]
+async fn desktop_update_sse_is_a_payload_free_nudge() {
+ let transport = Arc::new(FakeTransport::default());
+ let sink = Arc::new(FakeSink::default());
+ transport.stream(
+ [frame(
+ "desktop.update.requested",
+ json!({
+ "request_id": "forged",
+ "target": "99.99.99",
+ "remote_install_allowed": true,
+ }),
+ )],
+ false,
+ );
+ let task = spawn(transport.clone(), sink.clone());
+ settle().await;
+
+ assert_eq!(sink.desktop_update_nudges.load(Ordering::SeqCst), 1);
+ assert!(sink.delivered.lock().unwrap().is_empty());
+ assert!(transport.refetched.lock().unwrap().is_empty());
+ task.abort();
+}
+
#[tokio::test(start_paused = true)]
async fn approvals_reset_only_on_observed_non_pending_transitions() {
let transport = Arc::new(FakeTransport::default());
diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs
index b0d798a2d..1c4b33cb7 100644
--- a/desktop/src-tauri/build.rs
+++ b/desktop/src-tauri/build.rs
@@ -24,6 +24,9 @@ fn main() {
"pet_reset_shortcuts",
"pet_set_voice_mode",
"pet_reset_voice_shortcut",
+ "desktop_remote_install_allowed",
+ "desktop_remote_install_set",
+ "desktop_update_remote_decline",
"pet_ready",
"pet_context_menu",
"pet_set_expanded",
diff --git a/desktop/src-tauri/capabilities/main-desktop-update.json b/desktop/src-tauri/capabilities/main-desktop-update.json
index c83968081..c322b9bb0 100644
--- a/desktop/src-tauri/capabilities/main-desktop-update.json
+++ b/desktop/src-tauri/capabilities/main-desktop-update.json
@@ -12,6 +12,9 @@
"allow-desktop-update-state",
"allow-desktop-update-check",
"allow-desktop-update-install",
- "allow-desktop-update-skip"
+ "allow-desktop-update-skip",
+ "allow-desktop-remote-install-allowed",
+ "allow-desktop-remote-install-set",
+ "allow-desktop-update-remote-decline"
]
}
diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_remote_install_allowed.toml b/desktop/src-tauri/permissions/autogenerated/desktop_remote_install_allowed.toml
new file mode 100644
index 000000000..1cc9a2c5d
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/desktop_remote_install_allowed.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-desktop-remote-install-allowed"
+description = "Enables the desktop_remote_install_allowed command without any pre-configured scope."
+commands.allow = ["desktop_remote_install_allowed"]
+
+[[permission]]
+identifier = "deny-desktop-remote-install-allowed"
+description = "Denies the desktop_remote_install_allowed command without any pre-configured scope."
+commands.deny = ["desktop_remote_install_allowed"]
diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_remote_install_set.toml b/desktop/src-tauri/permissions/autogenerated/desktop_remote_install_set.toml
new file mode 100644
index 000000000..94c163f09
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/desktop_remote_install_set.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-desktop-remote-install-set"
+description = "Enables the desktop_remote_install_set command without any pre-configured scope."
+commands.allow = ["desktop_remote_install_set"]
+
+[[permission]]
+identifier = "deny-desktop-remote-install-set"
+description = "Denies the desktop_remote_install_set command without any pre-configured scope."
+commands.deny = ["desktop_remote_install_set"]
diff --git a/desktop/src-tauri/permissions/autogenerated/desktop_update_remote_decline.toml b/desktop/src-tauri/permissions/autogenerated/desktop_update_remote_decline.toml
new file mode 100644
index 000000000..bdbb84c8d
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/desktop_update_remote_decline.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-desktop-update-remote-decline"
+description = "Enables the desktop_update_remote_decline command without any pre-configured scope."
+commands.allow = ["desktop_update_remote_decline"]
+
+[[permission]]
+identifier = "deny-desktop-update-remote-decline"
+description = "Denies the desktop_update_remote_decline command without any pre-configured scope."
+commands.deny = ["desktop_update_remote_decline"]
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index aaacaa171..7daa6ee8f 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -120,6 +120,16 @@ const ZH_PRODUCT_CATALOG: &str = include_str!("../../../ui/src/i18n/zh.json");
#[derive(Default)]
struct PendingDesktopUpdateOpen(AtomicBool);
+impl PendingDesktopUpdateOpen {
+ fn request(&self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+
+ fn take(&self) -> bool {
+ self.0.swap(false, Ordering::SeqCst)
+ }
+}
+
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProductCatalog {
@@ -653,11 +663,19 @@ fn open_desktop_updates(app: &AppHandle) -> bool {
}
fn request_desktop_updates(app: &AppHandle) {
- app.state::<PendingDesktopUpdateOpen>().0.store(true, Ordering::SeqCst);
+ app.state::<PendingDesktopUpdateOpen>().request();
}
fn take_desktop_update_request(app: &AppHandle) -> bool {
- app.state::<PendingDesktopUpdateOpen>().0.swap(false, Ordering::SeqCst)
+ app.state::<PendingDesktopUpdateOpen>().take()
+}
+
+fn request_and_open_desktop_updates(app: &AppHandle) {
+ request_desktop_updates(app);
+ focus_or_restore_main_window(app);
+ if open_desktop_updates(app) {
+ let _ = take_desktop_update_request(app);
+ }
}
fn refresh_runtime_tray(app: &AppHandle, state: TrayRuntimeState) {
@@ -2337,6 +2355,9 @@ pub fn run() {
pet::pet_set_shortcut,
pet::pet_reset_shortcuts,
pet::pet_set_voice_mode,
+ updater::desktop_remote_install_allowed,
+ updater::desktop_remote_install_set,
+ updater::desktop_update_remote_decline,
pet::pet_ready,
pet::pet_context_menu,
pet::pet_set_expanded,
@@ -2454,6 +2475,15 @@ mod tests {
);
}
+ #[test]
+ fn a_pending_update_open_survives_until_a_workbench_takes_it() {
+ let pending = PendingDesktopUpdateOpen::default();
+ assert!(!pending.take());
+ pending.request();
+ assert!(pending.take());
+ assert!(!pending.take());
+ }
+
#[test]
fn a_control_refresh_without_a_status_keeps_the_status_already_shown() {
let unreachable = TrayRuntimeState::Unreachable;
diff --git a/desktop/src-tauri/src/notifications.rs b/desktop/src-tauri/src/notifications.rs
index 2bd154626..76eacae00 100644
--- a/desktop/src-tauri/src/notifications.rs
+++ b/desktop/src-tauri/src/notifications.rs
@@ -1,6 +1,7 @@
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
+use std::time::Duration;
use avibe_runtime_host::notifications::{
run_notifications, HttpNotificationTransport, NotificationFilter, NotificationGate, NotificationIntent,
@@ -11,9 +12,12 @@ use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Manager};
use tauri_plugin_notification::NotificationExt;
-use crate::{native_catalog_for_locales, MAIN_WINDOW};
+use crate::{native_catalog_for_locales, updater, MAIN_WINDOW};
pub const MENU_ID: &str = "notifications";
+// The Runtime expires an unacknowledged request after ten seconds. This
+// fallback stays below that deadline while SSE remains the normal path.
+const REMOTE_REQUEST_POLL_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -88,6 +92,7 @@ fn write_preference(path: &Path, enabled: bool) -> std::io::Result<()> {
struct Connection {
origin: LoopbackOrigin,
task: tauri::async_runtime::JoinHandle<()>,
+ remote_request_poll: tauri::async_runtime::JoinHandle<()>,
}
pub struct Notifications {
@@ -134,6 +139,7 @@ impl Notifications {
let observed_generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
if let Some(previous) = connection.take() {
previous.task.abort();
+ previous.remote_request_poll.abort();
}
let Ok(transport) = HttpNotificationTransport::new(origin.clone()) else {
eprintln!("The desktop notification connection could not be initialized.");
@@ -146,11 +152,18 @@ impl Notifications {
observed_generation,
};
let filter = self.filter.clone();
+ let poll_sink = sink.clone();
*connection = Some(Connection {
origin,
task: tauri::async_runtime::spawn(async move {
run_notifications(Arc::new(transport), filter, Arc::new(sink)).await;
}),
+ remote_request_poll: tauri::async_runtime::spawn(async move {
+ loop {
+ poll_sink.desktop_update_requested();
+ tokio::time::sleep(REMOTE_REQUEST_POLL_INTERVAL).await;
+ }
+ }),
});
}
@@ -159,6 +172,7 @@ impl Notifications {
self.generation.fetch_add(1, Ordering::SeqCst);
if let Some(connection) = connection.take() {
connection.task.abort();
+ connection.remote_request_poll.abort();
}
}
}
@@ -219,6 +233,12 @@ impl NotificationSink for NativeSink {
}
});
}
+
+ fn desktop_update_requested(&self) {
+ if self.generation.load(Ordering::SeqCst) == self.observed_generation {
+ updater::handle_remote_update_request(&self.app);
+ }
+ }
}
/// The Badging API's rule: zero clears. macOS would otherwise draw a literal
@@ -337,6 +357,7 @@ mod tests {
*state.connection.lock().unwrap() = Some(Connection {
origin: LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap(),
task,
+ remote_request_poll: tauri::async_runtime::spawn(std::future::pending()),
});
let previous = state.generation.load(Ordering::SeqCst);
state.stop();
diff --git a/desktop/src-tauri/src/update_install.rs b/desktop/src-tauri/src/update_install.rs
index 98d82e484..e8f4d7e8c 100644
--- a/desktop/src-tauri/src/update_install.rs
+++ b/desktop/src-tauri/src/update_install.rs
@@ -2,7 +2,12 @@
use tauri::AppHandle;
#[cfg(target_os = "macos")]
-pub fn install(_app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), String> {
+pub fn install_with_before_exit(
+ _app: &AppHandle,
+ bytes: &[u8],
+ version: &str,
+ before_exit: impl FnOnce(),
+) -> Result<(), String> {
use std::{fs, io::Cursor, process::Command};
let executable = std::env::current_exe().map_err(|e| e.to_string())?;
let current = executable
@@ -49,7 +54,10 @@ pub fn install(_app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), Stri
}
let backup = staging.path().join("previous.app");
match replace_with_rollback(current, &replacement, &backup, |a, b| fs::rename(a, b)) {
- Ok(()) => Ok(()),
+ Ok(()) => {
+ before_exit();
+ Ok(())
+ }
Err(error) => {
// Never let TempDir cleanup erase a backup that restoration could
// not move back (for example a filesystem failure).
@@ -129,7 +137,12 @@ fn replace_with_rollback(
}
#[cfg(target_os = "windows")]
-pub fn install(app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), String> {
+pub fn install_with_before_exit(
+ app: &AppHandle,
+ bytes: &[u8],
+ version: &str,
+ before_exit: impl FnOnce(),
+) -> Result<(), String> {
use std::{
fs,
os::windows::process::CommandExt,
@@ -169,8 +182,12 @@ pub fn install(app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), Strin
.spawn()
.map_err(|e| e.to_string())?;
let deadline = Instant::now() + Duration::from_secs(600);
- while !staging.path().join("ready").exists() {
+ let requires_host = staging.path().join("requires-host");
+ while !staging.path().join("ready").exists() && !requires_host.exists() {
if child.try_wait().map_err(|e| e.to_string())?.is_some() {
+ if requires_host.exists() {
+ return Err("requires_host".into());
+ }
return Err("installer preparation failed; current application retained".into());
}
if Instant::now() > deadline {
@@ -180,6 +197,11 @@ pub fn install(app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), Strin
}
std::thread::sleep(Duration::from_millis(100));
}
+ if requires_host.exists() {
+ let _ = child.wait();
+ return Err("requires_host".into());
+ }
+ before_exit();
// The helper has copied the previous install and now waits for this PID.
// Ownership transfers to it; it reports failures and relaunches the old app.
let _ = staging.keep();
@@ -188,7 +210,13 @@ pub fn install(app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), Strin
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
-pub fn install(_app: &AppHandle, _bytes: &[u8], _version: &str) -> Result<(), String> {
+pub fn install_with_before_exit(
+ _app: &AppHandle,
+ _bytes: &[u8],
+ _version: &str,
+ before_exit: impl FnOnce(),
+) -> Result<(), String> {
+ drop(before_exit);
Err("unsupported update platform".into())
}
diff --git a/desktop/src-tauri/src/update_windows.ps1 b/desktop/src-tauri/src/update_windows.ps1
index 54fb8e037..7cdea6b27 100644
--- a/desktop/src-tauri/src/update_windows.ps1
+++ b/desktop/src-tauri/src/update_windows.ps1
@@ -14,8 +14,13 @@ function Invoke-AvibeReplacement($requestData) {
if ($info.ProductVersion -ne $requestData.version) { throw 'Installer version mismatch' }
# Per-user NSIS installs are writable. Refuse elevation or a different scope.
$probe = Join-Path $requestData.directory ([Guid]::NewGuid().ToString() + '.probe')
- [IO.File]::WriteAllText($probe, '')
- Remove-Item -LiteralPath $probe
+ try {
+ [IO.File]::WriteAllText($probe, '')
+ Remove-Item -LiteralPath $probe
+ } catch {
+ [IO.File]::WriteAllText((Join-Path $requestData.staging 'requires-host'), 'requires_host')
+ throw 'requires_host'
+ }
Copy-Item -LiteralPath $requestData.directory -Destination $backup -Recurse
[IO.File]::WriteAllText($ready, 'ready')
Wait-Process -Id $requestData.pid -ErrorAction SilentlyContinue
diff --git a/desktop/src-tauri/src/updater.rs b/desktop/src-tauri/src/updater.rs
index 7bd80cc35..f7fb065a7 100644
--- a/desktop/src-tauri/src/updater.rs
+++ b/desktop/src-tauri/src/updater.rs
@@ -2,10 +2,16 @@
use avibe_runtime_host::{
download::{self, Length},
update::{self, Channel, Manifest, Release, REPOSITORY},
- update_status::{UpdateStatusPhase, UpdateStatusRecord, UpdateStatusStore, UPDATE_STATUS_FILE},
+ update_status::{
+ read_desktop_update_request, DesktopUpdateRequest, DesktopUpdateRequestError, RemoteRequestPhase,
+ RemoteRequestStatus, UpdateStatusPhase, UpdateStatusRecord, UpdateStatusStore, DESKTOP_UPDATE_REQUEST_FILE,
+ UPDATE_STATUS_FILE,
+ },
};
use serde::{Deserialize, Serialize};
use std::{
+ fs::{self, OpenOptions},
+ io::{self, Write},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
@@ -18,6 +24,7 @@ use tauri::{
AppHandle, Emitter, Manager, WebviewWindow,
};
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};
+use tauri_plugin_notification::NotificationExt;
pub const MENU_ID: &str = "desktop-update";
pub const CHANNEL_ID: &str = "desktop-update-test";
@@ -65,6 +72,47 @@ fn catalog() -> Catalog {
super::native_catalog_for_locales(sys_locale::get_locales()).updater
}
+#[derive(Deserialize, Serialize)]
+struct RemoteInstallPreference {
+ enabled: bool,
+}
+
+fn read_remote_install_preference(path: &Path) -> io::Result<bool> {
+ match fs::read(path) {
+ Ok(bytes) => serde_json::from_slice::<RemoteInstallPreference>(&bytes)
+ .map(|preference| preference.enabled)
+ .map_err(io::Error::other),
+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
+ Err(error) => Err(error),
+ }
+}
+
+fn write_remote_install_preference(path: &Path, enabled: bool) -> io::Result<()> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "preference path has no parent"))?;
+ fs::create_dir_all(parent)?;
+ let suffix = REMOTE_PREFERENCE_SEQUENCE.fetch_add(1, Ordering::Relaxed);
+ let temporary = parent.join(format!(
+ ".{REMOTE_INSTALL_PREFERENCE_FILE}.{}.{}.tmp",
+ std::process::id(),
+ suffix
+ ));
+ let mut file = OpenOptions::new().create_new(true).write(true).open(&temporary)?;
+ let bytes = serde_json::to_vec(&RemoteInstallPreference { enabled }).map_err(io::Error::other)?;
+ let result = (|| {
+ file.write_all(&bytes)?;
+ file.write_all(b"\n")?;
+ file.sync_all()?;
+ drop(file);
+ fs::rename(&temporary, path)
+ })();
+ if result.is_err() {
+ let _ = fs::remove_file(&temporary);
+ }
+ result
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
enum Phase {
@@ -78,12 +126,39 @@ enum Phase {
Disabled,
Error,
}
+
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DesktopRemoteRequestState {
+ request_id: String,
+ target: String,
+ phase: RemoteRequestPhase,
+ progress: Option<u8>,
+ error_code: Option<String>,
+ updated_at: String,
+}
+
+impl From<&RemoteRequestStatus> for DesktopRemoteRequestState {
+ fn from(status: &RemoteRequestStatus) -> Self {
+ Self {
+ request_id: status.request_id.clone(),
+ target: status.target.clone(),
+ phase: status.phase,
+ progress: status.progress,
+ error_code: status.error_code.clone(),
+ updated_at: status.updated_at.clone(),
+ }
+ }
+}
+
struct State {
phase: Phase,
latest: Option<String>,
channel: Channel,
manifest: Option<Manifest>,
availability_interactive: bool,
+ remote_install_allowed: bool,
+ remote_request: Option<RemoteRequestStatus>,
}
#[derive(Clone, Debug, Serialize)]
@@ -94,6 +169,8 @@ pub struct DesktopUpdateState {
channel: Channel,
skipped_version: Option<String>,
interactive: bool,
+ remote_install_allowed: bool,
+ remote_request: Option<DesktopRemoteRequestState>,
}
pub struct Updater {
state: Mutex<State>,
@@ -103,11 +180,17 @@ pub struct Updater {
source: AtomicUsize,
channel_path: PathBuf,
skipped_path: PathBuf,
+ remote_install_path: PathBuf,
+ remote_request_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>,
}
+
+const REMOTE_INSTALL_PREFERENCE_FILE: &str = "remote-install.json";
+const REMOTE_REQUEST_EXPIRY_CODE: &str = "expired";
+static REMOTE_PREFERENCE_SEQUENCE: AtomicUsize = AtomicUsize::new(0);
/// 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> {
@@ -126,6 +209,237 @@ fn check_record(state: &State, current: &str, checked_at: SystemTime) -> Option<
checked_at,
))
}
+
+fn status_for_publish(
+ state: &State,
+ current: &str,
+ previous: Option<UpdateStatusRecord>,
+ checked_at: SystemTime,
+) -> UpdateStatusRecord {
+ check_record(state, current, checked_at)
+ .or(previous)
+ .unwrap_or_else(|| {
+ UpdateStatusRecord::new(
+ UpdateStatusPhase::Current,
+ current,
+ state.latest.clone(),
+ state.channel,
+ checked_at,
+ )
+ })
+}
+
+fn base_status(app: &AppHandle, state: &State) -> UpdateStatusRecord {
+ let updater = app.state::<Updater>();
+ status_for_publish(
+ state,
+ &app.package_info().version.to_string(),
+ updater.status.read().ok().flatten(),
+ SystemTime::now(),
+ )
+}
+
+fn publish_status(app: &AppHandle) {
+ let updater = app.state::<Updater>();
+ let state = updater.state.lock().expect("updater state");
+ let record = base_status(app, &state).with_remote(state.remote_install_allowed, state.remote_request.clone());
+ if let Err(error) = updater.status.write(&record) {
+ eprintln!("desktop update status: {error}");
+ }
+}
+
+fn set_remote_phase_if(
+ app: &AppHandle,
+ request_id: &str,
+ target: &str,
+ phase: RemoteRequestPhase,
+ progress: Option<u8>,
+ error_code: Option<&str>,
+ should_replace: impl FnOnce(Option<&RemoteRequestStatus>) -> bool,
+) -> bool {
+ let status = RemoteRequestStatus::new(
+ request_id,
+ target,
+ phase,
+ progress,
+ error_code.map(str::to_owned),
+ SystemTime::now(),
+ );
+ let replaced = {
+ let updater = app.state::<Updater>();
+ let mut state = updater.state.lock().expect("updater state");
+ if !should_replace(state.remote_request.as_ref()) {
+ false
+ } else {
+ state.remote_request = Some(status);
+ true
+ }
+ };
+ if replaced {
+ publish_status(app);
+ emit_state(app);
+ }
+ replaced
+}
+
+fn set_remote_phase(
+ app: &AppHandle,
+ request_id: &str,
+ target: &str,
+ phase: RemoteRequestPhase,
+ progress: Option<u8>,
+ error_code: Option<&str>,
+) -> bool {
+ set_remote_phase_if(app, request_id, target, phase, progress, error_code, |current| {
+ remote_request_can_transition(current, request_id)
+ })
+}
+
+fn remote_request_can_transition(current: Option<&RemoteRequestStatus>, request_id: &str) -> bool {
+ current.is_none_or(|request| request.request_id == request_id && !request.phase.is_terminal())
+}
+
+fn expire_awaiting_remote_request(
+ state: &mut State,
+ busy: &AtomicBool,
+ request_id: &str,
+ target: &str,
+ now: SystemTime,
+) -> bool {
+ let Some(current) = state.remote_request.as_ref() else {
+ return false;
+ };
+ if current.request_id != request_id || current.target != target || current.phase != RemoteRequestPhase::AwaitingHost
+ {
+ return false;
+ }
+ state.remote_request = Some(RemoteRequestStatus::new(
+ request_id,
+ target,
+ RemoteRequestPhase::Expired,
+ None,
+ Some(REMOTE_REQUEST_EXPIRY_CODE.to_owned()),
+ now,
+ ));
+ busy.store(false, Ordering::SeqCst);
+ true
+}
+
+fn expire_remote_request(app: &AppHandle, request_id: &str, target: &str) -> bool {
+ let expired = {
+ let updater = app.state::<Updater>();
+ let mut state = updater.state.lock().expect("updater state");
+ expire_awaiting_remote_request(&mut state, &updater.busy, request_id, target, SystemTime::now())
+ };
+ if expired {
+ let updater = app.state::<Updater>();
+ let _ = updater.channel_menu.set_enabled(true);
+ publish_status(app);
+ emit_state(app);
+ }
+ expired
+}
+
+fn native_update_needs_remote_failure(phase: Phase) -> bool {
+ matches!(phase, Phase::Downloading | Phase::Installing)
+}
+
+fn end_native_update_after_remote_failure(app: &AppHandle) {
+ let should_end = {
+ let updater = app.state::<Updater>();
+ let should_end = native_update_needs_remote_failure(updater.state.lock().expect("updater state").phase);
+ should_end
+ };
+ if should_end {
+ set_state(app, Phase::Error, None);
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum RemoteRequestStart {
+ Started,
+ AlreadyHandled,
+ Busy,
+}
+
+fn claim_remote_request(
+ state: &mut State,
+ busy: &AtomicBool,
+ request: &DesktopUpdateRequest,
+ now: SystemTime,
+) -> RemoteRequestStart {
+ if state.remote_request.as_ref().is_some_and(|previous| {
+ previous.request_id == request.request_id && (previous.phase.is_terminal() || busy.load(Ordering::SeqCst))
+ }) {
+ return RemoteRequestStart::AlreadyHandled;
+ }
+ if busy
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ state.remote_request = Some(RemoteRequestStatus::new(
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::Failed,
+ None,
+ Some("update_in_progress".to_owned()),
+ now,
+ ));
+ return RemoteRequestStart::Busy;
+ }
+ state.remote_request = Some(RemoteRequestStatus::new(
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::Requested,
+ None,
+ None,
+ now,
+ ));
+ RemoteRequestStart::Started
+}
+
+fn remote_preference_can_change(state: &State) -> bool {
+ state
+ .remote_request
+ .as_ref()
+ .is_none_or(|request| request.phase.is_terminal())
+}
+
+fn startup_remote_request_outcome(
+ request: &RemoteRequestStatus,
+ current: &str,
+) -> Option<(RemoteRequestPhase, Option<&'static str>)> {
+ match request.phase {
+ RemoteRequestPhase::Restarting if request.target == current => Some((RemoteRequestPhase::Completed, None)),
+ RemoteRequestPhase::Restarting => Some((RemoteRequestPhase::Failed, Some("restart_version_mismatch"))),
+ RemoteRequestPhase::Completed
+ | RemoteRequestPhase::Failed
+ | RemoteRequestPhase::Declined
+ | RemoteRequestPhase::Expired => None,
+ RemoteRequestPhase::Requested
+ | RemoteRequestPhase::Acknowledged
+ | RemoteRequestPhase::Checking
+ | RemoteRequestPhase::AwaitingHost
+ | RemoteRequestPhase::Downloading
+ | RemoteRequestPhase::Installing => Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ }
+}
+
+fn reconcile_remote_request_on_startup(app: &AppHandle) {
+ let request = {
+ let updater = app.state::<Updater>();
+ let request = updater.state.lock().expect("updater state").remote_request.clone();
+ request
+ };
+ let Some(request) = request else {
+ return;
+ };
+ let Some((phase, error_code)) = startup_remote_request_outcome(&request, &app.package_info().version.to_string())
+ else {
+ return;
+ };
+ set_remote_phase(app, &request.request_id, &request.target, phase, None, error_code);
+}
fn label(phase: Phase, c: &Catalog) -> &str {
match phase {
Phase::Idle => &c.menu,
@@ -151,6 +465,13 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {
let status_dir = super::computer_use::state_dir(app)?;
#[cfg(not(target_os = "macos"))]
let status_dir = app.path().app_data_dir()?;
+ let status = UpdateStatusStore::new(status_dir.join(UPDATE_STATUS_FILE));
+ let remote_request = status.read().ok().flatten().and_then(|record| record.remote_request);
+ let remote_install_path = app.path().app_local_data_dir()?.join(REMOTE_INSTALL_PREFERENCE_FILE);
+ let remote_install_allowed = read_remote_install_preference(&remote_install_path).unwrap_or_else(|error| {
+ eprintln!("desktop remote-install preference: {error}");
+ false
+ });
app.manage(Updater {
state: Mutex::new(State {
phase: Phase::Idle,
@@ -158,12 +479,16 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {
channel,
manifest: None,
availability_interactive: false,
+ remote_install_allowed,
+ remote_request,
}),
busy: AtomicBool::new(false),
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)),
+ remote_install_path,
+ remote_request_path: status_dir.join(DESKTOP_UPDATE_REQUEST_FILE),
+ status,
menu: MenuItem::with_id(app, MENU_ID, &c.menu, true, None::<&str>)?,
channel_menu: CheckMenuItem::with_id(
app,
@@ -174,6 +499,7 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {
None::<&str>,
)?,
});
+ reconcile_remote_request_on_startup(app);
Ok(())
}
fn set_state(app: &AppHandle, phase: Phase, latest: Option<String>) {
@@ -210,6 +536,8 @@ fn state_snapshot(app: &AppHandle) -> DesktopUpdateState {
channel: state.channel,
skipped_version: skipped_version(&updater),
interactive: state.availability_interactive,
+ remote_install_allowed: state.remote_install_allowed,
+ remote_request: state.remote_request.as_ref().map(DesktopRemoteRequestState::from),
}
}
@@ -345,6 +673,86 @@ async fn asset(app: &AppHandle, client: &reqwest::Client, url: &str, length: Len
source.store(used, Ordering::SeqCst);
Ok(data)
}
+
+async fn asset_with_progress(
+ app: &AppHandle,
+ client: &reqwest::Client,
+ url: &str,
+ length: Length,
+ progress: impl FnMut(u64, u64) + Send,
+) -> Result<Vec<u8>, String> {
+ let source = &app.state::<Updater>().source;
+ let (data, used) = download::fetch_with_progress(
+ client,
+ &update::sources(url),
+ source.load(Ordering::SeqCst),
+ length,
+ progress,
+ )
+ .await?;
+ source.store(used, Ordering::SeqCst);
+ Ok(data)
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct RemoteInstallContext {
+ request_id: String,
+ target: String,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum RemoteDelivery {
+ Prompt,
+ Install,
+}
+
+fn remote_delivery(allowed: bool) -> RemoteDelivery {
+ if allowed {
+ RemoteDelivery::Install
+ } else {
+ RemoteDelivery::Prompt
+ }
+}
+
+fn should_publish_download_progress(current: Option<&RemoteRequestStatus>, request_id: &str, progress: u8) -> bool {
+ current.is_some_and(|current| {
+ current.request_id == request_id
+ && current.phase == RemoteRequestPhase::Downloading
+ && current.progress.is_none_or(|published| progress > published)
+ })
+}
+
+fn validate_remote_target(latest: &str, requested: &str) -> Result<(), &'static str> {
+ if latest == requested {
+ Ok(())
+ } else {
+ Err("target_mismatch")
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum RemoteRequestGateError {
+ Unavailable,
+ Expired,
+ Mismatch,
+}
+
+fn validate_remote_request_gate(
+ request: &DesktopUpdateRequest,
+ context: &RemoteInstallContext,
+ now: SystemTime,
+) -> Result<(), RemoteRequestGateError> {
+ if request.request_id != context.request_id || request.target != context.target {
+ return Err(RemoteRequestGateError::Mismatch);
+ }
+ if request.expires_in(now).is_zero() {
+ return Err(RemoteRequestGateError::Expired);
+ }
+ if !request.is_pending() {
+ return Err(RemoteRequestGateError::Mismatch);
+ }
+ Ok(())
+}
/// The mirror's index lists releases and their commits in one request; the
/// paginated GitHub API is the fallback when the mirror is unreachable.
async fn releases(client: &reqwest::Client) -> Result<Vec<Release>, String> {
@@ -443,19 +851,16 @@ 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) {
+ // Install progress and outcomes stay in memory: a failed install keeps
+ // the last `Available`, and the new app's startup check publishes
+ // `Current` after a successful hand-over.
+ fn publish_check(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;
};
+ let record = record.with_remote(state.remote_install_allowed, state.remote_request.clone());
if let Err(error) = updater.status.write(&record) {
eprintln!("desktop update status: {error}");
}
@@ -471,7 +876,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);
+ publish_check(&app);
if interactive {
show(&app, &catalog().disabled_detail, None);
}
@@ -484,7 +889,7 @@ pub fn check(app: AppHandle, interactive: bool) {
match find_update(&app, channel).await {
Ok(Some(manifest)) => {
set_available(&app, manifest.clone());
- publish(&app);
+ publish_check(&app);
let skipped = skipped_version(&app.state::<Updater>());
if !should_prompt(interactive, skipped.as_deref(), &manifest.version) {
finish(&app);
@@ -528,7 +933,7 @@ pub fn check(app: AppHandle, interactive: bool) {
Ok(None) => {
finish(&app);
set_state(&app, Phase::Current, None);
- publish(&app);
+ publish_check(&app);
if interactive {
let latest = app
.state::<Updater>()
@@ -544,7 +949,7 @@ pub fn check(app: AppHandle, interactive: bool) {
eprintln!("desktop update check: {error}");
finish(&app);
set_state(&app, Phase::Error, None);
- publish(&app);
+ publish_check(&app);
if interactive {
show(&app, &catalog().check_failed, None);
}
@@ -566,27 +971,63 @@ pub fn desktop_update_check(window: WebviewWindow, app: AppHandle) -> Result<(),
Ok(())
}
+#[tauri::command]
+pub fn desktop_remote_install_allowed(window: WebviewWindow, app: AppHandle) -> Result<bool, String> {
+ ensure_workbench(&window)?;
+ Ok(app
+ .state::<Updater>()
+ .state
+ .lock()
+ .expect("updater state")
+ .remote_install_allowed)
+}
+
+#[tauri::command]
+pub fn desktop_remote_install_set(window: WebviewWindow, app: AppHandle, enabled: bool) -> Result<bool, String> {
+ ensure_workbench(&window)?;
+ let updater = app.state::<Updater>();
+ {
+ let mut state = updater.state.lock().expect("updater state");
+ if !remote_preference_can_change(&state) {
+ return Err("Remote install preference cannot change while an update request is active.".to_owned());
+ }
+ write_remote_install_preference(&updater.remote_install_path, enabled)
+ .map_err(|error| format!("Remote install preference could not be saved: {error}"))?;
+ state.remote_install_allowed = enabled;
+ }
+ publish_status(&app);
+ emit_state(&app);
+ Ok(enabled)
+}
+
#[tauri::command]
pub fn desktop_update_install(window: WebviewWindow, app: AppHandle) -> Result<(), String> {
ensure_workbench(&window)?;
let updater = app.state::<Updater>();
- let manifest = {
+ let (manifest, remote) = {
let state = updater
.state
.lock()
.map_err(|_| "Desktop updater state is unavailable.".to_owned())?;
- if state.phase != Phase::Available {
+ let remote = state.remote_request.as_ref().and_then(|request| {
+ (request.phase == RemoteRequestPhase::AwaitingHost).then(|| RemoteInstallContext {
+ request_id: request.request_id.clone(),
+ target: request.target.clone(),
+ })
+ });
+ if remote.is_none() && state.phase != Phase::Available {
return Err("No desktop update is ready to install.".to_owned());
}
- state
+ let manifest = state
.manifest
.clone()
- .ok_or_else(|| "No desktop update is ready to install.".to_owned())?
+ .ok_or_else(|| "No desktop update is ready to install.".to_owned())?;
+ (manifest, remote)
};
- if updater.busy.swap(true, Ordering::SeqCst) {
+ if remote.is_none() && updater.busy.swap(true, Ordering::SeqCst) {
return Err("A desktop update is already in progress.".to_owned());
}
- install(app, manifest);
+ install_with_context(app, manifest, remote);
Ok(())
}
@@ -599,6 +1040,13 @@ pub fn desktop_update_skip(window: WebviewWindow, app: AppHandle) -> Result<(),
.state
.lock()
.map_err(|_| "Desktop updater state is unavailable.".to_owned())?;
+ if state
+ .remote_request
+ .as_ref()
+ .is_some_and(|request| request.phase == RemoteRequestPhase::AwaitingHost)
+ {
+ return Err("A remote desktop update is waiting for host action; use Ignore.".to_owned());
+ }
if state.phase != Phase::Available {
return Err("No desktop update is available to skip.".to_owned());
}
@@ -611,28 +1059,314 @@ pub fn desktop_update_skip(window: WebviewWindow, app: AppHandle) -> Result<(),
finish(&app);
Ok(())
}
+
+#[tauri::command]
+pub fn desktop_update_remote_decline(window: WebviewWindow, app: AppHandle) -> Result<(), String> {
+ ensure_workbench(&window)?;
+ let request = {
+ let updater = app.state::<Updater>();
+ let request = updater
+ .state
+ .lock()
+ .map_err(|_| "Desktop updater state is unavailable.".to_owned())?
+ .remote_request
+ .clone();
+ request
+ };
+ let Some(request) = request.filter(|request| request.phase == RemoteRequestPhase::AwaitingHost) else {
+ return Err("No remote desktop update is waiting for host action.".to_owned());
+ };
+ set_remote_phase(
+ &app,
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::Declined,
+ None,
+ None,
+ );
+ finish(&app);
+ Ok(())
+}
+
+fn reread_remote_request(app: &AppHandle, context: &RemoteInstallContext) -> Result<(), RemoteRequestGateError> {
+ let path = app.state::<Updater>().remote_request_path.clone();
+ let request = match read_desktop_update_request(&path, SystemTime::now()) {
+ Ok(request) => request,
+ Err(DesktopUpdateRequestError::Expired(_)) => return Err(RemoteRequestGateError::Expired),
+ Err(_) => return Err(RemoteRequestGateError::Unavailable),
+ };
+ validate_remote_request_gate(&request, context, SystemTime::now())
+}
+
+fn record_remote_gate_failure(
+ app: &AppHandle,
+ context: &RemoteInstallContext,
+ error: RemoteRequestGateError,
+) -> String {
+ let (phase, code) = match error {
+ RemoteRequestGateError::Expired => (RemoteRequestPhase::Expired, "expired"),
+ RemoteRequestGateError::Unavailable => (RemoteRequestPhase::Failed, "request_unavailable"),
+ RemoteRequestGateError::Mismatch => (RemoteRequestPhase::Failed, "request_mismatch"),
+ };
+ set_remote_phase(app, &context.request_id, &context.target, phase, None, Some(code));
+ end_native_update_after_remote_failure(app);
+ code.to_owned()
+}
+
+fn finish_remote_gate_failure(
+ app: &AppHandle,
+ context: &RemoteInstallContext,
+ error: RemoteRequestGateError,
+) -> String {
+ let code = record_remote_gate_failure(app, context, error);
+ finish(app);
+ code
+}
+
+fn notify_remote_request(app: &AppHandle) {
+ let c = catalog();
+ if app
+ .notification()
+ .builder()
+ .title(c.title)
+ .body(c.available)
+ .show()
+ .is_err()
+ {
+ eprintln!("The desktop update notification could not be submitted to the operating system.");
+ }
+}
+
+fn schedule_remote_expiry(app: &AppHandle, request: DesktopUpdateRequest) {
+ let wait = request.expires_in(SystemTime::now());
+ let handle = app.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(wait).await;
+ expire_remote_request(&handle, &request.request_id, &request.target);
+ });
+}
+
+fn fail_remote_request(app: &AppHandle, request: &DesktopUpdateRequest, error_code: &'static str) {
+ set_remote_phase(
+ app,
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::Failed,
+ None,
+ Some(error_code),
+ );
+ finish(app);
+}
+
+pub fn handle_remote_update_request(app: &AppHandle) {
+ let request_path = app.state::<Updater>().remote_request_path.clone();
+ let request = match read_desktop_update_request(&request_path, SystemTime::now()) {
+ Ok(request) => request,
+ Err(DesktopUpdateRequestError::Expired(request)) => {
+ expire_remote_request(app, &request.request_id, &request.target);
+ return;
+ }
+ Err(_) => return,
+ };
+ let updater = app.state::<Updater>();
+ let start = {
+ let mut state = updater.state.lock().expect("updater state");
+ claim_remote_request(&mut state, &updater.busy, &request, SystemTime::now())
+ };
+ if start == RemoteRequestStart::AlreadyHandled {
+ return;
+ }
+ publish_status(app);
+ emit_state(app);
+ if start == RemoteRequestStart::Busy {
+ return;
+ }
+ let handle = app.clone();
+ tauri::async_runtime::spawn(async move {
+ process_remote_update_request(handle, request).await;
+ });
+}
+
+async fn process_remote_update_request(app: AppHandle, request: DesktopUpdateRequest) {
+ let remote_install_allowed = app
+ .state::<Updater>()
+ .state
+ .lock()
+ .expect("updater state")
+ .remote_install_allowed;
+ set_remote_phase(
+ &app,
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::Acknowledged,
+ None,
+ None,
+ );
+ set_remote_phase(
+ &app,
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::Checking,
+ None,
+ None,
+ );
+ let channel = app.state::<Updater>().state.lock().expect("updater state").channel;
+ match find_update(&app, channel).await {
+ Ok(Some(manifest)) => {
+ app.state::<Updater>()
+ .state
+ .lock()
+ .expect("updater state")
+ .availability_interactive = true;
+ set_available(&app, manifest.clone());
+ if let Err(error_code) = validate_remote_target(&manifest.version, &request.target) {
+ fail_remote_request(&app, &request, error_code);
+ return;
+ }
+ publish_status(&app);
+ let remote = RemoteInstallContext {
+ request_id: request.request_id.clone(),
+ target: request.target.clone(),
+ };
+ if let Err(error) = reread_remote_request(&app, &remote) {
+ let code = finish_remote_gate_failure(&app, &remote, error);
+ eprintln!("remote desktop update request gate: {code}");
+ return;
+ }
+ match remote_delivery(remote_install_allowed) {
+ RemoteDelivery::Install => install_with_context(app, manifest, Some(remote)),
+ RemoteDelivery::Prompt => {
+ set_remote_phase(
+ &app,
+ &request.request_id,
+ &request.target,
+ RemoteRequestPhase::AwaitingHost,
+ None,
+ None,
+ );
+ super::request_and_open_desktop_updates(&app);
+ notify_remote_request(&app);
+ schedule_remote_expiry(&app, request);
+ }
+ }
+ }
+ Ok(None) => {
+ set_state(&app, Phase::Current, None);
+ publish_status(&app);
+ fail_remote_request(&app, &request, "target_mismatch");
+ }
+ Err(error) => {
+ eprintln!("remote desktop update check: {error}");
+ set_state(&app, Phase::Error, None);
+ publish_status(&app);
+ fail_remote_request(&app, &request, "check_failed");
+ }
+ }
+}
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) {
+ install_with_context(app, manifest, None);
+}
+
+fn install_with_context(app: AppHandle, manifest: Manifest, remote: Option<RemoteInstallContext>) {
+ if let Some(remote) = &remote {
+ if let Err(error) = reread_remote_request(&app, remote) {
+ let code = finish_remote_gate_failure(&app, remote, error);
+ eprintln!("remote desktop update request gate: {code}");
+ return;
+ }
+ }
set_state(&app, Phase::Downloading, None);
+ if let Some(remote) = &remote {
+ set_remote_phase(
+ &app,
+ &remote.request_id,
+ &remote.target,
+ RemoteRequestPhase::Downloading,
+ Some(0),
+ None,
+ );
+ }
tauri::async_runtime::spawn(async move {
let result = async {
let artifact = manifest
.validate(manifest.channel, &manifest.tag, &manifest.source_sha, TARGET)?
.clone();
let download = match client() {
- Ok(client) => asset(&app, &client, &artifact.url, Length::Exact(artifact.size)).await,
+ Ok(client) => {
+ let progress_app = app.clone();
+ let progress_remote = remote.clone();
+ asset_with_progress(
+ &app,
+ &client,
+ &artifact.url,
+ Length::Exact(artifact.size),
+ move |received, total| {
+ let Some(remote) = &progress_remote else {
+ return;
+ };
+ let progress = if total == 0 {
+ 0
+ } else {
+ received.saturating_mul(100).checked_div(total).unwrap_or(0).min(100) as u8
+ };
+ set_remote_phase_if(
+ &progress_app,
+ &remote.request_id,
+ &remote.target,
+ RemoteRequestPhase::Downloading,
+ Some(progress),
+ None,
+ |current| should_publish_download_progress(current, &remote.request_id, progress),
+ );
+ },
+ )
+ .await
+ }
Err(error) => Err(error),
};
let handle = app.clone();
+ let install_remote = remote.clone();
+ let install_version = manifest.version.clone();
tauri::async_runtime::spawn_blocking(move || {
update::install_verified(download, &artifact, KEY, |data| {
+ if let Some(remote) = &install_remote {
+ if let Err(error) = reread_remote_request(&handle, remote) {
+ let code = record_remote_gate_failure(&handle, remote, error);
+ return Err(format!("remote_request_gate:{code}"));
+ }
+ }
set_state(&handle, Phase::Installing, None);
- super::update_install::install(&handle, data, &manifest.version)
+ if let Some(remote) = &install_remote {
+ set_remote_phase(
+ &handle,
+ &remote.request_id,
+ &remote.target,
+ RemoteRequestPhase::Installing,
+ None,
+ None,
+ );
+ }
+ let before_exit_remote = install_remote.clone();
+ let before_exit_app = handle.clone();
+ super::update_install::install_with_before_exit(&handle, data, &install_version, move || {
+ if let Some(remote) = before_exit_remote {
+ set_remote_phase(
+ &before_exit_app,
+ &remote.request_id,
+ &remote.target,
+ RemoteRequestPhase::Restarting,
+ None,
+ None,
+ );
+ }
+ })
})
})
.await
@@ -640,10 +1374,21 @@ fn install(app: AppHandle, manifest: Manifest) {
Ok::<(), String>(())
}
.await;
- finish(&app);
match result {
Ok(()) => {
- set_state(&app, Phase::Installed, None);
+ if let Some(remote) = &remote {
+ set_remote_phase(
+ &app,
+ &remote.request_id,
+ &remote.target,
+ RemoteRequestPhase::Restarting,
+ None,
+ None,
+ );
+ } else {
+ set_state(&app, Phase::Installed, None);
+ }
+ finish(&app);
#[cfg(target_os = "macos")]
{
super::restart_after_computer_use_shutdown(app);
@@ -651,7 +1396,29 @@ fn install(app: AppHandle, manifest: Manifest) {
}
Err(error) => {
eprintln!("desktop update install: {error}");
- set_state(&app, Phase::Error, None);
+ if error.strip_prefix("remote_request_gate:").is_some() {
+ finish(&app);
+ return;
+ }
+ if let Some(remote) = &remote {
+ let error_code = if error == "requires_host" {
+ "requires_host"
+ } else {
+ "install_failed"
+ };
+ set_remote_phase(
+ &app,
+ &remote.request_id,
+ &remote.target,
+ RemoteRequestPhase::Failed,
+ None,
+ Some(error_code),
+ );
+ end_native_update_after_remote_failure(&app);
+ } else {
+ set_state(&app, Phase::Error, None);
+ }
+ finish(&app);
if !workbench_ready(&app) {
app.dialog()
.message(catalog().install_failed)
@@ -667,6 +1434,26 @@ fn install(app: AppHandle, manifest: Manifest) {
#[cfg(test)]
mod tests {
use super::*;
+
+ fn state_with_remote_request(request_id: &str, target: &str, phase: RemoteRequestPhase) -> State {
+ State {
+ phase: Phase::Available,
+ latest: Some(target.to_owned()),
+ channel: Channel::Stable,
+ manifest: None,
+ availability_interactive: true,
+ remote_install_allowed: false,
+ remote_request: Some(RemoteRequestStatus::new(
+ request_id,
+ target,
+ phase,
+ None,
+ None,
+ SystemTime::UNIX_EPOCH,
+ )),
+ }
+ }
+
#[test]
fn dialog_buttons_map_to_one_choice_and_dismissal_is_later() {
for locale in ["en", "zh"] {
@@ -724,6 +1511,8 @@ mod tests {
channel: Channel::Test,
skipped_version: Some("3.2.3".to_owned()),
interactive: true,
+ remote_install_allowed: false,
+ remote_request: None,
};
assert_eq!(
serde_json::to_value(state).unwrap(),
@@ -733,6 +1522,8 @@ mod tests {
"channel": "test",
"skippedVersion": "3.2.3",
"interactive": true,
+ "remoteInstallAllowed": false,
+ "remoteRequest": null,
})
);
}
@@ -756,6 +1547,8 @@ mod tests {
channel: Channel::Test,
manifest: None,
availability_interactive: false,
+ remote_install_allowed: false,
+ remote_request: None,
};
let expected = match phase {
Phase::Current => Some(UpdateStatusPhase::Current),
@@ -772,6 +1565,479 @@ mod tests {
}
}
+ #[test]
+ fn completed_remote_check_replaces_the_ordinary_result_and_preserves_remote_state() {
+ let previous = UpdateStatusRecord::new(
+ UpdateStatusPhase::Available,
+ "3.2.2",
+ Some("3.2.3".to_owned()),
+ Channel::Test,
+ SystemTime::UNIX_EPOCH,
+ );
+ let remote = RemoteRequestStatus::new(
+ "00000000-0000-4000-8000-000000000000",
+ "3.2.4",
+ RemoteRequestPhase::Failed,
+ None,
+ Some("target_mismatch".to_owned()),
+ SystemTime::UNIX_EPOCH,
+ );
+ let mut state = State {
+ phase: Phase::Error,
+ latest: Some("3.2.4".to_owned()),
+ channel: Channel::Stable,
+ manifest: None,
+ availability_interactive: true,
+ remote_install_allowed: true,
+ remote_request: Some(remote.clone()),
+ };
+
+ let published = status_for_publish(&state, "3.2.2", Some(previous.clone()), SystemTime::UNIX_EPOCH)
+ .with_remote(state.remote_install_allowed, state.remote_request.clone());
+ assert_eq!(published.phase, UpdateStatusPhase::Error);
+ assert_eq!(published.channel, Channel::Stable);
+ assert_eq!(published.latest, None);
+ assert_eq!(published.remote_request, Some(remote));
+
+ state.phase = Phase::Checking;
+ assert_eq!(
+ status_for_publish(&state, "3.2.2", Some(previous.clone()), SystemTime::UNIX_EPOCH,),
+ previous,
+ "in-flight phases keep the last completed ordinary result"
+ );
+ }
+
+ #[test]
+ fn remote_explicit_check_bypasses_a_saved_skip_without_rewriting_it() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("update-skipped.json");
+ persist_skipped_version(&path, "3.2.3").unwrap();
+
+ assert!(should_prompt(true, Some("3.2.3"), "3.2.3"));
+ assert_eq!(
+ serde_json::from_slice::<String>(&std::fs::read(path).unwrap()).unwrap(),
+ "3.2.3",
+ "a remote explicit check must not mutate the global skip preference"
+ );
+ }
+
+ #[test]
+ fn remote_delivery_is_selected_only_by_the_local_shell_preference() {
+ assert_eq!(remote_delivery(false), RemoteDelivery::Prompt);
+ assert_eq!(remote_delivery(true), RemoteDelivery::Install);
+ }
+
+ #[test]
+ fn remote_download_progress_never_regresses_across_source_retries() {
+ let current = RemoteRequestStatus::new(
+ "00000000-0000-4000-8000-000000000000",
+ "3.2.4",
+ RemoteRequestPhase::Downloading,
+ Some(42),
+ None,
+ SystemTime::UNIX_EPOCH,
+ );
+
+ assert!(!should_publish_download_progress(
+ Some(&current),
+ &current.request_id,
+ 0
+ ));
+ assert!(!should_publish_download_progress(
+ Some(&current),
+ &current.request_id,
+ 42
+ ));
+ assert!(should_publish_download_progress(
+ Some(&current),
+ &current.request_id,
+ 43
+ ));
+ }
+
+ #[test]
+ fn duplicate_nudges_cannot_turn_the_active_request_into_a_busy_failure() {
+ let request = DesktopUpdateRequest::parse(
+ serde_json::to_string(&serde_json::json!({
+ "schema_version": 1,
+ "request_id": "00000000-0000-4000-8000-000000000000",
+ "target": "3.2.4",
+ "state": "pending",
+ "created_at": "1970-01-01T00:01:40Z",
+ "expires_at": "1970-01-01T00:02:40Z",
+ }))
+ .unwrap()
+ .as_bytes(),
+ SystemTime::UNIX_EPOCH + Duration::from_secs(100),
+ )
+ .unwrap();
+ let mut state = State {
+ phase: Phase::Idle,
+ latest: None,
+ channel: Channel::Stable,
+ manifest: None,
+ availability_interactive: false,
+ remote_install_allowed: false,
+ remote_request: None,
+ };
+ let busy = AtomicBool::new(false);
+
+ assert_eq!(
+ claim_remote_request(
+ &mut state,
+ &busy,
+ &request,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(101),
+ ),
+ RemoteRequestStart::Started
+ );
+ assert!(busy.load(Ordering::SeqCst));
+ assert_eq!(
+ claim_remote_request(
+ &mut state,
+ &busy,
+ &request,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(102),
+ ),
+ RemoteRequestStart::AlreadyHandled
+ );
+ assert_eq!(
+ state.remote_request.as_ref().map(|status| status.phase),
+ Some(RemoteRequestPhase::Requested)
+ );
+ }
+
+ #[test]
+ fn remote_transitions_preserve_terminal_and_newer_receipts() {
+ let request_id = "00000000-0000-4000-8000-000000000000";
+ let receipt = |id, phase| RemoteRequestStatus::new(id, "3.2.4", phase, None, None, SystemTime::UNIX_EPOCH);
+
+ for phase in [
+ RemoteRequestPhase::Requested,
+ RemoteRequestPhase::Acknowledged,
+ RemoteRequestPhase::Checking,
+ RemoteRequestPhase::AwaitingHost,
+ RemoteRequestPhase::Downloading,
+ RemoteRequestPhase::Installing,
+ RemoteRequestPhase::Restarting,
+ ] {
+ let current = receipt(request_id, phase);
+ assert!(remote_request_can_transition(Some(&current), request_id));
+ }
+ for phase in [
+ RemoteRequestPhase::Completed,
+ RemoteRequestPhase::Failed,
+ RemoteRequestPhase::Declined,
+ RemoteRequestPhase::Expired,
+ ] {
+ let current = receipt(request_id, phase);
+ assert!(!remote_request_can_transition(Some(&current), request_id));
+ }
+ assert!(remote_request_can_transition(None, request_id));
+ assert!(!remote_request_can_transition(
+ Some(&receipt(
+ "11111111-1111-4111-8111-111111111111",
+ RemoteRequestPhase::Requested,
+ )),
+ request_id,
+ ));
+ }
+
+ #[test]
+ fn remote_expiry_is_order_independent_for_poll_and_timer() {
+ let request_id = "00000000-0000-4000-8000-000000000000";
+ let target = "3.2.4";
+
+ for (first, second) in [("poll", "timer"), ("timer", "poll")] {
+ let mut state = state_with_remote_request(request_id, target, RemoteRequestPhase::AwaitingHost);
+ let busy = AtomicBool::new(true);
+
+ assert!(
+ expire_awaiting_remote_request(
+ &mut state,
+ &busy,
+ request_id,
+ target,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1),
+ ),
+ "{first} wins the expiry race",
+ );
+ let expired = state.remote_request.clone();
+ assert!(!busy.load(Ordering::SeqCst));
+ assert!(
+ !expire_awaiting_remote_request(
+ &mut state,
+ &busy,
+ request_id,
+ target,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(2),
+ ),
+ "{second} observes the terminal receipt",
+ );
+ assert_eq!(state.remote_request, expired);
+ assert!(!busy.load(Ordering::SeqCst));
+ }
+ }
+
+ #[test]
+ fn remote_expiry_preserves_every_terminal_receipt_and_its_gate() {
+ let request_id = "00000000-0000-4000-8000-000000000000";
+ let target = "3.2.4";
+
+ for phase in [
+ RemoteRequestPhase::Completed,
+ RemoteRequestPhase::Failed,
+ RemoteRequestPhase::Declined,
+ RemoteRequestPhase::Expired,
+ ] {
+ let mut state = state_with_remote_request(request_id, target, phase);
+ let before = state.remote_request.clone();
+ let busy = AtomicBool::new(true);
+
+ assert!(!expire_awaiting_remote_request(
+ &mut state,
+ &busy,
+ request_id,
+ target,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1),
+ ));
+ assert_eq!(state.remote_request, before, "{phase:?}");
+ assert!(busy.load(Ordering::SeqCst), "{phase:?}");
+ }
+ }
+
+ #[test]
+ fn remote_expiry_does_not_release_an_active_update_gate() {
+ let request_id = "00000000-0000-4000-8000-000000000000";
+ let target = "3.2.4";
+
+ for phase in [
+ RemoteRequestPhase::Requested,
+ RemoteRequestPhase::Acknowledged,
+ RemoteRequestPhase::Checking,
+ RemoteRequestPhase::Downloading,
+ RemoteRequestPhase::Installing,
+ RemoteRequestPhase::Restarting,
+ ] {
+ let mut state = state_with_remote_request(request_id, target, phase);
+ let before = state.remote_request.clone();
+ let busy = AtomicBool::new(true);
+
+ assert!(!expire_awaiting_remote_request(
+ &mut state,
+ &busy,
+ request_id,
+ target,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1),
+ ));
+ assert_eq!(state.remote_request, before, "{phase:?}");
+ assert!(busy.load(Ordering::SeqCst), "{phase:?}");
+ }
+ }
+
+ #[test]
+ fn stale_remote_expiry_cannot_mutate_a_newer_request_or_gate() {
+ let current_request_id = "11111111-1111-4111-8111-111111111111";
+ let current_target = "3.2.5";
+ let mut state = state_with_remote_request(current_request_id, current_target, RemoteRequestPhase::AwaitingHost);
+ let before = state.remote_request.clone();
+ let busy = AtomicBool::new(true);
+
+ for (request_id, target) in [
+ ("00000000-0000-4000-8000-000000000000", "3.2.4"),
+ (current_request_id, "3.2.4"),
+ ] {
+ assert!(!expire_awaiting_remote_request(
+ &mut state,
+ &busy,
+ request_id,
+ target,
+ SystemTime::UNIX_EPOCH + Duration::from_secs(1),
+ ));
+ assert_eq!(state.remote_request, before);
+ assert!(busy.load(Ordering::SeqCst));
+ }
+ }
+
+ #[test]
+ fn remote_install_failures_end_every_native_progress_phase() {
+ for phase in [
+ Phase::Idle,
+ Phase::Checking,
+ Phase::Current,
+ Phase::Available,
+ Phase::Downloading,
+ Phase::Installing,
+ Phase::Installed,
+ Phase::Disabled,
+ Phase::Error,
+ ] {
+ assert_eq!(
+ native_update_needs_remote_failure(phase),
+ matches!(phase, Phase::Downloading | Phase::Installing),
+ "{phase:?}",
+ );
+ }
+ }
+
+ #[test]
+ fn remote_install_preference_is_stable_for_the_lifetime_of_a_request() {
+ let remote = |phase| {
+ RemoteRequestStatus::new(
+ "00000000-0000-4000-8000-000000000000",
+ "3.2.4",
+ phase,
+ None,
+ None,
+ SystemTime::UNIX_EPOCH,
+ )
+ };
+ let mut state = State {
+ phase: Phase::Idle,
+ latest: None,
+ channel: Channel::Stable,
+ manifest: None,
+ availability_interactive: false,
+ remote_install_allowed: false,
+ remote_request: None,
+ };
+
+ assert!(remote_preference_can_change(&state));
+ state.remote_request = Some(remote(RemoteRequestPhase::Checking));
+ assert!(!remote_preference_can_change(&state));
+ state.remote_request = Some(remote(RemoteRequestPhase::Completed));
+ assert!(remote_preference_can_change(&state));
+ }
+
+ #[test]
+ fn remote_target_must_equal_the_fresh_current_channel_result() {
+ assert_eq!(validate_remote_target("3.2.4", "3.2.4"), Ok(()));
+ assert_eq!(validate_remote_target("3.2.5", "3.2.4"), Err("target_mismatch"));
+ }
+
+ #[test]
+ fn remote_install_preference_defaults_off_and_round_trips_locally() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("remote-install.json");
+ assert!(!read_remote_install_preference(&path).unwrap());
+
+ write_remote_install_preference(&path, true).unwrap();
+ assert!(read_remote_install_preference(&path).unwrap());
+ write_remote_install_preference(&path, false).unwrap();
+ assert!(!read_remote_install_preference(&path).unwrap());
+ }
+
+ #[test]
+ fn remote_request_gate_rejects_replacement_and_expiry() {
+ let created = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
+ let expires = created + Duration::from_secs(60);
+ let request = DesktopUpdateRequest::parse(
+ serde_json::to_string(&serde_json::json!({
+ "schema_version": 1,
+ "request_id": "00000000-0000-4000-8000-000000000000",
+ "target": "3.2.4",
+ "state": "pending",
+ "created_at": "1970-01-01T00:01:40Z",
+ "expires_at": "1970-01-01T00:02:40Z",
+ }))
+ .unwrap()
+ .as_bytes(),
+ created,
+ )
+ .unwrap();
+ let context = RemoteInstallContext {
+ request_id: request.request_id.clone(),
+ target: request.target.clone(),
+ };
+
+ assert_eq!(validate_remote_request_gate(&request, &context, created), Ok(()));
+ assert_eq!(
+ validate_remote_request_gate(
+ &request,
+ &RemoteInstallContext {
+ request_id: "11111111-1111-4111-8111-111111111111".to_owned(),
+ target: context.target.clone(),
+ },
+ created,
+ ),
+ Err(RemoteRequestGateError::Mismatch)
+ );
+ assert_eq!(
+ validate_remote_request_gate(&request, &context, expires),
+ Err(RemoteRequestGateError::Expired)
+ );
+ }
+
+ #[test]
+ fn startup_reconciliation_settles_every_persisted_remote_phase() {
+ let request = |phase| {
+ RemoteRequestStatus::new(
+ "00000000-0000-4000-8000-000000000000",
+ "3.2.4",
+ phase,
+ None,
+ None,
+ SystemTime::UNIX_EPOCH,
+ )
+ };
+ for (phase, expected) in [
+ (
+ RemoteRequestPhase::Requested,
+ Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ ),
+ (
+ RemoteRequestPhase::Acknowledged,
+ Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ ),
+ (
+ RemoteRequestPhase::Checking,
+ Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ ),
+ (
+ RemoteRequestPhase::AwaitingHost,
+ Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ ),
+ (
+ RemoteRequestPhase::Downloading,
+ Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ ),
+ (
+ RemoteRequestPhase::Installing,
+ Some((RemoteRequestPhase::Failed, Some("shell_interrupted"))),
+ ),
+ (
+ RemoteRequestPhase::Restarting,
+ Some((RemoteRequestPhase::Completed, None)),
+ ),
+ (RemoteRequestPhase::Completed, None),
+ (RemoteRequestPhase::Failed, None),
+ (RemoteRequestPhase::Declined, None),
+ (RemoteRequestPhase::Expired, None),
+ ] {
+ assert_eq!(
+ startup_remote_request_outcome(&request(phase), "3.2.4"),
+ expected,
+ "{phase:?}",
+ );
+ }
+ }
+
+ #[test]
+ fn restart_receipt_fails_when_the_new_shell_version_does_not_match() {
+ let request = RemoteRequestStatus::new(
+ "00000000-0000-4000-8000-000000000000",
+ "3.2.4",
+ RemoteRequestPhase::Restarting,
+ None,
+ None,
+ SystemTime::UNIX_EPOCH,
+ );
+ assert_eq!(
+ startup_remote_request_outcome(&request, "3.2.3"),
+ Some((RemoteRequestPhase::Failed, Some("restart_version_mismatch")))
+ );
+ }
+
#[test]
fn every_native_update_state_has_localized_copy() {
for locale in ["en", "zh"] {
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index 4e65e4b62..711a1b374 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -127,7 +127,10 @@ fn desktop_update_commands_are_workbench_scoped() {
"allow-desktop-update-state",
"allow-desktop-update-check",
"allow-desktop-update-install",
- "allow-desktop-update-skip"
+ "allow-desktop-update-skip",
+ "allow-desktop-remote-install-allowed",
+ "allow-desktop-remote-install-set",
+ "allow-desktop-update-remote-decline"
])
);
let source = shipping_source("src/lib.rs");
@@ -136,6 +139,9 @@ fn desktop_update_commands_are_workbench_scoped() {
"updater::desktop_update_check",
"updater::desktop_update_install",
"updater::desktop_update_skip",
+ "updater::desktop_remote_install_allowed",
+ "updater::desktop_remote_install_set",
+ "updater::desktop_update_remote_decline",
] {
assert!(source.contains(command), "missing Workbench updater command {command}");
}
@@ -455,6 +461,9 @@ fn every_shell_command_is_declared_so_its_permission_exists() {
"pet_reset_shortcuts",
"pet_set_voice_mode",
"pet_reset_voice_shortcut",
+ "desktop_remote_install_allowed",
+ "desktop_remote_install_set",
+ "desktop_update_remote_decline",
"pet_ready",
"pet_context_menu",
"pet_set_expanded",
@@ -1136,6 +1145,36 @@ fn updates_have_one_native_owner_and_one_scoped_workbench_control_path() {
assert!(include_str!("../build.rs").contains("desktop_update_install"));
}
+#[test]
+fn windows_remote_update_refuses_an_unwritable_install_before_shell_exit() {
+ let installer = include_str!("../src/update_install.rs");
+ let helper = include_str!("../src/update_windows.ps1");
+ let windows_installer = installer
+ .split("#[cfg(target_os = \"windows\")]")
+ .nth(1)
+ .expect("Windows installer")
+ .split("#[cfg(not(any(target_os = \"macos\", target_os = \"windows\")))]")
+ .next()
+ .expect("Windows installer body");
+
+ let marker = helper.find("'requires-host'").expect("requires-host marker");
+ let ready = helper.find("[IO.File]::WriteAllText($ready").expect("ready marker");
+ assert!(
+ marker < ready,
+ "write access must be proved before the helper permits shell exit"
+ );
+
+ let wait_for_marker = windows_installer
+ .find("while !staging.path().join(\"ready\").exists() && !requires_host.exists()")
+ .expect("Rust waits for ready or requires-host");
+ let before_exit = windows_installer.find("before_exit();").expect("pre-exit receipt");
+ assert!(
+ wait_for_marker < before_exit,
+ "a privileged install must return requires_host before the shell records restart and exits"
+ );
+ assert!(windows_installer.contains("return Err(\"requires_host\".into());"));
+}
+
#[test]
fn workbench_window_permissions_are_narrow_and_match_literal_loopback_origins() {
use tauri::utils::acl::RemoteUrlPattern;
diff --git a/docs/plans/2026-10-29-remote-desktop-update.md b/docs/plans/2026-10-29-remote-desktop-update.md
new file mode 100644
index 000000000..e5953671f
--- /dev/null
+++ b/docs/plans/2026-10-29-remote-desktop-update.md
@@ -0,0 +1,251 @@
+# Remote Desktop Update Contract
+
+## Goal
+
+An Instance Member or Owner using a browser can request an update of a
+desktop-managed host. The request always enters the existing signed Rust
+updater. By default the host prompts a local user before installation. A local
+desktop-only preference may allow the same request to install without another
+click.
+
+For `managed_by: "desktop"`, this change does not reuse `/api/upgrade`, pip, or
+uv. Non-desktop packaged installs retain the existing Python `/api/upgrade`
+path, and source checkouts retain their existing build-refresh behavior. The
+change does not add remote control of the desktop preference.
+
+## Trust Boundaries
+
+- `POST /api/desktop/update/request` is explicitly Member-level, like
+ `/api/upgrade`, and remains behind the existing same-origin and CSRF
+ middleware. Editors and Viewers receive the same 403 response.
+- The Runtime is the only component that writes
+ `desktop-update-request.json`. A request is written only after authorization,
+ interruption confirmation, and desktop-managed availability checks pass.
+- SSE event `desktop.update.requested` is a nudge only. The shell ignores its
+ payload and acts only after reading and validating the request file.
+- The shell performs a fresh release check on its current channel, requires the
+ authenticated manifest's version to equal the requested target, and uses the
+ existing signature, artifact verification, replacement, restart, and bundled
+ Runtime hand-over path.
+- `remote-install.json` is shell-owned and defaults to disabled. It is read and
+ written only through Tauri IPC granted to the main Workbench window at the
+ adopted loopback origin. HTTP clients can only read the resulting value from
+ `/api/version`. The shell rejects preference changes while a remote request
+ is active, so the delivery reported at acknowledgement stays fixed for that
+ request.
+
+## Request File
+
+`desktop-update-request.json` lives beside `update-status.json`.
+
+```json
+{
+ "schema_version": 1,
+ "request_id": "UUID",
+ "target": "3.2.4-rc.1",
+ "state": "pending",
+ "created_at": "2026-10-29T02:00:00Z",
+ "expires_at": "2026-10-29T02:30:00Z"
+}
+```
+
+The Runtime writes the file with create, flush, `fsync`, and atomic replace
+after the Member role and browser mutation guards pass. The only states are
+`pending` and `expired`. On a ten-second acknowledgement timeout, the Runtime
+atomically changes the matching pending file to `expired` before returning
+`desktop_shell_unavailable`. The shell re-reads the file before installation
+and accepts only the same unexpired pending request.
+
+One request may be active. A retry with the same target while that request is
+non-terminal returns the existing `request_id`; another target returns
+`update_in_progress`. A terminal, declined, or expired request is never reused:
+the next accepted request gets a new UUID and replaces the old file.
+
+## Status File
+
+The shell extends schema version 1 of `update-status.json` additively:
+
+```json
+{
+ "schema_version": 1,
+ "phase": "available",
+ "current": "3.2.3-rc.11",
+ "latest": "3.2.4-rc.1",
+ "channel": "test",
+ "has_update": true,
+ "checked_at": "2026-10-29T02:00:00Z",
+ "remote_install_allowed": false,
+ "remote_request": {
+ "request_id": "UUID",
+ "target": "3.2.4-rc.1",
+ "phase": "awaiting_host",
+ "progress": null,
+ "error_code": null,
+ "updated_at": "2026-10-29T02:00:03Z"
+ }
+}
+```
+
+Remote phases are:
+
+`requested -> acknowledged -> checking -> awaiting_host | downloading ->
+installing -> restarting -> completed | failed | declined | expired`
+
+## Remote Request Lifecycle
+
+The Runtime writes only `desktop-update-request.json`. The shell writes only the
+`remote_request` receipt in `update-status.json`. The updater busy gate exists
+only in shell memory and disappears when that process exits.
+
+| Persisted receipt phase | Live poll or timer after request TTL | Shell startup reconciliation |
+| --- | --- | --- |
+| `requested` | Leave unchanged; its live worker owns settlement. | `failed/shell_interrupted` |
+| `acknowledged` | Leave unchanged; its live worker owns settlement. | `failed/shell_interrupted` |
+| `checking` | Leave unchanged; its live worker owns settlement. | `failed/shell_interrupted` |
+| `awaiting_host` | `expired` and release the busy gate through the single expiry chokepoint. | `failed/shell_interrupted` |
+| `downloading` | Leave unchanged; its live worker owns settlement. | `failed/shell_interrupted` |
+| `installing` | Leave unchanged; its live worker owns settlement. | `failed/shell_interrupted` |
+| `restarting` | Leave unchanged. | `completed` when the running shell version equals the target; otherwise `failed/restart_version_mismatch`. |
+| `completed` | Never rewrite. | Never rewrite. |
+| `failed` | Never rewrite. | Never rewrite. |
+| `declined` | Never rewrite. | Never rewrite. |
+| `expired` | Never rewrite. | Never rewrite. |
+
+Worker success, worker failure, and host decline write their terminal receipt
+before releasing the busy gate. Live expiry requires both request ID and target
+to match the current `awaiting_host` receipt, so a stale request file cannot
+mutate a newer receipt or release its gate. Startup never resumes a persisted
+non-terminal receipt: every such receipt belonged to the process that died.
+After startup reconciliation, no receipt remains non-terminal unless the new
+process accepts a new request.
+
+`progress` is an integer percentage only while downloading. The Runtime parser
+accepts older files without the new fields and ignores unknown fields. A malformed
+remote subsection is dropped without discarding a valid ordinary update result.
+`/api/version` relays `remote_install_allowed` and `remote_request` as read-only
+data.
+
+The shell preserves the remote subsection when publishing an ordinary check.
+It writes every remote transition atomically. A restart leaves `restarting`
+persisted. On startup, the new shell compares its package version with the
+target and writes `completed` on equality or
+`failed/restart_version_mismatch` otherwise.
+An app that never starts leaves `restarting`; the remote UI eventually reports
+that completion could not be confirmed.
+
+## Endpoint
+
+`POST /api/desktop/update/request`
+
+```json
+{
+ "target_version": "3.2.4-rc.1",
+ "confirm_interrupt": false
+}
+```
+
+The endpoint returns the following stable errors:
+
+- `not_desktop_managed`
+- `no_update_available`
+- `update_in_progress`
+- `desktop_shell_unavailable`
+- `confirmation_required`, with active Agent, Watch, and Task counts
+
+The Member or Owner caller receives a success response only after the shell has
+acknowledged the same request:
+
+```json
+{
+ "ok": true,
+ "request_id": "UUID",
+ "delivery": "prompt"
+}
+```
+
+`delivery` is `prompt` or `install`, derived from the shell-written
+`remote_install_allowed` value after acknowledgement. The client cannot choose
+it.
+
+Active interruption counts include running foreground Agent work and queued or
+running Harness Watch and scheduled Task runs. If the controller cannot answer,
+the endpoint fails closed and requires explicit interruption confirmation.
+
+The existing Member-level `POST /api/upgrade` remains the non-desktop packaged
+installer. A new Workbench may send optional `confirm_interrupt: false` and
+receive the same `confirmation_required` response before retrying with `true`.
+An omitted field preserves the legacy behavior and response shape so an old
+cached Workbench continues to upgrade. This PR does not change the endpoint's
+permission level.
+
+## Shell Behaviour
+
+The shell responds to the SSE nudge, reads the file once when the Runtime
+notification connection starts, and polls it every five seconds as a fallback.
+The fallback interval is intentionally shorter than the Runtime's ten-second
+acknowledgement deadline; a 30-second interval could only discover a request
+after the Runtime had expired it. The shell serializes processing with the
+existing updater busy gate and records `update_in_progress` rather than running
+two updater operations.
+
+For every accepted request it performs a fresh check. A target different from
+the latest authenticated manifest fails with `target_mismatch`.
+
+With remote installs disabled, the shell:
+
+1. records `awaiting_host`;
+2. restores and focuses the main window;
+3. opens the existing update popover with remote-request context;
+4. sends a native notification;
+5. waits for Install or Ignore.
+
+Ignore records `declined` and does not add the version to the global skip list.
+No response for 30 minutes records `expired`.
+
+With remote installs enabled, the shell proceeds through the same install
+function used by the local popover. On Windows this remains safe for unattended
+use only for the existing writable per-user install. Its pre-exit write probe
+fails fast as `requires_host` when the installation needs elevation.
+
+## Browser Behaviour
+
+For `managed_by: "desktop"` without a Tauri bridge:
+
+- Members and Owners see **Update on host**, confirmation, interruption counts,
+ delivery mode, progress, restart/reconnect state, and the terminal result.
+- Editors and Viewers see guidance to update in the desktop app on the host and
+ no mutation control.
+- During restart, the browser retries `/api/version` and confirms completion by
+ the request terminal state and resulting version. A bounded timeout says the
+ update was not confirmed and directs the user to the host.
+
+The local desktop Workbench additionally probes the preference IPC. Browsers and
+older shells hide the setting when the capability is absent.
+
+For non-desktop builds:
+
+- a package install keeps the existing Install action and `/api/upgrade` path;
+- a new Workbench shares interruption confirmation and the existing
+ restart/reconnect reload behavior;
+- an old Workbench remains valid because confirmation is opt-in;
+- a source checkout keeps the existing revision refresh and has no install
+ action.
+
+## Platform Findings and Residuals
+
+- macOS stages on the installation filesystem, verifies bundle identity,
+ architecture, and code signature, and restores the old app if the replacement
+ rename fails. After a successful rename, it does not retain the old app until
+ the new app passes a startup health check. The old Runtime remains serving
+ until the new shell completes hand-over, but app-start failure has no automatic
+ binary rollback in this change.
+- Windows verifies installer identity, proves the install directory is writable,
+ copies the old per-user install, and only then exits the shell. It invokes the
+ NSIS installer silently and restores the old install on failure. A directory
+ that needs elevation is rejected before shell exit.
+- Installation interrupts active Agent, Watch, Task, and IM work. The API
+ requires `confirm_interrupt` when known active work exists, but it cannot make
+ those operations resumable.
+- Real tunnel and installer validation requires a signed release candidate on
+ macOS and Windows. This PR uses unit, integration, and native transaction
+ tests and records real-device end-to-end verification as a release residual.
diff --git a/tests/test_desktop_update_request.py b/tests/test_desktop_update_request.py
new file mode 100644
index 000000000..a07ad4c02
--- /dev/null
+++ b/tests/test_desktop_update_request.py
@@ -0,0 +1,226 @@
+from datetime import datetime, timedelta, timezone
+import json
+
+import pytest
+
+from vibe.desktop_update_request import (
+ DesktopUpdateRequestError,
+ create_or_reuse_desktop_update_request,
+ expire_desktop_update_request,
+ parse_desktop_update_request,
+ read_desktop_update_request,
+)
+
+
+NOW = datetime(2026, 10, 29, 2, 0, tzinfo=timezone.utc)
+
+
+def _request(**changes):
+ payload = {
+ "schema_version": 1,
+ "request_id": "87dd4212-fb78-4c57-968c-2f699cc04462",
+ "target": "3.2.4-rc.1",
+ "state": "pending",
+ "created_at": "2026-10-29T02:00:00Z",
+ "expires_at": "2026-10-29T02:30:00Z",
+ }
+ payload.update(changes)
+ return payload
+
+
+ "payload",
+ [
+ None,
+ [],
+ _request(schema_version=True),
+ _request(request_id="forged"),
+ _request(target="../3.2.4"),
+ _request(state=[]),
+ _request(state={}),
+ _request(state=7),
+ _request(state=None),
+ _request(state="unknown"),
+ _request(state="acknowledged"),
+ _request(created_at="not-a-time"),
+ _request(expires_at="2026-10-29T01:59:59Z"),
+ {**_request(), "forged": True},
+ ],
+)
+def test_request_parser_rejects_bad_or_forged_input(payload) -> None:
+ assert parse_desktop_update_request(payload) is None
+
+
+def test_request_creation_is_idempotent_and_serializes_other_targets(tmp_path) -> None:
+ request_path = tmp_path / "desktop-update-request.json"
+ status_path = tmp_path / "update-status.json"
+
+ first = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW,
+ )
+ second = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW + timedelta(seconds=1),
+ )
+ assert first.reused is False
+ assert second.reused is True
+ assert second.request["request_id"] == first.request["request_id"]
+ assert read_desktop_update_request(request_path) == first.request
+
+ with pytest.raises(DesktopUpdateRequestError, match="update_in_progress"):
+ create_or_reuse_desktop_update_request(
+ "3.2.5",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW + timedelta(seconds=2),
+ )
+
+
+def test_terminal_status_is_not_reused_and_expired_request_cannot_revive(tmp_path) -> None:
+ request_path = tmp_path / "desktop-update-request.json"
+ status_path = tmp_path / "update-status.json"
+ first = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW,
+ )
+
+ status_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_request": {
+ "request_id": first.request["request_id"],
+ "target": "3.2.4-rc.1",
+ "phase": "expired",
+ "progress": None,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:10Z",
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ next_request = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW + timedelta(seconds=11),
+ )
+ assert next_request.request["request_id"] != first.request["request_id"]
+ assert expire_desktop_update_request(next_request.request["request_id"], path=request_path)
+ assert not expire_desktop_update_request(next_request.request["request_id"], path=request_path)
+
+ after_expiry = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW + timedelta(seconds=12),
+ )
+ assert after_expiry.request["request_id"] != next_request.request["request_id"]
+
+
+def test_unexpired_shell_status_is_the_idempotency_record(tmp_path) -> None:
+ request_path = tmp_path / "desktop-update-request.json"
+ status_path = tmp_path / "update-status.json"
+ status_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_install_allowed": False,
+ "remote_request": {
+ "request_id": "87dd4212-fb78-4c57-968c-2f699cc04462",
+ "target": "3.2.4-rc.1",
+ "phase": "awaiting_host",
+ "progress": None,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:05Z",
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ decision = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW + timedelta(seconds=10),
+ )
+ assert decision.reused is True
+ assert decision.needs_nudge is False
+ assert decision.request["request_id"] == "87dd4212-fb78-4c57-968c-2f699cc04462"
+
+
+ "phase",
+ [
+ "requested",
+ "acknowledged",
+ "awaiting_host",
+ "checking",
+ "downloading",
+ "installing",
+ "restarting",
+ ],
+)
[email protected]("expiry", ["file_state", "ttl"])
+def test_nonterminal_status_cannot_keep_an_expired_request_alive(
+ tmp_path,
+ phase,
+ expiry,
+) -> None:
+ request_path = tmp_path / "desktop-update-request.json"
+ status_path = tmp_path / "update-status.json"
+ first = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=NOW,
+ )
+ status_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_request": {
+ "request_id": first.request["request_id"],
+ "target": "3.2.4-rc.1",
+ "phase": phase,
+ "progress": None,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:05Z",
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ if expiry == "file_state":
+ assert expire_desktop_update_request(
+ first.request["request_id"],
+ path=request_path,
+ )
+ retry_at = NOW + timedelta(seconds=10)
+ else:
+ retry_at = NOW + timedelta(minutes=31)
+
+ replacement = create_or_reuse_desktop_update_request(
+ "3.2.4-rc.1",
+ request_path=request_path,
+ status_path=status_path,
+ now=retry_at,
+ )
+
+ assert replacement.reused is False
+ assert replacement.request["request_id"] != first.request["request_id"]
diff --git a/tests/test_desktop_update_request_api.py b/tests/test_desktop_update_request_api.py
new file mode 100644
index 000000000..2f245c6b9
--- /dev/null
+++ b/tests/test_desktop_update_request_api.py
@@ -0,0 +1,324 @@
+from __future__ import annotations
+
+import pytest
+
+from tests.ui_server_test_helpers import (
+ _save_config,
+ csrf_headers,
+ remote_peer,
+ remote_session_cookie,
+)
+from vibe import api, remote_access
+from vibe.desktop_update_request import read_desktop_update_request
+from vibe.upgrade_interruptions import UpgradeInterruptions
+from vibe.ui_server import app
+
+
+TARGET = "3.2.4-rc.1"
+
+
+def _version(*, has_update: bool = True):
+ return {
+ "current": "3.2.3rc11",
+ "latest": TARGET if has_update else None,
+ "has_update": has_update,
+ "error": None,
+ "managed_by": "desktop",
+ "build": {"kind": "package"},
+ "remote_install_allowed": False,
+ "remote_request": None,
+ }
+
+
+def _acknowledged(*, allowed: bool = False, phase: str = "awaiting_host", error_code=None):
+ remote = {
+ "request_id": "",
+ "target": TARGET,
+ "phase": phase,
+ "progress": None,
+ "error_code": error_code,
+ "updated_at": "2026-10-29T02:00:00Z",
+ }
+
+ async def wait(request_id: str):
+ remote["request_id"] = request_id
+ return (
+ {
+ "latest": TARGET,
+ "has_update": True,
+ "remote_install_allowed": allowed,
+ "remote_request": remote,
+ },
+ remote,
+ )
+
+ return wait
+
+
+ ("role", "expected"),
+ [("owner", 409), ("member", 409), ("editor", 403), ("viewer", 403)],
+)
+def test_desktop_update_request_role_matrix(monkeypatch, tmp_path, role, expected) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path, paired=True)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ f"{role}@example.com",
+ f"{role}-1",
+ role=role,
+ access_source="owner" if role == "owner" else "email",
+ ),
+ domain="alex.avibe.bot",
+ )
+ response = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert response.status_code == expected
+ if expected == 403:
+ assert response.get_json() == {
+ "ok": False,
+ "error": "instance_access_forbidden",
+ "required_role": "member",
+ }
+ else:
+ assert response.get_json()["error"] == "not_desktop_managed"
+
+
+def test_desktop_update_request_uses_same_origin_and_csrf_guards(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("AVIBE_COMPUTER_USE_STATE_DIR", str(tmp_path))
+ client = app.test_client()
+
+ missing_csrf = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers={"Origin": "http://127.0.0.1"},
+ )
+ assert missing_csrf.status_code == 403
+ assert missing_csrf.get_json()["message"] == "Forbidden: invalid csrf token"
+
+ headers = csrf_headers(client, "http://127.0.0.1")
+ invalid_origin = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers={**headers, "Origin": "https://attacker.example"},
+ base_url="http://127.0.0.1",
+ )
+ assert invalid_origin.status_code == 403
+ assert invalid_origin.get_json()["message"] == "Forbidden: invalid origin"
+ assert read_desktop_update_request(tmp_path / "desktop-update-request.json") is None
+
+
+def test_desktop_update_request_reports_confirmation_and_delivery(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("AVIBE_COMPUTER_USE_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(api, "get_version_info", _version)
+
+ async def interruptions():
+ return UpgradeInterruptions(agents=1, watches=2, tasks=3)
+
+ monkeypatch.setattr(
+ "vibe.upgrade_interruptions.count_upgrade_interruptions",
+ interruptions,
+ )
+ client = app.test_client()
+ headers = csrf_headers(client, "http://127.0.0.1")
+ needs_confirmation = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers=headers,
+ base_url="http://127.0.0.1",
+ )
+ assert needs_confirmation.status_code == 409
+ assert needs_confirmation.get_json() == {
+ "ok": False,
+ "error": "confirmation_required",
+ "counts": {
+ "agents": 1,
+ "watches": 2,
+ "tasks": 3,
+ "total": 6,
+ "unknown": False,
+ },
+ }
+
+ monkeypatch.setattr(
+ "vibe.ui_server._wait_for_desktop_update_ack",
+ _acknowledged(allowed=True),
+ )
+ accepted = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET, "confirm_interrupt": True},
+ headers=headers,
+ base_url="http://127.0.0.1",
+ )
+ assert accepted.status_code == 200
+ assert accepted.get_json()["delivery"] == "install"
+ assert accepted.get_json()["request_id"]
+
+
+ ("phase", "error_code", "expected_status", "expected_error"),
+ [
+ ("failed", "update_in_progress", 409, "update_in_progress"),
+ ("failed", "target_mismatch", 200, None),
+ ("failed", "check_failed", 200, None),
+ ],
+)
+def test_desktop_update_request_only_returns_sync_shell_rejections(
+ monkeypatch,
+ tmp_path,
+ phase,
+ error_code,
+ expected_status,
+ expected_error,
+) -> None:
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("AVIBE_COMPUTER_USE_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(api, "get_version_info", _version)
+
+ async def no_interruptions():
+ return UpgradeInterruptions(0, 0, 0)
+
+ monkeypatch.setattr(
+ "vibe.upgrade_interruptions.count_upgrade_interruptions",
+ no_interruptions,
+ )
+ monkeypatch.setattr(
+ "vibe.ui_server._wait_for_desktop_update_ack",
+ _acknowledged(phase=phase, error_code=error_code),
+ )
+ client = app.test_client()
+ response = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers=csrf_headers(client, "http://127.0.0.1"),
+ base_url="http://127.0.0.1",
+ )
+ assert response.status_code == expected_status
+ payload = response.get_json()
+ if expected_error is None:
+ assert payload["ok"] is True
+ assert payload["delivery"] == "prompt"
+ else:
+ assert payload["ok"] is False
+ assert payload["error"] == expected_error
+
+
+ ("managed", "has_update", "expected", "status"),
+ [
+ (False, True, "not_desktop_managed", 409),
+ (True, False, "no_update_available", 409),
+ ],
+)
+def test_desktop_update_request_preconditions(
+ monkeypatch,
+ tmp_path,
+ managed,
+ has_update,
+ expected,
+ status,
+) -> None:
+ if managed:
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ else:
+ monkeypatch.delenv("AVIBE_DESKTOP_MANAGED_RUNTIME", raising=False)
+ monkeypatch.setenv("AVIBE_COMPUTER_USE_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(api, "get_version_info", lambda: _version(has_update=has_update))
+ client = app.test_client()
+ response = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers=csrf_headers(client, "http://127.0.0.1"),
+ base_url="http://127.0.0.1",
+ )
+ assert response.status_code == status
+ assert response.get_json()["error"] == expected
+
+
+def test_desktop_update_request_expires_when_shell_does_not_ack(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("AVIBE_COMPUTER_USE_STATE_DIR", str(tmp_path))
+ monkeypatch.setattr(api, "get_version_info", _version)
+
+ async def no_interruptions():
+ return UpgradeInterruptions(0, 0, 0)
+
+ async def no_ack(_request_id):
+ return None
+
+ monkeypatch.setattr(
+ "vibe.upgrade_interruptions.count_upgrade_interruptions",
+ no_interruptions,
+ )
+ monkeypatch.setattr("vibe.ui_server._wait_for_desktop_update_ack", no_ack)
+ client = app.test_client()
+ response = client.post(
+ "/api/desktop/update/request",
+ json={"target_version": TARGET},
+ headers=csrf_headers(client, "http://127.0.0.1"),
+ base_url="http://127.0.0.1",
+ )
+ assert response.status_code == 503
+ assert response.get_json()["error"] == "desktop_shell_unavailable"
+ request = read_desktop_update_request(tmp_path / "desktop-update-request.json")
+ assert request is not None
+ assert request["state"] == "expired"
+
+
+def test_upgrade_keeps_legacy_shape_and_optional_confirmation(monkeypatch) -> None:
+ expected = {
+ "ok": True,
+ "message": "updated",
+ "output": None,
+ "activation_notice": None,
+ "restarting": True,
+ }
+ calls = []
+ monkeypatch.setattr(api, "do_upgrade", lambda: calls.append(True) or expected)
+
+ async def active():
+ return UpgradeInterruptions(1, 0, 0)
+
+ monkeypatch.setattr("vibe.upgrade_interruptions.count_upgrade_interruptions", active)
+ client = app.test_client()
+ headers = csrf_headers(client, "http://127.0.0.1")
+
+ legacy = client.post(
+ "/api/upgrade",
+ json={},
+ headers=headers,
+ base_url="http://127.0.0.1",
+ )
+ assert legacy.status_code == 200
+ assert legacy.get_json() == expected
+ assert calls == [True]
+
+ new_client = client.post(
+ "/api/upgrade",
+ json={"confirm_interrupt": False},
+ headers=headers,
+ base_url="http://127.0.0.1",
+ )
+ assert new_client.status_code == 409
+ assert new_client.get_json()["error"] == "confirmation_required"
+ assert calls == [True]
+
+ confirmed = client.post(
+ "/api/upgrade",
+ json={"confirm_interrupt": True},
+ headers=headers,
+ base_url="http://127.0.0.1",
+ )
+ assert confirmed.status_code == 200
+ assert confirmed.get_json() == expected
+ assert calls == [True, True]
diff --git a/tests/test_desktop_update_status.py b/tests/test_desktop_update_status.py
index 0b242e93d..779913f07 100644
--- a/tests/test_desktop_update_status.py
+++ b/tests/test_desktop_update_status.py
@@ -1,7 +1,12 @@
from pathlib import Path
+import pytest
+
from core.computer_use import COMPUTER_USE_STATE_DIR_ENV
-from vibe.desktop_update_status import desktop_update_status_path
+from vibe.desktop_update_status import (
+ desktop_update_status_path,
+ parse_desktop_update_status,
+)
def test_desktop_update_status_path_ignores_avibe_home(tmp_path: Path) -> None:
@@ -19,3 +24,116 @@ def test_desktop_update_status_path_ignores_avibe_home(tmp_path: Path) -> None:
home=tmp_path / "user",
platform="darwin",
) == tmp_path / "isolated-desktop" / "update-status.json"
+
+
+def test_old_status_defaults_remote_fields_without_losing_update() -> None:
+ assert parse_desktop_update_status(
+ {
+ "schema_version": 1,
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ }
+ ) == {
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_install_allowed": False,
+ "remote_request": None,
+ }
+
+
+def test_remote_status_is_relayed_and_bad_remote_fields_degrade_independently() -> None:
+ payload = {
+ "schema_version": 1,
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_install_allowed": True,
+ "remote_request": {
+ "request_id": "request-1",
+ "target": "3.2.4-rc.1",
+ "phase": "downloading",
+ "progress": 42,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:00Z",
+ },
+ }
+ assert parse_desktop_update_status(payload) == {
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_install_allowed": True,
+ "remote_request": payload["remote_request"],
+ }
+
+ payload["remote_install_allowed"] = "yes"
+ payload["remote_request"] = {**payload["remote_request"], "progress": True}
+ assert parse_desktop_update_status(payload) == {
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_install_allowed": False,
+ "remote_request": None,
+ }
+
+
+ ("field", "value", "kept"),
+ [
+ pytest.param("request_id", [], False, id="request-id-list"),
+ pytest.param("request_id", {}, False, id="request-id-object"),
+ pytest.param("request_id", 7, False, id="request-id-number"),
+ pytest.param("request_id", None, False, id="request-id-null"),
+ pytest.param("request_id", "opaque-request", True, id="request-id-opaque-string"),
+ pytest.param("target", [], False, id="target-list"),
+ pytest.param("target", {}, False, id="target-object"),
+ pytest.param("target", 7, False, id="target-number"),
+ pytest.param("target", None, False, id="target-null"),
+ pytest.param("target", "opaque-target", True, id="target-opaque-string"),
+ pytest.param("phase", [], False, id="phase-list"),
+ pytest.param("phase", {}, False, id="phase-object"),
+ pytest.param("phase", 7, False, id="phase-number"),
+ pytest.param("phase", None, False, id="phase-null"),
+ pytest.param("phase", "unknown", False, id="phase-unknown-string"),
+ pytest.param("progress", [], False, id="progress-list"),
+ pytest.param("progress", {}, False, id="progress-object"),
+ pytest.param("progress", 101, False, id="progress-out-of-range-number"),
+ pytest.param("progress", None, True, id="progress-null"),
+ pytest.param("progress", "unknown", False, id="progress-string"),
+ pytest.param("error_code", [], False, id="error-code-list"),
+ pytest.param("error_code", {}, False, id="error-code-object"),
+ pytest.param("error_code", 7, False, id="error-code-number"),
+ pytest.param("error_code", None, True, id="error-code-null"),
+ pytest.param("error_code", "unknown", True, id="error-code-opaque-string"),
+ pytest.param("updated_at", [], False, id="updated-at-list"),
+ pytest.param("updated_at", {}, False, id="updated-at-object"),
+ pytest.param("updated_at", 7, False, id="updated-at-number"),
+ pytest.param("updated_at", None, False, id="updated-at-null"),
+ pytest.param("updated_at", "unknown", False, id="updated-at-unknown-string"),
+ ],
+)
+def test_every_remote_status_field_degrades_without_losing_the_ordinary_result(
+ field: str,
+ value: object,
+ kept: bool,
+) -> None:
+ remote_request = {
+ "request_id": "request-1",
+ "target": "3.2.4-rc.1",
+ "phase": "downloading",
+ "progress": 42,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:00Z",
+ }
+ remote_request[field] = value
+ parsed = parse_desktop_update_status(
+ {
+ "schema_version": 1,
+ "latest": "3.2.4-rc.1",
+ "has_update": True,
+ "remote_install_allowed": True,
+ "remote_request": remote_request,
+ }
+ )
+
+ assert parsed is not None
+ assert parsed["latest"] == "3.2.4-rc.1"
+ assert parsed["has_update"] is True
+ assert parsed["remote_install_allowed"] is True
+ assert (parsed["remote_request"] is not None) is kept
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 20c819917..021b48ab4 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -330,6 +330,8 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("PUT", "/api/projects/project-1/agents-md"),
("GET", "/api/settings"),
("GET", "/api/users"),
+ ("POST", "/api/upgrade"),
+ ("POST", "/api/desktop/update/request"),
("GET", "/api/remote-access/status"),
("GET", "/api/remote-access/network-interfaces"),
("POST", "/api/remote-access/optimize-route"),
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 2e47566bc..41ca98dd7 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 296
+ assert len(endpoints) == 297
# Editors who use Vault read avault's authorization state; the handler admits only
# instance managers to raise the Keychain dialog on the host.
for method in ("GET", "POST"):
@@ -139,6 +139,8 @@ def test_complete_registered_api_management_inventory():
assert http_authorization_policy("POST", "/api/desktop-mini/session").minimum_role == "editor"
assert http_authorization_policy("GET", "/api/desktop/capabilities").minimum_role == "member"
assert http_authorization_policy("GET", "/api/desktop/computer-use/status").minimum_role == "member"
+ assert ("POST", "/api/desktop/update/request") in endpoints
+ assert http_authorization_policy("POST", "/api/desktop/update/request").minimum_role == "member"
# Additive read-only backend projection inherits native backend-management
# authorization; it does not grant lower-tier credential-management access.
assert ("GET", "/api/backend/{name}/connection") in endpoints
diff --git a/tests/test_upgrade_interruptions.py b/tests/test_upgrade_interruptions.py
new file mode 100644
index 000000000..e4f1a76a5
--- /dev/null
+++ b/tests/test_upgrade_interruptions.py
@@ -0,0 +1,110 @@
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from vibe import internal_client
+from vibe.upgrade_interruptions import count_upgrade_interruptions
+
+
+async def test_upgrade_interruptions_count_active_agents_watches_and_tasks(
+ monkeypatch,
+) -> None:
+ async def running_agents():
+ return {
+ "body": {
+ "agents": [
+ {"state": "active"},
+ {"state": "active"},
+ {"state": "idle"},
+ ]
+ }
+ }
+
+ store = SimpleNamespace(
+ count_runs=lambda *, status, run_type: {
+ ("watch", "queued"): 1,
+ ("watch", "running"): 2,
+ ("scheduled", "queued"): 3,
+ ("scheduled", "running"): 4,
+ }[(run_type, status)],
+ close=lambda: None,
+ )
+ monkeypatch.setattr(internal_client, "list_running_agents", running_agents)
+ monkeypatch.setattr(
+ "storage.background.SQLiteBackgroundTaskStore",
+ lambda **_kwargs: store,
+ )
+
+ result = await count_upgrade_interruptions()
+ assert result.as_dict() == {
+ "agents": 2,
+ "watches": 3,
+ "tasks": 7,
+ "total": 12,
+ "unknown": False,
+ }
+ assert result.requires_confirmation is True
+
+
+async def test_upgrade_interruptions_query_harness_rows_off_the_event_loop(
+ monkeypatch,
+) -> None:
+ async def running_agents():
+ return {"body": {"agents": []}}
+
+ event_loop_thread = threading.get_ident()
+ calls: list[tuple[int, str, str]] = []
+ closed_on: list[int] = []
+
+ class Store:
+ def __init__(self, **_kwargs) -> None:
+ calls.append((threading.get_ident(), "construct", ""))
+
+ def count_runs(self, *, status: str, run_type: str) -> int:
+ calls.append((threading.get_ident(), run_type, status))
+ return 1
+
+ def close(self) -> None:
+ closed_on.append(threading.get_ident())
+
+ monkeypatch.setattr(internal_client, "list_running_agents", running_agents)
+ monkeypatch.setattr("storage.background.SQLiteBackgroundTaskStore", Store)
+
+ result = await count_upgrade_interruptions()
+
+ assert result.watches == 2
+ assert result.tasks == 2
+ assert [(run_type, status) for _, run_type, status in calls[1:]] == [
+ ("watch", "queued"),
+ ("watch", "running"),
+ ("scheduled", "queued"),
+ ("scheduled", "running"),
+ ]
+ assert all(thread_id != event_loop_thread for thread_id, _, _ in calls)
+ assert closed_on and closed_on[0] != event_loop_thread
+
+
+async def test_upgrade_interruptions_fail_closed_when_controller_is_unavailable(
+ monkeypatch,
+) -> None:
+ async def unavailable():
+ raise internal_client.InternalServerUnavailable("down")
+
+ store = SimpleNamespace(
+ count_runs=lambda *, status, run_type: 0,
+ close=lambda: None,
+ )
+ monkeypatch.setattr(internal_client, "list_running_agents", unavailable)
+ monkeypatch.setattr(
+ "storage.background.SQLiteBackgroundTaskStore",
+ lambda **_kwargs: store,
+ )
+
+ result = await count_upgrade_interruptions()
+ assert result.total == 0
+ assert result.unknown is True
+ assert result.requires_confirmation is True
diff --git a/tests/test_version_identity.py b/tests/test_version_identity.py
index 9f42c7ee9..e698fa541 100644
--- a/tests/test_version_identity.py
+++ b/tests/test_version_identity.py
@@ -5,6 +5,7 @@ import pytest
from core import update_checker
from vibe import api
+from vibe.ui_server import app
# What the desktop updater writes for an available release; its own tests write
# the same document (desktop/runtime-host/src/update_status.rs).
@@ -113,6 +114,8 @@ DESKTOP_NO_CONCLUSION = {
"latest": None,
"has_update": False,
"error": None,
+ "remote_install_allowed": False,
+ "remote_request": None,
"build": {"kind": "package"},
"managed_by": "desktop",
}
@@ -141,6 +144,59 @@ def test_desktop_managed_runtime_relays_an_up_to_date_desktop(monkeypatch, tmp_p
assert api.get_version_info() == {**DESKTOP_NO_CONCLUSION, "latest": "3.2.2-rc.13"}
+def test_desktop_managed_runtime_relays_remote_update_progress(monkeypatch, tmp_path) -> None:
+ _desktop_managed(monkeypatch, tmp_path)
+ status = json.loads(DESKTOP_UPDATE_STATUS_FIXTURE.read_text(encoding="utf-8"))
+ status.update(
+ remote_install_allowed=True,
+ remote_request={
+ "request_id": "request-1",
+ "target": "3.2.3",
+ "phase": "downloading",
+ "progress": 65,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:00Z",
+ },
+ )
+ (tmp_path / "update-status.json").write_text(json.dumps(status), encoding="utf-8")
+
+ result = api.get_version_info()
+ assert result["remote_install_allowed"] is True
+ assert result["remote_request"] == status["remote_request"]
+
+
[email protected]("phase", [[], {}], ids=["list-phase", "object-phase"])
+def test_version_endpoint_keeps_the_ordinary_result_for_a_malformed_remote_subsection(
+ monkeypatch,
+ tmp_path,
+ phase,
+) -> None:
+ _desktop_managed(monkeypatch, tmp_path)
+ status = json.loads(DESKTOP_UPDATE_STATUS_FIXTURE.read_text(encoding="utf-8"))
+ status.update(
+ remote_install_allowed=True,
+ remote_request={
+ "request_id": "request-1",
+ "target": "3.2.3",
+ "phase": phase,
+ "progress": None,
+ "error_code": None,
+ "updated_at": "2026-10-29T02:00:00Z",
+ },
+ )
+ (tmp_path / "update-status.json").write_text(json.dumps(status), encoding="utf-8")
+
+ response = app.test_client().get("/api/version", base_url="http://127.0.0.1")
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ **DESKTOP_NO_CONCLUSION,
+ "latest": "3.2.3",
+ "has_update": True,
+ "remote_install_allowed": True,
+ }
+
+
def _fixture_with(**changes) -> str:
status = json.loads(DESKTOP_UPDATE_STATUS_FIXTURE.read_text(encoding="utf-8"))
status.update(changes)
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index d1034ba26..0f0c31ad2 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -139,7 +139,7 @@ vi.mock('./AppsLauncher', async () => {
vi.mock('./AccountMenu', () => ({ AccountMenu: () => <div data-testid="account-menu" /> }));
vi.mock('./LanguageSwitcher', () => ({ LanguageSwitcher: () => <div data-testid="language-switcher" /> }));
vi.mock('./ThemeToggle', () => ({ ThemeToggle: () => <div data-testid="theme-toggle" /> }));
-vi.mock('./VersionBadge', () => ({ VersionBadge: () => null }));
+vi.mock('./VersionBadge', () => ({ VersionBadge: () => <div data-testid="version-badge" /> }));
vi.mock('./apps/MobileDockDrawer', () => ({
MobileDockDrawer: () => <div data-testid="mobile-dock-drawer" />,
}));
@@ -1161,3 +1161,12 @@ describe('AppShell remote Apps access', () => {
expect(screen.queryByTestId('library-surface')).toBeNull();
});
});
+
+// Read-only members need the host guidance even though no update control is allowed.
+it.each(['editor', 'viewer'])('mounts the version badge for a read-capable %s', async () => {
+ viewport.isDesktop = true;
+ instanceAuth.capabilities.can_manage_instance = false;
+ instanceAuth.capabilities.can_read_instance = true;
+ render(<MemoryRouter initialEntries={['/']}><Routes><Route element={<AppShell />}><Route index element={<div />} /></Route></Routes></MemoryRouter>);
+ expect(await screen.findByTestId('version-badge')).toBeTruthy();
+});
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 9c6875b43..2242f0390 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -604,7 +604,7 @@ export const AppShell: React.FC = () => {
{/* Version row AYIIj — version on the LEFT, run state on the RIGHT. */}
<div className="flex items-center justify-between gap-2 px-1 py-0.5">
- {capabilities.can_manage_instance ? <VersionBadge openUpward /> : <span />}
+ {capabilities.can_read_instance ? <VersionBadge openUpward /> : <span />}
<span className="flex items-center gap-1.5 text-[10px] text-muted">
{isRunning ? t('common.running') : t('common.stopped')}
<span
diff --git a/ui/src/components/VersionBadge.test.tsx b/ui/src/components/VersionBadge.test.tsx
index f3e7630b1..24dadf3d8 100644
--- a/ui/src/components/VersionBadge.test.tsx
+++ b/ui/src/components/VersionBadge.test.tsx
@@ -1,18 +1,20 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import { VersionBadge } from './VersionBadge';
+import type { DesktopRemoteUpdateResult, VersionInfo, UpgradeResult } from '../context/ApiContext';
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' })),
+ getVersion: vi.fn<() => Promise<Partial<VersionInfo> & Pick<VersionInfo, 'current' | 'latest' | 'has_update'>>>(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 })),
+ requestDesktopUpdate: vi.fn<(...args: unknown[]) => Promise<DesktopRemoteUpdateResult>>(),
+ doUpgrade: vi.fn<(...args: unknown[]) => Promise<UpgradeResult>>(async () => ({ ok: true, message: 'Upgrade successful', output: null, restarting: false })),
}));
const defaultDesktopInvoke = vi.hoisted(() => async (command: string) => {
if (command === 'desktop_update_state') {
@@ -23,9 +25,19 @@ const defaultDesktopInvoke = vi.hoisted(() => async (command: string) => {
});
const desktopInvoke = vi.hoisted(() => vi.fn(defaultDesktopInvoke));
vi.mock('../context/ApiContext', () => ({ useApi: () => api }));
+const authorization = vi.hoisted(() => ({ remote: true, capabilities: { can_manage_instance: true, is_instance_owner: true } }));
+vi.mock('../context/InstanceAuthorizationContext', () => ({ useInstanceAuthorization: () => authorization }));
vi.mock('../lib/useIsDesktop', () => ({ useIsDesktop: () => true }));
+beforeEach(() => {
+ authorization.capabilities.can_manage_instance = true;
+ authorization.capabilities.is_instance_owner = true;
+ api.getVersion.mockReset().mockResolvedValue({ current: '9.9.9', latest: '10.0.0', has_update: true, managed_by: 'desktop' });
+ api.requestDesktopUpdate.mockReset().mockResolvedValue({ ok: true, request_id: 'request-1', delivery: 'prompt' });
+});
+
afterEach(() => {
+ vi.useRealTimers();
cleanup();
vi.clearAllMocks();
desktopInvoke.mockImplementation(defaultDesktopInvoke);
@@ -238,6 +250,9 @@ describe('desktop version ownership', () => {
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 });
+ fireEvent.click(entry);
+ expect(screen.queryByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateTitle') })).toBeNull();
+ expect(api.requestDesktopUpdate).not.toHaveBeenCalled();
});
it('uses shell updater ownership even when the adopted Runtime omits managed_by', async () => {
@@ -354,6 +369,23 @@ describe('desktop version ownership', () => {
expect(await screen.findByText(i18n.t('dashboard.autoUpdate'))).toBeTruthy();
});
+ it('loads the auto-update setting when an editor is promoted to member', async () => {
+ authorization.capabilities.can_manage_instance = false;
+ authorization.capabilities.is_instance_owner = false;
+ api.getVersion.mockResolvedValueOnce({ current: '9.9.9', latest: '9.9.9', has_update: false });
+ const view = render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+
+ fireEvent.click(await screen.findByTitle('v9.9.9'));
+ expect(screen.queryByText(i18n.t('dashboard.autoUpdate'))).toBeNull();
+ expect(api.getConfig).not.toHaveBeenCalled();
+
+ authorization.capabilities.can_manage_instance = true;
+ view.rerender(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+
+ await vi.waitFor(() => expect(api.getConfig).toHaveBeenCalledOnce());
+ expect(await screen.findByText(i18n.t('dashboard.autoUpdate'))).toBeTruthy();
+ });
+
it('shows a successful upgrade warning returned in the output', async () => {
api.getVersion.mockResolvedValueOnce({ current: '9.9.9', latest: '10.0.0', has_update: true });
api.doUpgrade.mockResolvedValueOnce({
@@ -367,6 +399,7 @@ describe('desktop version ownership', () => {
fireEvent.click(await screen.findByTitle('v9.9.9'));
fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirm') }));
expect(await screen.findByText('Stable launcher repair is still required.')).toBeTruthy();
expect(screen.queryByText('raw installer transcript')).toBeNull();
@@ -386,6 +419,7 @@ describe('desktop version ownership', () => {
fireEvent.click(await screen.findByTitle('v9.9.9'));
fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirm') }));
expect(await screen.findByText(/deferred activation helper/)).toBeTruthy();
expect(screen.queryByText('raw deferred helper transcript')).toBeNull();
@@ -404,6 +438,7 @@ describe('desktop version ownership', () => {
fireEvent.click(await screen.findByTitle('v9.9.9'));
fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirm') }));
expect(await screen.findByText(i18n.t('dashboard.upgradeSuccess'))).toBeTruthy();
expect(screen.queryByText(/installer stdout/)).toBeNull();
@@ -423,8 +458,181 @@ describe('desktop version ownership', () => {
fireEvent.click(await screen.findByTitle('v9.9.9'));
fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirm') }));
expect(await screen.findByText(i18n.t('dashboard.upgradeFailed'))).toBeTruthy();
expect(screen.queryByText('raw package-manager transcript')).toBeNull();
});
});
+
+// These contracts exercise the request/receipt boundary. Existing updater tests
+// only covered native install/skip and cannot catch remote authorization,
+// counted confirmation, or a disconnected host being mistaken for success.
+const remoteReceipt = (phase: NonNullable<VersionInfo['remote_request']>['phase'], progress: number | null = null): VersionInfo => ({
+ current: '9.9.9', latest: '10.0.0', has_update: true, error: null, managed_by: 'desktop',
+ remote_request: { request_id: 'request-1', target: '10.0.0', phase, progress, error_code: null, updated_at: '2026-10-29T02:00:00Z' },
+});
+
+async function openTimingPopup() {
+ vi.useFakeTimers();
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+ await act(() => vi.advanceTimersByTimeAsync(0));
+ fireEvent.click(screen.getByTitle('v9.9.9'));
+}
+
+async function requestFromBrowser() {
+ await openBrowserPopup('v9.9.9');
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateTitle') }));
+}
+
+function confirmRequest() {
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirm') }));
+}
+
+describe('remote desktop update contract', () => {
+ it.each(['owner', 'member', 'editor', 'viewer'] as const)('projects %s capability to request controls and guidance', async (role) => {
+ authorization.capabilities.can_manage_instance = role === 'owner' || role === 'member';
+ authorization.capabilities.is_instance_owner = role === 'owner';
+ await openBrowserPopup('v9.9.9');
+ expect(Boolean(screen.queryByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateTitle') })))
+ .toBe(role === 'owner' || role === 'member');
+ if (role === 'editor' || role === 'viewer') {
+ expect(screen.getByText(i18n.t('dashboard.desktopManagedUpdateMemberHint'))).toBeTruthy();
+ expect(api.getConfig).not.toHaveBeenCalled();
+ }
+ expect(api.requestDesktopUpdate).not.toHaveBeenCalled();
+ expect(api.doUpgrade).not.toHaveBeenCalled();
+ });
+
+ it('checks work on first submit, displays nested counts/unknown, and retries explicitly confirmed', async () => {
+ api.requestDesktopUpdate.mockResolvedValueOnce({ ok: false, error: 'confirmation_required', counts: {
+ agents: 2, watches: 3, tasks: 4, total: 9, unknown: true,
+ } });
+ await requestFromBrowser();
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateCheckWork'))).toBeTruthy();
+ confirmRequest();
+ expect(await screen.findByText(i18n.t('dashboard.desktopRemoteUpdateInterruptions', { agents: 2, watches: 3, tasks: 4 }))).toBeTruthy();
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateUnknownWork'))).toBeTruthy();
+ expect(api.requestDesktopUpdate).toHaveBeenLastCalledWith('10.0.0', { confirmInterrupt: false });
+ api.getVersion.mockResolvedValue(remoteReceipt('awaiting_host'));
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirmInterrupt') }));
+ expect(await screen.findByText(i18n.t('dashboard.desktopRemoteUpdateAwaitingHost'))).toBeTruthy();
+ expect(api.requestDesktopUpdate).toHaveBeenLastCalledWith('10.0.0', { confirmInterrupt: true });
+ expect(api.doUpgrade).not.toHaveBeenCalled();
+ });
+
+ it.each(['prompt', 'install'] as const)('shows %s delivery before submitting and follows the authoritative result', async (delivery) => {
+ api.getVersion.mockResolvedValue({ current: '9.9.9', latest: '10.0.0-rc.1', has_update: true, managed_by: 'desktop', remote_install_allowed: delivery === 'install' });
+ api.requestDesktopUpdate.mockResolvedValue({ ok: true, request_id: 'request-1', delivery });
+ await requestFromBrowser();
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateConfirmDescription', { delivery: i18n.t(delivery === 'install'
+ ? 'dashboard.desktopRemoteUpdateDeliveryInstall' : 'dashboard.desktopRemoteUpdateDeliveryPrompt') }))).toBeTruthy();
+ api.getVersion.mockResolvedValue({ ...remoteReceipt(delivery === 'install' ? 'downloading' : 'awaiting_host', 42), remote_install_allowed: delivery === 'install' });
+ confirmRequest();
+ expect(await screen.findByText(i18n.t(delivery === 'install' ? 'dashboard.desktopRemoteUpdateDownloading' : 'dashboard.desktopRemoteUpdateAwaitingHost', { progress: 42 }))).toBeTruthy();
+ // SemVer is sent unchanged, even though the badge normalizes display strings.
+ expect(api.requestDesktopUpdate).toHaveBeenCalledWith('10.0.0-rc.1', { confirmInterrupt: false });
+ });
+
+ it.each(['failed', 'declined', 'expired'] as const)('renders terminal %s from a receipt', async (phase) => {
+ api.getVersion.mockResolvedValue(remoteReceipt(phase));
+ await openBrowserPopup('v9.9.9');
+ const key = phase === 'failed' ? 'dashboard.desktopRemoteUpdateFailed' : phase === 'declined'
+ ? 'dashboard.desktopRemoteUpdateDeclined' : 'dashboard.desktopRemoteUpdateExpired';
+ expect(screen.getByText(i18n.t(key))).toBeTruthy();
+ expect(api.getVersion).toHaveBeenCalledTimes(1);
+ });
+
+ it('reconnects after disconnection and requires both the same receipt and resulting version', async () => {
+ api.getVersion.mockResolvedValue(remoteReceipt('installing'));
+ await openTimingPopup();
+ api.getVersion.mockRejectedValue(new Error('disconnected'));
+ await act(() => vi.advanceTimersByTimeAsync(2000));
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateRestarting'))).toBeTruthy();
+ api.getVersion.mockResolvedValue({ ...remoteReceipt('completed'), current: '10.0.0' });
+ await act(() => vi.advanceTimersByTimeAsync(2000));
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateCompleted', { target: '10.0.0' }))).toBeTruthy();
+ expect(screen.queryByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateTitle') })).toBeNull();
+ const calls = api.getVersion.mock.calls.length;
+ await act(() => vi.advanceTimersByTimeAsync(10_000));
+ expect(api.getVersion).toHaveBeenCalledTimes(calls);
+ });
+
+ it.each(['unreachable', 'stuck', 'wrong-version', 'hanging-read'] as const)('bounds %s reconnect and never claims success', async (mode) => {
+ const info = remoteReceipt(mode === 'wrong-version' ? 'completed' : 'restarting');
+ api.getVersion.mockResolvedValue(info);
+ await openTimingPopup();
+ if (mode === 'wrong-version') {
+ expect((screen.getByRole('button', {
+ name: i18n.t('dashboard.desktopRemoteUpdateTitle'),
+ }) as HTMLButtonElement).disabled).toBe(true);
+ }
+ if (mode === 'unreachable') api.getVersion.mockRejectedValue(new Error('offline'));
+ if (mode === 'hanging-read') api.getVersion.mockImplementation(() => new Promise(() => {}));
+ await act(() => vi.advanceTimersByTimeAsync(125_000));
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateTimedOut'))).toBeTruthy();
+ expect(screen.queryByText(i18n.t('dashboard.desktopRemoteUpdateCompleted', { target: '10.0.0' }))).toBeNull();
+ const calls = api.getVersion.mock.calls.length;
+ await act(() => vi.advanceTimersByTimeAsync(10_000));
+ expect(api.getVersion).toHaveBeenCalledTimes(calls);
+ expect(api.doUpgrade).not.toHaveBeenCalled();
+ });
+
+ it.each(['not_desktop_managed', 'no_update_available', 'update_in_progress', 'desktop_shell_unavailable'] as const)('handles %s without falling back to Runtime upgrade', async (error) => {
+ api.requestDesktopUpdate.mockResolvedValue({ ok: false, error });
+ await requestFromBrowser();
+ confirmRequest();
+ expect(await screen.findByRole('alert')).toBeTruthy();
+ expect(api.doUpgrade).not.toHaveBeenCalled();
+ });
+
+ it.each(['failed', 'declined', 'expired'] as const)('allows retry when a manual refresh discovers %s after timeout', async (phase) => {
+ api.getVersion.mockResolvedValue(remoteReceipt('restarting'));
+ await openTimingPopup();
+ await act(() => vi.advanceTimersByTimeAsync(125_000));
+ expect(screen.getByText(i18n.t('dashboard.desktopRemoteUpdateTimedOut'))).toBeTruthy();
+ api.getVersion.mockResolvedValue(remoteReceipt(phase));
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.checkUpdate') }));
+ await act(() => vi.advanceTimersByTimeAsync(0));
+ expect(screen.queryByText(i18n.t('dashboard.desktopRemoteUpdateTimedOut'))).toBeNull();
+ const requestButton = screen.getByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateTitle') });
+ expect((requestButton as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(requestButton);
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ });
+
+ it('shows local remote context and uses decline rather than global skip', async () => {
+ desktopInvoke.mockImplementation(async (command: string) => command === 'desktop_update_state'
+ ? { phase: 'available', latest: '10.0.0', channel: 'stable', interactive: true, skippedVersion: null,
+ remoteRequest: { requestId: 'request-1', target: '10.0.0', phase: 'awaiting_host', progress: null, errorCode: null, updatedAt: '' } }
+ : undefined);
+ renderInShell('9.9.9', '9.9.9', '10.0.0', true);
+ expect(await screen.findByText(i18n.t('dashboard.desktopRemoteUpdateLocalRequest', { target: '10.0.0' }))).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateIgnore') }));
+ await vi.waitFor(() => expect(desktopInvoke).toHaveBeenCalledWith('desktop_update_remote_decline'));
+ expect(desktopInvoke).not.toHaveBeenCalledWith('desktop_update_skip');
+ expect(desktopInvoke).not.toHaveBeenCalledWith('desktop_update_check');
+ });
+
+ it('keeps the Member pure-Web upgrade and handles its counted confirmation', async () => {
+ authorization.capabilities.is_instance_owner = false;
+ api.getVersion.mockResolvedValue({ current: '9.9.9', latest: '10.0.0', has_update: true });
+ api.doUpgrade.mockResolvedValueOnce({ ok: false, error: 'confirmation_required', counts: { agents: 1, watches: 0, tasks: 2, total: 3, unknown: false } });
+ await openBrowserPopup('v9.9.9');
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+ confirmRequest();
+ expect(await screen.findByText(i18n.t('dashboard.desktopRemoteUpdateInterruptions', { agents: 1, watches: 0, tasks: 2 }))).toBeTruthy();
+ expect(api.doUpgrade).toHaveBeenLastCalledWith({ confirmInterrupt: false });
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('dashboard.desktopRemoteUpdateConfirmInterrupt') }));
+ await vi.waitFor(() => expect(api.doUpgrade).toHaveBeenLastCalledWith({ confirmInterrupt: true }));
+ expect(api.requestDesktopUpdate).not.toHaveBeenCalled();
+ });
+
+ it.each(['editor', 'viewer'])('withholds pure-Web upgrade and config reads from %s', async () => {
+ authorization.capabilities.can_manage_instance = false;
+ api.getVersion.mockResolvedValue({ current: '9.9.9', latest: '10.0.0', has_update: true });
+ await openBrowserPopup('v9.9.9');
+ expect(screen.queryByRole('button', { name: i18n.t('dashboard.upgradeNow') })).toBeNull();
+ expect(api.getConfig).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsx
index 131492964..247c094b6 100644
--- a/ui/src/components/VersionBadge.tsx
+++ b/ui/src/components/VersionBadge.tsx
@@ -1,6 +1,11 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
-import { useApi, type VersionInfo, type UpgradeResult } from '../context/ApiContext';
+import {
+ useApi,
+ type UpdateInterruptionCounts,
+ type VersionInfo,
+ type UpgradeResult,
+} from '../context/ApiContext';
import { Download, X, RefreshCw, Check, AlertCircle, GitCommitHorizontal } from 'lucide-react';
import clsx from 'clsx';
import { ToggleSwitch } from './settings/SettingsPrimitives';
@@ -23,6 +28,8 @@ import {
} from '../lib/desktopShell';
import { useIsDesktop } from '../lib/useIsDesktop';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog';
+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
// Dev / regression builds carry long versions like
// `3.0.1.dev33+g1df6865a1.d20260608`. Collapse to the release core
@@ -54,9 +61,21 @@ function normalizeVersion(value: string): string {
].join('');
}
+type RemoteUpdateConfirmation = {
+ target: string;
+ delivery: 'prompt' | 'install' | 'runtime';
+ counts?: UpdateInterruptionCounts;
+};
+
+const REMOTE_RECONNECT_POLL_MS = 2000;
+const REMOTE_RECONNECT_TIMEOUT_MS = 120_000;
+const REMOTE_REQUEST_TIMEOUT_MS = 35 * 60_000;
+const TERMINAL_REMOTE_PHASES = ['completed', 'failed', 'declined', 'expired'];
+
export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {
const { t } = useTranslation();
const api = useApi();
+ const { capabilities } = useInstanceAuthorization();
const inDesktopShell = isDesktopShell();
const isDesktop = useIsDesktop();
const shellActions = React.useMemo(() => desktopUpdateShellActions(), []);
@@ -71,6 +90,12 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const [upgrading, setUpgrading] = React.useState(false);
const [restarting, setRestarting] = React.useState(false);
const [upgradeResult, setUpgradeResult] = React.useState<UpgradeResult | null>(null);
+ const [remoteConfirmation, setRemoteConfirmation] = React.useState<RemoteUpdateConfirmation | null>(null);
+ const [remoteRequesting, setRemoteRequesting] = React.useState(false);
+ const [remoteRequestError, setRemoteRequestError] = React.useState<string | null>(null);
+ const [remoteUpdateTimedOut, setRemoteUpdateTimedOut] = React.useState(false);
+ const [remoteDisconnected, setRemoteDisconnected] = React.useState(false);
+ const [remoteDelivery, setRemoteDelivery] = React.useState<'prompt' | 'install' | null>(null);
const [autoUpdate, setAutoUpdate] = React.useState<boolean | null>(null);
const [savingAutoUpdate, setSavingAutoUpdate] = React.useState(false);
const popupRef = React.useRef<HTMLDivElement>(null);
@@ -88,14 +113,14 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [isPopupOpen, isDesktop]);
- const loadAutoUpdateSetting = async () => {
+ const loadAutoUpdateSetting = React.useCallback(async () => {
try {
const config = await api.getConfig();
setAutoUpdate(config.update?.auto_update ?? true);
} catch (e) {
console.error('Failed to load config:', e);
}
- };
+ }, [api]);
const handleAutoUpdateToggle = async (enabled: boolean) => {
setSavingAutoUpdate(true);
@@ -115,6 +140,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
try {
const state = await actions.getState();
setDesktopUpdateState(state);
+ if (state.remoteRequest?.phase === 'awaiting_host') setIsPopupOpen(true);
setDesktopUpdaterStatus('available');
return state;
} catch (error) {
@@ -167,6 +193,13 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
try {
const info = await api.getVersion(rereadVersion || nativeStateAvailable ? { cache: false } : undefined);
setVersionInfo(info);
+ const receipt = info.remote_request;
+ if (receipt && receipt.request_id === versionInfo?.remote_request?.request_id
+ && TERMINAL_REMOTE_PHASES.includes(receipt.phase)
+ && (receipt.phase !== 'completed' || normalizeVersion(info.current) === normalizeVersion(receipt.target))) {
+ setRemoteUpdateTimedOut(false);
+ setRemoteDisconnected(false);
+ }
} catch (e) {
console.error('Failed to check version:', e);
} finally {
@@ -181,7 +214,11 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
window.__AVIBE_DESKTOP_UPDATES_HANDLED__ = true;
event.preventDefault();
setIsPopupOpen(true);
- void checkVersion(true);
+ void readDesktopUpdateState().then((state) => {
+ if (!state?.remoteRequest || TERMINAL_REMOTE_PHASES.includes(state.remoteRequest.phase)) {
+ void checkVersion(true);
+ }
+ }).catch(() => undefined);
};
window.addEventListener(DESKTOP_OPEN_UPDATES_EVENT, handleOpenUpdates);
return () => window.removeEventListener(DESKTOP_OPEN_UPDATES_EVENT, handleOpenUpdates);
@@ -196,6 +233,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
void listenDesktopUpdateState((state) => {
if (!active) return;
setDesktopUpdateState(state);
+ if (state.remoteRequest?.phase === 'awaiting_host') setIsPopupOpen(true);
setChecking(state.phase === 'checking');
setUpgrading(['downloading', 'installing'].includes(state.phase));
}).then((cleanup) => {
@@ -218,8 +256,6 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
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
@@ -228,35 +264,54 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ React.useEffect(() => {
+ // The shell owns updates; it reads the Runtime's version only to show skew.
+ if (inDesktopShell || !capabilities.can_manage_instance) return;
+ const timer = window.setTimeout(() => {
+ void loadAutoUpdateSetting();
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, [capabilities.can_manage_instance, inDesktopShell, loadAutoUpdateSetting]);
+
const handleUpgrade = async () => {
- setUpgrading(true);
- setUpgradeResult(null);
- try {
- if (isDesktopManaged && desktopActions) {
+ if (isDesktopManaged && desktopActions) {
+ setUpgrading(true);
+ setUpgradeResult(null);
+ try {
await desktopActions.install();
await waitForDesktopUpdate();
- return;
+ } catch (error) {
+ setUpgradeResult({ ok: false, message: String(error), output: null, restarting: false });
+ } finally {
+ setUpgrading(false);
}
- const result = await api.doUpgrade();
- setUpgradeResult(result);
- if (result.ok) {
- if (result.restarting) {
- setRestarting(true);
- scheduleUpgradeReload(() => {
- window.location.reload();
- });
- } else {
- setTimeout(() => checkVersion(), 1000);
- }
- }
- } catch (e) {
- setUpgradeResult({ ok: false, message: String(e), output: null, activation_notice: null, restarting: false });
- } finally {
- setUpgrading(false);
+ return;
}
+ if (!capabilities.can_manage_instance || (isDesktopManaged && !canRequestRemoteUpdate)) return;
+ // Preserve the exact manifest target on the wire; normalization is display-only.
+ const target = versionInfo?.latest;
+ if (!target) return;
+ setRemoteRequestError(null);
+ setIsPopupOpen(false);
+ setRemoteConfirmation({
+ target,
+ delivery: isDesktopManaged
+ ? versionInfo?.remote_install_allowed === true ? 'install' : 'prompt'
+ : 'runtime',
+ });
};
const isDesktopManaged = inDesktopShell || versionInfo?.managed_by === 'desktop';
+ const remoteDesktopWeb = isDesktopManaged && !inDesktopShell && desktopUpdaterStatus === 'unavailable';
+ const canRequestRemoteUpdate = remoteDesktopWeb && capabilities.can_manage_instance;
+ const remoteRequest = versionInfo?.remote_request ?? null;
+ const remoteRequestActive = Boolean(remoteRequest && !TERMINAL_REMOTE_PHASES.includes(remoteRequest.phase));
+ const remoteCompleted = remoteRequest?.phase === 'completed'
+ && normalizeVersion(versionInfo?.current ?? '') === normalizeVersion(remoteRequest.target);
+ const completedTargetStillReportedAvailable = remoteCompleted
+ && normalizeVersion(versionInfo?.latest ?? '') === normalizeVersion(remoteRequest.target);
+ const localRemoteRequest = desktopUpdateState?.remoteRequest?.phase === 'awaiting_host'
+ ? desktopUpdateState.remoteRequest : null;
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
@@ -264,7 +319,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const hasUpdate = desktopActions
? desktopUpdateState?.phase === 'available'
&& (desktopUpdateState.interactive || desktopUpdateState.skippedVersion !== desktopUpdateState.latest)
- : versionInfo?.has_update === true;
+ : versionInfo?.has_update === true && !completedTargetStillReportedAvailable;
// The desktop app reports SemVer; show it in the Runtime's PEP 440 form.
const latestVersion = isDesktopManaged && desktopUpdateState?.latest
? normalizeVersion(desktopUpdateState.latest)
@@ -299,7 +354,11 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const handleSkipDesktopUpdate = async () => {
if (!desktopActions) return;
try {
- await desktopActions.skip();
+ if (desktopUpdateState?.remoteRequest?.phase === 'awaiting_host') {
+ await desktopActions.declineRemoteRequest();
+ } else {
+ await desktopActions.skip();
+ }
await readDesktopUpdateState();
setIsPopupOpen(false);
} catch (e) {
@@ -313,7 +372,145 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
}
};
+ const submitRemoteUpdateRequest = async () => {
+ if (!remoteConfirmation || !capabilities.can_manage_instance || remoteRequesting) return;
+ const confirmation = remoteConfirmation;
+ setRemoteRequesting(true);
+ setRemoteRequestError(null);
+ try {
+ const options = { confirmInterrupt: Boolean(confirmation.counts) };
+ if (confirmation.delivery === 'runtime') {
+ // Old clients can still omit confirmation. New clients explicitly opt in.
+ const result = await api.doUpgrade(options);
+ if (result.error === 'confirmation_required') {
+ setRemoteConfirmation({ ...confirmation, counts: result.counts });
+ return;
+ }
+ setUpgradeResult(result);
+ if (result.ok && result.restarting) {
+ setRestarting(true);
+ scheduleUpgradeReload(() => window.location.reload());
+ } else if (result.ok) {
+ void checkVersion(true);
+ }
+ } else {
+ if (!isDesktopManaged || desktopActions) return;
+ const result = await api.requestDesktopUpdate(confirmation.target, options);
+ if (!result.ok) {
+ if (result.error === 'confirmation_required') {
+ setRemoteConfirmation({ ...confirmation, counts: result.counts });
+ return;
+ }
+ setRemoteRequestError(result.error);
+ if (result.error === 'update_in_progress') void checkVersion(true);
+ } else {
+ setRemoteDelivery(result.delivery);
+ setRemoteUpdateTimedOut(false);
+ // Keep tracking this receipt even if the host disconnects before its
+ // next version response. An acknowledgement is not installation success.
+ setVersionInfo((previous) => previous && ({
+ ...previous,
+ remote_request: {
+ request_id: result.request_id, target: confirmation.target,
+ phase: 'acknowledged', progress: null, error_code: null,
+ updated_at: new Date().toISOString(),
+ },
+ }));
+ }
+ }
+ setRemoteConfirmation(null);
+ setIsPopupOpen(true);
+ } catch {
+ setRemoteRequestError('request_failed');
+ } finally {
+ setRemoteRequesting(false);
+ }
+ };
+
+ const remoteRequestSettled = remoteRequest && TERMINAL_REMOTE_PHASES.includes(remoteRequest.phase)
+ && (remoteRequest.phase !== 'completed' || remoteCompleted);
+ const remoteRequestId = remoteDesktopWeb && !remoteRequestSettled ? remoteRequest?.request_id : undefined;
+ React.useEffect(() => {
+ if (!remoteRequestId) return;
+ let stopped = false;
+ let pollTimer: number | undefined;
+ let reconnectDeadline: number | undefined;
+ let deadlineTimer: number | undefined;
+ const controller = new AbortController();
+ const stop = () => {
+ stopped = true;
+ window.clearTimeout(pollTimer);
+ window.clearTimeout(deadlineTimer);
+ controller.abort();
+ };
+ const timeOut = () => {
+ stop();
+ setRemoteUpdateTimedOut(true);
+ };
+ // Also bound a host that remains reachable but never advances its receipt.
+ deadlineTimer = window.setTimeout(timeOut, REMOTE_REQUEST_TIMEOUT_MS);
+ const startReconnectDeadline = () => {
+ if (reconnectDeadline !== undefined) return;
+ reconnectDeadline = Date.now() + REMOTE_RECONNECT_TIMEOUT_MS;
+ window.clearTimeout(deadlineTimer);
+ deadlineTimer = window.setTimeout(timeOut, REMOTE_RECONNECT_TIMEOUT_MS);
+ };
+ const poll = async () => {
+ try {
+ const fresh = await api.getVersion({ cache: false, background: true, signal: controller.signal });
+ if (stopped) return;
+ const receipt = fresh.remote_request;
+ // A missing/replaced receipt cannot prove this request completed.
+ if (receipt?.request_id === remoteRequestId) {
+ setVersionInfo(fresh);
+ setRemoteUpdateTimedOut(false);
+ setRemoteDisconnected(false);
+ if (receipt.phase === 'restarting') startReconnectDeadline();
+ if (TERMINAL_REMOTE_PHASES.includes(receipt.phase)) {
+ if (receipt.phase !== 'completed' || normalizeVersion(fresh.current) === normalizeVersion(receipt.target)) {
+ setRemoteUpdateTimedOut(false);
+ stop();
+ return;
+ }
+ startReconnectDeadline();
+ }
+ } else {
+ startReconnectDeadline();
+ }
+ } catch {
+ if (stopped) return;
+ setRemoteDisconnected(true);
+ startReconnectDeadline();
+ }
+ if (!stopped) pollTimer = window.setTimeout(() => void poll(), REMOTE_RECONNECT_POLL_MS);
+ };
+ void poll();
+ return stop;
+ }, [api, remoteRequestId]);
+
+ const remoteStatusText = remoteUpdateTimedOut ? t('dashboard.desktopRemoteUpdateTimedOut')
+ : remoteDisconnected || remoteRequest?.phase === 'restarting' ? t('dashboard.desktopRemoteUpdateRestarting')
+ : remoteCompleted ? t('dashboard.desktopRemoteUpdateCompleted', { target: remoteRequest?.target })
+ : remoteRequest?.phase === 'completed' ? t('dashboard.desktopRemoteUpdateVerifying')
+ : remoteRequest?.phase === 'failed' ? t('dashboard.desktopRemoteUpdateFailed')
+ : remoteRequest?.phase === 'declined' ? t('dashboard.desktopRemoteUpdateDeclined')
+ : remoteRequest?.phase === 'expired' ? t('dashboard.desktopRemoteUpdateExpired')
+ : remoteRequest?.phase === 'awaiting_host' ? t('dashboard.desktopRemoteUpdateAwaitingHost')
+ : remoteRequest?.phase === 'checking' ? t('dashboard.desktopRemoteUpdateChecking')
+ : remoteRequest?.phase === 'downloading' ? (remoteRequest.progress === null
+ ? t('dashboard.desktopRemoteUpdateDownloadingUnknown')
+ : t('dashboard.desktopRemoteUpdateDownloading', { progress: remoteRequest.progress }))
+ : remoteRequest?.phase === 'installing' ? t('dashboard.desktopRemoteUpdateInstalling')
+ : t('dashboard.desktopRemoteUpdateRequested');
+ const remoteErrorText = remoteRequestError === 'desktop_shell_unavailable'
+ ? t('dashboard.desktopRemoteUpdateShellUnavailable')
+ : remoteRequestError === 'no_update_available' ? t('dashboard.desktopRemoteUpdateNoUpdate')
+ : remoteRequestError === 'not_desktop_managed' ? t('dashboard.desktopRemoteUpdateNotManaged')
+ : remoteRequestError === 'update_in_progress' ? t('dashboard.desktopRemoteUpdateInProgress')
+ : t('dashboard.desktopRemoteUpdateError');
+
return (
+ <>
<Popover open={isPopupOpen} onOpenChange={setIsPopupOpen}>
<div className="relative" ref={popupRef}>
{/* Version Badge trigger */}
@@ -368,7 +565,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
size="icon"
className="h-7 w-7 text-muted hover:text-foreground"
onClick={() => checkVersion(true)}
- disabled={checking || restarting}
+ disabled={checking || restarting || (remoteRequestActive && !remoteUpdateTimedOut) || Boolean(localRemoteRequest)}
aria-label={refreshLabel}
title={refreshLabel}
>
@@ -419,8 +616,35 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
</div>
)}
+ {localRemoteRequest && (
+ <p className="rounded-md border border-cyan/30 bg-cyan/10 px-3 py-2 text-sm text-cyan-ink">
+ {t('dashboard.desktopRemoteUpdateLocalRequest', { target: localRemoteRequest.target })}
+ </p>
+ )}
+ {remoteDesktopWeb && (
+ <p className="text-xs text-muted">{t(capabilities.can_manage_instance
+ ? 'dashboard.desktopManagedUpdateOwnerHint' : 'dashboard.desktopManagedUpdateMemberHint')}</p>
+ )}
+ {remoteDesktopWeb && remoteDelivery && (
+ <p className="text-xs text-muted">{t('dashboard.desktopRemoteUpdateConfirmDescription', {
+ delivery: t(remoteDelivery === 'install'
+ ? 'dashboard.desktopRemoteUpdateDeliveryInstall' : 'dashboard.desktopRemoteUpdateDeliveryPrompt'),
+ })}</p>
+ )}
+ {remoteDesktopWeb && remoteRequest && (
+ <div role="status" className="space-y-2 rounded-md border border-border px-3 py-2 text-sm">
+ <p>{remoteStatusText}</p>
+ {remoteRequest.phase === 'failed' && remoteRequest.error_code === 'requires_host' && (
+ <p>{t('dashboard.desktopRemoteUpdateRequiresHost')}</p>
+ )}
+ </div>
+ )}
+ {remoteRequestError && !remoteConfirmation && (
+ <p role="alert" className="text-sm text-destructive-ink">{remoteErrorText}</p>
+ )}
+
{/* Update Status */}
- {!isSourceBuild && (isDesktopManaged && desktopUpdateState?.phase === 'checking' ? (
+ {!isSourceBuild && !(remoteDesktopWeb && remoteRequest) && (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>
@@ -512,7 +736,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
)}
{/* Auto Update Toggle: only once the Runtime has said who manages it */}
- {versionInfo && !isSourceBuild && !isDesktopManaged && autoUpdate !== null && (
+ {versionInfo && capabilities.can_manage_instance && !isSourceBuild && !isDesktopManaged && autoUpdate !== null && (
<div className="flex items-center justify-between gap-3 border-t border-border pt-3">
<div className="min-w-0">
<div className="text-sm text-foreground">{t('dashboard.autoUpdate')}</div>
@@ -534,14 +758,24 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
{isDesktopManaged && desktopActions && desktopUpdateState?.phase === 'available' ? (
<div className="flex items-center gap-2">
<Button variant="ghost" size="xs" onClick={handleSkipDesktopUpdate} disabled={upgrading}>
- {t('dashboard.skipUpdate')}
+ {t(localRemoteRequest ? 'dashboard.desktopRemoteUpdateIgnore' : '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 ? (
+ ) : remoteDesktopWeb && canRequestRemoteUpdate ? (
+ <Button
+ variant="brand"
+ size="xs"
+ onClick={handleUpgrade}
+ disabled={upgrading || remoteRequesting || Boolean(remoteRequest && !remoteRequestSettled) || remoteUpdateTimedOut}
+ >
+ <Download size={14} className={remoteRequesting ? 'animate-bounce' : ''} />
+ {remoteRequesting ? t('dashboard.desktopRemoteUpdateRequesting') : t('dashboard.desktopRemoteUpdateTitle')}
+ </Button>
+ ) : !isDesktopManaged && capabilities.can_manage_instance ? (
<Button variant="brand" size="xs" onClick={handleUpgrade} disabled={upgrading}>
<Download size={14} className={upgrading ? 'animate-bounce' : ''} />
{upgrading ? t('dashboard.upgrading') : t('dashboard.upgradeNow')}
@@ -553,5 +787,61 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
)}
</div>
</Popover>
+
+ <Dialog
+ open={remoteConfirmation !== null && capabilities.can_manage_instance}
+ onOpenChange={(open) => {
+ if (!open && !remoteRequesting) setRemoteConfirmation(null);
+ }}
+ >
+ <DialogContent className="max-w-md" closeLabel={t('common.close')}>
+ <DialogHeader>
+ <DialogTitle>{t('dashboard.desktopRemoteUpdateConfirmTitle', {
+ target: remoteConfirmation?.target ?? latestVersion ?? '',
+ })}</DialogTitle>
+ <DialogDescription>
+ {t('dashboard.desktopRemoteUpdateConfirmDescription', {
+ delivery: remoteConfirmation?.delivery === 'runtime'
+ ? t('dashboard.runtimeUpdateDelivery')
+ : remoteConfirmation?.delivery === 'install'
+ ? t('dashboard.desktopRemoteUpdateDeliveryInstall')
+ : t('dashboard.desktopRemoteUpdateDeliveryPrompt'),
+ })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2 text-sm text-muted">
+ <p>{remoteConfirmation?.counts
+ ? t('dashboard.desktopRemoteUpdateInterruptions', remoteConfirmation.counts)
+ : t('dashboard.desktopRemoteUpdateCheckWork')}</p>
+ {remoteConfirmation?.counts?.unknown && <p>{t('dashboard.desktopRemoteUpdateUnknownWork')}</p>}
+ <p>{t('dashboard.updateInterruptWarning')}</p>
+ {remoteRequestError && <p role="alert" className="text-destructive-ink">{t('dashboard.desktopRemoteUpdateError')}</p>}
+
+ </div>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setRemoteConfirmation(null)}
+ disabled={remoteRequesting}
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ variant="brand"
+ onClick={() => void submitRemoteUpdateRequest()}
+ disabled={remoteRequesting}
+ >
+ {remoteRequesting
+ ? t('dashboard.desktopRemoteUpdateRequesting')
+ : remoteConfirmation?.counts
+ ? t('dashboard.desktopRemoteUpdateConfirmInterrupt')
+ : t('dashboard.desktopRemoteUpdateConfirm')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
);
};
diff --git a/ui/src/components/settings/DesktopRemoteUpdateSetting.test.tsx b/ui/src/components/settings/DesktopRemoteUpdateSetting.test.tsx
new file mode 100644
index 000000000..dd6b66a6a
--- /dev/null
+++ b/ui/src/components/settings/DesktopRemoteUpdateSetting.test.tsx
@@ -0,0 +1,76 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import i18n from '@/i18n';
+import { DesktopRemoteUpdateSetting } from './DesktopRemoteUpdateSetting';
+
+function shell(invoke: (command: string, args?: Record<string, unknown>) => Promise<unknown>) {
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+}
+function show() {
+ return render(<I18nextProvider i18n={i18n}><DesktopRemoteUpdateSetting /></I18nextProvider>);
+}
+afterEach(() => {
+ cleanup();
+ delete (window as { __AVIBE_DESKTOP_SHELL__?: true }).__AVIBE_DESKTOP_SHELL__;
+ delete (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
+});
+
+// No prior General setting wrote through Tauri IPC. These exercise real command
+// wrappers to catch false capability detection and a write before risk consent.
+describe('Desktop remote install setting', () => {
+ it('is absent on Web even with a generic invoke bridge', async () => {
+ const invoke = vi.fn();
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ show();
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(invoke).not.toHaveBeenCalled();
+ });
+
+ it.each(['rejected', 'undefined'] as const)('hides on an old shell with a %s probe', async (kind) => {
+ const invoke = vi.fn(async () => { if (kind === 'rejected') throw new Error('unknown command'); });
+ shell(invoke);
+ await act(async () => { show(); });
+ expect(invoke).toHaveBeenCalledWith('desktop_remote_install_allowed');
+ expect(screen.queryByRole('switch')).toBeNull();
+ });
+
+ it.each([true, false])('reads the shell value %s without writing', async (enabled) => {
+ const invoke = vi.fn(async () => enabled);
+ shell(invoke); show();
+ const control = await screen.findByRole('switch');
+ expect(control.getAttribute('aria-checked')).toBe(String(enabled));
+ expect(invoke).toHaveBeenCalledTimes(1);
+ });
+
+ it('explains risks before enabling, can cancel, and persists only after confirmation', async () => {
+ const invoke = vi.fn(async (command: string, args?: Record<string, unknown>) => command.endsWith('_set') ? args?.enabled : false);
+ shell(invoke); show();
+ const control = await screen.findByRole('switch');
+ fireEvent.click(control);
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.getByText(i18n.t('settings.general.remoteInstallWarning'))).toBeTruthy();
+ expect(invoke).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('common.cancel') }));
+ expect(invoke).toHaveBeenCalledTimes(1);
+ fireEvent.click(control);
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('settings.general.remoteInstallEnable') }));
+ await vi.waitFor(() => expect(control.getAttribute('aria-checked')).toBe('true'));
+ expect(invoke).toHaveBeenCalledWith('desktop_remote_install_set', { enabled: true });
+ fireEvent.click(control);
+ await vi.waitFor(() => expect(control.getAttribute('aria-checked')).toBe('false'));
+ expect(invoke).toHaveBeenCalledWith('desktop_remote_install_set', { enabled: false });
+ });
+
+ it('preserves the shell value and displays a rejected save', async () => {
+ const invoke = vi.fn(async (command: string) => { if (command.endsWith('_set')) throw new Error('not allowed'); return false; });
+ shell(invoke); show();
+ const control = await screen.findByRole('switch');
+ fireEvent.click(control);
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('settings.general.remoteInstallEnable') }));
+ expect(await screen.findByRole('alert')).toBeTruthy();
+ expect(control.getAttribute('aria-checked')).toBe('false');
+ });
+});
diff --git a/ui/src/components/settings/DesktopRemoteUpdateSetting.tsx b/ui/src/components/settings/DesktopRemoteUpdateSetting.tsx
new file mode 100644
index 000000000..e3b94382c
--- /dev/null
+++ b/ui/src/components/settings/DesktopRemoteUpdateSetting.tsx
@@ -0,0 +1,96 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { desktopRemoteInstallActions, isDesktopShell, type DesktopRemoteInstallActions } from '../../lib/desktopShell';
+import { SettingsPanel, ToggleSwitch } from './SettingsPrimitives';
+import { Button } from '../ui/button';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';
+
+/**
+ * A local-shell-only preference. The Runtime and remote browsers may report
+ * the resulting value, but only this Workbench window can read or write it.
+ */
+export const DesktopRemoteUpdateSetting: React.FC = () => {
+ const { t } = useTranslation();
+ const [actions, setActions] = React.useState<DesktopRemoteInstallActions | null>(null);
+ const [enabled, setEnabled] = React.useState<boolean | null>(null);
+ const [saving, setSaving] = React.useState(false);
+ const [confirming, setConfirming] = React.useState(false);
+ const [saveFailed, setSaveFailed] = React.useState(false);
+
+ React.useEffect(() => {
+ if (!isDesktopShell()) return;
+ const candidate = desktopRemoteInstallActions();
+ if (!candidate) return;
+ let active = true;
+ void candidate.get().then((value) => {
+ if (!active) return;
+ setActions(candidate);
+ setEnabled(value);
+ }).catch(() => {
+ // Unknown commands are the compatibility signal for an older shell.
+ if (active) {
+ setActions(null);
+ setEnabled(null);
+ }
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ if (!actions || enabled === null) return null;
+
+ const handleChange = async (next: boolean) => {
+ if (saving) return;
+ setSaving(true);
+ setSaveFailed(false);
+ try {
+ const saved = await actions.set(next);
+ setEnabled(saved);
+ setConfirming(false);
+ } catch {
+ setSaveFailed(true);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <>
+ <SettingsPanel
+ variant="preference"
+ title={t('settings.general.remoteInstallTitle')}
+ description={t('settings.general.remoteInstallDescription')}
+ actions={(
+ <ToggleSwitch
+ enabled={enabled}
+ onClick={() => enabled ? void handleChange(false) : setConfirming(true)}
+ disabled={saving}
+ label={t('settings.general.remoteInstallTitle')}
+ />
+ )}
+ >
+ {enabled && (
+ <p className="rounded-md border border-gold/30 bg-gold/10 px-3 py-2 text-[12px] leading-relaxed text-gold-ink">
+ {t('settings.general.remoteInstallWarning')}
+ </p>
+ )}
+ {saveFailed && !confirming && <p role="alert" className="text-sm text-destructive-ink">{t('settings.general.remoteInstallSaveFailed')}</p>}
+ </SettingsPanel>
+ <Dialog open={confirming} onOpenChange={(open) => { if (!saving) setConfirming(open); }}>
+ <DialogContent closeLabel={t('common.close')}>
+ <DialogHeader>
+ <DialogTitle>{t('settings.general.remoteInstallTitle')}</DialogTitle>
+ <DialogDescription>{t('settings.general.remoteInstallWarning')}</DialogDescription>
+ </DialogHeader>
+ {saveFailed && <p role="alert" className="text-sm text-destructive-ink">{t('settings.general.remoteInstallSaveFailed')}</p>}
+ <DialogFooter>
+ <Button variant="ghost" disabled={saving} onClick={() => setConfirming(false)}>{t('common.cancel')}</Button>
+ <Button variant="brand" disabled={saving} onClick={() => void handleChange(true)}>{t('settings.general.remoteInstallEnable')}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/ui/src/components/settings/SettingsGeneralPage.tsx b/ui/src/components/settings/SettingsGeneralPage.tsx
index 7519481ab..673dbc2f6 100644
--- a/ui/src/components/settings/SettingsGeneralPage.tsx
+++ b/ui/src/components/settings/SettingsGeneralPage.tsx
@@ -17,6 +17,7 @@ import {
import type { SettingsMenuPlacement } from '../../lib/settingsMenuPlacement';
import type { TranslationKey } from '../../i18n/types';
import { useDesktopPetSettings } from '../../lib/useDesktopPetSettings';
+import { DesktopRemoteUpdateSetting } from './DesktopRemoteUpdateSetting';
// The 88px miniature is a drawing OF a theme, not a preview rendered IN one:
// the Light card has to look light while the app is dark. Source Q8zxF1 builds
@@ -321,6 +322,7 @@ export const SettingsGeneralPage: React.FC = () => {
)}
</SettingsPanel>
)}
+ <DesktopRemoteUpdateSetting />
{/* i3LvLl — the autosave contract, stated once for the whole page. */}
<div className="flex items-center gap-2 text-[12px] text-muted">
diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsx
index 1d4c10348..4c9a08e11 100644
--- a/ui/src/components/settings/SettingsLayout.test.tsx
+++ b/ui/src/components/settings/SettingsLayout.test.tsx
@@ -32,7 +32,7 @@ const api = vi.hoisted(() => {
};
});
const authorization = vi.hoisted(() => ({
- capabilities: { can_manage_instance: true },
+ capabilities: { can_manage_instance: true, can_read_instance: true },
}));
const media = vi.hoisted(() => ({
matches: false,
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index aaeda4f78..82a90f268 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -411,7 +411,7 @@ export const SettingsLayout: React.FC = () => {
)}
</div>
<div className="flex shrink-0 items-center gap-1">
- {capabilities.can_manage_instance && (
+ {capabilities.can_read_instance && (
<div className="md:hidden">
<VersionBadge />
</div>
diff --git a/ui/src/context/ApiContext.desktopUpdate.test.tsx b/ui/src/context/ApiContext.desktopUpdate.test.tsx
new file mode 100644
index 000000000..013df5f93
--- /dev/null
+++ b/ui/src/context/ApiContext.desktopUpdate.test.tsx
@@ -0,0 +1,105 @@
+/* @vitest-environment jsdom */
+
+import { useEffect } from 'react';
+import { cleanup, render } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+const showToast = vi.hoisted(() => vi.fn());
+vi.mock('../lib/apiFetch', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../lib/apiFetch')>(),
+ apiFetch,
+}));
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast }) }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { ApiError, ApiProvider, useApi } from './ApiContext';
+
+let api: ReturnType<typeof useApi>;
+function CaptureApi() {
+ const value = useApi();
+ useEffect(() => { api = value; }, [value]);
+ return null;
+}
+const response = (payload: unknown, status = 200) => new Response(JSON.stringify(payload), {
+ status, headers: { 'Content-Type': 'application/json' },
+});
+beforeEach(() => {
+ apiFetch.mockReset();
+ showToast.mockReset();
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+// Component mocks cannot protect the HTTP boundary: requestJson must retain
+// the 409 body, and new clients must send false rather than omit confirmation.
+describe('update HTTP contracts', () => {
+ it.each(['desktop', 'runtime'] as const)('preserves %s nested 409 counts and sends false/true', async (kind) => {
+ const confirmation = {
+ ok: false, error: 'confirmation_required',
+ counts: { agents: 2, watches: 3, tasks: 4, total: 9, unknown: true },
+ };
+ const accepted = kind === 'desktop'
+ ? { ok: true, request_id: 'request-1', delivery: 'prompt' }
+ : { ok: true, message: 'Restarting', output: null, restarting: true };
+ apiFetch.mockResolvedValueOnce(response(confirmation, 409)).mockResolvedValueOnce(response(accepted));
+ const submit = (confirmInterrupt: boolean) => kind === 'desktop'
+ ? api.requestDesktopUpdate('3.2.4-rc.1', { confirmInterrupt })
+ : api.doUpgrade({ confirmInterrupt });
+ expect(await submit(false)).toEqual(confirmation);
+ expect(await submit(true)).toEqual(accepted);
+ expect(apiFetch.mock.calls.map(([path, init]) => [path, JSON.parse(init.body)])).toEqual(
+ [false, true].map((confirm_interrupt) => [
+ kind === 'desktop' ? '/api/desktop/update/request' : '/api/upgrade',
+ kind === 'desktop' ? { target_version: '3.2.4-rc.1', confirm_interrupt } : { confirm_interrupt },
+ ]),
+ );
+ expect(showToast).not.toHaveBeenCalled();
+ });
+
+ it('defaults desktop requests to false while retaining the legacy Runtime omission', async () => {
+ apiFetch.mockResolvedValueOnce(response({ ok: true, request_id: 'request-1', delivery: 'install' }))
+ .mockResolvedValueOnce(response({ ok: true, restarting: true }));
+ await api.requestDesktopUpdate('3.2.4');
+ await api.doUpgrade();
+ expect(JSON.parse(apiFetch.mock.calls[0][1].body)).toEqual({ target_version: '3.2.4', confirm_interrupt: false });
+ expect(JSON.parse(apiFetch.mock.calls[1][1].body)).toEqual({});
+ });
+
+ it.each(['not_desktop_managed', 'no_update_available', 'update_in_progress', 'desktop_shell_unavailable'])(
+ 'returns stable error %s without losing the error field', async (error) => {
+ apiFetch.mockResolvedValueOnce(response({ ok: false, error }, 409));
+ expect(await api.requestDesktopUpdate('3.2.4')).toEqual({ ok: false, error });
+ expect(showToast).not.toHaveBeenCalled();
+ },
+ );
+
+ it('rejects an authorization failure instead of treating it as an accepted receipt', async () => {
+ apiFetch.mockResolvedValueOnce(response({ ok: false, error: 'forbidden' }, 403));
+ await expect(api.requestDesktopUpdate('3.2.4')).rejects.toMatchObject({ status: 403, code: 'forbidden' });
+ expect(showToast).not.toHaveBeenCalled();
+ });
+
+ it('bounds a hung reconnect read without displaying a global error toast', async () => {
+ vi.useFakeTimers();
+ apiFetch.mockImplementationOnce((_path, { signal }: RequestInit) => new Promise((_resolve, reject) => {
+ signal!.addEventListener('abort', () => reject(signal!.reason), { once: true });
+ }));
+ const read = api.getVersion({ background: true, cache: false });
+ const rejection = expect(read).rejects.toBeTruthy();
+ await vi.advanceTimersByTimeAsync(10_000);
+ await rejection;
+ expect(showToast).not.toHaveBeenCalled();
+ });
+
+ it('rejects failed reconnect responses quietly', async () => {
+ apiFetch.mockResolvedValueOnce(response({}, 503));
+ await expect(api.getVersion({ background: true })).rejects.toBeInstanceOf(ApiError);
+ expect(showToast).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 386b82a34..915bdaa4b 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -720,8 +720,12 @@ export type ApiContextType = {
backend: string,
) => Promise<PickerAgentCatalog | null>;
getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;
- getVersion: (options?: { cache?: boolean }) => Promise<VersionInfo>;
- doUpgrade: () => Promise<UpgradeResult>;
+ getVersion: (options?: { cache?: boolean; background?: boolean; signal?: AbortSignal }) => Promise<VersionInfo>;
+ requestDesktopUpdate: (
+ targetVersion: string,
+ options?: { confirmInterrupt?: boolean },
+ ) => Promise<DesktopRemoteUpdateResult>;
+ doUpgrade: (options?: { confirmInterrupt: boolean }) => 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 }>;
browseMkdir: (path: string) => Promise<{ path: string }>;
@@ -1937,6 +1941,8 @@ export type VersionInfo = {
has_update: boolean;
error: string | null;
managed_by?: 'desktop';
+ remote_install_allowed?: boolean;
+ remote_request?: DesktopRemoteUpdateRequest | null;
build?: {
kind: 'package' | 'source';
revision?: string;
@@ -1944,13 +1950,66 @@ export type VersionInfo = {
};
};
-export type UpgradeResult = {
+export type DesktopRemoteUpdatePhase =
+ | 'requested'
+ | 'acknowledged'
+ | 'checking'
+ | 'awaiting_host'
+ | 'downloading'
+ | 'installing'
+ | 'restarting'
+ | 'completed'
+ | 'failed'
+ | 'declined'
+ | 'expired';
+
+export type DesktopRemoteUpdateRequest = {
+ request_id: string;
+ target: string;
+ phase: DesktopRemoteUpdatePhase;
+ progress: number | null;
+ error_code: string | null;
+ updated_at: string;
+};
+
+export type DesktopRemoteUpdateErrorCode =
+ | 'not_desktop_managed'
+ | 'no_update_available'
+ | 'update_in_progress'
+ | 'desktop_shell_unavailable'
+ | 'confirmation_required';
+
+export type DesktopRemoteUpdateResult =
+ | { ok: true; request_id: string; delivery: 'prompt' | 'install' }
+ | UpdateConfirmationRequired
+ | {
+ ok: false;
+ error: Exclude<DesktopRemoteUpdateErrorCode, 'confirmation_required'>;
+ message?: string;
+ };
+
+export type UpdateInterruptionCounts = {
+ agents: number;
+ watches: number;
+ tasks: number;
+ total: number;
+ unknown: boolean;
+};
+
+export type UpdateConfirmationRequired = {
+ ok: false;
+ error: 'confirmation_required';
+ counts: UpdateInterruptionCounts;
+};
+
+export type UpgradeResult = UpdateConfirmationRequired | {
ok: boolean;
message: string;
output: string | null;
activation_notice?: string | null;
restarting: boolean;
code?: string;
+ error?: never;
};
export type InstallResult = {
@@ -3763,8 +3822,48 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
})
.catch(() => null),
getLogs: (lines = 500, source) => postJson('/api/logs', source ? { lines, source } : { lines }),
- getVersion: (options) => getCachedJson('/api/version', 10_000, options),
- doUpgrade: () => postJson('/api/upgrade', {}),
+ getVersion: (options) => options?.background
+ ? withApiDeadline(10_000, options.signal, async (signal) => {
+ const response = await apiFetch('/api/version', { signal });
+ // Reconnect failures belong to the update status, not repeated toasts.
+ if (!response.ok) throw new ApiError('Version read unavailable', response.status, null);
+ const payload = await response.json();
+ if (typeof payload?.current !== 'string') throw new Error('Invalid version response');
+ return payload as VersionInfo;
+ })
+ : getCachedJson('/api/version', 10_000, options),
+ requestDesktopUpdate: async (targetVersion, options) => {
+ const { res, payloadJson } = await requestJson(
+ '/api/desktop/update/request',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ target_version: targetVersion,
+ confirm_interrupt: options?.confirmInterrupt ?? false,
+ }),
+ },
+ '/api/desktop/update/request',
+ { handleError: false },
+ );
+ if (!res.ok && !['not_desktop_managed', 'no_update_available', 'update_in_progress',
+ 'desktop_shell_unavailable', 'confirmation_required'].includes(payloadJson?.error)) {
+ throw new ApiError('Desktop update request failed', res.status, payloadJson?.error ?? null);
+ }
+ return payloadJson as DesktopRemoteUpdateResult;
+ },
+ doUpgrade: async (options) => {
+ if (!options) return postJson('/api/upgrade', {});
+ const { res, payloadJson } = await requestJson('/api/upgrade', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ confirm_interrupt: options.confirmInterrupt }),
+ }, '/api/upgrade', { handleError: false });
+ if (!res.ok && payloadJson?.error !== 'confirmation_required') {
+ throw new ApiError('Upgrade request failed', res.status, payloadJson?.error ?? null);
+ }
+ return payloadJson as UpgradeResult;
+ },
browseDirectory: (path, showHidden) => postJson('/api/browse', { path, show_hidden: showHidden || false }),
browseFavorites: () => getJson('/api/browse/favorites'),
browseMkdir: (path) => postJson('/api/browse/mkdir', { path }),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b0d3ad0c3..43f6a7b31 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -468,6 +468,11 @@
"menuPlacementDescription": "Let Settings take over the window, or open it beside the app sidebar. Saved in this browser.",
"menuPlacementStandalone": "Standalone",
"menuPlacementInline": "Inline",
+ "remoteInstallEnable": "Enable remote installs",
+ "remoteInstallSaveFailed": "The desktop preference could not be saved. Try again.",
+ "remoteInstallTitle": "Allow remote installs",
+ "remoteInstallDescription": "Let authorized members install updates from a browser without confirmation on the host. This setting can only be changed in the desktop app.",
+ "remoteInstallWarning": "Remote installs can restart Avibe without someone at the host, interrupt running work, and leave a failed update for someone on the host to repair.",
"autosaved": "Changes are saved automatically",
"languageSaveFailed": "The language changed here, but could not be saved for this instance",
"desktopMini": {
@@ -4186,6 +4191,42 @@
"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.",
+ "desktopManagedUpdateOwnerHint": "Request the update on the host. The desktop app will prompt there or install unattended according to its local setting.",
+ "desktopManagedUpdateMemberHint": "Update this host in the Avibe desktop app on the computer running Avibe.",
+ "desktopRemoteUpdateCheckWork": "Active work will be checked when you submit. If any work is running or cannot be checked, you will be asked to confirm interruption.",
+ "desktopRemoteUpdateUnknownWork": "Some activity could not be checked. Additional running work may be interrupted.",
+ "updateInterruptWarning": "Installation restarts Avibe and can interrupt Agent, Watch, Task, and IM work. Interrupted work may not resume.",
+ "runtimeUpdateDelivery": "a Runtime upgrade and restart",
+ "desktopRemoteUpdateLocalRequest": "An update to {{target}} was requested remotely. Install it now or ignore this request.",
+ "desktopRemoteUpdateRequiresHost": "This installation needs someone at the host to grant permission or repair the installation.",
+ "desktopRemoteUpdateVerifying": "The host reported completion. Waiting to confirm the installed version…",
+ "desktopRemoteUpdateDownloadingUnknown": "Downloading the update…",
+ "desktopRemoteUpdateShellUnavailable": "The desktop app did not respond. Open Avibe on the host and try again.",
+ "desktopRemoteUpdateNoUpdate": "This update is no longer available. Refresh the version information.",
+ "desktopRemoteUpdateNotManaged": "This host is no longer managed by the desktop app. Refresh the version information.",
+ "desktopRemoteUpdateInProgress": "Another update is in progress. Wait for the host to finish.",
+ "desktopRemoteUpdateTitle": "Update on host",
+ "desktopRemoteUpdateConfirmTitle": "Update the host to {{target}}?",
+ "desktopRemoteUpdateConfirmDescription": "The request will be delivered as {{delivery}}.",
+ "desktopRemoteUpdateDeliveryPrompt": "a host prompt",
+ "desktopRemoteUpdateDeliveryInstall": "an unattended install",
+ "desktopRemoteUpdateInterruptions": "{{agents}} agents, {{watches}} watches, and {{tasks}} tasks may be interrupted.",
+ "desktopRemoteUpdateConfirm": "Request update",
+ "desktopRemoteUpdateConfirmInterrupt": "Confirm and interrupt active work",
+ "desktopRemoteUpdateRequesting": "Requesting the host update…",
+ "desktopRemoteUpdateRequested": "The update request was sent to the host.",
+ "desktopRemoteUpdateAwaitingHost": "The host is waiting for someone there to approve the install.",
+ "desktopRemoteUpdateChecking": "The host is checking the signed release.",
+ "desktopRemoteUpdateDownloading": "Downloading the update: {{progress}}%",
+ "desktopRemoteUpdateInstalling": "Installing the update…",
+ "desktopRemoteUpdateRestarting": "Host restarting. Reconnecting automatically…",
+ "desktopRemoteUpdateCompleted": "The host finished updating to {{target}}.",
+ "desktopRemoteUpdateFailed": "The host could not finish the update. Check the desktop app on the host.",
+ "desktopRemoteUpdateDeclined": "The host declined the update.",
+ "desktopRemoteUpdateExpired": "The host update request expired.",
+ "desktopRemoteUpdateTimedOut": "Completion was not confirmed. Check the desktop app on the host.",
+ "desktopRemoteUpdateError": "The host could not accept the update request.",
+ "desktopRemoteUpdateIgnore": "Ignore this request",
"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.json
index e8abfd6a7..e6963b586 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -468,6 +468,11 @@
"menuPlacementDescription": "让设置占满窗口,或者展开在应用侧栏旁边。保存在当前浏览器。",
"menuPlacementStandalone": "独立",
"menuPlacementInline": "内联",
+ "remoteInstallEnable": "启用远程安装",
+ "remoteInstallSaveFailed": "未能保存桌面设置,请重试。",
+ "remoteInstallTitle": "允许远程安装",
+ "remoteInstallDescription": "允许有权限的成员从浏览器安装更新,无需在主机上再次确认。此设置只能在桌面应用中修改。",
+ "remoteInstallWarning": "远程安装可能在主机无人值守时重启 Avibe、中断正在运行的工作,并在更新失败时需要主机上的人修复。",
"autosaved": "修改会自动保存",
"languageSaveFailed": "语言已在本机切换,但未能保存到此实例",
"desktopMini": {
@@ -4186,6 +4191,42 @@
"autoUpdateHint": "空闲时自动安装",
"desktopManagedUpdate": "更新由运行 Avibe 的那台电脑上的桌面应用提供,请在那里检查更新。",
"desktopManagedUpdateAvailable": "有新版本 {{to}},请在运行 Avibe 的那台电脑上通过 Avibe 桌面应用更新。",
+ "desktopManagedUpdateOwnerHint": "请求主机更新。桌面应用会按本机设置在主机上提示确认,或直接无人值守安装。",
+ "desktopManagedUpdateMemberHint": "请在运行 Avibe 的那台电脑上的桌面应用中更新此主机。",
+ "desktopRemoteUpdateCheckWork": "提交时将检查活动工作。如果有工作正在运行或无法检查,将再次请你确认中断。",
+ "desktopRemoteUpdateUnknownWork": "部分活动无法检查,可能还会中断其他正在运行的工作。",
+ "updateInterruptWarning": "安装会重启 Avibe,可能中断 Agent、Watch、Task 和 IM 工作;中断的工作可能无法恢复。",
+ "runtimeUpdateDelivery": "Runtime 更新并重启",
+ "desktopRemoteUpdateLocalRequest": "有人远程请求更新到 {{target}}。你可以立即安装或忽略此请求。",
+ "desktopRemoteUpdateRequiresHost": "此安装需要主机上的用户授予权限或修复安装。",
+ "desktopRemoteUpdateVerifying": "主机已报告完成,正在等待确认已安装的版本…",
+ "desktopRemoteUpdateDownloadingUnknown": "正在下载更新…",
+ "desktopRemoteUpdateShellUnavailable": "桌面应用未响应。请在主机上打开 Avibe 后重试。",
+ "desktopRemoteUpdateNoUpdate": "此更新已不可用,请刷新版本信息。",
+ "desktopRemoteUpdateNotManaged": "此主机已不再由桌面应用管理,请刷新版本信息。",
+ "desktopRemoteUpdateInProgress": "另一个更新正在进行,请等待主机完成。",
+ "desktopRemoteUpdateTitle": "在主机上更新",
+ "desktopRemoteUpdateConfirmTitle": "将主机更新到 {{target}}?",
+ "desktopRemoteUpdateConfirmDescription": "请求将以{{delivery}}的方式送达。",
+ "desktopRemoteUpdateDeliveryPrompt": "主机提示确认",
+ "desktopRemoteUpdateDeliveryInstall": "无人值守安装",
+ "desktopRemoteUpdateInterruptions": "可能会中断 {{agents}} 个 Agent、{{watches}} 个 Watch 和 {{tasks}} 个 Task。",
+ "desktopRemoteUpdateConfirm": "请求更新",
+ "desktopRemoteUpdateConfirmInterrupt": "确认并中断正在运行的任务",
+ "desktopRemoteUpdateRequesting": "正在请求主机更新…",
+ "desktopRemoteUpdateRequested": "更新请求已发送到主机。",
+ "desktopRemoteUpdateAwaitingHost": "主机正在等待那里的用户确认安装。",
+ "desktopRemoteUpdateChecking": "主机正在检查已签名的版本。",
+ "desktopRemoteUpdateDownloading": "正在下载更新:{{progress}}%",
+ "desktopRemoteUpdateInstalling": "正在安装更新…",
+ "desktopRemoteUpdateRestarting": "主机正在重启,将自动重连…",
+ "desktopRemoteUpdateCompleted": "主机已更新到 {{target}}。",
+ "desktopRemoteUpdateFailed": "主机未能完成更新,请检查主机上的桌面应用。",
+ "desktopRemoteUpdateDeclined": "主机已拒绝更新。",
+ "desktopRemoteUpdateExpired": "主机更新请求已过期。",
+ "desktopRemoteUpdateTimedOut": "尚未确认更新完成,请检查主机上的桌面应用。",
+ "desktopRemoteUpdateError": "主机未能接受更新请求。",
+ "desktopRemoteUpdateIgnore": "忽略此请求",
"runtimeVersionSkew": "本应用为 v{{app}},但连接的 Avibe 运行时为 v{{runtime}}"
},
"doctor": {
diff --git a/ui/src/lib/desktopShell.ts b/ui/src/lib/desktopShell.ts
index 43b775b02..9be29553e 100644
--- a/ui/src/lib/desktopShell.ts
+++ b/ui/src/lib/desktopShell.ts
@@ -140,6 +140,26 @@ export type DesktopUpdateState = {
channel: 'stable' | 'test';
skippedVersion: string | null;
interactive: boolean;
+ remoteInstallAllowed?: boolean;
+ remoteRequest?: {
+ requestId: string;
+ target: string;
+ phase:
+ | 'requested'
+ | 'acknowledged'
+ | 'checking'
+ | 'awaiting_host'
+ | 'downloading'
+ | 'installing'
+ | 'restarting'
+ | 'completed'
+ | 'failed'
+ | 'declined'
+ | 'expired';
+ progress: number | null;
+ errorCode: string | null;
+ updatedAt: string;
+ } | null;
};
const desktopUpdateInvoke = (): ShellInvoke | null => {
@@ -163,6 +183,7 @@ export type DesktopUpdateShellActions = {
check: () => Promise<void>;
install: () => Promise<void>;
skip: () => Promise<void>;
+ declineRemoteRequest: () => Promise<void>;
};
export function desktopUpdateShellActions(): DesktopUpdateShellActions | null {
@@ -173,6 +194,33 @@ export function desktopUpdateShellActions(): DesktopUpdateShellActions | null {
check: async () => { await invoke('desktop_update_check'); },
install: async () => { await invoke('desktop_update_install'); },
skip: async () => { await invoke('desktop_update_skip'); },
+ declineRemoteRequest: async () => { await invoke('desktop_update_remote_decline'); },
+ };
+}
+
+export type DesktopRemoteInstallActions = {
+ get: () => Promise<boolean>;
+ set: (enabled: boolean) => Promise<boolean>;
+};
+
+/**
+ * The remote-install preference is shell-owned. The command probe is also the
+ * compatibility boundary: Web pages and older shells simply have no setting.
+ */
+export function desktopRemoteInstallActions(): DesktopRemoteInstallActions | null {
+ const invoke = desktopUpdateInvoke();
+ if (!invoke) return null;
+ return {
+ get: async () => {
+ const value = await invoke('desktop_remote_install_allowed');
+ if (typeof value !== 'boolean') throw new Error('Remote install preference is unavailable');
+ return value;
+ },
+ set: async (enabled) => {
+ const value = await invoke('desktop_remote_install_set', { enabled });
+ if (typeof value !== 'boolean') throw new Error('Remote install preference was not confirmed');
+ return value;
+ },
};
}
diff --git a/vibe/api.py b/vibe/api.py
index dc1368a60..15453c01d 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -6969,6 +6969,10 @@ def get_version_info() -> dict:
"latest": status["latest"] if status else None,
"has_update": status["has_update"] if status else False,
"error": None,
+ "remote_install_allowed": (
+ status["remote_install_allowed"] if status else False
+ ),
+ "remote_request": status["remote_request"] if status else None,
}
elif build.kind == "source":
result = {"current": __version__, "latest": None, "has_update": False, "error": None}
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 3283a7d26..e4c971a59 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -599,6 +599,7 @@ _MEMBER_HTTP_RULES = tuple(
("POST", r"^/api/logs$"),
("POST", r"^/api/opencode/options$"),
("POST", r"^/api/upgrade$"),
+ ("POST", r"^/api/desktop/update/request$"),
("POST", r"^/api/opencode/setup-permission$"),
("GET", r"^/api/opencode/permission-status$"),
("GET", r"^/api/claude/agents$"),
diff --git a/vibe/desktop_update_request.py b/vibe/desktop_update_request.py
new file mode 100644
index 000000000..92891c8e7
--- /dev/null
+++ b/vibe/desktop_update_request.py
@@ -0,0 +1,286 @@
+"""Runtime-owned requests for the desktop shell's signed updater."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+import json
+import logging
+from pathlib import Path
+import re
+import threading
+from typing import Any, Literal, TypedDict
+from uuid import UUID, uuid4
+
+from config.atomic_io import write_atomic
+from core.computer_use import desktop_computer_use_dir
+from vibe.desktop_update_status import (
+ DesktopUpdateStatus,
+ RemoteDesktopUpdateStatus,
+ read_desktop_update_status,
+)
+
+logger = logging.getLogger(__name__)
+
+UPDATE_REQUEST_SCHEMA_VERSION = 1
+UPDATE_REQUEST_FILE = "desktop-update-request.json"
+UPDATE_REQUEST_TTL = timedelta(minutes=30)
+_TARGET_VERSION = re.compile(
+ r"^[0-9]+(?:\.[0-9]+){2}"
+ r"(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z-]+)*)?"
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
+)
+_TERMINAL_PHASES = frozenset({"completed", "failed", "declined", "expired"})
+_ACKNOWLEDGED_PHASES = frozenset(
+ {
+ "acknowledged",
+ "awaiting_host",
+ "checking",
+ "downloading",
+ "installing",
+ "restarting",
+ *_TERMINAL_PHASES,
+ }
+)
+_REQUEST_LOCK = threading.Lock()
+
+
+class DesktopUpdateRequest(TypedDict):
+ schema_version: int
+ request_id: str
+ target: str
+ state: Literal["pending", "expired"]
+ created_at: str
+ expires_at: str
+
+
+@dataclass(frozen=True)
+class RequestDecision:
+ request: DesktopUpdateRequest
+ reused: bool
+ needs_nudge: bool
+
+
+class DesktopUpdateRequestError(RuntimeError):
+ def __init__(self, code: str):
+ super().__init__(code)
+ self.code = code
+
+
+def desktop_update_request_path(**kwargs: Any) -> Path:
+ return desktop_computer_use_dir(**kwargs) / UPDATE_REQUEST_FILE
+
+
+def _utc_timestamp(value: datetime) -> str:
+ normalized = value.astimezone(timezone.utc).replace(microsecond=0)
+ return normalized.isoformat().replace("+00:00", "Z")
+
+
+def _parse_timestamp(value: object) -> datetime | None:
+ if not isinstance(value, str) or not value or len(value) > 64:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ return None
+ return parsed.astimezone(timezone.utc)
+
+
+def valid_target_version(value: object) -> str | None:
+ if not isinstance(value, str):
+ return None
+ target = value.strip()
+ if target != value or len(target) > 96 or not _TARGET_VERSION.fullmatch(target):
+ return None
+ return target
+
+
+def parse_desktop_update_request(payload: object) -> DesktopUpdateRequest | None:
+ if not isinstance(payload, dict) or set(payload) != {
+ "schema_version",
+ "request_id",
+ "target",
+ "state",
+ "created_at",
+ "expires_at",
+ }:
+ return None
+ if type(payload.get("schema_version")) is not int or payload["schema_version"] != UPDATE_REQUEST_SCHEMA_VERSION:
+ return None
+ request_id = payload.get("request_id")
+ try:
+ parsed_id = UUID(request_id) if isinstance(request_id, str) else None
+ except ValueError:
+ return None
+ if parsed_id is None or str(parsed_id) != request_id:
+ return None
+ target = valid_target_version(payload.get("target"))
+ state = payload.get("state")
+ created_at = _parse_timestamp(payload.get("created_at"))
+ expires_at = _parse_timestamp(payload.get("expires_at"))
+ if target is None or not isinstance(state, str) or state not in {"pending", "expired"}:
+ return None
+ if created_at is None or expires_at is None or expires_at <= created_at:
+ return None
+ return {
+ "schema_version": UPDATE_REQUEST_SCHEMA_VERSION,
+ "request_id": request_id,
+ "target": target,
+ "state": state,
+ "created_at": _utc_timestamp(created_at),
+ "expires_at": _utc_timestamp(expires_at),
+ }
+
+
+def read_desktop_update_request(path: Path | None = None) -> DesktopUpdateRequest | None:
+ target = path or desktop_update_request_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 request %s: %s", target, exc)
+ return None
+ request = parse_desktop_update_request(payload)
+ if request is None:
+ logger.debug("Ignoring invalid desktop update request %s", target)
+ return request
+
+
+def _write_request(request: DesktopUpdateRequest, path: Path) -> None:
+ write_atomic(
+ path,
+ json.dumps(request, ensure_ascii=True, sort_keys=True, separators=(",", ":")) + "\n",
+ )
+
+
+def _request_pending(request: DesktopUpdateRequest, now: datetime) -> bool:
+ expires_at = _parse_timestamp(request["expires_at"])
+ return (
+ request["state"] == "pending"
+ and expires_at is not None
+ and expires_at > now
+ )
+
+
+def _remote_in_flight(remote: RemoteDesktopUpdateStatus | None) -> bool:
+ return remote is not None and remote["phase"] not in _TERMINAL_PHASES
+
+
+def _remote_request_expired(
+ remote: RemoteDesktopUpdateStatus | None,
+ existing: DesktopUpdateRequest | None,
+ now: datetime,
+) -> bool:
+ if remote is None or remote["phase"] in _TERMINAL_PHASES:
+ return False
+ if existing is not None and existing["request_id"] == remote["request_id"]:
+ return not _request_pending(existing, now)
+ updated_at = _parse_timestamp(remote["updated_at"])
+ return updated_at is not None and updated_at + UPDATE_REQUEST_TTL <= now
+
+
+def create_or_reuse_desktop_update_request(
+ target: str,
+ *,
+ request_path: Path | None = None,
+ status_path: Path | None = None,
+ now: datetime | None = None,
+) -> RequestDecision:
+ """Create one request, or return the same live request for an idempotent retry."""
+
+ normalized_target = valid_target_version(target)
+ if normalized_target is None:
+ raise DesktopUpdateRequestError("no_update_available")
+ moment = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
+ path = request_path or desktop_update_request_path()
+ with _REQUEST_LOCK:
+ status = read_desktop_update_status(status_path)
+ remote = status["remote_request"] if status else None
+ existing = read_desktop_update_request(path)
+ remote_expired = _remote_request_expired(remote, existing, moment)
+ if _remote_in_flight(remote) and not remote_expired:
+ if remote["target"] != normalized_target:
+ raise DesktopUpdateRequestError("update_in_progress")
+ if existing is not None and existing["request_id"] == remote["request_id"]:
+ return RequestDecision(existing, reused=True, needs_nudge=False)
+ # The shell has already acknowledged this request. Its status is the
+ # idempotency record even if the short-lived nudge file disappeared.
+ return RequestDecision(
+ {
+ "schema_version": UPDATE_REQUEST_SCHEMA_VERSION,
+ "request_id": remote["request_id"],
+ "target": remote["target"],
+ "state": "pending",
+ "created_at": remote["updated_at"],
+ "expires_at": _utc_timestamp(moment + UPDATE_REQUEST_TTL),
+ },
+ reused=True,
+ needs_nudge=False,
+ )
+
+ terminal_request_id = (
+ remote["request_id"]
+ if remote is not None
+ and (remote["phase"] in _TERMINAL_PHASES or remote_expired)
+ else None
+ )
+ if (
+ existing is not None
+ and _request_pending(existing, moment)
+ and existing["request_id"] != terminal_request_id
+ ):
+ if existing["target"] != normalized_target:
+ raise DesktopUpdateRequestError("update_in_progress")
+ return RequestDecision(existing, reused=True, needs_nudge=True)
+
+ request: DesktopUpdateRequest = {
+ "schema_version": UPDATE_REQUEST_SCHEMA_VERSION,
+ "request_id": str(uuid4()),
+ "target": normalized_target,
+ "state": "pending",
+ "created_at": _utc_timestamp(moment),
+ "expires_at": _utc_timestamp(moment + UPDATE_REQUEST_TTL),
+ }
+ _write_request(request, path)
+ return RequestDecision(request, reused=False, needs_nudge=True)
+
+
+def expire_desktop_update_request(
+ request_id: str,
+ *,
+ path: Path | None = None,
+) -> bool:
+ """Expire only the still-pending matching request."""
+
+ target = path or desktop_update_request_path()
+ with _REQUEST_LOCK:
+ current = read_desktop_update_request(target)
+ if (
+ current is None
+ or current["request_id"] != request_id
+ or current["state"] != "pending"
+ ):
+ return False
+ expired: DesktopUpdateRequest = {**current, "state": "expired"}
+ _write_request(expired, target)
+ return True
+
+
+def acknowledged_remote_request(
+ request_id: str,
+ *,
+ path: Path | None = None,
+) -> tuple[DesktopUpdateStatus, RemoteDesktopUpdateStatus] | None:
+ status = read_desktop_update_status(path)
+ remote = status["remote_request"] if status else None
+ if (
+ status is None
+ or remote is None
+ or remote["request_id"] != request_id
+ or remote["phase"] not in _ACKNOWLEDGED_PHASES
+ ):
+ return None
+ return status, remote
diff --git a/vibe/desktop_update_status.py b/vibe/desktop_update_status.py
index b89193cdc..e7cd756dd 100644
--- a/vibe/desktop_update_status.py
+++ b/vibe/desktop_update_status.py
@@ -14,6 +14,7 @@ newer app never breaks an older Runtime.
from __future__ import annotations
+from datetime import datetime
import json
import logging
from pathlib import Path
@@ -30,6 +31,34 @@ UPDATE_STATUS_FILE = "update-status.json"
class DesktopUpdateStatus(TypedDict):
latest: str | None
has_update: bool
+ remote_install_allowed: bool
+ remote_request: "RemoteDesktopUpdateStatus | None"
+
+
+class RemoteDesktopUpdateStatus(TypedDict):
+ request_id: str
+ target: str
+ phase: str
+ progress: int | None
+ error_code: str | None
+ updated_at: str
+
+
+REMOTE_UPDATE_PHASES = frozenset(
+ {
+ "requested",
+ "acknowledged",
+ "awaiting_host",
+ "checking",
+ "downloading",
+ "installing",
+ "restarting",
+ "completed",
+ "failed",
+ "declined",
+ "expired",
+ }
+)
def desktop_update_status_path(**kwargs: Any) -> Path:
@@ -51,7 +80,71 @@ def parse_desktop_update_status(payload: object) -> DesktopUpdateStatus | None:
latest = (latest or "").strip() or None
if has_update and latest is None:
return None
- return {"latest": latest, "has_update": has_update}
+ remote_install_allowed = payload.get("remote_install_allowed", False)
+ if not isinstance(remote_install_allowed, bool):
+ remote_install_allowed = False
+ return {
+ "latest": latest,
+ "has_update": has_update,
+ "remote_install_allowed": remote_install_allowed,
+ "remote_request": _parse_remote_request(payload.get("remote_request")),
+ }
+
+
+def _parse_remote_request(payload: object) -> RemoteDesktopUpdateStatus | None:
+ if payload is None:
+ return None
+ if not isinstance(payload, dict):
+ return None
+ request_id = payload.get("request_id")
+ target = payload.get("target")
+ phase = payload.get("phase")
+ progress = payload.get("progress")
+ error_code = payload.get("error_code")
+ updated_at = payload.get("updated_at")
+ if (
+ not isinstance(request_id, str)
+ or not request_id.strip()
+ or len(request_id) > 128
+ or not isinstance(target, str)
+ or not target.strip()
+ or len(target) > 96
+ or not isinstance(phase, str)
+ or phase not in REMOTE_UPDATE_PHASES
+ or not (
+ progress is None
+ or (
+ isinstance(progress, int)
+ and not isinstance(progress, bool)
+ and 0 <= progress <= 100
+ )
+ )
+ or not (
+ error_code is None
+ or (
+ isinstance(error_code, str)
+ and bool(error_code.strip())
+ and len(error_code) <= 128
+ )
+ )
+ or not isinstance(updated_at, str)
+ or len(updated_at) > 64
+ ):
+ return None
+ try:
+ parsed_updated_at = datetime.fromisoformat(updated_at.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed_updated_at.tzinfo is None:
+ return None
+ return {
+ "request_id": request_id,
+ "target": target,
+ "phase": phase,
+ "progress": progress,
+ "error_code": error_code,
+ "updated_at": updated_at,
+ }
def read_desktop_update_status(path: Path | None = None) -> DesktopUpdateStatus | None:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 163b19f2d..659e22ed8 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7143,6 +7143,131 @@ def version():
return jsonify(api.get_version_info())
+_DESKTOP_UPDATE_ACK_TIMEOUT_SECONDS = 10.0
+_DESKTOP_UPDATE_ACK_POLL_SECONDS = 0.1
+
+
+def _upgrade_confirmation_response(counts: Any):
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "error": "confirmation_required",
+ "counts": counts.as_dict(),
+ }
+ ),
+ 409,
+ )
+
+
+async def _wait_for_desktop_update_ack(request_id: str):
+ from vibe.desktop_update_request import acknowledged_remote_request
+
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + _DESKTOP_UPDATE_ACK_TIMEOUT_SECONDS
+ while True:
+ acknowledged = acknowledged_remote_request(request_id)
+ if acknowledged is not None:
+ return acknowledged
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ return None
+ await asyncio.sleep(min(_DESKTOP_UPDATE_ACK_POLL_SECONDS, remaining))
+
+
[email protected]("/api/desktop/update/request", methods=["POST"])
+async def desktop_update_request():
+ from vibe import api
+ from vibe.desktop_update_request import (
+ DesktopUpdateRequestError,
+ create_or_reuse_desktop_update_request,
+ expire_desktop_update_request,
+ valid_target_version,
+ )
+ from vibe.sse_broker import broker
+ from vibe.upgrade import is_desktop_managed_runtime
+ from vibe.upgrade_interruptions import count_upgrade_interruptions
+
+ payload = request.json or {}
+ if not isinstance(payload, dict) or not set(payload).issubset(
+ {"target_version", "confirm_interrupt"}
+ ):
+ return jsonify({"ok": False, "error": "invalid_request"}), 422
+ target = valid_target_version(payload.get("target_version"))
+ confirm_interrupt = payload.get("confirm_interrupt", False)
+ if target is None or not isinstance(confirm_interrupt, bool):
+ return jsonify({"ok": False, "error": "invalid_request"}), 422
+ if not is_desktop_managed_runtime():
+ return jsonify({"ok": False, "error": "not_desktop_managed"}), 409
+
+ version = api.get_version_info()
+ if (
+ version.get("managed_by") != "desktop"
+ or version.get("has_update") is not True
+ or version.get("latest") != target
+ ):
+ return jsonify({"ok": False, "error": "no_update_available"}), 409
+
+ interruptions = await count_upgrade_interruptions()
+ if not confirm_interrupt and interruptions.requires_confirmation:
+ return _upgrade_confirmation_response(interruptions)
+
+ try:
+ decision = create_or_reuse_desktop_update_request(target)
+ except DesktopUpdateRequestError as exc:
+ return jsonify({"ok": False, "error": exc.code}), 409
+ if decision.needs_nudge:
+ broker.publish(
+ "desktop.update.requested",
+ {"request_id": decision.request["request_id"]},
+ )
+
+ acknowledged = await _wait_for_desktop_update_ack(
+ decision.request["request_id"]
+ )
+ if acknowledged is None:
+ expire_desktop_update_request(decision.request["request_id"])
+ return (
+ jsonify({"ok": False, "error": "desktop_shell_unavailable"}),
+ 503,
+ )
+ status, remote = acknowledged
+ if (
+ remote["phase"] == "failed"
+ and remote["error_code"] == "update_in_progress"
+ ):
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "error": "update_in_progress",
+ "request_id": remote["request_id"],
+ }
+ ),
+ 409,
+ )
+ if remote["phase"] == "expired":
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "error": "desktop_shell_unavailable",
+ "request_id": remote["request_id"],
+ }
+ ),
+ 503,
+ )
+ return jsonify(
+ {
+ "ok": True,
+ "request_id": remote["request_id"],
+ "delivery": (
+ "install" if status["remote_install_allowed"] else "prompt"
+ ),
+ }
+ )
+
+
# =============================================================================
# POST Endpoints
# =============================================================================
@@ -8520,10 +8645,23 @@ async def opencode_options():
@app.route("/api/upgrade", methods=["POST"])
-def upgrade():
+async def upgrade():
from vibe import api
+ from vibe.upgrade_interruptions import count_upgrade_interruptions
- result = api.do_upgrade()
+ payload = request.json or {}
+ if not isinstance(payload, dict):
+ return jsonify({"ok": False, "error": "invalid_request"}), 422
+ confirm_interrupt = payload.get("confirm_interrupt")
+ if "confirm_interrupt" in payload and not isinstance(confirm_interrupt, bool):
+ return jsonify({"ok": False, "error": "invalid_request"}), 422
+ # Missing preserves the released endpoint: old Workbenches continue without
+ # acquiring a new confirmation contract.
+ if confirm_interrupt is False:
+ interruptions = await count_upgrade_interruptions()
+ if interruptions.requires_confirmation:
+ return _upgrade_confirmation_response(interruptions)
+ result = await asyncio.to_thread(api.do_upgrade)
return jsonify(result)
diff --git a/vibe/upgrade_interruptions.py b/vibe/upgrade_interruptions.py
new file mode 100644
index 000000000..42ebf2774
--- /dev/null
+++ b/vibe/upgrade_interruptions.py
@@ -0,0 +1,98 @@
+"""Active work that a host upgrade may interrupt."""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class UpgradeInterruptions:
+ agents: int
+ watches: int
+ tasks: int
+ unknown: bool = False
+
+ @property
+ def total(self) -> int:
+ return self.agents + self.watches + self.tasks
+
+ @property
+ def requires_confirmation(self) -> bool:
+ return self.unknown or self.total > 0
+
+ def as_dict(self) -> dict[str, int | bool]:
+ return {
+ "agents": self.agents,
+ "watches": self.watches,
+ "tasks": self.tasks,
+ "total": self.total,
+ "unknown": self.unknown,
+ }
+
+
+def _count_harness_interruptions() -> tuple[int, int]:
+ """Count only active Harness rows on a worker thread."""
+
+ from storage.background import SQLiteBackgroundTaskStore
+
+ store = SQLiteBackgroundTaskStore(include_private_metadata=False)
+ try:
+ def active(run_type: str) -> int:
+ return sum(
+ store.count_runs(status=status, run_type=run_type)
+ for status in ("queued", "running")
+ )
+
+ return active("watch"), active("scheduled")
+ finally:
+ store.close()
+
+
+async def count_upgrade_interruptions() -> UpgradeInterruptions:
+ """Read independent Controller and Harness liveness sources.
+
+ A source that cannot answer sets ``unknown`` instead of being represented as
+ zero. Callers can still proceed after an explicit confirmation.
+ """
+
+ from vibe import internal_client
+
+ agents = watches = tasks = 0
+ unknown = False
+ try:
+ snapshot = await internal_client.list_running_agents()
+ body = snapshot.get("body") if isinstance(snapshot, dict) else None
+ rows = body.get("agents") if isinstance(body, dict) else None
+ if not isinstance(rows, list):
+ unknown = True
+ else:
+ agents = sum(
+ 1
+ for row in rows
+ if isinstance(row, dict) and row.get("state") == "active"
+ )
+ except (
+ internal_client.InternalServerUnavailable,
+ internal_client.InternalServerTimeout,
+ ):
+ unknown = True
+ except Exception:
+ logger.warning("Could not count active Agents before upgrade", exc_info=True)
+ unknown = True
+
+ try:
+ watches, tasks = await asyncio.to_thread(_count_harness_interruptions)
+ except Exception:
+ logger.warning("Could not count active Harness work before upgrade", exc_info=True)
+ unknown = True
+
+ return UpgradeInterruptions(
+ agents=agents,
+ watches=watches,
+ tasks=tasks,
+ unknown=unknown,
+ )