Skip to content

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

feat(machines,cli): a machine has an id of its own, and a status you can ask for (#568)

Myriad-Dreaminc26edfa2c200
diff --git a/changelog/unreleased/2026-09-01-machines-identity.md b/changelog/unreleased/2026-09-01-machines-identity.md
new file mode 100644
index 00000000..b4892c38
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-machines-identity.md
@@ -0,0 +1,41 @@
+# Every machine has an id of its own, and a status you can ask for
+
+- **Date:** 2026-09-01
+- **Type:** feature
+- **Scope:** `server`, `cli`, `docs`
+- **PR:** [#568](https://github.com/Prism-Shadow/penguin-harness/pull/568)
+
+[中文版](2026-09-01-machines-identity.zh.md)
+
+A machine now says who it is and whether its server is up. The list opens with **this machine**, every installed one carries the last status probed for it, and `penguin server status` is the one command a controller runs over ssh to ask.
+
+## Which machine is which
+
+Every machine mints an id of its own — 16 base64url characters, by the server that runs there, this one included — and keeps it ever after. base64url because the id lands in paths, query strings and file names, where `+` and `/` do not survive; 96 bits because ids are minted on machines that never coordinate, so the bar is the birthday bound.
+
+An ssh alias cannot do that job: an alias is a line in one machine's config file, so the same host is `build-box` here and `bb` there, and two aliases for one host are two names for one machine. Aliases stay what you READ; the id is the identity behind them, and it is what anything stored points at.
+
+It rides the status probe's own round trip, so learning it costs nothing extra, and it is remembered beside the install record. A machine whose server has never started has no id yet — nothing has minted one — and says so rather than being given a made-up one. An alias repointed at a different host answers a different id, and the newer answer wins: an id never changes for a machine, so a change of id is a change of machine.
+
+## This machine, and whether the others are up
+
+The list opens with **this machine** — the host the server runs on, named by its hostname, with the version it runs and the port it serves on. It is read directly rather than probed (both facts are right here), it is always present, and it is never an install target: a server does not push this build over its own program directory while running from it, so `POST …/install` on it answers `409 self_install`.
+
+Every installed machine then carries its server's state: running with the port, stopped, or unreachable with OpenSSH's own diagnostic behind it. There is deliberately no separate "ssh" status — ssh is the transport, so a machine it cannot reach reads as one thing rather than two a reader has to combine.
+
+Status costs an ssh round trip per machine, so it is **never taken at list time** and never for the whole ssh config — only for the machines this Project actually installed on, five at a time, and only when `POST …/machines/probe` asks. A machine is asked one thing at a time: however many askers, the second waits for the first, so no number of tabs opens a second connection to it. Concurrent probe requests for a Project share one round rather than each starting their own.
+
+## `penguin server status`
+
+```bash
+penguin server status
+# {"running":true,"port":7364,"pid":41233,"machineId":"LNrJdHAZJ91G58i0"}
+```
+
+Machine-facing on purpose. The question used to be asked in shell — `cat` the lock, `sed` the pid out, `kill -0`, `cat` a second file for the id — which meant a parser on this side for a format nobody defined, and no answer at all from a Windows remote, `kill -0` having no cmd.exe equivalent. Asking the machine's own CLI moves both problems to the side that has Node. The invocation is shaped for the platform the install found — `$HOME/.penguin/node/bin/node` on POSIX, `%USERPROFILE%\.penguin\node\node.exe` under cmd.exe — and a machine whose platform is not on record is asked both ways.
+
+`running` requires the recorded pid to be alive **and** its port to accept, which the shell version could not do: it only had `kill -0`, and a recycled pid reads as a live server.
+
+Reading the id never mints one, and a status probe opens the database read-only — a controller asking a machine what it is must not reshape that machine's schema under the server running there, nor leave a data root behind on a machine that never had one.
+
+Output that holds no answer at all is reported as **unreachable**, not as stopped: a build too old for the subcommand prints an error, and reading that as a well-formed "no" would turn every such machine into a silently wrong one.
diff --git a/changelog/unreleased/2026-09-01-machines-identity.zh.md b/changelog/unreleased/2026-09-01-machines-identity.zh.md
new file mode 100644
index 00000000..4e008c64
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-machines-identity.zh.md
@@ -0,0 +1,41 @@
+# 每台机器都有自己的 id,也能被问出状态
+
+- **Date:** 2026-09-01
+- **Type:** feature
+- **Scope:** `server`, `cli`, `docs`
+- **PR:** [#568](https://github.com/Prism-Shadow/penguin-harness/pull/568)
+
+[English](2026-09-01-machines-identity.md)
+
+机器现在会说明自己是谁、服务是否在跑。列表以**本机**开头,每台已安装的机器带着最近一次探测到的状态,而 `penguin server status` 就是控制端通过 ssh 去问的那一条命令。
+
+## 哪台机器是哪台
+
+每台机器都由运行在其上的服务铸出自己的 id——16 个 base64url 字符,本机也不例外——此后一直保持不变。用 base64url 是因为这个 id 会出现在路径、查询串和文件名里,而 `+` 与 `/` 在那些地方活不下来;取 96 位是因为这些 id 由互不协调的机器各自铸出,标准应当是生日界。
+
+ssh 别名担不起这个职责:别名只是某一台机器配置文件里的一行,所以同一台主机在这边叫 `build-box`、在那边叫 `bb`,而同一台主机的两个别名就是一台机器的两个名字。别名仍然是给人**读**的;id 才是它们背后的身份,也是一切存储下来的引用所指向的东西。
+
+它搭乘状态探测本来就要走的那一趟往返,因此获知它不额外花钱,并且与安装记录一起被记住。服务从未启动过的机器还没有 id——没有任何东西铸出过它——于是它如实说没有,而不是被塞一个编造的。别名被改指到另一台主机后会答出不同的 id,且以新答案为准:id 对一台机器永不改变,所以 id 变了就意味着机器换了。
+
+## 本机,以及其他机器是否在跑
+
+列表以**本机**开头——服务所在的主机,用它的 hostname 命名,带着它运行的版本与正在服务的端口。它是直接读出来的而非探测得来(两个事实都在本地),它始终存在,且永远不是安装目标:服务不会在自己正运行的程序目录上覆盖推送本次构建,因此对它 `POST …/install` 会得到 `409 self_install`。
+
+随后每台已安装的机器带着它服务的状态:running 并附端口、stopped,或 unreachable 并附上 OpenSSH 自己的诊断。这里刻意没有单独的「ssh」状态——ssh 是传输方式,因此 ssh 到不了的机器读作一件事,而不是要读者自行合并的两件。
+
+状态每台要花一次 ssh 往返,因此**绝不在列表时获取**,也绝不对整个 ssh config 获取——只针对本 Project 确实安装过的机器,并发 5,且仅当 `POST …/machines/probe` 来问时。一台机器同一时刻只被问一件事:不管有多少人在问,第二个等第一个,所以再多标签页也不会对它多开一条连接。同一 Project 的并发探测请求共用一轮,而不是各起各的。
+
+## `penguin server status`
+
+```bash
+penguin server status
+# {"running":true,"port":7364,"pid":41233,"machineId":"LNrJdHAZJ91G58i0"}
+```
+
+它刻意是面向机器的。这个问题过去是用 shell 问的——`cat` 锁文件、`sed` 出 pid、`kill -0`、再 `cat` 第二个文件取 id——这意味着本侧要为一个无人定义的格式写解析器,而且 Windows 远端根本给不出答案,`kill -0` 在 cmd.exe 里没有对应物。改为询问机器自己的 CLI,把这两个问题都挪到了有 Node 的那一侧。调用形态按安装时探明的平台生成——POSIX 上是 `$HOME/.penguin/node/bin/node`,cmd.exe 下是 `%USERPROFILE%\.penguin\node\node.exe`——记录里没有平台的机器则两种都问一遍。
+
+`running` 为真要求记录的 pid 存活**且**其端口可建立连接,这是 shell 版本做不到的:它只有 `kill -0`,而被回收复用的 pid 会被读成一个活着的服务。
+
+读取 id 绝不会铸出一个,而状态探测以只读方式打开数据库——控制端询问一台机器「你是什么」时,不得在那台机器正运行的服务底下改动它的 schema,也不得在从未有过数据根目录的机器上留下一个。
+
+完全不含答案的输出会被报告为 **unreachable** 而非 stopped:版本过旧、没有该子命令的构建会打印一条错误,把它读作一个格式良好的「否」,会让每一台这样的机器都变成静默错误的机器。
diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts
index 2414da6b..5447064a 100644
--- a/packages/cli/src/commands/serve.ts
+++ b/packages/cli/src/commands/serve.ts
@@ -37,6 +37,7 @@ import { liveServerLock } from "@prismshadow/penguin-server/lock";
import type { Command } from "commander";
import type { Messages, WebProbeFailureKind } from "../i18n.js";
import { registerResetPasswordCommand } from "./reset-password.js";
+import { registerStatusCommand } from "./server-status.js";
/** Why the readiness poll gave up: failure class plus a one-line diagnostic from the last probe. */
export interface ReadinessFailure {
@@ -344,6 +345,7 @@ export function registerServeCommands(program: Command, t: Messages): void {
// Bare `penguin server` still starts the service (commander runs the action when no
// subcommand is named); the subcommand only dispatches on an exact name match.
registerResetPasswordCommand(server, t);
+ registerStatusCommand(server, t);
program
.command("web")
diff --git a/packages/cli/src/commands/server-status.ts b/packages/cli/src/commands/server-status.ts
new file mode 100644
index 00000000..e90d3c93
--- /dev/null
+++ b/packages/cli/src/commands/server-status.ts
@@ -0,0 +1,30 @@
+/**
+ * `penguin server status` — this data root's server state and machine id, as one line of
+ * JSON.
+ *
+ * Machine-facing on purpose: a CONTROLLER runs it over ssh to ask a machine what it is doing,
+ * and JSON is what spares that controller a parser for a format nobody defined. It answers
+ * whether or not a server is running (the data root is the source, not a live process), which
+ * is what makes it usable as a status probe rather than only a health check.
+ * Docs: /docs/cli § "penguin server / penguin web".
+ */
+import path from "node:path";
+import { readMachineStatus } from "@prismshadow/penguin-server/machine-status";
+import type { Command } from "commander";
+import type { Messages } from "../i18n.js";
+import { resolveRootOption } from "../root-option.js";
+
+/** Attaches the subcommand to the `penguin server` command (see registerServeCommands). */
+export function registerStatusCommand(server: Command, t: Messages): void {
+ server
+ .command("status")
+ .description(t.serverStatus.desc)
+ .option("--root <dir>", t.common.root)
+ .action(async (opts: { root?: string }) => {
+ const root = resolveRootOption(opts.root);
+ // PENGUIN_WEB_DB honored as everywhere else, or this reads an identity out of a
+ // database the live server never writes to.
+ const dbPath = process.env.PENGUIN_WEB_DB ?? path.join(root, "web.db");
+ process.stdout.write(JSON.stringify(await readMachineStatus(root, dbPath)) + "\n");
+ });
+}
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 08d4bc20..ad536b4b 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -322,6 +322,11 @@ export interface Messages {
noServer(root: string): string;
failed(detail: string): string;
};
+ /** `penguin server status`: help text. */
+ serverStatus: {
+ /** One-line description in `penguin server --help`. */
+ desc: string;
+ };
resetPassword: {
desc: string;
/** Refusal while a live server owns the data root (stop it first, then retry). */
@@ -842,6 +847,9 @@ const en: Messages = {
`${root} has no web.db — no server has ever run on this data root, so there is no account to mint for.`,
failed: (detail) => `Could not mint a token: ${detail}`,
},
+ serverStatus: {
+ desc: "Print this data root's server state and machine id as one line of JSON",
+ },
resetPassword: {
desc: "Reset the Web admin password to a fresh initial password (the server must be stopped)",
serverRunning: (url) =>
@@ -1349,6 +1357,9 @@ const zh: Messages = {
noServer: (root) => `${root} 上没有 web.db——该数据根上从未运行过服务,因此没有可签发的账号。`,
failed: (detail) => `签发失败:${detail}`,
},
+ serverStatus: {
+ desc: "以单行 JSON 打印本数据根目录的服务状态与本机 id",
+ },
resetPassword: {
desc: "把 Web 管理员密码重置为新的初始密码(须先停止服务)",
serverRunning: (url) =>
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index c7badfe5..3ddf3808 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -309,6 +309,19 @@ Port / host priority: command-line option > the `PORT` / `HOST` env vars (includ
Both run the service as a child process and stay behind as its supervisor: the terminal's Ctrl+C reaches the service, the command exits with the service's exit code, and when the service asks to be restarted — the Web App's **Restart and update** after `penguin update` has replaced the install — the supervisor relaunches it on the new release, printing a line as it does. A dev run through `tsx` cannot be relaunched by plain node and runs the service in-process instead; the Web App then tells the admin to restart by hand.
+### penguin server status
+
+Prints this data root's server state and the machine's own id, as one line of JSON. It answers whether or not a server is running — the data root is the source, not a live process:
+
+```bash
+penguin server status
+# {"running":true,"port":7364,"pid":41233,"machineId":"LNrJdHAZJ91G58i0"}
+```
+
+`running` requires both that the recorded pid is alive and that its port accepts a connection, so a recycled pid does not read as a live server. `machineId` is `null` until a server has started here at least once — the id is minted on first boot and never changes afterwards. The data root is selected by `PENGUIN_HOME` as usual.
+
+This is what the Machines page runs over ssh to ask a machine what it is doing, which is why the output is JSON rather than prose.
+
### penguin server reset-admin-password
Offline rescue when the Web admin password is forgotten. Run it with the server stopped — it refuses while one is running on the data root:
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 26a576e7..de6dcf72 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -309,6 +309,19 @@ penguin web
两者都把服务作为子进程运行,自己留在后面做托管:终端的 Ctrl+C 会送达服务,命令以服务的退出码退出;当服务请求重启——`penguin update` 替换安装后,Web App 里的「重启并更新」——托管进程会在新版本上重新拉起它,并打印一行提示。经 `tsx` 的开发运行无法被普通 node 重新拉起,改为在本进程内运行服务;此时 Web App 会提示管理员手动重启。
+### penguin server status
+
+以单行 JSON 打印本数据根目录的服务状态与本机 id。无论是否有服务在运行它都会作答——依据是数据根目录本身,而不是某个存活的进程:
+
+```bash
+penguin server status
+# {"running":true,"port":7364,"pid":41233,"machineId":"LNrJdHAZJ91G58i0"}
+```
+
+`running` 为真要求记录的 pid 存活**且**其端口可建立连接,因此被回收复用的 pid 不会被读成一个活着的服务。`machineId` 在本机从未启动过服务之前是 `null`——该 id 在首次启动时铸出,此后永不改变。数据根目录一如既往由 `PENGUIN_HOME` 选定。
+
+机器页正是通过 ssh 运行这条命令来询问一台机器的状态,这也是它输出 JSON 而非人类散文的原因。
+
### penguin server reset-admin-password
忘记 Web 管理员密码时的离线救援。须在服务停止后执行——数据根目录上有服务在运行时会拒绝:
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index c44543f3..2f7f2c6b 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -112,11 +112,12 @@ In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/projects/:projectId/machines | The host aliases of the SERVER's own `~/.ssh/config` with what THIS PROJECT has installed on each, the version this server would install, and the running or last install job: `{machines: [{id, alias, installed, elsewhere?}], imageVersion, job}`. `elsewhere` is a host another Project installed — a machine to adopt rather than install |
+| GET | /api/projects/:projectId/machines | This machine and the host aliases of the SERVER's own `~/.ssh/config` with what THIS PROJECT has installed on each, the last status probed for each, the version this server would install, and the running or last install job: `{machines: [{id, alias, machineId, installed, elsewhere?, local, status}], imageVersion, job}`. `elsewhere` is a host another Project installed — a machine to adopt rather than install |
+| POST | /api/projects/:projectId/machines/probe | Ask this Project's installed machines what they are doing (one ssh round trip each, five at a time) and answer the list with the fresh statuses |
| POST | /api/projects/:projectId/machines/:machineId/install | Start installing this build on that host and give it to this Project; `202` with the same body, the job now running |
| POST | /api/projects/:projectId/machines/:machineId/release | Drop that machine from this Project; the install on it stays |
-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.
+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 for the aliases it declares, so a config naming hundreds of hosts costs one file read. What an alias means is ssh's own to resolve from that same file, every time it is used, so nothing here can go stale against a config a person edits.
`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.
@@ -124,7 +125,7 @@ Admin only on a personal server as much as a multi-user one: the install spawns
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`.
+Refusals decided before any ssh runs have their own codes: `409` `install_running`, `404` `unknown_machine`, `409` `no_install_image`, and `409` `self_install` — the machine this server runs on, which it will not push this build over the program directory it is running from. `self_install` covers an alias pointing back home (`Host localhost`, a second name for this host) as well as the local row, once a probe has heard this server's own id from it.
### Version and Self-Update
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 66e59a05..9940ce4b 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -112,11 +112,12 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/projects/:projectId/machines | **服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、本服务端会安装的版本,以及正在运行或最近一次的安装任务:`{machines: [{id, alias, installed, elsewhere?}], imageVersion, job}`。`elsewhere` 表示该主机由别的 Project 装过——可以纳入,不必重装 |
+| GET | /api/projects/:projectId/machines | 本机,加上**服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、每台最近一次探测到的状态、本服务端会安装的版本,以及正在运行或最近一次的安装任务:`{machines: [{id, alias, machineId, installed, elsewhere?, local, status}], imageVersion, job}`。`elsewhere` 表示该主机由别的 Project 装过——可以纳入,不必重装 |
+| POST | /api/projects/:projectId/machines/probe | 询问本 Project 已安装的机器各自的状态(每台一次 ssh 往返,并发 5)并返回带有最新状态的列表 |
| POST | /api/projects/:projectId/machines/:machineId/install | 在该主机上安装当前构建,并把它归入本 Project;返回 `202` 与同样的响应体,此时任务已在运行 |
| POST | /api/projects/:projectId/machines/:machineId/release | 把该机器移出本 Project;机器上已安装的程序保持不动 |
-无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写,`ssh -G` 仅在真正安装时才解析别名,因此哪怕配置声明了几百台主机,列表也只是一次文件读取。
+无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写——只读其中声明的别名,因此哪怕配置声明了几百台主机,列表也只是一次文件读取。别名到底指向什么,每次都由 ssh 自己按同一份文件解析,因此这里不存在与人手改过的配置对不上的陈旧信息。
`imageVersion` 是将被推送的版本;为 `null` 表示本服务端根本没有安装镜像(只有从未被热推过的源码检出会是这种形态),此时任何安装都会以 `409` `no_install_image` 拒绝。该版本取自当前运行的安装自身:热推过的服务端推送它正在运行的 bundle(`0.0.0-hmr.<cli>.<web>`),tarball 或打包安装则推送自己的程序树,因此两端的一致是构造性的。
@@ -124,7 +125,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
安装是任务而非请求:它要探测对端,可能下载并校验一份 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`。
+在任何 ssh 运行之前就能判定的拒绝各有错误码:`409` `install_running`、`404` `unknown_machine`、`409` `no_install_image`,以及 `409` `self_install`——本服务端自己所在的那台机器,它不会把这份构建盖到自己正在运行的程序目录上。`self_install` 不只覆盖本机那一行:指回本机的别名(`Host localhost`、本机的第二个名字)一旦被探测到报出本服务端自己的 id,同样会被拒绝。
### 版本与在线更新
diff --git a/packages/server/package.json b/packages/server/package.json
index 2b78724e..6f8253d8 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -18,6 +18,10 @@
"types": "./dist/api/types.d.ts",
"import": "./dist/api/types.js"
},
+ "./machine-status": {
+ "types": "./dist/machine-status.d.ts",
+ "import": "./dist/machine-status.js"
+ },
"./lock": {
"types": "./dist/lock.d.ts",
"import": "./dist/lock.js"
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 101d9644..b2ab9434 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3335,6 +3335,40 @@ export interface MachineInfo {
* someone to spend a 30 MB transfer re-doing what is already done.
*/
elsewhere?: { version: string; at: string };
+ /**
+ * The machine's OWN id — 16 base64url characters minted by the server that runs there,
+ * stable across renames, re-aliasing and reinstalls. Null until a server has started on
+ * that machine, since nothing has minted one yet.
+ *
+ * This is what anything stored should point at; `id` above is an ADDRESS (`ssh:<alias>`),
+ * and `alias` is what people read. Two aliases for one host share a `machineId`, and an
+ * alias repointed at a different host answers a different one — an id never changes for a
+ * machine, so a change of id is a change of machine.
+ */
+ machineId: string | null;
+ /** The host this server itself runs on. Always present, always installed, never a target. */
+ local: boolean;
+ /**
+ * What the last probe found over there, or null when none has been taken. Never filled in
+ * at list time: a probe costs an ssh round trip per machine, so the list reports the last
+ * answer and the page asks for a fresh one when it wants one.
+ */
+ status: MachineServerStatus | null;
+}
+
+/**
+ * A machine's server as of one probe. There is deliberately no separate "ssh" state — ssh is
+ * the transport, so a machine it cannot reach reads as `unreachable` with OpenSSH's own
+ * diagnostic in `detail` rather than as two states a reader has to combine.
+ */
+export interface MachineServerStatus {
+ state: "running" | "stopped" | "unreachable";
+ /** ISO timestamp of the probe this answer came from. */
+ checkedAt: string;
+ /** The port it is serving on (`running`). */
+ port?: number;
+ /** Why the machine could not be reached (`unreachable`) — ssh's own words. */
+ detail?: string;
}
/**
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 28de2ae9..13c17fb0 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -782,6 +782,16 @@ export function buildAppDeps(
// back, so a restart-only migration is refused here instead of being left behind.
migrate(db, { swapPath: true });
+ /**
+ * This machine's own id is minted on the first boot of this data root and stable ever
+ * after — every stored reference to this machine, here and on the machines it reaches,
+ * points at it. Behind a function so a test that passes its own service never mints one.
+ */
+ const buildMachines = (): MachinesService => {
+ const repo = new MachinesRepo(db);
+ return new MachinesService(config.root, repo.ownId(), repo, {}, () => hmr.assetsDir());
+ };
+
const usersRepo = new UsersRepo(db);
const projectsRepo = new ProjectsRepo(db);
const membersRepo = new MembersRepo(db);
@@ -1095,9 +1105,7 @@ export function buildAppDeps(
lifecycle: caps.lifecycle,
// Anchored at the data root: that is where the hmr store the pushable image comes from
// lives, and where verified Node runtime downloads are cached between installs.
- machines:
- overrides.machines ??
- new MachinesService(config.root, new MachinesRepo(db), {}, () => hmr.assetsDir()),
+ machines: overrides.machines ?? buildMachines(),
hmr,
proxyControl: caps.proxyControl,
log,
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 2e47ae63..7afd5008 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -33,6 +33,19 @@ export function openExistingDatabase(dbPath: string): DatabaseSync {
return db;
}
+/**
+ * Opens an EXISTING database for reading only — SQLite refuses every write on the connection,
+ * so a reader cannot change the file even by mistake. For a question asked of a database some
+ * other process owns (`penguin server status`, run over ssh by a controller): the answer must
+ * not reshape that server's schema, and must not be able to. The caller has established that
+ * the file exists; a read-only open of a missing file is an error, not a creation.
+ */
+export function openDatabaseReadOnly(dbPath: string): DatabaseSync {
+ const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
+ db.exec("PRAGMA busy_timeout = 5000;");
+ return db;
+}
+
/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */
export function openDatabase(dbPath: string): DatabaseSync {
if (dbPath !== ":memory:") {
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index f869335f..3d4ced3d 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -199,7 +199,8 @@ export const MIGRATIONS: readonly Migration[] = [
version TEXT,
installed_at TEXT,
session_pid INTEGER,
- remote_port INTEGER
+ remote_port INTEGER,
+ platform TEXT
);
CREATE TABLE IF NOT EXISTS machine_project (
project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,
diff --git a/packages/server/src/db/repos/machines.ts b/packages/server/src/db/repos/machines.ts
index 015c3d56..fb2b351a 100644
--- a/packages/server/src/db/repos/machines.ts
+++ b/packages/server/src/db/repos/machines.ts
@@ -1,6 +1,6 @@
/**
- * What this server remembers about machines: one row per machine it has installed on, and
- * which machines each Project uses. In web.db, so a hot swap or a restart reads back exactly
+ * What this server remembers about machines: its own identity, one row per machine it has
+ * installed on, and which machines each Project uses. In web.db, so a hot swap or a restart reads back exactly
* what the last generation wrote — the JSON file this replaces could not survive a schema
* change, and nothing else this server remembers lives outside the database.
*
@@ -9,6 +9,7 @@
* are the table's, not this store's opinion of what matters.
*/
import type { DatabaseSync } from "node:sqlite";
+import { randomBytes } from "node:crypto";
export interface MachineRow {
/** `ssh:<alias>` */
@@ -22,14 +23,41 @@ export interface MachineRow {
sessionPid: number | null;
/** The port its server was bound to over there, as of the last connect. */
remotePort: number | null;
+ /** What the install found the machine to be; null until one has. The status probe speaks that dialect. */
+ platform: "linux" | "darwin" | "win32" | null;
}
/** Everything but the address may be patched; absent fields keep their value. */
type MachinePatch = Partial<Omit<MachineRow, "address">>;
+/**
+ * 12 random bytes as base64url: 16 characters a person can read in a tooltip, 96 bits
+ * against ids minted on machines that never coordinate.
+ */
+const MACHINE_ID_BYTES = 12;
+
export class MachinesRepo {
constructor(private readonly db: DatabaseSync) {}
+ /**
+ * This server's own id if one has been minted, WITHOUT minting one — `penguin server
+ * status` runs on a data root whose server may never have started, and must not create an
+ * identity as a side effect of the question.
+ */
+ peekOwnId(): string | null {
+ const row = this.db.prepare("SELECT machine_id FROM machine WHERE singleton = 1").get();
+ return row ? (row.machine_id as string) : null;
+ }
+
+ /** This server's own id, minted on first call and stable ever after. */
+ ownId(): string {
+ const existing = this.peekOwnId();
+ if (existing !== null) return existing;
+ const minted = randomBytes(MACHINE_ID_BYTES).toString("base64url");
+ this.db.prepare("INSERT INTO machine (singleton, machine_id) VALUES (1, ?)").run(minted);
+ return minted;
+ }
+
get(address: string): MachineRow | null {
const row = this.db.prepare("SELECT * FROM machines WHERE address = ?").get(address);
return row === undefined ? null : toRow(row);
@@ -49,12 +77,13 @@ export class MachinesRepo {
installedAt: null,
sessionPid: null,
remotePort: null,
+ platform: null,
}),
...patch,
};
this.db
.prepare(
- "INSERT OR REPLACE INTO machines (address, machine_id, version, installed_at, session_pid, remote_port) VALUES (?, ?, ?, ?, ?, ?)",
+ "INSERT OR REPLACE INTO machines (address, machine_id, version, installed_at, session_pid, remote_port, platform) VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.run(
address,
@@ -63,6 +92,7 @@ export class MachinesRepo {
next.installedAt,
next.sessionPid,
next.remotePort,
+ next.platform,
);
}
@@ -89,5 +119,6 @@ function toRow(row: Record<string, unknown>): MachineRow {
installedAt: (row.installed_at as string | null) ?? null,
sessionPid: (row.session_pid as number | null) ?? null,
remotePort: (row.remote_port as number | null) ?? null,
+ platform: (row.platform as MachineRow["platform"]) ?? null,
};
}
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index f3df42f5..ec6c56fc 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -151,7 +151,8 @@ CREATE TABLE IF NOT EXISTS machines ( -- one row per machine this serve
version TEXT, -- what this server last installed there; NULL = never
installed_at TEXT,
session_pid INTEGER, -- the ssh session this server holds to it; what a successor App closes after a hot swap
- remote_port INTEGER -- its server's port over there, as of the last connect
+ remote_port INTEGER, -- its server's port over there, as of the last connect
+ platform TEXT -- linux | darwin | win32, as the install found it: the shell dialect the status probe speaks to it in
);
CREATE TABLE IF NOT EXISTS machine_project ( -- which machines a Project uses; no row = none yet. Follows the Project out, like project_members
project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
index c4bce8e7..5498fb24 100644
--- a/packages/server/src/http/routes/machines.ts
+++ b/packages/server/src/http/routes/machines.ts
@@ -2,12 +2,15 @@
* Machines routes, under a Project (admin only, 403 for non-admins). Relative to
* `/api/projects/:projectId/machines`:
*
+ * POST /probe — refresh the statuses of this Project's machines (one ssh round
+ * trip each), then answer the list.
* POST /:machineId/install — start an install and give the machine to this Project; 202, or
* 409 when one runs.
* POST /:machineId/release — drop it from this Project. The install stays.
- * GET / — the ssh config's host aliases with what this Project has
- * installed on each, the version this server would install, and
- * the running or last job.
+ * GET / — this machine and the ssh config's host aliases with what this
+ * Project has installed on each, the last status probed for each,
+ * the version this server would install, and the running or last
+ * job.
*
* Under a Project because the page is, and because a Project's machines are where that
* Project's work runs. The machine itself is not project-scoped — one host, one program,
@@ -51,6 +54,11 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/", (c) => c.json(state(c)));
+ app.post("/probe", async (c) => {
+ await deps.machines.probeInstalled(requireValidId(c, "projectId"));
+ return c.json(state(c));
+ });
+
app.post("/:machineId/release", (c) => {
deps.machines.release(requireValidId(c, "projectId"), c.req.param("machineId"));
return c.json(state(c));
@@ -67,6 +75,13 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
if (started.why === "busy") {
throw new HttpError(409, "install_running", "An install is already running.");
}
+ if (started.why === "self") {
+ throw new HttpError(
+ 409,
+ "self_install",
+ "That is the machine this server runs on. It cannot push this build over the program directory it is running from.",
+ );
+ }
if (started.why === "unknown-machine") {
throw new HttpError(404, "unknown_machine", "No such host in this server's ssh config.");
}
diff --git a/packages/server/src/machine-status.ts b/packages/server/src/machine-status.ts
new file mode 100644
index 00000000..9e23e854
--- /dev/null
+++ b/packages/server/src/machine-status.ts
@@ -0,0 +1,75 @@
+/**
+ * "Is a server running on this data root, and which machine is this?" — answered from the
+ * root itself, by whoever can read it, with no server needed and safely while one runs (the
+ * same terms as `penguin auth token`, which writes to this database live).
+ *
+ * Exported as `@prismshadow/penguin-server/machine-status` for `penguin server status`, which
+ * is how a CONTROLLER asks: it runs that one command over ssh and reads back JSON. The
+ * question used to be asked in shell — `cat` the lock, `sed` the pid out of it, `kill -0`,
+ * `cat` a second file for the id — which meant a parser on this side for a format with no
+ * definition, and no answer at all from a Windows remote, `kill -0` having no cmd.exe
+ * equivalent. Asking the machine's own CLI moves both problems to the side that has Node.
+ *
+ * Liveness is the local lock's own test (pid alive AND the port accepting), which the shell
+ * version could not do: it only had `kill -0`, and a recycled pid reads as a live server.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { openDatabaseReadOnly } from "./db/database.js";
+import { MachinesRepo } from "./db/repos/machines.js";
+import { liveServerLock } from "./lock.js";
+
+/** What `penguin server status` prints, as one line of JSON. */
+export interface MachineStatus {
+ /** A server owns this root right now: its pid is alive and its port answers. */
+ running: boolean;
+ /** The live server's port and pid; null when nothing is running. */
+ port: number | null;
+ pid: number | null;
+ /**
+ * This machine's own id, or null when it has none yet — the id is minted the first time a
+ * server boots here, so an installed-but-never-run machine legitimately has none, and
+ * saying null is better than minting one to answer a question.
+ */
+ machineId: string | null;
+}
+
+/** `dbPath` may be elsewhere (PENGUIN_WEB_DB), as everywhere else that reads this database. */
+export async function readMachineStatus(
+ root: string,
+ dbPath: string = path.join(root, "web.db"),
+): Promise<MachineStatus> {
+ const lock = await liveServerLock(root);
+ return {
+ running: lock !== null,
+ port: lock?.port ?? null,
+ pid: lock?.pid ?? null,
+ machineId: readMachineId(dbPath),
+ };
+}
+
+/**
+ * Reads the id and changes nothing — and cannot: the connection is read-only.
+ *
+ * `openDatabaseReadOnly`, never `openDatabase`: the latter is the SCHEMA path — CREATE TABLE,
+ * the ensureColumn list, an ALTER with a backfill, and the migrations. A controller asking a
+ * machine what it is would then reshape that machine's database under the prepared statements
+ * of the server running there, on a build that may be older than this question. A read-only
+ * open makes that impossible rather than merely not done.
+ *
+ * Existence-checked first, because opening would create the file (and its directory) on a
+ * root no server has ever used — a probe must not leave a data root behind it. A machine
+ * whose database predates the `machine` table answers with no id rather than an error: it is
+ * one that has never run a build that mints one, which is the truth about it.
+ */
+function readMachineId(dbPath: string): string | null {
+ if (!fs.existsSync(dbPath)) return null;
+ const db = openDatabaseReadOnly(dbPath);
+ try {
+ return new MachinesRepo(db).peekOwnId();
+ } catch {
+ return null;
+ } finally {
+ db.close();
+ }
+}
diff --git a/packages/server/src/machines/answer.ts b/packages/server/src/machines/answer.ts
new file mode 100644
index 00000000..85cc62fd
--- /dev/null
+++ b/packages/server/src/machines/answer.ts
@@ -0,0 +1,28 @@
+/**
+ * Reading what a machine answered.
+ *
+ * Every command this side runs over ssh is now a `penguin` subcommand that prints one line of
+ * JSON, so there is one way to read one: find the line that is the answer, and ignore the
+ * rest. The rest is real — sshd runs the command in a shell that may greet, warn about
+ * pending updates, or print an MOTD, and none of that belongs to the machine's reply.
+ *
+ * `key` is what distinguishes the answer from any other object a shell might print. It is
+ * also why "no answer at all" is a distinct outcome rather than a default: a build too old
+ * for the subcommand prints an error, and reading that as a well-formed "no" would turn every
+ * such machine into a silently wrong one.
+ */
+
+/** The machine's answer, or null when nothing it printed is one. */
+export function jsonAnswer<T>(stdout: string, key: string): T | null {
+ for (const line of stdout.split("\n")) {
+ const text = line.trim();
+ if (!text.startsWith("{")) continue;
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (parsed !== null && typeof parsed === "object" && key in parsed) return parsed as T;
+ } catch {
+ // Not this line.
+ }
+ }
+ return null;
+}
diff --git a/packages/server/src/machines/commands.ts b/packages/server/src/machines/commands.ts
index 9d6f4691..986c8ea4 100644
--- a/packages/server/src/machines/commands.ts
+++ b/packages/server/src/machines/commands.ts
@@ -60,6 +60,56 @@ function connectionOptions(target: RemoteTarget): string[] {
];
}
+/**
+ * The far side's program directory, and the launcher inside it that everything here runs.
+ * Absolute, because sshd's non-login shell has no `~/.local/bin` on PATH — the symlink the
+ * installer drops there is for a person at a terminal, not for us.
+ *
+ * `$HOME/.penguin` is where install.sh puts it (`PENGUIN_INSTALL_DIR`, defaulting there),
+ * laid out as bin/ lib/ web/ node/, with the launcher exec'ing `node/bin/node lib/dist/…`
+ * (scripts/launchers/penguin). A remote's own override of that variable is not visible over
+ * a non-interactive ssh, so the default is the only thing this side can assume — the same
+ * assumption detect.ts makes to find the manifest.
+ */
+export const REMOTE_PROGRAM_DIR = "$HOME/.penguin";
+
+/**
+ * The CLI these commands run on a machine: the one PUSHED to it, not the one installed.
+ *
+ * `bin/penguin` is the released program, and a release only carries the subcommands this
+ * side asks for (`server status`, `auth token`, `server --detach`) once a release has
+ * shipped them. Reaching a machine would then be impossible until the next release —
+ * including for the build that introduces reaching machines at all.
+ *
+ * `dist/penguin-hmr.js` is the entry that loads the CLI out of that machine's own hmr store
+ * (packages/cli/src/penguin-hmr.ts), which is the CLI this server pushed there. It has
+ * shipped in the archive since long before any of this, so a machine installed by any
+ * release can run the current CLI. What it cannot do is run one that was never pushed: a
+ * machine with an empty store answers `no CLI pushed to <root>`, and the remedy is to
+ * install — which replicates the store on its way through (install-server.ts).
+ *
+ * Invoked through the bundled runtime rather than the launcher, because there is no
+ * launcher for this entry. Machines installed from here always carry that runtime: the
+ * install runs install.sh without `--universal`, which is the only mode that omits it.
+ */
+export const REMOTE_PENGUIN = `"${REMOTE_PROGRAM_DIR}/node/bin/node" "${REMOTE_PROGRAM_DIR}/lib/dist/penguin-hmr.js"`;
+
+/**
+ * The same program directory as cmd.exe names it. A Windows sshd hands a command to cmd.exe,
+ * where `$HOME` is four literal characters and the bundled runtime is `node\node.exe`
+ * (scripts/launchers/penguin.cmd) — so the POSIX form above is not "not found" there, it is
+ * a different sentence. `%USERPROFILE%` is what install.ps1 defaults to.
+ */
+export const REMOTE_PROGRAM_DIR_WINDOWS = "%USERPROFILE%\\.penguin";
+
+/** The pushed CLI, invoked in the dialect of the shell that will read the command. */
+export function remotePenguin(platform: "linux" | "darwin" | "win32"): string {
+ if (platform === "win32") {
+ return `"${REMOTE_PROGRAM_DIR_WINDOWS}\\node\\node.exe" "${REMOTE_PROGRAM_DIR_WINDOWS}\\lib\\dist\\penguin-hmr.js"`;
+ }
+ return REMOTE_PENGUIN;
+}
+
/** `ssh <options> <alias> <remote command>`. */
export function sshArgs(target: RemoteTarget, remoteCommand: string): string[] {
return [...connectionOptions(target), target.alias, remoteCommand];
diff --git a/packages/server/src/machines/server-state.ts b/packages/server/src/machines/server-state.ts
new file mode 100644
index 00000000..8343496d
--- /dev/null
+++ b/packages/server/src/machines/server-state.ts
@@ -0,0 +1,125 @@
+/**
+ * Is the server this build installed on that machine running, and which machine is it?
+ *
+ * One ssh round trip answers both: `penguin server status` over there prints one line of
+ * JSON (machine-status.ts). The far side has Node, so the far side formats; this side
+ * carries no parser for a shell's output. ssh's own failure is not a separate condition —
+ * it IS the answer "cannot reach this machine", carrying OpenSSH's diagnostic.
+ */
+import { remotePenguin } from "./commands.js";
+import { jsonAnswer } from "./answer.js";
+import type { RemoteTarget } from "./commands.js";
+import type { RemotePlatform } from "./detect.js";
+import type { ExecResult } from "./transport/index.js";
+import type { MachineStatus } from "../machine-status.js";
+
+/**
+ * `2>&1` so the far side's own complaint (an old build with no such subcommand, a launcher
+ * that is not there) comes back as text rather than being swallowed by the shared shell,
+ * which merges the streams and reports an empty stderr.
+ */
+export function readServerStateCommand(platform: RemotePlatform): string {
+ return `${remotePenguin(platform)} server status 2>&1`;
+}
+
+type MachineServerState =
+ /** The machine answered and a server owns its data root: it is up on that port. */
+ | { kind: "running"; port: number; pid: number }
+ /** The machine answered; nothing is serving there. The program is installed either way. */
+ | { kind: "stopped" }
+ /** No usable answer — unreachable, refused, or a build that cannot answer the question. */
+ | { kind: "unreachable"; detail: string };
+
+/** What one probe learned: the server's state, and who that machine says it is. */
+export interface MachineProbe {
+ state: MachineServerState;
+ /**
+ * The machine's own id, when it has one. Absent until a server has STARTED there — the id
+ * is minted by that server, not by the install — so a freshly installed machine answers
+ * `stopped` with no id, and gains one the first time it runs.
+ */
+ machineId: string | null;
+}
+
+/**
+ * Reads the answer out of the command's output.
+ *
+ * Line by line rather than parsing the whole thing: an ssh command runs in a shell that may
+ * print a banner, an MOTD or a warning of its own, and none of that is the machine's answer.
+ *
+ * Output holding no answer at all is NOT reported as "stopped". A build too old for the
+ * subcommand, or a launcher that is not where this side expects it, would then look exactly
+ * like a healthy machine with nothing running — so it reads as "cannot tell", carrying what
+ * the far side actually said.
+ */
+export function parseProbe(stdout: string): MachineProbe {
+ const said = stdout.trim();
+ const cannotTell = (detail: string): MachineProbe => ({
+ state: { kind: "unreachable", detail },
+ machineId: null,
+ });
+ const status = jsonAnswer<MachineStatus>(stdout, "running");
+ if (status === null) return cannotTell(said === "" ? "the machine said nothing." : said);
+
+ // The declared type is what a healthy far side sends; this is untrusted text off a wire,
+ // so the shape is checked rather than assumed. For the same reason output holding no
+ // answer is not "stopped": an answer whose shape is wrong is not an answer either, and
+ // coercing one MANUFACTURES a state. `"running": "false"` is a truthy string and would
+ // read as up; `"running": true` carrying no port would read as down. Both are worse than
+ // saying the machine could not be read.
+ const { running, port, pid } = status;
+ const id = status.machineId;
+ const machineId = typeof id === "string" && id !== "" ? id : null;
+ if (typeof running !== "boolean") return cannotTell(said);
+ if (!running) return { state: { kind: "stopped" }, machineId };
+ if (typeof port !== "number" || typeof pid !== "number") return cannotTell(said);
+ return { state: { kind: "running", port, pid }, machineId };
+}
+
+/**
+ * Probes one machine. Never throws: every failure is one of the states above.
+ *
+ * `exec` is the caller's channel — the machines service passes the machine's shared shell,
+ * so a probe every few minutes does not open a connection every few minutes. Required: the
+ * one-shot fallback this parameter used to have was a second mouth to the machine, opened
+ * outside the transport seam (see transport/connection.ts).
+ */
+export async function probeServerState(
+ target: RemoteTarget,
+ exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,
+ /**
+ * The dialect to ask in — what the install found the machine to be. Null when nothing is
+ * on record: the POSIX form is tried first and, if it holds no answer, the Windows form,
+ * the same way detectRemote asks. One round trip for a machine that is known, two at most
+ * for one that is not.
+ */
+ platform: RemotePlatform | null = null,
+): Promise<MachineProbe> {
+ const first = await probeIn(target, exec, platform ?? "linux");
+ if (platform !== null || first.state.kind !== "unreachable") return first;
+ const second = await probeIn(target, exec, "win32");
+ return second.state.kind === "unreachable" ? first : second;
+}
+
+async function probeIn(
+ target: RemoteTarget,
+ exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,
+ platform: RemotePlatform,
+): Promise<MachineProbe> {
+ const result = await exec(target, readServerStateCommand(platform));
+ if (result.code !== 0) {
+ // stdout as the fallback, not just stderr: over the shared shell the two streams are
+ // merged and stderr arrives empty (ssh-session.ts), so reading only stderr threw away
+ // the far side's own words — which here are the whole diagnostic, the command being one
+ // the machine either ran or could not find.
+ const detail = result.stderr.trim() || result.stdout.trim();
+ return {
+ state: {
+ kind: "unreachable",
+ detail: detail === "" ? "ssh exited without a message." : detail,
+ },
+ machineId: null,
+ };
+ }
+ return parseProbe(result.stdout);
+}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index 48d164ca..bd76d669 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -25,13 +25,25 @@
* `elsewhere` rather than hidden: adopting it costs a row, while re-installing costs a
* 30 MB transfer to reach the same place.
*/
-import type { MachineInfo, MachineInstallJob } from "../api/types.js";
-import { listHostAliases } from "./transport/index.js";
+import os from "node:os";
+import { VERSION } from "@prismshadow/penguin-core";
+import type { MachineInfo, MachineInstallJob, MachineServerStatus } from "../api/types.js";
+import { readServerLock } from "../lock.js";
+import { connectionTo, listHostAliases } from "./transport/index.js";
+import type { ExecResult } from "./transport/index.js";
+import type { RemoteTarget } from "./commands.js";
import { installOnRemote, resolvePushPlan } from "./install-server.js";
+import { probeServerState } from "./server-state.js";
import type { MachinesRepo } from "../db/repos/machines.js";
+/** The id of the entry standing for the machine this server runs on. */
+const LOCAL_MACHINE_ID = "local";
+
+/** How many machines the probe works on at once. */
+const CONCURRENCY = 5;
+
/** Why a start was refused before any ssh ran. */
-export type InstallRefusal = "busy" | "unknown-machine" | "no-image";
+export type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";
/**
* The three things this service does to the world, injectable as a set. Production passes
@@ -44,13 +56,28 @@ export interface MachinesEffects {
listAliases: typeof listHostAliases;
resolvePlan: typeof resolvePushPlan;
install: typeof installOnRemote;
+ probe: typeof probeServerState;
+ /** One command on a machine, over its own ssh. */
+ runOn: (target: RemoteTarget, command: string) => Promise<ExecResult>;
/** Injected so a test can pin the recorded timestamp instead of asserting around the clock. */
now: () => Date;
}
export class MachinesService {
#job: MachineInstallJob | null = null;
+ /**
+ * The last probe per address. In memory on purpose: a status is only true for the moment
+ * it was taken, so one that outlived its App would be a claim nobody measured.
+ */
+ readonly #statuses = new Map<string, MachineServerStatus>();
+ /**
+ * The probe round in flight per Project. Concurrent askers — every open tab schedules its
+ * own — share the round rather than each starting five workers: the answer is the same,
+ * and five was meant as a bound, not as a unit of multiplication.
+ */
+ readonly #probing = new Map<string, Promise<void>>();
readonly #effects: MachinesEffects;
+ readonly #machineId: string;
/** Where a pushed bundle's assets were unpacked; null in a packaged server (hmr.assetsDir). */
readonly #assets: () => string | null;
@@ -58,20 +85,57 @@ export class MachinesService {
/** `dataRoot` is the server's own data root: it holds the hmr state a push replicates. */
constructor(
private readonly dataRoot: string,
+ machineId: string,
private readonly repo: MachinesRepo,
effects: Partial<MachinesEffects> = {},
assets: () => string | null = () => null,
) {
this.#assets = assets;
+ this.#machineId = machineId;
this.#effects = {
listAliases: listHostAliases,
resolvePlan: resolvePushPlan,
install: installOnRemote,
+ probe: probeServerState,
+ // 30s: a probe is one short command, and a machine that cannot answer it in that time
+ // is one the list should call unreachable rather than wait on.
+ // One at a time per machine (transport/lane.ts): however many askers, a machine sees
+ // one of these commands at once, and the rest wait their turn on it.
+ runOn: (target, command) => connectionTo(target).exec(command),
now: () => new Date(),
...effects,
};
}
+ /**
+ * A machine's ssh target is its alias and nothing else — what the alias means is ssh's to
+ * resolve, from its own config, every time it is handed one.
+ */
+ #targetOf(alias: string): RemoteTarget {
+ return { alias, user: "" };
+ }
+
+ /**
+ * This machine: always installed, always up, never a target. Read directly rather than
+ * probed — both facts are right here — and absent from the install picker, because a
+ * server does not push this build over the program directory it is running from.
+ */
+ #localMachine(): MachineInfo {
+ const lock = readServerLock(this.dataRoot);
+ return {
+ id: LOCAL_MACHINE_ID,
+ alias: os.hostname(),
+ machineId: this.#machineId,
+ installed: { version: VERSION, at: lock?.startedAt ?? this.#effects.now().toISOString() },
+ local: true,
+ status: {
+ state: "running",
+ checkedAt: this.#effects.now().toISOString(),
+ ...(lock === null ? {} : { port: lock.port }),
+ },
+ };
+ }
+
/**
* The addresses a Project uses: exactly its own list, empty until an install gives it one.
*
@@ -101,7 +165,7 @@ export class MachinesService {
*/
list(projectId: string): MachineInfo[] {
const members = new Set(this.#members(projectId));
- return this.#effects.listAliases().map((alias): MachineInfo => {
+ const remotes = this.#effects.listAliases().map((alias): MachineInfo => {
const id = `ssh:${alias}`;
const row = this.repo.get(id);
const installed =
@@ -110,10 +174,83 @@ export class MachinesService {
return {
id,
alias,
+ machineId: row?.machineId ?? null,
installed: mine ? installed : null,
...(!mine && installed !== null ? { elsewhere: installed } : {}),
+ local: false,
+ status: this.#statuses.get(id) ?? null,
};
});
+ return [this.#localMachine(), ...remotes];
+ }
+
+ /**
+ * Asks this Project's installed machines what they are doing, five at a time, and keeps
+ * each answer. Never at list time: a probe is an ssh round trip per machine, and a page
+ * load is not a reason to open one to every host in a config.
+ */
+ async probeInstalled(projectId: string): Promise<void> {
+ const inFlight = this.#probing.get(projectId);
+ if (inFlight !== undefined) return inFlight;
+ const round = this.#probeRound(projectId).finally(() => this.#probing.delete(projectId));
+ this.#probing.set(projectId, round);
+ return round;
+ }
+
+ async #probeRound(projectId: string): Promise<void> {
+ const queue = this.list(projectId).filter((m) => !m.local && m.installed !== null);
+ const workers = Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {
+ for (let machine = queue.shift(); machine !== undefined; machine = queue.shift()) {
+ const checkedAt = this.#effects.now().toISOString();
+ const target = this.#targetOf(machine.alias);
+ const probe = await this.#effects.probe(
+ target,
+ this.#effects.runOn,
+ this.repo.get(machine.id)?.platform ?? null,
+ );
+ const state = probe.state;
+ this.#statuses.set(machine.id, {
+ state: state.kind,
+ checkedAt,
+ ...(state.kind === "running" ? { port: state.port } : {}),
+ ...(state.kind === "unreachable" ? { detail: state.detail } : {}),
+ });
+ this.#rememberMachineId(machine.id, probe.machineId);
+ }
+ });
+ await Promise.all(workers);
+ }
+
+ /**
+ * Records an id a probe just heard. An id NEVER changes for a machine, so a probe that
+ * answers a different one means the alias was repointed — the newer answer is the true one.
+ *
+ * And a different machine is not covered by what this row remembers. Everything the row
+ * holds about the far side — what this server installed there and when, what platform the
+ * install found, the port its server was last bound to — was learned from the machine that
+ * is no longer at this address. Kept, it would report the newcomer as already provisioned
+ * at a build it has never run, and the install that would have corrected that is exactly
+ * what an "already installed" record suppresses. The first id a machine ever gives keeps
+ * the record: null to minted is one machine finally saying who it is, not a substitution.
+ *
+ * `sessionPid` deliberately survives: it names the ssh child THIS server holds, which is
+ * the one that just answered, and forgetting it would leave a process nothing can close.
+ */
+ #rememberMachineId(address: string, machineId: string | null): void {
+ if (machineId === null) return;
+ const known = this.repo.get(address)?.machineId ?? null;
+ if (known === machineId) return;
+ if (known === null) {
+ this.repo.patch(address, { machineId });
+ return;
+ }
+ this.repo.patch(address, {
+ machineId,
+ version: null,
+ installedAt: null,
+ remotePort: null,
+ platform: null,
+ });
}
/** Drops a machine from a Project. The program stays installed; only the membership goes. */
@@ -151,8 +288,15 @@ export class MachinesService {
): Promise<{ ok: true } | { ok: false; why: InstallRefusal }> {
if (this.#job?.running === true) return { ok: false, why: "busy" };
+ // Never this machine: a server does not push this build over its own program directory
+ // while running from it. The synthetic row is the obvious case. An alias that points
+ // back home — `Host localhost`, a second name for this host — is the same machine at
+ // another address, and the id a probe once heard from it says so without any ssh; an
+ // alias never probed is asked inside the job, before anything is written.
+ if (machineId === LOCAL_MACHINE_ID) return { ok: false, why: "self" };
const alias = this.#effects.listAliases().find((entry) => `ssh:${entry}` === machineId);
if (alias === undefined) return { ok: false, why: "unknown-machine" };
+ if (this.repo.get(machineId)?.machineId === this.#machineId) return { ok: false, why: "self" };
const plan = this.#effects.resolvePlan(this.dataRoot);
if (plan === null) return { ok: false, why: "no-image" };
@@ -174,13 +318,28 @@ export class MachinesService {
// path does not turn into a `failed` outcome itself.
void (async () => {
try {
+ // The alias IS the target: what it means — user, host, port, key, jump host — is
+ // ssh's to resolve, from its own config, every time it is handed the alias.
+ const target = { alias, user: "" };
say(`Installing ${plan.version} on ${alias}…`);
+ // Asked before anything is written: only the machine can say whether this alias is
+ // this host under another name. Unreachable is not a refusal — a host with nothing
+ // installed yet answers exactly that — this server's own id is.
+ const heard = await this.#effects.probe(target, this.#effects.runOn, null);
+ this.#rememberMachineId(machineId, heard.machineId);
+ if (heard.machineId !== null && heard.machineId === this.#machineId) {
+ job.result = {
+ ok: false,
+ step: "connect",
+ message:
+ "That alias reaches this very machine — it answered with this server's own id. A server does not push this build over the program directory it is running from.",
+ };
+ return;
+ }
// 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({
- // The alias IS the target: what it means — user, host, port, key, jump host — is
- // ssh's to resolve, from its own config, every time it is handed the alias.
- target: { alias, user: "" },
+ target,
plan,
onProgress: say,
assets: this.#assets,
@@ -193,7 +352,11 @@ export class MachinesService {
// Remembered 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.repo.patch(machineId, { version, installedAt: this.#effects.now().toISOString() });
+ this.repo.patch(machineId, {
+ version,
+ installedAt: this.#effects.now().toISOString(),
+ platform: outcome.identity.platform,
+ });
this.#setMember(projectId, machineId, true);
job.result = { ok: true, kind: outcome.kind, version };
} catch (err) {
diff --git a/packages/server/test/database-read-only.test.ts b/packages/server/test/database-read-only.test.ts
new file mode 100644
index 00000000..311d6446
--- /dev/null
+++ b/packages/server/test/database-read-only.test.ts
@@ -0,0 +1,41 @@
+/**
+ * The read-only opener: what `penguin server status` reads a machine's database through.
+ * The point is not that the reader happens not to write — it is that it cannot.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { openDatabase, openDatabaseReadOnly } from "../src/db/database.js";
+
+describe("openDatabaseReadOnly", () => {
+ it("answers reads and refuses every write", () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-ro-"));
+ const file = path.join(dir, "web.db");
+ try {
+ openDatabase(file).close();
+ const db = openDatabaseReadOnly(file);
+ try {
+ expect(db.prepare("SELECT COUNT(*) AS n FROM machine").get()).toEqual({ n: 0 });
+ expect(() =>
+ db.exec("INSERT INTO machine (singleton, machine_id) VALUES (1, 'LNrJdHAZJ91G58i0')"),
+ ).toThrow(/readonly/);
+ } finally {
+ db.close();
+ }
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not create a database that is not there", () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-ro-"));
+ try {
+ const file = path.join(dir, "web.db");
+ expect(() => openDatabaseReadOnly(file)).toThrow();
+ expect(fs.existsSync(file)).toBe(false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.ts
index 7735698a..db35a7e3 100644
--- a/packages/server/test/machines-api.test.ts
+++ b/packages/server/test/machines-api.test.ts
@@ -32,6 +32,9 @@ import type { TestApp } from "./helpers.js";
/** Every route is under a Project now; the seeded one every server has. */
const PROJECT = "default_project";
+/** This machine's id. Minted from the `machine` table in the real server; fixed here. */
+const LOCAL_ID = "TESTlocalID00000";
+
const IDENTITY: RemoteIdentity = {
platform: "linux",
arch: "x64",
@@ -45,6 +48,9 @@ function effects(over: Partial<MachinesEffects> = {}): Partial<MachinesEffects>
listAliases: () => ["build-box", "nas"],
resolvePlan: () => ({ baseVersion: "9.9.9", harness: null, hmrDir: null, version: "9.9.9" }),
now: () => new Date("2026-08-24T12:00:00.000Z"),
+ // An install asks the machine who it is before writing anything; a host with nothing on
+ // it yet answers stopped with no id, which is the shape that refuses nothing.
+ probe: async () => ({ state: { kind: "stopped" as const }, machineId: null }),
install: async (opts): Promise<RemoteInstallOutcome> => {
opts.onProgress?.("Pushing…");
return { kind: "installed", output: "done", identity: IDENTITY };
@@ -77,7 +83,7 @@ describe("machines API", () => {
.run("default_project", "admin", "2026-08-24T00:00:00.000Z");
machinesRepo = new MachinesRepo(store);
t = await createTestApp({
- machines: new MachinesService(machinesRoot, machinesRepo, effects(over)),
+ machines: new MachinesService(machinesRoot, LOCAL_ID, machinesRepo, effects(over)),
});
admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
};
@@ -119,9 +125,30 @@ describe("machines API", () => {
const body = (await (
await admin.get(`/api/projects/${PROJECT}/machines`)
).json()) as MachinesResponse;
- expect(body.machines).toEqual([
- { id: "ssh:build-box", alias: "build-box", installed: null },
- { id: "ssh:nas", alias: "nas", installed: null },
+ // This machine leads the list: always present, always up, never a target.
+ expect(body.machines[0]).toMatchObject({
+ id: "local",
+ local: true,
+ machineId: LOCAL_ID,
+ status: { state: "running" },
+ });
+ expect(body.machines.slice(1)).toEqual([
+ {
+ id: "ssh:build-box",
+ alias: "build-box",
+ machineId: null,
+ installed: null,
+ local: false,
+ status: null,
+ },
+ {
+ id: "ssh:nas",
+ alias: "nas",
+ machineId: null,
+ installed: null,
+ local: false,
+ status: null,
+ },
]);
expect(body.imageVersion).toBe("9.9.9");
expect(body.job).toBeNull();
@@ -131,7 +158,8 @@ describe("machines API", () => {
await boot({ listAliases: () => [] });
const res = await admin.get(`/api/projects/${PROJECT}/machines`);
expect(res.status).toBe(200);
- expect(((await res.json()) as MachinesResponse).machines).toEqual([]);
+ // Not empty: this machine is always in the list, whatever the config says.
+ expect(((await res.json()) as MachinesResponse).machines.map((m) => m.id)).toEqual(["local"]);
});
it("reports no image when this server has none to push", async () => {
@@ -208,6 +236,51 @@ describe("machines API", () => {
});
});
+ it("an alias that points back at this machine is refused by the machine's own id, before anything is written", async () => {
+ // `Host localhost`, or a second alias for this host: the address is new to the store,
+ // so nothing recorded says "that is here" — only the machine can, and it does.
+ let installs = 0;
+ await boot({
+ probe: async () => ({
+ state: { kind: "running" as const, port: 7364, pid: 1 },
+ machineId: LOCAL_ID,
+ }),
+ install: async () => {
+ installs++;
+ return { kind: "installed", output: "", identity: IDENTITY };
+ },
+ });
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toMatchObject({
+ ok: false,
+ message: expect.stringContaining("this very machine"),
+ });
+ expect(installs).toBe(0);
+ expect(recordsInStore()).toEqual({});
+ });
+
+ it("records the platform the install found, and probes the machine in that dialect", async () => {
+ const dialects: (string | null)[] = [];
+ await boot({
+ install: async () => ({
+ kind: "installed",
+ output: "",
+ identity: { ...IDENTITY, platform: "win32" as const },
+ }),
+ probe: async (_target, _run, platform) => {
+ dialects.push(platform ?? null);
+ return { state: { kind: "stopped" as const }, machineId: null };
+ },
+ });
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(machinesRepo.get("ssh:nas")?.platform).toBe("win32");
+ // Before the install nothing was known (null); after it the probe speaks cmd.exe.
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+ expect(dialects).toEqual([null, "win32"]);
+ });
+
it("a throw from the push path still ends the job", async () => {
await boot({
install: () => {
@@ -247,7 +320,7 @@ describe("machines API", () => {
// 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, machinesRepo, effects());
+ const reborn = new MachinesService(machinesRoot, LOCAL_ID, machinesRepo, effects());
expect(reborn.job()).toBeNull();
expect(reborn.list(PROJECT).find((m) => m.id === "ssh:nas")?.installed).toEqual({
version: "9.9.9",
@@ -333,20 +406,140 @@ describe("machines API", () => {
});
await admin.post(`/api/projects/${PROJECT}/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);
+ expect((await listed()).filter((m) => !m.local).every((m) => m.installed === null)).toBe(
+ true,
+ );
+ expect(recordsInStore()).toEqual({});
});
+ });
- 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("asking the machines what they are doing", () => {
+ /** A machine that answers `penguin server status` with the JSON below. */
+ const answering = (o: Record<string, unknown>) =>
+ ({
+ probe: async () => {
+ const status = o as { running?: boolean; port?: number; pid?: number };
+ return {
+ state:
+ status.running === true
+ ? { kind: "running" as const, port: status.port!, pid: status.pid! }
+ : { kind: "stopped" as const },
+ machineId: (o.machineId as string | null) ?? null,
+ };
+ },
+ }) satisfies Partial<MachinesEffects>;
+
+ it("probes only the machines this Project installed on, and keeps the answer", async () => {
+ await boot(answering({ running: true, port: 7364, pid: 42, machineId: "LNrJdHAZJ91G58i0" }));
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ const body = (await (
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`)
+ ).json()) as MachinesResponse;
+ const nas = body.machines.find((m) => m.id === "ssh:nas");
+ expect(nas?.status).toMatchObject({ state: "running", port: 7364 });
+ // build-box was never installed on, so nothing was asked of it.
+ expect(body.machines.find((m) => m.id === "ssh:build-box")?.status).toBeNull();
+ });
+
+ it("remembers the id a machine answered, so later reads point at the machine", async () => {
+ await boot(answering({ running: true, port: 7364, pid: 42, machineId: "LNrJdHAZJ91G58i0" }));
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+
+ expect(machinesRepo.get("ssh:nas")?.machineId).toBe("LNrJdHAZJ91G58i0");
+ });
+
+ it("an alias repointed at another host answers a different id, and the newer one wins", async () => {
+ // An id never changes for a machine, so a change of id is a change of machine.
+ let answers = "first00000000000";
+ await boot({
+ probe: async () => ({
+ state: { kind: "running" as const, port: 7364, pid: 42 },
+ machineId: answers,
+ }),
+ });
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+ expect(machinesRepo.get("ssh:nas")?.machineId).toBe("first00000000000");
+ expect(machinesRepo.get("ssh:nas")?.version).not.toBeNull();
+
+ answers = "second0000000000";
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+ const row = machinesRepo.get("ssh:nas");
+ expect(row?.machineId).toBe("second0000000000");
+ // What the row knew was learned from the machine that is no longer at this address.
+ // Kept, the newcomer would read as already installed at a build it has never run —
+ // and an "already installed" record is exactly what suppresses the install that would
+ // have corrected it.
+ expect(row?.version).toBeNull();
+ expect(row?.installedAt).toBeNull();
+ expect(row?.platform).toBeNull();
+ expect(row?.remotePort).toBeNull();
+
+ const body = (await (
+ await admin.get(`/api/projects/${PROJECT}/machines`)
+ ).json()) as MachinesResponse;
+ expect(body.machines.find((m) => m.id === "ssh:nas")?.installed).toBeNull();
+ });
+
+ it("two probe requests at once share one round: each machine is asked once", async () => {
+ let probes = 0;
+ await boot({
+ probe: async () => {
+ probes++;
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ return { state: { kind: "stopped" as const }, machineId: null };
+ },
+ });
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ probes = 0;
+ // Two tabs, one Project: the second asker joins the round the first started.
+ await Promise.all([
+ admin.post(`/api/projects/${PROJECT}/machines/probe`),
+ admin.post(`/api/projects/${PROJECT}/machines/probe`),
+ ]);
+ expect(probes).toBe(1);
+ // A round that has settled is not reused: the next ask is a fresh one.
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+ expect(probes).toBe(2);
+ });
+
+ it("a machine with no server yet has no id, and says stopped rather than guessing", async () => {
+ await boot(answering({ running: false, machineId: null }));
+ await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await waitFor(() => t.deps.machines.job()?.running === false);
+
+ const body = (await (
+ await admin.post(`/api/projects/${PROJECT}/machines/probe`)
+ ).json()) as MachinesResponse;
+ const nas = body.machines.find((m) => m.id === "ssh:nas");
+ expect(nas?.status?.state).toBe("stopped");
+ expect(nas?.machineId).toBeNull();
});
});
describe("refusals decided before any ssh runs", () => {
+ it("409s an install through an alias a probe has already heard this machine's id from", async () => {
+ await boot();
+ machinesRepo.patch("ssh:nas", { machineId: LOCAL_ID });
+ const res = await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("self_install");
+ expect(t.deps.machines.job()).toBeNull();
+ });
+
+ it("409s an install onto the machine this server runs on", async () => {
+ await boot();
+ const res = await admin.post(`/api/projects/${PROJECT}/machines/local/install`);
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("self_install");
+ });
+
it("409s a second install while one is running", async () => {
let release = () => {};
const held = new Promise<void>((resolve) => {
diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.ts
index 4a7ffab6..a485cbbc 100644
--- a/packages/server/test/machines.test.ts
+++ b/packages/server/test/machines.test.ts
@@ -12,6 +12,11 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { machineIdentity, parseHostAliases } from "../src/machines/ssh-config.js";
+import {
+ parseProbe,
+ probeServerState,
+ readServerStateCommand,
+} from "../src/machines/server-state.js";
import { parseProbeOutput, POSIX_PROBE, WINDOWS_PROBE } from "../src/machines/detect.js";
import {
cmdQuote,
@@ -332,3 +337,111 @@ describe("shipping the installers", () => {
expect(fs.readFileSync(built, "utf8")).toBe(fs.readFileSync(source, "utf8"));
});
});
+
+describe("asking `penguin server status` in the machine's own dialect", () => {
+ const target = { alias: "nas", user: "deploy" };
+ const answered = {
+ code: 0,
+ stdout: `${JSON.stringify({ running: true, port: 7364, pid: 42, machineId: "LNrJdHAZJ91G58i0" })}\n`,
+ stderr: "",
+ timedOut: false,
+ };
+ // What cmd.exe says to `"$HOME/.penguin/node/bin/node"`: not "no such command", a path
+ // with four literal characters in it.
+ const cmdSaid = {
+ code: 1,
+ stdout: "The system cannot find the path specified.\r\n",
+ stderr: "",
+ timedOut: false,
+ };
+
+ it("speaks cmd.exe to a Windows machine: no $HOME, node.exe, backslashes", () => {
+ const command = readServerStateCommand("win32");
+ expect(command).toContain("%USERPROFILE%\\.penguin\\node\\node.exe");
+ expect(command).toContain("lib\\dist\\penguin-hmr.js");
+ expect(command).not.toContain("$HOME");
+ expect(readServerStateCommand("linux")).toContain("$HOME/.penguin/node/bin/node");
+ });
+
+ it("a machine whose platform is on record is asked once, in that dialect", async () => {
+ const asked: string[] = [];
+ const probe = await probeServerState(
+ target,
+ async (_t, command) => {
+ asked.push(command);
+ return answered;
+ },
+ "win32",
+ );
+ expect(asked).toHaveLength(1);
+ expect(asked[0]).toContain("%USERPROFILE%");
+ expect(probe.state).toMatchObject({ kind: "running", port: 7364 });
+ });
+
+ it("a machine whose platform is unknown is asked the POSIX way, then the Windows way", async () => {
+ const asked: string[] = [];
+ const probe = await probeServerState(
+ target,
+ async (_t, command) => {
+ asked.push(command);
+ return command.includes("%USERPROFILE%") ? answered : cmdSaid;
+ },
+ null,
+ );
+ expect(asked).toHaveLength(2);
+ expect(probe).toMatchObject({ state: { kind: "running" }, machineId: "LNrJdHAZJ91G58i0" });
+ });
+
+ it("when neither dialect answers, what the POSIX attempt heard is what is reported", async () => {
+ const refused = {
+ code: 255,
+ stdout: "",
+ stderr: "ssh: connect to host nas port 22: Connection refused",
+ timedOut: false,
+ };
+ const probe = await probeServerState(target, async () => refused, null);
+ expect(probe.state).toMatchObject({
+ kind: "unreachable",
+ detail: expect.stringContaining("Connection refused"),
+ });
+ });
+});
+
+describe("reading what `penguin server status` answered", () => {
+ const answer = (o: Record<string, unknown>) => JSON.stringify(o);
+
+ it("takes the state and the id out of the machine's own JSON", () => {
+ expect(
+ parseProbe(answer({ running: true, port: 7364, pid: 42, machineId: "LNrJdHAZJ91G58i0" })),
+ ).toEqual({ state: { kind: "running", port: 7364, pid: 42 }, machineId: "LNrJdHAZJ91G58i0" });
+ });
+
+ it("reads a machine with nothing serving, and one that has no id yet", () => {
+ expect(parseProbe(answer({ running: false, port: null, pid: null, machineId: null }))).toEqual({
+ state: { kind: "stopped" },
+ machineId: null,
+ });
+ });
+
+ it("finds the answer under a login shell's own banner", () => {
+ const said = `Welcome to build-box!\n{ not json }\n${answer({ running: false })}\n`;
+ expect(parseProbe(said).state).toEqual({ kind: "stopped" });
+ });
+
+ it("says it cannot tell rather than inventing a state out of a shape it does not know", () => {
+ // Neither of these is a state any machine reported; both would be made up on this side.
+ // A truthy string reads as up, and a claim of running carrying no port reads as down —
+ // the two directions this side could least afford to be wrong in.
+ const stringly = answer({ running: "false", port: 1, pid: 2 });
+ expect(parseProbe(stringly).state).toEqual({ kind: "unreachable", detail: stringly });
+ const portless = answer({ running: true, machineId: "LNrJdHAZJ91G58i0" });
+ expect(parseProbe(portless).state).toEqual({ kind: "unreachable", detail: portless });
+ });
+
+ it("says it cannot tell rather than 'stopped' when there is no answer at all", () => {
+ // A build too old for the subcommand prints an error. Reading that as a well-formed "no"
+ // would turn every such machine into a silently wrong one.
+ const said = "error: unknown command 'status'";
+ expect(parseProbe(said).state).toEqual({ kind: "unreachable", detail: said });
+ });
+});
diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.ts
index be4a85cc..21888b8a 100644
--- a/packages/server/tsup.config.ts
+++ b/packages/server/tsup.config.ts
@@ -20,6 +20,10 @@ export default defineConfig({
index: "src/index.ts",
"api/types": "src/api/types.ts",
lock: "src/lock.ts",
+ // "./machine-status": what `penguin server status` prints. A CONTROLLER runs that command
+ // over ssh to ask a machine what it is, so the reader has to be importable without a
+ // server — see src/machine-status.ts.
+ "machine-status": "src/machine-status.ts",
"initial-password": "src/initial-password.ts",
"reset-admin-password": "src/reset-admin-password.ts",
"auth-token": "src/auth-token.ts",
diff --git a/packages/web/src/features/machines/machines-page.tsx b/packages/web/src/features/machines/machines-page.tsx
index acc37646..b7d9a94d 100644
--- a/packages/web/src/features/machines/machines-page.tsx
+++ b/packages/web/src/features/machines/machines-page.tsx
@@ -124,7 +124,9 @@ export function MachinesPage() {
};
}, [running]);
- const machines = useMemo(() => state?.machines ?? [], [state]);
+ // The picker offers targets, and this machine is never one: a server does not push this
+ // build over the program directory it is running from (the API says 409 to the attempt).
+ const machines = useMemo(() => (state?.machines ?? []).filter((m) => !m.local), [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);
diff --git a/packages/web/src/features/machines/machines-view.ts b/packages/web/src/features/machines/machines-view.ts
index 9d72b55d..80329e5e 100644
--- a/packages/web/src/features/machines/machines-view.ts
+++ b/packages/web/src/features/machines/machines-view.ts
@@ -82,9 +82,11 @@ export function installButtonState(
* server can no longer resolve, let alone install to.
*/
export function installedMachines(state: MachinesResponse): MachineInfo[] {
+ // This machine is always installed and never a target: it is not a remote, so it is not
+ // in the list of remotes this server has put the program on.
return state.machines
.map((machine, index) => ({ machine, index }))
- .filter((entry) => entry.machine.installed != null)
+ .filter((entry) => !entry.machine.local && 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;
diff --git a/packages/web/test/machines-view.test.ts b/packages/web/test/machines-view.test.ts
index 3f1d24a0..edadbaa4 100644
--- a/packages/web/test/machines-view.test.ts
+++ b/packages/web/test/machines-view.test.ts
@@ -22,13 +22,19 @@ import {
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 => ({
+/** A remote row as the list answers it: no probe taken, no id heard yet. */
+const remote = (alias: string, installed: MachineInfo["installed"]): MachineInfo => ({
id: `ssh:${alias}`,
alias,
- installed: INSTALLED,
+ machineId: null,
+ installed,
+ local: false,
+ status: null,
});
+const fresh = (alias: string): MachineInfo => remote(alias, null);
+const carrying = (alias: string): MachineInfo => remote(alias, INSTALLED);
+
function response(
job: MachineInstallJob | null,
opts: { imageVersion?: string | null; machines?: MachineInfo[] } = {},
@@ -173,10 +179,10 @@ describe("installedMachines", () => {
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") },
+ remote("a", at("2026-08-20T00:00:00.000Z")),
+ remote("b", null),
+ remote("c", at("2026-08-24T00:00:00.000Z")),
+ remote("d", at("2026-08-22T00:00:00.000Z")),
];
expect(installedMachines(response(null, { machines })).map((m) => m.alias)).toEqual([
"c",
@@ -187,11 +193,7 @@ describe("installedMachines", () => {
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 machines: MachineInfo[] = [remote("x", same), remote("y", same), remote("z", same)];
const order = () => installedMachines(response(null, { machines })).map((m) => m.alias);
expect(order()).toEqual(["x", "y", "z"]);
expect(order()).toEqual(order());
@@ -199,11 +201,28 @@ describe("installedMachines", () => {
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") },
+ remote("a", at("2026-08-20T00:00:00.000Z")),
+ remote("c", at("2026-08-24T00:00:00.000Z")),
];
const state = response(null, { machines });
installedMachines(state);
expect(state.machines.map((m) => m.alias)).toEqual(["a", "c"]);
});
});
+
+describe("this machine in the list", () => {
+ /** The entry the server puts first: the host serving this page. */
+ const here = (): MachineInfo => ({
+ id: "local",
+ alias: "workstation",
+ machineId: "LNrJdHAZJ91G58i0",
+ installed: INSTALLED,
+ local: true,
+ status: { state: "running", checkedAt: INSTALLED.at, port: 7364 },
+ });
+
+ it("is never one of the installed remotes: there is nothing to reinstall from here", () => {
+ const listed = installedMachines(response(null, { machines: [here(), carrying("nas")] }));
+ expect(listed.map((m) => m.id)).toEqual(["ssh:nas"]);
+ });
+});