Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web,server,desktop): update the desktop client from the account menu (#386)

Yaowei Zheng812c4d62a180
diff --git a/changelog/unreleased/2026-08-20-client-update-button.md b/changelog/unreleased/2026-08-20-client-update-button.md
new file mode 100644
index 00000000..7b2738a9
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-client-update-button.md
@@ -0,0 +1,20 @@
+# Update the desktop client from the account menu
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `web`, `server`, `desktop`, `docs`
+- **PR:** [#386](https://github.com/Prism-Shadow/penguin-harness/pull/386)
+
+[中文版](2026-08-20-client-update-button.zh.md)
+
+Added a client-update row to the sidebar user menu of the desktop shell's own window — the slot the server update reminder leaves empty in desktop mode, where System settings has no Updates page. The row drives the shell's electron-updater end to end: check, background download with progress, then a confirmed restart-to-install (the same interruption warning as the shell's native prompt), with the installed client version shown alongside.
+
+## Details
+
+- The row appears only in the shell's own window (`desktopMode` and a `desktop`-via session together, the change-password rule inverted): a browser signed into the same desktop-mode server can neither read the machine's updater state nor restart its GUI app. The server enforces the same pair on the routes.
+- New desktop-mode API under `/api/desktop/update` (cookie-authed, unlike the shell's Bearer-token shutdown route): `GET` serves the shell's updater snapshot, `POST /check` and `POST /install` relay commands to the shell. Without a listening shell the commands answer 503 `shell_unreachable`.
+- The shell and the embedded server exchange these frames over the existing utilityProcess message port; the window itself remains a plain browser with no preload and no renderer IPC, every capability flowing through the server's HTTP API as before.
+- A downloaded build waits undisturbed: automatic re-checks stand down while one is pending (a re-download would invalidate the package on disk under the install button), and transient events — a check flickering by, its network failure — no longer hide the restart-to-install step.
+- A row-initiated check reports exactly one outcome as a toast — found (download starts by itself), already downloaded and waiting, already up to date, unsupported, or failed — matching the manual-check contract of System settings → Updates. A failure toast carries the shell's own reason where the updater gave one, so a download rejected by its checksum or its signature does not read as a network hiccup. Unsupported forms (dev run, non-AppImage Linux install) render the row disabled, with the reason as the tooltip of a wrapper rather than of the disabled control itself — a disabled button is dispatched no pointer events and would never open one.
+- The native menu flow (Check for Updates…, its dialogs, the restart prompt on download) was left unchanged.
+- The Web App guide gained a paragraph on the row, in both languages.
diff --git a/changelog/unreleased/2026-08-20-client-update-button.zh.md b/changelog/unreleased/2026-08-20-client-update-button.zh.md
new file mode 100644
index 00000000..7d0d349d
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-client-update-button.zh.md
@@ -0,0 +1,20 @@
+# 在账户菜单里更新桌面客户端
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `web`, `server`, `desktop`, `docs`
+- **PR:** [#386](https://github.com/Prism-Shadow/penguin-harness/pull/386)
+
+[English](2026-08-20-client-update-button.md)
+
+在桌面 shell 自身窗口的侧边栏用户菜单中新增了客户端更新行——正是服务端更新提醒行在桌面模式下空出的那个位置,桌面模式的系统设置里没有更新页。该行端到端驱动 shell 的 electron-updater:检查、带进度的后台下载、经确认的重启安装(与 shell 原生提示同样的「打断运行中任务」警告),并同排展示当前安装的客户端版本。
+
+## 细节
+
+- 该行只出现在 shell 自身窗口(`desktopMode` 与 `desktop` 来源会话两个条件同时成立,即修改密码规则的反向应用):通过浏览器登录同一桌面模式服务器的会话既读不到本机的更新状态,也无法重启他人的 GUI 应用。服务端在路由上强制执行同一对条件。
+- 新增桌面模式 API `/api/desktop/update`(Cookie 鉴权,不同于 shell 的 Bearer token shutdown 路由):`GET` 返回 shell 的更新快照,`POST /check` 与 `POST /install` 把命令转发给 shell。没有 shell 在听时命令返回 503 `shell_unreachable`。
+- shell 与内嵌服务器通过既有的 utilityProcess 消息端口交换这些帧;窗口本身仍是纯浏览器环境,没有 preload、没有渲染进程 IPC,一切能力照旧经服务器 HTTP API 流转。
+- 已下载的版本安然等待安装:有版本待装时自动再检查会主动停下(重新下载会让安装按钮之下的磁盘安装包失效),而一闪而过的检查、检查的网络失败等瞬态事件也不再掩盖「重启安装」这一步。
+- 由该行发起的检查以 toast 精确报告一次结果——发现新版本(自动开始下载)、已下载待装、已是最新、不支持自更新、或检查失败——与系统设置「更新」页手动检查的约定一致。更新器给出了原因时,失败 toast 会带上 shell 自己的说法,因此被校验和或签名拒绝的下载不会被读成一次网络抖动。不支持自更新的形态(开发运行、非 AppImage 的 Linux 安装)渲染为禁用行,原因挂在外层元素的 tooltip 上而非禁用控件本身——禁用按钮收不到指针事件,自身的 tooltip 永远不会弹出。
+- 原生菜单流程(Check for Updates…、其对话框、下载完成后的重启提示)保持不变。
+- Web App 指南新增了介绍该行的段落,中英文各一份。
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index 7a6830cc..5c458c6e 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -39,7 +39,8 @@ import { applyLoginShellEnv } from "./login-shell-env.js";
import { installAppMenu } from "./menu.js";
import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";
import type { EmbeddedServer } from "./server-process.js";
-import { initUpdater } from "./updater.js";
+import { getUpdaterStatus, handleUpdaterCommand, initUpdater, onUpdaterStatus } from "./updater.js";
+import { parseUpdaterCommand, updaterStatusMessage } from "./updater-status.js";
import {
desktopLoginUrl,
isAppUrl,
@@ -147,6 +148,22 @@ function createWindow(url: string): void {
void win.loadURL(url);
}
+/**
+ * Client-update relay over the utilityProcess port: forward the account-menu row's
+ * check/install frames to the updater, push every status fold back (plus the current
+ * snapshot now — the fresh child, restarts included, must not start blind). The
+ * subscription dies with the child; the next start wires the next one.
+ */
+function wireUpdaterRelay(child: EmbeddedServer["child"]): void {
+ child.on("message", (message: unknown) => {
+ const action = parseUpdaterCommand(message);
+ if (action !== null) handleUpdaterCommand(action);
+ });
+ const unsubscribe = onUpdaterStatus((status) => child.postMessage(updaterStatusMessage(status)));
+ child.on("exit", () => unsubscribe());
+ child.postMessage(updaterStatusMessage(getUpdaterStatus()));
+}
+
/** Starts (or restarts) the embedded server and points the window at desktop-login. */
async function startServerAndWindow(dataRoot: string): Promise<void> {
const started = await startEmbeddedServer({
@@ -157,6 +174,7 @@ async function startServerAndWindow(dataRoot: string): Promise<void> {
});
server = started;
appOrigin = started.origin;
+ wireUpdaterRelay(started.child);
// A run that stays up for a minute is healthy: reset the restart budget so a crash
// days later starts a fresh 1s/2s/4s ladder instead of hitting the cap immediately.
const healthyTimer = setTimeout(() => {
diff --git a/packages/desktop/src/update-support.ts b/packages/desktop/src/update-support.ts
index 8b9a17e4..a5276959 100644
--- a/packages/desktop/src/update-support.ts
+++ b/packages/desktop/src/update-support.ts
@@ -1,6 +1,6 @@
/**
* Whether this running form can update itself (pure; no Electron import, so it unit-tests
- * directly). See design § "桌面端原型 · 自动更新".
+ * directly).
*
* electron-updater can only replace the forms it installed: the NSIS installer on
* Windows, the app bundle on macOS, and an AppImage on Linux. A `.deb` belongs to the
diff --git a/packages/desktop/src/updater-status.ts b/packages/desktop/src/updater-status.ts
new file mode 100644
index 00000000..3cc05fd7
--- /dev/null
+++ b/packages/desktop/src/updater-status.ts
@@ -0,0 +1,88 @@
+/**
+ * Updater status tracking (pure; no Electron import, so it unit-tests directly).
+ *
+ * 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.
+ *
+ * Two 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).
+ * - 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`.
+ */
+import type {
+ DesktopUpdateStatus,
+ DesktopUpdaterCommandMessage,
+ DesktopUpdaterStatusMessage,
+} from "@prismshadow/penguin-server/api";
+
+/** electron-updater's events, reduced to what the status needs. */
+export type UpdaterEvent =
+ | { kind: "unsupported"; reason: "dev" | "linux-not-appimage" }
+ | { kind: "checking" }
+ | { kind: "not-available" }
+ | { kind: "available"; version: string }
+ | { kind: "progress"; percent: number }
+ | { kind: "downloaded"; version: string }
+ | { kind: "error"; message: string };
+
+/** Before any event: the app is simply running its installed version. */
+export function initialUpdateStatus(appVersion: string): DesktopUpdateStatus {
+ return { appVersion, state: "idle" };
+}
+
+/** Folds one updater event into the snapshot (see the module comment for the suppression rules). */
+export function nextUpdateStatus(prev: DesktopUpdateStatus, ev: UpdaterEvent): DesktopUpdateStatus {
+ const { appVersion } = prev;
+ if (prev.state === "downloaded") {
+ const replacement =
+ (ev.kind === "available" || 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.version === prev.version) return prev;
+ }
+ switch (ev.kind) {
+ case "unsupported":
+ return { appVersion, state: "unsupported", reason: ev.reason };
+ case "checking":
+ return { appVersion, state: "checking" };
+ case "not-available":
+ return { appVersion, state: "up-to-date" };
+ case "available":
+ return { appVersion, state: "downloading", version: ev.version, percent: 0 };
+ case "progress":
+ // A progress tick outside a download (stale timer) must not fabricate one.
+ return prev.state === "downloading"
+ ? { appVersion, state: "downloading", version: prev.version, percent: ev.percent }
+ : prev;
+ case "downloaded":
+ return { appVersion, state: "downloaded", version: ev.version };
+ case "error":
+ return { appVersion, state: "error", message: ev.message };
+ }
+}
+
+/** Wraps a snapshot for the port push. */
+export function updaterStatusMessage(status: DesktopUpdateStatus): DesktopUpdaterStatusMessage {
+ return { type: "desktop-updater-status", status };
+}
+
+/** Validates one server-relayed command frame off the port. */
+export function parseUpdaterCommand(data: unknown): DesktopUpdaterCommandMessage["action"] | null {
+ if (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;
+}
diff --git a/packages/desktop/src/updater.ts b/packages/desktop/src/updater.ts
index 9594d80a..a0884b1f 100644
--- a/packages/desktop/src/updater.ts
+++ b/packages/desktop/src/updater.ts
@@ -1,16 +1,18 @@
/**
- * Auto-update (design § "桌面端原型 · 自动更新").
+ * Auto-update.
*
* electron-updater against the GitHub Releases feed the build publishes
- * (`latest*.yml` + `.blockmap` ship as Release assets). The shell deliberately exposes
- * updates through **native UI only** — an app-menu item plus dialogs — because it injects
- * no IPC channel into the page; the Web App keeps hiding its own self-update entry in
- * desktop mode.
+ * (`latest*.yml` + `.blockmap` ship as Release assets). Updates surface in two places:
+ * the native app-menu item with its dialogs, and the account menu of the shell's own
+ * window — fed over the utilityProcess port to the embedded server (main.ts pushes each
+ * 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
- * follows — a manual action that answers with silence reads as broken.
+ * 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.
*
* 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
@@ -20,7 +22,10 @@
import { app, dialog, shell } from "electron";
import type { BrowserWindow } from "electron";
import electronUpdater from "electron-updater";
+import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";
import { feedUrlOverride, updateSupport } from "./update-support.js";
+import { initialUpdateStatus, nextUpdateStatus } from "./updater-status.js";
+import type { UpdaterEvent } from "./updater-status.js";
const { autoUpdater } = electronUpdater;
@@ -38,6 +43,78 @@ function log(line: string): void {
let manualCheckInFlight = false;
let downloadedVersion: string | null = null;
+// --- status relay (the account-menu row's data source) -----------------------
+
+let status: DesktopUpdateStatus = initialUpdateStatus(app.getVersion());
+let statusSeq = 0;
+const statusListeners = new Set<(status: DesktopUpdateStatus) => void>();
+
+/** Folds one event into the snapshot, stamps the seq and pushes it to every subscriber. */
+function emitStatus(ev: UpdaterEvent): void {
+ status = { ...nextUpdateStatus(status, ev), seq: ++statusSeq };
+ for (const listener of statusListeners) listener(status);
+}
+
+/**
+ * Re-pushes the current snapshot with a fresh seq — the NACK for a relayed check that
+ * changes nothing (already downloading, or a build already waiting): the row's armed
+ * check settles on what is, instead of waiting out its timeout.
+ */
+function reannounceStatus(): void {
+ status = { ...status, seq: ++statusSeq };
+ for (const listener of statusListeners) listener(status);
+}
+
+/** Current snapshot, for the initial push after a server (re)start. */
+export function getUpdaterStatus(): DesktopUpdateStatus {
+ return status;
+}
+
+/** Subscribes to every status fold; returns the unsubscribe (main.ts drops it when the server child exits). */
+export function onUpdaterStatus(listener: (status: DesktopUpdateStatus) => void): () => void {
+ statusListeners.add(listener);
+ return () => statusListeners.delete(listener);
+}
+
+/**
+ * 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.
+ */
+export function handleUpdaterCommand(action: "check" | "install"): void {
+ if (action === "check") {
+ const support = updateSupport({
+ isPackaged: app.isPackaged,
+ platform: process.platform,
+ env: process.env,
+ });
+ if (!support.supported) {
+ emitStatus({ kind: "unsupported", reason: support.reason });
+ return;
+ }
+ if (
+ downloadedVersion !== null ||
+ status.state === "downloading" ||
+ status.state === "checking"
+ ) {
+ reannounceStatus();
+ return;
+ }
+ void check();
+ return;
+ }
+ if (downloadedVersion === null) {
+ log("install requested with nothing downloaded (stale row); ignoring");
+ return;
+ }
+ // Same path as the dialog's "Restart now": quitAndInstall goes through the normal
+ // quit sequence, so the shell's before-quit hook still stops the embedded server
+ // gracefully before the files are replaced.
+ autoUpdater.quitAndInstall();
+}
+
/** Whether the "Check for Updates…" menu item should be enabled at all. */
export function updatesAvailableInThisForm(): boolean {
return updateSupport({ isPackaged: app.isPackaged, platform: process.platform, env: process.env })
@@ -56,6 +133,7 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
});
if (!support.supported) {
log(`disabled (${support.reason})`);
+ emitStatus({ kind: "unsupported", reason: support.reason });
return;
}
@@ -74,9 +152,13 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
log(`feed override: ${override}`);
}
- autoUpdater.on("checking-for-update", () => log("checking"));
+ autoUpdater.on("checking-for-update", () => {
+ log("checking");
+ emitStatus({ kind: "checking" });
+ });
autoUpdater.on("update-not-available", (info: { version: string }) => {
log(`up to date (${info.version})`);
+ emitStatus({ kind: "not-available" });
if (manualCheckInFlight) {
manualCheckInFlight = false;
void dialog.showMessageBox({
@@ -89,6 +171,7 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
});
autoUpdater.on("update-available", (info: { version: string }) => {
log(`update available: ${info.version} (downloading)`);
+ emitStatus({ kind: "available", version: info.version });
if (manualCheckInFlight) {
manualCheckInFlight = false;
void dialog.showMessageBox({
@@ -102,14 +185,17 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
});
autoUpdater.on("download-progress", (p: { percent: number }) => {
log(`downloading ${Math.round(p.percent)}%`);
+ emitStatus({ kind: "progress", percent: Math.round(p.percent) });
});
autoUpdater.on("update-downloaded", (info: { version: string }) => {
downloadedVersion = info.version;
log(`downloaded: ${info.version}`);
+ emitStatus({ kind: "downloaded", version: info.version });
void promptRestart(info.version, getWindow());
});
autoUpdater.on("error", (err: Error) => {
log(`error: ${err.message}`);
+ emitStatus({ kind: "error", message: err.message });
if (manualCheckInFlight) {
manualCheckInFlight = false;
void dialog
@@ -132,6 +218,12 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
}
async function check(): Promise<void> {
+ // A waiting build ends the checking: a re-check with autoDownload on would start
+ // fetching any newer release 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;
try {
await autoUpdater.checkForUpdates();
} catch (err) {
@@ -160,6 +252,15 @@ export async function checkForUpdatesManually(): Promise<void> {
await promptRestart(downloadedVersion, null);
return;
}
+ if (status.state === "downloading") {
+ // check() would decline anyway; a manual action still answers (the silence rule).
+ await dialog.showMessageBox({
+ type: "info",
+ message: "An update is downloading.",
+ detail: "You will be asked to restart when it is ready.",
+ });
+ return;
+ }
manualCheckInFlight = true;
await check();
}
diff --git a/packages/desktop/test/updater-status.test.ts b/packages/desktop/test/updater-status.test.ts
new file mode 100644
index 00000000..c16fa656
--- /dev/null
+++ b/packages/desktop/test/updater-status.test.ts
@@ -0,0 +1,175 @@
+/**
+ * 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.
+ */
+import { describe, expect, it } from "vitest";
+import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";
+import {
+ initialUpdateStatus,
+ nextUpdateStatus,
+ parseUpdaterCommand,
+ updaterStatusMessage,
+} from "../src/updater-status.js";
+import type { UpdaterEvent } from "../src/updater-status.js";
+
+function fold(events: UpdaterEvent[], from = initialUpdateStatus("1.0.0")): DesktopUpdateStatus {
+ return events.reduce(nextUpdateStatus, from);
+}
+
+describe("nextUpdateStatus", () => {
+ it("starts idle with the app version", () => {
+ expect(initialUpdateStatus("1.2.3")).toEqual({ appVersion: "1.2.3", state: "idle" });
+ });
+
+ it("walks the up-to-date path: checking → not-available", () => {
+ expect(fold([{ kind: "checking" }])).toEqual({ appVersion: "1.0.0", state: "checking" });
+ expect(fold([{ kind: "checking" }, { kind: "not-available" }])).toEqual({
+ appVersion: "1.0.0",
+ state: "up-to-date",
+ });
+ });
+
+ it("walks the download path: available → progress → downloaded", () => {
+ const downloading = fold([{ kind: "checking" }, { kind: "available", version: "1.1.0" }]);
+ expect(downloading).toEqual({
+ appVersion: "1.0.0",
+ state: "downloading",
+ version: "1.1.0",
+ percent: 0,
+ });
+ expect(nextUpdateStatus(downloading, { kind: "progress", percent: 42 })).toEqual({
+ appVersion: "1.0.0",
+ state: "downloading",
+ version: "1.1.0",
+ percent: 42,
+ });
+ expect(nextUpdateStatus(downloading, { kind: "downloaded", version: "1.1.0" })).toEqual({
+ appVersion: "1.0.0",
+ state: "downloaded",
+ version: "1.1.0",
+ });
+ });
+
+ it("ignores a progress tick outside a download (stale timer)", () => {
+ const idle = initialUpdateStatus("1.0.0");
+ expect(nextUpdateStatus(idle, { kind: "progress", percent: 90 })).toBe(idle);
+ });
+
+ it("records errors with their message", () => {
+ expect(fold([{ kind: "error", message: "boom" }])).toEqual({
+ appVersion: "1.0.0",
+ state: "error",
+ message: "boom",
+ });
+ });
+
+ it("keeps a downloaded build over transient noise: checking / error / up-to-date / same-version re-announces", () => {
+ const downloaded = fold([{ kind: "downloaded", version: "1.1.0" }]);
+ for (const ev of [
+ { kind: "checking" },
+ { kind: "error", message: "offline" },
+ { kind: "not-available" },
+ { kind: "available", version: "1.1.0" },
+ { kind: "downloaded", version: "1.1.0" },
+ { kind: "progress", percent: 10 },
+ ] satisfies UpdaterEvent[]) {
+ expect(nextUpdateStatus(downloaded, ev)).toBe(downloaded);
+ }
+ });
+
+ it("yields a downloaded build to a different version being 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: "downloading",
+ version: "1.2.0",
+ percent: 0,
+ });
+ expect(nextUpdateStatus(downloaded, { kind: "downloaded", version: "1.2.0" })).toEqual({
+ appVersion: "1.0.0",
+ state: "downloaded",
+ version: "1.2.0",
+ });
+ });
+
+ it("keeps a running download over a concurrent check's noise", () => {
+ const downloading = fold([{ kind: "available", version: "1.1.0" }]);
+ for (const ev of [
+ { kind: "checking" },
+ { kind: "not-available" },
+ { kind: "available", version: "1.1.0" },
+ ] satisfies UpdaterEvent[]) {
+ expect(nextUpdateStatus(downloading, ev)).toBe(downloading);
+ }
+ // Progress keeps flowing after the suppressed events — the regression this rule exists for.
+ expect(nextUpdateStatus(downloading, { kind: "progress", percent: 55 })).toEqual({
+ appVersion: "1.0.0",
+ state: "downloading",
+ version: "1.1.0",
+ percent: 55,
+ });
+ });
+
+ 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" }]);
+ expect(nextUpdateStatus(downloading, { kind: "available", version: "1.2.0" })).toEqual({
+ appVersion: "1.0.0",
+ state: "downloading",
+ version: "1.2.0",
+ percent: 0,
+ });
+ expect(nextUpdateStatus(downloading, { kind: "error", message: "disk full" })).toEqual({
+ appVersion: "1.0.0",
+ state: "error",
+ message: "disk full",
+ });
+ });
+
+ it("marks an unsupported form, even over a downloaded build (the form claim is authoritative)", () => {
+ expect(fold([{ kind: "unsupported", reason: "dev" }])).toEqual({
+ appVersion: "1.0.0",
+ state: "unsupported",
+ reason: "dev",
+ });
+ const downloaded = fold([{ kind: "downloaded", version: "1.1.0" }]);
+ expect(
+ nextUpdateStatus(downloaded, { kind: "unsupported", reason: "linux-not-appimage" }),
+ ).toEqual({ appVersion: "1.0.0", state: "unsupported", reason: "linux-not-appimage" });
+ });
+});
+
+describe("port frames", () => {
+ it("wraps a snapshot for the push", () => {
+ const status = initialUpdateStatus("1.0.0");
+ expect(updaterStatusMessage(status)).toEqual({ type: "desktop-updater-status", status });
+ });
+
+ it("accepts exactly the two command frames", () => {
+ expect(parseUpdaterCommand({ type: "desktop-updater-command", action: "check" })).toBe("check");
+ expect(parseUpdaterCommand({ type: "desktop-updater-command", action: "install" })).toBe(
+ "install",
+ );
+ });
+
+ it("rejects everything else", () => {
+ for (const data of [
+ null,
+ undefined,
+ "check",
+ 42,
+ {},
+ { type: "desktop-updater-command" },
+ { type: "desktop-updater-command", action: "restart" },
+ { type: "desktop-updater-status", action: "check" },
+ ]) {
+ expect(parseUpdaterCommand(data)).toBeNull();
+ }
+ });
+});
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 349c4ec3..be892cbc 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -160,6 +160,8 @@ Two numbers are deliberately not exposed. The per-message file **count** stays a
System settings → **Updates** carries the manual "Check for updates" action; the running version sits muted beside it, and its release date — stamped into the build by the release workflow, displayed without any network access — appears as the row's localized "Last updated Jul 26"-style hint (dev builds and releases that predate the stamping, v0.1.2 and earlier, have no date). The new-chat page shows the same identity as a version line under the brand. 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, the draft page's version line gains a small superscript "New version available" badge linking to the release, and the menu gains a "New version available" row that opens the Updates page, whose 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).
+**In the desktop app** the Updates page is absent — the shell updates itself — and the sidebar user menu carries a client-update row instead, 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 no such row: it can neither read that machine's updater state nor restart its window. 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.
+
## Projects and Members
The sidebar provides a Project switcher and supports creating new Projects. Members have two roles, owner and member: owners manage membership and exclusively edit models, Vault, and Schedules, as well as perform deletions.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 72cceef9..9dce659f 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -159,6 +159,8 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,
系统设置的**更新**页提供手动「检查更新」按钮,当前运行版本号以浅色显示在旁;其发布日期(由发布流程在构建时打入、直接显示、无需联网)以「最近更新日期 7 月 26 日」样式的提示展示(开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。新对话页在品牌下方以版本行显示同样的信息。侧边栏用户菜单首次打开后会向 GitHub 查询是否有新版本;点击「检查更新」则立即查询(绕过缓存结果),已是最新时以提示告知。发现新版本时,用户按钮上会出现提示圆点,新对话页的版本行会出现可跳转 Release 页面的「有新版本可用」上标小徽标,菜单内出现「有新版本可用」行,点击直达更新页;其弹窗提供更新说明链接,管理员还可点击「立即更新」,在服务器上执行 `penguin update`(数据目录不受影响)。更新完成后需要重启服务才会生效。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。
+**在桌面应用中**没有更新页——客户端自己更新——侧边栏用户菜单改为提供一行客户端更新入口,且只出现在 shell 自身的窗口里。该行端到端驱动应用自带的更新器:先是「检查更新」,随后是后台下载并把百分比显示在文案里,最后是「重启并安装 vX」;由于重启会打断正在运行的 Task,点击后会先要求确认。当前安装的客户端版本以浅色显示在该行右侧;应用也会按自己的节奏后台检查,所以打开菜单时该行可能已经在等你重启安装。用密码登录同一台桌面模式服务器的浏览器不会看到这一行:它既读不到那台机器的更新状态,也无法重启它的窗口。无法自我替换的形态——由系统包管理器管理的 Linux 安装(`.deb`)以及开发运行——该行渲染为禁用,原因显示在悬浮提示里;安装包本身见[桌面应用指南](/quickstart-desktop)。
+
## Project 与成员
侧边栏提供 Project 切换器,并支持创建新 Project。成员分为 Owner 与 Member 两种角色:Owner 负责成员管理,并独占模型、Vault、Schedule 的编辑以及各类删除操作。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index b4b27c66..ea46b739 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2221,6 +2221,60 @@ export interface UpdateCheckResponse {
error?: "network" | "rate_limited" | "bad_response";
}
+// ---------------------------------------------------------------------------
+// Desktop client update (desktop mode only)
+// ---------------------------------------------------------------------------
+
+/**
+ * The desktop shell's updater snapshot, pushed to the embedded server over the
+ * 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
+ * check (or its failure) must not hide the actionable "restart to install" step.
+ */
+export interface DesktopUpdateStatus {
+ /** Installed shell version (Electron app.getVersion()). */
+ appVersion: string;
+ /**
+ * Bumped by the shell on every updater event it folds, whether or not the visible
+ * state changed. A row-initiated check settles when the seq has moved past its
+ * at-click value and the state is no longer `checking` — snapshot equality can't
+ * carry that signal (a check that ends where it started is byte-identical).
+ */
+ seq?: number;
+ state:
+ "idle" | "checking" | "up-to-date" | "downloading" | "downloaded" | "error" | "unsupported";
+ /** Newer release being fetched / ready to install (`downloading`, `downloaded`). */
+ version?: string;
+ /** Download progress 0–100 (`downloading`). */
+ percent?: number;
+ /** Updater failure text (`error`). */
+ message?: string;
+ /** Why this install form cannot update itself (`unsupported`): dev run, or a Linux install that is not an AppImage (e.g. .deb — the system package manager owns it). */
+ reason?: "dev" | "linux-not-appimage";
+}
+
+/**
+ * GET /api/desktop/update (desktop-shell sessions only): the latest shell snapshot.
+ * `status` is null until the shell's first push lands (a beat after server start).
+ */
+export interface DesktopUpdateStatusResponse {
+ status: DesktopUpdateStatus | null;
+}
+
+/** Shell → server push over the utilityProcess message channel. */
+export interface DesktopUpdaterStatusMessage {
+ type: "desktop-updater-status";
+ status: DesktopUpdateStatus;
+}
+
+/** Server → shell command over the utilityProcess message channel (relayed from POST /api/desktop/update/check|install). */
+export interface DesktopUpdaterCommandMessage {
+ type: "desktop-updater-command";
+ action: "check" | "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
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 76792f72..a412e90b 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -71,7 +71,7 @@ import type { TitleNotifier } from "./runtime/title-generator.js";
import { UsageRecorder } from "./runtime/usage-recorder.js";
import { AdminService } from "./services/admin-service.js";
import { DesktopService } from "./services/desktop-service.js";
-import { desktopRoutes } from "./http/routes/desktop.js";
+import { desktopRoutes, desktopUpdateRoutes } from "./http/routes/desktop.js";
import { AgentConfigService } from "./services/agent-config-service.js";
import { MemoryService } from "./services/memory-service.js";
import { AgentService } from "./services/agent-service.js";
@@ -522,6 +522,11 @@ export function createApp(deps: AppDeps): Hono<AppEnv> {
const auth = authMiddleware(deps.authService);
app.use("/api/*", auth);
app.route("/api/me", meRoutes(deps));
+ // Cookie-authed (unlike the Bearer-token shutdown above): the page reads updater state
+ // and posts check/install here, gated to the shell's own window inside the routes.
+ if (deps.desktop) {
+ app.route("/api/desktop/update", desktopUpdateRoutes(deps));
+ }
app.route("/api/version", versionRoutes(deps));
app.route("/api/admin/users", adminUsersRoutes(deps));
app.route("/api/admin/settings", adminSettingsRoutes(deps));
diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.ts
index 572a35b0..33b9a0bc 100644
--- a/packages/server/src/http/routes/desktop.ts
+++ b/packages/server/src/http/routes/desktop.ts
@@ -1,16 +1,22 @@
/**
- * Desktop-mode routes: POST /api/desktop/shutdown, plus the shared desktop-mode guard
- * that turns off multi-user surfaces (see rejectInDesktopMode).
+ * Desktop-mode routes: POST /api/desktop/shutdown, the client-update relay under
+ * /api/desktop/update, plus the shared desktop-mode guard that turns off multi-user
+ * surfaces (see rejectInDesktopMode).
*
* The shutdown route is authenticated by the shell's Bearer token, not the cookie
* session (the shell holds no cookie), so it mounts OUTSIDE authMiddleware and only
* when desktop mode is enabled. Responds 202 first, then triggers the graceful
* shutdown a beat later so the response isn't cut off by the closing listener.
+ * The update routes are called by the page instead, so they mount INSIDE authMiddleware
+ * (see desktopUpdateRoutes).
*/
import { Hono } from "hono";
-import type { MiddlewareHandler } from "hono";
+import type { Context, MiddlewareHandler } from "hono";
+import type { DesktopUpdateStatusResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
+import type { AppEnv } from "../../auth/middleware.js";
import type { AppDeps } from "../../app.js";
+import type { DesktopService } from "../../services/desktop-service.js";
/**
* Guard for user-management surfaces (admin users, Project members): the desktop app is
@@ -52,3 +58,51 @@ export function desktopRoutes(deps: AppDeps): Hono {
return app;
}
+
+/**
+ * Client-update relay routes (mounted INSIDE authMiddleware at /api/desktop/update, and
+ * 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.
+ */
+export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ const requireShellSession = (c: Context<AppEnv>): DesktopService => {
+ const desktop = deps.desktop;
+ if (!desktop) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");
+ if (c.var.sessionVia !== "desktop") {
+ throw new HttpError(
+ 403,
+ "desktop_shell_only",
+ "Client updates are managed from the desktop app's own window.",
+ );
+ }
+ return desktop;
+ };
+
+ app.get("/", (c) => {
+ const desktop = requireShellSession(c);
+ return c.json({ status: desktop.getUpdateStatus() } satisfies DesktopUpdateStatusResponse);
+ });
+
+ app.post("/check", (c) => {
+ const desktop = requireShellSession(c);
+ if (!desktop.requestUpdateCommand("check")) {
+ 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")) {
+ throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");
+ }
+ return c.body(null, 202);
+ });
+
+ return app;
+}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 6e5fea1f..434b6703 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -27,6 +27,7 @@ import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js
import { attachTerminalWebSocket } from "./terminal/ws.js";
import { loopbackHostRoles } from "./services/preview-token.js";
import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";
+import { shellPortOf, wireShellUpdatePort } from "./services/desktop-update-port.js";
loadDotenv({ quiet: true });
@@ -214,6 +215,15 @@ process.on("SIGTERM", () => void shutdown("SIGTERM"));
// TerminateProcess with no signal delivery.
deps.desktop?.onShutdownRequest(() => void shutdown("desktop-shutdown"));
+// 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 plain
+// `penguin server|web` run, or tests) wires nothing.
+if (deps.desktop !== null) {
+ const shellPort = shellPortOf(process);
+ if (shellPort !== null) wireShellUpdatePort(deps.desktop, shellPort);
+}
+
// Process-level error fallback: once a background
// fire-and-forget promise (title generation, Session drive, etc.) throws, the error
// reaches the process without passing through any catch — persist it first for a
diff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.ts
index 4ec5ebcb..c00a5359 100644
--- a/packages/server/src/services/desktop-service.ts
+++ b/packages/server/src/services/desktop-service.ts
@@ -12,8 +12,15 @@
* where killing a child is a hard TerminateProcess).
*
* Comparisons hash both sides first so timingSafeEqual gets equal-length buffers.
+ *
+ * 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
+ * capability flows through this HTTP surface, never a renderer IPC bridge.
*/
import { createHash, timingSafeEqual } from "node:crypto";
+import type { DesktopUpdateStatus } from "../api/types.js";
function digest(value: string): Buffer {
return createHash("sha256").update(value).digest();
@@ -51,4 +58,31 @@ export class DesktopService {
this.shutdownHandler();
return true;
}
+
+ // --- client-update relay ---------------------------------------------------
+
+ private updateStatus: DesktopUpdateStatus | null = null;
+ private updateCommandSender: ((action: "check" | "install") => void) | null = null;
+
+ /** Latest shell snapshot; null until the shell's first push lands. */
+ getUpdateStatus(): DesktopUpdateStatus | null {
+ return this.updateStatus;
+ }
+
+ /** index.ts stores each shell push here (already validated at the message port). */
+ setUpdateStatus(status: DesktopUpdateStatus): void {
+ this.updateStatus = status;
+ }
+
+ /** index.ts registers the message-port sender; absent outside a shell-forked process. */
+ onUpdateCommand(sender: (action: "check" | "install") => 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 {
+ 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.ts
new file mode 100644
index 00000000..71b8a920
--- /dev/null
+++ b/packages/server/src/services/desktop-update-port.ts
@@ -0,0 +1,69 @@
+/**
+ * Shell↔server message-port relay for client updates (desktop mode only).
+ *
+ * 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
+ * module wires nothing; the update routes then answer 503 `shell_unreachable`.
+ *
+ * Wire shapes live in api/types.ts (DesktopUpdaterStatusMessage /
+ * DesktopUpdaterCommandMessage) so the shell imports the same contract.
+ */
+import type {
+ DesktopUpdateStatus,
+ DesktopUpdaterCommandMessage,
+ DesktopUpdaterStatusMessage,
+} from "../api/types.js";
+import type { DesktopService } from "./desktop-service.js";
+
+/** The slice of Electron's ParentPort this relay uses (structural: the server must not depend on Electron types). */
+export interface ShellPort {
+ on(event: "message", listener: (e: { data: unknown }) => void): void;
+ postMessage(message: unknown): void;
+}
+
+const UPDATE_STATES: ReadonlySet<string> = new Set([
+ "idle",
+ "checking",
+ "up-to-date",
+ "downloading",
+ "downloaded",
+ "error",
+ "unsupported",
+]);
+
+/** Validates one shell push. Strict on the discriminators, tolerant of extra fields — the two sides ship together, but a malformed frame must not poison the stored snapshot. */
+export function parseUpdaterStatusMessage(data: unknown): DesktopUpdateStatus | null {
+ if (typeof data !== "object" || data === null) return null;
+ const msg = data as Partial<DesktopUpdaterStatusMessage>;
+ if (msg.type !== "desktop-updater-status") return null;
+ const status = msg.status as Partial<DesktopUpdateStatus> | undefined;
+ if (typeof status !== "object" || status === null) return null;
+ if (typeof status.appVersion !== "string") return null;
+ if (typeof status.state !== "string" || !UPDATE_STATES.has(status.state)) return null;
+ if (status.seq !== undefined && typeof status.seq !== "number") return null;
+ return status as DesktopUpdateStatus;
+}
+
+/** Reads Electron's injected port off `process`, absent under plain Node. */
+export function shellPortOf(proc: NodeJS.Process): ShellPort | null {
+ const port = (proc as NodeJS.Process & { parentPort?: ShellPort }).parentPort;
+ return port && typeof port.on === "function" && typeof port.postMessage === "function"
+ ? port
+ : null;
+}
+
+/** Connects the port to the service: stores validated status pushes, registers the command sender. */
+export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): void {
+ port.on("message", (e) => {
+ const status = parseUpdaterStatusMessage(e.data);
+ if (status !== null) desktop.setUpdateStatus(status);
+ });
+ desktop.onUpdateCommand((action) => {
+ port.postMessage({
+ type: "desktop-updater-command",
+ action,
+ } satisfies DesktopUpdaterCommandMessage);
+ });
+}
diff --git a/packages/server/test/desktop-update.test.ts b/packages/server/test/desktop-update.test.ts
new file mode 100644
index 00000000..4b4fd26f
--- /dev/null
+++ b/packages/server/test/desktop-update.test.ts
@@ -0,0 +1,210 @@
+/**
+ * Client-update relay: the /api/desktop/update routes (shell-window sessions only), the
+ * DesktopService store/forward pair behind them, and the message-port glue.
+ *
+ * The session gate is pinned in both directions like the change-password one it
+ * mirrors: a desktop-via session may read and command, a password-via session against
+ * the same desktop-mode server gets 403 — its holder may be on another machine and
+ * must not restart this one's GUI app.
+ */
+import { describe, expect, it } from "vitest";
+import { createDesktopApp, createTestApp, desktopLoginCookie, loginAdmin } from "./helpers.js";
+import type {
+ DesktopUpdateStatus,
+ DesktopUpdateStatusResponse,
+ ErrorBody,
+} from "../src/api/types.js";
+import { DesktopService } from "../src/services/desktop-service.js";
+import {
+ parseUpdaterStatusMessage,
+ shellPortOf,
+ wireShellUpdatePort,
+} from "../src/services/desktop-update-port.js";
+import type { ShellPort } from "../src/services/desktop-update-port.js";
+
+const STATUS: DesktopUpdateStatus = {
+ appVersion: "0.2.3",
+ seq: 7,
+ state: "downloaded",
+ version: "0.3.0",
+};
+
+describe("GET /api/desktop/update", () => {
+ it("serves null before the shell's first push, then the stored snapshot", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const before = await t.app.request("/api/desktop/update", { headers: { cookie } });
+ expect(before.status).toBe(200);
+ expect((await before.json()) as DesktopUpdateStatusResponse).toEqual({ status: null });
+
+ t.deps.desktop!.setUpdateStatus(STATUS);
+ const after = await t.app.request("/api/desktop/update", { headers: { cookie } });
+ expect((await after.json()) as DesktopUpdateStatusResponse).toEqual({ status: STATUS });
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("answers 403 desktop_shell_only to a password-established session", async () => {
+ const t = await createDesktopApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const res = await t.app.request("/api/desktop/update", {
+ headers: { cookie: admin.cookie },
+ });
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as ErrorBody).error.code).toBe("desktop_shell_only");
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("does not exist outside desktop mode", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const res = await t.app.request("/api/desktop/update", {
+ headers: { cookie: admin.cookie },
+ });
+ expect(res.status).toBe(404);
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
+
+describe("POST /api/desktop/update/{check,install}", () => {
+ it("forwards to the registered shell sender and answers 202", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const actions: string[] = [];
+ t.deps.desktop!.onUpdateCommand((action) => actions.push(action));
+
+ const check = await t.app.request("/api/desktop/update/check", {
+ method: "POST",
+ headers: { cookie, "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(check.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"]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("refuses a password session, an unauthenticated caller, and a plain server", async () => {
+ // install is the route that replaces the running application, so its gate is pinned
+ // in every direction rather than inferred from the GET above.
+ const t = await createDesktopApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ let commanded = 0;
+ t.deps.desktop!.onUpdateCommand(() => {
+ commanded += 1;
+ });
+ for (const path of ["/api/desktop/update/check", "/api/desktop/update/install"]) {
+ const viaPassword = await t.app.request(path, {
+ method: "POST",
+ headers: { cookie: admin.cookie, "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(viaPassword.status).toBe(403);
+ expect(((await viaPassword.json()) as ErrorBody).error.code).toBe("desktop_shell_only");
+
+ const anonymous = await t.app.request(path, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(anonymous.status).toBe(401);
+ }
+ // Nothing reached the shell on any of those four attempts.
+ expect(commanded).toBe(0);
+ } finally {
+ await t.cleanup();
+ }
+
+ const plain = await createTestApp();
+ try {
+ const admin = await loginAdmin(plain.app);
+ const res = await plain.app.request("/api/desktop/update/install", {
+ method: "POST",
+ headers: { cookie: admin.cookie, "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(res.status).toBe(404);
+ } finally {
+ await plain.cleanup();
+ }
+ });
+
+ it("answers 503 shell_unreachable while no port is wired", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const res = await t.app.request("/api/desktop/update/check", {
+ method: "POST",
+ headers: { cookie, "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(res.status).toBe(503);
+ expect(((await res.json()) as ErrorBody).error.code).toBe("shell_unreachable");
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
+
+describe("desktop-update-port", () => {
+ it("parses only well-formed status frames", () => {
+ expect(parseUpdaterStatusMessage({ type: "desktop-updater-status", status: STATUS })).toEqual(
+ STATUS,
+ );
+ for (const data of [
+ null,
+ "status",
+ {},
+ { type: "desktop-updater-status" },
+ { type: "desktop-updater-status", status: null },
+ { type: "desktop-updater-status", status: { state: "downloaded" } }, // no appVersion
+ { type: "desktop-updater-status", status: { appVersion: "1", state: "resting" } },
+ { type: "desktop-updater-status", status: { appVersion: "1", state: "idle", seq: "7" } },
+ { type: "desktop-updater-command", status: STATUS },
+ ]) {
+ expect(parseUpdaterStatusMessage(data)).toBeNull();
+ }
+ });
+
+ it("stores pushed frames and posts commands through a wired port", () => {
+ const desktop = new DesktopService("t");
+ const posted: unknown[] = [];
+ let onMessage: ((e: { data: unknown }) => void) | undefined;
+ const port: ShellPort = {
+ on: (_event, listener) => {
+ onMessage = listener;
+ },
+ postMessage: (message) => posted.push(message),
+ };
+ wireShellUpdatePort(desktop, port);
+
+ onMessage!({ data: { type: "desktop-updater-status", status: STATUS } });
+ expect(desktop.getUpdateStatus()).toEqual(STATUS);
+ onMessage!({ data: { garbage: true } });
+ expect(desktop.getUpdateStatus()).toEqual(STATUS);
+
+ expect(desktop.requestUpdateCommand("check")).toBe(true);
+ expect(posted).toEqual([{ type: "desktop-updater-command", action: "check" }]);
+ });
+
+ it("finds no shell port on a plain Node process without parentPort", () => {
+ expect(shellPortOf(process)).toBeNull();
+ });
+});
diff --git a/packages/server/test/desktop.test.ts b/packages/server/test/desktop.test.ts
index 53a4ab7f..bd91c5a7 100644
--- a/packages/server/test/desktop.test.ts
+++ b/packages/server/test/desktop.test.ts
@@ -4,20 +4,21 @@
* closing the user-management and Project-member surfaces.
*/
import { describe, expect, it } from "vitest";
-import { apiClient, createTestApp, loginAdmin } from "./helpers.js";
+import {
+ apiClient,
+ createDesktopApp,
+ desktopLoginCookie,
+ createTestApp,
+ loginAdmin,
+ TEST_DESKTOP_TOKEN,
+} from "./helpers.js";
import type { ErrorBody, MeResponse } from "../src/api/types.js";
-const TOKEN = "test-desktop-token";
-
-function desktopApp() {
- return createTestApp({ config: { desktopToken: TOKEN } });
-}
-
describe("desktop-login", () => {
it("redeems the token once: cookie session, redirect to /, second attempt 401", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
- const res = await t.app.request(`/api/auth/desktop-login?token=${TOKEN}`);
+ const res = await t.app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`);
expect(res.status).toBe(302);
expect(res.headers.get("location")).toBe("/");
const cookie = res.headers.get("set-cookie");
@@ -31,7 +32,7 @@ describe("desktop-login", () => {
expect(body.user.userId).toBe("admin");
expect(body.desktopMode).toBe(true);
- const replay = await t.app.request(`/api/auth/desktop-login?token=${TOKEN}`);
+ const replay = await t.app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`);
expect(replay.status).toBe(401);
} finally {
await t.cleanup();
@@ -39,12 +40,14 @@ describe("desktop-login", () => {
});
it("rejects a wrong or missing token without consuming the real one", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
expect((await t.app.request("/api/auth/desktop-login?token=wrong")).status).toBe(401);
expect((await t.app.request("/api/auth/desktop-login")).status).toBe(401);
// The real token still works after failed attempts.
- expect((await t.app.request(`/api/auth/desktop-login?token=${TOKEN}`)).status).toBe(302);
+ expect(
+ (await t.app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`)).status,
+ ).toBe(302);
} finally {
await t.cleanup();
}
@@ -65,7 +68,7 @@ describe("desktop-login", () => {
describe("desktop shutdown endpoint", () => {
it("accepts the Bearer token repeatedly and triggers the registered handler", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
let requested = 0;
t.deps.desktop!.onShutdownRequest(() => {
@@ -73,7 +76,7 @@ describe("desktop shutdown endpoint", () => {
});
const res = await t.app.request("/api/desktop/shutdown", {
method: "POST",
- headers: { authorization: `Bearer ${TOKEN}` },
+ headers: { authorization: `Bearer ${TEST_DESKTOP_TOKEN}` },
});
expect(res.status).toBe(202);
// The route defers the trigger so the 202 can flush first.
@@ -83,7 +86,7 @@ describe("desktop shutdown endpoint", () => {
// Unlike the login token, the shutdown credential is NOT one-shot.
const again = await t.app.request("/api/desktop/shutdown", {
method: "POST",
- headers: { authorization: `Bearer ${TOKEN}` },
+ headers: { authorization: `Bearer ${TEST_DESKTOP_TOKEN}` },
});
expect(again.status).toBe(202);
} finally {
@@ -92,7 +95,7 @@ describe("desktop shutdown endpoint", () => {
});
it("rejects wrong or missing tokens, and does not exist outside desktop mode", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
const wrong = await t.app.request("/api/desktop/shutdown", {
method: "POST",
@@ -111,7 +114,7 @@ describe("desktop shutdown endpoint", () => {
// cookie auth middleware, which rejects the cookieless caller with 401.
const res = await plain.app.request("/api/desktop/shutdown", {
method: "POST",
- headers: { authorization: `Bearer ${TOKEN}` },
+ headers: { authorization: `Bearer ${TEST_DESKTOP_TOKEN}` },
});
expect(res.status).toBe(401);
} finally {
@@ -128,7 +131,7 @@ describe("desktop single-user mode", () => {
}
it("rejects the whole admin-users surface with desktop_single_user", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
// The seeded admin signed in through the regular login form: even a fully
// authorized admin session gets the dedicated 403, not admin_required.
@@ -155,7 +158,7 @@ describe("desktop single-user mode", () => {
});
it("rejects Project member management (reads and writes) with desktop_single_user", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
const admin = await loginAdmin(t.app);
const api = apiClient(t.app, admin.cookie);
@@ -190,15 +193,10 @@ describe("desktop single-user mode", () => {
});
describe("desktop-session password change", () => {
- async function desktopCookie(t: Awaited<ReturnType<typeof desktopApp>>): Promise<string> {
- const res = await t.app.request(`/api/auth/desktop-login?token=${TOKEN}`);
- return res.headers.get("set-cookie")!.split(";")[0]!;
- }
-
it("allows omitting oldPassword for a desktop session and clears the initial flag", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
- const cookie = await desktopCookie(t);
+ const cookie = await desktopLoginCookie(t.app);
const res = await apiClient(t.app, cookie).put("/api/me/password", {
newPassword: "brand-new-password",
});
@@ -211,9 +209,9 @@ describe("desktop-session password change", () => {
});
it("still validates oldPassword when it is provided by a desktop session", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
- const cookie = await desktopCookie(t);
+ const cookie = await desktopLoginCookie(t.app);
const res = await apiClient(t.app, cookie).put("/api/me/password", {
oldPassword: "wrong-password",
newPassword: "brand-new-password",
@@ -225,7 +223,7 @@ describe("desktop-session password change", () => {
});
it("keeps requiring oldPassword for password-established sessions in desktop mode", async () => {
- const t = await desktopApp();
+ const t = await createDesktopApp();
try {
// Sign in via the regular login form against the same desktop-mode server.
const admin = await loginAdmin(t.app);
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 33b7bf24..05deb0ad 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -108,6 +108,25 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
};
}
+/** The desktop-mode fixture token (see createDesktopApp). */
+export const TEST_DESKTOP_TOKEN = "test-desktop-token";
+
+/** A test app running in desktop mode (desktop.test.ts, desktop-update.test.ts). */
+export function createDesktopApp(): Promise<TestApp> {
+ return createTestApp({ config: { desktopToken: TEST_DESKTOP_TOKEN } });
+}
+
+/** Redeems the one-shot desktop-login for a `sessionVia: "desktop"` cookie. */
+export async function desktopLoginCookie(app: Hono<AppEnv>): Promise<string> {
+ const res = await app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`);
+ if (res.status !== 302) {
+ throw new Error(`Desktop login failed: ${res.status} ${await res.text()}`);
+ }
+ const setCookie = res.headers.get("set-cookie");
+ if (!setCookie) throw new Error("Desktop login response is missing set-cookie");
+ return setCookie.split(";")[0]!;
+}
+
/** Logs in and returns the session cookie (`penguin_session=...`). */
export async function loginUser(
app: Hono<AppEnv>,
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index c320b334..206de051 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -94,6 +94,7 @@ import type {
UiPrefs,
UpdateCheckResponse,
UpdateRunResponse,
+ DesktopUpdateStatusResponse,
UsageErrorsPage,
UsageGroupBy,
UsageResponse,
@@ -876,3 +877,13 @@ export const checkUpdate = (force = false) =>
/** 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: {} });
+
+// Desktop client update (desktop-shell sessions only) ----------------------------------
+
+export const getDesktopUpdate = () => apiFetch<DesktopUpdateStatusResponse>("/api/desktop/update");
+
+export const desktopUpdateCheck = () =>
+ apiFetch<void>("/api/desktop/update/check", { 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.tsx
new file mode 100644
index 00000000..fb9dfca9
--- /dev/null
+++ b/packages/web/src/components/account/desktop-update-row.tsx
@@ -0,0 +1,92 @@
+/**
+ * Client-update row in the sidebar user menu — the desktop-mode counterpart of the
+ * server update reminder (which 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.clientUnsupportedPackage
+ : 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/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 728eec46..0385dec7 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -137,6 +137,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 { offersClientUpdate } from "../../lib/desktop-update";
+import { requestClientInstall, useDesktopUpdate } from "../../lib/use-desktop-update";
import { useVersionInfo } from "../../lib/use-version-info";
import { SettingsDialog } from "../../features/settings/settings-dialog";
import type { SettingsSectionKey } from "../../lib/settings-sections";
@@ -279,7 +282,7 @@ export function Sidebar({
onCollapse?: () => void;
}) {
const navigate = useNavigate();
- const { user, logout, desktopMode } = useAuth();
+ const { user, logout, desktopMode, sessionVia } = useAuth();
const { locale } = useLocale();
const {
projects,
@@ -312,6 +315,13 @@ export function Sidebar({
const [settingsOpen, setSettingsOpen] = useState(false);
/** Page the settings dialog lands on: the update reminder row jumps straight to Updates. */
const [settingsSection, setSettingsSection] = useState<SettingsSectionKey>("general");
+ // 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);
// Update reminder: nothing is fetched until the dropdown first opens.
const { update } = useVersionInfo(userOpen);
const updateAvailable = update?.updateAvailable === true;
@@ -1700,6 +1710,24 @@ export function Sidebar({
<span className="min-w-0 truncate">{S.update.newVersion(newVersion)}</span>
</button>
)}
+ {/* Desktop stand-in for the reminder 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);
+ }}
+ />
+ )}
{/* Hidden in desktop mode: the window IS the session — logging out would
strand the user on a login page whose password was never shown. */}
{!desktopMode && (
@@ -1724,6 +1752,25 @@ export function Sidebar({
initialSection={settingsSection}
/>
+ {/* 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>
+
<CreateProjectDialog
open={createProjectOpen}
onClose={() => setCreateProjectOpen(false)}
diff --git a/packages/web/src/lib/desktop-update.ts b/packages/web/src/lib/desktop-update.ts
new file mode 100644
index 00000000..77d54a34
--- /dev/null
+++ b/packages/web/src/lib/desktop-update.ts
@@ -0,0 +1,161 @@
+/**
+ * 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).
+ */
+import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";
+import type { AccountMenuSession } from "./account-menu";
+
+/**
+ * Whether to offer the client-update row at all: only the shell's own window. Both
+ * halves matter, mirroring offersChangePassword's reasoning inverted — `desktopMode`
+ * alone would let a browser signed into the same desktop-mode server read this
+ * machine's updater state and restart its GUI app; `sessionVia` alone would offer the
+ * row to a stale desktop cookie replayed against a plain `penguin server`, where no
+ * shell is listening. The server enforces the same pair on the routes.
+ */
+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). */
+export type ClientCheckSettle =
+ | { kind: "up-to-date" }
+ | { 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 }
+ | { kind: "unsupported"; reason: "dev" | "linux-not-appimage" | null }
+ /**
+ * `message` is the shell's own failure text when there is one — an updater error is
+ * not always a failed check (a download that fails its sha512 or, on Windows, its
+ * Authenticode publisher check lands here too), so the generic "check failed" wording
+ * is only correct for the case with nothing to report: the watch timing out.
+ */
+ | { kind: "failed"; message: string | null };
+
+/** An armed check that saw no outcome for this long settles as failed (shell gone, frame lost). */
+export const CLIENT_CHECK_TIMEOUT_MS = 60_000;
+
+/**
+ * Decides whether an armed check has settled, given the snapshot seq at click time,
+ * the latest snapshot and the time since the click. The shell bumps `seq` on every
+ * event it folds — snapshot equality cannot carry the signal, since a check that ends
+ * where it started (still up to date) is byte-identical. A concurrent automatic check
+ * moving the seq settles the watch too; its outcome is a real, just-completed check,
+ * so reporting it answers the user truthfully. Without a seq on either side the
+ * fallback settles on any terminal state once two poll rounds have passed. Returns
+ * null while still in flight.
+ */
+export function clientCheckSettle(
+ atClickSeq: number | null,
+ now: DesktopUpdateStatus | null,
+ elapsedMs: number,
+): ClientCheckSettle | null {
+ const timedOut = elapsedMs >= CLIENT_CHECK_TIMEOUT_MS;
+ if (now === null) return timedOut ? { kind: "failed", message: null } : null;
+ if (now.state === "checking") return null; // visibly in flight — the row spins
+ const moved =
+ now.seq !== undefined && atClickSeq !== null ? now.seq !== atClickSeq : elapsedMs >= 4_000;
+ if (!moved) return timedOut ? { kind: "failed", message: null } : null;
+ switch (now.state) {
+ case "up-to-date":
+ return { kind: "up-to-date" };
+ case "downloading":
+ return { kind: "found", version: now.version ?? null };
+ case "downloaded":
+ return { kind: "ready", version: now.version ?? null };
+ case "unsupported":
+ return { kind: "unsupported", reason: now.reason ?? null };
+ case "error":
+ return { kind: "failed", message: now.message ?? null };
+ // idle: the seq moved but no check began (shouldn't happen); only the timeout ends it.
+ default:
+ return timedOut ? { kind: "failed", message: null } : null;
+ }
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 058c0581..1e20bc8f 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -155,6 +155,41 @@ export const en: Strings = {
"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. */
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",
+ /** Mirrors the shell's native restart prompt: the interruption warning must not disappear on the web path. */
+ clientInstallConfirmBody:
+ "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 installs owned by the system package manager (e.g. .deb). */
+ clientUnsupportedPackage:
+ "This install is managed by the system package manager — update it there",
},
/** Desktop task-completion notifications (window unfocused; desktop-shell sessions only). */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index b71f48ad..839a78c7 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -154,6 +154,35 @@ export const zh = {
"将下载最新版本并安装到服务器上的安装目录(数据目录不受影响)。安装完成后需要重启服务才会生效。",
/** Copy shown to non-admins in place of confirmBody (they can read the release notes but cannot run the update here). */
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: "重启并安装更新",
+ /** 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 installs owned by the system package manager (e.g. .deb). */
+ clientUnsupportedPackage: "此安装由系统包管理器管理,请通过包管理器更新",
},
/** Desktop task-completion notifications (window unfocused; desktop-shell sessions only). */
diff --git a/packages/web/src/lib/use-desktop-update.ts b/packages/web/src/lib/use-desktop-update.ts
new file mode 100644
index 00000000..a6d303d4
--- /dev/null
+++ b/packages/web/src/lib/use-desktop-update.ts
@@ -0,0 +1,141 @@
+/**
+ * Shared state behind the client-update row: the shell's updater snapshot, the armed
+ * row-initiated check, and the polling that feeds both.
+ *
+ * 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.
+ */
+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";
+
+/** 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). */
+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. */
+let watch: { atClickSeq: number | null; armedAt: number } | null = null;
+const listeners = new Set<() => void>();
+
+function notifyAll(): void {
+ for (const notify of listeners) notify();
+}
+
+/** Settles the armed check against the current cache, toasting 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.clientUnsupportedPackage
+ : S.update.clientUnsupportedDev,
+ );
+ break;
+ default:
+ toastError(
+ settle.message !== null
+ ? S.update.clientUpdateFailed(settle.message)
+ : S.update.checkFailed,
+ );
+ }
+}
+
+/** 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. */
+function poll(): Promise<void> {
+ if (inflight) return inflight;
+ inflight = (async () => {
+ try {
+ const res = await api.getDesktopUpdate();
+ statusCache = res.status;
+ } catch {
+ // The menu 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;
+ settleWatch();
+ notifyAll();
+ }
+ })();
+ return inflight;
+}
+
+/** Row action: arm the settle watch, then ask the shell to check. A failed POST disarms and reports itself. */
+export async function requestClientCheck(): Promise<void> {
+ if (watch !== null) return;
+ watch = { atClickSeq: statusCache?.seq ?? null, armedAt: Date.now() };
+ notifyAll();
+ try {
+ await api.desktopUpdateCheck();
+ void poll();
+ } catch (e) {
+ watch = null;
+ notifyAll();
+ toastError(apiErrorText(e));
+ }
+}
+
+/** Row action, behind the page's confirm dialog: the shell restarts into the downloaded build, so success renders nothing. */
+export async function requestClientInstall(): Promise<void> {
+ try {
+ await api.desktopUpdateInstall();
+ } catch (e) {
+ toastError(S.update.clientInstallFailed(apiErrorText(e)));
+ }
+}
+
+/**
+ * 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).
+ */
+export function useDesktopUpdate(
+ enabled: boolean,
+ menuOpen: boolean,
+): { status: DesktopUpdateStatus | null; checkPending: boolean } {
+ const [, force] = useReducer((x: number) => x + 1, 0);
+ useEffect(() => {
+ listeners.add(force);
+ return () => {
+ listeners.delete(force);
+ };
+ }, []);
+
+ const checkPending = watch !== null;
+ const hot =
+ checkPending || statusCache?.state === "checking" || statusCache?.state === "downloading";
+ const active = enabled && (menuOpen || checkPending);
+ useEffect(() => {
+ if (!active) return;
+ void poll();
+ const timer = setInterval(() => void poll(), hot ? FAST_POLL_MS : SLOW_POLL_MS);
+ return () => clearInterval(timer);
+ }, [active, hot]);
+
+ return { status: statusCache, checkPending };
+}
diff --git a/packages/web/test/desktop-update.test.ts b/packages/web/test/desktop-update.test.ts
new file mode 100644
index 00000000..b8381b45
--- /dev/null
+++ b/packages/web/test/desktop-update.test.ts
@@ -0,0 +1,170 @@
+/**
+ * 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).
+ *
+ * offersClientUpdate is pinned in all four combinations for the same reason as
+ * offersChangePassword next door: each single-field simplification fails a real case —
+ * `desktopMode` alone offers a remote browser a button that restarts someone else's
+ * GUI app, `sessionVia` alone offers it to a stale desktop cookie replayed against a
+ * plain server with no shell listening. vitest runs node-only here, so this asserts
+ * the pure helpers, not a rendered row (account-menu.test.ts convention).
+ */
+import { describe, expect, it } from "vitest";
+import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";
+import {
+ CLIENT_CHECK_TIMEOUT_MS,
+ clientCheckSettle,
+ clientUpdateRow,
+ offersClientUpdate,
+} from "../src/lib/desktop-update";
+
+describe("offersClientUpdate", () => {
+ it("offers the row only in the desktop shell's own window", () => {
+ expect(offersClientUpdate({ desktopMode: true, sessionVia: "desktop" })).toBe(true);
+ expect(offersClientUpdate({ desktopMode: true, sessionVia: "password" })).toBe(false);
+ expect(offersClientUpdate({ desktopMode: false, sessionVia: "desktop" })).toBe(false);
+ expect(offersClientUpdate({ desktopMode: false, sessionVia: "password" })).toBe(false);
+ });
+});
+
+const at = (
+ state: DesktopUpdateStatus["state"],
+ 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();
+ expect(clientCheckSettle(1, at("checking", { seq: 2 }), 3_000)).toBeNull();
+ expect(clientCheckSettle(1, at("up-to-date", { seq: 1 }), 3_000)).toBeNull();
+ });
+
+ it("settles on a terminal state once the seq moved — even to a byte-identical up-to-date", () => {
+ expect(clientCheckSettle(1, at("up-to-date", { seq: 3 }), 3_000)).toEqual({
+ kind: "up-to-date",
+ });
+ expect(clientCheckSettle(1, at("error", { seq: 3, message: "x" }), 3_000)).toEqual({
+ kind: "failed",
+ message: "x",
+ });
+ expect(
+ clientCheckSettle(1, at("downloading", { seq: 3, version: "0.3.0", percent: 1 }), 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",
+ });
+ expect(clientCheckSettle(1, at("unsupported", { seq: 3, reason: "dev" }), 3_000)).toEqual({
+ kind: "unsupported",
+ reason: "dev",
+ });
+ });
+
+ it("falls back to two poll rounds when either side carries no seq", () => {
+ const noSeq = { appVersion: "0.2.3", state: "up-to-date" } as DesktopUpdateStatus;
+ expect(clientCheckSettle(null, noSeq, 3_000)).toBeNull();
+ expect(clientCheckSettle(null, noSeq, 5_000)).toEqual({ kind: "up-to-date" });
+ });
+
+ it("times out an armed check that never sees an outcome, with nothing to report", () => {
+ expect(clientCheckSettle(1, null, CLIENT_CHECK_TIMEOUT_MS)).toEqual({
+ kind: "failed",
+ message: null,
+ });
+ expect(clientCheckSettle(1, at("up-to-date", { seq: 1 }), CLIENT_CHECK_TIMEOUT_MS)).toEqual({
+ kind: "failed",
+ message: null,
+ });
+ expect(clientCheckSettle(1, at("idle", { seq: 2 }), CLIENT_CHECK_TIMEOUT_MS)).toEqual({
+ kind: "failed",
+ message: null,
+ });
+ });
+
+ it("keeps the shell's failure text when the updater reported one", () => {
+ // A download that fails its sha512, or (Windows) its Authenticode publisher check,
+ // arrives as `error` too — reporting it as a failed *check* would be wrong, and
+ // would flatten a signature rejection into a network hiccup.
+ const invalidSignature = at("error", {
+ seq: 9,
+ message: "New version 0.3.0 is not signed by the application owner",
+ });
+ expect(clientCheckSettle(1, invalidSignature, 3_000)).toEqual({
+ kind: "failed",
+ message: "New version 0.3.0 is not signed by the application owner",
+ });
+ // An `error` snapshot the shell left messageless still settles, with nothing to add.
+ expect(clientCheckSettle(1, at("error", { seq: 9 }), 3_000)).toEqual({
+ kind: "failed",
+ message: null,
+ });
+ });
+});