Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Devices: Update all, one button for every machine this app may update (#7621)
Milind Sonic788300431b0
diff --git a/electron/main.mjs b/electron/main.mjsindex a26622a9d5..c1e36bedab 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -87,7 +87,7 @@ import {} from "./companion-account-service.mjs";import capabilitiesModule from "./capabilities.cjs";import environmentsModule from "./environments.cjs";-import { pairingPageUrl, vouchForPlainHttpServers } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare, remotePolicyAllows } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs";+import { pairingPageUrl, vouchForPlainHttpServers } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare, remotePolicyAllows } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs"; import { installUpdateAll } from "./update-all.mjs";import localOriginModule from "./local-origin.cjs";import { buildApplicationMenu } from "./menu.mjs";import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { installServerLending } from "./server-lending.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";@@ -2669,7 +2669,7 @@ ipcMain.handle("environments:add-from-link", localWorkspaceOnly("environments:adipcMain.handle("environments:forget", localWorkspaceOnly("environments:forget", (_event, id, purge) => forgetEnvironment(typeof id === "string" ? id : "", purge === true)));const savedServerStatus = createServerStatus({ entries: () => environmentsState.environments.filter((e) => e.kind === "remote" && !e.home && !e.team && !e.cloud), check: (origin) => checkServer(origin, (...args) => session.defaultSession.fetch(...args)),appVersion: app.getVersion(), onChange: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("environments:status-changed"); } });-installServerStatus({ ipcMain, guard: localWorkspaceOnly, status: savedServerStatus, app, powerMonitor, online: () => net.isOnline() });+installServerStatus({ ipcMain, guard: localWorkspaceOnly, status: savedServerStatus, app, powerMonitor, online: () => net.isOnline() }); installUpdateAll({ ipcMain, guard: localWorkspaceOnly, servers: savedServerStatus.saved, fetch: (...args) => session.defaultSession.fetch(...args), send: (channel, view) => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send(channel, view); } });// A cloud page may open the native chooser, never choose a destination or edit the saved list.// Once My Cloud is home the switcher lists only whole places, and shows only when there is more than My Cloud.diff --git a/electron/preload.cjs b/electron/preload.cjsindex 30d4f4dbc1..b1cad3e6c3 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -491,6 +491,19 @@ const bridge = {},},+ /** Update all on Settings → Devices: this app's own page only (never REMOTE_SAFE; main checks the sender again). */+ updateAll: {+ survey: (fresh) => ipcRenderer.invoke("update-all:survey", fresh === true),+ start: (ids, withApp) => ipcRenderer.invoke("update-all:start", ids, withApp === true),+ retry: (id) => ipcRenderer.invoke("update-all:retry", id),+ onState: (cb) => {+ ipcRenderer.invoke("update-all:state").then((view) => cb(view)).catch(() => {});+ const handler = (_event, view) => cb(view);+ ipcRenderer.on("update-all:state", handler);+ return () => ipcRenderer.removeListener("update-all:state", handler);+ },+ },+/** A remote page may read the list but never change where this window goes. */environments: {state: () => ipcRenderer.invoke("environments:state"),diff --git a/electron/server-status.mjs b/electron/server-status.mjsindex 2fd0e3e71d..bfc5015f20 100644--- a/electron/server-status.mjs+++ b/electron/server-status.mjs@@ -115,6 +115,10 @@ export function createServerStatus({ entries, check, appVersion, onChange = () =lastRefocus = now();for (const row of rows.values()) if (failing(row)) void look(row);},+ /** The saved servers it checks, `{ id, origin }`, whether or not they were looked at yet. */+ saved() {+ return entries().filter((entry) => entry.origin).map(({ id, origin }) => ({ id, origin }));+ },list() {return [...rows.values()].map((row) => ({ id: row.id, state: row.state, since: row.since, version: row.version, behind: versionBehind(row.version, appVersion), install: row.install }));},diff --git a/electron/update-all-run.d.mts b/electron/update-all-run.d.mtsnew file mode 100644index 0000000000..8cf7a008b1--- /dev/null+++ b/electron/update-all-run.d.mts@@ -0,0 +1,53 @@+import type { ServerUpdateStatus } from "../shared/server-update";++export declare const UPDATE_ALL: Readonly<{ pollMs: number; timeoutMs: number; giveUpMs: number }>;++/** Why a saved server is left out of Update all. */+export type ServerSkipWhy = "unreachable" | "signed-out" | "up-to-date" | "admin-only" | "by-hand" | "held" | "updating" | "too-soon";+/** Why a server is left out, or why its update (or this app's) failed. */+export type UpdateAllWhy =+ | ServerSkipWhy+ /** The run ended badly as the server reports it: `status.run` says how (rolled back, not changed, not started). */+ | "run"+ /** It finished on another version than the `latest` it named. */+ | "mismatch"+ /** It stayed unreachable past the server's own cut-off for a run. */+ | "not-back"+ /** This app's download, or its install, did not finish. */+ | "download" | "install"+ | "failed";++export interface ServerSurvey {+ reach: "ok" | "unreachable" | "signed-out" | "insecure";+ check?: { current: string; latest?: string; available: boolean; command?: string; install?: string } | null;+ status?: ServerUpdateStatus | null;+ adminOnly?: boolean;+}++export type ServerPlan =+ | { updates: true; current: string; latest: string; activeTurns: number }+ | { updates: false; why: ServerSkipWhy; current?: string; latest?: string; command?: string };++export interface AppPlan { version: string | null; handoff: boolean }++export interface UpdateAllFailure { why: UpdateAllWhy; version?: string | null; command?: string; status?: ServerUpdateStatus }++export interface UpdateAllRow {+ phase: "waiting" | "updating" | "restarting" | "done" | "handed-off" | "failed";+ /** When this phase began (ms). */+ since: number;+ latest?: string;+ /** The version read back from the machine once it is done. */+ version?: string;+ failure?: UpdateAllFailure;+}++/** Rows by saved server id, and `app` for this app. */+export interface UpdateAllView { running: boolean; rows: Record<string, UpdateAllRow> }++/** What Devices learns before Update all: each saved server's plan and this app's. */+export interface UpdateAllSurvey { servers: Array<{ id: string; plan: ServerPlan }>; app: AppPlan | null; view: UpdateAllView }++export declare function surveyServer(origin: string, fetchImpl: typeof fetch, options?: { fresh?: boolean; timeoutMs?: number }): Promise<ServerSurvey>;+export declare function serverPlan(survey: ServerSurvey, now?: number): ServerPlan;+export declare function appPlan(state: { status: string; version?: string; installMode?: string } | null | undefined): AppPlan | null;diff --git a/electron/update-all-run.mjs b/electron/update-all-run.mjsnew file mode 100644index 0000000000..f10aeb979a--- /dev/null+++ b/electron/update-all-run.mjs@@ -0,0 +1,263 @@+// Update all, on Settings → Devices: every saved server this app may update, then this app last. Each server is driven by+// its own answers (`GET /api/updates/check`, `GET/POST /api/updates/server`) and counts as updated only once its+// descriptor reports the `latest` that server named itself.+import { allowedServerOrigin } from "./server-address.mjs";++/** `giveUpMs`: how long a server may stay unreachable, the two hours a server itself gives a run before calling it cut off. */+export const UPDATE_ALL = Object.freeze({ pollMs: 4_000, timeoutMs: 15_000, giveUpMs: 2 * 60 * 60_000 });++const STATUS = "/api/updates/server";+const DESCRIPTOR = "/.well-known/openmausbot/environment";+const FAILED_RUNS = new Set(["rolled-back", "rollback-failed", "not-changed", "not-started"]);+/** The desktop's clock and a server's may differ; a run asked for this long before a request with no answer is older. */+const CLOCK_SLACK_MS = 5 * 60_000;+const WANTED_APP = new Set(["downloading", "preparing", "downloaded"]);++const readJson = (response) => response.json().catch(() => null);+const isCheck = (body) => typeof body?.current === "string" && typeof body?.available === "boolean";+const isStatus = (body) => typeof body?.mode === "string" && typeof body?.current === "string";++function serverClient(origin, fetchImpl, timeoutMs) {+ const send = (path, init = {}) => fetchImpl(`${origin}${path}`, {+ redirect: "error", cache: "no-store", credentials: "include", signal: AbortSignal.timeout(timeoutMs), ...init,+ headers: { accept: "application/json", origin, ...init.headers },+ });+ return {+ send,+ /** The status the admin's button reads; null while the server can't answer it (restarting, unreachable). */+ async status() {+ try {+ const response = await send(STATUS);+ const body = response.ok ? await readJson(response) : null;+ return isStatus(body) ? body : null;+ } catch {+ return null;+ }+ },+ async post() {+ const response = await send(STATUS, { method: "POST", body: "{}", headers: { "content-type": "application/json" } });+ return { status: response.status, body: (await readJson(response)) ?? {} };+ },+ /** The version the server's public descriptor reports now: the read-back that confirms an update. */+ async version() {+ try {+ const response = await send(DESCRIPTOR, { credentials: "omit" });+ const body = response.ok ? await readJson(response) : null;+ return typeof body?.environmentId === "string" && typeof body.version === "string" ? body.version.slice(0, 32) : null;+ } catch {+ return null;+ }+ },+ };+}++/**+ * One look at a saved server before Update all. `reach`: `ok`, `unreachable`, `signed-out` (its session is gone), or+ * `insecure` (a public http address, never contacted). With `ok`: its update check, the admin's status (null on a+ * server without the button), and `adminOnly` when this computer's session there is not an admin's.+ */+export async function surveyServer(origin, fetchImpl, { fresh = false, timeoutMs = UPDATE_ALL.timeoutMs } = {}) {+ if (!allowedServerOrigin(origin)) return { reach: "insecure" };+ const server = serverClient(origin, fetchImpl, timeoutMs);+ try {+ const checked = await server.send(`/api/updates/check${fresh ? "?fresh=1" : ""}`);+ if (checked.status === 401 || checked.status === 403) return { reach: "signed-out" };+ if (checked.status === 404) return { reach: "ok", check: null, status: null, adminOnly: false };+ const check = checked.ok ? await readJson(checked) : null;+ if (!isCheck(check)) return { reach: "unreachable" };+ const answered = await server.send(STATUS);+ const body = await readJson(answered);+ if (answered.status === 403 && body?.code === "admin_only") return { reach: "ok", check, status: null, adminOnly: true };+ return { reach: "ok", check, status: answered.ok && isStatus(body) ? body : null, adminOnly: false };+ } catch {+ return { reach: "unreachable" };+ }+}++/**+ * Whether Update all updates this server, from its own answers only (never from how it compares with this app: its+ * updater moves it to its own stable channel's latest). Otherwise `why` it is skipped, with the command to run there+ * when it is updated by hand.+ */+export function serverPlan(survey, now = Date.now()) {+ if (survey.reach === "signed-out") return { updates: false, why: "signed-out" };+ if (survey.reach !== "ok") return { updates: false, why: "unreachable" };+ const { check, status } = survey;+ if (!check) return { updates: false, why: "by-hand" };+ if (!check.available || !check.latest) return { updates: false, why: "up-to-date", current: check.current };+ const by = { current: check.current, latest: check.latest };+ if (survey.adminOnly) return { updates: false, why: "admin-only", ...by };+ const command = status?.command ?? check.command;+ if (!status) return { updates: false, why: "by-hand", ...by, ...(command ? { command } : {}) };+ if (status.run?.outcome === "requested" || status.run?.outcome === "running") return { updates: false, why: "updating", ...by };+ if (status.mode === "held") return { updates: false, why: "held", ...by };+ if (status.mode !== "button") return { updates: false, why: "by-hand", ...by, ...(command ? { command } : {}) };+ if (status.retryAt && status.retryAt > now) return { updates: false, why: "too-soon", ...by };+ return { updates: true, ...by, activeTurns: status.activeTurns ?? 0 };+}++/** Whether this app takes part: an update it is downloading or has downloaded. `handoff`: it finishes in a terminal. */+export function appPlan(state) {+ if (!state || !WANTED_APP.has(state.status)) return null;+ return { version: state.version ?? null, handoff: state.installMode === "handoff" };+}++const deferred = () => {+ let resolve;+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };+};++/**+ * Runs Update all. Servers go first, in parallel, each settled on its own; this app (`app`: the updater's `state()`,+ * `check()`, `install()` and `onState(cb) → stop`) installs last, once every server is settled or handed to its own+ * updater (it took the request, or dropped the connection as it restarts). `onChange(view)` gets every new view.+ *+ * Row phases: `waiting` (this app, until the servers are handed off), `updating`, `restarting` (no answer while it+ * restarts), `done` (`version` read back), `handed-off` (this app's command is in a terminal), `failed` (`failure`).+ */+export function createUpdateAll({ fetch: fetchImpl, app = null, onChange = () => {}, now = Date.now, sleep = (ms) => new Promise((done) => setTimeout(done, ms)), pollMs = UPDATE_ALL.pollMs, giveUpMs = UPDATE_ALL.giveUpMs, timeoutMs = UPDATE_ALL.timeoutMs }) {+ let rows = {};+ let running = null;+ const tasks = new Map();++ const view = () => ({ running: Boolean(running), rows: structuredClone(rows) });+ const set = (id, patch) => {+ const before = rows[id];+ const next = { ...before, ...patch, since: !before || (patch.phase && patch.phase !== before.phase) ? now() : before.since };+ if (next.phase !== "failed") delete next.failure;+ for (const key of Object.keys(next)) if (next[key] === undefined) delete next[key];+ rows = { ...rows, [id]: next };+ onChange(view());+ };+ const finish = (id, version) => set(id, { phase: "done", version });+ const fail = (id, failure) => set(id, { phase: "failed", failure });++ async function updateServer({ id, origin, latest }, handOff) {+ set(id, { phase: "updating", latest, version: undefined });+ const server = serverClient(origin, fetchImpl, timeoutMs);+ const askedAt = now();+ let ours = null;+ try {+ const { status, body } = await server.post();+ const code = body.code;+ if (status === 202 || (status === 409 && code === "running")) ours = body.status?.run?.at ?? null;+ else if (status === 409 && code === "up-to-date") {+ const version = await server.version();+ return version === latest ? finish(id, version) : fail(id, { why: "mismatch", version: version ?? body.status?.current ?? null });+ } else if (status === 409 && code === "unavailable") return fail(id, { why: "by-hand", ...(body.status?.command ? { command: body.status.command } : {}) });+ else if (status === 429) return fail(id, { why: "too-soon" });+ else if (status === 401) return fail(id, { why: "signed-out" });+ else if (status === 403) return fail(id, { why: "admin-only" });+ else return fail(id, { why: "failed" });+ } catch {+ // No answer: the server may already be stopping for the update. It is followed as if it had said so.+ }+ const isOurs = (run) => Boolean(run) && (ours !== null ? run.at === ours : run.at >= askedAt - CLOCK_SLACK_MS);+ let downSince = null;+ for (;;) {+ await sleep(pollMs);+ const status = await server.status();+ if (!status) {+ handOff();+ if (rows[id]?.phase !== "restarting") set(id, { phase: "restarting" });+ downSince ??= now();+ const version = await server.version();+ if (version === latest) return finish(id, version);+ if (now() - downSince >= giveUpMs) return fail(id, { why: "not-back" });+ continue;+ }+ downSince = null;+ const run = isOurs(status.run) ? status.run : null;+ if (run?.outcome === "running") handOff();+ if (run && FAILED_RUNS.has(run.outcome)) return fail(id, { why: "run", status });+ const going = run?.outcome === "requested" || run?.outcome === "running";+ if (!going && (run || status.current === latest)) {+ const version = await server.version();+ if (version === latest) return finish(id, version);+ if (version !== null) return fail(id, { why: "mismatch", version, status });+ } else if (!going) return fail(id, { why: "failed" });+ if (rows[id]?.phase !== "updating") set(id, { phase: "updating" });+ }+ }++ async function confirmCurrent(id, origin) {+ const version = await serverClient(origin, fetchImpl, timeoutMs).version();+ const latest = rows[id]?.latest;+ if (latest && version === latest) finish(id, version);+ else fail(id, { why: version ? "mismatch" : "unreachable", ...(version ? { version } : {}) });+ }++ function serverTask(server) {+ const gate = deferred();+ const done = updateServer(server, gate.resolve).catch(() => fail(server.id, { why: "failed" })).finally(gate.resolve);+ tasks.set(server.id, { server, gate: gate.promise, done });+ return done;+ }++ const appStateWhere = (wanted) => new Promise((resolve) => {+ let stop = () => {};+ let settled = false;+ const look = (state) => {+ if (settled || !state || !wanted(state)) return;+ settled = true;+ stop();+ resolve(state);+ };+ stop = app.onState(look) ?? (() => {});+ if (settled) stop();+ look(app.state());+ });++ async function updateApp() {+ set("app", { phase: "updating" });+ if (!WANTED_APP.has(app.state()?.status)) await app.check();+ const ready = await appStateWhere((state) => state.status !== "downloading" && state.status !== "preparing" && state.status !== "checking");+ if (ready.status !== "downloaded") return fail("app", { why: "download" });+ set("app", { phase: "restarting", latest: ready.version ?? undefined });+ app.install();+ const after = await appStateWhere((state) => state.status === "error" || state.status === "handed-off" || state.status === "downloaded");+ if (after.status === "handed-off") return set("app", { phase: "handed-off" });+ return fail("app", { why: "install" });+ }++ async function appTask() {+ set("app", { phase: "waiting" });+ await Promise.all([...tasks.values()].map((task) => task.gate));+ await updateApp().catch(() => fail("app", { why: "install" }));+ }++ return {+ view,+ /** `servers`: `{ id, origin, latest }` for each server its plan updates; `withApp`: this app too, last. A start+ * while a run is going joins it. */+ start({ servers, withApp }) {+ if (running) return view();+ rows = {};+ tasks.clear();+ const jobs = servers.map(serverTask);+ if (withApp && app) jobs.push(appTask());+ running = Promise.allSettled(jobs).then(() => { running = null; onChange(view()); });+ onChange(view());+ return view();+ },+ /** Tries one failed row again: this app with `id` "app", or a server with `next` from a fresh look: its new+ * `{ origin, latest }`; `{ origin, current: true }` when it says it is up to date, settled by reading its version back;+ * or the `{ failure }` it gives when it no longer updates. */+ retry(id, next) {+ if (rows[id]?.phase !== "failed") return view();+ if (next?.failure) {+ fail(id, next.failure);+ return view();+ }+ const job = id === "app" ? (app ? updateApp().catch(() => fail("app", { why: "install" })) : null)+ : next?.origin && next.current ? confirmCurrent(id, next.origin).catch(() => fail(id, { why: "failed" }))+ : next?.origin && next.latest ? serverTask({ id, origin: next.origin, latest: next.latest }) : null;+ if (!job) return view();+ const all = running ?? Promise.resolve();+ running = Promise.allSettled([all, job]).then(() => { running = null; onChange(view()); });+ onChange(view());+ return view();+ },+ };+}diff --git a/electron/update-all-run.node-test.mjs b/electron/update-all-run.node-test.mjsnew file mode 100644index 0000000000..e3e228d090--- /dev/null+++ b/electron/update-all-run.node-test.mjs@@ -0,0 +1,369 @@+import assert from "node:assert/strict";+import test from "node:test";++import { appPlan, createUpdateAll, serverPlan, surveyServer, UPDATE_ALL } from "./update-all-run.mjs";++const COMMAND = "cd /opt/mausbot && sudo ./update.sh";++/** A saved server's update routes. Each read of GET /api/updates/server first applies the next of `steps` (the host's+ * runner moving on), so a test lays out what the server goes through, poll by poll. */+function fakeServer(clock, { current = "0.1.170", latest = "0.1.175", mode = "button", admin = true, steps = [], post = null, retryAt } = {}) {+ const server = { current, latest, mode, admin, run: undefined, down: false, steps: [...steps], calls: [], retryAt };+ server.status = () => ({+ mode: server.mode, current: server.current, latest: server.latest, available: server.current !== server.latest, activeTurns: 0,+ command: COMMAND, ...(server.run ? { run: server.run } : {}), ...(server.retryAt ? { retryAt: server.retryAt } : {}),+ });+ server.handle = async (path, init) => {+ const method = init.method ?? "GET";+ server.calls.push({ method, path, origin: init.headers?.origin, credentials: init.credentials });+ if (path === "/api/updates/server" && method === "GET") server.steps.shift()?.(server);+ if (server.down) throw new TypeError("fetch failed");+ if (path === "/.well-known/openmausbot/environment") return Response.json({ environmentId: "env-1", version: server.current });+ if (path.startsWith("/api/updates/check")) return Response.json({ current: server.current, latest: server.latest, available: server.current !== server.latest, install: "docker", command: "docker compose pull" });+ if (path === "/api/updates/server") {+ if (!server.admin) return Response.json({ error: "Only an admin of this server, signed in, can update it.", code: "admin_only" }, { status: 403 });+ if (method === "POST") {+ if (post) return post(server);+ server.run = { outcome: "requested", from: server.current, at: clock.now };+ return Response.json({ status: server.status() }, { status: 202 });+ }+ return Response.json(server.status());+ }+ return Response.json({ error: "no route" }, { status: 404 });+ };+ return server;+}++function world(servers) {+ const clock = { now: 1_000_000 };+ const made = Object.fromEntries(Object.entries(servers).map(([host, options]) => [host, fakeServer(clock, options)]));+ const fetchImpl = async (url, init = {}) => {+ const parsed = new URL(url);+ const server = made[parsed.host];+ if (!server) throw new TypeError("fetch failed");+ return server.handle(parsed.pathname + parsed.search, init);+ };+ return { clock, servers: made, fetch: fetchImpl };+}++/** The host's runner: takes the request, then the server goes down while its new version starts, then answers again. */+const running = (server) => { server.run = { ...server.run, outcome: "running" }; };+const down = (server) => { server.down = true; };+const backOn = (version, outcome = "updated") => (server) => {+ server.down = false;+ server.current = version;+ server.run = { ...server.run, outcome, to: version };+};++function fakeApp(initial = { status: "downloaded", version: "0.1.182", installMode: "restart" }) {+ let state = initial;+ const listeners = new Set();+ const app = {+ events: [],+ state: () => state,+ set(next) { state = { ...state, ...next }; for (const listener of listeners) listener(state); },+ check: async () => { app.events.push("check"); },+ install: () => { app.events.push("install"); app.set({ status: "installing" }); },+ onState: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },+ };+ return app;+}++function runner(w, app = null, extra = {}) {+ const views = [];+ const run = createUpdateAll({ fetch: w.fetch, app, now: () => w.clock.now, sleep: async (ms) => { w.clock.now += ms; }, onChange: (view) => views.push(view), ...extra });+ const until = (done) => new Promise((resolve) => {+ const look = () => (done(run.view()) ? resolve(run.view()) : setTimeout(look, 1));+ look();+ });+ const finished = () => until((view) => !view.running);+ /** This app's install quits the process; in a test the run stays open there, so the test waits for this app's row. */+ const restarted = () => until((view) => view.rows.app?.phase === "restarting" && Object.values(view.rows).every((row) => row === view.rows.app || row.phase === "done" || row.phase === "failed"));+ return { run, views, finished, restarted };+}++const survey = async (w, host, options) => serverPlan(await surveyServer(`https://${host}`, w.fetch, options), w.clock.now);++test("a server updates when its own answer says so, to its own stable latest, whatever this app's version", async () => {+ // This app is on 0.1.182; the server's stable channel is at 0.1.175. The target is the server's latest, never the app's.+ const w = world({ "vps.example.com": { current: "0.1.170", latest: "0.1.175" } });+ assert.deepEqual(await survey(w, "vps.example.com"), { updates: true, current: "0.1.170", latest: "0.1.175", activeTurns: 0 });+});++test("a server older than this app but current on its own channel is up to date, not updated", async () => {+ const w = world({ "vps.example.com": { current: "0.1.175", latest: "0.1.175" } });+ assert.deepEqual(await survey(w, "vps.example.com"), { updates: false, why: "up-to-date", current: "0.1.175" });+});++test("each skipped server says why, from the server's own answer", async () => {+ const w = world({+ "member.example.com": { admin: false },+ "held.example.com": { mode: "held" },+ "npm.example.com": { mode: "command" },+ "desk.example.com": { mode: "none" },+ "busy.example.com": { steps: [] },+ "soon.example.com": { retryAt: 2_000_000 },+ });+ w.servers["busy.example.com"].run = { outcome: "running", from: "0.1.170", at: 1 };+ assert.deepEqual(await survey(w, "member.example.com"), { updates: false, why: "admin-only", current: "0.1.170", latest: "0.1.175" });+ assert.deepEqual(await survey(w, "held.example.com"), { updates: false, why: "held", current: "0.1.170", latest: "0.1.175" });+ assert.deepEqual(await survey(w, "npm.example.com"), { updates: false, why: "by-hand", current: "0.1.170", latest: "0.1.175", command: COMMAND });+ assert.equal((await survey(w, "desk.example.com")).why, "by-hand");+ assert.equal((await survey(w, "busy.example.com")).why, "updating");+ assert.equal((await survey(w, "soon.example.com")).why, "too-soon");+ assert.deepEqual(await survey(w, "gone.example.com"), { updates: false, why: "unreachable" });+});++test("a server without the button answers 404 there and is updated by hand with its check's command", async () => {+ const w = world({ "old.example.com": {} });+ const handle = w.servers["old.example.com"].handle;+ w.servers["old.example.com"].handle = async (path, init) => (path === "/api/updates/server" ? Response.json({ error: "no route" }, { status: 404 }) : handle(path, init));+ assert.deepEqual(await survey(w, "old.example.com"), { updates: false, why: "by-hand", current: "0.1.170", latest: "0.1.175", command: "docker compose pull" });+});++test("a server whose sign-in is gone, or a public http address, is skipped; the http one is never contacted", async () => {+ const w = world({ "out.example.com": {} });+ const handle = w.servers["out.example.com"].handle;+ w.servers["out.example.com"].handle = async (path, init) => (path.startsWith("/api/") ? Response.json({ error: "unauthorized" }, { status: 401 }) : handle(path, init));+ assert.deepEqual(await survey(w, "out.example.com"), { updates: false, why: "signed-out" });+ let asked = 0;+ const plan = serverPlan(await surveyServer("http://203.0.113.7:8799", async () => { asked++; throw new Error("sent"); }));+ assert.deepEqual(plan, { updates: false, why: "unreachable" });+ assert.equal(asked, 0);+});++test("the look before Update all asks for a fresh check only when told, with the stored sign-in and its own origin", async () => {+ const w = world({ "vps.example.com": {} });+ await survey(w, "vps.example.com");+ await survey(w, "vps.example.com", { fresh: true });+ const calls = w.servers["vps.example.com"].calls;+ assert.deepEqual(calls.map((call) => call.path), ["/api/updates/check", "/api/updates/server", "/api/updates/check?fresh=1", "/api/updates/server"]);+ assert.ok(calls.every((call) => call.origin === "https://vps.example.com" && call.credentials === "include"));+});++test("this app takes part only with an update downloading or downloaded", () => {+ assert.deepEqual(appPlan({ status: "downloaded", version: "0.1.182", installMode: "restart" }), { version: "0.1.182", handoff: false });+ assert.deepEqual(appPlan({ status: "downloading", installMode: "handoff" }), { version: null, handoff: true });+ assert.equal(appPlan({ status: "idle" }), null);+ assert.equal(appPlan({ status: "error", version: "0.1.182" }), null);+ assert.equal(appPlan(null), null);+});++test("a server is done only once its descriptor reads back the latest it named, after restarting", async () => {+ const w = world({ "vps.example.com": { steps: [running, down, down, backOn("0.1.175")] } });+ const { run, views, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.vps.phase, "done");+ assert.equal(end.rows.vps.version, "0.1.175");+ assert.deepEqual([...new Set(views.map((view) => view.rows.vps?.phase))], ["updating", "restarting", "done"]);+ const calls = w.servers["vps.example.com"].calls;+ assert.deepEqual(calls.at(-1), { method: "GET", path: "/.well-known/openmausbot/environment", origin: "https://vps.example.com", credentials: "omit" });+ assert.equal(calls.filter((call) => call.method === "POST").length, 1);+});++test("a read-back that gets no answer is asked again, never taken for another version", async () => {+ let misses = 1;+ const w = world({ "vps.example.com": { steps: [running, down, backOn("0.1.175")] } });+ const handle = w.servers["vps.example.com"].handle;+ w.servers["vps.example.com"].handle = async (path, init) => {+ if (path === "/.well-known/openmausbot/environment" && !w.servers["vps.example.com"].down && misses-- > 0) throw new TypeError("fetch failed");+ return handle(path, init);+ };+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.vps.phase, "done");+ assert.equal(misses, -1);+});++test("the new version answering while the host's run is still going is not done: a rollback after it fails the row", async () => {+ const w = world({ "vps.example.com": { steps: [running, (server) => { server.current = "0.1.175"; }, (server) => {+ server.current = "0.1.170";+ server.run = { ...server.run, outcome: "rolled-back" };+ }] } });+ const { run, views, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.vps.failure.why, "run");+ assert.ok(views.every((view) => view.rows.vps?.phase !== "done"));+});++test("a server that answers while its run is going is followed for as long as it says so, without the unreachable cut-off", async () => {+ const steps = Array.from({ length: 2000 }, () => running);+ const w = world({ "vps.example.com": { steps: [...steps, down, backOn("0.1.175")] } });+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.vps.phase, "done");+ assert.ok(w.clock.now - 1_000_000 > UPDATE_ALL.giveUpMs);+});++test("an update the host calls done is not done while the server still reports the old version", async () => {+ const w = world({ "vps.example.com": { steps: [running, (server) => { server.run = { ...server.run, outcome: "unchanged", to: server.current }; }] } });+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.vps.phase, "failed");+ assert.equal(end.rows.vps.failure.why, "mismatch");+ assert.equal(end.rows.vps.failure.version, "0.1.170");+});++test("a server that lands on another version than the latest it named ends as a mismatch, not a wait", async () => {+ const w = world({ "vps.example.com": { steps: [running, down, backOn("0.1.176")] } });+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.deepEqual({ phase: end.rows.vps.phase, why: end.rows.vps.failure.why, version: end.rows.vps.failure.version }, { phase: "failed", why: "mismatch", version: "0.1.176" });+});++test("the server's own outcomes end a run: rolled back, not started, not changed", async () => {+ const outcome = (name, reason) => (server) => { server.run = { ...server.run, outcome: name, ...(reason ? { reason } : {}) }; };+ const w = world({+ "a.example.com": { steps: [running, outcome("rolled-back")] },+ "b.example.com": { steps: [outcome("not-started")] },+ "c.example.com": { steps: [running, outcome("not-changed", "no-room")] },+ });+ const { run, finished } = runner(w);+ run.start({ servers: ["a", "b", "c"].map((id) => ({ id, origin: `https://${id}.example.com`, latest: "0.1.175" })), withApp: false });+ const end = await finished();+ for (const id of ["a", "b", "c"]) assert.equal(end.rows[id].failure.why, "run", id);+ assert.equal(end.rows.a.failure.status.run.outcome, "rolled-back");+ assert.equal(end.rows.b.failure.status.run.outcome, "not-started");+ assert.equal(end.rows.c.failure.status.run.reason, "no-room");+});++test("each refusal of the request is its own failure; an update already running is followed", async () => {+ const refuse = (status, code) => () => Response.json({ error: "no", code, status: { mode: "button", current: "0.1.170", available: true, activeTurns: 0, command: COMMAND } }, { status });+ const w = world({+ "soon.example.com": { post: refuse(429, "too-soon") },+ "member.example.com": { post: refuse(403, "admin_only") },+ "full.example.com": { post: refuse(500, "unwritable") },+ "hand.example.com": { post: refuse(409, "unavailable") },+ "going.example.com": { post: (server) => { server.run = { outcome: "running", from: "0.1.170", at: 5 }; return Response.json({ code: "running", status: server.status() }, { status: 409 }); }, steps: [down, backOn("0.1.175")] },+ });+ const { run, finished } = runner(w);+ run.start({ servers: ["soon", "member", "full", "hand", "going"].map((id) => ({ id, origin: `https://${id}.example.com`, latest: "0.1.175" })), withApp: false });+ const end = await finished();+ assert.equal(end.rows.soon.failure.why, "too-soon");+ assert.equal(end.rows.member.failure.why, "admin-only");+ assert.equal(end.rows.full.failure.why, "failed");+ assert.deepEqual(end.rows.hand.failure, { why: "by-hand", command: COMMAND });+ assert.equal(end.rows.going.phase, "done");+});++test("one server failing never stops another, and this app installs last, once the other handed off", async () => {+ const w = world({+ "bad.example.com": { post: () => Response.json({ code: "unwritable" }, { status: 500 }) },+ "good.example.com": { steps: [(server) => server, running, down, backOn("0.1.175")] },+ });+ const app = fakeApp();+ const seen = [];+ app.install = () => { seen.push(w.servers["good.example.com"].run.outcome); app.set({ status: "installing" }); };+ const { run, views, restarted } = runner(w, app);+ run.start({ servers: [{ id: "bad", origin: "https://bad.example.com", latest: "0.1.175" }, { id: "good", origin: "https://good.example.com", latest: "0.1.175" }], withApp: true });+ const end = await restarted();+ assert.equal(end.rows.bad.phase, "failed");+ assert.equal(end.rows.good.phase, "done");+ assert.equal(seen.length, 1);+ assert.notEqual(seen[0], "requested");+ assert.equal(end.rows.app.phase, "restarting");+ assert.equal(views.find((view) => view.rows.app)?.rows.app.phase, "waiting");+});++test("a server the host never takes the request from holds this app until the server says it never started", async () => {+ const w = world({ "slow.example.com": { steps: [(server) => server, (server) => server, (server) => { server.run = { ...server.run, outcome: "not-started" }; }] } });+ const app = fakeApp();+ const seen = [];+ app.install = () => { seen.push(w.servers["slow.example.com"].run.outcome); app.set({ status: "installing" }); };+ const { run, restarted } = runner(w, app);+ run.start({ servers: [{ id: "slow", origin: "https://slow.example.com", latest: "0.1.175" }], withApp: true });+ const end = await restarted();+ assert.deepEqual(seen, ["not-started"]);+ assert.equal(end.rows.slow.failure.why, "run");+ assert.equal(end.rows.app.phase, "restarting");+});++test("when this app's download fails only this app is skipped", async () => {+ const w = world({ "vps.example.com": { steps: [running, down, backOn("0.1.175")] } });+ const app = fakeApp({ status: "downloading", percent: 40 });+ const { run, finished } = runner(w, app);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: true });+ await new Promise((resolve) => setTimeout(resolve, 20));+ app.set({ status: "error", message: "network" });+ const end = await finished();+ assert.equal(end.rows.vps.phase, "done");+ assert.equal(end.rows.app.failure.why, "download");+ assert.deepEqual(app.events, []);+});++test("this app's update handed to a terminal ends handed off", async () => {+ const w = world({});+ const app = fakeApp({ status: "downloaded", version: "0.1.182", installMode: "handoff" });+ app.install = () => { app.events.push("install"); app.set({ status: "installing" }); app.set({ status: "handed-off" }); };+ const { run, finished } = runner(w, app);+ run.start({ servers: [], withApp: true });+ const end = await finished();+ assert.equal(end.rows.app.phase, "handed-off");+});++test("an install that did not take (the updater stayed on downloaded) fails this app's row", async () => {+ const w = world({});+ const app = fakeApp();+ app.install = () => { app.events.push("install"); };+ const { run, finished } = runner(w, app);+ run.start({ servers: [], withApp: true });+ const end = await finished();+ assert.equal(end.rows.app.failure.why, "install");+});++test("a server that never comes back fails after the server's own cut-off, not before", async () => {+ const w = world({ "vps.example.com": { steps: [running, down] } });+ const { run, views, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.vps.failure.why, "not-back");+ const wentDown = views.find((view) => view.rows.vps?.phase === "restarting").rows.vps.since;+ assert.ok(w.clock.now - wentDown >= UPDATE_ALL.giveUpMs);+ assert.ok(w.clock.now - wentDown < UPDATE_ALL.giveUpMs + UPDATE_ALL.pollMs);+});++test("a request with no answer is followed, but an old run it never replaced is not taken for this one", async () => {+ const w = world({+ "lost.example.com": { post: (server) => { server.down = false; throw new TypeError("fetch failed"); } },+ });+ w.servers["lost.example.com"].run = { outcome: "rolled-back", from: "0.1.160", at: 1 };+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "lost", origin: "https://lost.example.com", latest: "0.1.175" }], withApp: false });+ const end = await finished();+ assert.equal(end.rows.lost.failure.why, "failed");+});++test("Retry runs one failed server again from a fresh look, or records why it no longer updates", async () => {+ let refuse = true;+ const w = world({ "vps.example.com": { post: (server) => {+ if (refuse) return Response.json({ code: "too-soon" }, { status: 429 });+ server.run = { outcome: "requested", from: server.current, at: 7 };+ return Response.json({ status: server.status() }, { status: 202 });+ }, steps: [] } });+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ assert.equal((await finished()).rows.vps.failure.why, "too-soon");+ refuse = false;+ w.servers["vps.example.com"].steps.push(running, down, backOn("0.1.175"));+ run.retry("vps", { origin: "https://vps.example.com", latest: "0.1.175" });+ assert.equal((await finished()).rows.vps.phase, "done");+ run.retry("vps", { failure: { why: "held" } });+ assert.equal(run.view().rows.vps.phase, "done");+});++test("Retry on a server that now says it is up to date settles it by reading its version back", async () => {+ const w = world({ "vps.example.com": { post: () => Response.json({ code: "too-soon" }, { status: 429 }) } });+ const { run, finished } = runner(w);+ run.start({ servers: [{ id: "vps", origin: "https://vps.example.com", latest: "0.1.175" }], withApp: false });+ assert.equal((await finished()).rows.vps.failure.why, "too-soon");+ w.servers["vps.example.com"].current = "0.1.175";+ run.retry("vps", { origin: "https://vps.example.com", current: true });+ const end = await finished();+ assert.deepEqual({ phase: end.rows.vps.phase, version: end.rows.vps.version }, { phase: "done", version: "0.1.175" });+});diff --git a/electron/update-all.mjs b/electron/update-all.mjsnew file mode 100644index 0000000000..8dc8679668--- /dev/null+++ b/electron/update-all.mjs@@ -0,0 +1,38 @@+// The channels behind Update all on Settings → Devices (`guard`: this computer's own page only). The page names saved+// servers by id only: each origin comes from this app's own saved list, and each target from that server's own answer.+import { appUpdater } from "./updater.mjs";+import { appPlan, createUpdateAll, serverPlan, surveyServer } from "./update-all-run.mjs";++/** `servers()`: the saved servers Settings checks (`{ id, origin }`); `fetch`: the session that holds their sign-ins;+ * `send(channel, value)`: to this app's own window. */+export function installUpdateAll({ ipcMain, guard, servers, fetch: fetchImpl, send, app = appUpdater() }) {+ let looked = new Map();+ const run = createUpdateAll({ fetch: fetchImpl, app, onChange: (view) => send("update-all:state", view) });+ const savedServer = (id) => servers().find((entry) => entry.id === id && entry.origin);++ async function survey(fresh) {+ const answers = await Promise.all(servers().filter((entry) => entry.origin).map(async ({ id, origin }) =>+ ({ id, origin, plan: serverPlan(await surveyServer(origin, fetchImpl, { fresh })) })));+ looked = new Map(answers.map((answer) => [answer.id, answer]));+ return { servers: answers.map(({ id, plan }) => ({ id, plan })), app: appPlan(app?.state()), view: run.view() };+ }++ ipcMain.handle("update-all:survey", guard("update-all:survey", (_event, fresh) => survey(fresh === true)));+ ipcMain.handle("update-all:state", guard("update-all:state", () => run.view()));+ ipcMain.handle("update-all:start", guard("update-all:start", (_event, ids, withApp) => {+ const wanted = new Set(Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : []);+ const chosen = [...looked.values()]+ .filter((answer) => wanted.has(answer.id) && answer.plan.updates && savedServer(answer.id)?.origin === answer.origin)+ .map(({ id, origin, plan }) => ({ id, origin, latest: plan.latest }));+ return run.start({ servers: chosen, withApp: withApp === true && Boolean(appPlan(app?.state())) });+ }));+ ipcMain.handle("update-all:retry", guard("update-all:retry", async (_event, id) => {+ if (id === "app") return run.retry("app");+ const entry = typeof id === "string" ? savedServer(id) : undefined;+ if (!entry) return run.view();+ const plan = serverPlan(await surveyServer(entry.origin, fetchImpl, { fresh: true }));+ if (plan.updates) return run.retry(id, { origin: entry.origin, latest: plan.latest });+ if (plan.why === "up-to-date") return run.retry(id, { origin: entry.origin, current: true });+ return run.retry(id, { failure: { why: plan.why, ...(plan.command ? { command: plan.command } : {}) } });+ }));+}diff --git a/electron/updater.mjs b/electron/updater.mjsindex 02665809f3..db9f5ad6d8 100644--- a/electron/updater.mjs+++ b/electron/updater.mjs@@ -28,6 +28,7 @@ let updaterCoordinator = null;let pageAllowed = () => false;let quiet = null;let launch = null;+const stateListeners = new Set();/** Where these updaters install without asking anything: Squirrel.Mac, and the per-user NSIS installer run silently. */const QUIET_PLATFORMS = new Set(["darwin", "win32"]);@@ -113,6 +114,9 @@ function setState(patch) {const { messageCode: _stale, messageKey: _key, messageParams: _params, ...kept } = state;state = { ...(Object.hasOwn(patch, "message") ? kept : state), ...patch };if (quiet && patch.status === "error") installFailed(quietRecord());+ for (const listener of stateListeners) {+ try { listener(view()); } catch {}+ }try {const contents = win?.webContents;if (contents && pageAllowed({ sender: contents, senderFrame: contents.mainFrame })) contents.send("update:state", view());@@ -175,6 +179,20 @@ export function registerUpdaterIpc({ pageAllowed: allowed, serverPage = () => nu}));}+/** This app's own update for Update all on Settings → Devices: its state as the window sees it, a check, the install+ * (a restart, or the hand-off to a terminal) and each new state. A build without the updater has no state. */+export function appUpdater() {+ return {+ state: () => (updaterCoordinator ? view() : null),+ check: () => updaterCoordinator?.check(true) ?? Promise.resolve(),+ install: () => updaterCoordinator?.install(),+ onState: (listener) => {+ stateListeners.add(listener);+ return () => stateListeners.delete(listener);+ },+ };+}+/** How an update reaches this computer with nobody at it: installed at a quiet moment ("by-itself"), on the person's* Restart ("restart"), through their package manager ("package"), or not at all from this app ("none"). */export function unattendedUpdates() {diff --git a/src/components/devices/DeviceRows.tsx b/src/components/devices/DeviceRows.tsxindex ac612aeb88..71fa3da685 100644--- a/src/components/devices/DeviceRows.tsx+++ b/src/components/devices/DeviceRows.tsx@@ -25,6 +25,8 @@ export interface Opened {onRemoved: (notice: string | null, device: Device) => void;/** More of an open device's details, from what only the page reads (a phone's own controls). */extra?: (device: Device) => DeviceExtra | undefined;+ /** Its Update all state, under the row, while and after a run. */+ progress?: (device: Device) => ReactNode;}const SLOT = "flex size-8 shrink-0 items-center justify-center text-ink-secondary";@@ -61,6 +63,7 @@ function DeviceRow({ device, mark, opened, onAction, now }: {)}<ChevronRight size={14} aria-hidden="true" className={cn("-me-1 shrink-0 text-ink-tertiary transition-transform duration-150 motion-reduce:transition-none rtl:-scale-x-100", open && "rotate-90")} /></div>+ {opened.progress?.(device)}<div id={detailsId} hidden={!open} data-device-details={open ? device.id : undefined} className="ps-[60px] pe-4 pb-4 motion-safe:animate-fade-in">{open && <DeviceDetails device={device} onAction={onAction} now={now} pairing={opened.pairing} extra={opened.extra?.(device)}onPairing={(on, connected) => opened.onPairing(device, on, connected)} onRemoved={(text) => opened.onRemoved(text, device)} />}diff --git a/src/components/devices/UpdateAll.tsx b/src/components/devices/UpdateAll.tsxnew file mode 100644index 0000000000..d1f6d1fd61--- /dev/null+++ b/src/components/devices/UpdateAll.tsx@@ -0,0 +1,130 @@+import { useId, useMemo, useState, type ReactNode } from "react";+import { Check, ChevronRight, CircleAlert, Copy, Loader2, RefreshCw } from "lucide-react";+import { cn } from "@/lib/cn";+import { useCopyFeedback } from "@/lib/copy-text";+import type { Device } from "@/lib/devices";+import { t } from "@/lib/i18n";+import { planUpdateAll, progressText, rowFor, useUpdateAll, type UpdateAllLine, type UpdateAllPlan } from "@/lib/update-all";+import { ConfirmDialog } from "../ConfirmDialog";++/** A command to run on a skipped machine, with its copy button; spans only, as it sits inside the dialog's text. */+function CommandLine({ command }: { command: string }) {+ const { state, copy } = useCopyFeedback(command);+ return (+ <span className="flex min-w-0 items-start gap-2 rounded-lg bg-ink/[0.05] py-1 ps-3 pe-1">+ <code data-update-all-command="" className="min-w-0 flex-1 select-text py-1.5 font-mono text-[12px] leading-4 text-ink [overflow-wrap:anywhere]">{command}</code>+ <button type="button" onClick={copy} aria-label={state === "failed" ? t("common.copyFailed") : t("devicesPage.addFlow.copyCommand")} title={t("devicesPage.addFlow.copyCommand")} className="ui-icon-button shrink-0">+ {state === "copied" ? <Check size={14} aria-hidden="true" className="text-success" /> : <Copy size={14} aria-hidden="true" />}+ </button>+ </span>+ );+}++function MachineTable({ lines }: { lines: readonly UpdateAllLine[] }) {+ const head = "pb-1 text-[12px] leading-4 text-ink-tertiary";+ return (+ <span role="table" aria-label={t("devicesPage.updateAll.tableLabel")} data-update-all-table=""+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)] gap-x-3 rounded-lg bg-ink/[0.04] px-3 py-2 text-[13px] leading-[18px]">+ <span role="row" className="contents">+ <span role="columnheader" className={head}>{t("devicesPage.updateAll.machine")}</span>+ <span role="columnheader" className={head}>{t("devicesPage.updateAll.whatUpdates")}</span>+ </span>+ {lines.map((line) => (+ <span key={line.deviceId} role="row" data-update-all-row={line.deviceId} className="contents">+ <span role="cell" className="break-words py-1 font-medium text-ink">{line.name}</span>+ <span role="cell" className="break-words py-1 text-ink-secondary">{line.text}</span>+ </span>+ ))}+ </span>+ );+}++function SkippedList({ lines }: { lines: readonly UpdateAllLine[] }) {+ const [open, setOpen] = useState(false);+ const id = useId();+ if (lines.length === 0) return null;+ return (+ <span className="flex flex-col gap-2">+ <button type="button" aria-expanded={open} aria-controls={id} data-update-all-skipped={open ? "open" : "closed"} onClick={() => setOpen((now) => !now)}+ className="settings-quiet flex cursor-pointer items-center gap-1 self-start">+ <ChevronRight size={14} aria-hidden="true" className={cn("shrink-0 transition-transform duration-150 motion-reduce:transition-none rtl:-scale-x-100", open && "rotate-90")} />+ {t("devicesPage.updateAll.skipped", { count: lines.length })}+ </button>+ <span id={id} role="list" hidden={!open} className="flex flex-col gap-2 ps-[18px]">+ {lines.map((line) => (+ <span key={line.deviceId} role="listitem" data-update-all-skip={line.deviceId} className="flex flex-col gap-1">+ <span>+ <span className="font-medium text-ink">{line.name}</span>+ <span aria-hidden="true" className="text-ink-tertiary">{" · "}</span>+ {line.text}+ </span>+ {line.command && <CommandLine command={line.command} />}+ </span>+ ))}+ </span>+ </span>+ );+}++/** The one confirm before Update all: each machine and what updates on it, this app last, the skipped ones folded. */+export function UpdateAllDialog({ open, plan, checking, onCancel, onConfirm }: {+ open: boolean; plan: UpdateAllPlan; checking: boolean; onCancel: () => void; onConfirm: () => void;+}) {+ const count = plan.updating.length;+ const busy = plan.activeTurns > 0 ? t(plan.activeTurns === 1 ? "serverUpdate.confirmBusy.one" : "serverUpdate.confirmBusy.other", { count: plan.activeTurns }) : "";+ return (+ <ConfirmDialog open={open} tone="neutral" icon={<RefreshCw size={18} />} confirmDisabled={checking || count === 0}+ title={count === 0 && !checking ? t("devicesPage.updateAll.nothing") : t(count === 1 ? "devicesPage.updateAll.title.one" : "devicesPage.updateAll.title.other", { count })}+ confirmLabel={checking ? t("common.checking") : t("devicesPage.updateAll.confirm")} onCancel={onCancel} onConfirm={onConfirm}+ body={<span data-update-all-dialog="" className="flex flex-col gap-3">+ <span>{[t("devicesPage.updateAll.body"), busy].filter(Boolean).join(" ")}</span>+ <MachineTable lines={plan.updating} />+ <SkippedList lines={plan.skipped} />+ </span>} />+ );+}++/** A device's Update all state, under its row: what is happening, then a failure's reason with Try again. */+export function UpdateProgress({ name, phase, text, tone, busy, onRetry }: {+ name: string; phase: string; text: string; tone?: "danger"; busy: boolean; onRetry: () => void;+}) {+ const failed = phase === "failed";+ return (+ <div data-update-all-state={phase} className="-mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1.5 ps-[60px] pe-4 pb-3 text-[13px] leading-[18px]">+ <span role="status" className="flex min-w-0 items-start gap-1.5">+ <span className="flex h-[18px] w-3.5 shrink-0 items-center">+ {busy ? <Loader2 size={14} aria-hidden="true" className="text-ink-tertiary motion-safe:animate-spin" />+ : failed ? <CircleAlert size={14} aria-hidden="true" className="text-danger" />+ : phase === "done" ? <Check size={14} aria-hidden="true" className="text-success" /> : null}+ </span>+ <span className={cn("min-w-0 break-words", tone === "danger" ? "text-danger" : "text-ink-secondary")}>{text}</span>+ </span>+ {failed && <button type="button" data-update-all-retry="" onClick={onRetry} aria-label={`${t("common.tryAgain")}: ${name}`} className="ui-button ui-button-sm shrink-0">{t("common.tryAgain")}</button>}+ </div>+ );+}++/**+ * Update all on This computer's Devices page: the header button (only while something would update and no run is+ * going), its dialog, and each device's state during and after the run.+ */+export function useUpdateAllOnPage({ enabled, devices, olderPhones }: { enabled: boolean; devices: readonly Device[]; olderPhones: readonly string[] }) {+ const savedIds = devices.flatMap((device) => device.sources.flatMap((source) => (source.type === "place" ? [source.id] : []))).sort().join(",");+ const update = useUpdateAll(enabled, savedIds);+ const { survey, view, app, appMessage, checking, look, start, retry } = update;+ const [asking, setAsking] = useState(false);+ const plan = useMemo(() => planUpdateAll({ devices, servers: survey?.servers ?? null, app, olderPhones }), [devices, survey, app, olderPhones]);+ const shown = update.available && plan.updating.length > 0 && !view?.running;+ const button = useMemo(() => (shown+ ? <button type="button" data-update-all="" onClick={() => { setAsking(true); void look(true); }} className="ui-button ui-button-sm shrink-0">{t("devicesPage.updateAll.button")}</button>+ : null), [shown, look]);+ const dialog = update.available ? <UpdateAllDialog open={asking} plan={plan} checking={checking} onCancel={() => setAsking(false)}+ onConfirm={() => { setAsking(false); void start(plan.serverIds, plan.withApp); }} /> : null;+ const progress = (device: Device): ReactNode => {+ const found = rowFor(view, device);+ if (!found) return null;+ const state = progressText(found.row, Date.now(), found.id === "app" ? appMessage : undefined);+ return <UpdateProgress name={device.name} phase={found.row.phase} {...state} onRetry={() => void retry(found.id)} />;+ };+ return { button, dialog, progress };+}diff --git a/src/components/settings/pages/DevicesPage.tsx b/src/components/settings/pages/DevicesPage.tsxindex 680689766e..1e6d5abd14 100644--- a/src/components/settings/pages/DevicesPage.tsx+++ b/src/components/settings/pages/DevicesPage.tsx@@ -3,7 +3,7 @@ import { Laptop, Loader2 } from "lucide-react";import { deviceGroup, privateNetwork, groupByKind, type Device, type DeviceAction, type DeviceGroup, type PrivateNetwork } from "@/lib/devices";import { copyText } from "@/lib/copy-text";import { t } from "@/lib/i18n";-import { showTunnelRetiredNotice } from "@/lib/phone-link";+import { olderAppPhones, showTunnelRetiredNotice } from "@/lib/phone-link";import { revealPhonePairing, takePairOnOpen } from "@/lib/phone-pairing";import { phoneRemovePath } from "@/lib/phones";import { useDevices } from "@/lib/use-devices";@@ -17,6 +17,7 @@ import { DeviceMap, deviceMapShown } from "../../devices/DeviceMap";import { usePairAccess } from "../../devices/PairCodePanel";import { ComputerNameMore, OtherPlacesSection, PairWithCloudRow, PhoneAppFacts, ServerPhoneNotes } from "../../devices/PhoneSections";import { needsFirst, needsPerson } from "../../devices/device-parts";+import { useUpdateAllOnPage } from "../../devices/UpdateAll";import { networkLine, sshAliasOfAnchor } from "../../devices/device-words";import { AlwaysOnHomeSection } from "../../AlwaysOnHomeSection";import { PhoneControls } from "../../PairedPhones";@@ -60,6 +61,8 @@ const ADD_LABEL: Record<DeviceGroup, Parameters<typeof t>[0]> = { phones: "devicconst ADD_KIND: Record<DeviceGroup, AddKind | null> = { phones: "phone", computers: "computer", servers: null };const PHONES_ADD = "[data-add-group=phones]";+const NO_PHONES: readonly string[] = [];+type Adding = { start: AddKind | null; from: string; keys: boolean; ask?: PairAsk };export function DevicesPage() {@@ -176,10 +179,14 @@ export function DevicesPage() {const phoneConnected = devices.some((device) => device.kind === "phone" && device.status === "online");useEffect(() => { if (loaded) setDevicesSignal({ place: signalPlace, needsYou, phoneConnected }); }, [loaded, signalPlace, needsYou, phoneConnected]);+ const olderPhones = ctx.here && c.state && showTunnelRetiredNotice(c.account, c.state) ? olderAppPhones(c.state).map((phone) => phone.id) : NO_PHONES;+ const updateAll = useUpdateAllOnPage({ enabled: ctx.here, devices, olderPhones });+ const updateButton = updateAll.button;const isAdding = adding !== null;- const addButton = useMemo(() => <span data-settings-block="add" className="flex scroll-mt-4">+ const addButton = useMemo(() => <span data-settings-block="add" className="flex scroll-mt-4 items-center gap-2">+ {updateButton}<button type="button" data-add-device="" onClick={() => startAdding(null, "[data-add-device]")} className="ui-button ui-button-primary ui-button-sm shrink-0">{t("devicesPage.add")}</button>- </span>, [startAdding]);+ </span>, [startAdding, updateButton]);useLayoutEffect(() => {if (!setHeaderAction) return;setHeaderAction(isAdding ? null : addButton);@@ -259,6 +266,7 @@ export function DevicesPage() {onPairing: (device, on, connected) => { setPairing(on); if (connected) { setNotice({ text: t("devicesPage.pairedAgain", { name: device.name }), group: deviceGroup(device) }); refresh(); } },onRemoved: (text, device) => { setOpen(null); setNotice(text ? { text, group: deviceGroup(device) } : null); refresh(); },extra: phoneExtra,+ progress: updateAll.progress,};if (adding) {@@ -340,5 +348,6 @@ export function DevicesPage() {onAddComputer={() => startAdding("computer", "[data-always-on-add-computer]")} onConnect={() => startAdding("server", "[data-always-on-connect]")} />: <span data-settings-block="always-on" className="contents" />)}<OtherPlacesSection devices={devices} />+ {updateAll.dialog}</>;}diff --git a/src/components/settings/pages/DevicesPage.update-all.dom.test.ts b/src/components/settings/pages/DevicesPage.update-all.dom.test.tsnew file mode 100644index 0000000000..586ccff48f--- /dev/null+++ b/src/components/settings/pages/DevicesPage.update-all.dom.test.ts@@ -0,0 +1,223 @@+// @vitest-environment happy-dom+// Update all on the Devices page over a fake desktop bridge: when its button shows, what its one confirm lists, what it+// asks main to start, and each row's state while main reports the run.+import { act, createElement, useState, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { UpdateAllSurvey, UpdateAllView } from "../../../../electron/update-all-run.mjs";+import type { CompanionState } from "@/lib/companion-types";+import { setLocale } from "@/lib/i18n";+import { forgetSharedSession } from "@/lib/session-reuse";+import { initialState, StoreContext } from "@/state/store";+import type { UpdaterState } from "@/types/ogb";+import { fullContext } from "../settings-index";+import { SettingsShellContext, type SettingsShell } from "../settings-shell";+import { DevicesPage } from "./DevicesPage";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const NOW = Date.now();+const off = { on: false, since: null };++let host: HTMLDivElement;+let root: Root;+let survey: UpdateAllSurvey;+let updater: UpdaterState | null;+let pushView: ((view: UpdateAllView) => void) | null;+/** Main's view of the run, which every survey answer carries too. */+let current: UpdateAllView;+let updateAll: { survey: ReturnType<typeof vi.fn>; start: ReturnType<typeof vi.fn>; retry: ReturnType<typeof vi.fn>; onState: ReturnType<typeof vi.fn> };+let companion: CompanionState;+let retired: boolean;++const idle: UpdateAllView = { running: false, rows: {} };+const saved = [+ { id: "local", kind: "local", name: "This computer" },+ { id: "home", kind: "remote", name: "Ada’s Cloud", origin: "https://ada.mausbot.cloud", home: true },+ { id: "vps", kind: "remote", name: "Hetzner box", origin: "https://maus.example.com" },+ { id: "nuc", kind: "remote", name: "Garage NUC", origin: "https://nuc.example.com" },+ { id: "npm", kind: "remote", name: "Office box", origin: "https://office.example.com" },+];++function install() {+ updateAll = {+ survey: vi.fn(async () => ({ ...survey, view: current })),+ start: vi.fn(async () => ({ running: true, rows: { vps: { phase: "updating", since: NOW, latest: "0.1.175" }, app: { phase: "waiting", since: NOW } } })),+ retry: vi.fn(async () => ({ running: true, rows: { vps: { phase: "updating", since: NOW, latest: "0.1.175" } } })),+ onState: vi.fn((cb: (view: UpdateAllView) => void) => { pushView = cb; return () => { pushView = null; }; }),+ };+ (window as unknown as { ogb: unknown }).ogb = {+ platform: "darwin", app: { version: "0.1.180" },+ companion: { state: async () => companion },+ companionAccount: { state: async () => ({ available: true, status: "ready", email: "[email protected]", ...(retired ? { tunnelRetired: true } : {}) }) },+ environments: {+ state: async () => ({ localOrigin: "http://127.0.0.1:8799", remote: false, packaged: true, activeId: "local", environments: saved }),+ status: async () => ["vps", "nuc", "npm"].map((id) => ({ id, state: "connected", since: NOW, version: "0.1.170", behind: true, install: "docker" })),+ switch: vi.fn(), forget: vi.fn(), retry: vi.fn(),+ },+ ...(updater ? { updater: { check: vi.fn(), install: vi.fn(), onState: (cb: (state: UpdaterState) => void) => { cb(updater!); return () => {}; } } } : {}),+ updateAll,+ };+}++beforeEach(() => {+ setLocale("en");+ forgetSharedSession();+ pushView = null;+ current = idle;+ retired = false;+ updater = { status: "downloaded", version: "0.1.182", installMode: "restart" };+ companion = {+ enabled: true, keepAwake: false, port: 8810, pairing: null,+ devices: [{ id: "pixel", name: "Pixel 9", createdAt: NOW, lastSeenAt: NOW, cloudDesktopAccess: false, route: null }],+ connectedDeviceIds: [], routes: { wifi: { on: true, since: NOW }, relay: off, tailscale: off, https: off },+ };+ survey = {+ servers: [+ { id: "vps", plan: { updates: true, current: "0.1.170", latest: "0.1.175", activeTurns: 1 } },+ { id: "nuc", plan: { updates: false, why: "admin-only", current: "0.1.170", latest: "0.1.175" } },+ { id: "npm", plan: { updates: false, why: "by-hand", command: "npm install -g [email protected]" } },+ ],+ app: null, view: idle,+ };+ vi.stubGlobal("fetch", vi.fn(async (input: string) => {+ const path = new URL(input, "http://127.0.0.1").pathname;+ if (path === "/api/auth/session") return Response.json({ kind: "loopback", trust: "owner" });+ if (path === "/api/auth/sessions") return Response.json({ sessions: [], current: null });+ if (path === "/api/phones") return Response.json({ phones: [] });+ if (path === "/api/computers/bots") return Response.json({ now: NOW, rows: [] });+ if (path === "/api/auth/pairing") return Response.json({ pairings: [] });+ if (path === "/api/config") return Response.json({ membership: { authority: "local", pairingCodes: true } });+ return Response.json({ error: "no route" }, { status: 404 });+ }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(() => {+ act(() => root.unmount());+ host.remove();+ document.body.innerHTML = "";+ delete (window as unknown as { ogb?: unknown }).ogb;+ vi.unstubAllGlobals();+});++const settle = async () => { for (let i = 0; i < 12; i++) await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); };+const $ = (selector: string) => document.body.querySelector<HTMLElement>(selector);+const $$ = (selector: string) => [...document.body.querySelectorAll<HTMLElement>(selector)];+const click = async (selector: string) => { await act(async () => $(selector)!.click()); await settle(); };++function WithHeader({ shell }: { shell: SettingsShell }) {+ const [action, setAction] = useState<ReactNode | null>(null);+ return createElement(SettingsShellContext.Provider, { value: { ...shell, setHeaderAction: setAction } },+ createElement("header", { "data-settings-header": "" }, action), createElement(DevicesPage));+}+async function render(over: Partial<SettingsShell["ctx"]> = {}) {+ install();+ const shell: SettingsShell = { ctx: fullContext({ advanced: false, ...over }), place: { name: "This computer", kind: "computer", color: null, named: false }, page: "devices", anchor: null, go: vi.fn() };+ const state = { ...initialState, config: { profile: { email: "[email protected]" }, managedPolicy: null } as never, bots: [] as never };+ act(() => root.render(createElement(StoreContext.Provider, { value: { state, dispatch: vi.fn() } as never }, createElement(WithHeader, { shell }))));+ await settle();+}++describe("Update all on the Devices page", () => {+ it("sits in the header beside Add a device while something would update, asking each server once without a fresh check", async () => {+ await render();+ const header = $("[data-settings-header]")!;+ expect(header.querySelector("[data-update-all]")?.textContent).toBe("Update all");+ expect(header.querySelector("[data-add-device]")).not.toBeNull();+ expect(updateAll.survey).toHaveBeenCalledWith(false);+ expect(updateAll.survey.mock.calls.every(([fresh]) => fresh === false)).toBe(true);+ // Nothing else on the page announces it: no card, banner or dialog until it is pressed.+ expect($$('[role="dialog"], [role="alertdialog"]')).toHaveLength(0);+ expect($("[data-update-all-state]")).toBeNull();+ });++ it("is not shown when nothing would update, nor on a page that is not this computer's", async () => {+ survey = { ...survey, servers: survey.servers.filter((entry) => entry.id !== "vps") };+ updater = { status: "idle" };+ await render();+ expect($("[data-update-all]")).toBeNull();+ act(() => root.unmount());+ root = createRoot(host);+ survey = { ...survey, servers: [{ id: "vps", plan: { updates: true, current: "0.1.170", latest: "0.1.175", activeTurns: 0 } }] };+ await render({ here: false });+ expect($("[data-update-all]")).toBeNull();+ });++ it("shows for this app's own update alone", async () => {+ survey = { ...survey, servers: [] };+ await render();+ expect($("[data-update-all]")).not.toBeNull();+ });++ it("confirms once, listing each machine and what updates, this app last, the skipped ones folded with their reasons", async () => {+ retired = true;+ await render();+ await click("[data-update-all]");+ expect(updateAll.survey).toHaveBeenLastCalledWith(true);+ const dialog = $('[role="alertdialog"]')!;+ expect(dialog.querySelector("h2")?.textContent).toBe("Update 2 machines?");+ expect(dialog.textContent).toContain("A bot is answering in 1 chat right now.");+ const rows = $$("[data-update-all-row]").map((row) => [...row.querySelectorAll('[role="cell"]')].map((cell) => cell.textContent));+ expect(rows).toEqual([["Hetzner box", "To 0.1.175"], ["This computer", "This app, to 0.1.182 · restarts last"]]);+ const toggle = $("[data-update-all-skipped]")!;+ expect(toggle.textContent).toBe("4 skipped");+ expect(toggle.getAttribute("aria-expanded")).toBe("false");+ await click("[data-update-all-skipped]");+ const skipped = Object.fromEntries($$("[data-update-all-skip]").map((line) => [line.getAttribute("data-update-all-skip"), line.textContent]));+ expect(skipped).toEqual({+ "place:home": "Ada’s Cloud · Updates by itself",+ "place:nuc": "Garage NUC · Sign in there as an admin",+ "place:npm": "Office box · Update it by handnpm install -g [email protected]",+ "phone:pixel": "Pixel 9 · Update from the app store",+ });+ expect(dialog.querySelectorAll("table, p table, details")).toHaveLength(0);+ });++ it("keeps Cancel usable while the fresh look runs, and says when it leaves nothing to update", async () => {+ await render();+ let answer: (value: UpdateAllSurvey) => void = () => {};+ updateAll.survey.mockImplementationOnce(() => new Promise<UpdateAllSurvey>((resolve) => { answer = resolve; }));+ await click("[data-update-all]");+ const buttons = () => [...$('[role="alertdialog"]')!.querySelectorAll("button")];+ expect(buttons().find((button) => button.textContent === "Cancel")?.disabled).toBe(false);+ expect(buttons().find((button) => button.textContent === "Checking…")?.disabled).toBe(true);+ await act(async () => answer({ ...survey, servers: survey.servers.filter((entry) => entry.id !== "vps"), view: current }));+ await settle();+ expect($('[role="alertdialog"] h2')?.textContent).toBe("Update 1 machine?");+ expect(buttons().find((button) => button.textContent === "Update")?.disabled).toBe(false);+ });++ it("starts the servers and this app on Update, with nothing on Cancel", async () => {+ await render();+ await click("[data-update-all]");+ const cancel = [...$('[role="alertdialog"]')!.querySelectorAll("button")].find((button) => button.textContent === "Cancel")!;+ await act(async () => cancel.click());+ await settle();+ expect($('[role="alertdialog"]')).toBeNull();+ expect(updateAll.start).not.toHaveBeenCalled();+ await click("[data-update-all]");+ const confirm = [...$('[role="alertdialog"]')!.querySelectorAll("button")].find((button) => button.textContent === "Update")!;+ await act(async () => confirm.click());+ await settle();+ expect(updateAll.start).toHaveBeenCalledWith(["vps"], true);+ });++ it("shows each device's state on its row as main reports the run, with Try again on a failure", async () => {+ await render();+ const report = async (view: UpdateAllView) => { current = view; await act(async () => pushView!(view)); await settle(); };+ await report({ running: true, rows: { vps: { phase: "restarting", since: Date.now(), latest: "0.1.175" }, app: { phase: "waiting", since: Date.now() } } });+ expect($("[data-device-row='place:vps'] [data-update-all-state]")?.textContent).toBe("Restarting…");+ expect($("[data-device-row='here'] [data-update-all-state]")?.textContent).toBe("Restarts after the others");+ expect($("[data-update-all]")).toBeNull();+ await report({ running: true, rows: { vps: { phase: "done", since: Date.now(), latest: "0.1.175", version: "0.1.175" }, app: { phase: "restarting", since: Date.now() } } });+ expect($("[data-device-row='place:vps'] [data-update-all-state]")?.textContent).toBe("Updated to 0.1.175");+ await report({ running: false, rows: { vps: { phase: "failed", since: Date.now(), latest: "0.1.175", failure: { why: "not-back" } } } });+ const failed = $("[data-device-row='place:vps'] [data-update-all-state]")!;+ expect(failed.textContent).toContain("Failed: The server isn't back yet.");+ await act(async () => failed.querySelector<HTMLElement>("[data-update-all-retry]")!.click());+ await settle();+ expect(updateAll.retry).toHaveBeenCalledWith("vps");+ });+});diff --git a/src/devices-preview.tsx b/src/devices-preview.tsxindex 3708451577..e55fe5b6a1 100644--- a/src/devices-preview.tsx+++ b/src/devices-preview.tsx@@ -8,6 +8,8 @@// &home=on|off (Always-on home on this computer) &vps=default (a default SSH server too; page=ai&advanced=1 shows the// Self-hosted VPS panel under AI's computers) &e2e=0 (an older phone link: a typed code beside the QR)// &map=0|1 (the picture above the list off or on, whatever SHOW_DEVICE_MAP says)+// &updates=1 (Update all: the Mac mini and the Hetzner box can update, this app has one downloaded)+// &updateAll=open|running|done (its dialog with the skipped list open; rows mid-run; rows near the end)import { StrictMode } from "react";import { createRoot } from "react-dom/client";import { parseServerInput } from "../electron/server-address.mjs";@@ -92,9 +94,33 @@ const lendViews: Record<string, DesktopLendView> = {mini: { name: "Studio Mac mini", lendable: true, on: true, connected: true, paused: false },vps: { name: "Hetzner box", lendable: true, on: false, connected: false, paused: false },};+const updates = params.get("updates") === "1" || params.has("updateAll");+const updateAllShot = params.get("updateAll");+const failedRun = { why: "run", status: { mode: "button", current: "0.1.171", available: true, activeTurns: 0, run: { outcome: "rolled-back", from: "0.1.171", at: now - 3 * MIN } } };+const updateView = updateAllShot === "running" ? { running: true, rows: {+ vps: { phase: "restarting", since: now - MIN, latest: "0.1.175" },+ lan: { phase: "updating", since: now - MIN, latest: "0.1.175" },+ app: { phase: "waiting", since: now - 3 * MIN },+} } : updateAllShot === "done" ? { running: true, rows: {+ vps: { phase: "done", since: now - MIN, latest: "0.1.175", version: "0.1.175" },+ lan: { phase: "failed", since: now - MIN, latest: "0.1.175", failure: failedRun },+ app: { phase: "restarting", since: now - 10_000 },+} } : { running: false, rows: {} };+const updateSurvey = {+ servers: [+ { id: "mini", plan: { updates: false, why: "by-hand", current: "0.1.171", latest: "0.1.175", command: "npm install -g [email protected]" } },+ { id: "vps", plan: { updates: true, current: "0.1.170", latest: "0.1.175", activeTurns: 1 } },+ { id: "lan", plan: { updates: true, current: "0.1.171", latest: "0.1.175", activeTurns: 0 } },+ ],+ app: { version: "0.1.182", handoff: false }, view: updateView,+};const ogb = {platform: "darwin",app: { version: "0.1.180" },+ ...(updates && place === "computer" ? {+ updater: { check: async () => {}, install: async () => {}, onState: (cb: (state: unknown) => void) => { cb({ status: "downloaded", version: "0.1.182", installMode: "restart" }); return () => {}; } },+ updateAll: { survey: async () => updateSurvey, start: async () => updateView, retry: async () => updateView, onState: () => () => {} },+ } : {}),...(place === "computer" ? {companion: companionBridge,companionAccount: { state: async () => ({ available: true, status: "ready", email: "[email protected]", ...(retired ? { tunnelRetired: true } : {}) }) },@@ -187,6 +213,11 @@ createRoot(document.getElementById("root")!).render(const click = (selector: string) => document.querySelector<HTMLElement>(selector)?.click();const after = (ms: number, run: () => void) => window.setTimeout(run, ms);if (params.get("check") === "1") after(900, () => click("[data-network-action]"));+if (updateAllShot === "open") after(900, () => { click("[data-update-all]"); after(200, () => click("[data-update-all-skipped]")); });+if (updateAllShot === "running" || updateAllShot === "done") after(900, () => {+ document.querySelector("[data-settings-block=group-computers]")?.scrollIntoView({ block: "start" });+ document.body.dataset.shotReady = "";+});const select = params.get("select");if (select) after(900, () => click(`[data-device-node="${select}"]`));const add = params.get("add");diff --git a/src/lib/server-update.ts b/src/lib/server-update.tsindex 2e9fa9a831..9bd5f5eaeb 100644--- a/src/lib/server-update.ts+++ b/src/lib/server-update.ts@@ -119,7 +119,7 @@ const APP_ANSWER_TEXT: Partial<Record<AppUpdateAnswer, LocaleKey>> = {unavailable: "serverUpdate.appUnavailable",};-function runNote(status: ServerUpdateStatus | null): Pick<ServerUpdateView, "note" | "noteTone"> {+export function runNote(status: ServerUpdateStatus | null): Pick<ServerUpdateView, "note" | "noteTone"> {const run = status?.run;switch (run?.outcome) {case "updated": return { note: t("serverUpdate.updated", { version: run.to ?? status!.current }) };diff --git a/src/lib/update-all.test.ts b/src/lib/update-all.test.tsnew file mode 100644index 0000000000..e38b695829--- /dev/null+++ b/src/lib/update-all.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it } from "vitest";+import type { Device } from "./devices";+import { setLocale } from "./i18n";+import { SERVER_UPDATE_DEADLINE_MS } from "./server-update";+import { failureText, planUpdateAll, progressText, rowFor } from "./update-all";++const device = (over: Partial<Device> & Pick<Device, "id" | "name" | "kind" | "sources">): Device => ({+ status: "online", route: "internet", routes: ["internet"], canRunBots: false, canHostComputer: false, actions: [], ...over,+});++const here = device({ id: "here", name: "Ada’s MacBook", kind: "laptop", sources: [], here: true, route: "here", routes: ["here"] });+const vps = device({ id: "place:vps", name: "Hetzner box", kind: "server", sources: [{ type: "place", id: "vps" }] });+const nuc = device({ id: "place:nuc", name: "Garage NUC", kind: "desktop", sources: [{ type: "place", id: "nuc" }] });+const npm = device({ id: "place:npm", name: "Office box", kind: "server", sources: [{ type: "place", id: "npm" }] });+const cloud = device({ id: "place:home", name: "Ada’s Cloud", kind: "cloud", sources: [{ type: "place", id: "home" }], home: true });+const oldPhone = device({ id: "phone:p1", name: "Pixel 9", kind: "phone", sources: [{ type: "phone", id: "p1" }] });+const phone = device({ id: "phone:p2", name: "Ada’s iPhone", kind: "phone", sources: [{ type: "phone", id: "p2" }] });+const lent = device({ id: "lent:l1", name: "Lent laptop", kind: "laptop", sources: [{ type: "lent", id: "l1" }] });+const ssh = device({ id: "vps:gpu", name: "GPU box", kind: "server", sources: [{ type: "vps", id: "gpu" }] });+const signedIn = device({ id: "session:s1", name: "Ada’s MacBook Air", kind: "laptop", sources: [{ type: "session", id: "s1" }] });++beforeEach(() => setLocale("en"));++describe("planUpdateAll", () => {+ const servers = [+ { id: "vps", plan: { updates: true as const, current: "0.1.170", latest: "0.1.175", activeTurns: 2 } },+ { id: "nuc", plan: { updates: false as const, why: "admin-only" as const, current: "0.1.170", latest: "0.1.175" } },+ { id: "npm", plan: { updates: false as const, why: "by-hand" as const, command: "npm install -g [email protected]" } },+ ];++ it("lists each updating server with the version it named, then this app last", () => {+ const plan = planUpdateAll({ devices: [here, vps, nuc, npm, cloud], servers, app: { version: "0.1.182", handoff: false } });+ expect(plan.updating).toEqual([+ { deviceId: "place:vps", name: "Hetzner box", text: "To 0.1.175" },+ { deviceId: "here", name: "Ada’s MacBook", text: "This app, to 0.1.182 · restarts last" },+ ]);+ expect(plan.serverIds).toEqual(["vps"]);+ expect(plan.withApp).toBe(true);+ expect(plan.activeTurns).toBe(2);+ });++ it("skips the rest with a plain reason, the by-hand one with its command, and a Cloud as updating by itself", () => {+ const plan = planUpdateAll({ devices: [here, vps, nuc, npm, cloud], servers, app: null });+ expect(plan.skipped).toEqual([+ { deviceId: "place:nuc", name: "Garage NUC", text: "Sign in there as an admin" },+ { deviceId: "place:npm", name: "Office box", text: "Update it by hand", command: "npm install -g [email protected]" },+ { deviceId: "place:home", name: "Ada’s Cloud", text: "Updates by itself" },+ ]);+ expect(plan.withApp).toBe(false);+ });++ it("lists a phone only while it runs an older app, and leaves out machines with no known version", () => {+ const plan = planUpdateAll({ devices: [here, oldPhone, phone, lent, ssh, signedIn], servers: [], app: null, olderPhones: ["p1"] });+ expect(plan.updating).toEqual([]);+ expect(plan.skipped).toEqual([{ deviceId: "phone:p1", name: "Pixel 9", text: "Update from the app store" }]);+ });++ it("names the terminal when this app's update finishes there", () => {+ const plan = planUpdateAll({ devices: [here], servers: [], app: { version: null, handoff: true } });+ expect(plan.updating[0]!.text).toBe("This app · finishes in a terminal, last");+ });++ it("lists nothing to update before the servers have answered", () => {+ expect(planUpdateAll({ devices: [here, vps], servers: null, app: null }).updating).toEqual([]);+ });+});++describe("a row's state", () => {+ it("says what is happening, then the version read back", () => {+ expect(progressText({ phase: "updating", since: 0 }, 1).text).toBe("Updating…");+ expect(progressText({ phase: "restarting", since: 0 }, 1).text).toBe("Restarting…");+ expect(progressText({ phase: "restarting", since: 0 }, SERVER_UPDATE_DEADLINE_MS).text).toBe("The server isn't back yet");+ expect(progressText({ phase: "waiting", since: 0 }, 1).text).toBe("Restarts after the others");+ expect(progressText({ phase: "done", since: 0, latest: "0.1.175", version: "0.1.175" }, 1)).toEqual({ text: "Updated to 0.1.175", busy: false });+ });++ it("words a failure as Settings → Updates does for the same outcome", () => {+ const status = { mode: "button" as const, current: "0.1.170", available: true, activeTurns: 0, run: { outcome: "rolled-back" as const, from: "0.1.170", at: 1 } };+ expect(progressText({ phase: "failed", since: 0, failure: { why: "run", status } }, 1)).toEqual({+ text: "Failed: The update didn't work, so the server went back to v0.1.170. Your data is as it was. The reason is in .update/update.log on the server.", tone: "danger", busy: false,+ });+ expect(failureText({ why: "mismatch", version: "0.1.176" }, "0.1.175")).toBe("It's on 0.1.176, not 0.1.175.");+ expect(failureText({ why: "too-soon" })).toBe("Updates were asked for too often. Try again in a few minutes.");+ expect(failureText({ why: "up-to-date" })).toBe("Up to date");+ expect(failureText({ why: "download" }, undefined, "No network")).toBe("No network");+ expect(failureText({ why: "download" })).toBe("This app couldn't get its update. Try again.");+ });++ it("finds a device's row by its saved server, and this app's for this computer", () => {+ const view = { running: true, rows: { vps: { phase: "updating" as const, since: 0 }, app: { phase: "waiting" as const, since: 0 } } };+ expect(rowFor(view, vps)?.id).toBe("vps");+ expect(rowFor(view, here)?.id).toBe("app");+ expect(rowFor(view, nuc)).toBeNull();+ expect(rowFor(null, vps)).toBeNull();+ });+});diff --git a/src/lib/update-all.ts b/src/lib/update-all.tsnew file mode 100644index 0000000000..29ae8cd3f5--- /dev/null+++ b/src/lib/update-all.ts@@ -0,0 +1,160 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { appPlan, type AppPlan, type ServerPlan, type ServerSkipWhy, type UpdateAllFailure, type UpdateAllRow, type UpdateAllSurvey, type UpdateAllView } from "../../electron/update-all-run.mjs";+import type { Device } from "./devices";+import { t } from "./i18n";+import { runNote, SERVER_UPDATE_DEADLINE_MS } from "./server-update";+import { updaterMessage, useUpdaterState } from "./updater";++export type { UpdateAllRow, UpdateAllView };++/** A machine in the confirm dialog: what updates on it, or why it is skipped (with the command to run there, if any). */+export interface UpdateAllLine {+ deviceId: string;+ name: string;+ text: string;+ command?: string;+}++export interface UpdateAllPlan {+ updating: UpdateAllLine[];+ skipped: UpdateAllLine[];+ /** The saved servers to update, by id; this app is last when `withApp`. */+ serverIds: string[];+ withApp: boolean;+ /** Chats answering on the servers to update, which their restart stops. */+ activeTurns: number;+}++type SkipWhy = ServerSkipWhy | "cloud" | "phone";++const WHY_TEXT: Record<SkipWhy, Parameters<typeof t>[0]> = {+ unreachable: "devicesPage.updateAll.why.unreachable",+ "signed-out": "devicesPage.updateAll.why.signedOut",+ "up-to-date": "devicesPage.updateAll.why.upToDate",+ "admin-only": "devicesPage.updateAll.why.adminOnly",+ "by-hand": "devicesPage.updateAll.why.byHand",+ held: "serverUpdate.reason.held",+ updating: "devicesPage.updateAll.why.updating",+ "too-soon": "serverUpdate.reason.tooSoon",+ cloud: "devicesPage.updateAll.why.cloud",+ phone: "devicesPage.updateAll.why.phone",+};++export const whyText = (why: SkipWhy): string => t(WHY_TEXT[why]);++const placeOf = (device: Device) => device.sources.find((source) => source.type === "place")?.id ?? null;++/**+ * Every machine Update all lists: saved servers by their own answers, this app last, a Cloud as updating by itself and a+ * phone only while it runs an older app. Lent computers, SSH servers and other signed-in computers are left out: no+ * version is known for them here.+ */+export function planUpdateAll({ devices, servers, app, olderPhones = [] }: {+ devices: readonly Device[];+ servers: UpdateAllSurvey["servers"] | null;+ app: AppPlan | null;+ olderPhones?: readonly string[];+}): UpdateAllPlan {+ const plans = new Map((servers ?? []).map((entry) => [entry.id, entry.plan] as const));+ const updating: UpdateAllLine[] = [];+ const skipped: UpdateAllLine[] = [];+ const serverIds: string[] = [];+ let activeTurns = 0;+ for (const device of devices) {+ if (device.here) continue;+ const place = placeOf(device);+ const plan: ServerPlan | undefined = place ? plans.get(place) : undefined;+ if (place && plan) {+ if (plan.updates) {+ updating.push({ deviceId: device.id, name: device.name, text: t("devicesPage.updateAll.to", { version: plan.latest }) });+ serverIds.push(place);+ activeTurns += plan.activeTurns;+ } else {+ skipped.push({ deviceId: device.id, name: device.name, text: whyText(plan.why), ...(plan.why === "by-hand" && plan.command ? { command: plan.command } : {}) });+ }+ } else if (place && device.kind === "cloud") {+ skipped.push({ deviceId: device.id, name: device.name, text: whyText("cloud") });+ } else if (device.kind === "phone" && device.sources.some((source) => source.type === "phone" && olderPhones.includes(source.id))) {+ skipped.push({ deviceId: device.id, name: device.name, text: whyText("phone") });+ }+ }+ const here = devices.find((device) => device.here);+ if (app && here) {+ const text = app.version ? t("devicesPage.updateAll.appTo", { version: app.version }) : t("devicesPage.updateAll.app");+ updating.push({ deviceId: here.id, name: here.name, text: `${text} · ${t(app.handoff ? "devicesPage.updateAll.appLastTerminal" : "devicesPage.updateAll.appLast")}` });+ }+ return { updating, skipped, serverIds, withApp: Boolean(app && here), activeTurns };+}++/** Why a row failed, in the words Settings → Updates already uses for the same outcome. `appMessage`: this app's+ * updater's own words for its last error. */+export function failureText(failure: UpdateAllFailure | undefined, latest?: string, appMessage?: string): string {+ if (!failure) return t("serverUpdate.failed");+ switch (failure.why) {+ case "run": return runNote(failure.status ?? null).note ?? t("serverUpdate.failed");+ case "mismatch": return t("devicesPage.updateAll.mismatch", { version: failure.version ?? "?", latest: latest ?? "?" });+ case "not-back": return `${t("serverUpdate.notBack")}.`;+ case "download": return appMessage ?? t("serverUpdate.appFailed");+ case "install": return appMessage ?? t("update.card.failed");+ case "failed": return t("serverUpdate.failed");+ default: return whyText(failure.why);+ }+}++/** A row's state on the Devices page while and after Update all runs. `tone` marks a failure. */+export function progressText(row: UpdateAllRow, now: number, appMessage?: string): { text: string; tone?: "danger"; busy: boolean } {+ switch (row.phase) {+ case "waiting": return { text: t("devicesPage.updateAll.state.waiting"), busy: true };+ case "updating": return { text: t("devicesPage.updateAll.state.updating"), busy: true };+ case "restarting":+ return { text: now - row.since >= SERVER_UPDATE_DEADLINE_MS ? t("serverUpdate.notBack") : t("devicesPage.updateAll.state.restarting"), busy: true };+ case "done": return { text: t("devicesPage.updateAll.state.done", { version: row.version ?? row.latest ?? "" }), busy: false };+ case "handed-off": return { text: t("update.banner.finishInTerminal"), busy: false };+ case "failed": return { text: t("devicesPage.updateAll.state.failed", { reason: failureText(row.failure, row.latest, appMessage) }), tone: "danger", busy: false };+ }+}++/** The run's row for a device: its saved server's, or this app's for this computer. */+export function rowFor(view: UpdateAllView | null, device: Device): { id: string; row: UpdateAllRow } | null {+ if (!view) return null;+ const id = device.here ? "app" : placeOf(device);+ const row = id ? view.rows[id] : undefined;+ return id && row ? { id, row } : null;+}++/**+ * Update all's bridge on This computer's page: each saved server's own answer, read once when the page opens (and+ * fresh, skipping the servers' hour-long cache, when the dialog opens), the run's rows as main reports them, and this+ * app's update as its updater reports it. `servers`: the saved servers' ids, so a new one is asked about too.+ */+export function useUpdateAll(enabled: boolean, servers: string) {+ const bridge = enabled ? window.ogb?.updateAll : undefined;+ const updater = useUpdaterState();+ const [survey, setSurvey] = useState<UpdateAllSurvey | null>(null);+ const [view, setView] = useState<UpdateAllView | null>(null);+ const [checking, setChecking] = useState(false);+ const look = useCallback(async (fresh = false) => {+ if (!bridge) return;+ if (fresh) setChecking(true);+ try {+ const next = await bridge.survey(fresh);+ setSurvey(next);+ setView(next.view);+ } catch {+ setSurvey(null);+ } finally {+ if (fresh) setChecking(false);+ }+ }, [bridge]);+ useEffect(() => { void look(); }, [look, servers]);+ useEffect(() => bridge?.onState(setView), [bridge]);+ const wasRunning = useRef(false);+ useEffect(() => {+ if (wasRunning.current && view && !view.running) void look();+ wasRunning.current = Boolean(view?.running);+ }, [view, look]);+ const start = useCallback(async (ids: string[], withApp: boolean) => { if (bridge) setView(await bridge.start(ids, withApp)); }, [bridge]);+ const retry = useCallback(async (id: string) => { if (bridge) setView(await bridge.retry(id)); }, [bridge]);+ const app = updater ? appPlan(updater) : survey?.app ?? null;+ return { available: Boolean(bridge), survey, view, app, appMessage: updater?.status === "error" ? updaterMessage(updater, { restart: false }) : undefined, checking, look, start, retry };+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 829b862372..af0ee37da0 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -12152,6 +12152,35 @@"devicesPage.detail.usesBots": "Uses the bots here","devicesPage.addFlow.encryptedNoType": "This code is encrypted for your phone, so there’s nothing to type. Scan it in the app, or copy the link.","devicesPage.addFlow.serverCommandsLine": "These start {app} on that machine. They need Node.js 24 or later; a terminal is the window where you type commands.",+ "devicesPage.updateAll.button": "Update all",+ "devicesPage.updateAll.title.one": "Update {count} machine?",+ "devicesPage.updateAll.title.other": "Update {count} machines?",+ "devicesPage.updateAll.body": "Each one restarts to update, so anything running on it stops. This takes a few minutes.",+ "devicesPage.updateAll.confirm": "Update",+ "devicesPage.updateAll.tableLabel": "Machines to update",+ "devicesPage.updateAll.machine": "Machine",+ "devicesPage.updateAll.whatUpdates": "What updates",+ "devicesPage.updateAll.to": "To {version}",+ "devicesPage.updateAll.app": "This app",+ "devicesPage.updateAll.appTo": "This app, to {version}",+ "devicesPage.updateAll.appLast": "restarts last",+ "devicesPage.updateAll.appLastTerminal": "finishes in a terminal, last",+ "devicesPage.updateAll.skipped": "{count} skipped",+ "devicesPage.updateAll.why.unreachable": "Not reachable",+ "devicesPage.updateAll.why.signedOut": "Signed out here. Pair it again first",+ "devicesPage.updateAll.why.adminOnly": "Sign in there as an admin",+ "devicesPage.updateAll.why.byHand": "Update it by hand",+ "devicesPage.updateAll.why.updating": "Already updating",+ "devicesPage.updateAll.why.cloud": "Updates by itself",+ "devicesPage.updateAll.why.phone": "Update from the app store",+ "devicesPage.updateAll.mismatch": "It's on {version}, not {latest}.",+ "devicesPage.updateAll.state.waiting": "Restarts after the others",+ "devicesPage.updateAll.state.updating": "Updating…",+ "devicesPage.updateAll.state.restarting": "Restarting…",+ "devicesPage.updateAll.state.done": "Updated to {version}",+ "devicesPage.updateAll.state.failed": "Failed: {reason}",+ "devicesPage.updateAll.why.upToDate": "Up to date",+ "devicesPage.updateAll.nothing": "Nothing to update now","keys.vps.ownServer": "Your own server (SSH)","keys.vps.introBefore": "A Linux computer with Docker that you sign in to with SSH. {app} uses the SSH settings already on this computer and never keeps keys or passwords. The ","keys.vps.introAfter": " shows how to name it there.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 6b13aad06f..ae0f50087e 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -12152,6 +12152,35 @@"devicesPage.detail.usesBots": "Usa os bots daqui","devicesPage.addFlow.encryptedNoType": "Este código é criptografado para o seu telefone, então não há nada para digitar. Escaneie-o no app ou copie o link.","devicesPage.addFlow.serverCommandsLine": "Estes comandos iniciam o {app} naquela máquina. Eles precisam do Node.js 24 ou mais recente; um terminal é a janela onde você digita comandos.",+ "devicesPage.updateAll.button": "Atualizar tudo",+ "devicesPage.updateAll.title.one": "Atualizar {count} máquina?",+ "devicesPage.updateAll.title.other": "Atualizar {count} máquinas?",+ "devicesPage.updateAll.body": "Cada uma reinicia para atualizar, então o que estiver rodando nela para. Isso leva alguns minutos.",+ "devicesPage.updateAll.confirm": "Atualizar",+ "devicesPage.updateAll.tableLabel": "Máquinas a atualizar",+ "devicesPage.updateAll.machine": "Máquina",+ "devicesPage.updateAll.whatUpdates": "O que atualiza",+ "devicesPage.updateAll.to": "Para {version}",+ "devicesPage.updateAll.app": "Este app",+ "devicesPage.updateAll.appTo": "Este app, para {version}",+ "devicesPage.updateAll.appLast": "reinicia por último",+ "devicesPage.updateAll.appLastTerminal": "termina em um terminal, por último",+ "devicesPage.updateAll.skipped": "{count} ignoradas",+ "devicesPage.updateAll.why.unreachable": "Inacessível",+ "devicesPage.updateAll.why.signedOut": "Sem login aqui. Pareie de novo primeiro",+ "devicesPage.updateAll.why.adminOnly": "Entre lá como administrador",+ "devicesPage.updateAll.why.byHand": "Atualize manualmente",+ "devicesPage.updateAll.why.updating": "Já está atualizando",+ "devicesPage.updateAll.why.cloud": "Atualiza sozinha",+ "devicesPage.updateAll.why.phone": "Atualize pela loja de apps",+ "devicesPage.updateAll.mismatch": "Está na {version}, não na {latest}.",+ "devicesPage.updateAll.state.waiting": "Reinicia depois das outras",+ "devicesPage.updateAll.state.updating": "Atualizando…",+ "devicesPage.updateAll.state.restarting": "Reiniciando…",+ "devicesPage.updateAll.state.done": "Atualizado para {version}",+ "devicesPage.updateAll.state.failed": "Falhou: {reason}",+ "devicesPage.updateAll.why.upToDate": "Atualizada",+ "devicesPage.updateAll.nothing": "Nada para atualizar agora","keys.vps.introBefore": "Um computador Linux com Docker em que você entra por SSH. O {app} usa as configurações de SSH que já estão neste computador e nunca guarda chaves nem senhas. O ","keys.vps.introAfter": " mostra como nomeá-lo lá.","keys.vps.tailscaleToo": "Um computador na sua rede Tailscale também funciona: use o nome dele no Tailscale como HostName nas suas configurações de SSH.",diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex df649b7328..fc8d511c89 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -535,6 +535,15 @@ const __APP_VERSION__: string;seen?(): Promise<void>;onState(cb: (s: UpdaterState) => void): () => void;};+ /** Update all on Settings → Devices, this computer's own page only (electron/update-all.mjs). `survey(fresh)`: each+ * saved server's own answer, `fresh` skipping its hour-long cache. `start` takes saved-server ids; main finds their+ * addresses and targets itself. Absent in older desktop builds and on any other page. */+ updateAll?: {+ survey(fresh?: boolean): Promise<import("../../electron/update-all-run.mjs").UpdateAllSurvey>;+ start(ids: string[], withApp: boolean): Promise<import("../../electron/update-all-run.mjs").UpdateAllView>;+ retry(id: string): Promise<import("../../electron/update-all-run.mjs").UpdateAllView>;+ onState(cb: (view: import("../../electron/update-all-run.mjs").UpdateAllView) => void): () => void;+ };/** On a server's page from the Server menu: asks for this app's own update, from the person's click. The page* learns only what was done; the app asks in its own dialog before it restarts. Absent in older desktop builds. */appUpdate?: {