Skip to content

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

feat(server,web,desktop): install this build on a machine (#447)

Myriad-Dreaminc6d7633e4035
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index adb181b5..a55307e8 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -199,29 +199,14 @@ jobs:
# lib/: the CLI and its production deps (including workspace core/server/skills, all build outputs);
# Use pnpm's current deploy implementation with injected workspace packages; the hoisted target layout
# avoids deeply nested .pnpm/node_modules paths that exceed Windows PowerShell 5.1's legacy MAX_PATH limit.
- # bin/penguin launcher: resolve its own real path (following symlinks) -> default PENGUIN_WEB_DIST to
- # the sibling web/ -> use the bundled runtime (node/bin/node) if present, else fall back to system node.
+ # bin/penguin is scripts/launchers/penguin, shipped verbatim — it is the one spelling of
+ # the payload layout (lib/dist/penguin.js, web/, an optional node/), and the shape
+ # scripts/test-installer.sh pins.
- name: Assemble penguin/ (lib + web + bin)
run: |
pnpm --config.node-linker=hoisted --filter @prismshadow/penguin-cli --prod deploy "$PWD/out/penguin/lib"
cp -r packages/web/dist out/penguin/web
- mkdir -p out/penguin/bin
- cat > out/penguin/bin/penguin <<'EOF'
- #!/bin/sh
- SELF="$0"
- while [ -h "$SELF" ]; do
- DIR="$(cd "$(dirname "$SELF")" && pwd)"
- SELF="$(readlink "$SELF")"
- case "$SELF" in /*) ;; *) SELF="$DIR/$SELF" ;; esac
- done
- DIR="$(cd "$(dirname "$SELF")/.." && pwd)"
- export PENGUIN_WEB_DIST="${PENGUIN_WEB_DIST:-$DIR/web}"
- if [ -x "$DIR/node/bin/node" ]; then
- exec "$DIR/node/bin/node" "$DIR/lib/dist/penguin.js" "$@"
- fi
- exec node "$DIR/lib/dist/penguin.js" "$@"
- EOF
- chmod +x out/penguin/bin/penguin
+ install -D -m 755 scripts/launchers/penguin out/penguin/bin/penguin
# Program payloads: linux runtimes use .tar.xz, darwin .tar.gz (nodejs.org naming);
# node/ is only lightly trimmed (drop share/doc and share/man, keep the rest). Payloads
@@ -254,14 +239,9 @@ jobs:
tar -czf payloads/universal.tar.gz -C out penguin
# Windows payload: same lib/ + web/ layout, but a .zip (the native format), the official
- # win-x64 Node runtime — whose zip has node.exe at the ARCHIVE ROOT, not bin/ — and a
- # cmd launcher replacing the sh one (resolves its own dir, defaults PENGUIN_WEB_DIST to
- # the sibling web\, prefers the bundled node\node.exe, falls back to system node).
- # Deliberately NO penguin.ps1 launcher: PowerShell prefers .ps1 over .cmd on PATH, and
- # client Windows defaults to the Restricted execution policy, so shipping one makes the
- # plain `penguin` command fail with "running scripts is disabled" out of the box. Batch
- # files are exempt from the policy and both PowerShell and cmd.exe resolve penguin.cmd,
- # which forwards all args and the exit code.
+ # win-x64 Node runtime — whose zip has node.exe at the ARCHIVE ROOT, not bin/ — and
+ # penguin.cmd replacing the sh launcher (see scripts/launchers/penguin.cmd, including why
+ # there is deliberately no penguin.ps1).
#
# It also bundles MinGit under git\, so exec_command has a POSIX shell even on a machine
# with no Git for Windows: the shims advertise git\usr\bin\sh.exe as PENGUIN_BUNDLED_SHELL
@@ -286,23 +266,12 @@ jobs:
# Fail loudly here rather than shipping a package whose shell silently does not exist.
test -f out/penguin/git/usr/bin/sh.exe
test -f out/penguin/git/etc/profile
- rm -f out/penguin/bin/penguin
printf '{"schemaVersion":1,"target":"win32-x64"}\n' > out/penguin/package-manifest.json
- cat > out/penguin/bin/penguin.cmd <<'EOF'
- @echo off
- setlocal
- set "DIR=%~dp0.."
- if not defined PENGUIN_WEB_DIST set "PENGUIN_WEB_DIST=%DIR%\web"
- if exist "%DIR%\git\usr\bin\sh.exe" set "PENGUIN_BUNDLED_SHELL=%DIR%\git\usr\bin\sh.exe"
- if exist "%DIR%\node\node.exe" (
- "%DIR%\node\node.exe" "%DIR%\lib\dist\penguin.js" %*
- ) else (
- node "%DIR%\lib\dist\penguin.js" %*
- )
- exit /b %ERRORLEVEL%
- EOF
- # cmd.exe is only fully reliable with CRLF batch files.
- sed -i 's/$/\r/' out/penguin/bin/penguin.cmd
+ # The Windows package ships penguin.cmd INSTEAD of the sh launcher: a bare `penguin`
+ # on PATH would be picked up by Git Bash and run the wrong thing. The committed file
+ # is CRLF (.gitattributes), the only form cmd.exe is fully reliable with.
+ rm -f out/penguin/bin/penguin
+ install -D -m 644 scripts/launchers/penguin.cmd out/penguin/bin/penguin.cmd
(cd out && zip -qr ../payloads/win32-x64.zip penguin)
# The canonical artifacts: each payload is sealed with its checksum and the native
diff --git a/.prettierignore b/.prettierignore
index 2fc9749a..2f5cbb64 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -2,6 +2,9 @@
node_modules/
dist/
pnpm-lock.yaml
+# the assembled app directory some branches stage before packing (packages/desktop/.gitignore
+# ignores it there; prettier does not read .gitignore, so it needs saying again here)
+packages/desktop/stage/
# desktop build output: the installers electron-builder writes, and the assets
# scripts/build-assets.mjs copies in beside them (formatted in their own packages)
diff --git a/changelog/unreleased/2026-08-24-machines.md b/changelog/unreleased/2026-08-24-machines.md
new file mode 100644
index 00000000..8d8b3b55
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-machines.md
@@ -0,0 +1,41 @@
+# Install a server on another machine, from the Machines page
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `server`, `web`, `desktop`, `cli`, `tooling`, `docs`
+- **PR:** [#447](https://github.com/Prism-Shadow/penguin-harness/pull/447)
+
+[中文版](2026-08-24-machines.zh.md)
+
+**Machines**, a new page under Models, lists the hosts in the server's own `~/.ssh/config` and installs this build of PenguinHarness on the one you pick. It replaces the desktop app's **Install Server on Remote Host** menu entry, which shipped only inside the Electron shell.
+
+## Picking a host
+
+Targets come from `~/.ssh/config` and nowhere else — the config text, read once, with no `ssh -G` and no network. `Host *` patterns are skipped and `Include` globs expand the way OpenSSH expands them; the file is never written. An alias is resolved to a user, hostname and port only when it is installed to, and that resolution is `ssh -G`'s job, so `Match` and wildcard inheritance behave exactly as ssh says.
+
+Because a config routinely declares hundreds of entries, the hosts are a searchable picker rather than a list. The query matches as a **subsequence** (`gpu1` finds `gpu-01`), the matched characters are highlighted, and a counter names how many the view leaves out.
+
+Admin only: the install spawns ssh with the **server account's** keys and writes a program directory on another machine. Connections run `BatchMode=yes` — nothing here has a terminal for a password prompt — and OpenSSH's own diagnostic is shown verbatim when a key does not work.
+
+## What gets installed
+
+The release this server stands on, installed by the ordinary installer: the remote runs `install.sh` / `install.ps1` online, pinned to this server's own base version, and downloads the standard artifact — launchers, libs, web assets, bundled runtime — from the release sources over its own network (GitHub, or the OSS mirror the installer speed-picks). The ssh channel carries only the installer script.
+
+When this server itself runs a hot-pushed version, that state travels too: `hmr/harness.json` and the store are streamed across (local tar → ssh), and the remote's next boot runs the same pushed platform, web and CLI. The Machines page then shows the combined version, `<base>+hmr.<sha>`.
+
+A matching base skips the download; matching base and pushed state does nothing. The remote is left with what an ordinary install plus a push leaves — the program directory, on POSIX the `~/.local/bin/penguin` symlink, and the data root's `hmr/` state. No sudo, no systemd unit, no profile edits, and the rest of the data root is never touched.
+
+## Watching it, and what stays
+
+An install takes minutes in the bad case, so it is a job: the page starts it and polls, showing the far side's own words. One runs at a time, and the panel follows the job rather than the current selection. The job lives in server memory; re-running is the recovery, since every step is idempotent and the installer stages, smoke-tests and swaps, restoring the previous installation if anything fails after the swap begins.
+
+Which hosts carry this program is recorded in `<data root>/machines-installs.json` and listed under **Installed machines** with the version and time. It is what this server did, not a survey: a machine wiped by hand reads as installed until the next install corrects the record.
+
+## Details
+
+- New API, admin only: `GET /api/machines` and `POST /api/machines/:machineId/install`.
+- The capability moved from `packages/desktop/src/remote/` to `packages/server/src/machines/`, which is what makes it reachable from a browser, available to a tarball install, and shippable by hot push.
+- The far side runs the ordinary installers online — no payload is assembled or transferred, and staging, smoke test, swap, rollback and the PATH plumbing are the one implementation every release install runs. The trade: the remote must be able to reach GitHub or the OSS mirror for its first install and for base upgrades.
+- One payload layout, spelled once. `bin/penguin` and `bin/penguin.cmd` were written in four places — as shell heredocs in the release workflow and as strings inside three JavaScript modules — and the copies had drifted about where `web/` and the bundled runtime sat. They are now two ordinary files under `scripts/launchers/`, copied verbatim into each release package: readable, diffable, and runnable on their own.
+- The desktop app no longer stages a ~190 MB install image into its resources. Nothing read it: the app forks the server as one bundled file, so the lookup that was supposed to find that image never matched a packaged app at all — which also means the Machines page never worked there. A packaged app now names its release from its own manifest, and carries the ~4 KB installer scripts instead of an image: the far side downloads the release itself.
+- `install.ps1`'s fallback launcher — written only when a payload arrives without one — named a CLI entry (`lib\dist\index.js`) that has never existed.
diff --git a/changelog/unreleased/2026-08-24-machines.zh.md b/changelog/unreleased/2026-08-24-machines.zh.md
new file mode 100644
index 00000000..0f9ff5f4
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-machines.zh.md
@@ -0,0 +1,41 @@
+# 在 Machines 页面上,把服务端装到另一台机器
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `server`, `web`, `desktop`, `cli`, `tooling`, `docs`
+- **PR:** [#447](https://github.com/Prism-Shadow/penguin-harness/pull/447)
+
+[English](2026-08-24-machines.md)
+
+**Machines** 是 Models 之下的新页面:列出服务端自己 `~/.ssh/config` 里的主机,把当前这份 PenguinHarness 装到你选中的那台上。它取代了桌面端的 **Install Server on Remote Host** 菜单项——那一项只存在于 Electron 外壳里。
+
+## 选一台主机
+
+目标只来自 `~/.ssh/config`:读一次配置文本,不跑 `ssh -G`,不碰网络。`Host *` 这类模式条目会跳过,`Include` 的通配按 OpenSSH 的方式展开;文件永不被写。别名只在真正安装时才解析成用户、主机名和端口,而那一步交给 `ssh -G`,所以 `Match` 与通配继承的行为和 ssh 说的完全一致。
+
+一份配置动辄声明上百条,所以主机是可搜索的选择器而不是列表。查询按**子序列**匹配(`gpu1` 能找到 `gpu-01`),命中的字符会高亮,计数会说明当前视图漏掉了多少条。
+
+仅管理员可见:安装会用**服务端账号**的密钥拉起 ssh,并在另一台机器上写程序目录。连接带 `BatchMode=yes`——这里没有终端可供输入密码——密钥不通时原样展示 OpenSSH 自己的诊断信息。
+
+## 装上去的是什么
+
+这台服务端立足的那个 release,由常规安装器安装:远端在线运行 `install.sh` / `install.ps1`,钉在本机自己的底座版本上,经它自己的网络从 release 源(GitHub,或安装器测速选中的 OSS 镜像)下载标准产物——启动脚本、依赖库、Web 资源、内置运行时。ssh 通道只携带安装脚本本身。
+
+若本机正在跑热推的版本,这份状态也一并过去:`hmr/harness.json` 和 store 以流的方式复制(本地 tar → ssh),远端下次启动就运行同一份推送的 platform、web 与 CLI。Machines 页面随之显示合成版本 `<base>+hmr.<sha>`。
+
+底座相同则跳过下载;底座与推送状态都相同则什么都不做。远端最后拿到的和"普通安装 + 一次推送"留下的一样——程序目录、POSIX 上的 `~/.local/bin/penguin` 软链、数据根下的 `hmr/` 状态。不用 sudo,不写 systemd unit,不改 profile,数据根的其余部分从不被碰。
+
+## 过程与留存
+
+最坏情况下一次安装要几分钟,所以它是一个 job:页面发起后轮询,显示对端自己的输出。同一时刻只跑一个,面板跟随 job 而不是当前选中项。job 存在服务端内存里;重跑就是恢复手段——每一步都幂等,安装器会先暂存、冒烟测试再切换,切换开始后若失败则恢复上一份安装。
+
+哪些主机装过这份程序记在 `<数据根>/machines-installs.json`,在 **Installed machines** 下按版本和时间列出。它记录的是这台服务端做过什么,不是对远端的普查:被手工清掉的机器仍显示为已安装,直到下一次安装纠正这条记录。
+
+## 细节
+
+- 新增 API,仅管理员:`GET /api/machines` 与 `POST /api/machines/:machineId/install`。
+- 该能力从 `packages/desktop/src/remote/` 移到 `packages/server/src/machines/`,因此它能从浏览器触达、对 tarball 安装可用、并可随热推分发。
+- 对端跑的就是常规安装器的在线模式——不再组装或传输任何载荷;暂存、冒烟测试、切换、回滚和 PATH 处理就是每次 release 安装跑的那一份实现。交换条件:远端首装与底座升级时必须能访问 GitHub 或 OSS 镜像。
+- 载荷布局只写一遍。`bin/penguin` 与 `bin/penguin.cmd` 此前写在四处——release 工作流里的 shell heredoc,以及三个 JavaScript 模块里的字符串——副本已就 `web/` 和内置运行时的位置发生漂移。现在它们是 `scripts/launchers/` 下的两个普通文件,原样复制进每个 release 包:可读、可 diff、可直接运行。
+- 桌面端不再往 resources 里塞约 190 MB 的安装镜像。没有任何东西读它:桌面端把 server 打成单文件运行,本该找到该镜像的那段查找在打包后的应用里从来没有匹配成功过——这也意味着 Machines 页在桌面端一直不可用。打包后的应用现在从自己的清单读出所属 release,并改为携带约 4 KB 的安装脚本而非整份镜像:对端自己下载 release。
+- `install.ps1` 的兜底启动脚本——只在载荷未自带时写出——指向了一个从未存在过的 CLI 入口(`lib\dist\index.js`)。
diff --git a/install.ps1 b/install.ps1
index cc92dd2d..f996d218 100644
--- a/install.ps1
+++ b/install.ps1
@@ -614,9 +614,9 @@ try {
'if not defined PENGUIN_WEB_DIST set "PENGUIN_WEB_DIST=%DIR%\web"'
'if exist "%DIR%\git\usr\bin\sh.exe" set "PENGUIN_BUNDLED_SHELL=%DIR%\git\usr\bin\sh.exe"'
'if exist "%DIR%\node\node.exe" ('
- ' "%DIR%\node\node.exe" "%DIR%\lib\dist\index.js" %*'
+ ' "%DIR%\node\node.exe" "%DIR%\lib\dist\penguin.js" %*'
') else ('
- ' node "%DIR%\lib\dist\index.js" %*'
+ ' node "%DIR%\lib\dist\penguin.js" %*'
')'
'exit /b %ERRORLEVEL%'
) | Set-Content -LiteralPath $CmdShim -Encoding ascii
diff --git a/packages/desktop/scripts/build-assets.mjs b/packages/desktop/scripts/build-assets.mjs
index 9eb37cab..281bca81 100644
--- a/packages/desktop/scripts/build-assets.mjs
+++ b/packages/desktop/scripts/build-assets.mjs
@@ -17,6 +17,12 @@
* build/ is electron-builder's buildResources directory and does not ship inside the app.
* - `bin/penguin`, `bin/penguin.cmd` — the CLI launchers, whose script text lives in
* src/launcher.ts so it is unit-tested with the rest of the shell.
+ * - `dist/install.sh`, `dist/install.ps1` — the release installers, which the Machines page
+ * scp's to an SSH host and runs there (packages/server/src/machines/install-server.ts
+ * resolves them beside its own module). The server package ships them in its own dist/,
+ * but this app re-bundles the server into a single dist/server.js and a bundle carries no
+ * sibling files, so they are copied in again here. Only the ~4 KB scripts travel: the far
+ * side downloads the release itself.
*
* Run from anywhere (after tsup); all paths derive from this file's location.
*/
@@ -43,6 +49,16 @@ const skillsDest = path.join(pkgDir, "skills");
fs.rmSync(skillsDest, { recursive: true, force: true });
fs.cpSync(skillsSrc, skillsDest, { recursive: true });
+const repoRoot = path.resolve(pkgDir, "..", "..");
+for (const name of ["install.sh", "install.ps1"]) {
+ const src = path.join(repoRoot, name);
+ if (!fs.existsSync(src)) {
+ console.error(`[build-assets] ${name} is missing from the repository root.`);
+ process.exit(1);
+ }
+ fs.copyFileSync(src, path.join(distDir, name));
+}
+
const iconSrc = path.join(pkgDir, "build", "icon.png");
if (!fs.existsSync(iconSrc)) {
console.error("[build-assets] build/icon.png is missing — run `node scripts/render-icon.mjs`.");
@@ -86,5 +102,5 @@ fs.chmodSync(path.join(binDir, "penguin"), 0o755);
fs.writeFileSync(path.join(binDir, "penguin.cmd"), windowsLauncherScript());
console.log(
- `[build-assets] done: skills/, dist/icon.png, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,
+ `[build-assets] done: skills/, dist/icon.png, dist/install.{sh,ps1}, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,
);
diff --git a/packages/desktop/src/menu.ts b/packages/desktop/src/menu.ts
index d60b5ac2..c62e0091 100644
--- a/packages/desktop/src/menu.ts
+++ b/packages/desktop/src/menu.ts
@@ -1,7 +1,11 @@
/**
* Application menu. Electron's default menu cannot be extended, only replaced, so the
* standard structure is rebuilt here. The custom entries are native-only shell actions:
- * installing the bundled `penguin` command and checking for desktop updates.
+ * installing the bundled `penguin` command, and checking for desktop updates.
+ *
+ * Installing this build's server onto an SSH host used to live here too; it is now the
+ * Machines page in the Web App, served by the server itself (packages/server/src/machines)
+ * so that it travels by hot push and works in a browser, not just in this shell.
*/
import { app, Menu, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
diff --git a/packages/desktop/test/installer-assets.test.ts b/packages/desktop/test/installer-assets.test.ts
new file mode 100644
index 00000000..11ff0973
--- /dev/null
+++ b/packages/desktop/test/installer-assets.test.ts
@@ -0,0 +1,24 @@
+/**
+ * The release installers staged into this app's dist/ by scripts/build-assets.mjs.
+ *
+ * The Machines page scp's one of them to an SSH host and runs it there; install-server.ts
+ * resolves it beside its own module, which in a packaged app is dist/server.js. The server
+ * package ships them in its own dist/, but this app re-bundles the server into one file and
+ * a bundle carries no sibling files — so nothing in the module graph would notice them going
+ * missing, and a remote install would fail at "prepare the installer" instead.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const repoRoot = path.resolve(pkgDir, "..", "..");
+
+describe("staged release installers", () => {
+ it.each(["install.sh", "install.ps1"])("%s is copied into dist at build time", (name) => {
+ const built = path.join(pkgDir, "dist", name);
+ if (!fs.existsSync(built)) return; // Not built in this run; `pnpm build` covers it in CI.
+ expect(fs.readFileSync(built, "utf8")).toBe(fs.readFileSync(path.join(repoRoot, name), "utf8"));
+ });
+});
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index a6a263d6..3fbd8e27 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -108,6 +108,23 @@ The upload limits are two whole-MB integers governing composer file attachments;
In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::1` (loopback is never proxied).
+### Machines (admin only)
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | /api/machines | The host aliases of the SERVER's own `~/.ssh/config`, the version this server would install, and the running or last install job: `{machines: [{id, alias, installed}], imageVersion, job}` |
+| POST | /api/machines/:machineId/install | Start installing this build on that host; `202` with the same body, the job now running |
+
+Admin only on a personal server as much as a multi-user one: the install spawns ssh with the **server account's** keys and writes a program directory on another machine, which is an owner's capability rather than a visitor's. Nothing writes to the ssh config — it is read, and `ssh -G` resolves an alias only at install time, so a config declaring hundreds of hosts costs one file read.
+
+`imageVersion` is what would be pushed, or `null` when this server has no image at all (a development checkout that has never been hot-pushed to is the one such shape) — every install then refuses with `409` `no_install_image`. The version is the running install's own: a hot-pushed server sends the bundle it runs (`0.0.0-hmr.<cli>.<web>`), a tarball or packaged one sends its own tree, so the two ends match by construction.
+
+`installed` is the last install THIS server carried out on that machine — `{version, at}`, or `null` when it never has. It is persisted under the data root, so it survives a restart, a hot push, and installing on some other machine; a record of what was done rather than a survey of the far side, so a machine wiped by hand still reads as installed until the next install corrects it. A failed install records nothing.
+
+An install is a job, not a request: it probes the far side, may fetch and verify a Node runtime, and copies an image over scp — minutes in the bad case. `POST` starts it and returns at once; the client polls `GET` for `job.log`, which carries the far side's own words (ssh's diagnostics, the remote installer's output). `job.result` is `null` while running, then `{ok: true, kind: "installed" | "already-installed", version}` or `{ok: false, step, message}`. One job at a time; the job lives in memory and does not survive a hot push or a restart, and re-running is the recovery — every step is idempotent.
+
+Refusals decided before any ssh runs have their own codes: `409` `install_running`, `404` `unknown_machine`, `409` `no_install_image`, `502` `unresolvable_host`.
+
### Version and Self-Update
| Method | Path | Description |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 05252d76..a0d3c99d 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -108,6 +108,23 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
- PUT 校验:两者都必须是 1 到 200 之间的整数,且**生效后**的合计值(本次 PUT 给出的值,或本次不修改时的存量值)不得低于生效后的单个上限。其余一律 `400`,错误码 `invalid_attachment_limit`,且被拒绝的 PUT 不写入任何字段。
- 不可配置项:单条消息的附件数量(20)与内嵌图片上限(20MB,超出返回 `413` `image_too_large`)。内嵌图片会写入轨迹,并在每次翻阅历史与恢复会话时被重新读取,因此刻意不随附件上限放宽;`GET /api/me` 会在 `uploadLimits` 下报告以上全部数值,客户端据此按当前生效的上限预先校验。
+### 机器(仅管理员)
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | /api/machines | **服务端自身** `~/.ssh/config` 中的主机别名、本服务端会安装的版本,以及正在运行或最近一次的安装任务:`{machines: [{id, alias, installed}], imageVersion, job}` |
+| POST | /api/machines/:machineId/install | 在该主机上安装当前构建;返回 `202` 与同样的响应体,此时任务已在运行 |
+
+无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写,`ssh -G` 仅在真正安装时才解析别名,因此哪怕配置声明了几百台主机,列表也只是一次文件读取。
+
+`imageVersion` 是将被推送的版本;为 `null` 表示本服务端根本没有安装镜像(只有从未被热推过的源码检出会是这种形态),此时任何安装都会以 `409` `no_install_image` 拒绝。该版本取自当前运行的安装自身:热推过的服务端推送它正在运行的 bundle(`0.0.0-hmr.<cli>.<web>`),tarball 或打包安装则推送自己的程序树,因此两端的一致是构造性的。
+
+`installed` 是**本服务端**最近一次在该机器上完成的安装——`{version, at}`,从未安装过则为 `null`。它持久化在数据根目录下,因此能跨重启、跨热推、跨「在别的机器上安装」而保留;它记录的是本端做过什么,而非对远端的实地探查,所以被手工清空的远端仍显示为已安装,直到下一次安装将其修正。安装失败不写入任何记录。
+
+安装是任务而非请求:它要探测对端,可能下载并校验一份 Node 运行时,再经 scp 复制镜像——最坏情况以分钟计。`POST` 启动后立即返回,客户端轮询 `GET` 读取 `job.log`,其中是对端自己的原话(ssh 的诊断、远端安装器的输出)。运行期间 `job.result` 为 `null`,结束后为 `{ok: true, kind: "installed" | "already-installed", version}` 或 `{ok: false, step, message}`。同一时刻只允许一个任务;任务存于内存,热推与重启都不保留,重跑即是恢复手段——每一步都是幂等的。
+
+在任何 ssh 运行之前就能判定的拒绝各有错误码:`409` `install_running`、`404` `unknown_machine`、`409` `no_install_image`、`502` `unresolvable_host`。
+
### 版本与在线更新
| 方法 | 路径 | 说明 |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index a92f4abc..131812f1 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3012,3 +3012,54 @@ export interface UpdateRunResponse {
/** True when the install changed (or was already current): restart the service to run the new version. */
needsRestart: boolean;
}
+
+/** One `Host` entry of the server's `~/.ssh/config`, as the Machines page lists it. */
+export interface MachineInfo {
+ /** `ssh:<alias>` — the id the install route is asked for. */
+ id: string;
+ /**
+ * The alias exactly as written in the config. The list is the config text and nothing
+ * else — no `ssh -G`, no processes, no network — so a config declaring hundreds of hosts
+ * costs one file read; an alias is resolved only when it is actually installed to.
+ */
+ alias: string;
+ /**
+ * The last install THIS server carried out there, remembered on disk so it survives a
+ * restart, a hot push, and installing on some other machine. Null when this server has
+ * never installed there.
+ *
+ * A record of what was done, not a survey of the far side: a machine wiped by hand still
+ * reads as installed until the next install probes it and corrects the record. Asking the
+ * remote instead would cost an ssh round trip per host at page load, which is the price
+ * the config-text list exists to avoid.
+ */
+ installed: { version: string; at: string } | null;
+}
+
+/**
+ * The running or last install, polled by GET /api/machines while one runs. `log` carries the
+ * far side's own words where there are any: ssh's diagnostics and the remote installer's
+ * output say more about a refused key or an unusable Node than a paraphrase would.
+ */
+export interface MachineInstallJob {
+ machineId: string;
+ alias: string;
+ running: boolean;
+ log: string[];
+ result:
+ | null
+ | { ok: true; kind: "installed" | "already-installed"; version: string | null }
+ | { ok: false; step: string; message: string };
+}
+
+/** GET /api/machines, and the 202 body of POST /api/machines/:machineId/install. */
+export interface MachinesResponse {
+ machines: MachineInfo[];
+ /**
+ * The version an install would leave on the remote — the base release, plus a `+hmr.<sha>`
+ * suffix when this server carries a pushed version to replicate. Null for a development
+ * checkout, which stands on no release the remote could download.
+ */
+ imageVersion: string | null;
+ job: MachineInstallJob | null;
+}
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 925f9a75..5db8dc60 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -149,8 +149,10 @@ import { usageRoutes } from "./http/routes/usage.js";
import { agentSessionsRoutes, sessionsRoutes } from "./http/routes/sessions.js";
import { sessionMessagingRoutes } from "./http/routes/messaging.js";
import { versionRoutes } from "./http/routes/version.js";
+import { machinesRoutes } from "./http/routes/machines.js";
import { UsageRecorder } from "./runtime/usage-recorder.js";
import { previewRoutes } from "./http/routes/preview.js";
+import { MachinesService } from "./machines/service.js";
export interface AppDeps {
config: ServerConfig;
@@ -198,6 +200,12 @@ export interface AppDeps {
errors: ErrorRecorder;
/** Desktop mode (PENGUIN_DESKTOP_TOKEN): one-shot login + shutdown token holder; null outside desktop mode. */
desktop: DesktopService | null;
+ /**
+ * Installing this build on a machine from the server's own `~/.ssh/config` (the Machines
+ * page). Business, not runtime: spawning ssh and packing an image are in-process effects,
+ * so the whole capability ships by push — see machines/service.ts.
+ */
+ machines: MachinesService;
/** HMR host: loads/swaps/persists the platform and web bundles (park/boot kernel). */
hmr: HmrHost;
/**
@@ -234,6 +242,8 @@ export interface BuildDepsOverrides {
messagingInboundImageBudgetBytes?: number;
/** Test double: the QQ scan-to-connect transport (avoids real q.qq.com requests). */
qqScanTransport?: QQScanTransport;
+ /** Test double: machines service whose ssh effects are faked (the real one reads ~/.ssh/config and spawns ssh). */
+ machines?: MachinesService;
/**
* Test double: scrypt work factor for password hashes written through this app.
* Omitted in production, where the KDF runs at full strength.
@@ -937,6 +947,9 @@ export function buildAppDeps(
sessionSources,
errors,
desktop: caps.desktop,
+ // Anchored at the data root: that is where the hmr store the pushable image comes from
+ // lives, and where verified Node runtime downloads are cached between installs.
+ machines: overrides.machines ?? new MachinesService(config.root, {}, () => hmr.assetsDir()),
hmr,
proxyControl: caps.proxyControl,
log,
@@ -1033,6 +1046,7 @@ export function createApp(
app.route("/api/version", versionRoutes(deps));
app.route("/api/admin/users", adminUsersRoutes(deps));
app.route("/api/admin/settings", adminSettingsRoutes(deps));
+ app.route("/api/machines", machinesRoutes(deps));
app.route("/api/events", eventsRoutes(deps));
// Skill library listing: readable once logged in, not nested under a Project prefix.
app.route("/api/skills", skillLibraryRoutes());
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
index d5dda402..da2e0559 100644
--- a/packages/server/src/hmr/platform.ts
+++ b/packages/server/src/hmr/platform.ts
@@ -272,8 +272,11 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// registry id the successor owns
// Known exceptions, accepted with reasons: an in-flight self-update child (rare,
// bounded by its own 10-minute cap, and a successful update restarts the process
- // anyway) and SSE subscriber closures (they serve the old generation's stream until
- // the client reloads on web_updated — the channel hub itself is runtime-owned).
+ // anyway); an in-flight machines install (same shape — its ssh children run to their
+ // own timeouts, the far side's installer stages-and-swaps or rolls back on its own,
+ // and the progress log is simply lost, which re-running recovers); and SSE subscriber
+ // closures (they serve the old generation's stream until the client reloads on
+ // web_updated — the channel hub itself is runtime-owned).
// A build that adds a service with state of its own (sandbox settings, workflow
// refs, ssh tunnels, an in-flight job) adds it to the right list here — the list is
// the contract, not a description of today's services.
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
new file mode 100644
index 00000000..66d25c5b
--- /dev/null
+++ b/packages/server/src/http/routes/machines.ts
@@ -0,0 +1,69 @@
+/**
+ * Machines routes (admin only, 403 for non-admins):
+ * GET /api/machines — the ssh config's host aliases, the version this
+ * server would install, and the running or last job.
+ * POST /api/machines/:machineId/install — start an install; 202, or 409 when one runs.
+ *
+ * Admin rather than any logged-in user, on a multi-user server as much as a personal one:
+ * installing spawns ssh with the SERVER ACCOUNT's keys and writes a program directory on
+ * another machine. That is an owner's capability, not a visitor's, and the account whose
+ * keys are used is not the account making the request.
+ *
+ * The install is a job because it can take minutes (see ../../machines/service.ts); this
+ * route only starts it and reports it. Progress arrives by polling GET rather than over the
+ * event channel — the log lines belong to one page that is open while it waits, and a job
+ * that dies with its App has nothing to replay to a reconnecting subscriber.
+ */
+import { Hono } from "hono";
+import type { MachinesResponse } from "../../api/types.js";
+import { HttpError } from "../errors.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { AppDeps } from "../../app.js";
+
+export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.use("*", async (c, next) => {
+ if (!c.var.user.isAdmin) {
+ throw new HttpError(403, "admin_required", "Only an admin can install on a machine.");
+ }
+ await next();
+ });
+
+ const state = (): MachinesResponse => ({
+ machines: deps.machines.list(),
+ imageVersion: deps.machines.imageVersion(),
+ job: deps.machines.job(),
+ });
+
+ app.get("/", (c) => c.json(state()));
+
+ app.post("/:machineId/install", async (c) => {
+ const started = await deps.machines.startInstall(c.req.param("machineId"));
+ if (!started.ok) {
+ // Each refusal is its own code: the page renders a sentence per case, and "no image"
+ // in particular is a property of THIS server rather than of the machine picked.
+ if (started.why === "busy") {
+ throw new HttpError(409, "install_running", "An install is already running.");
+ }
+ if (started.why === "unknown-machine") {
+ throw new HttpError(404, "unknown_machine", "No such host in this server's ssh config.");
+ }
+ if (started.why === "no-image") {
+ throw new HttpError(
+ 409,
+ "no_install_image",
+ "This server has no install image to push. A packaged or installed server carries one; a development checkout gets one from its first hot push.",
+ );
+ }
+ throw new HttpError(
+ 502,
+ "unresolvable_host",
+ "ssh could not resolve that host. Check ~/.ssh/config, or that ssh is on PATH.",
+ );
+ }
+ return c.json(state(), 202);
+ });
+
+ return app;
+}
diff --git a/packages/server/src/machines/commands.ts b/packages/server/src/machines/commands.ts
new file mode 100644
index 00000000..c2e5178e
--- /dev/null
+++ b/packages/server/src/machines/commands.ts
@@ -0,0 +1,121 @@
+/**
+ * The exact ssh/scp invocations a remote install runs, built as argv arrays (no shell on this
+ * side) plus the small commands the far side executes. Pure, so every command this app would
+ * run against someone's machine is unit-visible.
+ *
+ * Three things run through a remote SHELL — probe, run the release installer, unpack the
+ * replicated hmr store — and each has a POSIX and a Windows form, because a default Windows
+ * OpenSSH session is cmd.exe, where `;`, `$VAR`, `'…'` and `rm` mean nothing. The installer
+ * itself is the ordinary one (install.sh, install.ps1), downloading the pinned release from
+ * the remote's own network.
+ *
+ * COUNT THE HANDSHAKES. Every one of these is a separate ssh connection, and a handshake to
+ * a distant or loaded host costs tens of seconds — so a step that can ride an existing
+ * connection must. A POSIX install is one call: the installer goes in on ssh's stdin, the
+ * same shape as the documented `curl … | sh`, which is what lets the scratch directory, the
+ * scp and the cleanup disappear entirely.
+ *
+ * Two further rules encoded here:
+ * - **BatchMode.** A GUI app has no terminal: an ssh that decides to ask for a password or a
+ * key passphrase would hang forever with nothing to type into. BatchMode turns that into an
+ * immediate, readable failure — v1 is key/agent auth, exactly as the design says.
+ * - **The user override rides the command line, never the config.** `-o User=…` selects the
+ * account for this connection; `~/.ssh/config` is read-only to us.
+ */
+import type { RemotePlatform } from "./detect.js";
+
+/** Wraps a value for a POSIX remote shell. Single quotes are literal there, except `'` itself. */
+export function shQuote(value: string): string {
+ return `'${value.replaceAll("'", `'\\''`)}'`;
+}
+
+/**
+ * Wraps a value for cmd.exe. There is no escape for `"` inside a quoted string, so a path
+ * containing one is refused rather than mis-executed — it cannot occur in a Windows path
+ * anyway, and guessing would be worse than saying so.
+ */
+export function cmdQuote(value: string): string {
+ if (value.includes('"')) throw new Error(`cannot quote for cmd.exe: ${value}`);
+ return `"${value}"`;
+}
+
+export const quoteFor = (platform: RemotePlatform, value: string): string =>
+ platform === "win32" ? cmdQuote(value) : shQuote(value);
+
+export interface RemoteTarget {
+ /** Alias as written in ~/.ssh/config — what the user picked. */
+ alias: string;
+ /** Login account. Empty means "whatever ssh resolves", i.e. no -o User override. */
+ user: string;
+}
+
+function connectionOptions(target: RemoteTarget): string[] {
+ return [
+ "-o",
+ "BatchMode=yes",
+ "-o",
+ "ConnectTimeout=10",
+ ...(target.user === "" ? [] : ["-o", `User=${target.user}`]),
+ ];
+}
+
+/** `ssh <options> <alias> <remote command>`. */
+export function sshArgs(target: RemoteTarget, remoteCommand: string): string[] {
+ return [...connectionOptions(target), target.alias, remoteCommand];
+}
+
+/**
+ * `scp <options> <files…> <alias>:<dir>`. The remote path is NOT quoted: current OpenSSH
+ * transfers over SFTP, where the path is taken literally and quotes would become part of the
+ * name. Scratch directories are chosen without quotes or shell metacharacters for that reason.
+ */
+export function scpArgs(target: RemoteTarget, localFiles: string[], remoteDir: string): string[] {
+ return [...connectionOptions(target), ...localFiles, `${target.alias}:${remoteDir}`];
+}
+
+/**
+ * Runs the ordinary installer on the far side, pinned to this server's own base release so
+ * the remote downloads exactly the version this side stands on.
+ *
+ * The two forms differ in WHERE THE SCRIPT IS, which is why that is in the type rather than
+ * in a comment: POSIX takes it on stdin (`sh -s`, the same shape as the documented
+ * `curl … | sh`), so the returned command carries no path and `scriptOnStdin` says the caller
+ * must pipe it — the command alone is only half the invocation. Windows cannot: `param()` is
+ * not valid in a PowerShell command stream, and `-File -` is PowerShell 7 only while a remote
+ * may have 5.1, so the script is copied to a path first and that path is required to build
+ * the command at all. Its delete is chained on rather than costing another handshake, and
+ * `-ExecutionPolicy Bypass` covers client Windows defaulting to Restricted.
+ *
+ * `versionTag` is a release tag (`v` + semver); the caller validated the spelling, and the
+ * quoting here keeps it one word regardless.
+ */
+export function runInstallScriptCommand(
+ versionTag: string,
+ where: { platform: "linux" | "darwin" } | { platform: "win32"; scriptPath: string },
+): { command: string; scriptOnStdin: boolean } {
+ if (where.platform === "win32") {
+ const script = cmdQuote(where.scriptPath);
+ return {
+ command:
+ `powershell -NoProfile -ExecutionPolicy Bypass -File ${script} -Version ${cmdQuote(versionTag)}` +
+ ` & del /q ${script}`,
+ scriptOnStdin: false,
+ };
+ }
+ return { command: `PENGUIN_VERSION=${shQuote(versionTag)} sh -s`, scriptOnStdin: true };
+}
+
+/**
+ * Unpacks the replicated hmr state (harness.json + store/), streamed to ssh's stdin as one
+ * tar.gz, into the remote's default data root — where a server this page installed will look
+ * for it on boot (hmr/host.ts's restore). `tar` reads stdin with `-f -` on both sides;
+ * Windows 10+ ships bsdtar.
+ */
+export function unpackStoreCommand(platform: RemotePlatform): string {
+ if (platform === "win32") {
+ const root = "%USERPROFILE%\\.penguin\\data";
+ return `(if not exist ${cmdQuote(root)} mkdir ${cmdQuote(root)}) & tar -xzf - -C ${cmdQuote(root)}`;
+ }
+ const root = "$HOME/.penguin/data";
+ return `mkdir -p "${root}" && tar -xzf - -C "${root}"`;
+}
diff --git a/packages/server/src/machines/detect.ts b/packages/server/src/machines/detect.ts
new file mode 100644
index 00000000..8e527c3f
--- /dev/null
+++ b/packages/server/src/machines/detect.ts
@@ -0,0 +1,119 @@
+/**
+ * "What is that machine, and what is on it already?" — asked before anything is sent.
+ *
+ * The probe has to speak whatever shell the host's sshd hands us: `sh` on Linux and macOS,
+ * `cmd.exe` on a default Windows OpenSSH install. Hence two commands rather than one clever
+ * one — a POSIX attempt, and a Windows attempt when the first one is clearly not understood.
+ *
+ * Both print the same three things: an identity line, the raw text of the installed
+ * program's package manifest (empty when nothing is installed), and the raw text of the data
+ * root's hmr/harness.json (empty when nothing was ever pushed there). Parsing happens here,
+ * not there: the far side only has to `cat` two files, which every shell can do.
+ */
+
+/** Separates the identity line from the manifest text in the probe's output. */
+const SECTION = "---penguin---";
+
+/**
+ * POSIX probe. `uname -s -m` names the machine; the manifest is read from the program
+ * directory the installer writes (`~/.penguin`), and harness.json from the default data root
+ * (core's resolveRoot: `~/.penguin/data`) — a remote's PENGUIN_INSTALL_DIR or PENGUIN_HOME
+ * override is not visible over a non-interactive ssh, and the defaults are where an install
+ * this page made would land.
+ */
+export const POSIX_PROBE = [
+ "uname -s -m",
+ `echo ${SECTION}`,
+ 'cat "$HOME/.penguin/lib/package.json" 2>/dev/null || true',
+ `echo ${SECTION}`,
+ 'cat "$HOME/.penguin/data/hmr/harness.json" 2>/dev/null || true',
+].join("; ");
+
+/**
+ * Windows (cmd.exe) probe. `&` chains commands there, `%…%` expands variables, `2>nul`
+ * discards the error from a missing file — none of which sh would do the same way, which is
+ * why this is a separate command rather than a portable one.
+ */
+export const WINDOWS_PROBE = [
+ "echo %OS% %PROCESSOR_ARCHITECTURE%",
+ `echo ${SECTION}`,
+ 'type "%USERPROFILE%\\.penguin\\lib\\package.json" 2>nul',
+ `echo ${SECTION}`,
+ 'type "%USERPROFILE%\\.penguin\\data\\hmr\\harness.json" 2>nul',
+].join("&");
+
+/** Node's own names, matching what the release targets are spelled from. */
+export type RemotePlatform = "linux" | "darwin" | "win32";
+export type RemoteArch = "x64" | "arm64";
+
+export interface RemoteIdentity {
+ platform: RemotePlatform;
+ arch: RemoteArch;
+ /** Version of the PenguinHarness installed there, or null when there is none. */
+ installedVersion: string | null;
+ /** Raw text of the remote data root's hmr/harness.json, or null when nothing was pushed. */
+ harness: string | null;
+}
+
+/** Maps what `uname -m` / `%PROCESSOR_ARCHITECTURE%` say onto Node's arch names. */
+function normalizeArch(raw: string): RemoteArch | null {
+ const value = raw.trim().toLowerCase();
+ if (["x86_64", "amd64"].includes(value)) return "x64";
+ if (["aarch64", "arm64"].includes(value)) return "arm64";
+ return null;
+}
+
+/** Maps `uname -s` / `%OS%` onto Node's platform names. */
+function normalizePlatform(raw: string): RemotePlatform | null {
+ const value = raw.trim().toLowerCase();
+ if (value === "linux") return "linux";
+ if (value === "darwin") return "darwin";
+ if (value.includes("windows")) return "win32";
+ return null;
+}
+
+/** The version out of a package manifest, or null when the text is not one. */
+function versionOf(manifestText: string): string | null {
+ try {
+ const parsed: unknown = JSON.parse(manifestText.trim());
+ if (typeof parsed === "object" && parsed !== null) {
+ const version = (parsed as { version?: unknown }).version;
+ if (typeof version === "string" && version !== "") return version;
+ }
+ } catch {
+ /* not a manifest: nothing is installed, or the file is damaged */
+ }
+ return null;
+}
+
+/**
+ * Reads either probe's output. Returns null when the identity line is not something we
+ * recognize — which is also how "this shell did not understand the command" surfaces, since
+ * cmd.exe answers a POSIX probe with an error message rather than a uname line.
+ */
+export function parseProbeOutput(stdout: string): RemoteIdentity | null {
+ const [identityPart, manifestPart = "", harnessPart = ""] = stdout.split(SECTION);
+ const lines = (identityPart ?? "")
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line !== "");
+ // Anything before the identity line is the shell's own noise (a banner, a warning), which
+ // is why the search is anchored on a line that parses as a machine rather than a position.
+ const identity = lines
+ .map((line) => {
+ const words = line.split(/\s+/);
+ if (words.length < 2) return null;
+ const platform = normalizePlatform(words[0]!);
+ const arch = normalizeArch(words[words.length - 1]!);
+ return platform && arch ? { platform, arch } : null;
+ })
+ .find((entry) => entry !== null);
+ if (!identity) return null;
+ const harness = harnessPart.trim();
+ return {
+ platform: identity.platform,
+ arch: identity.arch,
+ installedVersion: versionOf(manifestPart),
+ harness: harness === "" ? null : harness,
+ };
+}
diff --git a/packages/server/src/machines/exec.ts b/packages/server/src/machines/exec.ts
new file mode 100644
index 00000000..38811690
--- /dev/null
+++ b/packages/server/src/machines/exec.ts
@@ -0,0 +1,162 @@
+/**
+ * Running ssh and scp — the only impure corner of the remote install. Everything the
+ * commands say lives in commands.ts; this file just spawns them and reports what happened.
+ *
+ * No shell: argv goes straight to execFile, so nothing on this side interprets quotes,
+ * spaces or `$`. The remote command string is the one place a shell is involved, and it is
+ * quoted by commands.ts for exactly that reason.
+ *
+ * Failures are returned, never thrown, and carry ssh's own stderr verbatim — a wrong key, a
+ * host-key mismatch or a refused connection is the user's to read, and rewording OpenSSH's
+ * diagnostics into our own vocabulary would only lose detail.
+ */
+import { execFile, spawn } from "node:child_process";
+
+export interface ExecResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+/** Enough for a payload transfer over a slow link, short enough to not hang a menu forever. */
+const DEFAULT_TIMEOUT_MS = 10 * 60_000;
+
+export function run(
+ file: string,
+ args: string[],
+ opts: { timeoutMs?: number } = {},
+): Promise<ExecResult> {
+ return new Promise((resolve) => {
+ execFile(
+ file,
+ args,
+ { timeout: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 },
+ (error, stdout, stderr) => {
+ const code =
+ error && typeof (error as NodeJS.ErrnoException & { code?: number }).code === "number"
+ ? ((error as NodeJS.ErrnoException & { code: number }).code as number)
+ : error
+ ? 1
+ : 0;
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
+ },
+ );
+ });
+}
+
+/**
+ * Runs one command with `input` on its stdin, reporting each line of output as it arrives.
+ *
+ * This is how the ordinary installer reaches a POSIX remote: `ssh host 'sh -s'` with
+ * install.sh piped in, which is the same shape as the documented `curl … | sh` and saves the
+ * scratch directory, the scp and the cleanup a copied file would need — three ssh handshakes,
+ * each of which can cost tens of seconds.
+ *
+ * `onLine` exists because an install takes minutes: buffering until exit would show the far
+ * side's own progress only once it no longer matters. Lines are split on the way through, so
+ * a partial chunk never surfaces as a line of its own.
+ */
+export function runWithInput(
+ file: string,
+ args: string[],
+ opts: { input: Buffer; onLine?: (line: string) => void; timeoutMs?: number },
+): Promise<ExecResult> {
+ return new Promise((resolve) => {
+ const child = spawn(file, args, { stdio: ["pipe", "pipe", "pipe"] });
+ let stdout = "";
+ let stderr = "";
+ let pending = "";
+ const timer = setTimeout(() => child.kill(), opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ child.stdout.on("data", (chunk: Buffer) => {
+ const text = chunk.toString("utf8");
+ stdout += text;
+ if (opts.onLine === undefined) return;
+ pending += text;
+ const lines = pending.split("\n");
+ pending = lines.pop() ?? "";
+ for (const line of lines) {
+ const trimmed = line.trimEnd();
+ if (trimmed !== "") opts.onLine(trimmed);
+ }
+ });
+ child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString("utf8")));
+ child.on("close", (code) => {
+ clearTimeout(timer);
+ // Whatever the last chunk left without a newline is still a line the far side wrote.
+ if (pending.trim() !== "") opts.onLine?.(pending.trim());
+ resolve({ code: code ?? 1, stdout, stderr });
+ });
+ child.on("error", (err) => {
+ clearTimeout(timer);
+ resolve({ code: 1, stdout, stderr: `${stderr}${err.message}\n` });
+ });
+ // A remote that never reads stdin (a refused connection) closes the pipe under us.
+ child.stdin.on("error", () => {});
+ child.stdin.end(opts.input);
+ });
+}
+
+/**
+ * `producer | consumer`, without a shell: the producer's stdout is piped straight into the
+ * consumer's stdin — how the hmr store crosses to the remote (local tar → ssh). Failure of
+ * EITHER side fails the pair, with both stderr streams in the result; a broken pipe from a
+ * dead consumer must not read as a successful transfer.
+ */
+export function runPiped(
+ producer: { file: string; args: string[] },
+ consumer: { file: string; args: string[] },
+ opts: { timeoutMs?: number } = {},
+): Promise<ExecResult> {
+ return new Promise((resolve) => {
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const a = spawn(producer.file, producer.args, { stdio: ["ignore", "pipe", "pipe"] });
+ const b = spawn(consumer.file, consumer.args, { stdio: ["pipe", "pipe", "pipe"] });
+ a.stdout.pipe(b.stdin);
+ // A consumer that dies mid-stream closes the pipe; without this the producer's EPIPE
+ // would surface as an unhandled stream error instead of the consumer's own exit below.
+ b.stdin.on("error", () => a.kill());
+ let stdout = "";
+ let stderr = "";
+ b.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString("utf8")));
+ a.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString("utf8")));
+ b.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString("utf8")));
+ let aCode: number | null = null;
+ let bCode: number | null = null;
+ let settled = false;
+ const timer = setTimeout(() => {
+ a.kill();
+ b.kill();
+ }, timeoutMs);
+ const finish = () => {
+ if (settled || aCode === null || bCode === null) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ code: aCode !== 0 ? aCode : bCode, stdout, stderr });
+ };
+ a.on("close", (code) => {
+ aCode = code ?? 1;
+ finish();
+ });
+ b.on("close", (code) => {
+ bCode = code ?? 1;
+ finish();
+ });
+ a.on("error", (err) => {
+ aCode = 1;
+ stderr += `${err.message}\n`;
+ finish();
+ });
+ b.on("error", (err) => {
+ bCode = 1;
+ stderr += `${err.message}\n`;
+ finish();
+ });
+ });
+}
+
+/** True when the failure is "ssh could not authenticate without asking" — the BatchMode wall. */
+export function looksLikeAuthFailure(result: ExecResult): boolean {
+ return /permission denied|no supported authentication|host key verification failed/i.test(
+ result.stderr,
+ );
+}
diff --git a/packages/server/src/machines/install-server.ts b/packages/server/src/machines/install-server.ts
new file mode 100644
index 00000000..48ae6caa
--- /dev/null
+++ b/packages/server/src/machines/install-server.ts
@@ -0,0 +1,304 @@
+/**
+ * Installing THIS server's build onto another machine, from inside the server process —
+ * platform code, so the whole capability travels by hot push (see ../hmr/README.md).
+ *
+ * Nothing installable is produced here. The far side runs the ordinary release installer
+ * ONLINE, pinned to this server's own base release, so the program tree — launchers, libs,
+ * web assets, bundled runtime — is the standard artifact downloaded from the release
+ * sources, exactly as a person installing by hand would get it. What this code adds is only
+ * what makes the remote THIS machine's peer rather than a stock install: the hmr state
+ * (harness.json + store/) is streamed across afterwards, so the remote's next boot runs the
+ * same pushed platform, web and CLI this server runs (hmr/host.ts's restore).
+ *
+ * The remote therefore needs its own route to the release sources (GitHub or the OSS
+ * mirror); the ssh channel carries only the installer script and the store.
+ *
+ * The remote is left with exactly what a local install plus a push leaves: the program
+ * directory, the `~/.local/bin/penguin` symlink on POSIX, and the data root's hmr/ state.
+ * No sudo, no service units, no profile edits, and the rest of the data root is untouched.
+ */
+import { randomBytes } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { runInstallScriptCommand, scpArgs, sshArgs, unpackStoreCommand } from "./commands.js";
+import type { RemoteTarget } from "./commands.js";
+import { parseProbeOutput, POSIX_PROBE, WINDOWS_PROBE } from "./detect.js";
+import type { RemoteIdentity, RemotePlatform } from "./detect.js";
+import { looksLikeAuthFailure, run, runPiped, runWithInput } from "./exec.js";
+
+/** Which installer runs the far side; also the asset keys deploy.mjs pushes. */
+const installerFileFor = (platform: RemotePlatform): string =>
+ platform === "win32" ? "install.ps1" : "install.sh";
+
+/** The version out of a lib/package.json path, or null when it is not a manifest. */
+function versionOfManifest(manifestPath: string): string | null {
+ try {
+ const parsed: unknown = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
+ if (typeof parsed === "object" && parsed !== null) {
+ const version = (parsed as { version?: unknown }).version;
+ if (typeof version === "string" && version !== "") return version;
+ }
+ } catch {
+ /* absent or damaged: not an install */
+ }
+ return null;
+}
+
+/**
+ * What an install would put on the remote: the release this server stands on, plus the hmr
+ * state to replicate over it (null when nothing was ever pushed here). `version` is the
+ * display form the page and the install records use.
+ */
+export interface PushPlan {
+ /** The base release's version as lib/package.json spells it (no `v`). */
+ baseVersion: string;
+ /** Raw harness.json text of this server's own hmr state, or null when none exists. */
+ harness: string | null;
+ /** The hmr directory the store is streamed from; null exactly when `harness` is. */
+ hmrDir: string | null;
+ version: string;
+}
+
+/**
+ * The pushed-state suffix for a display version: the platform bundle's content sha out of a
+ * harness.json (`store/platform/<sha>.mjs`), shortened. Falls back to a bare marker for a
+ * manifest whose shape this build does not recognize — the suffix is display, not identity;
+ * equality checks compare the harness text itself.
+ */
+function harnessSuffix(harnessText: string): string {
+ try {
+ const parsed = JSON.parse(harnessText) as { platform?: { bundle?: string } };
+ const sha = /([0-9a-f]{8,})\.mjs$/.exec(parsed.platform?.bundle ?? "")?.[1];
+ if (sha !== undefined) return `+hmr.${sha.slice(0, 12)}`;
+ } catch {
+ /* fall through */
+ }
+ return "+hmr";
+}
+
+/**
+ * Resolves what this server would install elsewhere.
+ *
+ * The base release is read from the running install's own tree — the tarball layout
+ * (`<root>/lib/dist/penguin.js` under a `lib/`) or the desktop app's staged payload — the
+ * same way `penguin --version` would answer. A development checkout has neither, and
+ * answers null: it stands on no release the remote could download.
+ */
+export function resolvePushPlan(
+ dataRoot: string | null,
+ argv1: string | undefined = process.argv[1],
+): PushPlan | null {
+ const baseVersion = baseReleaseVersion(argv1);
+ if (baseVersion === null) return null;
+ let harness: string | null = null;
+ let hmrDir: string | null = null;
+ if (dataRoot !== null) {
+ const dir = path.join(dataRoot, "hmr");
+ try {
+ const text = fs.readFileSync(path.join(dir, "harness.json"), "utf8").trim();
+ if (text !== "") {
+ harness = text;
+ hmrDir = dir;
+ }
+ } catch {
+ /* never pushed to: the plan is the bare release */
+ }
+ }
+ return {
+ baseVersion,
+ harness,
+ hmrDir,
+ version: harness === null ? baseVersion : baseVersion + harnessSuffix(harness),
+ };
+}
+
+/**
+ * The base release version around the process entry, or null when this process stands on no
+ * published release. Read from disk rather than from the running artifact's own build info,
+ * because a hot-pushed server must still report the BASE it was installed from.
+ */
+function baseReleaseVersion(argv1: string | undefined): string | null {
+ if (!argv1 || path.basename(path.dirname(argv1)) !== "dist") return null;
+ const parent = path.dirname(path.dirname(argv1));
+
+ // Tarball install: <root>/lib/dist/<entry>.js. lib/package.json is the CLI package's own
+ // manifest, and keeps naming the base release while this process runs a pushed bundle.
+ if (path.basename(parent) === "lib") {
+ return versionOfManifest(path.join(parent, "package.json"));
+ }
+
+ // Packaged desktop app: <resources>/app/dist/server.js — the app forks the server as one
+ // bundled file (packages/desktop/tsup.config.ts), and asar is off, so these are real files.
+ // The app's own manifest names the release it was published under, app and tarballs
+ // shipping from one tag. A source run sits at packages/desktop rather than under
+ // resources/, and is deliberately unmatched: it stands on no release a remote could fetch.
+ if (path.basename(parent) === "app" && path.basename(path.dirname(parent)) === "resources") {
+ return versionOfManifest(path.join(parent, "package.json"));
+ }
+ return null;
+}
+
+/**
+ * Asks the machine what it is. POSIX first; a cmd.exe host answers that with an error, which
+ * parses as "not a machine I recognize", and the Windows form is tried next. Two round trips
+ * at worst, once per connect.
+ */
+export async function detectRemote(
+ target: RemoteTarget,
+): Promise<{ identity: RemoteIdentity } | { error: string }> {
+ for (const probe of [POSIX_PROBE, WINDOWS_PROBE]) {
+ const result = await run("ssh", sshArgs(target, probe), { timeoutMs: 30_000 });
+ const identity = parseProbeOutput(result.stdout);
+ if (identity) return { identity };
+ if (result.code !== 0 && looksLikeAuthFailure(result)) {
+ return {
+ error: `${result.stderr.trim()}\n\nConnections use BatchMode: set up key or agent authentication for that host first.`,
+ };
+ }
+ // A connection-level failure is fatal for both probes; only an unrecognized ANSWER is
+ // worth retrying in the other shell's dialect.
+ if (result.code !== 0 && result.stdout.trim() === "" && result.stderr.trim() !== "") {
+ const stderr = result.stderr.trim();
+ if (!/not recognized|command not found|is not recognized/i.test(stderr)) {
+ return { error: stderr };
+ }
+ }
+ }
+ return {
+ error: "Could not tell what that machine is: neither the POSIX nor the Windows probe answered.",
+ };
+}
+
+export type RemoteInstallOutcome =
+ | { kind: "already-installed"; version: string; identity: RemoteIdentity }
+ | { kind: "installed"; output: string; identity: RemoteIdentity }
+ | { kind: "failed"; step: string; detail: string };
+
+/**
+ * Installs the plan. Steps are sequential and each failure stops the run with the far side's
+ * own message; the scratch directory is removed on the way out either way, since a leftover
+ * script in someone's temp directory is litter we created.
+ */
+export async function installOnRemote(opts: {
+ target: RemoteTarget;
+ plan: PushPlan;
+ onProgress?: (line: string) => void;
+ /** Identity from an earlier probe in the same flow, to save the round trips. */
+ identity?: RemoteIdentity;
+ /** The hmr capability's assetsDir accessor: where a pushed bundle's assets were unpacked. */
+ assets?: () => string | null;
+}): Promise<RemoteInstallOutcome> {
+ const { target, plan } = opts;
+ const say = opts.onProgress ?? (() => {});
+
+ let identity = opts.identity;
+ if (identity === undefined) {
+ say("Asking what that machine is…");
+ const detected = await detectRemote(target);
+ if ("error" in detected) return { kind: "failed", step: "connect", detail: detected.error };
+ identity = detected.identity;
+ say(`${identity.platform}-${identity.arch}.`);
+ }
+
+ const baseCurrent = identity.installedVersion === plan.baseVersion;
+ if (baseCurrent && identity.harness === plan.harness) {
+ return { kind: "already-installed", version: plan.version, identity };
+ }
+
+ // Release tags are v-prefixed semver; a base that does not spell one cannot be pinned —
+ // notably 0.0.0-hmr.* trees, which stand on no published release.
+ if (
+ !/^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/.test(plan.baseVersion) ||
+ plan.baseVersion.startsWith("0.0.0")
+ ) {
+ return {
+ kind: "failed",
+ step: "resolve the release",
+ detail: `this install's own version (${plan.baseVersion}) does not name a published release.`,
+ };
+ }
+
+ let windowsTmp: { local: string; remote: string } | null = null;
+ try {
+ const output: string[] = [];
+ if (!baseCurrent) {
+ // The ordinary installer. Where it sits follows from what this server is: a hot-pushed
+ // bundle has it among the assets published with that same version, anything else is a
+ // packaged install and it is beside this module (dist/ after a build; this package's
+ // tsup.config.ts copies it there).
+ const installerFile = installerFileFor(identity.platform);
+ const installerHome = opts.assets?.() ?? path.dirname(fileURLToPath(import.meta.url));
+ let installer: Buffer;
+ try {
+ installer = fs.readFileSync(path.join(installerHome, installerFile));
+ } catch (err) {
+ return {
+ kind: "failed",
+ step: "prepare the installer",
+ detail: err instanceof Error ? err.message : String(err),
+ };
+ }
+
+ say(`Installing release ${plan.baseVersion} (downloaded on the remote)…`);
+ // Where the script ends up decides how it is invoked, so resolve that first and let the
+ // command itself say whether stdin has to carry it.
+ let where: Parameters<typeof runInstallScriptCommand>[1];
+ if (identity.platform === "win32") {
+ // A name of our own making: hex only, so it needs no quoting on either side.
+ const name = `penguin-${randomBytes(6).toString("hex")}.ps1`;
+ const local = path.join(os.tmpdir(), name);
+ fs.writeFileSync(local, installer);
+ windowsTmp = { local, remote: `%USERPROFILE%\\${name}` };
+ const copy = await run("scp", scpArgs(target, [local], "."));
+ if (copy.code !== 0) {
+ return { kind: "failed", step: "copy", detail: copy.stderr.trim() || "scp failed" };
+ }
+ where = { platform: "win32", scriptPath: windowsTmp.remote };
+ } else {
+ where = { platform: identity.platform };
+ }
+ const step = runInstallScriptCommand(`v${plan.baseVersion}`, where);
+ // One connection when the script rides stdin, and the far side's own progress is
+ // relayed as it arrives rather than after the minutes an install can take.
+ const install = step.scriptOnStdin
+ ? await runWithInput("ssh", sshArgs(target, step.command), {
+ input: installer,
+ onLine: say,
+ })
+ : await run("ssh", sshArgs(target, step.command));
+ if (install.code !== 0) {
+ return {
+ kind: "failed",
+ step: "install",
+ detail: `${install.stdout.trim()}\n${install.stderr.trim()}`.trim(),
+ };
+ }
+ output.push(install.stdout.trim());
+ }
+
+ if (plan.hmrDir !== null && identity.harness !== plan.harness) {
+ say("Replicating the pushed version…");
+ // harness.json and store/ only: uploads/ is this machine's scratch, not state.
+ const sync = await runPiped(
+ { file: "tar", args: ["-czf", "-", "-C", plan.hmrDir, "harness.json", "store"] },
+ { file: "ssh", args: sshArgs(target, unpackStoreCommand(identity.platform)) },
+ );
+ if (sync.code !== 0) {
+ return {
+ kind: "failed",
+ step: "replicate the pushed version",
+ detail: sync.stderr.trim() || `tar | ssh exited ${sync.code}`,
+ };
+ }
+ output.push(`Pushed version replicated (${plan.version}).`);
+ }
+
+ return { kind: "installed", output: output.join("\n").trim(), identity };
+ } finally {
+ // Nothing to clean on a POSIX remote: the installer was never a file there. A Windows
+ // one deletes its own copy as part of the install command; this is the local original.
+ if (windowsTmp !== null) fs.rmSync(windowsTmp.local, { force: true });
+ }
+}
diff --git a/packages/server/src/machines/installs.ts b/packages/server/src/machines/installs.ts
new file mode 100644
index 00000000..b3eeeb28
--- /dev/null
+++ b/packages/server/src/machines/installs.ts
@@ -0,0 +1,62 @@
+/**
+ * What this server has installed on which machine, remembered across restarts and hot
+ * pushes in one JSON file under the data root.
+ *
+ * Without it, "installed" is a property of the ONE in-memory job: it dies with the process,
+ * and installing on a second machine erases the first machine's answer. The record is what
+ * makes the picker able to say which hosts already carry this program and which version
+ * they got, without an ssh round trip per host at page load — the whole reason the list is
+ * config text in the first place.
+ *
+ * It is a record of what WE did, not a survey of the far side. A machine someone wiped by
+ * hand still reads as installed here; the install itself is what corrects that, since it
+ * probes the remote before deciding anything (an unchanged version is a no-op, a missing
+ * one installs). Treating the file as authoritative about the remote would be a lie, so
+ * nothing here does.
+ *
+ * Pure functions over the file's text; the service owns the I/O.
+ */
+
+/** One machine's last successful install, as this server carried it out. */
+export interface InstallRecord {
+ /** The version that landed — the image version this server sent, or what the remote already had. */
+ version: string;
+ /** ISO timestamp, so the picker can say "installed" with a date rather than just a flag. */
+ at: string;
+}
+
+/**
+ * Parses the file's text: machine id → record. Damage, a wrong shape, or a missing file all
+ * read as "nothing remembered" — this is a convenience over the ssh config, and refusing to
+ * serve the machines list because a cache file got corrupted would be the worse failure.
+ */
+export function parseInstallRecords(raw: string | null): Record<string, InstallRecord> {
+ if (raw === null || raw.trim() === "") return {};
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
+ const out: Record<string, InstallRecord> = {};
+ for (const [machineId, value] of Object.entries(parsed)) {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
+ const entry = value as Record<string, unknown>;
+ if (typeof entry.version !== "string" || entry.version === "") continue;
+ if (typeof entry.at !== "string" || entry.at === "") continue;
+ out[machineId] = { version: entry.version, at: entry.at };
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
+/** The file's next text after updating one machine's record (null forgets it). */
+export function withInstallRecord(
+ raw: string | null,
+ machineId: string,
+ record: InstallRecord | null,
+): string {
+ const all = parseInstallRecords(raw);
+ if (record === null) delete all[machineId];
+ else all[machineId] = record;
+ return JSON.stringify(all, null, 2) + "\n";
+}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
new file mode 100644
index 00000000..e7350961
--- /dev/null
+++ b/packages/server/src/machines/service.ts
@@ -0,0 +1,214 @@
+/**
+ * The machines service: this server's own `~/.ssh/config` as a list of targets, and putting
+ * this build on one of them.
+ *
+ * An install is a JOB, not a request. It probes the far side, has it download and install
+ * this server's base release, and streams the hmr state across — minutes, in the bad case —
+ * so POST starts it and the Web App polls for the progress lines. One at a time: the
+ * surface is a person installing on one machine.
+ *
+ * The JOB is not persisted. It lives in this App's memory and dies with it (see the park
+ * list in ../hmr/platform.ts — it is on the SUSPENDED side): a hot push during an install
+ * loses the progress log, and the recovery is to run it again, which is safe because every
+ * step is idempotent — the far side's installer stages, smoke-tests and swaps, and an
+ * unchanged version is a no-op.
+ *
+ * The RESULT is. Which machines carry this program is not a property of the last job — it
+ * has to outlive the job, the process and the next install somewhere else — so a successful
+ * install is written to `<data root>/machines-installs.json` (installs.ts) and read back
+ * into every list(). Without it "installed" would blink out the moment anything else
+ * happened, which is exactly what it did before this file wrote anything down.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import type { MachineInfo, MachineInstallJob } from "../api/types.js";
+import { listHostAliases, resolveTarget } from "./targets.js";
+import { installOnRemote, resolvePushPlan } from "./install-server.js";
+import { parseInstallRecords, withInstallRecord } from "./installs.js";
+import type { InstallRecord } from "./installs.js";
+
+/** Why a start was refused before any ssh ran. */
+export type InstallRefusal = "busy" | "unknown-machine" | "unresolvable" | "no-image";
+
+/**
+ * The three things this service does to the world, injectable as a set. Production passes
+ * none of them; tests pass all three, because the real ones read the developer's own
+ * ~/.ssh/config and spawn ssh against whatever it names. The push path itself is covered
+ * where it belongs — machines-push.test.ts drives the real installOnRemote against a fake
+ * ssh binary — so what is faked here is only the reaching-out, never the logic under test.
+ */
+export interface MachinesEffects {
+ listAliases: typeof listHostAliases;
+ resolveTarget: typeof resolveTarget;
+ resolvePlan: typeof resolvePushPlan;
+ install: typeof installOnRemote;
+ /** Injected so a test can pin the recorded timestamp instead of asserting around the clock. */
+ now: () => Date;
+}
+
+export class MachinesService {
+ #job: MachineInstallJob | null = null;
+ readonly #effects: MachinesEffects;
+
+ /**
+ * `dataRoot` is the server's own data root: it holds the hmr state a push replicates, and
+ * the install records below.
+ */
+ /** Where a pushed bundle's assets were unpacked; null in a packaged server (hmr.assetsDir). */
+ readonly #assets: () => string | null;
+
+ constructor(
+ private readonly dataRoot: string,
+ effects: Partial<MachinesEffects> = {},
+ assets: () => string | null = () => null,
+ ) {
+ this.#assets = assets;
+ this.#effects = {
+ listAliases: listHostAliases,
+ resolveTarget,
+ resolvePlan: resolvePushPlan,
+ install: installOnRemote,
+ now: () => new Date(),
+ ...effects,
+ };
+ }
+
+ /** Where the install records live — beside the other per-machine state in the data root. */
+ get #recordsFile(): string {
+ return path.join(this.dataRoot, "machines-installs.json");
+ }
+
+ /** The records file's text, or null when there is none yet (or it cannot be read). */
+ #readRecords(): string | null {
+ try {
+ return fs.readFileSync(this.#recordsFile, "utf8");
+ } catch {
+ return null; // Never installed from this server yet, or an unreadable file: nothing remembered.
+ }
+ }
+
+ /**
+ * The ssh config's host aliases, each carrying what this server last installed there.
+ * Empty when there is no config, which is not an error.
+ */
+ list(): MachineInfo[] {
+ const records = parseInstallRecords(this.#readRecords());
+ return this.#effects.listAliases().map((alias) => {
+ const id = `ssh:${alias}`;
+ return { id, alias, installed: records[id] ?? null };
+ });
+ }
+
+ /**
+ * The version this server would install, or null when it has no image to push — a dev
+ * checkout that has never been pushed to is the one shape with none. The page asks for it
+ * so it can say so up front, rather than letting every install fail at the same step.
+ */
+ imageVersion(): string | null {
+ return this.#effects.resolvePlan(this.dataRoot)?.version ?? null;
+ }
+
+ /** The running or last job; null before the first one. */
+ job(): MachineInstallJob | null {
+ return this.#job;
+ }
+
+ /**
+ * Starts an install, refusing rather than queueing. The refusals that can be decided here —
+ * a job already running, an alias this config does not declare, an ssh that cannot resolve
+ * it, no image to send — are answered synchronously, so the page distinguishes "did not
+ * start" from "started and failed" without reading the log.
+ */
+ async startInstall(
+ machineId: string,
+ ): Promise<{ ok: true } | { ok: false; why: InstallRefusal }> {
+ if (this.#job?.running === true) return { ok: false, why: "busy" };
+
+ const machine = this.list().find((entry) => entry.id === machineId);
+ if (machine === undefined) return { ok: false, why: "unknown-machine" };
+
+ const plan = this.#effects.resolvePlan(this.dataRoot);
+ if (plan === null) return { ok: false, why: "no-image" };
+
+ const resolved = await this.#effects.resolveTarget(machine.alias);
+ if (resolved === null) return { ok: false, why: "unresolvable" };
+
+ const job: MachineInstallJob = {
+ machineId,
+ alias: machine.alias,
+ running: true,
+ log: [],
+ result: null,
+ };
+ this.#job = job;
+
+ const say = (line: string) => {
+ job.log.push(line);
+ };
+ // Deliberately not awaited: the caller is an HTTP handler answering 202. Failures land
+ // in the job's own result — the catch below is the last resort for a throw the install
+ // path does not turn into a `failed` outcome itself.
+ void (async () => {
+ try {
+ say(`Installing ${plan.version} on ${resolved.machine}…`);
+ // No identity passed: installOnRemote runs the probe itself as its first step and
+ // narrates it, so the page shows what the machine turned out to be.
+ const outcome = await this.#effects.install({
+ target: { alias: machine.alias, user: resolved.settings.user },
+ plan,
+ onProgress: say,
+ assets: this.#assets,
+ });
+ if (outcome.kind === "failed") {
+ job.result = { ok: false, step: outcome.step, message: outcome.detail };
+ return;
+ }
+ const version = outcome.kind === "already-installed" ? outcome.version : plan.version;
+ // Remember it BEFORE the job settles, so the first poll that sees `running: false`
+ // already sees the machine marked installed — otherwise the page would flash the
+ // verdict and a still-uninstalled row in the same frame.
+ this.#remember(machineId, { version, at: this.#effects.now().toISOString() });
+ job.result = { ok: true, kind: outcome.kind, version };
+ } catch (err) {
+ job.result = {
+ ok: false,
+ step: "install",
+ message: err instanceof Error ? err.message : String(err),
+ };
+ } finally {
+ job.running = false;
+ }
+ })();
+
+ return { ok: true };
+ }
+
+ /**
+ * Writes one machine's record.
+ *
+ * Through a temp file and a rename rather than straight onto the target: a plain write
+ * truncates first, so a crash mid-write leaves bytes the parser reads as "nothing
+ * installed anywhere" — treating damage as empty is right for a cache, but it means a
+ * torn write silently forgets every OTHER machine too, not just the one being recorded.
+ * Rename is one step; a reader sees the old file or the new one.
+ *
+ * A failure here is swallowed: the install itself already succeeded, and the far side has
+ * the program whether or not this side managed to note it down. Forgetting costs one
+ * needless reinstall, which is a no-op on the remote.
+ */
+ #remember(machineId: string, record: InstallRecord): void {
+ const next = withInstallRecord(this.#readRecords(), machineId, record);
+ const tmp = `${this.#recordsFile}.tmp-${process.pid}`;
+ try {
+ fs.mkdirSync(path.dirname(this.#recordsFile), { recursive: true });
+ fs.writeFileSync(tmp, next);
+ fs.renameSync(tmp, this.#recordsFile);
+ } catch {
+ try {
+ fs.rmSync(tmp, { force: true });
+ } catch {
+ /* the temp file is litter at worst */
+ }
+ }
+ }
+}
diff --git a/packages/server/src/machines/ssh-config.ts b/packages/server/src/machines/ssh-config.ts
new file mode 100644
index 00000000..c3e0cbf7
--- /dev/null
+++ b/packages/server/src/machines/ssh-config.ts
@@ -0,0 +1,111 @@
+/**
+ * Reading `~/.ssh/config` — the only source of remote targets. We never write it, never
+ * keep a host list of our own, and never re-implement OpenSSH's matching rules: this module
+ * does exactly two things, both pure so they unit-test without a filesystem or an ssh binary.
+ *
+ * 1. `parseHostAliases` scans the config text for candidate aliases, following `Include`
+ * through a caller-supplied reader. It exists only because OpenSSH has no "list hosts"
+ * command and the UI needs something to show. Pattern entries (`*`, `?`, `!`) are skipped:
+ * they configure other hosts rather than name one.
+ * 2. `parseSshSettings` reads the output of `ssh -G <alias>`, which is OpenSSH's own answer
+ * to "what does this alias actually resolve to" — Match blocks, Include, wildcard
+ * inheritance and defaults all already applied.
+ */
+
+/** One line of `ssh -G` output: a lowercase keyword, a space, the value. */
+const SSH_G_LINE = /^([a-z0-9_]+)\s+(.*)$/;
+
+/** Config keywords that introduce host blocks; matched case-insensitively, as ssh does. */
+const HOST_KEYWORD = /^host\s+(.*)$/i;
+const INCLUDE_KEYWORD = /^include\s+(.*)$/i;
+
+/** A pattern entry configures other hosts instead of naming one, so it is not a target. */
+const isPattern = (alias: string) => /[*?!]/.test(alias);
+
+/**
+ * Host aliases declared in a config, in file order and de-duplicated. `readInclude` resolves
+ * an `Include` argument to the included files' text (empty array when it matches nothing);
+ * it is a parameter so this stays pure — the caller owns glob expansion, `~` resolution and
+ * the "an unreadable include is not an error" policy.
+ *
+ * Depth is bounded: OpenSSH allows nested includes, and a config that includes itself would
+ * otherwise spin forever.
+ */
+export function parseHostAliases(
+ text: string,
+ readInclude: (pattern: string) => string[],
+ depth = 0,
+): string[] {
+ const out: string[] = [];
+ for (const raw of text.split("\n")) {
+ const line = raw.trim();
+ if (line === "" || line.startsWith("#")) continue;
+ const include = INCLUDE_KEYWORD.exec(line);
+ if (include && depth < 8) {
+ for (const included of readInclude(include[1]!.trim())) {
+ out.push(...parseHostAliases(included, readInclude, depth + 1));
+ }
+ continue;
+ }
+ const host = HOST_KEYWORD.exec(line);
+ if (!host) continue;
+ // `Host a b c` declares several aliases for one block.
+ for (const alias of host[1]!.split(/\s+/)) {
+ if (alias !== "" && !isPattern(alias)) out.push(alias);
+ }
+ }
+ return [...new Set(out)];
+}
+
+/** The parts of `ssh -G` output this app uses; everything else in that output is ignored. */
+export interface SshSettings {
+ /** The login user ssh would use — part of a target's identity, not a detail. */
+ user: string;
+ hostname: string;
+ port: number;
+ /** May be empty: an agent-only setup declares no identity file. */
+ identityFiles: string[];
+ /** `none` in ssh's output becomes null. */
+ proxyJump: string | null;
+}
+
+/**
+ * Parses `ssh -G <alias>`. Absent or malformed fields fall back to ssh's own defaults
+ * rather than throwing: this feeds a host picker, and a config we cannot fully read should
+ * degrade to "looks like the alias itself on port 22", not to an error dialog.
+ */
+export function parseSshSettings(output: string, alias: string): SshSettings {
+ const values = new Map<string, string[]>();
+ for (const raw of output.split("\n")) {
+ const match = SSH_G_LINE.exec(raw.trim());
+ if (!match) continue;
+ const key = match[1]!;
+ const value = match[2]!.trim();
+ const existing = values.get(key);
+ if (existing) existing.push(value);
+ else values.set(key, [value]);
+ }
+ const first = (key: string): string | null => values.get(key)?.[0] ?? null;
+ const port = Number(first("port"));
+ const proxyJump = first("proxyjump");
+ return {
+ user: first("user") ?? "",
+ hostname: first("hostname") ?? alias,
+ port: Number.isInteger(port) && port > 0 && port <= 65535 ? port : 22,
+ identityFiles: values.get("identityfile") ?? [],
+ proxyJump: proxyJump === null || proxyJump.toLowerCase() === "none" ? null : proxyJump,
+ };
+}
+
+/**
+ * A remote target's stable name: the SSH identity, `<user>@<alias>`. The Linux account is
+ * part of it because each account has its own `~/.penguin` — hence its own server, its own
+ * accounts — so `deploy@build-box` and `root@build-box` are two machines as far as anything
+ * downstream is concerned.
+ * The ALIAS is used rather than the resolved hostname: it is what the user chose, it is
+ * what survives a DNS or jump-host change, and two aliases for one host are two targets
+ * only if the user wrote them that way.
+ */
+export function machineIdentity(alias: string, user: string): string {
+ return user === "" ? alias : `${user}@${alias}`;
+}
diff --git a/packages/server/src/machines/targets.ts b/packages/server/src/machines/targets.ts
new file mode 100644
index 00000000..6c8be028
--- /dev/null
+++ b/packages/server/src/machines/targets.ts
@@ -0,0 +1,74 @@
+/**
+ * Turning `~/.ssh/config` into a list of targets the menu can show, and one target into what
+ * ssh actually resolved. The parsing is in ssh-config.ts; this file owns the I/O — reading
+ * files, expanding `Include` globs, and asking ssh itself with `ssh -G`.
+ *
+ * An unreadable config, a missing config or an ssh that will not answer all degrade to "no
+ * targets" rather than to an error: this list is a convenience, and a user with no ssh setup
+ * should simply not see the feature offer them anything.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { run } from "./exec.js";
+import { machineIdentity, parseHostAliases, parseSshSettings } from "./ssh-config.js";
+import type { SshSettings } from "./ssh-config.js";
+
+const SSH_DIR = () => path.join(os.homedir(), ".ssh");
+
+/**
+ * Resolves one `Include` argument to the text of the files it matches. Patterns are relative
+ * to ~/.ssh unless absolute, and only the last path segment may glob — which is what
+ * OpenSSH's own configs use (`Include config.d/*`), and all this list needs.
+ */
+function readIncluded(pattern: string): string[] {
+ const expanded = pattern.startsWith("~/")
+ ? path.join(os.homedir(), pattern.slice(2))
+ : path.isAbsolute(pattern)
+ ? pattern
+ : path.join(SSH_DIR(), pattern);
+ const dir = path.dirname(expanded);
+ const base = path.basename(expanded);
+ try {
+ if (!base.includes("*") && !base.includes("?")) return [fs.readFileSync(expanded, "utf8")];
+ const matcher = new RegExp(
+ `^${base.replaceAll(".", "\\.").replaceAll("*", ".*").replaceAll("?", ".")}$`,
+ );
+ return fs
+ .readdirSync(dir)
+ .filter((entry) => matcher.test(entry))
+ .sort()
+ .map((entry) => {
+ try {
+ return fs.readFileSync(path.join(dir, entry), "utf8");
+ } catch {
+ return "";
+ }
+ });
+ } catch {
+ return []; // Missing or unreadable include: OpenSSH ignores it, so do we.
+ }
+}
+
+/** Host aliases declared in this machine's ssh config; empty when there is no usable config. */
+export function listHostAliases(): string[] {
+ try {
+ return parseHostAliases(fs.readFileSync(path.join(SSH_DIR(), "config"), "utf8"), readIncluded);
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * What ssh resolves an alias to, via `ssh -G` — Match blocks, Include and wildcard
+ * inheritance included, because ssh does the resolving, not us. Null when ssh cannot be run
+ * or refuses the alias.
+ */
+export async function resolveTarget(
+ alias: string,
+): Promise<{ alias: string; settings: SshSettings; machine: string } | null> {
+ const result = await run("ssh", ["-G", alias], { timeoutMs: 15_000 });
+ if (result.code !== 0 && result.stdout.trim() === "") return null;
+ const settings = parseSshSettings(result.stdout, alias);
+ return { alias, settings, machine: machineIdentity(alias, settings.user) };
+}
diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.ts
new file mode 100644
index 00000000..39ae4450
--- /dev/null
+++ b/packages/server/test/machines-api.test.ts
@@ -0,0 +1,328 @@
+/**
+ * The machines API: who may use it, what the list answers, and the install job's lifecycle
+ * as the Machines page sees it — start, poll, finish, and every way a start is refused
+ * before an ssh runs.
+ *
+ * The service's three reaching-out effects are faked (see MachinesEffects): the real ones
+ * read the developer's own ~/.ssh/config and spawn ssh against whatever it names. What the
+ * push actually does over ssh is covered by machines-push.test.ts, against a fake ssh
+ * binary and the real installOnRemote.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { MachinesResponse } from "../src/api/types.js";
+import { MachinesService } from "../src/machines/service.js";
+import type { MachinesEffects } from "../src/machines/service.js";
+import type { RemoteInstallOutcome } from "../src/machines/install-server.js";
+import type { RemoteIdentity } from "../src/machines/detect.js";
+import {
+ apiClient,
+ createTestApp,
+ loginAdmin,
+ makeTempRoot,
+ provisionUser,
+ waitFor,
+} from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const IDENTITY: RemoteIdentity = {
+ platform: "linux",
+ arch: "x64",
+ installedVersion: null,
+ harness: null,
+};
+
+/** An effects set that names two hosts and installs successfully, with the parts a test cares about overridden. */
+function effects(over: Partial<MachinesEffects> = {}): Partial<MachinesEffects> {
+ return {
+ listAliases: () => ["build-box", "nas"],
+ resolveTarget: async (alias) => ({
+ alias,
+ settings: {
+ user: "deploy",
+ hostname: `${alias}.example`,
+ port: 22,
+ identityFiles: [],
+ proxyJump: null,
+ },
+ machine: `deploy@${alias}`,
+ }),
+ resolvePlan: () => ({ baseVersion: "9.9.9", harness: null, hmrDir: null, version: "9.9.9" }),
+ now: () => new Date("2026-08-24T12:00:00.000Z"),
+ install: async (opts): Promise<RemoteInstallOutcome> => {
+ opts.onProgress?.("Pushing…");
+ return { kind: "installed", output: "done", identity: IDENTITY };
+ },
+ ...over,
+ };
+}
+
+describe("machines API", () => {
+ let t: TestApp;
+ let admin: ReturnType<typeof apiClient>;
+ /** The service's own data root — where it writes the install records this suite reads back. */
+ let machinesRoot: string;
+
+ const boot = async (over: Partial<MachinesEffects> = {}) => {
+ machinesRoot = await makeTempRoot();
+ t = await createTestApp({ machines: new MachinesService(machinesRoot, effects(over)) });
+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ };
+
+ /** The records file as the service left it on disk. */
+ const recordsOnDisk = (): unknown =>
+ JSON.parse(fs.readFileSync(path.join(machinesRoot, "machines-installs.json"), "utf8"));
+
+ afterEach(async () => {
+ await t.cleanup();
+ fs.rmSync(machinesRoot, { recursive: true, force: true });
+ });
+
+ describe("permission", () => {
+ beforeEach(() => boot());
+
+ it("is admin-only: a provisioned user gets 403", async () => {
+ const user = await provisionUser(t.app, "member");
+ const member = apiClient(t.app, user.cookie);
+ expect((await member.get("/api/machines")).status).toBe(403);
+ expect((await member.post("/api/machines/ssh:nas/install")).status).toBe(403);
+ });
+
+ it("needs a session at all", async () => {
+ expect((await t.app.request("/api/machines")).status).toBe(401);
+ });
+ });
+
+ describe("the list", () => {
+ it("is the ssh config's aliases, with the version this server would push", async () => {
+ await boot();
+ const body = (await (await admin.get("/api/machines")).json()) as MachinesResponse;
+ expect(body.machines).toEqual([
+ { id: "ssh:build-box", alias: "build-box", installed: null },
+ { id: "ssh:nas", alias: "nas", installed: null },
+ ]);
+ expect(body.imageVersion).toBe("9.9.9");
+ expect(body.job).toBeNull();
+ });
+
+ it("an empty or unreadable ssh config is a list of none, not an error", async () => {
+ await boot({ listAliases: () => [] });
+ const res = await admin.get("/api/machines");
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as MachinesResponse).machines).toEqual([]);
+ });
+
+ it("reports no image when this server has none to push", async () => {
+ await boot({ resolvePlan: () => null });
+ const body = (await (await admin.get("/api/machines")).json()) as MachinesResponse;
+ expect(body.imageVersion).toBeNull();
+ });
+ });
+
+ describe("installing", () => {
+ it("starts a job, narrates it, and finishes", async () => {
+ // Held open so the 202 is observed mid-flight, which is the real shape: a push takes
+ // minutes, and the page has to render a running job from this very body.
+ let release = () => {};
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await boot({
+ install: async (opts) => {
+ opts.onProgress?.("Pushing…");
+ await held;
+ return { kind: "installed", output: "done", identity: IDENTITY };
+ },
+ });
+ const started = await admin.post("/api/machines/ssh:nas/install");
+ expect(started.status).toBe(202);
+ expect(((await started.json()) as MachinesResponse).job).toMatchObject({
+ machineId: "ssh:nas",
+ alias: "nas",
+ running: true,
+ result: null,
+ });
+
+ release();
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ const body = (await (await admin.get("/api/machines")).json()) as MachinesResponse;
+ expect(body.job?.result).toEqual({ ok: true, kind: "installed", version: "9.9.9" });
+ // The first line is this server's own, the rest are the push's.
+ expect(body.job?.log[0]).toBe("Installing 9.9.9 on deploy@nas…");
+ expect(body.job?.log).toContain("Pushing…");
+ });
+
+ it("reports the far side's own words when the push fails", async () => {
+ await boot({
+ install: async () => ({
+ kind: "failed",
+ step: "connect",
+ detail: "Permission denied (publickey).",
+ }),
+ });
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toEqual({
+ ok: false,
+ step: "connect",
+ message: "Permission denied (publickey).",
+ });
+ });
+
+ it("a machine already on this version is a result, not a failure", async () => {
+ await boot({
+ install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),
+ });
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toEqual({
+ ok: true,
+ kind: "already-installed",
+ version: "9.9.9",
+ });
+ });
+
+ it("a throw from the push path still ends the job", async () => {
+ await boot({
+ install: () => {
+ throw new Error("scp vanished");
+ },
+ });
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toMatchObject({ ok: false, message: "scp vanished" });
+ });
+ });
+
+ describe("what stays installed", () => {
+ /** GET /api/machines, as the page reads it. */
+ const listed = async () =>
+ ((await (await admin.get("/api/machines")).json()) as MachinesResponse).machines;
+
+ it("a successful install is remembered, and is already visible on the first settled poll", async () => {
+ await boot();
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ const machines = await listed();
+ expect(machines.find((m) => m.id === "ssh:nas")?.installed).toEqual({
+ version: "9.9.9",
+ at: "2026-08-24T12:00:00.000Z",
+ });
+ // The machine that was never installed to is untouched.
+ expect(machines.find((m) => m.id === "ssh:build-box")?.installed).toBeNull();
+ });
+
+ it("survives the process: a fresh service over the same data root reads it back", async () => {
+ await boot();
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ // A new instance has no job and no memory — only the file. This is the restart case,
+ // and the hot-push case: the App is rebuilt, the data root is not.
+ const reborn = new MachinesService(machinesRoot, effects());
+ expect(reborn.job()).toBeNull();
+ expect(reborn.list().find((m) => m.id === "ssh:nas")?.installed).toEqual({
+ version: "9.9.9",
+ at: "2026-08-24T12:00:00.000Z",
+ });
+ });
+
+ it("installing elsewhere does not erase the first machine", async () => {
+ // The job is one slot, so before the records file existed this is exactly what made an
+ // installed machine disappear: the second install overwrote the only evidence.
+ await boot();
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ await admin.post("/api/machines/ssh:build-box/install");
+ await waitFor(() => t.deps.machines.job()?.machineId === "ssh:build-box");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ const machines = await listed();
+ expect(machines.every((m) => m.installed !== null)).toBe(true);
+ expect(recordsOnDisk()).toEqual({
+ "ssh:nas": { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" },
+ "ssh:build-box": { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" },
+ });
+ });
+
+ it("records what the REMOTE already had when nothing needed sending", async () => {
+ await boot({
+ install: async () => ({ kind: "already-installed", version: "8.8.8", identity: IDENTITY }),
+ });
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect((await listed()).find((m) => m.id === "ssh:nas")?.installed?.version).toBe("8.8.8");
+ });
+
+ it("a failed install records nothing", async () => {
+ await boot({
+ install: async () => ({ kind: "failed", step: "connect", detail: "no route to host" }),
+ });
+ await admin.post("/api/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect((await listed()).every((m) => m.installed === null)).toBe(true);
+ expect(fs.existsSync(path.join(machinesRoot, "machines-installs.json"))).toBe(false);
+ });
+
+ it("a damaged records file reads as nothing remembered, not as a broken list", async () => {
+ await boot();
+ fs.writeFileSync(path.join(machinesRoot, "machines-installs.json"), "{ not json");
+ const machines = await listed();
+ expect(machines).toHaveLength(2);
+ expect(machines.every((m) => m.installed === null)).toBe(true);
+ });
+ });
+
+ describe("refusals decided before any ssh runs", () => {
+ it("409s a second install while one is running", async () => {
+ let release = () => {};
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await boot({
+ install: async () => {
+ await held;
+ return { kind: "installed", output: "", identity: IDENTITY };
+ },
+ });
+ expect((await admin.post("/api/machines/ssh:nas/install")).status).toBe(202);
+ const second = await admin.post("/api/machines/ssh:build-box/install");
+ expect(second.status).toBe(409);
+ expect(((await second.json()) as { error: { code: string } }).error.code).toBe(
+ "install_running",
+ );
+ release();
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ });
+
+ it("404s a host this server's config does not declare", async () => {
+ await boot();
+ const res = await admin.post("/api/machines/ssh:not-in-config/install");
+ expect(res.status).toBe(404);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "unknown_machine",
+ );
+ expect(t.deps.machines.job()).toBeNull();
+ });
+
+ it("409s when this server carries no install image", async () => {
+ await boot({ resolvePlan: () => null });
+ const res = await admin.post("/api/machines/ssh:nas/install");
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "no_install_image",
+ );
+ });
+
+ it("502s a host ssh itself cannot resolve", async () => {
+ await boot({ resolveTarget: async () => null });
+ const res = await admin.post("/api/machines/ssh:nas/install");
+ expect(res.status).toBe(502);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "unresolvable_host",
+ );
+ });
+ });
+});
diff --git a/packages/server/test/machines-installs.test.ts b/packages/server/test/machines-installs.test.ts
new file mode 100644
index 00000000..6b0d0e66
--- /dev/null
+++ b/packages/server/test/machines-installs.test.ts
@@ -0,0 +1,68 @@
+/**
+ * The install-records file: what this server remembers having installed where. Damage of
+ * every shape has to read as "nothing remembered" rather than throw, because this file is a
+ * convenience over the ssh config — refusing to serve the machines list because a cache got
+ * corrupted would be the worse failure.
+ */
+import { describe, expect, it } from "vitest";
+import { parseInstallRecords, withInstallRecord } from "../src/machines/installs.js";
+
+const record = { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" };
+
+describe("parseInstallRecords", () => {
+ it("reads back what withInstallRecord wrote", () => {
+ const raw = withInstallRecord(null, "ssh:nas", record);
+ expect(parseInstallRecords(raw)).toEqual({ "ssh:nas": record });
+ });
+
+ it("treats absence, emptiness and damage alike: nothing remembered", () => {
+ for (const raw of [null, "", " ", "{ not json", "[]", "null", '"a string"']) {
+ expect(parseInstallRecords(raw)).toEqual({});
+ }
+ });
+
+ it("drops entries that are not a usable record, keeping the ones that are", () => {
+ const raw = JSON.stringify({
+ "ssh:good": record,
+ "ssh:no-version": { at: record.at },
+ "ssh:empty-version": { version: "", at: record.at },
+ "ssh:no-date": { version: "9.9.9" },
+ "ssh:not-an-object": 7,
+ "ssh:an-array": [record],
+ });
+ expect(parseInstallRecords(raw)).toEqual({ "ssh:good": record });
+ });
+});
+
+describe("withInstallRecord", () => {
+ it("adds without disturbing the others — the whole point of a per-machine file", () => {
+ let raw = withInstallRecord(null, "ssh:nas", record);
+ raw = withInstallRecord(raw, "ssh:build-box", { version: "8.8.8", at: record.at });
+ expect(parseInstallRecords(raw)).toEqual({
+ "ssh:nas": record,
+ "ssh:build-box": { version: "8.8.8", at: record.at },
+ });
+ });
+
+ it("replaces one machine's record in place", () => {
+ const raw = withInstallRecord(withInstallRecord(null, "ssh:nas", record), "ssh:nas", {
+ version: "10.0.0",
+ at: "2026-08-25T00:00:00.000Z",
+ });
+ expect(parseInstallRecords(raw)["ssh:nas"]?.version).toBe("10.0.0");
+ });
+
+ it("null forgets one machine and leaves the rest", () => {
+ let raw = withInstallRecord(null, "ssh:nas", record);
+ raw = withInstallRecord(raw, "ssh:build-box", record);
+ expect(parseInstallRecords(withInstallRecord(raw, "ssh:nas", null))).toEqual({
+ "ssh:build-box": record,
+ });
+ });
+
+ it("writes over damage rather than propagating it", () => {
+ expect(parseInstallRecords(withInstallRecord("{ not json", "ssh:nas", record))).toEqual({
+ "ssh:nas": record,
+ });
+ });
+});
diff --git a/packages/server/test/machines-push.test.ts b/packages/server/test/machines-push.test.ts
new file mode 100644
index 00000000..aa267296
--- /dev/null
+++ b/packages/server/test/machines-push.test.ts
@@ -0,0 +1,197 @@
+/**
+ * installOnRemote's orchestration, driven against stub `ssh`, `scp` and `tar` binaries on
+ * PATH: which dialect it probes in, that the release installer runs pinned to the base, that
+ * the hmr store streams over a pipe, the scratch directory being cleared even on failure,
+ * and each outcome the page renders. Real processes are spawned — only the far side is fake —
+ * so the argv this app hands to ssh is exercised rather than described.
+ *
+ * POSIX-only: the stubs are shell scripts. The Windows command forms are asserted as pure
+ * strings in machines.test.ts.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { installOnRemote } from "../src/machines/install-server.js";
+import type { PushPlan } from "../src/machines/install-server.js";
+
+const posixOnly = process.platform === "win32" ? describe.skip : describe;
+
+posixOnly("installOnRemote", () => {
+ let work: string;
+ let stubBin: string;
+ let logFile: string;
+ let originalPath: string | undefined;
+
+ const HARNESS = '{"platform":{"bundle":"store/platform/cafe0123456789ab.mjs"}}';
+
+ /** A plan the way resolvePushPlan builds one, with a real hmr dir to stream. */
+ const plan = (over: Partial<PushPlan> = {}): PushPlan => {
+ const hmrDir = path.join(work, "hmr");
+ fs.mkdirSync(path.join(hmrDir, "store"), { recursive: true });
+ fs.writeFileSync(path.join(hmrDir, "harness.json"), HARNESS);
+ fs.writeFileSync(path.join(hmrDir, "store", "x.mjs"), "//\n");
+ return {
+ baseVersion: "0.2.4",
+ harness: HARNESS,
+ hmrDir,
+ version: "0.2.4+hmr.cafe01234567",
+ ...over,
+ };
+ };
+
+ /** Where the push finds install.sh / install.ps1 — the repo root, in a source checkout. */
+ const assets = () => path.resolve(__dirname, "..", "..", "..");
+
+ /** Stub ssh/scp that log every invocation and answer as the scenario dictates. */
+ const writeStubs = (opts: { probe: string; posixUnknown?: boolean; installExit?: number }) => {
+ fs.writeFileSync(
+ path.join(stubBin, "ssh"),
+ [
+ "#!/bin/sh",
+ `printf 'ssh %s\\n' "$*" >> ${JSON.stringify(logFile)}`,
+ // NOT the `eval echo` idiom: some of these commands carry `&&`-joined mktemp/tar,
+ // which eval would EXECUTE on the test machine instead of merely naming.
+ 'for a in "$@"; do last=$a; done',
+ 'case "$last" in',
+ opts.posixUnknown
+ ? ` *uname*) echo "'uname' is not recognized as an internal or external command" 1>&2; exit 1 ;;`
+ : ` *uname*) printf '%b' ${JSON.stringify(opts.probe)} ;;`,
+ ` *PROCESSOR_ARCHITECTURE*) printf '%b' ${JSON.stringify(opts.probe)} ;;`,
+ " *mktemp*) echo /tmp/remote-scratch ;;",
+ // Single-quoted: sh's echo would otherwise eat the backslashes.
+ " *%TEMP%*) echo 'C:\\Temp\\penguin-scratch' ;;",
+ ` *sh\\ -s*) cat > /dev/null; echo "PenguinHarness 0.2.4 installed"; exit ${opts.installExit ?? 0} ;;`,
+ ` *install.ps1*) echo "PenguinHarness 0.2.4 installed"; exit ${opts.installExit ?? 0} ;;`,
+ // The store stream: swallow stdin so the local tar does not die on a broken pipe.
+ " *'tar -xzf -'*) cat > /dev/null ;;",
+ " *) : ;;",
+ "esac",
+ "exit 0",
+ ].join("\n"),
+ { mode: 0o755 },
+ );
+ fs.writeFileSync(
+ path.join(stubBin, "scp"),
+ ["#!/bin/sh", `printf 'scp %s\\n' "$*" >> ${JSON.stringify(logFile)}`, "exit 0"].join("\n"),
+ { mode: 0o755 },
+ );
+ };
+
+ const calls = (): string[] =>
+ fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8").trim().split("\n") : [];
+
+ beforeEach(() => {
+ work = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-push-test-"));
+ stubBin = path.join(work, "bin");
+ fs.mkdirSync(stubBin);
+ logFile = path.join(work, "calls.log");
+ originalPath = process.env.PATH;
+ process.env.PATH = `${stubBin}:${process.env.PATH ?? ""}`;
+ });
+ afterEach(() => {
+ process.env.PATH = originalPath;
+ fs.rmSync(work, { recursive: true, force: true });
+ });
+
+ const target = { alias: "build-box", user: "deploy" };
+
+ it("probes, installs over ONE ssh call, then streams the store", async () => {
+ writeStubs({ probe: "Linux x86_64\\n---penguin---\\n---penguin---\\n" });
+ const progress: string[] = [];
+ const outcome = await installOnRemote({
+ target,
+ plan: plan(),
+ assets,
+ onProgress: (line) => progress.push(line),
+ });
+
+ expect(outcome).toMatchObject({ kind: "installed" });
+ const log = calls();
+ // Three handshakes, and no scp, mktemp or rm anywhere: the installer went in on stdin.
+ expect(log).toHaveLength(3);
+ expect(log[0]).toContain("uname -s -m"); // identity first
+ // The release is downloaded ON THE REMOTE, pinned to this server's own base.
+ expect(log[1]).toContain("PENGUIN_VERSION='v0.2.4' sh -s");
+ // The hmr state crosses as a stream into the default data root.
+ expect(log[2]).toContain('tar -xzf - -C "$HOME/.penguin/data"');
+ expect(log.some((line) => line.startsWith("scp"))).toBe(false);
+ expect(log.some((line) => line.includes("mktemp") || line.includes("rm -rf"))).toBe(false);
+ expect(log.every((line) => line.includes("User=deploy"))).toBe(true);
+ expect(log.every((line) => line.includes("BatchMode=yes"))).toBe(true);
+ expect(progress).toContain("linux-x64.");
+ // The far side's own output is relayed as it arrives, not withheld until exit.
+ expect(progress).toContain("PenguinHarness 0.2.4 installed");
+ });
+
+ it("falls back to the Windows probe when the POSIX one is not understood", async () => {
+ writeStubs({
+ probe: "Windows_NT AMD64\\n---penguin---\\n---penguin---\\n",
+ posixUnknown: true,
+ });
+ const outcome = await installOnRemote({ target, plan: plan(), assets });
+
+ expect(outcome).toMatchObject({ kind: "installed" });
+ const log = calls();
+ expect(log[0]).toContain("uname -s -m");
+ expect(log[1]).toContain("%PROCESSOR_ARCHITECTURE%");
+ // PowerShell cannot take the script on stdin, so a Windows remote gets a copy — scp'd to
+ // the home directory, with the delete chained onto the command that runs it.
+ expect(log[2]).toMatch(/^scp .*\.ps1 build-box:\.$/);
+ expect(log[3]).toContain('-File "%USERPROFILE%\\penguin-');
+ expect(log[3]).toContain('-Version "v0.2.4"');
+ expect(log[3]).toContain("& del /q");
+ expect(log.some((line) => line.includes('mkdir "%TEMP%'))).toBe(false);
+ });
+
+ it("a matching base skips the installer and only streams the store", async () => {
+ writeStubs({
+ probe: 'Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n',
+ });
+ const outcome = await installOnRemote({ target, plan: plan(), assets });
+ expect(outcome).toMatchObject({ kind: "installed" });
+ const log = calls();
+ expect(log.some((line) => line.includes("install.sh"))).toBe(false);
+ expect(log.some((line) => line.includes("tar -xzf -"))).toBe(true);
+ });
+
+ it("does nothing when the remote already matches base AND pushed state", async () => {
+ writeStubs({
+ probe: `Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n${HARNESS}\\n`,
+ });
+ const outcome = await installOnRemote({ target, plan: plan(), assets });
+ expect(outcome).toMatchObject({ kind: "already-installed", version: "0.2.4+hmr.cafe01234567" });
+ expect(calls()).toHaveLength(1); // the probe, and nothing else
+ });
+
+ it("a bare release plan streams nothing", async () => {
+ writeStubs({ probe: "Linux x86_64\\n---penguin---\\n---penguin---\\n" });
+ const outcome = await installOnRemote({
+ target,
+ plan: plan({ harness: null, hmrDir: null, version: "0.2.4" }),
+ assets,
+ });
+ expect(outcome).toMatchObject({ kind: "installed" });
+ expect(calls().some((line) => line.includes("tar -xzf -"))).toBe(false);
+ });
+
+ it("reports the installer's own output on failure", async () => {
+ writeStubs({
+ probe: 'Linux x86_64\\n---penguin---\\n{"version":"0.0.1"}\\n---penguin---\\n',
+ installExit: 3,
+ });
+ const outcome = await installOnRemote({ target, plan: plan(), assets });
+ expect(outcome).toMatchObject({ kind: "failed", step: "install" });
+ expect((outcome as { detail: string }).detail).toContain("PenguinHarness 0.2.4 installed");
+ });
+
+ it("refuses a base that cannot name a release", async () => {
+ writeStubs({ probe: "Linux x86_64\\n---penguin---\\n---penguin---\\n" });
+ const outcome = await installOnRemote({
+ target,
+ plan: plan({ baseVersion: "0.0.0-hmr.cafe", version: "0.0.0-hmr.cafe" }),
+ assets,
+ });
+ expect(outcome).toMatchObject({ kind: "failed", step: "resolve the release" });
+ });
+});
diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.ts
new file mode 100644
index 00000000..d07a0719
--- /dev/null
+++ b/packages/server/test/machines.test.ts
@@ -0,0 +1,344 @@
+/**
+ * The pure half of the machines capability (platform code — see ../src/hmr/README.md):
+ * reading ~/.ssh/config and `ssh -G`, reading what the identity probe answered, choosing
+ * the Node runtime to send, the container the image travels in, finding the running
+ * server's own pushable image, and the exact ssh/scp commands all of that turns into.
+ * No network, no ssh binary.
+ */
+import fs from "node:fs";
+import zlib from "node:zlib";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { machineIdentity, parseHostAliases, parseSshSettings } from "../src/machines/ssh-config.js";
+import { parseProbeOutput, POSIX_PROBE, WINDOWS_PROBE } from "../src/machines/detect.js";
+import {
+ cmdQuote,
+ runInstallScriptCommand,
+ unpackStoreCommand,
+ scpArgs,
+ shQuote,
+ sshArgs,
+} from "../src/machines/commands.js";
+import { resolvePushPlan } from "../src/machines/install-server.js";
+
+describe("parseHostAliases", () => {
+ const noIncludes = () => [];
+
+ it("lists declared aliases in file order, expanding multi-alias blocks", () => {
+ const aliases = parseHostAliases(
+ ["Host build-box", " HostName 10.0.0.4", "", "Host gpu-1 gpu-1.lan", " User root"].join(
+ "\n",
+ ),
+ noIncludes,
+ );
+ expect(aliases).toEqual(["build-box", "gpu-1", "gpu-1.lan"]);
+ });
+
+ it("skips pattern entries — they configure other hosts rather than naming one", () => {
+ const aliases = parseHostAliases(
+ ["Host *", " ServerAliveInterval 30", "Host !prod *.lan", "Host real"].join("\n"),
+ noIncludes,
+ );
+ expect(aliases).toEqual(["real"]);
+ });
+
+ it("ignores comments and blank lines, and is case-insensitive like ssh", () => {
+ expect(parseHostAliases("# Host commented\n\nhost lower\nHOST upper", noIncludes)).toEqual([
+ "lower",
+ "upper",
+ ]);
+ });
+
+ it("follows Include through the supplied reader and de-duplicates the result", () => {
+ const files: Record<string, string> = {
+ "work/*": "Host build-box\nHost shared",
+ personal: "Host shared\nHost nas",
+ };
+ const aliases = parseHostAliases(
+ ["Include work/*", "Host laptop", "Include personal"].join("\n"),
+ (pattern) => (files[pattern] === undefined ? [] : [files[pattern]]),
+ );
+ expect(aliases).toEqual(["build-box", "shared", "laptop", "nas"]);
+ });
+
+ it("survives an include cycle instead of spinning", () => {
+ const aliases = parseHostAliases("Include self\nHost top", () => ["Include self\nHost deep"]);
+ expect(aliases).toContain("top");
+ expect(aliases).toContain("deep");
+ });
+});
+
+describe("parseSshSettings", () => {
+ it("reads what ssh resolved, keeping every identityfile", () => {
+ const settings = parseSshSettings(
+ [
+ "user deploy",
+ "hostname 10.0.0.4",
+ "port 2222",
+ "identityfile ~/.ssh/id_ed25519",
+ "identityfile ~/.ssh/id_rsa",
+ "proxyjump bastion",
+ ].join("\n"),
+ "build-box",
+ );
+ expect(settings).toEqual({
+ user: "deploy",
+ hostname: "10.0.0.4",
+ port: 2222,
+ identityFiles: ["~/.ssh/id_ed25519", "~/.ssh/id_rsa"],
+ proxyJump: "bastion",
+ });
+ });
+
+ it("falls back to ssh's own defaults rather than throwing on a config it cannot read", () => {
+ const settings = parseSshSettings("garbage\nport not-a-number\nproxyjump none", "gpu-1");
+ expect(settings.hostname).toBe("gpu-1"); // the alias stands in
+ expect(settings.port).toBe(22);
+ expect(settings.user).toBe("");
+ expect(settings.proxyJump).toBeNull();
+ });
+});
+
+describe("machineIdentity", () => {
+ it("is <user>@<alias>: the Linux account is part of the machine, the alias is the name", () => {
+ // Two accounts on one host are two machines — each has its own ~/.penguin, hence its
+ // own server and its own user table.
+ expect(machineIdentity("build-box", "deploy")).toBe("deploy@build-box");
+ expect(machineIdentity("build-box", "root")).toBe("root@build-box");
+ expect(machineIdentity("build-box", "")).toBe("build-box");
+ });
+});
+
+describe("identity probe", () => {
+ it("asks in each shell's own dialect — sh cannot read the Windows one and vice versa", () => {
+ // POSIX: `;` chains, $VAR expands, `cat` reads. Windows cmd: `&` chains, %VAR% expands,
+ // `type` reads. One command cannot do both, which is why there are two.
+ expect(POSIX_PROBE).toContain("uname -s -m");
+ expect(POSIX_PROBE).toContain('"$HOME/.penguin/lib/package.json"');
+ expect(POSIX_PROBE).toContain(".penguin/data/hmr/harness.json");
+ expect(WINDOWS_PROBE).toContain("%PROCESSOR_ARCHITECTURE%");
+ expect(WINDOWS_PROBE).toContain("%USERPROFILE%\\.penguin\\lib\\package.json");
+ expect(WINDOWS_PROBE).toContain("%USERPROFILE%\\.penguin\\data\\hmr\\harness.json");
+ expect(WINDOWS_PROBE).not.toContain(";");
+ });
+
+ it("reads identity, installed version and pushed state from the three sections", () => {
+ expect(
+ parseProbeOutput(
+ 'Linux x86_64\n---penguin---\n{"name":"x","version":"0.2.2"}\n---penguin---\n{"platform":{}}\n',
+ ),
+ ).toEqual({
+ platform: "linux",
+ arch: "x64",
+ installedVersion: "0.2.2",
+ harness: '{"platform":{}}',
+ });
+ });
+
+ it("a machine with nothing installed answers empty sections", () => {
+ expect(parseProbeOutput("Linux x86_64\n---penguin---\n---penguin---\n")).toMatchObject({
+ installedVersion: null,
+ harness: null,
+ });
+ });
+
+ it("skips a login banner before the identity line", () => {
+ expect(
+ parseProbeOutput("Welcome to build-box!\nLinux x86_64\n---penguin---\n---penguin---\n"),
+ ).toMatchObject({ platform: "linux", arch: "x64" });
+ });
+
+ it("recognizes every platform-arch pair the release targets name", () => {
+ expect(parseProbeOutput("Windows_NT AMD64\n---penguin---\n")).toMatchObject({
+ platform: "win32",
+ arch: "x64",
+ });
+ expect(parseProbeOutput("Darwin arm64\n---penguin---\n")).toMatchObject({
+ platform: "darwin",
+ arch: "arm64",
+ });
+ expect(parseProbeOutput("Linux aarch64\n---penguin---\n")).toMatchObject({
+ platform: "linux",
+ arch: "arm64",
+ });
+ });
+
+ it("an unrecognized answer (or an error message) parses as null", () => {
+ expect(
+ parseProbeOutput("'uname' is not recognized as an internal or external command"),
+ ).toBeNull();
+ expect(parseProbeOutput("")).toBeNull();
+ });
+
+ it("a damaged manifest reads as nothing installed", () => {
+ expect(parseProbeOutput("Linux x86_64\n---penguin---\nnot json at all")).toMatchObject({
+ installedVersion: null,
+ });
+ });
+});
+
+describe("ssh / scp invocations", () => {
+ const target = { alias: "build-box", user: "deploy" };
+
+ it("never lets ssh prompt: a GUI has no terminal to type a password into", () => {
+ const args = sshArgs(target, "uname -a");
+ expect(args).toContain("BatchMode=yes");
+ expect(args).toContain("ConnectTimeout=10");
+ expect(scpArgs(target, ["/tmp/a"], "/tmp/dir")).toContain("BatchMode=yes");
+ });
+
+ it("selects the account on the command line, never by writing the ssh config", () => {
+ expect(sshArgs(target, "true")).toContain("User=deploy");
+ expect(sshArgs({ alias: "build-box", user: "" }, "true").join(" ")).not.toContain("User=");
+ });
+
+ it("leaves the scp destination unquoted — modern scp transfers over SFTP, taking it literally", () => {
+ const args = scpArgs(target, ["/local/image.pack"], "/tmp/penguin-abc123");
+ expect(args.at(-1)).toBe("build-box:/tmp/penguin-abc123");
+ });
+
+ it("quotes per shell: single quotes for sh, double for cmd.exe", () => {
+ expect(shQuote("/tmp/it's here")).toBe(`'/tmp/it'\\''s here'`);
+ expect(cmdQuote("C:\\Users\\First Last\\tmp")).toBe('"C:\\Users\\First Last\\tmp"');
+ // cmd.exe has no escape for a quote inside a quoted string: refuse rather than mangle.
+ expect(() => cmdQuote('C:\\weird"path')).toThrow();
+ });
+
+ it("takes the installer on stdin, so a POSIX install costs ONE ssh handshake", () => {
+ // No path anywhere in it: nothing was copied, so nothing has to be placed or cleaned up.
+ // scriptOnStdin is the other half — the command alone would run an empty `sh -s`.
+ expect(runInstallScriptCommand("v0.2.4", { platform: "linux" })).toEqual({
+ command: "PENGUIN_VERSION='v0.2.4' sh -s",
+ scriptOnStdin: true,
+ });
+ });
+
+ it("runs a Windows remote's copy from a path, and deletes it in the same command", () => {
+ // PowerShell cannot take a param()-carrying script on stdin, so the file is real there —
+ // but the delete rides the same connection rather than costing another handshake, and the
+ // path is required to build the command at all rather than defaulting to an empty one.
+ expect(
+ runInstallScriptCommand("v0.2.4", {
+ platform: "win32",
+ scriptPath: "%USERPROFILE%\\penguin-ab12.ps1",
+ }),
+ ).toEqual({
+ command:
+ 'powershell -NoProfile -ExecutionPolicy Bypass -File "%USERPROFILE%\\penguin-ab12.ps1"' +
+ ' -Version "v0.2.4" & del /q "%USERPROFILE%\\penguin-ab12.ps1"',
+ scriptOnStdin: false,
+ });
+ });
+
+ it("unpacks the streamed store into the default data root", () => {
+ expect(unpackStoreCommand("linux")).toBe(
+ 'mkdir -p "$HOME/.penguin/data" && tar -xzf - -C "$HOME/.penguin/data"',
+ );
+ expect(unpackStoreCommand("win32")).toBe(
+ '(if not exist "%USERPROFILE%\\.penguin\\data" mkdir "%USERPROFILE%\\.penguin\\data") & tar -xzf - -C "%USERPROFILE%\\.penguin\\data"',
+ );
+ });
+});
+
+describe("resolvePushPlan", () => {
+ const manifest = JSON.stringify({ name: "@prismshadow/penguin-cli", version: "0.2.4" });
+
+ it("tarball install: the base release, with no pushed state", () => {
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-plan-"));
+ try {
+ const root = path.join(work, "penguin");
+ fs.mkdirSync(path.join(root, "lib", "dist"), { recursive: true });
+ fs.writeFileSync(path.join(root, "lib", "dist", "penguin.js"), "//\n");
+ fs.writeFileSync(path.join(root, "lib", "package.json"), manifest);
+
+ const plan = resolvePushPlan(work, path.join(root, "lib", "dist", "penguin.js"));
+ expect(plan).toMatchObject({ baseVersion: "0.2.4", harness: null, version: "0.2.4" });
+ } finally {
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+ });
+
+ it("a pushed server adds its hmr state, sha-suffixed", () => {
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-plan-"));
+ try {
+ const root = path.join(work, "penguin");
+ fs.mkdirSync(path.join(root, "lib", "dist"), { recursive: true });
+ fs.writeFileSync(path.join(root, "lib", "dist", "penguin.js"), "//\n");
+ fs.writeFileSync(path.join(root, "lib", "package.json"), manifest);
+ const hmrDir = path.join(work, "data", "hmr");
+ fs.mkdirSync(hmrDir, { recursive: true });
+ const harness = JSON.stringify({
+ platform: { bundle: "store/platform/cafe0123456789ab.mjs" },
+ });
+ fs.writeFileSync(path.join(hmrDir, "harness.json"), harness);
+
+ const plan = resolvePushPlan(
+ path.join(work, "data"),
+ path.join(root, "lib", "dist", "penguin.js"),
+ );
+ expect(plan).toMatchObject({
+ baseVersion: "0.2.4",
+ harness,
+ hmrDir,
+ version: "0.2.4+hmr.cafe01234567",
+ });
+ } finally {
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+ });
+
+ it("packaged desktop app: its own manifest names the release it shipped under", () => {
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-plan-"));
+ try {
+ // What the app forks: <resources>/app/dist/server.js, one bundled file, asar off.
+ const appDir = path.join(work, "resources", "app");
+ fs.mkdirSync(path.join(appDir, "dist"), { recursive: true });
+ fs.writeFileSync(
+ path.join(appDir, "package.json"),
+ JSON.stringify({ name: "@prismshadow/penguin-desktop", version: "0.2.4" }),
+ );
+
+ const plan = resolvePushPlan(null, path.join(appDir, "dist", "server.js"));
+ expect(plan).toMatchObject({ baseVersion: "0.2.4" });
+ } finally {
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+ });
+
+ it("a desktop SOURCE run stands on no release: packages/desktop is not under resources/", () => {
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-plan-"));
+ try {
+ const pkgDir = path.join(work, "packages", "desktop");
+ fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@prismshadow/penguin-desktop", version: "0.2.4" }),
+ );
+
+ expect(resolvePushPlan(null, path.join(pkgDir, "dist", "server.js"))).toBeNull();
+ } finally {
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+ });
+
+ it("a dev checkout stands on no release and answers null", () => {
+ expect(resolvePushPlan(null, "/repo/packages/server/src/index.ts")).toBeNull();
+ expect(resolvePushPlan(null, undefined)).toBeNull();
+ });
+});
+
+describe("shipping the installers", () => {
+ /**
+ * The push copies these files out of dist/; they are never imported, so nothing in the
+ * module graph would notice one going missing from a built package. The build copies them
+ * in (tsup.config.ts's onSuccess), and that copy is worth an assertion rather than a comment.
+ */
+ it.each(["install.sh", "install.ps1"])("%s is copied into dist at build time", (name) => {
+ const built = path.resolve(__dirname, "..", "dist", name);
+ if (!fs.existsSync(built)) return; // Not built in this run; `pnpm build` covers it in CI.
+ const source = path.resolve(__dirname, "..", "..", "..", name);
+ expect(fs.readFileSync(built, "utf8")).toBe(fs.readFileSync(source, "utf8"));
+ });
+});
diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.ts
index 0ab13224..be4a85cc 100644
--- a/packages/server/tsup.config.ts
+++ b/packages/server/tsup.config.ts
@@ -1,3 +1,6 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
import { defineConfig } from "tsup";
export default defineConfig({
@@ -33,4 +36,16 @@ export default defineConfig({
dts: true,
clean: true,
sourcemap: true,
+ // The release installers, as REAL files beside the bundles. A remote install scp's one to
+ // the far side and runs it there, resolving it next to this module — so it has to exist in
+ // dist/, which `files: ["dist"]` is what npm ships. tsup only emits its entries, and these
+ // are copied and never imported, so nothing in the module graph would pull them along.
+ // A missing source throws here, which fails the build rather than shipping a package whose
+ // Machines page dies at "prepare the installer".
+ onSuccess: async () => {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ for (const name of ["install.sh", "install.ps1"]) {
+ fs.copyFileSync(path.join(here, "..", "..", name), path.join(here, "dist", name));
+ }
+ },
});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 7a72924a..66466258 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -65,6 +65,7 @@ import type {
ModelOAuthStatusResponse,
ModelProtocolDetectRequest,
ModelProtocolDetectResponse,
+ MachinesResponse,
ModelsResponse,
ModelsUpdateRequest,
ModelTestRequest,
@@ -1063,6 +1064,22 @@ export const importAgent = (projectId: string, agentId: string, body: AgentImpor
{ method: "POST", body },
);
+// Machines (admin only) ----------------------------------------------------------------
+
+/**
+ * The server's ssh hosts, the version it would install, and the running or last install
+ * job. The Machines page polls this while a job runs — the progress lines live on the job,
+ * not on the event channel, because they belong to the one page that is waiting for them.
+ */
+export const getMachines = () => apiFetch<MachinesResponse>("/api/machines");
+
+/** Starts an install (202, long-running); the returned body already carries the new job. */
+export const installOnMachine = (machineId: string) =>
+ apiFetch<MachinesResponse>(`/api/machines/${encodeURIComponent(machineId)}/install`, {
+ method: "POST",
+ body: {},
+ });
+
// Version & self-update ----------------------------------------------------------------
export const getVersion = () => apiFetch<VersionResponse>("/api/version");
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 6b8dd77c..9cafe37d 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -67,8 +67,8 @@ import {
} from "../../lib/session-grouping";
import type { FolderCategory, SessionPartition } from "../../lib/session-grouping";
import {
- NAV_GROUP_KEYS,
initialNavGroupCollapsed,
+ navKeysFor,
storeNavGroupCollapsed,
} from "../../lib/nav-group-collapse";
import {
@@ -1485,10 +1485,10 @@ export function Sidebar({
),
);
- /** Page entries of the collapsible nav group (智能体 → 评估中心, driven by the NAV_GROUP_KEYS manifest). Always mounted — the collapse animates their height to zero and turns them inert. */
- const navItems: Array<{ to: string; label: string; icon: string }> = NAV_GROUP_KEYS.map(
- (key) => ({ to: `/${key}`, label: S.nav[key], icon: NAV_ICONS[key] }),
- );
+ /** Page entries of the collapsible nav group (智能体 → 评估中心, driven by the NAV_GROUP_KEYS manifest, minus the entries this user's role cannot reach). Always mounted — the collapse animates their height to zero and turns them inert. */
+ const navItems: Array<{ to: string; label: string; icon: string }> = navKeysFor(
+ user?.isAdmin === true,
+ ).map((key) => ({ to: `/${key}`, label: S.nav[key], icon: NAV_ICONS[key] }));
return (
<div className="flex h-full w-full flex-col">
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index b3a65530..23b3ed78 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -189,6 +189,8 @@ export const NAV_ICONS = {
/** Skill library (an open book: two pages + spine). */
skills: "M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",
models: "M7 7h10v10H7zM4 10h3m10 0h3M4 14h3m10 0h3M10 4v3m4-3v3m-4 10v3m4-3v3",
+ /** Machines (two stacked server units, each with its own status lamp). */
+ machines: "M4 4h16v6H4zM4 14h16v6H4zM7 7h.01M7 17h.01",
usage: "M4 20V10m6 10V4m6 16v-7m4 7H2",
traces: "M4 6h16M4 12h10M4 18h13",
/** Benchmark center (a trophy: cup + two handles + base). */
diff --git a/packages/web/src/features/machines/machines-match.ts b/packages/web/src/features/machines/machines-match.ts
new file mode 100644
index 00000000..7ee8bb9b
--- /dev/null
+++ b/packages/web/src/features/machines/machines-match.ts
@@ -0,0 +1,102 @@
+/**
+ * The machine picker's fuzzy search: an ssh config can declare hundreds of hosts, so the
+ * picker never lists them all — a few rows render and the query reaches the rest.
+ *
+ * Matching is a subsequence, not a substring, because ssh aliases are punctuated (`gpu-01`,
+ * `db_prod.eu`) and the useful query is the letters you remember, not the separators you do
+ * not: `gpu1` has to find `gpu-01`. The score then puts the obvious hits on top, and the
+ * matched characters are handed back as positions so the row can show WHY it matched — with
+ * a subsequence match, a row whose hit characters are invisible looks like a wrong result.
+ */
+
+/** One `Host` entry as the picker needs it: the alias is the label, the id is what installs. */
+export interface MachineLike {
+ id: string;
+ alias: string;
+}
+
+/**
+ * How many rows the picker shows at once. The search box reaches everything past this, and
+ * a counter names how many the current view leaves out — a silent truncation would read as
+ * "that host is not in my config".
+ */
+export const MAX_VISIBLE_MACHINES = 6;
+
+/** One machine that survived the query, with the character positions the query hit. */
+export interface MachineMatch<T extends MachineLike = MachineLike> {
+ machine: T;
+ /** Indices into `machine.alias` to highlight; empty for the empty query. */
+ positions: number[];
+}
+
+/** True when the alias character at `index` starts a word (`gpu-01` → g, 0). */
+const isWordStart = (alias: string, index: number) =>
+ index === 0 || /[-_./ ]/.test(alias[index - 1]!);
+
+/**
+ * Fuzzy match of `query` against one alias: every query character must appear, in order,
+ * but not adjacently — `gpu1` hits `gpu-01`. Greedy left-to-right with a small score:
+ * +3 for a character adjacent to the previous hit, +2 for one starting a word, +1
+ * otherwise — so contiguous runs rank above initial-letter matches, which rank above
+ * scattered ones. Null when the query does not fit at all.
+ */
+export function fuzzyMatch(
+ alias: string,
+ query: string,
+): { positions: number[]; score: number } | null {
+ const haystack = alias.toLowerCase();
+ const needle = query.toLowerCase();
+ const positions: number[] = [];
+ let score = 0;
+ let at = 0;
+ for (const ch of needle) {
+ const found = haystack.indexOf(ch, at);
+ if (found === -1) return null;
+ const previous = positions[positions.length - 1];
+ score +=
+ previous !== undefined && found === previous + 1 ? 3 : isWordStart(alias, found) ? 2 : 1;
+ positions.push(found);
+ at = found + 1;
+ }
+ return { positions, score };
+}
+
+/**
+ * The machines a query keeps, best first. An empty query keeps every machine in the
+ * server's order (which is the ssh config's own order); otherwise matches sort by score
+ * with that order as the tiebreak, so equally good hits stay in the order the config
+ * declares them rather than being reshuffled by something invisible.
+ */
+export function matchMachines<T extends MachineLike>(
+ machines: readonly T[],
+ query: string,
+): MachineMatch<T>[] {
+ const q = query.trim();
+ if (q === "") return machines.map((machine) => ({ machine, positions: [] }));
+ return machines
+ .map((machine, index) => {
+ const match = fuzzyMatch(machine.alias, q);
+ return match === null
+ ? null
+ : { machine, positions: match.positions, score: match.score, index };
+ })
+ .filter((entry): entry is NonNullable<typeof entry> => entry !== null)
+ .sort((a, b) => (a.score !== b.score ? b.score - a.score : a.index - b.index))
+ .map(({ machine, positions }) => ({ machine, positions }));
+}
+
+/** The alias split into contiguous runs for rendering: `hit` runs carry the highlight. */
+export function highlightSegments(
+ alias: string,
+ positions: number[],
+): Array<{ text: string; hit: boolean }> {
+ const hits = new Set(positions);
+ const out: Array<{ text: string; hit: boolean }> = [];
+ for (let i = 0; i < alias.length; i++) {
+ const hit = hits.has(i);
+ const last = out[out.length - 1];
+ if (last !== undefined && last.hit === hit) last.text += alias[i]!;
+ else out.push({ text: alias[i]!, hit });
+ }
+ return out;
+}
diff --git a/packages/web/src/features/machines/machines-page.tsx b/packages/web/src/features/machines/machines-page.tsx
new file mode 100644
index 00000000..315052fa
--- /dev/null
+++ b/packages/web/src/features/machines/machines-page.tsx
@@ -0,0 +1,374 @@
+/**
+ * Machines page: pick a host out of the SERVER's own `~/.ssh/config` and install this build
+ * on it.
+ *
+ * The host list is a PICKER, not a rendered list, because an ssh config routinely declares
+ * hundreds of entries: the panel shows a few rows, a fuzzy query reaches the rest, and the
+ * matched characters are highlighted so a subsequence hit (`gpu1` → `gpu-01`) reads as a
+ * match rather than as a wrong result. A counter names how many rows the current view leaves
+ * out — silent truncation would read as "that host is not in my config".
+ *
+ * The list itself is the config text; the server does no `ssh -G` and no network to produce
+ * it, so hundreds of hosts cost one file read and a row carries nothing but its alias.
+ *
+ * An install is a job on the server, not a request that finishes: it probes the machine,
+ * may fetch a Node runtime, copies an image over scp and runs an installer there. POST
+ * starts it and the page polls while it runs. The progress lines are the far side's own
+ * words wherever there are any, so they are rendered verbatim in a monospace block rather
+ * than interpreted here — a refused key or an unusable Node explains itself better than any
+ * status enum could.
+ *
+ * One job exists at a time server-side, so the panel below follows THE JOB and names the
+ * alias it belongs to, while the button follows the SELECTION: picking another host while
+ * one installs must not hide the install that is running.
+ *
+ * Which hosts already carry this program comes from each machine's own persisted record,
+ * not from the job — the job is one slot, so reading "installed" off it made a host stop
+ * looking installed the moment anything else was installed or the server restarted.
+ */
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { MachinesResponse } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { formatDateTime } from "../../lib/format";
+import { toneInk, toneStrip } from "../../lib/tone";
+import type { Tone } from "../../lib/tone";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { Button } from "../../components/ui/button";
+import { Dropdown } from "../../components/ui/dropdown";
+import { EmptyState } from "../../components/ui/empty-state";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { Skeleton } from "../../components/ui/skeleton";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { ChevronDown, NAV_ICONS } from "../../components/ui/icons";
+import { installButtonState, installedMachines, verdictOf } from "./machines-view";
+import type { MachineVerdict } from "./machines-view";
+import { MAX_VISIBLE_MACHINES, highlightSegments, matchMachines } from "./machines-match";
+
+/** How often a running job is re-read. Slow enough to be free, fast enough that a step reads as progress. */
+const POLL_MS = 1500;
+
+/** A finished job's one-line verdict, and the tone that carries it. */
+function verdictLine(verdict: MachineVerdict): { text: string; tone: Tone } {
+ if (verdict.kind === "failed") {
+ return { text: S.machines.failedAt(verdict.step), tone: "danger" };
+ }
+ const version = verdict.version ?? "";
+ return {
+ text:
+ verdict.kind === "already-installed"
+ ? S.machines.alreadyInstalled(version)
+ : S.machines.installed(version),
+ tone: "success",
+ };
+}
+
+export function MachinesPage() {
+ useDocumentTitle(S.machines.pageTitle);
+ const [state, setState] = useState<MachinesResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** True while a POST has not come back yet — the server has no job to report in that window. */
+ const [starting, setStarting] = useState(false);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+
+ /** The picker panel; closing it always clears the query, so it reopens unfiltered. */
+ const [pickerOpen, setPickerOpenState] = useState(false);
+ const [query, setQuery] = useState("");
+ const setPickerOpen = (open: boolean) => {
+ setPickerOpenState(open);
+ if (!open) setQuery("");
+ };
+
+ const load = useCallback(async () => {
+ try {
+ setState(await api.getMachines());
+ setError(null);
+ } catch (err) {
+ setError(apiErrorText(err));
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ // Poll only while a job runs. Chained timeouts rather than an interval: a slow response
+ // must not stack requests behind itself.
+ const running = state?.job?.running === true;
+ const loadRef = useRef(load);
+ loadRef.current = load;
+ useEffect(() => {
+ if (!running) return;
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const tick = () => {
+ timer = setTimeout(() => {
+ void loadRef.current().finally(() => {
+ if (!cancelled) tick();
+ });
+ }, POLL_MS);
+ };
+ tick();
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [running]);
+
+ const machines = useMemo(() => state?.machines ?? [], [state]);
+ const installed = useMemo(() => (state === null ? [] : installedMachines(state)), [state]);
+ const matched = useMemo(() => matchMachines(machines, query), [machines, query]);
+ const visible = matched.slice(0, MAX_VISIBLE_MACHINES);
+ const hiddenCount = matched.length - visible.length;
+ const selected = machines.find((machine) => machine.id === selectedId) ?? null;
+
+ const install = async () => {
+ if (selectedId === null) return;
+ setStarting(true);
+ try {
+ setState(await api.installOnMachine(selectedId));
+ setError(null);
+ } catch (err) {
+ setError(apiErrorText(err));
+ } finally {
+ setStarting(false);
+ }
+ };
+
+ const job = state?.job ?? null;
+ const verdict = job === null ? null : verdictOf(job);
+ const verdictText = verdict === null ? null : verdictLine(verdict);
+ const button =
+ state === null
+ ? { action: "install" as const, disabled: true }
+ : installButtonState(selected, state, starting);
+
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <div className="mx-auto max-w-3xl">
+ <h1 className="flex items-center gap-1.5 text-xl font-semibold">
+ {S.machines.pageTitle}
+ <InfoPopover label={S.machines.pageTitle}>{S.machines.pageDesc}</InfoPopover>
+ </h1>
+
+ {error !== null && (
+ <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>
+ {error}
+ </div>
+ )}
+
+ {state === null ? (
+ <div className="mt-6 space-y-2">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-9 w-full" />
+ </div>
+ ) : (
+ <>
+ {state.imageVersion === null ? (
+ <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.attention}`}>
+ {S.machines.noImage}
+ </div>
+ ) : (
+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
+ {S.machines.imageVersion(state.imageVersion)}
+ </p>
+ )}
+
+ {machines.length === 0 ? (
+ <EmptyState title={S.machines.empty} />
+ ) : (
+ <div className="mt-6 flex items-start gap-2">
+ {/* The picker. Fuzzy query over the aliases, matched characters bright and
+ the rest dimmed — with a subsequence match, an unmarked row looks wrong. */}
+ <Dropdown
+ open={pickerOpen}
+ setOpen={setPickerOpen}
+ className="min-w-0 flex-1"
+ menuClass="left-0 right-0 top-full mt-1 origin-top"
+ button={
+ <button
+ type="button"
+ onClick={() => setPickerOpen(!pickerOpen)}
+ aria-haspopup="listbox"
+ aria-expanded={pickerOpen}
+ className="flex w-full items-center gap-2 rounded-md border border-gray-300 bg-white px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-900 dark:hover:bg-gray-800"
+ >
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">
+ <GlyphIcon d={NAV_ICONS.machines} size={ICON_SIZE.rowLead} />
+ </span>
+ <span
+ className={`min-w-0 flex-1 truncate ${selected === null ? "text-gray-400 dark:text-gray-500" : ""}`}
+ >
+ {selected?.alias ?? S.machines.pick}
+ </span>
+ <ChevronDown className="shrink-0 text-gray-400" />
+ </button>
+ }
+ >
+ {machines.length > MAX_VISIBLE_MACHINES && (
+ <div className="px-2 pt-1 pb-1">
+ <input
+ type="search"
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={S.machines.search}
+ aria-label={S.machines.search}
+ className="w-full rounded-md border border-gray-200 bg-transparent px-2.5 py-1.5 text-sm transition-colors outline-none placeholder:text-gray-400 focus:border-gray-400 dark:border-gray-700 dark:placeholder:text-gray-500 dark:focus:border-gray-500"
+ />
+ </div>
+ )}
+ {visible.map(({ machine, positions }) => (
+ <button
+ key={machine.id}
+ type="button"
+ onClick={() => {
+ setSelectedId(machine.id);
+ setPickerOpen(false);
+ }}
+ className="flex w-full min-w-0 items-center gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800"
+ >
+ <span
+ className={`min-w-0 flex-1 truncate ${positions.length > 0 ? "text-gray-400 dark:text-gray-500" : ""}`}
+ >
+ {positions.length === 0
+ ? machine.alias
+ : highlightSegments(machine.alias, positions).map((segment, i) => (
+ <span
+ key={i}
+ className={
+ segment.hit
+ ? "font-semibold text-gray-900 dark:text-white"
+ : undefined
+ }
+ >
+ {segment.text}
+ </span>
+ ))}
+ </span>
+ {/* Which hosts already carry this program — the version, not a bare
+ tick, because a stale one is the reason to reinstall. */}
+ {machine.installed !== null && (
+ <span className={`shrink-0 text-xs ${toneInk.success}`}>
+ {machine.installed.version}
+ </span>
+ )}
+ </button>
+ ))}
+ {visible.length === 0 && (
+ <p className="px-3.5 py-2 text-sm text-gray-400 dark:text-gray-500">
+ {S.machines.noMatch}
+ </p>
+ )}
+ {hiddenCount > 0 && (
+ <p className="px-3.5 pt-1 pb-1.5 text-xs text-gray-400 dark:text-gray-500">
+ {S.machines.more(hiddenCount)}
+ </p>
+ )}
+ </Dropdown>
+ <Button
+ variant="primary"
+ disabled={button.disabled}
+ onClick={() => void install()}
+ className="shrink-0"
+ >
+ {button.action === "installing"
+ ? S.machines.installing
+ : button.action === "reinstall"
+ ? S.machines.reinstall
+ : S.machines.install}
+ </Button>
+ </div>
+ )}
+
+ {selected?.installed != null && (
+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
+ {S.machines.installedAt(
+ selected.installed.version,
+ formatDateTime(selected.installed.at),
+ )}
+ </p>
+ )}
+
+ {/* What this server has already installed, standing on the page rather than
+ only inside the picker: it is the answer to "what did I do", which a panel
+ that has to be opened one row at a time cannot give. */}
+ {installed.length > 0 && (
+ <section className="mt-6">
+ <h2 className="text-sm font-semibold text-gray-500 dark:text-gray-400">
+ {S.machines.installedTitle(installed.length)}
+ </h2>
+ <div className="mt-2 divide-y divide-gray-200 overflow-hidden rounded-md border border-gray-200 dark:divide-gray-800 dark:border-gray-800">
+ {installed.map((machine) => (
+ <button
+ key={machine.id}
+ type="button"
+ onClick={() => setSelectedId(machine.id)}
+ aria-current={machine.id === selectedId ? "true" : undefined}
+ className={`flex w-full min-w-0 items-center gap-3 px-3 py-2.5 text-left transition-colors duration-150 ${
+ machine.id === selectedId
+ ? "bg-gray-100 dark:bg-gray-800"
+ : "bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800/70"
+ }`}
+ >
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">
+ <GlyphIcon d={NAV_ICONS.machines} size={ICON_SIZE.rowLead} />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">
+ {machine.alias}
+ </span>
+ <span className={`shrink-0 text-xs ${toneInk.success}`}>
+ {machine.installed!.version}
+ </span>
+ <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">
+ {formatDateTime(machine.installed!.at)}
+ </span>
+ </button>
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* The job, whichever machine it belongs to — named, so a selection change
+ while one runs never leaves an unattributed log on screen. */}
+ {job !== null && (
+ <section className="mt-5 overflow-hidden rounded-md border border-gray-200 dark:border-gray-800">
+ <div className="flex items-center gap-2 bg-gray-50 px-3 py-2 dark:bg-gray-900">
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{job.alias}</span>
+ {running ? (
+ <span className={`text-xs ${toneInk.busy}`}>{S.machines.installing}</span>
+ ) : (
+ verdictText !== null && (
+ <span className={`text-xs ${toneInk[verdictText.tone]}`}>
+ {verdictText.text}
+ </span>
+ )
+ )}
+ </div>
+ {job.log.length > 0 && (
+ <div className="border-t border-gray-100 px-3 py-2 dark:border-gray-800">
+ <p className="text-xs font-medium text-gray-500 dark:text-gray-400">
+ {S.machines.output}
+ </p>
+ <pre className="mt-1 max-h-64 overflow-auto font-mono text-xs break-words whitespace-pre-wrap text-gray-700 dark:text-gray-300">
+ {job.log.join("\n")}
+ </pre>
+ {verdict?.kind === "failed" && (
+ <pre
+ className={`mt-2 font-mono text-xs break-words whitespace-pre-wrap ${toneInk.danger}`}
+ >
+ {verdict.message}
+ </pre>
+ )}
+ </div>
+ )}
+ </section>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/machines/machines-view.ts b/packages/web/src/features/machines/machines-view.ts
new file mode 100644
index 00000000..9d72b55d
--- /dev/null
+++ b/packages/web/src/features/machines/machines-view.ts
@@ -0,0 +1,93 @@
+/**
+ * What the Machines page's install control offers, decided as data rather than in JSX.
+ *
+ * The server keeps ONE install job at a time, so the button is governed by two things that
+ * are not the same: which machine is SELECTED in the picker, and which machine the job (if
+ * any) belongs to. They come apart the moment someone picks a second host while the first
+ * is still installing — the button must refuse, but the running job's log still belongs on
+ * screen, under the alias it is actually installing to. That is why the job panel renders
+ * from `state.job` directly and only the button consults the selection.
+ *
+ * "Already installed" is a THIRD thing, and it comes from the machine's own persisted
+ * record rather than from the job: the job is one slot, so deriving it from there made an
+ * installed machine vanish as soon as anything else was installed or the server restarted.
+ */
+import type {
+ MachineInfo,
+ MachineInstallJob,
+ MachinesResponse,
+} from "@prismshadow/penguin-server/api";
+
+/** The finished job's verdict, in the shape the page renders. */
+export type MachineVerdict =
+ | { kind: "installed"; version: string | null }
+ | { kind: "already-installed"; version: string | null }
+ | { kind: "failed"; step: string; message: string };
+
+export interface InstallButtonState {
+ /** What the button offers: a fresh install, one already under way, or a repeat of a finished one. */
+ action: "install" | "installing" | "reinstall";
+ /**
+ * True when the button must not start anything: nothing is selected, a job is running
+ * anywhere (one at a time, server-side), this page's own POST is in flight, or this
+ * server has no image to send at all.
+ */
+ disabled: boolean;
+}
+
+/** The verdict of a job that has finished, or null while it is still running. */
+export function verdictOf(job: MachineInstallJob): MachineVerdict | null {
+ if (job.result === null) return null;
+ if (job.result.ok) return { kind: job.result.kind, version: job.result.version };
+ return { kind: "failed", step: job.result.step, message: job.result.message };
+}
+
+/**
+ * `starting` is true while a POST has not come back yet. It exists because the server has
+ * no job to report during that window, and a button that stays on "Install" through a click
+ * reads as a click that did nothing.
+ */
+export function installButtonState(
+ selected: MachineInfo | null,
+ state: MachinesResponse,
+ starting: boolean,
+): InstallButtonState {
+ const job = state.job;
+ const runningSomewhere = job?.running === true;
+ const selectedIsRunning = runningSomewhere && job.machineId === selected?.id;
+ return {
+ action:
+ selectedIsRunning || starting
+ ? "installing"
+ : selected?.installed != null
+ ? "reinstall"
+ : "install",
+ disabled: selected === null || runningSomewhere || starting || state.imageVersion === null,
+ };
+}
+
+/**
+ * The machines this server has installed on, most recently installed first — the standing
+ * answer to "what did I already do", which the picker can only give one row at a time and
+ * only while it is open.
+ *
+ * Newest first because the list is read to check recent work, not to look a host up: the
+ * picker's search is what finds a specific alias. Ties (two installs in the same
+ * millisecond, which the tests do produce) keep the config's order rather than swapping
+ * around, so the list is stable between polls.
+ *
+ * Records whose host is no longer declared in the ssh config never reach here: the server
+ * builds the list from the config, so a renamed or deleted Host drops out of the page while
+ * its record sits harmlessly in the file. There is nothing useful to offer for a host this
+ * server can no longer resolve, let alone install to.
+ */
+export function installedMachines(state: MachinesResponse): MachineInfo[] {
+ return state.machines
+ .map((machine, index) => ({ machine, index }))
+ .filter((entry) => entry.machine.installed != null)
+ .sort((a, b) => {
+ const at = b.machine.installed!.at.localeCompare(a.machine.installed!.at);
+ return at !== 0 ? at : a.index - b.index;
+ })
+ .map((entry) => entry.machine);
+}
diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.ts
index 56db876c..b7f28d3e 100644
--- a/packages/web/src/lib/nav-group-collapse.ts
+++ b/packages/web/src/lib/nav-group-collapse.ts
@@ -17,12 +17,34 @@
* Page entries of the collapsible nav group, in rendered order. Each key names its
* route (`/<key>`), its S.nav label, and its NAV_ICONS glyph — the sidebar derives
* its nav rows from this manifest, so the covered range is pinned here (and in the
- * unit tests) rather than duplicated. Traces is deliberately absent: reading a Trace
- * happens in the chat toolbar's panel switcher, which is the only place it happens.
+ * unit tests) rather than duplicated. Some entries are admin-only (see below), so the
+ * sidebar renders navKeysFor(user.isAdmin), not the raw manifest. Traces is deliberately
+ * absent: reading a Trace happens in the chat toolbar's panel switcher, which is the only
+ * place it happens.
*/
-export const NAV_GROUP_KEYS = ["agents", "skills", "models", "usage", "benchmark"] as const;
+export const NAV_GROUP_KEYS = [
+ "agents",
+ "skills",
+ "models",
+ "machines",
+ "usage",
+ "benchmark",
+] as const;
export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];
+/**
+ * Entries the server refuses to a non-admin, so the sidebar does not offer them. Machines
+ * installs software on another machine over ssh with the SERVER account's keys, which
+ * `/api/machines` gates on `isAdmin` — a row that always answers 403 is worse than no row.
+ * On a personal or desktop server the only account IS the admin, so nothing is hidden there.
+ */
+const ADMIN_ONLY_NAV_KEYS: ReadonlySet<NavGroupKey> = new Set<NavGroupKey>(["machines"]);
+
+/** The manifest as this user sees it. */
+export function navKeysFor(isAdmin: boolean): readonly NavGroupKey[] {
+ return isAdmin ? NAV_GROUP_KEYS : NAV_GROUP_KEYS.filter((key) => !ADMIN_ONLY_NAV_KEYS.has(key));
+}
+
/**
* Page entries that are visible and reachable: collapsing hides the whole group (the
* chevron-button toggle and the pinned "New chat" block above are outside it and stay).
@@ -30,8 +52,8 @@ export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];
* height tween — but at zero height, faded out, and inert: exactly this empty set of
* reachable entries.
*/
-export function visibleNavKeys(collapsed: boolean): readonly NavGroupKey[] {
- return collapsed ? [] : NAV_GROUP_KEYS;
+export function visibleNavKeys(collapsed: boolean, isAdmin = true): readonly NavGroupKey[] {
+ return collapsed ? [] : navKeysFor(isAdmin);
}
/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 40e19be7..64dffccd 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -16,6 +16,7 @@ export const en: Strings = {
agents: "Agents",
skills: "Skills",
models: "Models",
+ machines: "Machines",
usage: "Cost Center",
traces: "Trajectories",
benchmark: "Evaluation Center",
@@ -29,6 +30,38 @@ export const en: Strings = {
unpinGroup: "Unpin group",
},
+ /** Machines page: the server's own ssh hosts, and installing this build on one. */
+ machines: {
+ pageTitle: "Machines",
+ pageDesc:
+ "The hosts declared in this server's own ~/.ssh/config. Pick one to install this build of PenguinHarness on it: the machine is probed, a matching Node runtime rides along only if it needs one, and the image is copied over and installed there. The config is read, never written, and the install uses the server account's own ssh keys.",
+ /** Version line under the title; `version` is what would be pushed. */
+ imageVersion: (version: string) => `Installs version ${version}`,
+ noImage:
+ "This server has no install image to push. A packaged or tarball install carries one; a source checkout gets one from its first hot push.",
+ empty: "No hosts in ~/.ssh/config.",
+ /** The picker: an ssh config can declare hundreds of hosts, so the panel is a fuzzy search over aliases. */
+ pick: "Choose a machine\u2026",
+ search: "Search hosts\u2026",
+ noMatch: "No host matches that.",
+ /** How many matches the visible rows leave out — a silent truncation would read as "not in my config". */
+ more: (count: number) => `${count} more \u2014 keep typing to narrow it down.`,
+ /** Heading of the standing list of machines this server has installed on. */
+ installedTitle: (count: number) => `Installed machines (${count})`,
+ /** What the selected machine already carries, remembered on the server across restarts. */
+ installedAt: (version: string, when: string) => `${version} installed here on ${when}.`,
+ install: "Install",
+ installing: "Installing\u2026",
+ reinstall: "Reinstall",
+ /** Terminal states of a finished job. */
+ installed: (version: string) => `Installed ${version}.`,
+ alreadyInstalled: (version: string) => `Already on ${version} \u2014 nothing to install.`,
+ failedAt: (step: string) => `The install failed while trying to ${step}.`,
+ /** The progress log's own heading, so the block is not an unlabelled wall of text. */
+ output: "Install output",
+ adminOnly: "Only an admin can install on a machine.",
+ },
+
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
terminal: {
title: "Terminal",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 932f15d3..0a7a0612 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -18,6 +18,7 @@ export const zh = {
agents: "智能体",
skills: "技能库",
models: "模型库",
+ machines: "机器",
usage: "成本中心",
traces: "轨迹观测",
benchmark: "评估中心",
@@ -31,6 +32,38 @@ export const zh = {
unpinGroup: "取消置顶",
},
+ /** Machines page: the server's own ssh hosts, and installing this build on one. */
+ machines: {
+ pageTitle: "机器",
+ pageDesc:
+ "本服务端 ~/.ssh/config 里声明的主机。选一台即可把当前这套 PenguinHarness 装上去:探测对端、按需带上匹配的 Node 运行时、复制镜像并在对端完成安装。配置文件只读不写,安装使用服务端账户自己的 ssh 密钥。",
+ /** Version line under the title; `version` is what would be pushed. */
+ imageVersion: (version: string) => `将安装的版本:${version}`,
+ noImage:
+ "本服务端没有可推送的安装镜像。打包安装或 tarball 安装自带镜像;源码检出则在第一次热推后获得。",
+ empty: "~/.ssh/config 中没有可用的主机。",
+ /** The picker: an ssh config can declare hundreds of hosts, so the panel is a fuzzy search over aliases. */
+ pick: "选择机器…",
+ search: "搜索主机…",
+ noMatch: "没有匹配的主机。",
+ /** How many matches the visible rows leave out — a silent truncation would read as "not in my config". */
+ more: (count: number) => `另有 ${count} 台未显示——继续输入以缩小范围。`,
+ /** Heading of the standing list of machines this server has installed on. */
+ installedTitle: (count: number) => `已安装的机器(${count})`,
+ /** What the selected machine already carries, remembered on the server across restarts. */
+ installedAt: (version: string, when: string) => `已安装 ${version}(${when})。`,
+ install: "安装",
+ installing: "安装中…",
+ reinstall: "重新安装",
+ /** Terminal states of a finished job. */
+ installed: (version: string) => `已安装 ${version}。`,
+ alreadyInstalled: (version: string) => `已经是 ${version},无需安装。`,
+ failedAt: (step: string) => `安装失败(${step})。`,
+ /** The progress log's own heading, so the block is not an unlabelled wall of text. */
+ output: "安装输出",
+ adminOnly: "只有管理员可以安装到机器上。",
+ },
+
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
terminal: {
title: "终端",
diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx
index 25bce148..695fd509 100644
--- a/packages/web/src/router.tsx
+++ b/packages/web/src/router.tsx
@@ -14,6 +14,7 @@ import { AgentsPage } from "./features/agents/agents-page";
import { AgentSettingsPage } from "./features/agents/agent-settings-page";
import { SkillsPage } from "./features/skills/skills-page";
import { ModelsPage } from "./features/models/models-page";
+import { MachinesPage } from "./features/machines/machines-page";
import { UsagePage } from "./features/usage/usage-page";
import { BenchmarkPage } from "./features/benchmark/benchmark-page";
import { TerminalPage } from "./features/terminal/terminal-page";
@@ -71,6 +72,9 @@ export function AppRouter() {
<Route path="/agents/:agentId" element={<AgentSettingsPage />} />
<Route path="/skills" element={<SkillsPage />} />
<Route path="/models" element={<ModelsPage />} />
+ {/* Admin-only server-side (403 otherwise); the sidebar hides the row for
+ everyone else, so a member only ever reaches this by typing the URL. */}
+ <Route path="/machines" element={<MachinesPage />} />
<Route path="/usage" element={<UsagePage />} />
<Route path="/benchmark" element={<BenchmarkPage />} />
{/* System settings and user management live in the settings dialog now (see
diff --git a/packages/web/test/machines-match.test.ts b/packages/web/test/machines-match.test.ts
new file mode 100644
index 00000000..cdcb5af2
--- /dev/null
+++ b/packages/web/test/machines-match.test.ts
@@ -0,0 +1,87 @@
+/**
+ * The machine picker's fuzzy search: subsequence matching (a query does not have to be a
+ * substring to hit), scoring that ranks contiguous and word-start hits above scattered
+ * ones, and the highlight segmentation the rows render from. An ssh config with hundreds
+ * of hosts is the case this exists for, so the cap and the "N more" arithmetic are pinned
+ * here too.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ MAX_VISIBLE_MACHINES,
+ fuzzyMatch,
+ highlightSegments,
+ matchMachines,
+} from "../src/features/machines/machines-match";
+import type { MachineLike } from "../src/features/machines/machines-match";
+
+const machine = (alias: string): MachineLike => ({ id: `ssh:${alias}`, alias });
+
+describe("fuzzyMatch", () => {
+ it("hits subsequences, not just substrings, case-insensitively", () => {
+ expect(fuzzyMatch("gpu-01", "gpu1")?.positions).toEqual([0, 1, 2, 5]);
+ expect(fuzzyMatch("Build-Box", "bb")?.positions).toEqual([0, 6]);
+ expect(fuzzyMatch("gpu-01", "gx")).toBeNull();
+ });
+
+ it("scores contiguous runs and word starts above scattered hits", () => {
+ const contiguous = fuzzyMatch("build-box", "build")!;
+ const scattered = fuzzyMatch("b-u-i-l-d", "build")!;
+ expect(contiguous.score).toBeGreaterThan(scattered.score);
+ });
+
+ it("an empty query fits everything, hitting nothing", () => {
+ expect(fuzzyMatch("gpu-01", "")).toEqual({ positions: [], score: 0 });
+ });
+});
+
+describe("matchMachines", () => {
+ const machines = ["staging", "gpu-01", "gpu-02", "big-gpu"].map(machine);
+
+ it("an empty query keeps every machine in the config's order", () => {
+ expect(matchMachines(machines, " ").map((m) => m.machine.alias)).toEqual([
+ "staging",
+ "gpu-01",
+ "gpu-02",
+ "big-gpu",
+ ]);
+ });
+
+ it("filters, ranks best-first, and keeps the config's order among ties", () => {
+ const hits = matchMachines(machines, "gpu").map((m) => m.machine.alias);
+ // The two word-start contiguous hits outrank big-gpu's later hit; between the equal
+ // gpu-01/gpu-02 the config's own order stands.
+ expect(hits).toEqual(["gpu-01", "gpu-02", "big-gpu"]);
+ expect(matchMachines(machines, "zzz")).toEqual([]);
+ });
+
+ it("carries the hit positions so the row can show why it matched", () => {
+ const [hit] = matchMachines([machine("gpu-01")], "gpu1");
+ expect(hit?.positions).toEqual([0, 1, 2, 5]);
+ });
+});
+
+describe("highlightSegments", () => {
+ it("splits into contiguous hit/miss runs covering the whole alias", () => {
+ expect(highlightSegments("gpu-01", [0, 1, 2, 5])).toEqual([
+ { text: "gpu", hit: true },
+ { text: "-0", hit: false },
+ { text: "1", hit: true },
+ ]);
+ expect(highlightSegments("abc", [])).toEqual([{ text: "abc", hit: false }]);
+ });
+});
+
+describe("a config with hundreds of hosts", () => {
+ const many = Array.from({ length: 300 }, (_, i) => machine(`node-${String(i).padStart(3, "0")}`));
+
+ it("narrows to the visible few, and the counter names the rest honestly", () => {
+ const all = matchMachines(many, "");
+ expect(all).toHaveLength(300);
+ expect(all.length - all.slice(0, MAX_VISIBLE_MACHINES).length).toBe(300 - MAX_VISIBLE_MACHINES);
+
+ // A query specific enough to fit on screen leaves nothing hidden.
+ const narrowed = matchMachines(many, "node287");
+ expect(narrowed.map((m) => m.machine.alias)).toEqual(["node-287"]);
+ expect(narrowed.length - narrowed.slice(0, MAX_VISIBLE_MACHINES).length).toBe(0);
+ });
+});
diff --git a/packages/web/test/machines-view.test.ts b/packages/web/test/machines-view.test.ts
new file mode 100644
index 00000000..3f1d24a0
--- /dev/null
+++ b/packages/web/test/machines-view.test.ts
@@ -0,0 +1,209 @@
+/**
+ * machines-view unit tests: what the Machines page's install control offers, given the
+ * server's single install job and whatever is selected in the picker.
+ *
+ * Two cases worth pinning. The server runs one job at a time, so selecting a second host
+ * while the first installs must refuse — without pretending the selection is the thing
+ * installing. And "already installed" comes from the machine's own persisted record, never
+ * from the job: reading it off the one job slot is what used to make an installed machine
+ * stop looking installed as soon as anything else was installed.
+ */
+import { describe, expect, it } from "vitest";
+import type {
+ MachineInfo,
+ MachineInstallJob,
+ MachinesResponse,
+} from "@prismshadow/penguin-server/api";
+import {
+ installButtonState,
+ installedMachines,
+ verdictOf,
+} from "../src/features/machines/machines-view";
+
+const INSTALLED = { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" };
+
+const fresh = (alias: string): MachineInfo => ({ id: `ssh:${alias}`, alias, installed: null });
+const carrying = (alias: string): MachineInfo => ({
+ id: `ssh:${alias}`,
+ alias,
+ installed: INSTALLED,
+});
+
+function response(
+ job: MachineInstallJob | null,
+ opts: { imageVersion?: string | null; machines?: MachineInfo[] } = {},
+): MachinesResponse {
+ return {
+ machines: opts.machines ?? [fresh("build-box"), fresh("nas")],
+ imageVersion: opts.imageVersion === undefined ? "9.9.9" : opts.imageVersion,
+ job,
+ };
+}
+
+function job(over: Partial<MachineInstallJob> = {}): MachineInstallJob {
+ return {
+ machineId: "ssh:nas",
+ alias: "nas",
+ running: true,
+ log: ["Installing 9.9.9 on deploy@nas…"],
+ result: null,
+ ...over,
+ };
+}
+
+const done = job({ running: false, result: { ok: true, kind: "installed", version: "9.9.9" } });
+
+describe("verdictOf", () => {
+ it("is null while the job runs", () => {
+ expect(verdictOf(job())).toBeNull();
+ });
+
+ it("carries the version on both kinds of success", () => {
+ expect(verdictOf(done)).toEqual({ kind: "installed", version: "9.9.9" });
+ expect(
+ verdictOf(
+ job({ running: false, result: { ok: true, kind: "already-installed", version: "9.9.9" } }),
+ ),
+ ).toEqual({ kind: "already-installed", version: "9.9.9" });
+ });
+
+ it("keeps the failing step and the far side's own message", () => {
+ expect(
+ verdictOf(
+ job({
+ running: false,
+ result: { ok: false, step: "connect", message: "Permission denied (publickey)." },
+ }),
+ ),
+ ).toEqual({ kind: "failed", step: "connect", message: "Permission denied (publickey)." });
+ });
+});
+
+describe("installButtonState", () => {
+ it("nothing selected: the button offers an install it cannot start", () => {
+ expect(installButtonState(null, response(null), false)).toEqual({
+ action: "install",
+ disabled: true,
+ });
+ });
+
+ it("a never-installed selection with no job running is ready to go", () => {
+ expect(installButtonState(fresh("nas"), response(null), false)).toEqual({
+ action: "install",
+ disabled: false,
+ });
+ });
+
+ it("the selected machine's own running job reads as installing", () => {
+ expect(installButtonState(fresh("nas"), response(job()), false)).toEqual({
+ action: "installing",
+ disabled: true,
+ });
+ });
+
+ it("picking ANOTHER host mid-install refuses without claiming that host is installing", () => {
+ // The job belongs to ssh:nas; the picker moved to ssh:build-box. One job at a time, so
+ // the button is disabled — but it must not say "installing" about a host that is not.
+ expect(installButtonState(fresh("build-box"), response(job()), false)).toEqual({
+ action: "install",
+ disabled: true,
+ });
+ });
+
+ it("a POST still in flight reads as installing before the server reports a job", () => {
+ expect(installButtonState(fresh("nas"), response(null), true)).toEqual({
+ action: "installing",
+ disabled: true,
+ });
+ });
+
+ it("a machine carrying the program offers a reinstall — from its record, not the job", () => {
+ // No job at all: this is the page after a restart, which is exactly the case that used
+ // to read as "never installed".
+ expect(installButtonState(carrying("nas"), response(null), false)).toEqual({
+ action: "reinstall",
+ disabled: false,
+ });
+ });
+
+ it("installing elsewhere leaves an installed machine still reading as installed", () => {
+ const elsewhere = job({
+ machineId: "ssh:build-box",
+ alias: "build-box",
+ running: false,
+ result: { ok: true, kind: "installed", version: "9.9.9" },
+ });
+ expect(installButtonState(carrying("nas"), response(elsewhere), false)).toEqual({
+ action: "reinstall",
+ disabled: false,
+ });
+ // ...and the machine that job belongs to reads as installed off its own record too.
+ expect(installButtonState(carrying("build-box"), response(elsewhere), false).action).toBe(
+ "reinstall",
+ );
+ });
+
+ it("a failed install leaves the selection on plain install: nothing was recorded", () => {
+ const failed = job({
+ running: false,
+ result: { ok: false, step: "connect", message: "Permission denied (publickey)." },
+ });
+ expect(installButtonState(fresh("nas"), response(failed), false)).toEqual({
+ action: "install",
+ disabled: false,
+ });
+ });
+
+ it("no install image disables the button whatever is selected", () => {
+ expect(
+ installButtonState(fresh("nas"), response(null, { imageVersion: null }), false).disabled,
+ ).toBe(true);
+ expect(
+ installButtonState(carrying("nas"), response(null, { imageVersion: null }), false).disabled,
+ ).toBe(true);
+ });
+});
+
+describe("installedMachines", () => {
+ const at = (iso: string) => ({ version: "9.9.9", at: iso });
+
+ it("is empty when nothing has been installed", () => {
+ expect(installedMachines(response(null))).toEqual([]);
+ });
+
+ it("keeps only the installed ones, most recent first", () => {
+ const machines: MachineInfo[] = [
+ { id: "ssh:a", alias: "a", installed: at("2026-08-20T00:00:00.000Z") },
+ { id: "ssh:b", alias: "b", installed: null },
+ { id: "ssh:c", alias: "c", installed: at("2026-08-24T00:00:00.000Z") },
+ { id: "ssh:d", alias: "d", installed: at("2026-08-22T00:00:00.000Z") },
+ ];
+ expect(installedMachines(response(null, { machines })).map((m) => m.alias)).toEqual([
+ "c",
+ "d",
+ "a",
+ ]);
+ });
+
+ it("keeps the config's order among installs sharing a timestamp, so the list does not shuffle between polls", () => {
+ const same = at("2026-08-24T00:00:00.000Z");
+ const machines: MachineInfo[] = [
+ { id: "ssh:x", alias: "x", installed: same },
+ { id: "ssh:y", alias: "y", installed: same },
+ { id: "ssh:z", alias: "z", installed: same },
+ ];
+ const order = () => installedMachines(response(null, { machines })).map((m) => m.alias);
+ expect(order()).toEqual(["x", "y", "z"]);
+ expect(order()).toEqual(order());
+ });
+
+ it("does not mutate the response's own machine order (the picker reads it too)", () => {
+ const machines: MachineInfo[] = [
+ { id: "ssh:a", alias: "a", installed: at("2026-08-20T00:00:00.000Z") },
+ { id: "ssh:c", alias: "c", installed: at("2026-08-24T00:00:00.000Z") },
+ ];
+ const state = response(null, { machines });
+ installedMachines(state);
+ expect(state.machines.map((m) => m.alias)).toEqual(["a", "c"]);
+ });
+});
diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.ts
index deceda63..d38c70d8 100644
--- a/packages/web/test/nav-group-collapse.test.ts
+++ b/packages/web/test/nav-group-collapse.test.ts
@@ -15,6 +15,7 @@ import {
NAV_GROUP_COLLAPSED_KEY,
NAV_GROUP_KEYS,
initialNavGroupCollapsed,
+ navKeysFor,
storeNavGroupCollapsed,
visibleNavKeys,
} from "../src/lib/nav-group-collapse";
@@ -37,7 +38,14 @@ describe("NAV_GROUP_KEYS", () => {
it("covers exactly the 智能体 → 评估中心 range, in rendered order", () => {
// Traces is deliberately absent: the Trace panel moved into the chat toolbar's panel
// switcher (features/dock), and /traces stays reachable through its deep links only.
- expect([...NAV_GROUP_KEYS]).toEqual(["agents", "skills", "models", "usage", "benchmark"]);
+ expect([...NAV_GROUP_KEYS]).toEqual([
+ "agents",
+ "skills",
+ "models",
+ "machines",
+ "usage",
+ "benchmark",
+ ]);
// Pin the endpoints by label: a manifest edit that shifts the range shows up here.
expect(zh.nav[NAV_GROUP_KEYS[0]]).toBe("智能体");
expect(zh.nav[NAV_GROUP_KEYS[NAV_GROUP_KEYS.length - 1]!]).toBe("评估中心");
@@ -60,12 +68,26 @@ describe("NAV_GROUP_KEYS", () => {
});
});
+describe("navKeysFor", () => {
+ it("hides the admin-only entries from a member, and nothing else", () => {
+ // /api/machines is admin-gated server-side (it spawns ssh with the server account's
+ // keys), so offering a member the row would only ever produce a 403.
+ expect([...navKeysFor(false)]).toEqual(["agents", "skills", "models", "usage", "benchmark"]);
+ expect(navKeysFor(true)).toEqual(NAV_GROUP_KEYS);
+ });
+});
+
describe("visibleNavKeys", () => {
it("expanded shows the whole group; collapsed leaves no entry visible or reachable (the sidebar renders the mounted rows inert at zero height)", () => {
expect(visibleNavKeys(false)).toEqual(NAV_GROUP_KEYS);
expect(visibleNavKeys(true)).toEqual([]);
});
+ it("a member's expanded group is their own manifest, not the admin's", () => {
+ expect(visibleNavKeys(false, false)).toEqual(navKeysFor(false));
+ expect(visibleNavKeys(true, false)).toEqual([]);
+ });
+
it("the chevron-button toggle's accessible names exist in both languages (icon-only button: aria + tooltip carry them)", () => {
for (const [locale, dict] of [
["zh", zh],
diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs
index 69b9d4e3..37e426ac 100644
--- a/scripts/deploy.mjs
+++ b/scripts/deploy.mjs
@@ -178,7 +178,7 @@ async function readWebManifest() {
}
/**
- * Native modules the pushed platform needs as real files. A bundle cannot carry one: it is
+ * Files the pushed platform needs as real files rather than bundled code. A bundle cannot carry one: it is
* imported from the runtime's data root, where node-pty's own relative `build/Release/
* pty.node` does not resolve. So the package ships whole — its JS, its prebuilds and its
* darwin `spawn-helper` — and the runtime unpacks it next to the bundle (hmr/host.ts's
@@ -219,6 +219,11 @@ async function readNativeAssets() {
exec.push(target);
}
}
+ // The ordinary installers: the machines push scp's one to the far side and runs it there
+ // against the payload, so they have to exist as files on the pushing side too.
+ for (const name of ["install.sh", "install.ps1"]) {
+ files[name] = (await fsp.readFile(path.join(ROOT, name))).toString("base64");
+ }
return { files, exec };
}
diff --git a/scripts/launchers/penguin b/scripts/launchers/penguin
new file mode 100755
index 00000000..aedb12db
--- /dev/null
+++ b/scripts/launchers/penguin
@@ -0,0 +1,23 @@
+#!/bin/sh
+# penguin CLI launcher, installed as bin/penguin inside the program directory.
+#
+# Runs the CLI on the Node runtime bundled at node/ when this package carries one,
+# otherwise on system Node (>= 24). The web assets sit beside it at web/.
+
+# This script's real location; readlink -f is not portable to macOS, hence the loop.
+SOURCE=$0
+while [ -h "$SOURCE" ]; do
+ DIR=$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)
+ SOURCE=$(readlink "$SOURCE")
+ case $SOURCE in
+ /*) ;;
+ *) SOURCE="$DIR/$SOURCE" ;;
+ esac
+done
+DIR=$(dirname "$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)")
+
+export PENGUIN_WEB_DIST="${PENGUIN_WEB_DIST:-$DIR/web}"
+if [ -x "$DIR/node/bin/node" ]; then
+ exec "$DIR/node/bin/node" "$DIR/lib/dist/penguin.js" "$@"
+fi
+exec node "$DIR/lib/dist/penguin.js" "$@"
diff --git a/scripts/launchers/penguin.cmd b/scripts/launchers/penguin.cmd
new file mode 100644
index 00000000..3318ee13
--- /dev/null
+++ b/scripts/launchers/penguin.cmd
@@ -0,0 +1,18 @@
+@echo off
+rem penguin CLI launcher, installed as bin\penguin.cmd inside the program directory.
+rem Runs the CLI on the Node runtime bundled at node\ when this package carries one,
+rem otherwise on system Node (>= 24). The web assets sit beside it at web\.
+rem
+rem There is deliberately no penguin.ps1 sibling: PowerShell prefers .ps1 over .cmd on
+rem PATH, and client Windows defaults to the Restricted execution policy, which would
+rem then break the plain `penguin` command. Batch files are exempt from that policy.
+setlocal
+set "DIR=%~dp0.."
+if not defined PENGUIN_WEB_DIST set "PENGUIN_WEB_DIST=%DIR%\web"
+if exist "%DIR%\git\usr\bin\sh.exe" set "PENGUIN_BUNDLED_SHELL=%DIR%\git\usr\bin\sh.exe"
+if exist "%DIR%\node\node.exe" (
+ "%DIR%\node\node.exe" "%DIR%\lib\dist\penguin.js" %*
+) else (
+ node "%DIR%\lib\dist\penguin.js" %*
+)
+exit /b %ERRORLEVEL%
diff --git a/scripts/test-installer.sh b/scripts/test-installer.sh
index 825976c0..a4af6dda 100755
--- a/scripts/test-installer.sh
+++ b/scripts/test-installer.sh
@@ -37,6 +37,26 @@ check_shared_constant "the OSS switch ratio" "SPEED_PROBE_OSS_SWITCH_RATIO_PERCE
check_shared_constant "the OSS switch ratio" '$SpeedProbeOssSwitchRatio = 1.5' install.ps1
check_shared_constant "the OSS switch ratio" "SPEED_PROBE_OSS_SWITCH_RATIO = 1.5;" "$LANDING_RULE"
+# --- The launchers the release packages ship verbatim (scripts/launchers/). They are the only
+# spelling of the payload layout, so moving where web/ or node/ sits fails here rather than
+# shipping a package whose `penguin` cannot find its own web assets. ---
+LAUNCHER_SH="$ROOT_DIR/scripts/launchers/penguin"
+LAUNCHER_CMD="$ROOT_DIR/scripts/launchers/penguin.cmd"
+[ -x "$LAUNCHER_SH" ] || fail_test "scripts/launchers/penguin is missing or not executable"
+for marker in 'PENGUIN_WEB_DIST:-$DIR/web' '$DIR/node/bin/node' '$DIR/lib/dist/penguin.js'; do
+ grep -qF "$marker" "$LAUNCHER_SH" || fail_test "the POSIX launcher does not carry $marker"
+done
+sh -n "$LAUNCHER_SH" || fail_test "the POSIX launcher is not valid sh"
+for marker in '%DIR%\web' '%DIR%\node\node.exe' '%DIR%\lib\dist\penguin.js'; do
+ grep -qF "$marker" "$LAUNCHER_CMD" || fail_test "the Windows launcher does not carry $marker"
+done
+# .gitattributes keeps this one CRLF, the only form cmd.exe is fully reliable with.
+grep -q "$(printf '\r')" "$LAUNCHER_CMD" || fail_test "the Windows launcher is not CRLF"
+# No penguin.ps1: PowerShell would prefer it on PATH, and Restricted policy would then break
+# the plain `penguin` command.
+[ ! -e "$ROOT_DIR/scripts/launchers/penguin.ps1" ] \
+ || fail_test "a penguin.ps1 launcher must not be shipped"
+
write_sha256() {
file="$1"
(cd "$(dirname "$file")" && sha256sum "$(basename "$file")" > "$(basename "$file").sha256")