Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(desktop): one Check for updates for this app and every server, Update everything, cancel

Salman Qureshi8b1cde292508
diff --git a/apps/desktop/src-tauri/src/commands/updates.rs b/apps/desktop/src-tauri/src/commands/updates.rs
index 0e233d3d..361cc89a 100644
--- a/apps/desktop/src-tauri/src/commands/updates.rs
+++ b/apps/desktop/src-tauri/src/commands/updates.rs
@@ -46,6 +46,8 @@ const STALL: Duration = Duration::from_secs(30);
pub struct UpdaterState {
update: Mutex<Option<Update>>,
downloading: AtomicBool,
+ /// "Cancel" on a running download: it stops and keeps its bytes (it resumes next time).
+ cancel: AtomicBool,
install_on_quit: AtomicBool,
}
@@ -390,6 +392,8 @@ enum Fail {
Retry(String),
/// Won't get better by retrying (404, too large, disk).
Stop(String),
+ /// The user cancelled.
+ Cancelled,
}
/// `Content-Range: bytes 100-999/1000` → 1000.
@@ -398,7 +402,7 @@ fn total_from_content_range(v: &str) -> Option<u64> {
}
/// 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> {
+async fn fetch_once(client: &reqwest::Client, url: &str, dir: &Path, version: &str, em: &Emitting<'_>, cancel: &AtomicBool) -> 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();
@@ -467,6 +471,10 @@ async fn fetch_once(client: &reqwest::Client, url: &str, dir: &Path, version: &s
Ok(Ok(None)) => break,
Ok(Ok(Some(c))) => c,
};
+ if cancel.load(Ordering::Relaxed) {
+ let _ = file.flush();
+ return Err(Fail::Cancelled);
+ }
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 {
@@ -490,6 +498,17 @@ async fn fetch_once(client: &reqwest::Client, url: &str, dir: &Path, version: &s
Ok(())
}
+/// The error a cancelled download returns (the app shows no error for it).
+const CANCELLED: &str = "Download cancelled.";
+
+/// Stop a running download. Its bytes stay: "Resume download" continues from there.
+#[tauri::command]
+pub fn desktop_update_cancel(state: State<'_, UpdaterState>) {
+ if state.downloading.load(Ordering::Relaxed) {
+ state.cancel.store(true, Ordering::Relaxed);
+ }
+}
+
struct Busy<'a>(&'a AtomicBool);
impl Drop for Busy<'_> {
fn drop(&mut self) { self.0.store(false, Ordering::Relaxed); }
@@ -506,6 +525,7 @@ pub async fn desktop_update_download(app: AppHandle, state: State<'_, UpdaterSta
return Err("Already downloading.".into());
}
let _busy = Busy(&state.downloading);
+ state.cancel.store(false, Ordering::Relaxed);
let client = http()?;
let url = update.download_url.to_string();
let mut em = Emitting { app: &app, version: update.version.clone(), attempt: 1 };
@@ -515,8 +535,13 @@ pub async fn desktop_update_download(app: AppHandle, state: State<'_, UpdaterSta
let mut ok = false;
for attempt in 1..=ATTEMPTS {
em.attempt = attempt;
- match fetch_once(&client, &url, &dir, &update.version, &em).await {
+ match fetch_once(&client, &url, &dir, &update.version, &em, &state.cancel).await {
Ok(()) => { ok = true; break; }
+ Err(Fail::Cancelled) => {
+ let have = fs::metadata(part_path(&dir, &update.version)).map(|m| m.len()).unwrap_or(0);
+ em.send("cancelled", have, None, None, "Download cancelled");
+ return Err(CANCELLED.into());
+ }
Err(Fail::Stop(e)) => { last = e; break; }
Err(Fail::Retry(e)) => {
last = e;
@@ -525,6 +550,10 @@ pub async fn desktop_update_download(app: AppHandle, state: State<'_, UpdaterSta
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 state.cancel.load(Ordering::Relaxed) {
+ em.send("cancelled", have, None, None, "Download cancelled");
+ return Err(CANCELLED.into());
+ }
}
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 19283bbb..861dc134 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -50,6 +50,7 @@ pub fn run() {
commands::updates::desktop_update_check,
commands::updates::desktop_update_status,
commands::updates::desktop_update_download,
+ commands::updates::desktop_update_cancel,
commands::updates::desktop_update_install,
commands::updates::desktop_update_set_install_on_quit,
notch::notch_show,
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index 160b81e4..b4944b64 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -2,15 +2,16 @@ use tauri::{
image::Image,
menu::{Menu, MenuItem, PredefinedMenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
- AppHandle,
+ AppHandle, Emitter,
};
/// The tray icon: the app's persistent presence while the window is hidden.
pub fn install(app: &AppHandle) -> tauri::Result<()> {
let open = MenuItem::with_id(app, "open", "Open Mercury", true, None::<&str>)?;
+ let updates = MenuItem::with_id(app, "check-updates", "Check for Updates…", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit Mercury", true, None::<&str>)?;
let separator = PredefinedMenuItem::separator(app)?;
- let menu = Menu::with_items(app, &[&open, &separator, &quit])?;
+ let menu = Menu::with_items(app, &[&open, &updates, &separator, &quit])?;
// macOS: a monochrome template image, tinted by the system to match the
// menu bar (light, dark, tinted wallpapers). Elsewhere: the colour tile.
@@ -30,6 +31,11 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> {
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id().as_ref() {
"open" => crate::show_main(app),
+ // The window opens Settings → About and checks this app and every server.
+ "check-updates" => {
+ crate::show_main(app);
+ let _ = app.emit("menu-check-updates", ());
+ }
"quit" => app.exit(0),
_ => {}
})
diff --git a/apps/desktop/src-tauri/tauri.release.conf.json b/apps/desktop/src-tauri/tauri.release.conf.json
new file mode 100644
index 00000000..d57cd002
--- /dev/null
+++ b/apps/desktop/src-tauri/tauri.release.conf.json
@@ -0,0 +1,5 @@
+{
+ "bundle": {
+ "createUpdaterArtifacts": true
+ }
+}
diff --git a/apps/desktop/src/updates/UpdateLayer.tsx b/apps/desktop/src/updates/UpdateLayer.tsx
index 0778e8e9..fdc19795 100644
--- a/apps/desktop/src/updates/UpdateLayer.tsx
+++ b/apps/desktop/src/updates/UpdateLayer.tsx
@@ -3,7 +3,8 @@ 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 { desktop as native, isTauri } from "~/shell/tauri";
+import { useUi } from "~/app/store";
import { useConnections } from "~/shell/connections";
import { ForceUpdate } from "./ForceUpdate";
import { canDismiss } from "./logic";
@@ -33,6 +34,18 @@ export function UpdateLayer() {
return () => { stop = true; clearInterval(t); window.removeEventListener("focus", onFocus); };
}, [connectionsLoaded]);
+ // Tray → "Check for Updates…": Settings → About, and check this app and every server.
+ useEffect(() => {
+ if (!isTauri) return;
+ let unlisten: (() => void) | null = null;
+ let gone = false;
+ void import("@tauri-apps/api/event").then(({ listen }) => listen("menu-check-updates", () => {
+ useUi.getState().openSettings("about");
+ void checkAll(true);
+ })).then((u) => { if (gone) u(); else unlisten = u; });
+ return () => { gone = true; unlisten?.(); };
+ }, []);
+
// 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);
diff --git a/apps/desktop/src/updates/UpdatesPanel.tsx b/apps/desktop/src/updates/UpdatesPanel.tsx
index 50aa5b1a..769cc91a 100644
--- a/apps/desktop/src/updates/UpdatesPanel.tsx
+++ b/apps/desktop/src/updates/UpdatesPanel.tsx
@@ -8,7 +8,7 @@ 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 { busyOn, cancelDesktopDownload, cancelServer, checkAll, clearServerAction, desktopKey, downloadDesktop, installDesktop, stopWaiting, updateEverything, updateServer, useUpdates } from "./store";
import type { ManifestMessage, UpdateJob } from "./types";
import { useUpdateView } from "./useUpdateView";
@@ -54,6 +54,8 @@ export function UpdatesPanel({ items, onClose }: { items: UpdateItem[]; onClose:
const ref = useRef<HTMLDivElement>(null);
const checking = useUpdates((s) => s.checking);
const checkedAt = useUpdates((s) => s.lastFullCheck);
+ const updatingAll = useUpdates((s) => s.updatingAll);
+ const { updatable } = useUpdateView();
const openSettings = useUi((s) => s.openSettings);
useEffect(() => {
const down = (e: MouseEvent) => {
@@ -79,8 +81,9 @@ export function UpdatesPanel({ items, onClose }: { items: UpdateItem[]; onClose:
</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">
+ <span className="flex items-center gap-3">
<button className="hover:text-ink" onClick={() => void checkAll(true)} disabled={checking}>Check now</button>
+ {updatable.length > 1 && <Button size="sm" variant="primary" loading={updatingAll} onClick={() => void updateEverything()}>Update all</Button>}
<button className="hover:text-ink" onClick={() => { onClose(); openSettings("about"); }}>Settings</button>
</span>
</div>
@@ -183,9 +186,12 @@ export function DesktopRow({ item, compact = false }: { item: UpdateItem; compac
{d.phase === "downloading" && (
<>
<Bar percent={p?.percent ?? null} />
- <div className="mt-1 flex justify-between text-xs text-ink3">
+ <div className="mt-1 flex justify-between gap-3 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>
+ <span className="flex gap-3">
+ {p ? timeLeft(p.downloaded, p.total, p.bytesPerSec) ?? "" : ""}
+ {p?.phase !== "verifying" && <button className="text-ink3 hover:text-ink" onClick={() => void cancelDesktopDownload()}>Cancel</button>}
+ </span>
</div>
</>
)}
@@ -229,6 +235,8 @@ const STEP: Record<UpdateJob["state"], string> = {
cancelled: "Cancelled",
};
+const CANCELLABLE: UpdateJob["state"][] = ["waiting-idle", "downloading", "verifying", "backing-up"];
+
export function ServerRow({ item, compact = false }: { item: UpdateItem; compact?: boolean }) {
const conn = item.connection!;
const entry = useUpdates((s) => s.servers[conn.id]);
@@ -271,7 +279,11 @@ export function ServerRow({ item, compact = false }: { item: UpdateItem; compact
: 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>}
+ <div className="mt-1 flex gap-3 text-xs">
+ {job?.state === "waiting-idle" && <button onClick={() => start(true)} className="text-accent hover:underline">Update now without waiting</button>}
+ {/* Only before Mercury is stopped: after that, finishing (or rolling back) is the safe way out. */}
+ {job && CANCELLABLE.includes(job.state) && <button onClick={() => void cancelServer(conn)} className="text-ink3 hover:text-ink">Cancel</button>}
+ </div>
</>
)}
{a.phase === "finished" && (
diff --git a/apps/desktop/src/updates/UpdatesSettings.tsx b/apps/desktop/src/updates/UpdatesSettings.tsx
index 5e776371..eb63f316 100644
--- a/apps/desktop/src/updates/UpdatesSettings.tsx
+++ b/apps/desktop/src/updates/UpdatesSettings.tsx
@@ -4,13 +4,15 @@ 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 { checkAll, checkAndUpdateAll, updateEverything, 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 { items, updatable } = useUpdateView();
+ const manualCheck = useUpdates((s) => s.manualCheck);
+ const updatingAll = useUpdates((s) => s.updatingAll);
const prefs = useUpdates((s) => s.prefs);
const setPrefs = useUpdates((s) => s.setPrefs);
const desktop = useUpdates((s) => s.desktop);
@@ -29,6 +31,23 @@ export function UpdatesSettings() {
return (
<div className="flex flex-col gap-3">
+ {/* One place for both: this app and every server it connects to. */}
+ <div className="flex flex-wrap items-center gap-3 rounded-lg border border-line bg-surface px-4 py-3">
+ <span className="min-w-0 flex-1 text-sm">
+ <span className="block text-ink">Updates</span>
+ <span className="block text-xs text-ink3">
+ {checking ? "Checking Mercury Desktop and your servers…"
+ : updatable.length ? `${updatable.length} update${updatable.length > 1 ? "s" : ""} ready to install: ${updatable.map((i) => `${i.name} ${i.next}`).join(", ")}.`
+ : manualCheck && Date.now() - manualCheck.at < 10 * 60_000 ? "Everything is up to date."
+ : "Mercury Desktop and every server you connect to."}
+ </span>
+ </span>
+ <Button size="sm" variant="secondary" loading={checking} onClick={() => void checkAll(true)}>Check for updates</Button>
+ {updatable.length > 0
+ ? <Button size="sm" variant="primary" loading={updatingAll} onClick={() => void updateEverything()}>{updatable.length > 1 ? "Update everything" : "Update"}</Button>
+ : !checking && <Button size="sm" variant="ghost" onClick={() => void checkAndUpdateAll()}>Check and update</Button>}
+ </div>
+
<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" />
@@ -41,8 +60,7 @@ export function UpdatesSettings() {
</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>
+ <button className="text-xs text-accent hover:underline" onClick={whatsNew}>What's new in {desktop.current || "this version"}</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>
diff --git a/apps/desktop/src/updates/logic.test.ts b/apps/desktop/src/updates/logic.test.ts
index 49eb4978..500d86d2 100644
--- a/apps/desktop/src/updates/logic.test.ts
+++ b/apps/desktop/src/updates/logic.test.ts
@@ -1,6 +1,6 @@
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 { buttonOf, forceOf, itemsOf, updatableOf, type Snapshot } from "./selectors";
import type { Connection } from "~/shell/connections";
import type { ServerUpdates, UpdateManifest } from "./types";
@@ -142,6 +142,28 @@ describe("the Update button", () => {
});
});
+describe("Update everything", () => {
+ const entry = (id: string, over: Partial<ServerUpdates> = {}, action: Snapshot["servers"][string]["action"] = { phase: "idle" }) =>
+ ({ connectionId: id, info: serverInfo(over), version: "1.4.2", error: null, checkedAt: NOW, action });
+ it("takes this app and every server that can update itself, and nothing already running", () => {
+ const s = snap({
+ desktop: { current: "0.1.0", available: { version: "0.2.0", currentVersion: "0.1.0", date: null, notes: null, ready: false, partialBytes: 0 }, phase: "idle", progress: null, error: null, checkedAt: NOW },
+ servers: {
+ home: entry("home"),
+ src: entry("src", { canSelfUpdate: false, install: "source" }),
+ busy: entry("busy", {}, { phase: "approval", code: "K7Q2M", where: "Telegram" }),
+ current: entry("current", { updateAvailable: false, latest: null }),
+ },
+ });
+ const items = itemsOf(s, [conn("home"), conn("src"), conn("busy"), conn("current")], NOW);
+ expect(updatableOf(items, s).map((i) => i.name)).toEqual(["Mercury Desktop", "home"]);
+ });
+ it("nothing while this app is installing", () => {
+ 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: "installing", progress: null, error: null, checkedAt: NOW } });
+ expect(updatableOf(itemsOf(s, [], NOW), s)).toEqual([]);
+ });
+});
+
describe("the force screen", () => {
const required = { version: "1.5.0", severity: "security" as const, reason: "x" };
const s = snap({ servers: {
diff --git a/apps/desktop/src/updates/native.ts b/apps/desktop/src/updates/native.ts
index 5d1b92c5..a1044dcb 100644
--- a/apps/desktop/src/updates/native.ts
+++ b/apps/desktop/src/updates/native.ts
@@ -23,6 +23,11 @@ export const updatesNative = {
if (!isTauri) return Promise.reject(new Error("Not running inside Mercury Desktop"));
return invoke<DesktopUpdateInfo>("desktop_update_download");
},
+ /** Stop a running download; its bytes stay, so it resumes next time. */
+ cancel(): Promise<void> {
+ if (!isTauri) return Promise.resolve();
+ return invoke<void>("desktop_update_cancel");
+ },
/** 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"));
diff --git a/apps/desktop/src/updates/selectors.ts b/apps/desktop/src/updates/selectors.ts
index 5d63c589..c614bc91 100644
--- a/apps/desktop/src/updates/selectors.ts
+++ b/apps/desktop/src/updates/selectors.ts
@@ -93,6 +93,17 @@ export function itemsOf(s: Snapshot, connections: Connection[], now: number): Up
return items;
}
+/** What "Update everything" updates: this app and every server that can update itself and isn't already. */
+export function updatableOf(items: UpdateItem[], s: Snapshot): UpdateItem[] {
+ return items.filter((i) => {
+ if (!i.next) return false;
+ if (i.kind === "desktop") return s.desktop.phase !== "installing";
+ const e = s.servers[i.connection!.id];
+ const a = e?.action;
+ return !!e?.info?.canSelfUpdate && !!a && (a.phase === "idle" || a.phase === "error" || (a.phase === "finished" && a.job.state !== "done"));
+ });
+}
+
/** 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 }
diff --git a/apps/desktop/src/updates/store.ts b/apps/desktop/src/updates/store.ts
index 37e7c29b..cbcb3c1f 100644
--- a/apps/desktop/src/updates/store.ts
+++ b/apps/desktop/src/updates/store.ts
@@ -18,7 +18,8 @@ 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 { approvalStatus, cancelServerUpdate, fetchServerUpdates, serverVersion, startServerUpdate, ServerError } from "./server";
+import { itemsOf, updatableOf, type UpdateItem } from "./selectors";
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";
@@ -130,6 +131,10 @@ interface UpdatesState {
whatsNew: WhatsNew | null;
lastFullCheck: number;
checking: boolean;
+ /** The last check the user asked for: what it found, for "Everything is up to date" / "2 updates found". */
+ manualCheck: { at: number; found: number } | null;
+ /** "Update everything" is running: servers first, then this app restarts once they're done. */
+ updatingAll: boolean;
setPrefs(patch: Partial<UpdatePrefs>): void;
setPanel(open: boolean): void;
@@ -151,6 +156,8 @@ export const useUpdates = create<UpdatesState>((set, get) => ({
whatsNew: null,
lastFullCheck: 0,
checking: false,
+ manualCheck: null,
+ updatingAll: false,
setPrefs: (patch) => {
const prefs = { ...get().prefs, ...patch };
@@ -193,7 +200,8 @@ export async function initUpdates(): Promise<void> {
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 phase = p.phase === "ready" ? "ready" : p.phase === "error" ? d.phase : p.phase === "cancelled" ? "idle" : "downloading";
+ useUpdates.setState({ desktop: { ...d, progress: p.phase === "cancelled" ? null : p, phase } });
});
}
const status = await updatesNative.status().catch(() => null);
@@ -217,11 +225,66 @@ export async function checkAll(force = false): Promise<void> {
if (manifest) useUpdates.setState({ manifest });
await Promise.allSettled([checkDesktop(), ...useConnections.getState().connections.map((c) => checkServer(c, force))]);
announce();
+ if (force) useUpdates.setState({ manualCheck: { at: Date.now(), found: updatableNow().length } });
} finally {
useUpdates.setState({ checking: false });
}
}
+/** What "Update everything" would update now: this app and every server that can update itself. */
+export function updatableNow(): UpdateItem[] {
+ const s = useUpdates.getState();
+ return updatableOf(itemsOf(s, useConnections.getState().connections, Date.now()), s);
+}
+
+/** Check now, and update whatever was found. */
+export async function checkAndUpdateAll(): Promise<void> {
+ await checkAll(true);
+ await updateEverything();
+}
+
+/**
+ * Every server that can update itself starts (owner approval where needed);
+ * this app downloads meanwhile and restarts last, once the servers are done,
+ * so their progress is never cut off halfway. A reply running here keeps the
+ * restart waiting for the user (the panel's "Restart to update").
+ */
+export async function updateEverything(): Promise<void> {
+ if (useUpdates.getState().updatingAll) return;
+ const items = updatableNow();
+ if (!items.length) return;
+ useUpdates.setState({ updatingAll: true, panelOpen: true });
+ try {
+ const servers = items.filter((i) => i.kind === "server").map((i) => updateServer(i.connection!));
+ const desktopItem = items.find((i) => i.kind === "desktop");
+ const downloaded = desktopItem
+ ? useUpdates.getState().desktop.available?.ready ? Promise.resolve(true) : downloadDesktop()
+ : Promise.resolve(false);
+ const [, ready] = await Promise.all([Promise.allSettled(servers), downloaded]);
+ if (!desktopItem || !ready || !useUpdates.getState().updatingAll) return;
+ const a = useRuntimeState.getState().agent;
+ if (a === "thinking" || a === "streaming" || a === "working" || a === "needs-you") return;
+ await installDesktop();
+ } finally {
+ useUpdates.setState({ updatingAll: false });
+ }
+}
+
+/** Stop a desktop download (keeps its bytes) and an "Update everything" waiting on it. */
+export async function cancelDesktopDownload(): Promise<void> {
+ useUpdates.setState({ updatingAll: false });
+ await updatesNative.cancel().catch(() => {});
+}
+
+/** Cancel a server update that hasn't stopped Mercury yet. */
+export async function cancelServer(conn: Connection): Promise<void> {
+ try {
+ await cancelServerUpdate(conn);
+ } catch (err) {
+ useUpdates.getState().setServer(conn.id, { action: { phase: "error", message: err instanceof Error ? err.message : String(err) } });
+ }
+}
+
export async function checkDesktop(): Promise<void> {
const s = useUpdates.getState();
if (s.desktop.phase === "downloading" || s.desktop.phase === "installing") return;
@@ -259,6 +322,13 @@ export async function downloadDesktop(): Promise<boolean> {
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (message === "Already downloading.") return false;
+ if (message === "Download cancelled.") {
+ // Not a failure: the bytes stay and "Resume download" picks up from there.
+ const cur = useUpdates.getState();
+ useUpdates.setState({ desktop: { ...cur.desktop, phase: "idle", progress: null, error: null, available: cur.desktop.available ? { ...cur.desktop.available } : null } });
+ void checkDesktop();
+ 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 } } });
diff --git a/apps/desktop/src/updates/types.ts b/apps/desktop/src/updates/types.ts
index 83423315..3d0eb5aa 100644
--- a/apps/desktop/src/updates/types.ts
+++ b/apps/desktop/src/updates/types.ts
@@ -66,7 +66,7 @@ export interface DesktopUpdateStatus {
}
export interface DownloadProgress {
- phase: "downloading" | "verifying" | "ready" | "retrying" | "error";
+ phase: "downloading" | "verifying" | "ready" | "retrying" | "error" | "cancelled";
version: string;
downloaded: number;
total: number | null;
diff --git a/apps/desktop/src/updates/useUpdateView.ts b/apps/desktop/src/updates/useUpdateView.ts
index 21237668..ec4828f0 100644
--- a/apps/desktop/src/updates/useUpdateView.ts
+++ b/apps/desktop/src/updates/useUpdateView.ts
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { useConnections } from "~/shell/connections";
import { useUpdates, LAUNCH_ID } from "./store";
-import { bannerMessages, buttonOf, forceOf, itemsOf } from "./selectors";
+import { bannerMessages, buttonOf, forceOf, itemsOf, updatableOf } 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 {
@@ -27,6 +27,7 @@ export function useUpdateView() {
const items = itemsOf(snap, connections, now);
return {
items,
+ updatable: updatableOf(items, snap),
button: buttonOf(items, desktop.phase === "ready"),
force: forceOf(items, activeId, acks, LAUNCH_ID, now),
banners: bannerMessages(snap, now),