A local-first multi-agent app development platform, built on PenguinHarness
feat(machines): hand a machine this build over its own update channel (#576)
Myriad-Dreaminb5b21977116d
diff --git a/changelog/unreleased/2026-09-01-machines-update.md b/changelog/unreleased/2026-09-01-machines-update.mdnew file mode 100644index 00000000..45976968--- /dev/null+++ b/changelog/unreleased/2026-09-01-machines-update.md@@ -0,0 +1,47 @@+# Handing a machine this build, and restarting it onto what it has++- **Date:** 2026-09-01+- **Type:** feature+- **Scope:** `server`, `cli`+- **PR:** [#576](https://github.com/Prism-Shadow/penguin-harness/pull/576)++[中文版](2026-09-01-machines-update.zh.md)++A machine that already carries the right release but different pushed state is a **hot update, not an install**. It now goes over that machine's own update channel, which asks the machine and reports its answer — refusals included.++## Over the machine's own update channel++The machine is asked, and a runtime that cannot claim this platform **refuses in words** rather than falling back to its packaged default while the machine is recorded at a version it is not running. Its answer is read in full: a `blocked` outcome is a refusal, and a build the machine took but could not write to its disk is reported as such and not recorded — it is live now and gone at the machine's next restart.++A server that carries no pushed state of its own — a packaged install, a release from a tarball — hands nothing over: a machine already at that release is simply done.++The hand-over carries the platform, CLI and web bundles **and the native assets**: a platform resolves `node-pty` out of its assets directory and nowhere else, so a hand-over without them leaves every terminal on that machine unable to start. Exec bits travel with the files, and `spawn-helper` by name as well as by mode, because a Windows sender has no exec bit to read.++## Files are not the process++Installing replaces the program **on disk**. A server that was up is then restarted onto it, or it would report the new version and behave like the old one. A server that was **down is left down**: installing software is not a decision that the machine should be serving.++That is also why **Restart** is a control of its own — a machine's files can be brought forward while it runs (a replicated store, an install that already matched), and only a restart makes the process match them. The stop is checked: a start after a stop that did not happen finds the port still held, and a readiness probe that only asks "does a server answer" reads that as success.++The connection survives a restart: it is an ssh session to the host, not to the server process, and the server coming back on the same port is reachable through it as before. A restart that fails after an install is the job's outcome, with **Restart** as the next step — not a line in its log under a clean result.++## When the version already matches and the update still fails++The job comes back **offering** to install anyway (`replaceProgram`): the release over there matches, so the installer is skipped, and the only thing that can still change the machine is installing it regardless — which replicates the store the update channel needs. Offered rather than done, and never inferred: it stops a server other people may be using.++An App that boots also hands its build to every machine recorded at a different one, five at a time.++## `penguin server stop`++```bash+penguin server stop+# {"ok":true,"pid":41233}+```++Machine-facing, like `penguin server status`: a controller restarting a machine's server needs to stop it and know that it stopped, and asking the machine's own CLI keeps the answer on the side that has Node. A root nothing is serving answers `{"ok":true}` — the outcome asked for, not a failure.++There is deliberately **no SIGKILL**. A server that has not let go of its lock 15 seconds after SIGTERM is reported, with the port it still holds; it may be holding a database or finishing a task, and destroying that on a timeout is not a controller's call to make. Stopped means the process is gone or the lock is no longer its — a listener that has closed while the server drains is not yet stopped. A server this account cannot signal is reported, not called stopped. On Windows the command refuses: a signal there ends the process outright, which is the destruction it exists not to do.++## Details++The far-side scripts a build ships — the two release installers, the one thing that has to arrive before the CLI does — now come from one list (`scripts/far-side-scripts.mjs`), shared by the packaged build and the hot push. Two hand-kept copies had already drifted once.diff --git a/changelog/unreleased/2026-09-01-machines-update.zh.md b/changelog/unreleased/2026-09-01-machines-update.zh.mdnew file mode 100644index 00000000..0caea0f5--- /dev/null+++ b/changelog/unreleased/2026-09-01-machines-update.zh.md@@ -0,0 +1,47 @@+# 把这次构建交给一台机器,并让它重启到手上的东西上++- **Date:** 2026-09-01+- **Type:** feature+- **Scope:** `server`, `cli`+- **PR:** [#576](https://github.com/Prism-Shadow/penguin-harness/pull/576)++[English](2026-09-01-machines-update.md)++一台机器若已经带着正确的发行版、只是推送状态不同,那就是一次**热更新,而不是安装**。它现在走那台机器自己的更新通道,由通道去问机器,并把机器的回答如实报出来——拒绝也照报。++## 走机器自己的更新通道++由通道去问机器:无法认领此 platform 的运行时会**用话拒绝**,而不是回退到自带的默认版本、同时被记成一个它并没有在跑的版本。它的回答会被完整读取:`blocked` 是拒绝;机器接受了却写不进磁盘的构建会如实报告且不计入记录——它此刻在跑,下次重启就没了。++自身没有推送状态的服务端——打包安装、tarball 发行——没有东西可交接:发行版已经一致的机器直接算完成。++这次交接带的是 platform、CLI、web 三份 bundle**以及原生资产**:platform 只从自己的 assets 目录里解析 `node-pty`,别处都不看,所以少了它们的交接会让那台机器上的每一个终端都起不来。exec 位随文件一起过去,`spawn-helper` 除按模式外还按**名字**处理,因为 Windows 那侧根本没有 exec 位可读。++## 文件不等于进程++安装替换的是**磁盘上**的程序。原本在跑的服务端随后会被重启到新程序上,否则它会报出新版本、却按旧的行事。而原本**没在跑的就让它继续不跑**:装软件并不等于决定这台机器应当开始服务。++这也正是**重启**要成为一个独立操作的原因——一台机器的文件可以在它运行时被更新(复制过去的 store、一次版本本就相同的安装),而只有重启才能让进程与之相符。停止这一步是**要核实的**:在一次并没有发生的停止之后去启动,会发现端口仍被那个没死的进程占着,而只问「有没有服务端在应答」的就绪探测会把这读成成功。++连接在重启中得以保留:它是通往主机的 ssh 会话而非通往服务端进程,服务端在同一端口回来后照样经它可达。安装之后重启失败,是任务的结果、下一步是**重启**——而不是干净结果下面日志里的一行。++## 版本已经一致、更新却仍然失败时++任务会回来**提议**照装不误(`replaceProgram`):那边的发行版是一致的,所以安装器被跳过了,而此时唯一还能改变这台机器的动作,就是无论如何装一遍——因为安装会顺路把更新通道所需要的 store 复制过去。是提议而不是径直去做,且从不推断:它会停掉一个别人可能正在用的服务端。++App 启动时还会把自己的构建交给每一台记录版本不同的机器,并发 5。++## `penguin server stop`++```bash+penguin server stop+# {"ok":true,"pid":41233}+```++和 `penguin server status` 一样,它面向机器:控制端要重启一台机器的服务端,就需要停掉它并确知它停了,而去问机器自己的 CLI,能把这个答案留在有 Node 的那一侧。本来就没有东西在服务的数据根目录会得到 `{"ok":true}`——那正是调用者要的结果,不是失败。++这里刻意**不发 SIGKILL**。SIGTERM 之后 15 秒仍不放开锁的服务端会被如实报出来,并附上它仍占着的端口;它可能正握着一个数据库、或正在收尾一项任务,而在超时后销毁这些,不是一个控制端该替它做的决定。「已停止」指的是进程已经不在、或锁已不再属于它——服务端在收尾期间监听器先关掉,这还不算停止。本账户无法发信号的服务端会被如实报告,而不是当作已停止。在 Windows 上这条命令会拒绝执行:那里的信号会直接结束进程,恰恰是它存在的目的所要避免的破坏。++## 细节++一次构建要随身携带的「跑在别处」的脚本——两个发行版安装器,唯一必须在 CLI 之前到达的东西——现在来自同一份清单(`scripts/far-side-scripts.mjs`),打包构建与热推共用它。两份手工维护的副本已经飘移过一次了。diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.tsindex 5447064a..674b8cf8 100644--- a/packages/cli/src/commands/serve.ts+++ b/packages/cli/src/commands/serve.ts@@ -38,6 +38,7 @@ import type { Command } from "commander";import type { Messages, WebProbeFailureKind } from "../i18n.js";import { registerResetPasswordCommand } from "./reset-password.js";import { registerStatusCommand } from "./server-status.js";+import { registerStopCommand } from "./server-stop.js";/** Why the readiness poll gave up: failure class plus a one-line diagnostic from the last probe. */export interface ReadinessFailure {@@ -346,6 +347,7 @@ export function registerServeCommands(program: Command, t: Messages): void {// subcommand is named); the subcommand only dispatches on an exact name match.registerResetPasswordCommand(server, t);registerStatusCommand(server, t);+ registerStopCommand(server, t);program.command("web")diff --git a/packages/cli/src/commands/server-stop.ts b/packages/cli/src/commands/server-stop.tsnew file mode 100644index 00000000..2c19d50a--- /dev/null+++ b/packages/cli/src/commands/server-stop.ts@@ -0,0 +1,122 @@+/**+ * `penguin server stop` — stops the server on this data root, and answers in one line of JSON.+ *+ * Machine-facing, like `penguin server status`: a CONTROLLER runs it over ssh. It lives here+ * rather than as an HTTP call to the server itself because it has to work on a server whose+ * PLATFORM is older than this build — a machine mid-upgrade, which is exactly when something+ * needs stopping. A platform route can only be relied on once the machine already runs it,+ * and the reason it needs stopping is usually that it does not.+ *+ * A signal, not a shell `kill`: the controller has no portable way to send one (`kill` and+ * `taskkill` are different commands with different spellings), while `process.kill` is the+ * same call on every platform this runs on.+ * Docs: /docs/cli § "penguin server / penguin web".+ */+import { liveServerLock, readServerLock } from "@prismshadow/penguin-server/lock";+import type { Command } from "commander";+import type { Messages } from "../i18n.js";+import { resolveRootOption } from "../root-option.js";++/** How long a server that was signalled gets to let go of its lock. */+const STOP_TIMEOUT_MS = 15_000;++/**+ * What this command does to the world, injectable so a test can drive every outcome+ * without a server to signal: the signal itself, the liveness of a pid, the clock, and the+ * platform — Windows is where a signal is not what it says it is.+ */+export interface StopEffects {+ kill: (pid: number, signal: NodeJS.Signals | 0) => void;+ platform: NodeJS.Platform;+ now: () => number;+ sleep: (ms: number) => Promise<void>;+}++/** What the command prints. `ok` is the outcome; `pid` names what was signalled. */+interface StopResult {+ ok: boolean;+ pid?: number;+ detail?: string;+}++export function registerStopCommand(server: Command, t: Messages): void {+ server+ .command("stop")+ .description(t.serverStop.desc)+ .option("--root <dir>", t.common.root)+ .action(async (opts: { root?: string }) => {+ const result = await stop(resolveRootOption(opts.root));+ process.stdout.write(JSON.stringify(result) + "\n");+ if (!result.ok) process.exitCode = 1;+ });+}++const realEffects: StopEffects = {+ kill: (pid, signal) => process.kill(pid, signal),+ platform: process.platform,+ now: () => Date.now(),+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+};++/** The error code a signal came back with, or null for anything that is not one. */+function codeOf(err: unknown): string | null {+ const code = (err as NodeJS.ErrnoException | null)?.code;+ return typeof code === "string" ? code : null;+}++export async function stop(root: string, fx: StopEffects = realEffects): Promise<StopResult> {+ // Already stopped is the outcome asked for, not a failure: the caller wants nothing serving+ // this root, and nothing is.+ const lock = await liveServerLock(root);+ if (lock === null) return { ok: true };+ // On Windows a "SIGTERM" from Node is not delivered to anything: the process is ended+ // outright, which skips the drain this command exists to allow — the database, a task+ // mid-flight. Refused rather than performed as if it were the same thing.+ if (fx.platform === "win32") {+ return {+ ok: false,+ pid: lock.pid,+ detail:+ "a graceful stop cannot be signalled on Windows; stop the server from its own console.",+ };+ }+ try {+ fx.kill(lock.pid, "SIGTERM");+ } catch (err) {+ // ESRCH: gone between the read and the signal — again, the outcome asked for. Anything+ // else — EPERM above all — means a live server this account could not signal, and it is+ // still serving.+ if (codeOf(err) === "ESRCH") return { ok: true };+ return {+ ok: false,+ pid: lock.pid,+ detail: `it could not be signalled (${codeOf(err) ?? err})`,+ };+ }+ const deadline = fx.now() + STOP_TIMEOUT_MS;+ for (;;) {+ // Stopped means the PROCESS is gone, or the lock is no longer its. The listener closing+ // is neither: a server drains after it stops accepting — still holding the lock and the+ // database — and a restart started on the listener's word alone would open SQLite+ // beside a process that has not let go of it yet.+ let alive = true;+ try {+ fx.kill(lock.pid, 0);+ } catch (err) {+ alive = codeOf(err) === "EPERM";+ }+ if (!alive) return { ok: true, pid: lock.pid };+ const held = readServerLock(root);+ if (held === null || held.pid !== lock.pid) return { ok: true, pid: lock.pid };+ if (fx.now() >= deadline) {+ // Deliberately no SIGKILL: this server holds a database and may be finishing a task,+ // and a controller deciding to destroy that on a timeout is not its call to make.+ return {+ ok: false,+ pid: lock.pid,+ detail: `it still holds ${held.port} 15s after SIGTERM`,+ };+ }+ await fx.sleep(250);+ }+}diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex ad536b4b..bf766e9a 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -327,6 +327,10 @@ export interface Messages {/** One-line description in `penguin server --help`. */desc: string;};+ /** `penguin server stop`: help text. */+ serverStop: {+ desc: string;+ };resetPassword: {desc: string;/** Refusal while a live server owns the data root (stop it first, then retry). */@@ -850,6 +854,9 @@ const en: Messages = {serverStatus: {desc: "Print this data root's server state and machine id as one line of JSON",},+ serverStop: {+ desc: "Stop the server running on this data root and report the outcome as JSON",+ },resetPassword: {desc: "Reset the Web admin password to a fresh initial password (the server must be stopped)",serverRunning: (url) =>@@ -1360,6 +1367,9 @@ const zh: Messages = {serverStatus: {desc: "以单行 JSON 打印本数据根目录的服务状态与本机 id",},+ serverStop: {+ desc: "停止本数据根目录上运行的服务,并以 JSON 报告结果",+ },resetPassword: {desc: "把 Web 管理员密码重置为新的初始密码(须先停止服务)",serverRunning: (url) =>diff --git a/packages/cli/test/server-stop.test.ts b/packages/cli/test/server-stop.test.tsnew file mode 100644index 00000000..a1752ed8--- /dev/null+++ b/packages/cli/test/server-stop.test.ts@@ -0,0 +1,144 @@+/**+ * `penguin server stop` (commands/server-stop.ts): what "stopped" means, and what a signal+ * that did not land means. Driven with injected effects — the signal, the clock, the+ * platform — against a real lock file, so no server has to exist to be stopped.+ */+import fs from "node:fs";+import net from "node:net";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { stop } from "../src/commands/server-stop.js";+import type { StopEffects } from "../src/commands/server-stop.js";++/** A lock the liveness probe accepts: this process's pid, and a port that answers. */+async function liveRoot(): Promise<{ root: string; port: number; close: () => void }> {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-stop-"));+ const server = net.createServer();+ const port = await new Promise<number>((resolve) =>+ server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)),+ );+ fs.writeFileSync(+ path.join(root, "server.lock"),+ JSON.stringify({ pid: process.pid, port, startedAt: "2026-09-01T00:00:00.000Z" }),+ );+ return { root, port, close: () => server.close() };+}++/** An error the way process.kill raises one. */+const signalError = (code: string): NodeJS.ErrnoException =>+ Object.assign(new Error(code), { code });++/** Effects with a clock that jumps on every sleep, so a wait of 15s costs nothing. */+function effects(over: Partial<StopEffects>): StopEffects {+ let now = 0;+ return {+ kill: () => {},+ platform: "linux",+ now: () => now,+ sleep: async (ms) => {+ now += ms;+ },+ ...over,+ };+}++describe("penguin server stop", () => {+ let live: Awaited<ReturnType<typeof liveRoot>>;+ beforeEach(async () => {+ live = await liveRoot();+ });+ afterEach(() => {+ live.close();+ fs.rmSync(live.root, { recursive: true, force: true });+ });++ it("a root nothing is serving is already the outcome asked for", async () => {+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-stop-empty-"));+ try {+ expect(await stop(empty, effects({}))).toEqual({ ok: true });+ } finally {+ fs.rmSync(empty, { recursive: true, force: true });+ }+ });++ it("refuses on Windows: a signal there ends the process outright, which is the destruction it exists not to do", async () => {+ const sent: unknown[] = [];+ const result = await stop(+ live.root,+ effects({ platform: "win32", kill: (...a) => sent.push(a) }),+ );+ expect(result).toMatchObject({ ok: false, pid: process.pid });+ expect(result.detail).toContain("Windows");+ expect(sent).toEqual([]);+ });++ it("a server that could not be signalled is still serving — only ESRCH is 'already gone'", async () => {+ const denied = await stop(+ live.root,+ effects({+ kill: () => {+ throw signalError("EPERM");+ },+ }),+ );+ expect(denied).toMatchObject({ ok: false, pid: process.pid });+ expect(denied.detail).toContain("EPERM");++ const gone = await stop(+ live.root,+ effects({+ kill: () => {+ throw signalError("ESRCH");+ },+ }),+ );+ expect(gone).toEqual({ ok: true });+ });++ it("stopped means the process is gone or the lock is no longer its; a closed listener is not yet that", async () => {+ // On the signal the listener closes at once — as a draining server's does — while the+ // process lives on and the lock still names it. That is not stopped, and the command+ // keeps waiting until its deadline.+ const result = await stop(+ live.root,+ effects({+ kill: (_pid, signal) => {+ if (signal === "SIGTERM") live.close();+ },+ }),+ );+ expect(result).toMatchObject({ ok: false, pid: process.pid });+ expect(result.detail).toContain("still holds");+ });++ it("the process exiting is the stop", async () => {+ let signalled = false;+ const result = await stop(+ live.root,+ effects({+ kill: (_pid, signal) => {+ if (signal === "SIGTERM") {+ signalled = true;+ return;+ }+ // Liveness checks after the signal: the process is gone.+ if (signalled) throw signalError("ESRCH");+ },+ }),+ );+ expect(result).toEqual({ ok: true, pid: process.pid });+ });++ it("the lock changing hands is the stop too", async () => {+ const result = await stop(+ live.root,+ effects({+ kill: (_pid, signal) => {+ if (signal === "SIGTERM") fs.rmSync(path.join(live.root, "server.lock"));+ },+ }),+ );+ expect(result).toEqual({ ok: true, pid: process.pid });+ });+});diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex 3ddf3808..0e231740 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -332,6 +332,19 @@ penguin server reset-admin-passwordThe built-in `admin` is returned to the unclaimed state — a random password nobody ever sees, and every one of admin's sessions revoked. Start the server again and open the first-login link it prints to set a new password; nothing is written down in the meantime. Other accounts are reset by the admin on the user-management page; this command only touches `admin`. The data root is selected by `PENGUIN_HOME` as usual.+### penguin server stop++Stops the server on this data root and reports the outcome as one line of JSON:++```bash+penguin server stop+# {"ok":true,"pid":41233}+```++A `SIGTERM` and a wait, never a `SIGKILL`: the server holds a database and may be finishing a task, and a caller deciding to destroy that on a timeout is not its call to make. A root with nothing serving it answers `{"ok":true}` — that is the outcome asked for, not a failure.++The Machines page runs this over ssh when it restarts a machine. It is a command rather than a request to the server itself because the machine that needs stopping is usually the one whose platform is behind, and a platform route only exists once the machine already runs the build that has it.+## penguin versionReports which build is running. The version number alone cannot answer that — every build made from a checkout between two releases also calls itself `0.2.3` — so a release and a source build identify themselves differently.diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex de6dcf72..e5d26808 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -332,6 +332,19 @@ penguin server reset-admin-password内置 `admin` 会被恢复成未认领状态——密码随机生成且无人见过,admin 的全部会话一并吊销。重新启动服务,打开它打印的首次登录链接即可设置新密码;整个过程无需记下任何东西。其他账号由管理员在用户管理页重置,本命令只作用于 `admin`。数据根目录照常由 `PENGUIN_HOME` 决定。+### penguin server stop++停止本数据根目录上的服务,并以单行 JSON 报告结果:++```bash+penguin server stop+# {"ok":true,"pid":41233}+```++只发 `SIGTERM` 并等待,绝不 `SIGKILL`:那个服务端持有数据库、也可能正在收尾一个任务,调用方因为超时就决定销毁它,这不是它该做的决定。根目录上本来就没有服务在跑时答 `{"ok":true}`——那正是调用方要的结果,不是失败。++Machines 页面重启一台机器时通过 ssh 执行它。之所以是命令而不是发给那个服务端的请求:需要被停止的机器,往往正是平台版本落后的那一台,而平台路由只有在机器已经跑上带它的构建之后才存在。+## penguin version报告当前运行的是哪个构建。仅凭版本号回答不了这个问题——两次发布之间由源码 checkout 构建出来的每一个版本也都自称 `0.2.3`——因此发布版与源码构建给出的身份并不相同。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 71731a78..5d50764d 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -114,9 +114,10 @@ In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::| --- | --- | --- || 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 job: `{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, 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/install | Start installing this build on that host and give it to this Project; `202` with the same body, the job now running. Body `{replaceProgram: true}` answers a job that came back asking for it: install the program even though its version already matches, and restart it || POST | /api/projects/:projectId/machines/:machineId/connect | Bring that machine's server up and HOLD the one connection to it — an `ssh -T -D` session that never idles out, is re-established on its own if it drops, and is restored after a restart or a hot push; `202` with the same body, the connect job now running. A Windows machine is `409` `connect_unsupported`: there is no shell to hold a session on || POST | /api/projects/:projectId/machines/:machineId/disconnect | Drop the connection. The remote server is left running — it is that machine's own, and other people may be on it |+| POST | /api/projects/:projectId/machines/:machineId/restart | Stop that machine's server and start it again on the same port; `202`, or `409` while a job runs. Its own control because a machine's FILES can be brought forward while it runs, and only a restart makes the process match them || GET | /api/projects/:projectId/machines/:machineId/dirs?path= | The subdirectories of `path` on that machine, over the held connection — what the workspace picker browses. Addressed by the machine's OWN id, like the proxy. `404` when the machine is not connected: a read never opens ssh on its own || POST | /api/projects/:projectId/machines/:machineId/release | Drop that machine from this Project; the install on it stays |@@ -134,7 +135,7 @@ Admin only on a personal server as much as a multi-user one: the install spawnsA connected machine's API is reachable at `/server/<machineId>/api/…` on THIS origin, dialled through the one ssh session this server holds to it — a channel inside that session, via its SOCKS port, never a second connection. Addressed by the machine's own id rather than the ssh alias it was reached through: an alias lives in one config file, so keying on it would change a machine's URLs the moment someone renamed a host — and being base64url, an id needs no percent-encoding in a path. **Admin only**, and one identity: the request is made over there as that machine's admin, with a session this server mints through its own ssh access (`penguin auth token` on the machine) — the browser's cookies never cross, and the machine's never come back. Only `/api` is forwarded — the frontend stays local.-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). A connect (`POST …/connect`) is a job of the same shape, `job.kind` telling the two apart. `job.result` is `null` while running, then `{ok: true, installed: "installed" | "already-installed", version}` for an install, `{ok: true, connected: true}` for a connect, 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.+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). A connect (`POST …/connect`) and a restart (`POST …/restart`) are jobs of the same shape, `job.kind` (`install` / `connect` / `restart`) telling them apart. `job.result` is `null` while running, then `{ok: true, installed: "installed" | "already-installed", version}` for an install, `{ok: true, connected: true}` for a connect or a restart, or `{ok: false, step, message, canReplaceProgram?}` — `canReplaceProgram` marks a failure whose next step is installing the program anyway (`POST …/install` with `{replaceProgram: true}`), offered rather than done because it restarts a server other people may be using. 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`, and `409` `self_install` — this server will not push this build over the program directory it is running from. Besides the `local` row, that covers an alias pointing back home (`Host localhost`, a second name for this host) once a probe has heard this server's own id from it.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 561162bf..2618c7b0 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -114,9 +114,10 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \| --- | --- | --- || GET | /api/projects/:projectId/machines | 本机,加上**服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、每台最近一次探测到的状态、本服务端会安装的版本,以及正在运行或最近一次的任务:`{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, 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/install | 在该主机上安装当前构建,并把它归入本 Project;返回 `202` 与同样的响应体,此时任务已在运行。请求体 `{replaceProgram: true}` 用于回答任务给出的那个提议:即便版本已一致也照装不误,并重启它 || POST | /api/projects/:projectId/machines/:machineId/connect | 把该机器的服务端拉起来,并**持有**对它的那唯一一条连接——一个 `ssh -T -D` 会话,不会因空闲而关闭,断了会自行重建,服务端重启或热推之后也会恢复;返回 `202` 与同样的响应体,此时连接任务已在运行。Windows 机器返回 `409` `connect_unsupported`:那边没有可以持有会话的 shell || POST | /api/projects/:projectId/machines/:machineId/disconnect | 断开连接。远端服务端**保持运行**——那是那台机器自己的服务端,别人可能正在上面 |+| POST | /api/projects/:projectId/machines/:machineId/restart | 停止该机器的服务端并在同一端口重新启动;返回 `202`,若已有任务在跑则 `409`。它值得成为一个独立操作,是因为一台机器的**文件**可以在它运行时被更新,而只有重启才能让进程与之相符 || GET | /api/projects/:projectId/machines/:machineId/dirs?path= | 该机器上 `path` 的子目录,经由持有的连接读取——工作区选择器浏览的就是它。与代理一样,按机器**自身的 id** 寻址。机器未连接时返回 `404`:读取从不自行打开 ssh || POST | /api/projects/:projectId/machines/:machineId/release | 把该机器移出本 Project;机器上已安装的程序保持不动 |@@ -134,7 +135,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \已连接机器的 API 可通过本源上的 `/server/<machineId>/api/…` 访问,经由本服务端持有的那一条 ssh 会话拨达——是该会话内部的一个 channel(走它的 SOCKS 端口),从不是第二条连接。以机器自身的 id 而非它被访问时所用的 ssh 别名寻址:别名只存在于某一份配置文件中,若以它为键,一旦有人重命名主机,该机器的 URL 就会随之改变;而 id 是 base64url,放在路径中无需任何百分号编码。**仅限管理员**,且只有一个身份:请求在对端以那台机器的管理员身份发出,会话由本服务端通过自己的 ssh 权限铸造(在机器上执行 `penguin auth token`)——浏览器的 cookie 不会过去,机器的 cookie 也不会回来。只有 `/api` 会被转发——前端始终是本地的。-安装是任务而非请求:它要探测对端,可能下载并校验一份 Node 运行时,再经 scp 复制镜像——最坏情况以分钟计。`POST` 启动后立即返回,客户端轮询 `GET` 读取 `job.log`,其中是对端自己的原话(ssh 的诊断、远端安装器的输出)。连接(`POST …/connect`)是同一形状的任务,以 `job.kind` 区分。运行期间 `job.result` 为 `null`,结束后安装为 `{ok: true, installed: "installed" | "already-installed", version}`、连接为 `{ok: true, connected: true}`,失败为 `{ok: false, step, message}`。同一时刻只允许一个任务;任务存于内存,热推与重启都不保留,重跑即是恢复手段——每一步都是幂等的。+安装是任务而非请求:它要探测对端,可能下载并校验一份 Node 运行时,再经 scp 复制镜像——最坏情况以分钟计。`POST` 启动后立即返回,客户端轮询 `GET` 读取 `job.log`,其中是对端自己的原话(ssh 的诊断、远端安装器的输出)。连接(`POST …/connect`)与重启(`POST …/restart`)是同一形状的任务,以 `job.kind`(`install` / `connect` / `restart`)区分。运行期间 `job.result` 为 `null`,结束后安装为 `{ok: true, installed: "installed" | "already-installed", version}`、连接与重启为 `{ok: true, connected: true}`,失败为 `{ok: false, step, message, canReplaceProgram?}`——`canReplaceProgram` 标记一种下一步是「无论如何都安装程序」的失败(`POST …/install` 带 `{replaceProgram: true}`),只提供选项而不自动执行,因为它会重启一个别人可能正在用的服务端。同一时刻只允许一个任务;任务存于内存,热推与重启都不保留,重跑即是恢复手段——每一步都是幂等的。在任何 ssh 运行之前就能判定的拒绝各有错误码:`409` `install_running`、`404` `unknown_machine`、`409` `no_install_image`,以及 `409` `self_install`——本服务端不会把这份构建盖到自己正在运行的程序目录上。除 `local` 那一行之外,指回本机的别名(`Host localhost`、本机的第二个名字)一旦被探测到报出本服务端自己的 id,同样会被拒绝。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex fb150ac3..9b8a974b 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3370,7 +3370,8 @@ export interface MachineInfo {/*** 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.+ * answer and the page asks for a fresh one when it wants one — on a widening schedule,+ * since each probe is an ssh round trip while the list is only the config's text.*/status: MachineServerStatus | null;}@@ -3397,7 +3398,7 @@ export interface MachineServerStatus {* refused key or an unusable Node than a paraphrase would.*/export interface MachineJob {- kind: "install" | "connect";+ kind: "install" | "connect" | "restart";machineId: string;alias: string;running: boolean;@@ -3406,7 +3407,19 @@ export interface MachineJob {| null| { ok: true; installed: "installed" | "already-installed"; version: string | null }| { ok: true; connected: true }- | { ok: false; step: string; message: string };+ | {+ ok: false;+ step: string;+ message: string;+ /**+ * The failure has a next step this side can take, and it needs saying yes to:+ * installing the PROGRAM over there and restarting it. Set when a hot update could+ * not be handed over — the machine's store holds no CLI this server can talk to, and+ * installing is what replicates one. Offered rather than done, because it restarts a+ * server this Project does not own alone.+ */+ canReplaceProgram?: true;+ };}/** GET /api/machines, and the 202 body of POST /api/machines/:machineId/install. */diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.tsindex 84642561..75e9e42b 100644--- a/packages/server/src/hmr/host.ts+++ b/packages/server/src/hmr/host.ts@@ -130,7 +130,7 @@ export interface UpgradeAllTarget {* directory whose materialization was interrupted; no asset path can collide with it* (assets arrive as `node_modules/...` paths).*/-const MATERIALIZED = ".materialized";+export const MATERIALIZED = ".materialized";export type UpgradeOutcome =| {diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex 91257934..f28d75f9 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -226,9 +226,14 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {void deps.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {errors.record({ source: "process", err, code: "trace_adoption_failed" });});- // Machines: re-hold every connection the record says was held, starting a remote- // server that is down on the way. Fire-and-forget for the same reason: a host that is- // slow to answer must not hold up the App that serves everything else.+ // Machines, in one sweep (service.ts start()): a push here is a push everywhere, so+ // this App booting hands the same build on to any machine still carrying a different+ // one — cheap when there is nothing to do, since which machines are behind is read+ // from the install records, not asked over the network — and then re-holds every+ // connection the record says was held, starting a remote server that is down on the+ // way and handing each its Model config as it connects. Fire-and-forget for the same+ // reason as the adoption sweep: a host that is slow to answer must not hold up the+ // App that serves everything else.void deps.machines.start().catch((err: unknown) => {errors.record({ source: "process", err, code: "machines_reconnect_failed" });});@@ -255,6 +260,8 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {//// DELIVERED (survives the swap; the successor adopts it at load):// - pty sessions registry `terminal:*` + parked handle ids → terminals.adopt+ // - machine tunnels ssh children + machines-connect.json (pid/port) → adopted by+ // the successor's tunnelPortFor, which checks the pid is alive// - runtime singletons db / auth / channels / config / proxy / desktop —// runtime-owned, re-claimed by every App; not this App's to park// SUSPENDED (stopped here; the successor rebuilds it fresh at load):@@ -290,6 +297,9 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {let drained: Promise<void> | undefined;ctx.effect(() => {terminals.quiesce();+ // Forwards to machines are DELIVERED, not suspended: the ssh children are separate+ // processes that keep forwarding across the swap, and the successor adopts them by the+ // pid recorded in web.db (machines/service.ts).const drains: Promise<unknown>[] = [];if (business !== null) {business.scheduler.stop();diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.tsindex 4e0babbe..7661f221 100644--- a/packages/server/src/http/routes/machines.ts+++ b/packages/server/src/http/routes/machines.ts@@ -12,6 +12,7 @@* POST /:machineId/connect — bring that machine's server up and hold a tunnel to it; 202,* or 409 when a connect already runs.* POST /:machineId/disconnect — drop the tunnel (the remote server stays up).+ * POST /:machineId/restart — stop that machine's server and start it again; 202, or 409.* GET /:machineId/dirs?path= — browse that machine's directories over ssh.** Under a Project because the page is, and because this Project's Model credentials go to@@ -61,9 +62,13 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {});app.post("/:machineId/install", async (c) => {+ // `replaceProgram`: the answer to a job that came back asking for it (see the job's+ // canReplaceProgram). Read leniently — an absent body is the ordinary install.+ const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;const started = await deps.machines.startInstall(requireValidId(c, "projectId"),c.req.param("machineId"),+ body.replaceProgram === true,);if (!started.ok) {// Each refusal is its own code: the page renders a sentence per case, and "no image"@@ -151,6 +156,28 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {return c.json(state(c));});+ /**+ * Restarts that machine's server: stop, then start on the same port. What makes it worth a+ * control of its own is that a machine's FILES can be brought forward while it runs — a+ * replicated store, an install that matched — and only a restart makes the process match+ * them. 202, or 409 when a job already runs.+ */+ app.post("/:machineId/restart", async (c) => {+ const started = await deps.machines.startRestart(c.req.param("machineId"));+ if (!started.ok) {+ if (started.why === "busy")+ throw new HttpError(409, "job_running", "A job 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 === "self") {+ throw new HttpError(409, "self_restart", "That is the machine this server runs on.");+ }+ throw new HttpError(409, "not_installed", "Nothing is installed on that machine yet.");+ }+ return c.json(state(c), 202);+ });+app.post("/:machineId/disconnect", (c) => {deps.machines.disconnect(c.req.param("machineId"));return c.json(state(c));diff --git a/packages/server/src/lock.ts b/packages/server/src/lock.tsindex 71658d21..031d1bce 100644--- a/packages/server/src/lock.ts+++ b/packages/server/src/lock.ts@@ -30,14 +30,14 @@ export function serverLockPath(root: string): string {return path.join(root, "server.lock");}-/** Reads the lock file; a missing or malformed file reads as "no lock". */-export function readServerLock(root: string): ServerLock | null {- let raw: string;- try {- raw = fs.readFileSync(serverLockPath(root), "utf8");- } catch {- return null;- }+/**+ * The lock's text, parsed; anything that is not one reads as "no lock".+ *+ * Exported because a lock is also read where the file is not: a controller looking at+ * ANOTHER machine gets this same text back from an ssh `cat` (machines/server-state.ts). The+ * shape is defined once here so the two readers cannot drift apart.+ */+export function parseServerLock(raw: string): ServerLock | null {try {const parsed = JSON.parse(raw) as Partial<ServerLock>;if (@@ -54,6 +54,15 @@ export function readServerLock(root: string): ServerLock | null {}}+/** Reads the lock file; a missing or malformed file reads as "no lock". */+export function readServerLock(root: string): ServerLock | null {+ try {+ return parseServerLock(fs.readFileSync(serverLockPath(root), "utf8"));+ } catch {+ return null;+ }+}+function pidAlive(pid: number): boolean {try {process.kill(pid, 0);diff --git a/packages/server/src/machines/install-server.ts b/packages/server/src/machines/install-server.tsindex edcb0bef..33f00f39 100644--- a/packages/server/src/machines/install-server.ts+++ b/packages/server/src/machines/install-server.ts@@ -180,6 +180,14 @@ export async function detectRemote(export type RemoteInstallOutcome =| { kind: "already-installed"; version: string; identity: RemoteIdentity }+ /**+ * The base release over there already matches; only the pushed state differs. Nothing to+ * INSTALL — this is a hot update, and the machine has a channel for it that answers+ * (machines/upgrade.ts). The caller routes it there rather than this path copying the+ * store over and restarting the process, which replaces a running server without ever+ * asking whether it can run what it was handed.+ */+ | { kind: "state-only"; identity: RemoteIdentity }| { kind: "installed"; output: string; identity: RemoteIdentity }| { kind: "failed"; step: string; detail: string };@@ -198,6 +206,16 @@ export async function installOnRemote(opts: {assets?: () => string | null;/** The channel to the machine; a test hands in a scripted one. */channel?: MachineChannel;+ /**+ * Run the installer even when the release over there already matches.+ *+ * For the case the short-circuit below gets wrong: a machine whose PROGRAM is the right+ * version and whose hmr store this server cannot reach — an empty store, or one holding a+ * build that cannot receive an update. Nothing about the versions says so, so this is asked+ * for and never inferred. The installer replicates the store on its way through, which is+ * what puts the machine back within reach.+ */+ forceInstaller?: boolean;}): Promise<RemoteInstallOutcome> {const { target, plan } = opts;const conn = opts.channel ?? connectionTo(target);@@ -212,10 +230,20 @@ export async function installOnRemote(opts: {say(`${identity.platform}-${identity.arch}.`);}- const baseCurrent = identity.installedVersion === plan.baseVersion;+ const baseCurrent =+ identity.installedVersion === plan.baseVersion && opts.forceInstaller !== true;if (baseCurrent && identity.harness === plan.harness) {return { kind: "already-installed", version: plan.version, identity };}+ if (baseCurrent) {+ // Same release, different pushed state: a hot update, not an install. Handing it over+ // as files and restarting the process would swap the code under a server that may not+ // be able to claim it — a runtime older than the pushed platform warns, falls back to+ // its packaged default, and carries on serving, so the restart looks like a success+ // from here and the machine is recorded at a version it is not running. The update+ // channel asks the machine itself and comes back with its answer, refusals included.+ return { kind: "state-only", 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.diff --git a/packages/server/src/machines/server-control.ts b/packages/server/src/machines/server-control.tsindex 0a8b4955..a95b4d39 100644--- a/packages/server/src/machines/server-control.ts+++ b/packages/server/src/machines/server-control.ts@@ -1,16 +1,19 @@/**- * Starting the INSTALLED server on a remote machine.+ * Starting and stopping the INSTALLED server on a remote machine.*- * One command on the shared shell — `nohup penguin server … &` — and then the status probe,- * on that same shell, until the server answers. Neither costs a handshake.+ * A start is one command on the shared shell — `nohup penguin server … &` — and then the+ * status probe, on that same shell, until the server answers. A stop is a request to the+ * server's own shutdown endpoint, over the forward this side holds, then watching that port+ * go quiet. Neither costs a handshake.** The remote server is a plain `penguin server` process, never supervised from here. A* machine that reboots simply reads as "not running" on the next probe.*/-import { SERVER_LOG_TAIL, startServerCommand } from "./commands.js";+import { REMOTE_PENGUIN, SERVER_LOG_TAIL, startServerCommand } from "./commands.js";import type { RemoteTarget } from "./commands.js";import type { ExecResult } from "./transport/index.js";import { probeServerState } from "./server-state.js";+import { jsonAnswer } from "./answer.js";/** How long a freshly started server gets to answer on its port. */const START_TIMEOUT_MS = 30_000;@@ -40,3 +43,23 @@ export async function startRemoteServer(const tail = (await exec(target, SERVER_LOG_TAIL)).stdout.trim();return { ok: false, detail: tail || "it did not answer within 30s." };}++/**+ * Stops the remote server, over its own CLI.+ *+ * `penguin server stop` and not a request to the server itself: the machine that needs+ * stopping is usually the one whose PLATFORM is behind, and a platform route only exists+ * once it is already running the build that has it. The CLI comes from the store this side+ * pushed (commands.ts's REMOTE_PENGUIN), so it speaks the current protocol whatever the+ * running platform is.+ */+export async function stopRemoteServer(+ target: RemoteTarget,+ exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,+): Promise<{ ok: true } | { ok: false; detail: string }> {+ const result = await exec(target, `${REMOTE_PENGUIN} server stop 2>&1`);+ const answer = jsonAnswer<{ ok: boolean; detail?: string }>(result.stdout, "ok");+ if (answer?.ok === true) return { ok: true };+ const said = answer?.detail ?? result.stdout.trim();+ return { ok: false, detail: said === "" ? "the machine said nothing." : said };+}diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.tsindex 4c50d77c..899dfc6a 100644--- a/packages/server/src/machines/service.ts+++ b/packages/server/src/machines/service.ts@@ -43,18 +43,19 @@ import {listHostAliases,sessionOf,} from "./transport/index.js";-import type { MachineConnection, ShellSession } from "./transport/index.js";+import type { ExecResult, MachineConnection, ShellSession } from "./transport/index.js";import { machineIdentity } from "./ssh-config.js";import { DIR_LIST_MARK, listDirsCommand } from "./commands.js";import type { RemoteTarget } from "./commands.js";-import type { ExecResult } from "./transport/index.js";import { installOnRemote, resolvePushPlan } from "./install-server.js";import { probeServerState } from "./server-state.js";+import { upgradeRemote } from "./upgrade.js";+import type { UpgradeOutcome } from "./upgrade.js";import { mintTokenOnRemote } from "./remote-token.js";import { syncModelsToMachine } from "./models-sync.js";import type { LocalModels } from "./models-sync.js";import { machineApi } from "./machine-api.js";-import { startRemoteServer } from "./server-control.js";+import { startRemoteServer, stopRemoteServer } from "./server-control.js";import type { MachineRow, MachinesRepo } from "../db/repos/machines.js";/** Why an install was refused before any ssh ran. */@@ -83,6 +84,8 @@ export interface MachinesEffects {session: (address: string) => ShellSession | null;/** An http.Agent that dials that machine's server through its session. */agent: (target: RemoteTarget, remotePort: number) => http.Agent;+ stopServer: (target: RemoteTarget) => ReturnType<typeof stopRemoteServer>;+ upgrade: typeof upgradeRemote;/** This server's own Project config, credentials in plaintext — the source of a model sync. */loadConfig: (projectId: string) => Promise<ProjectConfig>;/** Injected so a test can pin the recorded timestamp instead of asserting around the clock. */@@ -153,6 +156,8 @@ export class MachinesService {hold: (target) => connectionTo(target).hold(),session: (address) => sessionOf(address),agent: (target, remotePort) => connectionTo(target).agent(remotePort),+ stopServer: (target) => stopRemoteServer(target, this.#effects.runOn),+ upgrade: upgradeRemote,loadConfig: (projectId) => loadProjectConfig(dataRoot, projectId),now: () => new Date(),...effects,@@ -552,6 +557,12 @@ export class MachinesService {async startInstall(projectId: string,address: string,+ /**+ * Install the program even when its version already matches, and restart it. Answers the+ * one failure that needs it (see the job's `canReplaceProgram`); never inferred, because+ * it stops a server other people may be using.+ */+ replaceProgram = false,): Promise<{ ok: true } | { ok: false; why: InstallRefusal }> {if (this.#job?.running === true) return { ok: false, why: "busy" };const machine = this.#allMachines().find((entry) => entry.id === address);@@ -588,19 +599,91 @@ export class MachinesService {plan,onProgress: say,assets: this.#assets,+ ...(replaceProgram ? { forceInstaller: true } : {}),});if (outcome.kind === "failed") {return { ok: false, step: outcome.step, message: outcome.detail };}+ // What the machine is, before anything below asks it again: the hand-over and the+ // restart both probe, and they should already speak its dialect.+ this.repo.patch(address, { platform: outcome.identity.platform });+ // A server that carries no pushed state of its own — a packaged install, a release+ // from a tarball — has nothing to hand over: what is on that machine is what this+ // server would have sent. The hand-over is for the machine whose PROCESS may be+ // behind its files, and that can only be so when there is a pushed build to be behind.+ if (outcome.kind !== "installed" && plan.harness === null) {+ say("Nothing pushed here to hand over; the machine already carries this release.");+ } else if (outcome.kind !== "installed") {+ // The PROGRAM over there is already this release — either with our pushed state+ // (`already-installed`) or without it (`state-only`). Either way what may still be+ // wrong is the PROCESS: a server runs the code it loaded at start, so a machine whose+ // files were brought forward while it ran goes on serving the older ones, reporting a+ // version it is not running. The update channel is what makes the two agree, and it+ // asks the machine itself, so a runtime that cannot claim this platform refuses in+ // words rather than restarting into a silent fallback.+ say("Handing this build to its own update channel…");+ const pushed = await this.#handOverBuild(address, target, say);+ if (pushed.kind === "no-server") {+ say("Its server is not running; this build will be used when it next starts.");+ } else if (pushed.kind !== "upgraded") {+ return {+ ok: false,+ step: "hand over the pushed build",+ message:+ pushed.kind === "no-build"+ ? "this server stands on no build to hand over."+ : pushed.kind === "refused"+ ? `that machine refused this build — ${pushed.detail}`+ : pushed.detail,+ // Every failure on THIS path leaves the same next step: the release over there+ // matches, so the installer is skipped, and the only thing that can still change+ // the machine is installing it anyway — which replicates the store the update+ // channel needs. Not offered for `no-build`, which is this server's own lack.+ ...(pushed.kind !== "no-build" && !replaceProgram+ ? { canReplaceProgram: true as const }+ : {}),+ };+ } else if (!pushed.persisted) {+ // Live over there, and gone at its next restart: the machine could not write the+ // version to its disk. Not recorded as this version — the record would be true+ // until the first restart and false ever after — and the same next step as a+ // refusal, since installing anyway is what rewrites the store on its disk.+ return {+ ok: false,+ step: "hand over the pushed build",+ message:+ "that machine is running this build but could not write it to its disk — it will revert at its next restart. Check its disk and permissions.",+ ...(replaceProgram ? {} : { canReplaceProgram: true as const }),+ };+ } else {+ say(pushed.detail === "" ? "Update accepted." : pushed.detail);+ }+ }const version = outcome.kind === "already-installed" ? outcome.version : plan.version;- this.repo.patch(address, {- version,- installedAt: this.#effects.now().toISOString(),- platform: outcome.identity.platform,- });+ // Installing replaced the program ON DISK; a server that was up is restarted onto it,+ // or it would report the new version and behave like the old one.+ const restarted =+ outcome.kind === "installed"+ ? await this.#restartAfterInstall(address, target, say)+ : { ok: true as const };+ // The files landed whatever the restart did: the record says what is on its disk, and+ // membership says whose machine it is. A restart that failed is the job's outcome, not+ // a footnote in its log — the page shows it, with Restart as the next step.+ this.repo.patch(address, { version, installedAt: this.#effects.now().toISOString() });// The Project that asked for the install is the Project that gets the machine.this.#setMember(projectId, address, true);- return { ok: true, installed: outcome.kind, version };+ if (!restarted.ok) {+ return {+ ok: false,+ step: "restart its server",+ message: `installed, but ${restarted.detail} The old process is still serving; restart it.`,+ };+ }+ return {+ ok: true,+ installed: outcome.kind === "state-only" ? "installed" : outcome.kind,+ version,+ };});return { ok: true };}@@ -640,10 +723,16 @@ export class MachinesService {const probed = await this.#probe(address, target);this.#recordProbe(address, probed);if (probed.state.kind === "unreachable") {- // Reported in the machine's own words: OpenSSH's diagnostic, or the CLI's. What to do- // about a machine whose store holds no CLI this server can talk to is a later problem- // — this one is honest about not having reached it.- return { ok: false, step: "connect", message: probed.state.detail };+ // The same dead end an install reaches, and the same way out: the machine cannot+ // answer because the CLI in its store is not one this server can talk to, and the+ // installer is what replaces it. Offered here too — a connect that only reports+ // OpenSSH's or commander's words leaves a person with nothing to do next.+ return {+ ok: false,+ step: "connect",+ message: probed.state.detail,+ canReplaceProgram: true,+ };}// The refusal startConnect made from the record, made again from what was just heard: an// alias never probed before, or one repointed here since, answers this server's own id@@ -703,6 +792,11 @@ export class MachinesService {* slow to answer must not hold up the App that serves everything else.*/async start(): Promise<void> {+ // The build first, the connections second: a machine behind this build is brought+ // forward over a transient session and its server restarted, and only then re-held —+ // so the connection that stays is to the server that will keep running, and the Model+ // config handed over as it connects lands on the build that will read it.+ await this.syncOutOfDate();await this.autoConnect();}@@ -803,6 +897,128 @@ export class MachinesService {};}+ /** Hands a machine this server's pushed build, through the connection held to it. */+ async #handOverBuild(+ address: string,+ target: RemoteTarget,+ say: (line: string) => void,+ ): Promise<UpgradeOutcome> {+ const probed = await this.#effects.probe(+ target,+ this.#effects.runOn,+ this.repo.get(address)?.platform ?? null,+ );+ if (probed.state.kind === "unreachable") {+ return { kind: "failed", step: "reach", detail: probed.state.detail };+ }+ // A hot swap replaces the code a RUNNING server is serving; with none there is nothing+ // to swap, and nothing wrong either — its disk already holds what it will next load.+ if (probed.state.kind !== "running") return { kind: "no-server" };+ // A dial, not a hold: the agent below opens the session transiently if it is not up,+ // and a machine that was merely installed on is not made a held one by being brought+ // forward at boot — only a connect asks for that.+ const port = probed.state.port;+ this.repo.patch(address, { remotePort: port });+ const session = await this.#sessionOn(target);+ if (!("cookie" in session)) return { kind: "failed", step: "sign in", detail: session.detail };+ return this.#effects.upgrade({+ agent: this.#effects.agent(target, port),+ port,+ cookie: session.cookie,+ dataRoot: this.dataRoot,+ onProgress: say,+ });+ }++ /**+ * Stops a machine's server and starts it again on the same port, so what runs there is+ * what is on its disk.+ *+ * The stop is CHECKED. A start after a stop that did not happen finds the port still held+ * by the process that never died, and the readiness probe — which only asks whether a+ * server answers — reads that as success: the machine then reports a version it is not+ * running, which is the one outcome every guard on this path exists to prevent.+ */+ async #restartServer(+ address: string,+ target: RemoteTarget,+ say: (line: string) => void,+ ): Promise<{ ok: true; port: number } | { ok: false; detail: string }> {+ const before = await this.#effects.probe(+ target,+ this.#effects.runOn,+ this.repo.get(address)?.platform ?? null,+ );+ if (before.state.kind === "unreachable") return { ok: false, detail: before.state.detail };+ if (before.state.kind !== "running") {+ return { ok: false, detail: "no server is running on that machine." };+ }+ const port = before.state.port;+ say(`Stopping its server on port ${port}…`);+ const stopped = await this.#effects.stopServer(target);+ if (!stopped.ok) return { ok: false, detail: `it would not stop — ${stopped.detail}` };+ // Its sessions died with it. The connection did not: it is an ssh session to the HOST,+ // and the server coming back on the same port is reachable through it as before.+ this.#sessions.delete(address);+ say(`Starting it again on port ${port}…`);+ const started = await this.#effects.startServer(target, port);+ if (!started.ok) {+ return { ok: false, detail: `its server did not come back up: ${started.detail}` };+ }+ // It is a different process now, and possibly one with an identity it did not have a+ // moment ago: a machine mints its id when a server that mints one starts there.+ await this.#refreshStatus(address, target);+ this.repo.patch(address, { remotePort: port });+ return { ok: true, port };+ }++ /**+ * Restarts a machine's server as a job — the same shape as an install or a connect, and+ * for the same reason: a stop plus a readiness wait is tens of seconds.+ */+ async startRestart(address: string): Promise<{ ok: true } | { ok: false; why: ConnectRefusal }> {+ if (this.#job?.running === true) return { ok: false, why: "busy" };+ const machine = this.#allMachines().find((entry) => entry.id === address);+ if (machine === undefined) return { ok: false, why: "unknown-machine" };+ if (machine.local) return { ok: false, why: "self" };+ if (machine.installed === null) return { ok: false, why: "not-installed" };+ this.#startJob("restart", machine, async (say) => {+ const target = this.#targetOf(machine.alias);+ const done = await this.#restartServer(address, target, say);+ if (!done.ok) return { ok: false, step: "restart", message: done.detail };+ say(`Restarted on port ${done.port}.`);+ return { ok: true, connected: true };+ });+ return { ok: true };+ }++ /**+ * Puts a freshly installed build into service. Only for a machine whose server was already+ * running: one that was down is left down — installing software is not a decision that the+ * machine should be serving.+ */+ async #restartAfterInstall(+ address: string,+ target: RemoteTarget,+ say: (line: string) => void,+ ): Promise<{ ok: true } | { ok: false; detail: string }> {+ const before = await this.#effects.probe(+ target,+ this.#effects.runOn,+ this.repo.get(address)?.platform ?? null,+ );+ if (before.state.kind !== "running") {+ say("Its server was not running; the new build will be used when it next starts.");+ return { ok: true };+ }+ const done = await this.#restartServer(address, target, say);+ if (done.ok) {+ say(`Restarted on port ${done.port}.`);+ return { ok: true };+ }+ return { ok: false, detail: done.detail };+ }+// --- the automatic sweeps, run when an App boots ----------------------------------------------/** Runs `work` with this machine's slot held, or returns null when it is already busy. */@@ -834,6 +1050,27 @@ export class MachinesService {await Promise.all(workers);}+ /** Hands this server's build to every machine carrying a different one. */+ async syncOutOfDate(): Promise<void> {+ const plan = this.#effects.resolvePlan(this.dataRoot);+ if (plan === null) return;+ const behind = this.repo+ .all()+ .filter((row) => row.version !== null && row.version !== plan.version)+ .map((row) => row.address);+ await this.#sweep(behind, async (address, target) => {+ const outcome = await this.#handOverBuild(address, target, () => {});+ // Recorded only when the machine also wrote it down: a swap it could not persist is+ // gone at its next restart, and a record of it would outlive the thing it records.+ if (outcome.kind === "upgraded" && outcome.persisted) {+ this.repo.patch(address, {+ version: plan.version,+ installedAt: this.#effects.now().toISOString(),+ });+ }+ });+ }+/** Re-holds every machine recorded as held that this generation does not yet hold. */async autoConnect(): Promise<void> {const unconnected = this.#allMachines().filter(diff --git a/packages/server/src/machines/upgrade.ts b/packages/server/src/machines/upgrade.tsnew file mode 100644index 00000000..fc0b4d9c--- /dev/null+++ b/packages/server/src/machines/upgrade.ts@@ -0,0 +1,216 @@+/**+ * Sending THIS server's hot-pushed build to a machine, and applying it there.+ *+ * The same three artifacts the local server was pushed — platform, cli, web (plus any native+ * assets) — are re-packed into the body `/api/hmr/upgrade` takes and POSTed to the machine's+ * OWN copy of that endpoint, through the connection this side holds to it. What the far side+ * answers is the endpoint's own JSON, with its own error codes, exactly as the local push+ * reads it.+ *+ * The result is a hot swap: seconds, no restart, and nothing that machine was running dies.+ * That is the difference between this and reinstalling, which replaces the program on disk+ * and needs the server bounced to take effect.+ */+import fs from "node:fs";+import http from "node:http";+import path from "node:path";+import zlib from "node:zlib";+import { machineApi } from "./machine-api.js";+import { MATERIALIZED } from "../hmr/host.js";++/** Long enough for 8 MB over a slow link, plus the unpack, boot and commit on the far side. */+const APPLY_TIMEOUT_MS = 10 * 60_000;++export type UpgradeOutcome =+ /**+ * The machine took the build and is running it. `persisted` is its own word on whether the+ * version was also written to its disk: false means live now and gone at its next restart+ * (host.ts's persistVersion), which is not the same fact as upgraded, and is not recorded+ * as one.+ */+ | { kind: "upgraded"; detail: string; persisted: boolean }+ /** The machine answered, and said no — a refused body, a runtime that cannot take it. */+ | { kind: "refused"; detail: string }+ /** Nothing to send: this server has never been pushed to. */+ | { kind: "no-build" }+ /**+ * Nothing to update: no server is running over there. A hot swap replaces the code a+ * RUNNING server is serving, so this is not a failure — whatever is on its disk is what it+ * will load when it next starts.+ */+ | { kind: "no-server" }+ /** Could not reach it, or it never answered; `detail` is its own words where there are any. */+ | { kind: "failed"; step: string; detail: string };++/**+ * The upgrade body, rebuilt from this server's own hmr store: exactly what it was pushed,+ * forwarded unchanged — the native assets and the provenance included. Null when nothing has+ * been pushed here — a server running its packaged build has no bundle to hand on.+ *+ * The assets are not optional in practice: a pushed platform resolves node-pty out of its+ * assets directory and nowhere else (terminal/pty-module.ts), so a hand-over that dropped+ * them left the machine on a build whose every terminal failed with "no assets directory+ * available" — while the same build pushed by deploy.mjs worked. Exec bits come from the+ * files' modes, which the receiving host restores from the `exec` list.+ */+export function readPushedBuild(dataRoot: string): Buffer | null {+ try {+ const hmrDir = path.join(dataRoot, "hmr");+ const manifest = JSON.parse(fs.readFileSync(path.join(hmrDir, "harness.json"), "utf8")) as {+ platform?: { bundle?: string };+ cli?: { bundle?: string };+ web?: { manifest?: string };+ assets?: { dir?: string };+ source?: { repo?: string; revision?: string };+ };+ if (+ typeof manifest.platform?.bundle !== "string" ||+ typeof manifest.cli?.bundle !== "string" ||+ typeof manifest.web?.manifest !== "string"+ ) {+ return null;+ }+ const platform = fs.readFileSync(path.join(hmrDir, manifest.platform.bundle), "utf8");+ const cli = fs.readFileSync(path.join(hmrDir, manifest.cli.bundle), "utf8");+ // The web artifact is stored as gzip(JSON.stringify({ files })) — the same shape the+ // upgrade body carries, so it is unwrapped once here rather than re-encoded.+ const web = JSON.parse(+ zlib.gunzipSync(fs.readFileSync(path.join(hmrDir, manifest.web.manifest))).toString("utf8"),+ ) as { files: Record<string, string> };+ const assets =+ typeof manifest.assets?.dir === "string"+ ? readAssets(path.join(hmrDir, manifest.assets.dir))+ : undefined;+ const source =+ typeof manifest.source?.repo === "string" && typeof manifest.source.revision === "string"+ ? { repo: manifest.source.repo, revision: manifest.source.revision }+ : undefined;+ return zlib.gzipSync(+ Buffer.from(+ JSON.stringify({+ platform,+ cli,+ web,+ ...(assets ? { assets } : {}),+ ...(source ? { source } : {}),+ }),+ ),+ );+ } catch {+ return null; // No store, a partial record, or damage: nothing safe to forward.+ }+}++/** A materialized assets directory back into the shape it was pushed as. */+function readAssets(dir: string): { files: Record<string, string>; exec: string[] } {+ const files: Record<string, string> = {};+ const exec: string[] = [];+ for (const entry of fs.readdirSync(dir, { recursive: true, withFileTypes: true })) {+ if (!entry.isFile() || entry.name === MATERIALIZED) continue;+ const abs = path.join(entry.parentPath, entry.name);+ const rel = path.relative(dir, abs).split(path.sep).join("/");+ files[rel] = fs.readFileSync(abs).toString("base64");+ // The mode where the filesystem keeps one; by name where it cannot. A Windows machine has+ // no exec bit to read, and a hand-over from it would otherwise strip the bit off+ // node-pty's darwin spawn-helper — the one file whose bit decides whether a terminal+ // starts on the macOS machine receiving it. deploy.mjs applies the same rule on push.+ if (rel.endsWith("/spawn-helper") || (fs.statSync(abs).mode & 0o111) !== 0) exec.push(rel);+ }+ return { files, exec };+}++/** The machine's own words for a refusal: the API error envelope's message, else the text. */+export function refusalDetail(status: number, text: string): string {+ try {+ const body = JSON.parse(text) as { error?: { message?: string } };+ const message = body.error?.message;+ if (typeof message === "string" && message !== "") return message;+ } catch {+ // Not the API's error envelope; the text itself is the best there is.+ }+ const said = text.trim();+ return said === "" ? `it refused with ${status} and said nothing` : said;+}++/** Applies this server's build on the machine reachable at `port`. Never throws. */+export async function upgradeRemote(opts: {+ /** A dial through the machine's connection, and its server's port over there. */+ agent: http.Agent;+ port: number;+ /** A session on that machine, as its own cookie (`penguin_session=…`). */+ cookie: string;+ dataRoot: string;+ onProgress?: (line: string) => void;+}): Promise<UpgradeOutcome> {+ const payload = readPushedBuild(opts.dataRoot);+ if (payload === null) return { kind: "no-build" };+ opts.onProgress?.(`Sending this build (${(payload.byteLength / 1048576).toFixed(1)} MB)…`);+ let answer: { status: number; text: string };+ try {+ answer = await machineApi(opts.agent, opts.port, opts.cookie).postBytes(+ "/api/hmr/upgrade",+ "application/gzip",+ payload,+ APPLY_TIMEOUT_MS,+ );+ } catch (err) {+ return {+ kind: "failed",+ step: "apply",+ detail: (err instanceof Error ? err.message : String(err)).slice(0, 400),+ };+ }+ return classifyUpgradeAnswer(answer.status, answer.text);+}++/**+ * What the endpoint's answer means. A refusal is an ANSWER: the machine was reached and said+ * no, which is not the same as failing to reach it, and the page offers different things for+ * the two. And a 2xx is not yet a yes: `/api/hmr/upgrade` answers 200 for `blocked` — the+ * running version kept serving, the body names what would have been discarded — so clients+ * keep one parsing path (hmr/routes.ts), and scripts/deploy.mjs reads it the same way.+ */+export function classifyUpgradeAnswer(status: number, text: string): UpgradeOutcome {+ if (status < 200 || status >= 300) {+ return { kind: "refused", detail: refusalDetail(status, text).slice(0, 400) };+ }+ let body: {+ status?: unknown;+ persisted?: unknown;+ dropped?: unknown;+ missing?: unknown;+ invalid?: unknown;+ };+ try {+ body = JSON.parse(text) as typeof body;+ } catch {+ return {+ kind: "refused",+ detail: `it answered ${status} with something that is not its outcome: ${text.trim().slice(0, 200)}`,+ };+ }+ if (body.status === "blocked") {+ const names = (key: "dropped" | "missing" | "invalid") =>+ Array.isArray(body[key]) && body[key].length > 0+ ? `${key}: ${(body[key] as string[]).join(", ")}`+ : null;+ const why = [names("missing"), names("invalid"), names("dropped")]+ .filter((s) => s !== null)+ .join("; ");+ return {+ kind: "refused",+ detail: `it kept its current version${why === "" ? "" : ` — ${why}`}`.slice(0, 400),+ };+ }+ if (body.status !== "ok") {+ return {+ kind: "refused",+ detail: `it answered ${status} with an outcome this build does not know: ${text.trim().slice(0, 200)}`,+ };+ }+ return {+ kind: "upgraded",+ detail: text.trim().slice(0, 400),+ persisted: body.persisted !== false,+ };+}diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.tsindex c650f393..19d227cc 100644--- a/packages/server/test/machines-api.test.ts+++ b/packages/server/test/machines-api.test.ts@@ -47,6 +47,18 @@ const IDENTITY: RemoteIdentity = {/** Addresses the fake transport holds a session to. */const connected = new Set<string>();+/**+ * A plan with pushed state of its own: what a hot-pushed controller carries, and the only+ * shape under which an install can come back `state-only` — the release matches, the pushed+ * state does not — and the hand-over has something to hand over.+ */+const PUSHED_PLAN = {+ baseVersion: "9.9.9",+ harness: '{"platform":{"bundle":"store/platform/cafe.mjs"}}',+ hmrDir: "/nonexistent",+ version: "9.9.9+hmr.cafe",+};+/** 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 {@@ -54,6 +66,8 @@ function effects(over: Partial<MachinesEffects> = {}): Partial<MachinesEffects>resolvePlan: () => ({ baseVersion: "9.9.9", harness: null, hmrDir: null, version: "9.9.9" }),now: () => new Date("2026-08-24T12:00:00.000Z"),startServer: async () => ({ ok: true }),+ stopServer: async () => ({ ok: true as const }),+ upgrade: async () => ({ kind: "upgraded", detail: "", persisted: true }),runOn: async () => ({code: 0,stdout: "---penguin-auth-token---\nremote-token\n",@@ -294,9 +308,11 @@ describe("machines API", () => {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.+ // Before the install nothing was known (null). The install records what it found+ // before the restart asks the machine again, so that probe and the explicit one after+ // both speak cmd.exe.await admin.post(`/api/projects/${PROJECT}/machines/probe`);- expect(dialects).toEqual([null, "win32"]);+ expect(dialects).toEqual([null, "win32", "win32"]);});it("re-running an install keeps the machine id the record already carried", async () => {@@ -313,6 +329,140 @@ describe("machines API", () => {expect(machinesRepo.get("ssh:nas")?.machineId).toBe("kUkIyqU-1GOfXgKD");});+ it("a machine that refuses this build says so, instead of reporting an install", async () => {+ await boot({+ resolvePlan: () => PUSHED_PLAN,+ install: async () => ({ kind: "state-only", identity: IDENTITY }),+ upgrade: async () => ({+ kind: "refused",+ detail: "this runtime publishes no business capabilities this platform can claim",+ }),+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toMatchObject({+ ok: false,+ step: "hand over the pushed build",+ // The release over there matches, so the installer is skipped and nothing else can+ // change that machine: installing anyway is the one step left, and it needs a yes.+ canReplaceProgram: true,+ });+ expect((t.deps.machines.job()?.result as { message: string }).message).toContain(+ "no business capabilities",+ );+ });++ it("a machine with nothing running on it is done, not failed — its disk already has this", async () => {+ // A hot swap replaces the code a RUNNING server is serving. With none there is nothing+ // to swap and nothing wrong: the files are in place for its next start.+ let asked = false;+ await boot({+ probe: async () => ({ state: { kind: "stopped" }, machineId: null }),+ resolvePlan: () => PUSHED_PLAN,+ install: async () => ({ kind: "state-only", identity: IDENTITY }),+ upgrade: async () => {+ asked = true;+ return { kind: "upgraded", detail: "", persisted: true };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);++ expect(asked).toBe(false);+ expect(t.deps.machines.job()?.result).toMatchObject({ ok: true });+ expect(t.deps.machines.job()?.log.join(" ")).toContain("next starts");+ });++ it("a machine already carrying this build still gets it handed over: files are not the process", async () => {+ // `already-installed` is decided from what is on its disk. What runs there is what it+ // loaded at start — so a machine whose files were brought forward while it ran reports+ // a version it is not running until the update channel makes the two agree.+ let asked = false;+ await boot({+ // This server carries a pushed state of its own: there is something to hand over.+ resolvePlan: () => ({+ baseVersion: "9.9.9",+ harness: '{"platform":{"bundle":"store/platform/cafe.mjs"}}',+ hmrDir: "/nonexistent",+ version: "9.9.9+hmr.cafe",+ }),+ install: async () => ({+ kind: "already-installed",+ version: "9.9.9+hmr.cafe",+ identity: IDENTITY,+ }),+ upgrade: async () => {+ asked = true;+ return { kind: "upgraded", detail: "", persisted: true };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);++ expect(asked).toBe(true);+ expect(t.deps.machines.job()?.result).toMatchObject({+ ok: true,+ installed: "already-installed",+ });+ });++ it("a server with nothing pushed to it hands nothing over: a matching machine is simply done", async () => {+ // A packaged install has no pushed state (plan.harness === null) and readPushedBuild+ // would answer no-build. The former no-op must stay one, not become a failed job with+ // an offer to reinstall a machine that already matches.+ let asked = false;+ await boot({+ install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),+ upgrade: async () => {+ asked = true;+ return { kind: "no-build" };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(asked).toBe(false);+ expect(t.deps.machines.job()?.result).toMatchObject({+ ok: true,+ installed: "already-installed",+ });+ expect(t.deps.machines.job()?.log.join(" ")).toContain("Nothing pushed here");+ });++ it("a build the machine took but could not write down is not recorded as installed", async () => {+ // `persisted: false` is the machine's own word that the swap is live and will revert at+ // its next restart. Recording the version would be true until then and false after.+ await boot({+ resolvePlan: () => PUSHED_PLAN,+ install: async () => ({ kind: "state-only", identity: IDENTITY }),+ upgrade: async () => ({ kind: "upgraded", detail: "", persisted: false }),+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toMatchObject({+ ok: false,+ step: "hand over the pushed build",+ canReplaceProgram: true,+ });+ expect((t.deps.machines.job()?.result as { message: string }).message).toContain("revert");+ expect(machinesRepo.get("ssh:nas")?.version ?? null).toBeNull();+ });++ it("answering that offer runs the installer the version check would have skipped", async () => {+ let forced: boolean | undefined;+ await boot({+ install: async (opts) => {+ forced = opts.forceInstaller;+ return { kind: "installed", output: "", identity: IDENTITY };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install", {+ replaceProgram: true,+ });+ await waitFor(() => t.deps.machines.job()?.running === false);++ expect(forced).toBe(true);+ });+it("a throw from the push path still ends the job", async () => {await boot({install: () => {@@ -554,6 +704,83 @@ describe("machines API", () => {});});+ describe("putting a new build into service", () => {+ it("restarts a machine whose server was running, so the installed build is the running one", async () => {+ const calls: string[] = [];+ await boot({+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 99 }, machineId: null }),+ stopServer: async () => {+ calls.push("stop");+ return { ok: true as const };+ },+ startServer: async (_t, port) => {+ calls.push(`start:${port}`);+ return { ok: true };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toMatchObject({ ok: true, installed: "installed" });+ expect(calls).toEqual(["stop", "start:7364"]);+ expect(t.deps.machines.job()?.log.join(" ")).toContain("Stopping its server");+ });++ it("leaves a machine that was NOT running down — installing is not a decision to serve", async () => {+ const calls: string[] = [];+ await boot({+ probe: async () => ({ state: { kind: "stopped" }, machineId: null }),+ stopServer: async () => {+ calls.push("stop");+ return { ok: true as const };+ },+ startServer: async () => {+ calls.push("start");+ return { ok: true };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(calls).toEqual([]);+ expect(t.deps.machines.job()?.log.join(" ")).toContain("was not running");+ });++ it("does not restart when nothing was sent — an unchanged version is a no-op", async () => {+ const calls: string[] = [];+ await boot({+ install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 99 }, machineId: null }),+ stopServer: async () => {+ calls.push("stop");+ return { ok: true as const };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(calls).toEqual([]);+ });++ it("a restart that fails is the job's outcome, not a line in its log", async () => {+ // The files landed — the record says so — but the old process is still serving, and+ // an API reporting a clean install over that is exactly the disagreement every guard on+ // this path exists to prevent.+ await boot({+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 99 }, machineId: null }),+ startServer: async () => ({ ok: false, detail: "port 7364 already in use" }),+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toMatchObject({+ ok: false,+ step: "restart its server",+ });+ expect((t.deps.machines.job()?.result as { message: string }).message).toContain(+ "did not come back up",+ );+ // On disk it IS this version; the record says what is there, the job says what runs.+ expect(machinesRepo.get("ssh:nas")?.version).toBe("9.9.9");+ });+ });+describe("connecting", () => {/** An install this server did earlier, so the machine is one connect() accepts. */const installed = (version: string) =>@@ -958,6 +1185,34 @@ describe("machines API", () => {expect(reborn.list("default_project").find((m) => m.id === "ssh:nas")?.machineId).toBe(ID);});+ it("a restart records the id the machine minted when it came back", async () => {+ // A machine mints its id when a server that mints one starts there, so a restart can be+ // the moment an identity comes into existence. Until this side has heard it the machine+ // is addressable by nothing — the proxy cannot route to it and the workspace picker+ // will not offer it — so the restart asks rather than leaving it to the next probe.+ let id: string | null = null;+ await boot({+ // Already carrying this build, so the install path never restarts it: the explicit+ // restart below is the only thing that brings a new process — and its id — up.+ install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 1 }, machineId: id }),+ stopServer: async () => {+ id = ID; // It minted one on the way back up.+ return { ok: true as const };+ },+ });+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect((await byId("ssh:nas"))?.machineId).toBeNull();++ await admin.post("/api/projects/default_project/machines/ssh:nas/restart");+ await waitFor(() => t.deps.machines.job()?.kind === "restart");+ await waitFor(() => t.deps.machines.job()?.running === false);++ expect(t.deps.machines.job()?.result).toMatchObject({ ok: true });+ expect((await byId("ssh:nas"))?.machineId).toBe(ID);+ });+it("a machine whose server never started stays without one", async () => {await boot({ probe: async () => ({ state: { kind: "stopped" }, machineId: null }) });await admin.post("/api/projects/default_project/machines/ssh:nas/install");diff --git a/packages/server/test/machines-push.test.ts b/packages/server/test/machines-push.test.tsindex e7ff5a00..64864667 100644--- a/packages/server/test/machines-push.test.ts+++ b/packages/server/test/machines-push.test.ts@@ -211,6 +211,21 @@ describe("installOnRemote", () => {expect(calls[4]!.input?.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b]));});+ it("a matching base is a hot update to hand on, not an install to perform", async () => {+ // Same release, different pushed state. Nothing to install — and streaming the store over+ // and restarting the process would swap the code under a server without asking whether it+ // can claim it: a runtime older than the pushed platform warns, falls back to its packaged+ // default and keeps serving, so from here the restart reads as a success. The caller sends+ // this down the machine's own update channel, which answers.+ const channel = scripted({+ probe: 'Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n',+ });+ const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ expect(outcome).toMatchObject({ kind: "state-only" });+ // The probe, and nothing else: no installer, and no store either.+ expect(channel.calls).toHaveLength(1);+ });+it("does nothing when the remote already matches base AND pushed state", async () => {const channel = scripted({probe: `Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n${HARNESS}\\n`,diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.tsindex 1e0b1675..8f16df22 100644--- a/packages/server/test/machines.test.ts+++ b/packages/server/test/machines.test.ts@@ -11,6 +11,7 @@ import os from "node:os";import path from "node:path";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";+import { classifyUpgradeAnswer, readPushedBuild, refusalDetail } from "../src/machines/upgrade.js";import { machineIdentity, parseHostAliases } from "../src/machines/ssh-config.js";import {parseProbe,@@ -183,6 +184,53 @@ describe("ssh / scp invocations", () => {expect(() => sessionArgs(target, 70000)).toThrow(/bad port/);});+ it("a 200 is not yet a yes: blocked is a refusal, and a swap not written down is not durable", () => {+ // /api/hmr/upgrade answers 200 for `blocked` so clients keep one parsing path; the body+ // names what would have been discarded. And `persisted: false` is the machine saying the+ // swap is live and gone at its next restart.+ expect(+ classifyUpgradeAnswer(+ 200,+ JSON.stringify({+ status: "blocked",+ dropped: [],+ missing: ["assets/spawn-helper"],+ invalid: [],+ }),+ ),+ ).toEqual({+ kind: "refused",+ detail: "it kept its current version — missing: assets/spawn-helper",+ });+ expect(+ classifyUpgradeAnswer(+ 200,+ JSON.stringify({ status: "ok", persisted: false, web: { rev: "r" } }),+ ),+ ).toMatchObject({ kind: "upgraded", persisted: false });+ expect(+ classifyUpgradeAnswer(+ 200,+ JSON.stringify({ status: "ok", persisted: true, web: { rev: "r" } }),+ ),+ ).toMatchObject({ kind: "upgraded", persisted: true });+ expect(classifyUpgradeAnswer(200, "<html>")).toMatchObject({ kind: "refused" });+ });++ it("repeats the machine's own words when it refuses a build", () => {+ expect(+ refusalDetail(+ 409,+ JSON.stringify({ error: { code: "hmr_refused", message: "this runtime is too old" } }),+ ),+ ).toBe("this runtime is too old");+ });++ it("falls back to whatever it did say, rather than inventing a reason", () => {+ expect(refusalDetail(502, "<html>Bad Gateway</html>")).toBe("<html>Bad Gateway</html>");+ expect(refusalDetail(403, " ")).toContain("403");+ });+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");@@ -436,3 +484,99 @@ describe("reading what `penguin server status` answered", () => {expect(parseProbe(said).state).toEqual({ kind: "unreachable", detail: said });});});++describe("readPushedBuild", () => {+ it("hands on the native assets and the provenance, not only the three bundles", () => {+ // A platform resolves node-pty out of its assets directory and nowhere else; a hand-over+ // without them left every terminal on the machine failing with "no assets directory".+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-handover-"));+ try {+ const hmr = path.join(root, "hmr");+ const assets = path.join(hmr, "store", "assets", "abc");+ fs.mkdirSync(path.join(assets, "node_modules", "node-pty", "prebuilds", "darwin-arm64"), {+ recursive: true,+ });+ fs.mkdirSync(path.join(hmr, "store", "platform"), { recursive: true });+ fs.mkdirSync(path.join(hmr, "store", "cli"), { recursive: true });+ fs.mkdirSync(path.join(hmr, "store", "web"), { recursive: true });+ fs.writeFileSync(path.join(hmr, "store", "platform", "p.mjs"), "platform");+ fs.writeFileSync(path.join(hmr, "store", "cli", "c.mjs"), "cli");+ fs.writeFileSync(+ path.join(hmr, "store", "web", "w.webz"),+ zlib.gzipSync(Buffer.from(JSON.stringify({ files: { "index.html": "aGk=" } }))),+ );+ const helper = path.join(+ assets,+ "node_modules",+ "node-pty",+ "prebuilds",+ "darwin-arm64",+ "spawn-helper",+ );+ fs.writeFileSync(helper, "bin");+ fs.chmodSync(helper, 0o755);+ fs.writeFileSync(path.join(assets, "node_modules", "node-pty", "package.json"), "{}");+ fs.writeFileSync(path.join(assets, ".materialized"), "");+ fs.writeFileSync(+ path.join(hmr, "harness.json"),+ JSON.stringify({+ platform: { bundle: "store/platform/p.mjs" },+ cli: { bundle: "store/cli/c.mjs" },+ web: { manifest: "store/web/w.webz" },+ assets: { dir: "store/assets/abc" },+ source: { repo: "https://example.com/r.git", revision: "v1-3-gabc" },+ }),+ );++ const body = readPushedBuild(root);+ if (body === null) throw new Error("no body");+ const payload = JSON.parse(zlib.gunzipSync(body).toString("utf8")) as {+ platform: string;+ assets?: { files: Record<string, string>; exec: string[] };+ source?: { repo: string; revision: string };+ };+ expect(payload.platform).toBe("platform");+ expect(Object.keys(payload.assets?.files ?? {}).sort()).toEqual([+ "node_modules/node-pty/package.json",+ "node_modules/node-pty/prebuilds/darwin-arm64/spawn-helper",+ ]);+ // The marker is the host's bookkeeping, not an asset; the exec bit travels as a list —+ // and the spawn-helper is on it by NAME, so a Windows sender, which has no exec bit to+ // read, hands it over runnable too (the chmod above is a no-op there).+ expect(payload.assets?.exec).toEqual([+ "node_modules/node-pty/prebuilds/darwin-arm64/spawn-helper",+ ]);+ expect(payload.source).toEqual({ repo: "https://example.com/r.git", revision: "v1-3-gabc" });+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+ });++ it("still hands on a build that was pushed without assets", () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-handover-"));+ try {+ const hmr = path.join(root, "hmr");+ fs.mkdirSync(path.join(hmr, "s"), { recursive: true });+ fs.writeFileSync(path.join(hmr, "s", "p.mjs"), "p");+ fs.writeFileSync(path.join(hmr, "s", "c.mjs"), "c");+ fs.writeFileSync(+ path.join(hmr, "s", "w.webz"),+ zlib.gzipSync(Buffer.from(JSON.stringify({ files: {} }))),+ );+ fs.writeFileSync(+ path.join(hmr, "harness.json"),+ JSON.stringify({+ platform: { bundle: "s/p.mjs" },+ cli: { bundle: "s/c.mjs" },+ web: { manifest: "s/w.webz" },+ }),+ );+ const body = readPushedBuild(root);+ if (body === null) throw new Error("no body");+ const payload = JSON.parse(zlib.gunzipSync(body).toString("utf8")) as Record<string, unknown>;+ expect("assets" in payload).toBe(false);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.tsindex 21888b8a..9ec36f59 100644--- a/packages/server/tsup.config.ts+++ b/packages/server/tsup.config.ts@@ -2,6 +2,7 @@ import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { defineConfig } from "tsup";+import { FAR_SIDE_SCRIPTS } from "../../scripts/far-side-scripts.mjs";export default defineConfig({// Explicitly name entries to preserve subpath exports: "./api", "./lock",@@ -40,16 +41,22 @@ 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+ // Scripts that run somewhere else, as REAL files beside the bundles: the release installers+ // a remote install feeds to the far side (the one thing that has to arrive before the CLI+ // does; everything after is a `penguin` subcommand the machine already has). Each is+ // resolved next to this module at runtime, so each 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, failing the build rather than shipping a package whose// Machines page dies at "prepare the installer".+ //+ // The SET comes from scripts/far-side-scripts.mjs, shared with the hot push that has to+ // ship the same one (see that module): two hand-kept copies drifted once already.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));+ const repo = path.join(here, "..", "..");+ for (const { name, from } of FAR_SIDE_SCRIPTS) {+ fs.copyFileSync(path.join(repo, from), path.join(here, "dist", name));}},});diff --git a/scripts/deploy.mjs b/scripts/deploy.mjsindex 37e426ac..b3ca241e 100644--- a/scripts/deploy.mjs+++ b/scripts/deploy.mjs@@ -29,6 +29,7 @@ import { fileURLToPath } from "node:url";import { unsafePlaintextTarget } from "./deploy-target-safety.mjs";import { buildGitDefine, checkoutFacts, originUrl } from "./build-git-stamp.mjs";import { ESM_CJS_BANNER } from "./esm-cjs-banner.mjs";+import { FAR_SIDE_SCRIPTS } from "./far-side-scripts.mjs";const require = createRequire(import.meta.url);const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");@@ -219,10 +220,12 @@ 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");+ // The scripts that run on the FAR side — the release installers a remote install feeds+ // over, the one thing that has to arrive before the CLI does. A pushed bundle resolves them+ // from its own assets directory, so a push that omits one leaves a server that cannot+ // install a machine at all. Same set the packaged build copies into dist/; see the module.+ for (const { name, from } of FAR_SIDE_SCRIPTS) {+ files[name] = (await fsp.readFile(path.join(ROOT, from))).toString("base64");}return { files, exec };}diff --git a/scripts/far-side-scripts.mjs b/scripts/far-side-scripts.mjsnew file mode 100644index 00000000..29d929e2--- /dev/null+++ b/scripts/far-side-scripts.mjs@@ -0,0 +1,24 @@+/**+ * The scripts that run on the FAR side of a machines operation, and where they come from.+ *+ * `install-server.ts` resolves them beside the module+ * that spawns it — `opts.assets?.() ?? path.dirname(import.meta.url)`. That is dist/ for a+ * packaged install and the published assets directory for a hot-pushed bundle, so the same+ * set has to be produced by two different builds: packages/server/tsup.config.ts copies them+ * into dist/, scripts/deploy.mjs pushes them as assets.+ *+ * Written once here because it was written twice before, and the copies drifted: the push+ * shipped the two installers and neither applier, leaving a hot-pushed server that could not+ * upgrade a machine or sign in to one — each dying on an ENOENT naming a path inside its own+ * store. Neither build could notice, because each list is valid on its own. Both appliers+ * have since become `penguin` subcommands the machine already has, which is the reason only+ * the installers are left: an installer is the one thing that has to arrive BEFORE the CLI+ * does.+ *+ * `from` is relative to the repository root; `name` is the flat filename both destinations+ * use, which is the name the runtime looks for.+ */+export const FAR_SIDE_SCRIPTS = [+ { name: "install.sh", from: "install.sh" },+ { name: "install.ps1", from: "install.ps1" },+];