A local-first multi-agent app development platform, built on PenguinHarness
feat: add the command palette and the harness history (#768)
Myriad-Dreamin5979e019f9e2
diff --git a/changelog/unreleased/2026-08-30-command-palette.md b/changelog/unreleased/2026-08-30-command-palette.mdnew file mode 100644index 00000000..588d2cee--- /dev/null+++ b/changelog/unreleased/2026-08-30-command-palette.md@@ -0,0 +1,21 @@+# Ctrl+P opens a command palette; its first command is the harness history++- **Date:** 2026-08-30+- **Type:** feature+- **Scope:** `web`, `server`, `core`++[中文版](2026-08-30-command-palette.zh.md)++Ctrl+P (⌘P on macOS) opens a VS Code-style command palette: an input that filters a list of commands, ↑↓ to select, Enter to run, Escape to close. The palette is the mechanism; commands register with it instead of claiming shortcuts of their own.++## Harness history++The one command today: an overlay over whatever you were doing — it fills the window short of a small margin, and Escape, the close button or a click on the margin returns you exactly where you were — listing the harness versions this server's data root has committed through hot updates, newest first — the pushing checkout's revision and repository when the pusher recorded them, the commit time, the content-addressed platform / cli / web bundles that identify the code itself, which version is currently committed — and **what each push changed**. The record is kept by the platform, not the runtime: the runtime only commits a version (`harness.json`); the platform that boots *is* that version, and at every boot it writes the commit record together with the interface table (`ifaces.json`) it was built from under `<root>/harness-history/` — its own directory beside the runtime's store — so the history is complete on any runtime old enough to boot the platform. The page diffs each version's table against the one before: nodes of the tree added, removed or rewired (requires, provides, contributes, children, exports), interfaces added, removed or changed member by member, and a count of data-type changes. `GET /api/version/history/ifaces/:hash` serves a stored table, `GET /api/version/history/diff?from=&to=` the diff.++`GET /api/version/history` serves the record (newest 100) with the runtime's current commit.++**Module tree.** Each version has a *Module tree* view beside its changes: the whole tree its recorded table describes — groups, modules and components under them, and for any node what it requires (and from which module), provides or exports, and contributes.++**Rollback.** The runtime's store keeps one rollback copy of each artifact; the platform keeps the whole last five versions under `<root>/harness-history/versions/` — each as the upgrade body a hand-over forwards (bundles, web archive, native assets with their exec bits, provenance), read by the same helper the Machines page uses. Any kept version has a *Roll back to this version* button (admin; two clicks): the platform hands the kept body to the runtime's upgrade channel in-process — no network hop, bind address, HTTPS gate or token involved — and answers before the swap. A push that lands reloads every tab, as a push from outside does; one the runtime refuses leaves the platform running, and the refusal is shown on the history in the runtime's words (`lastRollback` on `GET /api/version/history`). `POST /api/version/history/rollback { id }`.++The record itself is written once the runtime's commit has landed, never at boot: on a push the runtime commits after the boot succeeds, so a line written earlier would carry the previous version's bundles under the new platform's table. Writes are atomic and serialized, and a read of the history writes nothing.diff --git a/changelog/unreleased/2026-08-30-command-palette.zh.md b/changelog/unreleased/2026-08-30-command-palette.zh.mdnew file mode 100644index 00000000..9721369e--- /dev/null+++ b/changelog/unreleased/2026-08-30-command-palette.zh.md@@ -0,0 +1,21 @@+# Ctrl+P 打开命令面板;第一条命令是 harness 历史++- **Date:** 2026-08-30+- **Type:** feature+- **Scope:** `web`, `server`, `core`++[English](2026-08-30-command-palette.md)++Ctrl+P(macOS 上为 ⌘P)打开一个 VS Code 风格的命令面板:一个输入框筛选命令列表,↑↓ 选择,Enter 执行,Escape 关闭。面板是机制;命令向它注册,而不是各自占用快捷键。++## Harness 历史++目前唯一的命令:一个覆盖在当前页面之上的层——几乎占满窗口、只留一圈窄边,Escape、关闭按钮或点击边缘就回到原来的位置——列出这台服务器的数据根通过热更新提交过的 harness 版本,最新在前——推送方记录的 checkout 修订与仓库(若有)、提交时间、标识代码本身的内容寻址 platform / cli / web bundle、当前提交的是哪个版本——以及**每次推送改了什么**。记录由 platform 而不是运行时维护:运行时只提交版本(`harness.json`);启动起来的 platform 就是那个版本,它在每次启动时把提交记录连同自己构建所用的接口表(`ifaces.json`)写到 `<root>/harness-history/`——运行时 store 旁边、它自己的目录——所以只要运行时老到还能启动这个 platform,历史就是完整的。页面把每个版本的表与前一个比对:树的节点新增、移除或改了接线(requires、provides、contributes、children、exports),接口新增、移除或逐成员变化,以及数据类型变化的计数。`GET /api/version/history/ifaces/:hash` 返回存储的表,`GET /api/version/history/diff?from=&to=` 返回差异。++`GET /api/version/history` 连同运行时当前提交一起返回这份记录(最新 100 条)。++**模块树。** 每个版本在"变化"旁边还有"模块树"视图:它记录的表所描述的整棵树——组、组下的模块与组件,以及任一节点需要什么(来自哪个模块)、提供或导出什么、投递什么。++**回滚。** 运行时的 store 只为每种产物保留一份回滚副本;platform 自己在 `<root>/harness-history/versions/` 下保留最近五个完整版本——每个版本就是一次机器间移交所转发的升级体(bundle、web 归档、带可执行位记录的原生资产、来源信息),由 Machines 页面所用的同一个读取器生成。任何保留了产物的版本都有"回滚到这个版本"按钮(管理员,两次点击):platform 在进程内把保留的升级体交给运行时的升级通道——不经网络、不涉及绑定地址、HTTPS 门禁或 token——并在切换前先应答。推送落地后所有标签页会像收到外部推送一样重新加载;被运行时拒绝的推送则让 platform 继续运行,拒绝原因以运行时的原话显示在历史上(`GET /api/version/history` 的 `lastRollback`)。`POST /api/version/history/rollback { id }`。++记录本身在运行时的提交落地之后才写入,而不是在启动时:推送时运行时在启动成功后才提交,过早写入的一行会把上一个版本的 bundle 记在新 platform 的接口表之下。写入是原子且串行的,读取历史不会写任何东西。diff --git a/packages/core/src/version-info.ts b/packages/core/src/version-info.tsindex 1947dabf..b93507e8 100644--- a/packages/core/src/version-info.ts+++ b/packages/core/src/version-info.ts@@ -100,6 +100,14 @@ export interface HarnessInfo {};}+/** What a stored interface table says about itself, without reading it. */+export interface IfacesSummary {+ hash: string;+ nodes: number;+ interfaces: number;+ types: number;+}+/*** What `penguin version --json` prints and what GET /api/version returns: the running* build's identity, plus the harness this machine has in its HMR store.@@ -109,6 +117,49 @@ export interface HarnessInfo {* `harness` describes the data root's store, so only a caller that knows which root is in* play can fill it.*/+/**+ * One harness version, as the platform that WAS that version recorded it at its boot: the+ * runtime's commit record (provenance, commit time, bundles) plus the interface table the+ * platform was built from. The runtime only commits; what was pushed is written by the+ * pushed code itself, so the record is complete on any runtime that can boot it.+ */+export interface HarnessHistoryEntry {+ /** The version's identity in the history: derived from its bundles (or its table, for a packaged boot). */+ id: string;+ /** Whether the platform kept this version's artifacts, so it can be pushed back. */+ rollbackable: boolean;+ source: HarnessSource | null;+ /** When the version was committed (ISO 8601); null for a commit that predates the record. */+ pushedAt: string | null;+ bundles: HarnessInfo["bundles"];+ ifaces: IfacesSummary | null;+}++/**+ * The harness versions that have booted on this data root, newest first, and the one the+ * runtime currently has committed. Kept by the platform under `<root>/harness-history/`,+ * apart from the runtime's store.+ */+export interface HarnessHistory {+ current: HarnessInfo | null;+ entries: HarnessHistoryEntry[];+ /**+ * The last push back the runtime refused, or null. A refused rollback leaves the platform+ * that asked for it running, so it is the one that can say why; a rollback that lands+ * replaces that platform, and the new one reports nothing here.+ */+ lastRollback: RollbackFailure | null;+}++/** Why a rollback did not happen, in the runtime's own words. */+export interface RollbackFailure {+ /** The version that was to be pushed back. */+ id: string;+ error: string;+ /** When the refusal came (ISO 8601). */+ at: string;+}+export interface VersionReport extends BuildInfo {harness: HarnessInfo | null;}diff --git a/packages/hmr/src/ifaces-diff.ts b/packages/hmr/src/ifaces-diff.tsnew file mode 100644index 00000000..b5cc90f9--- /dev/null+++ b/packages/hmr/src/ifaces-diff.ts@@ -0,0 +1,180 @@+/**+ * What changed between two interface tables (ifaces.json): the nodes of the tree, their+ * manifests, and the interfaces themselves at signature level. Pure — both tables are+ * data, and the diff is data too, so the history page can show a push as "what it changed"+ * rather than as a hash.+ */++interface Table {+ hash?: string;+ ifaces: Record<string, IfaceDecl>;+ types: Record<string, unknown>;+ modules: Record<string, Manifest>;+}+interface IfaceDecl {+ name: string;+ methods: Record<string, unknown>;+ fields?: Record<string, unknown>;+ slots?: Record<string, unknown>;+}+interface Manifest {+ name: string;+ kind?: string;+ requires: Record<string, { iface: string; from?: string }>;+ provides: Record<string, string>;+ contributes: Record<string, unknown[]>;+ children: unknown[];+ exports?: string[];+}++export interface MemberChange {+ name: string;+ change: "added" | "removed" | "changed";+}++export interface IfaceChange {+ key: string;+ change: "added" | "removed" | "changed";+ methods: MemberChange[];+ fields: MemberChange[];+ slots: MemberChange[];+}++export interface ModuleChange {+ name: string;+ change: "added" | "removed" | "changed";+ /** Requirement aliases whose interface or wiring changed. */+ requires: MemberChange[];+ provides: MemberChange[];+ /** Slot keys whose contribution list changed. */+ contributes: MemberChange[];+ children: MemberChange[];+ exports: MemberChange[];+ kind: { from: string | null; to: string | null } | null;+}++export interface IfacesDiff {+ from: string | null;+ to: string | null;+ modules: ModuleChange[];+ ifaces: IfaceChange[];+ types: { added: number; removed: number; changed: number };+}++const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);++function members(+ a: Record<string, unknown> | undefined,+ b: Record<string, unknown> | undefined,+): MemberChange[] {+ const out: MemberChange[] = [];+ const keys = new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})]);+ for (const name of [...keys].sort()) {+ const x = a?.[name];+ const y = b?.[name];+ if (x === undefined) out.push({ name, change: "added" });+ else if (y === undefined) out.push({ name, change: "removed" });+ else if (!same(x, y)) out.push({ name, change: "changed" });+ }+ return out;+}++const listAsRecord = (list: unknown[] | undefined): Record<string, unknown> =>+ Object.fromEntries(+ (list ?? []).map((v) => [typeof v === "string" ? v : JSON.stringify(v), true]),+ );++/** The changes from table `a` to table `b`; either may be null (nothing recorded on that side). */+export function diffIfaces(a: Table | null, b: Table | null): IfacesDiff {+ const A = a ?? { ifaces: {}, types: {}, modules: {} };+ const B = b ?? { ifaces: {}, types: {}, modules: {} };+ const modules: ModuleChange[] = [];+ for (const name of [...new Set([...Object.keys(A.modules), ...Object.keys(B.modules)])].sort()) {+ const x = A.modules[name];+ const y = B.modules[name];+ if (x === undefined || y === undefined) {+ modules.push({+ name,+ change: x === undefined ? "added" : "removed",+ requires: [],+ provides: [],+ contributes: [],+ children: [],+ exports: [],+ kind: null,+ });+ continue;+ }+ const c: ModuleChange = {+ name,+ change: "changed",+ requires: members(x.requires, y.requires),+ provides: members(x.provides, y.provides),+ contributes: members(x.contributes, y.contributes),+ children: members(listAsRecord(x.children), listAsRecord(y.children)),+ exports: members(listAsRecord(x.exports), listAsRecord(y.exports)),+ kind:+ (x.kind ?? null) === (y.kind ?? null) ? null : { from: x.kind ?? null, to: y.kind ?? null },+ };+ if (+ c.requires.length ++ c.provides.length ++ c.contributes.length ++ c.children.length ++ c.exports.length >+ 0 ||+ c.kind !== null+ )+ modules.push(c);+ }+ const ifaces: IfaceChange[] = [];+ for (const key of [...new Set([...Object.keys(A.ifaces), ...Object.keys(B.ifaces)])].sort()) {+ const x = A.ifaces[key];+ const y = B.ifaces[key];+ if (x === undefined || y === undefined) {+ ifaces.push({+ key,+ change: x === undefined ? "added" : "removed",+ methods: [],+ fields: [],+ slots: [],+ });+ continue;+ }+ const c: IfaceChange = {+ key,+ change: "changed",+ methods: members(x.methods, y.methods),+ fields: members(x.fields, y.fields),+ slots: members(x.slots, y.slots),+ };+ if (c.methods.length + c.fields.length + c.slots.length > 0) ifaces.push(c);+ }+ const t = members(A.types, B.types);+ return {+ from: a?.hash ?? null,+ to: b?.hash ?? null,+ modules,+ ifaces,+ types: {+ added: t.filter((m) => m.change === "added").length,+ removed: t.filter((m) => m.change === "removed").length,+ changed: t.filter((m) => m.change === "changed").length,+ },+ };+}++/** The summary a stored table carries in the history: its hash and what it describes. */+export function summarizeTable(table: Table): {+ hash: string;+ nodes: number;+ interfaces: number;+ types: number;+} {+ return {+ hash: table.hash ?? "",+ nodes: Object.keys(table.modules).length,+ interfaces: Object.keys(table.ifaces).length,+ types: Object.keys(table.types).length,+ };+}diff --git a/packages/hmr/src/index.ts b/packages/hmr/src/index.tsindex df12dbea..a2bb9f33 100644--- a/packages/hmr/src/index.ts+++ b/packages/hmr/src/index.ts@@ -37,3 +37,4 @@ export type {} from "./host.js";export { HotResources } from "./resources.js";export * from "./manifest.js";+export * from "./ifaces-diff.js";diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 21edb708..1d408ac5 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -24,7 +24,8 @@ import type {ToolDefinitionConfig,} from "@prismshadow/penguin-core/interfaces";// Build/harness identity is not an interface contract — it ships from the barrel (core's version-info.ts).-import type { HarnessInfo, VersionReport } from "@prismshadow/penguin-core";+import type { HarnessInfo, VersionReport, HarnessHistory } from "@prismshadow/penguin-core";+import type { IfacesDiff } from "@prismshadow/penguin-hmr";// ---------------------------------------------------------------------------// General@@ -3668,6 +3669,21 @@ export interface PluginReadmeResponse {*/export type VersionResponse = VersionReport;+export type { HarnessHistoryEntry, IfacesSummary } from "@prismshadow/penguin-core";++/** GET /api/version/history: the harness versions this data root has committed, newest first. */+export type VersionHistoryResponse = HarnessHistory;++/** POST /api/version/history/rollback `{ id }`: the push back has started; the swap follows. */+export interface VersionRollbackResponse {+ started: true;+ id: string;+}++/** GET /api/version/history/diff?from=&to=: what changed between two stored interface tables. */+export type VersionHistoryDiffResponse = IfacesDiff;+export type { IfaceChange, IfacesDiff, MemberChange, ModuleChange } from "@prismshadow/penguin-hmr";+/*** GET /api/version/update-check: newest published release vs the running version.* Always HTTP 200 (fail-soft): a lookup failure sets `error` and leaves `latestVersion`diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 6fc5d292..ae6460b0 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -271,7 +271,7 @@ export async function bootAppDeps(// test hands the tree) is honoured here too, and the process's own console otherwise.const logDouble = replacements.find(([cls]) => cls === ConsoleLog)?.[1] as Log | undefined;const shimLog = (line: string): void => (logDouble ?? new ConsoleLog()).line(line);- const shim = ensureCliShim(config.root, config.cliEntry);+ const shim = ensureCliShim(config.root, config.cliEntry ?? null);if (shim.kind === "written") {shimLog(`Agent CLI: ${path.join(shim.dir, "penguin")} -> ${shim.entry}`);} else if (shim.kind === "absent") {diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex 42a37ae9..2f8d77a0 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -68,6 +68,10 @@ export interface ServerConfig {* Whether `penguin server|web` supervises this process (PENGUIN_SUPERVISED=1) and relaunches* it when it exits with core's SERVER_RESTART_EXIT_CODE — what makes the web UI's "restart* to update" possible. False under a direct server start, a dev run, or the desktop shell.+ *+ * Required, unlike cliEntry below: the hot-update seam names it in the+ * config interface it claims (hmr/capabilities.ts's HMR_INTERFACES), and a runtime that+ * publishes a lifecycle capability publishes this field with it — the two arrived together.*/supervised: boolean;/**@@ -99,8 +103,11 @@ export interface ServerConfig {* (http/routes/version.ts), which accepts only an INSTALLED entry it can re-run as* `penguin update`: a checkout has no release to update to, but its CLI is exactly the* one an Agent working on that checkout should be running.+ *+ * OPTIONAL for the same reason: absent — a runtime older than this field — reads as null,+ * no CLI to offer and no shim written.*/- cliEntry: string | null;+ cliEntry?: string | null;}const DAY_MS = 24 * 60 * 60 * 1000;diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex 999f52a7..40adfa72 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -303,7 +303,12 @@ export function claimHmrCapabilities(resources: Resources): HmrClaim {}// Desktop is nullable by meaning, so it sits outside the all-present check.const desktop = resources.claim<DesktopService | null>(HMR_DESKTOP_RESOURCE_ID) ?? null;- const replacements = resources.claim<Replacements>(HMR_OVERRIDES_RESOURCE_ID) ?? [];+ // The slot's older occupant is the overrides bag ({}), not a list: a platform pushed onto+ // an older runtime reads that as "no replacements" rather than tripping over it.+ const claimedReplacements = resources.claim<unknown>(HMR_OVERRIDES_RESOURCE_ID);+ const replacements: Replacements = Array.isArray(claimedReplacements)+ ? (claimedReplacements as Replacements)+ : [];// Optional by design (see the resource's own note): an older runtime published no such// holder, and a fresh one is a correct, slightly forgetful substitute. A runtime older// than this platform may also publish a holder missing the fields added since; they arediff --git a/packages/server/src/hmr/pushed-build.ts b/packages/server/src/hmr/pushed-build.tsnew file mode 100644index 00000000..6146b83d--- /dev/null+++ b/packages/server/src/hmr/pushed-build.ts@@ -0,0 +1,87 @@+/**+ * The upgrade body, rebuilt from this server's own hmr store: exactly what was pushed here,+ * forwarded unchanged — the native assets and the provenance included. Two callers read it:+ * a hand-over to another machine (machines/upgrade.ts) and the harness history, which keeps+ * a version's body as the copy it can push back. One reader, so the two never disagree about+ * what a version's body is.+ */+import fs from "node:fs";+import path from "node:path";+import zlib from "node:zlib";+import { MATERIALIZED } from "./manifest.js";++/**+ * Null when nothing has been pushed here — a server running its packaged build has no bundle+ * to hand on.+ *+ * The assets are not optional in practice: a pushed platform resolves node-pty out of its+ * assets directory and nowhere else (terminal/pty-module.ts), so a hand-over that dropped+ * them left the machine on a build whose every terminal failed with "no assets directory+ * available" — while the same build pushed by deploy.mjs worked. Exec bits come from the+ * files' modes, which the receiving host restores from the `exec` list.+ */+export function readPushedBuild(dataRoot: string): Buffer | null {+ try {+ const hmrDir = path.join(dataRoot, "hmr");+ const manifest = JSON.parse(fs.readFileSync(path.join(hmrDir, "harness.json"), "utf8")) as {+ platform?: { bundle?: string };+ cli?: { bundle?: string };+ web?: { manifest?: string };+ assets?: { dir?: string };+ source?: { repo?: string; revision?: string };+ };+ if (+ typeof manifest.platform?.bundle !== "string" ||+ typeof manifest.cli?.bundle !== "string" ||+ typeof manifest.web?.manifest !== "string"+ ) {+ return null;+ }+ const platform = fs.readFileSync(path.join(hmrDir, manifest.platform.bundle), "utf8");+ const cli = fs.readFileSync(path.join(hmrDir, manifest.cli.bundle), "utf8");+ // The web artifact is stored as gzip(JSON.stringify({ files })) — the same shape the+ // upgrade body carries, so it is unwrapped once here rather than re-encoded.+ const web = JSON.parse(+ zlib.gunzipSync(fs.readFileSync(path.join(hmrDir, manifest.web.manifest))).toString("utf8"),+ ) as { files: Record<string, string> };+ const assets =+ typeof manifest.assets?.dir === "string"+ ? readAssets(path.join(hmrDir, manifest.assets.dir))+ : undefined;+ const source =+ typeof manifest.source?.repo === "string" && typeof manifest.source.revision === "string"+ ? { repo: manifest.source.repo, revision: manifest.source.revision }+ : undefined;+ return zlib.gzipSync(+ Buffer.from(+ JSON.stringify({+ platform,+ cli,+ web,+ ...(assets ? { assets } : {}),+ ...(source ? { source } : {}),+ }),+ ),+ );+ } catch {+ return null; // No store, a partial record, or damage: nothing safe to forward.+ }+}++/** A materialized assets directory back into the shape it was pushed as. */+function readAssets(dir: string): { files: Record<string, string>; exec: string[] } {+ const files: Record<string, string> = {};+ const exec: string[] = [];+ for (const entry of fs.readdirSync(dir, { recursive: true, withFileTypes: true })) {+ if (!entry.isFile() || entry.name === MATERIALIZED) continue;+ const abs = path.join(entry.parentPath, entry.name);+ const rel = path.relative(dir, abs).split(path.sep).join("/");+ files[rel] = fs.readFileSync(abs).toString("base64");+ // The mode where the filesystem keeps one; by name where it cannot. A Windows machine has+ // no exec bit to read, and a hand-over from it would otherwise strip the bit off+ // node-pty's darwin spawn-helper — the one file whose bit decides whether a terminal+ // starts on the macOS machine receiving it. deploy.mjs applies the same rule on push.+ if (rel.endsWith("/spawn-helper") || (fs.statSync(abs).mode & 0o111) !== 0) exec.push(rel);+ }+ return { files, exec };+}diff --git a/packages/server/src/http/routes/version.ts b/packages/server/src/http/routes/version.tsindex 72679af1..0c050545 100644--- a/packages/server/src/http/routes/version.ts+++ b/packages/server/src/http/routes/version.ts@@ -22,7 +22,17 @@import { versionReport } from "../../version-report.js";import { Hono } from "hono";import type { Context } from "hono";-import type { RestartResponse, UpdateJobStatus, VersionResponse } from "../../api/types.js";+import type {+ RestartResponse,+ UpdateJobStatus,+ UpdateRunResponse,+ VersionHistoryDiffResponse,+ VersionHistoryResponse,+ VersionResponse,+ VersionRollbackResponse,+} from "../../api/types.js";+import { diffIfaces } from "@prismshadow/penguin-hmr";+import type { HarnessHistoryIface } from "../../services/harness-history.js";import { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";@@ -38,6 +48,7 @@ export interface VersionRouteDeps {updateJob: UpdateJob;/** Whether a supervisor relaunches this process, and the restart trigger the update flow pulls. */lifecycle: Lifecycle;+ history: HarnessHistoryIface;}// The classifier lives with the job now; re-exported so its unit tests keep their import.@@ -59,6 +70,45 @@ export function versionRoutes(deps: VersionRouteDeps): Hono<AppEnv> {return c.json((await versionReport(deps.config.root)) satisfies VersionResponse);});+ /** The versions that have booted on this root, newest first, with the runtime's current commit. */+ app.get("/history", async (c) => {+ return c.json((await deps.history.list()) satisfies VersionHistoryResponse);+ });++ /** A recorded interface table by hash — what a version was built from. */+ app.get("/history/ifaces/:hash", async (c) => {+ const table = await deps.history.table(c.req.param("hash"));+ if (table === null) throw new HttpError(404, "not_found", "No interface table with that hash.");+ return c.json(table);+ });++ /** What changed between two recorded tables (`from` / `to` are hashes; either may be "none"). */+ app.get("/history/diff", async (c) => {+ const load = async (q: string | undefined) =>+ q === undefined || q === "none" ? null : await deps.history.table(q);+ const [from, to] = await Promise.all([load(c.req.query("from")), load(c.req.query("to"))]);+ const asTable = (t: unknown) => t as Parameters<typeof diffIfaces>[0];+ return c.json(diffIfaces(asTable(from), asTable(to)) satisfies VersionHistoryDiffResponse);+ });++ /**+ * Pushes a kept version back through the runtime (admin). Answers before the swap: this+ * platform is what gets replaced. A push the runtime refuses leaves this platform running,+ * and the next GET /history carries the refusal as `lastRollback`.+ */+ app.post("/history/rollback", async (c) => {+ if (!c.get("user").isAdmin) throw new HttpError(403, "forbidden", "Rollback is admin-only.");+ const { id } = (await c.req.json().catch(() => ({}))) as { id?: unknown };+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]+$/.test(id))+ throw new HttpError(400, "bad_request", "`id` names a recorded version.");+ const entries = (await deps.history.list()).entries;+ const target = entries.find((e) => e.id === id);+ if (target === undefined || !target.rollbackable)+ throw new HttpError(404, "not_found", "No kept artifacts for that version.");+ void deps.history.rollback(id).catch(() => undefined);+ return c.json({ started: true, id } satisfies VersionRollbackResponse, 202);+ });+app.get("/update-check", async (c) => {// ?force=1 (the web's manual "check for updates" action) bypasses the TTL cache;// see UpdateCheckService.check for why a user-initiated press-through is acceptable.diff --git a/packages/server/src/machines/upgrade.ts b/packages/server/src/machines/upgrade.tsindex 19916457..caea2a43 100644--- a/packages/server/src/machines/upgrade.ts+++ b/packages/server/src/machines/upgrade.ts@@ -11,12 +11,13 @@* That is the difference between this and reinstalling, which replaces the program on disk* and needs the server bounced to take effect.*/-import fs from "node:fs";import http from "node:http";-import path from "node:path";-import zlib from "node:zlib";import { machineApi } from "./machine-api.js";-import { MATERIALIZED } from "../hmr/manifest.js";+import { readPushedBuild } from "../hmr/pushed-build.js";++// The body a hand-over forwards is read by the same helper the harness history keeps its+// rollback copies with; re-exported so this module stays the machines' one import for it.+export { readPushedBuild };/** Long enough for 8 MB over a slow link, plus the unpack, boot and commit on the far side. */const APPLY_TIMEOUT_MS = 10 * 60_000;@@ -42,83 +43,6 @@ export type UpgradeOutcome =/** Could not reach it, or it never answered; `detail` is its own words where there are any. */| { kind: "failed"; step: string; detail: string };-/**- * The upgrade body, rebuilt from this server's own hmr store: exactly what it was pushed,- * forwarded unchanged — the native assets and the provenance included. Null when nothing has- * been pushed here — a server running its packaged build has no bundle to hand on.- *- * The assets are not optional in practice: a pushed platform resolves node-pty out of its- * assets directory and nowhere else (terminal/pty-module.ts), so a hand-over that dropped- * them left the machine on a build whose every terminal failed with "no assets directory- * available" — while the same build pushed by deploy.mjs worked. Exec bits come from the- * files' modes, which the receiving host restores from the `exec` list.- */-export function readPushedBuild(dataRoot: string): Buffer | null {- try {- const hmrDir = path.join(dataRoot, "hmr");- const manifest = JSON.parse(fs.readFileSync(path.join(hmrDir, "harness.json"), "utf8")) as {- platform?: { bundle?: string };- cli?: { bundle?: string };- web?: { manifest?: string };- assets?: { dir?: string };- source?: { repo?: string; revision?: string };- };- if (- typeof manifest.platform?.bundle !== "string" ||- typeof manifest.cli?.bundle !== "string" ||- typeof manifest.web?.manifest !== "string"- ) {- return null;- }- const platform = fs.readFileSync(path.join(hmrDir, manifest.platform.bundle), "utf8");- const cli = fs.readFileSync(path.join(hmrDir, manifest.cli.bundle), "utf8");- // The web artifact is stored as gzip(JSON.stringify({ files })) — the same shape the- // upgrade body carries, so it is unwrapped once here rather than re-encoded.- const web = JSON.parse(- zlib.gunzipSync(fs.readFileSync(path.join(hmrDir, manifest.web.manifest))).toString("utf8"),- ) as { files: Record<string, string> };- const assets =- typeof manifest.assets?.dir === "string"- ? readAssets(path.join(hmrDir, manifest.assets.dir))- : undefined;- const source =- typeof manifest.source?.repo === "string" && typeof manifest.source.revision === "string"- ? { repo: manifest.source.repo, revision: manifest.source.revision }- : undefined;- return zlib.gzipSync(- Buffer.from(- JSON.stringify({- platform,- cli,- web,- ...(assets ? { assets } : {}),- ...(source ? { source } : {}),- }),- ),- );- } catch {- return null; // No store, a partial record, or damage: nothing safe to forward.- }-}--/** A materialized assets directory back into the shape it was pushed as. */-function readAssets(dir: string): { files: Record<string, string>; exec: string[] } {- const files: Record<string, string> = {};- const exec: string[] = [];- for (const entry of fs.readdirSync(dir, { recursive: true, withFileTypes: true })) {- if (!entry.isFile() || entry.name === MATERIALIZED) continue;- const abs = path.join(entry.parentPath, entry.name);- const rel = path.relative(dir, abs).split(path.sep).join("/");- files[rel] = fs.readFileSync(abs).toString("base64");- // The mode where the filesystem keeps one; by name where it cannot. A Windows machine has- // no exec bit to read, and a hand-over from it would otherwise strip the bit off- // node-pty's darwin spawn-helper — the one file whose bit decides whether a terminal- // starts on the macOS machine receiving it. deploy.mjs applies the same rule on push.- if (rel.endsWith("/spawn-helper") || (fs.statSync(abs).mode & 0o111) !== 0) exec.push(rel);- }- return { files, exec };-}-/** The machine's own words for a refusal: the API error envelope's message, else the text. */export function refusalDetail(status: number, text: string): string {try {diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex fe37d68b..0bd70f47 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -61,6 +61,7 @@ import {UpdateCheck,} from "./services/update-check-service.js";import { UpdateJobService } from "./services/update-job.js";+import { HarnessHistoryStore } from "./services/harness-history.js";import { UsersRepo } from "./db/repos/users.js";import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";import { ServerSettingsRepo } from "./db/repos/server-settings.js";@@ -378,6 +379,7 @@ export class CompanyModule {}GlobalFetch,UpdateCheckService,UpdateJobService,+ HarnessHistoryStore,HttpModule,WebModule,InstallRoutes,diff --git a/packages/server/src/plugin/host.ts b/packages/server/src/plugin/host.tsindex 0b6e14cc..5469849c 100644--- a/packages/server/src/plugin/host.ts+++ b/packages/server/src/plugin/host.ts@@ -127,5 +127,20 @@ export const PLUGINS_RESOURCE_ID = "platform.plugins";* on the first hot push.*/export function pluginHostFrom(resources: Resources): PluginHost {- return resources.claim<PluginHost>(PLUGINS_RESOURCE_ID) ?? new PluginHost();+ const claimed = resources.claim<Partial<PluginHost> | null>(PLUGINS_RESOURCE_ID);+ // A runtime older than this contract publishes a host of another shape (the activate-era+ // one, or one without replacements). A pushed platform must still boot on it, so an+ // unrecognized host reads as "no plugins": what it registered belongs to a generation this+ // platform cannot honor, and the seam says so rather than crashing.+ if (claimed === null || claimed === undefined || typeof claimed.modules !== "function") {+ return new PluginHost();+ }+ if (typeof claimed.replacements !== "function") {+ const host = new PluginHost();+ for (const m of claimed.modules()) {+ host.use({ specifier: m.manifest.name, modules: [m], replaces: [] });+ }+ return host;+ }+ return claimed as PluginHost;}diff --git a/packages/server/src/services/harness-history.ts b/packages/server/src/services/harness-history.tsnew file mode 100644index 00000000..90c7fa78--- /dev/null+++ b/packages/server/src/services/harness-history.ts@@ -0,0 +1,333 @@+/**+ * The harness history, kept by the platform itself. The runtime commits a version+ * (harness.json) and knows nothing else about it; the platform that boots IS that version+ * and records it here — the runtime's commit record plus the interface table this platform+ * was built from — under `<root>/harness-history/`, its own directory beside the+ * runtime's store. Every boot records (a push, a restart, a fresh install), so the record+ * is complete on any runtime old enough to boot this platform.+ *+ * The record is made once the runtime's commit has LANDED, never before: on a push the+ * runtime commits after the boot succeeds, so at setup harness.json still names the previous+ * version, and a line written then would carry the previous bundles under this platform's+ * table. `hmrControl.current()` resolves when the swap that booted this platform is over —+ * commit included — and that is when the line is written. A generation the runtime put back+ * (its boot failed) never records: what harness.json names then is not it.+ */+import fsp from "node:fs/promises";+import path from "node:path";+import { Component, Interface, Use } from "@prismshadow/penguin-core/kernel";+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";+import { atomicWriteFile } from "@prismshadow/penguin-core";+import type {+ HarnessHistory,+ HarnessHistoryEntry,+ HarnessInfo,+ IfacesSummary,+ RollbackFailure,+} from "@prismshadow/penguin-core";+import table from "../ifaces.json" with { type: "json" };+import { readHarnessInfo } from "../hmr/manifest.js";+import { readPushedBuild } from "../hmr/pushed-build.js";+import { summarizeTable } from "@prismshadow/penguin-hmr";+import type {+ Channels,+ Clock,+ HmrControl,+ HmrControlApi,+ Log,+ Paths,+} from "../hmr/capabilities.js";++/** How many versions the history remembers; the newest are kept. */+export const HISTORY_KEEP = 100;++@Interface()+export abstract class HarnessHistoryIface {+ /** The recorded versions, newest first, with the runtime's current commit and the last rollback that failed. */+ abstract list(): Promise<HarnessHistory>;+ /** A recorded interface table by hash, or null. */+ abstract table(hash: string): Promise<unknown | null>;+ /**+ * Pushes a kept version back through the runtime's own upgrade channel. Resolves true+ * once the runtime has taken it (this platform is then being replaced); false when this+ * platform kept no artifacts for that id; throws when the runtime refused, after+ * recording the refusal for `list()`.+ */+ abstract rollback(id: string): Promise<boolean>;+}++/** How many versions' artifacts the platform keeps for rollback (the runtime's store keeps one). */+export const KEEP_VERSIONS = 5;++/** A version's id: its content-addressed bundles, or its table for a packaged boot. */+export function versionId(bundles: HarnessInfo["bundles"], tableHash: string | null): string {+ const sha = (p: string | null) =>+ p === null ? "" : p.slice(p.lastIndexOf("/") + 1).replace(/\.[a-z]+$/i, "");+ const fromBundles = [sha(bundles.platform), sha(bundles.cli), sha(bundles.web)]+ .filter(Boolean)+ .join("-");+ return fromBundles !== "" ? fromBundles : `packaged-${tableHash ?? "unknown"}`;+}++const str = (v: unknown): string | null => (typeof v === "string" && v.length > 0 ? v : null);++/** A stored table's summary, or null unless every part of it is there. */+function summaryOf(raw: unknown): IfacesSummary | null {+ const i = (raw ?? {}) as Record<string, unknown>;+ const hash = str(i.hash);+ if (hash === null) return null;+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0);+ return { hash, nodes: num(i.nodes), interfaces: num(i.interfaces), types: num(i.types) };+}++/** An entry as written to disk, or null unless it names a version. */+function entryOf(raw: unknown): HarnessHistoryEntry | null {+ const e = (raw ?? {}) as Record<string, unknown>;+ const b = (e.bundles ?? {}) as Record<string, unknown>;+ const bundles = { platform: str(b.platform), cli: str(b.cli), web: str(b.web) };+ const ifaces = summaryOf(e.ifaces);+ if (bundles.platform === null && bundles.cli === null && bundles.web === null && ifaces === null)+ return null;+ const src = (e.source ?? {}) as Record<string, unknown>;+ const repo = str(src.repo);+ const revision = str(src.revision);+ return {+ id: versionId(bundles, ifaces?.hash ?? null),+ rollbackable: false,+ source: repo !== null && revision !== null ? { repo, revision } : null,+ pushedAt: str(e.pushedAt),+ bundles,+ ifaces,+ };+}++/** Two entries name the same version when their bundles agree, or — for a packaged boot with no bundles — their tables do. */+function sameVersion(a: HarnessHistoryEntry, b: HarnessHistoryEntry): boolean {+ const noBundles = (e: HarnessHistoryEntry) =>+ e.bundles.platform === null && e.bundles.cli === null && e.bundles.web === null;+ if (noBundles(a) || noBundles(b))+ return noBundles(a) && noBundles(b) && a.ifaces?.hash === b.ifaces?.hash;+ return (+ a.bundles.platform === b.bundles.platform &&+ a.bundles.cli === b.bundles.cli &&+ a.bundles.web === b.bundles.web+ );+}++/** The file a kept version's upgrade body is stored as: exactly what pushing it back sends. */+const BUILD_FILE = "build.gz";++@Component()+export class HarnessHistoryStore implements HarnessHistoryIface {+ @Use() private readonly paths!: Paths;+ @Use() private readonly clock!: Clock;+ @Use() private readonly log!: Log;+ @Use() private readonly hmrControl!: HmrControl;+ @Use() private readonly channels!: Channels;++ /** The boot's record, so a read that arrives first waits for it instead of racing it. */+ private booted: Promise<void> = Promise.resolve();+ /** Records run one at a time: two at once would write the same file over each other. */+ private chain: Promise<void> = Promise.resolve();+ private disposed = false;+ /** The last push back the runtime refused, kept in memory: a refused push leaves this platform running. */+ private lastRollback: RollbackFailure | null = null;++ private get dir(): string {+ return path.join(this.paths.root, "harness-history");+ }++ setup({ effect }: ClassCtx): void {+ effect(() => {+ this.disposed = true;+ });+ // Not awaited: current() waits out the swap that is booting this very platform.+ this.booted = (this.hmrControl as unknown as HmrControlApi).current().then(+ () => this.recordQuietly(),+ () => undefined, // no generation could boot: nothing to record+ );+ }++ private async recordQuietly(): Promise<void> {+ try {+ await this.record();+ } catch {+ // A history that cannot be written is not a reason not to boot or to answer.+ }+ }++ /**+ * Upserts the line for the runtime's current commit. A line already there for the same+ * bundles is refreshed only when it carries THIS platform's table; one carrying another+ * table belongs to the platform that recorded it and is left alone. Nothing is written+ * when the line is already what it would be.+ */+ record(): Promise<void> {+ const run = this.chain.then(() => (this.disposed ? undefined : this.recordNow()));+ this.chain = run.catch(() => undefined);+ return run;+ }++ private async recordNow(): Promise<void> {+ const current = await readHarnessInfo(this.paths.root);+ const own = table as { hash: string; ifaces: object; types: object; modules: object };+ const summary = summarizeTable(own as unknown as Parameters<typeof summarizeTable>[0]);+ await fsp.mkdir(path.join(this.dir, "ifaces"), { recursive: true });+ const tablePath = path.join(this.dir, "ifaces", `${summary.hash}.json`);+ try {+ await fsp.access(tablePath);+ } catch {+ await atomicWriteFile(tablePath, JSON.stringify(own));+ }+ const entry: HarnessHistoryEntry = {+ id: versionId(current?.bundles ?? { platform: null, cli: null, web: null }, summary.hash),+ rollbackable: false,+ source: current?.source ?? null,+ pushedAt: current?.pushedAt ?? this.clock.now().toISOString(),+ bundles: current?.bundles ?? { platform: null, cli: null, web: null },+ ifaces: summary,+ };+ const entries = await this.entries();+ const at = entries.findIndex((e) => sameVersion(e, entry));+ if (at !== -1 && entries[at]!.ifaces?.hash !== summary.hash) return;+ const next = at === -1 ? [entry, ...entries] : entries.map((e, i) => (i === at ? entry : e));+ if (at === -1 || JSON.stringify(entries[at]) !== JSON.stringify(entry)) {+ await atomicWriteFile(+ path.join(this.dir, "history.json"),+ JSON.stringify(next.slice(0, HISTORY_KEEP), null, 2),+ );+ }+ // The runtime's store keeps one rollback copy of each artifact; the platform keeps a+ // few whole versions of its own, so the history can push one back.+ if (current !== null) await this.keepArtifacts(entry.id);+ }++ private versionsDir(): string {+ return path.join(this.dir, "versions");+ }++ /**+ * Keeps the committed version's upgrade body under `versions/<id>/`, once, and prunes the+ * oldest beyond KEEP_VERSIONS. The body is the one a hand-over forwards (hmr/pushed-build.ts):+ * bundles, the web archive, the native assets with their exec bits, the provenance.+ */+ private async keepArtifacts(id: string): Promise<void> {+ if (await this.kept(id)) return;+ const body = readPushedBuild(this.paths.root);+ // No store, a partial record, or a file the runtime already pruned: this version is not+ // kept, and the history line stands without it.+ if (body === null) return;+ const dir = path.join(this.versionsDir(), id);+ const tmp = `${dir}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;+ try {+ await fsp.mkdir(tmp, { recursive: true });+ await fsp.writeFile(path.join(tmp, BUILD_FILE), body);+ await fsp.writeFile(path.join(tmp, "version.json"), JSON.stringify({ id }));+ await fsp.rename(tmp, dir);+ } catch {+ await fsp.rm(tmp, { recursive: true, force: true });+ return;+ }+ // Prune: keep the newest KEEP_VERSIONS by the history's order.+ const keep = new Set((await this.entries()).map((e) => e.id).slice(0, KEEP_VERSIONS));+ for (const name of await fsp.readdir(this.versionsDir())) {+ if (!keep.has(name) && !name.includes(".tmp-"))+ await fsp.rm(path.join(this.versionsDir(), name), { recursive: true, force: true });+ }+ }++ private async kept(id: string): Promise<boolean> {+ if (!/^[A-Za-z0-9_-]+$/.test(id)) return false;+ try {+ await fsp.access(path.join(this.versionsDir(), id, "version.json"));+ return true;+ } catch {+ return false;+ }+ }++ async rollback(id: string): Promise<boolean> {+ if (!(await this.kept(id))) return false;+ try {+ await this.push(id);+ return true;+ } catch (err) {+ // The route has already answered; the refusal is kept for the next read of the+ // history, and logged where a failed push back is seen.+ const message = err instanceof Error ? err.message : String(err);+ this.lastRollback = { id, error: message, at: this.clock.now().toISOString() };+ this.log.line(`[harness-history] rollback to ${id} failed: ${message}`);+ throw err;+ }+ }++ /**+ * Hands the kept body to the runtime's upgrade channel in-process — the same endpoint a+ * deploy reaches over HTTP, minus the network: no bind address, scheme gate or token is+ * involved, because the code being pushed is already on this machine and the route that+ * called this has done the platform's own admin check. The runtime swaps this platform+ * out on success, exactly as it does for a push from outside.+ */+ private async push(id: string): Promise<void> {+ const body = await fsp.readFile(path.join(this.versionsDir(), id, BUILD_FILE));+ const control = this.hmrControl as unknown as HmrControlApi;+ const res = await control.endpoint(+ new Request("http://localhost/api/hmr/upgrade", {+ method: "POST",+ headers: { "content-type": "application/gzip" },+ body,+ }),+ );+ const text = await res.text();+ if (!res.ok) throw new Error(`rollback to ${id}: ${res.status} ${text}`);+ const outcome = JSON.parse(text) as { status: string; web?: { rev: string }; reason?: string };+ if (outcome.status !== "ok") {+ throw new Error(`rollback to ${id}: ${outcome.reason ?? text.slice(0, 200)}`);+ }+ this.lastRollback = null;+ this.log.line(`[harness-history] rolled back to ${id}: ${text.slice(0, 200)}`);+ // Live clients (browser tabs AND the desktop window) reload once a version lands — what+ // the HTTP route does for a push from outside (hmr/routes.ts).+ this.channels.broadcast(+ "user:",+ { type: "web_updated", rev: outcome.web?.rev ?? "" },+ "server_event",+ );+ }++ /** The entries on disk, newest first; a truncated or hand-edited file degrades to what still parses. */+ async entries(): Promise<HarnessHistoryEntry[]> {+ let parsed: unknown;+ try {+ parsed = JSON.parse(await fsp.readFile(path.join(this.dir, "history.json"), "utf8"));+ } catch {+ return [];+ }+ if (!Array.isArray(parsed)) return [];+ return parsed.map(entryOf).filter((e): e is HarnessHistoryEntry => e !== null);+ }++ async list(): Promise<HarnessHistory> {+ await this.booted;+ const [current, entries] = await Promise.all([+ readHarnessInfo(this.paths.root),+ this.entries(),+ ]);+ const marked = await Promise.all(+ entries.map(async (e) => ({ ...e, rollbackable: await this.kept(e.id) })),+ );+ return { current, entries: marked, lastRollback: this.lastRollback };+ }++ async table(hash: string): Promise<unknown | null> {+ if (!/^[0-9a-f]{64}$/.test(hash)) return null;+ try {+ return JSON.parse(await fsp.readFile(path.join(this.dir, "ifaces", `${hash}.json`), "utf8"));+ } catch {+ return null;+ }+ }+}++/** The current commit as the history should show it: what `readHarnessInfo` says, or null. */+export type { HarnessInfo };diff --git a/packages/server/src/services/update-check-service.ts b/packages/server/src/services/update-check-service.tsindex 41e42394..974791bf 100644--- a/packages/server/src/services/update-check-service.ts+++ b/packages/server/src/services/update-check-service.ts@@ -25,6 +25,7 @@ import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";import { versionRoutes } from "../http/routes/version.js";import type { Clock, Config, Lifecycle } from "../hmr/capabilities.js";import type { UpdateJob } from "./update-job.js";+import type { HarnessHistoryIface } from "./harness-history.js";/** Repository the released artifacts come from (same slug as cli/update.ts's REPO_SLUG). */const REPO_SLUG = "Prism-Shadow/penguin-harness";@@ -167,6 +168,7 @@ export class VersionRoutes {@Use() private readonly updateCheck!: UpdateCheck;@Use() private readonly updateJob!: UpdateJob;@Use() private readonly lifecycle!: Lifecycle;+ @Use() private readonly history!: HarnessHistoryIface;@Bind("VersionModule.routes") routes!: Hono<AppEnv>;setup() {this.routes = versionRoutes({@@ -174,6 +176,7 @@ export class VersionRoutes {updateCheck: this.updateCheck,updateJob: this.updateJob,lifecycle: this.lifecycle,+ history: this.history,});}}diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.tsindex bc4b2b6e..df7e531f 100644--- a/packages/server/test/config.test.ts+++ b/packages/server/test/config.test.ts@@ -86,7 +86,7 @@ describe("resolveServerConfig: PENGUIN_CLI_ENTRY parsing", () => {// for checkoutCliEntry itself).const blank = resolveServerConfig({ ...base, PENGUIN_CLI_ENTRY: " " }).cliEntry;expect(blank).toBe(resolveServerConfig({ ...base }).cliEntry);- expect(blank === null || blank.endsWith(`${path.sep}penguin.js`)).toBe(true);+ expect(blank === null || blank?.endsWith(`${path.sep}penguin.js`)).toBe(true);});});diff --git a/packages/server/test/harness-history.test.ts b/packages/server/test/harness-history.test.tsnew file mode 100644index 00000000..988c0105--- /dev/null+++ b/packages/server/test/harness-history.test.ts@@ -0,0 +1,442 @@+/**+ * The harness history is kept by the platform: every boot records the runtime's current+ * commit together with the booting platform's own interface table, under+ * <root>/harness-history/ — so the record is complete on any runtime old enough to boot+ * the platform, and never depends on the runtime knowing about it.+ */+import { afterEach, describe, expect, it } from "vitest";+import fs from "node:fs/promises";+import path from "node:path";+import { wire } from "@prismshadow/penguin-core/kernel";+import table from "../src/ifaces.json" with { type: "json" };+import {+ HarnessHistoryStore,+ HISTORY_KEEP,+ KEEP_VERSIONS,+} from "../src/services/harness-history.js";+import zlib from "node:zlib";+import { diffIfaces } from "@prismshadow/penguin-hmr";+import type { VersionHistoryDiffResponse, VersionHistoryResponse } from "../src/api/types.js";+import {+ apiClient,+ createTestApp,+ loginAdmin,+ makeTempRoot,+ provisionUser,+ type TestApp,+} from "./helpers.js";++const OWN_HASH = (table as { hash: string }).hash;++/** A runtime commit record, as harness.json would carry it. */+async function commit(+ root: string,+ n: number,+ source: { repo: string; revision: string } | null = null,+) {+ await fs.mkdir(path.join(root, "hmr"), { recursive: true });+ // The store's files behind the pointers, so the platform has something to keep.+ for (const [rel, body] of [+ [`store/platform/p${n}.mjs`, `export const platform = ${n};`],+ [`store/cli/c${n}.mjs`, `export const cli = ${n};`],+ [+ `store/web/w${n}.webz`,+ zlib.gzipSync(+ JSON.stringify({ files: { "index.html": Buffer.from(`<b>${n}</b>`).toString("base64") } }),+ ),+ ],+ [`assets/a${n}/node_modules/node-pty/spawn-helper`, "#!/bin/sh"],+ ] as Array<[string, string | Buffer]>) {+ await fs.mkdir(path.dirname(path.join(root, "hmr", rel)), { recursive: true });+ await fs.writeFile(path.join(root, "hmr", rel), body);+ }+ await fs.writeFile(+ path.join(root, "hmr", "harness.json"),+ JSON.stringify({+ platform: { bundle: `store/platform/p${n}.mjs` },+ cli: { bundle: `store/cli/c${n}.mjs` },+ web: { manifest: `store/web/w${n}.webz` },+ assets: { dir: `assets/a${n}` },+ ...(source ? { source } : {}),+ pushedAt: new Date(Date.UTC(2026, 7, 30, 0, 0, n)).toISOString(),+ }),+ );+}++/** What a rollback handed the runtime's upgrade channel, and what the runtime answered with. */+const pushed: Request[] = [];+const broadcasts: unknown[] = [];+let answer: () => Response = () =>+ new Response(JSON.stringify({ status: "ok", web: { rev: "r2" } }), { status: 200 });+/** Resolves when the test says the runtime's commit has landed (the swap that booted the platform is over). */+let landed: () => Promise<void> = async () => {};+const storeAt = (root: string) =>+ wire(HarnessHistoryStore, {+ paths: { root },+ clock: { now: () => new Date("2026-08-30T12:00:00Z") },+ log: { line: () => {} },+ hmrControl: {+ current: () => landed().then(() => ({})),+ endpoint: async (req: Request) => {+ pushed.push(req);+ return answer();+ },+ },+ channels: { broadcast: (...args: unknown[]) => broadcasts.push(args) },+ });++/** Boots the store the way the platform does: setup() defers the record to the commit. */+function bootedAt(root: string) {+ const store = storeAt(root);+ const disposers: Array<() => void> = [];+ store.setup({ effect: (fn: () => void) => disposers.push(fn) } as never);+ return { store, dispose: () => disposers.forEach((fn) => fn()) };+}++describe("harness history store", () => {+ it("records a boot once per version, with this platform's own table, newest first", async () => {+ const root = await makeTempRoot();+ const store = storeAt(root);+ // Nothing committed yet: a packaged boot, identified by its table.+ await store.record();+ let entries = await store.entries();+ expect(entries).toHaveLength(1);+ expect(entries[0]!.bundles).toEqual({ platform: null, cli: null, web: null });+ expect(entries[0]!.ifaces?.hash).toBe(OWN_HASH);+ expect(entries[0]!.pushedAt).toBe("2026-08-30T12:00:00.000Z");+ // The same version booting again is the same line, not a second one.+ await store.record();+ expect(await store.entries()).toHaveLength(1);+ // A committed version: the runtime's record, plus the table.+ await commit(root, 1, { repo: "r", revision: "v1" });+ await store.record();+ await commit(root, 2);+ await store.record();+ entries = await store.entries();+ expect(entries.map((e) => e.bundles.platform)).toEqual([+ "store/platform/p2.mjs",+ "store/platform/p1.mjs",+ null,+ ]);+ expect(entries[1]!.source).toEqual({ repo: "r", revision: "v1" });+ expect(entries[1]!.pushedAt).toBe(new Date(Date.UTC(2026, 7, 30, 0, 0, 1)).toISOString());+ // The table itself is on disk under its hash, once.+ const stored = (await store.table(OWN_HASH)) as { hash: string };+ expect(stored.hash).toBe(OWN_HASH);+ expect(await store.table("f".repeat(64))).toBeNull();+ expect(await store.table("../../harness")).toBeNull();+ });++ it("never overwrites another platform's line: the boot before a push sees the previous commit", async () => {+ const root = await makeTempRoot();+ // The previous platform recorded version 1 with ITS table …+ await commit(root, 1);+ await fs.mkdir(path.join(root, "harness-history"), { recursive: true });+ const theirs = {+ source: null,+ pushedAt: "2026-08-29T00:00:00.000Z",+ bundles: {+ platform: "store/platform/p1.mjs",+ cli: "store/cli/c1.mjs",+ web: "store/web/w1.webz",+ },+ ifaces: { hash: "e".repeat(64), nodes: 1, interfaces: 1, types: 0 },+ };+ await fs.writeFile(+ path.join(root, "harness-history", "history.json"),+ JSON.stringify([theirs]),+ );+ // … and this platform boots while harness.json still says version 1.+ const store = storeAt(root);+ await store.record();+ expect(await store.entries()).toEqual([{ id: "p1-c1-w1", rollbackable: false, ...theirs }]);+ // Once the runtime commits version 2, the record is this platform's own line.+ await commit(root, 2);+ await store.record();+ const entries = await store.entries();+ expect(entries.map((e) => [e.bundles.platform, e.ifaces?.hash === OWN_HASH])).toEqual([+ ["store/platform/p2.mjs", true],+ ["store/platform/p1.mjs", false],+ ]);+ });++ it("keeps a committed version's body and hands it back to the runtime's own upgrade channel", async () => {+ const root = await makeTempRoot();+ const store = storeAt(root);+ await commit(root, 1, { repo: "r", revision: "v1" });+ await store.record();+ await commit(root, 2);+ await store.record();+ const entries = (await store.list()).entries;+ expect(entries.map((e) => [e.id, e.rollbackable])).toEqual([+ ["p2-c2-w2", true],+ ["p1-c1-w1", true],+ ]);+ // Rolling back hands the channel exactly what a deploy would post — the body a hand-over+ // forwards — with no network, token or bind address in between.+ pushed.length = 0;+ broadcasts.length = 0;+ expect(await store.rollback("p1-c1-w1")).toBe(true);+ expect(pushed).toHaveLength(1);+ expect(new URL(pushed[0]!.url).pathname).toBe("/api/hmr/upgrade");+ expect(pushed[0]!.headers.get("content-type")).toBe("application/gzip");+ expect(pushed[0]!.headers.get("authorization")).toBeNull();+ const payload = JSON.parse(+ zlib.gunzipSync(Buffer.from(await pushed[0]!.arrayBuffer())).toString("utf8"),+ ) as {+ platform: string;+ cli: string;+ web: { files: Record<string, string> };+ assets: { files: Record<string, string>; exec: string[] };+ source: { revision: string };+ };+ expect(payload.platform).toBe("export const platform = 1;");+ expect(payload.cli).toBe("export const cli = 1;");+ expect(Buffer.from(payload.web.files["index.html"]!, "base64").toString()).toBe("<b>1</b>");+ expect(payload.assets.exec).toEqual(["node_modules/node-pty/spawn-helper"]);+ expect(payload.source.revision).toBe("v1");+ // Live clients are told to reload, as they are for a push from outside.+ expect(broadcasts).toEqual([["user:", { type: "web_updated", rev: "r2" }, "server_event"]]);+ expect((await store.list()).lastRollback).toBeNull();+ // Nothing kept under that id: not a rollback.+ expect(await store.rollback("nope")).toBe(false);+ expect(await store.rollback("../etc")).toBe(false);+ });++ it("a push the runtime refuses is reported on the next read, in the runtime's words", async () => {+ const root = await makeTempRoot();+ const store = storeAt(root);+ await commit(root, 1);+ await store.record();+ await commit(root, 2);+ await store.record();+ answer = () => new Response(JSON.stringify({ status: "refused", reason: "no upgrade route" }));+ try {+ await expect(store.rollback("p1-c1-w1")).rejects.toThrow(/no upgrade route/);+ expect((await store.list()).lastRollback).toMatchObject({+ id: "p1-c1-w1",+ error: expect.stringContaining("no upgrade route") as string,+ at: "2026-08-30T12:00:00.000Z",+ });+ // The channel's own 400 (a body it could not parse) is a refusal too.+ answer = () => new Response("expected a gzip body", { status: 400 });+ await expect(store.rollback("p2-c2-w2")).rejects.toThrow(/400 expected a gzip body/);+ expect((await store.list()).lastRollback?.id).toBe("p2-c2-w2");+ } finally {+ answer = () =>+ new Response(JSON.stringify({ status: "ok", web: { rev: "r2" } }), { status: 200 });+ }+ });++ it("records a boot only once the runtime's commit has landed, and never after being put back", async () => {+ // Version 1 is committed and the platform booting is version 2's: while its boot is in+ // flight harness.json still names version 1, and no line may be written for it.+ const root = await makeTempRoot();+ await commit(root, 1);+ let commitLanded!: () => void;+ landed = () =>+ new Promise<void>((resolve) => {+ commitLanded = resolve;+ });+ try {+ const { store } = bootedAt(root);+ await new Promise((r) => setTimeout(r, 20));+ expect(await store.entries()).toEqual([]);+ await commit(root, 2);+ commitLanded();+ const entries = (await store.list()).entries;+ expect(entries.map((e) => e.bundles.platform)).toEqual(["store/platform/p2.mjs"]);+ // A generation the runtime put back (its boot failed) is disposed before the swap ends:+ // what harness.json names then is the previous version, and it stays unrecorded.+ const failed = bootedAt(root);+ failed.dispose();+ commitLanded();+ await new Promise((r) => setTimeout(r, 20));+ await commit(root, 3);+ expect(await store.entries()).toHaveLength(1);+ } finally {+ landed = async () => {};+ }+ });++ it("writes one record at a time, and rewrites nothing when the line is unchanged", async () => {+ const root = await makeTempRoot();+ const store = storeAt(root);+ await commit(root, 1);+ await Promise.all([store.record(), store.record(), store.list(), store.record()]);+ const file = path.join(root, "harness-history", "history.json");+ expect(JSON.parse(await fs.readFile(file, "utf8"))).toHaveLength(1);+ const before = await fs.stat(file);+ await new Promise((r) => setTimeout(r, 20));+ await store.record();+ expect((await fs.stat(file)).mtimeMs).toBe(before.mtimeMs);+ expect(await fs.readdir(path.join(root, "harness-history", "versions"))).toEqual(["p1-c1-w1"]);+ });++ it("keeps the newest KEEP_VERSIONS versions' artifacts", async () => {+ const root = await makeTempRoot();+ const store = storeAt(root);+ for (let i = 0; i < KEEP_VERSIONS + 2; i++) {+ await commit(root, i);+ await store.record();+ }+ const dirs = (await fs.readdir(path.join(root, "harness-history", "versions"))).sort();+ expect(dirs).toHaveLength(KEEP_VERSIONS);+ expect(dirs).not.toContain("p0-c0-w0");+ expect(dirs).toContain(`p${KEEP_VERSIONS + 1}-c${KEEP_VERSIONS + 1}-w${KEEP_VERSIONS + 1}`);+ });++ it("keeps HISTORY_KEEP entries and degrades a corrupt file to what still parses", async () => {+ const root = await makeTempRoot();+ const store = storeAt(root);+ for (let i = 0; i < HISTORY_KEEP + 3; i++) {+ await commit(root, i);+ await store.record();+ }+ expect(await store.entries()).toHaveLength(HISTORY_KEEP);+ await fs.writeFile(path.join(root, "harness-history", "history.json"), "{ not json");+ expect(await store.entries()).toEqual([]);+ await fs.writeFile(+ path.join(root, "harness-history", "history.json"),+ JSON.stringify([{ pushedAt: "x" }, { bundles: { platform: "store/platform/z.mjs" } }]),+ );+ expect((await store.entries()).map((e) => e.bundles.platform)).toEqual([+ "store/platform/z.mjs",+ ]);+ });+});++const TABLE_A = {+ ifaces: {+ "@x#Users": {+ name: "Users",+ methods: { findById: { params: [{ data: "string" }], returns: { data: "string" } } },+ slots: {},+ },+ },+ types: { "@x#Row": { id: "string" } },+ modules: {+ UsersRepo: {+ name: "UsersRepo",+ kind: "component",+ requires: {},+ provides: { Users: "@x#Users" },+ contributes: {},+ children: [],+ },+ },+};+const TABLE_B = {+ ifaces: {+ "@x#Users": {+ name: "Users",+ methods: {+ findById: { params: [{ data: "string" }], returns: { data: "string|null" } },+ count: { params: [], returns: { data: "number" } },+ },+ slots: {},+ },+ "@x#Clock": {+ name: "Clock",+ methods: { now: { params: [], returns: { data: "number" } } },+ slots: {},+ },+ },+ types: { "@x#Row": { id: "string", name: "string" }, "@x#Extra": { n: "number" } },+ modules: {+ UsersRepo: {+ name: "UsersRepo",+ kind: "component",+ requires: { clock: { iface: "@x#Clock", from: "SystemClock" } },+ provides: { Users: "@x#Users" },+ contributes: {},+ children: [],+ },+ SystemClock: {+ name: "SystemClock",+ kind: "component",+ requires: {},+ provides: { Clock: "@x#Clock" },+ contributes: {},+ children: [],+ },+ },+};++describe("interface table diff", () => {+ it("names the nodes and interfaces that appeared, vanished, or changed, member by member", () => {+ const d = diffIfaces({ hash: "a", ...TABLE_A } as never, { hash: "b", ...TABLE_B } as never);+ expect([d.from, d.to]).toEqual(["a", "b"]);+ expect(d.modules.map((m) => [m.name, m.change])).toEqual([+ ["SystemClock", "added"],+ ["UsersRepo", "changed"],+ ]);+ expect(d.modules[1]!.requires).toEqual([{ name: "clock", change: "added" }]);+ expect(d.ifaces.map((i) => [i.key, i.change])).toEqual([+ ["@x#Clock", "added"],+ ["@x#Users", "changed"],+ ]);+ expect(d.ifaces[1]!.methods).toEqual([+ { name: "count", change: "added" },+ { name: "findById", change: "changed" },+ ]);+ expect(d.types).toEqual({ added: 1, removed: 0, changed: 1 });+ expect(+ diffIfaces({ hash: "b", ...TABLE_B } as never, { hash: "a", ...TABLE_A } as never).modules[0],+ ).toMatchObject({ name: "SystemClock", change: "removed" });+ expect(diffIfaces(null, { hash: "a", ...TABLE_A } as never).ifaces).toEqual([+ { key: "@x#Users", change: "added", methods: [], fields: [], slots: [] },+ ]);+ const same = diffIfaces({ hash: "a", ...TABLE_A } as never, { hash: "a", ...TABLE_A } as never);+ expect(same.modules).toEqual([]);+ expect(same.ifaces).toEqual([]);+ });+});++describe("GET /api/version/history", () => {+ let t: TestApp | null = null;+ afterEach(async () => {+ await t?.cleanup();+ t = null;+ });++ it("a fresh root already has this platform's boot on record, with its table", async () => {+ t = await createTestApp();+ const admin = await loginAdmin(t.app);+ const client = apiClient(t.app, admin.cookie);+ const body = (await (+ await client.get("/api/version/history")+ ).json()) as VersionHistoryResponse;+ expect(body.current).toBeNull(); // the runtime committed nothing+ expect(body.entries).toHaveLength(1);+ expect(body.entries[0]!.ifaces?.hash).toBe(OWN_HASH);+ const stored = (await (await client.get(`/api/version/history/ifaces/${OWN_HASH}`)).json()) as {+ hash: string;+ };+ expect(stored.hash).toBe(OWN_HASH);+ expect((await client.get(`/api/version/history/ifaces/${"c".repeat(64)}`)).status).toBe(404);+ expect((await client.get("/api/version/history/ifaces/..%2F..%2Fharness")).status).toBe(404);+ const diff = (await (+ await client.get(`/api/version/history/diff?from=none&to=${OWN_HASH}`)+ ).json()) as VersionHistoryDiffResponse;+ expect(diff.from).toBeNull();+ expect(diff.modules.length).toBeGreaterThan(0);+ expect(diff.modules.every((m) => m.change === "added")).toBe(true);+ });++ it("a committed version is recorded with the runtime's provenance and shown current", async () => {+ t = await createTestApp({+ beforeSeed: (root) => commit(root, 7, { repo: "r", revision: "v7" }),+ });+ const admin = await loginAdmin(t.app);+ const body = (await (+ await apiClient(t.app, admin.cookie).get("/api/version/history")+ ).json()) as VersionHistoryResponse;+ expect(body.current?.bundles.platform).toBe("store/platform/p7.mjs");+ expect(body.entries[0]).toMatchObject({+ source: { repo: "r", revision: "v7" },+ bundles: { platform: "store/platform/p7.mjs" },+ ifaces: { hash: OWN_HASH },+ });+ });+});diff --git a/packages/server/test/older-runtime-config.test.ts b/packages/server/test/older-runtime-config.test.tsnew file mode 100644index 00000000..59f559a5--- /dev/null+++ b/packages/server/test/older-runtime-config.test.ts@@ -0,0 +1,28 @@+/**+ * A pushed platform boots on the runtime that is already there, and that runtime publishes+ * the config ITS build knew. Settings added to Config since — and not named by the hot-update+ * seam's config interface (hmr/capabilities.ts's HMR_INTERFACES) — are therefore optional in+ * the interface, and an absent one reads as its default; otherwise the kernel refuses the push+ * ("does not satisfy 'Config': missing [...]") and every machine on an older runtime keeps+ * the platform it had. `supervised` is NOT one of them: the seam claims it by name, so a+ * runtime without it is refused at the claim with a reason, before any module boots.+ */+import { afterEach, describe, expect, it } from "vitest";+import { createTestApp, loginAdmin, type TestApp } from "./helpers.js";++describe("a platform on a runtime whose config predates newer settings", () => {+ let t: TestApp | null = null;+ afterEach(async () => {+ await t?.cleanup();+ t = null;+ });++ it("boots and serves without cliEntry", async () => {+ t = await createTestApp({ config: { cliEntry: undefined } });+ const admin = await loginAdmin(t.app);+ const res = await t.app.request("/api/projects/default_project/agents", {+ headers: { cookie: admin.cookie },+ });+ expect(res.status).toBe(200);+ });+});diff --git a/packages/server/test/plugin.test.ts b/packages/server/test/plugin.test.tsindex 9c5ee9c3..a9a98975 100644--- a/packages/server/test/plugin.test.ts+++ b/packages/server/test/plugin.test.ts@@ -69,6 +69,21 @@ describe("pluginHostFrom", () => {it("falls back to an empty host when nothing was published", () => {expect(pluginHostFrom(new HotResources()).modules()).toEqual([]);});++ it("reads a host of an older shape as no extensions, and one without replacements as having none", () => {+ // The activate-era runtime published a different object under the same id.+ const old = new HotResources();+ old.register(PLUGINS_RESOURCE_ID, { activated: [], iface: {} });+ expect(pluginHostFrom(old).modules()).toEqual([]);+ expect(pluginHostFrom(old).replacements().size).toBe(0);+ // A modules-only host (before replacements existed): its modules carry over.+ const partial = new HotResources();+ const m = backend("carried");+ partial.register(PLUGINS_RESOURCE_ID, { modules: () => [m] });+ const host = pluginHostFrom(partial);+ expect(host.modules()).toEqual([m]);+ expect(host.replacements().size).toBe(0);+ });});describe("plugin modules on the real platform", () => {diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 52ead73b..cfd387d4 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -194,6 +194,9 @@ import type {VaultResponse,VaultUpdateRequest,InstalledPluginsResponse,+ VersionHistoryDiffResponse,+ VersionHistoryResponse,+ VersionRollbackResponse,VersionResponse,WeChatBindingPutRequest,WeChatBindingResponse,@@ -1423,6 +1426,22 @@ export const installOnMachine = (projectId: string, machineId: string) =>// Version & self-update ----------------------------------------------------------------export const getVersion = () => apiFetch<VersionResponse>("/api/version");+/** The harness versions this data root has committed, newest first, and the current one. */+export const getVersionHistory = () => apiFetch<VersionHistoryResponse>("/api/version/history");+/** Push a kept version back (admin); the swap follows the 202. */+export const rollbackVersion = (id: string) =>+ apiFetch<VersionRollbackResponse>("/api/version/history/rollback", {+ method: "POST",+ body: { id },+ });+/** A recorded interface table by hash — the module tree a version was built from. */+export const getVersionIfacesTable = (hash: string) =>+ apiFetch<unknown>(`/api/version/history/ifaces/${encodeURIComponent(hash)}`);+/** What changed between two stored interface tables; either hash may be "none". */+export const getVersionHistoryDiff = (from: string, to: string) =>+ apiFetch<VersionHistoryDiffResponse>(+ `/api/version/history/diff?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ );/** `force` (the manual "check for updates" action) bypasses the server's TTL cache. */export const checkUpdate = (force = false) =>diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex 6ab04f94..e4fddfe2 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -39,6 +39,7 @@ import { ChangePasswordDialog } from "../account/change-password-dialog";import { UpdateModal } from "../account/update-modal";import { TerminalDockRuntime } from "../../features/terminal/terminal-view-pool";import { setDockScope } from "../../features/dock/dock-state";+import { AppPalette } from "../../features/palette/app-palette";import { toneStrip } from "../../lib/tone";/**@@ -517,6 +518,7 @@ export function AppLayout() {views live in this pool and are adopted into dock tab bodies by DOM handoff,so navigating between pages never reconnects a terminal. */}<TerminalDockRuntime />+ <AppPalette /></div>{/* The software-update modal, opened from the sidebar's update row and the draftdiff --git a/packages/web/src/components/ui/modal.tsx b/packages/web/src/components/ui/modal.tsxindex b7d3a0a0..e88c2163 100644--- a/packages/web/src/components/ui/modal.tsx+++ b/packages/web/src/components/ui/modal.tsx@@ -18,7 +18,7 @@*/import { useEffect, useId, useRef } from "react";import { createPortal } from "react-dom";-import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";+import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from "react";import { CloseButton } from "./icons";export interface ModalProps {@@ -86,27 +86,26 @@ export function nextFocusIndex(count: number, at: number, backward: boolean): nureturn (at + (backward ? -1 : 1) + count) % count;}-export function Modal({- open,- title,- onClose,- children,- footer,- widthClass,- headerless,- bare,-}: ModalProps) {- // Latest-callback ref, so the effect below re-runs ONLY on open/close: call sites pass an- // inline arrow for onClose, and re-running on its identity would pop and re-push this- // dialog's esc-layer on every render — jumping it back above a menu opened inside it, so- // Escape would close the whole dialog instead of just the menu. Dropdown keeps the same- // guard for the same reason.+/**+ * What makes a portaled panel a dialog for the keyboard, shared by Modal and the overlays that+ * own their layout (the command palette, the harness history): Escape closes it only while it+ * is the topmost esc-consuming layer; opening moves focus into the panel and closing hands it+ * back; Tab and Shift+Tab cycle inside it. The returned `onKeyDown` goes on the panel element,+ * which also needs `tabIndex={-1}` so it can hold focus when nothing inside can.+ *+ * `onClose` is read through a ref so the effects re-run ONLY on open/close: call sites pass an+ * inline arrow, and re-running on its identity would pop and re-push this dialog's esc-layer+ * on every render — jumping it back above a menu opened inside it, so Escape would close the+ * whole dialog instead of just the menu. Dropdown keeps the same guard for the same reason.+ */+export function useDialogLayer(+ open: boolean,+ panelRef: RefObject<HTMLElement | null>,+ onClose: () => void,+): { onKeyDown: (e: ReactKeyboardEvent<HTMLElement>) => void } {const onCloseRef = useRef(onClose);onCloseRef.current = onClose;- const titleId = useId();- const panelRef = useRef<HTMLDivElement>(null);-// Where focus goes when the dialog closes, read during render rather than in the effect// below: a child with `autoFocus` is focused during the same commit, before any effect// runs, so by effect time document.activeElement already points inside the dialog and the@@ -147,6 +146,7 @@ export function Modal({// Every close path lands in this cleanup: Escape, the close button, the overlay// mousedown, `open` going false, and the dialog unmounting outright.return () => restoreFocusRef.current?.focus();+ // Keyed on `open` alone (a ref object is stable), so the cleanup runs for every close path.}, [open]);/**@@ -160,7 +160,7 @@ export function Modal({* child, so its keydown bubbles through here; the containment check leaves that panel's own* focus alone.*/- const onPanelKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {+ const onPanelKeyDown = (e: ReactKeyboardEvent<HTMLElement>) => {if (e.key !== "Tab" || e.defaultPrevented) return;const panel = panelRef.current;if (!panel?.contains(document.activeElement)) return;@@ -175,6 +175,22 @@ export function Modal({const at = items.indexOf(document.activeElement as HTMLElement);items[nextFocusIndex(items.length, at, e.shiftKey)]?.focus();};+ return { onKeyDown: onPanelKeyDown };+}++export function Modal({+ open,+ title,+ onClose,+ children,+ footer,+ widthClass,+ headerless,+ bare,+}: ModalProps) {+ const titleId = useId();+ const panelRef = useRef<HTMLDivElement>(null);+ const { onKeyDown: onPanelKeyDown } = useDialogLayer(open, panelRef, onClose);if (!open) return null;return createPortal(diff --git a/packages/web/src/features/harness/harness-history-overlay.tsx b/packages/web/src/features/harness/harness-history-overlay.tsxnew file mode 100644index 00000000..514f6013--- /dev/null+++ b/packages/web/src/features/harness/harness-history-overlay.tsx@@ -0,0 +1,481 @@+/**+ * Harness history, as an overlay over whatever the user was doing — not a page, so+ * closing it returns to exactly where they were. It fills the viewport short of a small+ * margin; Escape (through the shared esc-layer stack), the close button, or a click on+ * the margin closes it.+ *+ * It lists the versions this server's data root committed through hot updates,+ * newest first, and what each push changed — provenance, the content-addressed bundles,+ * and the interface table (ifaces.json) it was built from, diffed against the version+ * before it: nodes of the tree that appeared, vanished or rewired; interfaces whose+ * members changed. A push is shown as what it changed, not as a hash.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { createPortal } from "react-dom";+import { CloseIcon } from "../../components/ui/icons";+import { useDialogLayer } from "../../components/ui/modal";+import type {+ HarnessHistoryEntry,+ IfaceChange,+ MemberChange,+ ModuleChange,+ VersionHistoryDiffResponse,+ VersionHistoryResponse,+} from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { Badge } from "../../components/ui/badge";+import { Skeleton } from "../../components/ui/skeleton";+import { formatDateTime } from "../../lib/format";+import { S } from "../../lib/strings";+import { toneStrip } from "../../lib/tone";+import { ModuleTreeView } from "./module-tree-view";++/** The last path segment without its extension: `store/platform/1a2b….mjs` → `1a2b…`. */+function shortSha(pointer: string | null): string {+ if (pointer === null) return "—";+ const base = pointer.slice(pointer.lastIndexOf("/") + 1);+ return base.replace(/\.[a-z]+$/i, "");+}++const changeTone: Record<MemberChange["change"], "green" | "red" | "amber"> = {+ added: "green",+ removed: "red",+ changed: "amber",+};++function isCurrent(+ entry: HarnessHistoryEntry,+ current: VersionHistoryResponse["current"],+): boolean {+ return (+ current !== null &&+ current.bundles.platform === entry.bundles.platform &&+ current.bundles.web === entry.bundles.web+ );+}++function Members({ label, items }: { label: string; items: MemberChange[] }) {+ if (items.length === 0) return null;+ return (+ <div className="flex flex-wrap items-baseline gap-1.5 text-xs">+ <span className="text-gray-500 dark:text-gray-400">{label}</span>+ {items.map((m) => (+ <span key={m.name} className="inline-flex items-center gap-1 font-mono">+ <Badge tone={changeTone[m.change]}>{S.harnessHistory.change[m.change]}</Badge>+ {m.name}+ </span>+ ))}+ </div>+ );+}++function ModuleRow({ m }: { m: ModuleChange }) {+ const t = S.harnessHistory;+ return (+ <li className="rounded-md border border-gray-200 px-3 py-2 dark:border-gray-800">+ <div className="flex items-center gap-2 font-mono text-sm">+ <Badge tone={changeTone[m.change]}>{t.change[m.change]}</Badge>+ {m.name}+ {m.kind ? (+ <span className="text-xs text-gray-500 dark:text-gray-400">+ {m.kind.from ?? "—"} → {m.kind.to ?? "—"}+ </span>+ ) : null}+ </div>+ {m.change === "changed" ? (+ <div className="mt-1 flex flex-col gap-1">+ <Members label={t.requires} items={m.requires} />+ <Members label={t.provides} items={m.provides} />+ <Members label={t.contributes} items={m.contributes} />+ <Members label={t.children} items={m.children} />+ <Members label={t.exports} items={m.exports} />+ </div>+ ) : null}+ </li>+ );+}++function IfaceRow({ i }: { i: IfaceChange }) {+ const t = S.harnessHistory;+ return (+ <li className="rounded-md border border-gray-200 px-3 py-2 dark:border-gray-800">+ <div className="flex items-center gap-2 font-mono text-sm" title={i.key}>+ <Badge tone={changeTone[i.change]}>{t.change[i.change]}</Badge>+ {i.key.slice(i.key.indexOf("#") + 1)}+ <span className="truncate text-xs text-gray-400 dark:text-gray-500">+ {i.key.slice(0, i.key.indexOf("#"))}+ </span>+ </div>+ {i.change === "changed" ? (+ <div className="mt-1 flex flex-col gap-1">+ <Members label={t.methods} items={i.methods} />+ <Members label={t.fields} items={i.fields} />+ <Members label={t.slots} items={i.slots} />+ </div>+ ) : null}+ </li>+ );+}++type DiffLoad =+ | { state: "idle" }+ | { state: "loading" }+ | { state: "error"; message: string }+ | { state: "ready"; diff: VersionHistoryDiffResponse };++export function HarnessHistoryOverlay({ open, onClose }: { open: boolean; onClose: () => void }) {+ const t = S.harnessHistory;+ const [history, setHistory] = useState<VersionHistoryResponse | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [selected, setSelected] = useState(0);+ const [diff, setDiff] = useState<DiffLoad>({ state: "idle" });+ // What the detail pane shows for the selected version: its changes, or its whole tree.+ const [view, setView] = useState<"changes" | "tree">("changes");+ // Rollback: armed by the first click, sent by the second. A push that lands replaces the+ // platform and the runtime tells every tab to reload (`web_updated`, state/sessions.tsx),+ // so success never reports here; the history is polled only for a refusal, which the+ // platform that asked keeps as `lastRollback` because it is the one still running.+ const [rollback, setRollback] = useState<+ | { state: "idle" }+ | { state: "armed"; id: string }+ | { state: "pushing"; id: string }+ | { state: "error"; message: string }+ >({ state: "idle" });++ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ setHistory(null);+ setError(null);+ setSelected(0);+ void api+ .getVersionHistory()+ .then((data) => {+ if (!cancelled) setHistory(data);+ })+ .catch((err: unknown) => {+ if (!cancelled) setError(err instanceof Error ? err.message : String(err));+ });+ return () => {+ cancelled = true;+ };+ }, [open]);++ // Escape closes it only while it is the topmost esc-consuming layer (shared with Modal /+ // Dropdown / the palette, see modal.tsx); Tab stays inside the panel, and closing hands+ // focus back to where it was.+ const panelRef = useRef<HTMLElement>(null);+ const { onKeyDown: onPanelKeyDown } = useDialogLayer(open, panelRef, onClose);++ const reload = () =>+ api+ .getVersionHistory()+ .then((data) => setHistory(data))+ .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)));++ const startRollback = async (id: string) => {+ setRollback({ state: "pushing", id });+ try {+ await api.rollbackVersion(id);+ // The swap, if it comes, reloads this tab; what can arrive here is the refusal.+ for (let i = 0; i < 40; i++) {+ await new Promise((r) => setTimeout(r, 1500));+ try {+ const h = await api.getVersionHistory();+ if (h.lastRollback?.id === id) {+ setRollback({ state: "error", message: h.lastRollback.error });+ setHistory(h);+ return;+ }+ } catch {+ // mid-swap: the seam queues or refuses; keep polling+ }+ }+ setRollback({ state: "error", message: S.harnessHistory.rollbackTimeout });+ await reload();+ } catch (err) {+ setRollback({ state: "error", message: err instanceof Error ? err.message : String(err) });+ }+ };++ const entries = useMemo(() => history?.entries ?? [], [history]);+ const entry = entries[selected] ?? null;+ const previous = entries[selected + 1] ?? null;++ // The diff is "this version against the one before it": the previous entry's table when+ // it has one, else nothing — so the oldest recorded table reads as everything appearing.+ useEffect(() => {+ if (entry === null || entry.ifaces === null) {+ setDiff({ state: "idle" });+ return;+ }+ let cancelled = false;+ setDiff({ state: "loading" });+ void api+ .getVersionHistoryDiff(previous?.ifaces?.hash ?? "none", entry.ifaces.hash)+ .then((d) => {+ if (!cancelled) setDiff({ state: "ready", diff: d });+ })+ .catch((err: unknown) => {+ if (!cancelled)+ setDiff({ state: "error", message: err instanceof Error ? err.message : String(err) });+ });+ return () => {+ cancelled = true;+ };+ }, [entry, previous]);++ if (!open) return null;++ return createPortal(+ <div+ // z-50 like Modal's overlay: a portaled menu or tooltip (z-[60]) opened from inside still paints above it.+ className="anim-fade fixed inset-0 z-50 bg-black/45"+ onMouseDown={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}+ >+ {/* 12px off every edge: enough to read as a layer over the app, not a page of it. */}+ <section+ ref={panelRef}+ role="dialog"+ aria-modal="true"+ aria-label={t.title}+ tabIndex={-1}+ onKeyDown={onPanelKeyDown}+ className="anim-pop absolute inset-3 flex flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-2xl dark:border-gray-800 dark:bg-gray-900"+ >+ <header className="flex items-start justify-between gap-4 border-b border-gray-200 px-5 py-3 dark:border-gray-800">+ <div>+ <h1 className="text-lg font-semibold">{t.title}</h1>+ <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">{t.pageDesc}</p>+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label={S.common.close}+ className="rounded-md p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100"+ >+ <CloseIcon />+ </button>+ </header>+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">+ <div className="mx-auto max-w-6xl">+ {error !== null && (+ <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>+ {error}+ </div>+ )}++ {history === null ? (+ <div className="mt-6 space-y-2">+ <Skeleton className="h-4 w-40" />+ <Skeleton className="h-9 w-full" />+ </div>+ ) : entries.length === 0 ? (+ <p className="mt-6 text-sm text-gray-500 dark:text-gray-400">{t.empty}</p>+ ) : (+ <div className="mt-6 grid gap-6 md:grid-cols-[minmax(260px,320px)_1fr]">+ <ol className="flex flex-col gap-1" aria-label={t.title}>+ {entries.map((e, i) => (+ <li key={`${e.bundles.platform ?? ""}-${i}`}>+ <button+ type="button"+ onClick={() => setSelected(i)}+ aria-current={i === selected ? "true" : undefined}+ className={`w-full rounded-md border px-3 py-2 text-left ${+ i === selected+ ? "border-gray-300 bg-gray-100 dark:border-gray-700 dark:bg-gray-800"+ : "border-gray-200 hover:bg-gray-50 dark:border-gray-800 dark:hover:bg-gray-900"+ }`}+ >+ <div className="flex items-baseline justify-between gap-2">+ <span className="truncate font-mono text-sm">+ {e.source?.revision ?? t.noProvenance}+ </span>+ {isCurrent(e, history.current) ? (+ <Badge tone="green">{t.current}</Badge>+ ) : null}+ </div>+ <div className="mt-0.5 flex justify-between gap-2 text-xs text-gray-500 dark:text-gray-400">+ <span>{e.pushedAt ? formatDateTime(e.pushedAt) : "—"}</span>+ <span className="font-mono">+ {e.ifaces ? e.ifaces.hash.slice(0, 8) : t.noTableShort}+ </span>+ </div>+ </button>+ </li>+ ))}+ </ol>++ {entry === null ? null : (+ <section className="min-w-0">+ <h2 className="font-mono text-lg">+ {entry.source?.revision ?? t.noProvenance}+ </h2>+ {entry.source ? (+ <p className="truncate text-sm text-gray-500 dark:text-gray-400">+ {entry.source.repo}+ </p>+ ) : null}+ <dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">+ <dt className="text-gray-500 dark:text-gray-400">{t.pushedAt}</dt>+ <dd>{entry.pushedAt ? formatDateTime(entry.pushedAt) : "—"}</dd>+ <dt className="text-gray-500 dark:text-gray-400">{t.bundles}</dt>+ <dd className="font-mono text-xs tabular-nums">+ platform {shortSha(entry.bundles.platform)} · cli{" "}+ {shortSha(entry.bundles.cli)} · web {shortSha(entry.bundles.web)}+ </dd>+ <dt className="text-gray-500 dark:text-gray-400">{t.table}</dt>+ <dd className="font-mono text-xs tabular-nums">+ {entry.ifaces+ ? `${entry.ifaces.hash} · ${t.tableCounts(entry.ifaces.nodes, entry.ifaces.interfaces, entry.ifaces.types)}`+ : t.noTable}+ </dd>+ </dl>++ {!isCurrent(entry, history.current) ? (+ <div className="mt-3 flex flex-wrap items-center gap-2 text-sm">+ {!entry.rollbackable ? (+ <span className="text-gray-500 dark:text-gray-400">{t.notKept}</span>+ ) : rollback.state === "armed" && rollback.id === entry.id ? (+ <>+ <span className="text-gray-700 dark:text-gray-300">+ {t.rollbackConfirm}+ </span>+ <button+ type="button"+ onClick={() => void startRollback(entry.id)}+ className="rounded-md bg-red-600 px-3 py-1 text-white hover:bg-red-700"+ >+ {t.rollbackYes}+ </button>+ <button+ type="button"+ onClick={() => setRollback({ state: "idle" })}+ className="rounded-md border border-gray-300 px-3 py-1 dark:border-gray-700"+ >+ {S.common.cancel}+ </button>+ </>+ ) : rollback.state === "pushing" && rollback.id === entry.id ? (+ <span className="text-gray-700 dark:text-gray-300">+ {t.rollbackPushing}+ </span>+ ) : (+ <button+ type="button"+ onClick={() => setRollback({ state: "armed", id: entry.id })}+ className="rounded-md border border-gray-300 px-3 py-1 hover:bg-gray-50 dark:border-gray-700 dark:hover:bg-gray-800"+ >+ {t.rollback}+ </button>+ )}+ {rollback.state === "error" ? (+ <span className="text-red-600 dark:text-red-400">{rollback.message}</span>+ ) : null}+ </div>+ ) : null}++ <div className="mt-6 flex items-center gap-1 text-sm">+ {(["changes", "tree"] as const).map((v) => (+ <button+ key={v}+ type="button"+ onClick={() => setView(v)}+ aria-pressed={view === v}+ className={`rounded-md px-2.5 py-1 ${+ view === v+ ? "bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900"+ : "text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"+ }`}+ >+ {v === "changes" ? t.viewChanges : t.viewTree}+ </button>+ ))}+ </div>+ {view === "tree" ? (+ entry.ifaces === null ? (+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{t.noTable}</p>+ ) : (+ <ModuleTreeView hash={entry.ifaces.hash} />+ )+ ) : (+ <>+ <h3 className="mt-6 text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">+ {previous+ ? t.changesSince(+ previous.source?.revision ??+ previous.ifaces?.hash.slice(0, 8) ??+ "—",+ )+ : t.changesFirst}+ </h3>+ {entry.ifaces === null ? (+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">+ {t.noTable}+ </p>+ ) : diff.state === "loading" || diff.state === "idle" ? (+ <Skeleton className="mt-2 h-9 w-full" />+ ) : diff.state === "error" ? (+ <div+ className={`mt-2 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}+ >+ {diff.message}+ </div>+ ) : diff.diff.modules.length + diff.diff.ifaces.length === 0 &&+ diff.diff.types.added ++ diff.diff.types.removed ++ diff.diff.types.changed ===+ 0 ? (+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">+ {t.noChanges}+ </p>+ ) : (+ <div className="mt-2 flex flex-col gap-4">+ {diff.diff.modules.length > 0 ? (+ <div>+ <h4 className="mb-1 text-sm font-medium">+ {t.nodes(diff.diff.modules.length)}+ </h4>+ <ul className="flex flex-col gap-1">+ {diff.diff.modules.map((m) => (+ <ModuleRow key={m.name} m={m} />+ ))}+ </ul>+ </div>+ ) : null}+ {diff.diff.ifaces.length > 0 ? (+ <div>+ <h4 className="mb-1 text-sm font-medium">+ {t.interfaces(diff.diff.ifaces.length)}+ </h4>+ <ul className="flex flex-col gap-1">+ {diff.diff.ifaces.map((i) => (+ <IfaceRow key={i.key} i={i} />+ ))}+ </ul>+ </div>+ ) : null}+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {t.typesSummary(+ diff.diff.types.added,+ diff.diff.types.removed,+ diff.diff.types.changed,+ )}+ </p>+ </div>+ )}+ </>+ )}+ </section>+ )}+ </div>+ )}+ </div>+ </div>+ </section>+ </div>,+ document.body,+ );+}diff --git a/packages/web/src/features/harness/module-tree-view.tsx b/packages/web/src/features/harness/module-tree-view.tsxnew file mode 100644index 00000000..1f52e65d--- /dev/null+++ b/packages/web/src/features/harness/module-tree-view.tsx@@ -0,0 +1,244 @@+/**+ * A version's whole module tree, read off its recorded interface table: the groups and+ * the nodes under them, each with what it requires, provides, exports and contributes.+ * Pure rendering over the table — the same data the CI page draws.+ */+import { useEffect, useMemo, useState } from "react";+import * as api from "../../api/endpoints";+import { Badge } from "../../components/ui/badge";+import { Skeleton } from "../../components/ui/skeleton";+import { S } from "../../lib/strings";+import { toneStrip } from "../../lib/tone";++interface Manifest {+ name: string;+ kind?: "module" | "component";+ requires: Record<string, { iface: string; from?: string }>;+ provides: Record<string, string>;+ contributes: Record<string, unknown[]>;+ children: Array<string | { keyed: string }>;+ exports?: string[];+}+interface Table {+ hash: string;+ modules: Record<string, Manifest>;+ ifaces: Record<string, unknown>;+}++type NodeKind = "group" | "module" | "component";+const kindOf = (m: Manifest): NodeKind =>+ m.kind === "component" ? "component" : m.exports?.length ? "group" : "module";+const kindTone: Record<NodeKind, "gray" | "brand" | "green"> = {+ group: "gray",+ module: "brand",+ component: "green",+};+const short = (key: string) => key.slice(key.indexOf("#") + 1);++function Node({+ name,+ table,+ depth,+ selected,+ onSelect,+}: {+ name: string;+ table: Table;+ depth: number;+ selected: string | null;+ onSelect: (name: string) => void;+}) {+ const m = table.modules[name];+ const [openState, setOpen] = useState(depth < 1);+ if (m === undefined) {+ return (+ <li className="text-xs text-gray-400 dark:text-gray-500" style={{ paddingLeft: depth * 16 }}>+ {name}+ </li>+ );+ }+ const kind = kindOf(m);+ const children = m.children.filter((c): c is string => typeof c === "string");+ const wildcard = m.children.length !== children.length;+ return (+ <li>+ <div+ className={`flex items-center gap-1.5 rounded px-1.5 py-0.5 text-sm ${+ selected === name+ ? "bg-gray-100 dark:bg-gray-800"+ : "hover:bg-gray-50 dark:hover:bg-gray-900"+ }`}+ style={{ paddingLeft: depth * 16 + 6 }}+ >+ {children.length > 0 || wildcard ? (+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ aria-expanded={openState}+ aria-label={openState ? S.harnessHistory.collapse : S.harnessHistory.expand}+ className="w-4 text-xs text-gray-400"+ >+ {openState ? "▾" : "▸"}+ </button>+ ) : (+ <span className="w-4" />+ )}+ <Badge tone={kindTone[kind]}>{S.harnessHistory.kind[kind]}</Badge>+ <button type="button" onClick={() => onSelect(name)} className="font-mono text-left">+ {name}+ </button>+ </div>+ {openState && (children.length > 0 || wildcard) ? (+ <ul>+ {children.map((c) => (+ <Node+ key={c}+ name={c}+ table={table}+ depth={depth + 1}+ selected={selected}+ onSelect={onSelect}+ />+ ))}+ {wildcard ? (+ <li+ className="text-xs text-gray-400 dark:text-gray-500"+ style={{ paddingLeft: (depth + 1) * 16 + 26 }}+ >+ {S.harnessHistory.extensionSlot}+ </li>+ ) : null}+ </ul>+ ) : null}+ </li>+ );+}++function Detail({ name, table }: { name: string; table: Table }) {+ const t = S.harnessHistory;+ const m = table.modules[name];+ if (m === undefined) return null;+ const kind = kindOf(m);+ const req = Object.entries(m.requires);+ const prov = Object.entries(m.provides);+ const contrib = Object.entries(m.contributes);+ const exportsSet = new Set(m.exports ?? []);+ const row = (label: string, body: React.ReactNode) => (+ <div className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">+ <dt className="text-gray-500 dark:text-gray-400">{label}</dt>+ <dd className="min-w-0">{body}</dd>+ </div>+ );+ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <Badge tone={kindTone[kind]}>{t.kind[kind]}</Badge>+ <span className="font-mono text-sm">{name}</span>+ </div>+ {row(+ t.requires,+ req.length === 0 ? (+ <span className="text-gray-400">—</span>+ ) : (+ <ul className="flex flex-col gap-0.5 font-mono">+ {req.map(([f, r]) => (+ <li key={f} title={r.iface}>+ {f}: {short(r.iface)}+ {r.from ? <span className="text-gray-400"> ← {r.from}</span> : null}+ </li>+ ))}+ </ul>+ ),+ )}+ {row(+ kind === "group" ? t.exports : t.provides,+ prov.length === 0 ? (+ <span className="text-gray-400">—</span>+ ) : (+ <ul className="flex flex-col gap-0.5 font-mono">+ {prov.map(([a, k]) => (+ <li key={a} title={k}>+ {a}+ {a !== short(k) ? <span className="text-gray-400">: {short(k)}</span> : null}+ {kind === "group" && !exportsSet.has(a) ? (+ <span className="text-gray-400"> ({t.ownProvision})</span>+ ) : null}+ </li>+ ))}+ </ul>+ ),+ )}+ {contrib.length > 0+ ? row(+ t.contributes,+ <ul className="flex flex-col gap-0.5 font-mono">+ {contrib.map(([slot, items]) => (+ <li key={slot}>+ {slot} × {items.length}+ </li>+ ))}+ </ul>,+ )+ : null}+ </div>+ );+}++export function ModuleTreeView({ hash }: { hash: string }) {+ const t = S.harnessHistory;+ const [table, setTable] = useState<Table | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [selected, setSelected] = useState<string | null>(null);+ useEffect(() => {+ let cancelled = false;+ setTable(null);+ setError(null);+ setSelected(null);+ void api+ .getVersionIfacesTable(hash)+ .then((data) => {+ if (!cancelled) setTable(data as Table);+ })+ .catch((err: unknown) => {+ if (!cancelled) setError(err instanceof Error ? err.message : String(err));+ });+ return () => {+ cancelled = true;+ };+ }, [hash]);+ const roots = useMemo(() => {+ if (table === null) return [];+ const childOf = new Set<string>();+ for (const m of Object.values(table.modules))+ for (const c of m.children) if (typeof c === "string") childOf.add(c);+ return Object.keys(table.modules).filter((n) => !childOf.has(n));+ }, [table]);+ if (error !== null)+ return (+ <div className={`mt-2 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>{error}</div>+ );+ if (table === null) return <Skeleton className="mt-2 h-9 w-full" />;+ return (+ <div className="mt-2 grid gap-4 md:grid-cols-[minmax(280px,1fr)_minmax(280px,1fr)]">+ <ul className="max-h-[60vh] overflow-y-auto rounded-md border border-gray-200 py-1 dark:border-gray-800">+ {roots.map((r) => (+ <Node+ key={r}+ name={r}+ table={table}+ depth={0}+ selected={selected}+ onSelect={setSelected}+ />+ ))}+ </ul>+ <div className="rounded-md border border-gray-200 px-3 py-2 dark:border-gray-800">+ {selected === null ? (+ <p className="text-sm text-gray-500 dark:text-gray-400">{t.pickNode}</p>+ ) : (+ <Detail name={selected} table={table} />+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/features/palette/app-palette.tsx b/packages/web/src/features/palette/app-palette.tsxnew file mode 100644index 00000000..1baf4807--- /dev/null+++ b/packages/web/src/features/palette/app-palette.tsx@@ -0,0 +1,32 @@+/**+ * The app's command palette and its actions. Mounted once in AppLayout; the palette is+ * the mechanism, this file is the registry: an action here, never a new global shortcut.+ * An action opens an overlay over the current page rather than navigating — closing it+ * leaves the user exactly where they were.+ */+import { useMemo, useState } from "react";+import type { PaletteAction } from "../../lib/command-palette";+import { S } from "../../lib/strings";+import { HarnessHistoryOverlay } from "../harness/harness-history-overlay";+import { CommandPalette } from "./command-palette";++export function AppPalette() {+ const [historyOpen, setHistoryOpen] = useState(false);+ const actions = useMemo<PaletteAction[]>(+ () => [+ {+ id: "harness-history",+ label: S.commandPalette.harnessHistory,+ keywords: ["harness history", "version", "hmr", "ifaces"],+ run: () => setHistoryOpen(true),+ },+ ],+ [],+ );+ return (+ <>+ <CommandPalette actions={actions} />+ <HarnessHistoryOverlay open={historyOpen} onClose={() => setHistoryOpen(false)} />+ </>+ );+}diff --git a/packages/web/src/features/palette/command-palette.tsx b/packages/web/src/features/palette/command-palette.tsxnew file mode 100644index 00000000..d5268f27--- /dev/null+++ b/packages/web/src/features/palette/command-palette.tsx@@ -0,0 +1,136 @@+/**+ * Ctrl+P / Cmd+P command palette, VSCode-style: a top-centered input filtering a list of+ * actions; Enter (or click) runs the selected one. The palette is mechanism only — its+ * actions come from the mount point (app-palette.tsx), so a new capability registers an+ * action instead of claiming another global shortcut.+ *+ * Keyboard model: ArrowUp/ArrowDown move the selection (wrapping), Enter runs, Escape+ * closes through the shared esc-layer stack (modal.tsx), and the shortcut that opened it+ * toggles it closed. Filtering is filterPaletteActions (lib/command-palette.ts).+ */+import { useEffect, useRef, useState } from "react";+import { createPortal } from "react-dom";+import { useDialogLayer } from "../../components/ui/modal";+import {+ filterPaletteActions,+ isCommandPaletteShortcut,+ type PaletteAction,+} from "../../lib/command-palette";+import { S } from "../../lib/strings";++function isMacPlatform(): boolean {+ if (typeof navigator === "undefined") return false;+ return /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);+}++export function CommandPalette({ actions }: { actions: readonly PaletteAction[] }) {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const [selected, setSelected] = useState(0);++ // Global shortcut, registered once (a functional update reads the latest `open`).+ // preventDefault on every match — otherwise the browser's print dialog opens underneath.+ useEffect(() => {+ const isMac = isMacPlatform();+ const onKey = (e: KeyboardEvent) => {+ if (!isCommandPaletteShortcut(e, isMac)) return;+ e.preventDefault();+ setOpen((o) => !o);+ setQuery("");+ setSelected(0);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ // Escape closes it only while it is the topmost esc-consuming layer (shared with Modal /+ // Dropdown, see modal.tsx), so an action's own dialog above it gets its Escape first; Tab+ // stays inside the panel, and closing hands focus back to where it was.+ const panelRef = useRef<HTMLDivElement>(null);+ const { onKeyDown: onPanelKeyDown } = useDialogLayer(open, panelRef, () => setOpen(false));++ if (!open) return null;++ const filtered = filterPaletteActions(actions, query);+ const sel = Math.min(selected, Math.max(filtered.length - 1, 0));++ const runAction = (action: PaletteAction) => {+ // Close first: an action may open its own overlay and expects the palette gone.+ setOpen(false);+ action.run();+ };++ const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ if (filtered.length === 0) return;+ const delta = e.key === "ArrowDown" ? 1 : -1;+ setSelected((sel + delta + filtered.length) % filtered.length);+ } else if (e.key === "Enter") {+ e.preventDefault();+ const action = filtered[sel];+ if (action !== undefined) runAction(action);+ }+ };++ return createPortal(+ <div+ // z-50 like Modal's overlay: a portaled menu or tooltip (z-[60]) opened from inside still paints above it.+ className="anim-fade fixed inset-0 z-50 flex justify-center bg-black/45 px-4 pt-[10vh]"+ onMouseDown={(e) => {+ if (e.target === e.currentTarget) setOpen(false);+ }}+ >+ <div+ ref={panelRef}+ role="dialog"+ aria-modal="true"+ aria-label={S.commandPalette.title}+ tabIndex={-1}+ onKeyDown={onPanelKeyDown}+ className="anim-pop h-fit w-full max-w-md overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl dark:border-gray-800 dark:bg-gray-900"+ >+ <input+ autoFocus+ value={query}+ onChange={(e) => {+ setQuery(e.target.value);+ setSelected(0);+ }}+ onKeyDown={onInputKeyDown}+ placeholder={S.commandPalette.placeholder}+ aria-label={S.commandPalette.placeholder}+ className="w-full border-b border-gray-200 bg-transparent px-4 py-3 text-sm outline-none placeholder:text-gray-400 dark:border-gray-800 dark:placeholder:text-gray-500"+ />+ {filtered.length === 0 ? (+ <p className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">+ {S.commandPalette.noResults}+ </p>+ ) : (+ <ul className="max-h-[40vh] overflow-y-auto py-1" role="listbox">+ {filtered.map((action, i) => (+ <li key={action.id} role="option" aria-selected={i === sel}>+ <button+ type="button"+ className={`w-full px-4 py-2 text-left text-sm ${+ i === sel+ ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-700 dark:text-gray-300"+ }`}+ onMouseEnter={() => setSelected(i)}+ onClick={() => runAction(action)}+ >+ {action.label}+ </button>+ </li>+ ))}+ </ul>+ )}+ <div className="border-t border-gray-200 px-4 py-2 text-right text-xs text-gray-400 dark:border-gray-800 dark:text-gray-500">+ {S.commandPalette.hint}+ </div>+ </div>+ </div>,+ document.body,+ );+}diff --git a/packages/web/src/lib/command-palette.ts b/packages/web/src/lib/command-palette.tsnew file mode 100644index 00000000..00c0ec7b--- /dev/null+++ b/packages/web/src/lib/command-palette.ts@@ -0,0 +1,46 @@+/**+ * Command palette (Ctrl+P / Cmd+P) pure logic: the shortcut matcher and the action+ * filter, kept apart from the component so they are testable without a DOM.+ */++/** Keyboard-event shape the matcher needs (a subset of KeyboardEvent, for easy testing). */+export type ShortcutKeyEvent = Pick<+ KeyboardEvent,+ "key" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey"+>;++/**+ * Ctrl+P on Windows/Linux, Cmd+P on macOS — the platform is a parameter (read once at+ * the call site) so the matcher stays a pure function. Shift and Alt must be up: Ctrl+Shift+P+ * belongs to the browser's own tooling, and a chord with Alt is never ours.+ */+export function isCommandPaletteShortcut(e: ShortcutKeyEvent, isMac: boolean): boolean {+ if (e.key !== "p" && e.key !== "P") return false;+ if (e.altKey || e.shiftKey) return false;+ return isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;+}++export interface PaletteAction {+ id: string;+ label: string;+ /** Searchable words beyond the label (an English alias under a Chinese label, say). */+ keywords?: readonly string[];+ run: () => void;+}++/**+ * Palette filtering, VSCode-style-lite: every whitespace-separated query token must appear+ * (case-insensitive substring) in the label or a keyword, in any order. Predictable over+ * fuzzy for a handful of actions; an empty query lists everything in registration order.+ */+export function filterPaletteActions<A extends { label: string; keywords?: readonly string[] }>(+ actions: readonly A[],+ query: string,+): A[] {+ const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);+ if (tokens.length === 0) return [...actions];+ return actions.filter((a) => {+ const hay = [a.label, ...(a.keywords ?? [])].join(" ").toLowerCase();+ return tokens.every((t) => hay.includes(t));+ });+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 08c1a803..0aed9030 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -254,6 +254,59 @@ export const en: Strings = {} as Record<string, string>,},+ commandPalette: {+ title: "Command Palette",+ placeholder: "Type to filter commands…",+ noResults: "No matching commands",+ hint: "Ctrl+P / ⌘P to toggle · ↑↓ to select · Enter to run",+ harnessHistory: "Harness history",+ },+ harnessHistory: {+ title: "Harness history",+ pageDesc:+ "Every harness version this server committed through a hot update, newest first, and what each push changed in the module tree and its interfaces.",+ loading: "Loading…",+ empty: "No harness has been pushed to this server yet.",+ current: "current",+ noProvenance: "(no provenance recorded)",+ pushedAt: "Committed",+ bundles: "Bundles",+ table: "Interface table",+ tableCounts: (nodes: number, interfaces: number, types: number) =>+ `${nodes} nodes · ${interfaces} interfaces · ${types} types`,+ noTable: "This push carried no interface table.",+ noTableShort: "no table",+ changesSince: (previous: string) => `Changes since ${previous}`,+ changesFirst: "Changes (first recorded table)",+ noChanges: "No interface or tree changes.",+ nodes: (n: number) => `Nodes (${n})`,+ interfaces: (n: number) => `Interfaces (${n})`,+ typesSummary: (added: number, removed: number, changed: number) =>+ `Data types: ${added} added, ${removed} removed, ${changed} changed`,+ change: { added: "added", removed: "removed", changed: "changed" },+ rollback: "Roll back to this version",+ rollbackConfirm: "Push this version back and swap now?",+ rollbackYes: "Roll back",+ rollbackPushing: "Pushing… the server swaps when it lands.",+ rollbackTimeout: "The server did not report the swap in time; check the history.",+ notKept: "Artifacts of this version were not kept; it cannot be pushed back.",+ viewChanges: "Changes",+ viewTree: "Module tree",+ kind: { group: "group", module: "module", component: "component" },+ expand: "Expand",+ collapse: "Collapse",+ extensionSlot: "+ extension modules",+ ownProvision: "own",+ pickNode: "Pick a node to see what it requires and provides.",+ requires: "requires",+ provides: "provides",+ contributes: "contributes",+ children: "children",+ exports: "exports",+ methods: "methods",+ fields: "fields",+ slots: "slots",+ },/*** The software-update flow (lib/update-flow.ts): the one modal for both the server release* and the desktop client, the account-menu row, the version-line badge, and the toasts fordiff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex e9ba481b..4becfcd8 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -270,6 +270,59 @@ export const zh = {} as Record<string, string>,},+ commandPalette: {+ title: "命令面板",+ placeholder: "输入以筛选命令…",+ noResults: "没有匹配的命令",+ hint: "Ctrl+P / ⌘P 切换 · ↑↓ 选择 · Enter 执行",+ harnessHistory: "Harness 历史",+ },+ harnessHistory: {+ title: "Harness 历史",+ pageDesc:+ "这台服务器通过热更新提交过的每个 harness 版本,最新在前,以及每次推送在模块树与接口上改了什么。",+ loading: "加载中…",+ empty: "还没有向这台服务器推送过 harness。",+ current: "当前",+ noProvenance: "(未记录来源)",+ pushedAt: "提交时间",+ bundles: "Bundle",+ table: "接口表",+ tableCounts: (nodes: number, interfaces: number, types: number) =>+ `${nodes} 个节点 · ${interfaces} 个接口 · ${types} 个类型`,+ noTable: "这次推送没有携带接口表。",+ noTableShort: "无表",+ changesSince: (previous: string) => `相对 ${previous} 的变化`,+ changesFirst: "变化(首个记录的表)",+ noChanges: "接口与树没有变化。",+ nodes: (n: number) => `节点(${n})`,+ interfaces: (n: number) => `接口(${n})`,+ typesSummary: (added: number, removed: number, changed: number) =>+ `数据类型:新增 ${added},移除 ${removed},变化 ${changed}`,+ change: { added: "新增", removed: "移除", changed: "变化" },+ rollback: "回滚到这个版本",+ rollbackConfirm: "把这个版本推回去并立即切换?",+ rollbackYes: "回滚",+ rollbackPushing: "推送中……到达后服务器会切换。",+ rollbackTimeout: "服务器没有及时报告切换;请查看历史。",+ notKept: "这个版本的产物没有保留,无法推回。",+ viewChanges: "变化",+ viewTree: "模块树",+ kind: { group: "组", module: "模块", component: "组件" },+ expand: "展开",+ collapse: "收起",+ extensionSlot: "+ 扩展模块",+ ownProvision: "自身",+ pickNode: "选一个节点,查看它需要和提供什么。",+ requires: "requires",+ provides: "provides",+ contributes: "contributes",+ children: "children",+ exports: "exports",+ methods: "方法",+ fields: "字段",+ slots: "槽位",+ },/*** The software-update flow (lib/update-flow.ts): the one modal for both the server release* and the desktop client, the account-menu row, the version-line badge, and the toasts fordiff --git a/packages/web/test/command-palette.test.ts b/packages/web/test/command-palette.test.tsnew file mode 100644index 00000000..201e9559--- /dev/null+++ b/packages/web/test/command-palette.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { filterPaletteActions, isCommandPaletteShortcut } from "../src/lib/command-palette";++const key = (+ k: string,+ mods: Partial<Record<"ctrlKey" | "metaKey" | "altKey" | "shiftKey", boolean>> = {},+) => ({+ key: k,+ ctrlKey: false,+ metaKey: false,+ altKey: false,+ shiftKey: false,+ ...mods,+});++describe("command palette shortcut", () => {+ it("is Ctrl+P off macOS and Cmd+P on it, and nothing else", () => {+ expect(isCommandPaletteShortcut(key("p", { ctrlKey: true }), false)).toBe(true);+ expect(isCommandPaletteShortcut(key("P", { ctrlKey: true }), false)).toBe(true);+ expect(isCommandPaletteShortcut(key("p", { metaKey: true }), false)).toBe(false);+ expect(isCommandPaletteShortcut(key("p", { metaKey: true }), true)).toBe(true);+ expect(isCommandPaletteShortcut(key("p", { ctrlKey: true }), true)).toBe(false);+ // The browser's own chords stay the browser's.+ expect(isCommandPaletteShortcut(key("P", { ctrlKey: true, shiftKey: true }), false)).toBe(+ false,+ );+ expect(isCommandPaletteShortcut(key("p", { ctrlKey: true, altKey: true }), false)).toBe(false);+ expect(isCommandPaletteShortcut(key("o", { ctrlKey: true }), false)).toBe(false);+ });+});++describe("command palette filter", () => {+ const actions = [+ { id: "history", label: "Harness history", keywords: ["version", "hmr"] },+ { id: "reload", label: "Reload page" },+ ];+ it("lists everything for an empty query, in registration order", () => {+ expect(filterPaletteActions(actions, " ").map((a) => a.id)).toEqual(["history", "reload"]);+ });+ it("matches every token, case-insensitively, against the label and the keywords", () => {+ expect(filterPaletteActions(actions, "HIST").map((a) => a.id)).toEqual(["history"]);+ expect(filterPaletteActions(actions, "harness hist").map((a) => a.id)).toEqual(["history"]);+ expect(filterPaletteActions(actions, "hmr").map((a) => a.id)).toEqual(["history"]);+ expect(filterPaletteActions(actions, "page harness")).toEqual([]);+ });+});diff --git a/packages/web/test/modal-focus.test.ts b/packages/web/test/modal-focus.test.tsindex b79ce02f..5fe3df80 100644--- a/packages/web/test/modal-focus.test.ts+++ b/packages/web/test/modal-focus.test.ts@@ -1,7 +1,9 @@/*** Focus behaviour of the Modal primitive (src/components/ui/modal.tsx), which every dialog in* the app inherits: focus enters the panel on open, Tab and Shift+Tab cycle inside it, and- * focus returns to the trigger on close.+ * focus returns to the trigger on close. The wiring lives in `useDialogLayer`, which the+ * command palette and the harness history overlay share with Modal, so what is pinned here+ * holds for those two as well.** `nextFocusIndex` is the arithmetic and is exercised directly. The wiring around it cannot* be: this suite is `environment: "node"` with no jsdom, and Modal renders throughdiff --git a/scripts/deploy.mjs b/scripts/deploy.mjsindex 00747e82..72eed894 100644--- a/scripts/deploy.mjs+++ b/scripts/deploy.mjs@@ -64,6 +64,7 @@ function usage(problem) {console.error(`${problem}\n\n` +"Usage: PENGUIN_ADMIN_PASSWORD=… node scripts/deploy.mjs <port|url> [--skip-web-build]\n" ++ " PENGUIN_API_TOKEN=$(cat <root>/api-token) node scripts/deploy.mjs <port|url>\n" +" <port> a port on this machine (an ssh -L tunnel to the target runtime, or a local server)\n" +" <url> a full origin, when the target is not reached over loopback\n",);@@ -74,8 +75,15 @@ const args = process.argv.slice(2);const skipWebBuild = args.includes("--skip-web-build");const target = args.find((a) => !a.startsWith("--"));if (target === undefined) usage("[deploy] no target given.");+// Two credentials, either one: the admin password (exchanged for a cookie), or the+// runtime's own local API token (`<root>/api-token`, admin-equivalent — see+// server/src/auth/api-token.ts), sent as a Bearer. A local push needs no password.const ADMIN_PASSWORD = process.env.PENGUIN_ADMIN_PASSWORD;-if (!ADMIN_PASSWORD) usage("[deploy] PENGUIN_ADMIN_PASSWORD is not set.");+const API_TOKEN = process.env.PENGUIN_API_TOKEN;+if (!ADMIN_PASSWORD && !API_TOKEN)+ usage(+ "[deploy] set PENGUIN_ADMIN_PASSWORD or PENGUIN_API_TOKEN (the runtime's <root>/api-token).",+ );/** A bare port means this machine's loopback (typically an ssh -L tunnel to the real target). */const baseUrl = /^\d+$/.test(target) ? `http://127.0.0.1:${target}` : target.replace(/\/+$/, "");@@ -124,6 +132,12 @@ function request(urlStr, { method = "GET", headers = {}, body } = {}) {});}+/** The request headers that authenticate as admin: a Bearer token, or a cookie from a password login. */+async function authHeaders() {+ if (API_TOKEN) return { authorization: `Bearer ${API_TOKEN}` };+ return { cookie: await login() };+}+/** Signs in as `admin` and returns the session cookie. */async function login() {const res = await request(`${baseUrl}/api/auth/login`, {@@ -279,7 +293,7 @@ async function main() {const assets = await readNativeAssets();const source = pushSource();- const cookie = await login();+ const auth = await authHeaders();const platform = await fsp.readFile(PLATFORM_BUNDLE);const cli = await fsp.readFile(CLI_BUNDLE);const mapValues = (o, f) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)]));@@ -301,7 +315,7 @@ async function main() {});const probe = await request(`${baseUrl}/api/hmr/assets/probe`, {method: "POST",- headers: { "content-type": "application/json", cookie },+ headers: { "content-type": "application/json", ...auth },body: JSON.stringify({ hashes: [...blobs.keys()] }),});if (probe.status === 200) {@@ -311,7 +325,7 @@ async function main() {if (bytes === undefined) continue;const put = await request(`${baseUrl}/api/hmr/blobs/${sha}`, {method: "PUT",- headers: { "content-type": "application/octet-stream", cookie },+ headers: { "content-type": "application/octet-stream", ...auth },body: bytes,});if (put.status !== 200) {@@ -333,7 +347,7 @@ async function main() {const started = Date.now();const res = await request(`${baseUrl}/api/hmr/upgrade`, {method: "POST",- headers: { "content-type": "application/gzip", cookie },+ headers: { "content-type": "application/gzip", ...auth },body: gz,});const seconds = ((Date.now() - started) / 1000).toFixed(1);