Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): T3-style in-app updates on macOS, Windows and Linux (CUA-1780) (#5326)

Francesco Bonaccia6de100971b2
diff --git a/apps/cua-spaces-desktop/README.md b/apps/cua-spaces-desktop/README.md
index 32496ce311..96cb94e187 100644
--- a/apps/cua-spaces-desktop/README.md
+++ b/apps/cua-spaces-desktop/README.md
@@ -97,7 +97,7 @@ numbers will grow once the real web UI replaces the placeholder.
| `src/system.ts`, `src/login-item.ts` | The bridge's system services: links and settings panes, Show in Finder / Explorer, notifications, the owner check before approving a device, launch at login on each system |
| `src/migrate-swift.ts` | macOS: takes over the Swift app's settings once (files, defaults domain) |
| `src/notch.ts`, `src/notch/` | The macOS notch: the app core's notch model and the Swift helper that draws it (see "The macOS notch") |
-| `src/updater.ts` | electron-updater behind Settings → About (automatic checks and installs, the channel, Check Now with its own windows), beta channel only until the Sparkle cutover, off by default |
+| `src/updater.ts` | electron-updater behind Settings → About (checks on launch and every few hours, on by default; background download; the in-app "Restart to update" indicator through `update.get` and `update.install`; the channel; Check Now), beta channel only until the Sparkle cutover on macOS |
| `scripts/sparkle/` | Sparkle's own update checks against an Electron build (`accepts.sh`, `selftest.sh`; [docs/sparkle-cutover.md](docs/sparkle-cutover.md)) |
| `scripts/feed-urls.mjs` | Makes a feed's installer URLs absolute (CI) |
| `scripts/smoke/` | Linux and Windows package checks in Docker |
diff --git a/apps/cua-spaces-desktop/docs/sparkle-cutover.md b/apps/cua-spaces-desktop/docs/sparkle-cutover.md
index 372a0f0689..33b259a2a5 100644
--- a/apps/cua-spaces-desktop/docs/sparkle-cutover.md
+++ b/apps/cua-spaces-desktop/docs/sparkle-cutover.md
@@ -82,15 +82,16 @@ Those are the rehearsal below.
Linux, and on macOS only after the cutover") asserts the old value; it
changes in the same commit, or electron-mac's tests fail before the
build.
-3. Migrated users update on their own (`src/update-prefs.ts`, done). Until
- the user chooses in Settings → About, automatic checks are on when
- `swiftMigration.found` is true and `sparkleAutomaticChecks !== false`
- (the Swift app's Info.plist turns Sparkle's checks on, so the key is only
- saved when the user changed it), and automatic installs follow
- `sparkleAutomaticDownloads`. A channel carried over from the Swift app
- that isn't served to the Electron app on macOS (Stable, before
- `STABLE_FEED`) falls back to the build's channel. Everyone else stays
- opt-in.
+3. Migrated users update on their own (`src/update-prefs.ts`, done).
+ Automatic checks are on for everyone, migrated or not, unless the user
+ turned them off in Settings → About or had turned them off in the Swift
+ app (`swiftMigration.found` with `sparkleAutomaticChecks === false`; the
+ Swift app's Info.plist turns Sparkle's checks on, so the key is only saved
+ when the user changed it). Found updates download in the background and
+ show the in-app "Restart to update" indicator; nothing restarts without a
+ click. A channel carried over from the Swift app that isn't served to the
+ Electron app on macOS (Stable, before `STABLE_FEED`) falls back to the
+ build's channel.
4. electron-builder sets `generateUpdatesFilesForAllChannels: true` from the
cutover on. Stable releases then also write `beta*.yml`, so betas move
on to the stable release.
diff --git a/apps/cua-spaces-desktop/src/bridge/about.ts b/apps/cua-spaces-desktop/src/bridge/about.ts
index 9c51776246..300860a2a3 100644
--- a/apps/cua-spaces-desktop/src/bridge/about.ts
+++ b/apps/cua-spaces-desktop/src/bridge/about.ts
@@ -3,7 +3,8 @@
// Settings → About and launch at login (`about.*`, `loginItem.*`): the
// updater's controls, channel and checks (the SwiftUI host's
-// `UpdatesModel`; here electron-updater, `src/updater.ts`), and the login
+// `UpdatesModel`; here electron-updater, `src/updater.ts`), the in-app
+// update indicator's state and "Restart to update" (`update.*`), and the login
// item (`LoginItem`; here Electron's login item settings on macOS and
// Windows, an autostart entry on Linux, `src/login-item.ts`).
import { bool } from "./args";
@@ -34,6 +35,14 @@ export function aboutMethods(ctx: BridgeContext): Handlers {
if (typeof args.channel === "string") u.choose(args.channel);
return encode(u.input);
},
+ // The in-app update indicator: a development run has no updater, so it is idle.
+ "update.get": () => encode(updates().updateState),
+ "update.install": () => {
+ const u = updates();
+ // The updater quits the app to install: answer first, then start it.
+ if (u.updateState.status === "downloaded") setTimeout(() => u.installUpdate(), 0);
+ return encode(u.updateState);
+ },
"about.checkNow": () => {
const u = withUpdater();
// The result is the updater's own window: start the check after this
diff --git a/apps/cua-spaces-desktop/src/bridge/host-parts.ts b/apps/cua-spaces-desktop/src/bridge/host-parts.ts
index 58bc42440b..08bca35a8f 100644
--- a/apps/cua-spaces-desktop/src/bridge/host-parts.ts
+++ b/apps/cua-spaces-desktop/src/bridge/host-parts.ts
@@ -51,27 +51,46 @@ async function runsAgents(model: AppModel): Promise<boolean> {
return model.agents.persistent.count > 0;
}
-export function hostParts(ctx: BridgeContext): HostParts {
- const known = parts.get(ctx.model);
+const updatesModels = new WeakMap<AppModel, UpdatesModel>();
+
+/**
+ * The updater's model, made once per app model. The bridge asks for it at
+ * start (to tell the page when the updater moves on) without making the
+ * other parts, which read their own state when first asked.
+ */
+export function updatesModel(ctx: BridgeContext): UpdatesModel {
+ const known = updatesModels.get(ctx.model);
if (known) return known;
const { model, platform } = ctx;
- const native = model.native;
const system = ctx.system ?? null;
- const tool = () => (model.servicesIn ? (name: string, args: Record<string, unknown> = {}) => model.backend.tool(name, args) : null);
- const telemetry = model.telemetry;
-
const updates = new UpdatesModel(
- native,
+ model.native,
system?.updater ?? null,
{ version: ctx.version, build: ctx.build ?? "", os: osLine(platform, undefined, undefined, systemVersion(platform)) },
- system?.updater?.channel === "beta" ? native.AppUpdateChannel.Beta : system?.updater ? native.AppUpdateChannel.Stable : model.settings.updateChannel,
+ system?.updater?.channel === "beta" ? model.native.AppUpdateChannel.Beta : system?.updater ? model.native.AppUpdateChannel.Stable : model.settings.updateChannel,
(channel) => {
model.settings = { ...model.settings, updateChannel: channel };
model.saveSettings();
},
platform,
);
- updates.telemetry = telemetry;
+ // Read when an event is recorded: the app model is given its telemetry after the bridge starts.
+ updates.telemetry = { record: (signals) => model.telemetry?.record(signals) };
+ updates.subscribe(() => model.changed("update"));
+ updatesModels.set(ctx.model, updates);
+ return updates;
+}
+
+export function hostParts(ctx: BridgeContext): HostParts {
+ const known = parts.get(ctx.model);
+ if (known) return known;
+ const { model, platform } = ctx;
+ const native = model.native;
+ const system = ctx.system ?? null;
+ const tool = () => (model.servicesIn ? (name: string, args: Record<string, unknown> = {}) => model.backend.tool(name, args) : null);
+ const telemetry = model.telemetry;
+
+ const updates = updatesModel(ctx);
const loginItem = new LoginItemModel(
native,
diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.ts
index 90e5c01999..80cde5da48 100644
--- a/apps/cua-spaces-desktop/src/bridge/index.ts
+++ b/apps/cua-spaces-desktop/src/bridge/index.ts
@@ -6,7 +6,7 @@
// SwiftUI host's names (`methods.ts`); this puts them in one table and tells
// the page when what it shows changed (`cua:event`: `spaces.changed`,
// `machines.changed`, `keyvault.changed`, `session.changed`, `settings.changed`,
-// `checklist.changed`, `startup.changed`, `spaces.createProgress`). `ipc.ts` carries it over
+// `checklist.changed`, `update.changed`, `startup.changed`, `spaces.createProgress`). `ipc.ts` carries it over
// Electron's IPC.
import { aboutMethods } from "./about";
import { agentKeysMethods } from "./agent-keys";
@@ -18,6 +18,7 @@ import type { BridgeContext } from "./context";
import { devicesMethods } from "./devices";
import { filesMethods } from "./files";
import { BridgeEvents, BridgeRegistry } from "./host";
+import { updatesModel } from "./host-parts";
import { hostSetupMethods } from "./host-setup";
import { joinMethods } from "./join-with-code";
import { keyvaultMethods } from "./keyvault";
@@ -114,6 +115,8 @@ function followModel(ctx: BridgeContext): () => void {
// The broker's overview, whether an action is running, and the copies dismissed from the notch.
"keyvault.changed": () => [encode(model.keyvault.overview), model.keyvault.busy, model.keyvault.dismissed],
"checklist.changed": () => model.checklist.stored,
+ // Where the updater is: found, downloading, ready.
+ "update.changed": () => updatesModel(ctx).updateState,
};
const byChange: Record<string, string> = {
spaces: "spaces.changed",
@@ -123,6 +126,7 @@ function followModel(ctx: BridgeContext): () => void {
agents: "agents.changed",
keyvault: "keyvault.changed",
checklist: "checklist.changed",
+ update: "update.changed",
};
const last = new Map<string, string>(Object.entries(read).map(([e, f]) => [e, signature(f())]));
const due = new Set<string>();
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index c8762cacce..d5d13ab954 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -26,7 +26,7 @@ export const METHODS = [
"volume.overview", "volume.storage", "volume.storageSet", "volume.mount", "volume.unmount",
"volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal",
"agents.setupDriver",
- "about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
+ "about.get", "about.set", "about.checkNow", "update.get", "update.install", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
"devices.revokePairingCode", "teams.list", "storage.get", "storage.run",
diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.ts
index e363a791bb..4d0c75fb58 100644
--- a/apps/cua-spaces-desktop/src/model/app-model.ts
+++ b/apps/cua-spaces-desktop/src/model/app-model.ts
@@ -52,7 +52,7 @@ import type { RuntimeFix, RuntimeFixAction, WindowsRuntime, WindowsRuntimeAdvice
import { TimeoutError, sleep, withTimeout } from "./time";
/** What changed, for the page's events. */
-export type ModelChange = "spaces" | "session" | "settings" | "machines" | "agents" | "keyvault" | "checklist";
+export type ModelChange = "spaces" | "session" | "settings" | "machines" | "agents" | "keyvault" | "checklist" | "update";
export interface AppModelDeps {
native: Native;
diff --git a/apps/cua-spaces-desktop/src/model/updates.ts b/apps/cua-spaces-desktop/src/model/updates.ts
index a226019304..ce8a028eb8 100644
--- a/apps/cua-spaces-desktop/src/model/updates.ts
+++ b/apps/cua-spaces-desktop/src/model/updates.ts
@@ -9,6 +9,7 @@
import * as os from "node:os";
import type { AppAboutInput, AppTelemetrySignal, AppUpdateChannel } from "../native/generated/index";
import type { Native } from "../native/load";
+import { initialUpdateState, reduceUpdate, type UpdateEvent, type UpdateStateValue } from "../update-state";
/** What About drives: electron-updater in a packaged app, an in-memory one in tests. */
export interface UpdaterDriving {
@@ -24,10 +25,14 @@ export interface UpdaterDriving {
channel: "stable" | "beta";
/** Called after any of the above changes. */
onChange: (() => void) | null;
- /** Told each step: `found`, `not_found`, `installed` or `failed` (fixed words). */
+ /** Told each step: `found`, `not_found`, `downloaded`, `installed` or `failed` (fixed words). */
onUpdateEvent: ((event: string) => void) | null;
- /** Checks now, with its own windows for what it found. */
+ /** Checks now; what it finds shows in the in-app indicator (a failure of this check, in a window). */
checkNow(): void;
+ /** Where the update is (found, downloading, ready): the in-app indicator. */
+ readonly state: UpdateStateValue;
+ /** "Restart to update": installs the downloaded update and relaunches. Only a click calls it. */
+ installNow(): void;
}
/** An in-memory updater (tests): nothing is checked or stored. */
@@ -42,6 +47,9 @@ export class FixtureUpdater implements UpdaterDriving {
checks = 0;
/** What the next check finds. */
nextResult = "not_found";
+ state: UpdateStateValue = initialUpdateState("0.0.0");
+ /** How many times "Restart to update" ran. */
+ installs = 0;
constructor(lastCheck: number | null = null) {
this.lastCheck = lastCheck;
}
@@ -51,6 +59,17 @@ export class FixtureUpdater implements UpdaterDriving {
this.onUpdateEvent?.(this.nextResult);
this.onChange?.();
}
+ /** Feeds what electron-updater would report (tests). */
+ report(event: UpdateEvent, word?: string) {
+ this.state = reduceUpdate(this.state, event);
+ if (word) this.onUpdateEvent?.(word);
+ this.onChange?.();
+ }
+ installNow() {
+ if (this.state.status !== "downloaded") return;
+ this.installs += 1;
+ this.onUpdateEvent?.("installed");
+ }
}
/** The version and machine lines the pane shows. */
@@ -119,6 +138,16 @@ export class UpdatesModel {
for (const l of [...this.listeners]) l();
}
+ /** The in-app indicator's state; idle with no updater (a development run). */
+ get updateState(): UpdateStateValue {
+ return this.updater?.state ?? initialUpdateState(this.info.version);
+ }
+
+ /** "Restart to update". */
+ installUpdate(): void {
+ this.updater?.installNow();
+ }
+
get channelWord(): "stable" | "beta" {
return this.channel === this.native.AppUpdateChannel.Beta ? "beta" : "stable";
}
diff --git a/apps/cua-spaces-desktop/src/update-prefs.ts b/apps/cua-spaces-desktop/src/update-prefs.ts
index 1aedbc0119..7bdf5508d9 100644
--- a/apps/cua-spaces-desktop/src/update-prefs.ts
+++ b/apps/cua-spaces-desktop/src/update-prefs.ts
@@ -4,28 +4,33 @@
// What the updater (updater.ts) does when the user hasn't chosen in this
// app. Kept free of Electron so it can be tested on its own.
//
-// Someone who moved over from the Swift app (migrate-swift.ts) keeps what
-// Sparkle did for them there: automatic checks stay on unless they had turned
-// them off (the Swift app's Info.plist sets SUEnableAutomaticChecks, so the
-// defaults domain only holds the key when the user changed it), and
-// automatic installs stay as they had them. Everyone else stays opt-in.
+// Automatic checks are on unless the user turned them off in this app, or in
+// the Swift app they moved over from (migrate-swift.ts: the Swift app's
+// Info.plist sets SUEnableAutomaticChecks, so the defaults domain only holds
+// the key when the user changed it). An update found by a check downloads in
+// the background; the in-app indicator then offers "Restart to update", and
+// nothing restarts without that click.
import type { Settings } from "./settings";
export type UpdateChannel = "stable" | "beta";
const movedFromSwift = (s: Settings) => s.swiftMigration?.found === true;
-/** Automatic checks: the choice made in this app, else the one carried over from Sparkle, else off. */
+/** Automatic checks: the choice made in this app, else the one carried over from Sparkle, else on. */
export function autoCheckPref(s: Settings, env: NodeJS.ProcessEnv = {}): boolean {
if (env.CUA_SPACES_AUTO_UPDATE === "1") return true;
if (typeof s.autoUpdate === "boolean") return s.autoUpdate;
- return movedFromSwift(s) && s.swiftMigration?.sparkleAutomaticChecks !== false;
+ return !movedFromSwift(s) || s.swiftMigration?.sparkleAutomaticChecks !== false;
}
-/** Automatic installs: the choice made in this app, else the one carried over from Sparkle (off by default there too). */
+/**
+ * Install a downloaded update when the app next quits (never a restart on
+ * its own): the choice made in this app, else on. Sparkle's "download
+ * automatically" was a different question (it is what the update waits for,
+ * and now every update downloads in the background), so it is not carried over.
+ */
export function autoInstallPref(s: Settings): boolean {
- if (typeof s.autoInstall === "boolean") return s.autoInstall;
- return movedFromSwift(s) && s.swiftMigration?.sparkleAutomaticDownloads === true;
+ return typeof s.autoInstall === "boolean" ? s.autoInstall : true;
}
/**
diff --git a/apps/cua-spaces-desktop/src/update-state.ts b/apps/cua-spaces-desktop/src/update-state.ts
new file mode 100644
index 0000000000..b301dab85a
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/update-state.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Where an update is, for the in-app indicator (the page's `update.get`).
+// A pure state machine over what electron-updater reports, kept free of
+// Electron so it can be tested on its own. The idea is T3 Code's updater
+// (github.com/pingdotgg/t3code, apps/desktop/src/updates/updateMachine.ts):
+// a downloaded update is never lost to a later check, a failed background
+// step is quiet, and nothing installs without the user's click.
+
+export type UpdateStatus = "idle" | "checking" | "available" | "downloading" | "downloaded" | "error";
+
+/** The `UpdateState` the page reads (apps/cua-spaces-web/src/bridge/contracts/settings.ts). */
+export interface UpdateStateValue {
+ status: UpdateStatus;
+ /** The version this app runs. */
+ currentVersion: string;
+ /** The version found, downloading or ready; null with none. */
+ version: string | null;
+ /** 0 to 100 while downloading; else null. */
+ percent: number | null;
+ /** The GitHub release notes page for `version`. */
+ notesUrl: string | null;
+ /** Why the last step failed (`error` only). */
+ message: string | null;
+}
+
+/** A background check waits this long after launch, so it never competes with starting up. */
+export const UPDATE_STARTUP_DELAY_MS = 15_000;
+/** And repeats at this pace while the app stays open. */
+export const UPDATE_POLL_MS = 4 * 60 * 60 * 1000;
+
+const RELEASES = "https://github.com/trycua/cua/releases/tag";
+
+/** The release notes for a version: the repository's `cua-spaces-v<version>` tag. */
+export function releaseNotesUrl(version: string): string {
+ return `${RELEASES}/cua-spaces-v${encodeURIComponent(version.trim())}`;
+}
+
+export const initialUpdateState = (currentVersion: string): UpdateStateValue => ({
+ status: "idle",
+ currentVersion,
+ version: null,
+ percent: null,
+ notesUrl: null,
+ message: null,
+});
+
+export type UpdateEvent =
+ | { type: "checking" }
+ | { type: "available"; version: string }
+ | { type: "progress"; percent: number }
+ | { type: "downloaded"; version: string }
+ | { type: "none" }
+ | { type: "error"; message: string };
+
+const downloadedState = (s: UpdateStateValue, version: string): UpdateStateValue => ({
+ ...s,
+ status: "downloaded",
+ version,
+ percent: 100,
+ notesUrl: releaseNotesUrl(version),
+ message: null,
+});
+
+/** The next state. A downloaded update stays downloaded through later checks and failures. */
+export function reduceUpdate(s: UpdateStateValue, e: UpdateEvent): UpdateStateValue {
+ const downloaded = s.status === "downloaded" && s.version !== null;
+ switch (e.type) {
+ case "checking":
+ // A found or running update is not hidden by the next check.
+ return s.status === "idle" || s.status === "error" ? { ...s, status: "checking", message: null } : s;
+ case "available":
+ if (downloaded && s.version === e.version) return s;
+ // A newer one than the one downloaded replaces it: its download starts now.
+ return { ...s, status: "available", version: e.version, percent: null, notesUrl: releaseNotesUrl(e.version), message: null };
+ case "progress":
+ if (downloaded) return s;
+ return { ...s, status: "downloading", percent: Math.max(0, Math.min(100, e.percent)), message: null };
+ case "downloaded":
+ return downloadedState(s, e.version);
+ case "none":
+ return downloaded ? s : { ...initialUpdateState(s.currentVersion) };
+ case "error":
+ // The downloaded update is still good; a failed check or download is the next poll's to retry.
+ return downloaded ? s : { ...s, status: "error", percent: null, message: e.message };
+ }
+}
diff --git a/apps/cua-spaces-desktop/src/updater.ts b/apps/cua-spaces-desktop/src/updater.ts
index 3fbdeb308e..f2bca479e9 100644
--- a/apps/cua-spaces-desktop/src/updater.ts
+++ b/apps/cua-spaces-desktop/src/updater.ts
@@ -5,14 +5,17 @@
// app-update.yml: the rolling `cua-spaces-latest` release of the repository
// the build came from (electron-builder.config.cjs). It stands where Sparkle
// does in the Swift app (Settings → About, `model/updates.ts`): automatic
-// checks, automatic installs, the channel, Check Now with its own windows
-// for what it found, and the last check.
+// checks, the channel, Check Now, and the last check.
//
-// Opt-in: nothing checks on its own unless the user turns automatic checks
-// on (Settings → About, `"autoUpdate": true` in settings.json, or
-// CUA_SPACES_AUTO_UPDATE=1). Someone who moved over from the Swift app keeps
-// Sparkle's choices instead (update-prefs.ts): checks on unless they had
-// turned them off there. The beta channel (prereleases, `beta*.yml`) is
+// The update UX is T3 Code's: a check on launch (after a short delay) and
+// every few hours, ON by default (update-prefs.ts: only an explicit off in
+// Settings → About, `"autoUpdate": false` in settings.json, or an off carried
+// over from Sparkle stops it). A found update downloads in the background,
+// with no window; the page's quiet in-app indicator (`update.get`) shows
+// "Update ready" with "Restart to update" and a link to the release notes.
+// Nothing restarts without that click (`installNow`); a downloaded update is
+// also applied when the app next quits unless "install automatically" is
+// off. The state machine is update-state.ts. The beta channel (prereleases, `beta*.yml`) is
// served everywhere. The stable channel (`latest*.yml`) is served on Windows
// and Linux, where stable releases ship the Electron app. On macOS stable
// releases still ship the Swift app, updated by Sparkle; Check Now on Stable
@@ -26,11 +29,10 @@ import { recordUpdateChannel } from "./mesh-channel";
import type { UpdaterDriving } from "./model/updates";
import { readSettings, writeSettings } from "./settings";
import { autoCheckPref, autoInstallPref, channelPref, type UpdateChannel } from "./update-prefs";
+import { initialUpdateState, reduceUpdate, UPDATE_POLL_MS, UPDATE_STARTUP_DELAY_MS, type UpdateEvent, type UpdateStateValue } from "./update-state";
export type { UpdateChannel } from "./update-prefs";
-const POLL_MS = 4 * 60 * 60 * 1000;
-
/** macOS only: off until stable releases publish the Electron macOS feed (the cutover). */
export const STABLE_FEED = false;
@@ -76,6 +78,9 @@ export class ElectronUpdater implements UpdaterDriving {
/** The check the user started shows "up to date" and errors; a background one only what it found. */
private userCheck = false;
private poll: NodeJS.Timeout | null = null;
+ private startup: NodeJS.Timeout | null = null;
+ state: UpdateStateValue = initialUpdateState(app.getVersion());
+ private installing = false;
private loaded: Promise<AutoUpdater> | null = null;
private listening = false;
/** This check's failure was reported (electron-updater both emits and rejects). */
@@ -105,7 +110,7 @@ export class ElectronUpdater implements UpdaterDriving {
}
set automaticallyInstalls(on: boolean) {
writeSettings({ autoInstall: on });
- void this.updater().then((u) => (u.autoDownload = on));
+ void this.updater().then((u) => (u.autoInstallOnAppQuit = on));
this.onChange?.();
}
@@ -144,13 +149,36 @@ export class ElectronUpdater implements UpdaterDriving {
void this.check();
}
- /** Background checks every few hours while automatic checks are on and the channel is served. */
+ /** Feeds the state machine; the page hears of a change. */
+ private report(event: UpdateEvent): void {
+ const next = reduceUpdate(this.state, event);
+ if (next === this.state) return;
+ this.state = next;
+ this.onChange?.();
+ }
+
+ /** "Restart to update": the only way an update restarts the app. */
+ installNow(): void {
+ if (this.installing || this.state.status !== "downloaded") return;
+ this.installing = true;
+ this.onUpdateEvent?.("installed");
+ void this.updater()
+ .then((u) => u.quitAndInstall())
+ .catch((e: unknown) => {
+ this.installing = false;
+ this.failed(e instanceof Error ? e : new Error(String(e)), true);
+ });
+ }
+
+ /** A check shortly after launch, then every few hours, while automatic checks are on and the channel is served. */
private schedule(): void {
if (this.poll) clearInterval(this.poll);
- this.poll = null;
+ if (this.startup) clearTimeout(this.startup);
+ this.poll = this.startup = null;
if (!this.automaticallyChecks || !channelServed(this.channel)) return;
- void this.check();
- this.poll = setInterval(() => void this.check(), POLL_MS);
+ this.startup = setTimeout(() => void this.check(), UPDATE_STARTUP_DELAY_MS);
+ this.startup.unref();
+ this.poll = setInterval(() => void this.check(), UPDATE_POLL_MS);
this.poll.unref();
}
@@ -163,13 +191,16 @@ export class ElectronUpdater implements UpdaterDriving {
// so betas move on to the next stable); stable never sees a beta.
autoUpdater.allowPrerelease = channel === "beta";
autoUpdater.allowDowngrade = false;
- autoUpdater.autoDownload = this.automaticallyInstalls;
- autoUpdater.autoInstallOnAppQuit = true;
+ // Found updates download in the background; they install on a click, or on quit when allowed.
+ autoUpdater.autoDownload = true;
+ autoUpdater.autoInstallOnAppQuit = this.automaticallyInstalls;
if (!this.listening) {
this.listening = true;
- autoUpdater.on("update-available", (i) => void this.found(i.version));
+ autoUpdater.on("checking-for-update", () => this.report({ type: "checking" }));
+ autoUpdater.on("update-available", (i) => this.found(i.version));
autoUpdater.on("update-not-available", () => this.notFound());
- autoUpdater.on("update-downloaded", (i) => void this.downloaded(i.version));
+ autoUpdater.on("download-progress", (p) => this.report({ type: "progress", percent: p.percent }));
+ autoUpdater.on("update-downloaded", (i) => this.downloaded(i.version));
autoUpdater.on("error", (e) => this.failed(e));
}
return autoUpdater;
@@ -190,59 +221,39 @@ export class ElectronUpdater implements UpdaterDriving {
} finally {
writeSettings({ lastUpdateCheck: Date.now() });
this.checking = false;
+ // A check that ended without saying anything found nothing.
+ if (this.state.status === "checking") this.report({ type: "none" });
this.onChange?.();
}
}
- private async found(version: string): Promise<void> {
+ private found(version: string): void {
this.onUpdateEvent?.("found");
- const user = this.userCheck;
this.userCheck = false;
- if (this.automaticallyInstalls) return; // Downloading; `downloaded` asks to relaunch.
- const choice = await message({
- type: "info",
- message: "A new version of Cua Spaces is available!",
- detail: `Cua Spaces ${version} is now available—you have ${app.getVersion()}. Would you like to download it now?`,
- buttons: ["Install Update", user ? "Not Now" : "Remind Me Later"],
- defaultId: 0,
- cancelId: 1,
- });
- if (choice === 0) void (await this.updater()).downloadUpdate().catch((e: unknown) => this.failed(e instanceof Error ? e : new Error(String(e))));
+ this.report({ type: "available", version });
}
private notFound(): void {
this.onUpdateEvent?.("not_found");
- if (!this.userCheck) return;
+ // Silent: Settings → About shows the check's time, and an update shows in the indicator.
this.userCheck = false;
- void message({
- type: "info",
- message: "You’re up to date!",
- detail: `Cua Spaces ${app.getVersion()} is currently the newest version available.`,
- buttons: ["OK"],
- });
- }
-
- private async downloaded(version: string): Promise<void> {
- const choice = await message({
- type: "info",
- message: "Ready to Install",
- detail: `Cua Spaces ${version} has been downloaded and is ready to use! Would you like to install it and relaunch Cua Spaces now?`,
- buttons: ["Install and Relaunch", "Install on Quit"],
- defaultId: 0,
- cancelId: 1,
- });
- if (choice !== 0) return;
- this.onUpdateEvent?.("installed");
- (await this.updater()).quitAndInstall();
+ this.report({ type: "none" });
+ }
+
+ private downloaded(version: string): void {
+ this.onUpdateEvent?.("downloaded");
+ this.report({ type: "downloaded", version });
}
- private failed(error: Error): void {
+ /** `install`: the click's own failure, which gets a window like a failed Check Now. */
+ private failed(error: Error, install = false): void {
this.reported = true;
this.onUpdateEvent?.("failed");
- const user = this.userCheck;
+ const user = this.userCheck || install;
this.userCheck = false;
console.warn(`[cua-spaces] update: ${error.message}`);
+ this.report({ type: "error", message: error.message });
if (!user) return;
- void message({ type: "warning", message: "Update Error!", detail: `An error occurred while checking for updates: ${error.message}`, buttons: ["OK"] });
+ void message({ type: "warning", message: "Update Error!", detail: `An error occurred while updating: ${error.message}`, buttons: ["OK"] });
}
}
diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.ts
index 79c62a4cad..01d8380506 100644
--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts
+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts
@@ -180,6 +180,8 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
["about.get", {}],
["about.set", { channel: "beta" }],
["about.checkNow", {}],
+ ["update.get", {}],
+ ["update.install", {}],
["loginItem.get", {}],
["loginItem.set", { on: true }],
["loginItem.openSettings", {}],
@@ -630,6 +632,37 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
expect(await code("about.checkNow")).toBe("unsupported");
});
+ it("the update indicator reads the updater, installs only when asked, and the page hears of each change", async () => {
+ expect(await call("update.get")).toMatchObject({ status: "idle", version: null, percent: null });
+ system.updater.report({ type: "available", version: "0.9.3" }, "found");
+ system.updater.report({ type: "progress", percent: 40 });
+ await tick(5);
+ expect(await call("update.get")).toMatchObject({ status: "downloading", version: "0.9.3", percent: 40 });
+ // Nothing is installed while it downloads, or when the page asks early.
+ await call("update.install");
+ await tick(5);
+ expect(system.updater.installs).toBe(0);
+ system.updater.report({ type: "downloaded", version: "0.9.3" }, "downloaded");
+ await tick(5);
+ expect(events.some((e) => e.event === "update.changed")).toBe(true);
+ expect(await call("update.get")).toMatchObject({ status: "downloaded", version: "0.9.3", percent: 100, notesUrl: "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3" });
+ expect(system.updater.installs).toBe(0);
+ const answer = await call("update.install");
+ expect((answer as { status: string }).status).toBe("downloaded");
+ await tick(5);
+ expect(system.updater.installs).toBe(1);
+ });
+
+ it("records found, downloaded and installed as updater steps", async () => {
+ const telemetry = model.telemetry as FixtureTelemetry;
+ const before = telemetry.recorded.length;
+ system.updater.report({ type: "available", version: "0.9.3" }, "found");
+ system.updater.report({ type: "downloaded", version: "0.9.3" }, "downloaded");
+ system.updater.installNow();
+ const actions = telemetry.recorded.slice(before).map((s) => (s as unknown as { inner: { action: string } }).inner.action);
+ expect(actions).toEqual(["checked", "found", "downloaded", "installed"]);
+ });
+
it("About carries the bundle's build, for \"Version 0.7.2 (0.7.2.41)\" as the SwiftUI app shows it", async () => {
await make({ build: "1.2.3.41" });
expect(((await call("about.get")) as Record<string, unknown>).build).toBe("1.2.3.41");
diff --git a/apps/cua-spaces-desktop/test/host-fixtures.ts b/apps/cua-spaces-desktop/test/host-fixtures.ts
index 9306098127..a3c1857df0 100644
--- a/apps/cua-spaces-desktop/test/host-fixtures.ts
+++ b/apps/cua-spaces-desktop/test/host-fixtures.ts
@@ -303,7 +303,7 @@ export class FixtureSystem implements SystemServices {
export const HOST_METHODS = [
"volume.overview", "volume.storage", "volume.storageSet", "volume.mount", "volume.unmount",
"volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal",
- "about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
+ "about.get", "about.set", "about.checkNow", "update.get", "update.install", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine",
"devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode", "teams.list",
"storage.get", "storage.run", "notifications.list", "notifications.markAllRead", "notifications.markRead",
@@ -315,7 +315,7 @@ export const HOST_METHODS = [
export const HOST_OPS = [
"volume.overview", "volume.storage", "volume.storageSet", "volume.mount", "volume.unmount",
"volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal",
- "about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
+ "about.get", "about.set", "about.checkNow", "update.get", "update.install", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename", "devices.revoke", "devices.confirmMachine",
"devices.createPairingCode", "devices.pairingCodes", "devices.revokePairingCode", "teams.list",
"storage.get", "storage.run", "notifications.list", "notifications.markAllRead", "notifications.markRead",
diff --git a/apps/cua-spaces-desktop/test/update-prefs.test.ts b/apps/cua-spaces-desktop/test/update-prefs.test.ts
index ccaae49ee1..26033d2ebf 100644
--- a/apps/cua-spaces-desktop/test/update-prefs.test.ts
+++ b/apps/cua-spaces-desktop/test/update-prefs.test.ts
@@ -29,20 +29,25 @@ describe("autoCheckPref", () => {
expect(autoCheckPref({ ...moved({ sparkleAutomaticChecks: false }), autoUpdate: true })).toBe(true);
});
- it("stays opt-in everywhere else", () => {
- expect(autoCheckPref({})).toBe(false);
- expect(autoCheckPref(fresh)).toBe(false);
+ it("is on by default for everyone else, and only an explicit off stops it", () => {
+ expect(autoCheckPref({})).toBe(true);
+ expect(autoCheckPref(fresh)).toBe(true);
expect(autoCheckPref({}, { CUA_SPACES_AUTO_UPDATE: "1" })).toBe(true);
expect(autoCheckPref({ autoUpdate: true })).toBe(true);
+ // The 0.9.0 default was off and the box was never touched: that stays off only if it was written.
+ expect(autoCheckPref({ autoUpdate: false })).toBe(false);
+ expect(autoCheckPref({ ...fresh, autoUpdate: false })).toBe(false);
});
});
describe("autoInstallPref", () => {
- it("follows Sparkle's automatic downloads, off by default", () => {
- expect(autoInstallPref(moved())).toBe(false);
- expect(autoInstallPref(moved({ sparkleAutomaticDownloads: true }))).toBe(true);
- expect(autoInstallPref({ ...moved({ sparkleAutomaticDownloads: true }), autoInstall: false })).toBe(false);
- expect(autoInstallPref(fresh)).toBe(false);
+ it("applies a downloaded update when the app quits, unless the user turned that off", () => {
+ expect(autoInstallPref({})).toBe(true);
+ expect(autoInstallPref(fresh)).toBe(true);
+ // Sparkle's "download automatically" was a different question; it is not carried over.
+ expect(autoInstallPref(moved())).toBe(true);
+ expect(autoInstallPref(moved({ sparkleAutomaticDownloads: false }))).toBe(true);
+ expect(autoInstallPref({ autoInstall: false })).toBe(false);
expect(autoInstallPref({ autoInstall: true })).toBe(true);
});
});
diff --git a/apps/cua-spaces-desktop/test/update-state.test.ts b/apps/cua-spaces-desktop/test/update-state.test.ts
new file mode 100644
index 0000000000..c59a8ef474
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/update-state.test.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+import { FixtureUpdater } from "../src/model/updates";
+import { initialUpdateState, reduceUpdate, releaseNotesUrl, UPDATE_POLL_MS, UPDATE_STARTUP_DELAY_MS, type UpdateEvent } from "../src/update-state";
+
+const run = (events: UpdateEvent[], from = initialUpdateState("0.9.2")) => events.reduce(reduceUpdate, from);
+
+describe("the update state machine", () => {
+ it("goes idle, checking, available, downloading, downloaded", () => {
+ let s = initialUpdateState("0.9.2");
+ expect(s).toEqual({ status: "idle", currentVersion: "0.9.2", version: null, percent: null, notesUrl: null, message: null });
+ s = reduceUpdate(s, { type: "checking" });
+ expect(s.status).toBe("checking");
+ s = reduceUpdate(s, { type: "available", version: "0.9.3" });
+ expect(s).toMatchObject({ status: "available", version: "0.9.3", percent: null, notesUrl: "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3" });
+ s = reduceUpdate(s, { type: "progress", percent: 41.5 });
+ expect(s).toMatchObject({ status: "downloading", percent: 41.5 });
+ s = reduceUpdate(s, { type: "downloaded", version: "0.9.3" });
+ expect(s).toMatchObject({ status: "downloaded", version: "0.9.3", percent: 100, message: null });
+ });
+
+ it("keeps a downloaded update through later checks, the same update found again, and failures", () => {
+ const ready = run([{ type: "available", version: "0.9.3" }, { type: "downloaded", version: "0.9.3" }]);
+ expect(run([{ type: "checking" }], ready)).toBe(ready);
+ expect(run([{ type: "none" }], ready)).toBe(ready);
+ expect(run([{ type: "available", version: "0.9.3" }], ready)).toBe(ready);
+ expect(run([{ type: "progress", percent: 10 }], ready)).toBe(ready);
+ expect(run([{ type: "error", message: "offline" }], ready)).toBe(ready);
+ });
+
+ it("downloads a newer update over the one waiting", () => {
+ const ready = run([{ type: "available", version: "0.9.3" }, { type: "downloaded", version: "0.9.3" }]);
+ expect(run([{ type: "available", version: "0.9.4" }], ready)).toMatchObject({ status: "available", version: "0.9.4", percent: null });
+ });
+
+ it("a failure keeps the reason, and the next check starts clean", () => {
+ const failed = run([{ type: "checking" }, { type: "error", message: "offline" }]);
+ expect(failed).toMatchObject({ status: "error", message: "offline" });
+ expect(reduceUpdate(failed, { type: "checking" })).toMatchObject({ status: "checking", message: null });
+ expect(reduceUpdate(failed, { type: "none" })).toEqual(initialUpdateState("0.9.2"));
+ });
+
+ it("does not hide a found or running update behind the next check", () => {
+ const found = run([{ type: "available", version: "0.9.3" }]);
+ expect(reduceUpdate(found, { type: "checking" })).toBe(found);
+ });
+
+ it("keeps the percent in 0 to 100", () => {
+ expect(run([{ type: "progress", percent: 140 }]).percent).toBe(100);
+ expect(run([{ type: "progress", percent: -3 }]).percent).toBe(0);
+ });
+
+ it("points at the repository's release tag", () => {
+ expect(releaseNotesUrl(" 0.9.3-rc.4 ")).toBe("https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3-rc.4");
+ });
+
+ it("checks shortly after launch, and every few hours", () => {
+ expect(UPDATE_STARTUP_DELAY_MS).toBe(15_000);
+ expect(UPDATE_POLL_MS).toBe(4 * 60 * 60 * 1000);
+ });
+});
+
+describe("the fixture updater (what the bridge drives)", () => {
+ it("restarts only when asked, and only with a download", () => {
+ const u = new FixtureUpdater();
+ const words: string[] = [];
+ u.onUpdateEvent = (w) => words.push(w);
+ u.report({ type: "available", version: "0.9.3" }, "found");
+ u.installNow();
+ expect(u.installs).toBe(0);
+ u.report({ type: "progress", percent: 50 });
+ u.report({ type: "downloaded", version: "0.9.3" }, "downloaded");
+ expect(u.installs).toBe(0);
+ u.installNow();
+ expect(u.installs).toBe(1);
+ expect(words).toEqual(["found", "downloaded", "installed"]);
+ });
+});
diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.md
index 520fc61ca1..79dcb53b99 100644
--- a/apps/cua-spaces-macos/README.md
+++ b/apps/cua-spaces-macos/README.md
@@ -118,7 +118,7 @@ with `{id, ok: true, result}` or `{id, ok: false, error: {code, message}}`
`native_only`, `forbidden`, `unsupported`, `failed`). `app.info` lists the
methods. Native events arrive as `cua:event` window events (`spaces.changed`,
`machines.changed`, `keyvault.changed`, `session.changed`, `settings.changed`,
-`agents.changed`, `spaces.createProgress`, `spaces.newRequested`,
+`agents.changed`, `update.changed`, `spaces.createProgress`, `spaces.newRequested`,
`settings.openRequested`). Results are the
core's records as the SwiftUI views get them (camelCase fields; enums as the
case name, or `{type, ...}` with a payload). `keyvault.get` also carries the
@@ -341,7 +341,24 @@ component released last, so a `/releases/latest/download/` URL would not
always be the Spaces feed; a fixed tag always is. The app is outside the App
Sandbox, so it needs no `SUEnableInstallerLauncherService`.
`SUVerifyUpdateBeforeExtraction` checks the signature before anything is
-unpacked.
+unpacked (Sparkle does this whatever the user driver).
+
+Sparkle shows no window of its own. `SparkleUpdater` runs an `SPUUpdater`
+with a custom user driver (`UpdateUserDriver`, over the plain-value
+`UpdateFlow` state machine in `UpdateDriver.swift`). It checks at launch and
+periodically (`SUEnableAutomaticChecks` is on; an explicit off is kept). An
+update found by a scheduled check downloads and extracts at once; Sparkle's
+ready-to-install reply is then held, and nothing restarts the app until the
+page calls `update.install` ("Restart to update"). With "install updates
+automatically" on, Sparkle's silent path reaches the same state through
+`updater(_:willInstallUpdateOnQuit:immediateInstallationBlock:)`. The page
+reads the state with `update.get` (`{status, currentVersion, version,
+percent, notesUrl, message}`; status is `idle`, `checking`, `available`,
+`downloading`, `downloaded` or `error`) and refetches on the `update.changed`
+event. Check Now (Settings, About) is quiet too: nothing found ends silently,
+and only an error from a check the user started shows a small "Update Error!"
+alert; background errors are logged. Usage telemetry records `found`,
+`not_found`, `downloaded`, `installed` and `failed`.
Channels: an `X.Y.Z-suffix` release is a `beta` item, which only apps set to
"Update to: Beta" (`AppSettings.updateChannel`) are offered.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdateDriver.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdateDriver.swift
new file mode 100644
index 0000000000..7fe74e2380
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdateDriver.swift
@@ -0,0 +1,313 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import Foundation
+import Sparkle
+
+/// What the page shows about an update, the JSON behind the bridge's
+/// `update.get`:
+/// `{status, currentVersion, version, percent, notesUrl, message}`.
+public struct UpdateState: Equatable, Sendable {
+ public enum Status: String, Sendable {
+ case idle, checking, available, downloading, downloaded, error
+ }
+
+ public var status: Status
+ /// This app's full version.
+ public var currentVersion: String
+ /// The update's version (the appcast item's display version).
+ public var version: String?
+ /// 0 to 100 while downloading, else nil.
+ public var percent: Int?
+ public var notesUrl: String?
+ public var message: String?
+
+ public init(status: Status = .idle, currentVersion: String, version: String? = nil, percent: Int? = nil,
+ notesUrl: String? = nil, message: String? = nil) {
+ self.status = status
+ self.currentVersion = currentVersion
+ self.version = version
+ self.percent = percent
+ self.notesUrl = notesUrl
+ self.message = message
+ }
+
+ public static func idle(currentVersion: String) -> UpdateState { UpdateState(currentVersion: currentVersion) }
+
+ /// The release's page: the repository's tag for a Cua Spaces version.
+ public static func notesURL(version: String) -> String {
+ "https://github.com/trycua/cua/releases/tag/cua-spaces-v\(version)"
+ }
+
+ /// The bridge's record; absent values are explicit nulls.
+ public var json: [String: Any] {
+ [
+ "status": status.rawValue,
+ "currentVersion": currentVersion,
+ "version": version.map { $0 as Any } ?? NSNull(),
+ "percent": percent.map { $0 as Any } ?? NSNull(),
+ "notesUrl": notesUrl.map { $0 as Any } ?? NSNull(),
+ "message": message.map { $0 as Any } ?? NSNull(),
+ ]
+ }
+}
+
+/// The update state machine over plain values (no Sparkle types), so each
+/// step is testable. `UpdateUserDriver` feeds it Sparkle's callbacks.
+public struct UpdateFlow: Equatable, Sendable {
+ public private(set) var state: UpdateState
+ /// A check the user started (its errors are shown).
+ public private(set) var userCheck = false
+ private var received: UInt64 = 0
+ private var expected: UInt64 = 0
+
+ public init(currentVersion: String) { state = .idle(currentVersion: currentVersion) }
+
+ /// The download takes the first 90 percent of the bar, extraction the rest.
+ private static let downloadShare = 90.0
+
+ /// A user-visible check begins.
+ public mutating func userCheckStarted() {
+ userCheck = true
+ state = UpdateState(status: .checking, currentVersion: state.currentVersion)
+ }
+
+ /// An update was found; it downloads at once.
+ public mutating func found(version: String) {
+ received = 0
+ expected = 0
+ state = UpdateState(status: .available, currentVersion: state.currentVersion, version: version,
+ notesUrl: UpdateState.notesURL(version: version))
+ }
+
+ public mutating func downloadStarted() {
+ received = 0
+ expected = 0
+ setPercent(0)
+ }
+
+ public mutating func expectedLength(_ length: UInt64) {
+ expected = length
+ setPercent(downloadPercent)
+ }
+
+ public mutating func receivedData(_ length: UInt64) {
+ received += length
+ setPercent(downloadPercent)
+ }
+
+ public mutating func extractionStarted() { setPercent(Int(Self.downloadShare)) }
+
+ /// `progress` is 0 to 1.
+ public mutating func extractionProgress(_ progress: Double) {
+ let p = min(max(progress.isFinite ? progress : 0, 0), 1)
+ setPercent(Int((Self.downloadShare + (100 - Self.downloadShare) * p).rounded()))
+ }
+
+ /// Downloaded, extracted, and waiting for the user's restart.
+ public mutating func downloaded() {
+ state.status = .downloaded
+ state.percent = nil
+ state.message = nil
+ }
+
+ public mutating func notFound() {
+ userCheck = false
+ state = .idle(currentVersion: state.currentVersion)
+ }
+
+ public mutating func failed(_ message: String) {
+ userCheck = false
+ state = UpdateState(status: .error, currentVersion: state.currentVersion, message: message)
+ }
+
+ /// Sparkle ended its session (after an install, an error, or no update).
+ public mutating func dismissed() {
+ userCheck = false
+ if state.status == .error { return }
+ state = .idle(currentVersion: state.currentVersion)
+ }
+
+ private var downloadPercent: Int {
+ guard expected > 0 else { return 0 }
+ return Int((Double(min(received, expected)) / Double(expected) * Self.downloadShare).rounded())
+ }
+
+ private mutating func setPercent(_ percent: Int) {
+ guard state.version != nil else { return }
+ state.status = .downloading
+ // Never backwards.
+ state.percent = max(state.percent ?? 0, min(max(percent, 0), 100))
+ }
+}
+
+/// Sparkle's user driver without windows: a background update downloads on
+/// its own and waits for the page's "Restart to update". Sparkle's
+/// ready-to-install reply is held until `installNow`; nothing restarts the
+/// app before that.
+@MainActor
+public final class UpdateUserDriver: NSObject, SPUUserDriver {
+ public private(set) var flow: UpdateFlow
+ /// Told after every state change.
+ public var onChange: (() -> Void)?
+ /// `downloaded` when the update is ready to install.
+ public var onEvent: ((String) -> Void)?
+ /// Shows an error to the person who started the check.
+ var presentError: (String) -> Void = UpdateUserDriver.alertError
+
+ /// Sparkle's held "ready to install" reply.
+ private var heldReply: ((SPUUserUpdateChoice) -> Void)?
+ /// The silent path's immediate install (`willInstallUpdateOnQuit`).
+ private var immediateInstall: (() -> Void)?
+ private var told = false
+
+ public var state: UpdateState { flow.state }
+
+ public init(currentVersion: String) {
+ flow = UpdateFlow(currentVersion: currentVersion)
+ super.init()
+ }
+
+ private func changed(_ edit: (inout UpdateFlow) -> Void) {
+ let before = flow
+ edit(&flow)
+ if flow != before { onChange?() }
+ }
+
+ /// The user pressed Check Now.
+ public func beginUserCheck() { changed { $0.userCheckStarted() } }
+
+ /// Both paths end here: the update waits for the user.
+ private func becameReady() {
+ changed { $0.downloaded() }
+ if !told {
+ told = true
+ onEvent?("downloaded")
+ }
+ }
+
+ /// The silent path (`automaticallyDownloadsUpdates`): Sparkle installs on
+ /// quit, or at once through `install`.
+ public func silentlyDownloaded(version: String, install: @escaping () -> Void) {
+ immediateInstall = install
+ if flow.state.version == nil { changed { $0.found(version: version) } }
+ becameReady()
+ }
+
+ /// Restart to update: the held reply, or the silent path's install.
+ /// False when nothing is downloaded.
+ @discardableResult
+ public func installNow() -> Bool {
+ guard flow.state.status == .downloaded else { return false }
+ if let reply = heldReply {
+ heldReply = nil
+ reply(.install)
+ return true
+ }
+ if let install = immediateInstall {
+ install()
+ return true
+ }
+ return false
+ }
+
+ /// The update cycle ended; a check nobody saw end is idle.
+ public func cycleFinished() {
+ if flow.state.status == .checking { changed { $0.dismissed() } }
+ }
+
+ // MARK: - Update found
+
+ /// What `showUpdateFound` does, over plain values.
+ func handleFound(version: String, informationOnly: Bool, reply: @escaping (SPUUserUpdateChoice) -> Void) {
+ // An information-only item has nothing to install.
+ guard !informationOnly else {
+ changed { $0.notFound() }
+ reply(.dismiss)
+ return
+ }
+ told = false
+ changed { $0.found(version: version) }
+ reply(.install)
+ }
+
+ public func showUpdateFound(with appcastItem: SUAppcastItem, state: SPUUserUpdateState,
+ reply: @escaping (SPUUserUpdateChoice) -> Void) {
+ handleFound(version: appcastItem.displayVersionString, informationOnly: appcastItem.isInformationOnlyUpdate,
+ reply: reply)
+ }
+
+ // MARK: - SPUUserDriver
+
+ public func show(_ request: SPUUpdatePermissionRequest, reply: @escaping (SUUpdatePermissionResponse) -> Void) {
+ // Checking is on by default (SUEnableAutomaticChecks); a user's own
+ // choice is kept. Automatic downloads follow the Settings toggle.
+ reply(SUUpdatePermissionResponse(automaticUpdateChecks: true, sendSystemProfile: false))
+ }
+
+ public func showUserInitiatedUpdateCheck(cancellation: @escaping () -> Void) { beginUserCheck() }
+
+ public func showUpdateReleaseNotes(with downloadData: SPUDownloadData) {}
+ public func showUpdateReleaseNotesFailedToDownloadWithError(_ error: any Error) {}
+
+ public func showUpdateNotFoundWithError(_ error: any Error, acknowledgement: @escaping () -> Void) {
+ changed { $0.notFound() }
+ acknowledgement()
+ }
+
+ public func showUpdaterError(_ error: any Error, acknowledgement: @escaping () -> Void) {
+ handleError(error.localizedDescription)
+ acknowledgement()
+ }
+
+ /// A background error is logged only; the check's user sees an alert.
+ func handleError(_ message: String) {
+ let shown = flow.userCheck
+ NSLog("Cua Spaces: the updater failed: %@", message)
+ changed { $0.failed(message) }
+ if shown { presentError(message) }
+ }
+
+ public func showDownloadInitiated(cancellation: @escaping () -> Void) { changed { $0.downloadStarted() } }
+ public func showDownloadDidReceiveExpectedContentLength(_ expectedContentLength: UInt64) {
+ changed { $0.expectedLength(expectedContentLength) }
+ }
+ public func showDownloadDidReceiveData(ofLength length: UInt64) { changed { $0.receivedData(length) } }
+ public func showDownloadDidStartExtractingUpdate() { changed { $0.extractionStarted() } }
+ public func showExtractionReceivedProgress(_ progress: Double) { changed { $0.extractionProgress(progress) } }
+
+ public func showReady(toInstallAndRelaunch reply: @escaping (SPUUserUpdateChoice) -> Void) {
+ // Held until installNow: replying here would restart the app.
+ heldReply = reply
+ becameReady()
+ }
+
+ public func showInstallingUpdate(withApplicationTerminated applicationTerminated: Bool,
+ retryTerminatingApplication: @escaping () -> Void) {
+ // The page already said "Restarting"; the app quits on its own.
+ if !applicationTerminated { return }
+ }
+
+ public func showUpdateInstalledAndRelaunched(_ relaunched: Bool, acknowledgement: @escaping () -> Void) {
+ acknowledgement()
+ }
+
+ public func showUpdateInFocus() {}
+
+ public func dismissUpdateInstallation() {
+ heldReply = nil
+ immediateInstall = nil
+ told = false
+ changed { $0.dismissed() }
+ }
+
+ private static func alertError(_ message: String) {
+ let alert = NSAlert()
+ alert.messageText = "Update Error!"
+ alert.informativeText = message
+ alert.addButton(withTitle: "OK")
+ NSApp.activate()
+ alert.runModal()
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift
index ff245198e6..c5f3f170ca 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift
@@ -24,20 +24,31 @@ public protocol UpdaterDriving: AnyObject {
var onChange: (() -> Void)? { get set }
/// The Sparkle channels to install from besides the default one.
var channels: [String] { get set }
- /// Checks now, with Sparkle's own progress and result windows.
+ /// A check the user started is running (not a held update that waits
+ /// for a restart).
+ var checking: Bool { get }
+ /// The update the page shows (the bridge's `update.get`).
+ var state: UpdateState { get }
+ /// Checks now, with no Sparkle window: an update found downloads on its
+ /// own, and an error is shown only here.
func checkNow()
- /// Told each updater step: `found`, `not_found`, `installed` or `failed`
- /// (usage telemetry; fixed words).
+ /// Restarts into the downloaded update (the page's "Restart to update");
+ /// does nothing while nothing is downloaded.
+ func installNow()
+ /// Told each updater step: `found`, `not_found`, `downloaded`,
+ /// `installed` or `failed` (usage telemetry; fixed words).
var onUpdateEvent: ((String) -> Void)? { get set }
}
-/// Sparkle, with its standard windows. Started only in an app bundle whose
-/// Info.plist names a feed and the EdDSA key (`SUFeedURL`,
-/// `SUPublicEDKey`).
+/// Sparkle with no windows of its own (`UpdateUserDriver`): a background
+/// update downloads quietly and the page offers "Restart to update".
+/// Signature checks are Sparkle's, whatever the user driver. Started only
+/// in an app bundle whose Info.plist names a feed and the EdDSA key
+/// (`SUFeedURL`, `SUPublicEDKey`).
@MainActor
-public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate, SPUStandardUserDriverDelegate,
- SUVersionDisplay {
- private var controller: SPUStandardUpdaterController!
+public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate {
+ private var updater: SPUUpdater!
+ private let driver: UpdateUserDriver
private var observations: [NSKeyValueObservation] = []
public var onChange: (() -> Void)?
public var channels: [String] = []
@@ -50,15 +61,13 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,
/// The relaunch prompt is shown once per run.
private var askedToRelaunch = false
- private var updater: SPUUpdater { controller.updater }
-
/// The updater for `bundle`, started; nil when the bundle has no feed
/// (a development build) or Sparkle refused to start.
public static func start(bundle: Bundle = .main, channels: [String]) -> SparkleUpdater? {
guard bundle.bundleURL.pathExtension == "app",
bundle.object(forInfoDictionaryKey: "SUFeedURL") is String,
bundle.object(forInfoDictionaryKey: "SUPublicEDKey") is String else { return nil }
- let updater = SparkleUpdater(channels: channels)
+ let updater = SparkleUpdater(channels: channels, bundle: bundle)
do {
try updater.updater.start()
} catch {
@@ -68,11 +77,13 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,
return updater
}
- private init(channels: [String]) {
+ private init(channels: [String], bundle: Bundle) {
self.channels = channels
+ driver = UpdateUserDriver(currentVersion: AboutBundleInfo(bundle: bundle).version)
super.init()
- controller = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: self,
- userDriverDelegate: self)
+ updater = SPUUpdater(hostBundle: bundle, applicationBundle: bundle, userDriver: driver, delegate: self)
+ driver.onChange = { [weak self] in self?.onChange?() }
+ driver.onEvent = { [weak self] event in self?.onUpdateEvent?(event) }
let changed: @Sendable () -> Void = { [weak self] in
DispatchQueue.main.async { self?.onChange?() }
}
@@ -96,6 +107,10 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,
public var lastCheck: Date? { updater.lastUpdateCheckDate }
public var canCheck: Bool { updater.canCheckForUpdates }
+ public var state: UpdateState { driver.state }
+ public var checking: Bool { driver.state.status == .checking }
+
+ public func installNow() { driver.installNow() }
public func checkNow() {
// A copy replaced under this process cannot install updates; say so
@@ -105,10 +120,14 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,
Self.askToRelaunch(replaced, launched: launched)
return
}
+ // An update downloading or waiting for a restart is the answer; and
+ // Sparkle starts no check while a session runs.
+ guard updater.canCheckForUpdates, [.idle, .error].contains(driver.state.status) else { return }
+ driver.beginUserCheck()
updater.checkForUpdates()
}
- /// Checks in the background (no window unless an update is found);
+ /// Checks in the background (no window);
/// end-to-end runs use it through `CUA_SPACES_UPDATE_CHECK`.
public func checkInBackground() { updater.checkForUpdatesInBackground() }
@@ -146,6 +165,22 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,
tell("found")
}
public nonisolated func updaterDidNotFindUpdate(_ updater: SPUUpdater) { tell("not_found") }
+
+ /// The silent path (`automaticallyDownloadsUpdates`): Sparkle never asks
+ /// the user driver, and installs on quit. Taking the install here makes
+ /// that update "downloaded" too, with the immediate install as Restart.
+ public nonisolated func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem,
+ immediateInstallationBlock immediateInstallHandler: @escaping () -> Void) -> Bool {
+ let version = item.displayVersionString
+ MainActor.assumeIsolated { driver.silentlyDownloaded(version: version, install: immediateInstallHandler) }
+ return true
+ }
+
+ /// A cycle that ended with nothing to show clears a pending "checking".
+ public nonisolated func updater(_ updater: SPUUpdater, didFinishUpdateCycleFor updateCheck: SPUUpdateCheck,
+ error: (any Error)?) {
+ MainActor.assumeIsolated { driver.cycleFinished() }
+ }
public nonisolated func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) { tell("installed") }
public nonisolated func updater(_ updater: SPUUpdater, didAbortWithError error: any Error) {
// "No update" also arrives here; only a real failure is one.
@@ -221,47 +256,6 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,
}
NSApp.terminate(nil)
}
-
- // MARK: - Versions in Sparkle's windows
-
- /// This app's full version (`CuaVersion`: 0.2.0-staging.5), which
- /// `CFBundleShortVersionString` (X.Y.Z only) leaves out.
- private nonisolated static var fullVersion: String? {
- Bundle.main.object(forInfoDictionaryKey: "CuaVersion") as? String
- }
-
- public nonisolated func standardUserDriverRequestsVersionDisplayer() -> (any SUVersionDisplay)? { self }
-
- // MARK: - Sparkle's alerts in front
-
- /// "You're up to date!" and the other alerts are modal: brought to the
- /// front, so one never waits unseen behind the New UI's window (or
- /// another app's) while the About pane says "Checking…".
- public nonisolated func standardUserDriverWillShowModalAlert() {
- MainActor.assumeIsolated { Self.bringAlertsForward() }
- }
-
- /// Activates the app: the modal alert that follows becomes the key
- /// window, in front of every other.
- static func bringAlertsForward() {
- NSApp.activate()
- }
-
- /// "0.2.0-staging.6 is now available; you have 0.2.0-staging.5" (the
- /// appcast item already carries the full version).
- public nonisolated func formatUpdateVersion(
- fromUpdate update: SUAppcastItem,
- andBundleDisplayVersion inOutBundleDisplayVersion: AutoreleasingUnsafeMutablePointer<NSString>,
- withBundleVersion bundleVersion: String
- ) -> String {
- if let full = Self.fullVersion { inOutBundleDisplayVersion.pointee = full as NSString }
- return update.displayVersionString
- }
-
- public nonisolated func formatBundleDisplayVersion(_ bundleDisplayVersion: String, withBundleVersion bundleVersion: String,
- matchingUpdate: SUAppcastItem?) -> String {
- Self.fullVersion ?? bundleDisplayVersion
- }
}
/// The app bundle this process was launched from, and whether the copy on
@@ -328,6 +322,11 @@ public final class FixtureUpdater: UpdaterDriving {
public var channels: [String] = []
public var onUpdateEvent: ((String) -> Void)?
public private(set) var checks = 0
+ /// What the page shows; scripted by tests through the `simulate` calls.
+ public var state = UpdateState.idle(currentVersion: "0.0.0") { didSet { onChange?() } }
+ public var checking: Bool { state.status == .checking }
+ /// Restarts asked for while an update was downloaded.
+ public private(set) var installs = 0
/// What the next check finds (`not_found` by default).
public var nextResult = "not_found"
@@ -339,6 +338,36 @@ public final class FixtureUpdater: UpdaterDriving {
onUpdateEvent?(nextResult)
onChange?()
}
+
+ public func installNow() {
+ guard state.status == .downloaded else { return }
+ installs += 1
+ onUpdateEvent?("installed")
+ state = .idle(currentVersion: state.currentVersion)
+ }
+
+ /// A check found `version`; it begins downloading at once.
+ public func simulateFound(version: String) {
+ state = UpdateState(status: .available, currentVersion: state.currentVersion, version: version,
+ notesUrl: UpdateState.notesURL(version: version))
+ onUpdateEvent?("found")
+ }
+
+ public func simulateProgress(percent: Int) {
+ state.status = .downloading
+ state.percent = percent
+ }
+
+ public func simulateDownloaded() {
+ state.status = .downloaded
+ state.percent = nil
+ onUpdateEvent?("downloaded")
+ }
+
+ public func simulateError(_ message: String) {
+ state = UpdateState(status: .error, currentVersion: state.currentVersion, message: message)
+ onUpdateEvent?("failed")
+ }
}
/// Settings → About: the core's `appAboutView` over the updater's state.
@@ -400,9 +429,20 @@ public final class UpdatesModel {
autoInstall: updater?.automaticallyInstalls ?? false,
channel: channel,
lastCheck: updater?.lastCheck.map(Self.dateText),
- checking: !(updater?.canCheck ?? true))
+ checking: updater?.checking ?? false)
}
+ /// What the page shows about an update (`update.get`).
+ public var updateState: UpdateState {
+ _ = revision
+ var state = updater?.state ?? .idle(currentVersion: info.version)
+ state.currentVersion = info.version
+ return state
+ }
+
+ /// "Restart to update": installs the downloaded update and restarts.
+ public func installUpdate() { updater?.installNow() }
+
static func dateText(_ date: Date) -> String {
date.formatted(date: .abbreviated, time: .shortened)
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
index 29c8d63048..32143066a6 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
@@ -89,6 +89,18 @@ extension WebUIBridge {
input["checking"] = true
return input
+ // The in-app update indicator: Sparkle downloads in the background,
+ // and the page asks to restart.
+ case "update.get": return model.updates.updateState.json
+ case "update.install":
+ guard model.updates.updater != nil else { throw Failure.unsupported("Updates are off in this build") }
+ // The app quits to install: answer first, then start.
+ let answer = model.updates.updateState.json
+ if model.updates.updateState.status == .downloaded {
+ DispatchQueue.main.async { [model] in model.updates.installUpdate() }
+ }
+ return answer
+
// Settings, launch at login
case "loginItem.get":
model.readLoginItem()
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index d4ee30c5cc..e65c7b5b09 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -39,7 +39,8 @@ public struct WebUIActions {
/// Events (native to web): `window.dispatchEvent(new CustomEvent("cua:event",
/// { detail: { event, payload } }))`, where `event` is `spaces.changed`,
/// `machines.changed`, `keyvault.changed`, `session.changed`,
-/// `settings.changed` or `agents.changed`; the UI asks again for what it
+/// `settings.changed`, `agents.changed` or `update.changed` (an update
+/// found, downloading, ready or failed); the UI asks again for what it
/// shows. `spaces.createProgress` carries a create's progress (the page's
/// pending id), and `spaces.newRequested` (`{on}`) asks the page to open
/// its New Space wizard (the app's New Space menu items, the notch).
@@ -85,7 +86,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"volume.overview", "volume.storage", "volume.storageSet", "volume.mount", "volume.unmount",
"volume.approve", "volume.deny", "volume.revoke", "volume.resolve", "volume.reveal",
"agents.setupDriver",
- "about.get", "about.set", "about.checkNow", "loginItem.get", "loginItem.set", "loginItem.openSettings",
+ "about.get", "about.set", "about.checkNow", "update.get", "update.install", "loginItem.get", "loginItem.set", "loginItem.openSettings",
"devices.get", "devices.enroll", "devices.checkEnrolled", "devices.approve", "devices.rename",
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
"devices.revokePairingCode", "teams.list", "storage.get", "storage.run",
@@ -954,6 +955,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
guard let self else { return "" }
return Self.signature([self.hostStatus(), BridgeValue.encode(self.model.devices.view)])
}
+ followChanges("update.changed") { [model] in Self.signature(model.updates.updateState.json) }
followChanges("checklist.changed") { [model] in Self.signature(model.checklist.stored) }
followChanges("agents.changed") { [model] in
Self.signature([model.persistent.agentsInput["agents"] ?? NSNull(),
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
index 2200260806..01718aa8e9 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -225,6 +225,7 @@ struct BridgeContractTests {
("volume.overview", [:]), ("volume.storage", [:]), ("volume.mount", [:]), ("volume.unmount", [:]),
("volume.storageSet", ["update": ["backend": "fs", "dry_run": true]]),
("about.get", [:]), ("about.set", ["channel": "beta"]), ("about.checkNow", [:]),
+ ("update.get", [:]), ("update.install", [:]),
("loginItem.get", [:]), ("loginItem.set", ["on": true]),
("devices.get", [:]), ("devices.enroll", [:]), ("devices.checkEnrolled", [:]),
("devices.createPairingCode", ["team": NSNull()]), ("devices.pairingCodes", [:]),
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift
index adabf22bc0..0837c92a12 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift
@@ -5,6 +5,7 @@ import CuaSDK
import CuaSpacesFFI
@testable import CuaSpacesMacKit
import Foundation
+import Sparkle
import Testing
/// Settings → About over an in-memory updater, and the first launch after
@@ -86,6 +87,166 @@ struct UpdatesTests {
#expect(saved == [.beta, .stable])
}
+ // MARK: - The in-app update flow
+
+ @Test func aFoundUpdateDownloadsThenWaitsForRestart() {
+ let updater = FixtureUpdater()
+ let telemetry = FixtureTelemetry()
+ let model = UpdatesModel(updater: updater, channel: .stable, info: Self.info)
+ model.telemetry = telemetry
+ #expect(model.updateState.status == .idle)
+ #expect(model.updateState.currentVersion == "0.2.0-staging.5")
+ updater.simulateFound(version: "0.2.0-staging.6")
+ #expect(model.updateState.status == .available)
+ #expect(model.updateState.notesUrl == "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.2.0-staging.6")
+ updater.simulateProgress(percent: 40)
+ #expect(model.updateState.status == .downloading && model.updateState.percent == 40)
+ #expect(!(model.input.checking))
+ updater.simulateDownloaded()
+ #expect(model.updateState.status == .downloaded && model.updateState.percent == nil)
+ // Nothing restarts until the user asks.
+ #expect(updater.installs == 0)
+ model.installUpdate()
+ #expect(updater.installs == 1)
+ #expect(model.updateState.status == .idle)
+ let words = telemetry.recorded.map { ParityTests.signalFrame($0)["action"] as! String }
+ #expect(words.contains("downloaded") && words.contains("installed"))
+ }
+
+ @Test func installingWithNothingDownloadedChangesNothing() {
+ let updater = FixtureUpdater()
+ let model = UpdatesModel(updater: updater, channel: .stable, info: Self.info)
+ model.installUpdate()
+ updater.simulateFound(version: "0.2.0-staging.6")
+ model.installUpdate()
+ #expect(updater.installs == 0)
+ #expect(model.updateState.status == .available)
+ }
+
+ @Test func theStateJSONHasTheContractsKeys() {
+ let idle = UpdateState.idle(currentVersion: "0.9.2").json
+ #expect(Set(idle.keys) == ["status", "currentVersion", "version", "percent", "notesUrl", "message"])
+ #expect(idle["status"] as? String == "idle")
+ #expect(idle["version"] is NSNull && idle["percent"] is NSNull && idle["notesUrl"] is NSNull && idle["message"] is NSNull)
+ let busy = UpdateState(status: .downloading, currentVersion: "0.9.2", version: "0.9.3", percent: 12,
+ notesUrl: UpdateState.notesURL(version: "0.9.3")).json
+ #expect(busy["percent"] as? Int == 12)
+ #expect(busy["notesUrl"] as? String == "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3")
+ }
+
+ @Test func aFlowReducesSparklesStepsToPercent() {
+ var flow = UpdateFlow(currentVersion: "0.9.2")
+ flow.userCheckStarted()
+ #expect(flow.state.status == .checking)
+ flow.found(version: "0.9.3")
+ flow.downloadStarted()
+ flow.expectedLength(1000)
+ flow.receivedData(500)
+ #expect(flow.state.percent == 45)
+ flow.receivedData(500)
+ #expect(flow.state.percent == 90)
+ flow.extractionStarted()
+ flow.extractionProgress(0.5)
+ #expect(flow.state.percent == 95)
+ flow.downloaded()
+ #expect(flow.state.status == .downloaded && flow.state.percent == nil && flow.state.version == "0.9.3")
+ flow.dismissed()
+ #expect(flow.state.status == .idle && flow.state.version == nil)
+ // Unknown length stays at 0, never past 100.
+ flow.found(version: "0.9.4")
+ flow.receivedData(10)
+ #expect(flow.state.percent == 0)
+ }
+
+ final class Replies {
+ var choices: [SPUUserUpdateChoice] = []
+ var acks = 0
+ }
+
+ @Test func theDriverHoldsTheInstallReplyUntilTheUserRestarts() {
+ let driver = UpdateUserDriver(currentVersion: "0.9.2")
+ let replies = Replies()
+ var events: [String] = []
+ var changes = 0
+ driver.onEvent = { events.append($0) }
+ driver.onChange = { changes += 1 }
+ // A background check finds an update: download at once.
+ driver.handleFound(version: "0.9.3", informationOnly: false) { replies.choices.append($0) }
+ #expect(replies.choices == [.install])
+ #expect(driver.state.status == .available)
+ driver.showDownloadInitiated {}
+ driver.showDownloadDidReceiveExpectedContentLength(100)
+ driver.showDownloadDidReceiveData(ofLength: 50)
+ #expect(driver.state.status == .downloading && driver.state.percent == 45)
+ driver.showDownloadDidStartExtractingUpdate()
+ driver.showExtractionReceivedProgress(1)
+ #expect(driver.state.percent == 100)
+ // Ready to install: held, not replied.
+ driver.showReady(toInstallAndRelaunch: { replies.choices.append($0) })
+ #expect(driver.state.status == .downloaded)
+ #expect(events == ["downloaded"])
+ #expect(replies.choices == [.install])
+ #expect(changes > 0)
+ #expect(driver.installNow())
+ #expect(replies.choices == [.install, .install])
+ // Once is enough.
+ #expect(!driver.installNow() || replies.choices.count == 2)
+ driver.dismissUpdateInstallation()
+ #expect(driver.state.status == .idle)
+ }
+
+ @Test func theSilentPathReachesDownloadedWithItsImmediateInstall() {
+ let driver = UpdateUserDriver(currentVersion: "0.9.2")
+ var events: [String] = []
+ var installs = 0
+ driver.onEvent = { events.append($0) }
+ driver.silentlyDownloaded(version: "0.9.3") { installs += 1 }
+ #expect(driver.state.status == .downloaded && driver.state.version == "0.9.3")
+ #expect(events == ["downloaded"])
+ #expect(installs == 0)
+ #expect(driver.installNow())
+ #expect(installs == 1)
+ }
+
+ @Test func nothingFoundAndBackgroundErrorsStayQuiet() {
+ let driver = UpdateUserDriver(currentVersion: "0.9.2")
+ var alerts: [String] = []
+ driver.presentError = { alerts.append($0) }
+ var acks = 0
+ driver.showUpdateNotFoundWithError(NSError(domain: "t", code: 1)) { acks += 1 }
+ #expect(acks == 1 && driver.state.status == .idle)
+ driver.showUpdaterError(NSError(domain: "t", code: 2, userInfo: [NSLocalizedDescriptionKey: "offline"])) { acks += 1 }
+ #expect(acks == 2 && alerts.isEmpty)
+ #expect(driver.state.status == .error && driver.state.message == "offline")
+ driver.dismissUpdateInstallation()
+ #expect(driver.state.status == .error)
+ }
+
+ @Test func aUserCheckErrorShowsAnAlert() {
+ let driver = UpdateUserDriver(currentVersion: "0.9.2")
+ var alerts: [String] = []
+ driver.presentError = { alerts.append($0) }
+ driver.beginUserCheck()
+ #expect(driver.state.status == .checking)
+ driver.showUpdaterError(NSError(domain: "t", code: 2, userInfo: [NSLocalizedDescriptionKey: "offline"])) {}
+ #expect(alerts == ["offline"])
+ }
+
+ @Test func aUserCheckThatFindsNothingEndsQuietly() {
+ let driver = UpdateUserDriver(currentVersion: "0.9.2")
+ driver.beginUserCheck()
+ driver.showUpdateNotFoundWithError(NSError(domain: "t", code: 1)) {}
+ #expect(driver.state.status == .idle)
+ }
+
+ @Test func anInformationOnlyItemIsNotInstalled() {
+ let driver = UpdateUserDriver(currentVersion: "0.9.2")
+ let replies = Replies()
+ driver.handleFound(version: "1.0.0", informationOnly: true) { replies.choices.append($0) }
+ #expect(replies.choices == [.dismiss])
+ #expect(driver.state.status == .idle)
+ }
+
// MARK: - The launch after an update
func settingsFile() -> String {
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
index 1e8b573deb..715b81fe05 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
@@ -366,7 +366,7 @@ struct WebUIHostTests {
@Test func everyPageOperationIsRouted() {
for m in ["spaces.add", "clouds.status", "teleport.catalog", "teleport.run", "sharing.share", "volume.overview",
- "agents.setupDriver", "about.set", "loginItem.set", "devices.approve", "storage.run",
+ "agents.setupDriver", "about.set", "update.get", "update.install", "loginItem.set", "devices.approve", "storage.run",
"notifications.list", "telemetry.track", "spaces.windows", "stream.pip", "spaces.thumbnail", "spaces.sendFiles", "host.setUp", "host.action",
"host.openSettings"] {
#expect(WebUIBridge.methods.contains(m), "\(m)")
@@ -570,6 +570,26 @@ struct WebUIHostTests {
#expect(updater.checks == 1)
}
+ @Test func updateInstallRestartsOnlyAfterADownload() async throws {
+ let (bridge, model) = bridge()
+ let updater = FixtureUpdater()
+ model.updates = UpdatesModel(updater: updater, channel: .stable)
+ updater.simulateFound(version: "0.9.3")
+ let a = try #require(try await bridge.handle("update.get", [:]) as? [String: Any])
+ #expect(a["status"] as? String == "available" && a["version"] as? String == "0.9.3")
+ let b = try #require(try await bridge.handle("update.install", [:]) as? [String: Any])
+ #expect(b["status"] as? String == "available")
+ await withCheckedContinuation { k in DispatchQueue.main.async { k.resume() } }
+ #expect(updater.installs == 0)
+ updater.simulateDownloaded()
+ let c = try #require(try await bridge.handle("update.install", [:]) as? [String: Any])
+ // The answer comes before the install starts.
+ #expect(c["status"] as? String == "downloaded")
+ #expect(updater.installs == 0)
+ await withCheckedContinuation { k in DispatchQueue.main.async { k.resume() } }
+ #expect(updater.installs == 1)
+ }
+
@Test func showWelcomeAgainRestartsTheFirstRun() async throws {
let (bridge, model) = bridge()
model.onboarding.finish()
diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.md
index a2ccd3835a..fd81cba2e5 100644
--- a/apps/cua-spaces-web/src/bridge/README.md
+++ b/apps/cua-spaces-web/src/bridge/README.md
@@ -109,7 +109,8 @@ Each is an existing Tauri command under a host-neutral name:
| `agents.detail`, `.readFile`, `.restoreFile`, `.addRoutine`, `.setRoutine`, `.removeRoutine`, `.allowComputer`, `.revokeComputer` | `agents_tool` (the tools `PersistentModel` runs; see `ops/agent-detail.ts`) |
Events (`HostEvent`): `spaces.changed`, `spaces.createProgress`,
-`machines.changed`, `settings.changed`, `keyvault.changed`,
+`machines.changed`, `settings.changed`, `update.changed` (the host's updater
+moved on: ask `update.get` again), `keyvault.changed`,
`session.signedIn`, `session.signInFailed`, `session.signedOut` and
`agents.changed` (no Tauri event yet; the store also refetches agents when a
watched run starts or ends, and when Spaces change). They
@@ -168,7 +169,7 @@ speaks it as is:
- Events arrive as `window` `cua:event` CustomEvents (`detail: { event }`):
`spaces.changed` (it also refreshes machines), `machines.changed` (this
Mac's host status or the account's devices), `keyvault.changed`,
- `settings.changed`, `session.changed` and `agents.changed`.
+ `settings.changed`, `update.changed`, `session.changed` and `agents.changed`.
- `spaces.cancelCreate {pendingId}`, `host.status`, `keyvault.approve
{requestId, items}`, `keyvault.deny {requestId}`, `keyvault.revokeGrant
{id}` and the seven `agents.*` methods keep the operation's own name and
@@ -424,6 +425,8 @@ mechanism. Types are in `contracts/settings.ts`, `contracts/devices.ts` and
| `about.get` | `{}` | `AboutInput` | `plugin:app\|version`, `get_environment` (no updater) | `UpdatesModel.input` |
| `about.set` | `{ autoCheck?, autoInstall?, channel? }` | `AboutInput` | unsupported | `UpdatesModel.setAutoCheck/setAutoInstall/choose(channel:)` |
| `about.checkNow` | `{}` | `AboutInput` | unsupported | `UpdatesModel.checkNow` |
+| `update.get` | `{}` | `UpdateState` (`status`, `currentVersion`, `version`, `percent`, `notesUrl`, `message`) | unsupported | `UpdatesModel.updateState` (Sparkle driven by `InAppUpdateDriver`; Electron: `update-state.ts`) |
+| `update.install` | `{}` | `UpdateState` | unsupported | `UpdatesModel.installUpdate`: "Restart to update". Only a click calls it; with nothing downloaded it changes nothing |
| `experiments.get` / `.set` | `{}` / `{ experiments }` | `Experiments` | UI storage `cua.settings.experiments` | `app.info`, `settings.choose {row: "experiment:…"}` (routed today) |
| `loginItem.get` / `.set` | `{}` / `{ on }` | `{ status, providesSpaces, runsAgents }` | `login_item_status` / `login_item_set`, `host_status`, `agents_tool` | `LoginItem.status()`, `register/unregister`, `HostModel.provideSpaces`, `PersistentModel` |
| `loginItem.openSettings` | `{}` | `null` | `host_open_settings` | `SMAppService.openSystemSettingsLoginItems()` |
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
index 8aad6faeff..e828be3030 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
@@ -104,6 +104,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"about.get": {},
"about.set": { channel: "beta" },
"about.checkNow": {},
+ "update.get": {},
+ "update.install": {},
"experiments.get": {},
"experiments.set": { experiments: { cuaVolume: true } },
"loginItem.get": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
index 20449223d6..429ea54135 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
@@ -88,6 +88,8 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"about.get": {},
"about.set": { channel: "beta" },
"about.checkNow": {},
+ "update.get": {},
+ "update.install": {},
"experiments.get": {},
"experiments.set": { experiments: { cuaVolume: true } },
"loginItem.get": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts
index c2dbe8a093..0d8a3d8466 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/hosts.test.ts
@@ -316,6 +316,20 @@ describe("electron adapter", () => {
await expect(createElectronAdapter(win).call("spaces.list", {})).rejects.toMatchObject({ code: "protocol" });
});
+ it("reads update.get and update.install from the host, and turns update.changed into the page's event", async () => {
+ const state = { status: "downloaded", currentVersion: "0.9.2", version: "0.9.3", percent: 100, notesUrl: "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3", message: null };
+ const asked: string[] = [];
+ const { win, subs } = electronHost(bridged((method) => (asked.push(method), { ok: true, result: state })));
+ const a = createElectronAdapter(win);
+ expect(await a.call("update.get", {})).toEqual(state);
+ expect(await a.call("update.install", {})).toEqual(state);
+ expect(asked).toEqual(["update.get", "update.install"]);
+ const got: HostEvent[] = [];
+ a.subscribe((e) => got.push(e));
+ subs.get(ELECTRON_EVENT_CHANNEL)?.({ event: "update.changed" });
+ expect(got).toEqual([{ type: "update.changed" }]);
+ });
+
it("delivers the host's cua:event pushes", () => {
const { win, subs } = electronHost(bridged(() => ({ ok: true, result: null })));
const a = createElectronAdapter(win);
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/update.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/update.test.tsx
new file mode 100644
index 0000000000..b6758e27e4
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/__tests__/update.test.tsx
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { createDemoAdapter } from "../adapters/demo";
+import { UnsupportedOperationError, type DataAdapter } from "../adapter";
+import { BridgeProvider, useUpdate, type UpdateHook, type UpdateState } from "../index";
+import type { HostEvent } from "../protocol";
+import { noCore, tick } from "./testCore";
+
+afterEach(cleanup);
+
+function mount(adapter: DataAdapter) {
+ const hook = {} as { current: UpdateHook };
+ function Probe() {
+ hook.current = useUpdate();
+ return null;
+ }
+ render(
+ <BridgeProvider adapter={adapter} core={noCore}>
+ <Probe />
+ </BridgeProvider>,
+ );
+ return hook;
+}
+
+const ready: Partial<UpdateState> = { status: "downloaded", version: "0.9.3", percent: 100, notesUrl: "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3" };
+
+describe("the update state (update.get, update.install, update.changed)", () => {
+ it("reads where the host's updater is", async () => {
+ const hook = mount(createDemoAdapter({ latencyMs: 0, update: ready }));
+ await waitFor(() => expect(hook.current.data?.state).toMatchObject({ status: "downloaded", version: "0.9.3" }));
+ expect(hook.current.data?.installing).toBe(false);
+ });
+
+ it("asks again when the host says its updater moved on", async () => {
+ let state: UpdateState = { status: "downloading", currentVersion: "0.9.2", version: "0.9.3", percent: 10, notesUrl: null, message: null };
+ const demo = createDemoAdapter({ latencyMs: 0 });
+ let push: (e: HostEvent) => void = () => {};
+ const adapter: DataAdapter = {
+ ...demo,
+ call: (op, args) => (op === "update.get" ? Promise.resolve({ ...state }) : demo.call(op, args)),
+ subscribe: (listener) => {
+ push = listener;
+ return demo.subscribe(listener);
+ },
+ } as DataAdapter;
+ const hook = mount(adapter);
+ await waitFor(() => expect(hook.current.data?.state.percent).toBe(10));
+ state = { ...state, status: "downloaded", percent: 100 };
+ // The page is told; it does not poll every moment.
+ await tick(30);
+ expect(hook.current.data?.state.status).toBe("downloading");
+ push({ type: "update.changed" });
+ await waitFor(() => expect(hook.current.data?.state).toMatchObject({ status: "downloaded", percent: 100 }));
+ });
+
+ it("restarts only when install is called, and clears the state once the host answers", async () => {
+ const demo = createDemoAdapter({ latencyMs: 0, update: ready });
+ const calls: string[] = [];
+ const adapter: DataAdapter = { ...demo, call: (op, args) => (calls.push(op), demo.call(op, args)) } as DataAdapter;
+ const hook = mount(adapter);
+ await waitFor(() => expect(hook.current.data?.state.status).toBe("downloaded"));
+ expect(calls).not.toContain("update.install");
+ await hook.current.install();
+ expect(calls).toContain("update.install");
+ await waitFor(() => expect(hook.current.data?.state.status).toBe("idle"));
+ });
+
+ it("is unsupported on a host with no updater (Tauri)", async () => {
+ const demo = createDemoAdapter({ latencyMs: 0 });
+ const adapter: DataAdapter = { ...demo, call: (op, args) => (op === "update.get" ? Promise.reject(new UnsupportedOperationError("tauri", "update.get")) : demo.call(op, args)) } as DataAdapter;
+ const hook = mount(adapter);
+ await waitFor(() => expect(hook.current.unsupported).toBe(true));
+ expect(hook.current.data).toBeUndefined();
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index f87de91d47..e81cec3736 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -11,6 +11,7 @@ import { Emitter, HostError, UnsupportedOperationError, type DataAdapter } from
import type { AgentSetupRow, PersistentAgent } from "../contracts/agents";
import type { MachineRow, OnboardingState } from "../contracts/host";
import type { KvItem } from "../contracts/keyvault";
+import type { UpdateState } from "../contracts/settings";
import type { SpaceOs, SpaceRow } from "../contracts/spaces";
import {
DEFAULT_SETTINGS,
@@ -76,12 +77,17 @@ export interface DemoOptions {
/** The machine the demo runs on: a Mac on Apple silicon unless set (the
* Electron shell passes its own system and architecture). */
platform?: DemoPlatform;
+ /** Where the updater is at start (`?demo=update-ready`, `?demo=update-downloading`). */
+ update?: Partial<UpdateState>;
}
+const DEMO_NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3";
+
/** `?demo=fresh` (signed out, first run), `?demo=locked` (Keyvault locked), `?demo=novault` (no Keyvault yet),
* `?demo=empty` (no Spaces yet), `?demo=keychain` (the startup screen),
* `?demo=mac-host` (New Space options and the Keyvault's Settings rows in the
- * SwiftUI host's shape) and `?demo=unenrolled` (this device not enrolled). */
+ * SwiftUI host's shape), `?demo=unenrolled` (this device not enrolled),
+ * `?demo=update-ready` (an update is downloaded) and `?demo=update-downloading`. */
export function demoOptionsFromSearch(search: string): DemoOptions {
const flags = new Set((new URLSearchParams(search).get("demo") ?? "").split(",").filter(Boolean));
return {
@@ -93,6 +99,11 @@ export function demoOptionsFromSearch(search: string): DemoOptions {
keychain: flags.has("keychain"),
macHost: flags.has("mac-host"),
unenrolled: flags.has("unenrolled"),
+ ...(flags.has("update-ready")
+ ? { update: { status: "downloaded" as const, version: "0.9.3", percent: 100, notesUrl: DEMO_NOTES } }
+ : flags.has("update-downloading")
+ ? { update: { status: "downloading" as const, version: "0.9.3", percent: 42, notesUrl: DEMO_NOTES } }
+ : {}),
};
}
@@ -468,7 +479,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
...demoAgentDetailHandlers({ wait, stepMs: step, now }),
...demoAgentKeysHandlers({ wait, stepMs: step, now }),
...demoVolumeHandlers({ state: state.volume, now, wait, step, emit, platform: state.platform }),
- ...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, unenrolled: options.unenrolled, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),
+ ...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, unenrolled: options.unenrolled, update: options.update, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),
...demoTelemetryHandlers(ctx),
...demoRelayUsageHandlers(ctx),
...demoSpaceDetailHandlers(ctx),
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
index 6a1aaa9666..c0d1a80cd1 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts
@@ -11,7 +11,7 @@ import { HostError } from "../../adapter";
import type { DeviceInput, DevicesInput, PairingCode } from "../../contracts/devices";
import type { MachineRow } from "../../contracts/host";
import type { NotificationInput } from "../../contracts/notifications";
-import type { AboutInput, DriveCheckInput, Experiments, LoginItemReport, StorageInput } from "../../contracts/settings";
+import type { AboutInput, DriveCheckInput, Experiments, LoginItemReport, StorageInput, UpdateState } from "../../contracts/settings";
import { NO_EXPERIMENTS } from "../../contracts/volume";
import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./platform";
import type { NotificationsOperations } from "../../ops/notifications";
@@ -36,6 +36,8 @@ export interface DemoSettingsContext {
addMachine?: (machine: MachineRow) => void;
/** This device is not on the relay until Enroll… signs in again. */
unenrolled?: boolean;
+ /** Where the updater is at start (idle: up to date). */
+ update?: Partial<UpdateState>;
}
/** How many times "Add a machine" reads the codes before the demo's other
@@ -148,6 +150,16 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {
cache: { size_bytes: Math.round(1.2 * GIB), capacity_bytes: 10 * GIB },
};
+ let update: UpdateState = {
+ status: "idle",
+ currentVersion: "0.6.0",
+ version: null,
+ percent: null,
+ notesUrl: null,
+ message: null,
+ ...ctx.update,
+ };
+
const about = (): AboutInput => ({
platform: platform.os,
version: "0.6.0",
@@ -196,6 +208,16 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {
return about();
},
+ "update.get": () => ({ ...update }),
+ "update.install": () => {
+ // Nothing downloaded: nothing to install, and the state says so.
+ if (update.status !== "downloaded") return { ...update };
+ // The real host relaunches into the new version.
+ update = { ...update, status: "idle", currentVersion: update.version ?? update.currentVersion, version: null, notesUrl: null };
+ emit({ type: "update.changed" });
+ return { ...update };
+ },
+
"experiments.get": () => ({ ...experiments }),
"experiments.set": ({ experiments: next }) => {
experiments = { ...next };
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index 35fed745bc..7a1d2a4cce 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -420,6 +420,7 @@ const EVENTS: Record<string, HostEvent[]> = {
"checklist.changed": [{ type: "checklist.changed" }],
"keyvault.changed": [{ type: "keyvault.changed" }],
"settings.changed": [{ type: "settings.changed" }],
+ "update.changed": [{ type: "update.changed" }],
"session.changed": [{ type: "session.changed" }],
};
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index 61402fbdce..09593b94d0 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -2648,6 +2648,56 @@
"currentTeamId"
]
},
+ "UpdateState": {
+ "type": "object",
+ "properties": {
+ "status": {
+ "enum": [
+ "idle",
+ "checking",
+ "available",
+ "downloading",
+ "downloaded",
+ "error"
+ ]
+ },
+ "currentVersion": {
+ "type": "string"
+ },
+ "version": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "percent": {
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "notesUrl": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "message": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "status",
+ "currentVersion",
+ "version",
+ "percent",
+ "notesUrl",
+ "message"
+ ]
+ },
"VolumeOverview": {
"type": "object",
"properties": {
@@ -5275,6 +5325,12 @@
]
}
},
+ "update.get": {
+ "$ref": "#/$defs/UpdateState"
+ },
+ "update.install": {
+ "$ref": "#/$defs/UpdateState"
+ },
"volume.approve": {
"type": "null"
},
@@ -6697,6 +6753,12 @@
]
}
},
+ "update.get": {
+ "$ref": "#/$defs/UpdateState"
+ },
+ "update.install": {
+ "$ref": "#/$defs/UpdateState"
+ },
"volume.approve": {
"type": "null"
},
diff --git a/apps/cua-spaces-web/src/bridge/contracts/settings.ts b/apps/cua-spaces-web/src/bridge/contracts/settings.ts
index e163bd516a..102a49ac9c 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/settings.ts
@@ -69,6 +69,29 @@ export interface AboutView {
updates: AboutUpdates | null;
}
+/* ---- In-app updates (`update.*`) ------------------------------------------ */
+
+/** Where an update is: nothing to do, a check running, found and about to
+ * download, downloading, ready to install, or the last step failed. */
+export type UpdateStatus = "idle" | "checking" | "available" | "downloading" | "downloaded" | "error";
+
+/** What the host's updater (Sparkle in the Mac app, electron-updater on
+ * Windows and Linux) reports for the in-app indicator. The host downloads
+ * on its own; it installs only on `update.install`. */
+export interface UpdateState {
+ status: UpdateStatus;
+ /** The version this app runs. */
+ currentVersion: string;
+ /** The version found, downloading or ready; null with none. */
+ version: string | null;
+ /** Download progress, 0 to 100, while `downloading`; else null. */
+ percent: number | null;
+ /** The GitHub release notes page for `version`; null with none. */
+ notesUrl: string | null;
+ /** Why the last step failed (`error` only); else null. */
+ message: string | null;
+}
+
/** What `about.set` changes. */
export type AboutSetting = { key: "autoCheck"; value: boolean } | { key: "autoInstall"; value: boolean } | { key: "channel"; value: UpdateChannelId };
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index eac0c57408..1ef78501aa 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -52,7 +52,7 @@ import type {
WizardEnv,
} from "./new-space";
import type { NotificationInput } from "./notifications";
-import type { AboutInput, DriveCheckInput, DriveStorageInput, LoginItemReport, StorageInput } from "./settings";
+import type { AboutInput, DriveCheckInput, DriveStorageInput, LoginItemReport, StorageInput, UpdateState } from "./settings";
import type { ShareEntry } from "./share";
import type { SpaceProgress, SpaceRow } from "./spaces";
import type { CatalogEntry, ConsentItem, KvDomainCount, KvInventory, OpenWindow, PlanStep, RemoteWindow, RunReport, TeleportPlan } from "./teleport";
@@ -259,6 +259,18 @@ const AboutShape = ref(
}),
);
+const UpdateShape = ref(
+ "UpdateState",
+ obj<UpdateState>()({
+ status: oneOf("idle", "checking", "available", "downloading", "downloaded", "error"),
+ currentVersion: str,
+ version: nullable(str),
+ percent: nullable(num),
+ notesUrl: nullable(str),
+ message: nullable(str),
+ }),
+);
+
const LoginItemShape = ref(
"LoginItemReport",
obj<LoginItemReport>()({ status: oneOf("enabled", "notRegistered", "requiresApproval", "notFound"), providesSpaces: bool, runsAgents: bool }),
@@ -842,6 +854,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"about.get": AboutShape,
"about.set": AboutShape,
"about.checkNow": AboutShape,
+ "update.get": UpdateShape,
+ "update.install": UpdateShape,
"experiments.get": ExperimentsShape,
"experiments.set": ExperimentsShape,
"loginItem.get": LoginItemShape,
@@ -1155,6 +1169,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"about.get": AboutShape,
"about.set": AboutShape,
"about.checkNow": AboutShape,
+ "update.get": UpdateShape,
+ "update.install": UpdateShape,
"loginItem.get": LoginItemShape,
"loginItem.set": LoginItemShape,
"loginItem.openSettings": nul,
diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.ts
index b0eea97b7d..a47c6d328e 100644
--- a/apps/cua-spaces-web/src/bridge/coverage.ts
+++ b/apps/cua-spaces-web/src/bridge/coverage.ts
@@ -136,6 +136,8 @@ export const HOST_COVERAGE = {
"about.get": { webkit: { methods: ["about.get"] }, tauri: ST["about.get"] },
"about.set": { webkit: { methods: ["about.set"] }, tauri: ST["about.set"], unsupported: { tauri: "the Tauri updater has one feed and no controls" } },
"about.checkNow": { webkit: { methods: ["about.checkNow"] }, tauri: ST["about.checkNow"], unsupported: { tauri: "the Tauri updater has one feed and no controls" } },
+ "update.get": { webkit: { methods: ["update.get"] }, tauri: ST["update.get"], unsupported: { tauri: "the Tauri updater has no in-app indicator" } },
+ "update.install": { webkit: { methods: ["update.install"] }, tauri: ST["update.install"], unsupported: { tauri: "the Tauri updater has no in-app indicator" } },
"experiments.get": { webkit: { methods: ["app.info"] }, tauri: ST["experiments.get"] },
"experiments.set": { webkit: { methods: ["app.info", "settings.choose"] }, tauri: ST["experiments.set"] },
"loginItem.get": { webkit: { methods: ["loginItem.get"] }, tauri: ST["loginItem.get"] },
diff --git a/apps/cua-spaces-web/src/bridge/ops/settings.ts b/apps/cua-spaces-web/src/bridge/ops/settings.ts
index 894fb83156..bc90d64e6d 100644
--- a/apps/cua-spaces-web/src/bridge/ops/settings.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/settings.ts
@@ -23,6 +23,7 @@ import type {
StorageInput,
StorageRequest,
UpdateChannelId,
+ UpdateState,
} from "../contracts/settings";
type Empty = Record<string, never>;
@@ -35,6 +36,13 @@ export interface SettingsOperations {
/** Check Now. */
"about.checkNow": { args: Empty; result: AboutInput };
+ /** The in-app update indicator: where the host's updater is. */
+ "update.get": { args: Empty; result: UpdateState };
+ /** "Restart to update": installs the downloaded update and relaunches.
+ * Only a click calls it; the host never restarts on its own. With nothing
+ * downloaded it changes nothing and answers the state. */
+ "update.install": { args: Empty; result: UpdateState };
+
/** Settings, Experiments: the switches as stored. */
"experiments.get": { args: Empty; result: Experiments };
"experiments.set": { args: { experiments: Experiments }; result: Experiments };
@@ -81,6 +89,8 @@ export const SETTINGS_OPERATIONS = [
"about.get",
"about.set",
"about.checkNow",
+ "update.get",
+ "update.install",
"experiments.get",
"experiments.set",
"loginItem.get",
@@ -156,6 +166,8 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string
"about.get": about,
"about.set": () => Promise.reject(new UnsupportedOperationError("tauri", "about.set")),
"about.checkNow": () => Promise.reject(new UnsupportedOperationError("tauri", "about.checkNow")),
+ "update.get": () => Promise.reject(new UnsupportedOperationError("tauri", "update.get")),
+ "update.install": () => Promise.reject(new UnsupportedOperationError("tauri", "update.install")),
// The Tauri app keeps the switches in its UI storage, as its own Settings does.
"experiments.get": async () => readExperiments(),
@@ -232,13 +244,15 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string
}
/** The Tauri updater has one feed and no controls. */
-export const TAURI_SETTINGS_UNSUPPORTED = ["about.set", "about.checkNow"] as const satisfies readonly SettingsOpName[];
+export const TAURI_SETTINGS_UNSUPPORTED = ["about.set", "about.checkNow", "update.get", "update.install"] as const satisfies readonly SettingsOpName[];
/** The Tauri commands each operation calls (`coverage.ts`). */
export const SETTINGS_TAURI_COMMANDS = {
"about.get": ["plugin:app|version", "get_environment"],
"about.set": [],
"about.checkNow": [],
+ "update.get": [],
+ "update.install": [],
"experiments.get": [],
"experiments.set": ["ui_storage_set"],
"loginItem.get": ["login_item_status", "host_status", "agents_tool"],
diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
index deddcb4539..c9b99eda9e 100644
--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts
@@ -67,6 +67,8 @@ export const WEBKIT_PAGE_OPS = [
"about.get",
"about.set",
"about.checkNow",
+ "update.get",
+ "update.install",
"loginItem.get",
"loginItem.set",
"loginItem.openSettings",
@@ -242,6 +244,8 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) =
"about.get": call("about.get"),
"about.set": call("about.set"),
"about.checkNow": call("about.checkNow"),
+ "update.get": call("update.get"),
+ "update.install": call("update.install"),
"loginItem.get": call("loginItem.get"),
"loginItem.set": call("loginItem.set"),
"loginItem.openSettings": none("loginItem.openSettings"),
diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.ts
index a7b030c4c4..5d9a128acb 100644
--- a/apps/cua-spaces-web/src/bridge/protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/protocol.ts
@@ -319,6 +319,8 @@ export type HostEvent =
| { type: "spaces.createProgress"; progress: CreateProgress }
| { type: "machines.changed" }
| { type: "settings.changed" }
+ /** The host's updater moved on (found, downloading, ready): ask `update.get` again. */
+ | { type: "update.changed" }
| { type: "keyvault.changed" }
/** Tauri `auth:signed-in`. */
| { type: "session.signedIn"; identity?: string }
@@ -343,6 +345,7 @@ export const HOST_EVENTS = [
"spaces.createProgress",
"machines.changed",
"settings.changed",
+ "update.changed",
"keyvault.changed",
"session.signedIn",
"session.signInFailed",
diff --git a/apps/cua-spaces-web/src/bridge/settings-feature.ts b/apps/cua-spaces-web/src/bridge/settings-feature.ts
index 88e3a19b2a..ff9fc47b5b 100644
--- a/apps/cua-spaces-web/src/bridge/settings-feature.ts
+++ b/apps/cua-spaces-web/src/bridge/settings-feature.ts
@@ -35,6 +35,7 @@ import type {
StorageInput,
StorageRequest,
StorageState,
+ UpdateState,
} from "./contracts/settings";
import type { HostEvent, SettingsValues } from "./protocol";
import {
@@ -60,7 +61,7 @@ import {
storageSection,
} from "./settings-derive";
-export type FeatureName = "about" | "experiments" | "loginItem" | "devices" | "storage" | "notifications";
+export type FeatureName = "about" | "update" | "experiments" | "loginItem" | "devices" | "storage" | "notifications";
export interface FeatureResource<T> {
data: T | undefined;
@@ -78,6 +79,12 @@ export interface AboutData {
canChange: boolean;
}
+export interface UpdateData {
+ state: UpdateState;
+ /** "Restart to update" is running. */
+ installing: boolean;
+}
+
export interface ExperimentsData {
experiments: Experiments;
/** The core's Experiments tab; null without the core. */
@@ -130,6 +137,10 @@ export interface FeatureOptions {
}
const NOTIFICATIONS_POLL_MS = 5_000;
+/** The host also tells the page when its updater moves on (`update.changed`);
+ * this is the slow safety net, and the pace while a download runs. */
+const UPDATE_POLL_MS = 60_000;
+const UPDATE_DOWNLOAD_POLL_MS = 2_000;
const STORAGE_POLL_MS = 2_000;
const ENROLL_POLL_MS = 3_000;
const ENROLL_POLL_LIMIT = 200;
@@ -164,6 +175,7 @@ export class SettingsFeature {
private readonly options: FeatureOptions;
private resources: { [K in FeatureName]: FeatureResource<unknown> } = {
about: idle(),
+ update: idle(),
experiments: idle(),
loginItem: idle(),
devices: idle(),
@@ -182,6 +194,8 @@ export class SettingsFeature {
private about: AboutInput | undefined;
private aboutCanChange = true;
+ private update: UpdateState | undefined;
+ private updateInstalling = false;
private experiments: Experiments = {};
private loginItem: LoginItemInput | undefined;
private devices: DevicesInput | undefined;
@@ -236,6 +250,7 @@ export class SettingsFeature {
this.ensured.add(name);
// The launch-at-login line and Storage's place follow the experiments.
if (name === "loginItem" || name === "storage") this.ensure("experiments");
+ if (name === "update") this.every("update-slow", UPDATE_POLL_MS, () => this.refresh("update"));
if (name === "notifications") this.every("notifications", NOTIFICATIONS_POLL_MS, () => this.refresh("notifications"));
void this.refresh(name);
}
@@ -261,6 +276,15 @@ export class SettingsFeature {
this.about = about;
break;
}
+ case "update": {
+ const state = await this.adapter.call("update.get", {});
+ if (pinned()) return;
+ this.update = state;
+ // A running download is followed closely; the host's event covers the rest.
+ if (state.status === "downloading") this.every("update", UPDATE_DOWNLOAD_POLL_MS, () => this.refresh("update"));
+ else this.stop("update");
+ break;
+ }
case "experiments": {
const experiments = await this.adapter.call("experiments.get", {});
if (pinned()) return;
@@ -297,6 +321,10 @@ export class SettingsFeature {
this.publish(name);
} catch (e) {
if (this.disposed) return;
+ if (name === "update" && isUnsupported(e)) {
+ this.stop("update");
+ this.stop("update-slow");
+ }
this.set(name, { isLoading: false, error: isUnsupported(e) ? null : toError(e), unsupported: isUnsupported(e) });
}
}
@@ -319,6 +347,9 @@ export class SettingsFeature {
case "about":
if (this.about) done({ input: this.about, view: aboutView(this.core, this.about), canChange: this.aboutCanChange } satisfies AboutData);
break;
+ case "update":
+ if (this.update) done({ state: this.update, installing: this.updateInstalling } satisfies UpdateData);
+ break;
case "experiments":
done({ experiments: this.experiments, page: experimentsPage(this.core, this.experiments) } satisfies ExperimentsData);
// What follows the switches.
@@ -369,6 +400,23 @@ export class SettingsFeature {
this.timers.delete(key);
}
+ /* ---- In-app update ---- */
+
+ /** "Restart to update". The host relaunches the app when it accepts. */
+ async installUpdate(): Promise<void> {
+ if (this.updateInstalling) return;
+ this.updateInstalling = true;
+ this.publish("update");
+ try {
+ this.update = await this.adapter.call("update.install", {});
+ } catch (e) {
+ throw toError(e);
+ } finally {
+ this.updateInstalling = false;
+ this.publish("update");
+ }
+ }
+
/* ---- About ---- */
async setAbout(patch: { autoCheck?: boolean; autoInstall?: boolean; channel?: AboutInput["channel"] }): Promise<void> {
@@ -812,6 +860,10 @@ export class SettingsFeature {
case "settings.changed":
reload("about", "experiments", "loginItem");
break;
+ case "update.changed":
+ // Settings, About follows the same updater (Last checked, Checking...).
+ reload("update", "about");
+ break;
case "session.signedIn":
case "session.signedOut":
case "session.changed":
diff --git a/apps/cua-spaces-web/src/bridge/settings-hooks.ts b/apps/cua-spaces-web/src/bridge/settings-hooks.ts
index 7d5bb5d6aa..445b02f6a4 100644
--- a/apps/cua-spaces-web/src/bridge/settings-hooks.ts
+++ b/apps/cua-spaces-web/src/bridge/settings-hooks.ts
@@ -22,9 +22,10 @@ import type {
NotificationsData,
SettingsFeature,
StorageData,
+ UpdateData,
} from "./settings-feature";
-export type { AboutData, DevicesData, ExperimentsData, FeatureResource, LoginItemData, NotificationsData, StorageData } from "./settings-feature";
+export type { UpdateData, AboutData, DevicesData, ExperimentsData, FeatureResource, LoginItemData, NotificationsData, StorageData } from "./settings-feature";
function useCtx(): BridgeContextValue {
const ctx = useContext(BridgeContext);
@@ -69,6 +70,18 @@ export function useAbout(): AboutHook {
return { ...r, setAbout: (p) => run((f) => f.setAbout(p)), checkNow: () => run((f) => f.checkNow()) };
}
+export interface UpdateHook extends Hook<UpdateData> {
+ /** "Restart to update": the host installs the downloaded update and relaunches. */
+ install(): Promise<void>;
+}
+
+/** The in-app update indicator: the host's updater state (found, downloading, ready). */
+export function useUpdate(): UpdateHook {
+ const r = useFeature<UpdateData>("update");
+ const run = useRun();
+ return { ...r, install: () => run((f) => f.installUpdate()) };
+}
+
export interface ExperimentsHook extends Hook<ExperimentsData> {
/** A switch's choice (`on` / `off`), by row id (`experiment:cua_volume`). */
chooseExperiment(row: string, option: string): Promise<void>;
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 5813a1f919..e1018d9fdf 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -103,6 +103,8 @@ export const WEBKIT_METHODS = [
"about.get",
"about.set",
"about.checkNow",
+ "update.get",
+ "update.install",
"loginItem.get",
"loginItem.set",
"loginItem.openSettings",
@@ -185,6 +187,7 @@ export const WEBKIT_EVENTS = [
"keyvault.changed",
"session.changed",
"settings.changed",
+ "update.changed",
"agents.changed",
"teleport.progress",
"startup.changed",
diff --git a/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx
index 92e2019542..f229f6c77f 100644
--- a/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx
+++ b/apps/cua-spaces-web/src/components/shell/relay-allowance-notice.tsx
@@ -2,7 +2,7 @@
// Copyright (c) 2026 Cua AI, Inc.
import { XIcon } from "lucide-react";
-import { useState } from "react";
+import { useSyncExternalStore } from "react";
import { useRelayUsageView, useSession } from "@/bridge";
import { Button } from "@/components/ui/button";
@@ -17,6 +17,23 @@ function readDismissed(): string | null {
}
}
+const listeners = new Set<() => void>();
+const subscribe = (l: () => void) => {
+ listeners.add(l);
+ return () => listeners.delete(l);
+};
+
+/**
+ * Whether the allowance notice is on screen now. The update indicator
+ * (`update-indicator.tsx`) steps back to an icon while it is, so the two
+ * prompts are never both open at once.
+ */
+export function useRelayAllowanceShowing(): boolean {
+ const notice = useRelayUsageView()?.notice;
+ const dismissed = useSyncExternalStore(subscribe, readDismissed, () => null);
+ return Boolean(notice) && dismissed !== notice?.dismissKey;
+}
+
/**
* The relay allowance for the month is used up: one line above every page
* with Upgrade, until dismissed (for that month and reason: the core's
@@ -25,7 +42,7 @@ function readDismissed(): string | null {
export function RelayAllowanceNotice() {
const notice = useRelayUsageView()?.notice;
const { openExternal } = useSession();
- const [dismissed, setDismissed] = useState(readDismissed);
+ const dismissed = useSyncExternalStore(subscribe, readDismissed, () => null);
if (!notice || dismissed === notice.dismissKey) return null;
const dismiss = () => {
try {
@@ -33,7 +50,7 @@ export function RelayAllowanceNotice() {
} catch {
// Not kept: it shows again next launch.
}
- setDismissed(notice.dismissKey);
+ for (const l of [...listeners]) l();
};
const upgradeUrl = notice.upgradeUrl;
return (
diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
index 3324c8919a..7241ef7600 100644
--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx
+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
@@ -17,6 +17,7 @@ import { SIDEBAR_DEFAULT, useUiStore } from "@/stores/ui";
import { Shortcut } from "@/components/ui/kbd";
import { SignInLink } from "@/components/sign-in-link";
import { useNavItems } from "./nav";
+import { SidebarUpdateIndicator } from "./update-indicator";
export function Sidebar() {
const width = useUiStore((s) => s.sidebarWidth);
@@ -65,7 +66,10 @@ export function Sidebar() {
);
})}
</nav>
- <AccountFooter />
+ <div className="mt-auto">
+ <SidebarUpdateIndicator />
+ <AccountFooter />
+ </div>
<ResizeHandle />
</aside>
);
diff --git a/apps/cua-spaces-web/src/components/shell/top-bar.tsx b/apps/cua-spaces-web/src/components/shell/top-bar.tsx
index e80d883208..fdbdee738f 100644
--- a/apps/cua-spaces-web/src/components/shell/top-bar.tsx
+++ b/apps/cua-spaces-web/src/components/shell/top-bar.tsx
@@ -11,6 +11,7 @@ import { bindingFor } from "@/lib/keybindings";
import { useTheme } from "@/lib/theme";
import { useUiStore } from "@/stores/ui";
import { useNavItems } from "./nav";
+import { TopBarUpdateIndicator } from "./update-indicator";
export function TopBar() {
const sidebarOpen = useUiStore((s) => s.sidebarOpen);
@@ -46,6 +47,7 @@ export function TopBar() {
<span className="flex-1 truncate text-left">Search or run a command</span>
<Shortcut spec={bindingFor("commandPalette.toggle") ?? ""} />
</button>
+ {sidebarOpen ? null : <TopBarUpdateIndicator />}
<Tooltip content={resolved === "dark" ? "Switch to light appearance" : "Switch to dark appearance"}>
<Button
variant="ghost"
diff --git a/apps/cua-spaces-web/src/components/shell/update-copy.test.ts b/apps/cua-spaces-web/src/components/shell/update-copy.test.ts
new file mode 100644
index 0000000000..ee0ef88b14
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/update-copy.test.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+
+import type { UpdateState } from "@/bridge";
+import { restartWarning, runsInProgress, updateView } from "./update-copy";
+
+const base: UpdateState = { status: "idle", currentVersion: "0.9.2", version: null, percent: null, notesUrl: null, message: null };
+
+describe("updateView", () => {
+ it("is quiet while idle, checking or failed", () => {
+ expect(updateView(undefined)).toBeNull();
+ for (const status of ["idle", "checking", "error"] as const) expect(updateView({ ...base, status, message: "offline" })).toBeNull();
+ });
+
+ it("says it is downloading, with the percent when the host has one", () => {
+ expect(updateView({ ...base, status: "available", version: "0.9.3" })).toEqual({ kind: "downloading", label: "Downloading update 0.9.3…", percent: null });
+ expect(updateView({ ...base, status: "downloading", version: "0.9.3", percent: 42.9 })).toEqual({ kind: "downloading", label: "Downloading update 0.9.3 (42%)", percent: 42 });
+ expect(updateView({ ...base, status: "downloading", version: "0.9.3", percent: 140 })?.kind).toBe("downloading");
+ });
+
+ it("says it is ready once downloaded", () => {
+ expect(updateView({ ...base, status: "downloaded", version: "0.9.3", percent: 100 })).toEqual({ kind: "ready", label: "Update ready", detail: "Cua Spaces 0.9.3" });
+ expect(updateView({ ...base, status: "downloaded" })).toEqual({ kind: "ready", label: "Update ready", detail: "A new version of Cua Spaces" });
+ });
+});
+
+describe("restart guard", () => {
+ it("counts only runs that are working", () => {
+ expect(runsInProgress(undefined)).toBe(0);
+ expect(runsInProgress([{ status: "idle" }, { status: "running" }, { status: "failed" }, { status: "running" }])).toBe(2);
+ });
+
+ it("names what a restart would stop", () => {
+ expect(restartWarning(1).description).toContain("An agent is still working");
+ expect(restartWarning(3).description).toContain("3 agents are still working");
+ expect(restartWarning(1)).toMatchObject({ confirm: "Restart anyway", cancel: "Not now" });
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/shell/update-copy.ts b/apps/cua-spaces-web/src/components/shell/update-copy.ts
new file mode 100644
index 0000000000..fd610cb9d2
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/update-copy.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import type { UpdateState } from "@/bridge";
+
+/** What the in-app update indicator shows for the host's updater. It is quiet:
+ * only a found, a downloading or a downloaded update shows anything. */
+export type UpdateView =
+ | { kind: "downloading"; label: string; percent: number | null }
+ | { kind: "ready"; label: string; detail: string };
+
+const versionText = (version: string | null) => (version ? ` ${version}` : "");
+
+/** The indicator for `state`; null when there is nothing to show (idle,
+ * checking, or a failed background step: the next check tries again). */
+export function updateView(state: UpdateState | undefined): UpdateView | null {
+ if (!state) return null;
+ switch (state.status) {
+ case "available":
+ case "downloading": {
+ const percent = state.status === "downloading" && state.percent !== null ? Math.max(0, Math.min(100, Math.floor(state.percent))) : null;
+ return { kind: "downloading", label: `Downloading update${versionText(state.version)}${percent === null ? "…" : ` (${percent}%)`}`, percent };
+ }
+ case "downloaded":
+ return { kind: "ready", label: "Update ready", detail: state.version ? `Cua Spaces ${state.version}` : "A new version of Cua Spaces" };
+ default:
+ return null;
+ }
+}
+
+/** Work a restart would cut short: the runs still working. */
+export function runsInProgress(runs: readonly { status: string }[] | undefined): number {
+ return runs?.filter((r) => r.status === "running").length ?? 0;
+}
+
+/** The question before "Restart to update" while work is running. */
+export function restartWarning(running: number): { title: string; description: string; confirm: string; cancel: string } {
+ return {
+ title: "Restart to update?",
+ description:
+ running === 1
+ ? "An agent is still working. Restarting Cua Spaces now stops it. You can also wait for it to finish and restart later."
+ : `${running} agents are still working. Restarting Cua Spaces now stops them. You can also wait for them to finish and restart later.`,
+ confirm: "Restart anyway",
+ cancel: "Not now",
+ };
+}
diff --git a/apps/cua-spaces-web/src/components/shell/update-indicator.test.tsx b/apps/cua-spaces-web/src/components/shell/update-indicator.test.tsx
new file mode 100644
index 0000000000..950dce2e2f
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/update-indicator.test.tsx
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createDemoAdapter } from "@/bridge/adapters/demo";
+import { noCore } from "@/bridge/__tests__/testCore";
+import { BridgeProvider, type DataAdapter, type UpdateState } from "@/bridge";
+
+const upsell = vi.hoisted(() => ({ open: false }));
+vi.mock("./relay-allowance-notice", () => ({ useRelayAllowanceShowing: () => upsell.open }));
+
+import { SidebarUpdateIndicator, TopBarUpdateIndicator } from "./update-indicator";
+
+afterEach(() => {
+ cleanup();
+ upsell.open = false;
+});
+
+const NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3";
+const ready: Partial<UpdateState> = { status: "downloaded", version: "0.9.3", percent: 100, notesUrl: NOTES };
+
+/** The demo host with an updater in `update`, recording what the page asks of it. */
+function host(update: Partial<UpdateState> | undefined, opts: { quiet?: boolean } = {}) {
+ const demo = createDemoAdapter({ latencyMs: 0, update });
+ const calls: string[] = [];
+ const opened: string[] = [];
+ const adapter: DataAdapter = {
+ ...demo,
+ call: (op, args) => {
+ calls.push(op);
+ if (op === "session.openExternal") {
+ opened.push((args as { url: string }).url);
+ return Promise.resolve(null) as ReturnType<typeof demo.call>;
+ }
+ // No agent is working: a restart cuts nothing short.
+ if (opts.quiet && op === "agents.runs") return Promise.resolve([]) as ReturnType<typeof demo.call>;
+ return demo.call(op, args);
+ },
+ };
+ const view = (ui = <SidebarUpdateIndicator />) =>
+ render(
+ <BridgeProvider adapter={adapter} core={noCore}>
+ {ui}
+ </BridgeProvider>,
+ );
+ return { demo, calls, opened, view };
+}
+
+describe("<SidebarUpdateIndicator>", () => {
+ it("shows nothing while up to date", async () => {
+ const { view, calls } = host(undefined);
+ view();
+ await waitFor(() => expect(calls).toContain("update.get"));
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ expect(document.querySelector("[data-update-indicator]")).toBeNull();
+ });
+
+ it("shows the download quietly, with its percent and no button", async () => {
+ const { view } = host({ status: "downloading", version: "0.9.3", percent: 42 });
+ view();
+ const row = await screen.findByRole("status");
+ expect(row.textContent).toBe("Downloading update 0.9.3 (42%)");
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("when ready, offers Restart to update and a What's new link to the release notes", async () => {
+ const { view, calls, opened } = host(ready, { quiet: true });
+ view();
+ expect(await screen.findByText("Update ready")).toBeTruthy();
+ expect(screen.getByText("Cua Spaces 0.9.3")).toBeTruthy();
+ fireEvent.click(screen.getByText("What's new"));
+ await waitFor(() => expect(opened).toEqual([NOTES]));
+ // Nothing installed until the click.
+ expect(calls).not.toContain("update.install");
+ fireEvent.click(screen.getByRole("button", { name: "Restart to update" }));
+ await waitFor(() => expect(calls).toContain("update.install"));
+ // The demo host relaunched into 0.9.3: the indicator is gone.
+ await waitFor(() => expect(document.querySelector("[data-update-indicator]")).toBeNull());
+ });
+
+ it("asks before restarting while an agent is running; Not now changes nothing, Restart anyway installs", async () => {
+ const { view, calls } = host(ready);
+ view();
+ // The demo has a run in progress.
+ await waitFor(() => expect(calls).toContain("agents.runs"));
+ await act(() => new Promise((r) => setTimeout(r, 20)));
+ fireEvent.click(await screen.findByRole("button", { name: "Restart to update" }));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(dialog.textContent).toContain("Restarting Cua Spaces now stops");
+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));
+ await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
+ expect(calls).not.toContain("update.install");
+ fireEvent.click(screen.getByRole("button", { name: "Restart to update" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Restart anyway" }));
+ await waitFor(() => expect(calls).toContain("update.install"));
+ });
+
+ it("steps back to an icon while an upgrade prompt is open", async () => {
+ upsell.open = true;
+ const { view } = host(ready);
+ view();
+ expect(await screen.findByRole("button", { name: "Update ready: restart to install" })).toBeTruthy();
+ expect(screen.queryByText("Restart to update")).toBeNull();
+ expect(screen.queryByText("What's new")).toBeNull();
+ });
+
+ it("shows nothing on a host with no updater (the call is unsupported)", async () => {
+ const demo = createDemoAdapter({ latencyMs: 0 });
+ const adapter: DataAdapter = { ...demo, call: (op, args) => (op === "update.get" ? Promise.reject(Object.assign(new Error("unsupported"), { code: "unsupported" })) : demo.call(op, args)) } as DataAdapter;
+ render(
+ <BridgeProvider adapter={adapter} core={noCore}>
+ <SidebarUpdateIndicator />
+ </BridgeProvider>,
+ );
+ await act(() => new Promise((r) => setTimeout(r, 10)));
+ expect(document.querySelector("[data-update-indicator]")).toBeNull();
+ });
+});
+
+describe("<TopBarUpdateIndicator>", () => {
+ it("is one icon with the same name, for when the sidebar is closed", async () => {
+ const { view } = host(ready);
+ view(<TopBarUpdateIndicator />);
+ expect(await screen.findByRole("button", { name: "Update ready: restart to install" })).toBeTruthy();
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/shell/update-indicator.tsx b/apps/cua-spaces-web/src/components/shell/update-indicator.tsx
new file mode 100644
index 0000000000..65b464df1c
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/shell/update-indicator.tsx
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { CheckIcon, DownloadIcon, RotateCwIcon } from "lucide-react";
+import { useState } from "react";
+
+import { useAgents, useSession, useUpdate } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { ConfirmDialog } from "@/components/ui/alert-dialog";
+import { Menu } from "@/components/ui/menu";
+import { toast } from "@/components/ui/toast";
+import { cn } from "@/lib/utils";
+import { useRelayAllowanceShowing } from "./relay-allowance-notice";
+import { restartWarning, runsInProgress, updateView, type UpdateView } from "./update-copy";
+
+/**
+ * Everything the indicator needs: what the host's updater shows, and the two
+ * actions. "Restart to update" asks first while an agent is running, and the
+ * host restarts only on this call: nothing here restarts on its own.
+ */
+function useUpdateIndicator() {
+ const { data, install } = useUpdate();
+ const { data: agents } = useAgents();
+ const { openExternal } = useSession();
+ const [asking, setAsking] = useState(false);
+ const view = updateView(data?.state);
+ const running = runsInProgress(agents?.runs);
+ const notesUrl = data?.state.notesUrl ?? null;
+
+ const restartNow = () => {
+ install().catch((e: unknown) => toast("Couldn't restart to update", { description: e instanceof Error ? e.message : String(e) }));
+ };
+ return {
+ view,
+ running,
+ installing: data?.installing ?? false,
+ asking,
+ setAsking,
+ restart: () => (running > 0 ? setAsking(true) : restartNow()),
+ restartNow,
+ whatsNew: notesUrl ? () => void openExternal(notesUrl).catch(() => {}) : null,
+ };
+}
+
+function ReadyIcon() {
+ return (
+ <span className="relative grid size-4 place-items-center" aria-hidden>
+ <RotateCwIcon className="size-4" strokeWidth={1.75} />
+ <span className="absolute -right-1 -bottom-1 grid size-2.5 place-items-center rounded-full bg-foreground text-background ring-2 ring-sidebar">
+ <CheckIcon className="size-2" strokeWidth={3} />
+ </span>
+ </span>
+ );
+}
+
+function ProgressRing({ percent }: { percent: number | null }) {
+ const r = 7;
+ const c = 2 * Math.PI * r;
+ return (
+ <span className="relative grid size-5 place-items-center" aria-hidden>
+ <svg viewBox="0 0 20 20" className={cn("absolute inset-0 size-full -rotate-90", percent === null && "animate-spin")}>
+ <circle cx="10" cy="10" r={r} fill="none" className="stroke-current/20" strokeWidth="1.5" />
+ <circle cx="10" cy="10" r={r} fill="none" stroke="currentColor" strokeLinecap="round" strokeWidth="1.5" strokeDasharray={c} strokeDashoffset={c * (1 - (percent ?? 25) / 100)} className="motion-reduce:transition-none" />
+ </svg>
+ <DownloadIcon className="size-2.5" />
+ </span>
+ );
+}
+
+function RestartDialog({ ui }: { ui: ReturnType<typeof useUpdateIndicator> }) {
+ const w = restartWarning(ui.running);
+ return (
+ <ConfirmDialog open={ui.asking} onOpenChange={ui.setAsking} title={w.title} description={w.description} confirmLabel={w.confirm} cancelLabel={w.cancel} destructive onConfirm={ui.restartNow} />
+ );
+}
+
+/**
+ * The sidebar's update line, above the account: quiet while it downloads,
+ * and a "Restart to update" with a "What's new" link once it is ready. While
+ * the relay allowance notice (an upgrade prompt) is open it shrinks to an
+ * icon, so the two are never both open.
+ */
+export function SidebarUpdateIndicator() {
+ const ui = useUpdateIndicator();
+ const upsellOpen = useRelayAllowanceShowing();
+ if (!ui.view) return null;
+ if (ui.view.kind === "downloading") return <DownloadingRow view={ui.view} />;
+ return (
+ <div data-update-indicator="ready" className="border-t px-3 py-2.5">
+ {upsellOpen ? (
+ <UpdateMenu ui={ui} compact />
+ ) : (
+ <>
+ <div className="flex items-center gap-2.5">
+ <span className="text-muted-foreground">
+ <ReadyIcon />
+ </span>
+ <div className="min-w-0 flex-1 leading-tight">
+ <div className="truncate text-xs font-medium">{ui.view.label}</div>
+ <div className="truncate text-2xs text-muted-foreground">{ui.view.detail}</div>
+ </div>
+ </div>
+ <div className="mt-2 flex items-center gap-3">
+ <Button size="sm" variant="outline" className="min-w-0 flex-1" data-update-restart="" disabled={ui.installing} onClick={ui.restart}>
+ Restart to update
+ </Button>
+ {ui.whatsNew ? (
+ <button type="button" data-update-whats-new="" onClick={ui.whatsNew} className="shrink-0 text-2xs text-muted-foreground underline decoration-dotted underline-offset-4 hover:text-foreground">
+ What's new
+ </button>
+ ) : null}
+ </div>
+ </>
+ )}
+ <RestartDialog ui={ui} />
+ </div>
+ );
+}
+
+function DownloadingRow({ view }: { view: Extract<UpdateView, { kind: "downloading" }> }) {
+ return (
+ <div data-update-indicator="downloading" role="status" className="flex items-center gap-2.5 border-t px-3 py-2.5 text-muted-foreground">
+ <ProgressRing percent={view.percent} />
+ <span className="min-w-0 flex-1 truncate text-2xs">{view.label}</span>
+ </div>
+ );
+}
+
+/** One icon with the same actions in a menu: the top bar (sidebar closed) and the compact sidebar. */
+function UpdateMenu({ ui, compact = false }: { ui: ReturnType<typeof useUpdateIndicator>; compact?: boolean }) {
+ if (!ui.view) return null;
+ const tip = ui.view.kind === "ready" ? `${ui.view.label}: restart to install` : ui.view.label;
+ const items = ui.view.kind === "ready" ? [{ label: "Restart to update", onSelect: ui.restart, disabled: ui.installing }, ...(ui.whatsNew ? [{ label: "What's new", onSelect: ui.whatsNew }] : [])] : [];
+ const icon = ui.view.kind === "ready" ? <ReadyIcon /> : <ProgressRing percent={ui.view.percent} />;
+ const button = (
+ <Button variant="ghost" size="icon-sm" aria-label={tip} title={tip} data-update-icon="" className={cn("text-muted-foreground", compact && "w-full justify-start gap-2 px-1.5")}>
+ {icon}
+ {compact ? <span className="truncate text-2xs">{ui.view.label}</span> : null}
+ </Button>
+ );
+ return (
+ <>
+ {items.length > 0 ? <Menu trigger={button} items={items} /> : button}
+ <RestartDialog ui={ui} />
+ </>
+ );
+}
+
+/** The top bar's update icon, shown only while the sidebar (and its line) is closed. */
+export function TopBarUpdateIndicator() {
+ const ui = useUpdateIndicator();
+ if (!ui.view) return null;
+ return (
+ <span data-update-indicator={ui.view.kind}>
+ <UpdateMenu ui={ui} />
+ </span>
+ );
+}
diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
index 91d9593311..85ea6f9d7e 100644
--- a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
+++ b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
@@ -46,7 +46,7 @@ Every event carries: `telemetry_schema_version`, `event_version`, `product`
| `cua_keyvault_action` | `action` (`setup`, `unlock`, `lock`, `import`, `site_login`), `method` (`os_key_store` (Touch ID on a Mac), `passphrase`, `recovery_key`, `none`), `outcome` | Keyvault adoption and how it is unlocked. Nothing about what is stored. |
| `cua_share` | `action` (`share`, `unshare`, `change_role`), `role` (`viewer`, `editor`, `none`), `outcome` | Sharing, and how often it is view-only. Never who. |
| `cua_presence_session` | `outcome`, `participants` (bucketed), `duration_bucket` | Multiplayer sessions, their size and length. |
-| `cua_app_update` | `action` (`checked`, `found`, `not_found`, `installed`, `failed`), `channel` (`stable` or `beta`), `trigger` (`user` or `background`) | Whether people update. |
+| `cua_app_update` | `action` (`checked`, `found`, `not_found`, `downloaded`, `installed`, `failed`), `channel` (`stable` or `beta`), `trigger` (`user` or `background`) | Whether people update. |
| `cua_device_enroll` | `method` (`sign_in`, `approval`, `rekey`), `outcome` | How devices join your account's relay. |
| `cua_experiment` | `action` (`experiment_on` or `experiment_off`), `experiment` (`cua_volume`, `your_cloud`, `sharing`) | Which experiments people try, and turn off again. |
diff --git a/docs/content/docs/spaces/guides/updates.mdx b/docs/content/docs/spaces/guides/updates.mdx
index 982316357a..6289d4878d 100644
--- a/docs/content/docs/spaces/guides/updates.mdx
+++ b/docs/content/docs/spaces/guides/updates.mdx
@@ -8,11 +8,15 @@ you. Everything is in **Settings, About**.
## How updates work
-The app checks once a day. When a new version is out, it offers to install
-it; with **Install updates automatically** on, it downloads the update in the
-background and installs it when you quit the app. **Check Now** checks right
+The app checks when it starts and again every few hours, and downloads a
+new version in the background. When one is ready, a line appears at the
+bottom of the sidebar: **Update ready**, with **Restart to update** and a
+**What's new** link to the release notes. Nothing restarts until you click.
+If an agent is still working, the app asks first. **Check Now** checks right
away, and **Last check** says when it last looked. Turn off **Automatically
-check for updates** to only check by hand.
+check for updates** to only check by hand. With **Install updates
+automatically** on (Windows and Linux), a downloaded update is also installed
+when you quit the app.
Every update is the same notarized disk image as the download on the
release page, and the app installs it only when its signature matches the
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index eec20d2a23..92fc3faecc 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -394,8 +394,17 @@ pub const KEYVAULT_METHODS: &[&str] = &["os_key_store", "passphrase", "recovery_
pub const SHARE_ACTIONS: &[&str] = &["share", "unshare", "change_role"];
/// The role a Space is shared with.
pub const SHARE_ROLES: &[&str] = &["viewer", "editor", "none"];
-/// Updater steps.
-pub const UPDATE_ACTIONS: &[&str] = &["checked", "found", "not_found", "installed", "failed"];
+/// Updater steps. In the product's words: `found` is update_available,
+/// `downloaded` is update_downloaded (the background download finished),
+/// `installed` is update_installed.
+pub const UPDATE_ACTIONS: &[&str] = &[
+ "checked",
+ "found",
+ "not_found",
+ "downloaded",
+ "installed",
+ "failed",
+];
/// Update channels (`cua-spaces-app-core` `about::UpdateChannel`).
pub const UPDATE_CHANNELS: &[&str] = &["stable", "beta"];
/// Who started an update check.
@@ -1258,7 +1267,7 @@ pub const EVENTS: &[EventSpec] = &[
p(
"action",
Kind::Enum(UPDATE_ACTIONS),
- "A check, an update found or not, installed, or failed.",
+ "A check, an update found or not, downloaded in the background, installed, or failed.",
),
p(
"channel",
diff --git a/libs/cua/crates/cua-telemetry/tests/privacy.rs b/libs/cua/crates/cua-telemetry/tests/privacy.rs
index 9d7097c119..20c91b6b16 100644
--- a/libs/cua/crates/cua-telemetry/tests/privacy.rs
+++ b/libs/cua/crates/cua-telemetry/tests/privacy.rs
@@ -216,6 +216,7 @@ fn all_builders(s: &str) -> Vec<Event> {
v.push(events::persistent_agent("create", Some(s), Outcome::Error, Some(s)).unwrap());
v.push(events::share("share", s, Outcome::Ok).unwrap());
v.push(events::app_update("installed", s, s).unwrap());
+ v.push(events::app_update("downloaded", s, s).unwrap());
v.push(events::device_enroll("rekey", Outcome::Ok).unwrap());
v.push(events::experiment("experiment_off", "your_cloud").unwrap());
v