A local-first multi-agent app development platform, built on PenguinHarness
feat: software update runs through one modal — confirm, download progress, restart (#540)
Yaowei Zheng3ff14161e205
diff --git a/changelog/unreleased/2026-08-28-update-modal.md b/changelog/unreleased/2026-08-28-update-modal.mdnew file mode 100644index 00000000..4a0cc6e8--- /dev/null+++ b/changelog/unreleased/2026-08-28-update-modal.md@@ -0,0 +1,62 @@+# Updating runs through one dialog: confirm, watch the download, restart++- **Date:** 2026-08-28+- **Type:** feature+- **Scope:** `web`, `server`, `desktop`, `cli`, `docs`+- **PR:** [#540](https://github.com/Prism-Shadow/penguin-harness/pull/540)+- **Breaking:** yes — `POST /api/version/update` answers with the job status instead of blocking until the run is over++[中文版](2026-08-28-update-modal.zh.md)++The two update entries — the "New version available" superscript on the new-chat page's+version line, and the row under System settings in the sidebar user menu — now open the same+update dialog, and the dialog walks the update the way an app updater does: a check, the+release offered with its notes and a **Download and update** button (nothing is fetched+before it is pressed), a progress bar with **Continue in background**, and **Restart and+update** once the release is ready. Before this, the superscript opened the GitHub page, the+server dialog ran the whole install inside one long request with no progress and ended in+"restart the service by hand", and in the desktop app "Check for updates" started the+download on its own.++## Details++- Web: `lib/update-flow.ts` is the one state machine (`unknown` / `checking` / `disabled` /+ `up-to-date` / `available` / `downloading` / `ready` / `restarting` / `error` /+ `unsupported`) over two backends — the server release and the desktop shell's updater — and+ `lib/use-update-flow.ts` owns the actions, the polling and the outcome toasts. The modal+ (`components/account/update-modal.tsx`) and the row (`update-row.tsx`) replace the update+ dialog, the server row, the desktop row and the install confirmation. Closing the dialog+ never cancels: the row keeps the percentage, the avatar dot appears once the release is+ ready, and the outcome toasts. The version line's superscript follows the flow ("New version+ available" / "Downloading update" / "Restart to update") and opens the dialog.+- Server: the self-update became a background job (`services/update-job.ts`) — `POST+ /api/version/update` starts it (or joins a running one) and `GET` reports `phase` and, while+ the installer's `curl --progress-bar` runs, a real `percent`; the finished result stays+ readable until the next start, which is also the retry. New `POST /api/version/restart`+ exits with core's `SERVER_RESTART_EXIT_CODE` (75) after the graceful shutdown when a+ supervisor is there (`PENGUIN_SUPERVISED=1`, published to the platform as the `lifecycle`+ runtime capability), and answers `no_supervisor` otherwise. The desktop relay gained+ `POST /api/desktop/update/download` and the `available` snapshot state.+- CLI: `penguin server` and `penguin web` run the service as a child process and supervise it+ — forwarding the terminal's signals, exiting with its code, and relaunching it on the+ restart code so the relaunch runs the newly installed release (printed as "Restarting the+ service to apply the update…"). A `tsx` dev run cannot be relaunched by plain node and keeps+ running in-process.+- Desktop: the shell no longer downloads on its own. A check ends in the new `available`+ state; the download starts on the page's `download` command or from the native dialog a+ menu-driven check now ends in ("Download" / "Later"), and the native "restart now" prompt+ follows only a download the native dialog started. The fallback-feed retry of a failed+ package download is unchanged.+- Docs: the Web App, CLI and Server API pages describe the dialog, the supervisor and the+ job/restart endpoints.++## Compatibility++- `POST /api/version/update` used to hold the request open for the whole run and answer+ `{status, output, needsRestart}`; it now answers at once with the job status+ (`{state, targetVersion, phase?, percent?, output, result?, …}`), the old shape living on as+ `result`. `GET /api/version/update` is where a client waits. The Web App and the server ship+ together, so no user action is needed; a script calling the old endpoint should poll GET.+- `DesktopUpdaterCommandMessage.action` and `DesktopUpdateStatus.state` are wider (`download`,+ `available`). The shell and the server ship in one package.+- `SessionConfig`-style SDK surfaces are untouched; nothing on disk changed.diff --git a/changelog/unreleased/2026-08-28-update-modal.zh.md b/changelog/unreleased/2026-08-28-update-modal.zh.mdnew file mode 100644index 00000000..6902a6b1--- /dev/null+++ b/changelog/unreleased/2026-08-28-update-modal.zh.md@@ -0,0 +1,48 @@+# 更新集中到一个弹窗:确认、看着下载、重启++- **Date:** 2026-08-28+- **Type:** feature+- **Scope:** `web`, `server`, `desktop`, `cli`, `docs`+- **PR:** [#540](https://github.com/Prism-Shadow/penguin-harness/pull/540)+- **Breaking:** yes — `POST /api/version/update` 改为立即返回任务状态,不再阻塞到整个更新结束++[English](2026-08-28-update-modal.md)++两个更新入口——新对话页版本行上的「有新版本可用」上标,以及侧边栏用户菜单里「系统设置」下方+的那一行——现在打开同一个更新弹窗,弹窗按应用更新器的方式走完更新:先检查,查到的版本连同更新+说明与「下载并更新」按钮一起给出(按下之前不下载任何东西),下载中显示进度条并可「放到后台」,+就绪后「重启并更新」。此前:上标直接跳 GitHub 页面;服务端的弹窗把整个安装塞进一个漫长的请求、+没有进度,最后只说「请手动重启服务」;桌面应用里「检查更新」一点就自行开始下载。++## 细节++- Web:`lib/update-flow.ts` 是唯一的状态机(`unknown` / `checking` / `disabled` /+ `up-to-date` / `available` / `downloading` / `ready` / `restarting` / `error` /+ `unsupported`),覆盖服务端版本与桌面 shell 更新器两个后端;`lib/use-update-flow.ts` 负责动作、+ 轮询与弹窗关闭时的结果提示。弹窗(`components/account/update-modal.tsx`)与行+ (`update-row.tsx`)取代了原来的更新弹窗、服务端行、桌面行与安装确认框。关闭弹窗从不取消任何+ 事:那一行继续显示百分比,就绪后头像出现圆点并弹出提示。版本行上标随状态变化(「有新版本可用」/+ 「正在下载更新」/「重启以更新」)并打开弹窗。+- Server:在线更新改为后台任务(`services/update-job.ts`)——`POST /api/version/update` 启动+ (或并入)任务,`GET` 报告 `phase`,以及安装器 `curl --progress-bar` 运行期间真实的 `percent`;+ 结束后的结果保留到下一次启动,再次启动即重试。新增 `POST /api/version/restart`:有托管进程时+ (`PENGUIN_SUPERVISED=1`,作为 `lifecycle` 运行时能力发布给 platform)在优雅关闭后以 core 的+ `SERVER_RESTART_EXIT_CODE`(75)退出,否则应答 `no_supervisor`。桌面中继新增+ `POST /api/desktop/update/download` 与快照状态 `available`。+- CLI:`penguin server` 与 `penguin web` 把服务作为子进程运行并托管它——转发终端信号、以其退出码+ 退出、在重启退出码上重新拉起,使重新拉起的进程运行刚安装的新版本(打印「正在重启服务以应用更+ 新…」)。经 `tsx` 的开发运行无法被普通 node 重新拉起,仍在本进程内运行。+- Desktop:shell 不再自行下载。检查以新增的 `available` 状态结束;下载由页面的 `download` 指令+ 或原生对话框开始——菜单发起的检查现在以「Download / Later」对话框收尾——原生的「立即重启」提示只+ 跟在原生对话框发起的下载之后。下载失败时切换备用源重试的逻辑不变。+- 文档:Web App、CLI 与 Server API 页面描述了弹窗、托管进程与任务 / 重启接口。++## 兼容性++- `POST /api/version/update` 原先把请求挂到整个更新结束并应答 `{status, output, needsRestart}`;+ 现在立即应答任务状态(`{state, targetVersion, phase?, percent?, output, result?, …}`),旧结构+ 保留在 `result` 里;等待结果改用 `GET /api/version/update`。Web App 与服务端一起发布,用户无需+ 做任何事;调用旧接口的脚本应改为轮询 GET。+- `DesktopUpdaterCommandMessage.action` 与 `DesktopUpdateStatus.state` 变宽(新增 `download`、+ `available`)。shell 与服务端在同一个安装包里发布。+- SDK 接口未动,磁盘上的数据没有任何变化。diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.tsindex 79830769..2414da6b 100644--- a/packages/cli/src/commands/serve.ts+++ b/packages/cli/src/commands/serve.ts@@ -13,11 +13,26 @@* service is ready, prints the URL, and opens a browser per-platform (`--no-open`* disables this). Before the import, PENGUIN_CLI_ENTRY is exported (when node can re-run* this entry) so the server's admin self-update endpoint can invoke `penguin update`.+ *+ * Supervision: when plain node can re-run this entry, the service runs as a CHILD process+ * (`node <entry> server …`, marked PENGUIN_SERVE_CHILD=1) and this process stays behind+ * as its supervisor — it forwards the terminal's signals, exits with the child's code, and+ * relaunches the child when it exits with core's SERVER_RESTART_EXIT_CODE. That exit is+ * what the Web App's "restart to update" asks for once `penguin update` has replaced the+ * install: the relaunch re-resolves the same entry path, which now holds the new release.+ * The child is told a supervisor is there (PENGUIN_SUPERVISED=1); a dev run through tsx+ * cannot be re-spawned by node and runs in-process as before, where the server reports+ * that a restart must be done by hand.* Docs: /docs/cli § "penguin server / penguin web".*/import { spawn } from "node:child_process";+import type { ChildProcess } from "node:child_process";import path from "node:path";-import { DEFAULT_SERVER_PORT, resolveRoot } from "@prismshadow/penguin-core";+import {+ DEFAULT_SERVER_PORT,+ SERVER_RESTART_EXIT_CODE,+ resolveRoot,+} from "@prismshadow/penguin-core";import { liveServerLock } from "@prismshadow/penguin-server/lock";import type { Command } from "commander";import type { Messages, WebProbeFailureKind } from "../i18n.js";@@ -100,10 +115,63 @@ async function existingInstanceUrl(): Promise<string | null> {return lock === null ? null : `http://localhost:${lock.port}/`;}-async function startServer(opts: {- port?: string;- host?: string;-}): Promise<{ host: string; port: number }> {+/** Marks the service child a supervising `penguin server|web` spawned: it runs the server in-process. */+export const SERVE_CHILD_ENV = "PENGUIN_SERVE_CHILD";++/** What the supervisor does when its child exits (pure; exported for unit tests). */+export function supervisorDecision(+ exit: { code: number | null; signal: NodeJS.Signals | null },+ stopping: boolean,+): { action: "respawn" } | { action: "exit"; code: number } {+ // The restart code is the child's own request to be relaunched; a signal-terminated+ // child reports no code and is simply gone. Once the supervisor itself was told to stop,+ // nothing is relaunched, whatever the child's last word.+ if (!stopping && exit.code === SERVER_RESTART_EXIT_CODE) return { action: "respawn" };+ return { action: "exit", code: exit.code ?? (exit.signal !== null ? 1 : 0) };+}++/**+ * Runs the service as a child of this process and keeps it running across restart+ * requests. Returns once the first child is spawned; the process then lives as long as+ * the child does (the handle keeps the event loop alive) and takes its exit code.+ */+function supervise(cliEntry: string, host: string, port: number, t: Messages): void {+ let stopping = false;+ let child: ChildProcess | null = null;+ const spawnChild = (): void => {+ child = spawn(process.execPath, [cliEntry, "server", "--port", String(port), "--host", host], {+ stdio: "inherit",+ env: { ...process.env, [SERVE_CHILD_ENV]: "1", PENGUIN_SUPERVISED: "1" },+ });+ child.on("exit", (code, signal) => {+ const decision = supervisorDecision({ code, signal }, stopping);+ if (decision.action === "respawn") {+ process.stdout.write(`${t.serve.restarting}\n`);+ spawnChild();+ return;+ }+ process.exitCode = decision.code;+ });+ };+ // A signal aimed at the supervisor alone (`kill <pid>`) must reach the service; one from+ // the terminal already reached both, and the child's shutdown is idempotent. Windows has+ // no signal to forward — the console delivers Ctrl+C to every process attached to it —+ // and kill() there is a hard TerminateProcess that would cut a shutdown short.+ if (process.platform !== "win32") {+ for (const signal of ["SIGINT", "SIGTERM"] as const) {+ process.on(signal, () => {+ stopping = true;+ child?.kill(signal);+ });+ }+ }+ spawnChild();+}++async function startServer(+ opts: { port?: string; host?: string },+ t: Messages,+): Promise<{ host: string; port: number }> {const port = resolvePort(opts.port, process.env.PORT);const host = opts.host ?? process.env.HOST ?? DEFAULT_HOST;process.env.PORT = String(port);@@ -117,6 +185,12 @@ async function startServer(opts: {if (cliEntry !== null) {process.env.PENGUIN_CLI_ENTRY = cliEntry;}+ // The same re-runnable entry is what makes supervision possible: the child is exactly+ // this command again, marked as the child so it does not supervise in turn.+ if (cliEntry !== null && process.env[SERVE_CHILD_ENV] !== "1") {+ supervise(cliEntry, host, port, t);+ return { host, port };+ }await import("@prismshadow/penguin-server");return { host, port };}@@ -265,7 +339,7 @@ export function registerServeCommands(program: Command, t: Messages): void {process.exitCode = 1;return;}- await startServer(opts);+ await startServer(opts, t);});// Bare `penguin server` still starts the service (commander runs the action when no// subcommand is named); the subcommand only dispatches on an exact name match.@@ -288,7 +362,7 @@ export function registerServeCommands(program: Command, t: Messages): void {if (opts.open) openBrowser(existing);return;}- const { host, port } = await startServer(opts);+ const { host, port } = await startServer(opts, t);const url = browserUrl(host, port);const readiness = await waitForReady(url);if (!readiness.ready) {diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex fcfde838..e4a0fac4 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -285,6 +285,8 @@ export interface Messages {port: string;host: string;noOpen: string;+ /** Printed by the supervising process as it relaunches the service on a restart request (the web UI's "restart to update"). */+ restarting: string;};/** `penguin server reset-admin-password`: help text and every line the command can print. */auth: {@@ -799,6 +801,7 @@ const en: Messages = {port: "Listen port (falls back to the PORT env var, default 7364)",host: "Listen address (falls back to the HOST env var, default 127.0.0.1)",noOpen: "Do not open a browser automatically",+ restarting: "Restarting the service to apply the update…",},auth: {desc: "Sign in to a PenguinHarness server from the terminal",@@ -1305,6 +1308,7 @@ const zh: Messages = {port: "监听端口(其次取环境变量 PORT,缺省 7364)",host: "监听地址(其次取环境变量 HOST,缺省 127.0.0.1)",noOpen: "不自动打开浏览器",+ restarting: "正在重启服务以应用更新…",},auth: {desc: "在终端里登录 PenguinHarness 服务",diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.tsindex 32e34a91..dd3f8785 100644--- a/packages/cli/test/serve.test.ts+++ b/packages/cli/test/serve.test.ts@@ -11,6 +11,7 @@ import {describeReadinessFailure,registerServeCommands,resolvePort,+ supervisorDecision,waitForReady,} from "../src/commands/serve.js";import { getMessages } from "../src/i18n.js";@@ -96,6 +97,36 @@ describe("cliEntryFor (the entry advertised for the web self-update)", () => {});});+describe("supervisorDecision (the service child's exit → respawn or exit)", () => {+ it("relaunches the service only on the restart code, and only while not stopping", () => {+ expect(supervisorDecision({ code: 75, signal: null }, false)).toEqual({ action: "respawn" });+ // The supervisor was told to stop (Ctrl+C reached it too): the child's last word is moot.+ expect(supervisorDecision({ code: 75, signal: null }, true)).toEqual({+ action: "exit",+ code: 75,+ });+ });++ it("passes every other exit through, and reads a signal death as failure", () => {+ expect(supervisorDecision({ code: 0, signal: null }, false)).toEqual({+ action: "exit",+ code: 0,+ });+ expect(supervisorDecision({ code: 3, signal: null }, false)).toEqual({+ action: "exit",+ code: 3,+ });+ expect(supervisorDecision({ code: null, signal: "SIGKILL" }, false)).toEqual({+ action: "exit",+ code: 1,+ });+ expect(supervisorDecision({ code: null, signal: null }, true)).toEqual({+ action: "exit",+ code: 0,+ });+ });+});+describe("readiness probe diagnostics", () => {afterEach(() => {vi.restoreAllMocks();diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 5bb1f302..ac5e0767 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -26,6 +26,7 @@ export type * from "./version-info.js";// Only the default server port leaves internal: the CLI / server default-port source of truth.export { DEFAULT_SERVER_PORT } from "./internal/ports.js";+export { SERVER_RESTART_EXIT_CODE } from "./internal/server-lifecycle.js";// Submodulesexport * from "./state/index.js";diff --git a/packages/core/src/internal/server-lifecycle.ts b/packages/core/src/internal/server-lifecycle.tsnew file mode 100644index 00000000..c5e58b88--- /dev/null+++ b/packages/core/src/internal/server-lifecycle.ts@@ -0,0 +1,10 @@+/**+ * The exit code with which the server asks its supervisor to relaunch it: the process+ * contract between `penguin server|web`, which runs the service as a child process and+ * respawns it on exactly this code, and the server's `POST /api/version/restart`, which+ * exits with it after a graceful shutdown once a self-update has been installed — so the+ * relaunch runs the new release. Lives in core because both sides import core and neither+ * may import the other's internals. 75 is BSD's EX_TEMPFAIL ("try again"), clear of every+ * code the server otherwise exits with (0, 1, and 3 for "already running").+ */+export const SERVER_RESTART_EXIT_CODE = 75;diff --git a/packages/desktop/src/updater-status.ts b/packages/desktop/src/updater-status.tsindex 3cc05fd7..b5853e53 100644--- a/packages/desktop/src/updater-status.ts+++ b/packages/desktop/src/updater-status.ts@@ -3,22 +3,29 @@** updater.ts folds electron-updater's events through `nextUpdateStatus` and pushes each* snapshot to the embedded server (main.ts wires the utilityProcess port), where- * GET /api/desktop/update serves it to the shell window's account menu. The wire shapes- * are the server's api contract (DesktopUpdateStatus / the two message types), imported- * type-only so nothing of the server bundles into the shell.+ * GET /api/desktop/update serves it to the shell window's update modal and account-menu+ * row. The wire shapes are the server's api contract (DesktopUpdateStatus / the two+ * message types), imported type-only so nothing of the server bundles into the shell.*- * Two deliberate suppression rules keep the headline truthful:+ * A check ends in `available` — the release is offered, nothing is fetched. The download+ * begins only on the user's say-so (`download-started`, from the page's download command+ * or the native dialog), and runs `downloading` → `downloaded`.+ *+ * Three deliberate suppression rules keep the headline truthful:** - A `downloaded` build outranks transient noise — `checking`, `not-available`,* `error`, a re-announce of the same version. Once a release sits on disk, "restart* to install" must not flicker away under a periodic re-check or its network* failure. What it does yield to: a **different** version being fetched- * (`available`/`downloaded` with another version — electron-updater invalidates the- * held package the moment a replacement download starts, so keeping the old headline- * would point the install button at a deleted file).+ * (`available`/`download-started`/`downloaded` with another version —+ * electron-updater invalidates the held package the moment a replacement download+ * starts, so keeping the old headline would point the install button at a deleted file).* - While `downloading`, a concurrent check's `checking` (and a same-version* re-announce) is suppressed: folding it would drop the download context and every* later progress tick with it. A download's own failure still lands as `error`.+ * - While `available`, a check's `checking` and a same-version re-announce are suppressed+ * too: the offer must not blink out under the fallback-feed re-check that a failed+ * download runs. A different version, an up-to-date answer, or an error replace it.*/import type {DesktopUpdateStatus,@@ -32,6 +39,8 @@ export type UpdaterEvent =| { kind: "checking" }| { kind: "not-available" }| { kind: "available"; version: string }+ /** The user accepted the offer: updater.ts is about to call downloadUpdate(). */+ | { kind: "download-started"; version: string }| { kind: "progress"; percent: number }| { kind: "downloaded"; version: string }| { kind: "error"; message: string };@@ -46,11 +55,21 @@ export function nextUpdateStatus(prev: DesktopUpdateStatus, ev: UpdaterEvent): Dconst { appVersion } = prev;if (prev.state === "downloaded") {const replacement =- (ev.kind === "available" || ev.kind === "downloaded") && ev.version !== prev.version;+ (ev.kind === "available" || ev.kind === "download-started" || ev.kind === "downloaded") &&+ ev.version !== prev.version;if (!replacement && ev.kind !== "unsupported") return prev;}if (prev.state === "downloading") {if (ev.kind === "checking" || ev.kind === "not-available") return prev;+ if (+ (ev.kind === "available" || ev.kind === "download-started") &&+ ev.version === prev.version+ ) {+ return prev;+ }+ }+ if (prev.state === "available") {+ if (ev.kind === "checking") return prev;if (ev.kind === "available" && ev.version === prev.version) return prev;}switch (ev.kind) {@@ -61,6 +80,8 @@ export function nextUpdateStatus(prev: DesktopUpdateStatus, ev: UpdaterEvent): Dcase "not-available":return { appVersion, state: "up-to-date" };case "available":+ return { appVersion, state: "available", version: ev.version };+ case "download-started":return { appVersion, state: "downloading", version: ev.version, percent: 0 };case "progress":// A progress tick outside a download (stale timer) must not fabricate one.@@ -84,5 +105,7 @@ export function parseUpdaterCommand(data: unknown): DesktopUpdaterCommandMessageif (typeof data !== "object" || data === null) return null;const msg = data as Partial<DesktopUpdaterCommandMessage>;if (msg.type !== "desktop-updater-command") return null;- return msg.action === "check" || msg.action === "install" ? msg.action : null;+ return msg.action === "check" || msg.action === "download" || msg.action === "install"+ ? msg.action+ : null;}diff --git a/packages/desktop/src/updater.ts b/packages/desktop/src/updater.tsindex be601d4e..a7d90fef 100644--- a/packages/desktop/src/updater.ts+++ b/packages/desktop/src/updater.ts@@ -8,11 +8,14 @@* status fold, GET /api/desktop/update serves it). The window itself stays a plain* browser: the relay adds server HTTP surface, never a renderer IPC bridge.*- * Automatic checks are quiet: they run on a timer, download in the background, and speak- * up only when a build is ready to install. A manual check reports every outcome (already- * up to date / downloading / failed), the same rule the Web App's check-for-updates row+ * A check only looks: it ends in `available`, and nothing is fetched until the user says+ * so — from the Web App's update modal (the relayed `download` command) or from the native+ * dialog a menu-driven check ends in. Automatic checks are quiet: they run on a timer and+ * surface an offer only as the page's badge. A manual check reports every outcome (already+ * up to date / a release offered / failed), the same rule the Web App's update entry* follows — a manual action that answers with silence reads as broken. A web-initiated- * check is manual too, but its outcomes render in the row that asked, not in dialogs.+ * check or download is manual too, but its outcomes render in the modal that asked, not+ * in dialogs: the native restart prompt follows only a download the native dialog started.** Release builds use Developer ID signing on macOS and Authenticode signing on Windows;* unsigned dry-run artifacts can still find updates, but platform trust and release@@ -22,7 +25,10 @@import { app, dialog, net, shell } from "electron";import type { BrowserWindow } from "electron";import electronUpdater from "electron-updater";-import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";+import type {+ DesktopUpdateStatus,+ DesktopUpdaterCommandMessage,+} from "@prismshadow/penguin-server/api";import { feedUrlOverride, updateSourceConfig, updateSupport } from "./update-support.js";import {feedLabel,@@ -55,6 +61,8 @@ function log(line: string): void {let manualCheckInFlight = false;let downloadedVersion: string | null = null;let downloadInFlight = false;+/** The running download was started from the native dialog: its outcomes get native dialogs too. */+let nativeDownload = false;type FeedState ={ phase: "pending" } | { phase: "unavailable" } | { phase: "ready"; fallbackUrl: string | null };@@ -181,23 +189,29 @@ function reannounceStatus(): void {for (const listener of statusListeners) listener(status);}-function reportUpdaterError(err: Error): void {+/**+ * Records a failure and, when the native path asked for the step that failed, tells the+ * user in a dialog: a menu-driven check, or a download started from the offer dialog.+ * Web-driven steps report through the status the modal reads.+ */+function reportUpdaterError(err: Error, step: "check" | "download"): void {emitStatus({ kind: "error", message: err.message });- if (manualCheckInFlight) {- manualCheckInFlight = false;- void dialog- .showMessageBox({- type: "error",- message: "Could not check for updates.",- detail: `${err.message}\n\nYou can always download the latest release manually.`,- buttons: ["Open Releases", "OK"],- defaultId: 1,- cancelId: 1,- })- .then((r) => {- if (r.response === 0) void shell.openExternal(RELEASES_URL);- });- }+ const native = step === "check" ? manualCheckInFlight : nativeDownload;+ if (!native) return;+ manualCheckInFlight = false;+ nativeDownload = false;+ void dialog+ .showMessageBox({+ type: "error",+ message: step === "check" ? "Could not check for updates." : "Could not download the update.",+ detail: `${err.message}\n\nYou can always download the latest release manually.`,+ buttons: ["Open Releases", "OK"],+ defaultId: 1,+ cancelId: 1,+ })+ .then((r) => {+ if (r.response === 0) void shell.openExternal(RELEASES_URL);+ });}/** Current snapshot, for the initial push after a server (re)start. */@@ -212,13 +226,18 @@ export function onUpdaterStatus(listener: (status: DesktopUpdateStatus) => void)}/**- * Server-relayed command from the account-menu row. `check` is a manual check whose- * outcomes render in the row (no dialogs); a check that cannot run answers with a- * status push instead of silence, so the row always settles. `install` restarts into a- * downloaded build — the page confirmed the interruption before sending it, and the- * row only offers it in the `downloaded` state, so a stale frame is dropped here.+ * Server-relayed command from the page's update modal. `check` is a manual check whose+ * outcomes render in the modal (no dialogs); a check that cannot run answers with a+ * status push instead of silence, so the modal always settles. `download` fetches the+ * release on offer — the page confirmed it before sending. `install` restarts into a+ * downloaded build — the page confirmed the interruption before sending it, and it only+ * offers the step in the `downloaded` state, so a stale frame is dropped here.*/-export function handleUpdaterCommand(action: "check" | "install"): void {+export function handleUpdaterCommand(action: DesktopUpdaterCommandMessage["action"]): void {+ if (action === "download") {+ void startDownload("web");+ return;+ }if (action === "check") {const support = updateSupport({isPackaged: app.isPackaged,@@ -232,6 +251,7 @@ export function handleUpdaterCommand(action: "check" | "install"): void {if (downloadedVersion !== null ||status.state === "downloading" ||+ status.state === "available" ||status.state === "checking") {reannounceStatus();@@ -276,9 +296,9 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {return;}- // Background downloads, explicit install: the user decides when to restart. The- // download is still started immediately after update-available; keeping the trigger- // here lets a failed package download retry the same tag on the fallback feed.+ // Explicit download, explicit install: the user decides both when to fetch and when to+ // restart. Owning the download call here (rather than autoDownload) is also what lets a+ // failed package download retry the same tag on the fallback feed.autoUpdater.autoDownload = false;autoUpdater.autoInstallOnAppQuit = false;autoUpdater.logger = null;@@ -301,18 +321,11 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {}});autoUpdater.on("update-available", (info: { version: string }) => {- log(`update available: ${info.version} (downloading)`);+ log(`update available: ${info.version} (offered)`);emitStatus({ kind: "available", version: info.version });- void downloadUpdateWithFallback();if (manualCheckInFlight) {manualCheckInFlight = false;- void dialog.showMessageBox({- type: "info",- message: `Version ${info.version} is available.`,- detail:- "It is downloading in the background; you will be asked to restart when it is ready.",- buttons: ["OK"],- });+ void promptDownload(info.version, getWindow());}});autoUpdater.on("download-progress", (p: { percent: number }) => {@@ -323,7 +336,12 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {downloadedVersion = info.version;log(`downloaded: ${info.version}`);emitStatus({ kind: "downloaded", version: info.version });- void promptRestart(info.version, getWindow());+ // Only the native path prompts: a download the page started ends in the modal's own+ // "restart to update" step, and a second prompt on top of it would be one too many.+ if (nativeDownload) {+ nativeDownload = false;+ void promptRestart(info.version, getWindow());+ }});autoUpdater.on("error", (err: Error) => {log(`error: ${err.message}`);@@ -336,7 +354,7 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {});return;}- reportUpdaterError(err);+ reportUpdaterError(err, "check");});const override = feedUrlOverride(process.env);@@ -386,8 +404,15 @@ async function check(): Promise<void> {// A waiting build ends the checking: a re-check that finds a newer release would// start fetching it and invalidate the downloaded package on disk while the UI still// points its install action at it. The user installs what they were offered; the next- // launch checks again. A running download likewise finishes undisturbed.- if (downloadedVersion !== null || status.state === "downloading") return;+ // launch checks again. A running download likewise finishes undisturbed, and a standing+ // offer stays what it is — the user takes it or leaves it; the next launch checks again.+ if (+ downloadedVersion !== null ||+ status.state === "downloading" ||+ status.state === "available"+ ) {+ return;+ }await refreshUpdateFeed();if (feedState.phase !== "ready") {const message =@@ -411,33 +436,60 @@ async function check(): Promise<void> {}}+/**+ * The user's "download" — from the page's modal (`web`) or the native offer dialog+ * (`native`): fetches the release on offer. Anything else on offer is answered with a+ * status push (a build already waiting or downloading, or nothing offered at all — a+ * stale frame), so the asking side settles instead of waiting.+ */+async function startDownload(origin: "native" | "web"): Promise<void> {+ if (downloadedVersion !== null || downloadInFlight) {+ reannounceStatus();+ return;+ }+ if (status.state !== "available" || status.version === undefined) {+ log("download requested with nothing offered (stale frame); ignoring");+ reannounceStatus();+ return;+ }+ nativeDownload = origin === "native";+ emitStatus({ kind: "download-started", version: status.version });+ await downloadUpdateWithFallback();+}++/**+ * One download of the offered release, retried once on the other pinned feed when the+ * package fetch fails there: the retry re-checks on the fallback feed (whose `checking`+ * and same-version `available` the status fold suppresses under the running download)+ * and downloads again if it offers the release.+ */async function downloadUpdateWithFallback(): Promise<void> {if (downloadedVersion !== null || downloadInFlight) return;downloadInFlight = true;- let delegatedToRetryCheck = false;try {await autoUpdater.downloadUpdate();} catch (err) {const error = err as Error;if (downloadedVersion !== null) return;- downloadInFlight = false;if (switchToFallbackFeed("download failed")) {- delegatedToRetryCheck = true;try {const retryResult = await autoUpdater.checkForUpdates();- if (retryResult === null || !retryResult.isUpdateAvailable) {- const message = "The fallback update source did not offer a downloadable update.";- log(message);- emitStatus({ kind: "error", message });+ if (retryResult !== null && retryResult.isUpdateAvailable) {+ await autoUpdater.downloadUpdate();+ return;}+ const message = "The fallback update source did not offer a downloadable update.";+ log(message);+ emitStatus({ kind: "error", message });+ nativeDownload = false;} catch (retryErr) {- log(`check failed: ${(retryErr as Error).message}`);+ reportUpdaterError(retryErr as Error, "download");}return;}- reportUpdaterError(error);+ reportUpdaterError(error, "download");} finally {- if (!delegatedToRetryCheck) downloadInFlight = false;+ downloadInFlight = false;}}@@ -480,6 +532,11 @@ export async function checkForUpdatesManually(): Promise<void> {});return;}+ if (status.state === "available" && status.version !== undefined) {+ // The offer stands (check() leaves it alone); a manual check re-presents it.+ await promptDownload(status.version, null);+ return;+ }manualCheckInFlight = true;await check();if (manualCheckInFlight && feedState.phase === "unavailable") {@@ -493,6 +550,27 @@ export async function checkForUpdatesManually(): Promise<void> {}}+/**+ * "A release is available" prompt for the native path. Downloading is the user's call+ * here exactly as it is in the Web App's modal; a "Later" leaves the offer standing.+ */+async function promptDownload(version: string, parent: BrowserWindow | null): Promise<void> {+ const options = {+ type: "info" as const,+ message: `Version ${version} is available.`,+ detail:+ "Download it now? PenguinHarness keeps running while it downloads, and you will be asked to restart when it is ready.",+ buttons: ["Download", "Later"],+ defaultId: 0,+ cancelId: 1,+ };+ const result = parent+ ? await dialog.showMessageBox(parent, options)+ : await dialog.showMessageBox(options);+ if (result.response !== 0) return;+ await startDownload("native");+}+/** "Ready to install" prompt; restarting is the only path that swaps the app. */async function promptRestart(version: string, parent: BrowserWindow | null): Promise<void> {const options = {diff --git a/packages/desktop/test/updater-status.test.ts b/packages/desktop/test/updater-status.test.tsindex c16fa656..438f326f 100644--- a/packages/desktop/test/updater-status.test.ts+++ b/packages/desktop/test/updater-status.test.ts@@ -2,12 +2,13 @@* updater-status.ts unit tests: the event → snapshot fold behind the account-menu* client-update row, and the port frame helpers.*- * Two behavioral rules are worth pinning hard. `downloaded` suppresses transient noise- * (a re-check failing on a train's Wi-Fi must not hide the one actionable step) but- * yields to a *different* version being fetched — a replacement download invalidates- * the held package, so keeping the old headline would point the install at a deleted- * file. And `downloading` suppresses a concurrent check's `checking`, which would- * drop the download context and every later progress tick with it.+ * Three behavioral rules are worth pinning hard. A check ends in `available` and never+ * downloads on its own — the fetch begins on `download-started`, the user's say-so. Then+ * `downloaded` suppresses transient noise (a re-check failing on a train's Wi-Fi must not+ * hide the one actionable step) but yields to a *different* version being fetched — a+ * replacement download invalidates the held package, so keeping the old headline would+ * point the install at a deleted file. And `downloading` suppresses a concurrent check's+ * `checking`, which would drop the download context and every later progress tick with it.*/import { describe, expect, it } from "vitest";import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";@@ -36,8 +37,11 @@ describe("nextUpdateStatus", () => {});});- it("walks the download path: available → progress → downloaded", () => {- const downloading = fold([{ kind: "checking" }, { kind: "available", version: "1.1.0" }]);+ it("walks the download path: available → download-started → progress → downloaded", () => {+ // A check only offers: nothing is fetched until the user says so.+ const offered = fold([{ kind: "checking" }, { kind: "available", version: "1.1.0" }]);+ expect(offered).toEqual({ appVersion: "1.0.0", state: "available", version: "1.1.0" });+ const downloading = nextUpdateStatus(offered, { kind: "download-started", version: "1.1.0" });expect(downloading).toEqual({appVersion: "1.0.0",state: "downloading",@@ -84,9 +88,14 @@ describe("nextUpdateStatus", () => {}});- it("yields a downloaded build to a different version being fetched (the held package is being replaced)", () => {+ it("yields a downloaded build to a different version being offered or fetched (the held package is being replaced)", () => {const downloaded = fold([{ kind: "downloaded", version: "1.1.0" }]);expect(nextUpdateStatus(downloaded, { kind: "available", version: "1.2.0" })).toEqual({+ appVersion: "1.0.0",+ state: "available",+ version: "1.2.0",+ });+ expect(nextUpdateStatus(downloaded, { kind: "download-started", version: "1.2.0" })).toEqual({appVersion: "1.0.0",state: "downloading",version: "1.2.0",@@ -99,12 +108,36 @@ describe("nextUpdateStatus", () => {});});+ it("keeps a standing offer over a re-check's checking and its same-version re-announce", () => {+ const offered = fold([{ kind: "available", version: "1.1.0" }]);+ for (const ev of [+ { kind: "checking" },+ { kind: "available", version: "1.1.0" },+ ] satisfies UpdaterEvent[]) {+ expect(nextUpdateStatus(offered, ev)).toBe(offered);+ }+ // A real answer replaces it: the release was pulled, or another one took its place.+ expect(nextUpdateStatus(offered, { kind: "not-available" })).toEqual({+ appVersion: "1.0.0",+ state: "up-to-date",+ });+ expect(nextUpdateStatus(offered, { kind: "available", version: "1.2.0" })).toEqual({+ appVersion: "1.0.0",+ state: "available",+ version: "1.2.0",+ });+ });+it("keeps a running download over a concurrent check's noise", () => {- const downloading = fold([{ kind: "available", version: "1.1.0" }]);+ const downloading = fold([+ { kind: "available", version: "1.1.0" },+ { kind: "download-started", version: "1.1.0" },+ ]);for (const ev of [{ kind: "checking" },{ kind: "not-available" },{ kind: "available", version: "1.1.0" },+ { kind: "download-started", version: "1.1.0" },] satisfies UpdaterEvent[]) {expect(nextUpdateStatus(downloading, ev)).toBe(downloading);}@@ -117,13 +150,17 @@ describe("nextUpdateStatus", () => {});});- it("lets a running download switch to a different announced version, and still fail on its own error", () => {- const downloading = fold([{ kind: "available", version: "1.1.0" }]);+ it("lets a running download yield to a different announced version (offered anew), and still fail on its own error", () => {+ const downloading = fold([+ { kind: "available", version: "1.1.0" },+ { kind: "download-started", version: "1.1.0" },+ ]);+ // The package being fetched is invalidated by the replacement; the new one needs the+ // user's say-so again, so it is offered, not fetched.expect(nextUpdateStatus(downloading, { kind: "available", version: "1.2.0" })).toEqual({appVersion: "1.0.0",- state: "downloading",+ state: "available",version: "1.2.0",- percent: 0,});expect(nextUpdateStatus(downloading, { kind: "error", message: "disk full" })).toEqual({appVersion: "1.0.0",@@ -151,8 +188,11 @@ describe("port frames", () => {expect(updaterStatusMessage(status)).toEqual({ type: "desktop-updater-status", status });});- it("accepts exactly the two command frames", () => {+ it("accepts exactly the three command frames", () => {expect(parseUpdaterCommand({ type: "desktop-updater-command", action: "check" })).toBe("check");+ expect(parseUpdaterCommand({ type: "desktop-updater-command", action: "download" })).toBe(+ "download",+ );expect(parseUpdaterCommand({ type: "desktop-updater-command", action: "install" })).toBe("install",);diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex c1b6922a..a0924041 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -307,6 +307,8 @@ penguin webPort / host priority: command-line option > the `PORT` / `HOST` env vars (including `.env`) > defaults.+Both run the service as a child process and stay behind as its supervisor: the terminal's Ctrl+C reaches the service, the command exits with the service's exit code, and when the service asks to be restarted — the Web App's **Restart and update** after `penguin update` has replaced the install — the supervisor relaunches it on the new release, printing a line as it does. A dev run through `tsx` cannot be relaunched by plain node and runs the service in-process instead; the Web App then tells the admin to restart by hand.+### penguin server reset-admin-passwordOffline rescue when the Web admin password is forgotten. Run it with the server stopped — it refuses while one is running on the data root:diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex 59fe4dba..46f0077e 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -307,6 +307,8 @@ penguin web端口 / 地址优先级:命令行选项 > 环境变量 `PORT` / `HOST`(含 `.env`)> 默认值。+两者都把服务作为子进程运行,自己留在后面做托管:终端的 Ctrl+C 会送达服务,命令以服务的退出码退出;当服务请求重启——`penguin update` 替换安装后,Web App 里的「重启并更新」——托管进程会在新版本上重新拉起它,并打印一行提示。经 `tsx` 的开发运行无法被普通 node 重新拉起,改为在本进程内运行服务;此时 Web App 会提示管理员手动重启。+### penguin server reset-admin-password忘记 Web 管理员密码时的离线救援。须在服务停止后执行——数据根目录上有服务在运行时会拒绝:diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 9a876579..b8827946 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -131,7 +131,9 @@ Refusals decided before any ssh runs have their own codes: `409` `install_runnin| --- | --- | --- || GET | /api/version | Identity of the running build plus this root's pushed harness: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` — the same record `penguin version --json` prints. `harness` describes the data root's HMR store (`{source, pushedAt, bundles}`, where `source` is the pushing checkout's `{repo, revision}`) and is null when nothing was ever pushed there. `describe` is the one-line identity (`v0.2.3` for a release, `v0.2.3-14-g9e8f7d6-dirty` for a build from a checkout); `channel` is `release` or `source`; `buildDate` (UTC yyyy-mm-dd) and `commit` are stamped at build time, so no network is needed, and are null in a source build or a release predating the stamping; `branch` and `dirty` carry a source build's git position and are null for a release || GET | /api/version/update-check | Compares the newest GitHub release with the running version: `{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`; `?force=1` (the manual "check for updates" action) bypasses the TTL cache, and the outcome is cached as usual |-| POST | /api/version/update | **Admin only.** Runs the CLI self-update (`penguin update --yes`) on the server host: `{status, output, needsRestart}` |+| GET | /api/version/update | **Admin only.** The self-update job's status: `{state: idle \| running \| done, targetVersion, phase?, percent?, output, result?, startedAt?, finishedAt?}` — `phase` (`resolving` / `downloading` / `installing`) and `percent` (read off the installer's progress bar) while running; `result` (`{status, reason?, output, needsRestart}`) once done. Polled by the update dialog while a run is in flight |+| POST | /api/version/update | **Admin only.** Starts the self-update job — `penguin update --yes` on the server host, in the background — unless one is running (then it is joined); answers with the status exactly as GET does. A finished run may be started again (a retry) |+| POST | /api/version/restart | **Admin only.** Asks the process to exit with the supervisor's restart code after a graceful shutdown, so `penguin server \| penguin web` relaunches it on the installed release: `{restarting: true}`; `{restarting: false, reason: "no_supervisor"}` when nothing supervises the process |`update-check` is the server's only outbound internet call and is strictly fail-soft: a failed lookup still returns 200 with `error` set (`network` / `rate_limited` / `bad_response`) and `latestVersion: null`, results are cached in memory (success 1 h, failure 10 min), and setting `PENGUIN_UPDATE_CHECK=off` disables the lookup entirely (`disabled: true`, no network call). The update `status` is `updated` (restart the service to run the new version), `failed`, or `unsupported` — the latter both when the server was not started via `penguin server|web` (`reason: "not_launched_via_cli"`) and when the CLI refuses (source checkout, unrecognized install layout, Windows); `output` carries the tail of the CLI's own output.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 889e21ba..6fb7ff57 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -131,7 +131,9 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \| --- | --- | --- || GET | /api/version | 当前运行构建的身份,外加该根目录被推送的 harness:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`,与 `penguin version --json` 输出同一份记录。`harness` 描述该数据根目录的 HMR store(`{source, pushedAt, bundles}`,其中 `source` 为推送方 checkout 的 `{repo, revision}`),从未被推送过时为 null。`describe` 是单行身份(发布版为 `v0.2.3`,源码构建为 `v0.2.3-14-g9e8f7d6-dirty`);`channel` 取 `release` 或 `source`;`buildDate`(UTC yyyy-mm-dd)与 `commit` 在构建时打入、无需联网,源码构建以及打入机制之前的发布版为 null;`branch` 与 `dirty` 记录源码构建的 git 位置,发布版为 null || GET | /api/version/update-check | 对比 GitHub 最新 Release 与当前版本:`{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`;`?force=1`(手动「检查更新」)绕过 TTL 缓存,结果照常写入缓存 |-| POST | /api/version/update | **仅管理员。**在服务器上执行 CLI 在线更新(`penguin update --yes`):`{status, output, needsRestart}` |+| GET | /api/version/update | **仅管理员。**在线更新任务的状态:`{state: idle \| running \| done, targetVersion, phase?, percent?, output, result?, startedAt?, finishedAt?}`——运行中带 `phase`(`resolving` / `downloading` / `installing`)与 `percent`(从安装器的进度条读出);结束后带 `result`(`{status, reason?, output, needsRestart}`)。更新弹窗在任务运行期间轮询它 |+| POST | /api/version/update | **仅管理员。**启动在线更新任务——在服务器上后台运行 `penguin update --yes`——已有任务在跑则并入;应答与 GET 完全一致。已结束的任务可以再次启动(即重试) |+| POST | /api/version/restart | **仅管理员。**请求进程在优雅关闭后以托管进程约定的重启退出码退出,由 `penguin server \| penguin web` 在已安装的版本上重新拉起:`{restarting: true}`;没有托管进程时为 `{restarting: false, reason: "no_supervisor"}` |`update-check` 是服务端唯一的对外网络请求,并且严格失败兜底:查询失败仍返回 200,只是设置 `error`(`network` / `rate_limited` / `bad_response`)且 `latestVersion` 为 null;结果在内存中缓存(成功 1 小时、失败 10 分钟);设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭该查询(返回 `disabled: true`,不发起任何网络请求)。更新的 `status` 为 `updated`(需重启服务才能运行新版本)、`failed` 或 `unsupported` —— 后者包括服务不是通过 `penguin server|web` 启动(`reason: "not_launched_via_cli"`),以及 CLI 自身拒绝执行(源码运行、无法识别的安装方式、Windows);`output` 携带 CLI 输出的末尾片段。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 55304c21..53e840a2 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -156,11 +156,11 @@ Two numbers are deliberately not exposed. The per-message file **count** stays a## Version and Updates-Checking for updates sits outside the settings dialog: one row in the sidebar user menu, directly under the **System settings** entry, so it is reachable without opening anything. The row has two states — it reads "Check for updates" and runs the manual check until a newer release is known, then turns in place into "New version vX available" and opens the update dialog instead. The running version sits muted on its right.+Updating works the way an app updater does, from one dialog. Two entries open it: the row directly under **System settings** in the sidebar user menu, and the small "New version available" superscript on the new-chat page's version line (`vX.Y.Z · Last updated Jul 26` — the date is stamped into the build by the release workflow and shown without any network access; dev builds and releases predating the stamping, v0.1.2 and earlier, have no date). The row names where things stand — "Check for updates", "Checking…", "New version vX available", "Downloading vX 42%", "Restart to update to vX" — with the running version muted on its right, and every state opens the dialog.-The running version's release date is stamped into the build by the release workflow and displayed without any network access: the new-chat page shows it under the brand as `vX.Y.Z · Last updated Jul 26` (dev builds and releases that predate the stamping, v0.1.2 and earlier, have no date). The app checks GitHub for a newer release once the sidebar user menu has first been opened, and immediately — bypassing the cached result — when the manual action is clicked; the latter reports "You're on the latest version" when nothing newer exists. When a newer release is found, a dot appears on the user button and the draft page's version line gains a small superscript "New version available" badge linking to the release. The update dialog carries the release-notes link, plus an "Update now" action for admins that runs `penguin update` on the server (the data directory is untouched). The service must be restarted afterwards for the update to take effect. Set `PENGUIN_UPDATE_CHECK=off` to disable the update check entirely — see the [Configuration Reference](/configuration).+The dialog walks the update through: opening it with nothing known runs a check (the app also checks GitHub once per load, and the manual check bypasses the cached result); a newer release is offered with its release-notes link and a **Download and update** button, and nothing is fetched until you press it; a progress bar follows the download, and **Continue in background** closes the dialog without cancelling anything — the row keeps showing the percentage, a dot on the user button appears once the release is ready, and a toast announces it; then **Restart and update** finishes the job. On a server the download is `penguin update` running in the background (the data directory is untouched), the bar reads the installer's own progress, and the restart is real when the service runs under `penguin web` or `penguin server`, which supervise it: the service comes back on the new release and the page reloads by itself. A service started some other way is told to restart by hand instead. Non-admins can read the release notes but cannot run the update. A failed download shows the update command's own output and offers a retry; an install that cannot update itself (a source checkout, an unrecognized layout, Windows) says why. Set `PENGUIN_UPDATE_CHECK=off` to disable the update check entirely — see the [Configuration Reference](/configuration).-**In the desktop app** that row becomes a client-update row — the shell updates itself, and the server check never appears in desktop mode — in the shell's own window only. It drives the app's own updater end to end: "Check for updates", then a background download with its percentage in the label, then "Restart to install vX", which asks for confirmation first because restarting interrupts running Tasks. The installed client version sits muted on the right, and the app also checks on its own schedule, so the row may already offer the restart when you open the menu. A browser signed into the same desktop-mode server with a password gets neither row: it can neither read that machine's updater state nor restart its window, and it cannot run the CLI self-update on that server either. Forms that cannot replace themselves — a Linux install owned by the system package manager (`.deb`), and a development run — render the row disabled with the reason as its tooltip; the [Desktop app guide](/quickstart-desktop) covers the installers.+**In the desktop app** the same dialog drives the app's own updater — in the shell's own window only, where the server release never appears. The shell checks on its own schedule but never downloads on its own: a found release shows up as the dot and the row, the download starts from the dialog, its percentage is the updater's real progress, and **Restart and update** restarts into the downloaded build (the shell's native "Check for Updates…" menu item offers the same download-then-restart steps in native dialogs). A browser signed into the same desktop-mode server with a password gets no update entry at all: it can neither read that machine's updater state nor restart its window, and it cannot run the CLI self-update on that server either. Forms that cannot replace themselves — a Linux install owned by the system package manager (`.deb`), and a development run — say so in the dialog; the [Desktop app guide](/quickstart-desktop) covers the installers.## Projects and Membersdiff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 3151c46a..efad73e3 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -155,11 +155,11 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,## 版本与更新-检查更新在设置弹窗之外:侧边栏用户菜单里,紧贴「系统设置」下方的一行,无需打开弹窗即可点到。该行只有两种状态——未知有新版本时读作「检查更新」并执行手动检查,一旦查到新版本便就地变为「新版本 vX 可用」并改为打开更新弹窗;当前运行版本号以浅色显示在该行右侧。+更新的交互和常见的应用更新器一样,集中在一个弹窗里。两个入口都打开它:侧边栏用户菜单里紧贴「系统设置」下方的那一行,以及新对话页版本行上的「有新版本可用」上标(版本行形如「vX.Y.Z · 最近更新日期 7 月 26 日」——日期由发布流程在构建时打入,直接显示、无需联网;开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。那一行会说明进行到哪一步——「检查更新」「检查中…」「新版本 vX 可用」「正在下载 vX 42%」「重启以更新到 vX」——右侧以浅色显示当前运行版本,任何状态点击都打开弹窗。-版本的发布日期由发布流程在构建时打入,直接显示、无需联网:新对话页在品牌下方的版本行以「vX.Y.Z · 最近更新日期 7 月 26 日」呈现(开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。侧边栏用户菜单首次打开后会向 GitHub 查询是否有新版本;点击「检查更新」则立即查询(绕过缓存结果),已是最新时以提示告知。发现新版本时,用户按钮上会出现提示圆点,新对话页的版本行会出现可跳转 Release 页面的「有新版本可用」上标小徽标。更新弹窗提供更新说明链接,管理员还可点击「立即更新」,在服务器上执行 `penguin update`(数据目录不受影响)。更新完成后需要重启服务才会生效。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。+弹窗按步骤走完更新:在一无所知时打开会先检查(应用每次加载也会向 GitHub 查一次,手动检查则绕过缓存结果);查到新版本时给出更新说明链接和「下载并更新」按钮,按下之前不会下载任何东西;下载中显示进度条,「放到后台」只是关掉弹窗、不取消下载——那一行继续显示百分比,下载就绪后用户按钮上出现圆点并弹出提示;最后「重启并更新」完成整个过程。在服务器上,下载就是后台运行的 `penguin update`(数据目录不受影响),进度条读的是安装器自己的进度;当服务由 `penguin web` 或 `penguin server` 托管时,重启是真实的——服务在新版本上回来,页面自动刷新;用其他方式启动的服务则被告知需要手动重启。非管理员可以看更新说明,但不能执行更新。下载失败会显示更新命令自己的输出并提供重试;无法自更新的安装方式(源码运行、无法识别的目录布局、Windows)会说明原因。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。-**在桌面应用中**这一行改为客户端更新入口——客户端自己更新,服务端的检查在桌面模式下完全不出现——且只出现在 shell 自身的窗口里。该行端到端驱动应用自带的更新器:先是「检查更新」,随后是后台下载并把百分比显示在文案里,最后是「重启并安装 vX」;由于重启会打断正在运行的 Task,点击后会先要求确认。当前安装的客户端版本以浅色显示在该行右侧;应用也会按自己的节奏后台检查,所以打开菜单时该行可能已经在等你重启安装。用密码登录同一台桌面模式服务器的浏览器两行都不会看到:它既读不到那台机器的更新状态,也无法重启它的窗口,更无法在那台服务器上跑 CLI 自更新。无法自我替换的形态——由系统包管理器管理的 Linux 安装(`.deb`)以及开发运行——该行渲染为禁用,原因显示在悬浮提示里;安装包本身见[桌面应用指南](/quickstart-desktop)。+**在桌面应用中**同一个弹窗驱动的是应用自带的更新器——只在 shell 自身的窗口里,服务端的版本在那里完全不出现。shell 会按自己的节奏后台检查,但绝不自行下载:查到的版本以圆点和那一行的文案出现,下载从弹窗开始,百分比来自更新器的真实进度,「重启并更新」重启进已下载的版本(shell 原生菜单里的「Check for Updates…」在原生对话框里提供同样的「先下载、再重启」两步)。用密码登录同一台桌面模式服务器的浏览器完全看不到更新入口:它既读不到那台机器的更新状态,也无法重启它的窗口,更无法在那台服务器上跑 CLI 自更新。无法自我替换的形态——由系统包管理器管理的 Linux 安装(`.deb`)以及开发运行——在弹窗里说明原因;安装包本身见[桌面应用指南](/quickstart-desktop)。## Project 与成员diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 98fd2269..57466a46 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3125,7 +3125,9 @@ export interface UpdateCheckResponse {* utilityProcess message channel and served at GET /api/desktop/update. `state` is the* discriminator; the optional fields belong to the states named on them.*- * A `downloaded` build stays the reported state until it is installed: a later periodic+ * The shell never downloads on its own: a check ends in `available`, and the download+ * starts only on the page's (or the native dialog's) say-so — the `download` command. A+ * `downloaded` build stays the reported state until it is installed: a later periodic* check (or its failure) must not hide the actionable "restart to install" step.*/export interface DesktopUpdateStatus {@@ -3139,8 +3141,15 @@ export interface DesktopUpdateStatus {*/seq?: number;state:- "idle" | "checking" | "up-to-date" | "downloading" | "downloaded" | "error" | "unsupported";- /** Newer release being fetched / ready to install (`downloading`, `downloaded`). */+ | "idle"+ | "checking"+ | "up-to-date"+ | "available"+ | "downloading"+ | "downloaded"+ | "error"+ | "unsupported";+ /** The newer release: offered (`available`), being fetched (`downloading`) or ready to install (`downloaded`). */version?: string;/** Download progress 0–100 (`downloading`). */percent?: number;@@ -3164,16 +3173,20 @@ export interface DesktopUpdaterStatusMessage {status: DesktopUpdateStatus;}-/** Server → shell command over the utilityProcess message channel (relayed from POST /api/desktop/update/check|install). */+/**+ * Server → shell command over the utilityProcess message channel (relayed from+ * POST /api/desktop/update/check|download|install): look for a release, fetch the one+ * offered, or restart into the one downloaded.+ */export interface DesktopUpdaterCommandMessage {type: "desktop-updater-command";- action: "check" | "install";+ action: "check" | "download" | "install";}/**- * POST /api/version/update (admin only): runs the CLI self-update (`penguin update --yes`)- * on the server host. `unsupported` covers both a server not launched via the CLI and the- * CLI's own refusals (source checkout, unrecognized install layout, Windows).+ * The outcome of one self-update run (`penguin update --yes` on the server host), carried+ * by {@link UpdateJobStatus.result}. `unsupported` covers both a server not launched via+ * the CLI and the CLI's own refusals (source checkout, unrecognized install layout, Windows).*/export interface UpdateRunResponse {status: "updated" | "failed" | "unsupported";@@ -3185,6 +3198,47 @@ export interface UpdateRunResponse {needsRestart: boolean;}+/**+ * Where a running self-update is: resolving the release and fetching the installer,+ * downloading the bundle (the one phase with a percentage), or verifying and installing it.+ */+export type UpdateJobPhase = "resolving" | "downloading" | "installing";++/**+ * GET / POST /api/version/update (admin only): the self-update job. POST starts a run when+ * none is in flight — a finished run may be started again, which is how a failed one is+ * retried — and answers with the status exactly as GET does; the page polls GET while+ * `state` is `running`. One job per process: two admins clicking at once share the one run,+ * and the finished status stays readable until the next start.+ */+export interface UpdateJobStatus {+ state: "idle" | "running" | "done";+ /** The release the run targets — the update check's newest version when the run started; null when none was known. */+ targetVersion: string | null;+ /** Running only. */+ phase?: UpdateJobPhase;+ /** Running, `downloading` only: 0–100 read off the installer's progress bar; null until its first tick. */+ percent?: number | null;+ /** Tail of the update command's combined stdout+stderr so far (capped; empty when nothing ran). */+ output: string;+ /** Done only. */+ result?: UpdateRunResponse;+ startedAt?: string;+ finishedAt?: string;+}++/**+ * POST /api/version/restart (admin only): asks the process to exit with the supervisor's+ * restart code after a graceful shutdown, so `penguin server|web` relaunches it on the+ * installed release. `restarting: false` when nothing supervises this process — it was+ * started some other way than through the CLI, or it is a dev run — and the page shows the+ * manual restart hint instead.+ */+export interface RestartResponse {+ restarting: boolean;+ reason?: "no_supervisor";+}+/** One `Host` entry of the server's `~/.ssh/config`, as the Machines page lists it. */export interface MachineInfo {/** `ssh:<alias>` — the id the install route is asked for. */diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex d56799d3..c003838a 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -36,6 +36,7 @@ import {RUNTIME_CONFIG_RESOURCE_ID,RUNTIME_DB_RESOURCE_ID,RUNTIME_DESKTOP_RESOURCE_ID,+ RUNTIME_LIFECYCLE_RESOURCE_ID,RUNTIME_HMR_RESOURCE_ID,RUNTIME_OVERRIDES_RESOURCE_ID,RUNTIME_PROXY_RESOURCE_ID,@@ -97,6 +98,7 @@ import type { QQScanTransport } from "./runtime/messaging/qq-scan.js";import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";import { AdminService } from "./services/admin-service.js";import { DesktopService } from "./services/desktop-service.js";+import { LifecycleService } from "./services/lifecycle-service.js";import { desktopRoutes, desktopUpdateRoutes } from "./http/routes/desktop.js";import { AgentConfigService } from "./services/agent-config-service.js";import { MemoryService } from "./services/memory-service.js";@@ -110,6 +112,7 @@ import { SessionService } from "./services/session-service.js";import { TraceIndexService } from "./services/trace-index.js";import { TraceService } from "./services/trace-service.js";import { UpdateCheckService } from "./services/update-check-service.js";+import { UpdateJobService } from "./services/update-job.js";import { UsageService } from "./services/usage-service.js";import { WorkspaceFilesService } from "./services/workspace-files-service.js";import { HmrHost } from "./hmr/host.js";@@ -184,6 +187,8 @@ export interface AppDeps {usageService: UsageService;/** GitHub latest-release lookup for the web UI's update reminder (cached, fail-soft). */updateCheck: UpdateCheckService;+ /** The admin self-update run in the background (`penguin update --yes`), with its progress for the update modal. */+ updateJob: UpdateJobService;workspaceFiles: WorkspaceFilesService;/** Signs/verifies short-lived Workspace preview tokens (separate preview origin). */previewTokens: PreviewTokenSigner;@@ -209,6 +214,8 @@ export interface AppDeps {errors: ErrorRecorder;/** Desktop mode (PENGUIN_DESKTOP_TOKEN): one-shot login + shutdown token holder; null outside desktop mode. */desktop: DesktopService | null;+ /** Process lifecycle: whether a supervisor relaunches this process, and the restart trigger (the "restart to update" step). */+ lifecycle: LifecycleService;/*** Installing this build on a machine from the server's own `~/.ssh/config` (the Machines* page). Business, not runtime: spawning ssh and packing an image are in-process effects,@@ -235,6 +242,8 @@ export interface BuildDepsOverrides {titles?: TitleNotifier;/** Test double: update-check service with a stubbed fetch/clock (avoids real network calls). */updateCheck?: UpdateCheckService;+ /** Tests: a job service over a scripted runner, so no real `penguin update` is ever spawned. */+ updateJob?: UpdateJobService;/** Test double: the Feishu connector's SDK factory (avoids real Lark network / long connections). */feishuSdk?: FeishuSdk;/** Test double: the Telegram connector's Bot API transport (avoids real Telegram network / long polls). */@@ -331,6 +340,7 @@ export async function bootAppDeps(hmr.resources.register(RUNTIME_OVERRIDES_RESOURCE_ID, overrides);const desktop = config.desktopToken !== null ? new DesktopService(config.desktopToken) : null;hmr.resources.register(RUNTIME_DESKTOP_RESOURCE_ID, desktop);+ hmr.resources.register(RUNTIME_LIFECYCLE_RESOURCE_ID, new LifecycleService(config.supervised));// The registry sweep only STARTS extension disposal (its disposers are sync) — the// fallback for exit paths that skip the graceful shutdown. The graceful path awaits// host.dispose() itself, bounded (index.ts); dispose is idempotent, so both may fire.@@ -878,6 +888,7 @@ export function buildAppDeps();const updateCheck =overrides.updateCheck ?? new UpdateCheckService(overrides.now ? { now: overrides.now } : {});+ const updateJob = overrides.updateJob ?? new UpdateJobService();const recorder = new UsageRecorder(usageRepo, overrides.now ?? (() => new Date()));const errors = new ErrorRecorder(errorsRepo, overrides.now ?? (() => new Date()));@@ -1063,6 +1074,7 @@ export function buildAppDeps(traceIndex,usageService,updateCheck,+ updateJob,workspaceFiles,previewTokens,benchmarks,@@ -1080,6 +1092,7 @@ export function buildAppDeps(sessionSources,errors,desktop: caps.desktop,+ lifecycle: caps.lifecycle,// Anchored at the data root: that is where the hmr store the pushable image comes from// lives, and where verified Node runtime downloads are cached between installs.machines: overrides.machines ?? new MachinesService(config.root, {}, () => hmr.assetsDir()),diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex 36864edd..e6e43724 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -61,6 +61,12 @@ export interface ServerConfig {* URL, which must never leave the machine.*/desktopToken: string | null;+ /**+ * Whether `penguin server|web` supervises this process (PENGUIN_SUPERVISED=1) and relaunches+ * it when it exits with core's SERVER_RESTART_EXIT_CODE — what makes the web UI's "restart+ * to update" possible. False under a direct server start, a dev run, or the desktop shell.+ */+ supervised: boolean;/*** Port announcement file (PENGUIN_PORT_FILE): after the listener is up, the actual* bound port is written here — the supervising process's way to learn the port when@@ -145,5 +151,6 @@ export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServedesktopToken,portFile: env.PENGUIN_PORT_FILE?.trim() || null,trustProxy: env.PENGUIN_TRUST_PROXY === "1",+ supervised: env.PENGUIN_SUPERVISED === "1",};}diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex b83c1318..f5dd75d1 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -30,6 +30,7 @@ import type { ProxySettings } from "../net/proxy.js";import type { BuildDepsOverrides } from "../app.js";import type { HmrHost } from "../hmr/host.js";import type { DesktopService } from "../services/desktop-service.js";+import type { LifecycleService } from "../services/lifecycle-service.js";/*** What one side of the seam speaks: a family, and a Go-style structural interface per@@ -90,6 +91,7 @@ interface RuntimeInterfaces extends Interfaces {proxy: MembersOf<ProxyControl>;hmr: MembersOf<HmrHost>;desktop: MembersOf<DesktopService>;+ lifecycle: MembersOf<LifecycleService>;}export const RUNTIME_INTERFACES: RuntimeInterfaces = {@@ -107,6 +109,7 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {"desktopToken","portFile","trustProxy",+ "supervised",],db: ["prepare", "exec", "close"],channels: ["get", "peek", "broadcast", "dispose", "setActivityProbe"],@@ -117,6 +120,7 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {// optional, so there are no members to verify.overrides: [],desktop: ["onShutdownRequest", "requestShutdown", "verifyToken", "redeemLoginToken"],+ lifecycle: ["supervised", "onRestartRequest", "requestRestart"],};export const RUNTIME_INTERFACES_RESOURCE_ID = "runtime:interfaces";@@ -184,6 +188,12 @@ export const RUNTIME_HMR_RESOURCE_ID = "runtime:hmr-host";* admin surfaces), so the claim must distinguish "not desktop" from "not published".*/export const RUNTIME_DESKTOP_RESOURCE_ID = "runtime:desktop";+/**+ * Process lifecycle (services/lifecycle-service.ts): whether a supervisor relaunches this+ * process, and the restart trigger. Always published — the platform's restart route needs+ * a definite "nobody would relaunch me" to refuse with, not a missing capability.+ */+export const RUNTIME_LIFECYCLE_RESOURCE_ID = "runtime:lifecycle";/** Test-only: BuildDepsOverrides published by bootAppDeps for the platform boot to claim. */export const RUNTIME_OVERRIDES_RESOURCE_ID = "runtime:overrides";@@ -226,6 +236,7 @@ export interface RuntimeCapabilities {hmr: HmrHost;/** Null on a non-desktop server (a real value, not an absent capability). */desktop: DesktopService | null;+ lifecycle: LifecycleService;/** The construction-override seam; {} outside tests. */overrides: BuildDepsOverrides;}@@ -274,7 +285,8 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {const channels = resources.claim<ChannelHub>(RUNTIME_CHANNELS_RESOURCE_ID);const proxyControl = resources.claim<ProxyControl>(RUNTIME_PROXY_RESOURCE_ID);const hmr = resources.claim<HmrHost>(RUNTIME_HMR_RESOURCE_ID);- if (!config || !db || !channels || !proxyControl || !hmr) {+ const lifecycle = resources.claim<LifecycleService>(RUNTIME_LIFECYCLE_RESOURCE_ID);+ if (!config || !db || !channels || !proxyControl || !hmr || !lifecycle) {return { kind: "refused", reason: "a declared capability was not actually published" };}// Desktop is nullable by meaning, so it sits outside the all-present check.@@ -298,6 +310,7 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {["channels", channels],["proxy", proxyControl],["hmr", hmr],+ ["lifecycle", lifecycle],...(desktop === null ? [] : ([["desktop", desktop]] as Array<[string, unknown]>)),];for (const [name, value] of live) {@@ -310,6 +323,6 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {}return {kind: "claimed",- caps: { config, db, authState, channels, proxyControl, hmr, desktop, overrides },+ caps: { config, db, authState, channels, proxyControl, hmr, desktop, lifecycle, overrides },};}diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.tsindex 33b9a0bc..65be3be2 100644--- a/packages/server/src/http/routes/desktop.ts+++ b/packages/server/src/http/routes/desktop.ts@@ -64,8 +64,9 @@ export function desktopRoutes(deps: AppDeps): Hono {* only in desktop mode). Restricted to the shell's own window (`sessionVia === "desktop"`,* the same two-field rule as the change-password gate, inverted): a browser signed into* the same desktop-mode server must not read the machine's updater state or restart its- * GUI app. Install consent is collected by the page's confirm dialog before the POST —- * the shell then installs only what its updater already downloaded and verified.+ * GUI app. Consent is collected by the page's update modal before each POST: `download`+ * fetches only the release the shell has offered, and `install` restarts only into what+ * its updater already downloaded and verified.*/export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -96,6 +97,14 @@ export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {return c.body(null, 202);});+ app.post("/download", (c) => {+ const desktop = requireShellSession(c);+ if (!desktop.requestUpdateCommand("download")) {+ throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");+ }+ return c.body(null, 202);+ });+app.post("/install", (c) => {const desktop = requireShellSession(c);if (!desktop.requestUpdateCommand("install")) {diff --git a/packages/server/src/http/routes/version.ts b/packages/server/src/http/routes/version.tsindex 73c7bfa1..bbcd27ba 100644--- a/packages/server/src/http/routes/version.ts+++ b/packages/server/src/http/routes/version.ts@@ -1,128 +1,47 @@/*** Version routes: the running release identity, the update-check reminder, and the- * admin-only self-update.+ * admin-only self-update with its restart.** GET /api/version -> versionReport(): the running build's identity plus* this root's pushed harness, the same record* `penguin version --json` prints* GET /api/version/update-check -> UpdateCheckService (fail-soft, cached, opt-out env;* ?force=1 bypasses the cache for the manual check)- * POST /api/version/update -> admin only: re-runs the CLI as `penguin update --yes`+ * GET /api/version/update -> admin only: the self-update job's status+ * POST /api/version/update -> admin only: starts the job — `penguin update --yes`+ * in the background, progress readable at GET+ * (services/update-job.ts owns the run)+ * POST /api/version/restart -> admin only: restart into the installed release*- * How the self-update works: `penguin server|web` exports PENGUIN_CLI_ENTRY (its own entry- * script path) before importing this server, and this route re-runs that script as- * `node <entry> update --yes` — the CLI's update command owns all install-kind detection,- * download and replacement logic (packages/cli/src/commands/update.ts). A server started- * any other way (tests, a custom embedding) has no CLI to run and reports "unsupported".- * SECURITY: the spawned argv is a fixed literal list; nothing from the request flows into- * the command, its arguments, or its environment.- *- * Interpreting the CLI's outcome: `penguin update` exits non-zero only when an upgrade was- * attempted and failed; refusals (source checkout, unrecognized layout, Windows) print a- * message and exit 0. Exit codes alone therefore cannot separate "updated" from- * "unsupported", so the spawn forces PENGUIN_LANG=en and classifies by the refusal- * messages' stable English fragments (packages/cli/src/i18n.ts, `update` section). That- * matching is reliable here because the spawned CLI and this server ship in lockstep from- * the same install — the strings can never be from a different release than this code.+ * The restart is the supervisor's job: `penguin server|web` runs this process as a child and+ * relaunches it when it exits with core's SERVER_RESTART_EXIT_CODE, which is what the+ * lifecycle capability's trigger does after the graceful shutdown. Without a supervisor the+ * route says so (`no_supervisor`) instead of stopping a service nobody would bring back,+ * and the page shows the manual restart hint.*/-import { spawn } from "node:child_process";import { versionReport } from "../../version-report.js";import { Hono } from "hono";-import type { UpdateRunResponse, VersionResponse } from "../../api/types.js";+import type { Context } from "hono";+import type { RestartResponse, UpdateJobStatus, VersionResponse } from "../../api/types.js";import { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";import type { AppDeps } from "../../app.js";-/** Only the tail of the update output is kept (installer logs can be long). */-const OUTPUT_CAP = 64 * 1024;-/** The whole update (download + install) must finish within this window. */-const UPDATE_TIMEOUT_MS = 10 * 60 * 1000;+// The classifier lives with the job now; re-exported so its unit tests keep their import.+export { classifyUpdateRun } from "../../services/update-job.js";-/**- * English fragments of the CLI refusal messages (packages/cli/src/i18n.ts `update.*`),- * one per refusal reason. `needsYes` / `cancelled` are omitted: `--yes` makes the- * confirmation gate proceed unconditionally, so neither can occur here.- */-const REFUSAL_MARKERS = [- "runs from a source checkout", // sourceCheckout- "Cannot tell how this penguin was installed", // unknownInstall- "could not be identified", // npmUnknownManager- "does not run on Windows", // windowsUnsupported- "cannot run your package manager for you", // windowsGlobalInstall-];+/** Delay between answering the restart request and leaving: lets the response flush. */+const RESTART_DELAY_MS = 50;-/**- * Maps the finished CLI run to an UpdateRunResponse. Exported for unit tests (tests never- * spawn anything real). Exit 0 with a refusal message is "unsupported"; any other exit 0- * is "updated" — including the CLI's "already on the latest version", because that means- * the *install* is current and only a restart of this (older, in-memory) process is- * missing, which is exactly what needsRestart says.- */-export function classifyUpdateRun(exitCode: number, output: string): UpdateRunResponse {- if (exitCode !== 0) return { status: "failed", output, needsRestart: false };- if (REFUSAL_MARKERS.some((marker) => output.includes(marker))) {- return { status: "unsupported", output, needsRestart: false };+function requireAdmin(c: Context<AppEnv>): void {+ if (!c.var.user.isAdmin) {+ throw new HttpError(403, "admin_required", "Only an admin can perform this operation.");}- return { status: "updated", output, needsRestart: true };-}--/** Runs `node <cliEntry> update --yes` to completion and classifies the outcome. */-function runSelfUpdate(cliEntry: string): Promise<UpdateRunResponse> {- return new Promise((resolve) => {- // PENGUIN_LANG=en pins the CLI's output language so classifyUpdateRun's markers match- // regardless of the deployment's configured CLI language.- const child = spawn(process.execPath, [cliEntry, "update", "--yes"], {- env: { ...process.env, PENGUIN_LANG: "en" },- stdio: ["ignore", "pipe", "pipe"],- });-- let output = "";- const append = (chunk: Buffer) => {- output = (output + chunk.toString("utf8")).slice(-OUTPUT_CAP);- };- child.stdout.on("data", append);- child.stderr.on("data", append);-- let timedOut = false;- const timer = setTimeout(() => {- timedOut = true;- child.kill("SIGTERM");- // A SIGTERM-ignoring child would otherwise leave this request hanging forever.- setTimeout(() => child.kill("SIGKILL"), 10_000).unref();- }, UPDATE_TIMEOUT_MS);- timer.unref();-- child.on("error", (err) => {- clearTimeout(timer);- resolve({- status: "failed",- output: `${output}\n[failed to run the update command: ${err.message}]`.trim(),- needsRestart: false,- });- });- child.on("close", (code) => {- clearTimeout(timer);- if (timedOut) {- resolve({- status: "failed",- output:- `${output}\n[the update run was killed after ${UPDATE_TIMEOUT_MS / 60_000} minutes]`.trim(),- needsRestart: false,- });- return;- }- resolve(classifyUpdateRun(code ?? -1, output.trim()));- });- });}export function versionRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();- // Two admins clicking "update" at once must not race two installers over the same- // install dir: concurrent requests share the one in-flight run (and its result).- let inflightRun: Promise<UpdateRunResponse> | null = null;-app.get("/", async (c) => {return c.json((await versionReport(deps.config.root)) satisfies VersionResponse);});@@ -133,23 +52,34 @@ export function versionRoutes(deps: AppDeps): Hono<AppEnv> {return c.json(await deps.updateCheck.check(c.req.query("force") === "1"));});+ app.get("/update", (c) => {+ requireAdmin(c);+ return c.json(deps.updateJob.status() satisfies UpdateJobStatus);+ });+app.post("/update", async (c) => {- if (!c.var.user.isAdmin) {- throw new HttpError(403, "admin_required", "Only an admin can perform this operation.");- }- const cliEntry = process.env.PENGUIN_CLI_ENTRY;- if (!cliEntry) {- return c.json({- status: "unsupported",- reason: "not_launched_via_cli",- output: "",- needsRestart: false,- } satisfies UpdateRunResponse);+ requireAdmin(c);+ // Which release the run targets is a label for the modal, read from the server's own+ // (cached) lookup — never from the request, and never something the run depends on:+ // `penguin update` resolves the release itself.+ const check = await deps.updateCheck.check(false);+ const target = check.updateAvailable ? check.latestVersion : null;+ const cliEntry = process.env.PENGUIN_CLI_ENTRY ?? null;+ return c.json(deps.updateJob.start(cliEntry, target) satisfies UpdateJobStatus);+ });++ app.post("/restart", (c) => {+ requireAdmin(c);+ if (!deps.lifecycle.supervised()) {+ return c.json({ restarting: false, reason: "no_supervisor" } satisfies RestartResponse);}- inflightRun ??= runSelfUpdate(cliEntry).finally(() => {- inflightRun = null;- });- return c.json(await inflightRun);+ // Answer first, then leave: the response must be on the wire before the listener closes.+ setTimeout(() => {+ if (!deps.lifecycle.requestRestart()) {+ console.error("[server] restart requested, but no restart trigger is registered");+ }+ }, RESTART_DELAY_MS).unref();+ return c.json({ restarting: true } satisfies RestartResponse);});return app;diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex a7ac529f..3e6778f6 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -19,6 +19,7 @@ import path from "node:path";import type { Server as HttpServer } from "node:http";import { config as loadDotenv } from "dotenv";import { serve } from "@hono/node-server";+import { SERVER_RESTART_EXIT_CODE } from "@prismshadow/penguin-core";import { bootAppDeps, createRuntimeApp, type AppDeps } from "./app.js";import { ADMIN_USER_ID } from "./auth/service.js";import { resolveServerConfig, type ServerConfig } from "./config.js";@@ -227,6 +228,14 @@ class PenguinServer {// TerminateProcess with no signal delivery.this.deps.desktop?.onShutdownRequest(() => void this.shutdown("desktop-shutdown"));+ // Restart-to-update: POST /api/version/restart lands here once a self-update is+ // installed — the same graceful shutdown, exiting with the code the supervising+ // `penguin server|web` respawns on, so the relaunch runs the new release. The+ // lifecycle service only fires it when a supervisor is actually there.+ this.deps.lifecycle.onRestartRequest(+ () => void this.shutdown("restart", SERVER_RESTART_EXIT_CODE),+ );+// Client-update relay: under the shell this process is an Electron utilityProcess and// carries process.parentPort; wire it to the desktop service so the update routes can// read the shell's updater snapshot and forward check/install. Absent port (a plaindiff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.tsindex f85b1762..0619569d 100644--- a/packages/server/src/services/desktop-service.ts+++ b/packages/server/src/services/desktop-service.ts@@ -15,12 +15,15 @@** The service is also the shell↔web relay for client updates: the shell pushes its* updater snapshot over the utilityProcess message channel (index.ts wires the port),- * the web reads it at GET /api/desktop/update and posts check/install commands that are- * forwarded back to the shell. The window itself stays a plain browser — every+ * the web reads it at GET /api/desktop/update and posts check/download/install commands+ * that are forwarded back to the shell. The window itself stays a plain browser — every* capability flows through this HTTP surface, never a renderer IPC bridge.*/import { createHash, timingSafeEqual } from "node:crypto";-import type { DesktopUpdateStatus } from "../api/types.js";+import type { DesktopUpdateStatus, DesktopUpdaterCommandMessage } from "../api/types.js";++/** What the page may ask the shell's updater to do (the relayed command's `action`). */+export type UpdaterCommand = DesktopUpdaterCommandMessage["action"];function digest(value: string): Buffer {return createHash("sha256").update(value).digest();@@ -62,7 +65,7 @@ export class DesktopService {// --- client-update relay ---------------------------------------------------private updateStatus: DesktopUpdateStatus | null = null;- private updateCommandSender: ((action: "check" | "install") => void) | null = null;+ private updateCommandSender: ((action: UpdaterCommand) => void) | null = null;/** Latest shell snapshot; null until the shell's first push lands. */getUpdateStatus(): DesktopUpdateStatus | null {@@ -75,12 +78,12 @@ export class DesktopService {}/** index.ts registers the message-port sender; absent outside a shell-forked process. */- onUpdateCommand(sender: (action: "check" | "install") => void): void {+ onUpdateCommand(sender: (action: UpdaterCommand) => void): void {this.updateCommandSender = sender;}/** Invoked by the update routes; false when no shell port is wired (tests, plain runs). */- requestUpdateCommand(action: "check" | "install"): boolean {+ requestUpdateCommand(action: UpdaterCommand): boolean {if (!this.updateCommandSender) return false;this.updateCommandSender(action);return true;diff --git a/packages/server/src/services/desktop-update-port.ts b/packages/server/src/services/desktop-update-port.tsindex 71b8a920..797b42db 100644--- a/packages/server/src/services/desktop-update-port.ts+++ b/packages/server/src/services/desktop-update-port.ts@@ -3,8 +3,8 @@** Under the desktop shell this server runs as an Electron utilityProcess, which injects* `process.parentPort` — an EventEmitter-ish port to the shell. The shell pushes its- * updater snapshot through it, and the update routes forward the page's check/install- * commands back. Under a plain `penguin server|web` run the port does not exist and this+ * updater snapshot through it, and the update routes forward the page's+ * check/download/install commands back. Under a plain `penguin server|web` run the port does not exist and this* module wires nothing; the update routes then answer 503 `shell_unreachable`.** Wire shapes live in api/types.ts (DesktopUpdaterStatusMessage /@@ -27,6 +27,7 @@ const UPDATE_STATES: ReadonlySet<string> = new Set(["idle","checking","up-to-date",+ "available","downloading","downloaded","error",diff --git a/packages/server/src/services/lifecycle-service.ts b/packages/server/src/services/lifecycle-service.tsnew file mode 100644index 00000000..1cfc79d1--- /dev/null+++ b/packages/server/src/services/lifecycle-service.ts@@ -0,0 +1,37 @@+/**+ * Process lifecycle as a runtime capability: whether a supervisor relaunches this process+ * when it exits, and the restart trigger the platform's `POST /api/version/restart` pulls+ * once a self-update is installed.+ *+ * The supervisor is `penguin server|web`, which runs the service as a child process and+ * respawns it on SERVER_RESTART_EXIT_CODE (core); it announces itself with+ * PENGUIN_SUPERVISED=1. Under anything else — the server entry started directly, a dev+ * run, the desktop shell (which updates the whole app, not the server) — a restart request+ * is refused rather than honored: exiting would stop the service with nobody to bring it+ * back, and the page tells the user to restart by hand instead.+ *+ * Mechanism only: what a restart is *for* is the platform's business (the update flow);+ * this class knows how to leave, and who is there to catch it.+ */+export class LifecycleService {+ private restartHandler: (() => void) | null = null;++ constructor(private readonly supervisedFlag: boolean) {}++ /** Whether a supervisor relaunches this process on the restart exit code (PENGUIN_SUPERVISED=1). */+ supervised(): boolean {+ return this.supervisedFlag;+ }++ /** index.ts registers the graceful-shutdown-then-restart trigger after listen(). */+ onRestartRequest(handler: () => void): void {+ this.restartHandler = handler;+ }++ /** Invoked by the restart route; false when unsupervised, or when no handler is registered (tests). */+ requestRestart(): boolean {+ if (!this.supervisedFlag || !this.restartHandler) return false;+ this.restartHandler();+ return true;+ }+}diff --git a/packages/server/src/services/update-job.ts b/packages/server/src/services/update-job.tsnew file mode 100644index 00000000..d4ed478f--- /dev/null+++ b/packages/server/src/services/update-job.ts@@ -0,0 +1,240 @@+/**+ * The self-update job: runs the CLI as `node <entry> update --yes` in the background and+ * exposes its progress, so the Web App's update modal can show a bar and be sent to the+ * background instead of holding one long request open (POST /api/version/update used to+ * answer only when the run was over — up to ten minutes with nothing to show). One job per+ * process: a start while one runs joins it, and the finished status stays readable until+ * the next start (which is also how a failed run is retried).+ *+ * How the self-update works: `penguin server|web` exports PENGUIN_CLI_ENTRY (its own entry+ * script path) before importing this server, and the job re-runs that script as+ * `node <entry> update --yes` — the CLI's update command owns all install-kind detection,+ * download and replacement logic (packages/cli/src/commands/update.ts). A server started+ * any other way (tests, a custom embedding) has no CLI to run and reports "unsupported".+ * SECURITY: the spawned argv is a fixed literal list; nothing from any request flows into+ * the command, its arguments, or its environment.+ *+ * Progress is read off the run's combined output, best-effort: the tarball installer+ * prints `Downloading <asset> from <source> ...` right before its `curl --progress-bar`+ * run, whose bar carries the percentage, and `<layer> checksum OK.` once the bundle is+ * verified; everything before the first is the release lookup and the installer fetch. A+ * run that prints none of it (an npm install, say) stays in `resolving` with no+ * percentage — the phase is a hint for the bar, never a fact the outcome depends on.+ *+ * Interpreting the CLI's outcome: `penguin update` exits non-zero only when an upgrade was+ * attempted and failed; refusals (source checkout, unrecognized layout, Windows) print a+ * message and exit 0. Exit codes alone therefore cannot separate "updated" from+ * "unsupported", so the spawn forces PENGUIN_LANG=en and classifies by the refusal+ * messages' stable English fragments (packages/cli/src/i18n.ts, `update` section). That+ * matching is reliable here because the spawned CLI and this server ship in lockstep from+ * the same install — the strings can never be from a different release than this code.+ *+ * A platform hot-swap while a run is in flight builds a fresh service that knows nothing of+ * it; the child finishes on its own and only its status is lost. Rare enough to accept.+ */+import { spawn } from "node:child_process";+import type { UpdateJobPhase, UpdateJobStatus, UpdateRunResponse } from "../api/types.js";++/** Only the tail of the update output is kept (installer logs can be long). */+const OUTPUT_CAP = 64 * 1024;+/** The whole update (download + install) must finish within this window. */+const UPDATE_TIMEOUT_MS = 10 * 60 * 1000;++/**+ * English fragments of the CLI refusal messages (packages/cli/src/i18n.ts `update.*`),+ * one per refusal reason. `needsYes` / `cancelled` are omitted: `--yes` makes the+ * confirmation gate proceed unconditionally, so neither can occur here.+ */+const REFUSAL_MARKERS = [+ "runs from a source checkout", // sourceCheckout+ "Cannot tell how this penguin was installed", // unknownInstall+ "could not be identified", // npmUnknownManager+ "does not run on Windows", // windowsUnsupported+ "cannot run your package manager for you", // windowsGlobalInstall+];++/**+ * Maps the finished CLI run to an UpdateRunResponse. Exit 0 with a refusal message is+ * "unsupported"; any other exit 0 is "updated" — including the CLI's "already on the+ * latest version", because that means the *install* is current and only a restart of this+ * (older, in-memory) process is missing, which is exactly what needsRestart says.+ */+export function classifyUpdateRun(exitCode: number, output: string): UpdateRunResponse {+ if (exitCode !== 0) return { status: "failed", output, needsRestart: false };+ if (REFUSAL_MARKERS.some((marker) => output.includes(marker))) {+ return { status: "unsupported", output, needsRestart: false };+ }+ return { status: "updated", output, needsRestart: true };+}++/** The bar's position: which phase the run is in, and the download percentage while it downloads. */+export interface UpdateProgress {+ phase: UpdateJobPhase;+ percent: number | null;+}++export const INITIAL_PROGRESS: UpdateProgress = { phase: "resolving", percent: null };++/** The installer's line right before its curl run (install.sh: `Downloading $ASSET from $drp_label ...`). */+const DOWNLOAD_LINE = /\bDownloading \S+ from .+\.\.\./;+/** The installer's line after the bundle verified (install.sh verify_sha256: `<layer> checksum OK.`). */+const VERIFIED_LINE = /checksum OK\./;+/** curl's progress bar redraws end in the percentage; the last one in a chunk is the freshest. */+const PERCENT = /(\d{1,3}(?:\.\d+)?)%/g;++/**+ * Folds one output chunk into the progress. Pure, so the parsing is unit-tested without a+ * child process. A chunk may carry the download line and its first bar redraws together+ * (it is one pipe read), so the phase is settled before the percentage is read; the+ * verified line ends the download phase even when a bar redraw follows in the same chunk.+ */+export function advanceUpdateProgress(prev: UpdateProgress, chunk: string): UpdateProgress {+ let { phase, percent } = prev;+ if (phase === "resolving" && DOWNLOAD_LINE.test(chunk)) phase = "downloading";+ if (phase === "downloading") {+ if (VERIFIED_LINE.test(chunk)) return { phase: "installing", percent: null };+ let last: number | null = null;+ for (const m of chunk.matchAll(PERCENT)) {+ const value = Number(m[1]);+ if (Number.isFinite(value)) last = Math.min(100, Math.max(0, Math.round(value)));+ }+ if (last !== null) percent = last;+ }+ return { phase, percent };+}++/** One finished run, as the runner reports it. */+export interface UpdateRunExit {+ /** The process exit code; -1 when it died without one. */+ exitCode: number;+ /** The run overran UPDATE_TIMEOUT_MS and was killed. */+ timedOut: boolean;+ /** The command could not be started at all (spawn error); the message. */+ spawnError?: string;+}++/**+ * Runs `node <cliEntry> update --yes` to completion, handing every output chunk to+ * `onOutput` as it arrives. Tests substitute a scripted runner through BuildDepsOverrides.+ */+export type UpdateRunner = (+ cliEntry: string,+ onOutput: (chunk: string) => void,+) => Promise<UpdateRunExit>;++export const spawnUpdateRunner: UpdateRunner = (cliEntry, onOutput) =>+ new Promise((resolve) => {+ // PENGUIN_LANG=en pins the CLI's output language so classifyUpdateRun's markers match+ // regardless of the deployment's configured CLI language.+ const child = spawn(process.execPath, [cliEntry, "update", "--yes"], {+ env: { ...process.env, PENGUIN_LANG: "en" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ const forward = (chunk: Buffer) => onOutput(chunk.toString("utf8"));+ child.stdout.on("data", forward);+ child.stderr.on("data", forward);++ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ child.kill("SIGTERM");+ // A SIGTERM-ignoring child would otherwise leave the job running forever.+ setTimeout(() => child.kill("SIGKILL"), 10_000).unref();+ }, UPDATE_TIMEOUT_MS);+ timer.unref();++ child.on("error", (err) => {+ clearTimeout(timer);+ resolve({ exitCode: -1, timedOut: false, spawnError: err.message });+ });+ child.on("close", (code) => {+ clearTimeout(timer);+ resolve({ exitCode: code ?? -1, timedOut });+ });+ });++export class UpdateJobService {+ private current: UpdateJobStatus = { state: "idle", targetVersion: null, output: "" };+ private progress: UpdateProgress = INITIAL_PROGRESS;++ constructor(private readonly runner: UpdateRunner = spawnUpdateRunner) {}++ /** The job as it stands (idle / running with progress / done with its result). */+ status(): UpdateJobStatus {+ return this.current;+ }++ /**+ * Starts a run unless one is in flight (then it is simply joined). `cliEntry` null — no+ * CLI to run — ends at once as `unsupported`, the same answer the old blocking route+ * gave, so the page renders the reason rather than a run that never moves.+ */+ start(cliEntry: string | null, targetVersion: string | null): UpdateJobStatus {+ if (this.current.state === "running") return this.current;+ if (cliEntry === null) {+ this.current = {+ state: "done",+ targetVersion,+ output: "",+ result: {+ status: "unsupported",+ reason: "not_launched_via_cli",+ output: "",+ needsRestart: false,+ },+ startedAt: new Date().toISOString(),+ finishedAt: new Date().toISOString(),+ };+ return this.current;+ }+ this.progress = INITIAL_PROGRESS;+ this.current = {+ state: "running",+ targetVersion,+ phase: "resolving",+ percent: null,+ output: "",+ startedAt: new Date().toISOString(),+ };+ void this.runner(cliEntry, (chunk) => this.absorb(chunk)).then((exit) => this.finish(exit));+ return this.current;+ }++ private absorb(chunk: string): void {+ if (this.current.state !== "running") return;+ this.progress = advanceUpdateProgress(this.progress, chunk);+ this.current = {+ ...this.current,+ phase: this.progress.phase,+ percent: this.progress.phase === "downloading" ? this.progress.percent : null,+ output: (this.current.output + chunk).slice(-OUTPUT_CAP),+ };+ }++ private finish(exit: UpdateRunExit): void {+ const output = this.current.output;+ const result: UpdateRunResponse =+ exit.spawnError !== undefined+ ? {+ status: "failed",+ output: `${output}\n[failed to run the update command: ${exit.spawnError}]`.trim(),+ needsRestart: false,+ }+ : exit.timedOut+ ? {+ status: "failed",+ output:+ `${output}\n[the update run was killed after ${UPDATE_TIMEOUT_MS / 60_000} minutes]`.trim(),+ needsRestart: false,+ }+ : classifyUpdateRun(exit.exitCode, output.trim());+ this.current = {+ state: "done",+ targetVersion: this.current.targetVersion,+ output: result.output,+ result,+ ...(this.current.startedAt !== undefined ? { startedAt: this.current.startedAt } : {}),+ finishedAt: new Date().toISOString(),+ };+ }+}diff --git a/packages/server/test/desktop-update.test.ts b/packages/server/test/desktop-update.test.tsindex 4b4fd26f..1d23b48d 100644--- a/packages/server/test/desktop-update.test.ts+++ b/packages/server/test/desktop-update.test.ts@@ -74,7 +74,7 @@ describe("GET /api/desktop/update", () => {});});-describe("POST /api/desktop/update/{check,install}", () => {+describe("POST /api/desktop/update/{check,download,install}", () => {it("forwards to the registered shell sender and answers 202", async () => {const t = await createDesktopApp();try {@@ -88,13 +88,19 @@ describe("POST /api/desktop/update/{check,install}", () => {body: "{}",});expect(check.status).toBe(202);+ const download = await t.app.request("/api/desktop/update/download", {+ method: "POST",+ headers: { cookie, "content-type": "application/json" },+ body: "{}",+ });+ expect(download.status).toBe(202);const install = await t.app.request("/api/desktop/update/install", {method: "POST",headers: { cookie, "content-type": "application/json" },body: "{}",});expect(install.status).toBe(202);- expect(actions).toEqual(["check", "install"]);+ expect(actions).toEqual(["check", "download", "install"]);} finally {await t.cleanup();}@@ -110,7 +116,11 @@ describe("POST /api/desktop/update/{check,install}", () => {t.deps.desktop!.onUpdateCommand(() => {commanded += 1;});- for (const path of ["/api/desktop/update/check", "/api/desktop/update/install"]) {+ for (const path of [+ "/api/desktop/update/check",+ "/api/desktop/update/download",+ "/api/desktop/update/install",+ ]) {const viaPassword = await t.app.request(path, {method: "POST",headers: { cookie: admin.cookie, "content-type": "application/json" },@@ -126,7 +136,7 @@ describe("POST /api/desktop/update/{check,install}", () => {});expect(anonymous.status).toBe(401);}- // Nothing reached the shell on any of those four attempts.+ // Nothing reached the shell on any of those six attempts.expect(commanded).toBe(0);} finally {await t.cleanup();diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex 51116a4c..4bb2222e 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -57,6 +57,7 @@ export function testConfig(root: string): ServerConfig {desktopToken: null,portFile: null,trustProxy: false,+ supervised: false,};}diff --git a/packages/server/test/hmr-resources.test.ts b/packages/server/test/hmr-resources.test.tsindex cf94cd7a..34e94824 100644--- a/packages/server/test/hmr-resources.test.ts+++ b/packages/server/test/hmr-resources.test.ts@@ -24,6 +24,7 @@ import {PENGUIN_FAMILY,RUNTIME_INTERFACES,RUNTIME_INTERFACES_RESOURCE_ID,+ RUNTIME_LIFECYCLE_RESOURCE_ID,RUNTIME_CHANNELS_RESOURCE_ID,RUNTIME_CONFIG_RESOURCE_ID,RUNTIME_DB_RESOURCE_ID,@@ -319,6 +320,7 @@ describe("runtime capability handshake", () => {r.register(RUNTIME_CHANNELS_RESOURCE_ID, carrying("channels"));r.register(RUNTIME_PROXY_RESOURCE_ID, () => {});r.register(RUNTIME_HMR_RESOURCE_ID, carrying("hmr"));+ r.register(RUNTIME_LIFECYCLE_RESOURCE_ID, carrying("lifecycle"));}it("refuses when the runtime publishes no descriptor (a runtime older than the handshake)", () => {diff --git a/packages/server/test/update-job.test.ts b/packages/server/test/update-job.test.tsnew file mode 100644index 00000000..d9b5b186--- /dev/null+++ b/packages/server/test/update-job.test.ts@@ -0,0 +1,175 @@+/**+ * update-job.ts unit tests: the progress read off the CLI's output, and the job's lifecycle+ * over a scripted runner (nothing is ever spawned here).+ */+import { describe, expect, it } from "vitest";+import {+ INITIAL_PROGRESS,+ UpdateJobService,+ advanceUpdateProgress,+ classifyUpdateRun,+} from "../src/services/update-job.js";+import type { UpdateRunExit, UpdateRunner } from "../src/services/update-job.js";++describe("advanceUpdateProgress", () => {+ it("stays resolving, with no percentage, until the installer announces the download", () => {+ const p = advanceUpdateProgress(INITIAL_PROGRESS, "Upgrade 0.2.9 -> 0.3.0\nSelected GitHub.\n");+ expect(p).toEqual({ phase: "resolving", percent: null });+ // A stray percentage before the download line is not a download percentage.+ expect(advanceUpdateProgress(p, "speed 100% ok\n")).toEqual({+ phase: "resolving",+ percent: null,+ });+ });++ it("reads curl's progress bar once the download line has passed, keeping the freshest percentage", () => {+ const started = advanceUpdateProgress(+ INITIAL_PROGRESS,+ "Downloading penguin-harness-0.3.0-linux-x64.tar.gz from GitHub ...\n",+ );+ expect(started).toEqual({ phase: "downloading", percent: null });+ const chunk = "\r#### 12.3%\r######## 31.9%";+ expect(advanceUpdateProgress(started, chunk)).toEqual({ phase: "downloading", percent: 32 });+ // The download line and its first redraws may arrive in one read.+ expect(+ advanceUpdateProgress(+ INITIAL_PROGRESS,+ "Downloading x.tar.gz from OSS mirror ...\n\r## 7.0%",+ ),+ ).toEqual({ phase: "downloading", percent: 7 });+ });++ it("moves to installing when the bundle verifies, dropping the percentage", () => {+ const downloading = { phase: "downloading" as const, percent: 100 };+ expect(advanceUpdateProgress(downloading, "Bundle checksum OK.\n")).toEqual({+ phase: "installing",+ percent: null,+ });+ // Installing is terminal for the bar: later percentages (a second curl) are ignored.+ expect(advanceUpdateProgress({ phase: "installing", percent: null }, "\r### 50.0%")).toEqual({+ phase: "installing",+ percent: null,+ });+ });++ it("clamps and rounds what it reads", () => {+ const downloading = { phase: "downloading" as const, percent: null };+ expect(advanceUpdateProgress(downloading, "999%")).toEqual({+ phase: "downloading",+ percent: 100,+ });+ expect(advanceUpdateProgress(downloading, "0.4%")).toEqual({+ phase: "downloading",+ percent: 0,+ });+ });+});++/** A runner whose output and exit the test scripts; `finish` ends the run. */+function scriptedRunner(): {+ runner: UpdateRunner;+ emit: (chunk: string) => void;+ finish: (exit: UpdateRunExit) => Promise<void>;+ entries: string[];+} {+ let onOutput: ((chunk: string) => void) | null = null;+ let resolveExit: ((exit: UpdateRunExit) => void) | null = null;+ const entries: string[] = [];+ const runner: UpdateRunner = (cliEntry, out) => {+ entries.push(cliEntry);+ onOutput = out;+ return new Promise((resolve) => {+ resolveExit = resolve;+ });+ };+ return {+ runner,+ entries,+ emit: (chunk) => onOutput?.(chunk),+ finish: async (exit) => {+ resolveExit?.(exit);+ // Let the service's `.then` settle.+ await new Promise((r) => setTimeout(r, 0));+ },+ };+}++describe("UpdateJobService", () => {+ it("starts idle, runs the CLI entry with progress, and ends updated with needsRestart", async () => {+ const script = scriptedRunner();+ const job = new UpdateJobService(script.runner);+ expect(job.status()).toEqual({ state: "idle", targetVersion: null, output: "" });++ const started = job.start("/opt/penguin/cli.js", "0.3.0");+ expect(started).toMatchObject({+ state: "running",+ targetVersion: "0.3.0",+ phase: "resolving",+ percent: null,+ output: "",+ });+ expect(script.entries).toEqual(["/opt/penguin/cli.js"]);+ // A second start joins the run rather than spawning another installer over the same dir.+ expect(job.start("/opt/penguin/cli.js", "0.3.0")).toBe(job.status());+ expect(script.entries).toHaveLength(1);++ script.emit("Downloading penguin.tar.gz from GitHub ...\n\r#### 40.0%");+ expect(job.status()).toMatchObject({ phase: "downloading", percent: 40 });+ script.emit("\r######## 100.0%\nBundle checksum OK.\n");+ expect(job.status()).toMatchObject({ phase: "installing", percent: null });+ await script.finish({ exitCode: 0, timedOut: false });+ expect(job.status()).toMatchObject({+ state: "done",+ targetVersion: "0.3.0",+ result: { status: "updated", needsRestart: true },+ });+ expect(job.status().output).toContain("Bundle checksum OK.");+ });++ it("classifies a refusal, a failure, a timeout and a spawn error", async () => {+ const refused = scriptedRunner();+ const a = new UpdateJobService(refused.runner);+ a.start("/e", null);+ refused.emit("This penguin runs from a source checkout, so there is nothing to download.");+ await refused.finish({ exitCode: 0, timedOut: false });+ expect(a.status().result).toMatchObject({ status: "unsupported", needsRestart: false });++ const failed = scriptedRunner();+ const b = new UpdateJobService(failed.runner);+ b.start("/e", "0.3.0");+ await failed.finish({ exitCode: 1, timedOut: false });+ expect(b.status().result).toMatchObject({ status: "failed" });+ // A failed run can be started again: that is the retry.+ expect(b.start("/e", "0.3.0").state).toBe("running");++ const timedOut = scriptedRunner();+ const c = new UpdateJobService(timedOut.runner);+ c.start("/e", null);+ await timedOut.finish({ exitCode: -1, timedOut: true });+ expect(c.status().result?.status).toBe("failed");+ expect(c.status().output).toContain("killed after 10 minutes");++ const broken = scriptedRunner();+ const d = new UpdateJobService(broken.runner);+ d.start("/e", null);+ await broken.finish({ exitCode: -1, timedOut: false, spawnError: "ENOENT" });+ expect(d.status().result?.status).toBe("failed");+ expect(d.status().output).toContain("ENOENT");+ });++ it("ends at once as unsupported when there is no CLI to run", () => {+ const script = scriptedRunner();+ const job = new UpdateJobService(script.runner);+ expect(job.start(null, "0.3.0")).toMatchObject({+ state: "done",+ result: { status: "unsupported", reason: "not_launched_via_cli", needsRestart: false },+ });+ expect(script.entries).toEqual([]);+ });++ it("classifyUpdateRun keeps its three verdicts", () => {+ expect(classifyUpdateRun(1, "x").status).toBe("failed");+ expect(classifyUpdateRun(0, "does not run on Windows").status).toBe("unsupported");+ expect(classifyUpdateRun(0, "installed").needsRestart).toBe(true);+ });+});diff --git a/packages/server/test/version.test.ts b/packages/server/test/version.test.tsindex 5ee691c0..a8677ec5 100644--- a/packages/server/test/version.test.ts+++ b/packages/server/test/version.test.ts@@ -11,7 +11,13 @@ import fs from "node:fs/promises";import path from "node:path";import { VERSION } from "@prismshadow/penguin-core";import { versionReport } from "../src/version-report.js";-import type { UpdateCheckResponse, UpdateRunResponse, VersionResponse } from "../src/api/types.js";+import type {+ RestartResponse,+ UpdateCheckResponse,+ UpdateJobStatus,+ UpdateRunResponse,+ VersionResponse,+} from "../src/api/types.js";import {FAILURE_TTL_MS,SUCCESS_TTL_MS,@@ -298,16 +304,56 @@ describe("POST /api/version/update", () => {const admin = await loginAdmin(t.app);const res = await apiClient(t.app, admin.cookie).post("/api/version/update", {});expect(res.status).toBe(200);- const body = (await res.json()) as UpdateRunResponse;- expect(body).toEqual({+ const body = (await res.json()) as UpdateJobStatus;+ expect(body.state).toBe("done");+ expect(body.result).toEqual({status: "unsupported",reason: "not_launched_via_cli",output: "",needsRestart: false,+ } satisfies UpdateRunResponse);+ // The finished status stays readable at GET until the next start.+ const again = await apiClient(t.app, admin.cookie).get("/api/version/update");+ expect(((await again.json()) as UpdateJobStatus).result?.status).toBe("unsupported");+ });++ it("GET /api/version/update is admin-only and idle before any run", async () => {+ const user = await provisionUser(t.app, "regular_user");+ expect((await apiClient(t.app, user.cookie).get("/api/version/update")).status).toBe(403);+ const admin = await loginAdmin(t.app);+ const res = await apiClient(t.app, admin.cookie).get("/api/version/update");+ expect(res.status).toBe(200);+ expect((await res.json()) as UpdateJobStatus).toEqual({+ state: "idle",+ targetVersion: null,+ output: "",});});});+describe("POST /api/version/restart", () => {+ it("is admin-only, and refuses when nothing supervises the process", async () => {+ // Tests boot unsupervised (PENGUIN_SUPERVISED unset): exiting would stop a service nobody+ // brings back, so the route says so instead of leaving.+ const t = await createTestApp();+ try {+ const user = await provisionUser(t.app, "regular_user");+ expect((await apiClient(t.app, user.cookie).post("/api/version/restart", {})).status).toBe(+ 403,+ );+ const admin = await loginAdmin(t.app);+ const res = await apiClient(t.app, admin.cookie).post("/api/version/restart", {});+ expect(res.status).toBe(200);+ expect((await res.json()) as RestartResponse).toEqual({+ restarting: false,+ reason: "no_supervisor",+ });+ } finally {+ await t.cleanup();+ }+ });+});+describe("classifyUpdateRun", () => {it("a non-zero exit is a failed upgrade attempt", () => {const r = classifyUpdateRun(1, "Upgrade failed; the previous install was left in place.");diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex d6c027ac..437f3751 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -125,7 +125,8 @@ import type {TraceImportResponse,UiPrefs,UpdateCheckResponse,- UpdateRunResponse,+ UpdateJobStatus,+ RestartResponse,DesktopUpdateStatusResponse,UsageErrorKind,UsageErrorsClearResponse,@@ -1167,9 +1168,16 @@ export const getVersion = () => apiFetch<VersionResponse>("/api/version");export const checkUpdate = (force = false) =>apiFetch<UpdateCheckResponse>(`/api/version/update-check${force ? "?force=1" : ""}`);-/** Admin only: runs `penguin update` on the server host (long request — up to 10 minutes). */-export const runUpdate = () =>- apiFetch<UpdateRunResponse>("/api/version/update", { method: "POST", body: {} });+/** Admin only: the self-update job's status — polled while it runs. */+export const getUpdateJob = () => apiFetch<UpdateJobStatus>("/api/version/update");++/** Admin only: starts the self-update job (`penguin update` on the server host, in the background) and answers with its status. */+export const startUpdateJob = () =>+ apiFetch<UpdateJobStatus>("/api/version/update", { method: "POST", body: {} });++/** Admin only: asks the supervised server process to restart into the installed release. */+export const restartServer = () =>+ apiFetch<RestartResponse>("/api/version/restart", { method: "POST", body: {} });// Desktop client update (desktop-shell sessions only) ----------------------------------@@ -1178,5 +1186,8 @@ export const getDesktopUpdate = () => apiFetch<DesktopUpdateStatusResponse>("/apexport const desktopUpdateCheck = () =>apiFetch<void>("/api/desktop/update/check", { method: "POST", body: {} });+export const desktopUpdateDownload = () =>+ apiFetch<void>("/api/desktop/update/download", { method: "POST", body: {} });+export const desktopUpdateInstall = () =>apiFetch<void>("/api/desktop/update/install", { method: "POST", body: {} });diff --git a/packages/web/src/components/account/desktop-update-row.tsx b/packages/web/src/components/account/desktop-update-row.tsxdeleted file mode 100644index 85079737..00000000--- a/packages/web/src/components/account/desktop-update-row.tsx+++ /dev/null@@ -1,93 +0,0 @@-/**- * Client-update row in the sidebar user menu — the desktop-mode counterpart of- * ServerUpdateRow, taking the same slot under the System settings entry (the server row- * stays hidden there: the CLI self-update has nothing to run under the shell). Rendered- * only in the shell's own window (see offersClientUpdate).- *- * Deliberately thin: the snapshot, the polling and the armed-check watch live in- * use-desktop-update.ts at module level, because this row unmounts whenever the menu- * closes — a check clicked here must still settle (and toast) afterwards. Install is- * not sent from here either: the click hands off to the Sidebar's confirm dialog- * (restarting interrupts running tasks, the same consent the shell's native prompt- * collects), which posts on confirmation.- */-import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";-import { S } from "../../lib/strings";-import { clientUpdateRow } from "../../lib/desktop-update";-import { requestClientCheck } from "../../lib/use-desktop-update";--export function DesktopUpdateRow({- status,- checkPending,- menuItemClass,- onInstallRequest,-}: {- /** Latest shell snapshot (null until its first push). */- status: DesktopUpdateStatus | null;- /** A row-initiated check is armed but the shell's `checking` frame hasn't landed yet. */- checkPending: boolean;- /** The menu's shared row class (owned by sidebar.tsx). */- menuItemClass: string;- /** Install click: the Sidebar closes the menu and opens the confirm dialog. */- onInstallRequest: () => void;-}) {- const row = clientUpdateRow(status, checkPending);- const disabled = row.action === "none";-- const label =- row.labelKind === "checking"- ? S.update.checking- : row.labelKind === "downloading"- ? S.update.clientDownloading(row.version, row.percent)- : row.labelKind === "install"- ? S.update.clientRestartToInstall(row.version)- : S.update.clientCheckNow;-- const reason =- row.labelKind === "unsupported"- ? row.unsupportedReason === "linux-not-appimage"- ? S.update.clientUnsupportedNonAppImage- : S.update.clientUnsupportedDev- : null;-- const button = (- <button- type="button"- disabled={disabled}- onClick={() => {- if (row.action === "install") onInstallRequest();- else if (row.action === "check") void requestClientCheck();- }}- className={`${menuItemClass} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`}- >- <span className="flex min-w-0 items-center gap-2">- {row.busy && (- <span- aria-hidden- className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"- />- )}- {!row.busy && row.labelKind === "install" && (- <span aria-hidden className="h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]" />- )}- <span className="min-w-0 truncate">{label}</span>- </span>- {row.appVersion !== null && (- <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">- {`v${row.appVersion}`}- </span>- )}- </button>- );-- // The unsupported reason has to hang off a wrapper: Chromium dispatches no pointer- // events to a disabled control, so a `title` written on the button itself never opens- // a tooltip — and the reason is the only thing that explains why the row is greyed out.- return reason !== null ? (- <span className="block" title={reason}>- {button}- </span>- ) : (- button- );-}diff --git a/packages/web/src/components/account/server-update-row.tsx b/packages/web/src/components/account/server-update-row.tsxdeleted file mode 100644index 43a05ba2..00000000--- a/packages/web/src/components/account/server-update-row.tsx+++ /dev/null@@ -1,67 +0,0 @@-/**- * Server-update row in the sidebar user menu — the web counterpart of DesktopUpdateRow,- * sitting in the same slot under the System settings entry so the update affordance is- * reachable without opening a dialog. Hidden in desktop mode, where updating is the- * shell's job and the client row takes this slot instead.- *- * One row, two states: it reads "check for updates" and runs the manual check until a- * newer release is known, then names that release and opens UpdateDialog (which carries- * the release-notes link and the admin-only self-update). Deliberately thin — the check- * state and the dialog live in the Sidebar, which stays mounted while this row unmounts- * with the menu, so a check clicked here still settles and still toasts.- */-import { S } from "../../lib/strings";--export function ServerUpdateRow({- version,- newVersion,- checking,- menuItemClass,- onCheck,- onOpenDialog,-}: {- /** Running server version for the right-aligned chip; null until the lazy fetch lands. */- version: string | null;- /** The newer release this row names, or null while none is known. */- newVersion: string | null;- /** A manual check is in flight (owned by the Sidebar, so it survives the menu closing). */- checking: boolean;- /** The menu's shared row class (owned by sidebar.tsx). */- menuItemClass: string;- /** Check click: forces a lookup past the server's TTL cache and toasts the outcome. */- onCheck: () => void;- /** Update click: the Sidebar closes the menu and opens UpdateDialog. */- onOpenDialog: () => void;-}) {- const offersUpdate = newVersion !== null;- const label = checking- ? S.update.checking- : offersUpdate- ? S.update.newVersion(newVersion)- : S.update.checkNow;-- return (- <button- type="button"- disabled={checking}- onClick={offersUpdate ? onOpenDialog : onCheck}- className={`${menuItemClass} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`}- >- <span className="flex min-w-0 items-center gap-2">- {checking && (- <span- aria-hidden- className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"- />- )}- {!checking && offersUpdate && (- <span aria-hidden className="h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]" />- )}- <span className="min-w-0 truncate">{label}</span>- </span>- {version !== null && (- <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">{`v${version}`}</span>- )}- </button>- );-}diff --git a/packages/web/src/components/account/update-dialog.tsx b/packages/web/src/components/account/update-dialog.tsxdeleted file mode 100644index 21873379..00000000--- a/packages/web/src/components/account/update-dialog.tsx+++ /dev/null@@ -1,155 +0,0 @@-/**- * Update dialog, opened from the user menu's single update row once a newer release is known.- * It is the only place the update story is told, so it carries everything the menu used to- * spread across three rows: the new version, the release-notes link, and — for admins only —- * the self-update action. It explains that the release is downloaded into the install- * directory and that the service must be restarted afterwards, then runs- * POST /api/version/update and shows the outcome: the CLI's own output tail in a scrollable- * <pre> for the failed/unsupported states, a restart hint on success. Non-admins get the same- * information plus the link, with no action to run (the endpoint is admin-only anyway).- * Closing is blocked while the update runs (the request can take minutes; navigating away- * would just hide the result).- */-import { useEffect, useState } from "react";-import type { UpdateRunResponse } from "@prismshadow/penguin-server/api";-import * as api from "../../api/endpoints";-import { S } from "../../lib/strings";-import { apiErrorText } from "../../lib/api-error";-import { stripAnsi } from "../../lib/strip-ansi";-import { Button } from "../ui/button";-import { Modal } from "../ui/modal";-import { toneInk } from "../../lib/tone";--type Phase = "confirm" | "running" | "done";--export function UpdateDialog({- open,- onClose,- latestVersion,- releaseUrl = null,- canUpdate,- onRunFinished,-}: {- open: boolean;- onClose: () => void;- latestVersion: string | null;- /** Release page of the new version; omitted/null when the check couldn't resolve one. */- releaseUrl?: string | null;- /** Admin: the self-update action is offered. Otherwise the dialog is read-only. */- canUpdate: boolean;- /**- * Fired once a self-update run has finished (whatever its outcome), when the dialog closes.- * The menu's single update row is the ONLY caller of the update check, and it stops offering- * that check once a newer release is known — so without this the reminder would survive its- * own update: the shared version-info cache never expires within a browser session, leaving- * the row stuck on "New version vX available" with no way back short of a page reload.- */- onRunFinished?: () => void;-}) {- const [phase, setPhase] = useState<Phase>("confirm");- const [result, setResult] = useState<UpdateRunResponse | null>(null);-- useEffect(() => {- if (!open) return;- setPhase("confirm");- setResult(null);- }, [open]);-- /** Closing: a finished run invalidates what the reminder row believes, so re-check on the way out. */- const close = () => {- if (phase === "done") onRunFinished?.();- onClose();- };-- const run = async () => {- setPhase("running");- try {- setResult(await api.runUpdate());- } catch (e) {- // The request itself failed (e.g. the connection dropped mid-run): surface it the- // same way as a failed run, with the error text where the output tail would be.- setResult({ status: "failed", output: apiErrorText(e), needsRestart: false });- }- setPhase("done");- };-- const statusLine =- result === null- ? null- : result.status === "updated"- ? { text: S.update.updated, className: toneInk.success }- : result.status === "unsupported"- ? { text: S.update.unsupported, className: toneInk.attention }- : { text: S.update.failed, className: toneInk.danger };-- return (- <Modal- open={open}- /* The title follows the audience: only an admin is here to run an update, and to- everyone else this dialog is the release announcement, so titling it "Update now"- would promise an action its own body then says they cannot take. */- title={- canUpdate- ? S.update.updateNow- : latestVersion !== null- ? S.update.newVersion(latestVersion)- : S.update.releaseNotes- }- onClose={phase === "running" ? () => undefined : close}- footer={- phase === "done" || !canUpdate ? (- <Button onClick={close}>{S.common.close}</Button>- ) : (- <>- <Button onClick={close} disabled={phase === "running"}>- {S.common.cancel}- </Button>- <Button variant="primary" disabled={phase === "running"} onClick={() => void run()}>- {phase === "running" ? S.update.updating : S.update.updateNow}- </Button>- </>- )- }- >- {phase === "done" && result !== null && statusLine !== null ? (- <div className="space-y-3">- <p className={`text-sm font-medium ${statusLine.className}`}>{statusLine.text}</p>- {result.status === "updated" && (- <p className="text-sm text-gray-600 dark:text-gray-400">{S.update.restartHint}</p>- )}- {result.output !== "" && (- <pre className="max-h-56 overflow-auto rounded-md bg-gray-100 p-3 text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:bg-gray-800 dark:text-gray-300">- {/* The update runs a package manager whose output may carry ANSI color when the server env forces it. */}- {stripAnsi(result.output)}- </pre>- )}- </div>- ) : (- <div className="space-y-2">- {latestVersion !== null && (- <p className="text-sm font-medium">{S.update.newVersion(latestVersion)}</p>- )}- {/* Release notes: the menu no longer carries this link, so it lives here. */}- {releaseUrl !== null && (- <p>- <a- href={releaseUrl}- target="_blank"- rel="noopener noreferrer"- className="text-sm text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"- >- {S.update.releaseNotes}- </a>- </p>- )}- <p className="text-sm text-gray-600 dark:text-gray-400">- {canUpdate ? S.update.confirmBody : S.update.adminOnly}- </p>- {phase === "running" && (- <p className="text-sm text-gray-500 dark:text-gray-400">{S.update.updating}</p>- )}- </div>- )}- </Modal>- );-}diff --git a/packages/web/src/components/account/update-modal.tsx b/packages/web/src/components/account/update-modal.tsxnew file mode 100644index 00000000..d41924d3--- /dev/null+++ b/packages/web/src/components/account/update-modal.tsx@@ -0,0 +1,284 @@+/**+ * The update modal: the one place the software update is explained and acted on, for+ * both backends (the server release, and the desktop shell's own updater in its window).+ * Opened from the account-menu row and the version line's badge; mounted once by the app+ * layout so it outlives the menu and the page the badge sits on.+ *+ * It walks the flow the way an app updater does: a check, a release offered with its+ * notes and a confirmation before anything is fetched, a progress bar while it downloads+ * (with "background" — closing never cancels; the row keeps reporting and the outcome+ * toasts), then "restart and update" once the release is ready. Failures show the+ * backend's own text — the update command's output tail, the shell's updater message —+ * and offer a retry; an install form that cannot update itself says why.+ *+ * The flow and the actions live in `use-update-flow.ts`; this file only renders.+ */+import type { ReactNode } from "react";+import { S } from "../../lib/strings";+import { stripAnsi } from "../../lib/strip-ansi";+import { toneInk } from "../../lib/tone";+import type { UpdateFlow, UpdateMode } from "../../lib/update-flow";+import {+ checkForUpdates,+ closeUpdateModal,+ downloadUpdate,+ installUpdate,+ useUpdateFlow,+ useUpdateFlowOwner,+} from "../../lib/use-update-flow";+import { Button } from "../ui/button";+import { Modal } from "../ui/modal";++const RELEASES_URL = "https://github.com/Prism-Shadow/penguin-harness/releases";++export function UpdateModal() {+ useUpdateFlowOwner();+ const { mode, flow, modalOpen, currentVersion } = useUpdateFlow();+ if (mode === "none") return null;+ return (+ <Modal+ open={modalOpen}+ title={S.update.title}+ onClose={closeUpdateModal}+ footer={<Footer mode={mode} flow={flow} />}+ >+ <div className="space-y-3">+ {currentVersion !== null && (+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.update.currentVersion(currentVersion)}+ </p>+ )}+ <Body mode={mode} flow={flow} />+ </div>+ </Modal>+ );+}++function Body({ mode, flow }: { mode: UpdateMode; flow: UpdateFlow }): ReactNode {+ switch (flow.kind) {+ case "unknown":+ case "checking":+ return <Line spinner>{S.update.checkingBody}</Line>;+ case "disabled":+ return (+ <>+ <p className="text-sm">{S.update.checkDisabled}</p>+ <ReleasesLink href={RELEASES_URL}>{S.update.openReleases}</ReleasesLink>+ </>+ );+ case "up-to-date":+ return <p className={`text-sm font-medium ${toneInk.success}`}>{S.update.upToDate}</p>;+ case "available":+ return (+ <>+ <p className="text-sm font-medium">{S.update.newVersion(flow.version)}</p>+ {flow.releaseUrl !== null && (+ <ReleasesLink href={flow.releaseUrl}>{S.update.releaseNotes}</ReleasesLink>+ )}+ <p className="text-sm text-gray-600 dark:text-gray-400">+ {!flow.canInstall+ ? S.update.adminOnly+ : mode === "client"+ ? S.update.availableBodyClient+ : S.update.availableBodyRelease}+ </p>+ </>+ );+ case "downloading":+ return (+ <>+ <p className="text-sm font-medium">{S.update.downloading(flow.version)}</p>+ <ProgressBar percent={flow.percent} />+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {flow.percent !== null+ ? `${flow.percent}%`+ : flow.phase === "installing"+ ? S.update.phaseInstalling+ : flow.phase === "downloading"+ ? S.update.phaseDownloading+ : S.update.phaseResolving}+ </p>+ </>+ );+ case "ready":+ return (+ <>+ <p className={`text-sm font-medium ${toneInk.success}`}>{S.update.ready(flow.version)}</p>+ <p className="text-sm text-gray-600 dark:text-gray-400">+ {flow.restart === "manual"+ ? S.update.readyBodyManual+ : mode === "client"+ ? S.update.readyBodyClient+ : S.update.readyBodyRelease}+ </p>+ </>+ );+ case "restarting":+ return (+ <Line spinner>+ {S.update.restarting}{" "}+ <span className="text-gray-500 dark:text-gray-400">+ {mode === "client" ? S.update.restartingBodyClient : S.update.restartingBodyRelease}+ </span>+ </Line>+ );+ case "error":+ return (+ <>+ <p className={`text-sm font-medium ${toneInk.danger}`}>+ {flow.retry === "check" ? S.update.checkFailed : S.update.failed}+ </p>+ {flow.message !== null && <p className="text-sm">{flow.message}</p>}+ {flow.detail !== null && <OutputTail text={flow.detail} />}+ </>+ );+ case "unsupported":+ return (+ <>+ <p className={`text-sm font-medium ${toneInk.attention}`}>+ {flow.reason.code === "dev"+ ? S.update.unsupportedDev+ : flow.reason.code === "linux-not-appimage"+ ? S.update.unsupportedNonAppImage+ : flow.reason.code === "not_launched_via_cli"+ ? S.update.unsupportedNotViaCli+ : S.update.unsupportedCli}+ </p>+ {flow.reason.code === "cli_refused" && flow.reason.detail !== "" && (+ <OutputTail text={flow.reason.detail} />+ )}+ <ReleasesLink href={RELEASES_URL}>{S.update.openReleases}</ReleasesLink>+ </>+ );+ }+}++function Footer({ mode, flow }: { mode: UpdateMode; flow: UpdateFlow }): ReactNode {+ const close = <Button onClick={closeUpdateModal}>{S.common.close}</Button>;+ switch (flow.kind) {+ case "unknown":+ case "checking":+ return close;+ case "up-to-date":+ return (+ <>+ {close}+ <Button variant="primary" onClick={() => void checkForUpdates()}>+ {S.update.checkNow}+ </Button>+ </>+ );+ case "available":+ if (!flow.canInstall) return close;+ return (+ <>+ <Button onClick={closeUpdateModal}>{S.update.later}</Button>+ <Button variant="primary" onClick={() => void downloadUpdate()}>+ {S.update.downloadAndInstall}+ </Button>+ </>+ );+ case "downloading":+ return <Button onClick={closeUpdateModal}>{S.update.background}</Button>;+ case "ready":+ if (flow.restart === "manual") return close;+ return (+ <>+ <Button onClick={closeUpdateModal}>{S.update.later}</Button>+ <Button variant="primary" onClick={() => void installUpdate()}>+ {S.update.restartNow}+ </Button>+ </>+ );+ case "restarting":+ return null;+ case "error":+ return (+ <>+ {close}+ <Button+ variant="primary"+ onClick={() => void (flow.retry === "check" ? checkForUpdates() : downloadUpdate())}+ >+ {S.update.retry}+ </Button>+ </>+ );+ case "unsupported":+ return mode === "client" ? (+ close+ ) : (+ // A server refusal is a fact about the install; the check can still run again.+ <>+ {close}+ <Button variant="primary" onClick={() => void checkForUpdates()}>+ {S.update.checkNow}+ </Button>+ </>+ );+ }+}++function Line({ spinner, children }: { spinner?: boolean; children: ReactNode }) {+ return (+ <p className="flex items-center gap-2 text-sm">+ {spinner && (+ <span+ aria-hidden+ className="inline-block h-3.5 w-3.5 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"+ />+ )}+ <span>{children}</span>+ </p>+ );+}++function ReleasesLink({ href, children }: { href: string; children: ReactNode }) {+ return (+ <p>+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"+ >+ {children}+ </a>+ </p>+ );+}++/**+ * The download bar: determinate with a percentage (the shell's updater, the installer's+ * curl bar), indeterminate — a pulsing segment — while the backend reports a phase without+ * one (resolving the release, verifying and installing). Width transitions only, so the+ * global reduced-motion rule leaves a correct resting state.+ */+function ProgressBar({ percent }: { percent: number | null }) {+ return (+ <div+ role="progressbar"+ aria-label={S.update.downloadProgress}+ aria-valuemin={0}+ aria-valuemax={100}+ {...(percent !== null ? { "aria-valuenow": percent } : {})}+ className="h-2 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-800"+ >+ <div+ className={`h-full rounded-full bg-[var(--accent-bg)] ${+ percent === null ? "w-1/3 animate-pulse" : "transition-[width] duration-300"+ }`}+ style={percent === null ? undefined : { width: `${percent}%` }}+ />+ </div>+ );+}++/** The update command's output tail (may carry ANSI colour when the server env forces it). */+function OutputTail({ text }: { text: string }) {+ return (+ <pre className="max-h-56 overflow-auto rounded-md bg-gray-100 p-3 text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:bg-gray-800 dark:text-gray-300">+ {stripAnsi(text)}+ </pre>+ );+}diff --git a/packages/web/src/components/account/update-row.tsx b/packages/web/src/components/account/update-row.tsxnew file mode 100644index 00000000..2de878d8--- /dev/null+++ b/packages/web/src/components/account/update-row.tsx@@ -0,0 +1,70 @@+/**+ * The account-menu update row — one row for both backends, reading the update flow. It+ * names where the flow stands (check / checking / a release offered / downloading with its+ * percentage / restart to update / restarting / cannot update), and every state opens the+ * update modal, which is where the flow is explained and acted on. The running version+ * sits muted on the right. Renders nothing where this session can update nothing.+ */+import { S } from "../../lib/strings";+import { updateRowModel } from "../../lib/update-flow";+import type { UpdateFlow } from "../../lib/update-flow";+import { useUpdateFlow } from "../../lib/use-update-flow";++export function UpdateRow({+ menuItemClass,+ onOpen,+}: {+ /** The menu's shared row class (owned by sidebar.tsx). */+ menuItemClass: string;+ /** Click: the Sidebar closes the menu and opens the update modal. */+ onOpen: () => void;+}) {+ const { mode, flow, currentVersion } = useUpdateFlow();+ if (mode === "none") return null;+ const row = updateRowModel(flow);+ return (+ <button+ type="button"+ onClick={onOpen}+ className={`${menuItemClass} flex items-center justify-between gap-2`}+ >+ <span className="flex min-w-0 items-center gap-2">+ {row.busy && (+ <span+ aria-hidden+ className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"+ />+ )}+ {row.dot && (+ <span aria-hidden className="h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]" />+ )}+ <span className="min-w-0 truncate">{rowLabel(flow)}</span>+ </span>+ {currentVersion !== null && (+ <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">+ {`v${currentVersion}`}+ </span>+ )}+ </button>+ );+}++/** The row's wording for one flow — read at render time (`S` is a live binding). */+export function rowLabel(flow: UpdateFlow): string {+ switch (flow.kind) {+ case "checking":+ return S.update.checking;+ case "available":+ return S.update.newVersion(flow.version);+ case "downloading":+ return S.update.rowDownloading(flow.version, flow.percent);+ case "ready":+ return S.update.restartToUpdate(flow.version);+ case "restarting":+ return S.update.rowRestarting;+ case "unsupported":+ return S.update.rowUnsupported;+ default:+ return S.update.checkNow;+ }+}diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex c9ca6db8..dd8f4be4 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -22,6 +22,7 @@ import { NEW_CHAT_ICON, Sidebar } from "./sidebar";import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";import { parkActiveDraft } from "../../features/chat/draft-sessions";import { ChangePasswordDialog } from "../account/change-password-dialog";+import { UpdateModal } from "../account/update-modal";import { TerminalDockRuntime } from "../../features/terminal/terminal-view-pool";import { setDockScope } from "../../features/dock/dock-state";import { toneStrip } from "../../lib/tone";@@ -326,6 +327,9 @@ export function AppLayout() {<TerminalDockRuntime /></div>+ {/* The software-update modal, opened from the sidebar's update row and the draft+ page's version badge alike; mounted here so it outlives both. */}+ <UpdateModal /><ChangePasswordDialogopen={changePasswordOpen}onClose={() => setChangePasswordOpen(false)}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 9b053e45..115fa237 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -159,14 +159,9 @@ import {} from "../../features/chat/draft-sessions";import type { DraftSessionEntry } from "../../features/chat/draft-sessions";import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";-import { DesktopUpdateRow } from "../account/desktop-update-row";-import { ServerUpdateRow } from "../account/server-update-row";-import { UpdateDialog } from "../account/update-dialog";-import { offersClientUpdate } from "../../lib/desktop-update";-import { requestClientInstall, useDesktopUpdate } from "../../lib/use-desktop-update";-import { forceUpdateCheck, updateCheckOutcome, useVersionInfo } from "../../lib/use-version-info";+import { UpdateRow } from "../account/update-row";+import { openUpdateModal } from "../../lib/use-update-flow";import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";-import { releaseUpdate } from "../../lib/update-badges";import { SettingsDialog } from "../../features/settings/settings-dialog";import { ICON_SIZE } from "../../lib/icon-scale";@@ -350,38 +345,8 @@ export function Sidebar({const [createProjectOpen, setCreateProjectOpen] = useState(false);const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);const [settingsOpen, setSettingsOpen] = useState(false);- // Client update (desktop shell window only): the snapshot and the armed-check flag live- // at module level in use-desktop-update.ts; this always-mounted hook instance drives the- // polling, so a check armed in the menu still settles after the menu closes.- const clientUpdateOffered = offersClientUpdate({ desktopMode, sessionVia });- const clientUpdate = useDesktopUpdate(clientUpdateOffered, userOpen);- /** Install confirmation (restarting interrupts running tasks — same consent as the shell's native prompt). */- const [clientInstallOpen, setClientInstallOpen] = useState(false);- // Server update: the app layout already ran the one check per session; keeping the dropdown- // as an activation only costs a retry after a failed one.- const { version, update } = useVersionInfo(userOpen);- /**- * The two update badges (use-update-badges.ts). Not the same gate as `newVersion` below,- * which drives the ROW: a badge only appears where the trail ends in a control this mode- * actually offers, so in the shell's own window the avatar marks the client build waiting- * to install rather than a server release the menu never shows here.- */+ /** The badges over the update and to-do trails (use-update-badges.ts); the avatar's dot follows the update flow's offer / restart states. */const badges = useUpdateBadges();- /**- * The newer release's version string, or null while none is known — the single update row's- * whole state machine. A resolved version is required, not just the boolean: the row's label- * names it, so a would-be "available but unnamed" result stays on the check action rather- * than rendering a versionless reminder.- */- const newVersion = releaseUpdate(update);- /** Release announcement + admin self-update, opened from the update row once a release is known. */- const [updateDialogOpen, setUpdateDialogOpen] = useState(false);- /**- * A manual server-update check is in flight. Held here rather than in the row, which- * unmounts with the menu: a check clicked and then dismissed must still settle, and the- * spinner must still be there when the menu is reopened mid-flight.- */- const [updateChecking, setUpdateChecking] = useState(false);const currentProjectId = currentProject?.projectId ?? null;/** This Project's read markers; re-renders the rows whenever one is stamped. */const sessionSeen = useSessionSeen(currentProjectId);@@ -932,29 +897,6 @@ export function Sidebar({loadMoreFor,]);- /**- * Manual server-update check, from the menu's update row: forces a lookup past the- * server's TTL cache and pushes the result into the shared version-info store, so the- * row turns into the update entry and the avatar's reminder dot appears at once. Every- * outcome toasts — the check is fail-soft (a failed lookup arrives as the `error` field,- * not an exception; the catch handles our own server being unreachable).- */- const runUpdateCheck = async () => {- if (updateChecking) return;- setUpdateChecking(true);- try {- const outcome = updateCheckOutcome(await forceUpdateCheck());- if (outcome.kind === "disabled") toastInfo(S.update.checkDisabled);- else if (outcome.kind === "failed") toastError(S.update.checkFailed);- else if (outcome.kind === "found") toastSuccess(S.update.foundNew(outcome.latestVersion));- else toastSuccess(S.update.upToDate);- } catch (e) {- toastError(apiErrorText(e));- } finally {- setUpdateChecking(false);- }- };-/** Archive / unarchive: persists immediately and updates in place (fails silently; the next list refresh self-corrects). */const toggleArchive = async (s: SessionInfo) => {// Archiving the currently open chat: expand the "archived" folder so it doesn't silently vanish from the sidebar with no way back.@@ -2208,41 +2150,20 @@ export function Sidebar({>{S.settings.systemSettings}</button>- {/* Update row, directly under the settings entry rather than on a page inside- it: the check is one click from the menu, and the same row turns into the- update entry once the lazy check (menu open) names a newer release. Desktop- mode never checks here — updating is the shell's job. */}- {!desktopMode && (- <ServerUpdateRow- version={version?.version ?? null}- newVersion={newVersion}- checking={updateChecking}- menuItemClass={menuItemClass}- onCheck={() => void runUpdateCheck()}- onOpenDialog={() => {- setUserOpen(false);- setUpdateDialogOpen(true);- }}- />- )}- {/* Desktop stand-in for the row above, in the shell's own window only:- the same slot updates the CLIENT through the shell's own updater (relayed- via /api/desktop/update) — which is what "updating is the shell's job"- means for someone sitting in front of the app. A browser signed into the- same desktop-mode server gets neither row: it can't run the CLI self-update- there, nor restart someone else's GUI app (offersClientUpdate mirrors the- gate the routes enforce). */}- {clientUpdateOffered && (- <DesktopUpdateRow- status={clientUpdate.status}- checkPending={clientUpdate.checkPending}- menuItemClass={menuItemClass}- onInstallRequest={() => {- setUserOpen(false);- setClientInstallOpen(true);- }}- />- )}+ {/* Update entry, directly under the settings entry rather than on a page inside+ it: one row for both backends (the server release here, the shell's own+ updater in the desktop window), naming where the update flow stands and+ opening the update modal — where the flow is explained and acted on. The+ modal is mounted by the app layout, so it outlives this menu. Hidden where+ this session can update nothing (a browser signed into a desktop-mode+ server, see updateModeFor). */}+ <UpdateRow+ menuItemClass={menuItemClass}+ onOpen={() => {+ setUserOpen(false);+ openUpdateModal();+ }}+ />{/* Hidden in desktop mode: the window IS the session — logging out wouldstrand the user on a login page whose password was never shown. */}{!desktopMode && (@@ -2263,39 +2184,6 @@ export function Sidebar({<SettingsDialog open={settingsOpen} onClose={() => setSettingsOpen(false)} />- {/* Release announcement, release-notes link and the admin-only self-update. Mounted- here rather than in the row, which unmounts as the menu closes on the click that- opens this. */}- <UpdateDialog- open={updateDialogOpen}- onClose={() => setUpdateDialogOpen(false)}- latestVersion={newVersion}- releaseUrl={update?.releaseUrl ?? null}- canUpdate={user?.isAdmin === true}- /* A finished self-update makes the known release stale — re-check silently so the- row stops offering the version that is now running. */- onRunFinished={() => void forceUpdateCheck().catch(() => undefined)}- />-- {/* Client-update install consent: restarting interrupts running tasks, the same- warning the shell's native prompt carries — the web row must not be the one- path that kills work without asking. */}- <ConfirmModal- open={clientInstallOpen}- title={S.update.clientInstallConfirmTitle}- onClose={() => setClientInstallOpen(false)}- onConfirm={() => {- setClientInstallOpen(false);- void requestClientInstall();- }}- confirmLabel={S.update.clientInstallConfirmAction}- tone="primary"- >- <p className="text-sm text-gray-600 dark:text-gray-300">- {S.update.clientInstallConfirmBody}- </p>- </ConfirmModal>-<CreateProjectDialogopen={createProjectOpen}onClose={() => setCreateProjectOpen(false)}diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 5951c736..c71d0b5d 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -61,6 +61,8 @@ import { Dropdown } from "../../components/ui/dropdown";import { PenguinLogo } from "../../components/ui/penguin-logo";import { toastError } from "../../components/ui/toast";import { useVersionInfo } from "../../lib/use-version-info";+import { versionBadgeFor } from "../../lib/update-flow";+import { openUpdateModal, useUpdateFlow } from "../../lib/use-update-flow";import { ChatInput } from "./chat-input";import type { ComposerControl } from "./chat-input";import { adoptDockScope } from "../dock/dock-state";@@ -845,16 +847,16 @@ const versionBadgeClass =* the running version's release* date, stamped into core's BUILD_DATE at build time — displayed as-is, no network;* dev builds and releases that predate the stamping (v0.1.2 and earlier) carry null- * and show the version alone. When the update check knows a newer release, a small- * superscript badge follows, linking to the release page (this surface's affordance; the- * sidebar user menu instead routes its single update row into the update dialog).+ * and show the version alone. When the update flow has something waiting — a release+ * offered, a download in the background, a restart pending — a small superscript badge+ * follows, a button into the update modal (the same modal the sidebar's update row opens).* Fetching starts on mount — useVersionInfo caches at module level, so after the first* resolution anywhere in the app this renders instantly and never refetches. Nothing* renders until the version resolves (no placeholder flicker under the brand).*/function VersionLine() {const { locale } = useLocale();- const { version, update } = useVersionInfo(true);+ const { version } = useVersionInfo(true);if (version === null) return null;const date = version.buildDate;return (@@ -862,27 +864,47 @@ function VersionLine() {{`v${version.version}${date !== null ? ` · ${S.update.lastUpdated(formatMonthDay(date, locale))}` : ""}`}- {update !== null &&- update.updateAvailable &&- update.latestVersion !== null &&- (update.releaseUrl !== null ? (- <a- href={update.releaseUrl}- target="_blank"- rel="noopener noreferrer"- title={S.update.newVersion(update.latestVersion)}- aria-label={S.update.newVersion(update.latestVersion)}- className={`${versionBadgeClass} hover:underline`}- >- {S.update.newVersionBadge}- </a>- ) : (- <span className={versionBadgeClass}>{S.update.newVersionBadge}</span>- ))}+ <VersionBadge /></p>);}+/**+ * The superscript on the version line: a button into the update modal, worded by where the+ * flow stands. Its title and accessible name carry the update row's own sentence, so the+ * two surfaces say the same thing about the same release.+ */+function VersionBadge() {+ const { mode, flow } = useUpdateFlow();+ const badge = versionBadgeFor(flow);+ if (mode === "none" || badge === null) return null;+ const text =+ badge === "available"+ ? S.update.newVersionBadge+ : badge === "downloading"+ ? S.update.badgeDownloading+ : S.update.badgeReady;+ const note =+ flow.kind === "available"+ ? S.update.newVersion(flow.version)+ : flow.kind === "downloading"+ ? S.update.rowDownloading(flow.version, flow.percent)+ : flow.kind === "ready"+ ? S.update.restartToUpdate(flow.version)+ : text;+ return (+ <button+ type="button"+ onClick={openUpdateModal}+ title={note}+ aria-label={note}+ className={`${versionBadgeClass} hover:underline`}+ >+ {text}+ </button>+ );+}+/** Agent selection (pill dropdown): avatar + name, menu opens downward with an internal scroll cap. */function AgentSelect({agents,diff --git a/packages/web/src/lib/desktop-update.ts b/packages/web/src/lib/desktop-update.tsindex 77d54a34..c2b1514e 100644--- a/packages/web/src/lib/desktop-update.ts+++ b/packages/web/src/lib/desktop-update.ts@@ -1,9 +1,8 @@/**- * Client-update row logic for the sidebar user menu (desktop shell only).- *- * The row's data is the shell's updater snapshot; use-desktop-update.ts owns the- * polling, the armed-check watch and the toasts, these helpers keep the mapping pure- * (vitest runs node-only here, so nothing renders — same split as account-menu.ts).+ * Client-update helpers for the desktop shell's own window: whether the client update+ * surface is offered at all, and when an armed row-initiated check has settled.+ * use-desktop-update.ts owns the polling and the armed watch; these keep the decisions+ * pure (vitest runs node-only here, so nothing renders — same split as account-menu.ts).*/import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";import type { AccountMenuSession } from "./account-menu";@@ -20,93 +19,10 @@ export function offersClientUpdate(session: AccountMenuSession): boolean {return session.desktopMode && session.sessionVia === "desktop";}-/** The row's render mode; action and busy derive from it (ROW_BEHAVIOR), so they cannot disagree. */-export type ClientUpdateLabelKind =- | "check"- | "checking"- | "downloading"- | "install"- | "unsupported"- /** No snapshot yet (the shell wires its port a beat after boot): render disabled until one lands. */- | "unknown";--const ROW_BEHAVIOR: Record<- ClientUpdateLabelKind,- { action: "check" | "install" | "none"; busy: boolean }-> = {- check: { action: "check", busy: false },- checking: { action: "none", busy: true },- downloading: { action: "none", busy: true },- install: { action: "install", busy: false },- unsupported: { action: "none", busy: false },- unknown: { action: "none", busy: false },-};--/** What the row renders for one snapshot. */-export interface ClientUpdateRowModel {- labelKind: ClientUpdateLabelKind;- /** What a click does; `none` renders the row disabled. Derived from labelKind. */- action: "check" | "install" | "none";- /** Spinner + no click while the shell is checking or downloading. Derived from labelKind. */- busy: boolean;- /** Newer release the label names (`downloading`, `install`). */- version: string | null;- /** Download progress 0–100, when the shell reported one. */- percent: number | null;- /** Installed client version for the right-aligned chip; null until the first push. */- appVersion: string | null;- /** Why updates are off (`unsupported` label's tooltip). */- unsupportedReason: "dev" | "linux-not-appimage" | null;-}--function rowOf(- labelKind: ClientUpdateLabelKind,- status: DesktopUpdateStatus | null,- rest: Partial<Pick<ClientUpdateRowModel, "version" | "percent" | "unsupportedReason">> = {},-): ClientUpdateRowModel {- return {- labelKind,- ...ROW_BEHAVIOR[labelKind],- version: null,- percent: null,- appVersion: status?.appVersion ?? null,- unsupportedReason: null,- ...rest,- };-}--/**- * Maps one snapshot to the row. `checkPending` is the gap between clicking the check- * and the shell's `checking` frame landing: the row already spins, so a second click- * cannot arm a second watch.- */-export function clientUpdateRow(- status: DesktopUpdateStatus | null,- checkPending = false,-): ClientUpdateRowModel {- if (status === null) return rowOf("unknown", status);- switch (status.state) {- case "unsupported":- return rowOf("unsupported", status, { unsupportedReason: status.reason ?? null });- case "checking":- return rowOf("checking", status);- case "downloading":- return rowOf("downloading", status, {- version: status.version ?? null,- percent: status.percent ?? null,- });- case "downloaded":- return rowOf("install", status, { version: status.version ?? null });- // idle / up-to-date / error all offer the (re-)check; error details reach the user- // through the settle toast of the check that produced them, not a persistent row.- default:- return checkPending ? rowOf("checking", status) : rowOf("check", status);- }-}--/** How one row-initiated check ended, for exactly one toast per outcome (the same rule as the server-update row's manual check). */+/** How one row-initiated check ended, for exactly one report per outcome (in the modal when it is open, a toast otherwise). */export type ClientCheckSettle =| { kind: "up-to-date" }+ /** The check offered a release (`available`), or ran into one already being fetched. */| { kind: "found"; version: string | null }/** The check ran into a build already sitting on disk: point at the install step, not at a download. */| { kind: "ready"; version: string | null }@@ -146,6 +62,7 @@ export function clientCheckSettle(switch (now.state) {case "up-to-date":return { kind: "up-to-date" };+ case "available":case "downloading":return { kind: "found", version: now.version ?? null };case "downloaded":diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex aa23788e..f612c85d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -184,73 +184,94 @@ export const en: Strings = {} as Record<string, string>,},- /** Version footer, update reminder, and admin self-update in the sidebar user menu. */+ /**+ * The software-update flow (lib/update-flow.ts): the one modal for both the server release+ * and the desktop client, the account-menu row, the version-line badge, and the toasts for+ * outcomes that land while the modal is closed. Null version = the backend named none.+ */update: {/** Version-line date label; `date` is formatMonthDay output, e.g. "Last updated Jul 26". */lastUpdated: (date: string) => `Last updated ${date}`,- /** Superscript badge on the version lines when the update check found a newer release. */+ /** The version line's superscript, a button into the modal; the other two follow the flow. */newVersionBadge: "New version available",+ badgeDownloading: "Downloading update",+ badgeReady: "Restart to update",+ /** A release offered: the row's label and the avatar badges' sentence. */newVersion: (v: string) => `New version v${v} available`,+ /** A release downloaded / installed and waiting for the restart: the row's label and the badges' sentence. */+ restartToUpdate: (v: string | null) =>+ v !== null ? `Restart to update to v${v}` : "Restart to finish updating",+ /** The combined wording for an anchor covering several update trails at once. */updatesAvailable: "Updates available",- /**- * The sidebar user menu's SINGLE update row: it reads "Check for updates" until a newer- * release is known and runs the manual check; once one is known it reads newVersion() and- * opens the update dialog instead (which carries the release-notes link and, for admins,- * the self-update action).- */+ // —— the account-menu row ——checkNow: "Check for updates",checking: "Checking…",- /** Success toast when the manual check finds a newer release; the row itself turns into the update entry. */- foundNew: (v: string) => `New version v${v} found — use the update entry to install`,+ rowDownloading: (v: string | null, percent: number | null) =>+ `Downloading${v !== null ? ` v${v}` : " update"}${percent !== null ? ` ${percent}%` : "…"}`,+ rowRestarting: "Restarting…",+ rowUnsupported: "Cannot update from here",+ // —— the modal ——+ title: "Software Update",+ currentVersion: (v: string) => `Current version v${v}`,+ checkingBody: "Checking for updates…",upToDate: "You're on the latest version",checkFailed: "Update check failed — try again later",checkDisabled: "Update checks are disabled (PENGUIN_UPDATE_CHECK=off)",releaseNotes: "Release notes",- updateNow: "Update now",- updating: "Updating…",- updated: "Update complete — restart the service to apply",- restartHint: "Restart by re-running penguin web (or penguin server) in a terminal",- failed: "Update failed",- unsupported: "This install cannot be updated from the web UI",- confirmBody:- "Downloads the latest release and installs it into the install directory on the server (the data directory is not touched). Restart the service afterwards for the update to take effect.",- /** Shown in place of confirmBody to non-admins, who can read the release notes but cannot run the update. */+ openReleases: "Open the Releases page",+ /** What "download and update" does, per backend. */+ availableBodyRelease:+ "Downloads the latest release and installs it into the install directory on the server (the data directory is not touched). You can close this window while it downloads; restart the service afterwards to run it.",+ availableBodyClient:+ "Downloads the new version. You can close this window and keep working while it downloads; restart the app once it is ready to finish updating.",+ /** Shown to non-admins in place of the body above (they can read the notes but cannot run the update). */adminOnly: "Only an administrator can run the update from here.",- /**- * Desktop client-update row in the sidebar user menu (shell window only): check →- * download progress → restart-to-install, driven by the shell's updater snapshot.- * It stands in for the server update surface, which desktop mode hides entirely.- * Null version/percent = the shell didn't name one.- */- clientCheckNow: "Check for updates",- /** Success toast when a row-initiated check finds a release (the download starts by itself). */- clientFoundNew: (v: string | null) =>- v !== null- ? `Version v${v} found — downloading in the background…`- : "New version found — downloading in the background…",- clientDownloading: (v: string | null, percent: number | null) =>- `Downloading${v !== null ? ` v${v}` : ""}…${percent !== null ? ` ${percent}%` : ""}`,- clientRestartToInstall: (v: string | null) =>- v !== null ? `Restart to install v${v}` : "Restart to install the update",- /** Success toast when a row-initiated check lands on a build already downloaded and waiting. */- clientDownloadReady: (v: string | null) =>- v !== null- ? `Version v${v} is ready — restart to install`- : "The update is ready — restart to install",- /** Error toast carrying the shell's own updater failure text — a failed download or signature check, not only a failed lookup. */- clientUpdateFailed: (detail: string) => `Client update failed: ${detail}`,- /** Install POST failed before the shell could act; `detail` is apiErrorText output. */- clientInstallFailed: (detail: string) => `Could not start the install: ${detail}`,- clientInstallConfirmTitle: "Restart and install the update",+ downloadAndInstall: "Download and update",+ later: "Later",+ background: "Continue in background",+ downloading: (v: string | null) =>+ v !== null ? `Downloading v${v}…` : "Downloading the update…",+ /** The progress bar's accessible name. */+ downloadProgress: "Download progress",+ /** The server job's stages, shown under the bar while it carries no percentage. */+ phaseResolving: "Resolving the release…",+ phaseDownloading: "Downloading the package…",+ phaseInstalling: "Verifying and installing…",+ ready: (v: string | null) => (v !== null ? `v${v} is ready` : "The update is ready"),+ readyBodyRelease:+ "Restart the service to run the new version. Running tasks will be interrupted; this page reloads once the service is back.",/** Mirrors the shell's native restart prompt: the interruption warning must not disappear on the web path. */- clientInstallConfirmBody:+ readyBodyClient:"PenguinHarness will restart to finish updating. Running tasks will be interrupted.",- clientInstallConfirmAction: "Restart now",- /** Tooltip on the disabled row in a dev (unpackaged) run. */- clientUnsupportedDev: "A dev run does not update itself",- /** Tooltip on the disabled row for a Linux install that is not an AppImage (a .deb, or an unpacked tree). */- clientUnsupportedNonAppImage:+ /** Nothing supervises the server process (not started through penguin web / penguin server), so the restart is the user's. */+ readyBodyManual:+ "The new version is installed. This service is not supervised by penguin web or penguin server, so it cannot be restarted from here: re-run penguin web (or penguin server) in a terminal.",+ restartNow: "Restart and update",+ restarting: "Restarting…",+ restartingBodyRelease: "This page reloads once the service is back.",+ restartingBodyClient: "The app is about to restart.",+ failed: "Update failed",+ retry: "Retry",+ /** Why this install cannot update itself. */+ unsupportedDev: "A dev run does not update itself",+ unsupportedNonAppImage:"Only the AppImage build updates itself on Linux — update a package install through your package manager",+ unsupportedNotViaCli:+ "This service was not started through penguin web or penguin server, so it cannot be updated from here",+ unsupportedCli: "This install cannot be updated from the web UI",+ // —— toasts: outcomes that land while the modal is closed ——+ foundNew: (v: string) => `New version v${v} found — open the update entry to download it`,+ foundNewUnnamed: "New version found — open the update entry to download it",+ readyToast: (v: string | null) =>+ v !== null ? `v${v} is ready — restart to update` : "The update is ready — restart to update",+ failedToast: "Update failed — open the update entry for details",+ unsupportedToast: "This install cannot be updated from the web UI",+ /** The shell's own updater failure text — a failed download or signature check, not only a failed lookup. */+ clientUpdateFailed: (detail: string) => `Client update failed: ${detail}`,+ /** A download / restart request failed before the backend could act; `detail` is apiErrorText output. */+ requestFailed: (detail: string) => `Could not run the update action: ${detail}`,+ restartTimedOut:+ "The service has not come back — check penguin web's output in the terminal, then reload this page",},/**diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 0f1a239a..f33cd5a5 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -189,72 +189,87 @@ export const zh = {} as Record<string, string>,},- /** Version footer, update reminder, and admin self-update in the sidebar user menu. */+ /**+ * The software-update flow (lib/update-flow.ts): the one modal for both the server release+ * and the desktop client, the account-menu row, the version-line badge, and the toasts for+ * outcomes that land while the modal is closed. Null version = the backend named none.+ */update: {/** Version-line date label (owner-specified wording); `date` is formatMonthDay output. */lastUpdated: (date: string) => `最近更新日期 ${date}`,- /** Superscript badge on the version lines when the update check found a newer release (owner-specified wording). */+ /** The version line's superscript (owner-specified wording), a button into the modal; the other two follow the flow. */newVersionBadge: "有新版本可用",+ badgeDownloading: "正在下载更新",+ badgeReady: "重启以更新",+ /** A release offered: the row's label and the avatar badges' sentence. */newVersion: (v: string) => `新版本 v${v} 可用`,- /**- * The combined wording for an anchor that leads to BOTH update trails at once (the- * mobile menu button): something is updatable, without claiming which — naming one of- * two would send the user down the wrong one.- */+ /** A release downloaded / installed and waiting for the restart: the row's label and the badges' sentence. */+ restartToUpdate: (v: string | null) => (v !== null ? `重启以更新到 v${v}` : "重启以完成更新"),+ /** The combined wording for an anchor covering several update trails at once. */updatesAvailable: "有可用更新",- /**- * The sidebar user menu's SINGLE update row: it reads checkNow until a newer release- * is known and runs the manual check; once one is known it reads newVersion() and- * opens the update dialog instead (which carries the release-notes link and, for- * admins, the self-update action).- */+ // —— the account-menu row ——checkNow: "检查更新",checking: "检查中…",- /** Success toast when the manual check finds a newer release; the row itself turns into the update entry. */- foundNew: (v: string) => `发现新版本 v${v},点击该更新入口即可安装`,+ rowDownloading: (v: string | null, percent: number | null) =>+ `正在下载${v !== null ? ` v${v}` : "更新"}${percent !== null ? ` ${percent}%` : "…"}`,+ rowRestarting: "正在重启…",+ rowUnsupported: "无法在线更新",+ // —— the modal ——+ title: "软件更新",+ currentVersion: (v: string) => `当前版本 v${v}`,+ checkingBody: "正在检查更新…",upToDate: "已是最新版本",checkFailed: "检查更新失败,请稍后重试",checkDisabled: "更新检查已关闭(PENGUIN_UPDATE_CHECK=off)",releaseNotes: "更新说明",- updateNow: "立即更新",- updating: "更新中…",- updated: "更新完成,重启服务后生效",- restartHint: "在终端重新运行 penguin web(或 penguin server)即可完成重启",- failed: "更新失败",- unsupported: "当前安装方式不支持在线更新",- confirmBody:- "将下载最新版本并安装到服务器上的安装目录(数据目录不受影响)。安装完成后需要重启服务才会生效。",- /** Copy shown to non-admins in place of confirmBody (they can read the release notes but cannot run the update here). */+ openReleases: "打开 Releases 页面",+ /** What "download and update" does, per backend. */+ availableBodyRelease:+ "将下载最新版本并安装到服务器上的安装目录(数据目录不受影响)。下载期间可以关闭本窗口,安装完成后重启服务即可生效。",+ availableBodyClient:+ "将下载新版本。下载期间可以关闭本窗口继续使用,下载完成后重启应用即可完成更新。",+ /** Shown to non-admins in place of the body above (they can read the notes but cannot run the update). */adminOnly: "只有管理员可以在这里执行更新。",- /**- * Desktop client-update row in the sidebar user menu (shell window only): check →- * download progress → restart-to-install, driven by the shell's updater snapshot.- * It stands in for the server update surface, which desktop mode hides entirely.- * Null version/percent = the shell didn't name one.- */- clientCheckNow: "检查更新",- /** Success toast when a row-initiated check finds a release (the download starts by itself). */- clientFoundNew: (v: string | null) =>- v !== null ? `发现新版本 v${v},正在后台下载…` : "发现新版本,正在后台下载…",- clientDownloading: (v: string | null, percent: number | null) =>- `${v !== null ? `v${v} ` : ""}下载中…${percent !== null ? ` ${percent}%` : ""}`,- clientRestartToInstall: (v: string | null) =>- v !== null ? `重启并安装 v${v}` : "重启并安装更新",- /** Success toast when a row-initiated check lands on a build already downloaded and waiting. */- clientDownloadReady: (v: string | null) =>- v !== null ? `新版本 v${v} 已就绪,可重启安装` : "更新已就绪,可重启安装",- /** Error toast carrying the shell's own updater failure text — a failed download or signature check, not only a failed lookup. */- clientUpdateFailed: (detail: string) => `客户端更新失败:${detail}`,- /** Install POST failed before the shell could act; `detail` is apiErrorText output. */- clientInstallFailed: (detail: string) => `无法开始安装:${detail}`,- clientInstallConfirmTitle: "重启并安装更新",+ downloadAndInstall: "下载并更新",+ later: "稍后",+ background: "放到后台",+ downloading: (v: string | null) => (v !== null ? `正在下载 v${v}…` : "正在下载更新…"),+ /** The progress bar's accessible name. */+ downloadProgress: "下载进度",+ /** The server job's stages, shown under the bar while it carries no percentage. */+ phaseResolving: "正在获取版本信息…",+ phaseDownloading: "正在下载安装包…",+ phaseInstalling: "正在校验并安装…",+ ready: (v: string | null) => (v !== null ? `v${v} 已就绪` : "更新已就绪"),+ readyBodyRelease: "重启服务即可运行新版本,正在运行的任务会被打断;服务回来后页面会自动刷新。",/** Mirrors the shell's native restart prompt: the interruption warning must not disappear on the web path. */- clientInstallConfirmBody: "PenguinHarness 将重启以完成更新,正在运行的任务会被打断。",- clientInstallConfirmAction: "立即重启",- /** Tooltip on the disabled row in a dev (unpackaged) run. */- clientUnsupportedDev: "开发运行不支持自更新",- /** Tooltip on the disabled row for a Linux install that is not an AppImage (a .deb, or an unpacked tree). */- clientUnsupportedNonAppImage: "Linux 上只有 AppImage 版本支持自更新——包安装请通过包管理器更新",+ readyBodyClient: "PenguinHarness 将重启以完成更新,正在运行的任务会被打断。",+ /** Nothing supervises the server process (not started through penguin web / penguin server), so the restart is the user's. */+ readyBodyManual:+ "新版本已安装。当前服务不是由 penguin web 或 penguin server 托管,无法从这里重启:请在终端重新运行 penguin web(或 penguin server)。",+ restartNow: "重启并更新",+ restarting: "正在重启…",+ restartingBodyRelease: "服务回来后页面会自动刷新。",+ restartingBodyClient: "应用即将重启。",+ failed: "更新失败",+ retry: "重试",+ /** Why this install cannot update itself. */+ unsupportedDev: "开发运行不支持自更新",+ unsupportedNonAppImage: "Linux 上只有 AppImage 版本支持自更新——包安装请通过包管理器更新",+ unsupportedNotViaCli: "当前服务不是通过 penguin web 或 penguin server 启动的,无法从这里更新",+ unsupportedCli: "当前安装方式不支持在线更新",+ // —— toasts: outcomes that land while the modal is closed ——+ foundNew: (v: string) => `发现新版本 v${v},打开更新入口即可下载`,+ foundNewUnnamed: "发现新版本,打开更新入口即可下载",+ readyToast: (v: string | null) =>+ v !== null ? `v${v} 已就绪,可重启更新` : "更新已就绪,可重启更新",+ failedToast: "更新失败,打开更新入口查看详情",+ unsupportedToast: "当前安装方式不支持在线更新",+ /** The shell's own updater failure text — a failed download or signature check, not only a failed lookup. */+ clientUpdateFailed: (detail: string) => `客户端更新失败:${detail}`,+ /** A download / restart request failed before the backend could act; `detail` is apiErrorText output. */+ requestFailed: (detail: string) => `无法执行更新操作:${detail}`,+ restartTimedOut: "服务迟迟没有回来,请查看终端里 penguin web 的输出后手动刷新页面",},/**diff --git a/packages/web/src/lib/update-badges.ts b/packages/web/src/lib/update-badges.tsindex 7e7cafef..88c96727 100644--- a/packages/web/src/lib/update-badges.ts+++ b/packages/web/src/lib/update-badges.ts@@ -10,56 +10,31 @@** Every gate here is written as "is there a control the user can reach": a badge over a path* with nothing actionable at the end of it is worse than no badge. That is why the software- * gate takes which row the running mode actually offers — desktop mode hides the server- * release row entirely and updates the client through the shell instead, so a newer server- * release must not raise a dot there.+ * gate reads the update flow, whose mode is the session's — a browser signed into a+ * desktop-mode server can update neither the server nor that machine's app, and its flow+ * never offers anything, so no dot leads it to a modal with nothing to do.** Pure decisions only (vitest runs node-only here, so nothing renders) — `use-update-badges.ts`* wires them to the live stores and turns a note into localized copy.*/-import type { DesktopUpdateStatus, UpdateCheckResponse } from "@prismshadow/penguin-server/api";-import { clientUpdateRow } from "./desktop-update";+import type { UpdateFlow } from "./update-flow";-/** A software update the running mode can act on, and the version the offer names. */+/** A software update the user can act on: a release offered (download it), or one downloaded / installed (restart into it). */export type SoftwareUpdate =- | { kind: "release"; version: string }- /** A client build the shell has downloaded; `version` is null when the shell did not name one. */- | { kind: "client"; version: string | null };+ | { kind: "available"; version: string }+ /** `version` is null when the backend did not name one. */+ | { kind: "ready"; version: string | null };/**- * The newer release the server-update row acts on, or null. A resolved version is required,- * not just the boolean — the row and every tooltip along the trail name it, so an "available- * but unnamed" result must not raise a dot leading to a versionless reminder. The check is- * fail-soft on the server, so a disabled check (`PENGUIN_UPDATE_CHECK=off`) and a failed- * lookup both arrive as `updateAvailable: false` and raise nothing.+ * The one software gate behind every dot on that trail, read off the update flow. A download+ * in flight is deliberately not one: the row shows its progress, but there is nothing for the+ * user to do until it lands, and a badge that cannot be cleared by acting on it is noise. The+ * mode gate is the flow's own: where this session can update nothing, the flow never leaves+ * `unknown`.*/-export function releaseUpdate(update: UpdateCheckResponse | null): string | null {- return update?.updateAvailable === true ? (update.latestVersion ?? null) : null;-}--export interface SoftwareUpdateInput {- /** Whether the sidebar user menu offers the server release row here (everything but desktop mode). */- releaseRowOffered: boolean;- /** Whether it offers the desktop client row here (`offersClientUpdate`: the shell's own window). */- clientRowOffered: boolean;- update: UpdateCheckResponse | null;- clientStatus: DesktopUpdateStatus | null;-}--/**- * The one software gate behind every dot on that trail. A client build still downloading is- * deliberately not one: the row shows its progress, but there is nothing for the user to do- * until it lands, and a badge that cannot be cleared by acting on it is noise.- */-export function softwareUpdate(input: SoftwareUpdateInput): SoftwareUpdate | null {- if (input.releaseRowOffered) {- const version = releaseUpdate(input.update);- if (version !== null) return { kind: "release", version };- }- if (input.clientRowOffered) {- const row = clientUpdateRow(input.clientStatus);- if (row.action === "install") return { kind: "client", version: row.version };- }+export function softwareUpdate(flow: UpdateFlow): SoftwareUpdate | null {+ if (flow.kind === "available") return { kind: "available", version: flow.version };+ if (flow.kind === "ready") return { kind: "ready", version: flow.version };return null;}diff --git a/packages/web/src/lib/update-flow.ts b/packages/web/src/lib/update-flow.tsnew file mode 100644index 00000000..618ca133--- /dev/null+++ b/packages/web/src/lib/update-flow.ts@@ -0,0 +1,263 @@+/**+ * The software-update flow: one state machine over two backends, rendered by the update+ * modal, the account-menu row and the version-line badge.+ *+ * `release` mode is every ordinary server: the newer release comes from the server's+ * GitHub lookup (`use-version-info.ts`), the download is the admin self-update job+ * (`penguin update` in the background, `GET/POST /api/version/update`) and the restart is+ * `POST /api/version/restart`, honored when `penguin server|web` supervises the process.+ * `client` mode is the desktop shell's own window: the shell's updater snapshot+ * (`use-desktop-update.ts`) carries every step, and the page only relays check / download+ * / install. `none` is a browser signed into a desktop-mode server, which can act on+ * neither and gets no update surface at all (the same gate as before this modal).+ *+ * The flow itself is what both surfaces agree on: nothing is fetched until the user+ * confirms, a running download can be sent to the background and keeps reporting through+ * the row, and a downloaded (or installed) release waits for an explicit restart. Pure+ * decisions only (vitest runs node-only here, so nothing renders) — `use-update-flow.ts`+ * feeds these from the live stores and owns the actions.+ */+import type {+ DesktopUpdateStatus,+ UpdateCheckResponse,+ UpdateJobPhase,+ UpdateJobStatus,+ VersionResponse,+} from "@prismshadow/penguin-server/api";+import type { AccountMenuSession } from "./account-menu";+import { offersClientUpdate } from "./desktop-update";+import { updateCheckOutcome } from "./use-version-info";++export type UpdateMode = "release" | "client" | "none";++/** Which backend this session updates through (see the module comment). */+export function updateModeFor(session: AccountMenuSession): UpdateMode {+ if (offersClientUpdate(session)) return "client";+ return session.desktopMode ? "none" : "release";+}++/** Why this install cannot update itself, as the backend reported it. */+export type UpdateUnsupported =+ | { code: "dev" }+ | { code: "linux-not-appimage" }+ | { code: "not_launched_via_cli" }+ /** The CLI declined (source checkout, unrecognized layout, Windows); `detail` is its own message. */+ | { code: "cli_refused"; detail: string };++export type UpdateFlow =+ /** No check has answered yet. */+ | { kind: "unknown" }+ | { kind: "checking" }+ /** Checks are turned off (PENGUIN_UPDATE_CHECK=off); the Releases page is the only way to look. */+ | { kind: "disabled" }+ | { kind: "up-to-date"; version: string | null }+ /** A newer release is offered; nothing has been fetched. `canInstall` is false for a non-admin on a server. */+ | { kind: "available"; version: string; releaseUrl: string | null; canInstall: boolean }+ /** `percent` null = indeterminate; `phase` is the server job's stage (client downloads have none). */+ | {+ kind: "downloading";+ version: string | null;+ percent: number | null;+ phase: UpdateJobPhase | null;+ }+ /** Downloaded (client) or installed (release): a restart runs it. `manual` = nothing can restart this process; the user does it by hand. */+ | { kind: "ready"; version: string | null; restart: "auto" | "manual" }+ | { kind: "restarting"; version: string | null }+ /** `detail` is the backend's own text (the update command's output tail); `retry` names the step that failed. */+ | { kind: "error"; message: string | null; detail: string | null; retry: "check" | "download" }+ | { kind: "unsupported"; reason: UpdateUnsupported };++/** What the page itself has in flight, beside the backend snapshots. */+export interface FlowLocal {+ /** A manual check was asked for and has not answered. */+ checking: boolean;+ /** The download request is on the wire — the backend has not yet reported the download. */+ downloadRequested: boolean;+ /** The restart step: asked for (waiting for the process to come back / the window to close), or refused because nothing supervises the process. */+ restart: "none" | "requested" | "manual";+}++export const NO_LOCAL: FlowLocal = { checking: false, downloadRequested: false, restart: "none" };++/** The Releases page of one version — the client mode's release-notes link (the shell names a version, never a URL). */+export function releaseUrlFor(version: string): string {+ return `https://github.com/Prism-Shadow/penguin-harness/releases/tag/v${version}`;+}++export interface ReleaseInputs {+ version: VersionResponse | null;+ update: UpdateCheckResponse | null;+ job: UpdateJobStatus | null;+ isAdmin: boolean;+}++/** The flow of an ordinary server (see the module comment); the job outranks the check, the restart outranks both. */+export function releaseFlow(i: ReleaseInputs, local: FlowLocal): UpdateFlow {+ const offered = i.update?.updateAvailable === true ? (i.update.latestVersion ?? null) : null;+ if (local.restart === "requested") {+ return { kind: "restarting", version: i.job?.targetVersion ?? offered };+ }+ if (i.job?.state === "running") {+ return {+ kind: "downloading",+ version: i.job.targetVersion,+ percent: i.job.percent ?? null,+ phase: i.job.phase ?? null,+ };+ }+ if (local.downloadRequested) {+ return { kind: "downloading", version: offered, percent: null, phase: "resolving" };+ }+ if (i.job?.state === "done" && i.job.result !== undefined) {+ const result = i.job.result;+ if (result.status === "updated") {+ return {+ kind: "ready",+ version: i.job.targetVersion,+ restart: local.restart === "manual" ? "manual" : "auto",+ };+ }+ if (result.status === "unsupported") {+ return {+ kind: "unsupported",+ reason:+ result.reason === "not_launched_via_cli"+ ? { code: "not_launched_via_cli" }+ : { code: "cli_refused", detail: result.output },+ };+ }+ return {+ kind: "error",+ message: null,+ detail: result.output === "" ? null : result.output,+ retry: "download",+ };+ }+ if (local.checking) return { kind: "checking" };+ if (i.update === null) return { kind: "unknown" };+ const outcome = updateCheckOutcome(i.update);+ switch (outcome.kind) {+ case "disabled":+ return { kind: "disabled" };+ case "failed":+ return { kind: "error", message: null, detail: null, retry: "check" };+ case "found":+ return {+ kind: "available",+ version: outcome.latestVersion,+ releaseUrl: i.update.releaseUrl,+ canInstall: i.isAdmin,+ };+ default:+ return { kind: "up-to-date", version: i.update.currentVersion };+ }+}++/** The flow of the desktop shell's own window: the shell's snapshot is the whole story, plus what the page has on the wire. */+export function clientFlow(status: DesktopUpdateStatus | null, local: FlowLocal): UpdateFlow {+ if (local.restart === "requested")+ return { kind: "restarting", version: status?.version ?? null };+ if (status === null) return local.checking ? { kind: "checking" } : { kind: "unknown" };+ switch (status.state) {+ case "unsupported":+ return {+ kind: "unsupported",+ reason:+ status.reason === "linux-not-appimage" ? { code: "linux-not-appimage" } : { code: "dev" },+ };+ case "checking":+ return { kind: "checking" };+ case "up-to-date":+ return local.checking+ ? { kind: "checking" }+ : { kind: "up-to-date", version: status.appVersion };+ case "available":+ if (local.downloadRequested) {+ return { kind: "downloading", version: status.version ?? null, percent: null, phase: null };+ }+ return status.version !== undefined+ ? {+ kind: "available",+ version: status.version,+ releaseUrl: releaseUrlFor(status.version),+ canInstall: true,+ }+ : { kind: "unknown" };+ case "downloading":+ return {+ kind: "downloading",+ version: status.version ?? null,+ percent: status.percent ?? null,+ phase: null,+ };+ case "downloaded":+ return { kind: "ready", version: status.version ?? null, restart: "auto" };+ case "error":+ return local.checking+ ? { kind: "checking" }+ : { kind: "error", message: status.message ?? null, detail: null, retry: "check" };+ default:+ return local.checking ? { kind: "checking" } : { kind: "unknown" };+ }+}++/** Whether opening the modal should also start a check: nothing is known, or the last answer is stale/failed. */+export function opensWithCheck(flow: UpdateFlow): boolean {+ return (+ flow.kind === "unknown" ||+ flow.kind === "up-to-date" ||+ (flow.kind === "error" && flow.retry === "check")+ );+}++/** The account-menu row's render mode; busy / dot / action derive from it so they cannot disagree. */+export type UpdateRowLabel =+ "check" | "checking" | "available" | "downloading" | "ready" | "restarting" | "unsupported";++export interface UpdateRowModel {+ label: UpdateRowLabel;+ /** The newer release the label names, when it names one. */+ version: string | null;+ /** Download progress, when the label carries one. */+ percent: number | null;+ /** Spinner: something is moving. */+ busy: boolean;+ /** Accent dot: something is waiting for the user (an offer, or a restart). */+ dot: boolean;+}++/** What the row says for one flow. Every state is clickable — the modal explains each one. */+export function updateRowModel(flow: UpdateFlow): UpdateRowModel {+ switch (flow.kind) {+ case "checking":+ return { label: "checking", version: null, percent: null, busy: true, dot: false };+ case "available":+ return { label: "available", version: flow.version, percent: null, busy: false, dot: true };+ case "downloading":+ return {+ label: "downloading",+ version: flow.version,+ percent: flow.percent,+ busy: true,+ dot: false,+ };+ case "ready":+ return { label: "ready", version: flow.version, percent: null, busy: false, dot: true };+ case "restarting":+ return { label: "restarting", version: flow.version, percent: null, busy: true, dot: false };+ case "unsupported":+ return { label: "unsupported", version: null, percent: null, busy: false, dot: false };+ default:+ return { label: "check", version: null, percent: null, busy: false, dot: false };+ }+}++/** What the version line's superscript says, or null when nothing is waiting — a button into the modal in every case. */+export type VersionBadge = "available" | "downloading" | "ready";++export function versionBadgeFor(flow: UpdateFlow): VersionBadge | null {+ if (flow.kind === "available" || flow.kind === "downloading" || flow.kind === "ready") {+ return flow.kind;+ }+ return null;+}diff --git a/packages/web/src/lib/use-desktop-update.ts b/packages/web/src/lib/use-desktop-update.tsindex 20c222c9..e9ef4a6c 100644--- a/packages/web/src/lib/use-desktop-update.ts+++ b/packages/web/src/lib/use-desktop-update.ts@@ -1,69 +1,61 @@/**- * Shared state behind the client-update row: the shell's updater snapshot, the armed- * row-initiated check, and the polling that feeds both.+ * The desktop shell's updater snapshot, shared by everything that reads it: the polling that+ * feeds it, the armed row-initiated check, and the three relay requests (check / download /+ * install). Client-mode half of the update flow — `use-update-flow.ts` reads the snapshot+ * through `useDesktopUpdate` and turns it into the modal's state.*- * Everything lives at module level (use-version-info.ts convention) because the row- * itself unmounts with the user menu: a check armed there must still settle — and- * toast its one outcome — after the menu closes. The single always-mounted consumer- * is the Sidebar's hook instance, which keeps polling while the menu is open or a- * watch is armed, fast only while something is actually moving (checking,- * downloading, armed watch) and lazily otherwise — a terminal snapshot (unsupported,- * downloaded) cannot change between clicks, so it only warrants an occasional- * refresh.+ * Everything lives at module level (use-version-info.ts convention): a check armed from the+ * modal must still settle after the modal is closed, and a download sent to the background+ * must keep reporting through the account-menu row. One always-mounted owner (the update+ * modal) drives the polling — fast while something is moving (checking, downloading, an+ * armed watch), lazily otherwise, and not at all when nothing is open and nothing moves: a+ * terminal snapshot (up to date, downloaded) cannot change between clicks.*/import { useEffect, useReducer } from "react";import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";import * as api from "../api/endpoints";-import { S } from "./strings";-import { apiErrorText } from "./api-error";import { clientCheckSettle } from "./desktop-update";-import { toastError, toastInfo, toastSuccess } from "../components/ui/toast";+import type { ClientCheckSettle } from "./desktop-update";/** Poll cadence while a check or download is moving (or a watch is armed). */const FAST_POLL_MS = 1_500;-/** Poll cadence for a static snapshot with the menu open — just enough to notice outside activity (the timer check, the native menu). */+/** Poll cadence for a static snapshot while the modal or menu is open — just enough to notice outside activity (the timer check, the native menu). */const SLOW_POLL_MS = 8_000;let statusCache: DesktopUpdateStatus | null = null;let inflight: Promise<void> | null = null;-/** The armed row-initiated check; null = none. Module-level so it survives the menu closing. */+/** The armed row-initiated check; null = none. Module-level so it survives the modal closing. */let watch: { atClickSeq: number | null; armedAt: number } | null = null;const listeners = new Set<() => void>();+/** Where a settled check reports (use-update-flow.ts decides between the modal and a toast). */+let settleListener: ((settle: ClientCheckSettle) => void) | null = null;function notifyAll(): void {for (const notify of listeners) notify();}-/** Settles the armed check against the current cache, toasting its one outcome. */+/** The latest snapshot, for callers outside React (the flow's actions). */+export function getDesktopUpdateStatus(): DesktopUpdateStatus | null {+ return statusCache;+}++/** Whether a row-initiated check is armed and unsettled (the shell's `checking` frame may not have landed yet). */+export function isClientCheckPending(): boolean {+ return watch !== null;+}++/** Registers the one place a settled check reports to. */+export function onClientCheckSettle(listener: (settle: ClientCheckSettle) => void): void {+ settleListener = listener;+}++/** Settles the armed check against the current cache, reporting its one outcome. */function settleWatch(): void {if (watch === null) return;const settle = clientCheckSettle(watch.atClickSeq, statusCache, Date.now() - watch.armedAt);if (settle === null) return;watch = null;- switch (settle.kind) {- case "up-to-date":- toastSuccess(S.update.upToDate);- break;- case "found":- toastSuccess(S.update.clientFoundNew(settle.version));- break;- case "ready":- toastSuccess(S.update.clientDownloadReady(settle.version));- break;- case "unsupported":- toastInfo(- settle.reason === "linux-not-appimage"- ? S.update.clientUnsupportedNonAppImage- : S.update.clientUnsupportedDev,- );- break;- default:- toastError(- settle.message !== null- ? S.update.clientUpdateFailed(settle.message)- : S.update.checkFailed,- );- }+ settleListener?.(settle);}/** One shared GET: concurrent callers ride the in-flight request (terminal-list.ts convention), so a slow answer can never be overtaken and overwritten by a newer one. */@@ -74,7 +66,7 @@ function poll(): Promise<void> {const res = await api.getDesktopUpdate();statusCache = res.status;} catch {- // The menu can outlive a server restart by a beat; the next poll self-corrects.+ // The page can outlive a server restart by a beat; the next poll self-corrects.// An armed watch still ages toward its timeout through the settle below.} finally {inflight = null;@@ -87,14 +79,14 @@ function poll(): Promise<void> {/*** One passive read of the shell's updater snapshot, for a consumer that does not poll: the- * update badge asks once per app load so a build downloaded before this load can raise its- * dot without the user opening the menu first. Concurrent callers ride the in-flight GET.+ * update badge asks once per app load so a release offered or downloaded before this load+ * can raise its dot without the user opening anything. Concurrent callers ride the in-flight GET.*/export function refreshDesktopUpdate(): void {void poll();}-/** Row action: arm the settle watch, then ask the shell to check. A failed POST disarms and reports itself. */+/** Arms the settle watch, then asks the shell to check. A failed POST disarms and reports itself through the settle listener. */export async function requestClientCheck(): Promise<void> {if (watch !== null) return;watch = { atClickSeq: statusCache?.seq ?? null, armedAt: Date.now() };@@ -105,27 +97,30 @@ export async function requestClientCheck(): Promise<void> {} catch (e) {watch = null;notifyAll();- toastError(apiErrorText(e));+ settleListener?.({ kind: "failed", message: e instanceof Error ? e.message : String(e) });}}-/** Row action, behind the page's confirm dialog: the shell restarts into the downloaded build, so success renders nothing. */+/** Asks the shell to fetch the release it offered; the snapshot reports the download from there. Rejects when the POST fails. */+export async function requestClientDownload(): Promise<void> {+ await api.desktopUpdateDownload();+ void poll();+}++/** Asks the shell to restart into the downloaded build; success renders nothing (the window goes away). Rejects when the POST fails. */export async function requestClientInstall(): Promise<void> {- try {- await api.desktopUpdateInstall();- } catch (e) {- toastError(S.update.clientInstallFailed(apiErrorText(e)));- }+ await api.desktopUpdateInstall();}/**- * The Sidebar's single always-mounted subscription: current snapshot plus whether a- * row-initiated check is still unsettled (the row spins on it before the shell's- * `checking` frame lands).+ * The snapshot, plus whether a row-initiated check is still unsettled (the flow spins on+ * it before the shell's `checking` frame lands). `enabled` is client mode; `wanted` is a+ * surface being open (the modal, the menu) — polling also runs on its own while a check or+ * download is moving, so a download sent to the background still reports.*/export function useDesktopUpdate(enabled: boolean,- menuOpen: boolean,+ wanted: boolean,): { status: DesktopUpdateStatus | null; checkPending: boolean } {const [, force] = useReducer((x: number) => x + 1, 0);useEffect(() => {@@ -138,7 +133,7 @@ export function useDesktopUpdate(const checkPending = watch !== null;const hot =checkPending || statusCache?.state === "checking" || statusCache?.state === "downloading";- const active = enabled && (menuOpen || checkPending);+ const active = enabled && (wanted || hot);useEffect(() => {if (!active) return;void poll();diff --git a/packages/web/src/lib/use-update-badges.ts b/packages/web/src/lib/use-update-badges.tsindex 36d3e72b..a2d7c6d8 100644--- a/packages/web/src/lib/use-update-badges.ts+++ b/packages/web/src/lib/use-update-badges.ts@@ -18,10 +18,9 @@* nothing there; syncing presets is owner-only, so a member never sees the Models dot (and* `use-project-todos.ts` does not even make that request).*/-import { useEffect, useMemo } from "react";+import { useMemo } from "react";import { S } from "./strings";-import { offersClientUpdate } from "./desktop-update";-import { refreshDesktopUpdate, useDesktopUpdate } from "./use-desktop-update";+import { useUpdateFlow } from "./use-update-flow";import { useVersionInfo } from "./use-version-info";import { badgeNote, softwareUpdate } from "./update-badges";import type { BadgeSource, SoftwareUpdate, UpdateBadgeNote } from "./update-badges";@@ -36,7 +35,6 @@ import type { Todo, TodoKey } from "./todo-badges";import { useTodoDismissals } from "./todo-dismissals";import { useProjectTodos } from "./use-project-todos";import { catalogDelta } from "../features/models/catalog-sync";-import { useAuth } from "../state/auth";import { useProject } from "../state/project";/** The nav routes that can carry a dot, and what each one's dot leads to. */@@ -58,29 +56,20 @@ export interface UpdateBadges {}export function useUpdateBadges(eager = false): UpdateBadges {- const { desktopMode, sessionVia } = useAuth();const { agents, currentProject } = useProject();const projectId = currentProject?.projectId ?? null;// Syncing presets is owner-only, so that trail has no control at its end for a member.const ownsProject = currentProject?.role === "owner";- const clientRowOffered = offersClientUpdate({ desktopMode, sessionVia });- const { update } = useVersionInfo(eager);- // Passive: the shell's snapshot is polled by the sidebar's own hook instance while the user- // menu is open. The one-shot refresh below is what lets a build downloaded before this load- // show up without opening anything.- const { status } = useDesktopUpdate(false, false);- useEffect(() => {- if (eager && clientRowOffered) refreshDesktopUpdate();- }, [eager, clientRowOffered]);+ // The eager instance is what fetches the version and the release check on load at all; the+ // flow below reads the same cache. The shell's snapshot is refreshed once on load by the+ // flow's owner (the update modal), so a release offered or downloaded before this load+ // shows up without the user opening anything.+ useVersionInfo(eager);+ const { flow } = useUpdateFlow();const probes = useProjectTodos(projectId, eager, ownsProject);const dismissed = useTodoDismissals(projectId, eager);- const software = softwareUpdate({- releaseRowOffered: !desktopMode,- clientRowOffered,- update,- clientStatus: status,- });+ const software = softwareUpdate(flow);// Memoized on the cached response's identity: this walks the whole built-in catalog, and the// hook re-runs on every render of the pages that read it (a keystroke in the model search box).@@ -150,10 +139,10 @@ function noteText(note: UpdateBadgeNote): string | null {switch (note.kind) {case "none":return null;- case "release":+ case "available":return S.update.newVersion(note.version);- case "client":- return S.update.clientRestartToInstall(note.version);+ case "ready":+ return S.update.restartToUpdate(note.version);case "kernel":return S.agent.kernelOutdatedHint;case "skills":diff --git a/packages/web/src/lib/use-update-flow.ts b/packages/web/src/lib/use-update-flow.tsnew file mode 100644index 00000000..eeafcebd--- /dev/null+++ b/packages/web/src/lib/use-update-flow.ts@@ -0,0 +1,355 @@+/**+ * The live update flow: the store behind the update modal, the account-menu row and the+ * version-line badge, and the actions they call. `update-flow.ts` holds the pure state+ * machine; this file feeds it from the shared caches (`use-version-info.ts` for the server+ * release, `use-desktop-update.ts` for the shell's snapshot) and runs the requests.+ *+ * Everything the flow adds of its own is module level (a zustand vanilla store): the modal+ * may be closed mid-download and reopened from another surface, and the outcome of a+ * request has to reach the user wherever they are — in the modal when it is open, as a+ * toast otherwise. One owner drives the polling and the toasts: `useUpdateFlowOwner`,+ * mounted once by the modal in the app layout. Every other consumer is passive+ * (`useUpdateFlow`), reading the same stores through subscriptions.+ */+import { useEffect, useRef } from "react";+import { createStore, useStore } from "zustand";+import type { UpdateJobStatus } from "@prismshadow/penguin-server/api";+import * as api from "../api/endpoints";+import { S } from "./strings";+import { apiErrorText } from "./api-error";+import { toastError, toastInfo, toastSuccess } from "../components/ui/toast";+import {+ clientFlow,+ opensWithCheck,+ releaseFlow,+ updateModeFor,+ type FlowLocal,+ type UpdateFlow,+ type UpdateMode,+} from "./update-flow";+import {+ forceUpdateCheck,+ getVersionInfo,+ updateCheckOutcome,+ useVersionInfo,+} from "./use-version-info";+import {+ getDesktopUpdateStatus,+ isClientCheckPending,+ onClientCheckSettle,+ refreshDesktopUpdate,+ requestClientCheck,+ requestClientDownload,+ requestClientInstall,+ useDesktopUpdate,+} from "./use-desktop-update";+import { useAuth } from "../state/auth";++/** How often the running self-update job is asked where it is. */+const JOB_POLL_MS = 1_000;+/** How often the page asks whether the restarted server is back. */+const RESTART_POLL_MS = 1_000;+/** A restart that has not come back by then is reported; the page stops waiting. */+const RESTART_TIMEOUT_MS = 90_000;++interface FlowState extends FlowLocal {+ /** Set by the owner from the session; actions read it to pick the backend. */+ mode: UpdateMode;+ isAdmin: boolean;+ modalOpen: boolean;+ /** The server's self-update job as last polled (release mode). */+ job: UpdateJobStatus | null;+}++const store = createStore<FlowState>(() => ({+ mode: "none",+ isAdmin: false,+ modalOpen: false,+ checking: false,+ downloadRequested: false,+ restart: "none",+ job: null,+}));++/** The flow for the current caches and local state — the one computation every surface renders. */+function currentFlow(): UpdateFlow {+ const s = store.getState();+ // Nothing this session can act on (a browser signed into a desktop-mode server, and the+ // beat before the owner has read the session): the flow stays `unknown`, so the row, the+ // badge and the modal all render nothing. It must not fall through to the release flow —+ // the avatar's dot reads this without a mode gate of its own, and a dot leading to a menu+ // with no update row is exactly the dead end update-badges.ts forbids.+ if (s.mode === "none") return { kind: "unknown" };+ // The armed client check is the shell store's own flag: it spins the flow until the+ // shell's `checking` frame lands, exactly as `checking` does for the release lookup.+ if (s.mode === "client") {+ return clientFlow(getDesktopUpdateStatus(), { ...s, checking: isClientCheckPending() });+ }+ const { version, update } = getVersionInfo();+ return releaseFlow({ version, update, job: s.job, isAdmin: s.isAdmin }, s);+}++/** Outcomes that land while the modal is closed are toasted; open, the modal shows them. */+function quiet(): boolean {+ return store.getState().modalOpen;+}++export function openUpdateModal(): void {+ store.setState({ modalOpen: true });+ if (opensWithCheck(currentFlow())) void checkForUpdates();+}++/** Closing never cancels anything: a download in flight keeps going and reports through the row. */+export function closeUpdateModal(): void {+ store.setState({ modalOpen: false });+}++export async function checkForUpdates(): Promise<void> {+ const s = store.getState();+ if (s.checking) return;+ if (s.mode === "client") {+ await requestClientCheck();+ return;+ }+ store.setState({ checking: true });+ try {+ const outcome = updateCheckOutcome(await forceUpdateCheck());+ if (quiet()) return;+ if (outcome.kind === "disabled") toastInfo(S.update.checkDisabled);+ else if (outcome.kind === "failed") toastError(S.update.checkFailed);+ else if (outcome.kind === "found") toastSuccess(S.update.foundNew(outcome.latestVersion));+ else toastSuccess(S.update.upToDate);+ } catch (e) {+ if (!quiet()) toastError(apiErrorText(e));+ } finally {+ store.setState({ checking: false });+ }+}++/** The user's confirmation: fetch (and, on a server, install) the offered release. */+export async function downloadUpdate(): Promise<void> {+ const s = store.getState();+ if (s.downloadRequested) return;+ store.setState({ downloadRequested: true, restart: "none" });+ try {+ if (s.mode === "client") {+ await requestClientDownload();+ // The snapshot takes over from here (see the owner effect); the local flag only bridges+ // the gap until the shell's `downloading` frame lands.+ return;+ }+ // The status the POST answers with is the whole truth from here on — including a run+ // that is already over (no CLI to run answers `done`/`unsupported` at once). Keeping+ // the local flag past it would render `downloading` forever: releaseFlow reads the+ // flag before the finished job, and only a RUNNING job is ever polled.+ const job = await api.startUpdateJob();+ store.setState({ job, downloadRequested: false });+ } catch (e) {+ toastError(S.update.requestFailed(apiErrorText(e)));+ store.setState({ downloadRequested: false });+ }+}++/** The user's "restart and update". */+export async function installUpdate(): Promise<void> {+ const s = store.getState();+ try {+ if (s.mode === "client") {+ await requestClientInstall();+ store.setState({ restart: "requested" });+ return;+ }+ const res = await api.restartServer();+ store.setState({ restart: res.restarting ? "requested" : "manual" });+ } catch (e) {+ toastError(S.update.requestFailed(apiErrorText(e)));+ }+}++/** Passive read of the flow, for the row, the badge and the modal's rendering. */+export function useUpdateFlow(): {+ mode: UpdateMode;+ flow: UpdateFlow;+ modalOpen: boolean;+ isAdmin: boolean;+ /** The running version, for the modal's header and the row's chip. */+ currentVersion: string | null;+} {+ const state = useStore(store);+ const { version } = useVersionInfo(false);+ useDesktopUpdate(false, false);+ return {+ mode: state.mode,+ flow: currentFlow(),+ modalOpen: state.modalOpen,+ isAdmin: state.isAdmin,+ currentVersion:+ state.mode === "client"+ ? (getDesktopUpdateStatus()?.appVersion ?? null)+ : (version?.version ?? null),+ };+}++/**+ * The one owner: sets the mode from the session, drives the shell polling while the modal is+ * open or something moves, polls the running job, waits out a restart, and toasts the+ * outcomes that land while the modal is closed. Mounted once, by the update modal.+ */+export function useUpdateFlowOwner(): void {+ const { user, desktopMode, sessionVia } = useAuth();+ const mode = updateModeFor({ desktopMode, sessionVia });+ const isAdmin = user?.isAdmin === true;+ useEffect(() => {+ store.setState({ mode, isAdmin });+ }, [mode, isAdmin]);++ const state = useStore(store);+ // A run still in flight from before this page load (or from another tab): "continue in+ // background" has to survive a reload, and only the server knows what is running. A+ // FINISHED run is deliberately not adopted — its outcome was already reported where it+ // was started, and resurrecting it here would answer every later page load with a stale+ // failure instead of the release still on offer. Admin-only (so is the endpoint), once+ // per mount; a failure leaves the flow on the check, which it would have shown anyway.+ useEffect(() => {+ if (mode !== "release" || !isAdmin) return;+ void api+ .getUpdateJob()+ .then((job) => {+ if (job.state === "running" && store.getState().job === null) store.setState({ job });+ })+ .catch(() => undefined);+ }, [mode, isAdmin]);++ // The shell's snapshot: polled while the modal is open, and on its own while a check or+ // download moves (use-desktop-update's own rule), so a download sent to the background+ // still reports through the row. One passive refresh on load raises a badge for a release+ // offered or downloaded before this page opened.+ const { status } = useDesktopUpdate(mode === "client", state.modalOpen);+ useEffect(() => {+ if (mode === "client") refreshDesktopUpdate();+ }, [mode]);++ // A settled client check reports in the modal when it is open, as a toast otherwise.+ useEffect(() => {+ onClientCheckSettle((settle) => {+ if (quiet()) return;+ switch (settle.kind) {+ case "up-to-date":+ toastSuccess(S.update.upToDate);+ break;+ case "found":+ toastSuccess(+ settle.version !== null ? S.update.foundNew(settle.version) : S.update.foundNewUnnamed,+ );+ break;+ case "ready":+ toastSuccess(S.update.readyToast(settle.version));+ break;+ case "unsupported":+ toastInfo(+ settle.reason === "linux-not-appimage"+ ? S.update.unsupportedNonAppImage+ : S.update.unsupportedDev,+ );+ break;+ default:+ toastError(+ settle.message !== null+ ? S.update.clientUpdateFailed(settle.message)+ : S.update.checkFailed,+ );+ }+ });+ }, []);++ // The download request's bridge: once the shell reports the download (or anything else —+ // a stale frame answers with a re-announce), the local flag has done its job.+ const requestSeq = useRef<number | null>(null);+ useEffect(() => {+ if (mode !== "client") return;+ if (state.downloadRequested) {+ // -1 stands in for a snapshot without a seq (only the shell's very first frame): any+ // later frame carries one, so it still reads as movement.+ const seq = status?.seq ?? -1;+ if (requestSeq.current === null) requestSeq.current = seq;+ else if (seq !== requestSeq.current || status?.state === "downloading") {+ requestSeq.current = null;+ store.setState({ downloadRequested: false });+ }+ } else {+ requestSeq.current = null;+ }+ }, [mode, state.downloadRequested, status]);++ // A client download that lands while the modal is closed is announced; open, the modal+ // shows the restart step itself.+ const lastClientState = useRef<string | null>(null);+ useEffect(() => {+ if (mode !== "client") return;+ const now = status?.state ?? null;+ if (now === "downloaded" && lastClientState.current === "downloading" && !quiet()) {+ toastSuccess(S.update.readyToast(status?.version ?? null));+ }+ lastClientState.current = now;+ }, [mode, status]);++ // The running self-update job (release mode): polled until it ends, then announced when+ // the modal is closed.+ const running = mode === "release" && state.job?.state === "running";+ useEffect(() => {+ if (!running) return;+ const timer = setInterval(() => {+ void api+ .getUpdateJob()+ .then((job) => {+ // Only the tick that sees the run end announces it: a slow earlier tick landing+ // afterwards must not toast a second time.+ const wasRunning = store.getState().job?.state === "running";+ store.setState({ job, downloadRequested: false });+ if (!wasRunning || job.state !== "done" || job.result === undefined || quiet()) return;+ if (job.result.status === "updated") toastSuccess(S.update.readyToast(job.targetVersion));+ else if (job.result.status === "failed") toastError(S.update.failedToast);+ else toastInfo(S.update.unsupportedToast);+ })+ .catch(() => {+ // Transient: the next tick asks again (the job keeps running on the server).+ });+ }, JOB_POLL_MS);+ return () => clearInterval(timer);+ }, [running]);++ // The restart (release mode): the server goes down and comes back on the new release;+ // the page reloads once it answers again — after having seen it gone, or with another+ // version — and gives up after a while with a hint.+ const restarting = mode === "release" && state.restart === "requested";+ useEffect(() => {+ if (!restarting) return;+ const before = getVersionInfo().version?.version ?? null;+ const startedAt = Date.now();+ let sawDown = false;+ const giveUp = (): void => {+ store.setState({ restart: "manual" });+ toastError(S.update.restartTimedOut);+ };+ const timer = setInterval(() => {+ // The deadline is checked on every tick, not only on a failed one. A poll that keeps+ // SUCCEEDING is the case that hangs: the restart window fell between two ticks and+ // the relaunched server reports the same version (the update was already installed,+ // so `penguin update` only reinstalled it), or the restart never happened at all —+ // `sawDown` then stays false and nothing here would ever end the wait.+ if (Date.now() - startedAt > RESTART_TIMEOUT_MS) {+ giveUp();+ return;+ }+ void api+ .getVersion()+ .then((res) => {+ if (sawDown || (before !== null && res.version !== before)) window.location.reload();+ })+ .catch(() => {+ sawDown = true;+ });+ }, RESTART_POLL_MS);+ return () => clearInterval(timer);+ }, [restarting]);+}diff --git a/packages/web/src/lib/use-version-info.ts b/packages/web/src/lib/use-version-info.tsindex b35adfc3..a9554f59 100644--- a/packages/web/src/lib/use-version-info.ts+++ b/packages/web/src/lib/use-version-info.ts@@ -66,6 +66,11 @@ export interface VersionInfo {update: UpdateCheckResponse | null;}+/** The module cache as it stands, for callers outside React (the update flow's actions). */+export function getVersionInfo(): VersionInfo {+ return { version: versionCache, update: updateCache };+}+export function useVersionInfo(active: boolean): VersionInfo {// Initial state comes from the module cache, so a remounted sidebar (locale switch)// shows the version footer and the update dot immediately, with no second request.diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.tsindex 5bf20685..7d006a0d 100644--- a/packages/web/test/account-menu.test.ts+++ b/packages/web/test/account-menu.test.ts@@ -115,16 +115,16 @@ describe("the sidebar user menu", () => {expect(source).not.toContain("ChangePasswordDialog");});- it("keeps both update rows outside the settings dialog, in one slot under its entry", () => {- // Updating is deliberately not a settings page: the menu carries the check itself, and- // the two rows are mutually exclusive by their own gates (a desktop-mode server never- // offers the server check; a browser session against one gets neither).- expect(source).toContain("<ServerUpdateRow");- expect(source).toContain("<DesktopUpdateRow");- expect(source).toContain("<UpdateDialog");- // The row's install/announce dialogs hang off the Sidebar, which outlives the menu the- // click closes — mounting them in the rows would unmount them on that same click.- expect(source).toContain("setUpdateDialogOpen(true)");- expect(source).toContain("setClientInstallOpen(true)");+ it("keeps the one update row outside the settings dialog, opening the modal the layout mounts", () => {+ // Updating is deliberately not a settings page: the menu carries the entry itself. One+ // row serves both backends (the server release, the shell's own updater in the desktop+ // window) and hides itself where the session can update nothing; every click opens the+ // update modal, which is mounted by the app layout — not here, where the menu closing on+ // that same click would unmount it, and not on the draft page whose badge opens it too.+ expect(source).toContain("<UpdateRow");+ expect(source).toContain("openUpdateModal()");+ expect(source).not.toContain("<UpdateModal");+ expect(source).not.toContain("ServerUpdateRow");+ expect(source).not.toContain("DesktopUpdateRow");});});diff --git a/packages/web/test/desktop-update.test.ts b/packages/web/test/desktop-update.test.tsindex b8381b45..a900e1c7 100644--- a/packages/web/test/desktop-update.test.ts+++ b/packages/web/test/desktop-update.test.ts@@ -1,7 +1,7 @@/**- * desktop-update.ts unit tests: who gets the client-update row, what it renders per- * shell snapshot, and when an armed row-initiated check settles (one toast per- * outcome).+ * desktop-update.ts unit tests: who gets the client update surface at all, and when an+ * armed row-initiated check settles (one report per outcome — in the modal when it is+ * open, a toast otherwise).** offersClientUpdate is pinned in all four combinations for the same reason as* offersChangePassword next door: each single-field simplification fails a real case —@@ -15,7 +15,6 @@ import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";import {CLIENT_CHECK_TIMEOUT_MS,clientCheckSettle,- clientUpdateRow,offersClientUpdate,} from "../src/lib/desktop-update";@@ -33,73 +32,6 @@ const at = (rest: Partial<DesktopUpdateStatus> = {},): DesktopUpdateStatus => ({ appVersion: "0.2.3", seq: 1, state, ...rest });-describe("clientUpdateRow", () => {- it("renders disabled until the shell's first push lands", () => {- expect(clientUpdateRow(null)).toMatchObject({- labelKind: "unknown",- action: "none",- busy: false,- appVersion: null,- });- });-- it("offers the (re-)check for idle, up-to-date and error snapshots", () => {- for (const state of ["idle", "up-to-date", "error"] as const) {- expect(clientUpdateRow(at(state))).toMatchObject({- labelKind: "check",- action: "check",- busy: false,- appVersion: "0.2.3",- });- }- });-- it("spins on an armed check before the shell's checking frame lands", () => {- expect(clientUpdateRow(at("idle"), true)).toMatchObject({- labelKind: "checking",- action: "none",- busy: true,- });- // Once the shell reports its own busy/terminal states, the snapshot wins.- expect(clientUpdateRow(at("downloaded", { version: "0.3.0" }), true)).toMatchObject({- labelKind: "install",- });- });-- it("renders busy states without an action", () => {- expect(clientUpdateRow(at("checking"))).toMatchObject({- labelKind: "checking",- action: "none",- busy: true,- });- expect(clientUpdateRow(at("downloading", { version: "0.3.0", percent: 42 }))).toMatchObject({- labelKind: "downloading",- action: "none",- busy: true,- version: "0.3.0",- percent: 42,- });- });-- it("offers the install once a build is downloaded", () => {- expect(clientUpdateRow(at("downloaded", { version: "0.3.0" }))).toMatchObject({- labelKind: "install",- action: "install",- busy: false,- version: "0.3.0",- });- });-- it("disables the row for an unsupported form, naming the reason", () => {- expect(clientUpdateRow(at("unsupported", { reason: "linux-not-appimage" }))).toMatchObject({- labelKind: "unsupported",- action: "none",- busy: false,- unsupportedReason: "linux-not-appimage",- });- });-});-describe("clientCheckSettle", () => {it("stays open while checking, before any snapshot, or while the seq has not moved", () => {expect(clientCheckSettle(1, null, 3_000)).toBeNull();@@ -118,6 +50,11 @@ describe("clientCheckSettle", () => {expect(clientCheckSettle(1, at("downloading", { seq: 3, version: "0.3.0", percent: 1 }), 3_000),).toEqual({ kind: "found", version: "0.3.0" });+ // A check ends in an offer now (nothing is fetched until the user says so): found too.+ expect(clientCheckSettle(1, at("available", { seq: 3, version: "0.3.0" }), 3_000)).toEqual({+ kind: "found",+ version: "0.3.0",+ });expect(clientCheckSettle(1, at("downloaded", { seq: 3, version: "0.3.0" }), 3_000)).toEqual({kind: "ready",version: "0.3.0",diff --git a/packages/web/test/update-badges.test.ts b/packages/web/test/update-badges.test.tsindex a7402bd2..d0cbc3d1 100644--- a/packages/web/test/update-badges.test.ts+++ b/packages/web/test/update-badges.test.ts@@ -1,148 +1,58 @@/*** Update-badge gate unit tests: what raises a notification dot, and what an anchor over- * several trails says. The rule every case here defends is that a dot must end in a control the user- * can actually reach — so the release gate is closed wherever the sidebar does not offer the- * release row, a fail-soft check raises nothing, and a download still in flight is not a badge.+ * several trails says. The rule every case here defends is that a dot must end in a control+ * the user can actually reach — so the software gate reads the update flow (which offers+ * nothing where the session can update nothing), and a download still in flight is not a+ * badge.** The Agent-kernel gate used to live here as `anyKernelOutdated`. It moved to `todo-badges.ts`* (and is covered there, as `kernelUpdateTodo`) when its page grew a notice with a way down: a* gate that can be dismissed has to name WHAT is waiting, not just whether something is.*/import { describe, expect, it } from "vitest";-import type { DesktopUpdateStatus, UpdateCheckResponse } from "@prismshadow/penguin-server/api";-import { badgeNote, releaseUpdate, softwareUpdate } from "../src/lib/update-badges";--function check(overrides: Partial<UpdateCheckResponse>): UpdateCheckResponse {- return {- currentVersion: "0.1.5",- buildDate: null,- latestVersion: null,- updateAvailable: false,- releaseUrl: null,- publishedAt: null,- checkedAt: "2026-08-26T00:00:00.000Z",- ...overrides,- };-}--const AVAILABLE = check({ updateAvailable: true, latestVersion: "0.2.0" });--function shell(overrides: Partial<DesktopUpdateStatus>): DesktopUpdateStatus {- return { appVersion: "0.1.5", state: "idle", ...overrides };-}--describe("releaseUpdate", () => {- it("names the newer release", () => {- expect(releaseUpdate(AVAILABLE)).toBe("0.2.0");- });-- it("raises nothing before the check has answered", () => {- expect(releaseUpdate(null)).toBeNull();- });-- it("raises nothing when the running version is current", () => {- expect(releaseUpdate(check({ latestVersion: "0.1.5" }))).toBeNull();- });-- it("raises nothing when the lookup failed — a fail-soft error is not an update", () => {- // The response is HTTP 200 with `error` set; updateAvailable stays false, so no badge and- // no noise. The user hears about a failure only from the manual check they asked for.- expect(releaseUpdate(check({ error: "network" }))).toBeNull();- expect(releaseUpdate(check({ error: "rate_limited" }))).toBeNull();- });-- it("raises nothing when checks are turned off (PENGUIN_UPDATE_CHECK=off)", () => {- expect(releaseUpdate(check({ disabled: true }))).toBeNull();- });-- it("raises nothing for an available-but-unnamed release", () => {- // Every tooltip along the trail names the version; without one the dot would lead to a- // versionless reminder.- expect(releaseUpdate(check({ updateAvailable: true }))).toBeNull();- });-});+import { badgeNote, softwareUpdate } from "../src/lib/update-badges";describe("softwareUpdate", () => {- const base = { releaseRowOffered: true, clientRowOffered: false, clientStatus: null };-- it("offers the release when the menu holds the release row", () => {- expect(softwareUpdate({ ...base, update: AVAILABLE })).toEqual({- kind: "release",- version: "0.2.0",- });- });-- it("stays silent about a release the running mode never offers a row for", () => {- // Desktop mode hides the server-update row and updates the client through the shell, so a- // dot for a newer server release there would point at nothing.- expect(softwareUpdate({ ...base, releaseRowOffered: false, update: AVAILABLE })).toBeNull();- });-- it("offers a downloaded client build waiting to be installed", () => {+ it("offers a release the flow has on offer", () => {expect(- softwareUpdate({- releaseRowOffered: false,- clientRowOffered: true,- update: null,- clientStatus: shell({ state: "downloaded", version: "0.3.0" }),- }),- ).toEqual({ kind: "client", version: "0.3.0" });+ softwareUpdate({ kind: "available", version: "0.3.0", releaseUrl: null, canInstall: true }),+ ).toEqual({ kind: "available", version: "0.3.0" });});- it("does not badge a client download still in flight", () => {- // The row shows its progress; there is nothing to act on until it lands, and a badge the- // user cannot clear by acting on it is noise.- expect(- softwareUpdate({- releaseRowOffered: false,- clientRowOffered: true,- update: null,- clientStatus: shell({ state: "downloading", version: "0.3.0", percent: 40 }),- }),- ).toBeNull();- });-- it("does not badge an idle, checking, up-to-date or unsupported shell", () => {- for (const state of ["idle", "checking", "up-to-date", "unsupported", "error"] as const) {- expect(- softwareUpdate({- releaseRowOffered: false,- clientRowOffered: true,- update: null,- clientStatus: shell({ state }),- }),- state,- ).toBeNull();- }+ it("offers a downloaded or installed release waiting for its restart, unnamed included", () => {+ expect(softwareUpdate({ kind: "ready", version: "0.3.0", restart: "auto" })).toEqual({+ kind: "ready",+ version: "0.3.0",+ });+ expect(softwareUpdate({ kind: "ready", version: null, restart: "manual" })).toEqual({+ kind: "ready",+ version: null,+ });});- it("stays silent when neither row is offered", () => {- // A browser signed into a desktop-mode server gets neither the release row nor the client- // row (offersClientUpdate's pair), so it gets no software badge either.+ it("does not badge a download still in flight", () => {+ // The row shows its progress; there is nothing for the user to do until it lands, and a+ // badge the user cannot clear by acting on it is noise.expect(- softwareUpdate({- releaseRowOffered: false,- clientRowOffered: false,- update: AVAILABLE,- clientStatus: shell({ state: "downloaded", version: "0.3.0" }),- }),+ softwareUpdate({ kind: "downloading", version: "0.3.0", percent: 40, phase: null }),).toBeNull();});- it("prefers the release when a mode somehow offers both rows", () => {+ it("stays silent for every other state — nothing known, current, checking, failed, unsupported", () => {+ expect(softwareUpdate({ kind: "unknown" })).toBeNull();+ expect(softwareUpdate({ kind: "checking" })).toBeNull();+ expect(softwareUpdate({ kind: "up-to-date", version: "0.2.9" })).toBeNull();+ expect(softwareUpdate({ kind: "disabled" })).toBeNull();expect(- softwareUpdate({- releaseRowOffered: true,- clientRowOffered: true,- update: AVAILABLE,- clientStatus: shell({ state: "downloaded", version: "0.3.0" }),- }),- ).toEqual({ kind: "release", version: "0.2.0" });+ softwareUpdate({ kind: "error", message: null, detail: null, retry: "check" }),+ ).toBeNull();+ expect(softwareUpdate({ kind: "unsupported", reason: { code: "dev" } })).toBeNull();+ expect(softwareUpdate({ kind: "restarting", version: "0.3.0" })).toBeNull();});});describe("badgeNote", () => {- const release = { kind: "release", version: "0.2.0" } as const;+ const release = { kind: "available", version: "0.2.0" } as const;const kernel = { kind: "kernel" } as const;const errors = { kind: "errors", count: 2 } as const;@@ -155,8 +65,8 @@ describe("badgeNote", () => {});it("carries a client build's version through, null included", () => {- expect(badgeNote([{ kind: "client", version: null }])).toEqual({- kind: "client",+ expect(badgeNote([{ kind: "ready", version: null }])).toEqual({+ kind: "ready",version: null,});});diff --git a/packages/web/test/update-flow.test.ts b/packages/web/test/update-flow.test.tsnew file mode 100644index 00000000..552dfcb3--- /dev/null+++ b/packages/web/test/update-flow.test.ts@@ -0,0 +1,302 @@+/**+ * update-flow.ts unit tests: the one state machine behind the update modal, the account-menu+ * row and the version-line badge, fed by the two backends.+ *+ * The rules pinned here are the ones a user sees: nothing is fetched until they confirm (a+ * check ends in `available`, never `downloading`), a download sent to the background still+ * reports through the row, an installed release waits for an explicit restart — and where the+ * process cannot be restarted from the page, the modal says so instead of pretending.+ */+import { describe, expect, it } from "vitest";+import type {+ DesktopUpdateStatus,+ UpdateCheckResponse,+ UpdateJobStatus,+} from "@prismshadow/penguin-server/api";+import {+ NO_LOCAL,+ clientFlow,+ opensWithCheck,+ releaseFlow,+ releaseUrlFor,+ updateModeFor,+ updateRowModel,+ versionBadgeFor,+} from "../src/lib/update-flow";+import type { FlowLocal } from "../src/lib/update-flow";++const check = (over: Partial<UpdateCheckResponse> = {}): UpdateCheckResponse => ({+ currentVersion: "0.2.9",+ buildDate: "2026-08-28",+ latestVersion: "0.3.0",+ updateAvailable: true,+ releaseUrl: "https://github.com/Prism-Shadow/penguin-harness/releases/tag/v0.3.0",+ publishedAt: null,+ checkedAt: "2026-08-28T00:00:00.000Z",+ ...over,+});++const job = (over: Partial<UpdateJobStatus> = {}): UpdateJobStatus => ({+ state: "idle",+ targetVersion: "0.3.0",+ output: "",+ ...over,+});++const shell = (over: Partial<DesktopUpdateStatus> = {}): DesktopUpdateStatus => ({+ appVersion: "0.2.9",+ state: "idle",+ ...over,+});++const release = (+ update: UpdateCheckResponse | null,+ j: UpdateJobStatus | null = null,+ local: Partial<FlowLocal> = {},+ isAdmin = true,+) => releaseFlow({ version: null, update, job: j, isAdmin }, { ...NO_LOCAL, ...local });++describe("updateModeFor", () => {+ it("is the shell's own window, an ordinary server, or nothing at all", () => {+ expect(updateModeFor({ desktopMode: true, sessionVia: "desktop" })).toBe("client");+ expect(updateModeFor({ desktopMode: false, sessionVia: "password" })).toBe("release");+ // A browser signed into a desktop-mode server can update neither.+ expect(updateModeFor({ desktopMode: true, sessionVia: "password" })).toBe("none");+ });+});++describe("releaseFlow (an ordinary server)", () => {+ it("knows nothing until the check answers, and spins while a manual check runs", () => {+ expect(release(null)).toEqual({ kind: "unknown" });+ expect(release(null, null, { checking: true })).toEqual({ kind: "checking" });+ });++ it("reads the check: disabled, failed, offered, or current", () => {+ expect(release(check({ disabled: true, updateAvailable: false }))).toEqual({+ kind: "disabled",+ });+ expect(release(check({ error: "network", updateAvailable: false }))).toMatchObject({+ kind: "error",+ retry: "check",+ });+ expect(release(check())).toEqual({+ kind: "available",+ version: "0.3.0",+ releaseUrl: check().releaseUrl,+ canInstall: true,+ });+ expect(release(check({ updateAvailable: false, latestVersion: "0.2.9" }))).toEqual({+ kind: "up-to-date",+ version: "0.2.9",+ });+ });++ it("offers a non-admin the release without the install", () => {+ expect(release(check(), null, {}, false)).toMatchObject({+ kind: "available",+ canInstall: false,+ });+ });++ it("bridges the download request until the job reports, then follows the job's progress", () => {+ expect(release(check(), null, { downloadRequested: true })).toEqual({+ kind: "downloading",+ version: "0.3.0",+ percent: null,+ phase: "resolving",+ });+ expect(release(check(), job({ state: "running", phase: "downloading", percent: 42 }))).toEqual({+ kind: "downloading",+ version: "0.3.0",+ percent: 42,+ phase: "downloading",+ });+ // A phase without a percentage is an indeterminate bar with the phase's caption.+ expect(release(check(), job({ state: "running", phase: "installing", percent: null }))).toEqual(+ { kind: "downloading", version: "0.3.0", percent: null, phase: "installing" },+ );+ });++ it("waits for the restart once the job installed, and says when that restart is the user's", () => {+ const done = job({+ state: "done",+ result: { status: "updated", output: "…", needsRestart: true },+ });+ expect(release(check(), done)).toEqual({ kind: "ready", version: "0.3.0", restart: "auto" });+ expect(release(check(), done, { restart: "manual" })).toEqual({+ kind: "ready",+ version: "0.3.0",+ restart: "manual",+ });+ expect(release(check(), done, { restart: "requested" })).toEqual({+ kind: "restarting",+ version: "0.3.0",+ });+ });++ it("surfaces a failed run with the command's output and a download retry", () => {+ const failed = job({+ state: "done",+ output: "Upgrade failed; the previous install was left in place.",+ result: {+ status: "failed",+ output: "Upgrade failed; the previous install was left in place.",+ needsRestart: false,+ },+ });+ expect(release(check(), failed)).toEqual({+ kind: "error",+ message: null,+ detail: "Upgrade failed; the previous install was left in place.",+ retry: "download",+ });+ });++ it("names why an install cannot update itself", () => {+ const notCli = job({+ state: "done",+ result: {+ status: "unsupported",+ reason: "not_launched_via_cli",+ output: "",+ needsRestart: false,+ },+ });+ expect(release(check(), notCli)).toEqual({+ kind: "unsupported",+ reason: { code: "not_launched_via_cli" },+ });+ const refused = job({+ state: "done",+ result: { status: "unsupported", output: "runs from a source checkout", needsRestart: false },+ });+ expect(release(check(), refused)).toEqual({+ kind: "unsupported",+ reason: { code: "cli_refused", detail: "runs from a source checkout" },+ });+ });+});++describe("clientFlow (the desktop shell's own window)", () => {+ it("knows nothing before the shell's first push, and spins on an armed check", () => {+ expect(clientFlow(null, NO_LOCAL)).toEqual({ kind: "unknown" });+ expect(clientFlow(null, { ...NO_LOCAL, checking: true })).toEqual({ kind: "checking" });+ expect(clientFlow(shell(), { ...NO_LOCAL, checking: true })).toEqual({ kind: "checking" });+ });++ it("offers a found release with its Releases page — nothing is fetched yet", () => {+ expect(clientFlow(shell({ state: "available", version: "0.3.0" }), NO_LOCAL)).toEqual({+ kind: "available",+ version: "0.3.0",+ releaseUrl: releaseUrlFor("0.3.0"),+ canInstall: true,+ });+ });++ it("bridges the download request until the shell's downloading frame, then follows its percentage", () => {+ expect(+ clientFlow(shell({ state: "available", version: "0.3.0" }), {+ ...NO_LOCAL,+ downloadRequested: true,+ }),+ ).toEqual({ kind: "downloading", version: "0.3.0", percent: null, phase: null });+ expect(+ clientFlow(shell({ state: "downloading", version: "0.3.0", percent: 42 }), NO_LOCAL),+ ).toEqual({ kind: "downloading", version: "0.3.0", percent: 42, phase: null });+ });++ it("waits for the restart once the build is downloaded, and reports the restart itself", () => {+ expect(clientFlow(shell({ state: "downloaded", version: "0.3.0" }), NO_LOCAL)).toEqual({+ kind: "ready",+ version: "0.3.0",+ restart: "auto",+ });+ expect(+ clientFlow(shell({ state: "downloaded", version: "0.3.0" }), {+ ...NO_LOCAL,+ restart: "requested",+ }),+ ).toEqual({ kind: "restarting", version: "0.3.0" });+ });++ it("carries the shell's own failure text, and names why a form cannot update itself", () => {+ expect(clientFlow(shell({ state: "error", message: "sha512 mismatch" }), NO_LOCAL)).toEqual({+ kind: "error",+ message: "sha512 mismatch",+ detail: null,+ retry: "check",+ });+ expect(+ clientFlow(shell({ state: "unsupported", reason: "linux-not-appimage" }), NO_LOCAL),+ ).toEqual({ kind: "unsupported", reason: { code: "linux-not-appimage" } });+ expect(clientFlow(shell({ state: "unsupported", reason: "dev" }), NO_LOCAL)).toEqual({+ kind: "unsupported",+ reason: { code: "dev" },+ });+ });+});++describe("opensWithCheck", () => {+ it("checks on opening when nothing is known, the answer is 'current', or the last check failed", () => {+ expect(opensWithCheck({ kind: "unknown" })).toBe(true);+ expect(opensWithCheck({ kind: "up-to-date", version: "0.2.9" })).toBe(true);+ expect(opensWithCheck({ kind: "error", message: null, detail: null, retry: "check" })).toBe(+ true,+ );+ });++ it("does not disturb an offer, a download, a ready build, or a failed download", () => {+ expect(+ opensWithCheck({ kind: "available", version: "0.3.0", releaseUrl: null, canInstall: true }),+ ).toBe(false);+ expect(+ opensWithCheck({ kind: "downloading", version: "0.3.0", percent: 10, phase: null }),+ ).toBe(false);+ expect(opensWithCheck({ kind: "ready", version: "0.3.0", restart: "auto" })).toBe(false);+ expect(opensWithCheck({ kind: "error", message: null, detail: "x", retry: "download" })).toBe(+ false,+ );+ });+});++describe("updateRowModel and versionBadgeFor", () => {+ it("spins while something moves, dots when something waits, and reads 'check' otherwise", () => {+ expect(updateRowModel({ kind: "unknown" })).toMatchObject({+ label: "check",+ busy: false,+ dot: false,+ });+ expect(updateRowModel({ kind: "checking" })).toMatchObject({ label: "checking", busy: true });+ expect(+ updateRowModel({ kind: "available", version: "0.3.0", releaseUrl: null, canInstall: true }),+ ).toMatchObject({ label: "available", version: "0.3.0", dot: true, busy: false });+ expect(+ updateRowModel({ kind: "downloading", version: "0.3.0", percent: 42, phase: null }),+ ).toMatchObject({ label: "downloading", percent: 42, busy: true, dot: false });+ expect(updateRowModel({ kind: "ready", version: "0.3.0", restart: "auto" })).toMatchObject({+ label: "ready",+ dot: true,+ });+ expect(updateRowModel({ kind: "restarting", version: null })).toMatchObject({+ label: "restarting",+ busy: true,+ });+ expect(updateRowModel({ kind: "unsupported", reason: { code: "dev" } })).toMatchObject({+ label: "unsupported",+ busy: false,+ dot: false,+ });+ });++ it("badges the version line for an offer, a background download and a pending restart only", () => {+ expect(versionBadgeFor({ kind: "unknown" })).toBeNull();+ expect(versionBadgeFor({ kind: "up-to-date", version: "0.2.9" })).toBeNull();+ expect(+ versionBadgeFor({ kind: "available", version: "0.3.0", releaseUrl: null, canInstall: true }),+ ).toBe("available");+ expect(+ versionBadgeFor({ kind: "downloading", version: "0.3.0", percent: null, phase: null }),+ ).toBe("downloading");+ expect(versionBadgeFor({ kind: "ready", version: "0.3.0", restart: "manual" })).toBe("ready");+ });+});