Skip to content

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

feat(machines): support the machine connection and management (#448)

Myriad-Dreamin48662c0a435f
diff --git a/changelog/unreleased/2026-09-09-machines-page.md b/changelog/unreleased/2026-09-09-machines-page.md
new file mode 100644
index 00000000..9547f6a9
--- /dev/null
+++ b/changelog/unreleased/2026-09-09-machines-page.md
@@ -0,0 +1,75 @@
+# The Machines page: use a machine, stop using it, and open a workspace on it
+
+- **Date:** 2026-09-09
+- **Type:** feature, fix
+- **Scope:** `web`, `server`
+- **PR:** [#448](https://github.com/Prism-Shadow/penguin-harness/pull/448)
+
+[中文版](2026-09-09-machines-page.zh.md)
+
+The page that drives all of it. A machine is something this Project runs agents on: **Use** one and this server installs the program, starts it, connects, hands over the Model config and stays connected; **Stop using** it and the machine is let go. Machines can also be picked in the workspace picker, so a Session can be started in a directory on another machine.
+
+**Not reachable yet.** The sidebar row, the route and the picker's machine row are held back deliberately, and turned on in one change of their own once the feature has settled. What lands here is the page itself.
+
+## The window never moves
+
+A call that names a machine is rewritten to `/server/<machineId>/api/…`, which the local server forwards. There is deliberately **no window-wide "active server" mode**. One existed and was removed: pointing an entire window at another machine put every page behind a tunnel, `/api/me` included — so a tunnel that dropped left the app unable to answer whether anyone was logged in, and the control for getting back was rendered inside the layout that never mounted. An escape hatch behind the thing that breaks is not an escape hatch.
+
+Naming the machine on the calls that actually concern it has no such failure: a dead tunnel breaks exactly the request that needed it, and says so. One string rule covers `fetch` and the SSE subscriptions alike.
+
+## Two verbs, one sentence per machine
+
+**Use** does everything a machine needs to run agents — install or update the program, start its server, connect, hand over the Model config — as one job, and **Stop using** lets it go. Each card says where the machine is in plain words ("Connected and ready", "Its server is not running — Use starts it"), and every sentence that names a problem is fixed by the same button. Install, update, restart, connect and disconnect are not separate controls a person has to order by hand.
+
+- One card per machine, this server first, sorted by name so an update or a probe never moves one. A card at rest is two lines: the name, and the state with the one detail beside it — when it was last checked, the build it carries when that is behind this server's, the far side's words when it failed. The dot at the card's edge is blue for a live connection, amber and red for what needs a person, grey for settled.
+- Selection is the card: click one to select it. Select all, select none, **Use** (a plug) and **Stop using** (the plug pulled) are glyphs alone in a bar that keeps a fixed slot between the title and the cards, so nothing moves when a selection appears or goes; the word stays as the tooltip and the accessible name. A batch works several machines at once on the server; the rest queue behind them.
+- A queued or working card grows a stepper under its name, one segment per step of the pipeline (check, install, hand over, restart, connect, sync), fed by the step the server says it is on.
+- The chevron unfolds the card: the build, the install date, the server's state and port, the last check, the machine id, the **server root** on that machine (`PENGUIN_HOME` — the profile decides it, so a dev instance reaches a machine's dev installation and never the release one beside it), the job's full output, and the forced install when a job offers it. The forced install ("Install anyway and restart") is offered on every failed install or connect except the run that was itself that install and the one failure installing cannot mend — this server having no build of its own to send — and it still warns that it interrupts whoever is using that machine.
+- Machines not yet in use live behind **Add machines…**, a search over the server's ssh config: the first matches, a fold for the rest, and a confirmation once something is picked. Picking several and confirming uses them all.
+- Once a machine is connected, staying connected is the server's job: a machine that drops and does not come back is retried on a widening wait — from a minute up to fifteen — until it is held again or someone stops using it. Restarting the server no longer leaves machines disconnected until someone visits the page.
+- The header shows this server's build and, when any machine in use is behind it, **Update all**, which brings every one of them forward and reconnects it in one tap.
+- The server answers `POST /api/projects/:projectId/machines/use` with `{ machines: [...] }` (a few machines at once, the rest queued, `202`; refusals that need no ssh come back by id) and `POST .../machines/stop-using`. The list carries `jobs`: every queued, running and last-finished job per machine, each with the pipeline step it is on (`phase`). The per-machine install, connect, restart, release and disconnect routes remain.
+
+## Declaring an ssh host from the page
+
+A machine that is not in the server's ssh config yet can be declared from the page. The **+** at the foot of the **Add machines…** panel opens a short form — alias, address, and optionally user, port and key file — and the server appends the matching `Host` block to its own `~/.ssh/config`. The new host then appears under **Add machines…** like any other.
+
+- The block is written in ssh's own syntax, led by a comment naming PenguinHarness and the time, so a person reading the file later knows which lines are not theirs. The directory and file are created with the modes ssh requires when they do not exist yet.
+- Values must each be one word with no `#`, the alias must not be a pattern, and the port must be a whole number from 1 to 65535. The form says so under the field before anything is sent. An alias the config already declares is refused: ssh would take the earlier block and silently ignore the new one.
+- A host this app wrote can be reconfigured: the gear in a card's details opens the same form on the block read back, and saving rewrites it in place. A block written by hand is shown but not saved — it may carry options the form does not know — and the form points at the file instead.
+- The server answers `POST /api/projects/:projectId/machines/ssh-hosts` with the machines list (`201`), `400 ssh_host_invalid` naming the field, or `409 ssh_host_exists`; `GET …/ssh-hosts/:alias` reads a block back with whether it may be rewritten, and `PUT …/ssh-hosts/:alias` rewrites one this app wrote (`404` none, `409 ssh_host_foreign` hand-written). Admin only, like the rest of the group.
+
+## Picking a workspace on a machine
+
+A workspace is a directory **on** a machine, so only one whose filesystem is reachable right now can be browsed: this one always, any other with a held connection. Every machine in use is **listed regardless**, the unreachable ones disabled with the reason at the row — a list that silently omits its answer is indistinguishable from a broken feature.
+
+Machines are identified by their own id and labelled by ssh alias, so a renamed host keeps its workspaces.
+
+## A machines table from before its migration
+
+A data root that ran the machines line before it was released has machines tables adopted with the columns they had — migration 4 creates them with `IF NOT EXISTS` — so a connect failed at "Opening the connection…" with `table machines has no column named session_pid`. Migration 12, `machines-columns`, adds `session_pid` and `platform` to a machines table that lacks them and leaves one that has them alone. Additive and swap-safe, so a hot push applies it; its undo does nothing, since migration 4 declares the same columns.
+
+## Two things the page said during an outage that were not true
+
+A machine card read **Connected** whenever this server held an ssh session to it — even when the last probe had found no server running over there, which the card's own unfolded details said in the next breath.
+
+The two facts are deliberately separate: the connection is a process on *this* side and outlives the far server, so it says the tunnel has somewhere to go, never that anything answers. Reading one for the other is what once produced a reconnect loop. The card was making the same mistake in the other direction — and worse, silently: because the row looked ready, **Enable** was withheld, so the one action that would start the far server again was hidden by the same bug that hid the fault.
+
+A held connection over a stopped server now reads *Connected, not serving* in the attention tone, and offers Enable. A held connection over an unreachable machine reads Unreachable, with ssh's own words.
+
+Found on a real fleet: a machine's server could not bind its port, and the page insisted everything was fine while nothing on it worked.
+
+### …and a plugin sync that contradicted the line above it
+
+A connect printed both of these, one after the other:
+
+```
+Models synced: default_project.
+Plugins of default_project not synced — that machine has no such Project
+```
+
+Both cannot be true, and the second was wrong. A machine on a build older than the Project plugin list answers 404 to a route it has never heard of, and the sync read every 404 as a missing Project. It now asks the one question every build can answer — does it list the Project? — and says which of the two it is: an older build to update, or a Project that really is not there.
+
+## Reach
+
+Machines are an admin capability end to end: the page, every route in the group, and the proxy to a machine's API.
diff --git a/changelog/unreleased/2026-09-09-machines-page.zh.md b/changelog/unreleased/2026-09-09-machines-page.zh.md
new file mode 100644
index 00000000..b462e4a6
--- /dev/null
+++ b/changelog/unreleased/2026-09-09-machines-page.zh.md
@@ -0,0 +1,75 @@
+# Machines 页面:使用一台机器、停用它,并在它上面打开工作区
+
+- **Date:** 2026-09-09
+- **Type:** feature, fix
+- **Scope:** `web`, `server`
+- **PR:** [#448](https://github.com/Prism-Shadow/penguin-harness/pull/448)
+
+[English](2026-09-09-machines-page.md)
+
+驱动这一切的页面。机器是这个 Project 用来跑 agent 的东西:**使用**一台,本服务端就安装程序、启动它、连接、下发 Model 配置并保持连接;**停用**它,机器就被放开。机器也可以在工作区选择器里被选中,因此可以在另一台机器的某个目录下开一个 Session。
+
+**暂时还进不去。** 侧边栏入口、路由与选择器里的机器一行被刻意留住,等功能稳定之后由一个单独的改动一次性放开。这里落地的是页面本身。
+
+## 窗口不会整个搬走
+
+点名了某台机器的调用会被改写成 `/server/<machineId>/api/…`,由本地服务端转发过去。这里刻意**没有整窗口的「当前服务器」模式**。它一度存在过,后来被移除了:把整个窗口指向另一台机器,会让每一个页面都落到隧道后面,`/api/me` 也不例外——于是隧道一断,应用连「有没有人登录」都答不上来,而用来退出这个状态的控件,恰恰渲染在那个永远没能挂载的布局里面。藏在故障物后面的逃生门不是逃生门。
+
+改为在真正与那台机器有关的调用上点名它,就不会这样失败:隧道死了,坏掉的正好是需要它的那个请求,而且它会说出来。一条字符串规则同时管住 `fetch` 与 SSE 订阅。
+
+## 两个动作,每台机器一句话
+
+**使用**一次做完让机器能跑 agent 所需的全部事情——安装或更新程序、启动对端服务、连接、下发 Model 配置——作为一个任务;**停用**则放开它。每张卡片用人话说明这台机器在哪一步(「已连接,随时可用」「对端服务未运行——点『使用』即可启动」),凡是提到问题的句子,都由同一个按钮解决。安装、更新、重启、连接、断开不是需要人手动排顺序的各自独立的控件。
+
+- 每台机器一张卡片,本服务端排第一,按名字排序,因此更新或探测不会挪动任何一张。静止时一张卡片只有两行:名字,以及状态和它旁边唯一要紧的那个信息——上次检查时间、落后于本服务端时它所装的版本、失败时对端的原话。卡片边缘的圆点:蓝色表示连接在线,琥珀色和红色表示需要人处理,灰色表示已安定。
+- 选择即卡片:点一下即选中。全选、全不选、**使用**(插头)和**停用**(拔下的插头)是纯图标,放在标题和卡片之间一条高度固定的操作条里,因此选择出现或消失时卡片不会移动;文字保留为 tooltip 与无障碍名称。批量操作在服务端同时处理多台,其余排队等候。
+- 排队或处理中的卡片在名字下方长出一条分段进度条,每段对应流程的一步(检查、安装、交接、重启、连接、下发配置),由服务端报告的当前步骤驱动。
+- 卡片右侧的箭头展开详情:版本、安装时间、对端服务状态和端口、上次检查、机器 ID、那台机器上的**服务端根目录**(`PENGUIN_HOME`——由 profile 决定,dev 实例访问的是机器上的 dev 安装,绝不会碰旁边的 release 安装)、任务的完整输出,以及任务给出时的强制安装。「强制安装并重启」出现在每一次失败的安装或连接上,只有两种情况除外:这次运行本身就是那次安装,以及安装也无法弥补的那一种失败——本服务端自己没有可发送的构建;它仍会提示这会打断正在使用那台机器的人。
+- 尚未使用的机器放在「添加机器…」后面,在服务端的 ssh 配置里搜索:先列前几个匹配,其余折叠在后,选中后才出现确认。多选后确认即一起使用。
+- 机器连上之后,保持连接是服务端的事:断开且未自行恢复的机器会以逐步拉长的间隔重试——从一分钟到十五分钟——直到重新连上或有人停用它。重启服务端后,不再需要有人打开页面机器才会重新连接。
+- 标题栏显示本服务端的版本;当有在用的机器落后于它时,出现「全部更新」,一次把它们全部更新并重新连接。
+- 服务端提供 `POST /api/projects/:projectId/machines/use`,请求体 `{ machines: [...] }`(同时处理多台、其余排队,返回 `202`;无需 ssh 即可判定的拒绝按 id 返回),以及 `POST .../machines/stop-using`。列表带有 `jobs`:每台机器排队中、运行中和最近一次完成的任务,以及各自所处的流程步骤(`phase`)。原有的按机器安装、连接、重启、释放、断开路由保留。
+
+## 在页内声明 ssh 主机
+
+还没写进服务端 ssh 配置的机器,可以直接在页面里声明。「添加机器…」面板底部的 **+** 打开一个简短的表单——别名、地址,以及可选的用户、端口和密钥文件——服务端会把对应的 `Host` 块追加到它自己的 `~/.ssh/config`。之后这台主机就和其他主机一样出现在「添加机器…」里。
+
+- 写入的是 ssh 自己的语法,开头一行注释标明由 PenguinHarness 于何时写入,方便日后翻看配置的人分辨哪些行不是自己写的。目录和文件不存在时,按 ssh 要求的权限创建。
+- 每个值必须是一个词且不含 `#`,别名不能是通配模式,端口必须是 1 到 65535 之间的整数。表单会在发送前就在字段下方说明。配置里已有的别名会被拒绝:ssh 只认先出现的那一块,新块会被静默忽略。
+- 由本应用写入的主机可以再配置:卡片详情里的齿轮会把那一段读回来,在同一个表单里打开,保存即原地改写。手写的那一段只展示不保存——它可能带有表单不认识的选项——表单会提示直接改文件。
+- 服务端提供 `POST /api/projects/:projectId/machines/ssh-hosts`,返回机器列表(`201`)、指明字段的 `400 ssh_host_invalid`,或 `409 ssh_host_exists`;`GET …/ssh-hosts/:alias` 读回一段并说明能否改写,`PUT …/ssh-hosts/:alias` 改写本应用写入的一段(`404` 不存在,`409 ssh_host_foreign` 为手写)。与该路由组其余部分一样仅管理员可用。
+
+## 在机器上选工作区
+
+工作区是某台机器**上**的一个目录,所以只有此刻文件系统可达的机器才能被浏览:本机永远可以,其余需要一条持有的连接。每一台在用的机器都**照样列出**,不可达的置灰并在行上写明原因——一个悄悄略去答案的列表,和一个坏掉的功能无法区分。
+
+机器以自身的 id 标识、以 ssh 别名显示,因此改了名的主机仍然保得住它的工作区。
+
+## 早于迁移的 machines 表
+
+一个数据根目录若在 machines 线发布之前就跑过它,其 machines 各表会按原有的列被接管——迁移 4 用 `IF NOT EXISTS` 创建它们——于是连接在「Opening the connection…」处失败,报 `table machines has no column named session_pid`。迁移 12 `machines-columns` 为缺少 `session_pid` 和 `platform` 的 machines 表补上这两列,已有的表原样保留。纯增量且可在热推送时应用;它的回退什么也不做,因为迁移 4 声明的正是同样的列。
+
+## 机器页在一次故障里说的两句不实的话
+
+只要本服务器持有到某台机器的 ssh 会话,机器卡片就显示**已连接**——哪怕最近一次探测发现那边根本没有服务端在跑,而这一点就写在同一张卡片展开后的详情里。
+
+这两件事是被刻意分开的:连接是**本侧**的一个进程,它比对端的服务端活得久,所以它只说明「隧道有地方可去」,从不说明「有人在应答」。把其中一个当作另一个,正是当年造成重连死循环的原因。卡片犯的是同一个错误的反方向——而且更糟,因为它是无声的:由于这一行看起来「就绪」,**启用**按钮被收了起来,于是唯一能把对端服务端重新拉起来的动作,被隐藏它故障的同一个 bug 一起隐藏了。
+
+现在:连接在、服务端已停止 → 显示「已连接,未在提供服务」,attention 色,并提供启用;连接在、机器连不上 → 显示连不上,并带上 ssh 自己的原话。
+
+这是在真实机群上发现的:一台机器的服务端绑不上端口,而页面坚称一切正常,实际上什么都做不了。
+
+### ……以及与上一行自相矛盾的插件同步
+
+一次连接会先后打印这两句:
+
+```
+Models synced: default_project.
+Plugins of default_project not synced — that machine has no such Project
+```
+
+两句不可能同时为真,错的是第二句。比「Project 插件清单」更旧的机器,对一条它从未听说过的路由回 404,而同步把所有 404 都读成「没有这个 Project」。现在它会追问一个所有版本都答得上来的问题——它列出这个 Project 了吗——并说清是哪一种:需要更新的旧版本,还是真的没有这个 Project。
+
+## 范围
+
+机器从头到尾都是管理员能力:页面、该路由组的每一条路由,以及通往机器 API 的代理。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index fdcdaffd..731f38c3 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -4032,6 +4032,15 @@ export interface MachineInfo {
* since each probe is an ssh round trip while the list is only the config's text.
*/
status: MachineServerStatus | null;
+ /**
+ * The data root the server there runs on (`PENGUIN_HOME`). This instance's PROFILE decides
+ * it — a dev instance names the machine's dev root and never the release one beside it
+ * (machines/layout.ts) — which is exactly what a reader looking at two instances of this
+ * page needs to tell them apart. Written in that machine's own spelling once its platform
+ * is known, and in the POSIX one before that; for `local` it is this process's own root,
+ * already resolved to an absolute path.
+ */
+ root: string;
}
/**
@@ -4056,10 +4065,18 @@ export interface MachineServerStatus {
* refused key or an unusable Node than a paraphrase would.
*/
export interface MachineJob {
- kind: "install" | "connect" | "restart";
+ /** `use` is the whole pipeline — install if needed, hand over, connect, sync — as one job. */
+ kind: "install" | "connect" | "restart" | "use";
machineId: string;
alias: string;
+ /** Waiting its turn: a few machines are worked on at once, and a batch queues the rest. */
+ queued: boolean;
running: boolean;
+ /**
+ * Which step of the pipeline the job is on, in `MACHINE_PHASES` order — what the page draws
+ * as a stepper. Null until the first step is named; a finished job keeps its last phase.
+ */
+ phase: MachinePhase | null;
log: string[];
result:
| null
@@ -4071,12 +4088,13 @@ export interface MachineJob {
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.
+ * installing the PROGRAM over there and restarting it. Every failed install or
+ * connect offers it — a failure that leaves no next step leaves a person stuck —
+ * except a run that was itself that install, and one this server could not act on
+ * (no build of its own to send), which says `false`. Offered rather than done,
+ * because it restarts a server this Project does not own alone.
*/
- canReplaceProgram?: true;
+ canReplaceProgram?: boolean;
};
}
@@ -4089,7 +4107,68 @@ export interface MachinesResponse {
* checkout, which stands on no release the remote could download.
*/
imageVersion: string | null;
+ /** The most recently started job, running or finished. */
job: MachineJob | null;
+ /**
+ * Every job worth showing this generation: the queued ones, the running one, and the last
+ * finished one per machine — so a batch reads as a list of rows each saying where it is.
+ */
+ jobs: MachineJob[];
+}
+
+/** The steps of bringing a machine into use, in the order a `use` job runs them. A step not needed is skipped, never revisited. */
+export const MACHINE_PHASES = [
+ "check",
+ "install",
+ "handover",
+ "restart",
+ "connect",
+ "sync",
+] as const;
+export type MachinePhase = (typeof MACHINE_PHASES)[number];
+
+/**
+ * `POST /api/projects/:projectId/machines/ssh-hosts`: append a host block to this server's
+ * `~/.ssh/config`. Answers the machines list (201), or 400 `ssh_host_invalid` naming the
+ * field, or 409 `ssh_host_exists`.
+ */
+export interface SshHostRequest {
+ /** The alias — what `ssh <alias>` will take, and the machine's name everywhere here. */
+ alias: string;
+ hostName: string;
+ user?: string;
+ port?: number;
+ identityFile?: string;
+}
+
+/**
+ * `GET /api/projects/:projectId/machines/ssh-hosts/:alias`: a host's block read back, and
+ * whether this app wrote it. Only a block this app wrote may be rewritten
+ * (`PUT …/ssh-hosts/:alias`, the same fields less the alias): a hand-written one may carry
+ * options this app does not know, and rewriting it would drop them.
+ */
+export interface SshHostResponse extends SshHostRequest {
+ editable: boolean;
+}
+
+/** `POST /api/projects/:projectId/machines/use`: bring these machines into use, as one queued batch. */
+export interface MachinesUseRequest {
+ /** Machine ids (`ssh:<alias>`). Every one is queued; refusals come back by id. */
+ machines: string[];
+ /** Install the program even where its version matches, and restart there — the answer to a job that asked for it. */
+ replaceProgram?: boolean;
+}
+
+/** Why one machine of a batch was not queued; the rest were. */
+export type MachineUseRefusal = "unknown-machine" | "self" | "no-image";
+
+export interface MachinesUseResponse extends MachinesResponse {
+ refused: { machineId: string; why: MachineUseRefusal }[];
+}
+
+/** `POST /api/projects/:projectId/machines/stop-using`: let go of these machines — connection dropped, Project membership released; the install stays. */
+export interface MachinesStopUsingRequest {
+ machines: string[];
}
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index ede57777..1f43b497 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -507,6 +507,23 @@ export const MIGRATIONS: readonly Migration[] = [
// back under whatever the settings say.
down() {},
},
+ {
+ version: 12,
+ name: "machines-columns",
+ // A machines table can predate migration 4 — a data root that ran the machines line
+ // before it was released kept forwards, not sessions — and that migration's IF NOT
+ // EXISTS adopted it whatever its columns were, so the first connect failed on the row's
+ // insert. Adds what is missing, nullable; a platform rolled back to 4 declared these
+ // columns itself, so there is nothing for it to mind.
+ swapSafe: true,
+ up(db) {
+ ensureColumn(db, "machines", "session_pid", "INTEGER");
+ ensureColumn(db, "machines", "platform", "TEXT");
+ },
+ // Nothing to undo: what this added, 4 already declares, and a column it found in place
+ // was never this migration's to take away.
+ down() {},
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
index 261f09e7..705eb353 100644
--- a/packages/server/src/http/routes/machines.ts
+++ b/packages/server/src/http/routes/machines.ts
@@ -12,6 +12,9 @@
* 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 /ssh-hosts — append a host block to this server's ~/.ssh/config; 201.
+ * GET /ssh-hosts/:alias — that block read back, and whether this app wrote it.
+ * PUT /ssh-hosts/:alias — rewrite a block this app wrote; 404 none, 409 hand-written.
* 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.
*
@@ -25,7 +28,12 @@
*/
import { Hono } from "hono";
import type { Context } from "hono";
-import type { DirListResponse, MachinesResponse } from "../../api/types.js";
+import type {
+ DirListResponse,
+ MachinesResponse,
+ MachinesUseResponse,
+ SshHostResponse,
+} from "../../api/types.js";
import { HttpError } from "../errors.js";
import { requireValidId } from "../validate.js";
import type { AppEnv } from "../../auth/middleware.js";
@@ -56,6 +64,123 @@ export function machinesRoutes(deps: MachinesRouteDeps): Hono<AppEnv> {
machines: deps.machines.list(requireValidId(c, "projectId")),
imageVersion: deps.machines.imageVersion(),
job: deps.machines.job(),
+ jobs: deps.machines.jobs(),
+ });
+
+ /**
+ * Bring machines into use — the one verb a person needs. Each is queued for the whole
+ * pipeline (install if needed, hand over, connect, sync); what could be refused without
+ * any ssh is answered by id in `refused`, and the rest report through `jobs`. 202 always:
+ * the queue is the answer, even when some rows were refused.
+ */
+ app.post("/use", async (c) => {
+ const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;
+ const machines = Array.isArray(body.machines)
+ ? body.machines.filter((m): m is string => typeof m === "string")
+ : [];
+ if (machines.length === 0) {
+ throw new HttpError(400, "bad_request", "Name at least one machine to use.");
+ }
+ const { refused } = deps.machines.startUse(
+ requireValidId(c, "projectId"),
+ machines,
+ body.replaceProgram === true,
+ );
+ return c.json({ ...state(c), refused } satisfies MachinesUseResponse, 202);
+ });
+
+ /**
+ * Add a host to this server's ssh config. 201 with the list, which now names it; 400 with
+ * the offending field when the entry would not survive as one line each; 409 when the
+ * alias is already declared — ssh would take the earlier block and ignore this one.
+ */
+ /** A host entry as a request body carries it; the port may arrive as a string from a form. */
+ const hostBody = (body: Record<string, unknown>) => {
+ const str = (key: string) =>
+ typeof body[key] === "string" ? (body[key] as string) : undefined;
+ const portRaw = body.port;
+ const port =
+ typeof portRaw === "number"
+ ? portRaw
+ : typeof portRaw === "string" && portRaw.trim() !== ""
+ ? Number(portRaw)
+ : undefined;
+ return {
+ alias: str("alias") ?? "",
+ hostName: str("hostName") ?? "",
+ user: str("user"),
+ port,
+ identityFile: str("identityFile"),
+ };
+ };
+ const invalid = (problem: { field: string; why: string }) =>
+ new HttpError(
+ 400,
+ "ssh_host_invalid",
+ `${problem.field}: ${problem.why === "required" ? "required" : "must be one word, with no space or #"}`,
+ );
+
+ app.post("/ssh-hosts", async (c) => {
+ const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;
+ const added = deps.machines.addSshHost(hostBody(body));
+ if (!added.ok) {
+ if (added.why === "exists") {
+ throw new HttpError(409, "ssh_host_exists", "That alias is already in the ssh config.");
+ }
+ throw invalid(added.problem);
+ }
+ return c.json(state(c), 201);
+ });
+
+ /** A host's block read back — for the form that configures it — and whether it may be rewritten. */
+ app.get("/ssh-hosts/:alias", (c) => {
+ const found = deps.machines.sshHost(c.req.param("alias"));
+ if (found === null) {
+ throw new HttpError(
+ 404,
+ "ssh_host_not_found",
+ "No Host block for that alias in ~/.ssh/config itself; it may live in an included file.",
+ );
+ }
+ return c.json({ ...found.entry, editable: found.editable } satisfies SshHostResponse);
+ });
+
+ /** Rewrite a block this app wrote. 404 when there is none; 409 when it was written by hand. */
+ app.put("/ssh-hosts/:alias", async (c) => {
+ const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;
+ const { alias: _ignored, ...entry } = hostBody(body);
+ const updated = deps.machines.updateSshHost(c.req.param("alias"), entry);
+ if (!updated.ok) {
+ if (updated.why === "not-found") {
+ throw new HttpError(
+ 404,
+ "ssh_host_not_found",
+ "No Host block for that alias in ~/.ssh/config.",
+ );
+ }
+ if (updated.why === "foreign") {
+ throw new HttpError(
+ 409,
+ "ssh_host_foreign",
+ "That block was written by hand; edit it in ~/.ssh/config.",
+ );
+ }
+ throw invalid(updated.problem);
+ }
+ return c.json(state(c));
+ });
+
+ /** Stop using machines: connections dropped, membership released; the install over there stays. */
+ app.post("/stop-using", async (c) => {
+ const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;
+ const machines = Array.isArray(body.machines)
+ ? body.machines.filter((m): m is string => typeof m === "string")
+ : [];
+ if (machines.length === 0) {
+ throw new HttpError(400, "bad_request", "Name at least one machine to stop using.");
+ }
+ deps.machines.stopUsing(requireValidId(c, "projectId"), machines);
+ return c.json(state(c));
});
app.get("/", (c) => c.json(state(c)));
diff --git a/packages/server/src/http/routes/plugins-installed.ts b/packages/server/src/http/routes/plugins-installed.ts
index 575834d8..6bd1f92b 100644
--- a/packages/server/src/http/routes/plugins-installed.ts
+++ b/packages/server/src/http/routes/plugins-installed.ts
@@ -46,6 +46,7 @@ import {
} from "../../plugin/loader.js";
import { pluginHostFrom } from "../../plugin/host.js";
import { Access, ProjectConfigStore } from "../../mechanisms/projects.js";
+import type { Machines } from "../../machines/service.js";
export interface InstalledPluginsDeps {
root: string;
@@ -62,6 +63,12 @@ export interface InstalledPluginsDeps {
* for the restart that will read it).
*/
apply: (change: ReassemblyChange) => Promise<boolean>;
+ /**
+ * Hands this Project's list to the machines it uses, strict parity. Not awaited: the
+ * person editing is not the one who should wait for a set of ssh tunnels — the same rule
+ * the model config changes under.
+ */
+ syncFleet: (projectId: string) => void;
}
export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv> {
@@ -195,6 +202,7 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>
await deps.apply(
edit(projectId, (listed) => (specifier in listed ? listed : { ...listed, [specifier]: {} })),
);
+ deps.syncFleet(projectId);
return c.json(await view(projectId));
});
@@ -209,6 +217,7 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>
return kept;
}),
);
+ deps.syncFleet(projectId);
return c.json(await view(projectId));
});
@@ -229,6 +238,7 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>
await deps.apply(
edit(projectId, (listed) => Object.fromEntries(names.map((s) => [s, listed[s] ?? {}]))),
);
+ deps.syncFleet(projectId);
return c.json(await view(projectId));
});
@@ -254,6 +264,7 @@ export class InstalledPluginRoutes {
@Use() private readonly reassembly!: Reassembly;
@Use() private readonly projectConfig!: ProjectConfigStore;
@Use() private readonly access!: Access;
+ @Use() private readonly machines!: Machines;
@Bind("InstalledPluginRoutes.routes") routes!: Hono<AppEnv>;
setup() {
const hmr = this.hmr;
@@ -269,6 +280,8 @@ export class InstalledPluginRoutes {
projectConfig: this.projectConfig,
access: this.access,
apply: (change) => this.reassembly.reassemble(change),
+ // The plugin list rides the same trip the model config takes to a Project's machines.
+ syncFleet: (projectId) => void this.machines.syncModelsEverywhere(projectId),
});
}
}
diff --git a/packages/server/src/machines/plugins-sync.ts b/packages/server/src/machines/plugins-sync.ts
new file mode 100644
index 00000000..1382e4b3
--- /dev/null
+++ b/packages/server/src/machines/plugins-sync.ts
@@ -0,0 +1,163 @@
+/**
+ * Handing a Project's plugin list to the machines that Project was given to.
+ *
+ * A Session created on a machine runs THERE, so a plugin it needs has to be loaded there:
+ * the surface a plugin contributes is offered by the server that will run it, and a create
+ * naming a kind that machine does not have is refused by that machine. Without this, a
+ * fleet means enabling the same plugin once per machine by hand, and there is no path in
+ * the product to do it — the Machines page is how remote is managed. Same problem the Model
+ * credentials have, answered the same way (machines/models-sync.ts).
+ *
+ * STRICT PARITY, decided by the operator (PRFC-0010): what goes over is the Project's whole
+ * list, and what the machine has beyond it is removed. That is the literal meaning of "the
+ * same plugins everywhere", and it has a cost worth stating at the call site: a
+ * platform-specific sandbox backend — `sandbox-winuser` on Windows, `sandbox-bwrap` on Linux —
+ * is not in the other's list and is therefore taken away. Keeping one means listing it
+ * fleet-wide; a machine that cannot resolve it shows an inert error row rather than losing
+ * the backend it can use.
+ *
+ * The list travels inside the tunnel to the machine's own `PUT /plugins/installed`, an
+ * ordinary authenticated call rather than a far-side script: that endpoint validates, writes
+ * the Project's config, and does its own hot apply. So a machine running a build new enough
+ * loads the plugin without restarting; an older one records the list and reports that it is
+ * waiting for a restart, which this sync reports back rather than papering over.
+ */
+import type { MachineApi } from "./machine-api.js";
+import type { InstalledPluginsResponse } from "../api/types.js";
+
+/** What a sync did, in the words the connect log shows. */
+export type PluginSyncOutcome =
+ | {
+ kind: "synced";
+ /** Projects whose plugin list was written on that machine (empty = nothing needed it). */
+ projects: string[];
+ /** Specifiers added over there, across those Projects. */
+ added: string[];
+ /** Specifiers removed over there because no synced Project asks for them. */
+ removed: string[];
+ /**
+ * Specifiers that machine lists but cannot resolve — most often a machine still on a
+ * build that does not ship the plugin. Reported, never silently dropped: it is the
+ * operator's choice that is not taking effect there.
+ */
+ unresolved: string[];
+ /** Whether that machine needs a restart before what was written actually loads. */
+ restartPending: boolean;
+ /** Projects the machine would not take, each with its own reason. */
+ refused: { projectId: string; detail: string }[];
+ }
+ | { kind: "failed"; detail: string };
+
+export interface SyncPluginsOptions {
+ api: MachineApi;
+ /** This side's half: what the Project asks for. */
+ loadLocal: (projectId: string) => Promise<string[]>;
+ /** The Projects this machine is used by. */
+ projects: readonly string[];
+}
+
+/** `PUT /api/projects/:p/plugins/installed` on the far side. */
+function pluginsPath(projectId: string): string {
+ return `/api/projects/${encodeURIComponent(projectId)}/plugins/installed`;
+}
+
+/**
+ * Why that machine answered 404 — the route is not there, or the Project is not there.
+ *
+ * The two are indistinguishable in the status alone and lead to opposite conclusions, so
+ * this asks the one question every build can answer: does it list the Project? Saying "that
+ * machine has no such Project" about a Project the models sync had just written, in the line
+ * above, sends an operator hunting a fault that does not exist — which is exactly what it did.
+ */
+async function refusal404(api: MachineApi, projectId: string): Promise<string> {
+ const listed = await api.request("GET", "/api/projects");
+ if (listed.status === 200) {
+ try {
+ const projects = (JSON.parse(listed.text) as { projects?: { projectId?: string }[] })
+ .projects;
+ if (projects?.some((p) => p.projectId === projectId) === true) {
+ return "that machine's build is older than the Project plugin list — update it, then sync again";
+ }
+ } catch {
+ // Unreadable list: fall through to the plainer answer below.
+ }
+ }
+ return "that machine has no such Project";
+}
+
+/**
+ * Writes each Project's list to that machine and reports what changed.
+ *
+ * A Project the machine does not have is not created here — creating a Project to hold a
+ * plugin list would invent a workspace nobody asked for. The models sync creates Projects
+ * because a Session cannot run without one; a plugin list has no such claim, so a missing
+ * Project is a refusal with its reason.
+ */
+export async function syncPluginsToMachine(opts: SyncPluginsOptions): Promise<PluginSyncOutcome> {
+ const written: string[] = [];
+ const added: string[] = [];
+ const removed: string[] = [];
+ const unresolved: string[] = [];
+ const refused: { projectId: string; detail: string }[] = [];
+ let restartPending = false;
+
+ for (const projectId of opts.projects) {
+ let want: string[];
+ try {
+ want = await opts.loadLocal(projectId);
+ } catch (err) {
+ refused.push({ projectId, detail: err instanceof Error ? err.message : String(err) });
+ continue;
+ }
+ // Read first: without knowing what is there, "added" and "removed" would be guesses, and
+ // a machine already in parity would still be written to on every connect.
+ const before = await opts.api.request("GET", pluginsPath(projectId));
+ if (before.status === 404) {
+ refused.push({ projectId, detail: await refusal404(opts.api, projectId) });
+ continue;
+ }
+ if (before.status !== 200) {
+ refused.push({ projectId, detail: `GET → ${before.status}: ${before.text.slice(0, 200)}` });
+ continue;
+ }
+ let had: string[];
+ try {
+ had = (JSON.parse(before.text) as InstalledPluginsResponse).plugins.map((p) => p.specifier);
+ } catch {
+ refused.push({ projectId, detail: "that machine's plugin list could not be read" });
+ continue;
+ }
+ const same = had.length === want.length && had.every((s, i) => s === want[i]);
+ if (same) continue;
+
+ const res = await opts.api.request("PUT", pluginsPath(projectId), { plugins: want });
+ if (res.status !== 200) {
+ refused.push({ projectId, detail: `PUT → ${res.status}: ${res.text.slice(0, 200)}` });
+ continue;
+ }
+ written.push(projectId);
+ for (const s of want) if (!had.includes(s)) added.push(s);
+ for (const s of had) if (!want.includes(s)) removed.push(s);
+ try {
+ const after = JSON.parse(res.text) as InstalledPluginsResponse;
+ if (after.restartPending) restartPending = true;
+ for (const row of after.plugins) {
+ if (row.error !== undefined && !unresolved.includes(row.specifier)) {
+ unresolved.push(row.specifier);
+ }
+ }
+ } catch {
+ // The write landed; only the report of it is unreadable.
+ }
+ }
+
+ return {
+ kind: "synced",
+ projects: written,
+ added: [...new Set(added)],
+ removed: [...new Set(removed)],
+ unresolved,
+ restartPending,
+ refused,
+ };
+}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index 66efdc50..9a62446e 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -27,19 +27,35 @@ import fs from "node:fs";
import os from "node:os";
import { DEFAULT_PROJECT_ID, VERSION, loadProjectConfig } from "@prismshadow/penguin-core";
import type { ProjectConfig } from "@prismshadow/penguin-core";
-import type { MachineInfo, MachineJob, MachineServerStatus } from "../api/types.js";
+import type {
+ MachineInfo,
+ MachineJob,
+ MachinePhase,
+ MachineServerStatus,
+ MachineUseRefusal,
+} from "../api/types.js";
import { readServerLock } from "../lock.js";
import { SESSION_COOKIE } from "../auth/middleware.js";
import http from "node:http";
import {
+ appendHostBlock,
closeAllConnections,
closeConnectionTo,
connectionTo,
listHostAliases,
+ readSshConfig,
sessionOf,
+ writeSshConfig,
} from "./transport/index.js";
import type { ExecResult, MachineConnection, ShellSession } from "./transport/index.js";
-import { machineIdentity } from "./ssh-config.js";
+import {
+ findHostBlock,
+ machineIdentity,
+ renderHostBlock,
+ replaceHostBlock,
+ validateHostEntry,
+} from "./ssh-config.js";
+import type { SshHostEntry, SshHostProblem } from "./ssh-config.js";
import { DIR_LIST_MARK, listDirsCommand } from "./commands.js";
import type { RemoteTarget } from "./commands.js";
import { installOnRemote, resolvePushPlan } from "./install-server.js";
@@ -48,6 +64,7 @@ import { upgradeRemote } from "./upgrade.js";
import type { UpgradeOutcome } from "./upgrade.js";
import { mintTokenOnRemote } from "./remote-token.js";
import { syncModelsToMachine } from "./models-sync.js";
+import { syncPluginsToMachine } from "./plugins-sync.js";
import type { LocalModels } from "./models-sync.js";
import { machineApi } from "./machine-api.js";
import { startRemoteServer, stopRemoteServer } from "./server-control.js";
@@ -66,6 +83,15 @@ import type { Db, Hmr, Paths } from "../hmr/capabilities.js";
import { currentRemoteLayout } from "./layout.js";
import type { RemoteLayout } from "./layout.js";
+/** A job's narrator: a line for the log, and optionally the step of the pipeline it begins. */
+type Say = (line: string, phase?: MachinePhase) => void;
+
+/** How often a machine recorded as held, and not held now, is tried again. */
+const KEEP_HELD_MS = 60_000;
+/** After a failed re-hold, the wait before the next try; doubles per failure up to the cap. */
+const REHOLD_BACKOFF_MIN_MS = 60_000;
+const REHOLD_BACKOFF_MAX_MS = 15 * 60_000;
+
/** Why an install was refused before any ssh ran. */
type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";
/** Why a connect was refused before any ssh ran. */
@@ -80,6 +106,10 @@ type ConnectRefusal = "busy" | "unknown-machine" | "not-installed" | "self" | "u
*/
export interface MachinesEffects {
listAliases: typeof listHostAliases;
+ /** The writes to the ssh config: appending a host block a person composed in the page, and rewriting one this app wrote. */
+ appendHost: typeof appendHostBlock;
+ readConfig: typeof readSshConfig;
+ writeConfig: typeof writeSshConfig;
resolvePlan: typeof resolvePushPlan;
install: typeof installOnRemote;
probe: typeof probeServerState;
@@ -150,6 +180,19 @@ export class MachinesService {
readonly #machineId: string;
/** Which installation on each machine this instance reaches — its profile's (layout.ts). */
readonly #layout: RemoteLayout;
+ /** Jobs waiting their turn, in order; the running one has left this list. */
+ readonly #queue: Array<{
+ job: MachineJob;
+ opts: { offerReplaceProgram: boolean };
+ work: (say: Say) => Promise<MachineJob["result"]>;
+ }> = [];
+ /** The latest job per machine — queued, running or finished — for the page's rows. */
+ readonly #jobs = new Map<string, MachineJob>();
+ /** The standing intent: while this App lives, machines recorded as held are re-held when found dropped. */
+ #keepHeld: ReturnType<typeof setInterval> | null = null;
+ /** Per machine, when the next re-hold may be tried (epoch ms) and how many tries have failed in a row. */
+ readonly #reholdNotBefore = new Map<string, number>();
+ readonly #reholdFailures = new Map<string, number>();
constructor(
private readonly dataRoot: string,
@@ -164,6 +207,9 @@ export class MachinesService {
this.#layout = layout;
this.#effects = {
listAliases: listHostAliases,
+ appendHost: appendHostBlock,
+ readConfig: readSshConfig,
+ writeConfig: writeSshConfig,
resolvePlan: resolvePushPlan,
install: installOnRemote,
probe: probeServerState,
@@ -274,10 +320,17 @@ export class MachinesService {
id: LOCAL_MACHINE_ID,
alias: os.hostname(),
machineId: this.#machineId,
- installed: { version: VERSION, at: lock?.startedAt ?? this.#effects.now().toISOString() },
+ // The build this process carries, not the package's release number: a hot-pushed
+ // server runs `0.2.9+hmr.<hash>`, and that is what it would install elsewhere, so it
+ // is what "this server" must say of itself — or the fleet reads as behind the wrong thing.
+ installed: {
+ version: this.imageVersion() ?? VERSION,
+ at: lock?.startedAt ?? this.#effects.now().toISOString(),
+ },
local: true,
connection: null,
api: null,
+ root: this.dataRoot,
status: {
state: "running",
checkedAt: this.#effects.now().toISOString(),
@@ -301,6 +354,9 @@ export class MachinesService {
local: false,
connection: session === null ? null : { pid: session.pid },
api: this.#apiSeen.get(id) ?? null,
+ // The layout's own spelling, in the shell that machine speaks. Unknown platform
+ // reads as POSIX: it is the majority, and an install corrects the record.
+ root: row?.platform === "win32" ? this.#layout.dataRoot.win : this.#layout.dataRoot.posix,
status: this.#statuses.get(id) ?? null,
};
});
@@ -532,39 +588,104 @@ export class MachinesService {
// --- jobs ---------------------------------------------------------------------------------
+ /**
+ * Queues a job. Up to CONCURRENCY machines are worked on at once — different hosts, so
+ * their ssh sessions and transfers do not contend — and one job per machine at a time; the
+ * rest wait in order, and each job knows whether it is waiting or working. Failures land
+ * in the job; nothing here throws.
+ */
#startJob(
kind: MachineJob["kind"],
machine: MachineInfo,
- work: (say: (line: string) => void) => Promise<MachineJob["result"]>,
+ /**
+ * Whether a failure offers installing the program anyway. Every failed install or
+ * connect does — a failure that leaves no next step leaves a person stuck — except a
+ * run that was itself that install, and a result that withholds it (`canReplaceProgram:
+ * false`, this server having nothing to send). Never taken on the page's own
+ * initiative: it stops a server other people may be using.
+ */
+ opts: { offerReplaceProgram: boolean },
+ work: (say: Say) => Promise<MachineJob["result"]>,
): void {
const job: MachineJob = {
kind,
machineId: machine.id,
alias: machine.alias,
- running: true,
+ queued: true,
+ running: false,
+ phase: null,
log: [],
result: null,
};
+ // One row per machine: a machine queued twice keeps the later ask (the earlier one is
+ // dropped from the queue), and a finished job is replaced by the next one on the same
+ // machine. A job already running is left to finish; the new one waits behind it.
+ const waiting = this.#queue.findIndex((entry) => entry.job.machineId === machine.id);
+ if (waiting !== -1) this.#queue.splice(waiting, 1);
+ this.#jobs.set(machine.id, job);
+ this.#queue.push({ job, opts, work });
+ this.#drain();
+ }
+
+ /** How many jobs are working right now. */
+ #runningCount(): number {
+ let n = 0;
+ for (const job of this.#jobs.values()) if (job.running) n += 1;
+ return n;
+ }
+
+ /** Whether any job is working — what the single-machine starters call "busy". */
+ #anyRunning(): boolean {
+ return this.#runningCount() > 0;
+ }
+
+ /** Starts queued jobs until CONCURRENCY are working; each one drains again as it ends. */
+ #drain(): void {
+ while (this.#runningCount() < CONCURRENCY) {
+ const next = this.#queue.shift();
+ if (next === undefined) return;
+ void this.#run(next.job, next.opts, next.work);
+ }
+ }
+
+ async #run(
+ job: MachineJob,
+ opts: { offerReplaceProgram: boolean },
+ work: (say: Say) => Promise<MachineJob["result"]>,
+ ): Promise<void> {
+ job.queued = false;
+ job.running = true;
this.#job = job;
- const say = (line: string) => {
+ const say: Say = (line, phase) => {
job.log.push(line);
+ if (phase !== undefined) job.phase = phase;
};
- // Not awaited: the caller is an HTTP handler answering 202. Failures land in the job.
- void (async () => {
- try {
- this.#busy.add(machine.id);
- job.result = await work(say);
- } catch (err) {
- job.result = {
- ok: false,
- step: kind,
- message: err instanceof Error ? err.message : String(err),
- };
- } finally {
- this.#busy.delete(machine.id);
- job.running = false;
+ try {
+ this.#busy.add(job.machineId);
+ job.result = await work(say);
+ } catch (err) {
+ job.result = {
+ ok: false,
+ step: job.kind,
+ message: err instanceof Error ? err.message : String(err),
+ };
+ } finally {
+ if (
+ opts.offerReplaceProgram &&
+ job.result?.ok === false &&
+ job.result.canReplaceProgram === undefined
+ ) {
+ job.result = { ...job.result, canReplaceProgram: true };
}
- })();
+ this.#busy.delete(job.machineId);
+ job.running = false;
+ }
+ this.#drain();
+ }
+
+ /** The queued, the running and the last finished job per machine — what the page lists. */
+ jobs(): MachineJob[] {
+ return [...this.#jobs.values()];
}
/**
@@ -576,13 +697,13 @@ export class MachinesService {
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.
+ * Install the program even when its version already matches, and restart it. Every
+ * failed job offers it (see `canReplaceProgram`); never taken on the page's own
+ * initiative, 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" };
+ if (this.#anyRunning()) return { ok: false, why: "busy" };
const machine = this.#allMachines().find((entry) => entry.id === address);
if (machine === undefined) return { ok: false, why: "unknown-machine" };
// Never this machine: a server does not push this build over its own program directory
@@ -595,124 +716,267 @@ export class MachinesService {
}
const plan = this.#effects.resolvePlan(this.dataRoot);
if (plan === null) return { ok: false, why: "no-image" };
- const target = this.#targetOf(machine.alias);
- this.#startJob("install", machine, async (say) => {
- say(`Installing ${plan.version} on ${machineIdentity(target.alias, target.user)}…`);
- // Only the machine can say whether this alias is this host under another name.
- // Unreachable is not a refusal — a host with nothing installed yet answers exactly
- // that — this server's own id is.
- const heard = await this.#effects.probe(target, this.#layout, this.#effects.runOn, null);
- this.#rememberMachineId(address, heard.machineId);
- if (heard.machineId !== null && heard.machineId === this.#machineId) {
+ this.#startJob("install", machine, { offerReplaceProgram: !replaceProgram }, (say) =>
+ this.#installWork(projectId, machine, plan, replaceProgram, say),
+ );
+ return { ok: true };
+ }
+
+ /** The install as one run: probe, install, hand over, restart, record — the body every install job runs. */
+ async #installWork(
+ projectId: string,
+ machine: MachineInfo,
+ plan: NonNullable<ReturnType<MachinesEffects["resolvePlan"]>>,
+ replaceProgram: boolean,
+ say: Say,
+ ): Promise<MachineJob["result"]> {
+ const address = machine.id;
+ const target = this.#targetOf(machine.alias);
+ say(`Installing ${plan.version} on ${machineIdentity(target.alias, target.user)}…`, "check");
+ // Only the machine can say whether this alias is this host under another name.
+ // Unreachable is not a refusal — a host with nothing installed yet answers exactly
+ // that — this server's own id is.
+ const heard = await this.#effects.probe(target, this.#layout, this.#effects.runOn, null);
+ this.#rememberMachineId(address, heard.machineId);
+ if (heard.machineId !== null && heard.machineId === this.#machineId) {
+ return {
+ ok: false,
+ step: "connect",
+ message:
+ "That alias reaches this very machine — it answered with this server's own id. A server does not push this build over the program directory it is running from.",
+ };
+ }
+ say("Putting the program there…", "install");
+ const outcome = await this.#effects.install({
+ target,
+ plan,
+ onProgress: say,
+ assets: this.#assets,
+ layout: this.#layout,
+ ...(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…", "handover");
+ 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: "connect",
+ step: "hand over the pushed build",
message:
- "That alias reaches this very machine — it answered with this server's own id. A server does not push this build over the program directory it is running from.",
+ 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,
+ // Installing anyway — every failed job's offer (#startJob) — is what replicates
+ // the store the update channel needs; withheld for `no-build`, this server's own
+ // lack, which installing would not mend.
+ ...(pushed.kind === "no-build" ? { canReplaceProgram: false as const } : {}),
};
- }
- const outcome = await this.#effects.install({
- target,
- plan,
- onProgress: say,
- assets: this.#assets,
- layout: this.#layout,
- ...(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;
- // 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);
- if (!restarted.ok) {
+ } 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: "restart its server",
- message: `installed, but ${restarted.detail} The old process is still serving; restart it.`,
+ 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.",
};
+ } else {
+ say(pushed.detail === "" ? "Update accepted." : pushed.detail);
}
+ }
+ const version = outcome.kind === "already-installed" ? outcome.version : plan.version;
+ // 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);
+ if (!restarted.ok) {
return {
- ok: true,
- installed: outcome.kind === "state-only" ? "installed" : outcome.kind,
- version,
+ 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,
+ };
+ }
+
+ /**
+ * Adds a host to this server's ssh config, so it can be enabled like any other. The block
+ * is validated before anything is written, and an alias the config already declares is
+ * refused rather than shadowed: ssh takes the first block that matches, so a second one
+ * would be silently ignored and the person would wonder why their edit did nothing.
+ */
+ addSshHost(
+ entry: SshHostEntry,
+ ):
+ | { ok: true }
+ | { ok: false; why: "invalid"; problem: SshHostProblem }
+ | { ok: false; why: "exists" } {
+ const problem = validateHostEntry(entry);
+ if (problem !== null) return { ok: false, why: "invalid", problem };
+ if (this.#effects.listAliases().includes(entry.alias.trim()))
+ return { ok: false, why: "exists" };
+ this.#effects.appendHost(renderHostBlock(entry, this.#effects.now()));
return { ok: true };
}
+ /**
+ * A host's block as the page can show it back: what it says, and whether this app wrote
+ * it — only then may the page rewrite it. A hand-written block may carry options this app
+ * does not know (a jump host, a key agent setting), and rewriting it would drop them.
+ */
+ sshHost(alias: string): { entry: SshHostEntry; editable: boolean } | null {
+ const text = this.#effects.readConfig();
+ if (text === null) return null;
+ const found = findHostBlock(text, alias);
+ return found === null ? null : { entry: found.entry, editable: found.ours };
+ }
+
+ /** Rewrites, in place, a block this app wrote; the alias stays, everything else is the new entry. */
+ updateSshHost(
+ alias: string,
+ entry: Omit<SshHostEntry, "alias">,
+ ):
+ | { ok: true }
+ | { ok: false; why: "invalid"; problem: SshHostProblem }
+ | { ok: false; why: "not-found" }
+ | { ok: false; why: "foreign" } {
+ const next: SshHostEntry = { ...entry, alias };
+ const problem = validateHostEntry(next);
+ if (problem !== null) return { ok: false, why: "invalid", problem };
+ const text = this.#effects.readConfig();
+ if (text === null) return { ok: false, why: "not-found" };
+ const found = findHostBlock(text, alias);
+ if (found === null) return { ok: false, why: "not-found" };
+ if (!found.ours) return { ok: false, why: "foreign" };
+ this.#effects.writeConfig(
+ replaceHostBlock(text, found, renderHostBlock(next, this.#effects.now())),
+ );
+ return { ok: true };
+ }
+
+ /**
+ * Brings machines into use, as one queued batch: for each, install (or bring the build
+ * forward) if the record says it is not on this server's build, then connect and hand it
+ * the Model config — the whole of what a person means by "use this machine", as one job
+ * per machine, one after another. Refusals decidable without ssh are answered by id, so
+ * the page can say them; everything else is queued and reported through `jobs`.
+ */
+ startUse(
+ projectId: string,
+ addresses: readonly string[],
+ replaceProgram = false,
+ ): { refused: { machineId: string; why: MachineUseRefusal }[] } {
+ const refused: { machineId: string; why: MachineUseRefusal }[] = [];
+ const plan = this.#effects.resolvePlan(this.dataRoot);
+ for (const address of new Set(addresses)) {
+ const machine = this.#allMachines().find((entry) => entry.id === address);
+ if (machine === undefined) {
+ refused.push({ machineId: address, why: "unknown-machine" });
+ continue;
+ }
+ if (machine.local || (machine.machineId !== null && machine.machineId === this.#machineId)) {
+ refused.push({ machineId: address, why: "self" });
+ continue;
+ }
+ if (plan === null) {
+ refused.push({ machineId: address, why: "no-image" });
+ continue;
+ }
+ this.#startJob("use", machine, { offerReplaceProgram: !replaceProgram }, (say) =>
+ this.#useWork(projectId, address, plan, replaceProgram, say),
+ );
+ }
+ return { refused };
+ }
+
+ /** One machine's "use": install where the record says the build is missing or different, then connect. */
+ async #useWork(
+ projectId: string,
+ address: string,
+ plan: NonNullable<ReturnType<MachinesEffects["resolvePlan"]>>,
+ replaceProgram: boolean,
+ say: Say,
+ ): Promise<MachineJob["result"]> {
+ // Read at run time, not at queue time: a batch's later rows see what the earlier ones did.
+ const machine = this.#allMachines().find((entry) => entry.id === address);
+ if (machine === undefined) {
+ return { ok: false, step: "use", message: "that host is no longer in the ssh config." };
+ }
+ const needsInstall =
+ replaceProgram || machine.installed === null || machine.installed.version !== plan.version;
+ if (needsInstall) {
+ const installed = await this.#installWork(projectId, machine, plan, replaceProgram, say);
+ if (installed !== null && !installed.ok) return installed;
+ } else {
+ say(`Already on ${plan.version}.`, "check");
+ // The Project that asked is the Project that uses it, install or no install.
+ this.#setMember(projectId, address, true);
+ }
+ // A Windows machine has no shell to hold a session on (see startConnect): installed is
+ // as far as "use" goes there, and the page says so from the platform on record.
+ if (this.repo.get(address)?.platform === "win32") {
+ return { ok: true, installed: "already-installed", version: plan.version };
+ }
+ const fresh = this.#allMachines().find((entry) => entry.id === address) ?? machine;
+ return this.#connect(fresh, say);
+ }
+
+ /**
+ * Lets go of machines: the connection is dropped and the Project stops listing them. The
+ * install over there stays — another Project may use it, and "stop using" is not "wipe".
+ * With the record's held mark cleared, nothing re-holds them on the next boot either.
+ */
+ stopUsing(projectId: string, addresses: readonly string[]): void {
+ for (const address of new Set(addresses)) {
+ this.disconnect(address);
+ this.release(projectId, address);
+ }
+ }
+
/**
* Brings a machine's server up and holds the connection to it, as a job — a start plus a
* readiness wait is minutes in the bad case. Every step is idempotent, so a repeat is safe.
*/
async startConnect(address: string): Promise<{ ok: true } | { ok: false; why: ConnectRefusal }> {
- if (this.#job?.running === true) return { ok: false, why: "busy" };
+ if (this.#anyRunning()) return { ok: false, why: "busy" };
const machine = this.#allMachines().find((entry) => entry.id === address);
if (machine === undefined) return { ok: false, why: "unknown-machine" };
// The machine's own id is what settles "that is here": the alias may point back home.
@@ -725,11 +989,13 @@ export class MachinesService {
// it with. Said here, in one sentence, rather than discovered as a POSIX command failing
// under cmd.exe in the job's log.
if (this.repo.get(address)?.platform === "win32") return { ok: false, why: "unsupported" };
- this.#startJob("connect", machine, (say) => this.#connect(machine, say));
+ this.#startJob("connect", machine, { offerReplaceProgram: true }, (say) =>
+ this.#connect(machine, say),
+ );
return { ok: true };
}
- async #connect(machine: MachineInfo, say: (line: string) => void): Promise<MachineJob["result"]> {
+ async #connect(machine: MachineInfo, say: Say): Promise<MachineJob["result"]> {
const address = machine.id;
const target = this.#targetOf(machine.alias);
@@ -738,20 +1004,14 @@ export class MachinesService {
// dead server — and every caller that then found the machine silent asked for another
// connect, which said "already connected" again, forever. Reconnecting (to retry a sync
// that failed, or pick up a new key) now costs one probe and stays honest.
- say("Asking what is running there…");
+ say("Asking what is running there…", "check");
const probed = await this.#probe(address, target);
this.#recordProbe(address, probed);
if (probed.state.kind === "unreachable") {
- // 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 same dead end an install reaches, and the same way out — installing anyway,
+ // which every failed job offers (#startJob): the machine cannot answer because the
+ // CLI in its store is not one this server can talk to, and the installer replaces it.
+ return { ok: false, step: "connect", message: probed.state.detail };
}
// 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
@@ -782,13 +1042,14 @@ export class MachinesService {
if (after.state.kind === "running") remotePort = after.state.port;
}
- say("Opening the connection…");
+ say("Opening the connection…", "connect");
const connection = await this.#connection(address, target);
if (!connection.ok) return { ok: false, step: "connect", message: connection.detail };
this.repo.patch(address, { remotePort });
say(`Connected; its server is on port ${remotePort} over there.`);
// An Agent started over there resolves its model against THAT machine's config, so a
// machine without our credentials is connected and unusable.
+ say("Handing over the Model config…", "sync");
await this.#syncModels(address, target, remotePort, say, this.#projectsUsing(address));
return { ok: true, connected: true };
}
@@ -821,6 +1082,14 @@ export class MachinesService {
// config handed over as it connects lands on the build that will read it.
await this.syncOutOfDate();
await this.autoConnect();
+ // Held is a standing intent, not a boot-time attempt: a machine that could not be
+ // re-held at boot — the network still settling, its server not yet up — or that drops
+ // later and whose session did not come back, is tried again on a widening wait until it
+ // is held or a person stops using it. Unref'd: a timer must not keep a process alive.
+ if (this.#keepHeld === null) {
+ this.#keepHeld = setInterval(() => void this.autoConnect(), KEEP_HELD_MS);
+ this.#keepHeld.unref?.();
+ }
}
/**
@@ -829,6 +1098,8 @@ export class MachinesService {
* Nothing here closes by a remembered pid: the child handles are this generation's own.
*/
stop(): void {
+ if (this.#keepHeld !== null) clearInterval(this.#keepHeld);
+ this.#keepHeld = null;
closeAllConnections();
}
@@ -839,7 +1110,7 @@ export class MachinesService {
address: string,
target: RemoteTarget,
port: number,
- say: (line: string) => void,
+ say: Say,
projects: string[],
): Promise<void> {
if (projects.length === 0) {
@@ -865,9 +1136,41 @@ export class MachinesService {
for (const { projectId, detail } of outcome.refused) {
say(`Models of ${projectId} not synced — ${detail}`);
}
+ // Same session, same Projects: a plugin a Project asks for has to be loaded on the
+ // machine that will run its Sessions, and enabling it once per machine by hand is not
+ // a path this product has (PRFC-0010).
+ const plugins = await syncPluginsToMachine({
+ api: machineApi(this.#effects.agent(target, port), port, session.cookie),
+ loadLocal: (projectId) => this.#localPlugins(projectId),
+ projects,
+ });
+ if (plugins.kind === "failed") {
+ say(`Plugins not synced — ${plugins.detail}`);
+ return;
+ }
+ if (plugins.added.length > 0) say(`Plugins added there: ${plugins.added.join(", ")}.`);
+ if (plugins.removed.length > 0) say(`Plugins removed there: ${plugins.removed.join(", ")}.`);
+ if (plugins.unresolved.length > 0) {
+ say(
+ `Listed there but not resolvable — that machine may need updating first: ${plugins.unresolved.join(", ")}.`,
+ );
+ }
+ if (plugins.restartPending) say(`That machine restarts to finish loading its plugins.`);
+ for (const { projectId, detail } of plugins.refused) {
+ say(`Plugins of ${projectId} not synced — ${detail}`);
+ }
void address;
}
+ /**
+ * What a Project asks for, by package name — the machine's list takes names; an unreadable
+ * config syncs nothing rather than emptying the machine.
+ */
+ async #localPlugins(projectId: string): Promise<string[]> {
+ const config = await this.#effects.loadConfig(projectId);
+ return Object.keys(config.plugins ?? {});
+ }
+
/**
* A sync of the given Projects to a machine, coalesced: while one runs, a second ask marks
* it to run once more when it ends. The trailing run reads the config fresh, so however
@@ -921,11 +1224,7 @@ 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> {
+ async #handOverBuild(address: string, target: RemoteTarget, say: Say): Promise<UpgradeOutcome> {
const probed = await this.#effects.probe(
target,
this.#layout,
@@ -966,7 +1265,7 @@ export class MachinesService {
async #restartServer(
address: string,
target: RemoteTarget,
- say: (line: string) => void,
+ say: Say,
): Promise<{ ok: true; port: number } | { ok: false; detail: string }> {
const before = await this.#effects.probe(
target,
@@ -979,7 +1278,7 @@ export class MachinesService {
return { ok: false, detail: "no server is running on that machine." };
}
const port = before.state.port;
- say(`Stopping its server on port ${port}…`);
+ say(`Stopping its server on port ${port}…`, "restart");
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,
@@ -1002,12 +1301,12 @@ export class MachinesService {
* 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" };
+ if (this.#anyRunning()) 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) => {
+ this.#startJob("restart", machine, { offerReplaceProgram: false }, 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 };
@@ -1025,7 +1324,7 @@ export class MachinesService {
async #restartAfterInstall(
address: string,
target: RemoteTarget,
- say: (line: string) => void,
+ say: Say,
): Promise<{ ok: true } | { ok: false; detail: string }> {
const before = await this.#effects.probe(
target,
@@ -1097,21 +1396,37 @@ export class MachinesService {
});
}
- /** Re-holds every machine recorded as held that this generation does not yet hold. */
+ /**
+ * Re-holds every machine recorded as held that this generation does not hold now — at
+ * boot, and every KEEP_HELD_MS after. A machine whose re-hold failed waits out a backoff
+ * that doubles per failure, so a host that is down for an hour costs a try every fifteen
+ * minutes and one that blinked is back within the minute; a success resets it.
+ */
async autoConnect(): Promise<void> {
+ const now = this.#effects.now().getTime();
const unconnected = this.#allMachines().filter(
(m) =>
!m.local &&
m.installed !== null &&
m.connection === null &&
this.repo.get(m.id)?.sessionPid != null &&
- this.repo.get(m.id)?.platform !== "win32",
+ this.repo.get(m.id)?.platform !== "win32" &&
+ (this.#reholdNotBefore.get(m.id) ?? 0) <= now,
);
await this.#sweep(
unconnected.map((m) => m.id),
async (address) => {
const machine = unconnected.find((m) => m.id === address)!;
- await this.#connect(machine, () => {});
+ const result = await this.#connect(machine, () => {});
+ if (result !== null && result.ok) {
+ this.#reholdNotBefore.delete(address);
+ this.#reholdFailures.delete(address);
+ return;
+ }
+ const failures = (this.#reholdFailures.get(address) ?? 0) + 1;
+ this.#reholdFailures.set(address, failures);
+ const wait = Math.min(REHOLD_BACKOFF_MIN_MS * 2 ** (failures - 1), REHOLD_BACKOFF_MAX_MS);
+ this.#reholdNotBefore.set(address, this.#effects.now().getTime() + wait);
},
);
}
@@ -1124,6 +1439,11 @@ export class MachinesService {
* to run once more (#syncCoalesced), and an install in flight on the machine is not a
* reason to lose a credential either — the two do not contend for the shell.
*/
+ /**
+ * Both syncs travel together (see #syncModels), so this is also how a plugin change
+ * reaches the fleet. Named for the models because that is what it was, and renaming an
+ * interface member is a contract change a pushed platform pays for.
+ */
async syncModelsEverywhere(projectId: string): Promise<void> {
const connected = this.list(projectId).filter(
(m) => !m.local && m.installed !== null && m.connection !== null,
@@ -1149,7 +1469,19 @@ export class MachinesService {
export abstract class Machines extends Interface<
Pick<
MachinesService,
- "list" | "imageVersion" | "job" | "startInstall" | "start" | "syncModelsEverywhere"
+ | "list"
+ | "imageVersion"
+ | "job"
+ | "startInstall"
+ | "start"
+ | "syncModelsEverywhere"
+ | "proxyTarget"
+ | "jobs"
+ | "startUse"
+ | "stopUsing"
+ | "addSshHost"
+ | "sshHost"
+ | "updateSshHost"
>
>() {}
diff --git a/packages/server/src/machines/ssh-config.ts b/packages/server/src/machines/ssh-config.ts
index ca108195..d779d9fa 100644
--- a/packages/server/src/machines/ssh-config.ts
+++ b/packages/server/src/machines/ssh-config.ts
@@ -1,8 +1,10 @@
/**
- * Reading `~/.ssh/config` for its host aliases — the only thing this app takes from it. We
- * never write it, never keep a host list of our own, and never resolve it: what an alias
- * means (user, host, port, key, jump host) is ssh's business, applied by ssh itself every
- * time it is handed the alias, so nothing here can go stale against a config a person edits.
+ * `~/.ssh/config` as this app touches it: reading it for its host aliases, and appending a
+ * host block a person composed in the Machines page. We never keep a host list of our own
+ * and never resolve an alias: what it means (user, host, port, key, jump host) is ssh's
+ * business, applied by ssh itself every time it is handed the alias, so nothing here can go
+ * stale against a config a person edits by hand. The one write is an append of a block in
+ * ssh's own syntax — the same lines the person would have typed — so the file stays theirs.
*
* `parseHostAliases` scans the config text for candidate aliases, following `Include`
* through a caller-supplied reader. It exists only because OpenSSH has no "list hosts"
@@ -65,3 +67,128 @@ export function parseHostAliases(
export function machineIdentity(alias: string, user: string): string {
return user === "" ? alias : `${user}@${alias}`;
}
+
+/** A host block as the Machines page composes it: the alias, and what ssh needs to reach it. */
+export interface SshHostEntry {
+ alias: string;
+ hostName: string;
+ user?: string;
+ port?: number;
+ identityFile?: string;
+}
+
+/** Which field of an entry cannot be written, and why. */
+export interface SshHostProblem {
+ field: keyof SshHostEntry;
+ why: "required" | "invalid";
+}
+
+/** A value that fits on one config line as one token: no whitespace, no comment, no newline. */
+const isToken = (value: string) => value !== "" && !/[\s#]/.test(value);
+
+/**
+ * The first thing wrong with an entry, or null. Strict where ssh is lenient, because this
+ * block is appended to a file a person also edits: an alias with a glob character would
+ * declare a pattern, a value with a space would need quoting we do not do, and a `#` would
+ * comment out the rest of its own line.
+ */
+export function validateHostEntry(entry: SshHostEntry): SshHostProblem | null {
+ if (entry.alias.trim() === "") return { field: "alias", why: "required" };
+ if (!isToken(entry.alias) || isPattern(entry.alias)) return { field: "alias", why: "invalid" };
+ if (entry.hostName.trim() === "") return { field: "hostName", why: "required" };
+ if (!isToken(entry.hostName)) return { field: "hostName", why: "invalid" };
+ if (entry.user !== undefined && entry.user !== "" && !isToken(entry.user)) {
+ return { field: "user", why: "invalid" };
+ }
+ if (
+ entry.port !== undefined &&
+ (!Number.isInteger(entry.port) || entry.port < 1 || entry.port > 65535)
+ ) {
+ return { field: "port", why: "invalid" };
+ }
+ if (
+ entry.identityFile !== undefined &&
+ entry.identityFile !== "" &&
+ !isToken(entry.identityFile)
+ ) {
+ return { field: "identityFile", why: "invalid" };
+ }
+ return null;
+}
+
+/**
+ * The block as ssh reads it, led by a comment naming who wrote it and when — so a person
+ * reading their config later knows the lines are not theirs and may edit or drop them.
+ * Options ssh would ignore for being empty are left out rather than written blank.
+ */
+export function renderHostBlock(entry: SshHostEntry, at: Date): string {
+ const lines = [
+ `# Added by PenguinHarness on ${at.toISOString()}`,
+ `Host ${entry.alias.trim()}`,
+ ` HostName ${entry.hostName.trim()}`,
+ ];
+ if (entry.user !== undefined && entry.user !== "") lines.push(` User ${entry.user.trim()}`);
+ if (entry.port !== undefined) lines.push(` Port ${entry.port}`);
+ if (entry.identityFile !== undefined && entry.identityFile !== "") {
+ lines.push(` IdentityFile ${entry.identityFile.trim()}`);
+ }
+ return lines.join("\n") + "\n";
+}
+
+/** The comment `renderHostBlock` leads with; a block that carries it is one this app wrote. */
+const MARKER = /^# Added by PenguinHarness on /;
+const OPTION = /^(\S+)\s+(.*)$/;
+
+/** A host block found in a config: its lines (`start` to `end`, exclusive), what it says, and whether this app wrote it. */
+export interface HostBlockFound {
+ start: number;
+ end: number;
+ entry: SshHostEntry;
+ ours: boolean;
+}
+
+/**
+ * The block declaring exactly `alias` — a `Host` line naming that one alias and nothing
+ * else — with the options this app knows read back out of it. The block runs to the next
+ * `Host` or `Match` line or the end of the file, less any trailing blank lines, and takes in
+ * the marker comment above it when there is one, so replacing the block replaces the
+ * comment too. A `Host a b` line is not a match: it configures two aliases at once, and
+ * rewriting it as one would drop the other.
+ */
+export function findHostBlock(text: string, alias: string): HostBlockFound | null {
+ const lines = text.split("\n");
+ for (let i = 0; i < lines.length; i++) {
+ const host = HOST_KEYWORD.exec(lines[i]!.trim());
+ if (!host) continue;
+ const aliases = host[1]!.split(/\s+/).filter((entry) => entry !== "");
+ if (aliases.length !== 1 || aliases[0] !== alias) continue;
+ let end = i + 1;
+ while (end < lines.length && !/^(host|match)\s/i.test(lines[end]!.trim())) end++;
+ while (end > i + 1 && lines[end - 1]!.trim() === "") end--;
+ const ours = i > 0 && MARKER.test(lines[i - 1]!.trim());
+ const entry: SshHostEntry = { alias, hostName: "" };
+ for (const raw of lines.slice(i + 1, end)) {
+ const line = raw.trim();
+ if (line === "" || line.startsWith("#")) continue;
+ const option = OPTION.exec(line);
+ if (!option) continue;
+ const key = option[1]!.toLowerCase();
+ const value = option[2]!.trim();
+ if (key === "hostname") entry.hostName = value;
+ else if (key === "user") entry.user = value;
+ else if (key === "port") {
+ const port = Number(value);
+ if (Number.isInteger(port)) entry.port = port;
+ } else if (key === "identityfile") entry.identityFile = value;
+ }
+ return { start: ours ? i - 1 : i, end, entry, ours };
+ }
+ return null;
+}
+
+/** The config with `found`'s lines replaced by a freshly rendered block. */
+export function replaceHostBlock(text: string, found: HostBlockFound, block: string): string {
+ const lines = text.split("\n");
+ lines.splice(found.start, found.end - found.start, ...block.replace(/\n$/, "").split("\n"));
+ return lines.join("\n");
+}
diff --git a/packages/server/src/machines/transport/index.ts b/packages/server/src/machines/transport/index.ts
index 07d4c4c1..869c43c7 100644
--- a/packages/server/src/machines/transport/index.ts
+++ b/packages/server/src/machines/transport/index.ts
@@ -22,4 +22,4 @@ export { sessionOf } from "./ssh-session.js";
export type { ShellSession } from "./ssh-session.js";
export { execFailureText, looksLikeAuthFailure, runBytes } from "./exec.js";
export type { ExecResult } from "./exec.js";
-export { listHostAliases } from "./targets.js";
+export { appendHostBlock, listHostAliases, readSshConfig, writeSshConfig } from "./targets.js";
diff --git a/packages/server/src/machines/transport/targets.ts b/packages/server/src/machines/transport/targets.ts
index 6b0341ee..bd3ea725 100644
--- a/packages/server/src/machines/transport/targets.ts
+++ b/packages/server/src/machines/transport/targets.ts
@@ -1,6 +1,7 @@
/**
- * Turning `~/.ssh/config` into the list of aliases the menu can show. The parsing is in
- * ssh-config.ts; this file owns the I/O — reading files and expanding `Include` globs.
+ * Turning `~/.ssh/config` into the list of aliases the menu can show, and appending a host
+ * block to it. The parsing and the rendering are in ssh-config.ts; this file owns the I/O —
+ * reading files, expanding `Include` globs, and the one append.
*
* Nothing here resolves an alias: what it means is ssh's business, applied by ssh itself
* every time it is handed one. An unreadable or missing config degrades to "no targets"
@@ -56,3 +57,37 @@ export function listHostAliases(): string[] {
return [];
}
}
+
+/**
+ * Appends a rendered host block to `~/.ssh/config`, creating the directory and the file with
+ * the modes ssh insists on when they do not exist yet (0700 and 0600; ssh refuses a config
+ * others can write). A blank line separates the block from whatever came before, and a file
+ * that did not end in a newline gets one first, so the block never joins a foreign line.
+ */
+export function appendHostBlock(block: string): void {
+ const dir = SSH_DIR();
+ const file = path.join(dir, "config");
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ let existing = "";
+ try {
+ existing = fs.readFileSync(file, "utf8");
+ } catch {
+ fs.writeFileSync(file, "", { mode: 0o600 });
+ }
+ const lead = existing === "" ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
+ fs.appendFileSync(file, lead + block);
+}
+
+/** The config's text, or null when there is none to read. */
+export function readSshConfig(): string | null {
+ try {
+ return fs.readFileSync(path.join(SSH_DIR(), "config"), "utf8");
+ } catch {
+ return null;
+ }
+}
+
+/** Writes the config back whole — after a block this app wrote was rewritten in place. */
+export function writeSshConfig(text: string): void {
+ fs.writeFileSync(path.join(SSH_DIR(), "config"), text, { mode: 0o600 });
+}
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index 1250b93f..87e923ae 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -573,8 +573,9 @@ describe("migration 8 → current: model-promotions", () => {
"model-promotions",
"model-provider-auth-tokens",
"sessions-sandbox",
+ "machines-columns",
]);
- expect(schemaVersion(db)).toBe(11);
+ expect(schemaVersion(db)).toBe(12);
expect(promotionsTableExists()).toEqual({ "1": 1 });
expect(authTokensTableExists()).toEqual({ "1": 1 });
@@ -594,8 +595,9 @@ describe("migration 8 → current: model-promotions", () => {
"model-promotions",
"model-provider-auth-tokens",
"sessions-sandbox",
+ "machines-columns",
]);
- expect(schemaVersion(db)).toBe(11);
+ expect(schemaVersion(db)).toBe(12);
} finally {
db.close();
}
@@ -612,8 +614,12 @@ describe("migration 9 → current: model-provider-auth-tokens", () => {
)
.get();
try {
- expect(migrate(db).applied).toEqual(["model-provider-auth-tokens", "sessions-sandbox"]);
- expect(schemaVersion(db)).toBe(11);
+ expect(migrate(db).applied).toEqual([
+ "model-provider-auth-tokens",
+ "sessions-sandbox",
+ "machines-columns",
+ ]);
+ expect(schemaVersion(db)).toBe(12);
expect(tableExists()).toEqual({ "1": 1 });
db.exec(
"INSERT INTO users (user_id, password_hash, is_admin, created_at)" +
@@ -686,6 +692,45 @@ describe("0.2.4 → current", () => {
});
});
+describe("a machines table from before migration 4", () => {
+ /** The machines table as the machines line created it before release: forwards, no session, no platform. */
+ const ADOPTED_MACHINES_DDL = `
+ CREATE TABLE machines (
+ address TEXT PRIMARY KEY,
+ machine_id TEXT,
+ version TEXT,
+ installed_at TEXT,
+ forward_port INTEGER,
+ forward_pid INTEGER,
+ remote_port INTEGER
+ );
+ `;
+
+ it("is adopted by migration 4 as it stands, and gains the columns the row writes at 10", () => {
+ // What a data root that ran the machines line before its migration holds: IF NOT EXISTS
+ // kept the table, and the first connect failed on the insert naming session_pid.
+ const db = open029();
+ try {
+ db.exec(ADOPTED_MACHINES_DDL);
+ db.exec("PRAGMA user_version = 3");
+ expect(migrate(db).applied).toEqual(
+ MIGRATIONS.filter((m) => m.version > 3).map((m) => m.name),
+ );
+ const columns = (db.prepare("PRAGMA table_info(machines)").all() as { name: string }[]).map(
+ (c) => c.name,
+ );
+ expect(columns).toEqual(expect.arrayContaining(["session_pid", "platform"]));
+ db.prepare(
+ "INSERT INTO machines (address, machine_id, version, installed_at, session_pid, remote_port, platform) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ ).run("ssh:nas", null, "9.9.9", "2026-09-04T00:00:00.000Z", 42, 7364, "linux");
+ // Idempotent: a table that already has them is left as it is.
+ expect(migrate(db).applied).toEqual([]);
+ } finally {
+ db.close();
+ }
+ });
+});
+
describe("rollbackTo", () => {
/** Every migration states an undo or states that it has none — never leaves it unsaid. */
it("every migration declares its down, one way or the other", () => {
diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.ts
index b9f098a9..736f75a6 100644
--- a/packages/server/test/machines-api.test.ts
+++ b/packages/server/test/machines-api.test.ts
@@ -13,7 +13,7 @@ import http from "node:http";
import type { AddressInfo } from "node:net";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import type { MachinesResponse } from "../src/api/types.js";
+import type { MachinesUseResponse, MachinesResponse } from "../src/api/types.js";
import type { DatabaseSync } from "node:sqlite";
import { openDatabase } from "../src/db/database.js";
import { MachinesRepo } from "../src/db/repos/machines.js";
@@ -184,6 +184,9 @@ describe("machines API", () => {
id: "local",
local: true,
status: { state: "running" },
+ // This process's own root, resolved — not the layout's template, which names
+ // where a server would run on some OTHER machine.
+ root: machinesRoot,
});
expect(body.machines[0]?.installed).not.toBeNull();
expect(body.machines.slice(1)).toEqual([
@@ -195,6 +198,9 @@ describe("machines API", () => {
local: false,
connection: null,
api: null,
+ // The release profile's root over there, in the shell a machine of unknown
+ // platform is assumed to speak.
+ root: "$HOME/.penguin/data",
status: null,
},
{
@@ -205,6 +211,9 @@ describe("machines API", () => {
local: false,
connection: null,
api: null,
+ // The release profile's root over there, in the shell a machine of unknown
+ // platform is assumed to speak.
+ root: "$HOME/.penguin/data",
status: null,
},
]);
@@ -275,6 +284,8 @@ describe("machines API", () => {
ok: false,
step: "connect",
message: "Permission denied (publickey).",
+ // Every failed install offers installing the program anyway.
+ canReplaceProgram: true,
});
});
@@ -1383,6 +1394,279 @@ describe("machines API", () => {
});
});
+ describe("using machines", () => {
+ const useBody = (machines: string[], replaceProgram = false) =>
+ admin.post("/api/projects/default_project/machines/use", {
+ machines,
+ ...(replaceProgram ? { replaceProgram } : {}),
+ });
+ const jobsOf = () => t.deps.machines.jobs();
+ const settled = () => jobsOf().every((job) => !job.queued && !job.running);
+
+ it("a batch works its machines side by side, and each ends connected", async () => {
+ let release = () => {};
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const installs: string[] = [];
+ await boot({
+ install: async (opts) => {
+ installs.push(opts.target.alias);
+ if (installs.length === 1) await held;
+ return { kind: "installed", output: "done", identity: IDENTITY };
+ },
+ });
+ const started = await useBody(["ssh:build-box", "ssh:nas"]);
+ expect(started.status).toBe(202);
+ const body = (await started.json()) as MachinesUseResponse;
+ expect(body.refused).toEqual([]);
+ // Two hosts, two jobs at once: the second does not wait for the first's held install.
+ expect(body.jobs.map((job) => [job.machineId, job.queued, job.running])).toEqual([
+ ["ssh:build-box", false, true],
+ ["ssh:nas", false, true],
+ ]);
+ await waitFor(() => jobsOf().some((job) => job.machineId === "ssh:nas" && !job.running));
+ expect(jobsOf().find((job) => job.machineId === "ssh:build-box")?.running).toBe(true);
+
+ release();
+ await waitFor(settled);
+ expect([...installs].sort()).toEqual(["build-box", "nas"]);
+ for (const job of jobsOf()) {
+ expect(job.kind).toBe("use");
+ expect(job.result).toEqual({ ok: true, connected: true });
+ }
+ expect(connected).toEqual(new Set(["ssh:build-box", "ssh:nas"]));
+ expect(Object.keys(recordsInStore()).sort()).toEqual(["ssh:build-box", "ssh:nas"]);
+ });
+
+ it("a machine already on this build is not reinstalled: use goes straight to connecting", async () => {
+ let installs = 0;
+ await boot({
+ install: async () => {
+ installs += 1;
+ return { kind: "installed", output: "done", identity: IDENTITY };
+ },
+ });
+ machinesRepo.patch("ssh:nas", { version: "9.9.9", installedAt: "2026-08-01T00:00:00.000Z" });
+ machinesRepo.setMembers("default_project", ["ssh:nas"]);
+ await useBody(["ssh:nas"]);
+ await waitFor(settled);
+ expect(installs).toBe(0);
+ expect(jobsOf()[0]?.log[0]).toBe("Already on 9.9.9.");
+ expect(jobsOf()[0]?.result).toEqual({ ok: true, connected: true });
+ });
+
+ it("a machine behind this build is brought forward first, then connected", async () => {
+ let installs = 0;
+ await boot({
+ install: async () => {
+ installs += 1;
+ return { kind: "installed", output: "done", identity: IDENTITY };
+ },
+ });
+ machinesRepo.patch("ssh:nas", { version: "9.9.8", installedAt: "2026-08-01T00:00:00.000Z" });
+ machinesRepo.setMembers("default_project", ["ssh:nas"]);
+ await useBody(["ssh:nas"]);
+ await waitFor(settled);
+ expect(installs).toBe(1);
+ expect(jobsOf()[0]?.result).toEqual({ ok: true, connected: true });
+ expect(recordsInStore()["ssh:nas"]?.version).toBe("9.9.9");
+ });
+
+ it("an install that fails stops that machine's job there, with the forced install on offer, and the next machine still runs", async () => {
+ await boot({
+ install: async (opts) =>
+ opts.target.alias === "build-box"
+ ? { kind: "failed", step: "connect", detail: "Permission denied (publickey)." }
+ : { kind: "installed", output: "done", identity: IDENTITY },
+ });
+ await useBody(["ssh:build-box", "ssh:nas"]);
+ await waitFor(settled);
+ const [box, nas] = jobsOf();
+ expect(box?.result).toEqual({
+ ok: false,
+ step: "connect",
+ message: "Permission denied (publickey).",
+ canReplaceProgram: true,
+ });
+ expect(nas?.result).toEqual({ ok: true, connected: true });
+ expect(connected).toEqual(new Set(["ssh:nas"]));
+ });
+
+ it("refusals that need no ssh come back by id, and the rest of the batch is still queued", async () => {
+ await boot();
+ const body = (await (
+ await useBody(["ssh:nope", "local", "ssh:nas"])
+ ).json()) as MachinesUseResponse;
+ expect(body.refused).toEqual([
+ { machineId: "ssh:nope", why: "unknown-machine" },
+ { machineId: "local", why: "self" },
+ ]);
+ expect(body.jobs.map((job) => job.machineId)).toEqual(["ssh:nas"]);
+ await waitFor(settled);
+ });
+
+ it("an empty batch is a bad request", async () => {
+ await boot();
+ expect((await useBody([])).status).toBe(400);
+ });
+
+ it("stop using drops the connection and the membership, and keeps the install", async () => {
+ await boot();
+ await useBody(["ssh:nas"]);
+ await waitFor(settled);
+ expect(connected.has("ssh:nas")).toBe(true);
+ const stopped = await admin.post("/api/projects/default_project/machines/stop-using", {
+ machines: ["ssh:nas"],
+ });
+ expect(stopped.status).toBe(200);
+ const body = (await stopped.json()) as MachinesResponse;
+ const nas = body.machines.find((machine) => machine.id === "ssh:nas");
+ // Released from the Project, the install itself remembered as somebody else's.
+ expect(nas?.installed).toBeNull();
+ expect(nas?.elsewhere?.version).toBe("9.9.9");
+ // Nothing re-holds a machine nobody uses: the held mark is gone from the record. (The
+ // fake transport's own registry is not the record's; the real one closes with the ssh.)
+ expect(machinesRepo.get("ssh:nas")?.sessionPid ?? null).toBeNull();
+ });
+
+ it("a machine whose re-hold failed waits out a backoff before the next try", async () => {
+ // A host that is down costs one ssh per try; without a backoff the standing intent
+ // would knock on it every minute forever.
+ let holds = 0;
+ let clock = new Date("2026-08-24T12:00:00.000Z");
+ await boot({
+ now: () => clock,
+ hold: async () => {
+ holds += 1;
+ return { ok: false, detail: "Connection refused" };
+ },
+ });
+ machinesRepo.patch("ssh:nas", {
+ version: "9.9.9",
+ installedAt: "2026-08-01T00:00:00.000Z",
+ sessionPid: 4242,
+ });
+ machinesRepo.setMembers("default_project", ["ssh:nas"]);
+ await t.deps.machines.autoConnect();
+ expect(holds).toBe(1);
+ // Within the first minute after a failure: not tried again.
+ await t.deps.machines.autoConnect();
+ expect(holds).toBe(1);
+ // Once the wait has passed, it is.
+ clock = new Date(clock.getTime() + 61_000);
+ await t.deps.machines.autoConnect();
+ expect(holds).toBe(2);
+ // The second failure doubles the wait: two minutes now, so one minute later is too soon.
+ clock = new Date(clock.getTime() + 61_000);
+ await t.deps.machines.autoConnect();
+ expect(holds).toBe(2);
+ });
+ });
+
+ describe("adding a host to the ssh config", () => {
+ const post = (body: Record<string, unknown>) =>
+ admin.post("/api/projects/default_project/machines/ssh-hosts", body);
+
+ it("appends the block, and the list names the new host at once", async () => {
+ const written: string[] = [];
+ const aliases = ["build-box", "nas"];
+ await boot({
+ listAliases: () => aliases,
+ appendHost: (block) => {
+ written.push(block);
+ aliases.push("orchid-2");
+ },
+ });
+ const res = await post({ alias: "orchid-2", hostName: "10.0.0.9", user: "k", port: "2222" });
+ expect(res.status).toBe(201);
+ expect(written).toEqual([
+ [
+ "# Added by PenguinHarness on 2026-08-24T12:00:00.000Z",
+ "Host orchid-2",
+ " HostName 10.0.0.9",
+ " User k",
+ " Port 2222",
+ "",
+ ].join("\n"),
+ ]);
+ const body = (await res.json()) as MachinesResponse;
+ expect(body.machines.some((m) => m.id === "ssh:orchid-2")).toBe(true);
+ });
+
+ it("refuses an alias the config already declares, writing nothing", async () => {
+ const written: string[] = [];
+ await boot({ appendHost: (block) => void written.push(block) });
+ const res = await post({ alias: "nas", hostName: "10.0.0.9" });
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "ssh_host_exists",
+ );
+ expect(written).toEqual([]);
+ });
+
+ const CONFIG = [
+ "# Added by PenguinHarness on 2026-08-01T00:00:00.000Z",
+ "Host nas",
+ " HostName 10.0.0.2",
+ "",
+ "Host build-box",
+ " HostName box.example.net",
+ " ProxyJump bastion",
+ ].join("\n");
+
+ it("reads a block back, saying whether this app wrote it", async () => {
+ await boot({ readConfig: () => CONFIG });
+ const ours = await admin.get("/api/projects/default_project/machines/ssh-hosts/nas");
+ expect(ours.status).toBe(200);
+ expect(await ours.json()).toEqual({ alias: "nas", hostName: "10.0.0.2", editable: true });
+ const theirs = await admin.get("/api/projects/default_project/machines/ssh-hosts/build-box");
+ expect(((await theirs.json()) as { editable: boolean }).editable).toBe(false);
+ const none = await admin.get("/api/projects/default_project/machines/ssh-hosts/nope");
+ expect(none.status).toBe(404);
+ });
+
+ it("rewrites a block this app wrote in place, and refuses one written by hand", async () => {
+ const written: string[] = [];
+ await boot({ readConfig: () => CONFIG, writeConfig: (text) => void written.push(text) });
+ const ok = await admin.put("/api/projects/default_project/machines/ssh-hosts/nas", {
+ hostName: "10.0.0.3",
+ user: "deploy",
+ });
+ expect(ok.status).toBe(200);
+ expect(written).toHaveLength(1);
+ expect(written[0]!.split("\n").slice(0, 5)).toEqual([
+ "# Added by PenguinHarness on 2026-08-24T12:00:00.000Z",
+ "Host nas",
+ " HostName 10.0.0.3",
+ " User deploy",
+ "",
+ ]);
+ expect(written[0]!.endsWith(" ProxyJump bastion")).toBe(true);
+
+ const foreign = await admin.put(
+ "/api/projects/default_project/machines/ssh-hosts/build-box",
+ { hostName: "x" },
+ );
+ expect(foreign.status).toBe(409);
+ expect(((await foreign.json()) as { error: { code: string } }).error.code).toBe(
+ "ssh_host_foreign",
+ );
+ expect(written).toHaveLength(1);
+ });
+
+ it("names the field that would not survive as one config line", async () => {
+ const written: string[] = [];
+ await boot({ appendHost: (block) => void written.push(block) });
+ const res = await post({ alias: "new box", hostName: "h" });
+ expect(res.status).toBe(400);
+ const body = (await res.json()) as { error: { code: string; message: string } };
+ expect(body.error.code).toBe("ssh_host_invalid");
+ expect(body.error.message).toContain("alias");
+ expect(written).toEqual([]);
+ });
+ });
+
describe("refusals decided before any ssh runs", () => {
it("409s an install through an alias a probe has already heard this machine's id from", async () => {
await boot();
diff --git a/packages/server/test/plugins-sync.test.ts b/packages/server/test/plugins-sync.test.ts
new file mode 100644
index 00000000..c9790881
--- /dev/null
+++ b/packages/server/test/plugins-sync.test.ts
@@ -0,0 +1,162 @@
+/**
+ * Handing a Project's plugin list to its machines, strict parity.
+ *
+ * The rule the operator chose: the Project's list is the truth, so a machine ends with
+ * exactly it — extras removed. The cost is the point of the "removes what the machine has
+ * beyond the list" case: a platform-specific sandbox backend is not in the other platform's
+ * list, so keeping one means listing it fleet-wide.
+ */
+import { describe, expect, it } from "vitest";
+import type { MachineApi } from "../src/machines/machine-api.js";
+import type { InstalledPluginsResponse } from "../src/api/types.js";
+import { syncPluginsToMachine } from "../src/machines/plugins-sync.js";
+
+/** A machine whose list is whatever was last written to it. */
+function fakeMachine(initial: Record<string, string[]>, opts: { restartPending?: boolean } = {}) {
+ const state = new Map(Object.entries(initial));
+ const calls: { method: string; path: string; body?: unknown }[] = [];
+ const body = (list: string[]): InstalledPluginsResponse => ({
+ plugins: list.map((specifier) => ({
+ specifier,
+ // "unresolvable there" is spelled the way the far side spells it: a row with a reason.
+ active: !specifier.includes("not-there"),
+ builtin: true,
+ modules: [],
+ replaces: [],
+ ...(specifier.includes("not-there") ? { error: "not installed on this machine" } : {}),
+ })),
+ shipped: [],
+ file: ".project_config.toml",
+ restartPending: opts.restartPending === true,
+ });
+ const api: MachineApi = {
+ request: async (method: string, path: string, payload?: unknown) => {
+ calls.push({ method, path, ...(payload === undefined ? {} : { body: payload }) });
+ if (path === "/api/projects") {
+ return {
+ status: 200,
+ text: JSON.stringify({ projects: [...state.keys()].map((projectId) => ({ projectId })) }),
+ };
+ }
+ const projectId = decodeURIComponent(path.split("/")[3] ?? "");
+ const has = state.get(projectId);
+ if (has === undefined) return { status: 404, text: "no such Project" };
+ if (method === "PUT") {
+ state.set(projectId, [...((payload as { plugins: string[] }).plugins ?? [])]);
+ }
+ return { status: 200, text: JSON.stringify(body(state.get(projectId) ?? [])) };
+ },
+ postBytes: async () => ({ status: 500, text: "unused" }),
+ };
+ return { api, calls, state };
+}
+
+const local = (lists: Record<string, string[]>) => (projectId: string) =>
+ Promise.resolve(lists[projectId] ?? []);
+
+describe("syncPluginsToMachine", () => {
+ it("writes what the Project asks for, and removes what the machine has beyond it", async () => {
+ const m = fakeMachine({ p1: ["@acme/keep", "@acme/theirs"] });
+ const out = await syncPluginsToMachine({
+ api: m.api,
+ loadLocal: local({ p1: ["@acme/keep", "@acme/ours"] }),
+ projects: ["p1"],
+ });
+ expect(out).toMatchObject({ kind: "synced", projects: ["p1"] });
+ if (out.kind !== "synced") throw new Error("unreachable");
+ expect(out.added).toEqual(["@acme/ours"]);
+ // Strict parity: what the machine had and this Project does not ask for is taken away.
+ expect(out.removed).toEqual(["@acme/theirs"]);
+ expect(m.state.get("p1")).toEqual(["@acme/keep", "@acme/ours"]);
+ });
+
+ it("writes nothing when the machine is already in parity", async () => {
+ const m = fakeMachine({ p1: ["@acme/same"] });
+ const out = await syncPluginsToMachine({
+ api: m.api,
+ loadLocal: local({ p1: ["@acme/same"] }),
+ projects: ["p1"],
+ });
+ expect(out.kind === "synced" && out.projects).toEqual([]);
+ // A connect must not rewrite a machine that already agrees.
+ expect(m.calls.some((c) => c.method === "PUT")).toBe(false);
+ });
+
+ it("reports a specifier the machine cannot resolve instead of dropping it", async () => {
+ // Most often a machine still on a build that does not ship the plugin: the operator's
+ // choice is not taking effect there, and silence would read as success.
+ const m = fakeMachine({ p1: [] });
+ const out = await syncPluginsToMachine({
+ api: m.api,
+ loadLocal: local({ p1: ["@acme/not-there"] }),
+ projects: ["p1"],
+ });
+ expect(out.kind === "synced" && out.unresolved).toEqual(["@acme/not-there"]);
+ expect(m.state.get("p1")).toEqual(["@acme/not-there"]);
+ });
+
+ it("reports a machine that still has to restart to finish loading", async () => {
+ const m = fakeMachine({ p1: [] }, { restartPending: true });
+ const out = await syncPluginsToMachine({
+ api: m.api,
+ loadLocal: local({ p1: ["@acme/one"] }),
+ projects: ["p1"],
+ });
+ expect(out.kind === "synced" && out.restartPending).toBe(true);
+ });
+
+ it("refuses a Project the machine does not have, rather than creating one", async () => {
+ // A Project exists to hold work; creating one over there to carry a plugin list would
+ // invent a workspace nobody asked for.
+ const m = fakeMachine({});
+ const out = await syncPluginsToMachine({
+ api: m.api,
+ loadLocal: local({ p1: ["@acme/one"] }),
+ projects: ["p1"],
+ });
+ expect(out.kind === "synced" && out.refused).toEqual([
+ { projectId: "p1", detail: "that machine has no such Project" },
+ ]);
+ expect(m.calls.some((c) => c.method === "PUT")).toBe(false);
+ });
+
+ it("tells a machine that lacks the ROUTE from one that lacks the Project", async () => {
+ // The same 404 means two opposite things, and the operator reads the difference. A
+ // machine on an older build listed the Project it was refused for, in the line right
+ // after the models sync had written that very Project.
+ const older = fakeMachine({});
+ older.api.request = async (method, path) => {
+ if (path === "/api/projects") {
+ return { status: 200, text: JSON.stringify({ projects: [{ projectId: "p1" }] }) };
+ }
+ return {
+ status: 404,
+ text: '{"error":{"code":"not_found","message":"Endpoint does not exist."}}',
+ };
+ };
+ const out = await syncPluginsToMachine({
+ api: older.api,
+ loadLocal: local({ p1: ["@acme/one"] }),
+ projects: ["p1"],
+ });
+ expect(out.kind === "synced" && out.refused).toEqual([
+ {
+ projectId: "p1",
+ detail:
+ "that machine's build is older than the Project plugin list — update it, then sync again",
+ },
+ ]);
+ });
+
+ it("carries on to the next Project when one is refused", async () => {
+ const m = fakeMachine({ p2: [] });
+ const out = await syncPluginsToMachine({
+ api: m.api,
+ loadLocal: local({ p1: ["@acme/one"], p2: ["@acme/two"] }),
+ projects: ["p1", "p2"],
+ });
+ expect(out.kind === "synced" && out.projects).toEqual(["p2"]);
+ expect(out.kind === "synced" && out.refused.map((r) => r.projectId)).toEqual(["p1"]);
+ expect(m.state.get("p2")).toEqual(["@acme/two"]);
+ });
+});
diff --git a/packages/server/test/ssh-config-hosts.test.ts b/packages/server/test/ssh-config-hosts.test.ts
new file mode 100644
index 00000000..c48ed799
--- /dev/null
+++ b/packages/server/test/ssh-config-hosts.test.ts
@@ -0,0 +1,173 @@
+/**
+ * The host block the Machines page appends to `~/.ssh/config`: what is refused before any
+ * write, and the exact lines that are written. Strictness is the point — the block joins a
+ * file a person edits by hand, so a glob in the alias or a `#` in a value would quietly
+ * change what ssh reads.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ findHostBlock,
+ renderHostBlock,
+ replaceHostBlock,
+ validateHostEntry,
+} from "../src/machines/ssh-config.js";
+
+const AT = new Date("2026-09-05T12:00:00.000Z");
+
+describe("validateHostEntry", () => {
+ it("wants an alias and an address", () => {
+ expect(validateHostEntry({ alias: "", hostName: "10.0.0.2" })).toEqual({
+ field: "alias",
+ why: "required",
+ });
+ expect(validateHostEntry({ alias: "nas", hostName: " " })).toEqual({
+ field: "hostName",
+ why: "required",
+ });
+ });
+
+ it("refuses an alias that would be a pattern or would not survive as one word", () => {
+ expect(validateHostEntry({ alias: "gpu-*", hostName: "h" })).toEqual({
+ field: "alias",
+ why: "invalid",
+ });
+ expect(validateHostEntry({ alias: "build box", hostName: "h" })).toEqual({
+ field: "alias",
+ why: "invalid",
+ });
+ expect(validateHostEntry({ alias: "nas#1", hostName: "h" })).toEqual({
+ field: "alias",
+ why: "invalid",
+ });
+ });
+
+ it("checks the optional fields only when given", () => {
+ expect(
+ validateHostEntry({ alias: "nas", hostName: "h", user: "", identityFile: "" }),
+ ).toBeNull();
+ expect(validateHostEntry({ alias: "nas", hostName: "h", user: "a b" })).toEqual({
+ field: "user",
+ why: "invalid",
+ });
+ expect(validateHostEntry({ alias: "nas", hostName: "h", port: 0 })).toEqual({
+ field: "port",
+ why: "invalid",
+ });
+ expect(validateHostEntry({ alias: "nas", hostName: "h", port: 22.5 })).toEqual({
+ field: "port",
+ why: "invalid",
+ });
+ expect(validateHostEntry({ alias: "nas", hostName: "h", port: 65535 })).toBeNull();
+ expect(validateHostEntry({ alias: "nas", hostName: "h", identityFile: "~/my key" })).toEqual({
+ field: "identityFile",
+ why: "invalid",
+ });
+ });
+});
+
+describe("renderHostBlock", () => {
+ it("writes the lines ssh reads, led by who wrote them and when, and nothing blank", () => {
+ expect(renderHostBlock({ alias: "nas", hostName: "10.0.0.2" }, AT)).toBe(
+ [
+ "# Added by PenguinHarness on 2026-09-05T12:00:00.000Z",
+ "Host nas",
+ " HostName 10.0.0.2",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("carries every option that was given, trimmed", () => {
+ expect(
+ renderHostBlock(
+ {
+ alias: " build-box ",
+ hostName: "box.example.net",
+ user: "deploy",
+ port: 2222,
+ identityFile: "~/.ssh/id_ed25519",
+ },
+ AT,
+ ),
+ ).toBe(
+ [
+ "# Added by PenguinHarness on 2026-09-05T12:00:00.000Z",
+ "Host build-box",
+ " HostName box.example.net",
+ " User deploy",
+ " Port 2222",
+ " IdentityFile ~/.ssh/id_ed25519",
+ "",
+ ].join("\n"),
+ );
+ });
+});
+
+const CONFIG = [
+ "Host *",
+ " ServerAliveInterval 30",
+ "",
+ "Host nas gpu-1",
+ " HostName 10.0.0.2",
+ "",
+ "# Added by PenguinHarness on 2026-09-05T12:00:00.000Z",
+ "Host orchid-2",
+ " HostName 10.0.0.9",
+ " User k",
+ " Port 2222",
+ "",
+ "",
+ "Host lab",
+ " HostName lab.example.net",
+ " ProxyJump bastion",
+].join("\n");
+
+describe("findHostBlock", () => {
+ it("reads back a block this app wrote, marker included, trailing blanks excluded", () => {
+ expect(findHostBlock(CONFIG, "orchid-2")).toEqual({
+ start: 6,
+ end: 11,
+ ours: true,
+ entry: { alias: "orchid-2", hostName: "10.0.0.9", user: "k", port: 2222 },
+ });
+ });
+
+ it("finds a hand-written block but says it is not ours", () => {
+ expect(findHostBlock(CONFIG, "lab")).toEqual({
+ start: 13,
+ end: 16,
+ ours: false,
+ entry: { alias: "lab", hostName: "lab.example.net" },
+ });
+ });
+
+ it("does not match a line declaring several aliases, or an alias that is not there", () => {
+ expect(findHostBlock(CONFIG, "nas")).toBeNull();
+ expect(findHostBlock(CONFIG, "nope")).toBeNull();
+ });
+});
+
+describe("replaceHostBlock", () => {
+ it("swaps the block's lines for the new ones and leaves the rest of the file alone", () => {
+ const found = findHostBlock(CONFIG, "orchid-2")!;
+ const block = renderHostBlock(
+ { alias: "orchid-2", hostName: "10.0.0.10", port: 22 },
+ new Date("2026-09-06T00:00:00.000Z"),
+ );
+ const next = replaceHostBlock(CONFIG, found, block);
+ expect(next.split("\n").slice(6, 11)).toEqual([
+ "# Added by PenguinHarness on 2026-09-06T00:00:00.000Z",
+ "Host orchid-2",
+ " HostName 10.0.0.10",
+ " Port 22",
+ "",
+ ]);
+ expect(next.split("\n").slice(0, 6)).toEqual(CONFIG.split("\n").slice(0, 6));
+ expect(next.endsWith(" ProxyJump bastion")).toBe(true);
+ expect(findHostBlock(next, "orchid-2")?.entry).toEqual({
+ alias: "orchid-2",
+ hostName: "10.0.0.10",
+ port: 22,
+ });
+ });
+});
diff --git a/packages/web/src/api/client.ts b/packages/web/src/api/client.ts
index 638b040e..67d4bf30 100644
--- a/packages/web/src/api/client.ts
+++ b/packages/web/src/api/client.ts
@@ -8,6 +8,7 @@
* login page — instead of each page popping its own "unauthorized" error.
*/
import { S } from "../lib/strings";
+import { apiUrl } from "../lib/server-context";
/** Unified API error: carries the HTTP status code and server error code (server error body {error:{code,message}}). */
export class ApiError extends Error {
@@ -42,6 +43,12 @@ export interface ApiFetchOptions {
body?: unknown;
/** Query parameters (undefined values are skipped). */
query?: Record<string, string | number | undefined>;
+ /**
+ * Which machine answers this call. Omitted or `null` is this server — the window never
+ * moves — and a machine id sends just this request down that machine's tunnel. Browsing
+ * another machine's directories to pick a workspace on it is the case this exists for.
+ */
+ server?: string | null;
}
/** Response metadata a caller may need alongside the parsed body. */
@@ -67,7 +74,9 @@ export async function apiFetchWithMeta<T>(
path: string,
options: ApiFetchOptions = {},
): Promise<{ data: T } & ApiFetchMeta> {
- let url = path;
+ // The one routing rule: a call that names a machine goes down that machine's tunnel;
+ // everything else stays here (see lib/server-context.ts).
+ let url = apiUrl(path, options.server ?? null);
if (options.query) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.query)) {
@@ -103,7 +112,12 @@ export async function apiFetchWithMeta<T>(
} catch {
// Non-JSON error body: fall back to the default message.
}
- if (response.status === 401 && !isAuthEndpoint(path)) onUnauthorized?.();
+ // A 401 from ANOTHER machine is that machine's answer, not this server's: it means we
+ // are not signed in over there, which says nothing about the session here. Treating it
+ // as a local logout is how clicking a remote host in a picker bounced the window to the
+ // login page of a server it was still perfectly signed in to.
+ const fromThisServer = (options.server ?? null) === null;
+ if (response.status === 401 && fromThisServer && !isAuthEndpoint(path)) onUnauthorized?.();
const retryAfter = response.headers.get("retry-after");
const retryAfterSeconds =
retryAfter !== null && /^\d+$/.test(retryAfter) ? Number(retryAfter) : undefined;
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index c6c61a21..21070ca6 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -76,6 +76,9 @@ import type {
PlatformModelSyncResponse,
ModelProtocolDetectRequest,
ModelProtocolDetectResponse,
+ MachinesUseResponse,
+ SshHostRequest,
+ SshHostResponse,
ModelsResponse,
ModelsUpdateRequest,
ModelTestRequest,
@@ -662,10 +665,19 @@ export const listSessions = (
};
/** Server directory browsing: `path` is an absolute path; empty means start from the server's home directory. */
-export const listDirs = (projectId: string, path = "") =>
- apiFetch<DirListResponse>(
- `/api/projects/${encodeURIComponent(projectId)}/dirs?path=${encodeURIComponent(path)}`,
- );
+/**
+ * Browses directories. With no machine, this server's own filesystem; with one, THAT
+ * machine's — listed by this server over ssh, so picking a workspace on another machine
+ * needs no second login to that machine's own server.
+ */
+export const listDirs = (projectId: string, path = "", machineId?: string | null) =>
+ machineId === undefined || machineId === null
+ ? apiFetch<DirListResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/dirs?path=${encodeURIComponent(path)}`,
+ )
+ : apiFetch<DirListResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/dirs?path=${encodeURIComponent(path)}`,
+ );
/**
* Skills a directory carries under `.agents/skills` / `.claude/skills`: what picking it at Agent
@@ -1459,12 +1471,96 @@ export const getMachines = (projectId: string) =>
apiFetch<MachinesResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines`);
/**
- * Starts an install (202, long-running) and gives the machine to this Project; the returned
- * body already carries the new job.
+ * Re-probes the installed machines' servers (one ssh round trip each, server-side) and
+ * answers the refreshed list. A POST because it spends those round trips — a GET that
+ * spawns processes is one a prefetch or a proxy may fire on its own.
+ */
+export const probeMachines = (projectId: string) =>
+ apiFetch<MachinesResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines/probe`, {
+ method: "POST",
+ body: {},
+ });
+
+/**
+ * Starts an install on a machine and gives it to this Project; answers the list with the
+ * running job. `replaceProgram` answers a job that came back asking for it — installing the
+ * program over there even though its version already matches, and restarting it.
+ */
+/**
+ * Brings machines into use — install or update if needed, start, connect, sync — as one
+ * queued batch (202). `refused` names the ones that could be turned down without any ssh.
+ * `replaceProgram` answers a job that came back asking for it.
*/
-export const installOnMachine = (projectId: string, machineId: string) =>
+export const useMachines = (projectId: string, machineIds: string[], replaceProgram = false) =>
+ apiFetch<MachinesUseResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines/use`, {
+ method: "POST",
+ body: replaceProgram
+ ? { machines: machineIds, replaceProgram: true }
+ : { machines: machineIds },
+ });
+
+/** Appends a host block to this server's ~/.ssh/config; answers the machines list, which now names it (201). */
+export const addSshHost = (projectId: string, host: SshHostRequest) =>
+ apiFetch<MachinesResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines/ssh-hosts`, {
+ method: "POST",
+ body: host,
+ });
+
+/** A host's ssh block read back, and whether this app wrote it (only then may it be rewritten). */
+export const getSshHost = (projectId: string, alias: string) =>
+ apiFetch<SshHostResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/ssh-hosts/${encodeURIComponent(alias)}`,
+ );
+
+/** Rewrites a block this app wrote; answers the machines list. */
+export const updateSshHost = (
+ projectId: string,
+ alias: string,
+ host: Omit<SshHostRequest, "alias">,
+) =>
+ apiFetch<MachinesResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/ssh-hosts/${encodeURIComponent(alias)}`,
+ { method: "PUT", body: host },
+ );
+
+/** Lets machines go: connections dropped, Project membership released; the install stays. */
+export const stopUsingMachines = (projectId: string, machineIds: string[]) =>
+ apiFetch<MachinesResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines/stop-using`, {
+ method: "POST",
+ body: { machines: machineIds },
+ });
+
+export const installOnMachine = (projectId: string, machineId: string, replaceProgram = false) =>
apiFetch<MachinesResponse>(
`/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/install`,
+ { method: "POST", body: replaceProgram ? { replaceProgram: true } : {} },
+ );
+
+/** Brings that machine's server up and holds a tunnel to it (202, long-running). */
+export const connectMachine = (projectId: string, machineId: string) =>
+ apiFetch<MachinesResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/connect`,
+ { method: "POST", body: {} },
+ );
+
+/** Drops a machine from this Project. The install stays — another Project may be using it. */
+export const releaseMachine = (projectId: string, machineId: string) =>
+ apiFetch<MachinesResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/release`,
+ { method: "POST", body: {} },
+ );
+
+/** Drops the tunnel; the remote server keeps running. */
+/** Restarts that machine's server so what runs there matches what is on its disk. */
+export const restartMachine = (projectId: string, machineId: string) =>
+ apiFetch<MachinesResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/restart`,
+ { method: "POST", body: {} },
+ );
+
+export const disconnectMachine = (projectId: string, machineId: string) =>
+ apiFetch<MachinesResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/disconnect`,
{ method: "POST", body: {} },
);
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index a2f37f60..aab71079 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -1251,8 +1251,8 @@ export function Sidebar({
* already there. Otherwise, past ten groups, the freshly added Workspace would sit on a
* page the user is not looking at and the click would read as a no-op.
*/
- const addWorkspace = (path: string) => {
- const next = registerWorkspace(registeredWorkspaces, path);
+ const addWorkspace = (path: string, machineId?: string | null) => {
+ const next = registerWorkspace(registeredWorkspaces, path, machineId ?? undefined);
if (next === registeredWorkspaces) return;
applyRegistryChange(next);
const key = workspaceGroupKey(path);
diff --git a/packages/web/src/features/chat/workspace-select.tsx b/packages/web/src/features/chat/workspace-select.tsx
index aa852ae9..76739b06 100644
--- a/packages/web/src/features/chat/workspace-select.tsx
+++ b/packages/web/src/features/chat/workspace-select.tsx
@@ -1,5 +1,10 @@
/**
- * Workspace picker, extracted from draft-view.tsx so the Project settings dialog's
+ * Workspace picker: which directory, and — when more than one machine is reachable — which
+ * MACHINE it is on. A workspace is a directory on a machine, so choosing one is choosing
+ * where the path has to exist; the browser lists that machine's filesystem, over the tunnel
+ * when it is not this one. The row only appears when there is a choice to make.
+ *
+ * Extracted from draft-view.tsx so the Project settings dialog's
* "new chat defaults" section can offer the same dir-browser popover the chat draft uses.
* Two trigger variants, one menu:
* - "pill" (default): the draft page's pill trigger with viewport-docked in-flow menu —
@@ -22,6 +27,8 @@ import { toastError } from "../../components/ui/toast";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { FOLDER_ICON } from "../../components/ui/group-list";
import { ICON_SIZE } from "../../lib/icon-scale";
+import { machineLabel, workspaceMachines } from "../../lib/workspace-machines";
+import type { WorkspaceMachine } from "../../lib/workspace-machines";
/** Shared style for pill trigger buttons (ChatGPT project button style: small rounded pill + icon + short name + collapse arrow). */
export const pillClass =
@@ -41,6 +48,8 @@ export function WorkspaceSelect({
projectId,
workspace,
onChange,
+ machineId,
+ chooseMachine,
variant = "pill",
trigger,
fieldLabel,
@@ -50,7 +59,12 @@ export function WorkspaceSelect({
}: {
projectId: string;
workspace: string;
- onChange: (path: string) => void;
+ /** `machineId` is null for this machine — the shape the registry stores. */
+ onChange: (path: string, machineId?: string | null) => void;
+ /** The machine to browse first; omitted starts on the window's current server. */
+ machineId?: string | null;
+ /** Offer the machine row. Off where a machine cannot be meaningfully chosen yet. */
+ chooseMachine?: boolean;
/** Trigger style: the draft page's pill (default), or a dialog form control (see the header comment). */
variant?: "pill" | "form";
/**
@@ -75,6 +89,18 @@ export function WorkspaceSelect({
}) {
const fieldName = fieldLabel ?? S.chat.workspace;
const [open, setOpen] = useState(false);
+ /**
+ * The machine being browsed. Its OWN state rather than a prop: picking a machine re-roots
+ * the browser without touching the window's active server, which is the whole point —
+ * a workspace on another machine is chosen from here, not by going there.
+ *
+ * Starts on this machine unless the caller names one — a workspace being edited that
+ * already lives elsewhere. The window itself never moves, so "here" is always the honest
+ * starting point.
+ */
+ const [machine, setMachine] = useState<string | null>(machineId ?? null);
+ const [machines, setMachines] = useState<WorkspaceMachine[]>([]);
+ const [machineOpen, setMachineOpen] = useState(false);
/**
* Menu docking, measured on each open: the pill follows the agent pill in a wrapping row, so
* its left offset varies with the agent's name — a statically left-anchored 20rem panel can
@@ -119,7 +145,7 @@ export function WorkspaceSelect({
setLoading(true);
setError(null);
api
- .listDirs(projectId, abs)
+ .listDirs(projectId, abs, machine)
.then((res) => {
if (seq === loadSeq.current) setDir(res);
})
@@ -132,9 +158,32 @@ export function WorkspaceSelect({
if (seq === loadSeq.current) setLoading(false);
});
},
- [projectId],
+ [projectId, machine],
);
+ /**
+ * loadDir through a ref: the machine row renders above the browser but has to drive it,
+ * and the callback is rebuilt whenever the machine changes — a direct reference captured
+ * at render time would browse the machine we just left.
+ */
+ const loadDirRef = useRef<(machineId: string | null) => void>(() => {});
+ loadDirRef.current = (nextMachine: string | null) => {
+ const seq = ++loadSeq.current;
+ setLoading(true);
+ setError(null);
+ api
+ .listDirs(projectId, "", nextMachine)
+ .then((res) => {
+ if (seq === loadSeq.current) setDir(res);
+ })
+ .catch((e: unknown) => {
+ if (seq === loadSeq.current) setError(apiErrorText(e));
+ })
+ .finally(() => {
+ if (seq === loadSeq.current) setLoading(false);
+ });
+ };
+
// Only loads on first expand: an already-filled absolute path is used as the starting point, otherwise the server falls back to the home directory.
const loadOnFirstOpen = (next: boolean) => {
if (next && !browsedRef.current) {
@@ -199,12 +248,94 @@ export function WorkspaceSelect({
const parentPath = dir?.parent ?? null;
// Hidden directories (starting with .) are excluded from the list.
const entries = (dir?.entries ?? []).filter((e) => !e.name.startsWith("."));
+ // The machines a workspace can live on: this PROJECT's machines, from the LOCAL server —
+ // the list is its own, whichever server the rest of the window is using.
+ useEffect(() => {
+ if (!open || chooseMachine !== true) return;
+ let cancelled = false;
+ void api
+ .getMachines(projectId)
+ .then((res) => {
+ if (!cancelled) setMachines(workspaceMachines(res));
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [open, chooseMachine, projectId]);
+
+ /**
+ * The row is shown whenever this surface offers machines at all — NOT only when more than
+ * one is reachable. A control that disappears when the answer is "just this one" reads as
+ * a missing feature, and leaves someone with 45 hosts in their ssh config wondering why
+ * they cannot pick any of them. Showing it with one entry, plus a line saying how many
+ * are a connect away, answers that question where hiding it asked a new one.
+ */
+ const machineRow = chooseMachine === true && machines.length > 0;
+
/** Folder glyph shared by both triggers. */
const folderIcon = (extraClass: string) => (
<GlyphIcon d={FOLDER_ICON} size={ICON_SIZE.rowLead} className={`text-gray-400 ${extraClass}`} />
);
const menu = (
<div className="space-y-1.5 px-2.5 pb-2.5 pt-2">
+ {/* Which machine's filesystem is being browsed. Changing it re-roots the browser at
+ that machine's home directory — a path is only meaningful on the machine it is on,
+ so carrying the current one across would be a path that likely does not exist. */}
+ {machineRow && (
+ <Dropdown
+ open={machineOpen}
+ setOpen={setMachineOpen}
+ menuClass="left-0 right-0 top-full mt-1 origin-top"
+ button={
+ <button
+ type="button"
+ onClick={() => setMachineOpen(!machineOpen)}
+ aria-haspopup="listbox"
+ aria-expanded={machineOpen}
+ className="flex w-full items-center gap-1.5 rounded-md border border-gray-200 px-2 py-1 text-left text-xs text-gray-600 transition-colors hover:bg-gray-50 dark:border-gray-800 dark:text-gray-300 dark:hover:bg-gray-800"
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {machineLabel(machines, machine) ?? S.chat.workspaceMachine}
+ </span>
+ <Chevron open={machineOpen} />
+ </button>
+ }
+ >
+ {machines.map((entry, index) => (
+ <button
+ key={entry.selectable ? (entry.id ?? "local") : `unusable-${index}`}
+ type="button"
+ disabled={!entry.selectable}
+ onClick={() => {
+ setMachineOpen(false);
+ if (entry.id === machine) return;
+ setMachine(entry.id);
+ // Start over at that machine's home directory.
+ loadDirRef.current(entry.id);
+ }}
+ className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:hover:bg-transparent dark:hover:bg-gray-800 dark:disabled:hover:bg-transparent"
+ >
+ <span
+ className={`min-w-0 flex-1 truncate ${entry.selectable ? "" : "text-gray-400 dark:text-gray-500"}`}
+ >
+ {entry.label}
+ </span>
+ {entry.local && (
+ <span className="shrink-0 text-gray-400">{S.chat.workspaceHere}</span>
+ )}
+ {/* A machine that cannot be browsed is shown, disabled, saying why — right
+ where "why can I not pick that one?" is asked. Leaving it out, or counting
+ it in a footnote, answers somewhere the question was not. */}
+ {entry.reason !== undefined && (
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ {S.chat.workspaceMachineWhy[entry.reason]}
+ </span>
+ )}
+ </button>
+ ))}
+ </Dropdown>
+ )}
<div className="rounded-md border border-gray-200 dark:border-gray-800">
{/* Current path (editable: Enter/blur commits, Escape discards) + "Use this directory" (closes the menu once selected) */}
<div className="flex items-center gap-1.5 border-b border-gray-100 px-1.5 py-1 dark:border-gray-800">
@@ -231,7 +362,7 @@ export function WorkspaceSelect({
disabled={!dir}
onClick={() => {
if (!dir) return;
- onChange(dir.path);
+ onChange(dir.path, machine);
setOpen(false);
}}
className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
@@ -298,7 +429,7 @@ export function WorkspaceSelect({
<button
type="button"
onClick={() => {
- onChange("");
+ onChange("", machine);
setOpen(false);
}}
className="text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
diff --git a/packages/web/src/features/machines/machines-page.tsx b/packages/web/src/features/machines/machines-page.tsx
index 55eef8b5..302f5347 100644
--- a/packages/web/src/features/machines/machines-page.tsx
+++ b/packages/web/src/features/machines/machines-page.tsx
@@ -1,95 +1,170 @@
/**
- * Machines page: pick a host out of the SERVER's own `~/.ssh/config` and install this build
- * on it.
+ * Machines: the fleet as cards, and two verbs.
*
- * The host list is a PICKER, not a rendered list, because an ssh config routinely declares
- * hundreds of entries: the panel shows a few rows, a fuzzy query reaches the rest, and the
- * matched characters are highlighted so a subsequence hit (`gpu1` → `gpu-01`) reads as a
- * match rather than as a wrong result. A counter names how many rows the current view leaves
- * out — silent truncation would read as "that host is not in my config".
+ * Enable is the whole of what a person wants from a machine — install or update the program
+ * there, start its server, connect, hand over the Model config — as one job the server
+ * queues per machine, so a batch is one tap. Disable lets a machine go.
*
- * The list itself is the config text; the server does no `ssh -G` and no network to produce
- * it, so hundreds of hosts cost one file read and a row carries nothing but its alias.
+ * One card per machine, one per row, this server first. A card at rest is two lines: the
+ * machine's name in mono, and beneath it the state in a word with the single detail that
+ * matters beside it — when it was last checked, the build it carries when that is behind
+ * this server's, the far side's words when it failed. State is said once: the dot at the
+ * card's edge is blue for a live link — this server, and a held connection — amber and red
+ * for what needs a person, grey for settled. Everything else — the build, the install
+ * date, the server, the machine id, the job's output, the forced install — lives inside
+ * the card and unfolds on the chevron, so the fleet at rest is names and dots.
*
- * An install is a job on the server, not a request that finishes: it probes the machine,
- * may fetch a Node runtime, copies an image over scp and runs an installer there. POST
- * starts it and the page polls while it runs. The progress lines are the far side's own
- * words wherever there are any, so they are rendered verbatim in a monospace block rather
- * than interpreted here — a refused key or an unusable Node explains itself better than any
- * status enum could.
+ * Selection is the card: clicking one toggles it and a selected card darkens its border;
+ * nothing is selected until someone clicks. Select all, select none, plug and unplug are icon
+ * buttons in a bar that keeps a fixed slot between the title and the cards, so the cards
+ * never move when a selection appears or goes. A queued or working card grows a stepper under its name, one
+ * segment per step of the pipeline, fed by the step the server says it is on.
*
- * One job exists at a time server-side, so the panel below follows THE JOB and names the
- * alias it belongs to, while the button follows the SELECTION: picking another host while
- * one installs must not hide the install that is running.
- *
- * Which hosts already carry this program comes from each machine's own persisted record,
- * not from the job — the job is one slot, so reading "installed" off it made a host stop
- * looking installed the moment anything else was installed or the server restarted.
+ * The page polls while a job is queued or running, and re-probes the servers on a widening
+ * schedule (probe-schedule.ts) so a machine that went quiet is noticed without a tap.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type { MachinesResponse } from "@prismshadow/penguin-server/api";
+import type { MachineInfo, MachineJob, MachinesResponse } from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
+import { useProject } from "../../state/project";
+import { useLocale } from "../../state/locale";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
-import { useProject } from "../../state/project";
-import { formatDateTime } from "../../lib/format";
-import { toneInk, toneStrip } from "../../lib/tone";
-import type { Tone } from "../../lib/tone";
+import { formatDateTime, formatMessageTime } from "../../lib/format";
+import { toneDot, toneInk, toneStrip } from "../../lib/tone";
import { ICON_SIZE } from "../../lib/icon-scale";
import { Button } from "../../components/ui/button";
import { Dropdown } from "../../components/ui/dropdown";
-import { EmptyState } from "../../components/ui/empty-state";
-import { InfoPopover } from "../../components/ui/info-popover";
import { Skeleton } from "../../components/ui/skeleton";
+import { toastError } from "../../components/ui/toast";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { noAutofill, panelSearchClass } from "../../components/ui/input";
-import { ChevronDown, NAV_ICONS } from "../../components/ui/icons";
-import { installButtonState, installedMachines, verdictOf } from "./machines-view";
-import type { MachineVerdict } from "./machines-view";
+import { ChevronDown, GEAR_ICON, NAV_ICONS } from "../../components/ui/icons";
+import {
+ MACHINE_PHASES,
+ anyJobPending,
+ behindMachines,
+ installedMachines,
+ jobFor,
+ localMachine,
+ readMachine,
+ readingTone,
+ wantsUse,
+} from "./machines-view";
+import type { MachineReading } from "./machines-view";
import { MAX_VISIBLE_MACHINES, highlightSegments, matchMachines } from "./machines-match";
+import { probeDelayMs, probeFingerprint } from "./probe-schedule";
+import { SshHostDialog } from "./ssh-host-dialog";
+import type { HostFormMode } from "./ssh-host-dialog";
-/** How often a running job is re-read. Slow enough to be free, fast enough that a step reads as progress. */
+/** How often the page re-reads the list while a job is queued or running. */
const POLL_MS = 1500;
-/** A finished job's one-line verdict, and the tone that carries it. */
-function verdictLine(verdict: MachineVerdict): { text: string; tone: Tone } {
- if (verdict.kind === "failed") {
- return { text: S.machines.failedAt(verdict.step), tone: "danger" };
+/**
+ * Enable: a plug seated in its socket, cord trailing. Disable: the plug lifted clear of the
+ * socket — prongs in the air, a gap, and the empty socket cup below. The two must differ in
+ * silhouette, not in detail: at icon size a detail is invisible.
+ */
+const PLUG_PATH = "M9 2v4M15 2v4M6 6h12v4a6 6 0 0 1-12 0V6zM12 16v6";
+const UNPLUG_PATH = "M9 2v3M15 2v3M6 5h12v3a6 6 0 0 1-12 0V5zM7 22h10M7 22v-4M17 22v-4";
+
+/** The + in the picker's foot: a new host for the ssh config. */
+const PLUS_PATH = "M12 5v14M5 12h14";
+/** The expand verb's glyph, on the 24-grid like the others; turned over when unfolded. */
+const CHEVRON_PATH = "M6 9l6 6 6-6";
+/** Select all: a box with a check. Select none: the empty box. */
+const SELECT_ALL_PATH = "M4 5h16v14H4zM8 12l3 3 5-6";
+const SELECT_NONE_PATH = "M4 5h16v14H4z";
+
+const MONO = "font-mono text-[13px] tabular-nums";
+
+/** The reason a card gives under its name, when it has one: the far side's own words. */
+function reasonText(reading: MachineReading): string | null {
+ switch (reading.kind) {
+ case "failed":
+ return `${S.machines.failedAt(reading.step)} ${reading.message}`;
+ case "unreachable":
+ return reading.detail;
+ case "working":
+ return reading.step;
+ default:
+ return null;
}
- const version = verdict.version ?? "";
- return {
- text:
- verdict.kind === "already-installed"
- ? S.machines.alreadyInstalled(version)
- : S.machines.installed(version),
- tone: "success",
- };
+}
+
+/** The one line under a machine's name: its state, and the one detail that matters beside it. */
+function stateLine(reading: MachineReading, machine: MachineInfo, locale: "zh" | "en"): string {
+ const m = S.machines;
+ const word = m.state[reading.kind];
+ const checked =
+ machine.connection !== null
+ ? m.now
+ : machine.status !== null
+ ? formatMessageTime(new Date(machine.status.checkedAt).getTime(), locale)
+ : null;
+ switch (reading.kind) {
+ case "behind":
+ return `${word} · ${reading.version}`;
+ case "failed":
+ return `${word} · ${reading.message}`;
+ case "queued":
+ case "working":
+ return word;
+ default:
+ return checked === null ? word : `${word} · ${checked}`;
+ }
+}
+
+/** Where the stepper stands: how many steps are done, and whether one is under way. */
+function stepIndex(job: MachineJob | null): number {
+ if (job === null || job.phase === null) return -1;
+ return MACHINE_PHASES.indexOf(job.phase);
+}
+
+function toggled(set: Set<string>, id: string): Set<string> {
+ const next = new Set(set);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
}
export function MachinesPage() {
useDocumentTitle(S.machines.pageTitle);
+ const { locale } = useLocale();
// Machines belong to the Project, like every other row in this nav group: switching
- // Projects switches which machines are listed, and installing here gives the machine to
- // THIS Project.
+ // Projects switches which machines are listed, and enabling one here gives the machine to
+ // THIS Project — the same one whose Model credentials it will be handed.
const { currentProject } = useProject();
const projectId = currentProject?.projectId ?? null;
const [state, setState] = useState<MachinesResponse | null>(null);
const [error, setError] = useState<string | null>(null);
- /** True while a POST has not come back yet — the server has no job to report in that window. */
- const [starting, setStarting] = useState(false);
- const [selectedId, setSelectedId] = useState<string | null>(null);
+ /** True while a POST has not come back yet. */
+ const [posting, setPosting] = useState(false);
+ /** The batch selection: nothing until someone clicks a card. */
+ const [picked, setPicked] = useState<Set<string>>(() => new Set());
+ /** Cards unfolded to show their details. */
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ /** The form that adds a host to the ssh config, or configures one; null while closed. */
+ const [hostForm, setHostForm] = useState<HostFormMode | null>(null);
- /** The picker panel; closing it always clears the query, so it reopens unfiltered. */
+ /** The picker panel; closing it always clears the query and its picks, so it reopens fresh. */
const [pickerOpen, setPickerOpenState] = useState(false);
const [query, setQuery] = useState("");
- const setPickerOpen = (open: boolean) => {
- setPickerOpenState(open);
- if (!open) setQuery("");
+ const [adding, setAdding] = useState<Set<string>>(() => new Set());
+ /** Whether the picker shows every match, or the first few with a chevron for the rest. */
+ const [showAll, setShowAll] = useState(false);
+ const setPickerOpen = (next: boolean) => {
+ setPickerOpenState(next);
+ if (!next) {
+ setQuery("");
+ setAdding(new Set());
+ setShowAll(false);
+ }
};
const load = useCallback(async () => {
- if (projectId === null) return; // No Project chosen yet: nothing to list machines for.
+ if (projectId === null) return; // No Project chosen yet: there is nothing to list machines for.
try {
setState(await api.getMachines(projectId));
setError(null);
@@ -102,13 +177,13 @@ export function MachinesPage() {
void load();
}, [load]);
- // Poll only while a job runs. Chained timeouts rather than an interval: a slow response
- // must not stack requests behind itself.
- const running = state?.job?.running === true;
+ // Poll only while a job is queued or running. Chained timeouts rather than an interval: a
+ // slow response must not stack requests behind itself.
+ const pending = state !== null && anyJobPending(state);
const loadRef = useRef(load);
loadRef.current = load;
useEffect(() => {
- if (!running) return;
+ if (!pending) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout>;
const tick = () => {
@@ -123,264 +198,714 @@ export function MachinesPage() {
cancelled = true;
clearTimeout(timer);
};
- }, [running]);
-
- // The picker offers targets, and this machine is never one: a server does not push this
- // build over the program directory it is running from (the API says 409 to the attempt).
- const machines = useMemo(() => (state?.machines ?? []).filter((m) => !m.local), [state]);
- const installed = useMemo(() => (state === null ? [] : installedMachines(state)), [state]);
- const matched = useMemo(() => matchMachines(machines, query), [machines, query]);
- const visible = matched.slice(0, MAX_VISIBLE_MACHINES);
+ }, [pending]);
+
+ const machines = useMemo(() => state?.machines ?? [], [state]);
+ const inUse = useMemo(() => (state === null ? [] : installedMachines(state)), [state]);
+ const local = useMemo(() => (state === null ? null : localMachine(state)), [state]);
+ const jobs = useMemo(() => state?.jobs ?? [], [state]);
+ const imageVersion = state?.imageVersion ?? null;
+ const selection = picked;
+ const inUseIds = useMemo(() => new Set(inUse.map((machine) => machine.id)), [inUse]);
+ const selectedIds = useMemo(
+ () => [...selection].filter((id) => inUseIds.has(id)),
+ [selection, inUseIds],
+ );
+ /** Machines in use that carry another build: what one tap brings to this server's version. */
+ const behind = useMemo(() => (state === null ? [] : behindMachines(state)), [state]);
+
+ /** Hosts the picker offers: in the config, not this machine, not already in use here. */
+ const addable = useMemo(
+ () => machines.filter((machine) => !machine.local && !inUseIds.has(machine.id)),
+ [machines, inUseIds],
+ );
+ const matched = useMemo(() => matchMachines(addable, query), [addable, query]);
+ const visible = showAll ? matched : matched.slice(0, MAX_VISIBLE_MACHINES);
const hiddenCount = matched.length - visible.length;
- const selected = machines.find((machine) => machine.id === selectedId) ?? null;
- const install = async () => {
- if (selectedId === null || projectId === null) return;
- setStarting(true);
+ /**
+ * Re-probe the servers in use on a widening schedule. Separate from the job poll above:
+ * that one follows a job and stops when the queue drains, this one watches machines
+ * nobody is touching and has to stay cheap for hours.
+ */
+ const settledRounds = useRef(0);
+ const lastPrint = useRef<string | null>(null);
+ const probe = useCallback(async () => {
+ if (projectId === null) return;
+ try {
+ const next = await api.probeMachines(projectId);
+ const print = probeFingerprint(next.machines);
+ // A round that changed nothing widens the interval; anything moving resets it.
+ settledRounds.current = print === lastPrint.current ? settledRounds.current + 1 : 0;
+ lastPrint.current = print;
+ setState(next);
+ setError(null);
+ } catch (err) {
+ setError(apiErrorText(err));
+ }
+ }, [projectId]);
+
+ const probeRef = useRef(probe);
+ probeRef.current = probe;
+ /** Nothing in use anywhere: there is no server to ask about, so no timer runs at all. */
+ const hasInUse = inUse.length > 0;
+ useEffect(() => {
+ if (!hasInUse) return;
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const arm = (delay: number) => {
+ timer = setTimeout(() => {
+ void probeRef.current().finally(() => {
+ if (!cancelled) arm(probeDelayMs(settledRounds.current));
+ });
+ }, delay);
+ };
+ // The first probe is immediate: opening the page is itself a reason to look.
+ arm(0);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [hasInUse]);
+
+ const post = async (run: (projectId: string) => Promise<MachinesResponse>) => {
+ if (projectId === null) return;
+ setPosting(true);
try {
- setState(await api.installOnMachine(projectId, selectedId));
+ setState(await run(projectId));
setError(null);
} catch (err) {
setError(apiErrorText(err));
} finally {
- setStarting(false);
+ setPosting(false);
}
};
- const job = state?.job ?? null;
- const verdict = job === null ? null : verdictOf(job);
- const verdictText = verdict === null ? null : verdictLine(verdict);
- const button =
- state === null
- ? { action: "install" as const, disabled: true }
- : installButtonState(selected, state, starting);
+ const use = (ids: string[], replaceProgram = false) =>
+ post(async (project) => {
+ const answer = await api.useMachines(project, ids, replaceProgram);
+ if (answer.refused.length > 0) {
+ const byId = new Map(machines.map((machine) => [machine.id, machine.alias]));
+ // Set after `post` clears the error, by way of the microtask order: post awaits
+ // this, so its setError(null) runs first and this one stands.
+ queueMicrotask(() =>
+ setError(
+ answer.refused
+ .map(({ machineId, why }) => {
+ const alias = byId.get(machineId) ?? machineId;
+ if (why === "self") return S.machines.refusedSelf(alias);
+ if (why === "no-image") return S.machines.noImage;
+ return S.machines.refusedUnknown(alias);
+ })
+ .join(" "),
+ ),
+ );
+ }
+ return answer;
+ });
+ const stopUsing = (ids: string[]) => post((project) => api.stopUsingMachines(project, ids));
+ const configure = async (alias: string) => {
+ if (projectId === null) return;
+ try {
+ setHostForm({ kind: "edit", host: await api.getSshHost(projectId, alias) });
+ } catch (err) {
+ toastError(apiErrorText(err));
+ }
+ };
+
+ const togglePicked = (id: string) => setPicked((prev) => toggled(prev, id));
+ const pickAll = () => setPicked(new Set(inUse.map((machine) => machine.id)));
+ const pickNone = () => setPicked(new Set());
+ const toggleExpanded = (id: string) => setExpanded((prev) => toggled(prev, id));
+ const toggleAdding = (id: string) => setAdding((prev) => toggled(prev, id));
+
+ const noImage = state !== null && imageVersion === null;
return (
<div className="h-full overflow-y-auto p-4 md:p-6">
<div className="mx-auto max-w-3xl">
- <h1 className="flex items-center gap-1.5 text-xl font-semibold">
- {S.machines.pageTitle}
- <InfoPopover label={S.machines.pageTitle}>{S.machines.pageDesc}</InfoPopover>
- </h1>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h1 className="text-xl font-semibold">{S.machines.pageTitle}</h1>
+ <div className="flex items-center gap-2">
+ {behind.length > 0 && (
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={posting || pending}
+ onClick={() => void use(behind.map((machine) => machine.id))}
+ >
+ {S.machines.updateAll(behind.length)}
+ </Button>
+ )}
+ <Dropdown
+ open={pickerOpen}
+ setOpen={setPickerOpen}
+ button={
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={state === null || addable.length === 0 || noImage}
+ onClick={() => setPickerOpen(!pickerOpen)}
+ aria-haspopup="listbox"
+ aria-expanded={pickerOpen}
+ >
+ <GlyphIcon d={NAV_ICONS.machines} size={ICON_SIZE.inlineGlyph} />
+ {S.machines.add}
+ </Button>
+ }
+ menuClass="top-full right-0 mt-1 w-80 max-w-[calc(100vw-2rem)] origin-top-right"
+ >
+ {/* The search row: matched characters bright and the rest dimmed — with a
+ subsequence match, an unmarked row looks wrong. */}
+ <div className="px-2 pt-2 pb-1">
+ <input
+ type="search"
+ autoFocus
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={S.machines.search}
+ aria-label={S.machines.search}
+ {...noAutofill}
+ className={`${panelSearchClass} px-2.5 py-1.5`}
+ />
+ </div>
+ <ul
+ role="listbox"
+ aria-multiselectable="true"
+ className="max-h-64 overflow-y-auto py-1"
+ >
+ {visible.map(({ machine, positions }) => {
+ const on = adding.has(machine.id);
+ return (
+ <li key={machine.id} role="option" aria-selected={on}>
+ <button
+ type="button"
+ onClick={() => toggleAdding(machine.id)}
+ className={`flex w-full min-w-0 items-center gap-2.5 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${
+ on
+ ? "bg-gray-100 shadow-[inset_3px_0_0_var(--accent-bg)] dark:bg-gray-800/60"
+ : ""
+ }`}
+ >
+ <span
+ className={`min-w-0 flex-1 truncate ${MONO} ${positions.length > 0 ? "text-gray-400 dark:text-gray-500" : ""}`}
+ >
+ {positions.length === 0
+ ? machine.alias
+ : highlightSegments(machine.alias, positions).map((segment, i) => (
+ <span
+ key={i}
+ className={
+ segment.hit
+ ? "font-semibold text-gray-900 dark:text-white"
+ : undefined
+ }
+ >
+ {segment.text}
+ </span>
+ ))}
+ </span>
+ {/* Installed by this server for another Project: adding it costs no
+ transfer, and the version says whether it is current. */}
+ {machine.elsewhere !== undefined && (
+ <span className={`shrink-0 text-xs ${toneInk.success}`}>
+ {machine.elsewhere.version}
+ </span>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ {matched.length === 0 && (
+ <li className="px-3.5 py-2 text-sm text-gray-400 dark:text-gray-500">
+ {addable.length === 0 ? S.machines.empty : S.machines.noMatch}
+ </li>
+ )}
+ </ul>
+ {/* The foot: the rest of the config folded behind a chevron — for when a search
+ is the wrong tool and a person wants to see the list — and, at the right, a
+ new host for the config. */}
+ <div className="flex items-center justify-between gap-2 border-t border-gray-200 px-2 py-1.5 dark:border-gray-800">
+ {hiddenCount > 0 || (showAll && matched.length > MAX_VISIBLE_MACHINES) ? (
+ <Verb
+ label={showAll ? S.machines.fewer : S.machines.expand}
+ title={showAll ? S.machines.fewer : S.machines.allHosts(hiddenCount)}
+ d={CHEVRON_PATH}
+ glyphClass={`transition-transform ${showAll ? "rotate-180" : ""}`}
+ ariaExpanded={showAll}
+ onClick={() => setShowAll((open) => !open)}
+ />
+ ) : (
+ <span />
+ )}
+ <Verb
+ label={S.machines.host.newVerb}
+ title={S.machines.host.addTitle}
+ d={PLUS_PATH}
+ onClick={() => {
+ setPickerOpen(false);
+ setHostForm({ kind: "add" });
+ }}
+ />
+ </div>
+ {/* The confirm appears once something is picked; an empty footer says nothing. */}
+ {adding.size > 0 && (
+ <div className="flex justify-end border-t border-gray-200 px-3 py-2 dark:border-gray-800">
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={posting}
+ onClick={() => {
+ const ids = [...adding];
+ setPickerOpen(false);
+ void use(ids);
+ }}
+ >
+ <GlyphIcon d={PLUG_PATH} size={ICON_SIZE.inlineGlyph} />
+ {S.machines.addSelected(adding.size)}
+ </Button>
+ </div>
+ )}
+ </Dropdown>
+ </div>
+ </div>
+ {projectId !== null && hostForm !== null && (
+ <SshHostDialog
+ key={hostForm.kind === "edit" ? hostForm.host.alias : "add"}
+ mode={hostForm}
+ projectId={projectId}
+ onClose={() => setHostForm(null)}
+ onSaved={(next) => {
+ setState(next);
+ setError(null);
+ }}
+ />
+ )}
{error !== null && (
<div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>
{error}
</div>
)}
+ {noImage && error === null && (
+ <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.attention}`}>
+ {S.machines.noImage}
+ </div>
+ )}
+
+ {/* The selection bar: a fixed slot between the title and the cards, so the cards
+ never move when a selection appears or goes. The count is the slot's label; on the
+ right, select all and none, then the two verbs — bare glyphs here (see Verb), each
+ dimmed when it would do nothing. */}
+ <div className="mt-3 flex min-h-10 flex-wrap items-center gap-x-3 gap-y-2 px-1 text-xs text-gray-500">
+ <span className="tabular-nums">{S.machines.selectedCount(selectedIds.length)}</span>
+ <span className="ml-auto flex flex-wrap items-center gap-1">
+ <Verb
+ wordless
+ label={S.machines.pickAll}
+ d={SELECT_ALL_PATH}
+ disabled={inUse.length === 0 || selectedIds.length === inUse.length}
+ onClick={pickAll}
+ />
+ <Verb
+ wordless
+ label={S.machines.pickNone}
+ d={SELECT_NONE_PATH}
+ disabled={selectedIds.length === 0}
+ onClick={pickNone}
+ />
+ <span className="mx-1 h-4 w-px bg-gray-200 dark:bg-gray-700" aria-hidden="true" />
+ <Verb
+ wordless
+ label={S.machines.use}
+ d={PLUG_PATH}
+ disabled={selectedIds.length === 0 || posting || noImage}
+ onClick={() => void use(selectedIds)}
+ />
+ <Verb
+ wordless
+ label={S.machines.stopUsing}
+ d={UNPLUG_PATH}
+ disabled={selectedIds.length === 0 || posting}
+ onClick={() => void stopUsing(selectedIds)}
+ />
+ </span>
+ </div>
{state === null ? (
- <div className="mt-6 space-y-2">
- <Skeleton className="h-4 w-40" />
- <Skeleton className="h-9 w-full" />
- </div>
+ <Skeleton className="h-40 w-full rounded-xl" />
) : (
- <>
- {state.imageVersion === null ? (
- <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.attention}`}>
- {S.machines.noImage}
- </div>
- ) : (
- <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
- {S.machines.imageVersion(state.imageVersion)}
- </p>
+ <ul className="space-y-2">
+ {local !== null && (
+ <LocalCard
+ machine={local}
+ locale={locale}
+ open={expanded.has(local.id)}
+ onToggleOpen={() => toggleExpanded(local.id)}
+ />
)}
-
- {machines.length === 0 ? (
- <EmptyState title={S.machines.empty} />
- ) : (
- <div className="mt-6 flex items-start gap-2">
- {/* The picker. Fuzzy query over the aliases, matched characters bright and
- the rest dimmed — with a subsequence match, an unmarked row looks wrong. */}
- <Dropdown
- open={pickerOpen}
- setOpen={setPickerOpen}
- className="min-w-0 flex-1"
- menuClass="left-0 right-0 top-full mt-1 origin-top"
- button={
- <button
- type="button"
- onClick={() => setPickerOpen(!pickerOpen)}
- aria-haspopup="listbox"
- aria-expanded={pickerOpen}
- className="flex w-full items-center gap-2 rounded-md border border-gray-300 bg-white px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-900 dark:hover:bg-gray-800"
- >
- <span className="shrink-0 text-gray-500 dark:text-gray-400">
- <GlyphIcon d={NAV_ICONS.machines} size={ICON_SIZE.rowLead} />
- </span>
- <span
- className={`min-w-0 flex-1 truncate ${selected === null ? "text-gray-400 dark:text-gray-500" : ""}`}
- >
- {selected?.alias ?? S.machines.pick}
- </span>
- <ChevronDown className="shrink-0 text-gray-400" />
- </button>
- }
- >
- {machines.length > MAX_VISIBLE_MACHINES && (
- <div className="px-2 pt-1 pb-1">
- <input
- type="search"
- autoFocus
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={S.machines.search}
- aria-label={S.machines.search}
- {...noAutofill}
- className={`${panelSearchClass} px-2.5 py-1.5`}
- />
- </div>
- )}
- {visible.map(({ machine, positions }) => (
- <button
- key={machine.id}
- type="button"
- onClick={() => {
- setSelectedId(machine.id);
- setPickerOpen(false);
- }}
- className="flex w-full min-w-0 items-center gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800"
- >
- <span
- className={`min-w-0 flex-1 truncate ${positions.length > 0 ? "text-gray-400 dark:text-gray-500" : ""}`}
- >
- {positions.length === 0
- ? machine.alias
- : highlightSegments(machine.alias, positions).map((segment, i) => (
- <span
- key={i}
- className={
- segment.hit
- ? "font-semibold text-gray-900 dark:text-white"
- : undefined
- }
- >
- {segment.text}
- </span>
- ))}
- </span>
- {/* Which hosts already carry this program — the version, not a bare
- tick, because a stale one is the reason to reinstall. */}
- {machine.installed !== null && (
- <span className={`shrink-0 text-xs ${toneInk.success}`}>
- {machine.installed.version}
- </span>
- )}
- </button>
- ))}
- {visible.length === 0 && (
- <p className="px-3.5 py-2 text-sm text-gray-400 dark:text-gray-500">
- {S.machines.noMatch}
- </p>
- )}
- {hiddenCount > 0 && (
- <p className="px-3.5 pt-1 pb-1.5 text-xs text-gray-400 dark:text-gray-500">
- {S.machines.more(hiddenCount)}
- </p>
- )}
- </Dropdown>
- <Button
- size="sm"
- variant="primary"
- disabled={button.disabled}
- onClick={() => void install()}
- className="shrink-0"
- >
- {button.action === "installing"
- ? S.machines.installing
- : button.action === "reinstall"
- ? S.machines.reinstall
- : S.machines.install}
- </Button>
- </div>
+ {inUse.map((machine) => (
+ <MachineCard
+ key={machine.id}
+ machine={machine}
+ job={jobFor(jobs, machine.id)}
+ imageVersion={imageVersion}
+ locale={locale}
+ selected={selection.has(machine.id)}
+ onToggle={() => togglePicked(machine.id)}
+ open={expanded.has(machine.id)}
+ onToggleOpen={() => toggleExpanded(machine.id)}
+ busy={posting}
+ onUse={(replaceProgram) => void use([machine.id], replaceProgram)}
+ onStopUsing={() => void stopUsing([machine.id])}
+ onConfigure={() => void configure(machine.alias)}
+ />
+ ))}
+ {inUse.length === 0 && (
+ <li className="rounded-xl border border-dashed border-gray-300 p-4 text-sm text-gray-500 dark:border-gray-700">
+ <p>{S.machines.noneInUse}</p>
+ <p className="mt-1 text-xs">{S.machines.sshHint}</p>
+ </li>
)}
+ </ul>
+ )}
+ </div>
+ </div>
+ );
+}
- {selected?.installed != null && (
- <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
- {S.machines.installedAt(
- selected.installed.version,
- formatDateTime(selected.installed.at),
- )}
- </p>
- )}
+/**
+ * Every verb on the page in one shape: a small secondary button carrying one glyph, and the
+ * word beside it — configure, new, force install. The glyph says which verb, the word
+ * confirms it. The forced install alone keeps the danger variant, since it interrupts
+ * whoever is on the machine.
+ *
+ * `wordless` is the SELECTION BAR alone, where four of these sit in a row over the cards.
+ * There the words read as a sentence nobody wrote, and each glyph is already the plainest
+ * thing about its button — the box, the empty box, the plug, the unplugged plug. The box
+ * around it goes with the word: a bordered button with nothing but a glyph in it draws a
+ * frame around something that was already legible, and four of those in a row are four
+ * frames. What is left is the glyph, with a hover the pointer can find; the word survives as
+ * the tooltip and as the accessible name, so nothing is lost to a screen reader or to a
+ * pointer that waits. Same shape as the chevron below, for the same reason.
+ */
+function Verb({
+ label,
+ d,
+ disabled = false,
+ onClick,
+ variant = "secondary",
+ title,
+ glyphClass = "",
+ ariaExpanded,
+ wordless = false,
+}: {
+ label: string;
+ d: string;
+ disabled?: boolean;
+ onClick: () => void;
+ variant?: "secondary" | "danger";
+ title?: string;
+ glyphClass?: string;
+ ariaExpanded?: boolean;
+ wordless?: boolean;
+}) {
+ const click = (event: { stopPropagation(): void }) => {
+ event.stopPropagation();
+ onClick();
+ };
+ if (wordless) {
+ return (
+ <button
+ type="button"
+ disabled={disabled}
+ title={title ?? label}
+ aria-label={label}
+ aria-expanded={ariaExpanded}
+ onClick={click}
+ className={`rounded-md p-1.5 text-gray-500 transition-colors enabled:hover:bg-gray-100 enabled:hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-400 dark:enabled:hover:bg-gray-800 dark:enabled:hover:text-gray-200`}
+ >
+ <GlyphIcon d={d} size={ICON_SIZE.inlineGlyph} className={glyphClass} />
+ </button>
+ );
+ }
+ return (
+ <Button
+ size="sm"
+ variant={variant}
+ disabled={disabled}
+ title={title ?? label}
+ aria-expanded={ariaExpanded}
+ className="whitespace-nowrap"
+ onClick={click}
+ >
+ <GlyphIcon d={d} size={ICON_SIZE.inlineGlyph} className={glyphClass} />
+ {label}
+ </Button>
+ );
+}
- {/* What this server has already installed, standing on the page rather than
- only inside the picker: it is the answer to "what did I do", which a panel
- that has to be opened one row at a time cannot give. */}
- {installed.length > 0 && (
- <section className="mt-6">
- <h2 className="text-sm font-semibold text-gray-500 dark:text-gray-400">
- {S.machines.installedTitle(installed.length)}
- </h2>
- <div className="mt-2 divide-y divide-gray-200 overflow-hidden rounded-md border border-gray-200 dark:divide-gray-800 dark:border-gray-800">
- {installed.map((machine) => (
- <button
- key={machine.id}
- type="button"
- onClick={() => setSelectedId(machine.id)}
- aria-current={machine.id === selectedId ? "true" : undefined}
- className={`flex w-full min-w-0 items-center gap-3 px-3 py-2.5 text-left transition-colors duration-150 ${
- machine.id === selectedId
- ? "bg-gray-100 dark:bg-gray-800"
- : "bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800/70"
- }`}
- >
- <span className="shrink-0 text-gray-500 dark:text-gray-400">
- <GlyphIcon d={NAV_ICONS.machines} size={ICON_SIZE.rowLead} />
- </span>
- <span className="min-w-0 flex-1 truncate text-sm font-medium">
- {machine.alias}
- </span>
- <span className={`shrink-0 text-xs ${toneInk.success}`}>
- {machine.installed!.version}
- </span>
- <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">
- {formatDateTime(machine.installed!.at)}
- </span>
- </button>
- ))}
- </div>
- </section>
- )}
+/** The chevron that unfolds a card's details. */
+function ExpandButton({
+ alias,
+ open,
+ controls,
+ onClick,
+}: {
+ alias: string;
+ open: boolean;
+ controls: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={`${S.machines.details}: ${alias}`}
+ aria-expanded={open}
+ aria-controls={controls}
+ onClick={(event) => {
+ event.stopPropagation();
+ onClick();
+ }}
+ className="rounded-md p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <ChevronDown
+ size={ICON_SIZE.chevron}
+ className={`transition-transform ${open ? "rotate-180" : ""}`}
+ />
+ </button>
+ );
+}
- {/* The job, whichever machine it belongs to — named, so a selection change
- while one runs never leaves an unattributed log on screen. */}
- {job !== null && (
- <section className="mt-5 overflow-hidden rounded-md border border-gray-200 dark:border-gray-800">
- <div className="flex items-center gap-2 bg-gray-50 px-3 py-2 dark:bg-gray-900">
- <span className="min-w-0 flex-1 truncate text-sm font-medium">{job.alias}</span>
- {running ? (
- <span className={`text-xs ${toneInk.busy}`}>{S.machines.installing}</span>
- ) : (
- verdictText !== null && (
- <span className={`text-xs ${toneInk[verdictText.tone]}`}>
- {verdictText.text}
- </span>
- )
- )}
- </div>
- {job.log.length > 0 && (
- <div className="border-t border-gray-100 px-3 py-2 dark:border-gray-800">
- <p className="text-xs font-medium text-gray-500 dark:text-gray-400">
- {S.machines.output}
- </p>
- <pre className="mt-1 max-h-64 overflow-auto font-mono text-xs break-words whitespace-pre-wrap text-gray-700 dark:text-gray-300">
- {job.log.join("\n")}
- </pre>
- {verdict?.kind === "failed" && (
- <pre
- className={`mt-2 font-mono text-xs break-words whitespace-pre-wrap ${toneInk.danger}`}
- >
- {verdict.message}
- </pre>
- )}
- </div>
- )}
- </section>
- )}
- </>
+/** The six-segment stepper under a working card, and the step it is on. */
+function Stepper({ step, caption }: { step: number; caption: string }) {
+ return (
+ <div className="mt-1.5 w-44 max-w-full">
+ <div className="flex gap-0.5" aria-hidden="true">
+ {MACHINE_PHASES.map((phase, index) => (
+ <span
+ key={phase}
+ className={`h-[3px] flex-1 rounded-sm ${
+ index < step
+ ? toneDot.busy
+ : index === step
+ ? `${toneDot.busy} animate-pulse`
+ : "bg-gray-200 dark:bg-gray-700"
+ }`}
+ />
+ ))}
+ </div>
+ <div className={`mt-1 truncate text-xs ${toneInk.busy}`}>{caption}</div>
+ </div>
+ );
+}
+
+const CARD = "rounded-xl border px-4 py-3 text-sm transition-colors";
+
+const domId = (machineId: string) => `machine-details-${machineId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
+
+/** This server's own card: not selectable — it is where the page is served from. */
+function LocalCard({
+ machine,
+ locale,
+ open,
+ onToggleOpen,
+}: {
+ machine: MachineInfo;
+ locale: "zh" | "en";
+ open: boolean;
+ onToggleOpen: () => void;
+}) {
+ const id = domId(machine.id);
+ return (
+ <li className={`${CARD} border-gray-200 dark:border-gray-800`}>
+ <div className="flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className={`${MONO} truncate font-medium`}>{machine.alias}</span>
+ <span className="shrink-0 rounded border border-gray-200 px-1.5 py-px text-[11px] text-gray-500 dark:border-gray-700">
+ {S.machines.localTitle}
+ </span>
+ </div>
+ <div className="mt-0.5 truncate text-xs text-gray-500">{S.machines.state.serving}</div>
+ </div>
+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot.link}`} aria-hidden="true" />
+ <ExpandButton alias={machine.alias} open={open} controls={id} onClick={onToggleOpen} />
+ </div>
+ <div id={id} hidden={!open}>
+ <Record machine={machine} locale={locale} />
+ </div>
+ </li>
+ );
+}
+
+function MachineCard({
+ machine,
+ job,
+ imageVersion,
+ locale,
+ selected,
+ onToggle,
+ open,
+ onToggleOpen,
+ busy,
+ onUse,
+ onStopUsing,
+ onConfigure,
+}: {
+ machine: MachineInfo;
+ job: MachineJob | null;
+ imageVersion: string | null;
+ locale: "zh" | "en";
+ selected: boolean;
+ onToggle: () => void;
+ open: boolean;
+ onToggleOpen: () => void;
+ busy: boolean;
+ onUse: (replaceProgram: boolean) => void;
+ onStopUsing: () => void;
+ onConfigure: () => void;
+}) {
+ const reading = readMachine(machine, job, imageVersion);
+ const tone = readingTone(reading);
+ const moving = reading.kind === "working" || reading.kind === "queued";
+ const step = moving ? stepIndex(job) : -1;
+ const caption =
+ reading.kind === "queued"
+ ? S.machines.queued
+ : step >= 0
+ ? S.machines.phase[MACHINE_PHASES[step]!]
+ : S.machines.working;
+ // The line under the name is grey unless it names a problem: the dot carries the state.
+ const lineInk =
+ tone === "attention" || tone === "danger" ? toneInk[tone] : "text-gray-500 dark:text-gray-400";
+ const id = domId(machine.id);
+ return (
+ <li
+ aria-selected={selected}
+ onClick={onToggle}
+ className={`${CARD} cursor-pointer ${
+ selected
+ ? "border-gray-900 bg-gray-100/70 dark:border-gray-200 dark:bg-gray-800/40"
+ : "border-gray-200 hover:border-gray-300 dark:border-gray-800 dark:hover:border-gray-700"
+ }`}
+ >
+ <div className="flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className={`${MONO} truncate font-medium`}>{machine.alias}</div>
+ {moving ? (
+ <Stepper step={step} caption={caption} />
+ ) : (
+ <div
+ className={`mt-0.5 truncate text-xs ${lineInk}`}
+ title={reasonText(reading) ?? undefined}
+ >
+ {stateLine(reading, machine, locale)}
+ </div>
+ )}
+ </div>
+ {wantsUse(reading) && (
+ <Verb label={S.machines.use} d={PLUG_PATH} disabled={busy} onClick={() => onUse(false)} />
)}
+ <span
+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot[tone]} ${moving ? "animate-pulse" : ""}`}
+ aria-hidden="true"
+ />
+ <ExpandButton alias={machine.alias} open={open} controls={id} onClick={onToggleOpen} />
</div>
+ <div id={id} hidden={!open} onClick={(event) => event.stopPropagation()}>
+ <Record machine={machine} locale={locale} />
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ {reading.kind === "failed" && reading.canReplaceProgram && (
+ <Verb
+ label={S.machines.replaceProgram}
+ title={S.machines.replaceProgramWhy}
+ d={PLUG_PATH}
+ variant="danger"
+ disabled={busy}
+ onClick={() => onUse(true)}
+ />
+ )}
+ {wantsUse(reading) && (
+ <Verb
+ label={S.machines.use}
+ d={PLUG_PATH}
+ disabled={busy}
+ onClick={() => onUse(false)}
+ />
+ )}
+ <Verb
+ label={S.machines.stopUsing}
+ d={UNPLUG_PATH}
+ disabled={busy}
+ onClick={onStopUsing}
+ />
+ <Verb
+ label={S.machines.host.configureVerb}
+ title={S.machines.host.configure}
+ d={GEAR_ICON}
+ disabled={busy}
+ onClick={onConfigure}
+ />
+ </div>
+ <Output job={job} />
+ </div>
+ </li>
+ );
+}
+
+/** The record, unfolded inside a card. */
+function Record({ machine, locale }: { machine: MachineInfo; locale: "zh" | "en" }) {
+ const m = S.machines;
+ return (
+ <dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 border-t border-gray-200 pt-3 text-xs dark:border-gray-800">
+ {machine.installed !== null && (
+ <>
+ <dt className="text-gray-500">{machine.local ? m.detailVersion : m.detailInstalled}</dt>
+ <dd className={MONO}>{machine.installed.version}</dd>
+ <dt className="text-gray-500">{machine.local ? m.detailStarted : m.detailSince}</dt>
+ <dd>{formatDateTime(machine.installed.at)}</dd>
+ </>
+ )}
+ {machine.status !== null && (
+ <>
+ <dt className="text-gray-500">{m.detailServer}</dt>
+ <dd>
+ {machine.status.state === "running"
+ ? m.serverUpOn(machine.status.port ?? 0)
+ : machine.status.state === "stopped"
+ ? m.state.stopped
+ : (machine.status.detail ?? m.state.unreachable)}
+ </dd>
+ <dt className="text-gray-500">{m.detailChecked}</dt>
+ <dd>{formatMessageTime(new Date(machine.status.checkedAt).getTime(), locale)}</dd>
+ </>
+ )}
+ {machine.machineId !== null && (
+ <>
+ <dt className="text-gray-500">{m.detailMachineId}</dt>
+ <dd className={`${MONO} truncate`}>{machine.machineId}</dd>
+ </>
+ )}
+ {/* Which installation over there this row is about: a dev instance and a release one
+ reach the same machine and mean different roots. */}
+ <dt className="text-gray-500">{m.detailRoot}</dt>
+ <dd className={`${MONO} break-all`}>{machine.root}</dd>
+ </dl>
+ );
+}
+
+/** The job's output, unfolded inside a card, with its latest line bright. */
+function Output({ job }: { job: MachineJob | null }) {
+ if (job === null || job.log.length === 0) return null;
+ return (
+ <div className="mt-3">
+ <div className="mb-1 text-xs text-gray-500">{S.machines.output}</div>
+ <pre className="max-h-64 overflow-auto rounded-md bg-gray-50 p-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-gray-500 dark:bg-gray-900">
+ {job.log.slice(0, -1).join("\n")}
+ {job.log.length > 1 ? "\n" : ""}
+ <span className="text-gray-900 dark:text-gray-100">{job.log.at(-1)}</span>
+ </pre>
</div>
);
}
diff --git a/packages/web/src/features/machines/machines-view.ts b/packages/web/src/features/machines/machines-view.ts
index d1f4b1cc..1e77f243 100644
--- a/packages/web/src/features/machines/machines-view.ts
+++ b/packages/web/src/features/machines/machines-view.ts
@@ -1,94 +1,185 @@
/**
- * What the Machines page's install control offers, decided as data rather than in JSX.
+ * What the Machines page derives from the server's answer: which machines are in use, the
+ * one sentence each row says, and what the batch selects by default.
*
- * The server keeps ONE install job at a time, so the button is governed by two things that
- * are not the same: which machine is SELECTED in the picker, and which machine the job (if
- * any) belongs to. They come apart the moment someone picks a second host while the first
- * is still installing — the button must refuse, but the running job's log still belongs on
- * screen, under the alias it is actually installing to. That is why the job panel renders
- * from `state.job` directly and only the button consults the selection.
- *
- * "Already installed" is a THIRD thing, and it comes from the machine's own persisted
- * record rather than from the job: the job is one slot, so deriving it from there made an
- * installed machine vanish as soon as anything else was installed or the server restarted.
+ * A row's reading follows a fixed precedence. The server's job for that machine is the
+ * freshest word (queued, working, failed); a held connection settles "ready" whatever an
+ * older job said, so a machine a re-hold brought back after a failed job reads as ready
+ * rather than failed; only then does the last probe speak. Every reading a person can act
+ * on is fixed by the same verb — use the machine — so the page never has to explain which
+ * of install, update, start, connect a row needs.
*/
-import type { MachineInfo, MachineJob, MachinesResponse } from "@prismshadow/penguin-server/api";
-
-/** The finished job's verdict, in the shape the page renders. */
-export type MachineVerdict =
- | { kind: "installed"; version: string | null }
- | { kind: "already-installed"; version: string | null }
- | { kind: "failed"; step: string; message: string };
+import type {
+ MachineInfo,
+ MachineJob,
+ MachinePhase,
+ MachinesResponse,
+} from "@prismshadow/penguin-server/api";
+import type { Tone } from "../../lib/tone";
-export interface InstallButtonState {
- /** What the button offers: a fresh install, one already under way, or a repeat of a finished one. */
- action: "install" | "installing" | "reinstall";
+export type MachineReading =
+ /** Waiting its turn behind another machine's job. */
+ | { kind: "queued" }
+ /** The server is working on it; `step` is its latest line. */
+ | { kind: "working"; step: string | null }
+ /** The last job failed, in the far side's own words; `canReplaceProgram` offers the forced install. */
+ | { kind: "failed"; step: string; message: string; canReplaceProgram: boolean }
+ /** Connected and answering: agents can run there. */
+ | { kind: "ready"; port: number | null }
/**
- * True when the button must not start anything: nothing is selected, a job is running
- * anywhere (one at a time, server-side), this page's own POST is in flight, or this
- * server has no image to send at all.
+ * A connection is held, but the last probe found no server running over there. Not a
+ * contradiction and not a corner case: the connection is an ssh process on THIS side and
+ * outlives the far server, so it says the tunnel has somewhere to go, never that anything
+ * answers. Its own reading because it needs its own action — `use` starts the server.
*/
- disabled: boolean;
+ | { kind: "linkedStopped" }
+ /** Installed, and that is as far as this server can take it (a Windows machine). */
+ | { kind: "installedOnly" }
+ /** Carrying a different build from the one this server would install. */
+ | { kind: "behind"; version: string }
+ /** Its server answers but nothing holds a connection to it. */
+ | { kind: "notConnected" }
+ | { kind: "unreachable"; detail: string | null }
+ | { kind: "stopped" }
+ /** Never probed. */
+ | { kind: "unknown" };
+
+/**
+ * The pipeline's steps in the order a `use` job runs them — the stepper's segments. Spelled
+ * here rather than imported because the server's api entry reaches the web as types only;
+ * the type keeps it in step with the server's `MachinePhase`, and `PHASE_COMPLETE` fails
+ * the build if a step is missing.
+ */
+export const MACHINE_PHASES = [
+ "check",
+ "install",
+ "handover",
+ "restart",
+ "connect",
+ "sync",
+] as const satisfies readonly MachinePhase[];
+const PHASE_COMPLETE: Record<MachinePhase, true> = {
+ check: true,
+ install: true,
+ handover: true,
+ restart: true,
+ connect: true,
+ sync: true,
+};
+void PHASE_COMPLETE;
+
+/** The job the server has for a machine — queued, running, or its last finished one. */
+export function jobFor(jobs: readonly MachineJob[], machineId: string): MachineJob | null {
+ return jobs.find((job) => job.machineId === machineId) ?? null;
}
-/** The verdict of a job that has finished, or null while it is still running. */
-export function verdictOf(job: MachineJob): MachineVerdict | null {
- if (job.result === null) return null;
- if (!job.result.ok) return { kind: "failed", step: job.result.step, message: job.result.message };
- // A connect has no install verdict to report; the controls that start one, and what they
- // render when it settles, arrive with the page that has them.
- if (!("installed" in job.result)) return null;
- return { kind: job.result.installed, version: job.result.version };
+export function readMachine(
+ machine: MachineInfo,
+ job: MachineJob | null,
+ imageVersion: string | null,
+): MachineReading {
+ if (job?.queued) return { kind: "queued" };
+ if (job?.running) return { kind: "working", step: job.log.at(-1) ?? null };
+ if (machine.connection !== null) {
+ // A held connection is not liveness — the lesson of #561, read the other way round. It
+ // used to win outright here, so a machine whose server had stopped still read "Connected"
+ // while its own details said otherwise, and `use` (the thing that would start it again)
+ // was withheld because the row looked ready. What the last probe found now has the say.
+ const status = machine.status;
+ if (status !== null && status.state === "stopped") return { kind: "linkedStopped" };
+ if (status !== null && status.state === "unreachable") {
+ return { kind: "unreachable", detail: status.detail ?? null };
+ }
+ return {
+ kind: "ready",
+ port: status?.state === "running" ? (status.port ?? null) : null,
+ };
+ }
+ const result = job?.result ?? null;
+ if (result !== null && !result.ok) {
+ return {
+ kind: "failed",
+ step: result.step,
+ message: result.message,
+ canReplaceProgram: result.canReplaceProgram === true,
+ };
+ }
+ if (result !== null && job?.kind === "use" && "installed" in result)
+ return { kind: "installedOnly" };
+ if (outOfDate(machine, imageVersion)) {
+ return { kind: "behind", version: machine.installed!.version };
+ }
+ const status = machine.status;
+ if (status === null) return { kind: "unknown" };
+ if (status.state === "unreachable") return { kind: "unreachable", detail: status.detail ?? null };
+ if (status.state === "stopped") return { kind: "stopped" };
+ return { kind: "notConnected" };
}
-/**
- * `starting` is true while a POST has not come back yet. It exists because the server has
- * no job to report during that window, and a button that stays on "Install" through a click
- * reads as a click that did nothing.
- */
-export function installButtonState(
- selected: MachineInfo | null,
- state: MachinesResponse,
- starting: boolean,
-): InstallButtonState {
- const job = state.job;
- const runningSomewhere = job?.running === true;
- const selectedIsRunning = runningSomewhere && job.machineId === selected?.id;
- return {
- action:
- selectedIsRunning || starting
- ? "installing"
- : selected?.installed != null
- ? "reinstall"
- : "install",
- disabled: selected === null || runningSomewhere || starting || state.imageVersion === null,
- };
+/** The tone a reading's mark carries — by what it means, as tone.ts asks; a held connection is `link`, never `success`. */
+export function readingTone(reading: MachineReading): Tone {
+ switch (reading.kind) {
+ case "queued":
+ case "working":
+ return "busy";
+ case "failed":
+ case "unreachable":
+ return "danger";
+ case "ready":
+ // A held connection is a live link, not a verdict: blue, never green.
+ return "link";
+ case "linkedStopped":
+ // The link is up and nothing is serving: something for a person to do, not a failure.
+ return "attention";
+ case "unknown":
+ return "muted";
+ default:
+ return "attention";
+ }
+}
+
+/** Whether "use" would change anything for this row — everything but ready, busy, and installed-as-far-as-it-goes. */
+export function wantsUse(reading: MachineReading): boolean {
+ return !["queued", "working", "ready", "installedOnly"].includes(reading.kind);
}
/**
- * The machines this server has installed on, most recently installed first — the standing
- * answer to "what did I already do", which the picker can only give one row at a time and
- * only while it is open.
- *
- * Newest first because the list is read to check recent work, not to look a host up: the
- * picker's search is what finds a specific alias. Ties (two installs in the same
- * millisecond, which the tests do produce) keep the config's order rather than swapping
- * around, so the list is stable between polls.
- *
- * Records whose host is no longer declared in the ssh config never reach here: the server
- * builds the list from the config, so a renamed or deleted Host drops out of the page while
- * its record sits harmlessly in the file. There is nothing useful to offer for a host this
- * server can no longer resolve, let alone install to.
+ * The machines in use here: those this server has installed on for this Project, by name.
+ * By name and nothing else, because the order must not move under a person's eyes: an
+ * update rewrites the install time, a probe rewrites the status, and a card that jumps to
+ * the top on either is a card someone was about to click. Names compare naturally, so
+ * `gpu-2` sits before `gpu-10`. The local entry is kept out: it is where you are, not
+ * something you did.
*/
export function installedMachines(state: MachinesResponse): MachineInfo[] {
- // This machine is always installed and never a target: it is not a remote, so it is not
- // in the list of remotes this server has put the program on.
return state.machines
- .map((machine, index) => ({ machine, index }))
- .filter((entry) => !entry.machine.local && entry.machine.installed != null)
- .sort((a, b) => {
- const at = b.machine.installed!.at.localeCompare(a.machine.installed!.at);
- return at !== 0 ? at : a.index - b.index;
- })
- .map((entry) => entry.machine);
+ .filter((machine) => machine.installed != null && !machine.local)
+ .sort((a, b) =>
+ a.alias.localeCompare(b.alias, undefined, { numeric: true, sensitivity: "base" }),
+ );
+}
+
+/** The local entry, which the server always puts first. */
+export function localMachine(state: MachinesResponse): MachineInfo | null {
+ return state.machines.find((machine) => machine.local) ?? null;
+}
+
+/**
+ * A machine carrying a different build from the one this server would install: what "use"
+ * brings forward. No image, or a fresh machine, is not "behind" — there is nothing to
+ * compare against, or nothing to update.
+ */
+export function outOfDate(machine: MachineInfo, imageVersion: string | null): boolean {
+ if (imageVersion === null || machine.local || machine.installed === null) return false;
+ return machine.installed.version !== imageVersion;
+}
+
+/** The machines in use that carry another build — what "update all" brings forward, in list order. */
+export function behindMachines(state: MachinesResponse): MachineInfo[] {
+ return installedMachines(state).filter((machine) => outOfDate(machine, state.imageVersion));
+}
+
+/** Whether any job is still to come, which is when the page keeps polling. */
+export function anyJobPending(state: MachinesResponse): boolean {
+ return state.jobs.some((job) => job.queued || job.running);
}
diff --git a/packages/web/src/features/machines/probe-schedule.ts b/packages/web/src/features/machines/probe-schedule.ts
new file mode 100644
index 00000000..ae77a3fe
--- /dev/null
+++ b/packages/web/src/features/machines/probe-schedule.ts
@@ -0,0 +1,50 @@
+/**
+ * How often the Machines page re-probes the servers it installed.
+ *
+ * Each probe is an ssh round trip per installed machine, so the interval widens as the
+ * answers stop changing: 15s, 30s, 45s, then a minute, two, three… up to ten. Something
+ * that just moved is worth watching closely; a fleet that has read the same for an hour is
+ * not worth an ssh child a minute.
+ *
+ * Any CHANGE resets it to the first step — a server that just went down, or an install that
+ * just finished, is the moment the next few answers matter most. The schedule lives here,
+ * on the page, rather than on the server: a timer over there would keep spawning ssh long
+ * after the last person closed the tab.
+ */
+
+/** The widening steps, in milliseconds. The last one repeats forever. */
+export const PROBE_STEPS_MS = [
+ 15_000, 30_000, 45_000, 60_000, 120_000, 180_000, 240_000, 300_000, 360_000, 420_000, 480_000,
+ 540_000, 600_000,
+] as const;
+
+/** The wait before the probe after `settledRounds` consecutive rounds that changed nothing. */
+export function probeDelayMs(settledRounds: number): number {
+ const index = Math.min(Math.max(settledRounds, 0), PROBE_STEPS_MS.length - 1);
+ return PROBE_STEPS_MS[index]!;
+}
+
+/**
+ * A fingerprint of everything a probe could have changed, compared between rounds to decide
+ * whether the schedule widens or resets.
+ *
+ * `checkedAt` is deliberately NOT part of it: every probe moves that, so including it would
+ * make every round look like a change and pin the interval at 15 seconds forever — which is
+ * exactly the bug this function exists to avoid. What counts is the state, the port it
+ * reports, and which machines are installed at all.
+ */
+export function probeFingerprint(
+ machines: ReadonlyArray<{
+ id: string;
+ installed: { version: string } | null;
+ status: { state: string; port?: number } | null;
+ }>,
+): string {
+ return machines
+ .map((machine) => {
+ const status = machine.status;
+ const state = status === null ? "-" : `${status.state}:${status.port ?? ""}`;
+ return `${machine.id}=${machine.installed?.version ?? "-"}/${state}`;
+ })
+ .join("|");
+}
diff --git a/packages/web/src/features/machines/ssh-host-dialog.tsx b/packages/web/src/features/machines/ssh-host-dialog.tsx
new file mode 100644
index 00000000..55f0a2da
--- /dev/null
+++ b/packages/web/src/features/machines/ssh-host-dialog.tsx
@@ -0,0 +1,245 @@
+/**
+ * The form that adds a host to this server's `~/.ssh/config` from the Machines page, or
+ * rewrites one this app wrote: the alias, and what ssh needs to reach it. Validated here
+ * the way the server validates it — one word per value, a port in range — so the person
+ * hears about a bad value under the field rather than in a toast after a round trip.
+ * Writing goes through the server, which appends or rewrites the block and answers the
+ * machines list; the caller takes that list as its state.
+ *
+ * A block written by hand is shown but not saved: it may carry options this form does not
+ * know, and rewriting it would drop them. The form says so and points at the file.
+ */
+import { useState } from "react";
+import type { ChangeEvent, KeyboardEvent } from "react";
+import type {
+ MachinesResponse,
+ SshHostRequest,
+ SshHostResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { toneStrip } from "../../lib/tone";
+import { Button } from "../../components/ui/button";
+import { Input } from "../../components/ui/input";
+import { Modal } from "../../components/ui/modal";
+import { toastSuccess } from "../../components/ui/toast";
+
+type Field = "alias" | "hostName" | "user" | "port" | "identityFile";
+type Form = Record<Field, string>;
+
+/** Adding a new host, or configuring one the server read back. */
+export type HostFormMode = { kind: "add" } | { kind: "edit"; host: SshHostResponse };
+
+const EMPTY: Form = { alias: "", hostName: "", user: "", port: "", identityFile: "" };
+
+function initialForm(mode: HostFormMode): Form {
+ if (mode.kind === "add") return EMPTY;
+ const { host } = mode;
+ return {
+ alias: host.alias,
+ hostName: host.hostName,
+ user: host.user ?? "",
+ port: host.port === undefined ? "" : String(host.port),
+ identityFile: host.identityFile ?? "",
+ };
+}
+
+/** One word: no whitespace and no `#`, which would comment out the rest of the config line. */
+const isToken = (value: string) => value !== "" && !/[\s#]/.test(value);
+
+/** The first thing wrong with the form, per field, or nothing. */
+export function validateHostForm(form: Form): Partial<Record<Field, string>> {
+ const m = S.machines.host;
+ const errors: Partial<Record<Field, string>> = {};
+ if (form.alias.trim() === "") errors.alias = S.common.requiredField;
+ else if (!isToken(form.alias.trim()) || /[*?!]/.test(form.alias)) errors.alias = m.oneWord;
+ if (form.hostName.trim() === "") errors.hostName = S.common.requiredField;
+ else if (!isToken(form.hostName.trim())) errors.hostName = m.oneWord;
+ if (form.user.trim() !== "" && !isToken(form.user.trim())) errors.user = m.oneWord;
+ if (form.port.trim() !== "") {
+ const port = Number(form.port);
+ if (!Number.isInteger(port) || port < 1 || port > 65535) errors.port = m.portRange;
+ }
+ if (form.identityFile.trim() !== "" && !isToken(form.identityFile.trim())) {
+ errors.identityFile = m.oneWord;
+ }
+ return errors;
+}
+
+/** The request the server takes, from a form that passed validation. */
+export function hostRequest(form: Form): SshHostRequest {
+ const request: SshHostRequest = { alias: form.alias.trim(), hostName: form.hostName.trim() };
+ if (form.user.trim() !== "") request.user = form.user.trim();
+ if (form.port.trim() !== "") request.port = Number(form.port);
+ if (form.identityFile.trim() !== "") request.identityFile = form.identityFile.trim();
+ return request;
+}
+
+/**
+ * Mount with a `key` that changes with the mode (the alias being configured, or "add"), so
+ * the form starts from the right values each time it opens; it keeps no state across modes.
+ */
+export function SshHostDialog({
+ mode,
+ projectId,
+ onClose,
+ onSaved,
+}: {
+ mode: HostFormMode;
+ projectId: string;
+ onClose: () => void;
+ /** The machines list as the server answered it after the write. */
+ onSaved: (state: MachinesResponse) => void;
+}) {
+ const m = S.machines.host;
+ const editing = mode.kind === "edit";
+ const locked = mode.kind === "edit" && !mode.host.editable;
+ const [form, setForm] = useState<Form>(() => initialForm(mode));
+ const [errors, setErrors] = useState<Partial<Record<Field, string>>>({});
+ const [busy, setBusy] = useState(false);
+
+ const set = (field: Field) => (event: ChangeEvent<HTMLInputElement>) => {
+ setForm((prev) => ({ ...prev, [field]: event.target.value }));
+ setErrors((prev) => (prev[field] === undefined ? prev : { ...prev, [field]: undefined }));
+ };
+
+ const submit = async () => {
+ if (locked) return;
+ const found = validateHostForm(form);
+ if (Object.values(found).some((error) => error !== undefined)) {
+ setErrors(found);
+ return;
+ }
+ setBusy(true);
+ try {
+ const request = hostRequest(form);
+ if (mode.kind === "edit") {
+ const { alias, ...rest } = request;
+ const state = await api.updateSshHost(projectId, alias, rest);
+ toastSuccess(m.saved(alias));
+ onSaved(state);
+ } else {
+ const state = await api.addSshHost(projectId, request);
+ toastSuccess(m.added(request.alias));
+ onSaved(state);
+ }
+ onClose();
+ } catch (err) {
+ // A refused alias lands under its field; anything else under the form's first field.
+ const text = apiErrorText(err);
+ setErrors(
+ text.includes("already") || text.includes("已") ? { alias: m.exists } : { alias: text },
+ );
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const onEnter = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Enter" && !busy) void submit();
+ };
+
+ return (
+ <Modal
+ open
+ title={editing ? m.editTitle : m.addTitle}
+ onClose={onClose}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy || locked}
+ onClick={() => void submit()}
+ >
+ {busy ? S.common.saving : editing ? S.common.save : m.add}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {locked && (
+ <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}>
+ {m.foreign}
+ </div>
+ )}
+ <Input
+ size="sm"
+ label={m.alias}
+ required
+ hint={editing ? undefined : m.aliasHint}
+ error={errors.alias}
+ value={form.alias}
+ onChange={set("alias")}
+ onKeyDown={onEnter}
+ className="font-mono"
+ placeholder="build-box"
+ autoComplete="off"
+ autoFocus={!editing}
+ disabled={editing}
+ />
+ <Input
+ size="sm"
+ label={m.hostName}
+ required
+ hint={m.hostNameHint}
+ error={errors.hostName}
+ value={form.hostName}
+ onChange={set("hostName")}
+ onKeyDown={onEnter}
+ className="font-mono"
+ placeholder="192.168.1.20"
+ autoComplete="off"
+ autoFocus={editing}
+ disabled={locked}
+ />
+ <div className="grid grid-cols-[1fr_7rem] gap-3">
+ <Input
+ size="sm"
+ label={m.user}
+ hint={m.userHint}
+ error={errors.user}
+ value={form.user}
+ onChange={set("user")}
+ onKeyDown={onEnter}
+ className="font-mono"
+ placeholder="deploy"
+ autoComplete="off"
+ disabled={locked}
+ />
+ <Input
+ size="sm"
+ label={m.port}
+ hint={m.portHint}
+ error={errors.port}
+ value={form.port}
+ onChange={set("port")}
+ onKeyDown={onEnter}
+ className="font-mono"
+ placeholder="22"
+ inputMode="numeric"
+ autoComplete="off"
+ disabled={locked}
+ />
+ </div>
+ <Input
+ size="sm"
+ label={m.identityFile}
+ hint={m.identityFileHint}
+ error={errors.identityFile}
+ value={form.identityFile}
+ onChange={set("identityFile")}
+ onKeyDown={onEnter}
+ className="font-mono"
+ placeholder="~/.ssh/id_ed25519"
+ autoComplete="off"
+ disabled={locked}
+ />
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/lib/server-context.ts b/packages/web/src/lib/server-context.ts
new file mode 100644
index 00000000..fa13066a
--- /dev/null
+++ b/packages/web/src/lib/server-context.ts
@@ -0,0 +1,26 @@
+/**
+ * Addressing another machine's API from this window, per call.
+ *
+ * The window is always on the local server and the frontend is always served locally. A call
+ * that names a machine is rewritten to `/server/<machineId>/api/…`, which the local server
+ * forwards through that machine's tunnel (see the server's machines/proxy.ts). Browsing a
+ * remote machine's directories to pick a workspace on it is what this exists for.
+ *
+ * There is deliberately NO window-wide "active server" mode. One existed and was removed:
+ * pointing an entire window at another machine put every page behind a tunnel, including
+ * `/api/me` — so a tunnel that dropped left the app unable to answer whether anyone was
+ * logged in, and the control for getting back was rendered inside the layout that never
+ * mounted. An escape hatch behind the thing that breaks is not an escape hatch. Naming the
+ * machine on the calls that actually concern it has no such failure: a dead tunnel breaks
+ * exactly the request that needed it, and says so.
+ */
+
+/**
+ * Where an API path goes: re-rooted onto `machineId`, or as-is for the local server. A pure
+ * string mapping, used by the fetch wrapper and the SSE subscriptions so one rule covers
+ * every call.
+ */
+export function apiUrl(path: string, machineId: string | null = null): string {
+ if (machineId === null || !path.startsWith("/api")) return path;
+ return `/server/${encodeURIComponent(machineId)}${path}`;
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 8b0fd906..461f4fb1 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -45,33 +45,97 @@ export const en: Strings = {
/** Machines page: the server's own ssh hosts, and installing this build on one. */
machines: {
pageTitle: "Machines",
- pageDesc:
- "The hosts declared in this server's own ~/.ssh/config. Pick one to install this build of PenguinHarness on it: the machine is probed, a matching Node runtime rides along only if it needs one, and the image is copied over and installed there. The config is read, never written, and the install uses the server account's own ssh keys.",
- /** Version line under the title; `version` is what would be pushed. */
- imageVersion: (version: string) => `Installs version ${version}`,
+ imageVersion: (version: string) => `This server: ${version}`,
noImage:
"This server has no install image to push. A packaged or tarball install carries one; a source checkout gets one from its first hot push.",
- empty: "No hosts in ~/.ssh/config.",
- /** The picker: an ssh config can declare hundreds of hosts, so the panel is a fuzzy search over aliases. */
- pick: "Choose a machine\u2026",
- search: "Search hosts\u2026",
- noMatch: "No host matches that.",
- /** How many matches the visible rows leave out — a silent truncation would read as "not in my config". */
- more: (count: number) => `${count} more \u2014 keep typing to narrow it down.`,
- /** Heading of the standing list of machines this server has installed on. */
- installedTitle: (count: number) => `Installed machines (${count})`,
- /** What the selected machine already carries, remembered on the server across restarts. */
- installedAt: (version: string, when: string) => `${version} installed here on ${when}.`,
- install: "Install",
- installing: "Installing\u2026",
- reinstall: "Reinstall",
- /** Terminal states of a finished job. */
- installed: (version: string) => `Installed ${version}.`,
- alreadyInstalled: (version: string) => `Already on ${version} \u2014 nothing to install.`,
- failedAt: (step: string) => `The install failed while trying to ${step}.`,
- /** The progress log's own heading, so the block is not an unlabelled wall of text. */
- output: "Install output",
- adminOnly: "Only an admin can install on a machine.",
+ empty: "No host in ~/.ssh/config left to add.",
+ search: "Search hosts…",
+ noMatch: "No host matches.",
+ localTitle: "this server",
+ noneInUse: "No machine in use yet.",
+ sshHint:
+ "A machine can be added when this server's account can ssh into it by key (`ssh <alias>` works in a terminal here). Whoever set up ssh can put it in ~/.ssh/config.",
+ now: "now",
+ allHosts: (count: number) => `${count} more in ~/.ssh/config`,
+ expand: "Expand",
+ fewer: "Collapse",
+ host: {
+ addTitle: "New ssh host",
+ newVerb: "New",
+ configureVerb: "Configure",
+ add: "Write to ssh config",
+ alias: "Alias (Host)",
+ aliasHint: "One word; `ssh <alias>` and this page will call the machine by it.",
+ hostName: "Address (HostName)",
+ hostNameHint: "An IP or a domain name.",
+ user: "User",
+ userHint: "Empty means this server account's own user name.",
+ port: "Port",
+ portHint: "Empty means 22.",
+ identityFile: "Key file (IdentityFile)",
+ identityFileHint: "Empty means ssh's default key.",
+ oneWord: "Must be one word: no space, no #.",
+ portRange: "A whole number from 1 to 65535.",
+ exists: "The ssh config already has this alias.",
+ added: (alias: string) => `Wrote ${alias}. Enable it from Add machines….`,
+ configure: "Configure ssh host",
+ editTitle: "Configure ssh host",
+ saved: (alias: string) => `Updated ${alias} in the ssh config.`,
+ foreign:
+ "This block was not written by PenguinHarness and may carry options this form does not know; edit it in ~/.ssh/config.",
+ },
+ add: "Add machines…",
+ addSelected: (count: number) => `Enable these ${count}`,
+ use: "Enable",
+ stopUsing: "Disable",
+ updateAll: (count: number) => `Update all (${count})`,
+ selectedCount: (count: number) => `${count} selected`,
+ pickAll: "all",
+ pickNone: "none",
+ state: {
+ serving: "Serving",
+ queued: "Queued",
+ working: "Working",
+ ready: "Connected",
+ failed: "Failed",
+ installedOnly: "Installed",
+ behind: "Behind",
+ notConnected: "Offline",
+ unreachable: "Unreachable",
+ stopped: "Stopped",
+ linkedStopped: "Connected, not serving",
+ unknown: "Unchecked",
+ },
+ phase: {
+ check: "Checking the machine…",
+ install: "Installing the program…",
+ handover: "Handing over the build…",
+ restart: "Restarting its server…",
+ connect: "Connecting…",
+ sync: "Handing over the Model config…",
+ },
+ stepOf: (step: number, total: number) => `step ${step} of ${total}`,
+ queued: "Waiting its turn behind the machines before it.",
+ working: "Working…",
+ failedAt: (step: string) => `Failed at "${step}".`,
+ replaceProgram: "Force install",
+ replaceProgramWhy:
+ "Whatever is on that machine now, put this build's program there and restart its server — anyone using it will be interrupted.",
+ refusedSelf: (alias: string) => `${alias} is the machine this server runs on; nothing to add.`,
+ refusedUnknown: (alias: string) => `${alias} is not in this server's ssh config.`,
+ details: "Details",
+ detailInstalled: "Installed",
+ detailSince: "Since",
+ detailVersion: "Version",
+ detailStarted: "Started",
+ detailServer: "Server",
+ detailChecked: "Checked",
+ detailMachineId: "Machine id",
+ detailRoot: "Server root",
+ serverUpOn: (port: number) => `up on port ${port}`,
+ output: "Output",
+ agentsUnreachable: "That machine is not connected — use it from the Machines page",
+ adminOnly: "Only an admin can manage machines.",
},
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
@@ -1970,6 +2034,13 @@ export const en: Strings = {
`Context compacted; thinking level switched to "${to}".`,
thinkingSwitchCompactFailed:
"The compaction did not finish; the thinking level was switched anyway.",
+ /** The machine a workspace lives on; the row only shows when more than one is reachable. */
+ workspaceMachine: "Machine",
+ workspaceHere: "here",
+ /** Why a listed machine cannot be picked — shown ON its row, where the question is asked. */
+ workspaceMachineWhy: {
+ "no-identity": "not identified",
+ },
workspaceUseThis: "Use this dir",
workspaceUp: "Parent dir",
workspaceNoSubdirs: "No subdirectories",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index e9243007..7a2ab7ae 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -50,33 +50,114 @@ export const zh = {
/** Machines page: the server's own ssh hosts, and installing this build on one. */
machines: {
pageTitle: "机器",
- pageDesc:
- "本服务端 ~/.ssh/config 里声明的主机。选一台即可把当前这套 PenguinHarness 装上去:探测对端、按需带上匹配的 Node 运行时、复制镜像并在对端完成安装。配置文件只读不写,安装使用服务端账户自己的 ssh 密钥。",
- /** Version line under the title; `version` is what would be pushed. */
- imageVersion: (version: string) => `将安装的版本:${version}`,
+ /** Tooltip on the version in the header: what this server would install. */
+ imageVersion: (version: string) => `本服务端版本:${version}`,
noImage:
"本服务端没有可推送的安装镜像。打包安装或 tarball 安装自带镜像;源码检出则在第一次热推后获得。",
- empty: "~/.ssh/config 中没有可用的主机。",
+ empty: "~/.ssh/config 中没有可添加的主机。",
/** The picker: an ssh config can declare hundreds of hosts, so the panel is a fuzzy search over aliases. */
- pick: "选择机器…",
search: "搜索主机…",
noMatch: "没有匹配的主机。",
- /** How many matches the visible rows leave out — a silent truncation would read as "not in my config". */
- more: (count: number) => `另有 ${count} 台未显示——继续输入以缩小范围。`,
- /** Heading of the standing list of machines this server has installed on. */
- installedTitle: (count: number) => `已安装的机器(${count})`,
- /** What the selected machine already carries, remembered on the server across restarts. */
- installedAt: (version: string, when: string) => `已安装 ${version}(${when})。`,
- install: "安装",
- installing: "安装中…",
- reinstall: "重新安装",
- /** Terminal states of a finished job. */
- installed: (version: string) => `已安装 ${version}。`,
- alreadyInstalled: (version: string) => `已经是 ${version},无需安装。`,
- failedAt: (step: string) => `安装失败(${step})。`,
+ /** The tag on this server's own row. */
+ localTitle: "本服务端",
+ noneInUse: "还没有在用的机器。",
+ sshHint:
+ "能加的机器,是本服务端账户用密钥就能 ssh 上去的主机(在这里的终端里 `ssh <别名>` 能直接进)。请配置 ssh 的人把它写进 ~/.ssh/config。",
+ now: "刚刚",
+ /** The chevron row at the foot of the picker's list: the matches it has not shown yet. */
+ allHosts: (count: number) => `ssh 配置中另有 ${count} 台`,
+ expand: "展开",
+ fewer: "收起",
+ /** The form that appends a host block to this server's ~/.ssh/config. */
+ host: {
+ addTitle: "新建 ssh 主机",
+ /** The one-word verbs on the buttons; the titles above say what they do in full. */
+ newVerb: "新建",
+ configureVerb: "配置",
+ add: "写入 ssh 配置",
+ alias: "别名(Host)",
+ aliasHint: "一个词,之后 `ssh <别名>` 和这里都用它称呼这台机器。",
+ hostName: "地址(HostName)",
+ hostNameHint: "IP 或域名。",
+ user: "用户(User)",
+ userHint: "留空则用本服务端账户的用户名。",
+ port: "端口(Port)",
+ portHint: "留空为 22。",
+ identityFile: "密钥文件(IdentityFile)",
+ identityFileHint: "留空则用 ssh 的默认密钥。",
+ oneWord: "必须是一个词:不能有空格或 #。",
+ portRange: "1 到 65535 之间的整数。",
+ exists: "ssh 配置里已有这个别名。",
+ added: (alias: string) => `已写入 ${alias}。现在可以从「添加机器…」里启用它。`,
+ /** Configuring a host this app wrote: the same form, the alias fixed. */
+ configure: "配置 ssh 主机",
+ editTitle: "配置 ssh 主机",
+ saved: (alias: string) => `已更新 ${alias} 的 ssh 配置。`,
+ foreign:
+ "这一段不是由 PenguinHarness 写入的,可能带有这里不认识的选项;请直接编辑 ~/.ssh/config。",
+ },
+ /** The verbs. */
+ add: "添加机器…",
+ addSelected: (count: number) => `启用这 ${count} 台`,
+ use: "启用",
+ stopUsing: "停用",
+ /** One tap brings every machine behind this build forward (and reconnects it). */
+ updateAll: (count: number) => `全部更新(${count})`,
+ /** The floating bar over a selection. */
+ selectedCount: (count: number) => `已选 ${count} 台`,
+ pickAll: "全选",
+ pickNone: "清空",
+ /** The one word in a row's State column, keyed by the row's reading; `serving` is this server's. */
+ state: {
+ serving: "服务中",
+ queued: "排队中",
+ working: "处理中",
+ ready: "已连接",
+ failed: "失败",
+ installedOnly: "已安装",
+ behind: "待更新",
+ notConnected: "未连接",
+ unreachable: "连不上",
+ stopped: "未运行",
+ linkedStopped: "已连接,未在提供服务",
+ unknown: "未检查",
+ },
+ /** The stepper's steps, in pipeline order, as the caption under a working row. */
+ phase: {
+ check: "检查对端…",
+ install: "安装程序…",
+ handover: "交接构建…",
+ restart: "重启服务…",
+ connect: "建立连接…",
+ sync: "下发模型配置…",
+ },
+ stepOf: (step: number, total: number) => `第 ${step}/${total} 步`,
+ queued: "排队中,等前面的机器处理完。",
+ working: "处理中…",
+ failedAt: (step: string) => `失败于「${step}」。`,
+ /** The forced install a failed job may offer. */
+ replaceProgram: "强制安装",
+ replaceProgramWhy:
+ "无论那台机器上现在是什么,都把这个构建的程序装上去并重启它的服务——正在用它的人会被打断。",
+ /** Refusals answered by machine id when a batch is queued. */
+ refusedSelf: (alias: string) => `${alias} 就是本服务端所在的机器,无需添加。`,
+ refusedUnknown: (alias: string) => `${alias} 不在本服务端的 ssh 配置里。`,
+ /** The detail pane. */
+ details: "详情",
+ detailInstalled: "已安装",
+ detailSince: "安装于",
+ /** This server's own card says what build it runs and since when, not what was installed. */
+ detailVersion: "版本",
+ detailStarted: "启动于",
+ detailServer: "对端服务",
+ detailChecked: "上次检查",
+ detailMachineId: "机器 ID",
+ detailRoot: "服务端根目录",
+ serverUpOn: (port: number) => `运行中,端口 ${port}`,
/** The progress log's own heading, so the block is not an unlabelled wall of text. */
- output: "安装输出",
- adminOnly: "只有管理员可以安装到机器上。",
+ output: "输出",
+ agentsUnreachable: "那台机器尚未连接——请在「机器」页面使用它",
+ adminOnly: "只有管理员可以管理机器。",
},
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
@@ -1959,6 +2040,13 @@ export const zh = {
thinkingSwitchApplied: (to: string): string => `上下文已压缩,思考等级已切换为「${to}」。`,
/** Compaction ended without completing — the switch still applies, so say both. */
thinkingSwitchCompactFailed: "压缩未成功完成,思考等级已照常切换。",
+ /** The machine a workspace lives on; the row only shows when more than one is reachable. */
+ workspaceMachine: "机器",
+ workspaceHere: "本机",
+ /** Why a listed machine cannot be picked — shown ON its row, where the question is asked. */
+ workspaceMachineWhy: {
+ "no-identity": "待识别",
+ },
workspaceUseThis: "使用此目录",
workspaceUp: "上级目录",
workspaceNoSubdirs: "无子目录",
diff --git a/packages/web/src/lib/tone.ts b/packages/web/src/lib/tone.ts
index 7516649c..e3d9cb49 100644
--- a/packages/web/src/lib/tone.ts
+++ b/packages/web/src/lib/tone.ts
@@ -11,7 +11,8 @@
* | ----------- | ----------------------------------------------------------- |
* | `busy` | executing right now |
* | `attention` | unfinished — waiting on time, on a queue, or on the user |
- * | `success` | finished well, connected, healthy |
+ * | `success` | finished well, healthy |
+ * | `link` | a live connection held right now — in contact, not a verdict |
* | `danger` | failed, destructive, over a limit |
* | `muted` | settled; the mark should recede |
*
@@ -29,12 +30,13 @@
*/
const INK = {
emerald: "text-emerald-600 dark:text-emerald-400",
+ blue: "text-blue-600 dark:text-blue-400",
amber: "text-amber-600 dark:text-amber-400",
red: "text-red-600 dark:text-red-400",
gray: "text-gray-400 dark:text-gray-500",
} as const;
-export type Tone = "busy" | "attention" | "success" | "danger" | "muted";
+export type Tone = "busy" | "attention" | "success" | "link" | "danger" | "muted";
/**
* Ink for a glyph or a line of status text. Measured as WCAG 2.x contrast ratios against the
@@ -44,11 +46,12 @@ export type Tone = "busy" | "attention" | "success" | "danger" | "muted";
* in both themes:
*
* - `busy` / `success` emerald-600 / emerald-400 …… 3.65–3.50 : 1 light, 10.83–10.03 : 1 dark
+ * - `link` blue-600 / blue-400 …………… 5.17–4.95 : 1 light, 8.26–7.69 : 1 dark
* - `attention` amber-600 / amber-400 ……… 3.20–3.06 : 1 light, 12.19–11.28 : 1 dark
* - `danger` red-600 / red-400 …………… 4.77–4.56 : 1 light, 7.27–6.73 : 1 dark
* - `muted` gray-400 / gray-500 ……… 2.60–2.49 : 1 light, 4.34–4.02 : 1 dark
*
- * The first three clear the 3:1 that WCAG 1.4.11 asks of a graphical object in both themes.
+ * The first four clear the 3:1 that WCAG 1.4.11 asks of a graphical object in both themes.
* `muted` does not, and is the one tone that may only mark a state already spelled out in
* adjacent text or in the mark's own accessible name — receding is its entire job.
*/
@@ -56,12 +59,14 @@ export const toneInk: Record<Tone, string> = {
busy: INK.emerald,
attention: INK.amber,
success: INK.emerald,
+ link: INK.blue,
danger: INK.red,
muted: INK.gray,
};
const SURFACE = {
emerald: "bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",
+ blue: "bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",
amber: "bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
red: "bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300",
gray: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300",
@@ -72,6 +77,7 @@ export const toneSurface: Record<Tone, string> = {
busy: SURFACE.emerald,
attention: SURFACE.amber,
success: SURFACE.emerald,
+ link: SURFACE.blue,
danger: SURFACE.red,
muted: SURFACE.gray,
};
@@ -86,6 +92,7 @@ export const toneDot: Record<Tone, string> = {
busy: "bg-emerald-500",
attention: "bg-amber-500",
success: "bg-emerald-500",
+ link: "bg-blue-500",
danger: "bg-red-500",
muted: "bg-gray-400 dark:bg-gray-600",
};
@@ -101,6 +108,7 @@ export const toneStrip: Record<Tone, string> = {
"border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-300",
success:
"border-emerald-300 bg-emerald-50 text-emerald-800 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300",
+ link: "border-blue-300 bg-blue-50 text-blue-800 dark:border-blue-700 dark:bg-blue-950/40 dark:text-blue-300",
danger:
"border-red-300 bg-red-50 text-red-800 dark:border-red-700 dark:bg-red-950/40 dark:text-red-300",
muted:
diff --git a/packages/web/src/lib/workspace-machines.ts b/packages/web/src/lib/workspace-machines.ts
new file mode 100644
index 00000000..0c8299a6
--- /dev/null
+++ b/packages/web/src/lib/workspace-machines.ts
@@ -0,0 +1,90 @@
+/**
+ * Which machines a workspace can be picked on, and how each is labelled.
+ *
+ * A workspace is a directory ON a machine. Only one whose filesystem is reachable right now
+ * can be browsed: this one always, and any other with a live tunnel. Every installed machine
+ * is LISTED regardless, the unreachable ones disabled with their reason at the row — a list
+ * that silently omits its answer is indistinguishable from a broken feature. Identified by
+ * machine id and labelled by ssh alias.
+ */
+import type { MachineInfo, MachinesResponse } from "@prismshadow/penguin-server/api";
+
+/** One machine a workspace can live on, and whether it can be browsed right now. */
+export interface WorkspaceMachine {
+ /** The machine's own id; null means the local server (which needs no proxy prefix). */
+ id: string | null;
+ /** The ssh alias, or this host's name for the local entry. */
+ label: string;
+ /** True for the machine serving this page. */
+ local: boolean;
+ /** False when its filesystem cannot be reached; `reason` says what is missing. */
+ selectable: boolean;
+ /** Why it cannot be browsed, for the row to render. Absent when it can. */
+ reason?: "no-identity";
+}
+
+/**
+ * Every machine, local first: the ones that can be browsed, and the installed ones that
+ * cannot, each with its reason.
+ *
+ * Hosts nothing was ever installed on are the one thing left out — they are not part of
+ * this feature yet, and listing 45 ssh entries as 45 failures would bury the two that
+ * matter. Being installed is what makes a machine a candidate; everything from there on
+ * says why it is or is not usable.
+ */
+export function workspaceMachines(state: MachinesResponse | null): WorkspaceMachine[] {
+ if (state === null) return [];
+ const out: WorkspaceMachine[] = [];
+ for (const machine of state.machines) {
+ if (machine.local) {
+ out.push({ id: null, label: machine.alias, local: true, selectable: true });
+ continue;
+ }
+ if (machine.installed === null) continue;
+ if (machine.machineId === null) {
+ // Installed, but nothing has minted an identity there yet — a workspace stored
+ // against it could never be matched back, so it cannot be chosen.
+ out.push({
+ id: null,
+ label: machine.alias,
+ local: false,
+ selectable: false,
+ reason: "no-identity",
+ });
+ continue;
+ }
+ // A tunnel is NOT required: this server browses that machine's directories over ssh
+ // (see the machines service's listDirs). The tunnel is for reaching that machine's own
+ // API, which picking a workspace does not do — requiring one here made a connect a
+ // prerequisite for reading a directory listing, which it never was.
+ out.push({ id: machine.machineId, label: machine.alias, local: false, selectable: true });
+ }
+ return out;
+}
+
+/**
+ * The label for a chosen machine id. Falls back to the id itself: a workspace may have been
+ * registered on a machine that has since disconnected or dropped out of the ssh config, and
+ * showing the raw id is honest where inventing a name would not be.
+ */
+export function machineLabel(machines: WorkspaceMachine[], id: string | null): string | null {
+ const found = machines.find((machine) => machine.id === id);
+ if (found !== undefined) return found.label;
+ return id;
+}
+
+/** True when a workspace lives on some machine other than this one. */
+export function isElsewhere(workspaceMachineId: string | null | undefined): boolean {
+ return (workspaceMachineId ?? null) !== null;
+}
+
+/** The machine a directory picked on `machine` should be recorded against. */
+export function recordedMachineId(machine: WorkspaceMachine | undefined): string | undefined {
+ // Absent rather than null for the local machine: an entry with no machine is one picked
+ // where the app was, which is every entry that existed before machines did.
+ return machine === undefined || machine.local ? undefined : (machine.id ?? undefined);
+}
+
+/** Reads the machine off a machine list entry, for callers holding a raw MachineInfo. */
+export const machineIdOf = (machine: MachineInfo): string | null =>
+ machine.local ? null : machine.machineId;
diff --git a/packages/web/src/lib/workspace-registry.ts b/packages/web/src/lib/workspace-registry.ts
index 58e6a9ff..7f27a9b5 100644
--- a/packages/web/src/lib/workspace-registry.ts
+++ b/packages/web/src/lib/workspace-registry.ts
@@ -25,6 +25,15 @@ export interface WorkspaceEntry {
path: string;
/** Display name overriding the path basename (set via 重命名工作区; absent = basename). */
alias?: string;
+ /**
+ * The machine this directory is ON, by its own id. Absent means the local machine —
+ * which is also every entry registered before workspaces could name one, so absence has
+ * to keep meaning "here" rather than "unknown".
+ *
+ * A path is only meaningful together with its machine: `/srv/app` on two machines is two
+ * different directories, so the pair is the identity and `path` alone is not.
+ */
+ machineId?: string;
}
/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */
@@ -68,7 +77,13 @@ function parseEntry(x: unknown): WorkspaceEntry | null {
if (p === "") return null;
const rawAlias = (x as { alias?: unknown }).alias;
const alias = typeof rawAlias === "string" ? rawAlias.trim() : "";
- return alias === "" ? { path: p } : { path: p, alias };
+ const rawMachine = (x as { machineId?: unknown }).machineId;
+ const machineId = typeof rawMachine === "string" && rawMachine !== "" ? rawMachine : undefined;
+ return {
+ path: p,
+ ...(alias === "" ? {} : { alias }),
+ ...(machineId === undefined ? {} : { machineId }),
+ };
}
return null;
}
@@ -123,10 +138,16 @@ export function saveWorkspaceRegistry(
export function registerWorkspace(
entries: readonly WorkspaceEntry[],
path: string,
+ machineId?: string,
): readonly WorkspaceEntry[] {
const p = normalizeWorkspacePath(path);
- if (p === "" || isTempWorkspace(p) || entries.some((e) => e.path === p)) return entries;
- return [{ path: p }, ...entries];
+ if (p === "" || isTempWorkspace(p)) return entries;
+ // Deduped on the PAIR: the same path on two machines is two different directories, and
+ // collapsing them would hide one behind the other with no way to tell which.
+ if (entries.some((e) => e.path === p && (e.machineId ?? null) === (machineId ?? null))) {
+ return entries;
+ }
+ return [{ path: p, ...(machineId === undefined ? {} : { machineId }) }, ...entries];
}
/**
diff --git a/packages/web/test/machines-probe-schedule.test.ts b/packages/web/test/machines-probe-schedule.test.ts
new file mode 100644
index 00000000..ac01fae7
--- /dev/null
+++ b/packages/web/test/machines-probe-schedule.test.ts
@@ -0,0 +1,81 @@
+/**
+ * The Machines page's re-probe schedule: how far apart the ssh round trips get when nothing
+ * is changing, and what counts as a change worth resetting for.
+ *
+ * The fingerprint deliberately excludes `checkedAt`. Every probe moves that timestamp, so
+ * including it would make every round look like a change and pin the interval at its
+ * shortest step forever — an ssh child per machine every 15 seconds, indefinitely.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ PROBE_STEPS_MS,
+ probeDelayMs,
+ probeFingerprint,
+} from "../src/features/machines/probe-schedule";
+
+const machine = (
+ id: string,
+ state: string | null,
+ extra: { port?: number; version?: string; checkedAt?: string } = {},
+) => ({
+ id,
+ installed: { version: extra.version ?? "9.9.9" },
+ status:
+ state === null ? null : { state, ...(extra.port === undefined ? {} : { port: extra.port }) },
+});
+
+describe("probeDelayMs", () => {
+ it("starts at 15s and widens through a minute to a ten-minute ceiling", () => {
+ expect(probeDelayMs(0)).toBe(15_000);
+ expect(probeDelayMs(1)).toBe(30_000);
+ expect(probeDelayMs(2)).toBe(45_000);
+ expect(probeDelayMs(3)).toBe(60_000);
+ expect(probeDelayMs(4)).toBe(120_000);
+ expect(probeDelayMs(PROBE_STEPS_MS.length - 1)).toBe(600_000);
+ });
+
+ it("never exceeds ten minutes, however long everything has been quiet", () => {
+ for (const rounds of [20, 100, 10_000]) expect(probeDelayMs(rounds)).toBe(600_000);
+ });
+
+ it("is monotonic — a longer quiet spell never probes sooner", () => {
+ const delays = PROBE_STEPS_MS.map((_, i) => probeDelayMs(i));
+ expect([...delays].sort((a, b) => a - b)).toEqual(delays);
+ });
+
+ it("treats a nonsensical round count as the first step rather than throwing", () => {
+ expect(probeDelayMs(-1)).toBe(15_000);
+ });
+});
+
+describe("probeFingerprint", () => {
+ it("ignores checkedAt, so an unchanged round really reads as unchanged", () => {
+ const before = probeFingerprint([machine("ssh:a", "running", { port: 7364 })]);
+ const after = probeFingerprint([machine("ssh:a", "running", { port: 7364 })]);
+ expect(after).toBe(before);
+ });
+
+ it("changes when a server goes down, comes up, or moves port", () => {
+ const running = probeFingerprint([machine("ssh:a", "running", { port: 7364 })]);
+ expect(probeFingerprint([machine("ssh:a", "stopped")])).not.toBe(running);
+ expect(probeFingerprint([machine("ssh:a", "unreachable")])).not.toBe(running);
+ expect(probeFingerprint([machine("ssh:a", "running", { port: 7365 })])).not.toBe(running);
+ });
+
+ it("changes when a machine is installed, reinstalled at a new version, or appears", () => {
+ const one = probeFingerprint([machine("ssh:a", "running", { port: 7364 })]);
+ expect(
+ probeFingerprint([machine("ssh:a", "running", { port: 7364, version: "10.0.0" })]),
+ ).not.toBe(one);
+ expect(
+ probeFingerprint([machine("ssh:a", "running", { port: 7364 }), machine("ssh:b", "stopped")]),
+ ).not.toBe(one);
+ });
+
+ it("distinguishes 'not probed yet' from every real state", () => {
+ const unprobed = probeFingerprint([machine("ssh:a", null)]);
+ for (const state of ["running", "stopped", "unreachable"]) {
+ expect(probeFingerprint([machine("ssh:a", state)])).not.toBe(unprobed);
+ }
+ });
+});
diff --git a/packages/web/test/machines-view.test.ts b/packages/web/test/machines-view.test.ts
index df424bdb..ff724230 100644
--- a/packages/web/test/machines-view.test.ts
+++ b/packages/web/test/machines-view.test.ts
@@ -1,235 +1,288 @@
/**
- * machines-view unit tests: what the Machines page's install control offers, given the
- * server's single install job and whatever is selected in the picker.
+ * machines-view unit tests: the one reading a Machines card gives, and the machines in use.
*
- * Two cases worth pinning. The server runs one job at a time, so selecting a second host
- * while the first installs must refuse — without pretending the selection is the thing
- * installing. And "already installed" comes from the machine's own persisted record, never
- * from the job: reading it off the one job slot is what used to make an installed machine
- * stop looking installed as soon as anything else was installed.
+ * The reading's precedence is the point. The server's job for a machine is the freshest
+ * word; a held connection settles "ready" over an older failed job, since a re-hold that
+ * brought the machine back must not leave the row saying it failed; and "in use" comes from
+ * the machine's own persisted record, never from the job slot.
*/
import { describe, expect, it } from "vitest";
import type { MachineInfo, MachineJob, MachinesResponse } from "@prismshadow/penguin-server/api";
import {
- installButtonState,
+ anyJobPending,
+ behindMachines,
installedMachines,
- verdictOf,
+ jobFor,
+ localMachine,
+ outOfDate,
+ readMachine,
+ readingTone,
+ wantsUse,
} from "../src/features/machines/machines-view";
const INSTALLED = { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" };
-/** A remote row as the list answers it: no probe taken, no id heard yet. */
-const remote = (alias: string, installed: MachineInfo["installed"]): MachineInfo => ({
+const fresh = (alias: string): MachineInfo => ({
id: `ssh:${alias}`,
alias,
machineId: null,
- installed,
+ installed: null,
local: false,
connection: null,
api: null,
+ root: "$HOME/.penguin/data",
status: null,
});
-
-const fresh = (alias: string): MachineInfo => remote(alias, null);
-const carrying = (alias: string): MachineInfo => remote(alias, INSTALLED);
+const carrying = (alias: string): MachineInfo => ({ ...fresh(alias), installed: INSTALLED });
+/** The entry the server puts first: this very machine. */
+const here = (): MachineInfo => ({
+ id: "local",
+ alias: "workstation",
+ machineId: "LNrJdHAZJ91G58i0",
+ installed: INSTALLED,
+ local: true,
+ connection: null,
+ api: null,
+ root: "/home/someone/.penguin/data",
+ status: { state: "running", checkedAt: INSTALLED.at, port: 7364 },
+});
function response(
- job: MachineJob | null,
+ jobs: MachineJob[],
opts: { imageVersion?: string | null; machines?: MachineInfo[] } = {},
): MachinesResponse {
return {
machines: opts.machines ?? [fresh("build-box"), fresh("nas")],
imageVersion: opts.imageVersion === undefined ? "9.9.9" : opts.imageVersion,
- job,
+ job: jobs.find((job) => job.running) ?? jobs.at(-1) ?? null,
+ jobs,
};
}
function job(over: Partial<MachineJob> = {}): MachineJob {
return {
- kind: "install",
+ kind: "use",
machineId: "ssh:nas",
alias: "nas",
+ queued: false,
running: true,
+ phase: null,
log: ["Installing 9.9.9 on deploy@nas…"],
result: null,
...over,
};
}
-const done = job({
+const failed = job({
running: false,
- result: { ok: true, installed: "installed", version: "9.9.9" },
+ result: { ok: false, step: "connect", message: "Permission denied.", canReplaceProgram: true },
});
-describe("verdictOf", () => {
- it("is null while the job runs", () => {
- expect(verdictOf(job())).toBeNull();
+describe("readMachine", () => {
+ it("a queued job reads as waiting, before anything the machine's own record says", () => {
+ const nas = { ...carrying("nas"), connection: { pid: 1 } };
+ expect(readMachine(nas, job({ queued: true, running: false }), "9.9.9")).toEqual({
+ kind: "queued",
+ });
});
- it("carries the version on both kinds of success", () => {
- expect(verdictOf(done)).toEqual({ kind: "installed", version: "9.9.9" });
- expect(
- verdictOf(
- job({
- running: false,
- result: { ok: true, installed: "already-installed", version: "9.9.9" },
- }),
- ),
- ).toEqual({ kind: "already-installed", version: "9.9.9" });
+ it("a running job reads as working, with its latest line", () => {
+ expect(readMachine(carrying("nas"), job(), "9.9.9")).toEqual({
+ kind: "working",
+ step: "Installing 9.9.9 on deploy@nas…",
+ });
+ expect(readMachine(carrying("nas"), job({ log: [] }), "9.9.9")).toEqual({
+ kind: "working",
+ step: null,
+ });
});
- it("keeps the failing step and the far side's own message", () => {
- expect(
- verdictOf(
- job({
- running: false,
- result: { ok: false, step: "connect", message: "Permission denied (publickey)." },
- }),
- ),
- ).toEqual({ kind: "failed", step: "connect", message: "Permission denied (publickey)." });
+ it("a held connection is ready, even over an older failed job", () => {
+ const nas: MachineInfo = {
+ ...carrying("nas"),
+ connection: { pid: 1 },
+ status: { state: "running", checkedAt: INSTALLED.at, port: 7364 },
+ };
+ expect(readMachine(nas, failed, "9.9.9")).toEqual({ kind: "ready", port: 7364 });
});
-});
-describe("installButtonState", () => {
- it("nothing selected: the button offers an install it cannot start", () => {
- expect(installButtonState(null, response(null), false)).toEqual({
- action: "install",
- disabled: true,
- });
+ it("a held connection over a stopped server says so, and leaves `use` on offer", () => {
+ // The outage this came from: an ssh session was up while the far server could not bind
+ // its port. The card read "Connected" (the connection won outright), its own details
+ // said the server was stopped, and the one action that would start it again was
+ // withheld because the row looked ready — so the page hid both the fault and the fix.
+ const nas: MachineInfo = {
+ ...carrying("nas"),
+ connection: { pid: 1 },
+ status: { state: "stopped", checkedAt: INSTALLED.at },
+ };
+ const reading = readMachine(nas, null, "9.9.9");
+ expect(reading).toEqual({ kind: "linkedStopped" });
+ expect(readingTone(reading)).toBe("attention");
+ expect(wantsUse(reading)).toBe(true);
});
- it("a never-installed selection with no job running is ready to go", () => {
- expect(installButtonState(fresh("nas"), response(null), false)).toEqual({
- action: "install",
- disabled: false,
+ it("a held connection over an unreachable machine is unreachable, with its words", () => {
+ const nas: MachineInfo = {
+ ...carrying("nas"),
+ connection: { pid: 1 },
+ status: { state: "unreachable", checkedAt: INSTALLED.at, detail: "ssh: connect refused" },
+ };
+ expect(readMachine(nas, null, "9.9.9")).toEqual({
+ kind: "unreachable",
+ detail: "ssh: connect refused",
});
});
- it("the selected machine's own running job reads as installing", () => {
- expect(installButtonState(fresh("nas"), response(job()), false)).toEqual({
- action: "installing",
- disabled: true,
+ it("a failed job keeps the failing step, the far side's words and the forced-install offer", () => {
+ expect(readMachine(carrying("nas"), failed, "9.9.9")).toEqual({
+ kind: "failed",
+ step: "connect",
+ message: "Permission denied.",
+ canReplaceProgram: true,
});
});
- it("picking ANOTHER host mid-install refuses without claiming that host is installing", () => {
- // The job belongs to ssh:nas; the picker moved to ssh:build-box. One job at a time, so
- // the button is disabled — but it must not say "installing" about a host that is not.
- expect(installButtonState(fresh("build-box"), response(job()), false)).toEqual({
- action: "install",
- disabled: true,
- });
- });
-
- it("a POST still in flight reads as installing before the server reports a job", () => {
- expect(installButtonState(fresh("nas"), response(null), true)).toEqual({
- action: "installing",
- disabled: true,
- });
+ it("a machine on another build is behind, whatever its server is doing", () => {
+ const nas: MachineInfo = {
+ ...carrying("nas"),
+ status: { state: "running", checkedAt: INSTALLED.at, port: 7364 },
+ };
+ expect(readMachine(nas, null, "9.9.10")).toEqual({ kind: "behind", version: "9.9.9" });
});
- it("a machine carrying the program offers a reinstall — from its record, not the job", () => {
- // No job at all: this is the page after a restart, which is exactly the case that used
- // to read as "never installed".
- expect(installButtonState(carrying("nas"), response(null), false)).toEqual({
- action: "reinstall",
- disabled: false,
- });
+ it("the last probe speaks when no job and no connection do", () => {
+ const at = INSTALLED.at;
+ expect(readMachine(carrying("nas"), null, "9.9.9")).toEqual({ kind: "unknown" });
+ expect(
+ readMachine(
+ {
+ ...carrying("nas"),
+ status: { state: "unreachable", checkedAt: at, detail: "timed out" },
+ },
+ null,
+ "9.9.9",
+ ),
+ ).toEqual({ kind: "unreachable", detail: "timed out" });
+ expect(
+ readMachine(
+ { ...carrying("nas"), status: { state: "stopped", checkedAt: at } },
+ null,
+ "9.9.9",
+ ),
+ ).toEqual({ kind: "stopped" });
+ expect(
+ readMachine(
+ { ...carrying("nas"), status: { state: "running", checkedAt: at, port: 7364 } },
+ null,
+ "9.9.9",
+ ),
+ ).toEqual({ kind: "notConnected" });
});
- it("installing elsewhere leaves an installed machine still reading as installed", () => {
- const elsewhere = job({
- machineId: "ssh:build-box",
- alias: "build-box",
+ it("a use that ended at installed, with nothing held, is as far as it goes", () => {
+ const installedOnly = job({
running: false,
result: { ok: true, installed: "installed", version: "9.9.9" },
});
- expect(installButtonState(carrying("nas"), response(elsewhere), false)).toEqual({
- action: "reinstall",
- disabled: false,
- });
- // ...and the machine that job belongs to reads as installed off its own record too.
- expect(installButtonState(carrying("build-box"), response(elsewhere), false).action).toBe(
- "reinstall",
- );
+ expect(readMachine(carrying("nas"), installedOnly, "9.9.9")).toEqual({ kind: "installedOnly" });
});
- it("a failed install leaves the selection on plain install: nothing was recorded", () => {
- const failed = job({
- running: false,
- result: { ok: false, step: "connect", message: "Permission denied (publickey)." },
- });
- expect(installButtonState(fresh("nas"), response(failed), false)).toEqual({
- action: "install",
- disabled: false,
- });
+ it("tones follow meaning: moving is busy, connected is a link, broken is danger, the rest want attention", () => {
+ expect(readingTone({ kind: "working", step: null })).toBe("busy");
+ expect(readingTone({ kind: "ready", port: 7364 })).toBe("link");
+ expect(readingTone({ kind: "unreachable", detail: null })).toBe("danger");
+ expect(readingTone({ kind: "stopped" })).toBe("attention");
+ expect(readingTone({ kind: "unknown" })).toBe("muted");
});
- it("no install image disables the button whatever is selected", () => {
- expect(
- installButtonState(fresh("nas"), response(null, { imageVersion: null }), false).disabled,
- ).toBe(true);
- expect(
- installButtonState(carrying("nas"), response(null, { imageVersion: null }), false).disabled,
- ).toBe(true);
+ it("use changes nothing for a ready or busy row, and fixes every other one", () => {
+ expect(wantsUse({ kind: "ready", port: null })).toBe(false);
+ expect(wantsUse({ kind: "queued" })).toBe(false);
+ expect(wantsUse({ kind: "stopped" })).toBe(true);
+ expect(wantsUse({ kind: "behind", version: "1" })).toBe(true);
+ });
+});
+
+describe("jobs and polling", () => {
+ it("finds a machine's job by id", () => {
+ expect(jobFor([failed], "ssh:nas")).toBe(failed);
+ expect(jobFor([failed], "ssh:build-box")).toBeNull();
+ });
+
+ it("keeps polling while anything is queued or running, and stops once all have finished", () => {
+ expect(anyJobPending(response([job({ queued: true, running: false })]))).toBe(true);
+ expect(anyJobPending(response([job()]))).toBe(true);
+ expect(anyJobPending(response([failed]))).toBe(false);
+ expect(anyJobPending(response([]))).toBe(false);
});
});
describe("installedMachines", () => {
- const at = (iso: string) => ({ version: "9.9.9", at: iso });
+ const older = { version: "9.9.8", at: "2026-08-20T00:00:00.000Z" };
it("is empty when nothing has been installed", () => {
- expect(installedMachines(response(null))).toEqual([]);
- });
-
- it("keeps only the installed ones, most recent first", () => {
- const machines: MachineInfo[] = [
- remote("a", at("2026-08-20T00:00:00.000Z")),
- remote("b", null),
- remote("c", at("2026-08-24T00:00:00.000Z")),
- remote("d", at("2026-08-22T00:00:00.000Z")),
- ];
- expect(installedMachines(response(null, { machines })).map((m) => m.alias)).toEqual([
- "c",
- "d",
- "a",
- ]);
+ expect(installedMachines(response([]))).toEqual([]);
+ });
+
+ it("keeps only the installed ones, by name — never by install time, which an update rewrites", () => {
+ const nas = { ...carrying("nas"), installed: older };
+ const box = carrying("build-box");
+ expect(
+ installedMachines(response([], { machines: [here(), fresh("spare"), nas, box] })),
+ ).toEqual([box, nas]);
+ // The same two after nas was just updated: the order does not move.
+ const fresher = { ...nas, installed: { version: "9.9.9", at: "2026-09-01T00:00:00.000Z" } };
+ expect(
+ installedMachines(response([], { machines: [here(), fresh("spare"), fresher, box] })),
+ ).toEqual([box, fresher]);
});
- it("keeps the config's order among installs sharing a timestamp, so the list does not shuffle between polls", () => {
- const same = at("2026-08-24T00:00:00.000Z");
- const machines: MachineInfo[] = [remote("x", same), remote("y", same), remote("z", same)];
- const order = () => installedMachines(response(null, { machines })).map((m) => m.alias);
- expect(order()).toEqual(["x", "y", "z"]);
- expect(order()).toEqual(order());
+ it("compares names naturally, so gpu-2 sits before gpu-10", () => {
+ const two = carrying("gpu-2");
+ const ten = carrying("gpu-10");
+ const one = carrying("GPU-1");
+ expect(installedMachines(response([], { machines: [here(), ten, two, one] }))).toEqual([
+ one,
+ two,
+ ten,
+ ]);
});
it("does not mutate the response's own machine order (the picker reads it too)", () => {
- const machines: MachineInfo[] = [
- remote("a", at("2026-08-20T00:00:00.000Z")),
- remote("c", at("2026-08-24T00:00:00.000Z")),
- ];
- const state = response(null, { machines });
+ const nas = { ...carrying("nas"), installed: older };
+ const box = carrying("build-box");
+ const state = response([], { machines: [nas, box] });
installedMachines(state);
- expect(state.machines.map((m) => m.alias)).toEqual(["a", "c"]);
+ expect(state.machines).toEqual([nas, box]);
+ });
+});
+
+describe("behindMachines", () => {
+ it("is the machines in use on another build, in list order, and nothing without a record", () => {
+ const old = { ...carrying("old"), installed: { version: "9.9.8", at: INSTALLED.at } };
+ const state = response([], { machines: [here(), fresh("spare"), carrying("nas"), old] });
+ expect(behindMachines(state).map((machine) => machine.id)).toEqual(["ssh:old"]);
+ expect(behindMachines({ ...state, imageVersion: null })).toEqual([]);
+ });
+});
+
+describe("the local machine", () => {
+ it("is the entry flagged local, wherever the server put it", () => {
+ expect(localMachine(response([], { machines: [fresh("nas"), here()] }))?.id).toBe("local");
+ expect(localMachine(response([]))).toBeNull();
});
});
-describe("this machine in the list", () => {
- /** The entry the server puts first: the host serving this page. */
- const here = (): MachineInfo => ({
- id: "local",
- alias: "workstation",
- machineId: "LNrJdHAZJ91G58i0",
- installed: INSTALLED,
- local: true,
- connection: null,
- api: null,
- status: { state: "running", checkedAt: INSTALLED.at, port: 7364 },
- });
-
- it("is never one of the installed remotes: there is nothing to reinstall from here", () => {
- const listed = installedMachines(response(null, { machines: [here(), carrying("nas")] }));
- expect(listed.map((m) => m.id)).toEqual(["ssh:nas"]);
+describe("outOfDate", () => {
+ it("compares the record's build against what this server would install", () => {
+ expect(outOfDate(carrying("nas"), "9.9.9")).toBe(false);
+ expect(outOfDate(carrying("nas"), "9.9.10")).toBe(true);
+ });
+
+ it("is never true without an image, for a fresh machine, or for this machine", () => {
+ expect(outOfDate(carrying("nas"), null)).toBe(false);
+ expect(outOfDate(fresh("nas"), "9.9.10")).toBe(false);
+ expect(outOfDate(here(), "9.9.10")).toBe(false);
});
});
diff --git a/packages/web/test/server-context.test.ts b/packages/web/test/server-context.test.ts
new file mode 100644
index 00000000..515304d7
--- /dev/null
+++ b/packages/web/test/server-context.test.ts
@@ -0,0 +1,53 @@
+/**
+ * The one rule that decides which machine a call reaches.
+ *
+ * There is no window-wide "active server" any more, and its absence is the point: pointing a
+ * whole window at another machine put every request behind a tunnel — `/api/me` included —
+ * so a dropped tunnel left the app unable to say whether anyone was logged in, with the way
+ * back rendered inside a layout that never mounted. Naming the machine per call cannot do
+ * that: a dead tunnel breaks exactly the request that needed it.
+ */
+import { describe, expect, it } from "vitest";
+import { apiUrl } from "../src/lib/server-context";
+
+const ID = "noeSE0FFHhNXl2J5";
+
+describe("apiUrl", () => {
+ it("leaves a call alone when no machine is named — the default is here", () => {
+ expect(apiUrl("/api/me")).toBe("/api/me");
+ expect(apiUrl("/api/me", null)).toBe("/api/me");
+ });
+
+ it("re-roots a named call onto that machine's proxy prefix", () => {
+ expect(apiUrl("/api/projects/p/dirs?path=/srv", ID)).toBe(
+ `/server/${ID}/api/projects/p/dirs?path=/srv`,
+ );
+ });
+
+ it("needs no encoding — a machine id is path-safe by construction", () => {
+ expect(apiUrl("/api/me", ID)).not.toContain("%");
+ });
+
+ it("touches ONLY /api paths: the frontend and previews are always local", () => {
+ // The window never leaves this origin, and a remote's pages are never proxied.
+ for (const path of ["/", "/assets/app.js", "/preview/tok/index.html", "/machines"]) {
+ expect(apiUrl(path, ID)).toBe(path);
+ }
+ });
+
+ it("cannot strand a window: an unknown machine breaks one call, not the app", () => {
+ // /api/me is never re-rooted unless a caller asks for it, and nothing does.
+ expect(apiUrl("/api/me")).toBe("/api/me");
+ });
+});
+
+describe("a 401 from another machine", () => {
+ it("is that machine's answer, not this server's", () => {
+ // The rule lives in client.ts (`options.server ?? null` decides), and this is the case
+ // it exists for: clicking a remote host in a picker used to bounce the window to the
+ // login page of a server it was still perfectly signed in to. Pinned here as the
+ // statement of intent, since the transport itself is not unit-reachable.
+ expect(apiUrl("/api/me", "noeSE0FFHhNXl2J5")).toBe("/server/noeSE0FFHhNXl2J5/api/me");
+ expect(apiUrl("/api/me")).toBe("/api/me");
+ });
+});
diff --git a/packages/web/test/tone.test.ts b/packages/web/test/tone.test.ts
index 09ea4589..dbe00c06 100644
--- a/packages/web/test/tone.test.ts
+++ b/packages/web/test/tone.test.ts
@@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url";
import { toneDot, toneInk, toneStrip, toneSurface } from "../src/lib/tone";
import type { Tone } from "../src/lib/tone";
-const TONES: Tone[] = ["busy", "attention", "success", "danger", "muted"];
+const TONES: Tone[] = ["busy", "attention", "success", "link", "danger", "muted"];
const read = (rel: string) =>
readFileSync(fileURLToPath(new URL(`../src/${rel}`, import.meta.url)), "utf8");
@@ -41,7 +41,7 @@ describe("tone tokens", () => {
it("fills a state dot with one value across both themes", () => {
// A 6px dot has no interior to read: one vivid mid-scale hue works on white and on black,
// where an ink pair tuned for a stroke does not. Muted is the exception — it must recede.
- for (const tone of ["busy", "attention", "success", "danger"] as const) {
+ for (const tone of ["busy", "attention", "success", "link", "danger"] as const) {
expect(toneDot[tone]).toMatch(/^bg-[a-z]+-500$/);
}
});
diff --git a/packages/web/test/workspace-machines.test.ts b/packages/web/test/workspace-machines.test.ts
new file mode 100644
index 00000000..772c3baa
--- /dev/null
+++ b/packages/web/test/workspace-machines.test.ts
@@ -0,0 +1,146 @@
+/**
+ * Which machines a workspace can be picked on. A workspace is a directory ON a machine, so
+ * the offer has to be exactly the machines whose filesystem can be browsed right now —
+ * offering one that cannot be reached would fail at the first click instead of the choice.
+ */
+import { describe, expect, it } from "vitest";
+import type { MachineInfo, MachinesResponse } from "@prismshadow/penguin-server/api";
+import {
+ isElsewhere,
+ machineLabel,
+ recordedMachineId,
+ workspaceMachines,
+} from "../src/lib/workspace-machines";
+
+const machine = (over: Partial<MachineInfo> & { alias: string }): MachineInfo => ({
+ id: `ssh:${over.alias}`,
+ machineId: null,
+ installed: null,
+ local: false,
+ root: "$HOME/.penguin/data",
+ connection: null,
+ api: null,
+ status: null,
+ ...over,
+});
+
+const state = (machines: MachineInfo[]): MachinesResponse => ({
+ machines,
+ imageVersion: "9.9.9",
+ job: null,
+ jobs: [],
+});
+
+const INSTALL = { version: "9.9.9", at: "2026-08-24T12:00:00.000Z" };
+const here = machine({
+ alias: "workstation",
+ id: "local",
+ local: true,
+ machineId: "LOCALaaaaaaaaaa",
+});
+const connected = machine({
+ alias: "far-box",
+ machineId: "noeSE0FFHhNXl2J5",
+ connection: { pid: 4242 },
+ installed: INSTALL,
+});
+
+describe("workspaceMachines", () => {
+ const installedNotConnected = machine({
+ alias: "cold",
+ installed: INSTALL,
+ machineId: "COLDaaaaaaaaaaaa",
+ });
+ const connectedNameless = machine({
+ alias: "ghost",
+ connection: { pid: 4242 },
+ installed: INSTALL,
+ });
+ const neverInstalled = machine({ alias: "just-an-ssh-host" });
+
+ it("is empty before the list has loaded", () => {
+ expect(workspaceMachines(null)).toEqual([]);
+ });
+
+ it("always offers this machine, as the null id the registry stores for it", () => {
+ expect(workspaceMachines(state([here]))).toEqual([
+ { id: null, label: "workstation", local: true, selectable: true },
+ ]);
+ });
+
+ it("offers a connected machine by its own id, labelled by its alias", () => {
+ expect(workspaceMachines(state([here, connected]))[1]).toEqual({
+ id: "noeSE0FFHhNXl2J5",
+ label: "far-box",
+ local: false,
+ selectable: true,
+ });
+ });
+
+ it("offers an installed machine even with no tunnel — browsing goes over ssh", () => {
+ const [, cold] = workspaceMachines(state([here, installedNotConnected]));
+ expect(cold).toMatchObject({ label: "cold", selectable: true });
+ expect(cold?.reason).toBeUndefined();
+ });
+
+ it("lists a connected machine that has no identity yet, with its own reason", () => {
+ const [, ghost] = workspaceMachines(state([here, connectedNameless]));
+ expect(ghost).toMatchObject({ label: "ghost", selectable: false, reason: "no-identity" });
+ });
+
+ it("gives a usable machine no reason at all, so a reason always means a problem", () => {
+ for (const entry of workspaceMachines(state([here, connected]))) {
+ expect(entry.selectable).toBe(true);
+ expect(entry.reason).toBeUndefined();
+ }
+ });
+
+ it("still leaves out plain ssh hosts — 45 config entries are not 45 failures", () => {
+ const listed = workspaceMachines(state([here, neverInstalled, machine({ alias: "another" })]));
+ expect(listed.map((m) => m.label)).toEqual(["workstation"]);
+ });
+});
+
+describe("machineLabel", () => {
+ const machines = workspaceMachines(state([here, connected]));
+
+ it("names this machine and a connected one", () => {
+ expect(machineLabel(machines, null)).toBe("workstation");
+ expect(machineLabel(machines, "noeSE0FFHhNXl2J5")).toBe("far-box");
+ });
+
+ it("falls back to the raw id for a machine that is gone, rather than inventing a name", () => {
+ expect(machineLabel(machines, "GONEaaaaaaaaaaaa")).toBe("GONEaaaaaaaaaaaa");
+ });
+});
+
+describe("isElsewhere", () => {
+ it("treats absent and null alike — an entry with no machine is one picked here", () => {
+ expect(isElsewhere(null)).toBe(false);
+ expect(isElsewhere(undefined)).toBe(false);
+ });
+
+ it("is true for a workspace that lives on another machine", () => {
+ expect(isElsewhere("noeSE0FFHhNXl2J5")).toBe(true);
+ });
+});
+
+describe("recordedMachineId", () => {
+ it("records nothing for this machine, so 'here' stays the absent case", () => {
+ expect(
+ recordedMachineId({ id: null, label: "workstation", local: true, selectable: true }),
+ ).toBeUndefined();
+ expect(recordedMachineId(undefined)).toBeUndefined();
+ });
+
+ it("records the id for another machine", () => {
+ expect(
+ recordedMachineId({
+ id: "noeSE0FFHhNXl2J5",
+ label: "far-box",
+ local: false,
+ selectable: true,
+ }),
+ ).toBe("noeSE0FFHhNXl2J5");
+ });
+});
diff --git a/packages/web/test/workspace-registry.test.ts b/packages/web/test/workspace-registry.test.ts
index 87c1ae83..9a205008 100644
--- a/packages/web/test/workspace-registry.test.ts
+++ b/packages/web/test/workspace-registry.test.ts
@@ -216,3 +216,62 @@ describe("mergeRegisteredWorkspaces", () => {
]);
});
});
+
+describe("a workspace's machine", () => {
+ it("records the machine a directory was picked on", () => {
+ const entries = registerWorkspace([], "/srv/app", "noeSE0FFHhNXl2J5");
+ expect(entries[0]).toEqual({ path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" });
+ });
+
+ it("leaves it absent for this machine, which is what every older entry looks like", () => {
+ expect(registerWorkspace([], "/srv/app")[0]).toEqual({ path: "/srv/app" });
+ });
+
+ it("keeps the same path on two machines as two workspaces", () => {
+ // `/srv/app` on two machines is two different directories; collapsing them would hide
+ // one behind the other with no way to tell which.
+ let entries = registerWorkspace([], "/srv/app", "noeSE0FFHhNXl2J5");
+ entries = registerWorkspace(entries, "/srv/app");
+ entries = registerWorkspace(entries, "/srv/app", "OTHERaaaaaaaaaaa");
+ expect(entries).toHaveLength(3);
+ expect(entries.map((e) => e.machineId)).toEqual([
+ "OTHERaaaaaaaaaaa",
+ undefined,
+ "noeSE0FFHhNXl2J5",
+ ]);
+ });
+
+ it("still dedups the same path on the SAME machine", () => {
+ const first = registerWorkspace([], "/srv/app", "noeSE0FFHhNXl2J5");
+ expect(registerWorkspace(first, "/srv/app", "noeSE0FFHhNXl2J5")).toBe(first);
+ const local = registerWorkspace([], "/srv/app");
+ expect(registerWorkspace(local, "/srv/app")).toBe(local);
+ });
+
+ it("round-trips through storage, and tolerates a stored entry without one", () => {
+ const store = new Map<string, string>();
+ const storage = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => void store.set(k, v),
+ };
+ saveWorkspaceRegistry(
+ "p",
+ [{ path: "/a", machineId: "noeSE0FFHhNXl2J5" }, { path: "/b" }],
+ storage,
+ );
+ expect(loadWorkspaceRegistry("p", storage)).toEqual([
+ { path: "/a", machineId: "noeSE0FFHhNXl2J5" },
+ { path: "/b" },
+ ]);
+ });
+
+ it("drops an empty machine id rather than storing a workspace on nothing", () => {
+ const store = new Map<string, string>();
+ store.set(workspaceRegistryKey("p"), JSON.stringify([{ path: "/a", machineId: "" }]));
+ const storage = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => void store.set(k, v),
+ };
+ expect(loadWorkspaceRegistry("p", storage)).toEqual([{ path: "/a" }]);
+ });
+});