A local-first multi-agent app development platform, built on PenguinHarness
feat(machines): run sessions on a machine (#450)
Myriad-Dreamin4ce48d791952
diff --git a/changelog/unreleased/2026-09-09-machines-run-agent.md b/changelog/unreleased/2026-09-09-machines-run-agent.mdnew file mode 100644index 00000000..e66fcc6d--- /dev/null+++ b/changelog/unreleased/2026-09-09-machines-run-agent.md@@ -0,0 +1,94 @@+# Run an agent on another machine — its Sessions, Workspaces, Agents, Benchmarks, plugins and terminal, in this window++- **Date:** 2026-09-09+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#450](https://github.com/Prism-Shadow/penguin-harness/pull/450)++[中文版](2026-09-09-machines-run-agent.zh.md)++Pick a workspace that lives on another machine and the conversation runs there: that machine's server drives the agent, holds the messages, writes the trace, serves the terminal. The window never moves — it stays on this server and names the machine on the calls that concern it. The machine has to be connected, and connecting is the server's: a held connection never idles out, is re-established on its own when it drops, and is restored after a restart or a hot push, so once a machine is connected on the Machines page it stays reachable from every window.++## A Session's calls follow the machine that owns it++A Session lives on the server whose filesystem its workspace is on, so **every** call about it has to reach that machine, and there are two dozen such endpoints. Rather than thread a machine argument through all of them, the routing is a rule over the path: a request to `/api/sessions/<id>/…` goes wherever `<id>` was last seen. Call sites are unchanged, and a Session's machine is recorded in exactly two places — when a list hands one back, and when one is created. The output stream follows the same rule.++Two kinds of address escape a rule over the path and carry the machine by hand: the Trace endpoints, which name a Session inside an Agent-level path, and a Workspace file's content URL or a message attachment's scratchpad image, which are addresses rather than calls. Without that, every preview, image, PDF and download of a Session on a machine asked this server for a file it does not have.++Deliberately narrow: the project-scoped `…/agents/:a/sessions` listing is **not** session-scoped. It asks a server which Sessions it has, and answering it from another machine would be that machine answering a question about this one.++## The composer follows the machine++Agents are per-server, so the composer offers the Agents that exist on the machine the chosen workspace is on — not this server's, which would name one the target cannot run. What that machine was last seen running is offered while it is asked, and stays on offer if it cannot be reached, with the row saying so. Starting a chat from a Workspace group keeps that group's machine, since a workspace path without its machine names a different directory on every host.++Switching the model stays on the machine too. The switch opens a new Session for the same Agent on the picked model and carries the source Session's Workspace so the files it refers to stay reachable — and that Workspace is a directory on the machine, so the new Session is created there, its first task (the `[model_switch_from]` block and the user's text) is posted there, and the trace the model reads for context is on the disk it is served from.++## One list, several machines++The sidebar's Session list is every connected machine's, merged: each server pages its own rows with its own offsets, so the merge walks one page from each and orders them together rather than sharing a cursor that would ask one machine for rows only another had reached. Folder counts are summed across the servers that answered.++A machine that cannot be asked is recorded as such, and what it last held is shown from a cache until it answers again. That is what separates "this server has not got that Session" from "nobody who might have it answered" — so a Session on a machine that is out of reach reads as out of reach rather than gone, and the open conversation is not dropped for a Session whose machine is merely down. Opening one whose machine is down says which machine it is waiting on, and opens it once the connection is back.++## A Workspace is a directory on a machine++`/srv/app` on this server and `/srv/app` on a machine are two different directories, so a Workspace group in the sidebar is keyed by the machine and the path — one folder per machine, named for the machine it is on: `app [SSH: prod-1]`, with the same form on its tooltip and on the Workspace line of a Session's detail panel. This server's own groups are written as before — no suffix, the same keys — so collapse state, pins and group order carry over. Each folder's "+" creates on its own machine, its badge counts only that machine's answer, and its pages are asked only of the machine it is on.++The manually-added Workspaces match the pair as well: loading a Project keeps both machines' entries for one path, and renaming or removing one acts on that machine's entry alone, keeping its machine. An unlabelled machine (the machine list is admin-only, and a host can drop out of `~/.ssh/config`) falls back to its own id rather than inventing a name.++## The list stays true without a reload++A Session created anywhere — the CLI, another tab, a schedule, an agent spawning a child — is announced on the user channel, and the list fetches the row rather than inventing it. Titles set through the API are announced the same way.++For Sessions on machines the list listens to each connected machine's own event stream through the proxy: a Session there changes state on **that** machine's server, and nothing else knows. A machine's own `web_updated` is ignored, since that is its web and not this window's.++## The Agents page lists every machine's Agents++An Agent belongs to the Project, but its state directory is created on whichever machine it has run on, so one that has only ever run on a machine exists only over there. The Agents page asks this server and every machine it holds a connection to, and merges the answers by agent id: this server describes an Agent it also has, and one that lives on exactly one machine is named for it — `[SSH: prod-1]` beside the name, in the machine's own casing.++What such a card can do is what the machine can answer. **New chat** opens the draft against that machine, with the temporary workspace on it, so the conversation starts where the Agent's state is. Settings and its stat shortcuts, usage and delete read or write a state directory this server does not have, so they are inert, with the reason on hover rather than a 404 after the click.++## The Evaluation Center reads every machine this server holds++A Benchmark belongs to the Project, and the Project is the same on every machine it is lent to. Its `benchmarks/` directory is not: it is written on whichever machine created or evaluated the Benchmark, so one Benchmark's cases and scoreboard are spread over as many disks as it has run on. The card list and a Benchmark's own page ask this server and every connected machine and fold the answers by benchmark id: one card per Benchmark, one history under it. The machine rides along as attribution rather than as a grouping key — an evaluation row names the machine whose scoreboard recorded it (`[SSH: prod-1]`) when the Benchmark is held in more than one place, a Benchmark only one machine has is named for that machine, and its tested Agents are those of every scoreboard.++A scoreboard's append order *is* its evaluation sequence, and the page trusts it over the timestamps — but two scoreboards on two disks share no append order at all, so a joined history is ordered by time, and a Benchmark that came from a single machine is left exactly as its file had it. A Benchmark's Cases are the union of what the machines holding it have, and a Case's files are read from the machine its listing came from. A machine that cannot answer is left out of the merge; everything this server holds still renders, and only when no source answered at all is there an error to report. Creating and deleting stay on this server: delete is offered only for a Benchmark this server holds, and removes this server's copy.++## A terminal, and the files behind it++A terminal opens on the machine its Workspace is on, including the fall-back to home, which is home *there*, and it survives this app restarting: the shell lives on that machine's server, so what is restored is the tab. The list that restores it is assembled from every connected machine, and it only prunes a conversation's stored tabs once every source has answered. Opening a terminal adopts a shell already running on that conversation's own machine before it starts a second one beside it. The stream is this server's own: a remote pty is named in the terminal id as `<terminalId>@<machineId>@<userId>`, and the platform relays the socket through the held connection.++## Plugins, per machine++A Project's plugin list gained per-machine tables: a plugin listed for certain machines runs only on those machines. The Plugins page and the plugin settings in the Settings dialog each gained a machine picker, for viewing and editing each machine in turn.++### Configuration++- **`[plugins.<machineId>]`** sits under the shared `[plugins]` table in `.project_config.toml` and lists what one machine runs in addition to the shared table. For a name both tables list, the machine's entry wins. The key is the machine's own 16-character id, minted by its server on first boot, never an ssh alias. This server uses its own id too.+- **Loading** reads this server's effective list: the shared table plus its own table. A plugin listed only for other machines is not loaded here.++### API++- `POST /api/projects/:projectId/plugins/installed` accepts `machineId`, which lists the package in that machine's table. Like the shared table, it takes only a plugin the build ships.+- `DELETE …?specifier=…&machineId=…` drops the package from that machine's table. Without `machineId`, it drops it from every table.+- An edit that does not change what this server runs is written without re-assembling the App here.+- `GET` rows carry `everywhere`, `machines` and `here`, and the response carries this server's `machineId`.++### Fleet sync++- A machine is handed the shared table plus its own table. There, the list lands as that Project's shared table.+- A plugin the machine lacks is added through that machine's own `POST`, which takes only what its build ships. A plugin not listed for a machine is never sent there.+- A plugin the machine refuses is reported in the connect log and left out of that sync. The other plugins still arrive.++### Plugins page++- **Machine picker.** A picker beside the settings button switches between **All machines**, **This server** and each machine the Project reaches. It appears once there is any machine besides this server.+- **All machines** lists every plugin. A plugin listed for some machines only is tagged with their names.+- **A machine's view** lists what that machine is asked to run, in the state that machine itself reports. Installing there enables the plugin on that machine only. A plugin from the shared table cannot be removed there, and its row says so.++### Plugin settings++The Plugins page of the Settings dialog shows its picker once the Project holds a connection to another machine. Picking a machine reads, saves and runs actions on that machine's own plugin settings through `/server/<machineId>/api/admin/plugin-config`. Each server keeps its settings in its own database, and nothing is copied between machines. A machine that cannot answer shows an empty page with the reason.++## Reach++Machines are an admin capability end to end: the Machines page, the proxy to a machine's API, and therefore everything here. A non-admin's list is this server's Sessions, exactly as before.diff --git a/changelog/unreleased/2026-09-09-machines-run-agent.zh.md b/changelog/unreleased/2026-09-09-machines-run-agent.zh.mdnew file mode 100644index 00000000..889bcde6--- /dev/null+++ b/changelog/unreleased/2026-09-09-machines-run-agent.zh.md@@ -0,0 +1,94 @@+# 在另一台机器上运行 Agent——它的 Session、工作区、Agent、Benchmark、插件与终端都在这个窗口里++- **Date:** 2026-09-09+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#450](https://github.com/Prism-Shadow/penguin-harness/pull/450)++[English](2026-09-09-machines-run-agent.md)++选一个位于另一台机器上的工作区,对话就在那台机器上运行:由那台机器的服务端驱动 Agent、保存消息、写入 trace、提供终端。窗口不会移动——它始终留在本服务端上,只在与那台机器相关的调用里点名它。机器需要处于已连接状态,而连接是服务端的事:持有的连接不会因空闲而关闭,断了会自行重建,服务端重启或热推之后也会恢复——所以一台机器在「机器」页面连接过一次之后,每个窗口都能一直到达它。++## Session 的调用跟着拥有它的机器走++一个 Session 活在其工作区所在文件系统的那台服务端上,所以关于它的**每一个**调用都必须到达那台机器,而这样的端点有二十多个。与其给它们全部加一个机器参数,路由是一条基于路径的规则:对 `/api/sessions/<id>/…` 的请求去往 `<id>` 最后一次被看到的地方。调用点原样不动,Session 所在的机器只在两处被记录——列表交回一条时,以及创建一条时。输出流遵循同一规则。++有两类地址逃过了基于路径的规则,需要自己带上机器:Trace 端点,它把 Session 放在 Agent 级路径里;以及工作区文件的内容 URL 和消息附件的 scratchpad 图片,它们是地址而不是调用。没有这一层,位于机器上的 Session 的每一个预览、图片、PDF 和下载都会向本服务端索要一个它没有的文件。++刻意收窄:项目级的 `…/agents/:a/sessions` 列表**不是** Session 级的。它问的是某台服务端有哪些 Session,让另一台机器来回答,就是那台机器在替这一台回答关于自己的问题。++## 编辑器跟着机器走++Agent 是按服务端划分的,所以编辑器提供的是所选工作区所在机器上存在的 Agent——而不是本服务端的,那会点名一个目标机器跑不了的 Agent。询问期间先给出那台机器上次被看到在跑的 Agent;若无法到达,这份列表仍然可选,并在行里说明原因。从工作区分组新建对话时保留该分组的机器,因为不带机器的工作区路径在每台主机上指向的都是不同的目录。++切换模型同样留在那台机器上。切换会为同一个 Agent 以所选模型开一个新 Session,并沿用原 Session 的工作区,好让对话引用的文件仍然可达——而这个工作区是那台机器上的目录,所以新 Session 在那里创建,它的第一个任务(`[model_switch_from]` 源信息块加用户的文字)发往那里,模型为取上下文而读的轨迹也就在它被服务的那块磁盘上。++## 一个列表,几台机器++侧边栏的 Session 列表是所有已连接机器的合并:每台服务端用自己的偏移量分页自己的行,所以合并从每台各取一页再排在一起,而不是共用一个游标去向一台机器要只有另一台才翻到过的行。文件夹计数按应答了的服务端求和。++无法询问的机器会被如实记录,它上次持有的内容会从缓存显示,直到它再次应答。这正是「本服务端没有那个 Session」与「可能持有它的人都没有应答」之间的区别——于是一台不可达机器上的 Session 读作不可达而非消失,正在打开的对话也不会因为它所在机器暂时不在而被丢掉。打开这样一个对话会说明它在等哪台机器,连接恢复后自动打开。++## 工作区是某台机器上的目录++本机的 `/srv/app` 与机器上的 `/srv/app` 是两个不同的目录,所以侧边栏的工作区分组按「机器 + 路径」建键——一台机器一个文件夹,并以所在机器命名:`app [SSH: prod-1]`,同样的写法用于它的悬浮提示,以及 Session 详情面板里的工作区一行。本机自己的分组写法照旧——不加后缀,键也不变——因此折叠状态、置顶与分组顺序原样保留。每个文件夹的「+」在它自己的机器上创建,计数只采信那台机器的回答,翻页也只问它所在的那台机器。++手工添加的工作区同样按这一对来匹配:加载项目时同一路径在两台机器上的条目都保留,重命名或删除只作用于那台机器的条目,并保留其机器。机器没有可用名称时(机器列表仅管理员可读,主机也可能从 `~/.ssh/config` 里消失),回退为它自己的 id,而不是编一个名字出来。++## 列表不用刷新也保持真实++在任何地方创建的 Session——CLI、另一个标签页、定时任务、Agent 派生的子 Session——都会在用户通道上被宣告,列表去取那一行而不是凭空造一行。通过 API 设置的标题以同样方式宣告。++对于机器上的 Session,列表通过代理监听每台已连接机器自己的事件流:那边的 Session 在**那台**机器的服务端上改变状态,其他人都不知道。机器自己的 `web_updated` 会被忽略,因为那是它的 web,不是这个窗口正在跑的。++## 智能体页面列出每台机器上的 Agent++Agent 属于 Project,但它的状态目录是在它运行过的那台机器上创建的,所以只在某台机器上跑过的 Agent 就只存在于那里。智能体页面会同时问本机与本机持有连接的每台机器,并按 agent id 归并:本机也有的 Agent 由本机描述;只存在于某一台机器上的,以那台机器命名——名字旁边是 `[SSH: prod-1]`,别名保持它自己的大小写。++这样一张卡片能做什么,取决于那台机器能回答什么。**新建对话**会以那台机器为目标打开草稿,临时工作区也建在它上面,于是对话就从 Agent 的状态所在之处开始。设置及其统计快捷入口、用量、删除读写的都是本机没有的状态目录,因此置为不可用,把原因放在悬停提示里,而不是让你点完之后收到一个 404。++## 评估中心会读遍本服务器持有的每台机器++Benchmark 属于 Project,而 Project 在它借给的每台机器上都是同一个。它的 `benchmarks/` 目录却不是:Benchmark 在哪台机器上创建或评测,就写在哪台机器上,于是同一个 Benchmark 的题目与记分板被摊在它跑过的所有磁盘上。卡片列表与 Benchmark 自己的页面会同时问本机与每台已连接的机器,并按 benchmark id 归并:一个 Benchmark 一张卡片,其下是一段完整历史。机器作为**归属信息**而非分组维度出现——当某个 Benchmark 存在于不止一处时,评测行会点名记录它的那块记分板所在的机器(`[SSH: prod-1]`);只存在于某台机器上的 Benchmark 以那台机器命名;它评测过的 Agent 取所有记分板的并集。++记分板的追加顺序**就是**评测序列,页面信任它胜过信任时间戳——但两块磁盘上的两份记分板之间根本不存在共同的追加顺序,因此合并出来的历史按时间排序,而只来自单台机器的 Benchmark 则原样保留其文件里的顺序。Benchmark 的题目取持有它的机器的并集,题目文件从其列表来源的那台机器读取。答不上来的机器会被排除在归并之外:本机持有的内容照常渲染,只有当没有任何来源作答时才报错。创建与删除仍只作用于本机:只有本机持有的 Benchmark 才提供删除,删除的也是本机这一份。++## 终端,以及它背后的文件++终端在其工作区所在的机器上打开——包括回退到家目录的情形,那也是*那台机器上*的家目录——并且在本应用重启后仍然存在:shell 活在那台机器的服务端上,需要恢复的只是标签。恢复它的列表由所有已连接机器汇成,只有在每个来源都应答之后才修剪对话里保存的标签。打开终端时优先接管对话自己机器上已经在跑的 shell,而不是在旁边再开一个。流始终是本服务端自己的:远端 pty 在终端 id 里以 `<terminalId>@<machineId>@<userId>` 命名,由平台经持有的连接中继套接字。++## 插件,按机器运行++Project 的插件清单新增按机器的子表:列给某几台机器的插件,只在那几台运行。插件页与设置弹窗中的插件设置各自新增机器选择器,用来逐台查看和编辑。++### 配置++- **`[plugins.<machineId>]`** 位于 `.project_config.toml` 的共享 `[plugins]` 表之下,列出某台机器在共享表之外还要运行的插件;两表同名时,以该机器的条目为准。键是机器自己的 16 位 ID(由该机器的服务端首次启动时生成),不用 ssh alias;本机同样使用自己的 ID。+- **加载**时,本机读取自己的有效清单,即共享表加上本机子表。只列给其他机器的插件,本机不加载。++### API++- `POST /api/projects/:projectId/plugins/installed` 接受 `machineId`,将包列入该机器的子表;与共享表一样,只接受构建自带的插件。+- `DELETE …?specifier=…&machineId=…` 只从该机器的子表中移除;不带 `machineId` 时从所有表中移除。+- 不改变本机运行内容的改动直接写盘,不重新装配本机 App。+- `GET` 的每行带 `everywhere`、`machines`、`here`,响应带本机 `machineId`。++### 机队同步++- 发给一台机器的是共享表加上它自己的子表;到了对端,清单落为该 Project 的共享表。+- 对端缺少的插件经对端自己的 `POST` 加入,它只接受其构建自带的插件。没有列给某台机器的插件从不发往那台。+- 对端拒绝的条目在连接日志中汇报,并从本次同步中略去;其余插件照常送达。++### 插件页++- **机器选择器。** 设置按钮旁新增选择器,可在「**所有机器**」「**本机**」与该 Project 连接的每台机器之间切换;只要除本机外还有机器,它就会出现。+- **「所有机器」**列出全部插件;只列给部分机器的插件,标注这些机器的名字。+- **某台机器的视角**列出那台机器要运行的插件,状态由那台机器自己报告。在此安装只对那台机器启用。共享表中的插件在这里不能移除,行上会注明原因。++### 插件设置++设置弹窗的「插件」页在 Project 连接了其他机器时显示机器选择器。选中某台机器后,读取、保存与执行动作都经 `/server/<machineId>/api/admin/plugin-config` 作用于那台机器自己的插件设置。每台服务端把设置存在自己的数据库里,机器之间不互相复制。无法应答的机器显示空页面,并注明原因。++## 范围++机器从头到尾都是管理员能力:「机器」页面、通往机器 API 的代理,因此这里的一切也是。非管理员的列表就是本服务端的 Session,与从前完全一样。diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.tsindex be2e704f..5bd5a956 100644--- a/packages/core/src/state/project-config.ts+++ b/packages/core/src/state/project-config.ts@@ -203,14 +203,15 @@ export interface ProjectConfig {* "@scope/other" = "1.2.3" # a version requirement* "@scope/third" = { version = "1.2" } # the table form, where later fields go*- * A table rather than a list so an entry can grow fields without a format change.+ * A table rather than a list so an entry can grow fields without a format change. A+ * `[plugins.<machineId>]` sub-table lists what that one machine runs besides (PluginTables).** Project-scoped because machines are lent to Projects, so this is what says which* machines a plugin has to reach. LOADING is per process, though — there is one module* tree — so a deployment runs the CLOSURE: the union over its Projects. A plugin any* Project asks for is in the tree, and what it contributes is visible to all of them.*/- plugins?: PluginTable;+ plugins?: PluginTables;models: ModelEntry[];}@@ -334,23 +335,64 @@ export interface PluginRequirement {version?: string;}-/** The `[plugins]` table: package name → what is asked of it, in the file's order. */+/** A plugin table: package name → what is asked of it, in the file's order. */export type PluginTable = Record<string, PluginRequirement>;/**- * Leniently parses the `[plugins]` table. An entry's value is a version requirement string+ * The whole `[plugins]` key: the table every machine runs, and each machine's own table.+ *+ * [plugins]+ * "@scope/everywhere" = "*"+ *+ * [plugins.Xk3v9Qa_bT2mLp0z]+ * "@scope/only-there" = "*"+ * "@scope/everywhere" = "1.2.3" # this machine's entry wins over the shared one+ *+ * A machine table is keyed by the machine's OWN id — the 16 characters its server mints on+ * first boot — never by an ssh alias, which a rename or a repointed host would silently move.+ * What a machine runs is `effectivePluginTable(tables, itsId)`: the shared table, plus its own+ * table, its own entry winning for a name both carry. A plugin listed only in a machine table+ * runs, and is installed, on that machine alone.+ */+export interface PluginTables {+ all: PluginTable;+ machines: Record<string, PluginTable>;+}++/** A machine's own id: 12 random bytes as base64url (the machines repo mints it). */+export const PLUGIN_MACHINE_ID = /^[A-Za-z0-9_-]{16}$/;++/**+ * Whether a `[plugins]` member is a machine's table rather than a plugin's requirement: a+ * key shaped like a machine id whose value is a table without `version`. The writer below+ * spells every requirement without fields as `"*"`, so a table of that shape is never one of+ * its requirements.+ */+function isMachineTable(key: string, value: unknown): boolean {+ return (+ PLUGIN_MACHINE_ID.test(key) &&+ value !== null &&+ typeof value === "object" &&+ !Array.isArray(value) &&+ !("version" in value)+ );+}++/**+ * Leniently parses one plugin table. An entry's value is a version requirement string* (`"*"` for any) or a table with an optional `version`; an entry of any other shape is* dropped rather than failing the load — a config whose plugin table is malformed still has- * to open, or a typo there would take the Project's models with it. A value that is not a- * table at all (the list form this key had before it was a table) reads as undefined:- * such a Project asks for no plugins until it is written again.+ * to open, or a typo there would take the Project's models with it. Machine tables inside+ * `[plugins]` are not entries of the shared table and are skipped (parsePluginTables reads+ * them). A value that is not a table at all (the list form this key had before it was a+ * table) reads as undefined: such a Project asks for no plugins until it is written again.*/export function parsePluginTable(value: unknown): PluginTable | undefined {if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;const out: PluginTable = {};for (const [rawName, spec] of Object.entries(value as Record<string, unknown>)) {const name = rawName.trim();- if (name === "") continue;+ if (name === "" || isMachineTable(name, spec)) continue;if (typeof spec === "string") {const version = spec.trim();out[name] = version === "" || version === "*" ? {} : { version };@@ -367,13 +409,47 @@ export function parsePluginTable(value: unknown): PluginTable | undefined {return out;}-/** The `[plugins]` table as it is written: the string form wherever only a version is asked. */+/** Parses the whole `[plugins]` key, the shared table and every machine's; undefined when it is not a table. */+export function parsePluginTables(value: unknown): PluginTables | undefined {+ const all = parsePluginTable(value);+ if (all === undefined) return undefined;+ const machines: Record<string, PluginTable> = {};+ for (const [key, spec] of Object.entries(value as Record<string, unknown>)) {+ if (isMachineTable(key, spec)) machines[key] = parsePluginTable(spec) ?? {};+ }+ return { all, machines };+}++/**+ * What one machine runs: the shared table, then that machine's own entries — its requirement+ * replacing the shared one for a name both list. `machineId` null means a machine whose id is+ * not known (a machine no server has started on yet): the shared table alone.+ */+export function effectivePluginTable(tables: PluginTables, machineId: string | null): PluginTable {+ const own = machineId === null ? undefined : tables.machines[machineId];+ return own === undefined ? { ...tables.all } : { ...tables.all, ...own };+}++/** A plugin table as it is written: the string form wherever only a version is asked. */export function pluginTableToToml(table: PluginTable,): Record<string, string | { version?: string }> {return Object.fromEntries(Object.entries(table).map(([name, req]) => [name, req.version ?? "*"]));}+/**+ * The whole `[plugins]` key as it is written: the shared entries, then one sub-table per+ * machine. A machine table left empty is dropped — "this machine adds nothing" is what its+ * absence already says.+ */+export function pluginTablesToToml(tables: PluginTables): Record<string, unknown> {+ const out: Record<string, unknown> = pluginTableToToml(tables.all);+ for (const [machineId, table] of Object.entries(tables.machines)) {+ if (Object.keys(table).length > 0) out[machineId] = pluginTableToToml(table);+ }+ return out;+}+export function parseCommandPolicy(value: unknown): CommandPolicyConfig | undefined {if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;const t = value as Record<string, unknown>;@@ -418,7 +494,7 @@ export function projectConfigFromTable(const visionModel = parseRefField(file, "vision_model", parsed.vision_model);const defaultChat = parseDefaultChat(parsed.default_chat);const commandPolicy = parseCommandPolicy(parsed.command_policy);- const plugins = parsePluginTable(parsed.plugins);+ const plugins = parsePluginTables(parsed.plugins);return {...(parsed.name !== undefined ? { name: parsed.name as string } : {}),...(defaultModel !== undefined ? { default_model: defaultModel } : {}),@@ -509,7 +585,9 @@ export async function saveProjectConfig(): Promise<void> {const file = projectConfigPath(root, projectId);await fs.mkdir(path.dirname(file), { recursive: true });- await atomicWriteFile(file, renderProjectConfigToml({ ...cfg }), {+ const { plugins, ...rest } = cfg;+ const table = plugins === undefined ? rest : { ...rest, plugins: pluginTablesToToml(plugins) };+ await atomicWriteFile(file, renderProjectConfigToml(table), {mode: 0o600,followSymlinks: true,});diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.tsindex f856da79..38dbb9d4 100644--- a/packages/core/test/state.test.ts+++ b/packages/core/test/state.test.ts@@ -39,6 +39,8 @@ import {buildToolConfig,selectBuiltinToolsForModel,defaultProjectConfig,+ effectivePluginTable,+ parsePluginTables,defaultSystemConfig,resetSystemConfigToDefaults,getModel,@@ -1515,6 +1517,36 @@ describe("command_policy (sandbox command policy block)", () => {});});+describe("plugins (shared and per-machine tables)", () => {+ it("a machine table survives a load → save round trip, and its entry wins on that machine", async () => {+ const cfg = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ cfg.plugins = {+ all: { "@acme/shared": {}, "@acme/pinned": { version: "1.0.0" } },+ machines: {+ Xk3v9Qa_bT2mLp0z: { "@acme/only-there": {}, "@acme/pinned": { version: "2.0.0" } },+ },+ };+ await saveProjectConfig(tmpRoot, DEFAULT_PROJECT_ID, cfg);+ const text = await fs.readFile(projectConfigPath(tmpRoot, DEFAULT_PROJECT_ID), "utf8");+ expect(text).toContain('[plugins.Xk3v9Qa_bT2mLp0z]\n"@acme/only-there" = "*"');+ const loaded = await loadProjectConfig(tmpRoot, DEFAULT_PROJECT_ID);+ expect(loaded.plugins).toEqual(cfg.plugins);+ expect(effectivePluginTable(loaded.plugins!, "Xk3v9Qa_bT2mLp0z")).toEqual({+ "@acme/shared": {},+ "@acme/pinned": { version: "2.0.0" },+ "@acme/only-there": {},+ });+ expect(effectivePluginTable(loaded.plugins!, "Other00000000000")).toEqual(cfg.plugins.all);+ });++ it("a requirement table on an id-shaped package name is still a requirement", () => {+ expect(parsePluginTables({ abcdefghijklmnop: { version: "1" } })).toEqual({+ all: { abcdefghijklmnop: { version: "1" } },+ machines: {},+ });+ });+});+describe("default_chat (new-chat defaults block)", () => {const block = {agent_id: "default_agent",diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 0628875f..079fbc0f 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -1046,7 +1046,7 @@ Real-time delivery uses Server-Sent Events, not WebSocket, on two kinds of chann| Channel | Path | Contents || --- | --- | --- || Per Session | `GET /api/sessions/:sessionId/stream` | The Session's message stream and run events, including `session_created` for its subagent Sessions and the goal-mode events |-| Per user | `GET /api/events` | The `hello` handshake and notifications across Sessions: `session_state`, `session_background`, `session_title`, `schedule_fired`, `schedule_queued`, `web_updated` and company mode's `org_*` events |+| Per user | `GET /api/events` | The `hello` handshake and notifications across Sessions: `session_created`, `session_state`, `session_background`, `session_title`, `schedule_fired`, `schedule_queued`, `web_updated` and company mode's `org_*` events |### Wire Format@@ -1071,7 +1071,7 @@ export type ServerEvent =| { type: "credentials_updated" }| { type: "hello" }| { type: "web_updated"; rev: string }- | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source: SessionSource }+ | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source?: SessionSource }| { type: "schedule_fired"; projectId: string; agentId: string; name: string; sessionId: string }| { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string }| { type: "goal_started"; sessionId: string; objective: string; budget: number }@@ -1094,7 +1094,7 @@ export type ServerEvent =| `credentials_updated` | The Project's model credentials changed || `hello` | Handshake on the user channel || `web_updated` | A hot update replaced the served web assets; clients reload |-| `session_created` | A new Session was registered, such as a subagent Session |+| `session_created` | A Session now exists: created by the Web App, the CLI, a schedule, or an agent spawning a child || `schedule_fired` | A scheduled task fired and its prompt was delivered || `schedule_queued` | The target Session is running, so this firing was queued || `goal_started` | A goal run began, before its first round |@@ -1112,7 +1112,7 @@ export type ServerEvent =- `session_background` fires when a command moves to the background past its yield window or starts with `run_in_background`, when a process exits or is stopped, and when a background subagent starts, settles or is released. It carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = subagent Sessions moved to the background and mid-round), zeros included, so a list can clear its mark without refetching. The list rows and the single-Session GET omit the field when both counts are zero. Its audience is the same as for `session_state`.- `credentials_updated` follows `PUT /models` or a completed key-minting flow. Cached runtimes were invalidated, so the client clears any composer state disabled by an auth failure.- `web_updated` carries the new web revision as `rev` and is sent to every user channel.-- `session_created` is sent on the parent Session's channel.+- `session_created` is sent for every creation to the user channels of the Project's owner and members, and for a subagent also on the parent Session's channel. `source` is absent for a user-created Session, as it is on the row. A title set through `PATCH /api/sessions/:id` is announced as `session_title` the same way.- `schedule_fired` names in `sessionId` the Session that received the prompt, which in new-Session mode is a new Session. A queued firing is sent once the Session is idle.- `goal_round` carries `used`, the tokens counted so far.- The `org_*` events are sent to the user channels of the Project's members. `org_channel` includes the message's mentions, so a client can tell whether it is addressed. These events are best effort; the organization routes carry the durable state.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 8bb023c2..d92b8d46 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -1046,7 +1046,7 @@ Telegram 连接时会先清空积压,跳过无连接期间发送的消息。| 通道 | 路径 | 内容 || --- | --- | --- || 每个 Session | `GET /api/sessions/:sessionId/stream` | Session 的消息流和运行事件,包括子 Agent Session 的 `session_created` 以及目标模式事件 |-| 每个用户 | `GET /api/events` | `hello` 握手和跨 Session 的通知:`session_state`、`session_background`、`session_title`、`schedule_fired`、`schedule_queued`、`web_updated` 以及公司模式的 `org_*` 事件 |+| 每个用户 | `GET /api/events` | `hello` 握手和跨 Session 的通知:`session_created`、`session_state`、`session_background`、`session_title`、`schedule_fired`、`schedule_queued`、`web_updated` 以及公司模式的 `org_*` 事件 |### 传输格式@@ -1071,7 +1071,7 @@ export type ServerEvent =| { type: "credentials_updated" }| { type: "hello" }| { type: "web_updated"; rev: string }- | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source: SessionSource }+ | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source?: SessionSource }| { type: "schedule_fired"; projectId: string; agentId: string; name: string; sessionId: string }| { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string }| { type: "goal_started"; sessionId: string; objective: string; budget: number }@@ -1094,7 +1094,7 @@ export type ServerEvent =| `credentials_updated` | Project 的模型凭据发生变化 || `hello` | 用户通道上的握手 || `web_updated` | 热更新替换了对外提供的 web 资源;客户端需重新加载 |-| `session_created` | 注册了一个新 Session,例如子 Agent Session |+| `session_created` | 一个 Session 现在存在了:由 Web App、CLI、定时任务或 Agent 派生子 Session 创建 || `schedule_fired` | 定时任务已触发,Prompt 已投递 || `schedule_queued` | 目标 Session 正在运行,这次触发已排队 || `goal_started` | 目标运行开始,在第一轮之前 |@@ -1112,7 +1112,7 @@ export type ServerEvent =- 以下情况会触发 `session_background`:命令超过让出窗口转入后台,或以 `run_in_background` 启动;进程退出或停止;后台子 Agent 开始一轮、结束一轮或释放。事件携带 `SessionInfo.backgroundTasks` 的当前值(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转入后台、正处于一轮中的子 Agent Session 数),归零时同样发送,列表无需重新拉取就能撤下标记。两个计数都为零时,列表行和单个 Session 的 GET 会省略这个字段。受众与 `session_state` 相同。- `credentials_updated` 在 `PUT /models` 或签发 API key 的流程完成之后发送。缓存的运行时已失效,客户端应清除因认证失败而禁用的输入框状态。- `web_updated` 以 `rev` 携带新的 web 修订号,发送到每个用户通道。-- `session_created` 发送到父 Session 的通道。+- `session_created` 在每次创建时发送到 Project 所有者和成员的用户通道;子 Agent Session 还会同时发送到父 Session 的通道。用户创建的 Session 没有 `source`,与行上一致。通过 `PATCH /api/sessions/:id` 设置的标题以同样方式作为 `session_title` 宣告。- `schedule_fired` 的 `sessionId` 是接收 Prompt 的 Session,在新建 Session 模式下是一个新 Session。排队的触发会在 Session 空闲后发送。- `goal_round` 携带 `used`,即目前累计的 Token 数。- `org_*` 事件发送到 Project 成员的用户通道。`org_channel` 包含消息里的提及信息,客户端可据此判断消息是否指向自己。这些事件是尽力而为的;持久状态以组织路由为准。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 731f38c3..280d979d 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -2572,13 +2572,18 @@ export type ServerEvent =| { type: "hello" }/** The served web assets were hot-swapped by a platform upgrade: clients reload to pick them up. */| { type: "web_updated"; rev: string }- /** New session registered (pushed over the parent session's channel for subagent sessions): frontend refreshes the list in place. */+ /**+ * A Session now exists. On the user channel for every creation — the CLI, another tab,+ * a schedule, an agent spawning a child — so the list learns about rows it did not make;+ * and on the parent Session's channel for a subagent, so a tab watching the parent run+ * refreshes in place. `source` is absent for a user-created Session, as it is on the row.+ */| {type: "session_created";projectId: string;agentId: string;sessionId: string;- source: SessionSource;+ source?: SessionSource;}| ScheduleServerEvent| GoalServerEvent@@ -5077,9 +5082,20 @@ export interface InstalledPlugin {replaces: string[];/*** Why the package is not running: unresolvable, or a load that- * failed (an import that threw, a module name another plugin already took).+ * failed (an import that threw, a module name another plugin already took). Only ever+ * reported for a plugin this server is asked to run (`here`).*/error?: string;+ /** Listed in the shared `[plugins]` table: every machine runs it. */+ everywhere: boolean;+ /** The machines whose own `[plugins.<machineId>]` table lists it, by machine id. */+ machines: string[];+ /**+ * Whether THIS server is asked to run it — shared, or listed for this server's own id. A+ * plugin listed only for other machines is neither installed nor loaded here, so `active`+ * is false and no `error` is reported for it.+ */+ here: boolean;}export interface InstalledPluginsResponse {@@ -5091,6 +5107,8 @@ export interface InstalledPluginsResponse {shipped: string[];/** The file the list lives in, named for the page that explains where to edit it by hand. */file: string;+ /** This server's own machine id — the key of its `[plugins.<machineId>]` table. */+ machineId: string;/** A listed plugin neither runs nor failed to load: the App could not be re-assembled around it (the previous one was restored), so a restart is what applies it. */restartPending: boolean;}diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.tsindex 3e1961cb..671e74fd 100644--- a/packages/server/src/auth/service.ts+++ b/packages/server/src/auth/service.ts@@ -233,6 +233,17 @@ export class AuthService implements Auth {return { user: toUserInfo(row), token: this.issueSession(row.userId, "password") };}+ /**+ * Whether a user is an admin, by id — for a caller that has a user's NAME rather than an+ * authenticated request: the terminal relay reads the owner out of a pty reference the+ * runtime has already matched against the signed-in user (machines/terminal-relay.ts), and+ * what is left to decide is whether that user may reach machines at all. Unknown users are+ * not admins.+ */+ isAdmin(userId: string): boolean {+ return this.users.findById(userId)?.isAdmin === true;+ }+/*** Desktop-mode sign-in: an admin session with no password check — the claim route already* redeemed the shell's one-shot token, which is the credential here. Throws only on adiff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex 23dc1eff..8c636037 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -46,6 +46,7 @@ import {import type { HmrHost, PlatformBundle } from "@prismshadow/penguin-hmr";import { TerminalManager } from "../terminal/manager.js";import type { TerminalSession } from "../terminal/session.js";+import type { RemoteTerminals } from "../machines/terminal-relay.js";import { identityFrom } from "../terminal/identity.js";import { bindTerminalStream } from "../terminal/stream.js";import { Hono } from "hono";@@ -69,6 +70,7 @@ import { PLUGINS_RESOURCE_ID, pluginHostFrom } from "../plugin/host.js";import type { PluginHost } from "../plugin/host.js";import { loadPluginHost } from "../plugin/loader.js";import { migrate } from "../db/migrations.js";+import { MachinesRepo } from "../db/repos/machines.js";import type { Auth } from "../mechanisms/identity.js";/**@@ -298,7 +300,14 @@ async function createInner(const plugins =caps === null? pluginHostFrom(ctx.resources)- : await loadPluginHost(ctx.resources, caps.config.root, caps.hmr.assetsDir());+ : await loadPluginHost(+ ctx.resources,+ caps.config.root,+ caps.hmr.assetsDir(),+ // A Project may list a plugin for one machine only (`[plugins.<machineId>]`); this+ // server's own id says which of those tables are its own.+ new MachinesRepo(caps.db).ownId(),+ );// Plus whatever a test stood up in process, which no closure could name (see the id).const injected = ctx.resources.claim<PluginHost | null>(HMR_TEST_PLUGINS_RESOURCE_ID);if (injected != null && typeof injected.entries === "function") {@@ -341,6 +350,9 @@ async function createInner(const auth = business?.api<Auth>("IdentityModule", "Auth") ?? null;const identity = identityFrom(auth);const manager = business?.api<SessionManager>("SessionRuntimeModule", "Sessions") ?? null;+ // A pty on a machine, served through this server's own stream (machines/terminal-relay.ts).+ // A bare kernel reaches no machines and serves only its own ptys.+ const remote = business?.api<RemoteTerminals>("TerminalRelay", "TerminalRelay") ?? null;// The runtime's one mid-request need of the CURRENT App is a hook installed over a// claimed capability — overwrite-only across swaps, so a dead generation's hook is// replaced and never removed: "is this session busy" for the channel sweep.@@ -435,7 +447,12 @@ async function createInner(}),http,terminals: () => terminals,- attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),+ attachStream: (ws, session, url, log) => {+ // The runtime handed the socket over exactly as for a local pty; the relay takes it+ // when the session is a reference to a machine's pty, and declines a local one.+ if (remote?.attach(ws, session, url, log) === true) return;+ bindTerminalStream(ws, session, url, log);+ },business: () => business,// Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose// effect cannot await — exposed for index.ts's shutdown to call before disposing.diff --git a/packages/server/src/http/routes/plugins-installed.ts b/packages/server/src/http/routes/plugins-installed.tsindex 6bd1f92b..eef794e8 100644--- a/packages/server/src/http/routes/plugins-installed.ts+++ b/packages/server/src/http/routes/plugins-installed.ts@@ -3,13 +3,16 @@** GET / this Project's list, joined with what the process runs,* plus which plugins the build ships (any member)- * POST / { specifier } add a plugin the build ships to this Project's list, and- * apply (admin); nothing is fetched from anywhere- * PUT / { plugins } rewrite this Project's list, and apply (admin)- * DELETE /?specifier=… drop it from this Project's list, and apply (admin)+ * POST / { specifier, add a plugin the build ships to this Project's shared table —+ * machineId? } or to that machine's own table — and apply (admin); nothing+ * is fetched from anywhere+ * PUT / { plugins } rewrite this Project's shared table, and apply (admin)+ * DELETE /?specifier=… drop it from every table of this Project — or, with+ * [&machineId=…] `machineId`, from that machine's own table — and apply (admin)** WHERE THE LIST LIVES. In the Project's own config (the `[plugins]` table of `.project_config.toml`,- * package name → requirement, Cargo's `[dependencies]` shape),+ * package name → requirement, Cargo's `[dependencies]` shape, plus a `[plugins.<machineId>]`+ * table for what one machine runs besides — PluginTables in core),* beside its models — because machines are lent to Projects, so a Project's list is what* says which machines a plugin has to reach (PRFC-0010). The data root's old `plugins.json`* is not read any more, deliberately without a migration: a deployment that had one starts@@ -36,7 +39,13 @@ import type { AppEnv } from "../../auth/middleware.js";import type { InstalledPlugin, InstalledPluginsResponse } from "../../api/types.js";import { HttpError } from "../errors.js";import { readJson, requireValidId } from "../validate.js";-import type { Config, Hmr, Reassembly, ReassemblyChange } from "../../hmr/capabilities.js";+import type { DatabaseSync } from "node:sqlite";+import {+ effectivePluginTable,+ PLUGIN_MACHINE_ID,+ type PluginTables,+} from "@prismshadow/penguin-core";+import type { Config, Db, Hmr, Reassembly, ReassemblyChange } from "../../hmr/capabilities.js";import {discoverBuiltinPlugins,PACKAGE_NAME,@@ -47,9 +56,12 @@ import {import { pluginHostFrom } from "../../plugin/host.js";import { Access, ProjectConfigStore } from "../../mechanisms/projects.js";import type { Machines } from "../../machines/service.js";+import { MachinesRepo } from "../../db/repos/machines.js";export interface InstalledPluginsDeps {root: string;+ /** This server's own machine id: the `[plugins.<machineId>]` table that is its own. */+ machineId: string;/** The current version's assets, where the builtin plugins a push carried live. */assetsDir: () => string | null;/** What the process's plugin host holds, by specifier, and what it could not load, with why. */@@ -83,8 +95,8 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>return projectId;};- const view = async (projectId: string): Promise<InstalledPluginsResponse> => {- const listed = await deps.projectConfig.getPlugins(projectId).catch((err: unknown) => {+ const tablesOf = (projectId: string): Promise<PluginTables> =>+ deps.projectConfig.getPluginTables(projectId).catch((err: unknown) => {// A Project whose config will not parse cannot be answered for — its models are just// as unreadable — and saying "no plugins" would read as a healthy empty deployment.throw new HttpError(@@ -93,15 +105,33 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>`${projectId}: ${PLUGINS_FILE} could not be read: ${err instanceof Error ? err.message : String(err)}`,);});++ const view = async (projectId: string): Promise<InstalledPluginsResponse> => {+ const tables = await tablesOf(projectId);+ const here = effectivePluginTable(tables, deps.machineId);+ // Every name any table lists, shared ones first: the page shows where each one runs.+ const names = [+ ...new Set([+ ...Object.keys(tables.all),+ ...Object.values(tables.machines).flatMap((t) => Object.keys(t)),+ ]),+ ];const { loaded, skipped } = deps.running();const bases = pluginBases(deps.root, deps.assetsDir());- // Exactly what this Project lists: a plugin the build ships is not asked for until a- // Project says so. `builtin` on a row is where the package CAME FROM, a tag, not a- // second way of being asked for. What the package declares is read from its files;- // whether the process holds it, and why not, is the host's — a load that failed says- // so, rather than passing as a restart that would not help.+ // `builtin` on a row is where the package CAME FROM, a tag, not a second way of being+ // asked for. What the package declares is read from its files; whether the process holds+ // it, and why not, is the host's — a load that failed says so, rather than passing as a+ // restart that would not help. A plugin listed only for other machines is not on this+ // one by design, so its missing files are not an error here.const plugins: InstalledPlugin[] = [];- for (const specifier of Object.keys(listed)) {+ for (const specifier of names) {+ const where = {+ everywhere: specifier in tables.all,+ machines: Object.entries(tables.machines)+ .filter(([, t]) => specifier in t)+ .map(([id]) => id),+ here: specifier in here,+ };const declared = await readPluginDeclaration(specifier, bases);if ("error" in declared) {plugins.push({@@ -110,12 +140,13 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>builtin: false,modules: [],replaces: [],- error: declared.error,+ ...(where.here ? { error: declared.error } : {}),+ ...where,});continue;}- const active = loaded.has(specifier);- const failure = skipped.get(specifier);+ const active = where.here && loaded.has(specifier);+ const failure = where.here ? skipped.get(specifier) : undefined;plugins.push({specifier,active,@@ -123,6 +154,7 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>modules: declared.modules,replaces: declared.replaces,...(!active && failure !== undefined ? { error: failure } : {}),+ ...where,});}return {@@ -131,9 +163,10 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>// and asking for one is a list edit rather than a download.shipped: await discoverBuiltinPlugins(bases),file: PLUGINS_FILE,- // A listed plugin that neither runs nor failed is waiting for a runtime that can- // re-assemble the App — otherwise applying already loaded it.- restartPending: plugins.some((p) => !p.active && p.error === undefined),+ machineId: deps.machineId,+ // A plugin this server is asked to run that neither runs nor failed is waiting for a+ // runtime that can re-assemble the App — otherwise applying already loaded it.+ restartPending: plugins.some((p) => p.here && !p.active && p.error === undefined),};};@@ -154,6 +187,15 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>return s;};+ /** The machine a verb is scoped to — its own table — or null for the shared table. */+ const machineOf = (value: unknown): string | null => {+ if (value === undefined || value === null || value === "") return null;+ if (typeof value !== "string" || !PLUGIN_MACHINE_ID.test(value)) {+ throw new HttpError(400, "bad_request", "machineId must be a machine's own id.");+ }+ return value;+ };+/*** Only a plugin the build ships can be asked for: it is already on the machine, so asking* is consent, not a download. Nothing is fetched from a registry — a listed plugin that is@@ -174,33 +216,56 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>}};- type PluginTable = Awaited<ReturnType<ProjectConfigStore["getPlugins"]>>;/**- * An edit of this Project's table as a re-assembly change: read and written inside the- * re-assembly's queue, so two edits never interleave, and undone — the table as it was —- * when the new tree fails to boot.+ * Writes an edit of this Project's tables. When what THIS server runs changes, the edit is a+ * re-assembly change: read and written inside the re-assembly's queue, so two edits never+ * interleave, and undone — the tables as they were — when the new tree fails to boot. An+ * edit that only concerns other machines is written as it is: re-assembling would stop+ * every agent run in flight here for a tree that stays the same.*/- const edit = (projectId: string, next: (listed: PluginTable) => PluginTable) => {- let previous: PluginTable | null = null;- const change: ReassemblyChange = {+ const edit = async (projectId: string, next: (tables: PluginTables) => PluginTables) => {+ const current = await tablesOf(projectId);+ const same = (a: PluginTables, b: PluginTables) =>+ JSON.stringify(effectivePluginTable(a, deps.machineId)) ===+ JSON.stringify(effectivePluginTable(b, deps.machineId));+ if (same(current, next(current))) {+ await deps.projectConfig.setPluginTables(projectId, next(current));+ return;+ }+ let previous: PluginTables | null = null;+ await deps.apply({write: async () => {- previous = await deps.projectConfig.getPlugins(projectId);- await deps.projectConfig.setPlugins(projectId, next(previous));+ previous = await deps.projectConfig.getPluginTables(projectId);+ await deps.projectConfig.setPluginTables(projectId, next(previous));},undo: async () => {- if (previous !== null) await deps.projectConfig.setPlugins(projectId, previous);+ if (previous !== null) await deps.projectConfig.setPluginTables(projectId, previous);},- };- return change;+ });};app.post("/", async (c) => {requireAdmin(c);const projectId = scope(c);- const specifier = specifierOf((await readJson(c)).specifier);+ const body = await readJson(c);+ const specifier = specifierOf(body.specifier);+ const machineId = machineOf(body.machineId);+ // Only a plugin the build ships can be asked for, of any machine: the machines run this+ // build too, and asking is consent, not a download.await requireShipped([specifier]);- await deps.apply(- edit(projectId, (listed) => (specifier in listed ? listed : { ...listed, [specifier]: {} })),+ await edit(projectId, (tables) =>+ machineId === null+ ? { ...tables, all: { ...tables.all, [specifier]: tables.all[specifier] ?? {} } }+ : {+ ...tables,+ machines: {+ ...tables.machines,+ [machineId]: {+ ...tables.machines[machineId],+ [specifier]: tables.machines[machineId]?.[specifier] ?? {},+ },+ },+ },);deps.syncFleet(projectId);return c.json(await view(projectId));@@ -210,12 +275,24 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>requireAdmin(c);const projectId = scope(c);const specifier = specifierOf(c.req.query("specifier"));- await deps.apply(- edit(projectId, (listed) => {- const kept = { ...listed };- delete kept[specifier];- return kept;- }),+ const machineId = machineOf(c.req.query("machineId"));+ const without = (table: PluginTables["all"] | undefined) => {+ const kept = { ...table };+ delete kept[specifier];+ return kept;+ };+ await edit(projectId, (tables) =>+ machineId === null+ ? {+ all: without(tables.all),+ machines: Object.fromEntries(+ Object.entries(tables.machines).map(([id, t]) => [id, without(t)]),+ ),+ }+ : {+ ...tables,+ machines: { ...tables.machines, [machineId]: without(tables.machines[machineId]) },+ },);deps.syncFleet(projectId);return c.json(await view(projectId));@@ -229,15 +306,20 @@ export function installedPluginRoutes(deps: InstalledPluginsDeps): Hono<AppEnv>if (!Array.isArray(list)) {throw new HttpError(400, "bad_request", "plugins must be an array of package specifiers.");}- // Names only, over the wire — the same names POST accepts. A name the list already- // carries was consented to when it was written; a NEW one is gated exactly as POST- // gates it. A name that stays keeps what the file asked of it.+ // Names only, over the wire — the same names POST accepts. A name the shared table+ // already carries was consented to when it was written; a NEW one is gated exactly as POST+ // gates it. A name that stays keeps what the file asked of it. Machine tables are not+ // touched: this is the verb the fleet sync speaks, and what it hands over is the shared list.const names = list.map(specifierOf);- const already = await deps.projectConfig.getPlugins(projectId).catch(() => ({}));+ const already = await deps.projectConfig+ .getPluginTables(projectId)+ .then((t) => t.all)+ .catch(() => ({}));await requireShipped(names.filter((s) => !(s in already)));- await deps.apply(- edit(projectId, (listed) => Object.fromEntries(names.map((s) => [s, listed[s] ?? {}]))),- );+ await edit(projectId, (tables) => ({+ ...tables,+ all: Object.fromEntries(names.map((s) => [s, tables.all[s] ?? {}])),+ }));deps.syncFleet(projectId);return c.json(await view(projectId));});@@ -265,11 +347,13 @@ export class InstalledPluginRoutes {@Use() private readonly projectConfig!: ProjectConfigStore;@Use() private readonly access!: Access;@Use() private readonly machines!: Machines;+ @Use() private readonly db!: Db;@Bind("InstalledPluginRoutes.routes") routes!: Hono<AppEnv>;setup() {const hmr = this.hmr;this.routes = installedPluginRoutes({root: this.config.root,+ machineId: new MachinesRepo(this.db as unknown as DatabaseSync).ownId(),assetsDir: () => hmr.assetsDir(),// Claimed per call rather than captured: the host belongs to the process, and a hot// swap hands the same one to the next platform.diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 7c0bd131..ad1013c9 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -81,6 +81,8 @@ export interface SessionsRouteDeps {previewTokens: PreviewTokenSigner;projectConfigService: ProjectConfigStore;access: Access;+ /** Tells everyone who can see the Project about a change the list could not otherwise learn of. */+ projectEvents: ProjectEvents;serverSettingsRepo: Settings;sessionService: SessionService;sessionSources: SessionOrigins;@@ -124,7 +126,12 @@ import { chatDefaultsRoutes } from "./chat-defaults.js";import { commandPolicyRoutes } from "./command-policy.js";import { usageRoutes } from "./usage.js";import { PreviewTokens } from "./preview.js";-import type { Access, ModelOAuth, ProjectConfigStore } from "../../mechanisms/projects.js";+import type {+ Access,+ ModelOAuth,+ ProjectConfigStore,+ ProjectEvents,+} from "../../mechanisms/projects.js";import type { PlatformAuth } from "../../services/platform-auth-service.js";import type { ModelScopeAuth } from "../../services/modelscope-auth-service.js";import type { Schedules, SessionIndex, SessionOrigins } from "../../mechanisms/sessions.js";@@ -682,6 +689,14 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {// Manual renaming takes priority over auto-generation: TitleGenerator only ever replaces the fallback title it wrote itself, never a manual rename.deps.sessionsRepo.updateTitle(row.sessionId, title);updated = { ...updated, title };+ // The list learns of a rename it did not make — the CLI's `--title`, another tab —+ // the same way it learns of a generated one: the generator publishes this exact+ // event, and the row handler is already listening for it.+ deps.projectEvents.notifyProjectUsers(row.projectId, {+ type: "session_title",+ sessionId: row.sessionId,+ title,+ });}if (approvalMode !== undefined) {// Takes effect immediately: a running approve callback re-reads the DB on every decision.@@ -1714,6 +1729,7 @@ export class SessionApiRoutes {@Use() private readonly messaging!: Messaging;@Use() private readonly schedulesRepo!: Schedules;@Use() private readonly access!: Access;+ @Use() private readonly projectEvents!: ProjectEvents;@Use() private readonly projectConfig!: ProjectConfigStore;@Use() private readonly modelOAuth!: ModelOAuth;@Use() private readonly platformAuth!: PlatformAuth;@@ -1759,6 +1775,7 @@ export class SessionApiRoutes {previewTokens: this.previewTokens as PreviewTokenSigner,projectConfigService,access,+ projectEvents: this.projectEvents,serverSettingsRepo: this.settings,sessionService,sessionSources: this.sources,diff --git a/packages/server/src/machines/plugins-sync.ts b/packages/server/src/machines/plugins-sync.tsindex 1382e4b3..2a6f7322 100644--- a/packages/server/src/machines/plugins-sync.ts+++ b/packages/server/src/machines/plugins-sync.ts@@ -16,6 +16,12 @@* fleet-wide; a machine that cannot resolve it shows an inert error row rather than losing* the backend it can use.*+ * WHAT A MACHINE IS HANDED is what the Project asks of THAT machine: the shared `[plugins]`+ * table plus the machine's own `[plugins.<machineId>]` table, its entry winning. Over there+ * it lands as the Project's shared table — the machine runs it, it does not re-share it. A+ * plugin the machine is not asked for is never sent there; one it is asked for and does not+ * list yet is added by that machine's own POST, which takes only what its build ships.+ ** 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@@ -48,10 +54,16 @@ export type PluginSyncOutcome =}| { kind: "failed"; detail: string };+/** One plugin as a Project asks it of a machine: the package name and, when pinned, its version. */+export interface WantedPlugin {+ name: string;+ version?: string;+}+export interface SyncPluginsOptions {api: MachineApi;- /** This side's half: what the Project asks for. */- loadLocal: (projectId: string) => Promise<string[]>;+ /** This side's half: what the Project asks of this machine, shared and machine-own tables merged. */+ loadLocal: (projectId: string) => Promise<WantedPlugin[]>;/** The Projects this machine is used by. */projects: readonly string[];}@@ -102,13 +114,14 @@ export async function syncPluginsToMachine(opts: SyncPluginsOptions): Promise<Pllet restartPending = false;for (const projectId of opts.projects) {- let want: string[];+ let wanted: WantedPlugin[];try {- want = await opts.loadLocal(projectId);+ wanted = await opts.loadLocal(projectId);} catch (err) {refused.push({ projectId, detail: err instanceof Error ? err.message : String(err) });continue;}+ const want = wanted.map((p) => p.name);// 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));@@ -121,8 +134,13 @@ export async function syncPluginsToMachine(opts: SyncPluginsOptions): Promise<Plcontinue;}let had: string[];+ let shipped: string[];try {- had = (JSON.parse(before.text) as InstalledPluginsResponse).plugins.map((p) => p.specifier);+ const parsed = JSON.parse(before.text) as InstalledPluginsResponse;+ // The machine's shared table is the list this sync owns; a row its own machine tables+ // add is not (a build that predates them reports every row as shared).+ had = parsed.plugins.filter((p) => p.everywhere !== false).map((p) => p.specifier);+ shipped = parsed.shipped ?? [];} catch {refused.push({ projectId, detail: "that machine's plugin list could not be read" });continue;@@ -130,14 +148,32 @@ export async function syncPluginsToMachine(opts: SyncPluginsOptions): Promise<Plconst 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 });+ // What the machine lacks and its build does not ship is installed there first: its PUT+ // lists only what is already on its disk. A failed install is reported and left out of+ // the list, so one unreachable package does not keep the rest from arriving.+ const failedInstall = new Set<string>();+ for (const plugin of wanted) {+ if (had.includes(plugin.name) || shipped.includes(plugin.name)) continue;+ const specifier =+ plugin.version === undefined ? plugin.name : `${plugin.name}@${plugin.version}`;+ const res = await opts.api.request("POST", pluginsPath(projectId), { specifier });+ if (res.status !== 200) {+ failedInstall.add(plugin.name);+ refused.push({+ projectId,+ detail: `installing ${specifier} → ${res.status}: ${res.text.slice(0, 200)}`,+ });+ }+ }+ const listed = want.filter((s) => !failedInstall.has(s));+ const res = await opts.api.request("PUT", pluginsPath(projectId), { plugins: listed });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);+ for (const s of listed) if (!had.includes(s)) added.push(s);+ for (const s of had) if (!listed.includes(s)) removed.push(s);try {const after = JSON.parse(res.text) as InstalledPluginsResponse;if (after.restartPending) restartPending = true;diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.tsindex 9a62446e..fddf4fc5 100644--- a/packages/server/src/machines/service.ts+++ b/packages/server/src/machines/service.ts@@ -25,7 +25,12 @@*/import fs from "node:fs";import os from "node:os";-import { DEFAULT_PROJECT_ID, VERSION, loadProjectConfig } from "@prismshadow/penguin-core";+import {+ DEFAULT_PROJECT_ID,+ VERSION,+ effectivePluginTable,+ loadProjectConfig,+} from "@prismshadow/penguin-core";import type { ProjectConfig } from "@prismshadow/penguin-core";import type {MachineInfo,@@ -64,7 +69,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 { syncPluginsToMachine, type WantedPlugin } from "./plugins-sync.js";import type { LocalModels } from "./models-sync.js";import { machineApi } from "./machine-api.js";import { startRemoteServer, stopRemoteServer } from "./server-control.js";@@ -1141,7 +1146,10 @@ export class MachinesService {// 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),+ // Asked of THIS machine: its own table joins the shared one, keyed by the id its server+ // minted — null (no server there has reported one) reads the shared table alone.+ loadLocal: (projectId) =>+ this.#localPlugins(projectId, this.repo.get(address)?.machineId ?? null),projects,});if (plugins.kind === "failed") {@@ -1163,12 +1171,15 @@ export class MachinesService {}/**- * What a Project asks for, by package name — the machine's list takes names; an unreadable- * config syncs nothing rather than emptying the machine.+ * What a Project asks of one machine, by package name with its pinned version; an+ * unreadable config syncs nothing rather than emptying the machine.*/- async #localPlugins(projectId: string): Promise<string[]> {+ async #localPlugins(projectId: string, machineId: string | null): Promise<WantedPlugin[]> {const config = await this.#effects.loadConfig(projectId);- return Object.keys(config.plugins ?? {});+ const table = effectivePluginTable(config.plugins ?? { all: {}, machines: {} }, machineId);+ return Object.entries(table).map(([name, req]) =>+ req.version === undefined ? { name } : { name, version: req.version },+ );}/**diff --git a/packages/server/src/machines/terminal-relay.ts b/packages/server/src/machines/terminal-relay.tsnew file mode 100644index 00000000..12594099--- /dev/null+++ b/packages/server/src/machines/terminal-relay.ts@@ -0,0 +1,269 @@+/**+ * A terminal on a machine, served through this server's own terminal stream.+ *+ * The runtime serves ONE kind of socket, `/api/terminals/<id>/stream`, and everything it+ * does with it is ask the platform: `terminals().get(id)` for the session, then+ * `attachStream(ws, session, url)` to drive the protocol. It never looks inside either. So a+ * terminal that lives on a machine needs no runtime change at all — the terminal manager+ * answers `get` with a reference to the remote pty (asked of this relay for an id it does+ * not hold itself), and `attachStream` relays the socket to that machine's own stream+ * through the connection this server holds to it (a channel dialled through the session's+ * SOCKS port, like every other request to a machine's API). Platform code, pushed like any+ * other; the runtime is exactly what it was.+ *+ * The reference is spelled in the id: `<terminalId>@<machineId>@<userId>`. The user id is+ * there for the runtime's owner check, which compares the session's `ownerUserId` with the+ * authenticated user — a client can only name itself, and an id naming anyone else is+ * refused before this code runs. What that leaves to check here is that the user may reach+ * machines at all, which is this server's admins (the session minted on the machine is an+ * admin's).+ *+ * The relay carries messages verbatim. The protocol (frames, backpressure, restore) is the+ * machine's; both ends speak it and this server does not need to.+ */+import type http from "node:http";+import { WebSocket } from "ws";+import type { RawData, WebSocket as WsSocket } from "ws";+import { Component, Interface, Use } from "@prismshadow/penguin-core/kernel";+import type { Terminal } from "../terminal/manager.js";+import type { Auth } from "../mechanisms/identity.js";+import type { Machines } from "./service.js";++const SEP = "@";++/** A remote pty, in the shape the runtime's owner check reads. */+export interface RemoteTerminalRef {+ id: string;+ ownerUserId: string;+ remote: { machineId: string; terminalId: string };+}++/** `<terminalId>@<machineId>@<userId>`, or null for an ordinary (local) id. */+export function parseRemoteTerminalRef(id: string): RemoteTerminalRef | null {+ let text = id;+ try {+ text = decodeURIComponent(id);+ } catch {+ // A malformed escape cannot name a terminal anywhere; fall through to "not remote".+ }+ const parts = text.split(SEP);+ if (parts.length !== 3 || parts.some((p) => p === "")) return null;+ const [terminalId, machineId, ownerUserId] = parts as [string, string, string];+ return { id: text, ownerUserId, remote: { machineId, terminalId } };+}++export const isRemoteTerminalRef = (session: object): session is RemoteTerminalRef =>+ "remote" in session;++/**+ * Viewer frames held while the machine's stream is still opening. Generous for what actually+ * arrives in that window — an opening resize and a few keystrokes — and bounded because a+ * viewer can paste into a handshake that never completes.+ */+const PENDING_INPUT_MAX_BYTES = 256 * 1024;++/**+ * Backpressure watermarks for the viewer's socket, the same pair the machine's own stream+ * uses on its viewers (terminal/stream.ts).+ */+const BACKPRESSURE_HIGH_WATER = 1024 * 1024;+const BACKPRESSURE_LOW_WATER = 64 * 1024;+const BACKPRESSURE_POLL_MS = 250;++const frameBytes = (data: RawData): number => {+ if (Array.isArray(data)) return data.reduce((total, part) => total + part.length, 0);+ return data instanceof ArrayBuffer ? data.byteLength : data.length;+};++export interface RelayDeps {+ /**+ * What the proxy needs to reach the machine's API by its own id — a dial through the held+ * connection, the port over there, and a session there — or null when it is not connected.+ */+ proxyTarget(+ machineId: string,+ ): Promise<{ agent: http.Agent; port: number; cookie: string } | null>;+ isAdmin(userId: string): boolean;+}++/**+ * Joins the viewer's socket to the machine's stream for this pty. Closes the viewer with a+ * WebSocket status (not a hang) for every way this can fail: the caller may not reach+ * machines, the machine is not connected, or its stream refused.+ */+export async function relayTerminalStream(+ ws: WsSocket,+ ref: RemoteTerminalRef,+ url: URL,+ deps: RelayDeps,+ log: (line: string) => void,+): Promise<void> {+ if (!deps.isAdmin(ref.ownerUserId)) return ws.close(1008, "forbidden");++ // The remote socket, once there is one. Everything below is written to run before it+ // exists, because the viewer can go away — and does, on a pane closed or reopened — while+ // the dial and the handshake are still in flight.+ let remote: WebSocket | null = null;+ let closing = false;++ // A close that arrived without a status (1005/1006) cannot be sent as one; ws throws.+ const sendable = (code: number) =>+ code === 1000 ||+ code === 1001 ||+ code === 1008 ||+ code === 1011 ||+ code === 1013 ||+ (code >= 3000 && code <= 4999)+ ? code+ : 1000;+ let drainTimer: ReturnType<typeof setInterval> | null = null;+ const stopDrainPoll = () => {+ if (drainTimer !== null) clearInterval(drainTimer);+ drainTimer = null;+ };+ const closeBoth = (raw: number, reason: string) => {+ closing = true;+ stopDrainPoll();+ const code = sendable(raw);+ if (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING) ws.close(code, reason);+ if (+ remote !== null &&+ (remote.readyState === remote.OPEN || remote.readyState === remote.CONNECTING)+ ) {+ remote.close(code, reason);+ }+ };++ // Frames the viewer sends before the machine's stream is open are held, not dropped: the+ // pane's opening geometry rides in one of them, and a shell started at the wrong size stays+ // at it until something resizes the pane again.+ const pending: { data: RawData; isBinary: boolean }[] = [];+ let pendingBytes = 0;++ // Listened to HERE, before the dial below — not after it. A viewer that closed during the+ // handshake would otherwise never fire a close on a listener attached afterwards, and the+ // socket opened below would stay attached to the pty on the machine with nobody reading it:+ // one leaked pty stream per pane closed at the wrong moment.+ ws.on("message", (data, isBinary) => {+ if (remote !== null && remote.readyState === remote.OPEN) {+ remote.send(data, { binary: isBinary });+ return;+ }+ const size = frameBytes(data);+ if (pendingBytes + size > PENDING_INPUT_MAX_BYTES) return;+ pending.push({ data, isBinary });+ pendingBytes += size;+ });+ ws.on("close", (code, reason) => closeBoth(code, reason.toString()));+ ws.on("error", () => closeBoth(1011, "viewer failed"));++ const target = await deps.proxyTarget(ref.remote.machineId).catch(() => null);+ // The viewer left while this server was reaching the machine: there is nothing to relay to,+ // and dialling anyway is exactly the leak above.+ if (closing) return;+ if (target === null) return ws.close(1013, "machine not connected");++ const path = `/api/terminals/${encodeURIComponent(ref.remote.terminalId)}/stream${url.search}`;+ // Through the connection, like every request to a machine's API: the agent's sockets are+ // SOCKS dials inside the held ssh session (transport/connection.ts). Canonical host, as the+ // request proxy sends it — the App answers on `localhost` and refuses `127.0.0.1`. No+ // Origin: the machine's guard reads its absence as a non-browser client, which this is.+ const socket = new WebSocket(`ws://127.0.0.1:${target.port}${path}`, {+ agent: target.agent,+ headers: { host: `localhost:${target.port}`, cookie: target.cookie },+ perMessageDeflate: false,+ });+ remote = socket;++ /**+ * Backpressure on behalf of a viewer the machine cannot see.+ *+ * The machine's own stream watches its socket's buffer and stops sending to a viewer that+ * falls behind, resyncing it with a fresh screen once it drains (terminal/stream.ts). But+ * the socket it watches is this relay's, which is fast and local to it — so a slow browser+ * link makes THIS server the buffer, and a `cat` of a large log grows it without bound.+ * Reading the machine's socket is stopped instead: the bytes back up through the connection+ * to where the lag detection can see them, and it does the dropping and resyncing it+ * already knows how to do.+ */+ const applyBackpressure = () => {+ if (drainTimer !== null || ws.bufferedAmount <= BACKPRESSURE_HIGH_WATER) return;+ socket.pause();+ drainTimer = setInterval(() => {+ if (ws.readyState !== ws.OPEN || socket.readyState !== socket.OPEN) {+ stopDrainPoll();+ socket.resume();+ return;+ }+ if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) return;+ stopDrainPoll();+ socket.resume();+ }, BACKPRESSURE_POLL_MS);+ };++ socket.on("open", () => {+ for (const frame of pending) socket.send(frame.data, { binary: frame.isBinary });+ pending.length = 0;+ pendingBytes = 0;+ socket.on("message", (data, isBinary) => {+ if (ws.readyState !== ws.OPEN) return;+ ws.send(data, { binary: isBinary });+ applyBackpressure();+ });+ });+ // A handshake the machine refused: pass its status on as a close reason rather than+ // inventing one — 404 for a pty that is gone reads differently from 401.+ socket.on("unexpected-response", (_req, res) => {+ res.resume();+ closeBoth(1011, `machine answered ${res.statusCode ?? "?"}`);+ });+ socket.on("error", (err) => {+ log(`[machines] terminal relay to ${ref.remote.machineId}: ${err.message}`);+ closeBoth(1011, "relay failed");+ });+ // Either end closing takes the other with it: a half-open pipe to a shell is a pane that+ // looks alive and answers nothing.+ socket.on("close", (code, reason) => closeBoth(code, reason.toString()));+}++/**+ * RemoteTerminals: the mechanism TerminalRelay implements. The terminal manager asks it for+ * an id it does not hold, and the platform offers it every socket before serving a local pty.+ */+@Interface()+export abstract class RemoteTerminals {+ /** The reference a remote id names, in the shape the runtime's owner check reads; undefined for a local id. */+ abstract get(id: string): Terminal | undefined;+ /**+ * Joins a viewer's socket to the machine's stream when `session` is a remote reference.+ * False for a local pty, which the caller then serves itself.+ */+ abstract attach(ws: WsSocket, session: Terminal, url: URL, log: (line: string) => void): boolean;+}++@Component()+export class TerminalRelay implements RemoteTerminals {+ @Use() private readonly machines!: Machines;+ @Use() private readonly auth!: Auth;++ get(id: string): Terminal | undefined {+ const ref = parseRemoteTerminalRef(id);+ // The runtime only reads `ownerUserId` off this before handing it back to attach.+ return ref === null ? undefined : (ref as unknown as Terminal);+ }++ attach(ws: WsSocket, session: Terminal, url: URL, log: (line: string) => void): boolean {+ if (!isRemoteTerminalRef(session)) return false;+ void relayTerminalStream(+ ws,+ session,+ url,+ {+ proxyTarget: (machineId) => this.machines.proxyTarget(machineId),+ isAdmin: (userId) => this.auth.isAdmin(userId),+ },+ log,+ );+ return true;+ }+}diff --git a/packages/server/src/mechanisms/identity.ts b/packages/server/src/mechanisms/identity.tsindex 70112593..e36043e5 100644--- a/packages/server/src/mechanisms/identity.ts+++ b/packages/server/src/mechanisms/identity.ts@@ -55,6 +55,7 @@ export abstract class Auth extends Interface<{localApiToken(): string | null;authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null;authenticateWithMeta(token: string): { user: UserRow; via: SessionVia; renewed: boolean } | null;+ isAdmin(userId: string): boolean;}>() {}/** Admin: the mechanism AdminService implements. */diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.tsindex 4d9eb23a..90dc3ff8 100644--- a/packages/server/src/mechanisms/projects.ts+++ b/packages/server/src/mechanisms/projects.ts@@ -22,6 +22,7 @@ import type {ModelsUpdateRequest,ProjectRole,ProjectSummary,+ ServerEvent,} from "../api/types.js";import type { UserRow } from "../db/repos/users.js";import type { RawTable, UtilityCompletion } from "../services/project-config-service.js";@@ -29,7 +30,7 @@ import type {ListEndpointModelsOptions,ModelRequestContext,ModelRef,- PluginTable,+ PluginTables,ProjectConfig,} from "@prismshadow/penguin-core";import type { TieredRates } from "../services/usage-service.js";@@ -114,10 +115,10 @@ export abstract class ProjectConfigStore extends Interface<{setDefaultModelRef(projectId: string, ref: ModelRefDto): Promise<ModelRefDto>;getChatDefaults(projectId: string): Promise<ChatDefaultsDto>;setChatDefaults(projectId: string, req: ChatDefaultsDto): Promise<ChatDefaultsDto>;- /** The `[plugins]` table this Project asks for: package name → requirement, in the file's order. */- getPlugins(projectId: string): Promise<PluginTable>;- /** Replaces the table (a declarative PUT); answers what was written. */- setPlugins(projectId: string, plugins: PluginTable): Promise<PluginTable>;+ /** The `[plugins]` key: the shared table and each machine's own, package name → requirement, in the file's order. */+ getPluginTables(projectId: string): Promise<PluginTables>;+ /** Replaces the tables (a declarative PUT); answers what was written. */+ setPluginTables(projectId: string, tables: PluginTables): Promise<PluginTables>;getCommandPolicy(projectId: string): Promise<CommandPolicyDto>;setCommandPolicy(projectId: string,@@ -222,3 +223,14 @@ export abstract class ModelOAuth extends Interface<{code: string;}): Promise<{ ok: true; applied: number } | { ok: false; error: ModelOAuthErrorCode }>;}>() {}++/**+ * ProjectEvents: the mechanism ProjectNotifier implements — a user-level event to everyone+ * who can see a Project, its owner and its members with GET /api/events open. The runtime+ * publishes a Session's state flips and its generated title this way, and a route+ * publishes a change the list could not otherwise learn of (a rename, a new Session).+ */+@Interface()+export abstract class ProjectEvents {+ abstract notifyProjectUsers(projectId: string, event: ServerEvent): void;+}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 096f862a..665a61a5 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -97,6 +97,7 @@ import { TraceService } from "./services/trace-service.js";import { WorkspaceFilesService } from "./services/workspace-files-service.js";import { RevealService } from "./services/reveal-path.js";import { ProjectAccess } from "./services/project-access.js";+import { ProjectNotifier } from "./services/project-events.js";import { ProjectService, ProjectRuns } from "./services/project-service.js";import { AuthService, InitialProjectProvisioner } from "./auth/service.js";import { AdminService } from "./services/admin-service.js";@@ -115,6 +116,7 @@ import { Machines, MachinesModule } from "./machines/service.js";import { OrganizationModule, OrgScheduler, OrgService } from "./runtime/organization/service.js";import { OrgRoutes } from "./http/routes/organizations.js";import { OrgRuns, OrgSessions } from "./runtime/organization/deps.js";+import { TerminalRelay } from "./machines/terminal-relay.js";import { ProjectAdminRoutes } from "./http/routes/projects.js";import { AdminRoutes } from "./http/routes/admin.js";import { MeRoutes } from "./http/routes/me.js";@@ -136,6 +138,7 @@ import {ModelOAuth,ModelProviderAuthTokens,ProjectConfigStore,+ ProjectEvents,ProjectLifecycle,Projects,} from "./mechanisms/projects.js";@@ -272,6 +275,7 @@ export class IdentityModule {}MembersRepo,AgentsRepo,ProjectAccess,+ ProjectNotifier,ProjectService,ProjectConfigService,ModelOAuthService,@@ -292,6 +296,7 @@ export class IdentityModule {}PlatformAuth,ModelScopeAuth,InitialProjectProvisioner,+ ProjectEvents,],})export class ProjectsModule {}@@ -462,6 +467,7 @@ export class WorkflowsModule {}SandboxSettingsModule,TerminalModule,MachinesModule,+ TerminalRelay,WorkflowsModule,Startup,],diff --git a/packages/server/src/plugin/loader.ts b/packages/server/src/plugin/loader.tsindex e47b9740..c517c17d 100644--- a/packages/server/src/plugin/loader.ts+++ b/packages/server/src/plugin/loader.ts@@ -23,7 +23,11 @@import fs from "node:fs/promises";import type { Dirent } from "node:fs";import { parse as parseToml } from "smol-toml";-import { parsePluginTable, projectConfigPath } from "@prismshadow/penguin-core";+import {+ effectivePluginTable,+ parsePluginTables,+ projectConfigPath,+} from "@prismshadow/penguin-core";import { findPackageJSON } from "node:module";import { existsSync, readFileSync, statSync } from "node:fs";import path from "node:path";@@ -82,8 +86,16 @@ export async function listProjectIds(root: string): Promise<string[]> {return ids.sort();}-/** One Project's list, in the order it wrote them; empty when it asks for none. */-export async function readProjectPluginList(root: string, projectId: string): Promise<string[]> {+/**+ * What one Project asks `machineId` to run, in the order it wrote them; empty when it asks+ * for none. `machineId` is the machine's own id — this server's, for what it loads itself —+ * and null reads the shared table alone.+ */+export async function readProjectPluginList(+ root: string,+ projectId: string,+ machineId: string | null = null,+): Promise<string[]> {let text: string;try {text = await fs.readFile(projectConfigPath(root, projectId), "utf8");@@ -108,17 +120,23 @@ export async function readProjectPluginList(root: string, projectId: string): Pr);return [];}- return Object.keys(parsePluginTable((parsed as { plugins?: unknown }).plugins) ?? {});+ const tables = parsePluginTables((parsed as { plugins?: unknown }).plugins);+ return tables === undefined ? [] : Object.keys(effectivePluginTable(tables, machineId));}/**- * The closure this deployment runs: the union over its Projects, first-asked order. One- * process, one module tree — so this is what `loadPlugins` loads, whoever asked for it.+ * The closure a machine runs: the union over this root's Projects of what each asks THAT+ * machine for, first-asked order. One process, one module tree — so with this server's own+ * id it is what `loadPlugins` loads, whoever asked for it; a plugin every Project lists only+ * for other machines is neither loaded nor installed here.*/-export async function readPluginClosure(root: string): Promise<string[]> {+export async function readPluginClosure(+ root: string,+ machineId: string | null = null,+): Promise<string[]> {const out: string[] = [];for (const projectId of await listProjectIds(root)) {- for (const specifier of await readProjectPluginList(root, projectId)) {+ for (const specifier of await readProjectPluginList(root, projectId, machineId)) {if (!out.includes(specifier)) out.push(specifier);}}@@ -544,6 +562,8 @@ export async function loadPlugins(* place (a package updated under `<root>/plugins`) means different code, and that is imported.*/reuse: ReadonlyMap<string, LoadedPlugin> = new Map(),+ /** This server's own machine id, which selects its `[plugins.<id>]` tables; null reads the shared tables alone. */+ machineId: string | null = null,): Promise<PluginLoadResult> {const failed = new Map<string, string>();const pushedAssets = assetsDir === undefined ? await committedAssetsDir(root) : assetsDir;@@ -551,7 +571,7 @@ export async function loadPlugins(// The closure over this root's Projects, and nothing else. A plugin the BUILD ships is// available without a download — that is what `builtin` means — but availability is not// consent: it loads when a Project asks for it, like every other plugin.- const specifiers = await readPluginClosure(root);+ const specifiers = await readPluginClosure(root, machineId);const loaded: LoadedPlugin[] = [];for (const specifier of specifiers) {// Reused only when the SAME FILE is behind the name. A push writes the builtin plugins to@@ -642,13 +662,15 @@ export async function loadPluginHost(root: string,/** The booting version's assets (hmr.assetsDir()), not the committed ones — see loadPlugins. */assetsDir?: string | null,+ /** This server's own machine id (see loadPlugins). */+ machineId: string | null = null,): Promise<PluginHost> {const inherited = pluginHostFrom(resources);// An older generation's host may predate `entries()`; then nothing is reused and every// specifier is imported again, which the ESM cache makes cheap.const reuse =typeof inherited.entries === "function" ? inherited.entries() : new Map<string, LoadedPlugin>();- const result = await loadPlugins(root, assetsDir, reuse);+ const result = await loadPlugins(root, assetsDir, reuse, machineId);const host = new PluginHost();for (const entry of result.loaded) {// A module name clash is a LOAD failure, isolated per entry like an import failure.diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex e9cb622d..986a2416 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -90,10 +90,9 @@ import { ModelScopeAuth } from "../services/modelscope-auth-service.js";import { TitleGenerator } from "./title-generator.js";import { loopbackHostRoles } from "../services/preview-token.js";import { mergedNoProxy } from "../net/proxy.js";-import { userChannelKey } from "../http/routes/events.js";import type { SandboxService } from "../sandbox/service.js";import type { AuthState, Channels, Clock, Config, Log } from "../hmr/capabilities.js";-import type { Members, ProjectConfigStore, Projects } from "../mechanisms/projects.js";+import type { ProjectConfigStore, ProjectEvents } from "../mechanisms/projects.js";import type { SessionIndex, SessionOrigins } from "../mechanisms/sessions.js";import type { Errors, UsageRecording } from "../mechanisms/observability.js";import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";@@ -2349,8 +2348,7 @@ export class SessionsModule {@Use() private readonly traceIndex!: TraceIndex;@Use() private readonly traceStore!: TraceIndexStore;@Use(SandboxModule) private readonly sandbox!: Sandbox;- @Use() private readonly projectsRepo!: Projects;- @Use() private readonly membersRepo!: Members;+ @Use() private readonly projectEvents!: ProjectEvents;@Use() private readonly messagingRepo!: MessagingBindings;/** Company-mode caches: which organization owns a Session (read at every command spawn). */@Use() private readonly orgCache!: OrgCache;@@ -2429,17 +2427,8 @@ export class SessionsModule {}),};- const notifyProjectUsers = (projectId: string, event: ServerEvent): void => {- const ownerUserId = this.projectsRepo.findById(projectId)?.ownerUserId;- if (ownerUserId === undefined) return;- const audience = new Set([- ownerUserId,- ...this.membersRepo.list(projectId).map((m) => m.userId),- ]);- for (const userId of audience) {- channels.peek(userChannelKey(userId))?.publish(event, "server_event");- }- };+ const notifyProjectUsers = (projectId: string, event: ServerEvent): void =>+ this.projectEvents.notifyProjectUsers(projectId, event);const titles = this.titleGenerators.create({sessions: sessionsRepo,channels,@@ -2482,6 +2471,7 @@ export class SessionsModule {traceStore: this.traceStore,proxyEnv: env.proxyEnv,controlEnv: env.controlEnv,+ notifyProjectUsers,messagingChannel: (sessionId) => enabledMessagingChannel(this.messagingRepo, sessionId),// Company mode: which organization owns a Session, so development mode's list can hide// organization sessions and the company sidebar can group its own. The caches are adiff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex aa63a646..12893320 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -33,8 +33,8 @@ import {DEFAULT_COMMAND_POLICY_RULES,effectiveCommandPolicyRules,parseCommandPolicy,- parsePluginTable,- pluginTableToToml,+ parsePluginTables,+ pluginTablesToToml,GenerativeModel,canonicalClientType,listEndpointModels as coreListEndpointModels,@@ -53,7 +53,7 @@ import {} from "@prismshadow/penguin-core";import { providerInfo } from "@prismshadow/penguin-core/model-catalog";import type {- PluginTable,+ PluginTables,CommandPolicyRule,GenerativeModelConfig,LLMOutcome,@@ -802,21 +802,24 @@ export class ProjectConfigService implements ProjectConfigStore {return this.getCommandPolicy(projectId);}- /** The `[plugins]` table this Project asks for, in the file's order; empty when it asks for none. */- async getPlugins(projectId: string): Promise<PluginTable> {- return parsePluginTable((await this.readRaw(projectId)).plugins) ?? {};+ /**+ * The `[plugins]` key this Project writes: the shared table and each machine's own, in the+ * file's order; both empty when it asks for none.+ */+ async getPluginTables(projectId: string): Promise<PluginTables> {+ return parsePluginTables((await this.readRaw(projectId)).plugins) ?? { all: {}, machines: {} };}/**- * Replaces this Project's plugin table (a declarative PUT, validated at the route).+ * Replaces this Project's plugin tables (a declarative PUT, validated at the route).* Read-modify-write like setCommandPolicy, so every other key survives. An empty table is* written as an empty table rather than removed: "this Project asks for none" is a* decision, and a reader cannot tell it from "never configured" if the key vanishes.*/- async setPlugins(projectId: string, plugins: PluginTable): Promise<PluginTable> {+ async setPluginTables(projectId: string, tables: PluginTables): Promise<PluginTables> {const raw = await this.readRaw(projectId);- await this.writeRaw(projectId, { ...raw, plugins: pluginTableToToml(plugins) });- return this.getPlugins(projectId);+ await this.writeRaw(projectId, { ...raw, plugins: pluginTablesToToml(tables) });+ return this.getPluginTables(projectId);}/**diff --git a/packages/server/src/services/project-events.ts b/packages/server/src/services/project-events.tsnew file mode 100644index 00000000..01835a8f--- /dev/null+++ b/packages/server/src/services/project-events.ts@@ -0,0 +1,32 @@+/**+ * Everyone who can see a Project, told about an event — in ONE place.+ *+ * The audience is the rule ProjectAccess reads to answer "may this user see the Project":+ * the owner plus the members. Publishing is per user channel and only to a user who has+ * GET /api/events open (`peek`, never `get`): a channel opened here would be one nobody is+ * listening on. The session runtime, the title generator and the sessions route all+ * publish through this, so the audience rule is written once.+ */+import { Component, Use } from "@prismshadow/penguin-core/kernel";+import type { ServerEvent } from "../api/types.js";+import type { Channels } from "../hmr/capabilities.js";+import type { ChannelHub } from "../runtime/channel.js";+import { userChannelKey } from "../http/routes/events.js";+import type { Members, ProjectEvents, Projects } from "../mechanisms/projects.js";++@Component()+export class ProjectNotifier implements ProjectEvents {+ @Use() private readonly projects!: Projects;+ @Use() private readonly members!: Members;+ @Use() private readonly channels!: Channels;++ notifyProjectUsers(projectId: string, event: ServerEvent): void {+ const ownerUserId = this.projects.findById(projectId)?.ownerUserId;+ if (ownerUserId === undefined) return;+ const audience = new Set([ownerUserId, ...this.members.list(projectId).map((m) => m.userId)]);+ const channels = this.channels as ChannelHub;+ for (const userId of audience) {+ channels.peek(userChannelKey(userId))?.publish(event, "server_event");+ }+ }+}diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 862a84b7..08c70b85 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -29,6 +29,7 @@ import type {SessionInfo,SessionSandbox,SessionSource,+ ServerEvent,} from "../api/types.js";import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/errors.js";import { badRequest } from "../http/validate.js";@@ -152,6 +153,14 @@ export interface SessionServiceDeps {* this harness's own `penguin`, put in front of every command an Agent runs.*/pathPrepend?: () => string[];+ /**+ * Tells every user of a Project that a Session now exists. The list only ever learns+ * about rows it did not create itself from this: a Session started by the CLI, by+ * another tab, by a schedule, or by an agent spawning a child sat invisible until the+ * next full reload without it. Optional so the service keeps unit-testing without a+ * channel registry; absent means nobody is told.+ */+ notifyProjectUsers?: (projectId: string, event: ServerEvent) => void;/*** The channel of the Session's ENABLED messaging binding, or null when none is enabled* (SessionInfo.messagingChannel, the sidebar row's per-channel indicator — saved-but-@@ -598,7 +607,15 @@ export class SessionService {};this.deps.sessions.insert(row);this.deps.manager.adopt(row, session);-+ // After the insert: a reader who reacts by fetching the list must find the row there.+ const source = this.deps.sources.get(session.sessionId);+ this.deps.notifyProjectUsers?.(args.projectId, {+ type: "session_created",+ projectId: args.projectId,+ agentId: args.agentId,+ sessionId: row.sessionId,+ ...(source ? { source } : {}),+ });return this.toInfo(row, false);}diff --git a/packages/server/src/terminal/manager.ts b/packages/server/src/terminal/manager.tsindex cd2bb548..01099b50 100644--- a/packages/server/src/terminal/manager.ts+++ b/packages/server/src/terminal/manager.ts@@ -29,6 +29,7 @@ import { Hmr, ResourceGroups } from "../hmr/capabilities.js";import { terminalRoutes } from "./routes.js";import { identityFrom } from "./identity.js";import type { Auth } from "../mechanisms/identity.js";+import type { RemoteTerminals } from "../machines/terminal-relay.js";/** How long an exited session stays listable/attachable before it is disposed. */export const EXITED_SESSION_GRACE_MS = 5 * 60 * 1000;@@ -56,6 +57,12 @@ export class TerminalManager {graceMs?: number;/** Where a pushed bundle's node-pty assets live (hmr.assetsDir); absent falls back to the packaged require. */assets?: () => string | null;+ /**+ * A pty this manager does not hold — served elsewhere and named in the id — asked+ * after the local registry says no, so `get` answers for it in the shape the+ * runtime's owner check reads.+ */+ beyond?: (id: string) => TerminalSession | undefined;} = {},) {}@@ -205,7 +212,7 @@ export class TerminalManager {}get(id: string): TerminalSession | undefined {- return this.sessions.get(id);+ return this.sessions.get(id) ?? this.opts.beyond?.(id);}list(userId: string): TerminalSession[] {@@ -318,12 +325,15 @@ export class TerminalModule {@Use() private readonly hmr!: Hmr;@Use() private readonly resourceGroups!: ResourceGroups;@Use() private readonly auth!: Auth;+ /** Answers `get` for a pty on a machine (machines/terminal-relay.ts). */+ @Use() private readonly remote!: RemoteTerminals;@Provide() terminals!: Terminals;@Bind("TerminalModule.routes") routes!: ReturnType<typeof terminalRoutes>;setup({ resources, effect }: ClassCtx, context: Json) {const terminals = new TerminalManager(resources, {// A pushed bundle's node-pty binaries live where the host materialized them.assets: () => this.hmr.assetsDir() ?? null,+ beyond: (id) => this.remote.get(id),});// Shells started before this App existed are still running in the registry: claim// them back so a push is invisible to whoever was typing in one — unless their groupdiff --git a/packages/server/test/plugin-loader.test.ts b/packages/server/test/plugin-loader.test.tsindex 4984f90f..f9a94366 100644--- a/packages/server/test/plugin-loader.test.ts+++ b/packages/server/test/plugin-loader.test.ts@@ -125,6 +125,19 @@ describe("plugin list", () => {expect(await readProjectPluginList(root, "p1")).toEqual(["ok", "pinned", "tabled"]);});+ it("a machine runs the shared table plus its own, and no other machine's", async () => {+ // Keyed by the machine's own id, never an alias: a plugin listed for one machine is not+ // in any other machine's closure, so it is neither loaded nor installed there.+ await writeProject(+ "p1",+ 'models = []\n[plugins]\nshared = "*"\n\n[plugins.Mine000000000000]\nmine = "*"\n\n[plugins.Other00000000000]\nother = "*"\n',+ );+ expect(await readProjectPluginList(root, "p1", "Mine000000000000")).toEqual(["shared", "mine"]);+ expect(await readPluginClosure(root, "Other00000000000")).toEqual(["shared", "other"]);+ // A machine whose id is not known reads the shared table alone.+ expect(await readPluginClosure(root)).toEqual(["shared"]);+ });+it("the list form this key once had is not read: such a Project asks for none", async () => {// Deliberately no compatibility (PRFC-0010): a table replaced the list before release,// and a file still carrying the list starts with no plugins until it is written again.diff --git a/packages/server/test/plugins-installed.test.ts b/packages/server/test/plugins-installed.test.tsindex 74ead7d6..f141367b 100644--- a/packages/server/test/plugins-installed.test.ts+++ b/packages/server/test/plugins-installed.test.ts@@ -174,6 +174,74 @@ describe("installed plugins", () => {).toBe(403);});+ it("a plugin asked of another machine only is listed there, and neither installed nor loaded here", async () => {+ const other = "Other00000000000";+ // Of any machine, only what the build ships can be asked for.+ const refused = await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/not-shipped",+ machineId: other,+ });+ expect(refused.status).toBe(400);+ await ship({ name: "@acme/elsewhere", module: "Elsewhere" });+ const res = await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/elsewhere",+ machineId: other,+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as InstalledPluginsResponse;+ expect(body.plugins).toEqual([+ expect.objectContaining({+ specifier: "@acme/elsewhere",+ active: false,+ everywhere: false,+ machines: [other],+ here: false,+ }),+ ]);+ expect(body.plugins[0]!.error).toBeUndefined();+ expect(body.restartPending).toBe(false);+ expect(await fs.readFile(listFile(), "utf8")).toContain(+ `[plugins.${other}]\n"@acme/elsewhere" = "*"`,+ );++ // Removing it from that machine's table leaves the shared table alone.+ await ship({ name: "@acme/one", module: "One" });+ await admin.put("/api/projects/default_project/plugins/installed", { plugins: ["@acme/one"] });+ const removed = await admin.delete(+ `/api/projects/default_project/plugins/installed?specifier=@acme/elsewhere&machineId=${other}`,+ );+ expect(removed.status).toBe(200);+ expect((await view()).plugins.map((p) => [p.specifier, p.everywhere])).toEqual([+ ["@acme/one", true],+ ]);+ expect(+ (+ await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/one",+ machineId: "ssh:not-an-id",+ })+ ).status,+ ).toBe(400);+ });++ it("a plugin listed for this server's own id runs here", async () => {+ await ship({ name: "@acme/mine", module: "Mine" });+ const self = (await view()).machineId;+ const res = await admin.post("/api/projects/default_project/plugins/installed", {+ specifier: "@acme/mine",+ machineId: self,+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as InstalledPluginsResponse;+ expect(body.plugins[0]).toMatchObject({+ specifier: "@acme/mine",+ active: true,+ everywhere: false,+ machines: [self],+ here: true,+ });+ });+it("reports why a listed plugin failed to load, not a restart that would not help", async () => {// A shipped package that throws on import.await ship({diff --git a/packages/server/test/plugins-sync.test.ts b/packages/server/test/plugins-sync.test.tsindex c9790881..b3a8e996 100644--- a/packages/server/test/plugins-sync.test.ts+++ b/packages/server/test/plugins-sync.test.ts@@ -12,7 +12,17 @@ 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 } = {}) {+function fakeMachine(+ initial: Record<string, string[]>,+ opts: {+ restartPending?: boolean;+ shipped?: string[];+ /** Packages npm cannot fetch over there. */+ unfetchable?: string[];+ /** Rows that machine's own `[plugins.<id>]` tables add, per Project. */+ ownRows?: Record<string, string[]>;+ } = {},+) {const state = new Map(Object.entries(initial));const calls: { method: string; path: string; body?: unknown }[] = [];const body = (list: string[]): InstalledPluginsResponse => ({@@ -24,9 +34,13 @@ function fakeMachine(initial: Record<string, string[]>, opts: { restartPending?:modules: [],replaces: [],...(specifier.includes("not-there") ? { error: "not installed on this machine" } : {}),+ everywhere: true,+ machines: [],+ here: true,})),- shipped: [],+ shipped: opts.shipped ?? [],file: ".project_config.toml",+ machineId: "Theirs0000000000",restartPending: opts.restartPending === true,});const api: MachineApi = {@@ -44,15 +58,37 @@ function fakeMachine(initial: Record<string, string[]>, opts: { restartPending?:if (method === "PUT") {state.set(projectId, [...((payload as { plugins: string[] }).plugins ?? [])]);}- return { status: 200, text: JSON.stringify(body(state.get(projectId) ?? [])) };+ if (method === "POST") {+ const specifier = (payload as { specifier: string }).specifier;+ if (opts.unfetchable?.includes(specifier)) {+ return { status: 400, text: "npm: 404 Not Found" };+ }+ const name = specifier.replace(/(.)@.*$/, "$1");+ state.set(projectId, [...(state.get(projectId) ?? []), name]);+ }+ const reply = body(state.get(projectId) ?? []);+ for (const specifier of opts.ownRows?.[projectId] ?? []) {+ reply.plugins.push({+ specifier,+ active: true,+ builtin: false,+ modules: [],+ replaces: [],+ everywhere: false,+ machines: ["Theirs0000000000"],+ here: true,+ });+ }+ return { status: 200, text: JSON.stringify(reply) };},postBytes: async () => ({ status: 500, text: "unused" }),};return { api, calls, state };}-const local = (lists: Record<string, string[]>) => (projectId: string) =>- Promise.resolve(lists[projectId] ?? []);+const local =+ (lists: Record<string, (string | { name: string; version: string })[]>) => (projectId: string) =>+ Promise.resolve((lists[projectId] ?? []).map((p) => (typeof p === "string" ? { name: p } : p)));describe("syncPluginsToMachine", () => {it("writes what the Project asks for, and removes what the machine has beyond it", async () => {@@ -159,4 +195,54 @@ describe("syncPluginsToMachine", () => {expect(out.kind === "synced" && out.refused.map((r) => r.projectId)).toEqual(["p1"]);expect(m.state.get("p2")).toEqual(["@acme/two"]);});+ it("installs over there only what that machine is asked for and lacks, pinned as asked", async () => {+ // A plugin listed for other machines never reaches this one's loadLocal, so nothing+ // fetches it here; what does reach it is fetched by the machine's own POST.+ const m = fakeMachine({ p1: ["@acme/had"] });+ const out = await syncPluginsToMachine({+ api: m.api,+ loadLocal: local({ p1: ["@acme/had", { name: "@acme/new", version: "1.2.3" }] }),+ projects: ["p1"],+ });+ expect(m.calls.filter((c) => c.method === "POST").map((c) => c.body)).toEqual([+ { specifier: "@acme/[email protected]" },+ ]);+ expect(out.kind === "synced" && out.added).toEqual(["@acme/new"]);+ expect(m.state.get("p1")).toEqual(["@acme/had", "@acme/new"]);+ });++ it("lists a plugin the machine's build ships without a download", async () => {+ const m = fakeMachine({ p1: [] }, { shipped: ["@acme/builtin"] });+ await syncPluginsToMachine({+ api: m.api,+ loadLocal: local({ p1: ["@acme/builtin"] }),+ projects: ["p1"],+ });+ expect(m.calls.some((c) => c.method === "POST")).toBe(false);+ expect(m.state.get("p1")).toEqual(["@acme/builtin"]);+ });++ it("reports a package that machine cannot fetch and still delivers the rest", async () => {+ const m = fakeMachine({ p1: [] }, { unfetchable: ["@acme/gone"] });+ const out = await syncPluginsToMachine({+ api: m.api,+ loadLocal: local({ p1: ["@acme/gone", "@acme/ok"] }),+ projects: ["p1"],+ });+ expect(out.kind === "synced" && out.refused.map((r) => r.detail)).toEqual([+ "installing @acme/gone → 400: npm: 404 Not Found",+ ]);+ expect(m.state.get("p1")).toEqual(["@acme/ok"]);+ });++ it("leaves rows the machine's own tables add out of the comparison", async () => {+ const m = fakeMachine({ p1: ["@acme/same"] }, { ownRows: { p1: ["@acme/its-own"] } });+ const out = await syncPluginsToMachine({+ api: m.api,+ loadLocal: local({ p1: ["@acme/same"] }),+ projects: ["p1"],+ });+ expect(out.kind === "synced" && out.removed).toEqual([]);+ expect(m.calls.some((c) => c.method === "PUT")).toBe(false);+ });});diff --git a/packages/server/test/session-created-events.test.ts b/packages/server/test/session-created-events.test.tsnew file mode 100644index 00000000..bdb15d53--- /dev/null+++ b/packages/server/test/session-created-events.test.ts@@ -0,0 +1,109 @@+/**+ * `session_created` on the user channel: the list learns about rows it did not make.+ *+ * A Session created by the CLI, by another tab, by a schedule or by an agent spawning a+ * child went through the same route as one created from the list — and the list never+ * heard about it, because nothing announced it. `session_state` and `session_title` cannot+ * stand in: both act on a row the list already holds and ignore an unknown id. So this+ * event is the one thing that makes a Session appear without a reload, and the audience+ * rule is the same as for the state events: the Project's owner and members, nobody else.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type {+ ProjectCreateResponse,+ ServerEvent,+ SessionCreateResponse,+} from "../src/api/types.js";+import { userChannelKey } from "../src/http/routes/events.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** A client that has GET /api/events open: what the publish side checks for. */+function inbox(t: TestApp, userId: string): ServerEvent[] {+ const events: ServerEvent[] = [];+ t.deps.channels.get(userChannelKey(userId)).subscribe((evt) => {+ if (evt.event === "server_event") events.push(JSON.parse(evt.data) as ServerEvent);+ });+ return events;+}++const created = (events: ServerEvent[]) =>+ events.flatMap((e) => (e.type === "session_created" ? [e] : []));++describe("session_created on the user channel", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let projectId: string;+ let boxes: { owner: ServerEvent[]; member: ServerEvent[]; stranger: ServerEvent[] };++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner");+ await provisionUser(t.app, "member");+ await provisionUser(t.app, "stranger");+ owner = apiClient(t.app, a.cookie);+ const res = (await (+ await owner.post("/api/projects", { projectId: "owner-live", name: "project" })+ ).json()) as ProjectCreateResponse;+ projectId = res.project.projectId;+ await owner.post(`/api/projects/${projectId}/members`, { userId: "member" });+ await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],+ });+ boxes = {+ owner: inbox(t, "owner"),+ member: inbox(t, "member"),+ stranger: inbox(t, "stranger"),+ };+ });++ afterEach(async () => {+ await t.cleanup();+ });++ it("reaches the Project's owner and members with the new row's ids, and nobody else", async () => {+ const res = (await (+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})+ ).json()) as SessionCreateResponse;+ const sessionId = res.session.sessionId;++ for (const who of ["owner", "member"] as const) {+ const got = created(boxes[who]);+ expect(got, who).toHaveLength(1);+ expect(got[0]).toMatchObject({ projectId, agentId: "default_agent", sessionId });+ // A user-created Session has no source marker, on the row or in the event.+ expect(got[0]).not.toHaveProperty("source");+ }+ expect(created(boxes.stranger)).toHaveLength(0);+ });++ it("is published after the row is in place, so a reader who reloads on it finds the row", async () => {+ let seenAtPublish: boolean | null = null;+ t.deps.channels.get(userChannelKey("owner")).subscribe((evt) => {+ if (evt.event !== "server_event") return;+ const ev = JSON.parse(evt.data) as ServerEvent;+ if (ev.type === "session_created") {+ seenAtPublish = t.deps.sessionsRepo.findById(ev.sessionId) !== null;+ }+ });+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {});+ expect(seenAtPublish).toBe(true);+ });++ it("a title set by PATCH is announced too — the CLI's --title, another tab's rename", async () => {+ const res = (await (+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})+ ).json()) as SessionCreateResponse;+ const sessionId = res.session.sessionId;+ await owner.patch(`/api/sessions/${sessionId}`, { title: "made by the CLI" });+ const titles = (events: ServerEvent[]) =>+ events.flatMap((e) => (e.type === "session_title" ? [e] : []));+ for (const who of ["owner", "member"] as const) {+ expect(titles(boxes[who]), who).toEqual([+ { type: "session_title", sessionId, title: "made by the CLI" },+ ]);+ }+ expect(titles(boxes.stranger)).toHaveLength(0);+ });+});diff --git a/packages/server/test/terminal-relay.test.ts b/packages/server/test/terminal-relay.test.tsnew file mode 100644index 00000000..35437057--- /dev/null+++ b/packages/server/test/terminal-relay.test.ts@@ -0,0 +1,165 @@+/**+ * A pty on a machine is named in the terminal id (machines/terminal-relay.ts).+ *+ * The runtime serves one socket path and asks the platform for the session by id, so the+ * whole of "which machine, which pty, which user" has to fit in that id. Pinned: the spelling+ * round-trips, an ordinary id is never mistaken for a remote one, and the owner the runtime+ * checks is exactly the user the client named — which is what makes naming anyone else+ * refusable before the relay runs.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { EventEmitter, once } from "node:events";+import http from "node:http";+import type { AddressInfo } from "node:net";+import { WebSocketServer } from "ws";+import type { RawData, WebSocket as WsSocket } from "ws";+import {+ isRemoteTerminalRef,+ parseRemoteTerminalRef,+ relayTerminalStream,+} from "../src/machines/terminal-relay.js";++describe("remote terminal references", () => {+ it("parses <terminalId>@<machineId>@<userId>", () => {+ const ref = parseRemoteTerminalRef("t-1@AtZ2EEKC5jxZipMN@admin");+ expect(ref).toEqual({+ id: "t-1@AtZ2EEKC5jxZipMN@admin",+ ownerUserId: "admin",+ remote: { machineId: "AtZ2EEKC5jxZipMN", terminalId: "t-1" },+ });+ expect(isRemoteTerminalRef(ref!)).toBe(true);+ });++ it("is null for a plain local id, and for anything half-spelled", () => {+ expect(parseRemoteTerminalRef("6f4861fc-d64e-48d3-afad-89e1108e3e55")).toBeNull();+ expect(parseRemoteTerminalRef("t@m")).toBeNull();+ expect(parseRemoteTerminalRef("t@@u")).toBeNull();+ expect(parseRemoteTerminalRef("a@b@c@d")).toBeNull();+ });++ it("reads a percent-encoded separator too", () => {+ expect(parseRemoteTerminalRef("t%40m%40u")?.remote).toEqual({+ machineId: "m",+ terminalId: "t",+ });+ });+});++/**+ * The relay's own plumbing, against a real WebSocket server standing in for the machine.+ *+ * Both promises here are about the window between a viewer asking for a remote pty and the+ * machine's stream opening — a round trip through the held connection, during which the+ * viewer is free to go away or to type.+ */+describe("relaying a viewer to a machine's stream", () => {+ /** The viewer's end: enough of a ws socket for the relay, plus a way to drop it. */+ class FakeViewer extends EventEmitter {+ readonly CONNECTING = 0;+ readonly OPEN = 1;+ readyState = 1;+ bufferedAmount = 0;+ readonly received: string[] = [];+ closedWith: { code: number; reason: string } | null = null;++ send(data: RawData): void {+ this.received.push(data.toString());+ }++ close(code: number, reason: string): void {+ this.closedWith = { code, reason };+ this.readyState = 3;+ this.emit("close", code, Buffer.from(reason));+ }++ /** The browser going away — a pane closed, a reload, a dock reattaching. */+ drop(): void {+ this.readyState = 3;+ this.emit("close", 1001, Buffer.from("gone"));+ }+ }++ const ref = parseRemoteTerminalRef("t-1@m-1@admin")!;+ const url = new URL("http://localhost/api/terminals/t-1@m-1@admin/stream?cols=80&rows=24");++ let machine: WebSocketServer;+ let machinePort: number;+ /** Sockets the machine accepted, and every frame each of them was sent. */+ let accepted: { socket: WsSocket; frames: string[] }[];++ beforeEach(async () => {+ accepted = [];+ machine = new WebSocketServer({ host: "127.0.0.1", port: 0 });+ machine.on("connection", (socket) => {+ const entry = { socket, frames: [] as string[] };+ accepted.push(entry);+ socket.on("message", (data) => entry.frames.push(data.toString()));+ });+ await once(machine, "listening");+ machinePort = (machine.address() as AddressInfo).port;+ });++ afterEach(async () => {+ // Sockets a test left open first: close() waits for every client, and a relayed stream+ // stays up exactly as a real one would.+ for (const client of machine.clients) client.terminate();+ await new Promise<void>((resolve) => machine.close(() => resolve()));+ });++ const depsFor = (+ target: Promise<{ agent: http.Agent; port: number; cookie: string } | null>,+ ) => ({+ proxyTarget: () => target,+ isAdmin: () => true,+ });++ const settle = async (predicate: () => boolean): Promise<void> => {+ for (let attempt = 0; attempt < 100; attempt += 1) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ };++ it("dials nobody when the viewer left while the machine was being reached", async () => {+ const viewer = new FakeViewer();+ let reached: (t: { agent: http.Agent; port: number; cookie: string }) => void = () => undefined;+ const target = new Promise<{ agent: http.Agent; port: number; cookie: string }>((resolve) => {+ reached = resolve;+ });+ const relaying = relayTerminalStream(+ viewer as unknown as WsSocket,+ ref,+ url,+ depsFor(target),+ () => undefined,+ );+ // The pane closes first; the connection to the machine answers only afterwards.+ viewer.drop();+ reached({ agent: new http.Agent(), port: machinePort, cookie: "" });+ await relaying;+ await settle(() => accepted.length > 0);+ // Nothing was opened, so nothing is attached to a pty over there with no reader. Before+ // the viewer's close was listened to from the start, this left one stream per pane.+ expect(accepted).toHaveLength(0);+ });++ it("holds the frames typed before the machine's stream opened", async () => {+ const viewer = new FakeViewer();+ await relayTerminalStream(+ viewer as unknown as WsSocket,+ ref,+ url,+ depsFor(Promise.resolve({ agent: new http.Agent(), port: machinePort, cookie: "" })),+ () => undefined,+ );+ // The opening resize, sent while the handshake above is still in flight.+ viewer.emit("message", Buffer.from("resize 80x24"), true);+ await settle(() => (accepted[0]?.frames.length ?? 0) > 0);+ expect(accepted[0]?.frames).toEqual(["resize 80x24"]);++ // And the machine's output reaches the viewer once both ends are up.+ accepted[0]!.socket.send("hello");+ await settle(() => viewer.received.length > 0);+ expect(viewer.received).toEqual(["hello"]);+ });+});diff --git a/packages/web/src/api/client.ts b/packages/web/src/api/client.tsindex 67d4bf30..8cabdd11 100644--- a/packages/web/src/api/client.ts+++ b/packages/web/src/api/client.ts@@ -9,6 +9,7 @@*/import { S } from "../lib/strings";import { apiUrl } from "../lib/server-context";+import { machineForPath } from "../lib/session-machines";/** Unified API error: carries the HTTP status code and server error code (server error body {error:{code,message}}). */export class ApiError extends Error {@@ -44,9 +45,13 @@ export interface ApiFetchOptions {/** 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.+ * Which machine answers this call, when the caller knows and the path does not say.+ *+ * Omitted, a Session-scoped path routes itself to the machine that Session lives on (see+ * lib/session-machines.ts) and everything else stays here — the window never moves. Pass+ * `null` to force this server, or an id to send one request through that machine's+ * connection; browsing another machine's directories to pick a workspace on it, or asking+ * a machine for ITS Agents, are the calls that need it.*/server?: string | null;}@@ -74,9 +79,10 @@ export async function apiFetchWithMeta<T>(path: string,options: ApiFetchOptions = {},): Promise<{ data: T } & ApiFetchMeta> {- // 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);+ // Two routing rules, in order: an explicit `server` wins, otherwise a Session-scoped path+ // goes to the machine that Session lives on. Everything else stays here.+ const target = "server" in options ? (options.server ?? null) : machineForPath(path);+ let url = apiUrl(path, target);if (options.query) {const params = new URLSearchParams();for (const [key, value] of Object.entries(options.query)) {@@ -116,7 +122,7 @@ export async function apiFetchWithMeta<T>(// 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;+ const fromThisServer = target === null;if (response.status === 401 && fromThisServer && !isAuthEndpoint(path)) onUnauthorized?.();const retryAfter = response.headers.get("retry-after");const retryAfterSeconds =diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 21070ca6..503bbf54 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -217,6 +217,8 @@ import type {} from "@prismshadow/penguin-server/api";import type { MCPServerConfig } from "@prismshadow/penguin-core/interfaces";import { apiFetch, apiFetchWithMeta } from "./client";+import { machineForSession, rememberSessionMachine } from "../lib/session-machines";+import { apiUrl } from "../lib/server-context";// Auth & user -----------------------------------------------------------------@@ -268,19 +270,31 @@ export const adminDeleteUser = (userId: string) =>/** Server-global settings (admin only): currently the "use system HTTP proxy" switch. */export const adminGetSettings = () => apiFetch<ServerSettingsResponse>("/api/admin/settings");+/*+ * Plugin configuration is kept by each server in its own database, so `server` names the+ * machine whose settings are read or written — through this server's tunnel to it — and null+ * is this server's own. Nothing copies these values between machines.+ */+/** Every loaded plugin that declares a configuration, with its schema and masked values (admin). */-export const adminGetPluginConfig = () =>- apiFetch<PluginConfigResponse>("/api/admin/plugin-config");+export const adminGetPluginConfig = (server: string | null = null) =>+ apiFetch<PluginConfigResponse>("/api/admin/plugin-config", { server });/** One package's update (admin): omitted fields keep their value, a masked secret sent back keeps the stored one. */-export const adminPutPluginConfig = (body: PluginConfigUpdateRequest) =>- apiFetch<PluginConfigResponse>("/api/admin/plugin-config", { method: "PUT", body });+export const adminPutPluginConfig = (+ body: PluginConfigUpdateRequest,+ server: string | null = null,+) => apiFetch<PluginConfigResponse>("/api/admin/plugin-config", { method: "PUT", body, server });/** Runs one settings group's action (admin): what a deployment must DO on the machine, once. */-export const adminRunPluginConfigAction = (body: { name: string; action: string }) =>+export const adminRunPluginConfigAction = (+ body: { name: string; action: string },+ server: string | null = null,+) =>apiFetch<PluginConfigActionResponse>("/api/admin/plugin-config/action", {method: "POST",body,+ server,});/** Omitted fields keep their current value; applies immediately (no restart). */@@ -585,8 +599,15 @@ export const importMemoryScope = (// Agent & its configuration -----------------------------------------------------------------export const listAgents = (projectId: string) =>- apiFetch<AgentsResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents`);+/**+ * A project's Agents. With a machine, THAT machine's — Agents are per-server, so a Session+ * created on one can only name an Agent that exists there.+ */+export const listAgents = (projectId: string, machineId?: string | null) =>+ apiFetch<AgentsResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/agents`,+ machineId === undefined ? {} : { server: machineId },+ );export const createAgent = (projectId: string, body: AgentCreateRequest) =>apiFetch<AgentCreateResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents`, {@@ -651,6 +672,12 @@ export const listSessions = (/** The user's own rows only: an organization's desk, ticket and sub-sessions leave the page and the totals together (the development list's contract). */excludeOrg?: boolean;},+ /**+ * Which machine to ask. This path is NOT session-scoped, so nothing about it can be routed+ * from an id — it asks a server which Sessions IT has, and only the caller knows which+ * servers are worth asking. Omitted (or null) means this one.+ */+ machineId?: string | null,) => {const qs = opts? `?limit=${opts.limit}&offset=${opts.offset}` +@@ -661,6 +688,7 @@ export const listSessions = (: "";return apiFetch<SessionsResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/sessions${qs}`,+ { server: machineId ?? null },);};@@ -688,11 +716,31 @@ export const listDirectorySkills = (projectId: string, path: string) =>`/api/projects/${encodeURIComponent(projectId)}/dir-skills?path=${encodeURIComponent(path)}`,);-export const createSession = (projectId: string, agentId: string, body: SessionCreateRequest) =>- apiFetch<SessionCreateResponse>(+/**+ * Creates a Session on the machine that owns its workspace.+ *+ * The Session is created THERE because that is where its workspace is: that server runs the+ * agent, holds the messages, writes the trace. The id it hands back is recorded against that+ * machine, so every later call about the Session routes itself without any call site knowing+ * (see lib/session-machines.ts).+ *+ * `machineId` is the workspace's, not a preference — a path names a different directory on+ * every machine, so creating a Session for `/srv/app` on the wrong one is not a degraded+ * result, it is a different request.+ */+export const createSession = async (+ projectId: string,+ agentId: string,+ body: SessionCreateRequest,+ machineId?: string | null,+) => {+ const created = await apiFetch<SessionCreateResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/sessions`,- { method: "POST", body },+ { method: "POST", body, server: machineId ?? null },);+ rememberSessionMachine(created.session.sessionId, machineId ?? null);+ return created;+};export const forkSession = (sessionId: string, body: SessionForkRequest) =>apiFetch<SessionForkResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, {@@ -1025,10 +1073,15 @@ export const getAgentTraceEvents = (offset: number,limit: number,) =>+ // These name a Session without SAYING so in a way the routing rule can read: the rule is+ // over the path, and only `/api/sessions/<id>/…` declares its Session. So each of the three+ // Trace calls passes the owner explicitly — sent to this server instead, they asked about a+ // Session that lives on a machine, which truthfully has no such Trace file here, and the+ // panel reported the Trace as gone while it sat on the machine intact.apiFetch<TraceEventsResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +`/traces/${encodeURIComponent(sessionId)}/${index}`,- { query: { offset, limit } },+ { query: { offset, limit }, server: machineForSession(sessionId) },);export const getAgentTraceAnalysis = (@@ -1040,6 +1093,7 @@ export const getAgentTraceAnalysis = (apiFetch<TraceAnalysisResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +`/traces/${encodeURIComponent(sessionId)}/${index}/analysis`,+ { server: machineForSession(sessionId) },);/** Trace file download URL: the server sets Content-Disposition attachment, usable directly in <a download>. */@@ -1049,8 +1103,13 @@ export const agentTraceDownloadUrl = (sessionId: string,index: number,): string =>- `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +- `/traces/${encodeURIComponent(sessionId)}/${index}/download`;+ // A browser-followed URL, so the proxy prefix has to be IN it — there is no request here+ // for the routing rule to act on.+ apiUrl(+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` ++ `/traces/${encodeURIComponent(sessionId)}/${index}/download`,+ machineForSession(sessionId),+ );/** Imports a Trace JSONL file (owner only); the response says where the file landed (sessionId / index / date). */export const importAgentTrace = (projectId: string, agentId: string, body: TraceImportRequest) =>@@ -1167,8 +1226,22 @@ export const listWorkspaceFiles = (sessionId: string, path: string) =>apiFetch<WorkspaceFilesResponse>(`/api/sessions/${sessionId}/files`, { query: { path } });/** File content URL (inline preview / download=1 triggers download; usable directly in <a>/<img>/fetch). */+/**+ * File content URL (inline preview / download=1 triggers download; usable directly in+ * <a>/<img>/<iframe>/fetch).+ *+ * Routed like every other Session call, by hand: this is a URL, not a call, so it never+ * passes through the fetch wrapper that applies the rule (lib/session-machines.ts). Left+ * bare, every preview, image, PDF and download of a Session that lives on a machine asked+ * THIS server for a Session it does not have — and the workspace browser reports the+ * resulting failure as "preview not supported for this type", since a file it cannot read+ * is indistinguishable from one it cannot render.+ */export const workspaceFileUrl = (sessionId: string, path: string, download = false): string =>- `/api/sessions/${sessionId}/files/content?path=${encodeURIComponent(path)}${download ? "&download=1" : ""}`;+ apiUrl(+ `/api/sessions/${sessionId}/files/content?path=${encodeURIComponent(path)}${download ? "&download=1" : ""}`,+ machineForSession(sessionId),+ );/*** "Open in a new tab" for a Workspace html file: an App-origin link that mints a signed@@ -1380,13 +1453,26 @@ export const removeAgentSkill = (projectId: string, agentId: string, name: strin// Benchmarks sit at the Project level, beside agents rather than under one: a Benchmark can// evaluate many agents, so no agent id travels in these paths.-export const listBenchmarks = (projectId: string) =>- apiFetch<BenchmarksResponse>(`/api/projects/${encodeURIComponent(projectId)}/benchmarks`);+/**+ * A Project's Benchmarks as ONE server holds them. A `benchmarks/` directory is written on+ * whichever machine created or evaluated the Benchmark, so the Evaluation Center asks this+ * server and each machine it holds, then merges the answers (lib/benchmark-merge.ts). The path+ * is not Session-scoped, so nothing about it can be routed from an id — the machine is passed.+ */+export const listBenchmarks = (projectId: string, machineId?: string | null) =>+ apiFetch<BenchmarksResponse>(`/api/projects/${encodeURIComponent(projectId)}/benchmarks`, {+ server: machineId ?? null,+ });-export const listBenchmarkCases = (projectId: string, benchmarkId: string) =>+export const listBenchmarkCases = (+ projectId: string,+ benchmarkId: string,+ machineId?: string | null,+) =>apiFetch<BenchmarkCasesResponse>(`/api/projects/${encodeURIComponent(projectId)}/benchmarks/${encodeURIComponent(benchmarkId)}` +`/cases`,+ { server: machineId ?? null },);/** Creates a Benchmark by hand (owner only); the server writes the on-disk layout. 409 `benchmark_exists` on a taken id. */@@ -1419,12 +1505,11 @@ export const listBenchmarkCaseFiles = (caseId: string,path: string,material: CaseMaterial,+ machineId?: string | null,) =>apiFetch<WorkspaceFilesResponse>(benchmarkCaseFilesPath(projectId, benchmarkId, caseId, material),- {- query: { path },- },+ { query: { path }, server: machineId ?? null },);export const benchmarkCaseFileUrl = (@@ -1433,7 +1518,7 @@ export const benchmarkCaseFileUrl = (caseId: string,path: string,material: CaseMaterial,- options?: { download?: boolean; preview?: boolean },+ options?: { download?: boolean; preview?: boolean; machineId?: string | null },): string => {const base = `${benchmarkCaseFilesPath(projectId,@@ -1442,7 +1527,9 @@ export const benchmarkCaseFileUrl = (material,)}/content?path=${encodeURIComponent(path)}`;return (- base ++ // A browser-followed URL (an <img> src, a download link), so the proxy prefix has to be+ // IN it — there is no request here for a routing rule to act on.+ apiUrl(base, options?.machineId ?? null) +(options?.download ? "&download=1" : "") +(options?.preview && !options.download ? "&preview=1" : ""));@@ -1920,17 +2007,34 @@ export const setDesktopTray = (patch: DesktopTrayPatch) =>// ---- Workflows (an Agent's own extension packages, served as tabs beside the chat) ----const workflowsBase = (projectId: string, agentId: string) =>`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/workflows`;-export const getWorkflows = (projectId: string, agentId: string) =>- apiFetch<{ workflows: WorkflowInfo[] }>(workflowsBase(projectId, agentId));+/**+ * `machineId` on each of these: an Agent's workflows live where its state directory does, so+ * the workflows of an Agent that only a machine has are asked of THAT machine's server.+ */+export const getWorkflows = (projectId: string, agentId: string, machineId: string | null = null) =>+ apiFetch<{ workflows: WorkflowInfo[] }>(workflowsBase(projectId, agentId), {+ server: machineId,+ });/** Re-import the folder now (the server also does this whenever a file changes). */-export const reloadWorkflow = (projectId: string, agentId: string, workflowId: string) =>+export const reloadWorkflow = (+ projectId: string,+ agentId: string,+ workflowId: string,+ machineId: string | null = null,+) =>apiFetch<{ workflow: WorkflowInfo }>(`${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}/reload`,- { method: "POST", body: {} },+ { method: "POST", body: {}, server: machineId },);-export const getWorkflowHistory = (projectId: string, agentId: string, workflowId: string) =>+export const getWorkflowHistory = (+ projectId: string,+ agentId: string,+ workflowId: string,+ machineId: string | null = null,+) =>apiFetch<{ versions: WorkflowVersion[] }>(`${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}/history`,+ { server: machineId },);/** Restore a recorded version's files (state.json is kept) and reload. */export const rollbackWorkflow = (@@ -1938,15 +2042,22 @@ export const rollbackWorkflow = (agentId: string,workflowId: string,revision: string,+ machineId: string | null = null,) =>apiFetch<{ workflow: WorkflowInfo }>(`${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}/rollback`,- { method: "POST", body: { revision } },+ { method: "POST", body: { revision }, server: machineId },);/** Delete the folder and the versions recorded for it; nothing of the workflow is kept. */-export const removeWorkflow = (projectId: string, agentId: string, workflowId: string) =>+export const removeWorkflow = (+ projectId: string,+ agentId: string,+ workflowId: string,+ machineId: string | null = null,+) =>apiFetch<void>(`${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}`, {method: "DELETE",+ server: machineId,});// ---- The plugins a Project asks for, and the confinement agent commands run under ----@@ -1957,8 +2068,12 @@ export const removeWorkflow = (projectId: string, agentId: string, workflowId: s*/const pluginsPath = (projectId: string) =>`/api/projects/${encodeURIComponent(projectId)}/plugins/installed`;-export const getInstalledPlugins = (projectId: string) =>- apiFetch<InstalledPluginsResponse>(pluginsPath(projectId));+/**+ * `server` reads a machine's own list through this server's tunnel — what it actually runs —+ * and null reads this server's, which holds the Project's tables for the whole fleet.+ */+export const getInstalledPlugins = (projectId: string, server: string | null = null) =>+ apiFetch<InstalledPluginsResponse>(pluginsPath(projectId), { server });/** Admin only; applied without a restart where the runtime can re-assemble the App. */export const putInstalledPlugins = (projectId: string, plugins: readonly string[]) =>apiFetch<InstalledPluginsResponse>(pluginsPath(projectId), {@@ -1966,17 +2081,31 @@ export const putInstalledPlugins = (projectId: string, plugins: readonly string[body: { plugins },});/**- * Admin only: asks this Project for a plugin the build ships — refused for one it does not,- * so the list never names a package that is not on the machine — then re-assembles the App.+ * Admin only: asks this Project for a plugin the build ships — in the shared table, or with+ * `machineId` in that machine's own table — refused for one it does not, so the list never+ * names a package that is not on the machine; then re-assembles the App where it runs here.*/-export const installPlugin = (projectId: string, specifier: string) =>+export const installPlugin = (+ projectId: string,+ specifier: string,+ machineId: string | null = null,+) =>apiFetch<InstalledPluginsResponse>(pluginsPath(projectId), {method: "POST",- body: { specifier },+ body: machineId === null ? { specifier } : { specifier, machineId },});-/** Admin only: drops it from this Project's list and re-assembles the App; nothing on disk changes. */-export const uninstallPlugin = (projectId: string, specifier: string) =>+/**+ * Admin only: drops it from every table of this Project, or with `machineId` from that+ * machine's own table; nothing on disk changes.+ */+export const uninstallPlugin = (+ projectId: string,+ specifier: string,+ machineId: string | null = null,+) =>apiFetch<InstalledPluginsResponse>(- `${pluginsPath(projectId)}?specifier=${encodeURIComponent(specifier)}`,+ `${pluginsPath(projectId)}?specifier=${encodeURIComponent(specifier)}${+ machineId === null ? "" : `&machineId=${encodeURIComponent(machineId)}`+ }`,{ method: "DELETE" },);diff --git a/packages/web/src/api/sse.ts b/packages/web/src/api/sse.tsindex c05bdbf0..bbe6c564 100644--- a/packages/web/src/api/sse.ts+++ b/packages/web/src/api/sse.ts@@ -13,6 +13,8 @@*/import type { OmniMessage } from "@prismshadow/penguin-core/omnimessage";import type { ServerEvent } from "@prismshadow/penguin-server/api";+import { apiUrl } from "../lib/server-context";+import { machineForSession } from "../lib/session-machines";export interface StreamHandlers {/**@@ -63,10 +65,20 @@ function subscribe(url: string, handlers: StreamHandlers): StreamConnection {/** Subscribes to a Session's output stream (GET /api/sessions/:sessionId/stream). */export function openSessionStream(sessionId: string, handlers: StreamHandlers): StreamConnection {- return subscribe(`/api/sessions/${encodeURIComponent(sessionId)}/stream`, handlers);+ // Routed like every other Session call: the stream comes from the machine running it.+ const path = `/api/sessions/${encodeURIComponent(sessionId)}/stream`;+ return subscribe(apiUrl(path, machineForSession(sessionId)), handlers);}-/** Subscribes to the user-level server event stream (GET /api/events; reserved for scheduled-task notifications). */-export function openUserEvents(handlers: StreamHandlers): StreamConnection {- return subscribe("/api/events", handlers);+/**+ * Subscribes to the user-level server event stream (GET /api/events) — this server's, or a+ * machine's through the same-origin proxy. A Session on a machine changes state on THAT+ * machine's server, and only its stream says so; the list is assembled from every connected+ * machine, so its liveness has to be too.+ */+export function openUserEvents(+ handlers: StreamHandlers,+ machineId: string | null = null,+): StreamConnection {+ return subscribe(apiUrl("/api/events", machineId), handlers);}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex aab71079..3c9b5f2d 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -80,6 +80,8 @@ import {workspaceLabel,} from "../../lib/session-grouping";import type { FolderCategory, SessionPartition } from "../../lib/session-grouping";+import { machineForSession } from "../../lib/session-machines";+import { nameOnMachine } from "../../lib/workspace-machines";import {initialNavGroupCollapsed,navKeysFor,@@ -399,6 +401,7 @@ export function Sidebar({countsByAgent,workspaceCountsByAgent,workspaceLatestByAgent,+ machineLabels,isLoadedFor,hasMoreFor,loadMoreFor,@@ -512,12 +515,16 @@ export function Sidebar({const [registeredWorkspaces, setRegisteredWorkspaces] = useState<readonly WorkspaceEntry[]>(() =>loadWorkspaceRegistry(currentProjectId),);- /** Registered Workspace being renamed (alias edit; null = none) and the alias being typed. */- const [renamingWorkspace, setRenamingWorkspace] = useState<{ path: string } | null>(null);+ /** Registered Workspace being renamed (alias edit; null = none) and the alias being typed. The machine is half of which directory this is. */+ const [renamingWorkspace, setRenamingWorkspace] = useState<{+ path: string;+ machineId: string | null;+ } | null>(null);const [workspaceAliasText, setWorkspaceAliasText] = useState("");/** Registered Workspace pending removal confirmation (null = none); label = the group's displayed name for the confirm copy. */const [deletingWorkspace, setDeletingWorkspace] = useState<{path: string;+ machineId: string | null;label: string;} | null>(null);/** Live title search: the input's visibility and its query (transient — never persisted). */@@ -629,7 +636,9 @@ export function Sidebar({() =>mergeRegisteredWorkspaces(completeWorkspaceGroups(- groupSessionsByWorkspace(sessions),+ // A Workspace is a directory on a machine: rows from two machines that share a path+ // string are two groups, and the "+" of each opens a chat on its own machine.+ groupSessionsByWorkspace(sessions, (s) => machineForSession(s.sessionId)),workspaceGroupCounts,workspaceGroupLatest,),@@ -712,7 +721,7 @@ export function Sidebar({? s.agentId: groupMode === "time"? TIME_FOLDERS_GROUP_KEY- : workspaceGroupKey(s.workspace);+ : workspaceGroupKey(s.workspace, machineForSession(s.sessionId));/*** Collapse/expand a group. A folder-only group flips the OTHER set: it is collapsed by@@ -1047,7 +1056,7 @@ export function Sidebar({? s.agentId: groupMode === "time"? TIME_FOLDERS_GROUP_KEY- : workspaceGroupKey(s.workspace);+ : workspaceGroupKey(s.workspace, machineForSession(s.sessionId));const key = folderKey(groupKey, category);setOpenFolders((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));// Same on-demand load a click-expand does, for this Session's own Agent (siblings of@@ -1203,7 +1212,11 @@ export function Sidebar({* pinned "New chat" and the header's create button name nothing. Every field left unnamed* starts on the Project's new-chat defaults, then the built-in fallback (new-chat.ts).*/- const newChat = ({ agentId, workspace }: { agentId?: string; workspace?: string } = {}) => {+ const newChat = ({+ agentId,+ workspace,+ machineId,+ }: { agentId?: string; workspace?: string; machineId?: string } = {}) => {// Typed-but-unsent text in the ACTIVE new-chat draft becomes a parked draft// conversation first (a row in the list below, sendable anytime — draft-sessions.ts),// so this click always lands on an empty composer and never silently shelves content;@@ -1212,7 +1225,10 @@ export function Sidebar({if (agentId) setCurrentAgentId(agentId);const state = {...(agentId ? { agentId } : {}),- ...(workspace !== undefined ? { workspace } : {}),+ // The machine travels WITH the path, always — including its absence. A path names a+ // different directory on every machine, so handing the composer one without the other+ // is handing it a directory it cannot find.+ ...(workspace !== undefined ? { workspace, machineId } : {}),};navigate(`/chat/${DRAFT_SESSION_ID}`, Object.keys(state).length > 0 ? { state } : undefined);onNavigate?.();@@ -1255,28 +1271,44 @@ export function Sidebar({const next = registerWorkspace(registeredWorkspaces, path, machineId ?? undefined);if (next === registeredWorkspaces) return;applyRegistryChange(next);- const key = workspaceGroupKey(path);+ const key = workspaceGroupKey(path, machineId ?? null);const existing = orderedWorkspaceGroups.findIndex((g) => g.key === key);setGroupPage(groupPageOf(existing >= 0 ? existing : orderedWorkspaceGroups.length));};- /** Paths with a registry entry — only their groups offer the rename/remove overflow. */- const registeredPaths = useMemo(- () => new Set(registeredWorkspaces.map((e) => e.path)),+ /**+ * The ssh alias of a group's machine, or null for this server's own groups — what a name+ * is qualified with. An unlabelled machine (the list is admin-only, and a machine can also+ * drop out of the ssh config) falls back to its id: honest, where inventing a name is not.+ */+ const machineNameOf = (machineId: string | null): string | null =>+ machineId === null ? null : (machineLabels.get(machineId) ?? machineId);++ /** Registered Workspaces by GROUP key — only their groups offer the rename/remove overflow. */+ const registeredKeys = useMemo(+ () => new Set(registeredWorkspaces.map((e) => workspaceGroupKey(e.path, e.machineId ?? null))),[registeredWorkspaces],);/** Open the alias editor pre-filled with the current alias ("" = following the basename). */- const openRenameWorkspace = (path: string) => {- setWorkspaceAliasText(registeredWorkspaces.find((e) => e.path === path)?.alias ?? "");- setRenamingWorkspace({ path });+ const openRenameWorkspace = (path: string, machineId: string | null) => {+ setWorkspaceAliasText(+ registeredWorkspaces.find((e) => e.path === path && (e.machineId ?? null) === machineId)+ ?.alias ?? "",+ );+ setRenamingWorkspace({ path, machineId });};/** Commit the alias (blank reverts the label to the directory basename). Direct save — no server, nothing destructive. */const confirmRenameWorkspace = () => {if (!renamingWorkspace) return;applyRegistryChange(- setWorkspaceAlias(registeredWorkspaces, renamingWorkspace.path, workspaceAliasText),+ setWorkspaceAlias(+ registeredWorkspaces,+ renamingWorkspace.path,+ renamingWorkspace.machineId,+ workspaceAliasText,+ ),);setRenamingWorkspace(null);};@@ -1289,7 +1321,13 @@ export function Sidebar({*/const confirmDeleteWorkspace = () => {if (!deletingWorkspace) return;- applyRegistryChange(unregisterWorkspace(registeredWorkspaces, deletingWorkspace.path));+ applyRegistryChange(+ unregisterWorkspace(+ registeredWorkspaces,+ deletingWorkspace.path,+ deletingWorkspace.machineId,+ ),+ );setDeletingWorkspace(null);};@@ -2354,13 +2392,21 @@ export function Sidebar({* sentence that says what the dimmed header and its count mean, which carries that* same path inside it.*/+ const qualifiedPath =+ group.fullPath !== null+ ? nameOnMachine(group.fullPath, machineNameOf(group.machineId))+ : null;const headerTitle =foldedOnly === undefined- ? group.fullPath- : S.chat.folderOnlyGroup(foldedOnly, group.fullPath ?? undefined);+ ? qualifiedPath+ : S.chat.folderOnlyGroup(foldedOnly, qualifiedPath ?? undefined);const drag = groupDragProps(group.key, workspaceGroupSequence);/** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */const counts = workspaceGroupCounts.get(group.key);+ /** Read once so the registry actions below keep the narrowing (null = the merged temp group, which has no single path). */+ const fullPath = group.fullPath;+ /** The ssh alias qualifying this group's names, or null when it is on this server. */+ const machineName = machineNameOf(group.machineId);const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];const agentsFor = (category: SessionCategory) => [...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),@@ -2385,7 +2431,10 @@ export function Sidebar({/></span>}- label={group.temp ? S.chat.tempWorkspaces : group.label}+ label={nameOnMachine(+ group.temp ? S.chat.tempWorkspaces : group.label,+ machineName,+ )}count={foldedOnly !== undefined? foldedOnly@@ -2403,19 +2452,30 @@ export function Sidebar({type="button"title={S.chat.newSessionInWorkspace}aria-label={S.chat.newSessionInWorkspace}- onClick={() => newChat({ workspace: group.fullPath ?? "" })}+ onClick={() =>+ newChat({+ workspace: fullPath ?? "",+ // The machine travels with the path: this group's rows live on it,+ // and the same path here is a different directory (or none).+ ...(group.machineId ? { machineId: group.machineId } : {}),+ })+ }className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"><Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} /></button>{/* Manually-added (registry-backed) Workspaces only: rename-alias /- remove-from-sidebar overflow, to the right of the "+" (session-- derived groups have no registry entry for these to act on). */}- {registeredPaths.has(group.key) && (+ remove-from-sidebar overflow, to the right of the "+" (session-+ derived groups have no registry entry for these to act on). */}+ {fullPath !== null && registeredKeys.has(group.key) && (<GroupOverflowMenu- onRename={() => openRenameWorkspace(group.key)}+ onRename={() => openRenameWorkspace(fullPath, group.machineId)}onDelete={() =>- setDeletingWorkspace({ path: group.key, label: group.label })+ setDeletingWorkspace({+ path: fullPath,+ machineId: group.machineId,+ label: group.label,+ })}/>)}diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsxindex 991104cb..866a36d9 100644--- a/packages/web/src/features/agents/agents-page.tsx+++ b/packages/web/src/features/agents/agents-page.tsx@@ -78,6 +78,9 @@ import type { PickableItem } from "../skills/skill-pick-list";import { addSkillNames, removeSkillNames, toggleSkillName } from "../skills/skill-selection";import { ICON_SIZE } from "../../lib/icon-scale";import { AiCreateModal, CreateButtons } from "../ai-create";+import { mergeAgents } from "../../lib/benchmark-merge";+import type { AgentSource } from "../../lib/benchmark-merge";+import { useSessions } from "../../state/sessions";/** Built-in Agent shipped with every Project (default_agent only; the server also rejects deletion, so no delete entry point is shown here). */const BUILTIN_AGENT_IDS = new Set(["default_agent"]);@@ -127,17 +130,16 @@ export function AgentsPage() {const { locale } = useLocale();const { user } = useAuth();const { currentProject, agents, agentsLoading, reloadAgents, setCurrentAgentId } = useProject();+ /**+ * An Agent belongs to the Project, but its state directory is created on whichever machine it+ * has run on — so one that has only ever run over there exists only over there, and a list+ * built from this server alone does not have it at all.+ */+ const { machineIds, machineLabels } = useSessions();+ const [machineAgents, setMachineAgents] = useState<AgentSource[]>([]);+ const machinesKey = [...machineIds].join(",");/** Header search, the Models page's shape: name, id and description, case-insensitive. */const [query, setQuery] = useState("");- const shownAgents = useMemo(() => {- const needle = query.trim().toLowerCase();- if (needle === "") return agents;- return agents.filter((a) =>- [agentDisplayName(a), a.agentId, a.description ?? ""].some((field) =>- field.toLowerCase().includes(needle),- ),- );- }, [agents, query]);/** The kernel trail's raised badge, or undefined — the notice under the title acts on it or clears it. */const kernelTodo = useUpdateBadges().todos.agents;/** The bulk kernel update's confirmation is open. */@@ -338,6 +340,27 @@ export function AgentsPage() {}};+ useEffect(() => {+ setMachineAgents([]);+ if (!projectId || machinesKey === "") return;+ let cancelled = false;+ void Promise.allSettled(+ machinesKey.split(",").map(async (machineId) => ({+ machineId,+ agents: (await api.listAgents(projectId, machineId)).agents,+ })),+ ).then((answers) => {+ // A machine that cannot answer contributes no Agents, which is what not reading it+ // means; this server's own list still stands on its own.+ if (!cancelled) {+ setMachineAgents(answers.flatMap((a) => (a.status === "fulfilled" ? [a.value] : [])));+ }+ });+ return () => {+ cancelled = true;+ };+ }, [projectId, machinesKey]);+/*** "New Chat": enters draft state (same as sidebar group header) — the Session is only* actually created when the first message is sent. agentId travels via route state: when the@@ -345,14 +368,43 @@ export function AgentsPage() {* overrides it, ensuring that clicking "New Chat" on a given card always lands on that Agent* rather than the previous one from the cache.*/- const newChat = (agentId: string) => {+ const newChat = (agentId: string, machineId: string | null = null) => {// Typed-but-unsent draft text becomes a parked draft conversation first, and every field// but the Agent starts on the Project's new-chat defaults (new-chat.ts).if (user && projectId) prepareNewChatDraft(user.userId, projectId);- setCurrentAgentId(agentId);- navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });+ // The current Agent is one of THIS server's. An id that only a machine has matches none of+ // them, and the chat page renders nothing — the draft included — until there is a current+ // Agent, so naming one here left a placeholder that never resolved. The draft takes a+ // machine's Agent from the route state below, and validates it against that machine's list.+ if (machineId === null) setCurrentAgentId(agentId);+ navigate(`/chat/${DRAFT_SESSION_ID}`, {+ // An Agent that lives on a machine runs there: the draft is handed that machine with an+ // empty Workspace, which is the temporary workspace ON it. The draft applies a machine+ // only together with a path, since a machine without one would send the Session to a+ // machine the chosen path is not on.+ state: machineId === null ? { agentId } : { agentId, workspace: "", machineId },+ });};+ /** The ssh alias of a machine, or null for this server; an unlabelled machine falls back to its id. */+ const machineNameOf = (machineId: string | null): string | null =>+ machineId === null ? null : (machineLabels.get(machineId) ?? machineId);++ /** Every Agent of the Project, wherever its state directory is, this server's described first. */+ const mergedAgents = useMemo(+ () => mergeAgents([{ machineId: null, agents }, ...machineAgents]),+ [agents, machineAgents],+ );+ const shownAgents = useMemo(() => {+ const needle = query.trim().toLowerCase();+ if (needle === "") return mergedAgents;+ return mergedAgents.filter(({ agent: a }) =>+ [agentDisplayName(a), a.agentId, a.description ?? ""].some((field) =>+ field.toLowerCase().includes(needle),+ ),+ );+ }, [mergedAgents, query]);+/*** Stat icon click: same navigation as the "Settings" button plus `?tab=` so the settings* page lands directly on the matching tab (unknown keys fall back to Overview there, so@@ -494,8 +546,15 @@ export function AgentsPage() {compressed to two lines of text (name line + combined description/stats line) tominimize row height */<div className="space-y-3">- {shownAgents.map((a) => {+ {shownAgents.map(({ agent: a, machineIds: on }) => {const builtin = BUILTIN_AGENT_IDS.has(a.agentId);+ // An Agent this server does not have: everything below reads and writes its state+ // directory, which is on the machine. Its name says where it is, its New chat opens+ // there, and the rest is inert rather than answering 404 from here.+ const machineName = on.includes(null) ? null : machineNameOf(on[0] ?? null);+ const elsewhere = machineName !== null;+ const elsewhereTitle =+ machineName === null ? "" : S.agent.livesOnMachine(machineName);return (<divkey={a.agentId}@@ -518,6 +577,14 @@ export function AgentsPage() {<span className="min-w-0 truncate text-base font-bold">{agentDisplayName(a)}</span>+ {machineName !== null && (+ <span+ className="shrink-0 font-mono text-[11px] normal-case text-gray-400 dark:text-gray-500"+ title={elsewhereTitle}+ >+ {S.chat.machineTag(machineName)}+ </span>+ )}<span className="hidden shrink-0 font-mono text-xs text-gray-400 md:inline dark:text-gray-500">{a.agentId}</span>@@ -560,6 +627,7 @@ export function AgentsPage() {<buttontype="button"className={STAT_LINK_CLASS}+ disabled={elsewhere}title={S.agent.toolCount(a.toolCount)}aria-label={S.agent.toolCount(a.toolCount)}onClick={() => openSettingsTab(a.agentId, "tools")}@@ -570,6 +638,7 @@ export function AgentsPage() {<buttontype="button"className={STAT_LINK_CLASS}+ disabled={elsewhere}title={S.skills.skillCount(a.skillCount)}aria-label={S.skills.skillCount(a.skillCount)}onClick={() => openSettingsTab(a.agentId, "skills")}@@ -580,6 +649,7 @@ export function AgentsPage() {<buttontype="button"className={STAT_LINK_CLASS}+ disabled={elsewhere}title={S.hooks.hookCount(a.hookCount)}aria-label={S.hooks.hookCount(a.hookCount)}onClick={() => openSettingsTab(a.agentId, "hooks")}@@ -590,6 +660,7 @@ export function AgentsPage() {<buttontype="button"className={STAT_LINK_CLASS}+ disabled={elsewhere}title={S.agent.memoryCount(a.memoryCount)}aria-label={S.agent.memoryCount(a.memoryCount)}onClick={() => openSettingsTab(a.agentId, "memory")}@@ -600,6 +671,7 @@ export function AgentsPage() {<buttontype="button"className={STAT_LINK_CLASS}+ disabled={elsewhere}title={S.agent.vaultKeyCount(a.vaultKeyCount)}aria-label={S.agent.vaultKeyCount(a.vaultKeyCount)}onClick={() => openSettingsTab(a.agentId, "vault")}@@ -610,6 +682,7 @@ export function AgentsPage() {<buttontype="button"className={STAT_LINK_CLASS}+ disabled={elsewhere}title={S.agent.scheduleCount(a.scheduleCount)}aria-label={S.agent.scheduleCount(a.scheduleCount)}onClick={() => openSettingsTab(a.agentId, "schedules")}@@ -636,12 +709,18 @@ export function AgentsPage() {{/* Button group to the right of the sparkline: "New Chat" shows text, the rest are square icon buttons (tooltip shows the full name) */}<div className="flex shrink-0 items-center gap-2">- <Button size="sm" variant="primary" onClick={() => newChat(a.agentId)}>+ <Button+ size="sm"+ variant="primary"+ onClick={() => newChat(a.agentId, on.includes(null) ? null : (on[0] ?? null))}+ ><GlyphIcon d={CARD_ICONS.newChat} />{S.chat.newSessionMenu}</Button><Buttonsize="sm"+ disabled={elsewhere}+ {...(elsewhere ? { title: elsewhereTitle } : {})}onClick={() => {setCurrentAgentId(a.agentId);navigate(`/agents/${a.agentId}`);@@ -652,8 +731,9 @@ export function AgentsPage() {</Button><Buttonsize="icon"- title={S.nav.usage}+ title={elsewhere ? elsewhereTitle : S.nav.usage}aria-label={S.nav.usage}+ disabled={elsewhere}onClick={() => navigate(`/usage?agentId=${encodeURIComponent(a.agentId)}`)}><GlyphIcon@@ -679,8 +759,9 @@ export function AgentsPage() {<Buttonsize="icon"variant="danger"- title={S.agent.deleteAgent}+ title={elsewhere ? elsewhereTitle : S.agent.deleteAgent}aria-label={S.agent.deleteAgent}+ disabled={elsewhere}onClick={() =>setDeleting({ agentId: a.agentId, name: agentDisplayName(a) })}diff --git a/packages/web/src/features/benchmark/benchmark-case-browser.tsx b/packages/web/src/features/benchmark/benchmark-case-browser.tsxindex ed86d7a9..de3619fd 100644--- a/packages/web/src/features/benchmark/benchmark-case-browser.tsx+++ b/packages/web/src/features/benchmark/benchmark-case-browser.tsx@@ -135,9 +135,16 @@ interface Props {projectId: string;benchmarkId: string;caseSummary: BenchmarkCaseSummary;+ /**+ * The machine whose disk holds this Case's files; null for this server. A Benchmark's Cases+ * can be read off any machine that has them, and the listing this browser was opened from+ * recorded which one — asking a different server for the same path is asking about a+ * directory it may not have.+ */+ machineId: string | null;}-export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary }: Props) {+export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary, machineId }: Props) {const { locale } = useLocale();/** Listings by tree path; a missing key means "not fetched yet". */const [listings, setListings] = useState<Listings>(() => new Map());@@ -160,8 +167,11 @@ export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary }: PrfilePath: string,options?: { download?: boolean; preview?: boolean },) =>- api.benchmarkCaseFileUrl(projectId, benchmarkId, caseSummary.id, filePath, material, options),- [projectId, benchmarkId, caseSummary.id],+ api.benchmarkCaseFileUrl(projectId, benchmarkId, caseSummary.id, filePath, material, {+ ...options,+ machineId,+ }),+ [projectId, benchmarkId, caseSummary.id, machineId],);/**@@ -182,6 +192,7 @@ export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary }: PrcaseSummary.id,path,material,+ machineId,);if (!current()) return null;setListings((m) => new Map(m).set(treePath, res.entries));@@ -201,7 +212,7 @@ export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary }: Pr}}},- [projectId, benchmarkId, caseSummary.id],+ [projectId, benchmarkId, caseSummary.id, machineId],);/** Opens a file in the preview pane: the text kinds are read, the rest are served by URL. */@@ -254,7 +265,7 @@ export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary }: Pr// The request counters are deliberately not reset: a listing still in flight for the case// being left would otherwise match the new case's first request and land in its tree.readmeOpened.current = false;- }, [projectId, benchmarkId, caseSummary.id]);+ }, [projectId, benchmarkId, caseSummary.id, machineId]);useEffect(() => {void loadDir("rubric");diff --git a/packages/web/src/features/benchmark/benchmark-detail-page.tsx b/packages/web/src/features/benchmark/benchmark-detail-page.tsxindex ce765d9c..e4c418d4 100644--- a/packages/web/src/features/benchmark/benchmark-detail-page.tsx+++ b/packages/web/src/features/benchmark/benchmark-detail-page.tsx@@ -7,8 +7,11 @@*/import { useEffect, useState } from "react";import { useNavigate, useParams } from "react-router";-import type { BenchmarkSummary, ModelsResponse } from "@prismshadow/penguin-server/api";+import type { ModelsResponse } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";+import type { MergedBenchmark } from "../../lib/benchmark-merge";+import { nameOnMachine } from "../../lib/workspace-machines";+import { useSessions } from "../../state/sessions";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";@@ -21,6 +24,7 @@ import { GlyphIcon } from "../../components/ui/glyph-icon";import { Skeleton } from "../../components/ui/skeleton";import { BenchmarkDetail } from "./benchmark-detail";import { benchmarkPath } from "./benchmark-prompts";+import { fetchBenchmarks } from "./benchmark-sources";import { UseBenchmarkModal } from "./use-benchmark-modal";/** Back to the list: the arrow-left every detail page's back button carries. */@@ -50,10 +54,11 @@ export function BenchmarkDetailPage() {const benchmarkId = params.benchmarkId ?? "";const navigate = useNavigate();const { currentProject, agents } = useProject();+ const { machineIds, machineLabels } = useSessions();const projectId = currentProject?.projectId ?? null;const isOwner = currentProject?.role === "owner";- const [benchmark, setBenchmark] = useState<BenchmarkSummary | null>(null);+ const [benchmark, setBenchmark] = useState<MergedBenchmark | null>(null);const [error, setError] = useState<string | null>(null);/** The Project's list came back without this id: the Benchmark was deleted, or the link is stale. */const [missing, setMissing] = useState(false);@@ -63,18 +68,18 @@ export function BenchmarkDetailPage() {useDocumentTitle(benchmark?.title ?? S.benchmark.title);// The Project's list is the only read that carries a Benchmark's scoreboard, so the page takes- // it whole and picks its own out of it.+ // it whole — merged over this server and the machines it holds — and picks its own out of it.+ const machinesKey = machineIds.join(",");useEffect(() => {if (!projectId || benchmarkId === "") return;let cancelled = false;setBenchmark(null);setError(null);setMissing(false);- api- .listBenchmarks(projectId)- .then((data) => {+ fetchBenchmarks(projectId, machinesKey === "" ? [] : machinesKey.split(","))+ .then((merged) => {if (cancelled) return;- const found = data.benchmarks.find((b) => b.id === benchmarkId) ?? null;+ const found = merged.find((b) => b.id === benchmarkId) ?? null;setBenchmark(found);setMissing(found === null);})@@ -84,7 +89,7 @@ export function BenchmarkDetailPage() {return () => {cancelled = true;};- }, [projectId, benchmarkId]);+ }, [projectId, benchmarkId, machinesKey]);// The Project's models, for the Use dialog's conversation-model picker; a failure just leaves// the picker at the Project default.@@ -104,6 +109,15 @@ export function BenchmarkDetailPage() {if (!projectId) return null;+ /** The ssh alias of a machine, or null for this server. An unlabelled machine falls back to its id. */+ const machineNameOf = (machineId: string | null): string | null =>+ machineId === null ? null : (machineLabels.get(machineId) ?? machineId);+ /** The one machine holding this Benchmark when it is not on this server; null otherwise. */+ const onlyMachine =+ benchmark !== null && benchmark.machineIds.length === 1+ ? machineNameOf(benchmark.machineIds[0] ?? null)+ : null;+// A Benchmark that is not published has no settled cases or scores to show and nothing to// evaluate against: a draft is still being written and calibrated by the agent, and a failed// one never finished calibrating and can only be deleted.@@ -125,7 +139,9 @@ export function BenchmarkDetailPage() {} else if (masked) {body = <UnpublishedNotice failed={failed} isOwner={isOwner} />;} else {- body = <BenchmarkDetail projectId={projectId} benchmark={benchmark} />;+ body = (+ <BenchmarkDetail projectId={projectId} benchmark={benchmark} machineNameOf={machineNameOf} />+ );}return (@@ -147,7 +163,11 @@ export function BenchmarkDetailPage() {Use, and shows the building or creation-failed notice in place of the detail. */}<div className="mb-4 flex flex-wrap items-center gap-x-2 gap-y-1"><h1 className="min-w-0 truncate text-xl font-semibold">- {benchmark?.title ?? benchmarkId}+ {benchmark === null+ ? benchmarkId+ : onlyMachine !== null+ ? nameOnMachine(benchmark.title, onlyMachine)+ : benchmark.title}</h1>{/* A Benchmark that no longer resolves has no directory to name and nothing to use:the title and the way back are all this row keeps. */}diff --git a/packages/web/src/features/benchmark/benchmark-detail.tsx b/packages/web/src/features/benchmark/benchmark-detail.tsxindex 73e2a4d9..11644c51 100644--- a/packages/web/src/features/benchmark/benchmark-detail.tsx+++ b/packages/web/src/features/benchmark/benchmark-detail.tsx@@ -5,15 +5,13 @@* thinking-level columns. A row there opens that evaluation in a dialog, a case opens the case* browser in another, and either dialog can hand what it shows to an agent as a question. This* is the body of the Benchmark's own page (the title lives in that page's header), which mounts- * it once its Benchmark has been read, so nothing stays open from the Benchmark before it.+ * it once its Benchmark has been read, so nothing stays open from the Benchmark before it. The+ * Benchmark is the merge of every machine holding it: a row names the machine its round was read+ * from when there is more than one, and a case's files come from the machine that listed it.*/import { useEffect, useState } from "react";-import type {- BenchmarkCaseSummary,- BenchmarkEvaluation,- BenchmarkSummary,-} from "@prismshadow/penguin-server/api";-import * as api from "../../api/endpoints";+import type { BenchmarkCaseSummary, BenchmarkEvaluation } from "@prismshadow/penguin-server/api";+import type { MergedBenchmark, MergedCase } from "../../lib/benchmark-merge";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { formatDateTime, formatMoney, formatScore, humanizeDuration } from "../../lib/format";@@ -32,6 +30,7 @@ import { makeRangeGeom, segmentPath } from "../usage/chart-geom";import { ChartFrame, useChartWidth } from "../usage/chart-svg";import { AskAiModal } from "./ask-ai-modal";import { BenchmarkCaseBrowser } from "./benchmark-case-browser";+import { fetchBenchmarkCases } from "./benchmark-sources";import {evaluationLabel,labelSeries,@@ -174,10 +173,17 @@ const CELL = "px-3 py-2";/** One evaluation record: a clickable row; the detail it used to unfold is a dialog of its own. */function EvaluationRow({evaluation,+ machineName,onOpen,currency,}: {evaluation: BenchmarkEvaluation;+ /**+ * The ssh alias of the machine whose scoreboard recorded this round, when the Benchmark is+ * held in more than one place — otherwise null, and nothing is said. A row read without+ * knowing where it ran is a row that cannot be reproduced.+ */+ machineName: string | null;onOpen: () => void;currency: Currency;}) {@@ -199,6 +205,11 @@ function EvaluationRow({>{formatDateTime(evaluation.time)}</button>+ {machineName !== null && (+ <span className="ml-1.5 font-mono text-[11px] text-gray-400 dark:text-gray-500">+ {S.chat.machineTag(machineName)}+ </span>+ )}</td><td className={`${CELL} text-xs text-gray-500 dark:text-gray-400`}>{evaluation.agentId ? (@@ -317,14 +328,18 @@ function CasesSection({export function BenchmarkDetail({projectId,benchmark: bm,+ machineNameOf,}: {projectId: string;- benchmark: BenchmarkSummary;+ benchmark: MergedBenchmark;+ /** The ssh alias of a machine, or null for this server. */+ machineNameOf: (machineId: string | null) => string | null;}) {const { currency } = useTheme();- const [caseStatements, setCaseStatements] = useState<BenchmarkCaseSummary[] | null>(null);+ const [caseStatements, setCaseStatements] = useState<MergedCase[] | null>(null);const [caseError, setCaseError] = useState<string | null>(null);const [openCaseId, setOpenCaseId] = useState<string | null>(null);+ const machinesKey = bm.machineIds.map((machineId) => machineId ?? "").join(",");/** Which evaluation's dialog is open, as a position in scoreboard order. */const [openEvaluationIndex, setOpenEvaluationIndex] = useState<number | null>(null);/** The case whose Ask AI dialog is open; kept as an id so it cannot outlive its case dialog. */@@ -337,10 +352,9 @@ export function BenchmarkDetail({setOpenEvaluationIndex(null);setAskingCaseId(null);let cancelled = false;- api- .listBenchmarkCases(projectId, bm.id)- .then((data) => {- if (!cancelled) setCaseStatements(data.cases);+ fetchBenchmarkCases(projectId, bm)+ .then((cases) => {+ if (!cancelled) setCaseStatements(cases);}).catch((error: unknown) => {if (!cancelled) setCaseError(apiErrorText(error));@@ -348,7 +362,9 @@ export function BenchmarkDetail({return () => {cancelled = true;};- }, [projectId, bm.id]);+ // The machines are part of what the read asks; the key keeps a re-render from re-asking.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [projectId, bm.id, machinesKey]);// The Scoreboard append order is the evaluation sequence. Preserve it even when a malformed// timestamp would otherwise reorder Agent versions; the detail table shows that sequence newest first.@@ -405,6 +421,7 @@ export function BenchmarkDetail({<EvaluationRowkey={index}evaluation={ev}+ machineName={bm.machineIds.length > 1 ? machineNameOf(ev.machineId) : null}onOpen={() => setOpenEvaluationIndex(index)}currency={currency}/>@@ -441,7 +458,12 @@ export function BenchmarkDetail({</Button>}>- <BenchmarkCaseBrowser projectId={projectId} benchmarkId={bm.id} caseSummary={openCase} />+ <BenchmarkCaseBrowser+ projectId={projectId}+ benchmarkId={bm.id}+ caseSummary={openCase}+ machineId={openCase.machineId}+ /></Modal>)}{openCase && askingCaseId === openCase.id && (diff --git a/packages/web/src/features/benchmark/benchmark-page.tsx b/packages/web/src/features/benchmark/benchmark-page.tsxindex 50d2223f..8b8d1c6e 100644--- a/packages/web/src/features/benchmark/benchmark-page.tsx+++ b/packages/web/src/features/benchmark/benchmark-page.tsx@@ -7,7 +7,8 @@* label, a sparkline of the scoreboard, when it was last evaluated, and its actions; opening one* enters the Benchmark's own page (`/benchmark/:benchmarkId`) instead of splitting this one in* two, the way an Agent's card enters its settings. `?agentId=` narrows the list to the- * Benchmarks that tested that Agent.+ * Benchmarks that tested that Agent. The list is read off this server and every machine it holds+ * (benchmark-sources.ts): a Benchmark written on a machine is listed too, under its id.*/import { useEffect, useState } from "react";import { useNavigate, useSearchParams } from "react-router";@@ -25,6 +26,9 @@ import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { STAT_ICONS } from "../../lib/stat-icons";import { toneInk } from "../../lib/tone";import { agentDisplayName, useProject } from "../../state/project";+import { useSessions } from "../../state/sessions";+import type { MergedBenchmark } from "../../lib/benchmark-merge";+import { nameOnMachine } from "../../lib/workspace-machines";import { useLocale } from "../../state/locale";import { AgentAvatar } from "../../components/ui/agent-avatar";import { Button } from "../../components/ui/button";@@ -39,6 +43,7 @@ import { AiCreateModal, CreateButtons, pickDefaultAgent } from "../ai-create";import { latestWithDelta, matchesBenchmarkQuery, sparklineSeries } from "./benchmark-metrics";import { benchmarkCreateExamples, benchmarkCreateTail } from "./benchmark-prompts";import { benchmarkRoute } from "./benchmark-route";+import { fetchBenchmarks } from "./benchmark-sources";import { CreateBenchmarkModal } from "./create-benchmark-modal";import { ScoreSparkline } from "./score-sparkline";import { UseBenchmarkModal } from "./use-benchmark-modal";@@ -156,6 +161,7 @@ export function BenchmarkCard({benchmark,locale,nameOf,+ machineName,canDelete,onOpen,onUse,@@ -164,6 +170,8 @@ export function BenchmarkCard({benchmark: BenchmarkSummary;locale: "zh" | "en";nameOf: (agentId: string) => string;+ /** The ssh alias of the one machine that holds this Benchmark, or null when this server has it. */+ machineName: string | null;canDelete: boolean;onOpen: () => void;onUse: () => void;@@ -190,7 +198,9 @@ export function BenchmarkCard({className="min-w-[14rem] flex-1 text-left"><span className="flex items-center gap-2">- <span className="min-w-0 truncate text-base font-bold">{benchmark.title}</span>+ <span className="min-w-0 truncate text-base font-bold">+ {machineName !== null ? nameOnMachine(benchmark.title, machineName) : benchmark.title}+ </span><span className="hidden shrink-0 font-mono text-xs text-gray-400 md:inline dark:text-gray-500">{benchmark.id}</span>@@ -314,6 +324,7 @@ export function BenchmarkPage() {useDocumentTitle(S.benchmark.title);const navigate = useNavigate();const { currentProject, currentAgent, agents } = useProject();+ const { machineIds, machineLabels } = useSessions();const { locale } = useLocale();const projectId = currentProject?.projectId ?? null;const isOwner = currentProject?.role === "owner";@@ -321,7 +332,9 @@ export function BenchmarkPage() {const [searchParams, setSearchParams] = useSearchParams();const filterAgentId = searchParams.get("agentId");- const [benchmarks, setBenchmarks] = useState<BenchmarkSummary[] | null>(null);+ const [benchmarks, setBenchmarks] = useState<MergedBenchmark[] | null>(null);+ /** Bumped to read the list again — after a delete that leaves a machine's copy behind. */+ const [reload, setReload] = useState(0);const [error, setError] = useState<string | null>(null);const [query, setQuery] = useState("");const [models, setModels] = useState<ModelsResponse | null>(null);@@ -333,17 +346,18 @@ export function BenchmarkPage() {const [deleting, setDeleting] = useState<string | null>(null);const [deleteBusy, setDeleteBusy] = useState(false);- // Benchmarks belong to the Project, so the page reads one list — and a Project change starts- // it over rather than showing the previous Project's cards while the next list is in flight.+ // Benchmarks belong to the Project, so the page reads one list, merged over this server and+ // the machines it holds — and a Project change starts it over rather than showing the previous+ // Project's cards while the next list is in flight. A machine that connects re-asks.+ const machinesKey = machineIds.join(",");useEffect(() => {if (!projectId) return;let cancelled = false;setBenchmarks(null);setError(null);- api- .listBenchmarks(projectId)- .then((data) => {- if (!cancelled) setBenchmarks(data.benchmarks);+ fetchBenchmarks(projectId, machinesKey === "" ? [] : machinesKey.split(","))+ .then((merged) => {+ if (!cancelled) setBenchmarks(merged);}).catch((e: unknown) => {if (!cancelled) setError(apiErrorText(e));@@ -351,7 +365,7 @@ export function BenchmarkPage() {return () => {cancelled = true;};- }, [projectId]);+ }, [projectId, machinesKey, reload]);// The Project's models, for the Use dialog's conversation-model picker; a failure just// leaves the picker at the Project default.@@ -373,6 +387,9 @@ export function BenchmarkPage() {const agentOf = (agentId: string): AgentSummary | undefined =>agents.find((a) => a.agentId === agentId);+ /** The ssh alias of a machine, or null for this server. An unlabelled machine falls back to its id. */+ const machineNameOf = (machineId: string | null): string | null =>+ machineId === null ? null : (machineLabels.get(machineId) ?? machineId);const nameOf = (agentId: string): string => {const agent = agentOf(agentId);return agent ? agentDisplayName(agent) : agentId;@@ -394,7 +411,7 @@ export function BenchmarkPage() {{ replace: true },);- const benchmarkOf = (benchmarkId: string | null): BenchmarkSummary | null =>+ const benchmarkOf = (benchmarkId: string | null): MergedBenchmark | null =>benchmarkId === null ? null : (benchmarks?.find((b) => b.id === benchmarkId) ?? null);const usingBenchmark = benchmarkOf(using);const deletingBenchmark = benchmarkOf(deleting);@@ -406,7 +423,12 @@ export function BenchmarkPage() {try {await api.deleteBenchmark(projectId, benchmarkId);toastSuccess(S.benchmark.deleted);- setBenchmarks((prev) => (prev ?? []).filter((b) => b.id !== benchmarkId));+ // Delete removes this server's directory; a copy a machine holds is still a Benchmark.+ if (deletingBenchmark !== null && deletingBenchmark.machineIds.length > 1) {+ setReload((n) => n + 1);+ } else {+ setBenchmarks((prev) => (prev ?? []).filter((b) => b.id !== benchmarkId));+ }setDeleting(null);} catch (e) {toastError(apiErrorText(e));@@ -449,7 +471,9 @@ export function BenchmarkPage() {benchmark={b}locale={locale}nameOf={nameOf}- canDelete={isOwner}+ machineName={b.machineIds.length === 1 ? machineNameOf(b.machineIds[0] ?? null) : null}+ // Only this server's copy can be deleted from here.+ canDelete={isOwner && b.machineIds.includes(null)}onOpen={() => open(b.id)}onUse={() => setUsing(b.id)}onDelete={() => setDeleting(b.id)}diff --git a/packages/web/src/features/benchmark/benchmark-sources.ts b/packages/web/src/features/benchmark/benchmark-sources.tsnew file mode 100644index 00000000..88b3b64e--- /dev/null+++ b/packages/web/src/features/benchmark/benchmark-sources.ts@@ -0,0 +1,49 @@+/**+ * The Evaluation Center's reads, fanned out over this server and every machine it holds.+ *+ * A machine that cannot answer is left out rather than failing the read: its scoreboard is+ * missing from the merge, which is what "could not read it" means, while everything this+ * server holds still renders. Only when NO source answered is there an error to report.+ */+import * as api from "../../api/endpoints";+import { mergeBenchmarkCases, mergeBenchmarks } from "../../lib/benchmark-merge";+import type { MergedBenchmark, MergedCase } from "../../lib/benchmark-merge";++/** Settles one read per source (this server first) into the answers that came back. */+async function askEach<T>(+ sources: readonly (string | null)[],+ read: (machineId: string | null) => Promise<T>,+): Promise<{ machineId: string | null; value: T }[]> {+ const answers = await Promise.allSettled(+ sources.map(async (machineId) => ({ machineId, value: await read(machineId) })),+ );+ const answered = answers.flatMap((a) => (a.status === "fulfilled" ? [a.value] : []));+ if (answered.length === 0 && answers[0]?.status === "rejected") throw answers[0].reason;+ return answered;+}++/** The Project's Benchmarks as this server and the given machines hold them, merged. */+export async function fetchBenchmarks(+ projectId: string,+ machineIds: readonly string[],+): Promise<MergedBenchmark[]> {+ const answered = await askEach([null, ...machineIds], (machineId) =>+ api.listBenchmarks(projectId, machineId),+ );+ return mergeBenchmarks(+ answered.map(({ machineId, value }) => ({ machineId, benchmarks: value.benchmarks })),+ );+}++/** One Benchmark's Cases, asked of the machines that hold a copy of it, merged. */+export async function fetchBenchmarkCases(+ projectId: string,+ benchmark: Pick<MergedBenchmark, "id" | "machineIds">,+): Promise<MergedCase[]> {+ const answered = await askEach(benchmark.machineIds, (machineId) =>+ api.listBenchmarkCases(projectId, benchmark.id, machineId),+ );+ return mergeBenchmarkCases(+ answered.map(({ machineId, value }) => ({ machineId, cases: value.cases })),+ );+}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex cfdd3253..72ead4a8 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -99,7 +99,14 @@ import { ChatDropRegion } from "./drop-zone";import { ConversationOutline, OutlineMenuButton, useOutlineRailFit } from "./conversation-outline";import { DraftView } from "./draft-view";import { prepareNewChatDraft } from "./new-chat";-import { resolveRoutedSession, sessionForProject, sessionProbeKey } from "./session-project";+import {+ heldRouteSession,+ resolveRoutedSession,+ sessionForProject,+ sessionProbeKey,+} from "./session-project";+import { machineForSession } from "../../lib/session-machines";+import { nameOnMachine } from "../../lib/workspace-machines";import { CHAT_DEFAULTS_CHANGED_EVENT, chatDefaultsChangedDetail } from "./chat-defaults-event";import { advanceCostStat, applyUsageFetch, createCostStatHold } from "./header-stats";import type { CostStatDisplay } from "./header-stats";@@ -303,10 +310,12 @@ export function ChatPage() {const { currentProject, currentAgent, setCurrentAgentId, reloadAgents, agents } = useProject();const projectId = currentProject?.projectId ?? null;const agentId = currentAgent?.agentId ?? null;- const workflowTabs = useWorkflowTabs(projectId, agentId);const {sessions,loading: sessionsLoading,+ machineLabels,+ machinesUnreachable,+ offlineMachineIds,reload: reloadSessions,add: addSession,isDeleted: isSessionDeleted,@@ -424,17 +433,55 @@ export function ChatPage() {* the open conversation. See resolveRoutedSession.*/const [fetchedSession, setFetchedSession] = useState<SessionInfo | null>(null);- const selected = draft ? null : resolveRoutedSession(routeSessionId, sessions, fetchedSession);+ const listed = draft ? null : resolveRoutedSession(routeSessionId, sessions, fetchedSession);+ /**+ * The routed Session, held across a refetch that momentarily does not list it.+ *+ * `listed` is derived from a list that reload() rebuilds WHOLESALE: for the tick between+ * the fetches landing and the merged array being set, a source that answers slower, a+ * machine that misses one round, or a Session whose category changed under a page that is+ * not loaded, all read as "that row is not here". None of them mean the conversation on+ * screen has gone anywhere, so the render must not take them for it — dropping `selected`+ * for that tick paints the skeleton over a conversation the reader is in the middle of.+ *+ * Held only for the route it was seen on, and only until the direct lookup SAYS it is gone:+ * `routeSessionPending` and the redirect below still read `listed`, so a Session actually+ * deleted still probes, still fails, and still redirects — one tick later than before.+ */+ const probeKey = projectId && routeSessionId ? sessionProbeKey(projectId, routeSessionId) : null;+ const [probeFailedKey, setProbeFailedKey] = useState<string | null>(null);+ const heldSession = useRef<SessionInfo | null>(null);+ heldSession.current = heldRouteSession(+ heldSession.current,+ listed,+ routeSessionId ?? null,+ probeKey !== null && probeFailedKey === probeKey,+ );+ const selected = draft ? null : heldSession.current;+ // The tabs beside a conversation are its OWN Agent's, asked of the server that Agent's+ // workflows live on: a Session on a machine runs a copy of the Agent there, and the workflows+ // it built are in that copy. The current Agent is always one of this server's, so going by+ // it listed the wrong Agent's workflows (or none) for every Session on a machine.+ const workflowTabs = useWorkflowTabs(+ projectId,+ selected?.agentId ?? agentId,+ selected === null ? null : machineForSession(selected.sessionId),+ );// New shells start in this conversation's Workspace — its files are what a terminal// opened here is for. While drafting, the Workspace is the one picked in the draft and// DraftView publishes it instead (a child effect runs before this one, so this must// yield rather than clobber it with null). Leaving the chat for another page keeps the// last conversation's Workspace: it is a better default than home for the hotkey,- // which stays live everywhere.+ // which stays live everywhere. With the machine that Workspace is on: the path only means+ // anything on its own filesystem, and a shell for this conversation belongs beside the+ // agent running it.useEffect(() => {if (draft) return;- setDockCwd(selected?.workspace ?? null);- }, [draft, selected?.workspace]);+ setDockCwd(+ selected?.workspace ?? null,+ selected === null ? null : machineForSession(selected.sessionId),+ );+ }, [draft, selected]);// Currently effective model (session state, the model reference comes from the Session DTO): model selection in draft state is handled internally by DraftView.const activeModelRef = selected@@ -695,9 +742,9 @@ export function ChatPage() {// The Session list is paged: a deep-linked Session (old bookmark, cross-page jump) may sit// beyond the loaded pages. Look it up directly and insert it before the auto-select effect- // below concludes it doesn't exist; only a failed probe releases that redirect.- const probeKey = projectId && routeSessionId ? sessionProbeKey(projectId, routeSessionId) : null;- const [probeFailedKey, setProbeFailedKey] = useState<string | null>(null);+ // below concludes it doesn't exist; only a failed probe releases that redirect. `probeKey`+ // and `probeFailedKey` are declared up with `selected`, which needs them to know when to+ // let the held Session go./*** The route names a Session we cannot answer for YET: not in the loaded pages, and the* direct lookup that settles it has not failed. Ordinary with a paged list — a deep link,@@ -706,7 +753,49 @@ export function ChatPage() {* means — their disagreeing is what once painted "no Sessions yet" over a conversation* that was about to appear.*/- const routeSessionPending = !!routeSessionId && selected === null && probeFailedKey !== probeKey;+ /**+ * Nobody who could answer for this Session is answering, so a failed lookup settles nothing.+ *+ * Two shapes of that. Either no owner is recorded and some machine is out of reach — the+ * probe then asks THIS server (lib/session-machines.ts: absence means here), which 404s+ * about a Session that is alive THERE. Or the owner IS recorded and is itself one of the+ * machines not answering, which is every row restored from the cache. Reading either as+ * "gone" is what drops the reader into the draft page mid-conversation.+ */+ const routeSessionOwner = routeSessionId ? machineForSession(routeSessionId) : null;++ /**+ * The ssh alias of the machine a Session is on, or null for this server's own. Falls back+ * to the machine id when the list could not be read (it is admin-only) — honest, where+ * inventing a name is not.+ */+ const machineNameOf = (sessionId: string): string | null => {+ const machineId = machineForSession(sessionId);+ return machineId === null ? null : (machineLabels.get(machineId) ?? machineId);+ };+ const routeSessionUnowned =+ !!routeSessionId &&+ // Except one we deleted ourselves. That is the one case where a failed lookup settles it+ // whoever is out of reach — nobody is going to answer differently — and leaving it open+ // held the page on a skeleton for as long as some machine stayed down, on the ordinary+ // act of deleting the conversation you are looking at.+ !isSessionDeleted(routeSessionId) &&+ (routeSessionOwner === null+ ? machinesUnreachable+ : offlineMachineIds.includes(routeSessionOwner));+ // Read from `listed`, never from `selected`: the held Session above keeps the conversation+ // on screen through a refetch, but it must not tell the probe that the row is loaded — a+ // Session that really is gone has to keep probing until the lookup fails and releases both.+ const routeSessionPending =+ !!routeSessionId && listed === null && (probeFailedKey !== probeKey || routeSessionUnowned);+ /**+ * The lookup has failed and the only servers that could still answer for this Session are+ * out of reach. It is not gone — so the redirect must not fire and the row must not be+ * dropped — but it is not loading either, and a skeleton that never resolves reads as a+ * hung page. Say what is actually the matter instead, and let the recheck open it when the+ * connection is back (state/sessions.tsx: OFFLINE_RECHECK_MS).+ */+ const routeSessionOffline = routeSessionPending && probeFailedKey === probeKey;useEffect(() => {if (draft || !projectId || !routeSessionId || !probeKey || sessionsLoading) return;// Settled (row loaded, or the lookup already failed): nothing to probe — and a failed@@ -1173,13 +1262,22 @@ export function ChatPage() {};let createdId: string | null = null;try {- const created = await api.createSession(projectId, selected.agentId, {- provider: ref.provider,- modelId: ref.modelId,- workspace: selected.workspace,- approvalMode: selected.approvalMode,- sandbox: selected.sandbox,- });+ const created = await api.createSession(+ projectId,+ selected.agentId,+ {+ provider: ref.provider,+ modelId: ref.modelId,+ workspace: selected.workspace,+ approvalMode: selected.approvalMode,+ sandbox: selected.sandbox,+ },+ // On the machine the source Session is on: the Workspace being carried over is a+ // directory THERE, and this server would refuse a path it does not have+ // ("Workspace does not exist or is inaccessible"). The machine travels with the+ // path, here as everywhere.+ machineForSession(selected.sessionId),+ );createdId = created.session.sessionId;const res = await api.postTask(createdId, { input: [origin, ...input] });addSession(created.session);@@ -1915,7 +2013,7 @@ export function ChatPage() {// armed Remove, and none of that belongs to the next tab.key={workflowTabs.activeTab.tabId}projectId={projectId}- agentId={agentId}+ agentId={selected?.agentId ?? agentId}tab={workflowTabs.activeTab}onChanged={() => void workflowTabs.refresh()}onRemoved={() => {@@ -2072,7 +2170,11 @@ export function ChatPage() {<p className="text-xs font-medium text-gray-500 dark:text-gray-400">{S.chat.workspace}</p>- <p className="break-all font-mono text-xs leading-5">{selected.workspace}</p>+ {/* The machine too: a path names a directory only together with the+ filesystem it is on, and the same path exists on more than one of them. */}+ <p className="break-all font-mono text-xs leading-5">+ {nameOnMachine(selected.workspace, machineNameOf(selected.sessionId))}+ </p></div><div><p className="text-xs font-medium text-gray-500 dark:text-gray-400">@@ -2331,6 +2433,17 @@ export function ChatPage() {</div></>)+ ) : routeSessionOffline ? (+ <EmptyState+ title={+ routeSessionOwner === null+ ? S.chat.sessionOnOfflineMachineUnknown+ : S.chat.sessionOnOfflineMachine(+ machineLabels.get(routeSessionOwner) ?? routeSessionOwner,+ )+ }+ description={S.chat.sessionOfflineHint}+ />) : sessionsLoading || routeSessionPending ? (<div className="space-y-3 p-6"><Skeleton className="h-5 w-1/2" />diff --git a/packages/web/src/features/chat/draft-cache.ts b/packages/web/src/features/chat/draft-cache.tsindex 4243ce8b..8c9916e4 100644--- a/packages/web/src/features/chat/draft-cache.ts+++ b/packages/web/src/features/chat/draft-cache.ts@@ -18,6 +18,12 @@ export interface DraftCache {text?: string;agentId?: string;workspace?: string;+ /**+ * The machine that workspace is on; absent means this one. A path alone is not enough to+ * act on — `/srv/app` names a different directory on every machine — so the pair travels+ * together from the picker all the way to Session creation.+ */+ machineId?: string;approvalMode?: ApprovalMode;/** The draft's own permission picks; a half left out follows the server's sandbox settings. */sandbox?: Partial<SessionSandbox>;@@ -107,6 +113,7 @@ export function draftFromUnknown(parsed: unknown): DraftCache {if (typeof o.text === "string") out.text = o.text;if (typeof o.agentId === "string") out.agentId = o.agentId;if (typeof o.workspace === "string") out.workspace = o.workspace;+ if (typeof o.machineId === "string" && o.machineId !== "") out.machineId = o.machineId;const modelRef = parseModelRef(o.modelRef);if (modelRef) out.modelRef = modelRef;if (typeof o.handoffAgentId === "string") out.handoffAgentId = o.handoffAgentId;diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 4b28b1ed..3b8f232b 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -56,6 +56,8 @@ import { S } from "../../lib/strings";import { UNCONFINED } from "../../lib/permission-level";import { formatMonthDay } from "../../lib/format";import { apiErrorText } from "../../lib/api-error";+import { rememberSessionMachine } from "../../lib/session-machines";+import { cachedMachineAgents, rememberMachineAgents } from "../../lib/machine-cache";import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";import { agentDisplayName, useProject } from "../../state/project";@@ -159,7 +161,16 @@ export function DraftView({}) {const navigate = useNavigate();const location = useLocation();- const { agents, setCurrentAgentId } = useProject();+ const { agents: localAgents, setCurrentAgentId } = useProject();+ /**+ * Agents on the machine the workspace is on. They are per-server: a Session created on+ * another machine can only name an Agent that exists THERE, so offering this machine's+ * list would offer choices that cannot be made. Empty while loading, which the validation+ * below already treats as "not ready" rather than "none".+ */+ const [remoteAgents, setRemoteAgents] = useState<AgentSummary[]>([]);+ /** Why the remote list may be empty, for the composer's empty row: still asking, or beyond reach. */+ const [remoteAgentsState, setRemoteAgentsState] = useState<"loading" | "unreachable">("loading");const { add } = useSessions();// The draft key includes a user dimension (#68 cross-account leakage). RequireAuth// guarantees the user is logged in here; on the off chance there's no user (the@@ -192,12 +203,20 @@ export function DraftView({// once the Agent list and the Project's defaults are in — never a stand-in it would swap out.const [agentId, setAgentId] = useState<string | null>(cached.agentId ?? null);const [workspace, setWorkspace] = useState(cached.workspace ?? "");+ /**+ * The machine that workspace is on (null = this one). Carried beside the path because a+ * path alone does not identify a directory: `/srv/app` exists on many machines and means+ * a different one on each.+ */+ const [workspaceMachine, setWorkspaceMachine] = useState<string | null>(cached.machineId ?? null);+ /** The Agents actually offerable for this draft: the target machine's, or this one's. */+ const agents = workspaceMachine === null ? localAgents : remoteAgents;// A terminal opened while drafting starts in the Workspace chosen here; "" is the// temporary Workspace, whose directory the server only creates with the Session, so// that case falls back to home (setDockCwd's null).useEffect(() => {- setDockCwd(workspace || null);- }, [workspace]);+ setDockCwd(workspace || null, workspaceMachine);+ }, [workspace, workspaceMachine]);const [approvalMode, setApprovalMode] = useState<ApprovalMode>(cached.approvalMode ?? "allow-all",);@@ -272,18 +291,37 @@ export function DraftView({const routeState = location.state as {agentId?: string;workspace?: string;+ machineId?: string;} | null;const stateAgentId = routeState?.agentId;+ // Read here rather than beside their own effect below: the Agent resolution waits on them+ // (see `routeMachineSettled`), and a dependency array is evaluated during the render that+ // declares it.+ const stateWorkspace = routeState?.workspace;+ const stateMachineId = routeState?.machineId;const appliedStateKey = useRef<string | null>(null);useEffect(() => {if (agents.length === 0) return; // list not ready yet, nothing to validate against — wait for the next passconst valid = (id: string | null | undefined): id is string =>!!id && agents.some((a) => a.agentId === id);+ // The route may name an Agent that only exists on the machine it names alongside it (the+ // Agents page offers a new chat on a machine's own Agent). That machine is applied by the+ // Workspace effect below, one render later, and its Agents are fetched after that — so+ // this pass would validate the id against THIS server's list, reject it, and spend the+ // one-shot key on the fallback Agent, which is then what the Session is created with.+ // Nothing is decided until the list being validated against is the one the route asked+ // for. A machine named without a path is never applied at all (the machine travels with+ // the path), so it cannot hold this up.+ const routeMachineSettled =+ stateMachineId === undefined ||+ stateWorkspace === undefined ||+ workspaceMachine === stateMachineId;if (stateAgentId &&appliedStateKey.current !== location.key &&loadAppliedRouteKey("agentId") !== location.key) {+ if (!routeMachineSettled) return;appliedStateKey.current = location.key;saveAppliedRouteKey("agentId", location.key);if (valid(stateAgentId)) {@@ -296,13 +334,21 @@ export function DraftView({// there was is gone): the new-chat default, once the Project's defaults are known.if (chatDefaults === null) return;setAgentId(newChatAgentId(agents, chatDefaults));- }, [agents, agentId, location.key, stateAgentId, chatDefaults]);+ }, [+ agents,+ agentId,+ location.key,+ stateAgentId,+ stateMachineId,+ stateWorkspace,+ workspaceMachine,+ chatDefaults,+ ]);// Explicit Workspace from route state (the workspace-mode group header "+"): applied once per// location.key, same convention as the Agent above, overriding the cached selection ("" pre-fills// the temporary workspace). Unlike the Agent there's no list to validate against, so this is a// separate effect that never has to wait for a load.- const stateWorkspace = routeState?.workspace;const appliedWorkspaceKey = useRef<string | null>(null);useEffect(() => {if (@@ -315,7 +361,10 @@ export function DraftView({appliedWorkspaceKey.current = location.key;saveAppliedRouteKey("workspace", location.key);setWorkspace(stateWorkspace);- }, [location.key, stateWorkspace]);+ // Set together with the path, and to null when the route names none: a machine left over+ // from a cached draft would send this Session to a machine the chosen path is not on.+ setWorkspaceMachine(stateMachineId ?? null);+ }, [location.key, stateWorkspace, stateMachineId]);// Project defaults for Workspace / approval mode: the same apply-once discipline as the// route-state effects above, deferred until the defaults resolve. A field is only seeded@@ -499,6 +548,9 @@ export function DraftView({if (!userId) return;const data: DraftCache = { text: textRef.current, workspace, approvalMode };if (Object.keys(sandboxPick).length > 0) data.sandbox = sandboxPick;+ // Saved with the path: a draft restored without its machine would create the Session+ // here, against a path that only exists somewhere else.+ if (workspaceMachine !== null) data.machineId = workspaceMachine;if (agentId) data.agentId = agentId;if (modelRef) data.modelRef = modelRef;if (skillsRef.current.length > 0) data.skills = skillsRef.current;@@ -518,6 +570,7 @@ export function DraftView({draftId,agentId,workspace,+ workspaceMachine,approvalMode,sandboxPick,modelRef,@@ -636,10 +689,41 @@ export function DraftView({setCurrentAgentId(a.agentId);};+ // The Agents of the machine the workspace is on. What that machine was last seen running+ // is offered first, so the picker has something while the machine is asked — and stays on+ // offer if it cannot be: it is the best account of that machine anyone has. The machine's+ // own answer replaces it wholesale, including with nothing, so an Agent deleted over there+ // stops being offered here. Nothing here connects: a machine with no held connection+ // answers as unreachable, and the Machines page is where a person connects it.+ useEffect(() => {+ if (workspaceMachine === null) {+ setRemoteAgents([]);+ return;+ }+ let cancelled = false;+ setRemoteAgents(cachedMachineAgents(projectId, workspaceMachine));+ setRemoteAgentsState("loading");+ void (async () => {+ try {+ const answered = (await api.listAgents(projectId, workspaceMachine)).agents;+ rememberMachineAgents(projectId, workspaceMachine, answered);+ if (!cancelled) setRemoteAgents(answered);+ } catch {+ if (!cancelled) setRemoteAgentsState("unreachable");+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [workspaceMachine, projectId]);+/** User edits routed through these two so a late-arriving project default cannot clobber them. */- const changeWorkspace = useCallback((path: string) => {+ const changeWorkspace = useCallback((path: string, machineId?: string | null) => {touchedRef.current.workspace = true;setWorkspace(path);+ // The machine travels with the path, always — including back to null when the pick moves+ // home, or the next Session would be created on the machine the previous pick named.+ setWorkspaceMachine(machineId ?? null);}, []);const changeApprovalMode = useCallback((mode: ApprovalMode) => {touchedRef.current.approval = true;@@ -675,15 +759,26 @@ export function DraftView({// A draft the Evaluation Center's Use dialog composed creates its Session as an// evaluation run, which the sidebar files under the Evaluations folder.if (cached.source !== undefined) body.source = cached.source;- const created = await api.createSession(projectId, agentId, body);+ // Created ON the machine that owns the workspace: that server runs the agent in it.+ const created = await api.createSession(projectId, agentId, body, workspaceMachine);createdId = created.session.sessionId;const res = await api.postTask(createdId, { input, ...(goal ? { goal } : {}) });+ // postTask answers with the CURRENT id: a Session with no Trace whose process+ // restarted in between self-heals into a new one. Everything recorded a moment ago+ // under the id we created is then about a Session that no longer answers to it, and+ // the routing map is the half that fails silently — a remote Session left mapped+ // under the old id would be asked of THIS server, which does not have it. Re-recorded+ // BEFORE the lookup below, which is itself one of those calls.+ if (res.sessionId !== createdId) rememberSessionMachine(res.sessionId, workspaceMachine);// Re-fetch the row before listing it: the server persisted the fallback title at// Task start (inside the postTask call), and its session_title push may have gone// out before this row existed in the list, where it patched nothing. The fresh row// also carries the post-self-heal id, matching where we navigate.const fresh = await api.getSession(res.sessionId).catch(() => null);- add(fresh?.session ?? created.session);+ // Listed under the id we are about to navigate to. Falling back to the created row+ // verbatim would list the OLD id — a stale row, and a route naming a Session the+ // list does not contain.+ add(fresh?.session ?? { ...created.session, sessionId: res.sessionId });discardDraft();// The draft now has an id of its own, so its docks move with it: anything left// behind under the draft's scope would surface in the NEXT new conversation@@ -817,8 +912,23 @@ export function DraftView({{/* Ownership selection right below the card (small pill dropdowns, styled after ChatGPT's project picker button) */}<div className="mt-2 flex flex-wrap items-center gap-2">- <AgentSelect agents={agents} selected={selectedAgent} onSelect={selectAgent} />- <WorkspaceSelect projectId={projectId} workspace={workspace} onChange={changeWorkspace} />+ <AgentSelect+ agents={agents}+ selected={selectedAgent}+ onSelect={selectAgent}+ empty={+ workspaceMachine !== null && remoteAgentsState === "unreachable"+ ? S.machines.agentsUnreachable+ : S.common.loading+ }+ />+ <WorkspaceSelect+ projectId={projectId}+ workspace={workspace}+ machineId={workspaceMachine}+ onChange={changeWorkspace}+ chooseMachine+ /></div>{/* Example tasks: canned builds showing off the one-sentence → app flow; a click fills@@ -967,10 +1077,13 @@ function AgentSelect({agents,selected,onSelect,+ empty,}: {agents: AgentSummary[];selected: AgentSummary | null;onSelect: (agent: AgentSummary) => void;+ /** The empty row's text — why there is nothing to pick yet. */+ empty: string;}) {const [open, setOpen] = useState(false);return (@@ -1002,9 +1115,7 @@ function AgentSelect({}><div className="max-h-56 overflow-y-auto">- {agents.length === 0 && (- <p className="px-3 py-1.5 text-xs text-gray-400">{S.common.loading}</p>- )}+ {agents.length === 0 && <p className="px-3 py-1.5 text-xs text-gray-400">{empty}</p>}{agents.map((a) => {const active = a.agentId === selected?.agentId;return (diff --git a/packages/web/src/features/chat/session-project.ts b/packages/web/src/features/chat/session-project.tsindex 9b24215d..602dcd9a 100644--- a/packages/web/src/features/chat/session-project.ts+++ b/packages/web/src/features/chat/session-project.ts@@ -31,3 +31,29 @@ export function sessionForProject(session: SessionInfo, projectId: string): Sessexport function sessionProbeKey(projectId: string, sessionId: string): string {return `${projectId}:${sessionId}`;}++/**+ * What the chat page should go on showing for the routed Session, given what the list says+ * right now — the previous answer, held, when the list has momentarily stopped naming it.+ *+ * The Session list is rebuilt WHOLESALE by every refetch, so "not in the list" is two very+ * different facts wearing one face: the row is gone, or the array on hand is one tick old.+ * A source that answers slower than its siblings, a machine that misses a round, a Session+ * whose category changed under a page that is not loaded — all of them un-name a live+ * conversation for a tick. Taking that for "gone" is what paints the skeleton over a+ * conversation being read; holding the last answer through it is what this is for.+ *+ * The hold is released the moment either thing that could make it a LIE happens: the route+ * moved to another Session, or the direct lookup came back and said this one is not there.+ * So a deleted Session still leaves the screen — one tick later than it used to.+ */+export function heldRouteSession(+ held: SessionInfo | null,+ listed: SessionInfo | null,+ routeSessionId: string | null,+ probeSaysGone: boolean,+): SessionInfo | null {+ if (listed !== null) return listed;+ if (held === null || held.sessionId !== routeSessionId) return null;+ return probeSaysGone ? null : held;+}diff --git a/packages/web/src/features/dock/dock-terminal.ts b/packages/web/src/features/dock/dock-terminal.tsindex e1b51034..104c24f9 100644--- a/packages/web/src/features/dock/dock-terminal.ts+++ b/packages/web/src/features/dock/dock-terminal.ts@@ -12,6 +12,7 @@ import {type TerminalInfo,} from "../terminal/terminal-view";import { liveTerminals, noteTerminalCreated, refreshTerminals } from "../terminal/terminal-list";+import { machineForTerminal, rememberTerminalMachine } from "../../lib/terminal-machines";import {addTerminalTab,currentDockScope,@@ -35,10 +36,21 @@ const HOME_CWD = "~";* falls back to home.*/let workspaceCwd: string | null = null;+/**+ * And the machine that directory is ON. A Workspace path is only meaningful on its own+ * filesystem, so the machine travels with it — the same pairing every other Workspace+ * carries in this feature. Null = this server.+ */+let workspaceMachine: string | null = null;-/** Points new shells at this absolute Workspace path; null restores the home default. */-export function setDockCwd(path: string | null): void {+/**+ * Points new shells at this absolute Workspace path, on `machineId`; null path restores the+ * home default. A shell for a conversation that lives on a machine has to be a pty on THAT+ * machine: the files it is for are there, and the agent it sits beside is there.+ */+export function setDockCwd(path: string | null, machineId: string | null = null): void {workspaceCwd = path !== null && path.trim() !== "" ? path : null;+ workspaceMachine = workspaceCwd === null ? null : machineId;}/** A rejected working directory (gone, replaced by a file, relative) — see resolveCwd server-side. */@@ -56,8 +68,15 @@ function isBadCwd(err: unknown): boolean {* how a server-side spawn failure used to present.*/export async function createShellInDock(position?: DockPosition): Promise<void> {+ // The machine is named explicitly: there is no terminal id yet for the routing rule to+ // read, which is the one call in this feature that cannot use it.+ const machine = workspaceMachine;const create = (cwd: string): Promise<TerminalInfo> =>- fetchJson<TerminalInfo>("/api/terminals", { method: "POST", body: JSON.stringify({ cwd }) });+ fetchJson<TerminalInfo>(+ "/api/terminals",+ { method: "POST", body: JSON.stringify({ cwd }) },+ machine,+ );try {let created: TerminalInfo;try {@@ -65,8 +84,11 @@ export async function createShellInDock(position?: DockPosition): Promise<void>} catch (err) {if (workspaceCwd === null || !isBadCwd(err)) throw err;console.warn(`[terminal] Workspace unusable as cwd, opening in ${HOME_CWD}:`, err);+ // Home is still home ON THAT MACHINE: a Workspace that has gone is no reason to put+ // the shell on a different computer from the conversation it belongs to.created = await create(HOME_CWD);}+ rememberTerminalMachine(created.id, machine);noteTerminalCreated(created);addTerminalTab(created.id, position);} catch (err) {@@ -92,12 +114,18 @@ export async function createShellInDock(position?: DockPosition): Promise<void>* every live shell is already tabbed somewhere (or none exists) is a new one created.*/export async function openTerminalInDock(position?: DockPosition): Promise<void> {- const listed = await fetchJson<{ terminals: TerminalInfo[] }>("/api/terminals").catch(() => null);- const live = (listed?.terminals ?? liveTerminals()).filter((t) => t.alive);- const adoptable = unownedTerminals(live.map((t) => t.id)).at(-1);+ // Through the list, not a bare fetch of this server's collection: a terminal is a pty on+ // ONE machine, and `/api/terminals` asked without a machine answers for this one alone —+ // so a conversation on a machine would never find the shell it already has there, and+ // would spawn a second one beside it on every open.+ await refreshTerminals();+ const live = liveTerminals().filter((t) => t.alive);+ // And it has to be a shell on the machine this conversation's files are on, for the same+ // reason createShellInDock creates one there.+ const here = live.filter((t) => machineForTerminal(t.id) === workspaceMachine);+ const adoptable = unownedTerminals(here.map((t) => t.id)).at(-1);if (adoptable !== undefined) {addTerminalTab(adoptable, position);- void refreshTerminals();return;}await createShellInDock(position);@@ -115,7 +143,14 @@ export async function openTerminalInDock(position?: DockPosition): Promise<void>*/export function detachTerminal(id: string, position: DockPosition): void {const fromScope = currentDockScope();- const popup = window.open(`/terminal?id=${encodeURIComponent(id)}`, "_blank");+ // The machine travels in the URL: the new window starts with an empty terminal map, so+ // without it a detached remote pane would try to attach to a pty on the wrong computer.+ const machine = machineForTerminal(id);+ const popup = window.open(+ `/terminal?id=${encodeURIComponent(id)}` ++ (machine === null ? "" : `&machine=${encodeURIComponent(machine)}`),+ "_blank",+ );removeTab(`terminal:${id}`);if (!popup) return; // blocked popup: the shell stays reachable from the "+" menusconst timer = window.setInterval(() => {diff --git a/packages/web/src/features/machines/machine-picker.tsx b/packages/web/src/features/machines/machine-picker.tsxnew file mode 100644index 00000000..b74ee770--- /dev/null+++ b/packages/web/src/features/machines/machine-picker.tsx@@ -0,0 +1,77 @@+/**+ * The compact machine switch in a page header: a small secondary button naming the machine+ * in view, the same height and shape as the icon buttons beside it, over a plain list of+ * machine names. Used where a page shows one machine at a time (the Plugins page, the+ * Settings dialog's Plugins page).+ *+ * The panel is portaled: one of its hosts is a dialog whose scrolling body would clip an+ * in-place panel.+ */+import { useState } from "react";+import { Button } from "../../components/ui/button";+import { Dropdown } from "../../components/ui/dropdown";+import { menuRowClass } from "../../components/ui/field";+import { CheckIcon, ChevronDown } from "../../components/ui/icons";++export interface MachineChoice {+ value: string;+ label: string;+}++export function MachinePicker({+ choices,+ value,+ onChange,+ "aria-label": ariaLabel,+}: {+ choices: readonly MachineChoice[];+ value: string;+ onChange: (value: string) => void;+ "aria-label": string;+}) {+ const [open, setOpen] = useState(false);+ const current = choices.find((c) => c.value === value);+ return (+ <Dropdown+ open={open}+ setOpen={setOpen}+ className="flex"+ menuClass="w-56 max-w-[calc(100vw-2rem)] origin-top-right py-1"+ portal={{ direction: "down", align: "right" }}+ button={+ <Button+ size="sm"+ className="h-8 max-w-48 shrink-0"+ aria-haspopup="listbox"+ aria-expanded={open}+ aria-label={`${ariaLabel}: ${current?.label ?? value}`}+ onClick={() => setOpen(!open)}+ >+ <span className="min-w-0 truncate">{current?.label ?? value}</span>+ <ChevronDown className="shrink-0 text-gray-400" />+ </Button>+ }+ >+ <ul role="listbox" aria-label={ariaLabel} className="max-h-72 overflow-y-auto">+ {choices.map((choice) => {+ const selected = choice.value === value;+ return (+ <li key={choice.value} role="option" aria-selected={selected}>+ <button+ type="button"+ onClick={() => {+ setOpen(false);+ if (!selected) onChange(choice.value);+ }}+ className={`${menuRowClass} flex items-center gap-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-800 ${selected ? "font-medium" : ""}`}+ >+ <span className="min-w-0 flex-1 truncate">{choice.label}</span>+ {selected && <CheckIcon className="shrink-0" />}+ </button>+ </li>+ );+ })}+ </ul>+ </Dropdown>+ );+}diff --git a/packages/web/src/features/plugins/plugins-page.tsx b/packages/web/src/features/plugins/plugins-page.tsxindex d66ad995..ab88e6b5 100644--- a/packages/web/src/features/plugins/plugins-page.tsx+++ b/packages/web/src/features/plugins/plugins-page.tsx@@ -59,6 +59,8 @@ import { bulkOutcome, failedList, firstFailure, noticeCounts } from "../../lib/bimport { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";import { agentDisplayName, useProject } from "../../state/project";+import { useSessions } from "../../state/sessions";+import { MachinePicker, type MachineChoice } from "../machines/machine-picker";import { AgentAvatar } from "../../components/ui/agent-avatar";import { Button } from "../../components/ui/button";import { Chevron } from "../../components/ui/chevron";@@ -245,6 +247,53 @@ export function PluginsPage() {}, [projectId]);useEffect(reloadDeployment, [reloadDeployment]);+ const { machineIds, machineLabels } = useSessions();+ /** The machine the page shows and edits: null for all machines, or a machine's own id. */+ const [viewMachine, setViewMachine] = useState<string | null>(null);+ useEffect(() => setViewMachine(null), [projectId]);+ const selfId = deployment?.machineId;+ /** What the viewed machine answered itself — or why it could not — when it is not this server. */+ const [remote, setRemote] = useState<+ | { machineId: string; res: InstalledPluginsResponse }+ | { machineId: string; error: string }+ | null+ >(null);+ // Read again after every change of the list: the machine is handed its part in the+ // background, so a row reads "not on that machine yet" until it has answered with it.+ useEffect(() => {+ setRemote(null);+ if (projectId === null || viewMachine === null || viewMachine === selfId) return;+ let cancelled = false;+ api.getInstalledPlugins(projectId, viewMachine).then(+ (res) => !cancelled && setRemote({ machineId: viewMachine, res }),+ (e: unknown) => !cancelled && setRemote({ machineId: viewMachine, error: apiErrorText(e) }),+ );+ return () => {+ cancelled = true;+ };+ }, [projectId, viewMachine, selfId, deployment]);+ const nameOf = (machineId: string) =>+ machineId === selfId ? S.plugins.thisServer : (machineLabels.get(machineId) ?? machineId);+ const view: PluginView = {+ machineId: viewMachine,+ remote: remote !== null && "res" in remote ? remote.res : null,+ nameOf,+ };+ /** Whether the machine in view is this server itself, or every machine including it. */+ const viewIncludesHere = viewMachine === null || viewMachine === selfId;+ // The picker offers the machines this Project reaches and any a table names; a deployment+ // with neither has one machine, and no picker.+ const otherMachines = [+ ...new Set([...machineIds, ...(deployment?.plugins ?? []).flatMap((p) => p.machines ?? [])]),+ ].filter((id) => id !== selfId);+ const machineChoices: MachineChoice[] = [+ { value: ALL_MACHINES_CHOICE, label: S.plugins.allMachines },+ ...(selfId === undefined ? [] : [selfId, ...otherMachines]).map((id) => ({+ value: id,+ label: nameOf(id),+ })),+ ];+// The registry, fetched once on page entry.useEffect(() => {let cancelled = false;@@ -280,8 +329,8 @@ export function PluginsPage() {setPendingSpecifier(specifier);try {const next = install- ? await api.installPlugin(projectId, specifier)- : await api.uninstallPlugin(projectId, specifier);+ ? await api.installPlugin(projectId, specifier, viewMachine)+ : await api.uninstallPlugin(projectId, specifier, viewMachine);setDeployment(next);const row = next.plugins.find((p) => p.specifier === specifier);if (install && row?.error !== undefined) {@@ -528,8 +577,8 @@ export function PluginsPage() {navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });};- const allInstalled = installedPluginRows(groups ?? [], locale, deployment, index ?? []);- const allAvailable = availablePluginRows(deployment, index ?? []);+ const allInstalled = installedPluginRows(groups ?? [], locale, deployment, index ?? [], view);+ const allAvailable = availablePluginRows(deployment, index ?? [], view);const facets = pluginFacets([...allInstalled, ...allAvailable]);const picked = { categories: pickedCategories, kinds: pickedKinds, states: pickedStates };const filtering =@@ -561,15 +610,27 @@ export function PluginsPage() {admin's page; this opens the dialog there rather than sending anyone through theuser menu to find it. */}{isAdmin && (- <Button- size="sm"- className="h-8 w-8 shrink-0 justify-center p-0"- aria-label={S.plugins.openSettings}- title={S.plugins.openSettings}- onClick={() => setSettingsOpen(true)}- >- <GlyphIcon d={GEAR_ICON} size={ICON_SIZE.iconButton} />- </Button>+ <div className="flex shrink-0 items-center gap-2">+ {/* Which machine's plugins the rows show, and which table an install or a+ removal edits: the shared one, or that machine's own. */}+ {otherMachines.length > 0 && (+ <MachinePicker+ aria-label={S.plugins.viewMachine}+ choices={machineChoices}+ value={viewMachine ?? ALL_MACHINES_CHOICE}+ onChange={(v) => setViewMachine(v === ALL_MACHINES_CHOICE ? null : v)}+ />+ )}+ <Button+ size="sm"+ className="h-8 w-8 shrink-0 justify-center p-0"+ aria-label={S.plugins.openSettings}+ title={S.plugins.openSettings}+ onClick={() => setSettingsOpen(true)}+ >+ <GlyphIcon d={GEAR_ICON} size={ICON_SIZE.iconButton} />+ </Button>+ </div>)}</div><SettingsDialog@@ -594,7 +655,12 @@ export function PluginsPage() {/>)}- {deployment !== null && deployment.restartPending && (+ {remote !== null && "error" in remote && remote.machineId === viewMachine && (+ <div className={`mt-4 rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ {S.plugins.machineUnreadable(nameOf(remote.machineId), remote.error)}+ </div>+ )}+ {deployment !== null && viewIncludesHere && deployment.restartPending && (<div className={`mt-4 rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>{S.plugins.restartPending}</div>@@ -656,6 +722,8 @@ export function PluginsPage() {state={row.state}error={row.error}shipped={row.shipped}+ onlyOn={row.onlyOn}+ removeBlocked={row.removeBlocked}busy={pendingSpecifier === row.specifier}blocked={pendingSpecifier !== null && pendingSpecifier !== row.specifier}onInstall={null}@@ -777,13 +845,64 @@ interface ModulePluginRow {/** Why the process could not load it, when `state` is `failed`. */error?: string;shipped: boolean;+ /** The machines it is listed for, by name, when the shared table does not list it. */+ onlyOn?: string[];+ /** Why Remove is unavailable in this view, when it is. */+ removeBlocked?: string;}/**- * What a listed module plugin is here: running; waiting for a runtime that can re-assemble- * (`pending`); or FAILED — the process tried and could not load it, for the reason the- * server sends, which no restart would change.+ * What a listed module plugin is on the machine in view: running; waiting for a runtime that+ * can re-assemble (`pending`); FAILED — the process tried and could not load it, for the+ * reason the server sends, which no restart would change; `elsewhere` — the all-machines view+ * of a plugin listed only for other machines, which this server neither installs nor loads;+ * or `unsynced` — listed for a machine that has not reported running it.*/-type ModuleState = "none" | "pending" | "active" | "failed";+type ModuleState = "none" | "pending" | "active" | "failed" | "elsewhere" | "unsynced";++/**+ * Which machine the page shows: `machineId` null for all machines (the shared table), or a+ * machine's own id. `remote` is that machine's own answer when it is not this server — what+ * it actually runs — and null when it is this server or could not be read.+ */+export interface PluginView {+ machineId: string | null;+ remote: InstalledPluginsResponse | null;+ /** A machine's display name, by its own id. */+ nameOf: (machineId: string) => string;+}++/** The picker's value for all machines: a machine id is never this short. */+const ALL_MACHINES_CHOICE = "*";++const ALL_MACHINES: PluginView = { machineId: null, remote: null, nameOf: (id) => id };++/** Whether a listed plugin belongs in the view: shared, or listed for the machine in view. */+function inView(listed: InstalledPluginsResponse["plugins"][number], view: PluginView): boolean {+ return (+ view.machineId === null ||+ listed.everywhere !== false ||+ (listed.machines ?? []).includes(view.machineId)+ );+}++/** A listed plugin's state as the machine in view has it. */+function stateIn(+ listed: InstalledPluginsResponse["plugins"][number],+ view: PluginView,+ selfId: string | undefined,+): { state: ModuleState; error?: string } {+ const local = (row: InstalledPluginsResponse["plugins"][number]) =>+ row.active+ ? { state: "active" as const }+ : row.error !== undefined+ ? { state: "failed" as const, error: row.error }+ : { state: "pending" as const };+ if (view.machineId === null)+ return listed.here === false ? { state: "elsewhere" } : local(listed);+ if (view.machineId === selfId) return local(listed);+ const there = view.remote?.plugins.find((p) => p.specifier === listed.specifier);+ return there === undefined ? { state: "unsynced" } : local(there);+}/*** What is installed, in one list: the library's plugins — they ship with the build, so@@ -796,6 +915,7 @@ export function installedPluginRows(locale: Parameters<typeof localizedText>[0],deployment: InstalledPluginsResponse | null,index: readonly PluginIndexEntry[],+ view: PluginView = ALL_MACHINES,): PluginRow[] {const rows: PluginRow[] = [];for (const group of groups) {@@ -803,13 +923,21 @@ export function installedPluginRows(for (const plugin of group.plugins) rows.push({ kind: "library", plugin, category });}for (const listed of deployment?.plugins ?? []) {+ if (!inView(listed, view)) continue;+ const shared = listed.everywhere !== false;+ const ownTable = view.machineId !== null && (listed.machines ?? []).includes(view.machineId);rows.push({kind: "module",specifier: listed.specifier,entry: index.find((e) => e.name === listed.specifier),- state: listed.active ? "active" : listed.error !== undefined ? "failed" : "pending",- ...(listed.error !== undefined ? { error: listed.error } : {}),- shipped: listed.builtin || deployment?.shipped.includes(listed.specifier) === true,+ ...stateIn(listed, view, deployment?.machineId),+ shipped:+ listed.builtin || (view.remote ?? deployment)?.shipped.includes(listed.specifier) === true,+ ...(shared ? {} : { onlyOn: (listed.machines ?? []).map(view.nameOf) }),+ // A machine's view edits that machine's own table; a shared entry is not in it.+ ...(view.machineId !== null && shared && !ownTable+ ? { removeBlocked: S.plugins.sharedCannotRemove }+ : {}),});}return rows;@@ -823,8 +951,17 @@ export function installedPluginRows(export function availablePluginRows(deployment: InstalledPluginsResponse | null,index: readonly PluginIndexEntry[],+ view: PluginView = ALL_MACHINES,): ModulePluginRow[] {- const listed = new Set((deployment?.plugins ?? []).map((p) => p.specifier));+ // What the machine in view does not run yet: in the all-machines view, anything the shared+ // table lacks — a plugin listed for some machines is still offered for all of them.+ const listed = new Set(+ (deployment?.plugins ?? [])+ .filter((p) => (view.machineId === null ? p.everywhere !== false : inView(p, view)))+ .map((p) => p.specifier),+ );+ // What the machine in view ships, when it answered; this server's otherwise.+ const shippedList = (view.remote ?? deployment)?.shipped ?? [];const seen = new Set<string>();const rows: ModulePluginRow[] = [];for (const entry of index) {@@ -835,10 +972,10 @@ export function availablePluginRows(specifier: entry.name,entry,state: "none",- shipped: deployment?.shipped.includes(entry.name) === true,+ shipped: shippedList.includes(entry.name),});}- for (const name of deployment?.shipped ?? []) {+ for (const name of shippedList) {if (listed.has(name) || seen.has(name)) continue;seen.add(name);rows.push({ kind: "module", specifier: name, entry: undefined, state: "none", shipped: true });@@ -920,7 +1057,9 @@ export function rowFacets(row: PluginRow): {? ["installed", "restart"]: row.state === "failed"? ["installed", "failed"]- : ["available"];+ : row.state === "none"+ ? ["available"]+ : ["installed"];return { categories: row.entry?.categories ?? [], kinds: ["modules"], states };}@@ -1427,6 +1566,8 @@ function ModuleRow({state,error,shipped,+ onlyOn,+ removeBlocked,busy,blocked,onInstall,@@ -1439,6 +1580,10 @@ function ModuleRow({error?: string;/** The build carries this one: installing it copies nothing over the network. */shipped: boolean;+ /** The machines it is listed for, by name, when not every machine runs it. */+ onlyOn?: string[];+ /** Why Remove is unavailable in this view, when it is. */+ removeBlocked?: string;/** This row's own install or removal is running. */busy: boolean;/** Another row's is: one at a time, so the rest are held rather than queued. */@@ -1454,7 +1599,11 @@ function ModuleRow({? S.plugins.installedRestart: state === "failed"? S.plugins.stateFailed- : S.plugins.notInstalled;+ : state === "unsynced"+ ? S.plugins.notSynced+ : state === "elsewhere"+ ? S.plugins.notHere+ : S.plugins.notInstalled;// Metadata line, the library card's shape: version · updated · what it is here.const updated =entry?.updatedAt === undefined@@ -1493,7 +1642,7 @@ function ModuleRow({className={state === "active"? toneInk.success- : state === "pending"+ : state === "pending" || state === "unsynced"? toneInk.attention: state === "failed"? toneInk.danger@@ -1512,6 +1661,7 @@ function ModuleRow({{(entry?.categories ?? []).map((category) => (<Tag key={category}>{category}</Tag>))}+ {onlyOn !== undefined && <Tag>{S.plugins.onlyOn(onlyOn.join(", "))}</Tag>}{shipped && <Tag title={S.plugins.builtinHint}>{S.plugins.builtin}</Tag>}{(entry?.keywords ?? []).map((keyword) => (<Tag key={keyword} mono>@@ -1557,8 +1707,8 @@ function ModuleRow({className="h-8 w-8 shrink-0 justify-center p-0"aria-label={`${S.plugins.uninstall} ${specifier}`}aria-busy={busy}- title={S.plugins.uninstall}- disabled={busy || blocked}+ title={removeBlocked ?? S.plugins.uninstall}+ disabled={busy || blocked || removeBlocked !== undefined}onClick={onRemove}>{busy ? (diff --git a/packages/web/src/features/settings/plugins-section.tsx b/packages/web/src/features/settings/plugins-section.tsxindex 45b2adfa..46ffcf08 100644--- a/packages/web/src/features/settings/plugins-section.tsx+++ b/packages/web/src/features/settings/plugins-section.tsx@@ -10,6 +10,11 @@* clear checkbox drops it. The server validates against the same schema and answers a* rejected field by name, which renders under that field.*+ * Each server keeps its own values, so the page edits one machine at a time: a picker at the+ * top switches between this server and the machines the Project holds a connection to, and+ * every read, save and action goes to the picked machine through this server's tunnel.+ * Nothing is copied between machines.+ ** Values hydrate when the section mounts and the saved response is adopted as the new* baseline, the proxy page's rule; the plugin picks the change up through its watch, so* nothing here says "restart".@@ -30,6 +35,11 @@ import { Switch } from "../../components/ui/switch";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { toneInk, toneStrip } from "../../lib/tone";import { SectionShell } from "./section-shell";+import { useSessions } from "../../state/sessions";+import { MachinePicker } from "../machines/machine-picker";++/** The picker's value for this server; a machine id is never this short. */+const THIS_SERVER = "*";/*** A field's draft: strings and numbers as typed (a number stays the string in the box until@@ -104,6 +114,12 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {const [clearing, setClearing] = useState<Set<string>>(new Set());const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});const [busy, setBusy] = useState<string | null>(null);+ const { machineIds, machineLabels } = useSessions();+ /** The machine whose settings the page shows and saves: null for this server. */+ const [machine, setMachine] = useState<string | null>(null);+ /** Why the picked machine's settings could not be read, when they could not. */+ const [loadError, setLoadError] = useState<string | null>(null);+ const nameOf = (id: string) => machineLabels.get(id) ?? id;const adopt = (list: PluginConfigEntry[]) => {setEntries(list);@@ -124,18 +140,29 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {useEffect(() => {let cancelled = false;- void api.adminGetPluginConfig().then(+ setEntries(null);+ setLoadError(null);+ setFieldErrors({});+ void api.adminGetPluginConfig(machine).then((config) => {if (!cancelled) adopt(config.plugins);},(e: unknown) => {- if (!cancelled) toastError(apiErrorText(e));+ if (cancelled) return;+ if (machine === null) {+ toastError(apiErrorText(e));+ return;+ }+ // A machine that cannot answer — no connection, or a build without these routes —+ // shows an empty page with the reason, not this server's settings under its name.+ adopt([]);+ setLoadError(apiErrorText(e));},);return () => {cancelled = true;};- }, []);+ }, [machine]);/*** While any group reports work in progress (an install it started), its notices and actions@@ -148,8 +175,10 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {useEffect(() => {if (!inProgress) return;let cancelled = false;+ // The machine whose settings are on screen: an install started over there reports its+ // progress over there.const timer = setTimeout(() => {- void api.adminGetPluginConfig().then(+ void api.adminGetPluginConfig(machine).then((config) => {if (cancelled) return;setEntries((prev) =>@@ -176,7 +205,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {cancelled = true;clearTimeout(timer);};- }, [entries, inProgress]);+ }, [entries, inProgress, machine]);/*** The update one entry's draft makes, or `null` when it changes nothing; `false` when a@@ -233,7 +262,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {try {for (const [entry, values] of updates) {try {- const res = await api.adminPutPluginConfig({ name: entry.name, values });+ const res = await api.adminPutPluginConfig({ name: entry.name, values }, machine);const saved = res.plugins.find((e) => e.name === entry.name);if (saved !== undefined) adoptOne(saved);else adopt(res.plugins);@@ -264,7 +293,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {const runAction = async (entry: PluginConfigEntry, action: string) => {setBusy(`${entry.name}\0${action}`);try {- const res = await api.adminRunPluginConfigAction({ name: entry.name, action });+ const res = await api.adminRunPluginConfigAction({ name: entry.name, action }, machine);adopt(res.plugins);const message = localized(res.message, res.messageZh) ?? res.message;if (res.ok) toastSuccess(message);@@ -276,7 +305,25 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {}};- if (entries === null) return <SectionShell>{null}</SectionShell>;+ // Only when there is another machine to pick: a single server has nothing to switch to.+ const picker =+ machineIds.length > 0 ? (+ <div className="flex justify-end">+ <MachinePicker+ aria-label={S.settings.pluginConfigMachine}+ choices={[+ { value: THIS_SERVER, label: S.plugins.thisServer },+ ...machineIds.map((id) => ({ value: id, label: nameOf(id) })),+ ]}+ value={machine ?? THIS_SERVER}+ onChange={(v) => {+ if (busy === null) setMachine(v === THIS_SERVER ? null : v);+ }}+ />+ </div>+ ) : null;++ if (entries === null) return <SectionShell>{picker}</SectionShell>;const patch = (plugin: string, name: string, value: unknown) => {setDrafts((prev) => ({ ...prev, [plugin]: { ...(prev[plugin] ?? {}), [name]: value } }));@@ -506,6 +553,12 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {const cards = entries.filter((e) => e.parent === undefined || !names.has(e.parent));return (<SectionShell>+ {picker}+ {machine !== null && loadError !== null && (+ <p className={`rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ {S.plugins.machineUnreadable(nameOf(machine), loadError)}+ </p>+ )}<FocusCard focus={focus} ready={entries.length > 0} />{cards.map((card) => {const children = entries.filter((e) => e.parent === card.name);diff --git a/packages/web/src/features/terminal/terminal-list.ts b/packages/web/src/features/terminal/terminal-list.tsindex 862bcdce..d308a6c9 100644--- a/packages/web/src/features/terminal/terminal-list.ts+++ b/packages/web/src/features/terminal/terminal-list.ts@@ -13,6 +13,13 @@*/import type { TerminalInfo } from "./terminal-view";import { pruneTerminalTabs } from "../dock/dock-state";+import { apiUrl } from "../../lib/server-context";+import {+ rememberTerminalMachine,+ terminalMachinesPublished,+ terminalSources,+ terminalUrl,+} from "../../lib/terminal-machines";/*** Shell titles usually open with a `user@host` marker (bash and zsh default title@@ -91,24 +98,60 @@ export function refreshTerminals(): Promise<void> {if (inflight) return inflight;inflight = (async () => {try {- const res = await fetch("/api/terminals", { credentials: "same-origin" });+ // Every source, this server first: a terminal is a pty on ONE machine's kernel, so+ // the list is not one server's answer. A machine that does not answer contributes+ // nothing and its terminals are simply not listed this round — which is right, since+ // a pane whose bytes cannot arrive is not a pane anyone can use.+ const answers = await Promise.all(+ terminalSources().map(async (source) => {+ const res = await fetch(apiUrl("/api/terminals", source), {+ credentials: "same-origin",+ }).catch(() => null);+ return { source, res };+ }),+ );+ const here = answers.find((a) => a.source === null)?.res ?? null;// 404 means the route does not exist at all: the running runtime predates the// terminal API. Under hot update the Web App and the runtime can be different// versions by design, so the UI has to notice rather than offer a dead control.- if (res.status === 404 && !unsupported) {+ // Asked of THIS server only — a machine on an older build says nothing about the+ // control this page offers.+ if (here?.status === 404 && !unsupported) {unsupported = true;for (const listener of [...listeners]) listener();return;}- if (!res.ok) return; // signed out or server unreachable: keep the last known list+ if (here === null || !here.ok) return; // signed out or unreachable: keep the last listunsupported = false;- const data = (await res.json()) as { terminals: TerminalInfo[] };- const listed = new Set(data.terminals.map((t) => t.id));+ const terminals: TerminalInfo[] = [];+ for (const { source, res } of answers) {+ if (res === null || !res.ok) continue;+ const part = (await res.json()) as { terminals: TerminalInfo[] };+ for (const terminal of part.terminals) {+ terminals.push(terminal);+ // Where it lives, so the two calls about it — attach and kill — reach that+ // machine. Rebuilt by the very list that displays them.+ rememberTerminalMachine(terminal.id, source);+ }+ }+ const listed = new Set(terminals.map((t) => t.id));for (const id of pendingKills.keys()) {if (!listed.has(id)) pendingKills.delete(id); // fully gone: nothing left to hide}- const live = data.terminals.filter((t) => t.alive && !isPendingKill(t.id));- pruneTerminalTabs(new Set(live.map((t) => t.id)));+ const live = terminals.filter((t) => t.alive && !isPendingKill(t.id));+ // Pruning is the one thing here that DESTROYS something: it drops terminal tabs out+ // of every conversation's stored arrangement. So it may only act on a complete+ // picture — every source answered, and the machine set already published. Neither+ // holds on a fresh page: the machines are published once the machine list has been+ // read, and a connection the server is still re-holding after a restart answers+ // nothing yet, so an early refresh sees this server alone. Pruning on that would+ // delete the tabs of terminals that are alive on a machine, and storage does not get+ // them back. Displaying the short list meanwhile is fine — a pane whose bytes cannot+ // arrive is not usable yet, but it is not gone either, and the next complete refresh+ // restores it.+ if (terminalMachinesPublished() && answers.every((a) => a.res !== null && a.res.ok)) {+ pruneTerminalTabs(new Set(live.map((t) => t.id)));+ }commit(live);} catch {// Network hiccup: the next poll/focus refresh will catch up.@@ -157,7 +200,7 @@ export async function killTerminal(id: string): Promise<void> {pendingKills.set(id, Date.now() + 10_000);commit(raw.filter((t) => t.id !== id));try {- await fetch(`/api/terminals/${encodeURIComponent(id)}`, {+ await fetch(terminalUrl(`/api/terminals/${encodeURIComponent(id)}`), {method: "DELETE",credentials: "same-origin",});diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsxindex f591ffbf..ed7b6adb 100644--- a/packages/web/src/features/terminal/terminal-page.tsx+++ b/packages/web/src/features/terminal/terminal-page.tsx@@ -6,6 +6,7 @@* /terminal?id=<id> attach exactly that terminal (the detach handoff)* /terminal?cwd=/some/dir create the terminal in that directory* /terminal?name=<name> display/session name for a newly created terminal+ * /terminal?machine=<id> the machine the pty is on (absent = this server)** Once a terminal is attached, its id is written back into the URL (replaceState, no* navigation), so a reload — or copying the address to another window — reattaches to the@@ -28,6 +29,7 @@ import {type TerminalInfo,type TerminalStatus,} from "./terminal-view";+import { rememberTerminalMachine } from "../../lib/terminal-machines";const STORAGE_KEY = "penguin.terminal.page.id";@@ -35,6 +37,13 @@ export interface TerminalPageParams {id: string | null;cwd: string;name: string | null;+ /**+ * The machine the terminal is (or should be) on. In the URL because this page is opened+ * in a NEW window: nothing in it has seen a terminal list yet, so the in-memory map that+ * addresses every other terminal call is empty here and the URL is the only thing that+ * can say where the pty lives.+ */+ machine: string | null;}/** Parses the /terminal search string into attach parameters (exported for tests). */@@ -43,10 +52,12 @@ export function parseTerminalParams(search: string): TerminalPageParams {const id = params.get("id");const cwd = params.get("cwd");const name = params.get("name");+ const machine = params.get("machine");return {id: id && id.trim() ? id.trim() : null,cwd: cwd && cwd.trim() ? cwd.trim() : "~",name: name && name.trim() ? name.trim() : null,+ machine: machine && machine.trim() ? machine.trim() : null,};}@@ -65,27 +76,36 @@ async function attachOrCreate(// 1. An explicit id wins — this is the detach handoff. A dead-but-not-yet-reaped// terminal is still returned so the user sees its final screen and exit status.if (params.id) {+ // Seeded before the probe, so this and every later call about it — attach, resize,+ // kill — address the machine that holds it.+ rememberTerminalMachine(params.id, params.machine);const existing = await probeJson<TerminalInfo>(`/api/terminals/${params.id}`).catch(() => null);if (existing) return existing;} else {// 2. Bare visit: reattach to this page's previous terminal when it is still alive.const storedId = localStorage.getItem(STORAGE_KEY);if (storedId) {+ rememberTerminalMachine(storedId, params.machine);const stored = await probeJson<TerminalInfo>(`/api/terminals/${storedId}`).catch(() => null);if (stored?.alive) return stored;}}- // 3. Create afresh from the URL's cwd/name.- const created = await fetchJson<TerminalInfo>("/api/terminals", {- method: "POST",- body: JSON.stringify({- cwd: params.cwd,- cols,- rows,- ...(params.name !== null ? { name: params.name } : {}),- }),- });+ // 3. Create afresh from the URL's cwd/name — on the machine the cwd is a path ON.+ const created = await fetchJson<TerminalInfo>(+ "/api/terminals",+ {+ method: "POST",+ body: JSON.stringify({+ cwd: params.cwd,+ cols,+ rows,+ ...(params.name !== null ? { name: params.name } : {}),+ }),+ },+ params.machine,+ );+ rememberTerminalMachine(created.id, params.machine);return created;}diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsxindex 3a30ecfa..b8fafd81 100644--- a/packages/web/src/features/terminal/terminal-view.tsx+++ b/packages/web/src/features/terminal/terminal-view.tsx@@ -18,6 +18,8 @@ import type { ITheme, Terminal as XTerminal } from "@xterm/xterm";import { TerminalOpcode, decodeFrame, encodeFrame, encodeResize } from "./terminal-frames";import { LinkClickTracker, openTerminalLink, positionFromPointer } from "./terminal-links";import { useTheme } from "../../state/theme";+import { useAuth } from "../../state/auth";+import { machineForTerminal, terminalUrl } from "../../lib/terminal-machines";/*** xterm and its addons load lazily, on the first actual terminal render: their UMD@@ -114,8 +116,17 @@ export function terminalTheme(dark: boolean): ITheme {return dark ? DARK_THEME : LIGHT_THEME;}-async function request(path: string, init?: RequestInit): Promise<Response> {- return fetch(path, {+/**+ * Every terminal round-trip goes through here, and so is addressed to the machine that holds+ * the terminal it names (lib/terminal-machines.ts). `server` is for the one call with no id+ * to route by: creating a terminal names its machine before the terminal exists.+ */+async function request(+ path: string,+ init?: RequestInit,+ server?: string | null,+): Promise<Response> {+ return fetch(terminalUrl(path, server), {credentials: "same-origin",...init,headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },@@ -150,23 +161,39 @@ function httpError(}/** Any non-ok status is an error, 404 included — use probeJson where absence is expected. */-export async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {- const res = await request(path, init);+export async function fetchJson<T>(+ path: string,+ init?: RequestInit,+ server?: string | null,+): Promise<T> {+ const res = await request(path, init, server);if (!res.ok) throw httpError(path, init, res, await res.text());return (await res.json()) as T;}/** Existence probe: 404 means "not there" and answers null; every other failure throws. */-export async function probeJson<T>(path: string, init?: RequestInit): Promise<T | null> {- const res = await request(path, init);+export async function probeJson<T>(+ path: string,+ init?: RequestInit,+ server?: string | null,+): Promise<T | null> {+ const res = await request(path, init, server);if (res.status === 404) return null;if (!res.ok) throw httpError(path, init, res, await res.text());return (await res.json()) as T;}-function streamUrl(id: string, cols: number, rows: number): string {+/**+ * Always THIS server's stream. A pty on a machine is named in the id instead of the path —+ * `<terminalId>@<machineId>@<userId>` — and this server's platform relays the socket through+ * the connection it holds (server: machines/terminal-relay.ts). The user id is what the+ * runtime's owner check reads; naming anyone else is refused there.+ */+function streamUrl(id: string, cols: number, rows: number, userId: string): string {const scheme = location.protocol === "https:" ? "wss:" : "ws:";- return `${scheme}//${location.host}/api/terminals/${id}/stream?cols=${cols}&rows=${rows}`;+ const machine = machineForTerminal(id);+ const ref = machine === null ? id : `${id}@${machine}@${userId}`;+ return `${scheme}//${location.host}/api/terminals/${ref}/stream?cols=${cols}&rows=${rows}`;}export interface TerminalViewProps {@@ -203,6 +230,7 @@ export function TerminalView({// (the view pool exists to keep exactly those alive). The ref is what lets the// once-per-mount effect below read the current appearance without depending on it.const { terminalDark } = useTheme();+ const userId = useAuth().user?.userId ?? "";const darkRef = useRef(terminalDark);darkRef.current = terminalDark;const termRef = useRef<XTerminal | null>(null);@@ -458,7 +486,7 @@ export function TerminalView({if (disposed) return;callbacks.current.onInfo?.(terminal);- socket = new WebSocket(streamUrl(terminal.id, term.cols, term.rows));+ socket = new WebSocket(streamUrl(terminal.id, term.cols, term.rows, userId));socket.binaryType = "arraybuffer";socket.onopen = () => report("ready");diff --git a/packages/web/src/features/workflows/workflow-app-page.tsx b/packages/web/src/features/workflows/workflow-app-page.tsxindex 6e7a0e76..2d8189a7 100644--- a/packages/web/src/features/workflows/workflow-app-page.tsx+++ b/packages/web/src/features/workflows/workflow-app-page.tsx@@ -11,7 +11,7 @@* navigating.*/import { useEffect, useMemo, useState } from "react";-import { useNavigate, useParams } from "react-router";+import { useNavigate, useParams, useSearchParams } from "react-router";import * as api from "../../api/endpoints";import type { PaletteAction } from "../../lib/command-palette";import { S } from "../../lib/strings";@@ -32,6 +32,8 @@ export function WorkflowAppPage() {const agentId = params["agentId"] ?? "";const workflowId = params["workflowId"] ?? "";const tabKey = params["tabKey"];+ // A workflow of an Agent that lives on a machine is asked of that machine (`?machine=<id>`).+ const machineId = useSearchParams()[0].get("machine");const navigate = useNavigate();const [tab, setTab] = useState<WorkflowTab | null | undefined>(undefined);const [failure, setFailure] = useState<string | null>(null);@@ -40,9 +42,9 @@ export function WorkflowAppPage() {let alive = true;const load = async () => {try {- const res = await api.getWorkflows(projectId, agentId);+ const res = await api.getWorkflows(projectId, agentId, machineId);if (!alive) return;- setTab(appPageTab(workflowTabsOf(res.workflows), workflowId, tabKey));+ setTab(appPageTab(workflowTabsOf(res.workflows, machineId), workflowId, tabKey));setFailure(null);} catch (err) {if (alive) setFailure(err instanceof Error ? err.message : String(err));@@ -69,7 +71,7 @@ export function WorkflowAppPage() {window.removeEventListener(WORKFLOW_UPDATED_EVENT, onUpdated);conn.close();};- }, [projectId, agentId, workflowId, tabKey]);+ }, [projectId, agentId, workflowId, tabKey, machineId]);const exit = useMemo<PaletteAction[]>(() => [diff --git a/packages/web/src/features/workflows/workflow-tabs.tsx b/packages/web/src/features/workflows/workflow-tabs.tsxindex 33dc1bb0..66250dec 100644--- a/packages/web/src/features/workflows/workflow-tabs.tsx+++ b/packages/web/src/features/workflows/workflow-tabs.tsx@@ -34,7 +34,11 @@ import { useTheme } from "../../state/theme";import { localizedText } from "../chat/skill-use";/** The Agent's workflow tabs, kept fresh by the server's `workflow_updated` events. */-export function useWorkflowTabs(projectId: string | null, agentId: string | null) {+export function useWorkflowTabs(+ projectId: string | null,+ agentId: string | null,+ machineId: string | null = null,+) {const [tabs, setTabs] = useState<WorkflowTab[]>([]);const [notices, setNotices] = useState<WorkflowNotice[]>([]);const [active, setActiveRaw] = useState<string | null>(null);@@ -51,14 +55,14 @@ export function useWorkflowTabs(projectId: string | null, agentId: string | nullreturn;}try {- const res = await api.getWorkflows(projectId, agentId);+ const res = await api.getWorkflows(projectId, agentId, machineId);if (asked.current !== mine) return;- setTabs(workflowTabsOf(res.workflows));+ setTabs(workflowTabsOf(res.workflows, machineId));setNotices(workflowNoticesOf(res.workflows));} catch {// The strip is a convenience over the chat: a failed list leaves it as it was.}- }, [projectId, agentId]);+ }, [projectId, agentId, machineId]);useEffect(() => {setActiveRaw(null);@@ -191,7 +195,9 @@ export function WorkflowFrame({const loadHistory = useCallback(async () => {try {- setVersions((await api.getWorkflowHistory(projectId, agentId, tab.workflowId)).versions);+ setVersions(+ (await api.getWorkflowHistory(projectId, agentId, tab.workflowId, tab.machineId)).versions,+ );} catch (err) {setFailure(err instanceof Error ? err.message : String(err));}@@ -205,7 +211,9 @@ export function WorkflowFrame({setBusy("reload");setFailure(null);try {- onChanged((await api.reloadWorkflow(projectId, agentId, tab.workflowId)).workflow);+ onChanged(+ (await api.reloadWorkflow(projectId, agentId, tab.workflowId, tab.machineId)).workflow,+ );} catch (err) {setFailure(err instanceof Error ? err.message : String(err));} finally {@@ -218,7 +226,8 @@ export function WorkflowFrame({setFailure(null);try {onChanged(- (await api.rollbackWorkflow(projectId, agentId, tab.workflowId, revision)).workflow,+ (await api.rollbackWorkflow(projectId, agentId, tab.workflowId, revision, tab.machineId))+ .workflow,);} catch (err) {setFailure(err instanceof Error ? err.message : String(err));@@ -265,7 +274,7 @@ export function WorkflowFrame({setBusy("remove");setFailure(null);try {- await api.removeWorkflow(projectId, agentId, tab.workflowId);+ await api.removeWorkflow(projectId, agentId, tab.workflowId, tab.machineId);onRemoved();} catch (err) {setFailure(err instanceof Error ? err.message : String(err));@@ -278,7 +287,8 @@ export function WorkflowFrame({// (`parent.postMessage({ type: "penguin:fill-app" }, "*")`) — only from our own frame.const navigate = useNavigate();const fillApp = useCallback(- () => void navigate(workflowAppPath(projectId, agentId, tab.workflowId, tab.key)),+ () =>+ void navigate(workflowAppPath(projectId, agentId, tab.workflowId, tab.key, tab.machineId)),[navigate, projectId, agentId, tab.workflowId, tab.key],);useEffect(() => {diff --git a/packages/web/src/lib/attachments.ts b/packages/web/src/lib/attachments.tsindex f86527dd..6862b2d6 100644--- a/packages/web/src/lib/attachments.ts+++ b/packages/web/src/lib/attachments.ts@@ -17,6 +17,8 @@* left displayed as-is in the text (e.g. a "could not be saved" note, a path outside this* system, or a marker-shaped line a user simply typed).*/+import { apiUrl } from "./server-context";+import { machineForSession } from "./session-machines";import {ATTACHED_FILE_PREFIX,ATTACHED_IMAGE_PREFIX,@@ -41,12 +43,22 @@ export interface ParsedAttachments {*/const SCRATCHPAD_PATH = /[/\\]scratchpad[/\\]([^/\\]+)[/\\]([^/\\]+)$/;-/** Resolves a single image line's address; returns null if unrecognized (the line is kept in the text). */+/**+ * Resolves a single image line's address; returns null if unrecognized (the line is kept in+ * the text). A scratchpad address names its own Session, so it carries the routing rule with+ * it: an attachment on a Session that lives on a machine has to be fetched from THERE, and+ * this is a URL rather than a call, so nothing else would apply the rule for it.+ */function resolveAttachment(value: string): string | null {if (/^https?:\/\//i.test(value)) return value;const m = SCRATCHPAD_PATH.exec(value);- if (m)- return `/api/sessions/${encodeURIComponent(m[1]!)}/scratchpad/${encodeURIComponent(m[2]!)}`;+ if (m) {+ const sessionId = m[1]!;+ return apiUrl(+ `/api/sessions/${encodeURIComponent(sessionId)}/scratchpad/${encodeURIComponent(m[2]!)}`,+ machineForSession(sessionId),+ );+ }return null;}diff --git a/packages/web/src/lib/benchmark-merge.ts b/packages/web/src/lib/benchmark-merge.tsnew file mode 100644index 00000000..6c3610f8--- /dev/null+++ b/packages/web/src/lib/benchmark-merge.ts@@ -0,0 +1,161 @@+/**+ * A Project's Benchmarks, read off every machine this server holds.+ *+ * A Benchmark belongs to the Project, and the Project is the same on each machine it is lent+ * to. Its `benchmarks/` directory, though, is written where the Benchmark was created or+ * evaluated — so one Benchmark's cases and scoreboard can be spread over as many disks as it+ * has run on, while the Evaluation Center read only the disk it is served from.+ *+ * So the merge is BY IDENTITY, never by machine: one entry per benchmark id, one history of+ * evaluations under it. The machine rides along as attribution — which disk an evaluation was+ * read from, and where a Case's files have to be fetched from — and is not a grouping key.+ *+ * The same holds one level up, for the Agents themselves: an Agent that has only ever run on a+ * machine has its state directory only over there, so a tree built from this server's Agent+ * list has no row to hang its Benchmarks off (mergeAgents, below).+ *+ * Two rules are load-bearing:+ *+ * - **Order.** A scoreboard's append order IS its evaluation sequence, and the page preserves+ * it rather than trusting timestamps. Two scoreboards on two disks share no append order at+ * all, so a merged history can only be ordered by time — and a benchmark that came from a+ * single machine is therefore left exactly as that file had it.+ * - **First source wins the description.** The caller lists this server first, so a title, a+ * `runs` count or a status read here is the one displayed. They describe the same Benchmark;+ * where two disks disagree, the one the person is looking at is the honest choice.+ */+import type {+ AgentSummary,+ BenchmarkCaseSummary,+ BenchmarkEvaluation,+ BenchmarkSummary,+} from "@prismshadow/penguin-server/api";++/** One server's answer about a Project's Agents, with the machine that gave it. */+export interface AgentSource {+ machineId: string | null;+ agents: readonly AgentSummary[];+}++/** One Agent of a Project, and the machines that actually hold its state directory. */+export interface MergedAgent {+ agent: AgentSummary;+ /** Where this Agent exists, in the order the sources were asked; this server is null. */+ machineIds: (string | null)[];+}++/**+ * The Agents of a Project as every machine together has them.+ *+ * An Agent belongs to the Project, but its state directory is created on whichever machine it+ * has run on — so an Agent that has only ever run on a machine exists only over there, and a+ * page that lists this server's Agents cannot show it at all.+ *+ * The first source to name an Agent describes it (this server, when it has it): a name and a+ * description read here are the ones the person is looking at. `machineIds` is what the caller+ * asks about that Agent — asking a machine that has never heard of it earns a 404 per call.+ */+export function mergeAgents(sources: readonly AgentSource[]): MergedAgent[] {+ const byId = new Map<string, MergedAgent>();+ for (const source of sources) {+ for (const agent of source.agents) {+ const existing = byId.get(agent.agentId);+ if (existing === undefined)+ byId.set(agent.agentId, { agent, machineIds: [source.machineId] });+ else existing.machineIds.push(source.machineId);+ }+ }+ return [...byId.values()];+}++/** One server's answer about a Project's Benchmarks, with the machine that gave it. */+export interface BenchmarkSource {+ /** The machine's own id; null for the server serving this page. */+ machineId: string | null;+ benchmarks: readonly BenchmarkSummary[];+}++/** An evaluation, and the machine whose scoreboard recorded it. */+export type MergedEvaluation = BenchmarkEvaluation & { machineId: string | null };++/** One Benchmark, as every machine together holds it. */+export interface MergedBenchmark extends Omit<BenchmarkSummary, "evaluations"> {+ evaluations: MergedEvaluation[];+ /**+ * The machines holding a copy, in the order they were asked (this server first). More than+ * one means the same benchmark was evaluated in more than one place — which is what makes+ * an evaluation row's machine worth showing.+ */+ machineIds: (string | null)[];+}++/** Newest last, by the timestamp the scoreboard recorded; entries without one keep their place. */+function byTime(a: MergedEvaluation, b: MergedEvaluation): number {+ return (a.time ?? "").localeCompare(b.time ?? "");+}++/**+ * Folds every machine's answer into one list of Benchmarks, in the order the sources were+ * asked (so this server's benchmarks lead, and a machine-only one follows).+ */+export function mergeBenchmarks(sources: readonly BenchmarkSource[]): MergedBenchmark[] {+ const byId = new Map<string, MergedBenchmark>();+ for (const source of sources) {+ for (const benchmark of source.benchmarks) {+ const evaluations = benchmark.evaluations.map((evaluation) => ({+ ...evaluation,+ machineId: source.machineId,+ }));+ const existing = byId.get(benchmark.id);+ if (existing === undefined) {+ byId.set(benchmark.id, {+ ...benchmark,+ evaluations,+ agentIds: [...benchmark.agentIds],+ machineIds: [source.machineId],+ });+ continue;+ }+ existing.machineIds.push(source.machineId);+ existing.evaluations.push(...evaluations);+ // The Agents it has tested are those of every scoreboard, first-seen order kept.+ for (const agentId of benchmark.agentIds) {+ if (!existing.agentIds.includes(agentId)) existing.agentIds.push(agentId);+ }+ // The count of a directory nobody merged: the machines hold overlapping case sets, so+ // the largest is the closest true statement available from the list endpoint alone.+ existing.caseCount = Math.max(existing.caseCount, benchmark.caseCount);+ }+ }+ const merged = [...byId.values()];+ for (const benchmark of merged) {+ // Only where two files were joined: a single scoreboard keeps the order it was written in.+ if (benchmark.machineIds.length > 1) benchmark.evaluations.sort(byTime);+ }+ return merged;+}++/** One server's answer about a Benchmark's Cases. */+export interface CaseSource {+ machineId: string | null;+ cases: readonly BenchmarkCaseSummary[];+}++/** A Case, and the machine whose disk its files have to be read from. */+export type MergedCase = BenchmarkCaseSummary & { machineId: string | null };++/**+ * The union of the Cases every machine holds for one Benchmark, first source winning a+ * shared id. A Case's files are then fetched from the machine it is recorded against: they+ * are two copies of one Case, and reading one of them is reading the Case.+ */+export function mergeBenchmarkCases(sources: readonly CaseSource[]): MergedCase[] {+ const byId = new Map<string, MergedCase>();+ for (const source of sources) {+ for (const item of source.cases) {+ if (byId.has(item.id)) continue;+ byId.set(item.id, { ...item, machineId: source.machineId });+ }+ }+ return [...byId.values()];+}diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex cc0cdf34..1f905f9e 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -229,6 +229,18 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "install",why: "Pinned Session ids.",},+ {+ kind: "family",+ key: "penguin.machineSessions.",+ scope: "install",+ why: "The Sessions each machine was last seen holding, shown until its connection is held again. Project id and machine id in the key, Session ids in the value — a new root knows none of them.",+ },+ {+ kind: "family",+ key: "penguin.machineAgents.",+ scope: "install",+ why: "The Agents each machine was last seen running, offered by the composer until its connection is held again. Keyed by the same Project and machine a new root would not have.",+ },{kind: "family",key: "penguin.sessionOrder.",diff --git a/packages/web/src/lib/machine-cache.ts b/packages/web/src/lib/machine-cache.tsnew file mode 100644index 00000000..75ad0d8d--- /dev/null+++ b/packages/web/src/lib/machine-cache.ts@@ -0,0 +1,116 @@+/**+ * What each machine was last seen holding, kept across a restart.+ *+ * A machine can only be asked over a held connection, and the moment this page comes up the+ * server may still be re-holding them (a hot push closes every connection its generation+ * opened; the successor brings each back). Everything built only from what answers RIGHT NOW+ * is then this server's answer alone: its Sessions in the list, and — for a workspace that+ * lives over there — no Agents at all to start one with. The remote half of someone's work+ * is simply not there, which reads as lost rather than as pending.+ *+ * So the last answer each machine gave is written down, and shown while that machine is out+ * of reach. It is replaced wholesale the moment the machine answers again — never merged,+ * because something the machine no longer has would then outlive it.+ *+ * Per machine rather than per list: this server's own answers are always available and never+ * need caching, and a machine that answers must replace ITS entries without touching a+ * neighbour's.+ *+ * Storage is best-effort in both directions. Every browser can refuse it (private windows,+ * cleared site data, storage disabled), and reading back something that no longer parses is+ * the same as having nothing — in every one of those cases the page degrades to exactly what+ * it did before there was a cache.+ */+import type { AgentSummary, SessionInfo } from "@prismshadow/penguin-server/api";++const SESSIONS_PREFIX = "penguin.machineSessions.";+const AGENTS_PREFIX = "penguin.machineAgents.";++/**+ * Rows kept per machine. Comfortably more than the sidebar's first page, and far short of+ * what would make the write worth worrying about — this is a placeholder for a list that is+ * about to be refetched, not a copy of the machine's history.+ */+export const CACHED_ROWS_PER_MACHINE = 200;++const keyFor = (prefix: string, projectId: string, machineId: string) =>+ `${prefix}${projectId}:${machineId}`;++/** Replaces one entry. An empty list clears it, which is how something deleted stops returning. */+function remember(prefix: string, projectId: string, machineId: string, items: unknown[]): void {+ try {+ const key = keyFor(prefix, projectId, machineId);+ if (items.length === 0) {+ localStorage.removeItem(key);+ return;+ }+ localStorage.setItem(key, JSON.stringify(items.slice(0, CACHED_ROWS_PER_MACHINE)));+ } catch {+ // Storage refused or is full: the answer is merely not remembered across the next restart.+ }+}++/**+ * One entry, keeping only what `hasId` recognises — a value written by an older version, or+ * hand-edited, may hold something that can be neither rendered nor addressed.+ */+function cached<T>(+ prefix: string,+ projectId: string,+ machineId: string,+ hasId: (row: object) => boolean,+): T[] {+ try {+ const raw = localStorage.getItem(keyFor(prefix, projectId, machineId));+ if (raw === null) return [];+ const parsed: unknown = JSON.parse(raw);+ if (!Array.isArray(parsed)) return [];+ return parsed.filter((row): row is T => typeof row === "object" && row !== null && hasId(row));+ } catch {+ return [];+ }+}++/** Replaces the Sessions this machine is remembered as holding. */+export function rememberMachineSessions(+ projectId: string,+ machineId: string,+ sessions: readonly SessionInfo[],+): void {+ remember(SESSIONS_PREFIX, projectId, machineId, [...sessions]);+}++/** The Sessions this machine was last seen holding. Empty when nothing is remembered. */+export function cachedMachineSessions(projectId: string, machineId: string): SessionInfo[] {+ return cached<SessionInfo>(+ SESSIONS_PREFIX,+ projectId,+ machineId,+ (row) => typeof (row as SessionInfo).sessionId === "string",+ );+}++/**+ * Replaces the Agents this machine is remembered as running.+ *+ * Agents are per server, not per Project: a machine has its own set, and the composer offers+ * THAT set when the chosen workspace lives over there. Until the machine answers there is+ * nothing to pick, so a draft on a remote workspace could not be started at all.+ */+export function rememberMachineAgents(+ projectId: string,+ machineId: string,+ agents: readonly AgentSummary[],+): void {+ remember(AGENTS_PREFIX, projectId, machineId, [...agents]);+}++/** The Agents this machine was last seen running. Empty when nothing is remembered. */+export function cachedMachineAgents(projectId: string, machineId: string): AgentSummary[] {+ return cached<AgentSummary>(+ AGENTS_PREFIX,+ projectId,+ machineId,+ (row) => typeof (row as AgentSummary).agentId === "string",+ );+}diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.tsindex da6465f2..29f8c683 100644--- a/packages/web/src/lib/session-grouping.ts+++ b/packages/web/src/lib/session-grouping.ts@@ -44,19 +44,52 @@ export function isTempWorkspace(workspace: string): boolean {return p === "" || TEMP_WORKSPACE_RE.test(p) || AGENT_WORKSPACES_RE.test(p);}-/** Stable group key for a Session's Workspace (collapse state / React key): the path itself, or the temp sentinel. */-export function workspaceGroupKey(workspace: string): string {- return isTempWorkspace(workspace) ? TEMP_WORKSPACE_GROUP_KEY : workspace.trim();+/**+ * Stable group key for a Session's Workspace (collapse state / React key): the path itself,+ * or the temp sentinel — prefixed by the machine the directory is ON.+ *+ * A Workspace is a directory on a machine, so `/srv/app` on two machines is two different+ * directories and the pair is the identity (the same rule workspace-registry.ts stores by,+ * and the dashboard's rows follow). Keying on the path alone merged them into one folder+ * whose "+" then opened a chat here, in whatever this machine has at that path.+ *+ * A machine of `null` — this server — keys exactly as it did before machines existed, which+ * is what every persisted key already on a browser (collapse state, pin set, group order)+ * was written as. `\0` appears in no path and in no machine id, so the two halves stay+ * separable and neither can forge the other's shape.+ */+export function workspaceGroupKey(workspace: string, machineId: string | null = null): string {+ const key = isTempWorkspace(workspace) ? TEMP_WORKSPACE_GROUP_KEY : workspace.trim();+ return machineId === null ? key : `${machineId}\0${key}`;+}++/**+ * The machine half of a group key; null for this server's own groups — including every key+ * written before a group could name a machine, and the sentinel keys of the other grouping+ * modes, which begin with the separator and so have no machine half.+ */+export function workspaceGroupMachine(groupKey: string): string | null {+ const sep = groupKey.indexOf("\0");+ return sep <= 0 ? null : groupKey.slice(0, sep);+}++/** The Workspace half of a group key: the path, or the temp sentinel. */+export function workspaceGroupPath(groupKey: string): string {+ const sep = groupKey.indexOf("\0");+ return sep <= 0 ? groupKey : groupKey.slice(sep + 1);}/*** Query value that names a Workspace group to the server's list endpoint — the group's* path, or the sentinel the server merges every auto-created temporary Workspace under* (its `TEMP_WORKSPACE_GROUP`; stored Workspaces are realpath results and therefore- * absolute, so the bare word cannot collide with one).+ * absolute, so the bare word cannot collide with one). The machine half is dropped: the+ * query goes TO that machine (the page key carries the source), and no server is asked+ * about a path in another server's name.*/export function workspaceGroupQuery(groupKey: string): string {- return groupKey === TEMP_WORKSPACE_GROUP_KEY ? "temp" : groupKey;+ const path = workspaceGroupPath(groupKey);+ return path === TEMP_WORKSPACE_GROUP_KEY ? "temp" : path;}/** Short display label: the last path segment (the filesystem root yields "/"). */@@ -274,19 +307,20 @@ export interface GroupCounts {}/**- * Folds the per-Agent per-Workspace-path category counts (SessionsResponse.workspaceCounts)- * into workspace-mode groups, keyed like groupSessionsByWorkspace (exact path;- * temporary-workspace paths merged into the temp group). The sidebar labels a group's- * folders and decides its "More" from its own share — never from an Agent's other- * Workspaces, which would advertise folders whose content lives in other groups.+ * Folds the per-Agent per-group category counts (SessionsResponse.workspaceCounts, keyed by+ * the store into workspaceGroupKey form) into workspace-mode groups. The keys arrive+ * machine-qualified because each machine answers about its own paths: summing two machines'+ * counts for one path string would put both totals on both folders, each contradicting the+ * rows under it. The sidebar labels a group's folders and decides its "More" from its own+ * share — never from an Agent's other Workspaces, which would advertise folders whose+ * content lives in other groups.*/export function aggregateWorkspaceCounts(byAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>,): Map<string, GroupCounts> {const out = new Map<string, GroupCounts>();- for (const [agentId, byWorkspace] of byAgent) {- for (const [workspace, counts] of Object.entries(byWorkspace)) {- const key = workspaceGroupKey(workspace);+ for (const [agentId, byGroup] of byAgent) {+ for (const [key, counts] of Object.entries(byGroup)) {let group = out.get(key);if (!group) {group = {@@ -357,12 +391,14 @@ export function aggregateWorkspaceLatest(}export interface WorkspaceGroup<T = SessionInfo> {- /** Stable group key: the Workspace path, or TEMP_WORKSPACE_GROUP_KEY for the merged temp group. */+ /** Stable group key: the machine and the Workspace path (workspaceGroupKey), or the temp sentinel for the merged temp group — one per machine. */key: string;/** Display label: the path basename; empty for the temp group (the sidebar renders the localized name). */label: string;/** Full path for tooltips; null for the merged temp group (its members' paths all differ). */fullPath: string | null;+ /** The machine the directory is on; null for this server — a path is only a directory together with its machine. */+ machineId: string | null;/** True for the merged temporary-workspace group. */temp: boolean;/** Member Sessions, newest first (createdAt desc). */@@ -379,20 +415,28 @@ export interface WorkspaceGroup<T = SessionInfo> {* Generic over the row type (defaulting to SessionInfo, the sidebar's rows): the Trace* page groups its own Session rows with the same logic — only `workspace` and the* `createdAt` sort key are touched.+ *+ * Which machine a Session is on is asked of the caller rather than read off the row: the+ * rows are the server's own SessionInfo, and where each one lives is the browser's fact,+ * held by the map that routes every call about it (lib/session-machines.ts). The default+ * says "this server", which is what a list of one server's Sessions is.*/export function groupSessionsByWorkspace<T extends { workspace: string; createdAt: string }>(sessions: T[],+ machineOf: (session: T) => string | null = () => null,): WorkspaceGroup<T>[] {const byKey = new Map<string, WorkspaceGroup<T>>();for (const s of sessions) {- const key = workspaceGroupKey(s.workspace);+ const machineId = machineOf(s);+ const key = workspaceGroupKey(s.workspace, machineId);let group = byKey.get(key);if (!group) {- const temp = key === TEMP_WORKSPACE_GROUP_KEY;+ const temp = isTempWorkspace(s.workspace);group = {key,label: temp ? "" : workspaceLabel(s.workspace),fullPath: temp ? null : s.workspace.trim(),+ machineId,temp,sessions: [],};@@ -434,11 +478,15 @@ export function completeWorkspaceGroups<T extends { createdAt: string }>(if (existing.has(key)) continue;if (!ALL_CATEGORIES.some((category) => totals[category] > 0)) continue;existing.add(key);- const temp = key === TEMP_WORKSPACE_GROUP_KEY;+ // A counted key names a directory ON a machine, the way the loaded groups are keyed:+ // its path half is what the label and the tooltip show, never the whole key.+ const workspace = workspaceGroupPath(key);+ const temp = workspace === TEMP_WORKSPACE_GROUP_KEY;out.push({key,- label: temp ? "" : workspaceLabel(key),- fullPath: temp ? null : key,+ label: temp ? "" : workspaceLabel(workspace),+ fullPath: temp ? null : workspace,+ machineId: workspaceGroupMachine(key),temp,sessions: [],});diff --git a/packages/web/src/lib/session-machines.ts b/packages/web/src/lib/session-machines.tsnew file mode 100644index 00000000..433c04f7--- /dev/null+++ b/packages/web/src/lib/session-machines.ts@@ -0,0 +1,63 @@+/**+ * Which machine owns a Session.+ *+ * A Session lives on the server whose filesystem its workspace is on: that server runs the+ * agent, holds the messages, writes the trace, serves the files. So every call about a+ * Session has to reach THAT machine — and there are two dozen such endpoints.+ *+ * Rather than thread a machine argument through all of them, the routing is a rule over the+ * PATH: a request to `/api/sessions/<id>/…` goes wherever `<id>` was last seen. Call sites+ * stay unchanged, and a Session's machine is recorded in exactly two places — when a list+ * hands one back, and when one is created.+ *+ * Absence means this machine, which is also every Session that existed before Sessions could+ * live anywhere else. In-memory on purpose: the mapping is rebuilt by the very list that+ * displays them, and a stale entry surviving a reload would route a call at a machine that+ * may no longer own — or may no longer have — that Session.+ */++/** sessionId → the machine it lives on. Absent = this server. */+const owners = new Map<string, string>();++/** Records where a Session lives. `null` (this machine) is stored as absence, not as a value. */+export function rememberSessionMachine(sessionId: string, machineId: string | null): void {+ if (machineId === null) owners.delete(sessionId);+ else owners.set(sessionId, machineId);+}++/** The machine a Session lives on, or null for this one. */+export function machineForSession(sessionId: string): string | null {+ return owners.get(sessionId) ?? null;+}++/** Forgets everything — for a project switch, where the whole list is about to be rebuilt. */+export function forgetSessionMachines(): void {+ owners.clear();+}++/**+ * The session id a path is about, or null when it is not a session-scoped path.+ *+ * Deliberately narrow: only `/api/sessions/<id>` and paths beneath it. The project-scoped+ * `/api/projects/:p/agents/:a/sessions` listing is NOT session-scoped — it asks a server+ * which Sessions it has, and answering it from another machine would be that machine+ * answering a question about this one.+ */+export function sessionIdInPath(path: string): string | null {+ const match = /^\/api\/sessions\/([^/?#]+)/.exec(path);+ if (match === null) return null;+ try {+ return decodeURIComponent(match[1]!);+ } catch {+ return match[1]!; // A malformed escape is not a reason to lose the id.+ }+}++/**+ * The machine a request should go to, from its path alone: the owner of the Session it names,+ * or null for this one. This is the whole routing rule.+ */+export function machineForPath(path: string): string | null {+ const sessionId = sessionIdInPath(path);+ return sessionId === null ? null : machineForSession(sessionId);+}diff --git a/packages/web/src/lib/session-merge.ts b/packages/web/src/lib/session-merge.tsnew file mode 100644index 00000000..23723fe5--- /dev/null+++ b/packages/web/src/lib/session-merge.ts@@ -0,0 +1,33 @@+/**+ * Merging what several machines answered into the one list the sidebar shows.+ *+ * Each machine answers about itself — its own Sessions, its own pagination, its own counts —+ * so the merge happens here, and one thing about it fails quietly: a folder badge that only+ * counted one machine would contradict the rows right under it. Counts are therefore SUMMED+ * across the sources that answered; a source that could not answer contributes no count,+ * which is the truth — a count is a claim about what a server holds now.+ */++/** Newest first, by the field the server's own index orders on; ties by id, so the order is total. */+export function newestFirst<T extends { createdAt: string; sessionId: string }>(+ a: T,+ b: T,+): number {+ return b.createdAt.localeCompare(a.createdAt) || b.sessionId.localeCompare(a.sessionId);+}++/**+ * Sums the per-category counts each machine reported. Undefined when no source reported any —+ * a store must not turn "nobody counted" into a zero, which the folder would render as empty.+ */+export function mergeCounts<T extends Record<string, number>>(+ counts: Array<T | undefined>,+): T | undefined {+ const present = counts.filter((entry): entry is T => entry !== undefined);+ if (present.length === 0) return undefined;+ const out = {} as Record<string, number>;+ for (const entry of present) {+ for (const [key, value] of Object.entries(entry)) out[key] = (out[key] ?? 0) + value;+ }+ return out as T;+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 461f4fb1..785b776d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -260,6 +260,8 @@ export const en: Strings = {/** A secret field with a stored value: submitting it empty keeps the stored one. */pluginSecretKeepHint: "Leave empty to keep the saved value",pluginSecretClear: "Clear stored value",+ /** The Plugins settings page's machine picker: each server keeps its own plugin settings. */+ pluginConfigMachine: "Machine",/** Under a number field whose box does not parse; the save is not sent. */pluginFieldNotNumber: "Must be a number",uploadLimitsTitle: "Upload limits",@@ -1066,6 +1068,7 @@ export const en: Strings = {mcpDeleteConfirm: (name: string): string =>`Delete MCP Server "${name}"? Its tools stop being available from the next Session on.`,defaultValue: "(default)",+ livesOnMachine: (machine: string) => `This Agent lives on ${machine}; manage it there`,deleteAgent: "Delete agent",builtinUndeletable: "Built-in agents cannot be deleted",deleteConfirm: (name: string): string =>@@ -1792,6 +1795,20 @@ export const en: Strings = {applyConfirmRemove: (name: string) => `Remove ${name}?`,applyConfirmBody: "Agent runs in progress in every Project will be stopped.",pageTitle: "Plugins",+ /** The header's machine picker: which machine's plugins the page shows and edits. */+ viewMachine: "Machine",+ allMachines: "All machines",+ thisServer: "This server",+ /** A row listed for some machines only, by alias. */+ onlyOn: (names: string) => `only on ${names}`,+ /** An all-machines row listed only for other machines. */+ notHere: "not on this server",+ /** A row the Project lists for a machine that has not reported it running yet. */+ notSynced: "not on that machine yet",+ /** Remove is unavailable in a machine's view for a plugin the shared table lists. */+ sharedCannotRemove: "Enabled on all machines: remove it in the All machines view.",+ machineUnreadable: (name: string, reason: string) =>+ `Could not read what ${name} runs: ${reason}`,/** Header icon button opening the Settings dialog on its Plugins page (admin only). */openSettings: "Plugin settings",pageDesc:@@ -2078,6 +2095,8 @@ export const en: Strings = {deleteWorkspaceConfirm: (name: string) =>`Remove "${name}"? This only removes the workspace group from the sidebar — the directory on disk and existing chats are untouched, and it can be re-added anytime.`,tempWorkspaces: "Temporary workspaces",+ onMachine: (name: string, machine: string) => `${name} [SSH: ${machine}]`,+ machineTag: (machine: string) => `[SSH: ${machine}]`,newSessionInWorkspace: "New chat in this workspace",draftSubtitle: "The self-evolving agent that excels at AI development tasks",/** Folder names for the draft page's collapsible examples (bookmark-style: exactly one open at a time). */@@ -2484,6 +2503,12 @@ Scenarios:statParenOpen: " (",statParenClose: ")",noSessions: "No Sessions yet",+ /** The routed conversation is on a machine with no connection held: not gone, just out of reach from here. */+ sessionOnOfflineMachine: (machine: string) =>+ `This conversation is on ${machine}, which is not connected right now.`,+ sessionOnOfflineMachineUnknown:+ "This conversation is on a machine that is not connected right now.",+ sessionOfflineHint: "It will open as soon as the connection is back.",emptyStream: "Send a message to start the conversation",historyLoadFailed: "Failed to load history",statsLabel: "Stats",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 7a2ab7ae..bd2599ad 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -294,6 +294,8 @@ export const zh = {/** A secret field with a stored value: submitting it empty keeps the stored one. */pluginSecretKeepHint: "留空保持已保存的值不变",pluginSecretClear: "清除已存值",+ /** The Plugins settings page's machine picker: each server keeps its own plugin settings. */+ pluginConfigMachine: "机器",/** Under a number field whose box does not parse; the save is not sent. */pluginFieldNotNumber: "必须是数字",uploadLimitsTitle: "上传限制",@@ -1064,6 +1066,8 @@ export const zh = {`确认删除 MCP Server「${name}」?其工具自下次 Session 起不再可用。`,defaultValue: "(缺省)",/** Reset link next to the runtime dropdowns: rewinds the local pick back to "not overridden" (the menus offer no inherit row). */+ /** An Agent whose state directory is on a machine: what this server cannot act on, and where it can be. */+ livesOnMachine: (machine: string) => `该 Agent 在 ${machine} 上,请到那台机器上管理`,deleteAgent: "删除 Agent",builtinUndeletable: "内置 Agent 不可被删除",deleteConfirm: (name: string): string =>@@ -1802,6 +1806,19 @@ export const zh = {applyConfirmRemove: (name: string) => `移除 ${name}?`,applyConfirmBody: "所有 Project 中正在进行的 Agent 运行都会被中止。",pageTitle: "插件",+ /** The header's machine picker: which machine's plugins the page shows and edits. */+ viewMachine: "机器",+ allMachines: "所有机器",+ thisServer: "本机",+ /** A row listed for some machines only, by alias. */+ onlyOn: (names: string) => `仅在 ${names}`,+ /** An all-machines row listed only for other machines. */+ notHere: "本机不运行",+ /** A row the Project lists for a machine that has not reported it running yet. */+ notSynced: "尚未同步到该机器",+ /** Remove is unavailable in a machine's view for a plugin the shared table lists. */+ sharedCannotRemove: "已对所有机器启用:请在「所有机器」视图中移除。",+ machineUnreadable: (name: string, reason: string) => `无法读取 ${name} 运行的插件:${reason}`,/** Header icon button opening the Settings dialog on its Plugins page (admin only). */openSettings: "插件设置",pageDesc:@@ -2084,6 +2101,10 @@ export const zh = {deleteWorkspaceConfirm: (name: string) =>`确定移除「${name}」?仅从侧边栏移除该工作区分组,不影响磁盘目录与已有会话,可随时重新添加。`,tempWorkspaces: "临时工作区",+ /** A name that only means something on another machine, written with the ssh alias that reaches it. */+ onMachine: (name: string, machine: string) => `${name} [SSH: ${machine}]`,+ /** The same mark on its own, for a row that is attributed to a machine rather than named after one. */+ machineTag: (machine: string) => `[SSH: ${machine}]`,newSessionInWorkspace: "在此工作区新建对话",draftSubtitle: "最擅长 AI 开发任务的自进化 Agent",/** Collapsed group names for the home-page examples (bookmark style; only one open at a time). */@@ -2490,6 +2511,10 @@ Benchmark:statParenOpen: "(",statParenClose: ")",noSessions: "还没有 Session",+ /** The routed conversation is on a machine with no connection held: not gone, just out of reach from here. */+ sessionOnOfflineMachine: (machine: string) => `这个对话在 ${machine} 上,当前没有连接。`,+ sessionOnOfflineMachineUnknown: "这个对话在某台机器上,当前没有连接。",+ sessionOfflineHint: "连接恢复后会自动打开。",emptyStream: "发送一条消息开始对话",historyLoadFailed: "历史消息加载失败",statsLabel: "统计信息",diff --git a/packages/web/src/lib/terminal-machines.ts b/packages/web/src/lib/terminal-machines.tsnew file mode 100644index 00000000..7383a044--- /dev/null+++ b/packages/web/src/lib/terminal-machines.ts@@ -0,0 +1,98 @@+/**+ * Which machine a terminal lives on.+ *+ * A terminal is a pty process on one machine's kernel: it is created there, its bytes come+ * from there, and killing it means killing it there. So every call about one has to reach+ * THAT machine — the same problem Sessions have, answered the same way (lib/session-machines.ts):+ * a rule over the PATH, so the call sites stay unchanged and the mapping is recorded in one+ * place, when a list hands a terminal back or when one is created.+ *+ * Absence means this machine, which is also every terminal that existed before terminals+ * could live anywhere else. In memory on purpose: it is rebuilt by the very list that+ * displays them, and a stale entry surviving a reload would address a pty on a machine that+ * may no longer hold — or no longer have — it.+ */+import { apiUrl } from "./server-context";++/** terminalId → the machine it lives on. Absent = this server. */+const owners = new Map<string, string>();++/** The machines whose terminals belong in the list, published by SessionsProvider. */+let machineIds: readonly string[] = [];+/**+ * Whether that publication has happened at all. Before it, an empty `machineIds` means+ * "not asked yet", not "no machines" — and the two must not be confused by anything that+ * treats the list as the whole truth. A fresh page sits in that state until the machine+ * list has been read once, which is exactly when a Project's terminals may all be elsewhere.+ */+let published = false;++/** Records where a terminal lives. `null` (this machine) is stored as absence, not a value. */+export function rememberTerminalMachine(terminalId: string, machineId: string | null): void {+ if (machineId === null) owners.delete(terminalId);+ else owners.set(terminalId, machineId);+}++/** The machine a terminal lives on, or null for this one. */+export function machineForTerminal(terminalId: string): string | null {+ return owners.get(terminalId) ?? null;+}++/** Forgets everything — for a sign-out, where the whole list is about to be rebuilt. */+export function forgetTerminalMachines(): void {+ owners.clear();+ machineIds = [];+ published = false;+}++/**+ * The machines the terminal list should ask, besides this one. Kept here rather than read+ * from the Sessions store because the list refreshes from a module-scope timer and the+ * Ctrl+` hotkey creates shells from a module-scope listener — neither has React context.+ */+export function setTerminalMachines(ids: readonly string[]): void {+ machineIds = [...ids];+ published = true;+}++/**+ * Whether the machine set is known yet. A caller that would DISCARD something on the+ * strength of a terminal's absence has to wait for this; one that merely displays what it+ * can does not.+ */+export function terminalMachinesPublished(): boolean {+ return published;+}++/** Every source the terminal list asks: this server first, then each machine. */+export function terminalSources(): (string | null)[] {+ return [null, ...machineIds];+}++/**+ * The terminal id a path is about, or null when it is not terminal-scoped.+ *+ * Deliberately narrow, exactly as the Session rule is: only `/api/terminals/<id>` and paths+ * beneath it. The bare `/api/terminals` collection is NOT — it asks a server which terminals+ * IT has, and answering that from another machine would be that machine answering a question+ * about this one.+ */+export function terminalIdInPath(path: string): string | null {+ const match = /^\/api\/terminals\/([^/?#]+)/.exec(path);+ if (match === null) return null;+ try {+ return decodeURIComponent(match[1]!);+ } catch {+ return match[1]!; // A malformed escape is not a reason to lose the id.+ }+}++/**+ * A terminal path, addressed to the machine that holds it. `server` overrides the rule, for+ * the one call that cannot use it: creating a terminal names a machine before any id exists.+ */+export function terminalUrl(path: string, server?: string | null): string {+ if (server !== undefined) return apiUrl(path, server);+ const id = terminalIdInPath(path);+ return apiUrl(path, id === null ? null : machineForTerminal(id));+}diff --git a/packages/web/src/lib/workflow-tabs.ts b/packages/web/src/lib/workflow-tabs.tsindex 220e7164..c2c85ffe 100644--- a/packages/web/src/lib/workflow-tabs.ts+++ b/packages/web/src/lib/workflow-tabs.ts@@ -13,6 +13,7 @@* the strip pointing at nothing.*/import type { WorkflowInfo } from "@prismshadow/penguin-server/api";+import { apiUrl } from "./server-context";export interface WorkflowTab {/** `<workflowId>/<key>`: what the strip selects by. */@@ -22,8 +23,10 @@ export interface WorkflowTab {key: string;title: string;titleZh?: string;- /** Where the page is served from. */+ /** Where the page is served from — through the machine's connection when the workflow lives on one. */src: string;+ /** The machine whose server holds the workflow (the Agent's Session runs there); null = this server. */+ machineId: string | null;/** The workflow's package name, for the frame's bar. */name: string;version: string | null;@@ -76,7 +79,10 @@ export function workflowNoticesOf(workflows: readonly WorkflowInfo[]): WorkflowN.map((w) => ({ workflowId: w.id, error: w.error, hints: w.hints ?? [] }));}-export function workflowTabsOf(workflows: readonly WorkflowInfo[]): WorkflowTab[] {+export function workflowTabsOf(+ workflows: readonly WorkflowInfo[],+ machineId: string | null = null,+): WorkflowTab[] {return workflows.flatMap((w) =>w.tabs.flatMap((tab) =>"iframe" in tab.renderer@@ -87,7 +93,8 @@ export function workflowTabsOf(workflows: readonly WorkflowInfo[]): WorkflowTab[key: tab.key,title: tab.title,...(tab.titleZh === undefined ? {} : { titleZh: tab.titleZh }),- src: tab.renderer.iframe.src,+ src: apiUrl(tab.renderer.iframe.src, machineId),+ machineId,name: w.name,version: w.version,revision: w.revision,@@ -119,9 +126,12 @@ export function workflowAppPath(agentId: string,workflowId: string,tabKey?: string,+ machineId: string | null = null,): string {const segments = [projectId, agentId, workflowId, ...(tabKey === undefined ? [] : [tabKey])];- return `/app/${segments.map(encodeURIComponent).join("/")}`;+ const path = `/app/${segments.map(encodeURIComponent).join("/")}`;+ // The machine is not part of the workflow's name, only of where to ask for it.+ return machineId === null ? path : `${path}?machine=${encodeURIComponent(machineId)}`;}/** The tab a full-page route names: that key, or the workflow's first tab when it names none. */diff --git a/packages/web/src/lib/workspace-machines.ts b/packages/web/src/lib/workspace-machines.tsindex 0c8299a6..d109d1da 100644--- a/packages/web/src/lib/workspace-machines.ts+++ b/packages/web/src/lib/workspace-machines.ts@@ -8,6 +8,7 @@* machine id and labelled by ssh alias.*/import type { MachineInfo, MachinesResponse } from "@prismshadow/penguin-server/api";+import { S } from "./strings";/** One machine a workspace can live on, and whether it can be browsed right now. */export interface WorkspaceMachine {@@ -85,6 +86,16 @@ export function recordedMachineId(machine: WorkspaceMachine | undefined): stringreturn machine === undefined || machine.local ? undefined : (machine.id ?? undefined);}+/**+ * A name qualified by the machine it is on: `Name [SSH: alias]`, and the bare name for this+ * one. Two machines can hold the same directory path — and the same Workspace name — so a+ * name shown without its machine is a name that cannot be told apart from another machine's.+ * This server needs no saying: it is where the app is, and marking it would mark everything.+ */+export function nameOnMachine(name: string, machineLabel: string | null): string {+ return machineLabel === null ? name : S.chat.onMachine(name, machineLabel);+}+/** 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.tsindex 7f27a9b5..26176ca8 100644--- a/packages/web/src/lib/workspace-registry.ts+++ b/packages/web/src/lib/workspace-registry.ts@@ -1,29 +1,35 @@/*** Manually-added Workspaces of the sidebar (pure decisions, unit tested): the header's- * 新建工作区 button lets the user browse to a directory, and the picked path must show+ * new-workspace button lets the user browse to a directory, and the picked path must show* up as a workspace group IMMEDIATELY — even with zero Sessions. There is no Workspace* entity on the server (groups are otherwise derived purely from Session paths), so the* picked paths persist frontend-side per Project (`penguin.…` key naming, injectable* storage — the model-group-expansion.ts convention) and merge into the grouping as* empty groups.*- * An entry is `{ path, alias? }`: the alias is a display name set via the group's- * 重命名工作区 (it replaces the basename as the group label — for session-backed groups- * too — while the full path stays in the tooltip; an empty alias reverts to the- * basename). Loads stay tolerant of the branch's earlier string-only stored shape.+ * An entry is `{ path, machineId?, alias? }`, and the first two together are its identity:+ * one directory on one machine. The alias is a display name set via the group's rename+ * action (it replaces the basename as the group label — for session-backed groups too —+ * while the full path stays in the tooltip; an empty alias reverts to the basename). Loads+ * stay tolerant of the branch's earlier string-only stored shape.*- * Lifecycle: an entry stays until 删除工作区 unregisters it (sidebar-only — disk and- * Sessions are never touched; with Sessions present the group simply persists as+ * Lifecycle: an entry stays until the group's remove action unregisters it (sidebar-only —+ * disk and Sessions are never touched; with Sessions present the group simply persists as* session-derived). Once Sessions exist the entry mostly dedups away at merge, but it* still carries the alias and keeps the group visible after those Sessions are gone.*/-import { isTempWorkspace, workspaceGroupKey, workspaceLabel } from "./session-grouping";+import {+ isTempWorkspace,+ workspaceGroupKey,+ workspaceGroupPath,+ workspaceLabel,+} from "./session-grouping";import type { WorkspaceGroup } from "./session-grouping";/** One registered Workspace: the normalized path, plus an optional display alias. */export interface WorkspaceEntry {path: string;- /** Display name overriding the path basename (set via 重命名工作区; absent = basename). */+ /** Display name overriding the path basename (set via the group's rename action; absent = basename). */alias?: string;/*** The machine this directory is ON, by its own id. Absent means the local machine —@@ -36,6 +42,18 @@ export interface WorkspaceEntry {machineId?: string;}+/**+ * Whether two entries name the SAME directory: the path and the machine both, with absence+ * and null both meaning this one. Every lookup in this module goes through it — a path-only+ * match would rename, or delete, whichever machine's entry came first in the array.+ */+function sameWorkspace(+ a: { path: string; machineId?: string | null },+ b: { path: string; machineId?: string | null },+): boolean {+ return a.path === b.path && (a.machineId ?? null) === (b.machineId ?? null);+}+/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */export interface WorkspaceRegistryStorage {getItem(key: string): string | null;@@ -103,7 +121,9 @@ export function loadWorkspaceRegistry(const out: WorkspaceEntry[] = [];for (const x of parsed) {const entry = parseEntry(x);- if (entry !== null && !out.some((e) => e.path === entry.path)) out.push(entry);+ // Deduped on the PAIR, as registerWorkspace stores it: dropping the second machine's+ // entry here would lose a Workspace on load, silently and for good.+ if (entry !== null && !out.some((e) => sameWorkspace(e, entry))) out.push(entry);}return out;} catch {@@ -144,36 +164,47 @@ export function registerWorkspace(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;- }+ if (entries.some((e) => sameWorkspace(e, { path: p, machineId }))) return entries;return [{ path: p, ...(machineId === undefined ? {} : { machineId }) }, ...entries];}/*** Sets (or, with a blank alias, clears) a registered Workspace's display alias.- * Returns the INPUT array unchanged (same reference) when the path isn't registered- * or the alias doesn't actually change.+ * Returns the INPUT array unchanged (same reference) when the pair isn't registered+ * or the alias doesn't actually change. The machine is carried across the rewrite: an+ * entry that lost it would name a directory here rather than the one that was renamed.*/export function setWorkspaceAlias(entries: readonly WorkspaceEntry[],path: string,+ machineId: string | null,alias: string,): readonly WorkspaceEntry[] {const a = alias.trim();- const entry = entries.find((e) => e.path === path);+ const target = { path, ...(machineId === null ? {} : { machineId }) };+ const entry = entries.find((e) => sameWorkspace(e, target));if (!entry || (entry.alias ?? "") === a) return entries;return entries.map((e) =>- e.path === path ? (a === "" ? { path: e.path } : { path: e.path, alias: a }) : e,+ sameWorkspace(e, target)+ ? {+ path: e.path,+ ...(a === "" ? {} : { alias: a }),+ ...(e.machineId === undefined ? {} : { machineId: e.machineId }),+ }+ : e,);}-/** 删除工作区: drops the registry entry (sidebar-only — disk and Sessions are untouched). Same-reference fast exit when the path isn't registered. */+/** Drops the registry entry (sidebar-only — disk and Sessions are untouched). Same-reference fast exit when the pair isn't registered. */export function unregisterWorkspace(entries: readonly WorkspaceEntry[],path: string,+ machineId: string | null = null,): readonly WorkspaceEntry[] {- return entries.some((e) => e.path === path) ? entries.filter((e) => e.path !== path) : entries;+ const target = { path, ...(machineId === null ? {} : { machineId }) };+ return entries.some((e) => sameWorkspace(e, target))+ ? entries.filter((e) => !sameWorkspace(e, target))+ : entries;}/**@@ -195,18 +226,23 @@ export function mergeRegisteredWorkspaces<T>(registered: readonly WorkspaceEntry[],): WorkspaceGroup<T>[] {const aliasByKey = new Map(- registered.filter((e) => e.alias !== undefined).map((e) => [e.path, e.alias as string]),+ registered+ .filter((e) => e.alias !== undefined)+ .map((e) => [workspaceGroupKey(e.path, e.machineId ?? null), e.alias as string]),);const existing = new Set(groups.map((g) => g.key));const added: WorkspaceGroup<T>[] = [];- for (const { path, alias } of registered) {- const key = workspaceGroupKey(path);- if (existing.has(key) || key !== path) continue; // already grouped, or a temp-shaped path+ for (const { path, alias, machineId } of registered) {+ const machine = machineId ?? null;+ const key = workspaceGroupKey(path, machine);+ // Already grouped (by its own machine's Sessions), or a temp-shaped path.+ if (existing.has(key) || workspaceGroupPath(key) !== path) continue;existing.add(key);added.push({key,label: alias ?? workspaceLabel(path),fullPath: path,+ machineId: machine,temp: false,sessions: [],});diff --git a/packages/web/src/state/project.tsx b/packages/web/src/state/project.tsxindex adb96463..3420e32c 100644--- a/packages/web/src/state/project.tsx+++ b/packages/web/src/state/project.tsx@@ -123,11 +123,7 @@ function createProjectStore() {try {const res = await api.listAgents(currentProjectId);const wanted = get().currentAgentId ?? localStorage.getItem(agentKey(currentProjectId));- const found = res.agents.find((a) => a.agentId === wanted);- // Default to conversing with default_agent.- const fallback =- res.agents.find((a) => a.agentId === "default_agent") ?? res.agents[0] ?? null;- set({ agents: res.agents, currentAgentId: (found ?? fallback)?.agentId ?? null });+ set({ agents: res.agents, currentAgentId: agentOf(res.agents, wanted)?.agentId ?? null });} finally {set({ agentsLoading: false });}@@ -141,6 +137,25 @@ function createProjectStore() {}));}+/**+ * The Agent an id names among THIS server's, else the one a conversation defaults to+ * (`default_agent`, then the first). The id may name an Agent only a machine has — a draft or+ * a Session on that machine follows its pick through to the current Agent — and the current+ * Agent is never one of those: the chat page renders nothing until there is a current Agent,+ * so resolving such an id to null left every chat route on its placeholder until a reload.+ */+export function agentOf(+ agents: readonly AgentSummary[],+ agentId: string | null,+): AgentSummary | null {+ return (+ agents.find((a) => a.agentId === agentId) ??+ agents.find((a) => a.agentId === "default_agent") ??+ agents[0] ??+ null+ );+}+export function ProjectProvider({ children }: { children: ReactNode }) {const [store] = useState(createProjectStore);const state = useStore(store);@@ -158,7 +173,7 @@ export function ProjectProvider({ children }: { children: ReactNode }) {const value = useMemo<ProjectContextValue>(() => {const currentProject =state.projects.find((p) => p.projectId === state.currentProjectId) ?? null;- const currentAgent = state.agents.find((a) => a.agentId === state.currentAgentId) ?? null;+ const currentAgent = agentOf(state.agents, state.currentAgentId);return {projects: state.projects,projectsLoading: state.projectsLoading,diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex 6a16369b..a48386a9 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -32,7 +32,15 @@* user-event subscription) and republishes the store's state through the same context value* as before. Mutations read current values via store.getState() (the old refs' job).*/-import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import type { ReactNode } from "react";import type {ServerEvent,@@ -45,9 +53,24 @@ import type {import { useStore } from "zustand/react";import { createStore } from "zustand/vanilla";import * as api from "../api/endpoints";+import { ApiError } from "../api/client";import { openUserEvents } from "../api/sse";import { isCompanyEvent, publishCompanyEvent, publishCompanyResync } from "./company";import { WORKFLOW_UPDATED_EVENT } from "../lib/workflow-tabs";+import { mergeCounts, newestFirst } from "../lib/session-merge";+import {+ forgetSessionMachines,+ machineForSession,+ rememberSessionMachine,+} from "../lib/session-machines";+import {+ cachedMachineAgents,+ cachedMachineSessions,+ rememberMachineAgents,+ rememberMachineSessions,+} from "../lib/machine-cache";+import { setTerminalMachines } from "../lib/terminal-machines";+import { machineIdOf } from "../lib/workspace-machines";import {FOLDER_CATEGORIES,SIDEBAR_PAGE_SIZE,@@ -55,6 +78,7 @@ import {sessionCategory,splitPage,workspaceGroupKey,+ workspaceGroupMachine,workspaceGroupQuery,} from "../lib/session-grouping";import { noteScheduleEvent } from "../features/schedules/schedule-store";@@ -67,12 +91,25 @@ interface SessionsContextValue {byAgent: ReadonlyMap<string, SessionInfo[]>;/** agentId → per-category totals from the last list fetch (folder labels; kept in step locally on add / remove / archive toggles). */countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;- /** agentId → the same totals broken down by Workspace path (workspace-mode groups read their own share from it; maintained like countsByAgent). */+ /** agentId → the same totals broken down by Workspace group — a path ON a machine, keyed by workspaceGroupKey (workspace-mode groups read their own share from it; maintained like countsByAgent). */workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;/** agentId → each Workspace path's newest Session `createdAt` from the last list fetch: what places a workspace-mode group before any of its rows are loaded. */workspaceLatestByAgent: ReadonlyMap<string, Readonly<Record<string, string>>>;/** Every run status the user channel has reported this page's lifetime, by Session id — loaded row or not (see useLiveSessionStatuses). */liveStatuses: ReadonlyMap<string, SessionStatus>;+ /**+ * machineId → the ssh alias that reaches it, for naming what is not on this server. Empty+ * when the machine list could not be read (it is admin-only): a caller then shows the bare+ * name, which is what it showed before machines existed.+ */+ machineLabels: ReadonlyMap<string, string>;+ /**+ * The Project's machines this server holds a connection to — the ones whose API can be+ * reached through the proxy right now. Any page that has to ask "what does this Agent have+ * over there" fans out over this alongside this server, rather than fetching the+ * admin-only machine list of its own.+ */+ machineIds: string[];/*** Whether a pair's first page has been fetched (false = the folder shows nothing because* nothing was asked for yet). `workspaceGroup` asks about ONE group's own stream, which@@ -82,12 +119,34 @@ interface SessionsContextValue {/** Whether the server still holds unfetched Sessions of a category for an Agent (or for one of its Workspace groups) — an unloaded pair answers from the counts. */hasMoreFor: (agentId: string, category: SessionCategory, workspaceGroup?: string) => boolean;/**- * Whether the list is still being assembled — including the window where the Agent set it+ * Whether the list has NOTHING to show yet — including the window where the Agent set it* is fetched for is itself being refetched (a Project switch clears it). Consumers gate* their "no sessions" empty state on this, so it must not read false while the answer is* merely not known yet.+ *+ * Emphatically not "a fetch is in flight". A refresh over rows already on screen leaves+ * this false: the chat page renders a skeleton IN PLACE OF the open conversation while it+ * is true, so a refresh that raised it would blank the conversation you are reading — and+ * the list refreshes whenever the machine set moves.*/loading: boolean;+ /**+ * Whether a machine of this Project could not be asked this round — no connection is held+ * to it, or the server behind the connection did not answer.+ *+ * A Session missing from the list means "this server has not got it", which is only the+ * same as "it does not exist" when every server that could hold it answered. The chat page+ * reads this before deciding a routed id is gone: concluding that from a lookup against+ * THIS server, while the machine the Session lives on is out of reach, drops the reader+ * out of a conversation that is merely unreachable.+ */+ machinesUnreachable: boolean;+ /**+ * The Project's machines that did not answer this round, by machine id. Their rows on+ * screen come from the cache (lib/machine-cache.ts), so a caller that has to decide whether+ * a Session is REACHABLE — not merely whether it is listed — asks this.+ */+ offlineMachineIds: string[];reload: () => Promise<void>;/** Fetches a category's first page for each given unloaded Agent and the next page for each loaded one with more (no-op otherwise); `workspaceGroup` pages that group's own stream instead of the Agent's whole one. */loadMoreFor: (@@ -131,27 +190,38 @@ export interface LiveRowFields {const SessionsContext = createContext<SessionsContextValue | null>(null);/**- * Page-state key of one (Agent, category, Workspace-group) triple. The scope is the- * server's query form of a group (workspaceGroupQuery) — a path or the temp sentinel —- * and "" means the Agent's whole stream, which is what Agent and time grouping page down.- * "\0" appears in none of the three (the merged temp group's own key does contain one,- * which is exactly why the query form is what gets stored).+ * Page-state key of one (Agent, category, Workspace-group, source) run. The scope is the+ * server's query form of a group (workspaceGroupQuery) — a path or the temp sentinel — and+ * "" means the Agent's whole stream. The source is the machine whose Sessions that stream is+ * walked on (`null` = this server): each server pages its own rows with its own offsets, so+ * one shared cursor would ask machine B for rows only machine A had reached. "\0" appears in+ * none of the four (the merged temp group's own key does contain one, which is exactly why+ * the query form is what gets stored).*/-const pageKey = (agentId: string, category: SessionCategory, scope = "") =>- `${agentId}\0${category}\0${scope}`;+const pageKey = (+ agentId: string,+ category: SessionCategory,+ scope = "",+ source: string | null = null,+) => `${agentId}\0${category}\0${scope}\0${source ?? ""}`;/** Every list category, in the order the store loads them (active eagerly, the folders on demand). */const ALL_CATEGORIES: readonly string[] = ["active", ...FOLDER_CATEGORIES];-/** The triple a page key names, or null if it is not one (never, in practice — a guard for the reload scan). */+/** The run a page key names, or null if it is not one (never, in practice — a guard for the reload scan). */function parsePageKey(key: string,-): { agentId: string; category: SessionCategory; scope: string } | null {+): { agentId: string; category: SessionCategory; scope: string; source: string | null } | null {const parts = key.split("\0");- if (parts.length !== 3) return null;- const [agentId, category, scope] = parts as [string, string, string];+ if (parts.length !== 4) return null;+ const [agentId, category, scope, source] = parts as [string, string, string, string];return ALL_CATEGORIES.includes(category)- ? { agentId, category: category as SessionCategory, scope }+ ? {+ agentId,+ category: category as SessionCategory,+ scope,+ source: source === "" ? null : source,+ }: null;}@@ -159,6 +229,23 @@ function parsePageKey(const scopeOf = (workspaceGroup?: string) =>workspaceGroup === undefined || workspaceGroup === "" ? "" : workspaceGroupQuery(workspaceGroup);+/**+ * Which servers a scope is about: every one for the Agent's whole stream, and exactly the+ * one a Workspace group is ON for a group.+ *+ * A group is a directory on a machine, so the others hold nothing of it. Asking them is not+ * merely wasteful: their answers about a path that happens to have the same name would decide+ * this group's "load more" and its loaded-ness — a folder offering more rows that belong to+ * another machine's folder, and never arrive in this one.+ */+const sourcesFor = (+ allSources: readonly (string | null)[],+ workspaceGroup?: string,+): (string | null)[] =>+ workspaceGroup === undefined || workspaceGroup === ""+ ? [...allSources]+ : [workspaceGroupMachine(workspaceGroup)];+/** One pair's paging cursor. */interface PagePosition {/** Whether the server still has unfetched rows past `fetched`. */@@ -177,6 +264,31 @@ interface SessionsStoreState {/** Provider-synced fetch context: the current Project and its Agent set (what reload() targets). */projectId: string | null;agentIds: string[];+ /**+ * Machines whose Sessions are merged into this list, alongside this server's: the ones this+ * server holds a connection to. A Session lives on the server whose filesystem its+ * workspace is on, so a Project's list is not one server's answer — it is every one of+ * them, ordered together.+ */+ machineIds: string[];+ /**+ * The Project's machines this list could NOT ask — no connection held — by machine id.+ * It is the difference between "this server does not have that Session" and "nobody who+ * might have it answered", which is the whole question for a routed id that is missing+ * from the list (features/chat/chat-page.tsx). Their rows come from the cache.+ */+ offlineMachineIds: string[];+ /**+ * machineId → the Agents THAT machine runs, which are not this Project's.+ *+ * An Agent is per server: a machine has its own set, and the Agents page offers a new chat+ * on one of them (features/agents/agents-page.tsx). The Session that follows belongs to an+ * Agent this server has never heard of, so a list built from this server's Agent ids alone+ * would ask the machine the wrong question and drop the row on the next reload — and with+ * it the record of which machine holds that Session, which is what a deep link needs to+ * reach it at all.+ */+ agentIdsByMachine: Readonly<Record<string, string[]>>;sessions: SessionInfo[];/**@@ -282,7 +394,10 @@ export function createSessionsStore() {const workspaceCounts = get().workspaceCountsByAgent;const wsCur = workspaceCounts.get(agentId);if (wsCur) {- const ws = wsCur[workspace] ?? {+ // Keyed by GROUP, as the fetch stores them: the badge belongs to the directory on+ // the machine this Session is on, not to every machine holding that path string.+ const key = workspaceGroupKey(workspace, machineForSession(session.sessionId));+ const ws = wsCur[key] ?? {active: 0,subagent: 0,schedule: 0,@@ -292,7 +407,7 @@ export function createSessionsStore() {const next = new Map(workspaceCounts);next.set(agentId, {...wsCur,- [workspace]: { ...ws, [category]: Math.max(0, ws[category] + delta) },+ [key]: { ...ws, [category]: Math.max(0, ws[category] + delta) },});set({ workspaceCountsByAgent: next });}@@ -301,6 +416,9 @@ export function createSessionsStore() {return {projectId: null,agentIds: [],+ machineIds: [],+ offlineMachineIds: [],+ agentIdsByMachine: {},sessions: [],deletedSessionIds: new Set(),@@ -312,41 +430,65 @@ export function createSessionsStore() {loading: true,reload: async () => {- const { projectId, agentIds } = get();+ const { projectId, agentIds, machineIds, offlineMachineIds, agentIdsByMachine } = get();// No context to fetch against yet. `loading` is deliberately left alone rather than// cleared: nothing was loaded, so reporting "done" here would be a lie — and one the// empty state renders. The Provider's reset step raised it and a later reload,// once an Agent set exists, is what clears it.if (!projectId || agentIds.length === 0) return;const g = ++gen;- set({ loading: true });+ // Only when there is nothing on screen. Rows already listed stay true while this+ // refetches — a machine appearing or dropping out changes which servers are asked,+ // not whether what is already shown is still so — and the chat page reads this flag+ // to decide whether to draw a skeleton over the open conversation.+ if (get().sessions.length === 0) set({ loading: true });+ let applied = false;+ // This server first, then every machine of the Project this server holds a+ // connection to. Order matters only as a tie-break for equal timestamps.+ const sources: (string | null)[] = [null, ...machineIds];+ // One job per (Agent, source), asking each server about the Agents IT can answer for:+ // this server about the Project's, a machine about those plus its own. A machine-only+ // Agent's Sessions are listed by nobody otherwise.+ const jobs = sources.flatMap((source) => {+ const ids =+ source === null+ ? agentIds+ : [...new Set([...agentIds, ...(agentIdsByMachine[source] ?? [])])];+ return ids.map((agentId) => ({ agentId, source }));+ });try {const results = await Promise.all(- agentIds.map(async (agentId) => {+ jobs.map(async ({ agentId, source }) => {// The Agent's whole-stream active first page (with per-category totals)- // always; plus the first page of every other pair already on screen — an open- // folder, and each Workspace group paging its own stream — because a reload- // triggered by a server event must refresh them, not blank them.+ // always; plus the first page of every other pair already on screen — an+ // open folder, and each Workspace group paging its own stream — because a+ // reload triggered by a server event must refresh them, not blank them.const pairs: { category: SessionCategory; scope: string }[] = [{ category: "active", scope: "" },];for (const key of get().pageState.keys()) {const parsed = parsePageKey(key);- if (parsed === null || parsed.agentId !== agentId) continue;+ if (parsed === null || parsed.agentId !== agentId || parsed.source !== source)+ continue;if (parsed.category === "active" && parsed.scope === "") continue;pairs.push({ category: parsed.category, scope: parsed.scope });}try {const pages = await Promise.all(pairs.map(async ({ category, scope }) => {- const res = await api.listSessions(projectId, agentId, {- offset: 0,- limit: SIDEBAR_PAGE_SIZE + 1,- category,- excludeOrg: true,- ...(scope === "" ? {} : { workspaceGroup: scope }),- ...(category === "active" && scope === "" ? { withCounts: true } : {}),- });+ const res = await api.listSessions(+ projectId,+ agentId,+ {+ offset: 0,+ limit: SIDEBAR_PAGE_SIZE + 1,+ category,+ excludeOrg: true,+ ...(scope === "" ? {} : { workspaceGroup: scope }),+ ...(category === "active" && scope === "" ? { withCounts: true } : {}),+ },+ source,+ );return {category,scope,@@ -357,40 +499,187 @@ export function createSessionsStore() {};}),);- return { agentId, pages };- } catch {- // A single Agent's fetch failure shouldn't bring down the whole batch (e.g. its directory was deleted externally).- return { agentId, pages: [] };+ return { agentId, source, pages, answered: true };+ } catch (err) {+ // Two very different things arrive here, and treating them alike is what+ // emptied the sidebar. An Agent is per-server, so a server simply not+ // having this one answers 404: an ANSWER, and the ordinary case. Anything+ // else — this server mid-swap, a connection held to a server that is not+ // serving, the network — is a failure to answer at all, and an empty+ // result standing in for it replaces rows that are perfectly alive.+ const absent = err instanceof ApiError && err.status === 404;+ return { agentId, source, pages: [], answered: absent };}}),);if (g !== gen) return;+ // Agents this server did not answer about. Per Agent, not per server: a damaged+ // index or a 500 on ONE Agent is a different event from this server being+ // unreadable, and reading the first as the second is what leaves the page on a+ // skeleton — nothing is applied, so `loading` is never cleared, and on a quiet+ // server nothing asks again.+ const unanswered = new Set(+ results.flatMap((r) => (r.source === null && !r.answered ? [r.agentId] : [])),+ );+ // This server did not answer about ANY of them. It holds the Sessions every other+ // source is merged AROUND, so there is no list to build — and building one anyway+ // would replace everything on screen with a handful of remote rows, or with nothing+ // at all. A reload is a refresh, and a refresh that cannot read anything changes+ // nothing: the rows stand, `loading` is left as it was, and the next one tries+ // again. This is the ordinary state during a hot swap and for the moment after a+ // reconnect.+ if (unanswered.size === agentIds.length && agentIds.length > 0) return;+ // Machines that did not answer are treated exactly like machines that were never+ // asked: their rows come from the cache below, and their cache is left alone.+ const silent = new Set(+ results.flatMap((r) => (r.source !== null && !r.answered ? [r.source] : [])),+ );const nextSessions: SessionInfo[] = [];const seen = new Set<string>();+ // What each machine answered, kept so it can be shown after the next restart while+ // the server re-holds its connection to that machine (lib/machine-cache.ts).+ const rowsByMachine = new Map<string, SessionInfo[]>();const nextPageState = new Map<string, PagePosition>();const nextCounts = new Map<string, SessionCategoryCounts>();const nextWorkspaceCounts = new Map<string,Readonly<Record<string, SessionCategoryCounts>>>();+ // Counts are SUMMED across sources, not overwritten: a folder badge that counted+ // one machine would contradict the rows underneath it (mergeCounts).+ const countParts = new Map<string, SessionCategoryCounts[]>();+ // Each answer with the machine that gave it: a path means a directory only+ // together with the filesystem it was read from.+ const workspaceParts = new Map<+ string,+ Array<{+ source: string | null;+ counts: Readonly<Record<string, SessionCategoryCounts>>;+ }>+ >();+ // Newest-Session stamps per group, keyed the way the counts are (a path on a+ // machine); the newest answer for a group wins.const nextWorkspaceLatest = new Map<string, Readonly<Record<string, string>>>();for (const r of results) {for (const p of r.pages) {- nextPageState.set(pageKey(r.agentId, p.category, p.scope), {+ nextPageState.set(pageKey(r.agentId, p.category, p.scope, r.source), {hasMore: p.hasMore,fetched: p.items.length,});- if (p.counts) nextCounts.set(r.agentId, p.counts);- if (p.workspaceCounts) nextWorkspaceCounts.set(r.agentId, p.workspaceCounts);- if (p.workspaceLatest) nextWorkspaceLatest.set(r.agentId, p.workspaceLatest);- for (const s of p.items) {- if (!seen.has(s.sessionId)) {- seen.add(s.sessionId);- nextSessions.push(s);+ if (p.counts)+ countParts.set(r.agentId, [...(countParts.get(r.agentId) ?? []), p.counts]);+ if (p.workspaceCounts) {+ workspaceParts.set(r.agentId, [+ ...(workspaceParts.get(r.agentId) ?? []),+ { source: r.source, counts: p.workspaceCounts },+ ]);+ }+ if (p.workspaceLatest) {+ const latest: Record<string, string> = {+ ...(nextWorkspaceLatest.get(r.agentId) ?? {}),+ };+ for (const [path, stamp] of Object.entries(p.workspaceLatest)) {+ const groupKey = workspaceGroupKey(path, r.source);+ const held = latest[groupKey];+ if (held === undefined || held < stamp) latest[groupKey] = stamp;}+ nextWorkspaceLatest.set(r.agentId, latest);+ }+ for (const s of p.items) {+ if (seen.has(s.sessionId)) continue;+ seen.add(s.sessionId);+ nextSessions.push(s);+ if (r.source !== null)+ rowsByMachine.set(r.source, [...(rowsByMachine.get(r.source) ?? []), s]);+ // Where this row lives, so the two dozen Session-scoped calls about it reach+ // the machine that holds it. Rebuilt by the very list that displays them,+ // which is why the map is in memory and this is the only place it is filled.+ rememberSessionMachine(s.sessionId, r.source);}}}+ for (const [agentId, parts] of countParts) {+ const merged = mergeCounts(parts);+ if (merged) nextCounts.set(agentId, merged);+ }+ for (const [agentId, parts] of workspaceParts) {+ // Per GROUP, which is a path on a machine. Each machine answers about its own+ // filesystem, so two machines' counts for paths that are equal as strings belong+ // to two different directories: summing them would put both totals under both+ // folders, each one contradicting the rows beneath it.+ const byGroup = new Map<string, SessionCategoryCounts[]>();+ for (const { source, counts: byPath } of parts) {+ for (const [path, counts] of Object.entries(byPath)) {+ const groupKey = workspaceGroupKey(path, source);+ byGroup.set(groupKey, [...(byGroup.get(groupKey) ?? []), counts]);+ }+ }+ const out: Record<string, SessionCategoryCounts> = {};+ for (const [groupKey, list] of byGroup) {+ const merged = mergeCounts(list);+ if (merged) out[groupKey] = merged;+ }+ nextWorkspaceCounts.set(agentId, out);+ }+ // Only a machine that ANSWERED replaces what it is remembered as holding — including+ // with nothing, which is how a Session deleted over there stops coming back from+ // the cache. A machine that went quiet during the fetch keeps its cache: erasing it+ // would leave the fallback with nothing to fall back to.+ for (const machineId of machineIds) {+ if (silent.has(machineId)) continue;+ rememberMachineSessions(projectId, machineId, rowsByMachine.get(machineId) ?? []);+ }+ // And every machine this list could not read contributes what it last held — the+ // ones with no connection held, and the ones that went quiet during the fetch.+ // `seen` still guards, so a live answer always wins over a remembered one. Their+ // owner entries are recorded the same way, so opening such a Session addresses the+ // machine that has it rather than this server — which would answer 404 about+ // someone else's.+ //+ // Folder badges are NOT topped up from here: counts come from the servers that+ // answered, so an out-of-reach machine's rows show without being counted. Better+ // than the alternative — a count is a claim about what a server holds now, and the+ // cache cannot make that claim.+ for (const machineId of new Set([...offlineMachineIds, ...silent])) {+ for (const s of cachedMachineSessions(projectId, machineId)) {+ if (seen.has(s.sessionId)) continue;+ seen.add(s.sessionId);+ nextSessions.push(s);+ rememberSessionMachine(s.sessionId, machineId);+ }+ }+ // An Agent this server could not answer about keeps everything it already had: its+ // rows here, the page positions they were loaded at, and its badge counts. The list+ // is rebuilt wholesale, so without this one Agent's failed call erases it — and an+ // erased Agent is indistinguishable, on screen, from one that has no conversations.+ // Its counts are kept as last read rather than remerged from the machines that did+ // answer: a total missing this server's share would contradict the rows beneath it.+ if (unanswered.size > 0) {+ const held = get();+ for (const s of held.sessions) {+ if (!unanswered.has(s.agentId) || machineForSession(s.sessionId) !== null) continue;+ if (seen.has(s.sessionId)) continue;+ seen.add(s.sessionId);+ nextSessions.push(s);+ }+ for (const [key, position] of held.pageState) {+ const parsed = parsePageKey(key);+ if (parsed === null || parsed.source !== null) continue;+ if (!unanswered.has(parsed.agentId) || nextPageState.has(key)) continue;+ nextPageState.set(key, position);+ }+ for (const agentId of unanswered) {+ const counts = held.countsByAgent.get(agentId);+ if (counts) nextCounts.set(agentId, counts);+ const workspaceCounts = held.workspaceCountsByAgent.get(agentId);+ if (workspaceCounts) nextWorkspaceCounts.set(agentId, workspaceCounts);+ const latest = held.workspaceLatestByAgent.get(agentId);+ if (latest) nextWorkspaceLatest.set(agentId, latest);+ }+ }+ // Newest first across every source: each answered sorted, and concatenating sorted+ // lists does not give a sorted list.+ nextSessions.sort(newestFirst);// No fetch returns an organization row (`excludeOrg`), so one held here entered// through add() for the page showing it (an open desk or ticket session) and no// reload can bring it back: carry it over, or that page's writes stop reaching it.@@ -402,8 +691,13 @@ export function createSessionsStore() {workspaceCountsByAgent: nextWorkspaceCounts,workspaceLatestByAgent: nextWorkspaceLatest,});+ applied = true;} finally {- if (g === gen) set({ loading: false });+ // Only a reload that produced a list may report one. Abandoning above leaves the+ // flag exactly as it was — false with rows on screen, which is still true of them;+ // true with none, because none were fetched and saying otherwise is what paints an+ // empty state over a list that was merely unreadable this round.+ if (g === gen && applied) set({ loading: false });}},@@ -423,54 +717,71 @@ export function createSessionsStore() {* walked, so the pool absorbs any overlap by sessionId.*/loadMoreFor: async (agentIds, category, workspaceGroup) => {- const { projectId } = get();+ const { projectId, machineIds } = get();if (!projectId) return;+ const sources = sourcesFor([null, ...machineIds], workspaceGroup);const scope = scopeOf(workspaceGroup);- const targets = [...new Set(agentIds)].filter((agentId) => {- const position = get().pageState.get(pageKey(agentId, category, scope));- // An unloaded pair: the Agent's own totals still decide whether asking is worth a- // request. A scoped pair cannot consult them (they are not broken down by group- // here), so it always gets its first page — the caller only asks for a group it- // has reason to believe holds rows.- if (position === undefined)- return scope !== "" || (get().countsByAgent.get(agentId)?.[category] ?? 0) > 0;- return position.hasMore;- });+ // One target per (Agent, SOURCE): each server pages its own Sessions with its own+ // offsets, so a shared cursor would ask one machine for rows only another had+ // reached — silently skipping the rows in between.+ const targets = [...new Set(agentIds)].flatMap((agentId) =>+ sources+ .filter((source) => {+ const position = get().pageState.get(pageKey(agentId, category, scope, source));+ // An unloaded pair: the Agent's own totals still decide whether asking is+ // worth a request — they are the SUM over sources, so a machine with none+ // still gets one first page, which is what discovers that it has none. A+ // scoped pair cannot consult them (they are not broken down by group here),+ // so it always gets its first page — the caller only asks for a group it has+ // reason to believe holds rows.+ if (position === undefined)+ return scope !== "" || (get().countsByAgent.get(agentId)?.[category] ?? 0) > 0;+ return position.hasMore;+ })+ .map((source) => ({ agentId, source })),+ );if (targets.length === 0) return;const g = gen;/**- * Rows of this (Agent, category, group) already in the pool. They arrived on pages of- * the Agent's whole stream, and a prefix of that stream cut by Workspace is a prefix- * of the group's stream — so the count doubles as the offset a FIRST scoped fetch- * starts from. Without it that fetch would re-read rows the group already shows and- * the click would appear to do nothing.+ * Rows of this (Agent, category, group) already in the pool from ONE source. They+ * arrived on pages of that source's whole stream, and a prefix of that stream cut by+ * Workspace is a prefix of the group's stream — so the count doubles as the offset a+ * FIRST scoped fetch starts from. Without it that fetch would re-read rows the group+ * already shows and the click would appear to do nothing; counting every source's+ * rows would instead skip rows only this source holds.*/- const loadedInScope = (agentId: string, group: string) =>+ const loadedInScope = (agentId: string, source: string | null, group: string) =>get().sessions.filter((s) =>s.agentId === agentId &&sessionCategory(s) === category &&- workspaceGroupKey(s.workspace) === group,+ workspaceGroupKey(s.workspace, machineForSession(s.sessionId)) === group &&+ machineForSession(s.sessionId) === source,).length;const results = await Promise.all(- targets.map(async (agentId) => {- const position = get().pageState.get(pageKey(agentId, category, scope));+ targets.map(async ({ agentId, source }) => {+ const position = get().pageState.get(pageKey(agentId, category, scope, source));const offset =position?.fetched ??(workspaceGroup === undefined || workspaceGroup === ""? 0- : loadedInScope(agentId, workspaceGroup));+ : loadedInScope(agentId, source, workspaceGroup));try {const fetched = (- await api.listSessions(projectId, agentId, {- offset,- limit: SIDEBAR_PAGE_SIZE + 1,- category,- excludeOrg: true,- ...(scope === "" ? {} : { workspaceGroup: scope }),- })+ await api.listSessions(+ projectId,+ agentId,+ {+ offset,+ limit: SIDEBAR_PAGE_SIZE + 1,+ category,+ excludeOrg: true,+ ...(scope === "" ? {} : { workspaceGroup: scope }),+ },+ source,+ )).sessions;- return { agentId, offset, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };+ return { agentId, source, offset, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };} catch {// Transient failure: leave the pair's state untouched (still unloaded / still// has-more), so the affordance stays and the user can retry.@@ -482,11 +793,19 @@ export function createSessionsStore() {const ok = results.filter((r) => r !== null);const prev = get().sessions;const seen = new Set(prev.map((s) => s.sessionId));- const appended = ok.flatMap((r) => r.items.filter((s) => !seen.has(s.sessionId)));+ const appended: SessionInfo[] = [];+ for (const r of ok) {+ for (const row of r.items) {+ if (seen.has(row.sessionId)) continue;+ seen.add(row.sessionId);+ appended.push(row);+ rememberSessionMachine(row.sessionId, r.source);+ }+ }const prevPageState = get().pageState;const nextPageState = new Map(prevPageState);for (const r of ok) {- const key = pageKey(r.agentId, category, scope);+ const key = pageKey(r.agentId, category, scope, r.source);nextPageState.set(key, {hasMore: r.hasMore,// A first scoped fetch started at the rows the group already held (see@@ -508,11 +827,15 @@ export function createSessionsStore() {// (deep-link self-heal of an unfetched row) the counts already include it — a// possible one-off drift self-heals on the next reload.const existed = get().sessions.some((s) => s.sessionId === session.sessionId);+ // Per SOURCE and stream: the row belongs to the machine it lives on, and the whole+ // stream (scope "") is the one the totals were fetched against.+ const source = machineForSession(session.sessionId);+ const category = sessionCategory(session);if (!existed &&- get().pageState.get(pageKey(session.agentId, sessionCategory(session)))?.hasMore === false+ get().pageState.get(pageKey(session.agentId, category, "", source))?.hasMore === false) {- adjustCount(session, sessionCategory(session), 1);+ adjustCount(session, category, 1);}set({sessions: [session, ...get().sessions.filter((s) => s.sessionId !== session.sessionId)],@@ -672,11 +995,29 @@ export function applyUserEvent(store: SessionsStore,ev: ServerEvent,onWebUpdated: () => void,+ /** The machine the event came from; null for this server. */+ source: string | null = null,): void {// The served web assets were hot-swapped (dev watch-push / platform upgrade): reload so this- // window runs the new code.+ // window runs the new code. Only this server's word counts: a machine's web being pushed is+ // that machine's affair, and this window is not running it.if (ev.type === "web_updated") {- onWebUpdated();+ if (source === null) onWebUpdated();+ return;+ }+ // A Session now exists that this list did not create — the CLI, another tab, a schedule, an+ // agent spawning a child, on this server or on a machine. Nothing short of a fetch can put+ // the row in place with everything a row needs (title, workspace, counts), so reload; the+ // same answer schedule_fired gives below, for the same reason.+ //+ // The Project is compared whatever the event came from. A machine's Projects carry THIS+ // server's ids — installing one creates the same Project over there, and every list call+ // below names it (machines/models-sync.ts) — so a machine's events are as unrelated to this+ // list as this server's are when the id differs. Reloading on all of them meant every+ // Session and every subagent started in any other Project on any connected machine refetched+ // the whole list, Agents × sources.+ if (ev.type === "session_created") {+ if (ev.projectId === store.getState().projectId) void store.getState().reload();return;}// A Session changed run state. This is what keeps every row honest: a tab subscribes to the@@ -757,10 +1098,20 @@ export function applyUserEvent(// list so it appears immediately. schedule_queued doesn't change the list (the target Session// already exists), so it goes no further, as does every other Session-scoped event.if (ev.type !== "schedule_fired") return;- // The event carries projectId: a trigger from another Project is unrelated to the current list.+ // The event carries projectId: a trigger from another Project is unrelated to the current+ // list, wherever it fired (see session_created).if (ev.projectId === store.getState().projectId) void store.getState().reload();}+/**+ * How often the machine list is re-read while some machine of the Project is out of reach.+ * A cheap GET — the list is config text and the server's own connection state, no ssh — so+ * the page learns that a re-held connection is back without anyone visiting the Machines+ * page. Nothing here connects: holding a connection is the server's, and re-holding one+ * that dropped is the transport's (machines/transport/ssh-session.ts).+ */+export const OFFLINE_RECHECK_MS = 30_000;+export function SessionsProvider({ children }: { children: ReactNode }) {const { currentProject, agents } = useProject();const projectId = currentProject?.projectId ?? null;@@ -771,7 +1122,114 @@ export function SessionsProvider({ children }: { children: ReactNode }) {const [store] = useState(createSessionsStore);const state = useStore(store);+ /**+ * The Project's machines, whose Sessions belong in this list too — the ones this server+ * holds a connection to, and the ones it does not, which contribute their cached rows and+ * mark the list as incomplete. Read from the machine list, which is the server's own word:+ * a held connection is a fact about a process on that side, and the transport re-holds one+ * that drops (machines/transport/ssh-session.ts). Nothing on this page connects.+ *+ * Failure leaves both empty, which degrades to exactly the old behaviour: this server's+ * Sessions, listed. That is the right failure — a partial list beats none.+ */+ const [machineIdsKey, setMachineIdsKey] = useState("");+ const [offlineMachineIdsKey, setOfflineMachineIdsKey] = useState("");+ /**+ * machineId → its ssh alias, as JSON so an unchanged answer keeps its identity (the id+ * lists above are strings for the same reason). What the list is FOR: a Workspace group+ * from another machine is named with the alias that reaches it, and an alias is the only+ * part of a machine a person recognises.+ */+ const [machineLabelsJson, setMachineLabelsJson] = useState("[]");+ /**+ * machineId → its own Agent ids, as JSON for the same reason the lists above are strings.+ * What the list is FOR: a Session started on a machine's own Agent is listed by nobody+ * unless that machine is asked about that Agent (see `agentIdsByMachine` in the store).+ */+ const [machineAgentIdsJson, setMachineAgentIdsJson] = useState("{}");+ const [machinesEpoch, setMachinesEpoch] = useState(0);+ useEffect(() => {+ if (projectId === null) {+ setMachineIdsKey("");+ setOfflineMachineIdsKey("");+ setMachineLabelsJson("[]");+ setMachineAgentIdsJson("{}");+ return;+ }+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | null = null;+ void (async () => {+ try {+ const res = await api.getMachines(projectId);+ if (cancelled) return;+ const installed = res.machines.filter(+ (machine) => !machine.local && machine.installed !== null && machine.machineId !== null,+ );+ const held = installed.filter((m) => m.connection !== null);+ const offline = installed.filter((m) => m.connection === null);+ setMachineIdsKey(held.map(machineIdOf).join(","));+ setOfflineMachineIdsKey(offline.map(machineIdOf).join(","));+ setMachineLabelsJson(+ JSON.stringify(installed.map((machine) => [machine.machineId, machine.alias])),+ );+ // The terminal list asks the same machines, from a module-scope timer with no React+ // context to read them from (lib/terminal-machines.ts).+ setTerminalMachines(held.map(machineIdOf).filter((id): id is string => id !== null));+ // While something is out of reach, look again in a while: the server may be+ // re-holding it after a restart or a push, and the list should learn so without a+ // visit to the Machines page. Stops on its own once every machine answers.+ if (offline.length > 0) {+ timer = setTimeout(() => setMachinesEpoch((epoch) => epoch + 1), OFFLINE_RECHECK_MS);+ }+ // Then what each machine is RUNNING. An Agent is per server, so a machine's set is+ // its own, and a Session started on one of its Agents (the Agents page offers exactly+ // that) is listed only if the machine is asked about that Agent by name. A machine+ // that cannot answer contributes what it was last seen running — the same account the+ // composer offers a remote draft, and better than dropping its rows.+ const answers = await Promise.all(+ installed.map(async (machine) => {+ const machineId = machineIdOf(machine);+ if (machineId === null) return null;+ const remembered = () =>+ cachedMachineAgents(projectId, machineId).map((a) => a.agentId);+ if (machine.connection === null) return [machineId, remembered()] as const;+ try {+ const listed = (await api.listAgents(projectId, machineId)).agents;+ rememberMachineAgents(projectId, machineId, listed);+ return [machineId, listed.map((a) => a.agentId)] as const;+ } catch {+ return [machineId, remembered()] as const;+ }+ }),+ );+ if (cancelled) return;+ setMachineAgentIdsJson(+ JSON.stringify(Object.fromEntries(answers.filter((entry) => entry !== null))),+ );+ } catch {+ // No machine list (not an admin, or the call failed): the list is this server's alone.+ // Said so out loud rather than left unsaid — the terminal list waits for this word+ // before it may drop a tab whose terminal is gone, and a user who can never read the+ // machine list would otherwise keep every dead tab in their dock forever+ // (features/terminal/terminal-list.ts).+ if (!cancelled) setTerminalMachines([]);+ }+ })();+ return () => {+ cancelled = true;+ if (timer !== null) clearTimeout(timer);+ };+ }, [projectId, machinesEpoch]);++ /**+ * The Project and its Agent set: what the list is OF. A change here invalidates every row+ * on screen, so it clears them. The machine set is deliberately not part of it — see below.+ */+ const contextKey = `${projectId ?? ""}\u0000${agentIdsKey}`;+ const appliedContext = useRef<string | null>(null);useEffect(() => {+ const contextChanged = appliedContext.current !== contextKey;+ appliedContext.current = contextKey;// Sync the fetch context and reset the loaded pages in the same synchronous step:// reload() picks the categories to refetch from pageState, so a Project switch can't// carry folder page state across via shared Agent ids (default_agent exists in every@@ -783,21 +1241,47 @@ export function SessionsProvider({ children }: { children: ReactNode }) {store.setState({projectId,agentIds: agentIdsKey === "" ? [] : agentIdsKey.split(","),- sessions: [],- pageState: new Map(),- countsByAgent: new Map(),- workspaceCountsByAgent: new Map(),- workspaceLatestByAgent: new Map(),- // The pages were just cleared, so the list is loading from this instant — including- // the window where the Agent set itself is still being refetched (a Project switch- // empties it, which makes reload() below return without fetching or clearing the- // flag). Raising it HERE, on fetch-context change, is what keeps an unrelated- // reloadAgents() — same agent set, fired after every completed turn — from flapping- // the app-wide flag.- loading: true,+ machineIds: machineIdsKey === "" ? [] : machineIdsKey.split(","),+ offlineMachineIds: offlineMachineIdsKey === "" ? [] : offlineMachineIdsKey.split(","),+ agentIdsByMachine: JSON.parse(machineAgentIdsJson) as Record<string, string[]>,+ // Cleared only when the CONTEXT changed. A machine appearing, or dropping out, changes+ // which servers are asked — not whether what is already on screen is still true.+ // reload() below rebuilds the list wholesale from whatever answers, so a departed+ // machine's rows leave on their own; clearing first would instead blank the sidebar,+ // and with it the chat page, for as long as the fetch takes.+ ...(contextChanged+ ? {+ sessions: [],+ pageState: new Map(),+ countsByAgent: new Map(),+ workspaceCountsByAgent: new Map(),+ workspaceLatestByAgent: new Map(),+ // The pages were just cleared, so the list is loading from this instant —+ // including the window where the Agent set itself is still being refetched (a+ // Project switch empties it, which makes reload() below return without fetching+ // or clearing the flag). Raising it HERE, on fetch-context change, is what keeps+ // an unrelated reloadAgents() — same agent set, fired after every completed turn+ // — from flapping the app-wide flag.+ loading: true,+ }+ : {}),});+ // Which machine owns which Session is rebuilt by the very fetch below, so the old+ // answers are dropped with the rows they described: a stale entry would route a call at+ // a machine that may no longer hold — or no longer have — that Session. Only alongside+ // the rows themselves: dropped while they are still displayed, every one of them would+ // route at THIS server until the refetch lands.+ if (contextChanged) forgetSessionMachines();void store.getState().reload();- }, [store, projectId, agentIdsKey]);+ }, [+ store,+ projectId,+ agentIdsKey,+ machineIdsKey,+ offlineMachineIdsKey,+ machineAgentIdsJson,+ contextKey,+ ]);// User-level event stream (/api/events); see applyUserEvent for what each event does. The// connection stays a single one for the whole login session and doesn't reconnect on Project@@ -811,24 +1295,60 @@ export function SessionsProvider({ children }: { children: ReactNode }) {return () => conn.close();}, [store]);- const { pageState, countsByAgent } = state;+ const { pageState, countsByAgent, machineIds } = state;++ // One more stream per connected machine: a Session there changes state on that machine's+ // server, and this server never hears of it. Keyed on the held set, so a machine that+ // drops out has its stream closed and one that comes up gets one. EventSource reconnects+ // on its own while the connection behind the proxy is briefly down.+ const heldKey = machineIds.join(",");+ useEffect(() => {+ const ids = heldKey === "" ? [] : heldKey.split(",");+ const conns = ids.map((machineId) =>+ openUserEvents(+ {+ onOmniMessage: () => undefined,+ onServerEvent: (ev) => applyUserEvent(store, ev, () => undefined, machineId),+ },+ machineId,+ ),+ );+ return () => {+ for (const conn of conns) conn.close();+ };+ }, [store, heldKey]);+ const sources = useMemo<(string | null)[]>(() => [null, ...machineIds], [machineIds]);++ // Loaded only when EVERY source has answered: one machine's first page arriving does not+ // make the folder complete, and treating it as loaded would hide the rest behind a+ // "load more" that never appears.const isLoadedFor = useCallback((agentId: string, category: SessionCategory, workspaceGroup?: string) =>- pageState.has(pageKey(agentId, category, scopeOf(workspaceGroup))),- [pageState],+ sourcesFor(sources, workspaceGroup).every((source) =>+ pageState.has(pageKey(agentId, category, scopeOf(workspaceGroup), source)),+ ),+ [pageState, sources],);+ // More if ANY source has more — or if a source has not been asked at all and the counts,+ // which are the sum over sources, say the category holds something.const hasMoreFor = useCallback((agentId: string, category: SessionCategory, workspaceGroup?: string) => {const scope = scopeOf(workspaceGroup);- const position = pageState.get(pageKey(agentId, category, scope));- if (position !== undefined) return position.hasMore;- // Unloaded pair: anything the counts report is by definition still unfetched. A group's- // own stream is not in those counts, so an unloaded scoped pair answers from the- // Agent's total for the category — the group's share of it cannot exceed that.+ let anyUnloaded = false;+ for (const source of sourcesFor(sources, workspaceGroup)) {+ const position = pageState.get(pageKey(agentId, category, scope, source));+ if (position === undefined) anyUnloaded = true;+ else if (position.hasMore) return true;+ }+ if (!anyUnloaded) return false;+ // Unloaded: the counts are the sum over sources, so anything they report is by+ // definition still unfetched somewhere. A group's own stream is not in those counts,+ // so an unloaded scoped pair answers from the Agent's total for the category — the+ // group's share of it cannot exceed that.return (countsByAgent.get(agentId)?.[category] ?? 0) > 0;},- [pageState, countsByAgent],+ [pageState, countsByAgent, sources],);// Reads the store directly rather than the subscribed snapshot: this answers "is this id@@ -860,6 +1380,13 @@ export function SessionsProvider({ children }: { children: ReactNode }) {return map;}, [state.sessions]);+ const machineLabels = useMemo<ReadonlyMap<string, string>>(() => {+ const entries = JSON.parse(machineLabelsJson) as [string | null, string][];+ return new Map(+ entries.flatMap(([id, alias]) => (id === null ? [] : [[id, alias] as [string, string]])),+ );+ }, [machineLabelsJson]);+const value = useMemo<SessionsContextValue>(() => {return {sessions: state.sessions,@@ -868,9 +1395,13 @@ export function SessionsProvider({ children }: { children: ReactNode }) {workspaceCountsByAgent: state.workspaceCountsByAgent,workspaceLatestByAgent: state.workspaceLatestByAgent,liveStatuses: state.liveStatuses,+ machineLabels,+ machineIds: state.machineIds,isLoadedFor,hasMoreFor,loading: state.loading,+ machinesUnreachable: state.offlineMachineIds.length > 0,+ offlineMachineIds: state.offlineMachineIds,reload: state.reload,loadMoreFor: state.loadMoreFor,add: state.add,@@ -880,7 +1411,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {setStatus: state.setStatus,setTitle: state.setTitle,};- }, [state, byAgent, isLoadedFor, hasMoreFor, isDeleted]);+ }, [state, byAgent, machineLabels, isLoadedFor, hasMoreFor, isDeleted]);return <SessionsContext.Provider value={value}>{children}</SessionsContext.Provider>;}diff --git a/packages/web/test/benchmark-merge.test.ts b/packages/web/test/benchmark-merge.test.tsnew file mode 100644index 00000000..f8c72f6f--- /dev/null+++ b/packages/web/test/benchmark-merge.test.ts@@ -0,0 +1,201 @@+/**+ * benchmark-merge.ts unit tests: a Project's Benchmarks read off several machines and folded+ * into one list. A Benchmark is one identity, so the merge is by benchmark id — the machine is+ * attribution (which scoreboard recorded a round, whose disk holds a Case's files), never a+ * grouping key. The order rule is the subtle one: a single scoreboard keeps the append order+ * it was written in, and only a history joined from two disks is ordered by time.+ */+import { describe, expect, it } from "vitest";+import type { BenchmarkEvaluation, BenchmarkSummary } from "@prismshadow/penguin-server/api";+import { mergeAgents, mergeBenchmarks, mergeBenchmarkCases } from "../src/lib/benchmark-merge";++const MACHINE = "noeSE0FFHhNXl2J5";++const evaluation = (time: string, over: Partial<BenchmarkEvaluation> = {}): BenchmarkEvaluation =>+ ({+ time,+ modelId: "claude-4-8",+ provider: "custom",+ thinkingLevel: "medium",+ version: 1,+ score: 80,+ cost: null,+ durationMs: 1000,+ cases: [],+ ...over,+ }) as BenchmarkEvaluation;++const benchmark = (id: string, over: Partial<BenchmarkSummary> = {}): BenchmarkSummary =>+ ({+ id,+ title: id,+ status: "published",+ caseCount: 2,+ evaluations: [],+ agentIds: [],+ ...over,+ }) as BenchmarkSummary;++describe("mergeBenchmarks", () => {+ it("folds one benchmark id into one entry, recording every machine that holds it", () => {+ const merged = mergeBenchmarks([+ {+ machineId: null,+ benchmarks: [benchmark("example", { evaluations: [evaluation("2026-09-01T00:00:00Z")] })],+ },+ {+ machineId: MACHINE,+ benchmarks: [benchmark("example", { evaluations: [evaluation("2026-09-02T00:00:00Z")] })],+ },+ ]);+ expect(merged).toHaveLength(1);+ expect(merged[0]!.machineIds).toEqual([null, MACHINE]);+ expect(merged[0]!.evaluations.map((e) => e.machineId)).toEqual([null, MACHINE]);+ });++ it("orders a joined history by time — two scoreboards share no append order", () => {+ const merged = mergeBenchmarks([+ {+ machineId: null,+ benchmarks: [+ benchmark("example", {+ evaluations: [evaluation("2026-09-01T00:00:00Z"), evaluation("2026-09-03T00:00:00Z")],+ }),+ ],+ },+ {+ machineId: MACHINE,+ benchmarks: [benchmark("example", { evaluations: [evaluation("2026-09-02T00:00:00Z")] })],+ },+ ]);+ expect(merged[0]!.evaluations.map((e) => e.time)).toEqual([+ "2026-09-01T00:00:00Z",+ "2026-09-02T00:00:00Z",+ "2026-09-03T00:00:00Z",+ ]);+ });++ it("leaves a single machine's scoreboard in its written order, timestamps or not", () => {+ // The append order IS the evaluation sequence: re-sorting it would reorder Agent versions+ // on the strength of a timestamp the file may not even have got right.+ const merged = mergeBenchmarks([+ {+ machineId: null,+ benchmarks: [+ benchmark("example", {+ evaluations: [+ evaluation("2026-09-05T00:00:00Z", { version: 1 }),+ evaluation("2026-09-01T00:00:00Z", { version: 2 }),+ ],+ }),+ ],+ },+ ]);+ expect(merged[0]!.evaluations.map((e) => e.version)).toEqual([1, 2]);+ });++ it("keeps the first source's description and the largest case count", () => {+ const merged = mergeBenchmarks([+ {+ machineId: null,+ benchmarks: [benchmark("example", { title: "Here", runs: 3, caseCount: 2 })],+ },+ {+ machineId: MACHINE,+ benchmarks: [benchmark("example", { title: "There", runs: 9, caseCount: 5 })],+ },+ ]);+ expect(merged[0]).toMatchObject({ title: "Here", runs: 3, caseCount: 5 });+ });++ it("names every Agent either scoreboard tested, in first-seen order", () => {+ const merged = mergeBenchmarks([+ { machineId: null, benchmarks: [benchmark("example", { agentIds: ["a", "b"] })] },+ { machineId: MACHINE, benchmarks: [benchmark("example", { agentIds: ["b", "c"] })] },+ ]);+ expect(merged[0]!.agentIds).toEqual(["a", "b", "c"]);+ });++ it("lists a benchmark only a machine has, after this server's own", () => {+ const merged = mergeBenchmarks([+ { machineId: null, benchmarks: [benchmark("here")] },+ { machineId: MACHINE, benchmarks: [benchmark("there")] },+ ]);+ expect(merged.map((b) => b.id)).toEqual(["here", "there"]);+ expect(merged[1]!.machineIds).toEqual([MACHINE]);+ expect(mergeBenchmarks([])).toEqual([]);+ });++ it("never mutates the answers it was given", () => {+ const mine = benchmark("example", {+ evaluations: [evaluation("2026-09-01T00:00:00Z")],+ agentIds: ["a"],+ });+ mergeBenchmarks([+ { machineId: null, benchmarks: [mine] },+ {+ machineId: MACHINE,+ benchmarks: [+ benchmark("example", {+ evaluations: [evaluation("2026-09-02T00:00:00Z")],+ agentIds: ["b"],+ }),+ ],+ },+ ]);+ expect(mine.evaluations).toHaveLength(1);+ expect(mine.agentIds).toEqual(["a"]);+ expect(mine.evaluations[0]).not.toHaveProperty("machineId");+ });+});++describe("mergeAgents", () => {+ const agent = (agentId: string, name?: string) =>+ ({ agentId, ...(name === undefined ? {} : { name }) }) as never;++ it("lists an Agent only a machine has — its Benchmarks had no row to hang off", () => {+ const merged = mergeAgents([+ { machineId: null, agents: [agent("default_agent")] },+ { machineId: MACHINE, agents: [agent("default_agent"), agent("revival_worker")] },+ ]);+ expect(merged.map((m) => [m.agent.agentId, m.machineIds])).toEqual([+ ["default_agent", [null, MACHINE]],+ ["revival_worker", [MACHINE]],+ ]);+ });++ it("keeps the first source's description of a shared Agent", () => {+ const merged = mergeAgents([+ { machineId: null, agents: [agent("default_agent", "Here")] },+ { machineId: MACHINE, agents: [agent("default_agent", "There")] },+ ]);+ expect(merged[0]!.agent.name).toBe("Here");+ expect(mergeAgents([])).toEqual([]);+ });+});++describe("mergeBenchmarkCases", () => {+ it("takes the union, first source winning a shared id, and records where each is read from", () => {+ const merged = mergeBenchmarkCases([+ {+ machineId: null,+ cases: [+ { id: "case-1", title: "Here" },+ { id: "case-2", title: "Only here" },+ ],+ },+ {+ machineId: MACHINE,+ cases: [+ { id: "case-1", title: "There" },+ { id: "case-3", title: "Only there" },+ ],+ },+ ]);+ expect(merged.map((c) => [c.id, c.title, c.machineId])).toEqual([+ ["case-1", "Here", null],+ ["case-2", "Only here", null],+ ["case-3", "Only there", MACHINE],+ ]);+ });+});diff --git a/packages/web/test/current-agent.test.ts b/packages/web/test/current-agent.test.tsnew file mode 100644index 00000000..f462238d--- /dev/null+++ b/packages/web/test/current-agent.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import type { AgentSummary } from "@prismshadow/penguin-server/api";+import { agentOf } from "../src/state/project";++const agent = (agentId: string) => ({ agentId }) as AgentSummary;++describe("agentOf — the current Agent is always one of this server's", () => {+ const agents = [agent("writer"), agent("default_agent"), agent("reviewer")];++ it("returns the Agent the id names", () => {+ expect(agentOf(agents, "reviewer")?.agentId).toBe("reviewer");+ });++ it("falls back to default_agent for an id only a machine has", () => {+ // A draft on a machine follows its pick through to the current Agent; resolving that id to+ // null left the chat page, which waits on a current Agent, on its placeholder for good.+ expect(agentOf(agents, "ema")?.agentId).toBe("default_agent");+ expect(agentOf(agents, null)?.agentId).toBe("default_agent");+ });++ it("falls back to the first Agent when there is no default_agent, and to null when there are none", () => {+ expect(agentOf([agent("writer"), agent("reviewer")], "ema")?.agentId).toBe("writer");+ expect(agentOf([], "ema")).toBeNull();+ });+});diff --git a/packages/web/test/machine-cache.test.ts b/packages/web/test/machine-cache.test.tsnew file mode 100644index 00000000..cffadccd--- /dev/null+++ b/packages/web/test/machine-cache.test.ts@@ -0,0 +1,97 @@+/**+ * What each machine was last seen holding (lib/machine-cache.ts): replaced wholesale by the+ * machine's own answer — including with nothing, which is how a deleted Session stops coming+ * back — kept per machine, and degrading to nothing when storage refuses or holds junk.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { AgentSummary, SessionInfo } from "@prismshadow/penguin-server/api";+import {+ CACHED_ROWS_PER_MACHINE,+ cachedMachineAgents,+ cachedMachineSessions,+ rememberMachineAgents,+ rememberMachineSessions,+} from "../src/lib/machine-cache";++/** The browser's storage, as far as this module needs it. Node has none. */+function memoryStorage(): Storage {+ const map = new Map<string, string>();+ return {+ get length() {+ return map.size;+ },+ clear: () => map.clear(),+ getItem: (k) => map.get(k) ?? null,+ key: (i) => [...map.keys()][i] ?? null,+ removeItem: (k) => void map.delete(k),+ setItem: (k, v) => void map.set(k, String(v)),+ };+}++const row = (sessionId: string): SessionInfo =>+ ({+ sessionId,+ projectId: "p",+ agentId: "a",+ workspace: "/w",+ createdAt: "2026-01-01",+ }) as SessionInfo;+const agent = (agentId: string): AgentSummary => ({ agentId, name: agentId }) as AgentSummary;++describe("machine cache", () => {+ const original = (globalThis as { localStorage?: Storage }).localStorage;+ beforeEach(() => {+ (globalThis as { localStorage?: Storage }).localStorage = memoryStorage();+ });+ afterEach(() => {+ (globalThis as { localStorage?: Storage }).localStorage = original;+ });++ it("remembers per (project, machine), and a machine's answer replaces only its own entry", () => {+ rememberMachineSessions("p", "M1", [row("a"), row("b")]);+ rememberMachineSessions("p", "M2", [row("c")]);+ rememberMachineSessions("p", "M1", [row("a")]);+ expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["a"]);+ expect(cachedMachineSessions("p", "M2").map((s) => s.sessionId)).toEqual(["c"]);+ expect(cachedMachineSessions("other", "M1")).toEqual([]);+ });++ it("an empty answer clears the entry — something deleted over there stops coming back", () => {+ rememberMachineSessions("p", "M1", [row("a")]);+ rememberMachineSessions("p", "M1", []);+ expect(cachedMachineSessions("p", "M1")).toEqual([]);+ });++ it("keeps at most the placeholder's worth of rows", () => {+ rememberMachineSessions(+ "p",+ "M1",+ Array.from({ length: CACHED_ROWS_PER_MACHINE + 5 }, (_, i) => row(`s${i}`)),+ );+ expect(cachedMachineSessions("p", "M1")).toHaveLength(CACHED_ROWS_PER_MACHINE);+ });++ it("junk in storage reads as nothing remembered, and rows without an id are dropped", () => {+ localStorage.setItem("penguin.machineSessions.p:M1", "not json");+ expect(cachedMachineSessions("p", "M1")).toEqual([]);+ localStorage.setItem(+ "penguin.machineAgents.p:M1",+ JSON.stringify([{ name: "x" }, { agentId: "a" }]),+ );+ expect(cachedMachineAgents("p", "M1").map((a) => a.agentId)).toEqual(["a"]);+ });++ it("storage that refuses is not an error — the answer is merely not remembered", () => {+ (globalThis as { localStorage?: Storage }).localStorage = {+ ...memoryStorage(),+ setItem: () => {+ throw new Error("QuotaExceededError");+ },+ getItem: () => {+ throw new Error("SecurityError");+ },+ } as Storage;+ expect(() => rememberMachineAgents("p", "M1", [agent("a")])).not.toThrow();+ expect(cachedMachineAgents("p", "M1")).toEqual([]);+ });+});diff --git a/packages/web/test/owner-only-actions.test.ts b/packages/web/test/owner-only-actions.test.tsindex 488cc049..c99f5057 100644--- a/packages/web/test/owner-only-actions.test.ts+++ b/packages/web/test/owner-only-actions.test.ts@@ -60,6 +60,7 @@ describe("a failed Benchmark's notices", () => {benchmark: failed,locale: "zh",nameOf: (agentId: string) => agentId,+ machineName: null,canDelete,onOpen: noop,onUse: noop,diff --git a/packages/web/test/plugin-config-machine.test.ts b/packages/web/test/plugin-config-machine.test.tsnew file mode 100644index 00000000..b9e2063e--- /dev/null+++ b/packages/web/test/plugin-config-machine.test.ts@@ -0,0 +1,41 @@+/**+ * Plugin settings are kept by each server in its own database, so the Settings dialog's+ * Plugins page reads and writes a picked machine's settings through that machine's proxy+ * prefix, and this server's own when none is picked.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as api from "../src/api/endpoints";++const ID = "noeSE0FFHhNXl2J5";++describe("plugin config endpoints", () => {+ const calls: { url: string; method: string }[] = [];+ beforeEach(() => {+ calls.length = 0;+ vi.stubGlobal("WebSocket", undefined);+ vi.stubGlobal("fetch", async (url: string, init?: { method?: string }) => {+ calls.push({ url, method: init?.method ?? "GET" });+ return new Response(JSON.stringify({ plugins: [], ok: true, message: "" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ });+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("goes to the picked machine, and stays here otherwise", async () => {+ await api.adminGetPluginConfig();+ await api.adminGetPluginConfig(ID);+ await api.adminPutPluginConfig({ name: "sandbox", values: {} }, ID);+ await api.adminRunPluginConfigAction({ name: "sandbox", action: "setup" }, ID);+ // The client may probe the session first; only the plugin-config calls are in question.+ expect(calls.filter((c) => c.url.includes("plugin-config"))).toEqual([+ { url: "/api/admin/plugin-config", method: "GET" },+ { url: `/server/${ID}/api/admin/plugin-config`, method: "GET" },+ { url: `/server/${ID}/api/admin/plugin-config`, method: "PUT" },+ { url: `/server/${ID}/api/admin/plugin-config/action`, method: "POST" },+ ]);+ });+});diff --git a/packages/web/test/plugin-machine-view.test.ts b/packages/web/test/plugin-machine-view.test.tsnew file mode 100644index 00000000..e2ee6009--- /dev/null+++ b/packages/web/test/plugin-machine-view.test.ts@@ -0,0 +1,78 @@+/**+ * The Plugins page's machine picker: all machines show every table with where each plugin+ * runs; a machine's view shows what that machine is asked for, in the state that machine+ * reports, and edits only its own table.+ */+import { describe, expect, it } from "vitest";+import type { InstalledPluginsResponse } from "@prismshadow/penguin-server/api";+import {+ availablePluginRows,+ installedPluginRows,+ type PluginView,+} from "../src/features/plugins/plugins-page";++const SELF = "Self000000000000";+const GPU = "Gpu0000000000000";++const row = (+ specifier: string,+ where: { everywhere: boolean; machines: string[]; here: boolean },+ active = where.here,+): InstalledPluginsResponse["plugins"][number] => ({+ specifier,+ active,+ builtin: false,+ modules: [],+ replaces: [],+ ...where,+});++const deployment: InstalledPluginsResponse = {+ plugins: [+ row("@acme/shared", { everywhere: true, machines: [], here: true }),+ row("@acme/gpu-only", { everywhere: false, machines: [GPU], here: false }),+ ],+ shipped: [],+ file: ".project_config.toml",+ machineId: SELF,+ restartPending: false,+};++const nameOf = (id: string) => (id === GPU ? "gpu-box" : "this server");+const modules = (rows: ReturnType<typeof installedPluginRows>) =>+ rows.flatMap((r) => (r.kind === "module" ? [r] : []));++describe("plugin rows per machine", () => {+ it("all machines: every plugin, and a machine-only one says where it runs", () => {+ const view: PluginView = { machineId: null, remote: null, nameOf };+ const rows = modules(installedPluginRows([], "en", deployment, [], view));+ expect(rows.map((r) => [r.specifier, r.state, r.onlyOn])).toEqual([+ ["@acme/shared", "active", undefined],+ ["@acme/gpu-only", "elsewhere", ["gpu-box"]],+ ]);+ // Offered for all machines, since the shared table does not list it.+ expect(availablePluginRows(deployment, [], view)).toEqual([]);+ });++ it("this server: what it is asked for, and a shared plugin cannot be removed from its table", () => {+ const view: PluginView = { machineId: SELF, remote: null, nameOf };+ const rows = modules(installedPluginRows([], "en", deployment, [], view));+ expect(rows.map((r) => r.specifier)).toEqual(["@acme/shared"]);+ expect(rows[0]!.removeBlocked).toBeDefined();+ });++ it("another machine: the state it reports, and what it has not received yet", () => {+ const remote: InstalledPluginsResponse = {+ ...deployment,+ machineId: GPU,+ plugins: [row("@acme/gpu-only", { everywhere: true, machines: [], here: true }, false)],+ };+ remote.plugins[0]!.error = "npm: 404";+ const view: PluginView = { machineId: GPU, remote, nameOf };+ const rows = modules(installedPluginRows([], "en", deployment, [], view));+ expect(rows.map((r) => [r.specifier, r.state, r.removeBlocked === undefined])).toEqual([+ ["@acme/shared", "unsynced", false],+ ["@acme/gpu-only", "failed", true],+ ]);+ });+});diff --git a/packages/web/test/route-session-hold.test.ts b/packages/web/test/route-session-hold.test.tsnew file mode 100644index 00000000..d527e78a--- /dev/null+++ b/packages/web/test/route-session-hold.test.ts@@ -0,0 +1,35 @@+/**+ * The chat page keeps showing the routed Session through a refetch that momentarily stops+ * listing it (features/chat/session-project.ts, heldRouteSession). The list is rebuilt+ * wholesale by every reload, so "not in the list" is two facts wearing one face — gone, or+ * one tick old — and only the direct lookup failing, or the route moving on, may release the+ * hold.+ */+import { describe, expect, it } from "vitest";+import type { SessionInfo } from "@prismshadow/penguin-server/api";+import { heldRouteSession } from "../src/features/chat/session-project";++const row = (sessionId: string) => ({ sessionId }) as SessionInfo;++describe("heldRouteSession", () => {+ it("the listed row always wins", () => {+ expect(heldRouteSession(row("old"), row("s1"), "s1", false)).toEqual(row("s1"));+ });++ it("holds the previous answer while the list momentarily does not name the route", () => {+ expect(heldRouteSession(row("s1"), null, "s1", false)).toEqual(row("s1"));+ });++ it("lets go when the route moved to another Session", () => {+ expect(heldRouteSession(row("s1"), null, "s2", false)).toBeNull();+ expect(heldRouteSession(row("s1"), null, null, false)).toBeNull();+ });++ it("lets go when the direct lookup says the Session is gone", () => {+ expect(heldRouteSession(row("s1"), null, "s1", true)).toBeNull();+ });++ it("has nothing to hold on a first render", () => {+ expect(heldRouteSession(null, null, "s1", false)).toBeNull();+ });+});diff --git a/packages/web/test/session-aggregation.test.ts b/packages/web/test/session-aggregation.test.tsnew file mode 100644index 00000000..8b8400f6--- /dev/null+++ b/packages/web/test/session-aggregation.test.ts@@ -0,0 +1,296 @@+/**+ * One list, several machines (state/sessions.tsx). Each server pages its own rows with its+ * own cursor; counts are summed; and the line the whole list rests on — a source that COULD+ * NOT answer is not a source that ANSWERED NOTHING: this server failing abandons the reload+ * and leaves the rows standing, a machine going quiet keeps its cached rows, and only a 404+ * (this server has not got that Agent) is an answer.+ *+ * Exercised against the store directly (node, no DOM), with the API module mocked and a+ * memory `localStorage` for the per-machine cache.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ServerEvent, SessionInfo, SessionsResponse } from "@prismshadow/penguin-server/api";+import { ApiError } from "../src/api/client";++type Answer = SessionsResponse | Error;+/** What each (machine, agent) answers; a missing entry throws like an unreachable server. */+const answers = new Map<string, Answer>();+/** Which servers were asked, and for which Workspace group — what the fan-out tests read. */+const asked: { machineId: string | null; workspaceGroup?: string }[] = [];+const key = (machineId: string | null, agentId: string) => `${machineId ?? ""}|${agentId}`;++vi.mock("../src/api/endpoints", () => ({+ listSessions: async (+ _projectId: string,+ agentId: string,+ opts: { workspaceGroup?: string } | undefined,+ machineId?: string | null,+ ) => {+ asked.push({+ machineId: machineId ?? null,+ ...(opts?.workspaceGroup === undefined ? {} : { workspaceGroup: opts.workspaceGroup }),+ });+ const answer = answers.get(key(machineId ?? null, agentId));+ if (answer === undefined) throw new ApiError(0, "network_error", "no answer");+ if (answer instanceof Error) throw answer;+ return answer;+ },+}));++import { applyUserEvent, createSessionsStore } from "../src/state/sessions";+import { machineForSession } from "../src/lib/session-machines";+import { cachedMachineSessions, rememberMachineSessions } from "../src/lib/machine-cache";++const row = (sessionId: string, createdAt: string, agentId = "a1"): SessionInfo =>+ ({+ sessionId,+ projectId: "p",+ agentId,+ workspace: "/w",+ createdAt,+ lastActiveAt: createdAt,+ status: "idle",+ hasTrace: false,+ }) as SessionInfo;++const page = (+ sessions: SessionInfo[],+ active: number,+ workspaceCounts?: Record<string, { active: number }>,+): SessionsResponse =>+ ({+ sessions,+ counts: { active, subagent: 0, schedule: 0, archived: 0 },+ ...(workspaceCounts === undefined ? {} : { workspaceCounts }),+ }) as SessionsResponse;++function memoryStorage(): Storage {+ const map = new Map<string, string>();+ return {+ get length() {+ return map.size;+ },+ clear: () => map.clear(),+ getItem: (k) => map.get(k) ?? null,+ key: (i) => [...map.keys()][i] ?? null,+ removeItem: (k) => void map.delete(k),+ setItem: (k, v) => void map.set(k, String(v)),+ };+}++describe("the list across machines", () => {+ const originalStorage = (globalThis as { localStorage?: Storage }).localStorage;+ beforeEach(() => {+ answers.clear();+ asked.length = 0;+ (globalThis as { localStorage?: Storage }).localStorage = memoryStorage();+ });+ afterEach(() => {+ (globalThis as { localStorage?: Storage }).localStorage = originalStorage;+ });++ const boot = (machineIds: string[], offlineMachineIds: string[] = []) => {+ const store = createSessionsStore();+ store.setState({ projectId: "p", agentIds: ["a1"], machineIds, offlineMachineIds });+ return store;+ };++ it("asks a machine about ITS Agents too — an Agent that exists only there", async () => {+ // A new chat started from a machine's Agent card belongs to an Agent this server has+ // never heard of. Asked only about this Project's Agents, the machine answers nothing+ // about it: the row was listed once (add) and vanished on the next reload, taking with+ // it the record of which machine holds it — after which a deep link asks THIS server,+ // gets a 404, and the conversation cannot be reached at all.+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), new ApiError(404, "not_found", "no such agent"));+ answers.set(+ key("M1", "theirs"),+ page([row("over-there", "2026-01-03T00:00:00Z", "theirs")], 1),+ );+ const store = boot(["M1"]);+ store.setState({ agentIdsByMachine: { M1: ["theirs"] } });+ await store.getState().reload();+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["over-there", "here"]);+ expect(machineForSession("over-there")).toBe("M1");+ // And this server is never asked about an Agent that is not its own.+ expect(asked.filter((a) => a.machineId === null)).toHaveLength(1);+ });++ it("one Agent this server cannot answer about keeps its rows; the rest still refresh", async () => {+ answers.set(key(null, "a1"), page([row("a1-row", "2026-01-02T00:00:00Z")], 1));+ answers.set(key(null, "a2"), page([row("a2-row", "2026-01-01T00:00:00Z", "a2")], 1));+ const store = createSessionsStore();+ store.setState({+ projectId: "p",+ agentIds: ["a1", "a2"],+ machineIds: [],+ offlineMachineIds: [],+ });+ await store.getState().reload();+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["a1-row", "a2-row"]);++ // a2's index is damaged and its list 500s, while a1 answers as before. Erasing a2 would+ // read, on screen, as an Agent with no conversations; abandoning the whole reload would+ // leave the page on a skeleton nothing clears.+ answers.set(key(null, "a2"), new ApiError(500, "internal", "broken index"));+ answers.set(+ key(null, "a1"),+ page([row("a1-row", "2026-01-02T00:00:00Z"), row("a1-new", "2026-01-04T00:00:00Z")], 2),+ );+ await store.getState().reload();+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual([+ "a1-new",+ "a1-row",+ "a2-row",+ ]);+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(2);+ // Kept as last read: a total without this server's share would contradict the row below it.+ expect(store.getState().countsByAgent.get("a2")?.active).toBe(1);+ expect(store.getState().loading).toBe(false);+ });++ it("merges every source newest-first, records where each row lives, and sums the counts", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 2));+ const store = boot(["M1"]);+ await store.getState().reload();+ const { sessions, countsByAgent, loading } = store.getState();+ expect(sessions.map((s) => s.sessionId)).toEqual(["there", "here"]);+ expect(machineForSession("there")).toBe("M1");+ expect(machineForSession("here")).toBeNull();+ expect(countsByAgent.get("a1")?.active).toBe(3);+ expect(loading).toBe(false);+ // What the machine answered is remembered for the next restart.+ expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["there"]);+ });++ it("a server that has not got the Agent answered — 404 is an answer, and its cache is cleared", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), new ApiError(404, "not_found", "no such agent"));+ rememberMachineSessions("p", "M1", [row("stale", "2026-01-01T00:00:00Z")]);+ const store = boot(["M1"]);+ await store.getState().reload();+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["here"]);+ expect(cachedMachineSessions("p", "M1")).toEqual([]);+ });++ it("a machine that could not answer keeps its cached rows on screen and its cache intact", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ // M1 is held but its server did not answer (no entry → network error); M2 has no connection.+ rememberMachineSessions("p", "M1", [row("m1-cached", "2026-01-01T00:00:00Z")]);+ rememberMachineSessions("p", "M2", [row("m2-cached", "2026-01-04T00:00:00Z")]);+ const store = boot(["M1"], ["M2"]);+ await store.getState().reload();+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual([+ "m2-cached",+ "here",+ "m1-cached",+ ]);+ expect(machineForSession("m2-cached")).toBe("M2");+ expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["m1-cached"]);+ // Counts come only from servers that answered: the cache makes no claim about now.+ expect(store.getState().countsByAgent.get("a1")?.active).toBe(1);+ });++ it("this server not answering abandons the reload: the rows stand and loading is left alone", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ const store = boot([]);+ await store.getState().reload();+ expect(store.getState().sessions).toHaveLength(1);+ expect(store.getState().loading).toBe(false);++ answers.delete(key(null, "a1")); // mid-swap: nothing answers here+ await store.getState().reload();+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["here"]);+ expect(store.getState().loading).toBe(false);+ });++ it("keeps two machines' counts for one path apart — a badge is about a directory, not a string", async () => {+ // `/w` on this server and `/w` on M1 are two different directories, and each folder's+ // badge has to match the rows under it. Summed onto one key, both folders claimed 7.+ answers.set(+ key(null, "a1"),+ page([row("here", "2026-01-02T00:00:00Z")], 1, { "/w": { active: 2 } }),+ );+ answers.set(+ key("M1", "a1"),+ page([row("there", "2026-01-03T00:00:00Z")], 1, { "/w": { active: 5 } }),+ );+ const store = boot(["M1"]);+ await store.getState().reload();+ const byGroup = store.getState().workspaceCountsByAgent.get("a1");+ expect(byGroup?.["/w"]?.active).toBe(2);+ expect(byGroup?.[`M1\u0000/w`]?.active).toBe(5);+ });++ it("a group's page is asked only of the machine that group is on, by path", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 1));+ const store = boot(["M1"]);+ await store.getState().reload();++ asked.length = 0;+ await store.getState().loadMoreFor(["a1"], "active", `M1\u0000/w`);+ // `/w` exists on this server too: asking it would page another directory's rows into+ // this group, and leave the group's "load more" waiting on a machine it is not on. The+ // machine half never travels in the query — the request already goes to that machine.+ expect(asked).toEqual([{ machineId: "M1", workspaceGroup: "/w" }]);++ asked.length = 0;+ await store.getState().loadMoreFor(["a1"], "active", "/w");+ expect(asked).toEqual([{ machineId: null, workspaceGroup: "/w" }]);+ });++ it("a refresh over rows already on screen does not raise loading", async () => {+ answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));+ const store = boot([]);+ await store.getState().reload();+ let raised = false;+ const unsubscribe = store.subscribe((state) => {+ if (state.loading) raised = true;+ });+ await store.getState().reload();+ unsubscribe();+ expect(raised).toBe(false);+ });+});++/**+ * Which events from a machine concern this list (applyUserEvent in state/sessions.tsx).+ *+ * A machine's Projects carry THIS server's ids — installing one creates the same Project+ * over there, and every list call names it — so the id in the event is as meaningful from a+ * machine as from here.+ */+describe("events arriving from a machine", () => {+ const created = (projectId: string): ServerEvent =>+ ({ type: "session_created", projectId, agentId: "a1", sessionId: "s1" }) as ServerEvent;++ const countingStore = () => {+ const store = createSessionsStore();+ store.setState({ projectId: "p", agentIds: ["a1"] });+ let reloads = 0;+ store.setState({+ reload: async () => {+ reloads += 1;+ },+ });+ return { store, reloads: () => reloads };+ };++ it("reloads for this Project, wherever the Session was created", () => {+ const { store, reloads } = countingStore();+ applyUserEvent(store, created("p"), () => undefined, "M1");+ applyUserEvent(store, created("p"), () => undefined, null);+ expect(reloads()).toBe(2);+ });++ it("ignores another Project on a machine, as it does here", () => {+ // Unconditional for machines, every Session and every subagent started in any other+ // Project on any connected machine refetched this whole list, Agents x sources.+ const { store, reloads } = countingStore();+ applyUserEvent(store, created("other"), () => undefined, "M1");+ applyUserEvent(store, created("other"), () => undefined, null);+ expect(reloads()).toBe(0);+ });+});diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.tsindex 0c451cc7..c4830640 100644--- a/packages/web/test/session-grouping.test.ts+++ b/packages/web/test/session-grouping.test.ts@@ -34,6 +34,9 @@ import {timeGroupKey,totalCategoryCounts,workspaceGroupKey,+ workspaceGroupMachine,+ workspaceGroupPath,+ workspaceGroupQuery,workspaceLabel,} from "../src/lib/session-grouping";@@ -72,6 +75,8 @@ function session(const TEMP_A = "/data/proj/agents/default_agent/workspaces/tmp-1a2b3c4d";const TEMP_B = "/data/proj/agents/agent_helper/workspaces/tmp-00ff00aa";+/** A machine's own id, as one mints for itself: 16 base64url characters. */+const MACHINE = "noeSE0FFHhNXl2J5";describe("isTempWorkspace (temporary-workspace pattern from core's createTempWorkspace)", () => {it("matches <...>/workspaces/tmp-<8hex> with either path separator, and the empty path", () => {@@ -114,6 +119,31 @@ describe("workspaceGroupKey / workspaceLabel", () => {expect(workspaceGroupKey("")).toBe(TEMP_WORKSPACE_GROUP_KEY);});+ it("a machine's directory keys under that machine, and this server keys as it always did", () => {+ // The same path on two machines is two different directories. Absence keeps meaning+ // "here", which is what every key already persisted in a browser was written as.+ expect(workspaceGroupKey("/srv/repo", MACHINE)).toBe(`${MACHINE}\u0000/srv/repo`);+ expect(workspaceGroupKey("/srv/repo", null)).toBe("/srv/repo");+ expect(workspaceGroupKey("/srv/repo", MACHINE)).not.toBe(workspaceGroupKey("/srv/repo"));+ expect(workspaceGroupKey(TEMP_A, MACHINE)).toBe(`${MACHINE}\u0000${TEMP_WORKSPACE_GROUP_KEY}`);+ });++ it("a key splits back into the machine that holds it and the workspace half", () => {+ expect(workspaceGroupMachine(workspaceGroupKey("/srv/repo", MACHINE))).toBe(MACHINE);+ expect(workspaceGroupMachine(workspaceGroupKey(TEMP_A, MACHINE))).toBe(MACHINE);+ expect(workspaceGroupMachine("/srv/repo")).toBeNull();+ expect(workspaceGroupMachine(TEMP_WORKSPACE_GROUP_KEY)).toBeNull();+ expect(workspaceGroupPath(workspaceGroupKey("/srv/repo", MACHINE))).toBe("/srv/repo");+ expect(workspaceGroupPath(workspaceGroupKey(TEMP_A, MACHINE))).toBe(TEMP_WORKSPACE_GROUP_KEY);+ });++ it("the server query drops the machine half — the request already goes to that machine", () => {+ expect(workspaceGroupQuery(workspaceGroupKey("/srv/repo", MACHINE))).toBe("/srv/repo");+ expect(workspaceGroupQuery(workspaceGroupKey(TEMP_A, MACHINE))).toBe("temp");+ expect(workspaceGroupQuery("/srv/repo")).toBe("/srv/repo");+ expect(workspaceGroupQuery(TEMP_WORKSPACE_GROUP_KEY)).toBe("temp");+ });+it("labels are the last path segment; the filesystem root yields '/'", () => {expect(workspaceLabel("/srv/penguin/repo")).toBe("repo");expect(workspaceLabel("/srv/repo/")).toBe("repo");@@ -169,6 +199,32 @@ describe("groupSessionsByWorkspace", () => {expect(tempOnly[0]!.key).toBe(TEMP_WORKSPACE_GROUP_KEY);});+ it("splits one path across machines into one group each, and names the machine on the group", () => {+ // The sidebar's "+" opens a chat in the group's directory: one merged group would open+ // it here, in whatever this machine happens to have at that path.+ const here = session("/srv/app", "2026-07-01T10:00:00.000Z");+ const there = session("/srv/app", "2026-07-02T10:00:00.000Z");+ const groups = groupSessionsByWorkspace([here, there], (s) =>+ s.sessionId === there.sessionId ? MACHINE : null,+ );+ expect(groups.map((g) => g.key)).toEqual([`${MACHINE}\u0000/srv/app`, "/srv/app"]);+ expect(groups[0]).toMatchObject({ machineId: MACHINE, label: "app", fullPath: "/srv/app" });+ expect(groups[1]).toMatchObject({ machineId: null, label: "app", fullPath: "/srv/app" });+ });++ it("keeps each machine's temporary workspaces in its own temp group", () => {+ const here = session(TEMP_A, "2026-07-01T10:00:00.000Z");+ const there = session(TEMP_B, "2026-07-02T10:00:00.000Z");+ const groups = groupSessionsByWorkspace([here, there], (s) =>+ s.sessionId === there.sessionId ? MACHINE : null,+ );+ expect(groups.map((g) => g.key)).toEqual([+ `${MACHINE}\u0000${TEMP_WORKSPACE_GROUP_KEY}`,+ TEMP_WORKSPACE_GROUP_KEY,+ ]);+ expect(groups.every((g) => g.temp)).toBe(true);+ });+it("keeps archived sessions in their group (the sidebar splits active/archived per group)", () => {const active = session("/srv/alpha", "2026-07-02T10:00:00.000Z");const archived = session("/srv/alpha", "2026-07-01T10:00:00.000Z", { archived: true });@@ -334,13 +390,12 @@ describe("aggregateWorkspaceCounts (per-group exact server share)", () => {expect(aggregateWorkspaceCounts(new Map()).size).toBe(0);});- it("folds every temporary-workspace path into the merged temp group, deduplicating agents", () => {+ it("sums the temp group's paths, which the store has already folded onto its key", () => {const byAgent = new Map([["agent_a",{- [TEMP_A]: { ...zero, active: 1 },- [TEMP_B]: { ...zero, active: 2, archived: 1 },+ [TEMP_WORKSPACE_GROUP_KEY]: { ...zero, active: 3, archived: 1 },},],]);@@ -357,6 +412,21 @@ describe("aggregateWorkspaceCounts (per-group exact server share)", () => {},});});++ it("counts one path on two machines as two groups (one badge each, matching its own rows)", () => {+ const byAgent = new Map<string, Record<string, SessionCategoryCounts>>([+ [+ "agent_a",+ {+ "/srv/app": { ...zero, active: 2 },+ [`${MACHINE}\u0000/srv/app`]: { ...zero, active: 5 },+ },+ ],+ ]);+ const groups = aggregateWorkspaceCounts(byAgent);+ expect(groups.get("/srv/app")?.totals.active).toBe(2);+ expect(groups.get(`${MACHINE}\u0000/srv/app`)?.totals.active).toBe(5);+ });});describe("pinnedFirst (stable pinned-before-unpinned partition)", () => {@@ -574,6 +644,21 @@ describe("completeWorkspaceGroups (every counted Workspace is a group, placed byagents: { active: [], subagent: [], schedule: [], benchmark: [], archived: [] },});+ it("reads a machine-qualified count key as that machine's directory, not as a path", () => {+ const key = workspaceGroupKey("/srv/alpha", "gpu-box");+ const groups = completeWorkspaceGroups([], new Map([[key, counted({ active: 1 })]]), new Map());+ expect(groups).toEqual([+ {+ key,+ label: workspaceLabel("/srv/alpha"),+ fullPath: "/srv/alpha",+ machineId: "gpu-box",+ temp: false,+ sessions: [],+ },+ ]);+ });+it("adds an empty group for a counted Workspace the loaded rows never touched, and orders every group by its newest stamp", () => {// Loaded: one Agent's first page reached only alpha (newest) and a temp workspace.const loaded = groupSessionsByWorkspace([diff --git a/packages/web/test/session-machines.test.ts b/packages/web/test/session-machines.test.tsnew file mode 100644index 00000000..e7cba674--- /dev/null+++ b/packages/web/test/session-machines.test.ts@@ -0,0 +1,58 @@+/**+ * The routing rule (lib/session-machines.ts): a call about a Session goes to the machine the+ * Session lives on, read off the PATH, so two dozen call sites need no machine argument.+ * Pinned: which paths the rule reads, which it deliberately does not, and that absence means+ * this server.+ */+import { afterEach, describe, expect, it } from "vitest";+import {+ forgetSessionMachines,+ machineForPath,+ machineForSession,+ rememberSessionMachine,+ sessionIdInPath,+} from "../src/lib/session-machines";++afterEach(() => forgetSessionMachines());++describe("the session id in a path", () => {+ it("reads /api/sessions/<id> and everything beneath it", () => {+ expect(sessionIdInPath("/api/sessions/abc")).toBe("abc");+ expect(sessionIdInPath("/api/sessions/abc/messages?limit=5")).toBe("abc");+ expect(sessionIdInPath("/api/sessions/abc/files/content?path=%2Fx")).toBe("abc");+ });++ it("decodes an escaped id, and keeps a malformed escape rather than losing the id", () => {+ expect(sessionIdInPath("/api/sessions/a%20b/stream")).toBe("a b");+ expect(sessionIdInPath("/api/sessions/%E0%A4%A/stream")).toBe("%E0%A4%A");+ });++ it("is deliberately narrow: the project-scoped listing asks a server which Sessions IT has", () => {+ expect(sessionIdInPath("/api/projects/p/agents/a/sessions")).toBeNull();+ expect(sessionIdInPath("/api/sessions")).toBeNull();+ expect(sessionIdInPath("/api/me")).toBeNull();+ });+});++describe("where a Session lives", () => {+ it("absence means this server, and null is stored as absence", () => {+ expect(machineForSession("s1")).toBeNull();+ rememberSessionMachine("s1", "M1");+ expect(machineForSession("s1")).toBe("M1");+ rememberSessionMachine("s1", null);+ expect(machineForSession("s1")).toBeNull();+ });++ it("routes a Session-scoped path to the owner, and everything else here", () => {+ rememberSessionMachine("s1", "M1");+ expect(machineForPath("/api/sessions/s1/messages")).toBe("M1");+ expect(machineForPath("/api/sessions/other/messages")).toBeNull();+ expect(machineForPath("/api/projects/p/agents/a/sessions")).toBeNull();+ });++ it("forgets everything on a Project switch", () => {+ rememberSessionMachine("s1", "M1");+ forgetSessionMachines();+ expect(machineForSession("s1")).toBeNull();+ });+});diff --git a/packages/web/test/session-merge.test.ts b/packages/web/test/session-merge.test.tsnew file mode 100644index 00000000..1aff798d--- /dev/null+++ b/packages/web/test/session-merge.test.ts@@ -0,0 +1,42 @@+/**+ * Merging what several machines answered (lib/session-merge.ts): counts are summed across the+ * sources that answered, never zeroed by one that did not; the order is total, so equal+ * timestamps do not reshuffle between refreshes.+ */+import { describe, expect, it } from "vitest";+import { mergeCounts, newestFirst } from "../src/lib/session-merge";++describe("mergeCounts", () => {+ it("sums each category across the sources that reported", () => {+ expect(+ mergeCounts([+ { active: 2, archived: 1 },+ { active: 3, archived: 0 },+ ]),+ ).toEqual({ active: 5, archived: 1 });+ });++ it("a source that could not answer contributes nothing — and nobody counting is not zero", () => {+ expect(mergeCounts([{ active: 2 }, undefined])).toEqual({ active: 2 });+ expect(mergeCounts([undefined, undefined])).toBeUndefined();+ });+});++describe("newestFirst", () => {+ it("orders by createdAt descending, then by id, so the order is total", () => {+ const rows = [+ { sessionId: "b", createdAt: "2026-01-01T00:00:00.000Z" },+ { sessionId: "a", createdAt: "2026-01-01T00:00:00.000Z" },+ { sessionId: "c", createdAt: "2026-01-02T00:00:00.000Z" },+ ];+ expect([...rows].sort(newestFirst).map((r) => r.sessionId)).toEqual(["c", "b", "a"]);+ // The same input in another order lands the same way: equal stamps are not "stable+ // by source", they are decided.+ expect(+ [...rows]+ .reverse()+ .sort(newestFirst)+ .map((r) => r.sessionId),+ ).toEqual(["c", "b", "a"]);+ });+});diff --git a/packages/web/test/terminal-machines.test.ts b/packages/web/test/terminal-machines.test.tsnew file mode 100644index 00000000..6f435252--- /dev/null+++ b/packages/web/test/terminal-machines.test.ts@@ -0,0 +1,61 @@+/**+ * Which machine a terminal lives on (lib/terminal-machines.ts): the same rule Sessions use,+ * over `/api/terminals/<id>`, plus the one thing terminals add — the list must not treat "no+ * machines published yet" as "no machines", because that is the moment it would prune tabs+ * belonging to shells alive elsewhere.+ */+import { afterEach, describe, expect, it } from "vitest";+import {+ forgetTerminalMachines,+ machineForTerminal,+ rememberTerminalMachine,+ setTerminalMachines,+ terminalIdInPath,+ terminalMachinesPublished,+ terminalSources,+ terminalUrl,+} from "../src/lib/terminal-machines";++afterEach(() => forgetTerminalMachines());++describe("the terminal id in a path", () => {+ it("reads /api/terminals/<id> and beneath, not the bare collection", () => {+ expect(terminalIdInPath("/api/terminals/t1")).toBe("t1");+ expect(terminalIdInPath("/api/terminals/t1/stream?cols=80")).toBe("t1");+ expect(terminalIdInPath("/api/terminals")).toBeNull();+ expect(terminalIdInPath("/api/sessions/s1")).toBeNull();+ });+});++describe("addressing a terminal", () => {+ it("goes to the machine that holds it, and stays here for one nobody recorded", () => {+ rememberTerminalMachine("t1", "M1");+ expect(machineForTerminal("t1")).toBe("M1");+ expect(terminalUrl("/api/terminals/t1")).toBe("/server/M1/api/terminals/t1");+ expect(terminalUrl("/api/terminals/t2")).toBe("/api/terminals/t2");+ });++ it("an explicit server overrides the rule — creating a terminal has no id yet to route by", () => {+ expect(terminalUrl("/api/terminals", "M2")).toBe("/server/M2/api/terminals");+ expect(terminalUrl("/api/terminals", null)).toBe("/api/terminals");+ });+});++describe("the machine set", () => {+ it("is not published until set, and an empty publication is a real answer", () => {+ expect(terminalMachinesPublished()).toBe(false);+ expect(terminalSources()).toEqual([null]);+ setTerminalMachines([]);+ expect(terminalMachinesPublished()).toBe(true);+ setTerminalMachines(["M1", "M2"]);+ expect(terminalSources()).toEqual([null, "M1", "M2"]);+ });++ it("is forgotten whole on sign-out", () => {+ setTerminalMachines(["M1"]);+ rememberTerminalMachine("t1", "M1");+ forgetTerminalMachines();+ expect(terminalMachinesPublished()).toBe(false);+ expect(machineForTerminal("t1")).toBeNull();+ });+});diff --git a/packages/web/test/trace-routing.test.ts b/packages/web/test/trace-routing.test.tsnew file mode 100644index 00000000..17b8efb4--- /dev/null+++ b/packages/web/test/trace-routing.test.ts@@ -0,0 +1,59 @@+/**+ * Every call that names a Session reaches the machine the Session lives on.+ *+ * The routing rule reads `/api/sessions/<id>/…` off the path (lib/session-machines.ts). Two+ * kinds of call escape it and have to carry the machine by hand: an endpoint that buries a+ * Session id in an Agent-level path (the Trace endpoints), and a bare URL used in `<img>`,+ * `<iframe>`, `fetch` or a download link, which never passes through the fetch wrapper. Both+ * failed the same way — asked of this server about a Session on a machine, which truthfully+ * had no such file — and both are pinned here by scanning the source, so the next endpoint of+ * either shape is caught the moment it is written.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";+import { agentTraceDownloadUrl, workspaceFileUrl } from "../src/api/endpoints";+import { forgetSessionMachines, rememberSessionMachine } from "../src/lib/session-machines";++const SOURCE = fs.readFileSync(+ path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "src", "api", "endpoints.ts"),+ "utf8",+);++afterEach(() => forgetSessionMachines());++describe("Session ids buried in Agent-level paths", () => {+ it("every /traces/<sessionId> endpoint passes the Session's machine explicitly", () => {+ // Each `export const … =` block that builds a `/traces/${…sessionId…}` path must mention+ // machineForSession: the rule cannot read the id out of that path.+ const blocks = SOURCE.split(/\nexport const /).slice(1);+ const offenders = blocks+ .filter((block) => /\/traces\/\$\{encodeURIComponent\(sessionId\)\}/.test(block))+ .filter((block) => !block.includes("machineForSession(sessionId)"))+ .map((block) => block.split(/[\s=(]/)[0]);+ expect(offenders).toEqual([]);+ });+});++describe("URLs, which no fetch wrapper routes", () => {+ it("a Workspace file's address follows its Session to the machine", () => {+ expect(workspaceFileUrl("s1", "/a b.txt")).toBe(+ "/api/sessions/s1/files/content?path=%2Fa%20b.txt",+ );+ rememberSessionMachine("s1", "M1");+ expect(workspaceFileUrl("s1", "/a b.txt", true)).toBe(+ "/server/M1/api/sessions/s1/files/content?path=%2Fa%20b.txt&download=1",+ );+ });++ it("a Trace download link does too", () => {+ rememberSessionMachine("s2", "M2");+ expect(agentTraceDownloadUrl("p", "a", "s2", 3)).toBe(+ "/server/M2/api/projects/p/agents/a/traces/s2/3/download",+ );+ expect(agentTraceDownloadUrl("p", "a", "elsewhere", 0)).toBe(+ "/api/projects/p/agents/a/traces/elsewhere/0/download",+ );+ });+});diff --git a/packages/web/test/workflow-tabs.test.ts b/packages/web/test/workflow-tabs.test.tsindex 42cf211e..62cdb636 100644--- a/packages/web/test/workflow-tabs.test.ts+++ b/packages/web/test/workflow-tabs.test.ts@@ -48,6 +48,19 @@ describe("workflow tabs", () => {expect(tabs[2]!.error).toBe("module tree rejected");});+ it("serves the page of a machine's workflow through that machine, and says which", () => {+ // A Session on a machine runs a copy of the Agent there, and the workflows it built live in+ // that copy: the page is fetched through the machine's connection, and every later call+ // about the tab (reload, history, remove) has to go the same way.+ const [local] = workflowTabsOf([info({})]);+ expect(local).toMatchObject({ machineId: null, src: `${UI}/index.html` });+ const [remote] = workflowTabsOf([info({})], "m-1");+ expect(remote).toMatchObject({ machineId: "m-1", src: `/server/m-1${UI}/index.html` });+ expect(workflowAppPath("p", "a", "demo", "board", "m-1")).toBe(+ "/app/p/a/demo/board?machine=m-1",+ );+ });+it("falls back to Chat when the active tab is gone", () => {const tabs = workflowTabsOf([info({})]);expect(settleActiveTab("demo/board", tabs)).toBe("demo/board");diff --git a/packages/web/test/workspace-registry.test.ts b/packages/web/test/workspace-registry.test.tsindex 9a205008..b090ea59 100644--- a/packages/web/test/workspace-registry.test.ts+++ b/packages/web/test/workspace-registry.test.ts@@ -41,6 +41,7 @@ function group(key: string, over: Partial<WorkspaceGroup<{ id: string }>> = {})key,label: key.split("/").filter(Boolean).pop() ?? "/",fullPath: key,+ machineId: null as string | null,temp: false,sessions: [] as { id: string }[],...over,@@ -97,17 +98,17 @@ describe("setWorkspaceAlias", () => {const entries: readonly WorkspaceEntry[] = [{ path: "/a" }, { path: "/b" }];it("sets a trimmed alias, clears it on blank (revert to basename), and never mutates the input", () => {- const named = setWorkspaceAlias(entries, "/a", " My App ");+ const named = setWorkspaceAlias(entries, "/a", null, " My App ");expect(named).toEqual([{ path: "/a", alias: "My App" }, { path: "/b" }]);expect(entries[0]).toEqual({ path: "/a" }); // input untouched (React state discipline)- expect(setWorkspaceAlias(named, "/a", " ")).toEqual([{ path: "/a" }, { path: "/b" }]);+ expect(setWorkspaceAlias(named, "/a", null, " ")).toEqual([{ path: "/a" }, { path: "/b" }]);});it("same-reference fast exit: unknown path, unchanged alias, or clearing an alias that isn't set", () => {- expect(setWorkspaceAlias(entries, "/zzz", "X")).toBe(entries);- expect(setWorkspaceAlias(entries, "/a", "")).toBe(entries);- const named = setWorkspaceAlias(entries, "/a", "X");- expect(setWorkspaceAlias(named, "/a", " X ")).toBe(named);+ expect(setWorkspaceAlias(entries, "/zzz", null, "X")).toBe(entries);+ expect(setWorkspaceAlias(entries, "/a", null, "")).toBe(entries);+ const named = setWorkspaceAlias(entries, "/a", null, "X");+ expect(setWorkspaceAlias(named, "/a", null, " X ")).toBe(named);});});@@ -274,4 +275,72 @@ describe("a workspace's machine", () => {};expect(loadWorkspaceRegistry("p", storage)).toEqual([{ path: "/a" }]);});++ it("loads both machines' entries for one path (a path-only dedup here lost one for good)", () => {+ const store = new Map<string, string>();+ store.set(+ workspaceRegistryKey("p"),+ JSON.stringify([{ path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" }, { path: "/srv/app" }]),+ );+ 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: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ { path: "/srv/app" },+ ]);+ });++ it("renames one machine's workspace, keeps its machine, and leaves the other machine's alone", () => {+ const entries: readonly WorkspaceEntry[] = [+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ { path: "/srv/app" },+ ];+ expect(setWorkspaceAlias(entries, "/srv/app", "noeSE0FFHhNXl2J5", "Prod")).toEqual([+ { path: "/srv/app", alias: "Prod", machineId: "noeSE0FFHhNXl2J5" },+ { path: "/srv/app" },+ ]);+ expect(setWorkspaceAlias(entries, "/srv/app", null, "Here")).toEqual([+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ { path: "/srv/app", alias: "Here" },+ ]);+ });++ it("removes one machine's workspace, not every entry sharing the path", () => {+ const entries: readonly WorkspaceEntry[] = [+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ { path: "/srv/app" },+ ];+ expect(unregisterWorkspace(entries, "/srv/app", "noeSE0FFHhNXl2J5")).toEqual([+ { path: "/srv/app" },+ ]);+ expect(unregisterWorkspace(entries, "/srv/app")).toEqual([+ { path: "/srv/app", machineId: "noeSE0FFHhNXl2J5" },+ ]);+ expect(unregisterWorkspace(entries, "/srv/app", "UNREGISTEREDaaaa")).toBe(entries);+ });++ it("merges one group per machine, and an alias relabels only its own", () => {+ const remote = "noeSE0FFHhNXl2J5";+ const groups = [+ group(`${remote}\u0000/srv/app`, {+ fullPath: "/srv/app",+ machineId: remote,+ label: "app",+ sessions: [{ id: "s1" }],+ }),+ ];+ const merged = mergeRegisteredWorkspaces(groups, [+ { path: "/srv/app", machineId: remote, alias: "Prod" },+ { path: "/srv/app" },+ ]);+ expect(merged.map((g) => g.key)).toEqual([`${remote}\u0000/srv/app`, "/srv/app"]);+ // The remote group keeps its Sessions and takes its own alias …+ expect(merged[0]).toMatchObject({ label: "Prod", machineId: remote });+ expect(merged[0]!.sessions).toEqual([{ id: "s1" }]);+ // … and this machine's entry becomes its own empty group, unaliased.+ expect(merged[1]).toMatchObject({ label: "app", machineId: null, fullPath: "/srv/app" });+ expect(merged[1]!.sessions).toEqual([]);+ });});