Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): updates you can trust — resumable signed downloads, an Update button, force updates, what's new
Salman Qureshif8047d11c779
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lockindex 8d9c76a2..0f6aa056 100644--- a/apps/desktop/src-tauri/Cargo.lock+++ b/apps/desktop/src-tauri/Cargo.lock@@ -2411,10 +2411,12 @@ dependencies = [name = "mercury-desktop"version = "0.1.0"dependencies = [+ "base64 0.22.1","dirs 6.0.0","flate2","keyring","log",+ "minisign-verify","objc2-app-kit","reqwest 0.12.28","serde",@@ -2435,6 +2437,7 @@ dependencies = ["tauri-plugin-store","tauri-plugin-updater","tauri-plugin-window-state",+ "tokio",][[package]]diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex f560d469..7cf778b3 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -39,6 +39,10 @@ tar = "0.4"serde = { version = "1", features = ["derive"] }serde_json = "1"dirs = "6"+# Updates: the signed manifest (same key as the update packages) and the resumable download.+minisign-verify = "0.3"+base64 = "0.22"+tokio = { version = "1", features = ["time"] }log = "0.4"[target.'cfg(target_os = "macos")'.dependencies]diff --git a/apps/desktop/src-tauri/src/commands/mod.rs b/apps/desktop/src-tauri/src/commands/mod.rsindex 2842f266..7c3551c4 100644--- a/apps/desktop/src-tauri/src/commands/mod.rs+++ b/apps/desktop/src-tauri/src/commands/mod.rs@@ -1,3 +1,4 @@pub mod installer;pub mod local;pub mod secrets;+pub mod updates;diff --git a/apps/desktop/src-tauri/src/commands/testdata/manifest.json b/apps/desktop/src-tauri/src/commands/testdata/manifest.jsonnew file mode 100644index 00000000..75032084--- /dev/null+++ b/apps/desktop/src-tauri/src/commands/testdata/manifest.json@@ -0,0 +1 @@+{"schema":1,"issuedAt":"2026-11-03T00:00:00Z"}\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/commands/testdata/manifest.json.sig b/apps/desktop/src-tauri/src/commands/testdata/manifest.json.signew file mode 100644index 00000000..f23138e0--- /dev/null+++ b/apps/desktop/src-tauri/src/commands/testdata/manifest.json.sig@@ -0,0 +1 @@+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUV2VUTlRLNTFvNitQZlJFUURSMTRXbVVHbmRzTURMMlFaSjZNci9iMlhLb0JkZW00aElaV3lNakYyd05lb2lYc1JSWUxEYVhwNEJOU2JxTHRFRHJCOENjV3k3TlJIQ2dZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjgzNTk2CWZpbGU6bWFuaWZlc3QuanNvbgpWZjJHVHRzQ1UvcU9xNjVTVE9IcU9KL1NZU2hianN5eG54L29zUVBQR3NkaFFiMFVQZDhGengyY0dOOXZtZENrQS92bllySktzNkp6dWRyaUVJZjBCQT09Cg==\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/commands/updates.rs b/apps/desktop/src-tauri/src/commands/updates.rsnew file mode 100644index 00000000..0e233d3d--- /dev/null+++ b/apps/desktop/src-tauri/src/commands/updates.rs@@ -0,0 +1,650 @@+//! Updates for Mercury Desktop itself, and the signed update manifest+//! (docs/updates.md).+//!+//! - `updates_manifest`: fetch `manifest.json` + `.sig`, verify the minisign+//! signature with the updater's public key (the one in tauri.conf.json:+//! one key signs packages and the manifest), refuse a manifest older than+//! one already seen (replay), cache it for six hours. Unverified → the UI+//! ignores everything that would force or announce.+//! - `desktop_update_check` / `_download` / `_install`: the Tauri updater+//! finds the release; the download is ours, because the plugin's starts+//! from zero every time. Ours resumes (HTTP Range + If-Range on the ETag),+//! retries with back-off, notices a stalled connection, keeps the bytes in+//! the cache folder across restarts, and only marks a package ready after+//! its signature checks out (a bad one is deleted so the next try is clean).+//! - A ready package installs when the user says so, or when they quit+//! (on by default, like most editors).++use serde::Serialize;+use serde_json::Value;+use std::{+ fs,+ io::Write,+ path::{Path, PathBuf},+ sync::{+ atomic::{AtomicBool, Ordering},+ Mutex,+ },+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},+};+use tauri::{AppHandle, Emitter, Manager, State};+use tauri_plugin_updater::{Update, UpdaterExt};++const USER_AGENT: &str = concat!("mercury-desktop/", env!("CARGO_PKG_VERSION"));+const MANIFEST_URLS: [&str; 2] = [+ "https://mercuryagent.sh/updates/manifest.json",+ "https://raw.githubusercontent.com/cosmicstack-labs/mercury-agent/main/website/static/updates/manifest.json",+];+const MANIFEST_TTL_MS: u64 = 6 * 60 * 60 * 1000;+const MAX_MANIFEST_BYTES: usize = 512 * 1024;+const MAX_PACKAGE_BYTES: u64 = 1024 * 1024 * 1024;+const ATTEMPTS: u32 = 5;+/// No byte for this long = the connection is dead; reconnect and resume.+const STALL: Duration = Duration::from_secs(30);++#[derive(Default)]+pub struct UpdaterState {+ update: Mutex<Option<Update>>,+ downloading: AtomicBool,+ install_on_quit: AtomicBool,+}++impl UpdaterState {+ pub fn new() -> Self {+ let s = Self::default();+ s.install_on_quit.store(true, Ordering::Relaxed);+ s+ }+}++fn now_ms() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)+}++fn http() -> Result<reqwest::Client, String> {+ reqwest::Client::builder()+ .user_agent(USER_AGENT)+ .connect_timeout(Duration::from_secs(20))+ .redirect(reqwest::redirect::Policy::limited(5))+ .build()+ .map_err(|e| e.to_string())+}++/* ── the manifest ─────────────────────────────────────────────── */++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ManifestResult {+ manifest: Option<Value>,+ verified: bool,+ checked_at: Option<u64>,+ error: Option<String>,+}++#[derive(serde::Serialize, serde::Deserialize, Default)]+#[serde(rename_all = "camelCase")]+struct ManifestCache {+ text: Option<String>,+ sig: Option<String>,+ checked_at: u64,+ /// The newest `issuedAt` ever accepted: an older manifest is a replay.+ highest_issued_at: Option<String>,+}++fn updates_data_dir(app: &AppHandle) -> Result<PathBuf, String> {+ let dir = app.path().app_data_dir().map_err(|e| e.to_string())?.join("updates");+ fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ Ok(dir)+}++fn read_cache(app: &AppHandle) -> ManifestCache {+ updates_data_dir(app)+ .ok()+ .and_then(|d| fs::read_to_string(d.join("manifest-cache.json")).ok())+ .and_then(|t| serde_json::from_str(&t).ok())+ .unwrap_or_default()+}++fn write_cache(app: &AppHandle, cache: &ManifestCache) {+ if let Ok(dir) = updates_data_dir(app) {+ if let Ok(text) = serde_json::to_string(cache) {+ let tmp = dir.join("manifest-cache.json.tmp");+ if fs::write(&tmp, text).is_ok() {+ let _ = fs::rename(tmp, dir.join("manifest-cache.json"));+ }+ }+ }+}++/// The updater's public key from tauri.conf.json (base64 of the minisign `.pub` text).+fn updater_pubkey(app: &AppHandle) -> Option<String> {+ app.config()+ .plugins+ .0+ .get("updater")+ .and_then(|u| u.get("pubkey"))+ .and_then(|k| k.as_str())+ .map(str::to_string)+ .filter(|k| !k.trim().is_empty())+}++fn b64_text(s: &str) -> Result<String, String> {+ use base64::Engine;+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(s.trim())+ .map_err(|e| format!("bad base64: {e}"))?;+ String::from_utf8(bytes).map_err(|_| "not text".to_string())+}++/// `sig` is what `tauri signer sign` writes: base64 of the `.minisig` text.+pub fn verify_minisign(pubkey_b64: &str, data: &[u8], sig_b64: &str) -> Result<(), String> {+ let pk = minisign_verify::PublicKey::decode(&b64_text(pubkey_b64)?).map_err(|e| format!("public key: {e}"))?;+ let sig = minisign_verify::Signature::decode(&b64_text(sig_b64)?).map_err(|e| format!("signature: {e}"))?;+ pk.verify(data, &sig, false).map_err(|e| format!("signature does not match: {e}"))+}++fn issued_at(text: &str) -> Option<String> {+ serde_json::from_str::<Value>(text).ok()?.get("issuedAt")?.as_str().map(str::to_string)+}++/// RFC 3339 timestamps in UTC ("…Z") compare as strings; anything else is treated as unknown.+fn older(a: &str, b: &str) -> bool {+ a.ends_with('Z') && b.ends_with('Z') && a < b+}++async fn fetch_limited(client: &reqwest::Client, url: &str) -> Result<String, String> {+ let res = client.get(url).timeout(Duration::from_secs(15)).send().await.map_err(|e| e.to_string())?;+ if !res.status().is_success() {+ return Err(format!("{url} answered {}", res.status()));+ }+ let bytes = res.bytes().await.map_err(|e| e.to_string())?;+ if bytes.len() > MAX_MANIFEST_BYTES {+ return Err("manifest too large".into());+ }+ String::from_utf8(bytes.to_vec()).map_err(|_| "manifest is not text".into())+}++fn result_from(pubkey: Option<&str>, text: Option<&str>, sig: Option<&str>, checked_at: u64, error: Option<String>) -> ManifestResult {+ let Some(text) = text else {+ return ManifestResult { manifest: None, verified: false, checked_at: (checked_at > 0).then_some(checked_at), error };+ };+ let verified = match (pubkey, sig) {+ (Some(pk), Some(sig)) => verify_minisign(pk, text.as_bytes(), sig).is_ok(),+ _ => false,+ };+ ManifestResult {+ manifest: serde_json::from_str(text).ok(),+ verified,+ checked_at: Some(checked_at),+ error,+ }+}++#[tauri::command]+pub async fn updates_manifest(app: AppHandle, force: bool) -> Result<ManifestResult, String> {+ let pubkey = updater_pubkey(&app);+ let mut cache = read_cache(&app);+ if !force && cache.text.is_some() && now_ms().saturating_sub(cache.checked_at) < MANIFEST_TTL_MS {+ return Ok(result_from(pubkey.as_deref(), cache.text.as_deref(), cache.sig.as_deref(), cache.checked_at, None));+ }++ let client = http()?;+ let mut last_error: Option<String> = None;+ for url in MANIFEST_URLS {+ let text = match fetch_limited(&client, url).await {+ Ok(t) => t,+ Err(e) => { last_error = Some(e); continue; }+ };+ let sig = match fetch_limited(&client, &format!("{url}.sig")).await {+ Ok(s) => s,+ Err(e) => { last_error = Some(format!("no signature: {e}")); continue; }+ };+ let Some(pk) = pubkey.as_deref() else {+ last_error = Some("this build has no update key".into());+ break;+ };+ if let Err(e) = verify_minisign(pk, text.as_bytes(), &sig) {+ // A mirror serving a bad file must not hide a good one.+ last_error = Some(e);+ continue;+ }+ let issued = issued_at(&text);+ if let (Some(new), Some(seen)) = (issued.as_deref(), cache.highest_issued_at.as_deref()) {+ if older(new, seen) {+ last_error = Some("the manifest served is older than one already seen".into());+ continue;+ }+ }+ cache.text = Some(text);+ cache.sig = Some(sig);+ cache.checked_at = now_ms();+ if issued.is_some() {+ cache.highest_issued_at = issued;+ }+ write_cache(&app, &cache);+ return Ok(result_from(pubkey.as_deref(), cache.text.as_deref(), cache.sig.as_deref(), cache.checked_at, None));+ }+ // Offline or refused: what we had (still verified on its own merits), and why.+ Ok(result_from(pubkey.as_deref(), cache.text.as_deref(), cache.sig.as_deref(), cache.checked_at, last_error))+}++/* ── the desktop's own update ─────────────────────────────────── */++#[derive(Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct UpdateInfo {+ version: String,+ current_version: String,+ date: Option<String>,+ notes: Option<String>,+ /// Downloaded and verified: installing is a restart away.+ ready: bool,+ /// Bytes already on disk from an earlier, interrupted download.+ partial_bytes: u64,+}++#[derive(Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct DownloadProgress {+ phase: &'static str,+ version: String,+ downloaded: u64,+ total: Option<u64>,+ percent: Option<f64>,+ bytes_per_sec: Option<f64>,+ attempt: u32,+ message: String,+}++#[derive(serde::Serialize, serde::Deserialize, Default)]+#[serde(rename_all = "camelCase")]+struct PartMeta {+ url: String,+ etag: Option<String>,+ total: Option<u64>,+}++fn cache_dir(app: &AppHandle) -> Result<PathBuf, String> {+ let dir = app.path().app_cache_dir().map_err(|e| e.to_string())?.join("updates");+ fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ Ok(dir)+}++/// Only characters a version has; never a path.+fn safe_version(v: &str) -> String {+ v.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')).collect()+}++fn part_path(dir: &Path, v: &str) -> PathBuf { dir.join(format!("{}.part", safe_version(v))) }+fn meta_path(dir: &Path, v: &str) -> PathBuf { dir.join(format!("{}.part.json", safe_version(v))) }+fn ready_path(dir: &Path, v: &str) -> PathBuf { dir.join(format!("{}.ready", safe_version(v))) }+fn pending_path(dir: &Path) -> PathBuf { dir.join("pending.json") }++/// Keep only the files of `keep` (or nothing).+fn clean_other_versions(dir: &Path, keep: Option<&str>) {+ let keep = keep.map(safe_version);+ let Ok(entries) = fs::read_dir(dir) else { return };+ for e in entries.flatten() {+ let name = e.file_name().to_string_lossy().to_string();+ if name == "pending.json" { continue; }+ let mine = keep.as_deref().is_some_and(|k| name == format!("{k}.part") || name == format!("{k}.part.json") || name == format!("{k}.ready"));+ if !mine { let _ = fs::remove_file(e.path()); }+ }+}++fn info_of(update: &Update, dir: &Path) -> UpdateInfo {+ UpdateInfo {+ version: update.version.clone(),+ current_version: update.current_version.clone(),+ date: update.date.map(|d| d.to_string()),+ notes: update.body.clone(),+ ready: ready_path(dir, &update.version).exists(),+ partial_bytes: fs::metadata(part_path(dir, &update.version)).map(|m| m.len()).unwrap_or(0),+ }+}++/// The update found last, or the one found before a restart (its manifest was kept).+fn current_update(app: &AppHandle, state: &UpdaterState) -> Option<Update> {+ if let Some(u) = state.update.lock().ok().and_then(|g| g.clone()) {+ return Some(u);+ }+ let dir = cache_dir(app).ok()?;+ let raw: Value = serde_json::from_str(&fs::read_to_string(pending_path(&dir)).ok()?).ok()?;+ let update = app.updater().ok()?.restore_update(raw).ok().flatten()?;+ if let Ok(mut g) = state.update.lock() { *g = Some(update.clone()); }+ Some(update)+}++#[tauri::command]+pub async fn desktop_update_check(app: AppHandle, state: State<'_, UpdaterState>) -> Result<Option<UpdateInfo>, String> {+ let dir = cache_dir(&app)?;+ let found = app+ .updater()+ .map_err(|e| e.to_string())?+ .check()+ .await+ .map_err(|e| e.to_string())?;+ match found {+ Some(update) => {+ let _ = fs::write(pending_path(&dir), serde_json::to_string(&update.raw_json).unwrap_or_default());+ clean_other_versions(&dir, Some(&update.version));+ let info = info_of(&update, &dir);+ if let Ok(mut g) = state.update.lock() { *g = Some(update); }+ Ok(Some(info))+ }+ None => {+ // Up to date (or the release was pulled): nothing to keep.+ let _ = fs::remove_file(pending_path(&dir));+ clean_other_versions(&dir, None);+ if let Ok(mut g) = state.update.lock() { *g = None; }+ Ok(None)+ }+ }+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DesktopUpdateStatus {+ current_version: String,+ pending: Option<UpdateInfo>,+ downloading: bool,+ install_on_quit: bool,+}++#[tauri::command]+pub fn desktop_update_status(app: AppHandle, state: State<'_, UpdaterState>) -> Result<DesktopUpdateStatus, String> {+ let dir = cache_dir(&app)?;+ let current = app.package_info().version.to_string();+ let pending = current_update(&app, &state).filter(|u| u.version != current).map(|u| info_of(&u, &dir));+ Ok(DesktopUpdateStatus {+ current_version: current,+ pending,+ downloading: state.downloading.load(Ordering::Relaxed),+ install_on_quit: state.install_on_quit.load(Ordering::Relaxed),+ })+}++#[tauri::command]+pub fn desktop_update_set_install_on_quit(state: State<'_, UpdaterState>, enabled: bool) {+ state.install_on_quit.store(enabled, Ordering::Relaxed);+}++struct Emitting<'a> {+ app: &'a AppHandle,+ version: String,+ attempt: u32,+}++impl Emitting<'_> {+ fn send(&self, phase: &'static str, downloaded: u64, total: Option<u64>, bps: Option<f64>, message: impl Into<String>) {+ let percent = total.filter(|t| *t > 0).map(|t| (downloaded as f64 / t as f64 * 100.0).min(100.0));+ let _ = self.app.emit(+ "desktop-update-progress",+ DownloadProgress { phase, version: self.version.clone(), downloaded, total, percent, bytes_per_sec: bps, attempt: self.attempt, message: message.into() },+ );+ }+}++enum Fail {+ /// Worth another try (network, 5xx, stall).+ Retry(String),+ /// Won't get better by retrying (404, too large, disk).+ Stop(String),+}++/// `Content-Range: bytes 100-999/1000` → 1000.+fn total_from_content_range(v: &str) -> Option<u64> {+ v.rsplit('/').next()?.trim().parse().ok()+}++/// One attempt: continue from what's on disk when the server allows it.+async fn fetch_once(client: &reqwest::Client, url: &str, dir: &Path, version: &str, em: &Emitting<'_>) -> Result<(), Fail> {+ let part = part_path(dir, version);+ let meta_file = meta_path(dir, version);+ let mut meta: PartMeta = fs::read_to_string(&meta_file).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();+ let mut have = fs::metadata(&part).map(|m| m.len()).unwrap_or(0);+ if meta.url != url {+ // Another URL (a re-published release): the old bytes aren't this file's.+ have = 0;+ let _ = fs::remove_file(&part);+ meta = PartMeta { url: url.to_string(), ..Default::default() };+ }+ if have > 0 && meta.total == Some(have) {+ return Ok(());+ }++ let mut req = client.get(url).header(reqwest::header::ACCEPT, "application/octet-stream");+ if have > 0 {+ req = req.header(reqwest::header::RANGE, format!("bytes={have}-"));+ // If the file changed since, the server sends all of it (200) instead of a mismatched tail.+ if let Some(etag) = meta.etag.as_deref() {+ req = req.header(reqwest::header::IF_RANGE, etag);+ }+ }+ let mut res = req.send().await.map_err(|e| Fail::Retry(format!("couldn't connect: {e}")))?;+ let status = res.status();+ let append = match status.as_u16() {+ 206 => true,+ 200 => false,+ 416 if have > 0 => {+ // We already have every byte (or the file shrank): start over cleanly next time.+ let _ = fs::remove_file(&part);+ let _ = fs::remove_file(&meta_file);+ return Err(Fail::Retry("the download restarts from the beginning".into()));+ }+ 408 | 429 | 500..=599 => return Err(Fail::Retry(format!("the server answered {status}"))),+ _ => return Err(Fail::Stop(format!("the server answered {status}"))),+ };+ let headers = res.headers().clone();+ let etag = headers.get(reqwest::header::ETAG).and_then(|v| v.to_str().ok()).map(str::to_string);+ let total = if append {+ headers.get(reqwest::header::CONTENT_RANGE).and_then(|v| v.to_str().ok()).and_then(total_from_content_range)+ } else {+ res.content_length()+ };+ if total.is_some_and(|t| t > MAX_PACKAGE_BYTES) {+ return Err(Fail::Stop("the update is unexpectedly large".into()));+ }+ meta.etag = etag.or(meta.etag);+ meta.total = total.or(meta.total);+ let _ = fs::write(&meta_file, serde_json::to_string(&meta).unwrap_or_default());++ let mut file = fs::OpenOptions::new()+ .create(true)+ .write(true)+ .append(append)+ .truncate(!append)+ .open(&part)+ .map_err(|e| Fail::Stop(format!("can't write the download: {e}")))?;+ let mut done = if append { have } else { 0 };+ let started = Instant::now();+ let start_bytes = done;+ let mut last_emit = Instant::now() - Duration::from_secs(1);+ loop {+ let chunk = match tokio::time::timeout(STALL, res.chunk()).await {+ Err(_) => return Err(Fail::Retry("the connection stalled".into())),+ Ok(Err(e)) => return Err(Fail::Retry(format!("the connection dropped: {e}"))),+ Ok(Ok(None)) => break,+ Ok(Ok(Some(c))) => c,+ };+ file.write_all(&chunk).map_err(|e| Fail::Stop(format!("can't write the download (disk full?): {e}")))?;+ done += chunk.len() as u64;+ if done > MAX_PACKAGE_BYTES {+ return Err(Fail::Stop("the update is unexpectedly large".into()));+ }+ if last_emit.elapsed() >= Duration::from_millis(250) {+ last_emit = Instant::now();+ let secs = started.elapsed().as_secs_f64();+ let bps = (secs > 0.5).then(|| (done - start_bytes) as f64 / secs);+ em.send("downloading", done, meta.total, bps, "Downloading");+ }+ }+ file.flush().map_err(|e| Fail::Stop(e.to_string()))?;+ if let Some(t) = meta.total {+ if done < t {+ return Err(Fail::Retry("the download ended early".into()));+ }+ }+ meta.total = Some(done);+ let _ = fs::write(&meta_file, serde_json::to_string(&meta).unwrap_or_default());+ Ok(())+}++struct Busy<'a>(&'a AtomicBool);+impl Drop for Busy<'_> {+ fn drop(&mut self) { self.0.store(false, Ordering::Relaxed); }+}++#[tauri::command]+pub async fn desktop_update_download(app: AppHandle, state: State<'_, UpdaterState>) -> Result<UpdateInfo, String> {+ let update = current_update(&app, &state).ok_or("No update to download. Check for updates first.")?;+ let dir = cache_dir(&app)?;+ if ready_path(&dir, &update.version).exists() {+ return Ok(info_of(&update, &dir));+ }+ if state.downloading.swap(true, Ordering::Relaxed) {+ return Err("Already downloading.".into());+ }+ let _busy = Busy(&state.downloading);+ let client = http()?;+ let url = update.download_url.to_string();+ let mut em = Emitting { app: &app, version: update.version.clone(), attempt: 1 };+ em.send("downloading", fs::metadata(part_path(&dir, &update.version)).map(|m| m.len()).unwrap_or(0), None, None, "Starting the download");++ let mut last = String::new();+ let mut ok = false;+ for attempt in 1..=ATTEMPTS {+ em.attempt = attempt;+ match fetch_once(&client, &url, &dir, &update.version, &em).await {+ Ok(()) => { ok = true; break; }+ Err(Fail::Stop(e)) => { last = e; break; }+ Err(Fail::Retry(e)) => {+ last = e;+ if attempt == ATTEMPTS { break; }+ let wait = Duration::from_secs((2u64 << attempt).min(30));+ let have = fs::metadata(part_path(&dir, &update.version)).map(|m| m.len()).unwrap_or(0);+ em.send("retrying", have, None, None, format!("{last}. Trying again in {} s (attempt {} of {ATTEMPTS})", wait.as_secs(), attempt + 1));+ tokio::time::sleep(wait).await;+ }+ }+ }+ if !ok {+ let have = fs::metadata(part_path(&dir, &update.version)).map(|m| m.len()).unwrap_or(0);+ em.send("error", have, None, None, last.clone());+ return Err(if have > 0 { format!("Download paused: {last}. It continues from here next time.") } else { format!("Download failed: {last}.") });+ }++ em.send("verifying", 0, None, None, "Checking the signature");+ let part = part_path(&dir, &update.version);+ let bytes = fs::read(&part).map_err(|e| e.to_string())?;+ if let Err(e) = update.verify(&bytes) {+ // Never keep (or resume) bytes that don't match: the next try starts clean.+ let _ = fs::remove_file(&part);+ let _ = fs::remove_file(meta_path(&dir, &update.version));+ let msg = format!("The download didn't match its signature and was deleted ({e}). Try again.");+ em.send("error", 0, None, None, msg.clone());+ return Err(msg);+ }+ fs::rename(&part, ready_path(&dir, &update.version)).map_err(|e| e.to_string())?;+ let _ = fs::remove_file(meta_path(&dir, &update.version));+ em.send("ready", bytes.len() as u64, Some(bytes.len() as u64), None, "Ready to install");+ Ok(info_of(&update, &dir))+}++fn install_ready(app: &AppHandle, state: &UpdaterState, restart_after: bool) -> Result<(), String> {+ let update = current_update(app, state).ok_or("No update is ready.")?;+ let dir = cache_dir(app)?;+ let ready = ready_path(&dir, &update.version);+ let bytes = fs::read(&ready).map_err(|_| "The update isn't downloaded yet.".to_string())?;+ // `install` verifies again: a package changed on disk is refused.+ let update = update.restart_after_install(restart_after);+ if let Err(e) = update.install(&bytes) {+ let _ = fs::remove_file(&ready);+ return Err(format!("Installing failed: {e}. The package was removed; it downloads again next time."));+ }+ let _ = fs::remove_file(&ready);+ let _ = fs::remove_file(pending_path(&dir));+ Ok(())+}++#[tauri::command]+pub fn desktop_update_install(app: AppHandle, state: State<'_, UpdaterState>) -> Result<(), String> {+ install_ready(&app, &state, true)?;+ // Windows has exited into the installer by now; macOS and Linux relaunch.+ app.restart();+}++/// Quitting with a downloaded update installs it, unless turned off.+pub fn install_on_quit(app: &AppHandle) {+ let Some(state) = app.try_state::<UpdaterState>() else { return };+ if !state.install_on_quit.load(Ordering::Relaxed) || state.downloading.load(Ordering::Relaxed) {+ return;+ }+ let Some(update) = current_update(app, &state) else { return };+ let Ok(dir) = cache_dir(app) else { return };+ if !ready_path(&dir, &update.version).exists() {+ return;+ }+ if let Err(e) = install_ready(app, &state, false) {+ log::warn!("install on quit: {e}");+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn content_range_total() {+ assert_eq!(total_from_content_range("bytes 100-999/1000"), Some(1000));+ assert_eq!(total_from_content_range("bytes 0-0/*"), None);+ }++ #[test]+ fn versions_never_become_paths() {+ assert_eq!(safe_version("../../etc/passwd"), "....etcpasswd");+ assert_eq!(safe_version("0.2.0-beta.1"), "0.2.0-beta.1");+ }++ #[test]+ fn replay_order() {+ assert!(older("2026-11-01T00:00:00Z", "2026-11-03T00:00:00Z"));+ assert!(!older("2026-11-03T00:00:00Z", "2026-11-03T00:00:00Z"));+ assert!(!older("garbage", "2026-11-03T00:00:00Z"));+ }++ #[test]+ fn cleans_other_versions_only() {+ let dir = std::env::temp_dir().join(format!("mercury-upd-test-{}", now_ms()));+ fs::create_dir_all(&dir).unwrap();+ for f in ["0.2.0.part", "0.2.0.part.json", "0.1.9.ready", "pending.json"] {+ fs::write(dir.join(f), b"x").unwrap();+ }+ clean_other_versions(&dir, Some("0.2.0"));+ assert!(dir.join("0.2.0.part").exists());+ assert!(dir.join("0.2.0.part.json").exists());+ assert!(!dir.join("0.1.9.ready").exists());+ assert!(dir.join("pending.json").exists());+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn rejects_a_bad_signature() {+ let conf: Value = serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap();+ let key = conf["plugins"]["updater"]["pubkey"].as_str().unwrap();+ assert!(verify_minisign(key, b"hello", "bm90IGEgc2lnbmF0dXJl").is_err());+ }++ #[test]+ fn verifies_a_manifest_signed_with_the_update_key() {+ let conf: Value = serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap();+ let key = conf["plugins"]["updater"]["pubkey"].as_str().unwrap();+ let data = include_bytes!("testdata/manifest.json");+ let sig = include_str!("testdata/manifest.json.sig");+ assert!(verify_minisign(key, data, sig).is_ok());+ // One byte changed: refused.+ let mut tampered = data.to_vec();+ tampered[2] ^= 1;+ assert!(verify_minisign(key, &tampered, sig).is_err());+ }+}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex b5939141..19283bbb 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -36,6 +36,7 @@ pub fn run() {.plugin(tauri_plugin_os::init()).plugin(tauri_plugin_process::init()).plugin(tauri_plugin_dialog::init())+ .manage(commands::updates::UpdaterState::new()).invoke_handler(tauri::generate_handler![commands::local::detect_local_runtime,commands::local::read_attach_token,@@ -45,6 +46,12 @@ pub fn run() {commands::secrets::secret_get,commands::secrets::secret_set,commands::secrets::secret_delete,+ commands::updates::updates_manifest,+ commands::updates::desktop_update_check,+ commands::updates::desktop_update_status,+ commands::updates::desktop_update_download,+ commands::updates::desktop_update_install,+ commands::updates::desktop_update_set_install_on_quit,notch::notch_show,notch::notch_hide,])@@ -79,6 +86,10 @@ pub fn run() {if let tauri::RunEvent::Reopen { .. } = event {show_main(app);}+ // Quitting with a downloaded update installs it (Settings → About can turn this off).+ if let tauri::RunEvent::Exit = event {+ commands::updates::install_on_quit(app);+ }let _ = (app, &event);});}diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 26512410..88e60915 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -96,7 +96,7 @@"endpoints": ["https://mercuryagent.sh/desktop/latest.json"],- "pubkey": "",+ "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEVCNjg5RDJCNTMzMzc5RDYKUldUV2VUTlRLNTFvNjFKY2NMR2RRQXVjcXRIbVNiN2tYNkNQSUprMWJVM0NjeHRmL045Q3RUSDYK","windows": {"installMode": "passive"}diff --git a/apps/desktop/src/app/App.tsx b/apps/desktop/src/app/App.tsxindex 27dad6ee..dccb83a2 100644--- a/apps/desktop/src/app/App.tsx+++ b/apps/desktop/src/app/App.tsx@@ -11,6 +11,7 @@ import { desktop } from "~/shell/tauri";import { updateLocalRuntime } from "~/shell/updateLocal";import { configureApi } from "~/api/client";import { installApprovalHandler } from "~/components/OwnerApprovals";+import { UpdateLayer } from "~/updates/UpdateLayer";// A remote Mercury asks its owner before some actions: wait for the answer, then carry on.installApprovalHandler();@@ -26,6 +27,8 @@ export function App() {return (<TooltipProvider><Root />+ {/* Updates work on every screen: a required one shows over everything. */}+ <UpdateLayer /></TooltipProvider>);}diff --git a/apps/desktop/src/app/notify/store.ts b/apps/desktop/src/app/notify/store.tsindex 2c8ebad5..ec504046 100644--- a/apps/desktop/src/app/notify/store.ts+++ b/apps/desktop/src/app/notify/store.ts@@ -41,10 +41,12 @@ export interface CustomSound { name: string; url: string }export interface Alert {id: string;- kind: "needs" | "done" | "failed" | "ask";+ kind: "needs" | "done" | "failed" | "ask" | "update";title: string;body: string;sessionId?: string;+ /** One button (updates: "What's new", a message's link). */+ action?: { label: string; run: () => void };}interface NotifyState {diff --git a/apps/desktop/src/components/Alerts.tsx b/apps/desktop/src/components/Alerts.tsxindex 31f08f54..4ddcd4ac 100644--- a/apps/desktop/src/components/Alerts.tsx+++ b/apps/desktop/src/components/Alerts.tsx@@ -1,4 +1,4 @@-import { AlertTriangle, BellRing, CheckCircle2, Hand, X } from "lucide-react";+import { AlertTriangle, BellRing, CheckCircle2, Hand, Sparkles, X } from "lucide-react";import { useEffect } from "react";import { askPermission, openFromAlert, sendTest } from "~/app/notify/notify";import { useNotify, type Alert } from "~/app/notify/store";@@ -10,7 +10,7 @@ import { cx } from "~/lib/cx";* "needs you" alert stays until handled; the rest fade after a while.*/-const STAY_MS: Record<Alert["kind"], number | null> = { needs: null, ask: null, done: 9000, failed: 14000 };+const STAY_MS: Record<Alert["kind"], number | null> = { needs: null, ask: null, done: 9000, failed: 14000, update: 20000 };export function Alerts() {const alerts = useNotify((s) => s.alerts);@@ -32,7 +32,7 @@ function AlertCard({ alert: a }: { alert: Alert }) {return () => window.clearTimeout(t);}, [a.id, a.kind, dismiss]);- const Icon = a.kind === "needs" ? Hand : a.kind === "failed" ? AlertTriangle : a.kind === "ask" ? BellRing : CheckCircle2;+ const Icon = a.kind === "needs" ? Hand : a.kind === "failed" ? AlertTriangle : a.kind === "ask" ? BellRing : a.kind === "update" ? Sparkles : CheckCircle2;const tone = a.kind === "needs" ? "text-amber" : a.kind === "failed" ? "text-red" : "text-accent";return (<div role={a.kind === "needs" ? "alert" : "status"} className="pointer-events-auto flex animate-fade-in gap-3 rounded-xl border border-line bg-surface/95 p-3 shadow-xl backdrop-blur">@@ -46,6 +46,9 @@ function AlertCard({ alert: a }: { alert: Alert }) {{a.kind === "needs" ? "Answer" : "Open"}</button>)}+ {a.action && (+ <button onClick={() => { dismiss(a.id); a.action!.run(); }} className="rounded-md bg-ink/[0.07] px-2.5 py-1 text-xs font-medium text-ink hover:bg-ink/[0.12]">{a.action.label}</button>+ )}{a.kind === "ask" && (<><button onClick={() => { dismiss(a.id); setPrefs({ system: true }); void askPermission().then(() => sendTest()); }} className="rounded-md bg-accent px-2.5 py-1 text-xs font-medium text-on-accent hover:opacity-90">Turn on</button>diff --git a/apps/desktop/src/layout/EnvironmentBar.tsx b/apps/desktop/src/layout/EnvironmentBar.tsxindex a30eb921..735988f6 100644--- a/apps/desktop/src/layout/EnvironmentBar.tsx+++ b/apps/desktop/src/layout/EnvironmentBar.tsx@@ -6,6 +6,7 @@ import { usePulse } from "~/app/pulse";import { useRuntimeState, useUi } from "~/app/store";import { useConnections, type Connection } from "~/shell/connections";import { StateOrb } from "~/components/indicators/StateOrb";+import { UpdateButton } from "~/updates/UpdatesPanel";/*** Where am I? The strip across the top of the window answers it at a@@ -62,6 +63,8 @@ export function EnvironmentBar({ connection, health }: { connection: Connection;<div className="flex-1" data-tauri-drag-region />+ <UpdateButton />+<span className="font-mono text-ink4" title={`Runtime ${health.version} · API v${health.apiVersion ?? "?"} · pid ${health.pid}`}>Mercury {health.version || "?"} · API v{health.apiVersion ?? "?"}</span>diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsxindex fa309224..7929f4e3 100644--- a/apps/desktop/src/layout/Workspace.tsx+++ b/apps/desktop/src/layout/Workspace.tsx@@ -20,6 +20,7 @@ import { BrainView } from "~/views/brain/BrainView";import { ArtifactsView } from "~/views/artifacts/ArtifactsView";import { ErrorBoundary } from "~/components/ErrorBoundary";import { CloudBanner } from "~/views/settings/Cloud";+import { UpdateBanner } from "~/updates/UpdateLayer";import { CallLayer } from "~/views/call/Call";import { useNotifications } from "~/app/notify/notify";import { Alerts } from "~/components/Alerts";@@ -53,6 +54,7 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti<div className="flex h-full w-full flex-col overflow-hidden bg-bg"><EnvironmentBar connection={connection} health={health} /><CloudBanner supported={!!health.features?.includes("cloud.signin")} />+ <UpdateBanner /><div className="flex min-h-0 flex-1"><Rail connectionName={connection.name} /><main className="relative flex min-w-0 flex-1 flex-col">diff --git a/apps/desktop/src/shell/useRuntime.ts b/apps/desktop/src/shell/useRuntime.tsindex 2b7c9b8f..b2d2b964 100644--- a/apps/desktop/src/shell/useRuntime.ts+++ b/apps/desktop/src/shell/useRuntime.ts@@ -74,7 +74,10 @@ export function useRuntime(connection: Connection, onUnauthorized: () => void):}void bringUp();- return () => { cancelled = true; if (timer) clearTimeout(timer); };+ // A server update finished on this connection: reconnect onto the new version.+ const onReconnect = (e: Event) => { if ((e as CustomEvent<{ connectionId: string }>).detail?.connectionId === connection.id) retry(); };+ window.addEventListener("mercury:reconnect", onReconnect);+ return () => { cancelled = true; if (timer) clearTimeout(timer); window.removeEventListener("mercury:reconnect", onReconnect); };}, [connection, attempt, retry]);return { status, retry };diff --git a/apps/desktop/src/updates/ForceUpdate.tsx b/apps/desktop/src/updates/ForceUpdate.tsxnew file mode 100644index 00000000..c30e7921--- /dev/null+++ b/apps/desktop/src/updates/ForceUpdate.tsx@@ -0,0 +1,103 @@+import { ShieldAlert } from "lucide-react";+import { useEffect, useState } from "react";+import { Button } from "~/components/ui/Button";+import { Markdown } from "~/components/Markdown";+import { cx } from "~/lib/cx";+import { desktop as native, isTauri } from "~/shell/tauri";+import type { ForceState } from "./selectors";+import { useUpdates } from "./store";+import { DesktopRow, RELEASES_URL, ServerRow } from "./UpdatesPanel";++/**+ * A required update (security or compatibility): a full screen that Esc+ * and clicks outside don't close. The way out is deliberate: "Continue+ * without updating" asks you to tick every risk first, and holds until the+ * app restarts or for 24 hours. Meanwhile the top-right button stays red.+ * The window can still be minimised.+ */+const RISKS = [+ "I understand this version has a known problem that the update fixes.",+ "Mercury may stop working with my servers or some features until I update.",+ "I'm responsible for anything exposed while I stay on this version.",+ "I'll update as soon as I can.",+];++export function ForceUpdate({ force }: { force: ForceState }) {+ const acknowledge = useUpdates((s) => s.acknowledge);+ const [skipping, setSkipping] = useState(false);+ const [ticks, setTicks] = useState<boolean[]>(RISKS.map(() => false));+ const item = force.item;+ const conn = item.connection;+ const security = force.required.severity === "security";+ const remote = conn?.kind === "remote";+ const serverInfo = useUpdates((s) => (conn ? s.servers[conn.id]?.info : null));++ // Swallow Escape so nothing underneath closes or acts.+ useEffect(() => {+ const key = (e: KeyboardEvent) => { if (e.key === "Escape") { e.stopPropagation(); e.preventDefault(); } };+ window.addEventListener("keydown", key, true);+ return () => window.removeEventListener("keydown", key, true);+ }, []);++ const what = force.kind === "desktop" ? "Mercury Desktop" : `Mercury on ${item.name}`;+ const notes = item.release?.notes;++ return (+ <div className="fixed inset-0 z-[80] flex items-center justify-center bg-bg/95 p-6 backdrop-blur-sm" role="alertdialog" aria-modal="true" aria-labelledby="force-title">+ <div className="flex max-h-full w-[min(560px,100%)] flex-col overflow-hidden rounded-2xl border border-line bg-surface shadow-2xl" data-tauri-drag-region>+ <div className="flex items-start gap-3 border-b border-line px-6 py-5">+ <span className={cx("flex h-10 w-10 shrink-0 items-center justify-center rounded-xl", security ? "bg-red/10 text-red" : "bg-amber/15 text-amber")}><ShieldAlert size={20} /></span>+ <div className="min-w-0">+ <h2 id="force-title" className="text-md font-semibold text-ink">{security ? `${what} needs a security update` : `${what} needs an update`}</h2>+ <p className="mt-1 text-sm text-ink2">+ {force.required.reason || (security ? "This version has a security problem that's fixed in the update." : "This version is no longer supported.")}+ {" "}Version {item.current || "?"} is below {force.required.version}, the lowest still supported.+ </p>+ </div>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto">+ {notes && (+ <div className="border-b border-line px-6 py-4">+ <div className="mb-1 text-2xs font-medium uppercase tracking-wider text-ink4">What's new in {item.next ?? item.release?.version}</div>+ <div className="max-h-56 overflow-y-auto text-sm" data-selectable><Markdown text={notes} /></div>+ </div>+ )}+ {/* The same row as the panel: progress, retry, rollback, approval. */}+ {force.kind === "desktop" ? <DesktopRow item={item} compact /> : <ServerRow item={item} compact />}+ {force.kind === "server" && remote && serverInfo && serverInfo.canSelfUpdate && (+ <p className="px-6 pb-3 text-xs text-ink3">Updating a remote Mercury needs its owner's approval: they get a code on their messaging app or that computer.</p>+ )}+ {force.kind === "server" && remote && !serverInfo?.canSelfUpdate && (+ <p className="px-6 pb-3 text-xs text-ink3">Ask the owner of {item.name} to run <code className="font-mono">mercury upgrade</code> on that computer.</p>+ )}+ {force.kind === "desktop" && !isTauri && <p className="px-6 pb-3 text-xs text-ink3">Download the new version from <button className="text-accent hover:underline" onClick={() => void native.openExternal(RELEASES_URL)}>the releases page</button>.</p>}++ {skipping && (+ <div className="border-t border-line bg-ink/[0.02] px-6 py-4">+ <p className="text-sm font-medium text-ink">Continue without updating?</p>+ <p className="mt-0.5 text-xs text-ink3">Tick each one to continue. This holds until Mercury Desktop restarts, or for 24 hours.</p>+ <div className="mt-3 flex flex-col gap-2">+ {RISKS.map((r, i) => (+ <label key={r} className="flex cursor-pointer items-start gap-2.5 text-sm text-ink2">+ <input type="checkbox" className="mt-0.5 h-4 w-4 shrink-0 accent-[rgb(var(--red))]" checked={ticks[i]} onChange={(e) => setTicks(ticks.map((t, j) => (j === i ? e.target.checked : t)))} />+ {r}+ </label>+ ))}+ </div>+ </div>+ )}+ </div>++ <div className="flex items-center justify-between gap-3 border-t border-line px-6 py-3">+ {!skipping+ ? <button className="text-xs text-ink4 hover:text-ink3 hover:underline" onClick={() => setSkipping(true)}>Continue without updating</button>+ : <button className="text-xs text-ink4 hover:text-ink3 hover:underline" onClick={() => { setSkipping(false); setTicks(RISKS.map(() => false)); }}>Back</button>}+ {skipping && (+ <Button size="sm" variant="danger" disabled={!ticks.every(Boolean)} onClick={() => acknowledge(force.key)}>Continue anyway</Button>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/updates/UpdateLayer.tsx b/apps/desktop/src/updates/UpdateLayer.tsxnew file mode 100644index 00000000..0778e8e9--- /dev/null+++ b/apps/desktop/src/updates/UpdateLayer.tsx@@ -0,0 +1,80 @@+import { Megaphone, TriangleAlert, X } from "lucide-react";+import { useEffect } from "react";+import { Dialog } from "~/components/ui/Dialog";+import { Markdown } from "~/components/Markdown";+import { cx } from "~/lib/cx";+import { desktop as native } from "~/shell/tauri";+import { useConnections } from "~/shell/connections";+import { ForceUpdate } from "./ForceUpdate";+import { canDismiss } from "./logic";+import { checkAll, checkServer, initUpdates, useUpdates } from "./store";+import { RELEASES_URL } from "./UpdatesPanel";+import { useUpdateView } from "./useUpdateView";++const SIX_HOURS = 6 * 3_600_000;++/**+ * Mounted once at the root, whatever screen is up: checks on start, every+ * six hours and when the window comes back after six hours; shows a+ * required update over everything, and the "What's new" notes.+ */+export function UpdateLayer() {+ const { force } = useUpdateView();+ const connectionsLoaded = useConnections((s) => s.loaded);+ const activeId = useConnections((s) => s.activeId);++ useEffect(() => {+ if (!connectionsLoaded) return;+ let stop = false;+ void initUpdates().then(() => { if (!stop) void checkAll(); });+ const t = setInterval(() => void checkAll(), SIX_HOURS);+ const onFocus = () => void checkAll(); // throttled inside: only after six hours+ window.addEventListener("focus", onFocus);+ return () => { stop = true; clearInterval(t); window.removeEventListener("focus", onFocus); };+ }, [connectionsLoaded]);++ // A newly chosen connection is asked at once (it may need an update the others don't).+ useEffect(() => {+ const c = useConnections.getState().connections.find((x) => x.id === activeId);+ if (c && useUpdates.getState().loaded) void checkServer(c);+ }, [activeId]);++ return (+ <>+ {force && <ForceUpdate force={force} />}+ <WhatsNewDialog />+ </>+ );+}++function WhatsNewDialog() {+ const w = useUpdates((s) => s.whatsNew);+ const show = useUpdates((s) => s.showWhatsNew);+ return (+ <Dialog open={!!w} onOpenChange={(o) => { if (!o) show(null); }} title={w?.title ?? ""} description="What's new" width={560}>+ {w?.notes+ ? <div className="max-h-[60vh] overflow-y-auto text-sm" data-selectable><Markdown text={w.notes} /></div>+ : <p className="text-sm text-ink3">The release notes for {w?.version} are on the releases page.</p>}+ <div className="mt-4 flex justify-end">+ <button className="text-xs text-accent hover:underline" onClick={() => void native.openExternal(w?.notesUrl || RELEASES_URL)}>Full release notes</button>+ </div>+ </Dialog>+ );+}++/** Warnings and critical notices from the manifest, under the top bar. */+export function UpdateBanner() {+ const { banners } = useUpdateView();+ const dismiss = useUpdates((s) => s.dismissMessage);+ const m = banners[0];+ if (!m) return null;+ const critical = m.level === "critical";+ return (+ <div className={cx("flex items-center gap-3 border-b px-4 py-1.5 text-xs text-ink2", critical ? "border-red/30 bg-red/[0.07]" : "border-amber/30 bg-amber/[0.08]")} role={critical ? "alert" : "status"}>+ {critical ? <TriangleAlert size={13} className="shrink-0 text-red" /> : <Megaphone size={13} className="shrink-0 text-amber" />}+ <span className="min-w-0 flex-1 truncate"><span className="font-medium text-ink">{m.title}</span>{m.body ? ` · ${m.body}` : ""}</span>+ {m.link && <button className="shrink-0 text-accent hover:underline" onClick={() => void native.openExternal(m.link!.url)}>{m.link.label || "Read more"}</button>}+ {canDismiss(m) && <button onClick={() => dismiss(m.id)} className="text-ink4 hover:text-ink" aria-label="Dismiss"><X size={13} /></button>}+ </div>+ );+}diff --git a/apps/desktop/src/updates/UpdatesPanel.tsx b/apps/desktop/src/updates/UpdatesPanel.tsxnew file mode 100644index 00000000..50aa5b1a--- /dev/null+++ b/apps/desktop/src/updates/UpdatesPanel.tsx@@ -0,0 +1,316 @@+import { AlertTriangle, ArrowUpCircle, CheckCircle2, ChevronDown, ChevronRight, KeyRound, Laptop, RotateCcw, Server, ShieldAlert, X } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { Button } from "~/components/ui/Button";+import { Markdown } from "~/components/Markdown";+import { cx } from "~/lib/cx";+import { useUi } from "~/app/store";+import { useRuntimeState } from "~/app/store";+import { desktop as native } from "~/shell/tauri";+import { formatBytes, MAX_FAILURES, timeLeft, type Urgency } from "./logic";+import type { UpdateItem } from "./selectors";+import { busyOn, checkAll, clearServerAction, desktopKey, downloadDesktop, installDesktop, stopWaiting, updateServer, useUpdates } from "./store";+import type { ManifestMessage, UpdateJob } from "./types";+import { useUpdateView } from "./useUpdateView";++export const RELEASES_URL = "https://github.com/cosmicstack-labs/mercury-agent/releases";++const TONE: Record<Urgency, string> = {+ low: "text-ink2 bg-ink/[0.06] hover:bg-ink/[0.1]",+ elevated: "text-accent bg-accent/10 hover:bg-accent/15",+ high: "text-amber bg-amber/15 hover:bg-amber/20",+ critical: "text-red bg-red/10 hover:bg-red/15",+};++/**+ * Top right, like Chrome's: there only when something can be updated+ * (this app or any server it connects to), louder the longer it waits,+ * red and permanent when an update is required. Click for the panel.+ */+export function UpdateButton() {+ const { button, items } = useUpdateView();+ const open = useUpdates((s) => s.panelOpen);+ const setPanel = useUpdates((s) => s.setPanel);+ if (!button) return null;+ return (+ <>+ <button+ data-no-drag+ data-update-button+ onClick={() => setPanel(!open)}+ className={cx("flex h-6 items-center gap-1.5 rounded-full px-2.5 text-xs font-medium transition-colors", TONE[button.urgency])}+ aria-label={`${button.label}${button.count > 1 ? `, ${button.count} items` : ""}`}+ aria-expanded={open}+ >+ {button.required ? <ShieldAlert size={13} /> : <ArrowUpCircle size={13} />}+ {button.label}+ {button.count > 1 && <span className="rounded-full bg-current/15 px-1 font-mono text-2xs opacity-80">{button.count}</span>}+ </button>+ {open && <UpdatesPanel items={items} onClose={() => setPanel(false)} />}+ </>+ );+}++export function UpdatesPanel({ items, onClose }: { items: UpdateItem[]; onClose: () => void }) {+ const ref = useRef<HTMLDivElement>(null);+ const checking = useUpdates((s) => s.checking);+ const checkedAt = useUpdates((s) => s.lastFullCheck);+ const openSettings = useUi((s) => s.openSettings);+ useEffect(() => {+ const down = (e: MouseEvent) => {+ const t = e.target as HTMLElement;+ if (ref.current?.contains(t) || t.closest("[data-update-button]")) return;+ onClose();+ };+ const key = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };+ window.addEventListener("mousedown", down);+ window.addEventListener("keydown", key);+ return () => { window.removeEventListener("mousedown", down); window.removeEventListener("keydown", key); };+ }, [onClose]);+ const shown = items.filter((i) => !i.snoozed || i.required || i.active);+ return (+ <div ref={ref} data-no-drag className="fixed right-3 top-10 z-50 flex max-h-[78vh] w-[420px] max-w-[94vw] flex-col overflow-hidden rounded-xl border border-line bg-raised text-sm text-ink shadow-2xl animate-fade-in" role="dialog" aria-label="Updates">+ <div className="flex items-center justify-between border-b border-line px-4 py-2.5">+ <span className="font-medium">Updates</span>+ <button onClick={onClose} className="rounded p-0.5 text-ink4 hover:text-ink" aria-label="Close"><X size={14} /></button>+ </div>+ <div className="flex min-h-0 flex-col divide-y divide-line overflow-y-auto">+ {shown.length === 0 && <p className="px-4 py-6 text-center text-ink3">Everything is up to date.</p>}+ {shown.map((i) => (i.kind === "desktop" ? <DesktopRow key={i.key} item={i} /> : <ServerRow key={i.key} item={i} />))}+ </div>+ <div className="flex items-center justify-between border-t border-line px-4 py-2 text-xs text-ink4">+ <span>{checking ? "Checking…" : checkedAt ? `Checked ${ago(checkedAt)}` : ""}</span>+ <span className="flex gap-3">+ <button className="hover:text-ink" onClick={() => void checkAll(true)} disabled={checking}>Check now</button>+ <button className="hover:text-ink" onClick={() => { onClose(); openSettings("about"); }}>Settings</button>+ </span>+ </div>+ </div>+ );+}++function ago(at: number): string {+ const m = Math.round((Date.now() - at) / 60_000);+ if (m < 1) return "just now";+ if (m < 60) return `${m} min ago`;+ const h = Math.round(m / 60);+ return h < 24 ? `${h} h ago` : `${Math.round(h / 24)} d ago`;+}++function Head({ icon: Icon, item }: { icon: typeof Laptop; item: UpdateItem }) {+ return (+ <div className="flex items-start gap-2.5">+ <span className={cx("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg", item.required ? "bg-red/10 text-red" : "bg-ink/[0.06] text-ink2")}><Icon size={14} /></span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate font-medium">{item.name}</span>+ {item.required && <span className="rounded-full bg-red/10 px-1.5 text-2xs font-medium text-red">{item.required.severity === "security" ? "Security update" : "Required"}</span>}+ </div>+ <div className="font-mono text-xs text-ink3">{item.current || "?"}{item.next ? ` → ${item.next}` : ""}</div>+ </div>+ </div>+ );+}++/** Release notes before you update: decide with what's new in front of you. */+export function Notes({ item, defaultOpen = false }: { item: UpdateItem; defaultOpen?: boolean }) {+ const [open, setOpen] = useState(defaultOpen);+ const notes = item.release?.notes;+ const url = item.release?.notesUrl;+ if (!notes && !url) return null;+ return (+ <div className="mt-2">+ {notes ? (+ <>+ <button onClick={() => setOpen(!open)} className="flex items-center gap-1 text-xs text-ink3 hover:text-ink">+ {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />} What's new in {item.next ?? item.release?.version}+ </button>+ {open && <div className="mt-1.5 max-h-60 overflow-y-auto rounded-lg bg-ink/[0.03] px-3 py-2 text-sm" data-selectable><Markdown text={notes} /></div>}+ </>+ ) : null}+ {url && <button onClick={() => void native.openExternal(url)} className="mt-1 text-xs text-accent hover:underline">Full release notes</button>}+ </div>+ );+}++function Bar({ percent }: { percent: number | null }) {+ return (+ <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-ink/[0.08]" role="progressbar" aria-valuenow={percent ?? undefined} aria-valuemin={0} aria-valuemax={100}>+ {percent === null+ ? <div className="h-full w-1/3 animate-pulse rounded-full bg-accent/70" />+ : <div className="h-full rounded-full bg-accent transition-[width] duration-300" style={{ width: `${Math.max(2, Math.min(100, percent))}%` }} />}+ </div>+ );+}++function Messages({ messages }: { messages: ManifestMessage[] }) {+ if (!messages.length) return null;+ return (+ <div className="mt-2 flex flex-col gap-1.5">+ {messages.map((m) => (+ <div key={m.id} className={cx("rounded-lg px-3 py-2 text-xs", m.level === "critical" ? "bg-red/10 text-ink" : m.level === "warning" ? "bg-amber/10 text-ink" : "bg-ink/[0.04] text-ink2")}>+ <div className="font-medium">{m.title}</div>+ {m.body && <div className="mt-0.5 text-ink2">{m.body}</div>}+ {m.link && <button onClick={() => void native.openExternal(m.link!.url)} className="mt-1 text-accent hover:underline">{m.link.label || "Read more"}</button>}+ </div>+ ))}+ </div>+ );+}++/* ── Mercury Desktop ── */++export function DesktopRow({ item, compact = false }: { item: UpdateItem; compact?: boolean }) {+ const d = useUpdates((s) => s.desktop);+ const failures = useUpdates((s) => (item.next ? s.prefs.failures[desktopKey(item.next)] : undefined));+ const later = useUpdates((s) => s.later);+ const agent = useRuntimeState((s) => s.agent);+ const [confirm, setConfirm] = useState(false);+ const p = d.progress;+ const replying = agent === "thinking" || agent === "streaming" || agent === "working";+ const gaveUp = (failures?.count ?? 0) >= MAX_FAILURES;++ function restart() {+ if (replying && !confirm) { setConfirm(true); return; }+ setConfirm(false);+ void installDesktop();+ }++ return (+ <div className="px-4 py-3">+ {!compact && <Head icon={Laptop} item={item} />}+ {!item.next && item.required && <p className="mt-2 text-xs text-ink3">This version is no longer supported. The update isn't available to this app yet: download it from the website.</p>}++ {d.phase === "downloading" && (+ <>+ <Bar percent={p?.percent ?? null} />+ <div className="mt-1 flex justify-between text-xs text-ink3">+ <span>{p?.phase === "retrying" ? p.message : p?.phase === "verifying" ? "Checking the signature…" : `Downloading ${formatBytes(p?.downloaded)}${p?.total ? ` of ${formatBytes(p.total)}` : ""}`}</span>+ <span>{p ? timeLeft(p.downloaded, p.total, p.bytesPerSec) ?? "" : ""}</span>+ </div>+ </>+ )}+ {d.phase === "installing" && <><Bar percent={null} /><p className="mt-1 text-xs text-ink3">Installing. Mercury Desktop restarts by itself.</p></>}+ {d.phase === "error" && d.error && (+ <p className="mt-2 flex gap-1.5 text-xs text-red"><AlertTriangle size={13} className="mt-px shrink-0" />{d.error}</p>+ )}+ {gaveUp && (+ <p className="mt-1 text-xs text-ink3">This didn't work {failures!.count} times, so Mercury stopped trying on its own. You can download the new version from the website instead.</p>+ )}+ {confirm && <p className="mt-2 text-xs text-amber">A reply is still coming in. It keeps running on the server; you'll see it when the app is back. Restart anyway?</p>}++ {!compact && <Notes item={item} />}++ <div className="mt-2.5 flex flex-wrap items-center justify-end gap-2">+ {!item.required && d.phase !== "installing" && <Button size="sm" variant="ghost" onClick={() => later(item.key)}>Later</Button>}+ {gaveUp && <Button size="sm" variant="outline" onClick={() => void native.openExternal(RELEASES_URL)}>Download from website</Button>}+ {item.next && d.phase === "ready" && <Button size="sm" variant="primary" onClick={restart}>{confirm ? "Restart anyway" : "Restart to update"}</Button>}+ {item.next && (d.phase === "idle" || d.phase === "checking") && !d.available?.ready && <Button size="sm" variant="primary" onClick={() => void downloadDesktop()}>{d.available?.partialBytes ? "Resume download" : "Download"}</Button>}+ {item.next && d.phase === "error" && <Button size="sm" variant="primary" onClick={() => void (d.available?.ready ? installDesktop() : downloadDesktop())}><RotateCcw size={12} /> Try again</Button>}+ {!item.next && item.required && <Button size="sm" variant="primary" onClick={() => void native.openExternal(RELEASES_URL)}>Download</Button>}+ </div>+ </div>+ );+}++/* ── a server ── */++const STEP: Record<UpdateJob["state"], string> = {+ "waiting-idle": "Waiting for running work to finish",+ downloading: "Downloading",+ verifying: "Checking the download",+ "backing-up": "Backing up",+ stopping: "Stopping Mercury",+ installing: "Installing",+ starting: "Starting the new version",+ checking: "Making sure it works",+ done: "Updated",+ "rolled-back": "Rolled back",+ failed: "Failed",+ cancelled: "Cancelled",+};++export function ServerRow({ item, compact = false }: { item: UpdateItem; compact?: boolean }) {+ const conn = item.connection!;+ const entry = useUpdates((s) => s.servers[conn.id]);+ const later = useUpdates((s) => s.later);+ const [confirm, setConfirm] = useState(false);+ const [showLog, setShowLog] = useState(false);+ if (!entry) return null;+ const info = entry.info;+ const a = entry.action;+ const local = conn.kind === "local";++ function start(now = false) {+ if (!now && busyOn(conn) && !confirm) { setConfirm(true); return; }+ setConfirm(false);+ void updateServer(conn, { now });+ }++ const job = a.phase === "running" || a.phase === "finished" ? a.job : a.phase === "restarting" ? a.job : null;+ const blocked = info?.blocked && item.next && info.blocked.version === item.next ? info.blocked : null;+ const cannot = info && !info.canSelfUpdate;++ return (+ <div className="px-4 py-3">+ {!compact && <Head icon={Server} item={item} />}+ {item.required?.reason && <p className="mt-2 text-xs text-ink2">{item.required.reason}</p>}+ <Messages messages={item.messages} />++ {a.phase === "approval" && (+ <div className="mt-2 flex items-start gap-2 rounded-lg bg-amber/10 px-3 py-2 text-xs">+ <KeyRound size={13} className="mt-0.5 shrink-0 text-amber" />+ <span className="flex-1">Waiting for the owner's approval. Approve it on {a.where} · code <span className="font-mono font-medium">{a.code}</span>. It starts by itself once approved.</span>+ <button onClick={() => stopWaiting(conn)} className="text-ink3 hover:text-ink">Cancel</button>+ </div>+ )}+ {(a.phase === "running" || a.phase === "restarting" || a.phase === "starting") && (+ <>+ <Bar percent={a.phase === "starting" ? null : job?.percent ?? null} />+ <div className="mt-1 text-xs text-ink3">+ {a.phase === "starting" ? "Starting the update…"+ : a.phase === "restarting" ? `Restarting ${conn.name}… (it's offline for a moment)`+ : job ? `${STEP[job.state]}${job.message && job.message !== STEP[job.state] ? ` · ${job.message}` : ""}${job.total ? ` · ${formatBytes(job.bytes)} of ${formatBytes(job.total)}` : ""}` : ""}+ </div>+ {job?.state === "waiting-idle" && <button onClick={() => start(true)} className="mt-1 text-xs text-accent hover:underline">Update now without waiting</button>}+ </>+ )}+ {a.phase === "finished" && (+ <div className={cx("mt-2 flex gap-1.5 text-xs", a.job.state === "done" ? "text-accent" : a.job.state === "rolled-back" ? "text-amber" : a.job.state === "failed" ? "text-red" : "text-ink3")}>+ {a.job.state === "done" ? <CheckCircle2 size={13} className="mt-px shrink-0" /> : <AlertTriangle size={13} className="mt-px shrink-0" />}+ <span>+ {a.job.state === "done" ? `Updated to ${a.job.to}.`+ : a.job.state === "rolled-back" ? `${a.job.to} didn't start properly, so ${conn.name} went back to ${a.job.from}. Nothing was lost.${a.job.error ? ` (${a.job.error})` : ""}`+ : a.job.state === "failed" ? `The update failed: ${a.job.error ?? a.job.message}. ${conn.name} still runs ${a.job.from}.`+ : "The update was cancelled."}+ </span>+ </div>+ )}+ {job && job.log?.length > 0 && (a.phase === "finished" && a.job.state !== "done") && (+ <div className="mt-1">+ <button onClick={() => setShowLog(!showLog)} className="flex items-center gap-1 text-xs text-ink3 hover:text-ink">{showLog ? <ChevronDown size={12} /> : <ChevronRight size={12} />} Details</button>+ {showLog && <pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded-lg bg-ink/[0.04] p-2 font-mono text-2xs text-ink2" data-selectable>{job.log.join("\n")}</pre>}+ </div>+ )}+ {a.phase === "error" && <p className="mt-2 flex gap-1.5 text-xs text-red"><AlertTriangle size={13} className="mt-px shrink-0" />{a.message}</p>}+ {blocked && a.phase === "idle" && (+ <p className="mt-2 text-xs text-ink3">Updating to {blocked.version} failed {blocked.failures} times{blocked.lastError ? ` (${blocked.lastError})` : ""}, so Mercury stopped trying on its own. On {local ? "this computer" : "that computer"}, run <code className="font-mono">mercury upgrade</code> to see what's wrong, or try once more.</p>+ )}+ {cannot && item.next && <p className="mt-2 text-xs text-ink3">{info?.cannotReason ?? "This Mercury can't update itself."} {local ? "Run" : "On that computer, run"} <code className="font-mono">mercury upgrade</code>.</p>}+ {!info && item.next && <p className="mt-2 text-xs text-ink3">This Mercury is too old to update from here. {local ? "Run" : "On that computer, run"} <code className="font-mono">mercury upgrade</code> once; after that it updates from this app.</p>}+ {confirm && <p className="mt-2 text-xs text-amber">Mercury is answering right now. The update waits until running work is done (up to 10 minutes), or can start right away and stop it.</p>}++ {!compact && <Notes item={item} />}++ <div className="mt-2.5 flex flex-wrap items-center justify-end gap-2">+ {a.phase === "finished" && <Button size="sm" variant="ghost" onClick={() => clearServerAction(conn)}>Dismiss</Button>}+ {!item.required && a.phase === "idle" && item.next && <Button size="sm" variant="ghost" onClick={() => later(item.key)}>Later</Button>}+ {confirm && <Button size="sm" variant="outline" onClick={() => start(true)}>Update now</Button>}+ {item.next && info?.canSelfUpdate && (a.phase === "idle" || a.phase === "error" || (a.phase === "finished" && a.job.state !== "done")) && (+ <Button size="sm" variant="primary" onClick={() => { if (confirm) { setConfirm(false); void updateServer(conn); } else start(); }}>+ {confirm ? "Wait, then update" : a.phase === "idle" ? (blocked ? "Try again" : "Update server") : <><RotateCcw size={12} /> Try again</>}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/updates/UpdatesSettings.tsx b/apps/desktop/src/updates/UpdatesSettings.tsxnew file mode 100644index 00000000..5e776371--- /dev/null+++ b/apps/desktop/src/updates/UpdatesSettings.tsx@@ -0,0 +1,86 @@+import { Laptop, Server } from "lucide-react";+import { Switch } from "~/components/ui/Switch";+import { Mono } from "~/components/ui/bits";+import { Button } from "~/components/ui/Button";+import { useConnections } from "~/shell/connections";+import { updatesNative } from "./native";+import { checkAll, useUpdates, type WhatsNew } from "./store";+import { DesktopRow, ServerRow } from "./UpdatesPanel";+import { useUpdateView } from "./useUpdateView";++/** Settings → About: versions, check now, what's new, the two switches, every server. */+export function UpdatesSettings() {+ const { items } = useUpdateView();+ const prefs = useUpdates((s) => s.prefs);+ const setPrefs = useUpdates((s) => s.setPrefs);+ const desktop = useUpdates((s) => s.desktop);+ const servers = useUpdates((s) => s.servers);+ const manifest = useUpdates((s) => s.manifest);+ const checking = useUpdates((s) => s.checking);+ const showWhatsNew = useUpdates((s) => s.showWhatsNew);+ const connections = useConnections((s) => s.connections);+ const desktopItem = items.find((i) => i.kind === "desktop");+ const rel = manifest?.manifest?.desktop?.channels?.stable;++ function whatsNew() {+ const w: WhatsNew = { title: `Mercury Desktop ${desktop.current}`, version: desktop.current, notes: rel?.version === desktop.current ? rel.notes : null, notesUrl: rel?.version === desktop.current ? rel.notesUrl : null };+ showWhatsNew(w);+ }++ return (+ <div className="flex flex-col gap-3">+ <div className="rounded-lg border border-line bg-surface">+ <div className="flex items-center gap-2.5 px-4 py-3 text-sm">+ <Laptop size={15} className="text-ink3" />+ <span className="flex-1">Mercury Desktop</span>+ <Mono>{desktop.current || "dev"}</Mono>+ </div>+ {desktopItem ? <div className="border-t border-line"><DesktopRow item={desktopItem} /></div> : (+ <p className="border-t border-line px-4 py-2.5 text-xs text-ink3">+ {desktop.error && !desktop.available ? `Couldn't check: ${desktop.error}` : "Up to date."}+ </p>+ )}+ <div className="flex items-center gap-3 border-t border-line px-4 py-2.5">+ <Button size="sm" variant="secondary" loading={checking} onClick={() => void checkAll(true)}>Check for updates</Button>+ <button className="text-xs text-accent hover:underline" onClick={whatsNew}>What's new</button>+ {manifest && !manifest.verified && manifest.manifest && <span className="text-xs text-amber">The update notice couldn't be verified, so it's ignored.</span>}+ </div>+ </div>++ <div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">+ <label className="flex items-center justify-between gap-4 px-4 py-3">+ <span>+ <span className="block text-sm text-ink">Download updates automatically</span>+ <span className="block text-xs text-ink3">In the background; nothing installs until you restart.</span>+ </span>+ <Switch checked={prefs.autoDownload} onCheckedChange={(v) => setPrefs({ autoDownload: v })} />+ </label>+ <label className="flex items-center justify-between gap-4 px-4 py-3">+ <span>+ <span className="block text-sm text-ink">Install a downloaded update when I quit</span>+ <span className="block text-xs text-ink3">The next start is the new version.</span>+ </span>+ <Switch checked={prefs.installOnQuit} onCheckedChange={(v) => { setPrefs({ installOnQuit: v }); void updatesNative.setInstallOnQuit(v); }} />+ </label>+ </div>++ <div className="rounded-lg border border-line bg-surface">+ <div className="px-4 pb-1 pt-3 text-2xs font-medium uppercase tracking-wider text-ink4">Servers</div>+ {connections.map((c) => {+ const e = servers[c.id];+ const item = items.find((i) => i.kind === "server" && i.connection?.id === c.id);+ return (+ <div key={c.id} className="border-t border-line first:border-t-0">+ <div className="flex items-center gap-2.5 px-4 py-2.5 text-sm">+ <Server size={14} className="text-ink3" />+ <span className="min-w-0 flex-1 truncate">{c.name}</span>+ <Mono>{e?.info?.current ?? e?.version ?? (e?.error ? "offline" : "…")}</Mono>+ </div>+ {item ? <ServerRow item={item} compact /> : e && !e.error ? <p className="px-4 pb-2.5 text-xs text-ink3">Up to date.</p> : null}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/updates/logic.test.ts b/apps/desktop/src/updates/logic.test.tsnew file mode 100644index 00000000..49eb4978--- /dev/null+++ b/apps/desktop/src/updates/logic.test.ts@@ -0,0 +1,165 @@+import { describe, expect, it } from "vitest";+import { ackHolds, compareVersions, messagesFor, requiredBy, snoozed, timeLeft, urgencyOf, versionMatches } from "./logic";+import { buttonOf, forceOf, itemsOf, type Snapshot } from "./selectors";+import type { Connection } from "~/shell/connections";+import type { ServerUpdates, UpdateManifest } from "./types";++const DAY = 86_400_000;+const NOW = Date.parse("2026-11-03T12:00:00Z");++describe("version order", () => {+ it("numbers, not strings", () => {+ expect(compareVersions("1.10.0", "1.9.9")).toBe(1);+ expect(compareVersions("1.4.2", "1.4.2")).toBe(0);+ expect(compareVersions("v1.4.2", "1.4.3")).toBe(-1);+ });+ it("a pre-release comes before its release", () => {+ expect(compareVersions("1.5.0-dev.20261103.abc", "1.5.0")).toBe(-1);+ expect(compareVersions("1.5.0-beta.2", "1.5.0-beta.10")).toBe(-1);+ });+ it("ranges: every comparator must hold", () => {+ expect(versionMatches("<1.5.0", "1.4.9")).toBe(true);+ expect(versionMatches(">=1.2.0 <1.4.3", "1.4.3")).toBe(false);+ expect(versionMatches("=1.4.1", "1.4.1")).toBe(true);+ expect(versionMatches("", "9.9.9")).toBe(true);+ });+});++describe("how loud the Update button is (Chrome-style)", () => {+ it("rises with age", () => {+ expect(urgencyOf(NOW - 1 * DAY, NOW)).toBe("low");+ expect(urgencyOf(NOW - 2 * DAY, NOW)).toBe("elevated");+ expect(urgencyOf(NOW - 5 * DAY, NOW)).toBe("high");+ expect(urgencyOf(NOW - 8 * DAY, NOW)).toBe("critical");+ });+ it("a security fix or a required update starts red", () => {+ expect(urgencyOf(NOW, NOW, { security: true })).toBe("critical");+ expect(urgencyOf(NOW, NOW, { required: true })).toBe("critical");+ });+});++describe("force updates", () => {+ const min = { version: "1.4.2", severity: "security" as const, reason: "Fixes a leak" };+ it("only a verified manifest can require an update", () => {+ expect(requiredBy("1.4.1", min, true)).toEqual(min);+ expect(requiredBy("1.4.1", min, false)).toBeNull();+ expect(requiredBy("1.4.2", min, true)).toBeNull();+ expect(requiredBy("", min, true)).toBeNull();+ });+ it("'continue anyway' ends with the app, or after 24 hours", () => {+ const ack = { key: "k", at: NOW, launchId: "a" };+ expect(ackHolds(ack, "k", "a", NOW + 23 * 3_600_000)).toBe(true);+ expect(ackHolds(ack, "k", "a", NOW + 25 * 3_600_000)).toBe(false);+ expect(ackHolds(ack, "k", "b", NOW)).toBe(false); // restarted+ expect(ackHolds(ack, "other", "a", NOW)).toBe(false); // a newer minimum+ });+ it("'Later' is for a day", () => {+ expect(snoozed(NOW + 1000, NOW)).toBe(true);+ expect(snoozed(NOW - 1000, NOW)).toBe(false);+ expect(snoozed(undefined, NOW)).toBe(false);+ });+});++describe("manifest messages", () => {+ const manifest: UpdateManifest = {+ schema: 1,+ issuedAt: "2026-11-03T00:00:00Z",+ messages: [+ { id: "a", title: "For everyone", apps: ["desktop", "server"] },+ { id: "b", title: "Servers only", apps: ["server"] },+ { id: "c", title: "Old desktops", apps: ["desktop"], versions: "<0.2.0" },+ { id: "d", title: "Not yet", apps: ["desktop"], startsAt: "2026-12-01T00:00:00Z" },+ { id: "e", title: "Over", apps: ["desktop"], endsAt: "2026-11-01T00:00:00Z" },+ { id: "f", title: "Critical", apps: ["desktop"], level: "critical", dismissible: false },+ ],+ };+ it("right app, version and dates", () => {+ expect(messagesFor(manifest, true, "desktop", "0.1.0", NOW).map((m) => m.id)).toEqual(["a", "c", "f"]);+ expect(messagesFor(manifest, true, "desktop", "0.2.0", NOW).map((m) => m.id)).toEqual(["a", "f"]);+ expect(messagesFor(manifest, true, "server", "1.4.2", NOW).map((m) => m.id)).toEqual(["a", "b"]);+ });+ it("an unverified manifest says nothing", () => {+ expect(messagesFor(manifest, false, "desktop", "0.1.0", NOW)).toEqual([]);+ });+ it("dismissed ones stay gone, except a critical one that can't be dismissed", () => {+ expect(messagesFor(manifest, true, "desktop", "0.1.0", NOW, { a: NOW, f: NOW }).map((m) => m.id)).toEqual(["c", "f"]);+ });+});++it("time left", () => {+ expect(timeLeft(50, 100, 1)).toBe("less than a minute left");+ expect(timeLeft(0, 6000, 50)).toBe("about 2 min left");+ expect(timeLeft(0, null, 50)).toBeNull();+});++/* ── what the button, panel and force screen show ── */++const conn = (id: string, kind: "local" | "remote" = "remote"): Connection => ({ id, kind, name: id, baseUrl: `https://${id}.example`, createdAt: "" });++function snap(over: Partial<Snapshot> = {}): Snapshot {+ return {+ prefs: { firstSeen: {}, later: {}, dismissedMessages: {}, shownMessages: {}, lastDesktopVersion: null, lastServerVersion: {}, failures: {}, autoDownload: true, installOnQuit: true },+ manifest: null,+ desktop: { current: "0.1.0", available: null, phase: "idle", progress: null, error: null, checkedAt: null },+ servers: {},+ ...over,+ };+}++const serverInfo = (over: Partial<ServerUpdates> = {}): ServerUpdates => ({+ current: "1.4.2", channel: "stable", install: "binary", canSelfUpdate: true, latest: { version: "1.5.0", notes: "New" }, updateAvailable: true,+ required: null, manifestVerified: true, checkedAt: NOW, job: null, blocked: null, justUpdated: null, messages: [], ...over,+});++describe("the Update button", () => {+ it("hidden when there's nothing to do", () => {+ expect(buttonOf(itemsOf(snap(), [], NOW), false)).toBeNull();+ });+ it("one per thing to update: this app and each server", () => {+ const s = snap({+ desktop: { current: "0.1.0", available: { version: "0.2.0", currentVersion: "0.1.0", date: null, notes: null, ready: true, partialBytes: 0 }, phase: "ready", progress: null, error: null, checkedAt: NOW },+ servers: { home: { connectionId: "home", info: serverInfo(), version: "1.4.2", error: null, checkedAt: NOW, action: { phase: "idle" } } },+ });+ const items = itemsOf(s, [conn("home")], NOW);+ expect(items.map((i) => i.kind)).toEqual(["desktop", "server"]);+ expect(buttonOf(items, true)).toMatchObject({ label: "Update", count: 2 });+ expect(buttonOf(items.slice(0, 1), true)).toMatchObject({ label: "Restart to update" });+ });+ it("'Later' hides it for a day, but never a required update", () => {+ const later = { "server:home:1.5.0": NOW + DAY };+ const s = snap({ prefs: { ...snap().prefs, later }, servers: { home: { connectionId: "home", info: serverInfo(), version: "1.4.2", error: null, checkedAt: NOW, action: { phase: "idle" } } } });+ expect(buttonOf(itemsOf(s, [conn("home")], NOW), false)).toBeNull();+ const req = snap({ prefs: { ...snap().prefs, later }, servers: { home: { connectionId: "home", info: serverInfo({ required: { version: "1.5.0", severity: "security", reason: "x" } }), version: "1.4.2", error: null, checkedAt: NOW, action: { phase: "idle" } } } });+ expect(buttonOf(itemsOf(req, [conn("home")], NOW), false)).toMatchObject({ label: "Update required", required: true, urgency: "critical" });+ });+ it("an older server without the updates API: the manifest's version decides", () => {+ const s = snap({+ manifest: { manifest: { schema: 1, issuedAt: "x", server: { channels: { stable: { version: "1.5.0" } } } }, verified: true, checkedAt: NOW, error: null },+ servers: { old: { connectionId: "old", info: null, version: "1.3.0", error: null, checkedAt: NOW, action: { phase: "idle" } } },+ });+ const items = itemsOf(s, [conn("old")], NOW);+ expect(items[0]).toMatchObject({ kind: "server", current: "1.3.0", next: "1.5.0" });+ });+});++describe("the force screen", () => {+ const required = { version: "1.5.0", severity: "security" as const, reason: "x" };+ const s = snap({ servers: {+ a: { connectionId: "a", info: serverInfo({ required }), version: "1.4.2", error: null, checkedAt: NOW, action: { phase: "idle" } },+ } });+ const items = itemsOf(s, [conn("a"), conn("b")], NOW);+ it("a server forces it only when it's the connection in use", () => {+ expect(forceOf(items, "a", {}, "L", NOW)?.kind).toBe("server");+ expect(forceOf(items, "b", {}, "L", NOW)).toBeNull();+ });+ it("gone while 'continue anyway' holds", () => {+ const f = forceOf(items, "a", {}, "L", NOW)!;+ expect(forceOf(items, "a", { [f.key]: { key: f.key, at: NOW, launchId: "L" } }, "L", NOW + 1000)).toBeNull();+ expect(forceOf(items, "a", { [f.key]: { key: f.key, at: NOW, launchId: "L" } }, "L2", NOW + 1000)).not.toBeNull();+ });+ it("the desktop's own minimum, from a verified manifest only", () => {+ const m = { manifest: { schema: 1, issuedAt: "x", desktop: { minimum: { version: "0.2.0", severity: "required" as const } } }, checkedAt: NOW, error: null };+ expect(forceOf(itemsOf(snap({ manifest: { ...m, verified: true } }), [], NOW), null, {}, "L", NOW)?.kind).toBe("desktop");+ expect(forceOf(itemsOf(snap({ manifest: { ...m, verified: false } }), [], NOW), null, {}, "L", NOW)).toBeNull();+ });+});diff --git a/apps/desktop/src/updates/logic.ts b/apps/desktop/src/updates/logic.tsnew file mode 100644index 00000000..e318b776--- /dev/null+++ b/apps/desktop/src/updates/logic.ts@@ -0,0 +1,139 @@+/* ═══════════════════════════════════════════════════════════════+ Update rules, kept pure so they're tested: version order, how loud+ the Update button is, whether a force update applies and whether its+ "continue anyway" still holds, and which manifest messages show.+ See docs/updates.md.+ ═══════════════════════════════════════════════════════════════ */++import type { ManifestMessage, Minimum, UpdateManifest } from "./types";++/** -1 / 0 / 1. "1.4.2" < "1.5.0"; a pre-release sorts before its release ("1.5.0-dev.1" < "1.5.0"). */+export function compareVersions(a: string, b: string): number {+ const split = (v: string) => {+ const [core, pre = ""] = v.trim().replace(/^v/, "").split(/-(.*)/s, 2);+ return { nums: core.split(".").map((n) => parseInt(n, 10) || 0), pre };+ };+ const x = split(a);+ const y = split(b);+ for (let i = 0; i < Math.max(x.nums.length, y.nums.length, 3); i++) {+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);+ if (d) return d > 0 ? 1 : -1;+ }+ if (x.pre === y.pre) return 0;+ if (!x.pre) return 1;+ if (!y.pre) return -1;+ const px = x.pre.split(".");+ const py = y.pre.split(".");+ for (let i = 0; i < Math.max(px.length, py.length); i++) {+ if (px[i] === undefined) return -1;+ if (py[i] === undefined) return 1;+ const nx = /^\d+$/.test(px[i]) ? Number(px[i]) : NaN;+ const ny = /^\d+$/.test(py[i]) ? Number(py[i]) : NaN;+ if (!Number.isNaN(nx) && !Number.isNaN(ny)) { if (nx !== ny) return nx > ny ? 1 : -1; continue; }+ if (px[i] !== py[i]) return px[i] > py[i] ? 1 : -1;+ }+ return 0;+}++export const isNewer = (a: string, b: string) => compareVersions(a, b) > 0;++/** "<1.5.0", ">=1.2.0 <1.4.3", "=1.4.1": every comparator must hold. Empty = every version. */+export function versionMatches(range: string | null | undefined, version: string): boolean {+ const parts = (range ?? "").trim().split(/\s+/).filter(Boolean);+ for (const part of parts) {+ const m = /^(>=|<=|>|<|=)?\s*v?(.+)$/.exec(part);+ if (!m) return false;+ const c = compareVersions(version, m[2]);+ const op = m[1] ?? "=";+ const ok = op === ">=" ? c >= 0 : op === "<=" ? c <= 0 : op === ">" ? c > 0 : op === "<" ? c < 0 : c === 0;+ if (!ok) return false;+ }+ return true;+}++const DAY = 86_400_000;++/**+ * How loud the Update button is, the way Chrome does it: quiet when an+ * update is new, then louder the longer it waits. A security fix starts red.+ */+export type Urgency = "low" | "elevated" | "high" | "critical";++export function urgencyOf(firstSeenAt: number, now: number, opts: { security?: boolean; required?: boolean } = {}): Urgency {+ if (opts.required || opts.security) return "critical";+ const age = Math.max(0, now - firstSeenAt);+ if (age >= 7 * DAY) return "critical";+ if (age >= 4 * DAY) return "high";+ if (age >= 2 * DAY) return "elevated";+ return "low";+}++const ORDER: Urgency[] = ["low", "elevated", "high", "critical"];+export const louder = (a: Urgency, b: Urgency): Urgency => (ORDER.indexOf(a) >= ORDER.indexOf(b) ? a : b);++/** Is `current` below a required minimum? Only a verified manifest may say so. */+export function requiredBy(current: string | null | undefined, minimum: Minimum | null | undefined, verified: boolean): Minimum | null {+ if (!verified || !current || !minimum?.version) return null;+ return compareVersions(current, minimum.version) < 0 ? minimum : null;+}++/** "Continue without updating" lasts until the app restarts, or 24 hours, whichever comes first. */+export const ACK_MS = DAY;++export interface ForceAck { key: string; at: number; launchId: string }++export function ackHolds(ack: ForceAck | undefined, key: string, launchId: string, now: number): boolean {+ return !!ack && ack.key === key && ack.launchId === launchId && now - ack.at < ACK_MS;+}++/** "Later" hides a (not required) update for a day. */+export const LATER_MS = DAY;++export function snoozed(until: number | undefined, now: number): boolean {+ return typeof until === "number" && until > now;+}++/** Manifest messages this app shows now: right app, version, dates, not dismissed. Unverified → none. */+export function messagesFor(+ manifest: UpdateManifest | null,+ verified: boolean,+ app: "desktop" | "server",+ version: string,+ now: number,+ dismissed: Record<string, number> = {},+): ManifestMessage[] {+ if (!verified || !manifest || !Array.isArray(manifest.messages)) return [];+ return manifest.messages.filter((m) => {+ if (!m || typeof m.id !== "string" || typeof m.title !== "string") return false;+ if (!Array.isArray(m.apps) || !m.apps.includes(app)) return false;+ if (m.versions && !versionMatches(m.versions, version)) return false;+ if (m.startsAt && Date.parse(m.startsAt) > now) return false;+ if (m.endsAt && Date.parse(m.endsAt) <= now) return false;+ // A message that can't be dismissed (critical only) ignores old dismissals.+ if (canDismiss(m) && dismissed[m.id]) return false;+ return true;+ });+}++export function canDismiss(m: ManifestMessage): boolean {+ return m.dismissible !== false || m.level !== "critical";+}++export function formatBytes(n: number | null | undefined): string {+ if (!n || n < 0) return "0 B";+ if (n < 1024) return `${n} B`;+ if (n < 1024 ** 2) return `${(n / 1024).toFixed(0)} KB`;+ if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`;+ return `${(n / 1024 ** 3).toFixed(2)} GB`;+}++/** "about 2 min left" from bytes and speed; null while unknown. */+export function timeLeft(done: number, total: number | null | undefined, bytesPerSec: number | null | undefined): string | null {+ if (!total || !bytesPerSec || bytesPerSec <= 0 || done >= total) return null;+ const s = (total - done) / bytesPerSec;+ if (s < 60) return "less than a minute left";+ return `about ${Math.round(s / 60)} min left`;+}++/** After this many failed tries at one version, stop trying on our own and offer the website. */+export const MAX_FAILURES = 3;diff --git a/apps/desktop/src/updates/native.ts b/apps/desktop/src/updates/native.tsnew file mode 100644index 00000000..5d1b92c5--- /dev/null+++ b/apps/desktop/src/updates/native.ts@@ -0,0 +1,40 @@+/* The native half of updates (src-tauri/src/commands/updates.rs). In a+ plain browser (`npm run dev`) there is nothing to update: everything+ answers "no update" so the UI still renders. */++import { invoke } from "@tauri-apps/api/core";+import { isTauri } from "~/shell/tauri";+import type { DesktopUpdateInfo, DesktopUpdateStatus, DownloadProgress, ManifestResult } from "./types";++export const updatesNative = {+ manifest(force: boolean): Promise<ManifestResult> {+ if (!isTauri) return Promise.resolve({ manifest: null, verified: false, checkedAt: null, error: "browser" });+ return invoke<ManifestResult>("updates_manifest", { force });+ },+ check(): Promise<DesktopUpdateInfo | null> {+ if (!isTauri) return Promise.resolve(null);+ return invoke<DesktopUpdateInfo | null>("desktop_update_check");+ },+ status(): Promise<DesktopUpdateStatus> {+ if (!isTauri) return Promise.resolve({ currentVersion: "dev", pending: null, downloading: false, installOnQuit: true });+ return invoke<DesktopUpdateStatus>("desktop_update_status");+ },+ download(): Promise<DesktopUpdateInfo> {+ if (!isTauri) return Promise.reject(new Error("Not running inside Mercury Desktop"));+ return invoke<DesktopUpdateInfo>("desktop_update_download");+ },+ /** Installs and restarts the app (on Windows the installer takes over). */+ install(): Promise<void> {+ if (!isTauri) return Promise.reject(new Error("Not running inside Mercury Desktop"));+ return invoke<void>("desktop_update_install");+ },+ setInstallOnQuit(enabled: boolean): Promise<void> {+ if (!isTauri) return Promise.resolve();+ return invoke<void>("desktop_update_set_install_on_quit", { enabled });+ },+ async onProgress(cb: (p: DownloadProgress) => void): Promise<() => void> {+ if (!isTauri) return () => {};+ const { listen } = await import("@tauri-apps/api/event");+ return listen<DownloadProgress>("desktop-update-progress", (e) => cb(e.payload));+ },+};diff --git a/apps/desktop/src/updates/selectors.ts b/apps/desktop/src/updates/selectors.tsnew file mode 100644index 00000000..5d63c589--- /dev/null+++ b/apps/desktop/src/updates/selectors.ts@@ -0,0 +1,131 @@+/* What the Update button, the panel and the force screen show, derived+ from the store. Pure functions of state, so they're tested. */++import type { Connection } from "~/shell/connections";+import { ackHolds, canDismiss, isNewer, louder, messagesFor, requiredBy, snoozed, urgencyOf, type Urgency } from "./logic";+import type { DesktopState, ServerEntry, UpdatePrefs } from "./store";+import type { ChannelRelease, ManifestMessage, ManifestResult, Minimum } from "./types";+import type { ForceAck } from "./logic";++export interface UpdateItem {+ key: string;+ kind: "desktop" | "server";+ connection?: Connection;+ name: string;+ current: string;+ next: string | null;+ release: ChannelRelease | null;+ required: Minimum | null;+ urgency: Urgency;+ snoozed: boolean;+ messages: ManifestMessage[];+ /** Something is happening (download, server job): keep it visible. */+ active: boolean;+}++export interface Snapshot {+ prefs: UpdatePrefs;+ manifest: ManifestResult | null;+ desktop: DesktopState;+ servers: Record<string, ServerEntry>;+}++export function desktopRequired(s: Snapshot): Minimum | null {+ return requiredBy(s.desktop.current, s.manifest?.manifest?.desktop?.minimum, !!s.manifest?.verified);+}++export function itemsOf(s: Snapshot, connections: Connection[], now: number): UpdateItem[] {+ const items: UpdateItem[] = [];+ const m = s.manifest;+ const verified = !!m?.verified;++ // This app.+ const dRequired = desktopRequired(s);+ const dRelease = verified ? m?.manifest?.desktop?.channels?.stable ?? null : null;+ const dNext = s.desktop.available?.version ?? (dRequired && dRelease && s.desktop.current && isNewer(dRelease.version, s.desktop.current) ? dRelease.version : null);+ if (dNext || dRequired) {+ const key = `desktop:${dNext ?? dRequired?.version}`;+ items.push({+ key,+ kind: "desktop",+ name: "Mercury Desktop",+ current: s.desktop.current,+ next: dNext,+ release: dRelease?.version === dNext ? dRelease : s.desktop.available ? { version: s.desktop.available.version, notes: s.desktop.available.notes ?? undefined, date: s.desktop.available.date ?? undefined } : null,+ required: dRequired,+ urgency: urgencyOf(s.prefs.firstSeen[key] ?? now, now, { required: !!dRequired }),+ snoozed: !dRequired && snoozed(s.prefs.later[key], now),+ messages: [],+ active: s.desktop.phase === "downloading" || s.desktop.phase === "installing",+ });+ }++ // Every server this app connects to.+ for (const c of connections) {+ const e = s.servers[c.id];+ if (!e) continue;+ const info = e.info;+ const current = info?.current ?? e.version ?? "";+ const fallback = verified ? m?.manifest?.server?.channels?.stable ?? null : null;+ const release = info ? info.latest : fallback && current && isNewer(fallback.version, current) ? fallback : null;+ const available = info ? info.updateAvailable && !!info.latest : !!release;+ const required = info?.required ?? null;+ const active = e.action.phase !== "idle";+ const messages = info?.messages ?? [];+ if (!available && !required && !active && !messages.length) continue;+ const next = available ? release?.version ?? null : null;+ const key = `server:${c.id}:${next ?? required?.version ?? current}`;+ items.push({+ key,+ kind: "server",+ connection: c,+ name: c.name,+ current,+ next,+ release,+ required,+ urgency: urgencyOf(s.prefs.firstSeen[key] ?? now, now, { required: !!required, security: required?.severity === "security" }),+ snoozed: !required && !active && snoozed(s.prefs.later[key], now),+ messages,+ active,+ });+ }+ return items;+}++/** What the top-right button says, or null when there is nothing to do. */+export interface ButtonState { label: string; urgency: Urgency; required: boolean; count: number }++export function buttonOf(items: UpdateItem[], desktopReady: boolean): ButtonState | null {+ const visible = items.filter((i) => !i.snoozed && (i.next || i.required || i.active));+ if (!visible.length) return null;+ const required = visible.some((i) => i.required);+ const urgency = visible.reduce<Urgency>((u, i) => louder(u, i.urgency), "low");+ const onlyDesktop = visible.length === 1 && visible[0].kind === "desktop";+ const label = required ? "Update required" : onlyDesktop && desktopReady ? "Restart to update" : "Update";+ return { label, urgency, required, count: visible.length };+}++/** The force screen: which required update, if its "continue anyway" doesn't hold. */+export interface ForceState { key: string; kind: "desktop" | "server"; required: Minimum; item: UpdateItem }++export function forceOf(items: UpdateItem[], activeConnectionId: string | null, acks: Record<string, ForceAck>, launchId: string, now: number): ForceState | null {+ for (const i of items) {+ if (!i.required) continue;+ // A server forces the screen only when it's the one this window uses.+ if (i.kind === "server" && i.connection?.id !== activeConnectionId) continue;+ // Not tied to the version on offer: a newer release appearing doesn't undo "continue anyway".+ const key = `force:${i.kind}:${i.connection?.id ?? "app"}:${i.required.version}`;+ if (ackHolds(acks[key], key, launchId, now)) continue;+ return { key, kind: i.kind, required: i.required, item: i };+ }+ return null;+}++/** Warning / critical manifest messages for this app: the banner. */+export function bannerMessages(s: Snapshot, now: number): ManifestMessage[] {+ return messagesFor(s.manifest?.manifest ?? null, !!s.manifest?.verified, "desktop", s.desktop.current || "0.0.0", now, s.prefs.dismissedMessages)+ .filter((m) => m.level === "warning" || m.level === "critical");+}++export { canDismiss };diff --git a/apps/desktop/src/updates/server.ts b/apps/desktop/src/updates/server.tsnew file mode 100644index 00000000..0a52d830--- /dev/null+++ b/apps/desktop/src/updates/server.ts@@ -0,0 +1,86 @@+/* ═══════════════════════════════════════════════════════════════+ A server's updates, for ANY connection (not only the active one):+ each request carries that connection's own credential. Updating a+ server rides through its restart: the daemon is down for a few+ seconds, and a local one comes back with a new attach token.+ ═══════════════════════════════════════════════════════════════ */++import { credentialFor, type Connection } from "~/shell/connections";+import type { ServerUpdates, UpdateJob } from "./types";++export class ServerError extends Error {+ constructor(message: string, readonly status: number, readonly body: Record<string, unknown> = {}) {+ super(message);+ }+}++async function call<T>(conn: Connection, path: string, init: RequestInit = {}, timeoutMs = 10_000): Promise<T> {+ const token = await credentialFor(conn).catch(() => null);+ const res = await fetch(`${conn.baseUrl.replace(/\/+$/, "")}${path}`, {+ ...init,+ headers: {+ Accept: "application/json",+ ...(init.body ? { "Content-Type": "application/json" } : {}),+ ...(token ? { Authorization: `Bearer ${token}` } : {}),+ ...(init.headers as Record<string, string> | undefined),+ },+ signal: AbortSignal.timeout(timeoutMs),+ });+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) throw new ServerError(typeof body.error === "string" ? body.error : `${conn.name} answered ${res.status}`, res.status, body);+ return body as T;+}++/** null = this Mercury predates updates (no /api/updates): the caller falls back to its health version. */+export async function fetchServerUpdates(conn: Connection, refresh = false): Promise<ServerUpdates | null> {+ try {+ return await call<ServerUpdates>(conn, refresh ? "/api/updates/check" : "/api/updates", refresh ? { method: "POST", body: "{}" } : {});+ } catch (err) {+ if (err instanceof ServerError && err.status === 404) return null;+ // Rate-limited manual check: the plain status is fine.+ if (refresh && err instanceof ServerError && err.status === 429) return fetchServerUpdates(conn, false);+ throw err;+ }+}++export async function serverVersion(conn: Connection): Promise<string | null> {+ const h = await call<{ version?: string }>(conn, "/api/health", {}, 6000).catch(() => null);+ return h?.version ?? null;+}++export type StartOutcome =+ | { kind: "started"; job: UpdateJob }+ | { kind: "approval"; approvalId: string; code: string; where: string; expiresAt?: number };++/** Start updating a server. A remote device gets an owner question (428) first. */+export async function startServerUpdate(conn: Connection, opts: { now?: boolean; approvalId?: string } = {}): Promise<StartOutcome> {+ try {+ const r = await call<{ job: UpdateJob }>(conn, "/api/updates/server", {+ method: "POST",+ body: JSON.stringify({ now: !!opts.now }),+ headers: opts.approvalId ? { "X-Mercury-Approval": opts.approvalId } : {},+ });+ return { kind: "started", job: r.job };+ } catch (err) {+ if (err instanceof ServerError && err.status === 409 && err.body.job) return { kind: "started", job: err.body.job as UpdateJob };+ if (err instanceof ServerError && err.status === 428 && typeof err.body.approvalId === "string" && !opts.approvalId) {+ return {+ kind: "approval",+ approvalId: err.body.approvalId,+ code: String(err.body.code ?? ""),+ where: String(err.body.where ?? "the computer Mercury runs on"),+ expiresAt: typeof err.body.expiresAt === "number" ? err.body.expiresAt : undefined,+ };+ }+ throw err;+ }+}++export async function approvalStatus(conn: Connection, approvalId: string): Promise<string> {+ const r = await call<{ status?: string }>(conn, `/api/security/approvals/${encodeURIComponent(approvalId)}/status`, {}, 8000);+ return r.status ?? "pending";+}++export async function cancelServerUpdate(conn: Connection): Promise<void> {+ await call(conn, "/api/updates/server/cancel", { method: "POST", body: "{}" });+}diff --git a/apps/desktop/src/updates/store.ts b/apps/desktop/src/updates/store.tsnew file mode 100644index 00000000..37e7c29b--- /dev/null+++ b/apps/desktop/src/updates/store.ts@@ -0,0 +1,446 @@+/* ═══════════════════════════════════════════════════════════════+ Updates: this app, every server it connects to, and what the signed+ manifest says. One store so the Update button, the panel, the force+ screen, Settings and the toasts all agree.++ Rules (docs/updates.md):+ - nothing here blocks the app unless a VERIFIED manifest (or the+ server's own check) says an update is required;+ - downloads run quietly in the background and resume; failures are+ shown where you look (the panel), never as pop-ups; after three+ failed tries at one version we stop trying on our own;+ - everything is dismissible except a required update.+ ═══════════════════════════════════════════════════════════════ */++import { create } from "zustand";+import { isTauri } from "~/shell/tauri";+import { useConnections, type Connection } from "~/shell/connections";+import { useNotify } from "~/app/notify/store";+import { useRuntimeState } from "~/app/store";+import { updatesNative } from "./native";+import { approvalStatus, fetchServerUpdates, serverVersion, startServerUpdate, ServerError } from "./server";+import { isNewer, LATER_MS, MAX_FAILURES, messagesFor, type ForceAck } from "./logic";+import { JOB_FINISHED, type DesktopUpdateInfo, type DownloadProgress, type ManifestResult, type ServerUpdates, type UpdateJob } from "./types";++/* ── persisted preferences and memory (this device) ── */++export interface UpdatePrefs {+ /** When an update was first seen, per "desktop:<v>" / "server:<connection>:<v>": how loud the button is. */+ firstSeen: Record<string, number>;+ /** "Later": hidden until then (same keys). */+ later: Record<string, number>;+ dismissedMessages: Record<string, number>;+ /** Info messages are a toast once. */+ shownMessages: Record<string, number>;+ lastDesktopVersion: string | null;+ lastServerVersion: Record<string, string>;+ failures: Record<string, { count: number; lastError: string }>;+ autoDownload: boolean;+ installOnQuit: boolean;+}++const DEFAULT_PREFS: UpdatePrefs = {+ firstSeen: {}, later: {}, dismissedMessages: {}, shownMessages: {},+ lastDesktopVersion: null, lastServerVersion: {}, failures: {},+ autoDownload: true, installOnQuit: true,+};++const STORE_FILE = "updates.json";+const DEV_KEY = "mercury-desktop-updates";++async function readPrefs(): Promise<UpdatePrefs> {+ try {+ if (isTauri) {+ const { load } = await import("@tauri-apps/plugin-store");+ const store = await load(STORE_FILE, { defaults: {}, autoSave: false });+ return { ...DEFAULT_PREFS, ...((await store.get<Partial<UpdatePrefs>>("prefs")) ?? {}) };+ }+ const raw = localStorage.getItem(DEV_KEY);+ return { ...DEFAULT_PREFS, ...(raw ? (JSON.parse(raw) as Partial<UpdatePrefs>) : {}) };+ } catch {+ return { ...DEFAULT_PREFS };+ }+}++let saveTimer: ReturnType<typeof setTimeout> | null = null;+function savePrefs(prefs: UpdatePrefs): void {+ if (saveTimer) clearTimeout(saveTimer);+ saveTimer = setTimeout(() => {+ void (async () => {+ try {+ if (isTauri) {+ const { load } = await import("@tauri-apps/plugin-store");+ const store = await load(STORE_FILE, { defaults: {}, autoSave: false });+ await store.set("prefs", prefs);+ await store.save();+ } else {+ localStorage.setItem(DEV_KEY, JSON.stringify(prefs));+ }+ } catch { /* a preference not saved is not worth an error */ }+ })();+ }, 300);+}++/* ── live state ── */++export type DesktopPhase = "idle" | "checking" | "downloading" | "ready" | "installing" | "error";++export interface DesktopState {+ current: string;+ available: DesktopUpdateInfo | null;+ phase: DesktopPhase;+ progress: DownloadProgress | null;+ error: string | null;+ checkedAt: number | null;+}++export type ServerAction =+ | { phase: "idle" }+ | { phase: "starting" }+ | { phase: "approval"; code: string; where: string }+ | { phase: "running"; job: UpdateJob }+ /** The daemon is between versions: not answering for a moment. */+ | { phase: "restarting"; job: UpdateJob | null }+ | { phase: "finished"; job: UpdateJob }+ | { phase: "error"; message: string };++export interface ServerEntry {+ connectionId: string;+ /** null = this Mercury has no /api/updates yet (older); `version` came from its health. */+ info: ServerUpdates | null;+ version: string | null;+ error: string | null;+ checkedAt: number;+ action: ServerAction;+}++export interface WhatsNew { title: string; version: string; notes?: string | null; notesUrl?: string | null }++/** New for every start of the app: a force update's "continue anyway" ends with it. */+export const LAUNCH_ID = Math.random().toString(36).slice(2);++interface UpdatesState {+ loaded: boolean;+ prefs: UpdatePrefs;+ manifest: ManifestResult | null;+ desktop: DesktopState;+ servers: Record<string, ServerEntry>;+ acks: Record<string, ForceAck>;+ panelOpen: boolean;+ whatsNew: WhatsNew | null;+ lastFullCheck: number;+ checking: boolean;++ setPrefs(patch: Partial<UpdatePrefs>): void;+ setPanel(open: boolean): void;+ showWhatsNew(w: WhatsNew | null): void;+ later(key: string): void;+ dismissMessage(id: string): void;+ acknowledge(key: string): void;+ setServer(id: string, patch: Partial<ServerEntry>): void;+}++export const useUpdates = create<UpdatesState>((set, get) => ({+ loaded: false,+ prefs: { ...DEFAULT_PREFS },+ manifest: null,+ desktop: { current: "", available: null, phase: "idle", progress: null, error: null, checkedAt: null },+ servers: {},+ acks: {},+ panelOpen: false,+ whatsNew: null,+ lastFullCheck: 0,+ checking: false,++ setPrefs: (patch) => {+ const prefs = { ...get().prefs, ...patch };+ set({ prefs });+ savePrefs(prefs);+ },+ setPanel: (panelOpen) => set({ panelOpen }),+ showWhatsNew: (whatsNew) => set({ whatsNew }),+ later: (key) => get().setPrefs({ later: { ...get().prefs.later, [key]: Date.now() + LATER_MS } }),+ dismissMessage: (id) => get().setPrefs({ dismissedMessages: { ...get().prefs.dismissedMessages, [id]: Date.now() } }),+ acknowledge: (key) => set((s) => ({ acks: { ...s.acks, [key]: { key, at: Date.now(), launchId: LAUNCH_ID } } })),+ setServer: (id, patch) => set((s) => {+ const prev = s.servers[id] ?? { connectionId: id, info: null, version: null, error: null, checkedAt: 0, action: { phase: "idle" } as ServerAction };+ return { servers: { ...s.servers, [id]: { ...prev, ...patch } } };+ }),+}));++export const desktopKey = (v: string) => `desktop:${v}`;+export const serverKey = (connectionId: string, v: string) => `server:${connectionId}:${v}`;++function noteFirstSeen(key: string): void {+ const { prefs, setPrefs } = useUpdates.getState();+ if (prefs.firstSeen[key]) return;+ // Keep the map small: entries older than 60 days are long resolved.+ const cutoff = Date.now() - 60 * 86_400_000;+ const firstSeen = Object.fromEntries(Object.entries(prefs.firstSeen).filter(([, at]) => at > cutoff));+ setPrefs({ firstSeen: { ...firstSeen, [key]: Date.now() } });+}++/* ── loading and checking ── */++let progressUnlisten: (() => void) | null = null;++export async function initUpdates(): Promise<void> {+ if (useUpdates.getState().loaded) return;+ const prefs = await readPrefs();+ useUpdates.setState({ loaded: true, prefs });+ void updatesNative.setInstallOnQuit(prefs.installOnQuit);+ if (!progressUnlisten) {+ progressUnlisten = await updatesNative.onProgress((p) => {+ const d = useUpdates.getState().desktop;+ if (d.available && p.version !== d.available.version) return;+ useUpdates.setState({ desktop: { ...d, progress: p, phase: p.phase === "ready" ? "ready" : p.phase === "error" ? d.phase : "downloading" } });+ });+ }+ const status = await updatesNative.status().catch(() => null);+ if (status) {+ useUpdates.setState((s) => ({+ desktop: { ...s.desktop, current: status.currentVersion, available: status.pending, phase: status.pending?.ready ? "ready" : status.downloading ? "downloading" : "idle" },+ }));+ }+}++const SIX_HOURS = 6 * 3_600_000;++/** Everything: the manifest, this app, every server. `force` = the user asked (bypasses the 6 h throttle). */+export async function checkAll(force = false): Promise<void> {+ const st = useUpdates.getState();+ if (st.checking) return;+ if (!force && Date.now() - st.lastFullCheck < SIX_HOURS) return;+ useUpdates.setState({ checking: true, lastFullCheck: Date.now() });+ try {+ const manifest = await updatesNative.manifest(force).catch(() => null);+ if (manifest) useUpdates.setState({ manifest });+ await Promise.allSettled([checkDesktop(), ...useConnections.getState().connections.map((c) => checkServer(c, force))]);+ announce();+ } finally {+ useUpdates.setState({ checking: false });+ }+}++export async function checkDesktop(): Promise<void> {+ const s = useUpdates.getState();+ if (s.desktop.phase === "downloading" || s.desktop.phase === "installing") return;+ useUpdates.setState({ desktop: { ...s.desktop, phase: "checking", error: null } });+ try {+ const available = await updatesNative.check();+ const d = useUpdates.getState().desktop;+ useUpdates.setState({ desktop: { ...d, available, phase: available?.ready ? "ready" : "idle", checkedAt: Date.now(), current: available?.currentVersion ?? d.current } });+ if (available) {+ noteFirstSeen(desktopKey(available.version));+ const { prefs } = useUpdates.getState();+ const failed = prefs.failures[desktopKey(available.version)]?.count ?? 0;+ if (!available.ready && prefs.autoDownload && failed < MAX_FAILURES) void downloadDesktop();+ }+ } catch (err) {+ // No release feed yet, offline…: say so in the panel only, and only when asked.+ const d = useUpdates.getState().desktop;+ useUpdates.setState({ desktop: { ...d, phase: d.available?.ready ? "ready" : "idle", error: err instanceof Error ? err.message : String(err), checkedAt: Date.now() } });+ }+}++export async function downloadDesktop(): Promise<boolean> {+ const d = useUpdates.getState().desktop;+ if (!d.available) return false;+ const key = desktopKey(d.available.version);+ useUpdates.setState({ desktop: { ...d, phase: "downloading", error: null } });+ try {+ const info = await updatesNative.download();+ const cur = useUpdates.getState();+ useUpdates.setState({ desktop: { ...cur.desktop, available: info, phase: "ready", error: null } });+ const failures = { ...cur.prefs.failures };+ delete failures[key];+ cur.setPrefs({ failures });+ return true;+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ if (message === "Already downloading.") return false;+ const cur = useUpdates.getState();+ const prev = cur.prefs.failures[key]?.count ?? 0;+ cur.setPrefs({ failures: { ...cur.prefs.failures, [key]: { count: prev + 1, lastError: message } } });+ useUpdates.setState({ desktop: { ...cur.desktop, phase: "error", error: message } });+ return false;+ }+}++/** Install the downloaded update and restart. */+export async function installDesktop(): Promise<void> {+ const d = useUpdates.getState().desktop;+ useUpdates.setState({ desktop: { ...d, phase: "installing", error: null } });+ try {+ if (!d.available?.ready) {+ const ok = await downloadDesktop();+ if (!ok) return;+ }+ await updatesNative.install();+ } catch (err) {+ const cur = useUpdates.getState().desktop;+ const message = err instanceof Error ? err.message : String(err);+ const key = cur.available ? desktopKey(cur.available.version) : "desktop:?";+ const { prefs, setPrefs } = useUpdates.getState();+ setPrefs({ failures: { ...prefs.failures, [key]: { count: (prefs.failures[key]?.count ?? 0) + 1, lastError: message } } });+ useUpdates.setState({ desktop: { ...cur, phase: "error", error: message, available: cur.available ? { ...cur.available, ready: false } : null } });+ }+}++export async function checkServer(conn: Connection, refresh = false): Promise<void> {+ const { setServer, servers } = useUpdates.getState();+ const busy = servers[conn.id]?.action.phase;+ if (busy === "running" || busy === "restarting" || busy === "starting") return;+ try {+ const info = await fetchServerUpdates(conn, refresh);+ const version = info?.current ?? (await serverVersion(conn));+ setServer(conn.id, { info, version, error: null, checkedAt: Date.now() });+ const latest = info?.latest?.version ?? manifestServerLatest();+ if (version && latest && (info ? info.updateAvailable : isNewer(latest, version))) noteFirstSeen(serverKey(conn.id, latest));+ noticeServerVersion(conn, info, version);+ // An update already running there (started from its CLI, or before this app opened): follow it.+ const action = useUpdates.getState().servers[conn.id]?.action.phase;+ if (info?.job && !JOB_FINISHED.includes(info.job.state) && (action === "idle" || action === "finished" || action === "error")) void followJob(conn, info.job);+ } catch (err) {+ setServer(conn.id, { error: err instanceof Error ? err.message : String(err), checkedAt: Date.now() });+ }+}++function manifestServerLatest(): string | null {+ const m = useUpdates.getState().manifest;+ return m?.verified ? m.manifest?.server?.channels?.stable?.version ?? null : null;+}++/* ── what's new, and messages ── */++/** A server now runs a newer version than last time we looked: say so once. */+function noticeServerVersion(conn: Connection, info: ServerUpdates | null, version: string | null): void {+ if (!version) return;+ const { prefs, setPrefs } = useUpdates.getState();+ const last = prefs.lastServerVersion[conn.id];+ if (last === version) return;+ setPrefs({ lastServerVersion: { ...prefs.lastServerVersion, [conn.id]: version } });+ if (!last || !isNewer(version, last)) return;+ const notes = info?.latest?.version === version ? info.latest : useUpdates.getState().manifest?.manifest?.server?.channels?.stable;+ const w: WhatsNew = { title: `${conn.name} now runs Mercury ${version}`, version, notes: notes?.version === version ? notes.notes : null, notesUrl: notes?.version === version ? notes.notesUrl : null };+ useNotify.getState().pushAlert({ kind: "update", title: w.title, body: `Updated from ${last}.`, action: { label: "What's new", run: () => useUpdates.getState().showWhatsNew(w) } });+}++/** After the desktop updated itself (version changed since last launch). */+export function noticeDesktopVersion(): void {+ const { prefs, setPrefs, desktop, manifest } = useUpdates.getState();+ const current = desktop.current;+ if (!current || current === "dev") return;+ const last = prefs.lastDesktopVersion;+ if (last === current) return;+ setPrefs({ lastDesktopVersion: current });+ if (!last || !isNewer(current, last)) return;+ const rel = manifest?.manifest?.desktop?.channels?.stable;+ const w: WhatsNew = { title: `Mercury Desktop ${current}`, version: current, notes: rel?.version === current ? rel.notes : null, notesUrl: rel?.version === current ? rel.notesUrl : null };+ useNotify.getState().pushAlert({ kind: "update", title: `Mercury Desktop updated to ${current}`, body: `You were on ${last}.`, action: { label: "What's new", run: () => useUpdates.getState().showWhatsNew(w) } });+}++/** Info messages from the manifest: a toast, once. (Warnings and critical ones are a banner.) */+function announce(): void {+ noticeDesktopVersion();+ const { manifest, desktop, prefs, setPrefs } = useUpdates.getState();+ const msgs = messagesFor(manifest?.manifest ?? null, !!manifest?.verified, "desktop", desktop.current || "0.0.0", Date.now(), prefs.dismissedMessages);+ const fresh = msgs.filter((m) => (m.level ?? "info") === "info" && !prefs.shownMessages[m.id]);+ if (!fresh.length) return;+ const shown = { ...prefs.shownMessages };+ for (const m of fresh.slice(0, 2)) {+ shown[m.id] = Date.now();+ useNotify.getState().pushAlert({+ kind: "update",+ title: m.title,+ body: m.body ?? "",+ action: m.link ? { label: m.link.label || "Read more", run: () => void import("~/shell/tauri").then(({ desktop: d }) => d.openExternal(m.link!.url)) } : undefined,+ });+ }+ setPrefs({ shownMessages: shown });+}++/* ── updating a server ── */++const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));++/** Is a reply running on this connection right now? (Only known for the one this window shows.) */+export function busyOn(conn: Connection): boolean {+ if (useConnections.getState().activeId !== conn.id) return false;+ const a = useRuntimeState.getState().agent;+ return a === "thinking" || a === "streaming" || a === "working" || a === "needs-you";+}++export async function updateServer(conn: Connection, opts: { now?: boolean } = {}): Promise<void> {+ const { setServer } = useUpdates.getState();+ setServer(conn.id, { action: { phase: "starting" } });+ try {+ let outcome = await startServerUpdate(conn, opts);+ if (outcome.kind === "approval") {+ setServer(conn.id, { action: { phase: "approval", code: outcome.code, where: outcome.where } });+ const until = (outcome.expiresAt ?? Date.now() + 10 * 60_000) + 5_000;+ let allowed = false;+ while (Date.now() < until) {+ await pause(2000);+ if (useUpdates.getState().servers[conn.id]?.action.phase !== "approval") return; // cancelled+ const s = await approvalStatus(conn, outcome.approvalId).catch(() => "pending");+ if (s === "allowed") { allowed = true; break; }+ if (s === "denied" || s === "expired") break;+ }+ if (!allowed) { setServer(conn.id, { action: { phase: "error", message: "The owner didn't approve the update." } }); return; }+ outcome = await startServerUpdate(conn, { ...opts, approvalId: outcome.approvalId });+ if (outcome.kind !== "started") { setServer(conn.id, { action: { phase: "error", message: "The owner didn't approve the update." } }); return; }+ }+ await followJob(conn, outcome.job);+ } catch (err) {+ const message = err instanceof ServerError || err instanceof Error ? err.message : String(err);+ setServer(conn.id, { action: { phase: "error", message } });+ }+}++/** Stop waiting for an approval (the server's question simply expires). */+export function stopWaiting(conn: Connection): void {+ useUpdates.getState().setServer(conn.id, { action: { phase: "idle" } });+}++/** Poll the job through the restart, until it's done, rolled back or failed. */+async function followJob(conn: Connection, first: UpdateJob): Promise<void> {+ const { setServer } = useUpdates.getState();+ let job = first;+ let downSince: number | null = null;+ setServer(conn.id, { action: { phase: "running", job } });+ for (;;) {+ if (JOB_FINISHED.includes(job.state)) break;+ await pause(1500);+ try {+ const info = await fetchServerUpdates(conn);+ downSince = null;+ if (!info) throw new Error("no updates API");+ setServer(conn.id, { info, version: info.current });+ if (info.job && info.job.id === job.id) job = info.job;+ else if (!info.job && info.current === job.to) job = { ...job, state: "done", percent: 100, message: `Updated to ${job.to}` };+ setServer(conn.id, { action: { phase: "running", job } });+ } catch {+ // Between versions: the daemon is down for a moment (a local one also gets a new token).+ downSince ??= Date.now();+ setServer(conn.id, { action: { phase: "restarting", job } });+ if (Date.now() - downSince > 6 * 60_000) {+ setServer(conn.id, { action: { phase: "error", message: `${conn.name} hasn't answered for 6 minutes. If it doesn't come back, run \`mercury start\` there (and \`mercury logs\` to see why).` } });+ return;+ }+ }+ }+ setServer(conn.id, { action: { phase: "finished", job } });+ if (job.state === "done" && useConnections.getState().activeId === conn.id) {+ // The window's own connection: reconnect onto the new version (events, token).+ window.dispatchEvent(new CustomEvent("mercury:reconnect", { detail: { connectionId: conn.id } }));+ }+ void checkServer(conn);+}++/** Clear a finished job's card. */+export function clearServerAction(conn: Connection): void {+ useUpdates.getState().setServer(conn.id, { action: { phase: "idle" } });+}++export { isNewer };diff --git a/apps/desktop/src/updates/types.ts b/apps/desktop/src/updates/types.tsnew file mode 100644index 00000000..83423315--- /dev/null+++ b/apps/desktop/src/updates/types.ts@@ -0,0 +1,119 @@+/* The shapes in docs/updates.md, as the desktop reads them. */++export interface ChannelRelease {+ version: string;+ date?: string;+ notes?: string;+ notesUrl?: string;+}++export interface Minimum {+ version: string;+ severity?: "security" | "required";+ reason?: string;+ since?: string;+}++export interface ManifestMessage {+ id: string;+ title: string;+ body?: string;+ level?: "info" | "warning" | "critical";+ apps: Array<"desktop" | "server">;+ versions?: string | null;+ startsAt?: string | null;+ endsAt?: string | null;+ link?: { label: string; url: string } | null;+ dismissible?: boolean;+}++export interface AppSection {+ channels?: { stable?: ChannelRelease | null; dev?: ChannelRelease | null };+ minimum?: Minimum | null;+}++export interface UpdateManifest {+ schema: number;+ issuedAt: string;+ server?: AppSection;+ desktop?: AppSection;+ messages?: ManifestMessage[];+}++export interface ManifestResult {+ manifest: UpdateManifest | null;+ verified: boolean;+ checkedAt: number | null;+ error: string | null;+}++/* ── the desktop's own update (Rust) ── */++export interface DesktopUpdateInfo {+ version: string;+ currentVersion: string;+ date: string | null;+ notes: string | null;+ ready: boolean;+ partialBytes: number;+}++export interface DesktopUpdateStatus {+ currentVersion: string;+ pending: DesktopUpdateInfo | null;+ downloading: boolean;+ installOnQuit: boolean;+}++export interface DownloadProgress {+ phase: "downloading" | "verifying" | "ready" | "retrying" | "error";+ version: string;+ downloaded: number;+ total: number | null;+ percent: number | null;+ bytesPerSec: number | null;+ attempt: number;+ message: string;+}++/* ── a server's GET /api/updates ── */++export type JobState =+ | "waiting-idle" | "downloading" | "verifying" | "backing-up" | "stopping"+ | "installing" | "starting" | "checking"+ | "done" | "rolled-back" | "failed" | "cancelled";++export interface UpdateJob {+ id: string;+ from: string;+ to: string;+ state: JobState;+ percent: number | null;+ bytes?: number;+ total?: number;+ message: string;+ startedAt: number;+ updatedAt: number;+ error?: string;+ log: string[];+ attempt: number;+}++export const JOB_FINISHED: JobState[] = ["done", "rolled-back", "failed", "cancelled"];++export interface ServerUpdates {+ current: string;+ channel: "stable" | "dev";+ install: "binary" | "npm" | "source" | "unknown";+ canSelfUpdate: boolean;+ cannotReason?: string;+ latest: ChannelRelease | null;+ updateAvailable: boolean;+ required: (Minimum & { severity: "security" | "required" }) | null;+ manifestVerified: boolean;+ checkedAt: number | null;+ job: UpdateJob | null;+ blocked: { version: string; failures: number; lastError?: string } | null;+ justUpdated: { from: string; to: string; at: number } | null;+ messages: ManifestMessage[];+}diff --git a/apps/desktop/src/updates/useUpdateView.ts b/apps/desktop/src/updates/useUpdateView.tsnew file mode 100644index 00000000..21237668--- /dev/null+++ b/apps/desktop/src/updates/useUpdateView.ts@@ -0,0 +1,36 @@+import { useEffect, useMemo, useState } from "react";+import { useConnections } from "~/shell/connections";+import { useUpdates, LAUNCH_ID } from "./store";+import { bannerMessages, buttonOf, forceOf, itemsOf } from "./selectors";++/** A clock that ticks once a minute: the button gets louder with age, an acknowledgement ends after 24 h. */+export function useMinuteClock(): number {+ const [now, setNow] = useState(Date.now());+ useEffect(() => {+ const t = setInterval(() => setNow(Date.now()), 60_000);+ return () => clearInterval(t);+ }, []);+ return now;+}++export function useUpdateView() {+ const prefs = useUpdates((s) => s.prefs);+ const manifest = useUpdates((s) => s.manifest);+ const desktop = useUpdates((s) => s.desktop);+ const servers = useUpdates((s) => s.servers);+ const acks = useUpdates((s) => s.acks);+ const connections = useConnections((s) => s.connections);+ const activeId = useConnections((s) => s.activeId);+ const now = useMinuteClock();+ return useMemo(() => {+ const snap = { prefs, manifest, desktop, servers };+ const items = itemsOf(snap, connections, now);+ return {+ items,+ button: buttonOf(items, desktop.phase === "ready"),+ force: forceOf(items, activeId, acks, LAUNCH_ID, now),+ banners: bannerMessages(snap, now),+ now,+ };+ }, [prefs, manifest, desktop, servers, acks, connections, activeId, now]);+}diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsxindex 4fe1a04b..6bb3bafb 100644--- a/apps/desktop/src/views/settings/SettingsView.tsx+++ b/apps/desktop/src/views/settings/SettingsView.tsx@@ -1,4 +1,5 @@import { Activity, Info, MessagesSquare, Palette, Server, Sparkles, UserRound } from "lucide-react";+import { UpdatesSettings } from "~/updates/UpdatesSettings";import { useEffect, useState } from "react";import { cx } from "~/lib/cx";import { useUi } from "~/app/store";@@ -9,7 +10,7 @@ import { useConnections, type Connection } from "~/shell/connections";import { desktop, isTauri } from "~/shell/tauri";import { Button } from "~/components/ui/Button";import { Switch } from "~/components/ui/Switch";-import { Badge, Mono, Segmented } from "~/components/ui/bits";+import { Badge, Mono, SectionTitle, Segmented } from "~/components/ui/bits";import { Dialog } from "~/components/ui/Dialog";import { AddRemote } from "~/shell/AddRemote";import { StateOrb } from "~/components/indicators/StateOrb";@@ -260,6 +261,8 @@ function About({ health, onAnalytics }: { health: HealthInfo; onAnalytics?: () =<button className="mt-3 text-xs text-accent hover:underline" onClick={() => void desktop.openExternal("https://mercuryagent.sh")}>mercuryagent.sh</button>{onAnalytics && <button className="ml-4 mt-3 text-xs text-accent hover:underline" onClick={onAnalytics}>Your activity →</button>}</div>+ <SectionTitle>Updates</SectionTitle>+ <UpdatesSettings /></section>);}