A local-first multi-agent app development platform, built on PenguinHarness
feat(desktop): --dev runs an installed build as a second, isolated instance (#544)
Myriad-Dreamin3d50055a93b6
diff --git a/.agents/skills/penguin-harness-manual-test/SKILL.md b/.agents/skills/penguin-harness-manual-test/SKILL.mdindex f3f8d6fe..3b22f0a5 100644--- a/.agents/skills/penguin-harness-manual-test/SKILL.md+++ b/.agents/skills/penguin-harness-manual-test/SKILL.md@@ -14,6 +14,7 @@ workspace deps); `pnpm desktop` runs a full `pnpm -r build`, so it is slow to st| --- | --- | --- || `pnpm dev` | http://localhost:7365 | `~/.penguin/dev-data` || `pnpm desktop` | its own window | `~/.penguin/dev-data` |+| installed app, launched with `--dev` | its own window | `~/.penguin/dev-data` || `pnpm dev:landing` | http://localhost:7366 | none (static) || `pnpm dev:docs` | http://localhost:7367 | none (static) |diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex c19f22b5..b21b3417 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -88,9 +88,23 @@ step further: an unpackaged run takes a dev-suffixed app identity (`PenguinHarnewith its own userData directory, single-instance lock, and sticky port, and defaults to`~/.penguin/dev-data` even when launched without the env var(`pnpm --dir packages/desktop start`) — so it runs side by side with an installed release-build, with neither instance seeing the other. Every unpackaged launch prints which pair+build, with neither instance seeing the other. Every dev-profile launch prints which pairit picked: `[shell] dev instance '<name>' on data root <root>`.+That dev profile is a switch, not a property of being unpackaged: an installed release+build launched with `--dev` (a second shortcut whose target ends in `--dev`, or+`PenguinHarness.exe --dev`) takes the same dev identity and `~/.penguin/dev-data`, so one+installation runs twice side by side — the release instance on your real data and a+second one on a scratch root — without a checkout. It runs the release's own code, so it+is a way to try the app against separate data, not a way to see uncommitted changes. A+`--dev` instance does not update itself and does not repair the `penguin` command link;+both belong to the one installation the two instances share, and the release instance+does them. The profile also reaches other machines: the shell passes it to its server as+`PENGUIN_PROFILE`, and the Machines page then works with the machine's installation for+that profile — `~/.penguin-dev` on port 7371 for dev, beside the release one — so a dev+instance never touches the release server someone is using there+(`packages/server/src/machines/layout.ts`).+Two one-time moves came with that split. A bare `pnpm --dir packages/desktop start` usedto run on `~/.penguin/data` (the release/CLI root) and now runs on `~/.penguin/dev-data`,so sessions made that way are no longer in the window — run it withdiff --git a/changelog/unreleased/2026-08-29-desktop-dev-profile.md b/changelog/unreleased/2026-08-29-desktop-dev-profile.mdnew file mode 100644index 00000000..4663738b--- /dev/null+++ b/changelog/unreleased/2026-08-29-desktop-dev-profile.md@@ -0,0 +1,43 @@+# Run an installed desktop build as a second, isolated instance with `--dev`++- **Date:** 2026-08-29+- **Type:** feature+- **Scope:** `desktop`, `server`, `core`, `docs`+- **PR:** [#544](https://github.com/Prism-Shadow/penguin-harness/pull/544)+- **Breaking:** yes — machine records in a dev-profile data root describe the release installation on those machines and are not converted++[中文版](2026-08-29-desktop-dev-profile.zh.md)++The desktop shell's dev isolation — the `PenguinHarness-Dev` identity with its own userData directory, single-instance lock and sticky port, and the `~/.penguin/dev-data` default data root — became a **profile** selected by a command-line switch rather than a side effect of running unpackaged. An installed release build launched with `--dev` takes that profile, so the same installation runs twice side by side: the release instance on `~/.penguin/data`, and a second one on the dev root, with neither seeing the other. An unpackaged run (`pnpm desktop`) still defaults to the dev profile, and `PENGUIN_HOME` still overrides the data root in either profile.++## Details++- `--dev` is matched exactly on the process arguments; `--dev=…` and `--dev-tools` do not select it. On Windows a second shortcut whose target ends in `--dev` is the intended way to launch it.+- A `--dev` instance runs the installed release's own code. It is a way to use the app against separate data without a source checkout, not a way to run uncommitted changes.+- The updater stands down on the dev profile (`unsupported`, reason `dev`) whether or not the build is packaged: the installation it would replace is the release instance's, possibly running beside it.+- The per-launch repair of the bundled `penguin` command link runs only on the release profile, so the shared installation has one owner for it.+- The `[shell] dev instance '<name>' on data root <root>` startup line prints for every dev-profile launch, packaged or not.+- The dev AppUserModelID has no installed shortcut carrying it, so Windows toasts from a `--dev` instance may not render; the release instance is unaffected.++## Machines++The profile holds on every machine the instance reaches. The shell hands it to its server as `PENGUIN_PROFILE` (the `pnpm dev:server` and `pnpm penguin` scripts set it too), and the Machines page installs to, probes, starts, stops and connects to the machine's installation for that profile: release at `~/.penguin` with its data at `~/.penguin/data` on port 7364; dev at `~/.penguin-dev` with `~/.penguin-dev/data` on port 7371 (`DEFAULT_DEV_SERVER_PORT`). A dev instance therefore never restarts the release server a person is using on that machine, and the two profiles keep separate Agents, Sessions and pushed versions on both ends. Every remote command names its program directory and data root explicitly (`PENGUIN_INSTALL_DIR`, `PENGUIN_HOME`) rather than relying on the far side's defaults.++- The profile travels with every remote command as `PENGUIN_PROFILE`, next to `PENGUIN_HOME`, so a server started on a machine reaches further machines in the same profile it was started in.+- The `penguin` command a person types on that machine stays with the release installation. A dev-profile install runs the installer with `--no-modify-path` (`-NoModifyPath` for `install.ps1`), a new installer flag that leaves `~/.local/bin/penguin` and the Windows user Path untouched.+- The wait for a remote start ends as soon as the launched process is gone, with the far side's log as the failure, rather than running out its 30 seconds. The port recorded after a start is the one the machine reports serving on.+- The "Install 'penguin' Command…" menu item is offered on the release profile only, like the per-launch repair of that link.++## Compatibility++Release-profile data roots are unaffected: their machine records were written under the layout they are still read with.++A **dev-profile** data root (`~/.penguin/dev-data`, as used by `pnpm dev`, `pnpm desktop` or an earlier `--dev` build) holds machine records written when every instance reached `~/.penguin`. They are not converted, and nothing reads them leniently: a recorded version is one the dev installation there does not have, and a remembered port is the release server's. Connecting from such a record fails with the machine's own words, or starts the dev server on the port the release server there expects to come back to.++Before reaching a machine from a dev-profile instance, clear what the records remember, with the instance stopped:++```sh+sqlite3 ~/.penguin/dev-data/web.db "UPDATE machines SET version = NULL, installed_at = NULL, remote_port = NULL;"+```++Then install from the dev instance. Nothing on the machine has to be removed, and the release installation there is left as it is.diff --git a/changelog/unreleased/2026-08-29-desktop-dev-profile.zh.md b/changelog/unreleased/2026-08-29-desktop-dev-profile.zh.mdnew file mode 100644index 00000000..5d127ee6--- /dev/null+++ b/changelog/unreleased/2026-08-29-desktop-dev-profile.zh.md@@ -0,0 +1,43 @@+# 用 `--dev` 把已安装的桌面版作为第二个隔离实例启动++- **Date:** 2026-08-29+- **Type:** feature+- **Scope:** `desktop`, `server`, `core`, `docs`+- **PR:** [#544](https://github.com/Prism-Shadow/penguin-harness/pull/544)+- **Breaking:** yes — dev profile 数据根里的机器记录描述的是那些机器上的 release 安装,不做转换++[English](2026-08-29-desktop-dev-profile.md)++桌面壳的 dev 隔离——`PenguinHarness-Dev` 身份及其独立的 userData 目录、单实例锁和记忆端口,以及默认的 `~/.penguin/dev-data` 数据根——改为由命令行开关选择的 **profile**,不再是"未打包运行"的副作用。已安装的 release 版加 `--dev` 启动即取该 profile,于是同一份安装可以并排跑两个实例:release 实例在 `~/.penguin/data`,第二个在 dev 根上,互不可见。未打包运行(`pnpm desktop`)仍默认 dev profile;`PENGUIN_HOME` 在两个 profile 下都仍然覆盖数据根。++## 细节++- `--dev` 按进程参数精确匹配;`--dev=…` 和 `--dev-tools` 都不算。Windows 上推荐的启动方式是复制一个快捷方式,目标末尾加 `--dev`。+- `--dev` 实例运行的是已安装 release 自身的代码。它用于在没有源码的情况下对着另一套数据使用应用,不是用来跑未提交修改的。+- dev profile 下更新器一律停用(`unsupported`,原因 `dev`),无论是否打包:它要替换的安装属于 release 实例,而后者可能正在旁边运行。+- 每次启动对捆绑 `penguin` 命令链接的修复只在 release profile 上进行,共用的安装因此只有一个 owner。+- `[shell] dev instance '<name>' on data root <root>` 启动行对每个 dev profile 启动都会打印,打包与否无关。+- dev 的 AppUserModelID 没有对应的已安装快捷方式,所以 `--dev` 实例的 Windows 通知可能不渲染;release 实例不受影响。++## 机器++profile 在实例触及的每台机器上都成立。壳以 `PENGUIN_PROFILE` 把它交给自己的 server(`pnpm dev:server` 和 `pnpm penguin` 脚本也会设置),Machines 页面安装、探测、启动、停止和连接的都是那台机器上该 profile 的安装:release 在 `~/.penguin`,数据在 `~/.penguin/data`,端口 7364;dev 在 `~/.penguin-dev`,数据在 `~/.penguin-dev/data`,端口 7371(`DEFAULT_DEV_SERVER_PORT`)。因此 dev 实例永远不会重启那台机器上别人正在用的 release server,两个 profile 在两端都各自保有 Agent、Session 和推送版本。每条远程命令都显式指明程序目录和数据根(`PENGUIN_INSTALL_DIR`、`PENGUIN_HOME`),不依赖远端的默认值。++- profile 以 `PENGUIN_PROFILE` 随每条远程命令一起传递,与 `PENGUIN_HOME` 并列,因此在某台机器上启动的 server 再去触及其他机器时,仍处于它被启动时的那个 profile。+- 那台机器上用户键入的 `penguin` 命令始终归 release 安装所有。dev profile 的安装以 `--no-modify-path`(`install.ps1` 为 `-NoModifyPath`)运行安装脚本;这是安装脚本新增的参数,不改动 `~/.local/bin/penguin`,也不改动 Windows 的用户 Path。+- 对远程启动的等待在被启动的进程退出后随即结束,并以对端日志作为失败原因,不再等满 30 秒。启动后记录的端口以那台机器自己报告的为准。+- 「Install 'penguin' Command…」菜单项只在 release profile 下提供,与每次启动时对该链接的修复一致。++## 兼容性++release profile 的数据根不受影响:其中的机器记录写下时的布局,就是现在读取它们的布局。++**dev profile** 的数据根(`~/.penguin/dev-data`,由 `pnpm dev`、`pnpm desktop` 或更早的 `--dev` 构建使用)里的机器记录,写于所有实例都触及 `~/.penguin` 的时候。这些记录不做转换,也没有任何宽容读取:记录的版本是那台机器的 dev 安装并不具备的版本,记住的端口是 release server 的端口。从这样的记录发起连接,要么带着那台机器自己的报错失败,要么把 dev server 启动在那里的 release server 回来时要用的端口上。++从 dev profile 的实例触及机器之前,先停掉该实例,清掉记录里记住的内容:++```sh+sqlite3 ~/.penguin/dev-data/web.db "UPDATE machines SET version = NULL, installed_at = NULL, remote_port = NULL;"+```++然后从 dev 实例安装一次。那台机器上无须删除任何东西,那里的 release 安装保持原样。diff --git a/install.ps1 b/install.ps1index f996d218..139d3628 100644--- a/install.ps1+++ b/install.ps1@@ -12,6 +12,8 @@# $env:PENGUIN_DOWNLOAD_SPEED_PROBE = "0" disable same-version OSS/GitHub probe timing in auto mode# $env:PENGUIN_DOWNLOAD_BASE_URL = "https://..." exact online asset directory selected by the stable forwarder# $env:PENGUIN_DOWNLOAD_FALLBACK_BASE_URL = "https://..." fallback for PENGUIN_DOWNLOAD_BASE_URL+# -NoModifyPath do not add <install>\bin to the user Path; for a second installation+# beside the one the `penguin` command belongs to## Each Release attaches exactly one Windows artifact: penguin-win32-x64.zip, a shallow installer# bundle holding install.cmd, this script, the program payload (payload.zip) and the payload's@@ -32,7 +34,8 @@param([string]$Version = "",[string]$InstallDir = "",- [string]$ArchivePath = ""+ [string]$ArchivePath = "",+ [switch]$NoModifyPath)$ErrorActionPreference = "Stop"@@ -672,9 +675,11 @@ try {# (unexpanded) value, append to it, and write it back with its original value kind.# The registry only exists on Windows; skip the block elsewhere (functional test runs# of this script on pwsh/Linux — where the old API was a silent no-op anyway). ---+# -NoModifyPath skips it: `penguin` resolves to the first bin directory on the+# Path, and a second installation's entry there would answer whenever the first is absent.$BinDir = Join-Path $InstallDir "bin"$PathUpdateMessage = ""-if ($env:OS -eq "Windows_NT") {+if (-not $NoModifyPath -and $env:OS -eq "Windows_NT") {$EnvKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment", $true)if ($null -eq $EnvKey) { $EnvKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey("Environment") }try {@@ -714,7 +719,12 @@ public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint M}}# Make `penguin` work in this session too.-if (($env:Path -split ";") -notcontains $BinDir) { $env:Path = "$env:Path;$BinDir" }+$PenguinCommand = "penguin"+if (-not $NoModifyPath) {+ if (($env:Path -split ";") -notcontains $BinDir) { $env:Path = "$env:Path;$BinDir" }+} else {+ $PenguinCommand = "& `"$(Join-Path $BinDir "penguin.cmd")`""+}Write-Host ""Write-Host "PenguinHarness $InstalledVersion installed to $InstallDir"@@ -724,6 +734,6 @@ if ($PathUpdateMessage) {}Write-Host ""Write-Host "Get started:"-Write-Host " penguin --help # all commands"-Write-Host " penguin web # start the Web UI at http://127.0.0.1:7364 (a first-login link is printed on first start)"-Write-Host " penguin server # headless server (PORT / HOST to override)"+Write-Host " $PenguinCommand --help # all commands"+Write-Host " $PenguinCommand web # start the Web UI at http://127.0.0.1:7364 (a first-login link is printed on first start)"+Write-Host " $PenguinCommand server # headless server (PORT / HOST to override)"diff --git a/install.sh b/install.shindex 7c374321..862fd1a5 100644--- a/install.sh+++ b/install.sh@@ -14,6 +14,8 @@# PENGUIN_DOWNLOAD_BASE_URL=<url> exact online asset directory selected by the stable forwarder# PENGUIN_DOWNLOAD_FALLBACK_BASE_URL=<url> fallback for PENGUIN_DOWNLOAD_BASE_URL# --universal install the universal package (no bundled Node runtime; needs system Node >= 24)+# --no-modify-path do not put `penguin` on PATH (no ~/.local/bin/penguin symlink); for a second+# installation beside the one the command belongs to## Each Release attaches exactly one artifact per target: penguin-<target>.tar.gz, a shallow# installer bundle holding this script, the program payload (payload.tar.gz) and the payload's@@ -37,6 +39,7 @@ GITHUB_LATEST_BASE="$REPO/releases/latest/download"VERSION="${PENGUIN_VERSION:-}"INSTALL_DIR="${PENGUIN_INSTALL_DIR:-$HOME/.penguin}"BIN_DIR="$HOME/.local/bin"+MODIFY_PATH=1UNIVERSAL=0ARCHIVE="${PENGUIN_ARCHIVE:-}"SOURCE_MODE="${PENGUIN_DOWNLOAD_SOURCE:-auto}"@@ -119,6 +122,10 @@ while [ $# -gt 0 ]; doUNIVERSAL=1shift;;+ --no-modify-path)+ MODIFY_PATH=0+ shift+ ;;--archive)[ $# -ge 2 ] || fail "--archive requires a path to a Release archive"ARCHIVE="$2"@@ -757,14 +764,21 @@ OLD_DIR=""rm -rf "$STAGING"STAGING=""-# --- Symlink into ~/.local/bin and check PATH only after the install is known to work. ----mkdir -p "$BIN_DIR"-ln -sf "$INSTALL_DIR/bin/penguin" "$BIN_DIR/penguin"+# --- Symlink into ~/.local/bin and check PATH only after the install is known to work.+# --no-modify-path skips both: ~/.local/bin/penguin is one name, and a second+# installation that took it would hand its program to whoever types `penguin`. ---PATH_MISSING=0-case ":$PATH:" in- *":$BIN_DIR:"*) ;;- *) PATH_MISSING=1 ;;-esac+PENGUIN_COMMAND="penguin"+if [ "$MODIFY_PATH" -eq 1 ]; then+ mkdir -p "$BIN_DIR"+ ln -sf "$INSTALL_DIR/bin/penguin" "$BIN_DIR/penguin"+ case ":$PATH:" in+ *":$BIN_DIR:"*) ;;+ *) PATH_MISSING=1 ;;+ esac+else+ PENGUIN_COMMAND="$INSTALL_DIR/bin/penguin"+fiecho ""echo "PenguinHarness $installed_version installed to $INSTALL_DIR"@@ -780,6 +794,6 @@ if [ "$PATH_MISSING" -eq 1 ]; thenfiecho ""echo "Get started:"-echo " penguin --help # all commands"-echo " penguin web # start the Web UI at http://127.0.0.1:7364 (a first-login link is printed on first start)"-echo " penguin server # headless server (PORT / HOST to override)"+echo " $PENGUIN_COMMAND --help # all commands"+echo " $PENGUIN_COMMAND web # start the Web UI at http://127.0.0.1:7364 (a first-login link is printed on first start)"+echo " $PENGUIN_COMMAND server # headless server (PORT / HOST to override)"diff --git a/package.json b/package.jsonindex 20244809..ef4dd075 100644--- a/package.json+++ b/package.json@@ -18,7 +18,7 @@"test:e2e": "pnpm --filter @prismshadow/penguin-core test:e2e","build": "pnpm -r build && pnpm link:cli","link:cli": "pnpm --dir packages/cli link --global || echo '[link:cli] pnpm global directory not configured; skipping the global penguin link (run pnpm setup once first)'",- "penguin": "node scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data-cli PORT=7369 -- tsx packages/cli/src/penguin.ts",+ "penguin": "node scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data-cli PENGUIN_PROFILE=dev PORT=7369 -- tsx packages/cli/src/penguin.ts","dev": "concurrently -n server,web -c cyan,magenta \"pnpm dev:server\" \"pnpm dev:web\"","dev:server": "pnpm --filter @prismshadow/penguin-server dev","dev:web": "node scripts/dev-prebuild.mjs && pnpm --filter @prismshadow/penguin-web dev",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 5f3f91a8..db1a60ef 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -20,7 +20,7 @@"typecheck": "tsc --noEmit -p tsconfig.json","test": "vitest run --passWithNoTests","build": "tsup",- "penguin": "node ../../scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data-cli PORT=7369 -- tsx src/penguin.ts"+ "penguin": "node ../../scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data-cli PENGUIN_PROFILE=dev PORT=7369 -- tsx src/penguin.ts"},"dependencies": {"@modelcontextprotocol/client": "^2.0.0",diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 1577606e..66cf6cb8 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -25,7 +25,7 @@ export * from "./interfaces/index.js";export type * from "./version-info.js";// Only the default server port leaves internal: the CLI / server default-port source of truth.-export { DEFAULT_SERVER_PORT } from "./internal/ports.js";+export { DEFAULT_DEV_SERVER_PORT, DEFAULT_SERVER_PORT } from "./internal/ports.js";export { SERVER_RESTART_EXIT_CODE } from "./internal/server-lifecycle.js";// Submodulesdiff --git a/packages/core/src/internal/ports.ts b/packages/core/src/internal/ports.tsindex 7ce35586..ae099b13 100644--- a/packages/core/src/internal/ports.ts+++ b/packages/core/src/internal/ports.ts@@ -19,10 +19,12 @@* | 7367 | `pnpm dev:docs` (Vite) | none (static) | `packages/docs/vite.config.ts` |* | 7368 | `pnpm dev:server` (dev backend) | `~/.penguin/dev-data` | `packages/server/package.json` `dev` |* | 7369 | `pnpm penguin web` (dev CLI) | `~/.penguin/dev-data-cli` | the root and cli `penguin` scripts |+ * | 7371 | a machine's dev-profile server | `~/.penguin-dev/data` there | `DEFAULT_DEV_SERVER_PORT` below |** The desktop app binds no fixed port in either form (PORT=0 with a per-instance sticky- * preference); its release form shares `~/.penguin/data` with the CLI by design and its- * dev form takes `~/.penguin/dev-data` (see `packages/desktop/src/app-identity.ts`). The+ * preference); its release profile shares `~/.penguin/data` with the CLI by design and its+ * dev profile — an unpackaged run, or any build launched with `--dev` — takes+ * `~/.penguin/dev-data` (see `packages/desktop/src/app-identity.ts`). The* web e2e harness runs on 8930/8931 against a throwaway root (`packages/web/e2e/run.sh`).** The development backend deliberately does **not** share 7364 with an installed one: the@@ -48,3 +50,13 @@/** Default main server / Web UI port; deliberately avoids common defaults like 3000/8080. */export const DEFAULT_SERVER_PORT = 7364;++/**+ * Where a dev-profile instance starts the server it installs on another machine+ * (`packages/server/src/machines/layout.ts`). Its own number because the release-profile+ * server on that machine holds 7364, and the forward's local port must equal the remote+ * one for Workspace previews to resolve — so the two profiles cannot share a number on+ * either end. Not 7370: the design repository's reading site (`site/`) serves there, on the+ * same developer box whose forward to a machine needs this number free locally.+ */+export const DEFAULT_DEV_SERVER_PORT = 7371;diff --git a/packages/desktop/src/app-identity.ts b/packages/desktop/src/app-identity.tsindex 56028f48..224299b6 100644--- a/packages/desktop/src/app-identity.ts+++ b/packages/desktop/src/app-identity.ts@@ -2,8 +2,12 @@* Per-form app identity — pure, no Electron imports, so it unit-tests under plain* vitest.*- * A dev (unpackaged) shell must be able to run while an installed release build is- * running (#292). Electron keys everything that must stay per-instance on the app+ * A dev shell must be able to run while an installed release build is running (#292).+ * "Dev" is a *profile* — an instance identity plus its default data root — and not the+ * same thing as being unpackaged: an unpackaged run defaults to it, and a packaged+ * build opts into it with `--dev`, so one installed exe can also run as a second,+ * isolated instance. What stays keyed on `app.isPackaged` is capability, not identity:+ * whether there is an installed artifact to update or a bundled CLI to install. Electron keys everything that must stay per-instance on the app* name: the userData directory holds the Chromium profile and this shell's state* files (server-port, preferred-port, cli-install-offered), and the single-instance* lock is derived from it — under a shared name a second launch does not open a@@ -35,9 +39,26 @@ export interface AppIdentity {appUserModelId: string;}-/** The identity for this form: release, or dev-suffixed so both can run side by side. */-export function appIdentity(isPackaged: boolean): AppIdentity {- return isPackaged+/** Which instance this process is: the installed app, or the isolated dev instance. */+export type Profile = "release" | "dev";++/** The command-line switch that puts a packaged build on the dev profile. */+export const DEV_SWITCH = "--dev";++/**+ * The profile rule: `--dev` on the command line always selects the dev profile; without+ * it an unpackaged run is dev (the repo's `pnpm desktop`) and a packaged one is release.+ * Read from `process.argv` rather than `app.commandLine` so it can run before anything+ * touches Electron's cached paths (see the tripwire above).+ */+export function resolveProfile(opts: { argv: readonly string[]; isPackaged: boolean }): Profile {+ if (opts.argv.includes(DEV_SWITCH)) return "dev";+ return opts.isPackaged ? "release" : "dev";+}++/** The identity for this profile: release, or dev-suffixed so both can run side by side. */+export function appIdentity(profile: Profile): AppIdentity {+ return profile === "release"? { name: "PenguinHarness", appUserModelId: "com.prismshadow.penguinharness" }: { name: "PenguinHarness-Dev", appUserModelId: "com.prismshadow.penguinharness.dev" };}@@ -56,9 +77,10 @@ export function devDataRoot(homedir: string): string {/*** This form's data root, i.e. the precedence rule itself: an explicit `PENGUIN_HOME`- * always wins; without one a release build shares the CLI's root by design, so a desktop- * install and the CLI see the same Agents, Sessions and usage, while a dev run takes the- * repo's dev root instead of attaching to — or writing into — the release install's data.+ * always wins; without one the release profile shares the CLI's root by design, so a+ * desktop install and the CLI see the same Agents, Sessions and usage, while the dev+ * profile takes the repo's dev root instead of attaching to — or writing into — the+ * release install's data.** `releaseRoot` stays a thunk (core's `resolveRoot`) so core remains the single* definition point of `~/.penguin/data`; it is only called when there is no explicit@@ -67,9 +89,11 @@ export function devDataRoot(homedir: string): string {*/export function desktopDataRoot(opts: {envHome: string | undefined;- isPackaged: boolean;+ profile: Profile;homedir: string;releaseRoot: () => string;}): string {- return opts.envHome ?? (opts.isPackaged ? opts.releaseRoot() : devDataRoot(opts.homedir));+ return (+ opts.envHome ?? (opts.profile === "release" ? opts.releaseRoot() : devDataRoot(opts.homedir))+ );}diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex a7ec57a6..ae8253da 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -25,9 +25,12 @@* stop). Settings › Appearance turns the icon off and on, reaching the shell over the same* utilityProcess relay the client updater uses.*- * Dev isolation: an unpackaged run takes a dev-suffixed identity (own userData, and with- * it the single-instance lock and sticky port) and defaults to the ~/.penguin/dev-data- * root, so it runs beside an installed release build (see app-identity.ts).+ * Dev isolation: the dev profile — an unpackaged run, or any build launched with `--dev`+ * — takes a dev-suffixed identity (own userData, and with it the single-instance lock and+ * sticky port) and defaults to the ~/.penguin/dev-data root, so it runs beside an+ * installed release build (see app-identity.ts). Updating and the per-launch CLI link+ * repair stay with the release profile: both touch the one installation the two+ * instances share.** Smoke hook (PENGUIN_DESKTOP_SMOKE=1): after the first load settles, print a* `DESKTOP-SMOKE-RESULT {json}` line (+ screenshot when PENGUIN_DESKTOP_SMOKE_SHOT is@@ -40,7 +43,7 @@ import { app, BrowserWindow, dialog, shell } from "electron";import type { WindowOpenHandlerResponse } from "electron";import { resolveRoot } from "@prismshadow/penguin-core";import { liveServerLock } from "@prismshadow/penguin-server/lock";-import { appIdentity, desktopDataRoot } from "./app-identity.js";+import { appIdentity, desktopDataRoot, resolveProfile } from "./app-identity.js";import { embeddedCliEntry } from "./launcher.js";import { webDistEntry, webDistFor } from "./web-dist.js";import { resolveTrayIcon, resolveWindowIcon } from "./app-icon.js";@@ -75,10 +78,11 @@ import {} from "./util.js";// Identity first: the name decides the userData directory, which also keys the-// single-instance lock requested below — a dev (unpackaged) run takes a dev-suffixed-// identity so it runs beside an installed release build instead of quitting into its-// window (#292; see app-identity.ts).-const identity = appIdentity(app.isPackaged);+// single-instance lock requested below — the dev profile takes a dev-suffixed identity+// so it runs beside an installed release build instead of quitting into its window+// (#292; see app-identity.ts).+const profile = resolveProfile({ argv: process.argv, isPackaged: app.isPackaged });+const identity = appIdentity(profile);app.setName(identity.name);// Windows toasts (the web app's task-completion notifications) need the AppUserModelID// of the installed shortcuts; electron-builder stamps them with the appId. Keep the@@ -403,6 +407,7 @@ async function startServerAndWindow(dataRoot: string): Promise<void> {appPath: app.getAppPath(),env: process.env,}),+ profile,portFile: path.join(app.getPath("userData"), "server-port"),preferredPortFile: path.join(app.getPath("userData"), "preferred-port"),log: (chunk) => process.stdout.write(`[server] ${chunk}`),@@ -445,15 +450,15 @@ async function handleServerExit(dataRoot: string, code: number): Promise<void> {}async function boot(): Promise<void> {- // Explicit PENGUIN_HOME wins; otherwise a release build shares the CLI's data root and- // a dev run takes the repo's dev root (the rule, and why, live in app-identity.ts).+ // Explicit PENGUIN_HOME wins; otherwise the release profile shares the CLI's data root+ // and the dev profile takes the repo's dev root (the rule, and why, live in app-identity.ts).const dataRoot = desktopDataRoot({envHome: process.env.PENGUIN_HOME,- isPackaged: app.isPackaged,+ profile,homedir: os.homedir(),releaseRoot: resolveRoot,});- if (!app.isPackaged) {+ if (profile === "dev") {process.stdout.write(`[shell] dev instance '${app.name}' on data root ${dataRoot}\n`);}const existing = await liveServerLock(dataRoot);@@ -513,8 +518,11 @@ if (!app.requestSingleInstanceLock()) {log: (line) => process.stdout.write(`[shell] ${line}\n`),});// Standard menu plus native desktop-only actions; the window gets no IPC channel.+ // The install item is the release profile's, like the per-launch repair below: the+ // `penguin` command has one owner, and a `--dev` instance of the same install would+ // rewrite it and record having done so in its own userData.installAppMenu({- includeCliInstall: currentCliInstallKind() !== null,+ includeCliInstall: profile === "release" && currentCliInstallKind() !== null,onInstallCli: () => void installCliCommand(win),});// Before boot, and whatever the window is doing: the icon is there for as long as the@@ -530,9 +538,13 @@ if (!app.requestSingleInstanceLock()) {initUpdater(() => win);await boot();// Install or repair the bundled 'penguin' command. Runs every launch: that is what- // carries it across an update and repairs a link a moved app left dangling. Skipped+ // carries it across an update and repairs a link a moved app left dangling. Only the+ // release profile does it — a `--dev` instance of the same install has nothing of+ // its own to link, and one owner keeps the link from being rewritten twice. Skipped// in smoke mode — the macOS administrator prompt would hang the automated run.- if (process.env.PENGUIN_DESKTOP_SMOKE !== "1") await ensureCliCommand();+ if (profile === "release" && process.env.PENGUIN_DESKTOP_SMOKE !== "1") {+ await ensureCliCommand();+ }})().catch((err) => fatal(`${app.name} failed to start.`, err)),);}diff --git a/packages/desktop/src/server-process.ts b/packages/desktop/src/server-process.tsindex f6f454c7..81c30a8b 100644--- a/packages/desktop/src/server-process.ts+++ b/packages/desktop/src/server-process.ts@@ -10,6 +10,7 @@ import fs from "node:fs";import path from "node:path";import { app, utilityProcess } from "electron";import type { UtilityProcess } from "electron";+import type { Profile } from "./app-identity.js";import { embeddedCliEntry } from "./launcher.js";import { osProxyEnv } from "./os-proxy.js";import { choosePort, readPreferredPort, rememberPreferredPort } from "./port-memory.js";@@ -105,6 +106,8 @@ async function waitForHttp(origin: string, exited: () => boolean): Promise<void>*/export async function startEmbeddedServer(opts: {dataRoot: string;+ /** Which instance this is; the server reaches other machines' matching installation by it. */+ profile: Profile;/** Pinned web dist (packaged app), or null to leave it to the server's default lookup. */webDist: string | null;/**@@ -130,6 +133,7 @@ export async function startEmbeddedServer(opts: {// The server's "use system HTTP proxy" switch then governs whether they are used....(await osProxyEnv()),PENGUIN_HOME: opts.dataRoot,+ PENGUIN_PROFILE: opts.profile,...(opts.webDist !== null ? { PENGUIN_WEB_DIST: opts.webDist } : {}),...(opts.cliEntry !== null ? { PENGUIN_CLI_ENTRY: opts.cliEntry } : {}),HOST: "127.0.0.1",diff --git a/packages/desktop/src/update-support.ts b/packages/desktop/src/update-support.tsindex f2bd0266..d90e33fc 100644--- a/packages/desktop/src/update-support.ts+++ b/packages/desktop/src/update-support.ts@@ -5,17 +5,23 @@* electron-updater can only replace the forms it installed: the NSIS installer on* Windows, the app bundle on macOS, and an AppImage on Linux. A `.deb` belongs to the* system package manager — silently "updating" around dpkg would leave the two disagreeing- * about what is installed — and a dev run has no installed artifact at all.+ * about what is installed — and a dev run has no installed artifact at all. A packaged+ * build on the dev profile (`--dev`) does have one, but it is the release instance's+ * installation, possibly running beside it; replacing it from here would pull the files+ * out from under that instance, so the dev profile stands down too.*/+import type { Profile } from "./app-identity.js";+export type UpdateSupport ={ supported: true } | { supported: false; reason: "dev" | "linux-not-appimage" };export function updateSupport(opts: {isPackaged: boolean;+ profile: Profile;platform: NodeJS.Platform;env: NodeJS.ProcessEnv;}): UpdateSupport {- if (!opts.isPackaged) return { supported: false, reason: "dev" };+ if (!opts.isPackaged || opts.profile !== "release") return { supported: false, reason: "dev" };// The AppImage runtime exports APPIMAGE with the path of the running image; a deb// install (or an extracted tree) has no such variable, and that is exactly the// distinction electron-updater's Linux path depends on.diff --git a/packages/desktop/src/updater.ts b/packages/desktop/src/updater.tsindex a7d90fef..1610d685 100644--- a/packages/desktop/src/updater.ts+++ b/packages/desktop/src/updater.ts@@ -29,6 +29,7 @@ import type {DesktopUpdateStatus,DesktopUpdaterCommandMessage,} from "@prismshadow/penguin-server/api";+import { resolveProfile } from "./app-identity.js";import { feedUrlOverride, updateSourceConfig, updateSupport } from "./update-support.js";import {feedLabel,@@ -58,6 +59,9 @@ function log(line: string): void {process.stdout.write(`[updater] ${line}\n`);}+// Pure over argv and isPackaged, so resolving it here again costs nothing and keeps the+// menu's enabled state (read before initUpdater) in step with the running instance.+const profile = resolveProfile({ argv: process.argv, isPackaged: app.isPackaged });let manualCheckInFlight = false;let downloadedVersion: string | null = null;let downloadInFlight = false;@@ -241,6 +245,7 @@ export function handleUpdaterCommand(action: DesktopUpdaterCommandMessage["actioif (action === "check") {const support = updateSupport({isPackaged: app.isPackaged,+ profile,platform: process.platform,env: process.env,});@@ -276,8 +281,12 @@ export function handleUpdaterCommand(action: DesktopUpdaterCommandMessage["actio/** Whether the "Check for Updates…" menu item should be enabled at all. */export function updatesAvailableInThisForm(): boolean {- return updateSupport({ isPackaged: app.isPackaged, platform: process.platform, env: process.env })- .supported;+ return updateSupport({+ isPackaged: app.isPackaged,+ profile,+ platform: process.platform,+ env: process.env,+ }).supported;}/**@@ -287,6 +296,7 @@ export function updatesAvailableInThisForm(): boolean {export function initUpdater(getWindow: () => BrowserWindow | null): void {const support = updateSupport({isPackaged: app.isPackaged,+ profile,platform: process.platform,env: process.env,});@@ -498,6 +508,7 @@ export async function checkForUpdatesManually(): Promise<void> {if (!updatesAvailableInThisForm()) {const support = updateSupport({isPackaged: app.isPackaged,+ profile,platform: process.platform,env: process.env,});diff --git a/packages/desktop/test/app-identity.test.ts b/packages/desktop/test/app-identity.test.tsindex 7583e3a8..09d55ede 100644--- a/packages/desktop/test/app-identity.test.ts+++ b/packages/desktop/test/app-identity.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";-import { appIdentity, desktopDataRoot, devDataRoot } from "../src/app-identity.js";+import { appIdentity, desktopDataRoot, devDataRoot, resolveProfile } from "../src/app-identity.js";const builderConfig = fs.readFileSync(fileURLToPath(new URL("../electron-builder.yml", import.meta.url)),@@ -16,24 +16,42 @@ function builderValue(key: string): string {return m[1]!;}+describe("resolveProfile", () => {+ it("an unpackaged run is dev, a packaged one release", () => {+ expect(resolveProfile({ argv: ["electron", "."], isPackaged: false })).toBe("dev");+ expect(resolveProfile({ argv: ["PenguinHarness.exe"], isPackaged: true })).toBe("release");+ });++ it("--dev puts a packaged build on the dev profile", () => {+ // The point of the switch: one installed exe launched twice, once bare and once with+ // --dev, yields two identities and so two instances side by side.+ expect(resolveProfile({ argv: ["PenguinHarness.exe", "--dev"], isPackaged: true })).toBe("dev");+ });++ it("--dev is exact — a prefix or a value-carrying form does not match", () => {+ expect(resolveProfile({ argv: ["x", "--dev-tools"], isPackaged: true })).toBe("release");+ expect(resolveProfile({ argv: ["x", "--dev=1"], isPackaged: true })).toBe("release");+ });+});+describe("appIdentity", () => {it("release identity matches what electron-builder stamps on installed builds", () => {// The AppUserModelID must equal the appId electron-builder writes into the installed// shortcuts (Windows toast routing), and the name must equal productName. This test// is the sync the main.ts comment used to only ask for.- expect(appIdentity(true)).toEqual({+ expect(appIdentity("release")).toEqual({name: builderValue("productName"),appUserModelId: builderValue("appId"),});});it("dev identity is dev-suffixed so a dev run coexists with a release install", () => {- const dev = appIdentity(false);+ const dev = appIdentity("dev");// The name keys the userData directory (Chromium profile, port memory) and the// single-instance lock: sharing it would make a dev launch quit into the release// instance's window.- expect(dev.name).not.toBe(appIdentity(true).name);- expect(dev.appUserModelId).not.toBe(appIdentity(true).appUserModelId);+ expect(dev.name).not.toBe(appIdentity("release").name);+ expect(dev.appUserModelId).not.toBe(appIdentity("release").appUserModelId);expect(dev).toEqual({name: "PenguinHarness-Dev",appUserModelId: "com.prismshadow.penguinharness.dev",@@ -50,8 +68,8 @@ describe("devDataRoot", () => {/*** The precedence rule #292 turns on. These pin the RULE, not the constants: flipping the- * packaged branch, dropping the PENGUIN_HOME precedence, or letting either form fall into- * the other's root has to fail here.+ * release branch, dropping the PENGUIN_HOME precedence, or letting either profile fall+ * into the other's root has to fail here.*/describe("desktopDataRoot", () => {const releaseRoot = path.join("/home/dev", ".penguin", "data");@@ -66,13 +84,13 @@ describe("desktopDataRoot", () => {return fn;}- it("an explicit PENGUIN_HOME wins in both forms", () => {- for (const isPackaged of [true, false]) {+ it("an explicit PENGUIN_HOME wins in both profiles", () => {+ for (const profile of ["release", "dev"] as const) {const release = stubRelease();expect(desktopDataRoot({envHome: "/srv/elsewhere",- isPackaged,+ profile,homedir: "/home/dev",releaseRoot: release,}),@@ -82,12 +100,12 @@ describe("desktopDataRoot", () => {}});- it("a packaged build with no PENGUIN_HOME shares the CLI's root via core's resolver", () => {+ it("the release profile with no PENGUIN_HOME shares the CLI's root via core's resolver", () => {const release = stubRelease();expect(desktopDataRoot({envHome: undefined,- isPackaged: true,+ profile: "release",homedir: "/home/dev",releaseRoot: release,}),@@ -96,11 +114,11 @@ describe("desktopDataRoot", () => {expect(release.calls).toBe(1);});- it("an unpackaged run with no PENGUIN_HOME takes the dev root, never the release one", () => {+ it("the dev profile with no PENGUIN_HOME takes the dev root, never the release one", () => {const release = stubRelease();const root = desktopDataRoot({envHome: undefined,- isPackaged: false,+ profile: "dev",homedir: "/home/dev",releaseRoot: release,});diff --git a/packages/desktop/test/update-support.test.ts b/packages/desktop/test/update-support.test.tsindex fe337c9e..20e929e0 100644--- a/packages/desktop/test/update-support.test.ts+++ b/packages/desktop/test/update-support.test.ts@@ -4,17 +4,23 @@ import { feedUrlOverride, updateSourceConfig, updateSupport } from "../src/updatdescribe("updateSupport", () => {it("supports packaged macOS and Windows builds", () => {for (const platform of ["darwin", "win32"] as const) {- expect(updateSupport({ isPackaged: true, platform, env: {} })).toEqual({ supported: true });+ expect(updateSupport({ isPackaged: true, profile: "release", platform, env: {} })).toEqual({+ supported: true,+ });}});it("supports Linux only when running as an AppImage", () => {const env = { APPIMAGE: "/opt/PenguinHarness.AppImage" };- expect(updateSupport({ isPackaged: true, platform: "linux", env })).toEqual({- supported: true,- });+ expect(updateSupport({ isPackaged: true, profile: "release", platform: "linux", env })).toEqual(+ {+ supported: true,+ },+ );// A deb install has no APPIMAGE: updating around dpkg would desync the two.- expect(updateSupport({ isPackaged: true, platform: "linux", env: {} })).toEqual({+ expect(+ updateSupport({ isPackaged: true, profile: "release", platform: "linux", env: {} }),+ ).toEqual({supported: false,reason: "linux-not-appimage",});@@ -22,9 +28,23 @@ describe("updateSupport", () => {it("never updates a dev run, whatever the platform", () => {expect(- updateSupport({ isPackaged: false, platform: "darwin", env: { APPIMAGE: "/x" } }),+ updateSupport({+ isPackaged: false,+ profile: "dev",+ platform: "darwin",+ env: { APPIMAGE: "/x" },+ }),).toEqual({ supported: false, reason: "dev" });});++ it("never updates a packaged build on the dev profile: the installation is the release instance's", () => {+ for (const platform of ["darwin", "win32"] as const) {+ expect(updateSupport({ isPackaged: true, profile: "dev", platform, env: {} })).toEqual({+ supported: false,+ reason: "dev",+ });+ }+ });});describe("feedUrlOverride", () => {diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.mdindex e76984a4..2be82692 100644--- a/packages/docs/content/quickstart-cli.en.md+++ b/packages/docs/content/quickstart-cli.en.md@@ -164,7 +164,7 @@ The dev entry points (`pnpm penguin`, `pnpm dev`, `pnpm desktop`) default to a s| Item | Details || --- | --- || Install directory | `~/.penguin` by default; override it with the `PENGUIN_INSTALL_DIR` environment variable |-| Command entry | A symlink, `~/.local/bin/penguin`. The script warns if `~/.local/bin` is not on `PATH` |+| Command entry | A symlink, `~/.local/bin/penguin`. The script warns if `~/.local/bin` is not on `PATH`. The `--no-modify-path` flag leaves the link alone, for a second installation beside the one `penguin` belongs to || Version | The `PENGUIN_VERSION=vX.Y.Z` environment variable, or the `--version vX.Y.Z` script flag. The stable entry installs the latest Release by default; a versioned Release installer installs its own tag || Download source | `PENGUIN_DOWNLOAD_SOURCE=auto` (default), `oss` or `github`. `auto` times a probe file and keeps the free GitHub download unless the OSS mirror is clearly faster, and falls back to the same version on the other source. `PENGUIN_DOWNLOAD_SPEED_PROBE=0` skips the measurement || Local archive | `PENGUIN_ARCHIVE=<file>` or `--archive <file>`. Accepts a Release bundle, which verifies itself with its sealed payload checksum, or a payload or legacy program archive with a `<file>.sha256` next to it. A renamed legacy file may use the platform asset's canonical `.sha256` |@@ -178,7 +178,7 @@ Script flags go after `sh -s --`, for example `curl -fsSL https://penguin.ooo/in| Item | Details || --- | --- || Install directory | `%USERPROFILE%\.penguin` by default; override it with the `PENGUIN_INSTALL_DIR` environment variable |-| Command entry | The `bin\penguin.cmd` launcher. There is deliberately no `.ps1` launcher: batch files are exempt from the PowerShell execution policy, so `penguin` works even under the default Restricted policy. The installer adds `%USERPROFILE%\.penguin\bin` to your **user** Path and broadcasts the change. Open a **new terminal window** once; a new tab of an already-running terminal keeps the old Path |+| Command entry | The `bin\penguin.cmd` launcher. There is deliberately no `.ps1` launcher: batch files are exempt from the PowerShell execution policy, so `penguin` works even under the default Restricted policy. The installer adds `%USERPROFILE%\.penguin\bin` to your **user** Path and broadcasts the change. Open a **new terminal window** once; a new tab of an already-running terminal keeps the old Path. The `-NoModifyPath` switch leaves the Path alone, for a second installation beside the one `penguin` belongs to || Version pin | Set `$env:PENGUIN_VERSION = "vX.Y.Z"` before running the installer || Local archive | `$env:PENGUIN_ARCHIVE = "<file>"` or `-ArchivePath <file>`. Accepts the Release bundle, which verifies itself with its sealed payload checksum, or a payload or legacy zip with a `<file>.sha256` next to it. A renamed legacy file may use `penguin-win32-x64.zip.sha256` || Integrity check | Always on. Online downloads are verified against the published `.sha256`, and bundle payloads against the checksum sealed inside the bundle |diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.mdindex f9c15cd9..3350affa 100644--- a/packages/docs/content/quickstart-cli.zh.md+++ b/packages/docs/content/quickstart-cli.zh.md@@ -164,7 +164,7 @@ pnpm install && pnpm build| 项目 | 说明 || --- | --- || 安装目录 | 默认为 `~/.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 |-| 命令入口 | 符号链接 `~/.local/bin/penguin`。如果 `~/.local/bin` 不在 `PATH` 中,脚本会给出提示 |+| 命令入口 | 符号链接 `~/.local/bin/penguin`。如果 `~/.local/bin` 不在 `PATH` 中,脚本会给出提示。脚本参数 `--no-modify-path` 则不改动这个链接,用于在 `penguin` 所属的安装之外再装一份 || 版本 | 环境变量 `PENGUIN_VERSION=vX.Y.Z`,或脚本参数 `--version vX.Y.Z`。稳定入口默认安装最新的 Release,某个版本的 Release 安装器默认安装自身的 tag || 下载来源 | `PENGUIN_DOWNLOAD_SOURCE=auto`(默认)、`oss` 或 `github`。`auto` 会对测速文件计时,除非 OSS 镜像明显更快,否则保持免费的 GitHub 下载,并可回退到另一个来源的同一版本。`PENGUIN_DOWNLOAD_SPEED_PROBE=0` 跳过测速 || 本地压缩包 | `PENGUIN_ARCHIVE=<file>` 或 `--archive <file>`。接受 Release 安装包(凭封入的负载校验值自行校验),或旁边带有 `<file>.sha256` 的负载、旧版程序压缩包。重命名过的旧版文件可以使用平台标准文件名的 `.sha256` |@@ -178,7 +178,7 @@ pnpm install && pnpm build| 项目 | 说明 || --- | --- || 安装目录 | 默认为 `%USERPROFILE%\.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 |-| 命令入口 | 启动器 `bin\penguin.cmd`。特意不提供 `.ps1` 启动器:批处理文件不受 PowerShell 执行策略限制,所以在默认的 Restricted 策略下 `penguin` 也能运行。安装器会把 `%USERPROFILE%\.penguin\bin` 加入**用户** Path 并广播这一变更。之后请**新开一个终端窗口**,已在运行的终端即使新开标签页,也仍沿用旧的 Path |+| 命令入口 | 启动器 `bin\penguin.cmd`。特意不提供 `.ps1` 启动器:批处理文件不受 PowerShell 执行策略限制,所以在默认的 Restricted 策略下 `penguin` 也能运行。安装器会把 `%USERPROFILE%\.penguin\bin` 加入**用户** Path 并广播这一变更。之后请**新开一个终端窗口**,已在运行的终端即使新开标签页,也仍沿用旧的 Path。`-NoModifyPath` 开关则不改动 Path,用于在 `penguin` 所属的安装之外再装一份 || 版本固定 | 运行安装器之前设置 `$env:PENGUIN_VERSION = "vX.Y.Z"` || 本地压缩包 | `$env:PENGUIN_ARCHIVE = "<file>"` 或 `-ArchivePath <file>`。接受 Release 安装包(凭封入的负载校验值自行校验),或旁边带有 `<file>.sha256` 的负载、旧版 zip。重命名过的旧版文件可以使用 `penguin-win32-x64.zip.sha256` || 完整性校验 | 始终开启。在线下载对照发布的 `.sha256` 校验,安装包里的负载对照包内封入的校验值校验 |diff --git a/packages/server/package.json b/packages/server/package.jsonindex 70f98669..58241f96 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -61,7 +61,7 @@"node": ">=24"},"scripts": {- "dev": "node ../../scripts/dev-prebuild.mjs && node ../../scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data PORT=7368 -- tsx watch src/index.ts",+ "dev": "node ../../scripts/dev-prebuild.mjs && node ../../scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data PENGUIN_PROFILE=dev PORT=7368 -- tsx watch src/index.ts","start": "node --disable-warning=ExperimentalWarning dist/index.js","typecheck": "pnpm gen:ifaces && tsc --noEmit -p tsconfig.json","gen:ifaces": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out src/ifaces.json",diff --git a/packages/server/src/machines/commands.ts b/packages/server/src/machines/commands.tsindex e3b3bd80..e20d4209 100644--- a/packages/server/src/machines/commands.ts+++ b/packages/server/src/machines/commands.ts@@ -24,6 +24,7 @@* account for this connection; `~/.ssh/config` is read-only to us.*/import type { RemotePlatform } from "./detect.js";+import type { RemoteLayout } from "./layout.js";/** Wraps a value for a POSIX remote shell. Single quotes are literal there, except `'` itself. */export function shQuote(value: string): string {@@ -57,22 +58,22 @@ function connectionOptions(target: RemoteTarget): string[] {];}-/**- * The far side's program directory, and the launcher inside it that everything here runs.- * Absolute, because sshd's non-login shell has no `~/.local/bin` on PATH — the symlink the- * installer drops there is for a person at a terminal, not for us.- *- * `$HOME/.penguin` is where install.sh puts it (`PENGUIN_INSTALL_DIR`, defaulting there),- * laid out as bin/ lib/ web/ node/, with the launcher exec'ing `node/bin/node lib/dist/…`- * (scripts/launchers/penguin). A remote's own override of that variable is not visible over- * a non-interactive ssh, so the default is the only thing this side can assume — the same- * assumption detect.ts makes to find the manifest.- */-export const REMOTE_PROGRAM_DIR = "$HOME/.penguin";-/*** The CLI these commands run on a machine: the one PUSHED to it, not the one installed.*+ * Run out of the layout's program directory by absolute path, because sshd's non-login+ * shell has no `~/.local/bin` on PATH — the symlink the installer drops there is for a+ * person at a terminal, not for us. The directory is laid out as bin/ lib/ web/ node/ by+ * install.sh (`PENGUIN_INSTALL_DIR`, which runInstallScriptCommand names), with the+ * launcher exec'ing `node/bin/node lib/dist/…` (scripts/launchers/penguin). The data root+ * rides along as PENGUIN_HOME: the CLI's `server status`, `server stop` and `auth token`+ * all act on the root they are given, and the profile's root is not the default one.+ * The profile rides along too, as PENGUIN_PROFILE: the server started by this command+ * reaches machines of its own, and it reads its layout from that variable (layout.ts) —+ * without it a dev-profile server would reach the NEXT machine's release installation.+ * Named for the release profile as well, so an account that exports the variable cannot+ * turn a release server into a dev one.+ ** `bin/penguin` is the released program, and a release only carries the subcommands this* side asks for (`server status`, `auth token`, `server --detach`) once a release has* shipped them. Reaching a machine would then be impossible until the next release —@@ -88,23 +89,22 @@ export const REMOTE_PROGRAM_DIR = "$HOME/.penguin";* Invoked through the bundled runtime rather than the launcher, because there is no* launcher for this entry. Machines installed from here always carry that runtime: the* install runs install.sh without `--universal`, which is the only mode that omits it.+ *+ * Spelled in the dialect of the shell that will read it. A Windows sshd hands a command to+ * cmd.exe, where `$HOME` is four literal characters and the bundled runtime is+ * `node\node.exe` (scripts/launchers/penguin.cmd) — so the POSIX form is not "not found"+ * there, it is a different sentence. `%USERPROFILE%` is what install.ps1 defaults to.*/-export const REMOTE_PENGUIN = `"${REMOTE_PROGRAM_DIR}/node/bin/node" "${REMOTE_PROGRAM_DIR}/lib/dist/penguin-hmr.js"`;--/**- * The same program directory as cmd.exe names it. A Windows sshd hands a command to cmd.exe,- * where `$HOME` is four literal characters and the bundled runtime is `node\node.exe`- * (scripts/launchers/penguin.cmd) — so the POSIX form above is not "not found" there, it is- * a different sentence. `%USERPROFILE%` is what install.ps1 defaults to.- */-export const REMOTE_PROGRAM_DIR_WINDOWS = "%USERPROFILE%\\.penguin";--/** The pushed CLI, invoked in the dialect of the shell that will read the command. */-export function remotePenguin(platform: "linux" | "darwin" | "win32"): string {+export function remotePenguin(platform: RemotePlatform, layout: RemoteLayout): string {if (platform === "win32") {- return `"${REMOTE_PROGRAM_DIR_WINDOWS}\\node\\node.exe" "${REMOTE_PROGRAM_DIR_WINDOWS}\\lib\\dist\\penguin-hmr.js"`;+ const dir = layout.programDir.win;+ return `set "PENGUIN_HOME=${layout.dataRoot.win}" & set "PENGUIN_PROFILE=${layout.profile}" & "${dir}\\node\\node.exe" "${dir}\\lib\\dist\\penguin-hmr.js"`;}- return REMOTE_PENGUIN;+ const dir = layout.programDir.posix;+ // `env`, not a bare `VAR=value` prefix: startServerCommand puts `nohup` in front of this,+ // and nohup takes the first word as the program — a bare assignment there is "no such+ // command", and the server never starts.+ return `env PENGUIN_HOME="${layout.dataRoot.posix}" PENGUIN_PROFILE=${layout.profile} "${dir}/node/bin/node" "${dir}/lib/dist/penguin-hmr.js"`;}/** `ssh <options> <alias> <remote command>`. */@@ -140,17 +140,34 @@ export function scpArgs(target: RemoteTarget, localFiles: string[], remoteDir: sexport function runInstallScriptCommand(versionTag: string,where: { platform: "linux" | "darwin" } | { platform: "win32"; scriptPath: string },+ layout: RemoteLayout,): { command: string; scriptOnStdin: boolean } {+ // The program directory is named on every install, release profile included: the+ // installer's default happens to match that profile, but the far side's own override of+ // PENGUIN_INSTALL_DIR would not be visible here, and the rest of these commands assume+ // the layout they were given.+ //+ // `--no-modify-path` for a layout that does not own the machine's `penguin` command: the+ // installer would otherwise repoint `~/.local/bin/penguin` (or extend the user Path) at+ // this program directory, and a person typing `penguin` there would run the dev program+ // against the release data root.if (where.platform === "win32") {const script = cmdQuote(where.scriptPath);return {command:+ `set "PENGUIN_INSTALL_DIR=${layout.programDir.win}" & ` +`powershell -NoProfile -ExecutionPolicy Bypass -File ${script} -Version ${cmdQuote(versionTag)}` ++ (layout.ownsCommand ? "" : " -NoModifyPath") +` & del /q ${script}`,scriptOnStdin: false,};}- return { command: `PENGUIN_VERSION=${shQuote(versionTag)} sh -s`, scriptOnStdin: true };+ return {+ command:+ `PENGUIN_INSTALL_DIR="${layout.programDir.posix}" PENGUIN_VERSION=${shQuote(versionTag)} sh -s` ++ (layout.ownsCommand ? "" : " -- --no-modify-path"),+ scriptOnStdin: true,+ };}/**@@ -165,12 +182,12 @@ export function runInstallScriptCommand(* `<root>/hmr` — and the machine goes on answering with whatever it held before, so the* replication reports success and achieves nothing.*/-export function unpackStoreCommand(platform: RemotePlatform): string {+export function unpackStoreCommand(platform: RemotePlatform, layout: RemoteLayout): string {if (platform === "win32") {- const root = "%USERPROFILE%\\.penguin\\data\\hmr";+ const root = `${layout.dataRoot.win}\\hmr`;return `(if not exist ${cmdQuote(root)} mkdir ${cmdQuote(root)}) & tar -xzf - -C ${cmdQuote(root)}`;}- const root = "$HOME/.penguin/data/hmr";+ const root = `${layout.dataRoot.posix}/hmr`;return `mkdir -p "${root}" && tar -xzf - -C "${root}"`;}@@ -178,19 +195,37 @@ export function unpackStoreCommand(platform: RemotePlatform): string {* Starts the installed server in the background and returns at once; readiness is the* caller's probe. `nohup` and the redirections are what let it outlive the shell that ran it,* and the log is the far side's own words when it comes up and dies.+ *+ * Prints the launched process's pid (`$!`) as its only output, so the caller can tell a+ * server that is still coming up from one that already died (launchedPid, isAliveCommand).*/-export function startServerCommand(port: number): string {+export function startServerCommand(port: number, layout: RemoteLayout): string {if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`bad port ${port}`);- const log = `"${REMOTE_PROGRAM_DIR}/data/server.log"`;+ const root = layout.dataRoot.posix;// --host is PINNED, not defaulted: the CLI falls back to the HOST environment variable when// it is omitted, so a login shell carrying HOST=0.0.0.0 would put that machine's server on// every interface. This side only ever reaches it as a channel inside the ssh session, at// loopback on the far end, so binding wider is exposure with nothing asking for it.- return `mkdir -p "${REMOTE_PROGRAM_DIR}/data" && nohup ${REMOTE_PENGUIN} server --host 127.0.0.1 --port ${port} >> ${log} 2>&1 < /dev/null &`;+ return `mkdir -p "${root}" && nohup ${remotePenguin("linux", layout)} server --host 127.0.0.1 --port ${port} >> "${root}/server.log" 2>&1 < /dev/null & echo $!`;+}++/** The pid startServerCommand printed; null when the output holds none. */+export function launchedPid(stdout: string): number | null {+ const lines = stdout.trim().split(/\r?\n/);+ const last = lines[lines.length - 1]?.trim() ?? "";+ return /^[1-9]\d*$/.test(last) ? Number(last) : null;+}++/** Answers `alive` or `gone` for a pid on the far side. */+export function isAliveCommand(pid: number): string {+ if (!Number.isInteger(pid) || pid < 1) throw new Error(`bad pid ${pid}`);+ return `kill -0 ${pid} 2>/dev/null && echo alive || echo gone`;}/** The last lines of that log, for a start that did not answer. */-export const SERVER_LOG_TAIL = `tail -n 20 "${REMOTE_PROGRAM_DIR}/data/server.log" 2>/dev/null`;+export function serverLogTail(layout: RemoteLayout): string {+ return `tail -n 20 "${layout.dataRoot.posix}/server.log" 2>/dev/null`;+}// --- tunnelling to that server ---------------------------------------------------------------diff --git a/packages/server/src/machines/detect.ts b/packages/server/src/machines/detect.tsindex 8e527c3f..230d5fdf 100644--- a/packages/server/src/machines/detect.ts+++ b/packages/server/src/machines/detect.ts@@ -11,36 +11,41 @@* not there: the far side only has to `cat` two files, which every shell can do.*/+import type { RemoteLayout } from "./layout.js";+/** Separates the identity line from the manifest text in the probe's output. */const SECTION = "---penguin---";/**- * POSIX probe. `uname -s -m` names the machine; the manifest is read from the program- * directory the installer writes (`~/.penguin`), and harness.json from the default data root- * (core's resolveRoot: `~/.penguin/data`) — a remote's PENGUIN_INSTALL_DIR or PENGUIN_HOME- * override is not visible over a non-interactive ssh, and the defaults are where an install- * this page made would land.+ * POSIX probe. `uname -s -m` names the machine; the manifest is read from the layout's+ * program directory, and harness.json from its data root — a remote's own+ * PENGUIN_INSTALL_DIR or PENGUIN_HOME override is not visible over a non-interactive ssh,+ * and the layout is where an install this page made would land (layout.ts).*/-export const POSIX_PROBE = [- "uname -s -m",- `echo ${SECTION}`,- 'cat "$HOME/.penguin/lib/package.json" 2>/dev/null || true',- `echo ${SECTION}`,- 'cat "$HOME/.penguin/data/hmr/harness.json" 2>/dev/null || true',-].join("; ");+export function posixProbe(layout: RemoteLayout): string {+ return [+ "uname -s -m",+ `echo ${SECTION}`,+ `cat "${layout.programDir.posix}/lib/package.json" 2>/dev/null || true`,+ `echo ${SECTION}`,+ `cat "${layout.dataRoot.posix}/hmr/harness.json" 2>/dev/null || true`,+ ].join("; ");+}/*** Windows (cmd.exe) probe. `&` chains commands there, `%…%` expands variables, `2>nul`* discards the error from a missing file — none of which sh would do the same way, which is* why this is a separate command rather than a portable one.*/-export const WINDOWS_PROBE = [- "echo %OS% %PROCESSOR_ARCHITECTURE%",- `echo ${SECTION}`,- 'type "%USERPROFILE%\\.penguin\\lib\\package.json" 2>nul',- `echo ${SECTION}`,- 'type "%USERPROFILE%\\.penguin\\data\\hmr\\harness.json" 2>nul',-].join("&");+export function windowsProbe(layout: RemoteLayout): string {+ return [+ "echo %OS% %PROCESSOR_ARCHITECTURE%",+ `echo ${SECTION}`,+ `type "${layout.programDir.win}\\lib\\package.json" 2>nul`,+ `echo ${SECTION}`,+ `type "${layout.dataRoot.win}\\hmr\\harness.json" 2>nul`,+ ].join("&");+}/** Node's own names, matching what the release targets are spelled from. */export type RemotePlatform = "linux" | "darwin" | "win32";diff --git a/packages/server/src/machines/install-server.ts b/packages/server/src/machines/install-server.tsindex d7244510..19315203 100644--- a/packages/server/src/machines/install-server.ts+++ b/packages/server/src/machines/install-server.ts@@ -24,8 +24,9 @@ import path from "node:path";import { fileURLToPath } from "node:url";import { runInstallScriptCommand, unpackStoreCommand } from "./commands.js";import type { RemoteTarget } from "./commands.js";-import { parseProbeOutput, POSIX_PROBE, WINDOWS_PROBE } from "./detect.js";+import { parseProbeOutput, posixProbe, windowsProbe } from "./detect.js";import type { RemoteIdentity, RemotePlatform } from "./detect.js";+import type { RemoteLayout } from "./layout.js";import { connectionTo, looksLikeAuthFailure, runBytes } from "./transport/index.js";import type { MachineChannel } from "./transport/index.js";@@ -149,10 +150,11 @@ function baseReleaseVersion(argv1: string | undefined): string | null {*/export async function detectRemote(target: RemoteTarget,+ layout: RemoteLayout,channel?: MachineChannel,): Promise<{ identity: RemoteIdentity } | { error: string }> {const conn = channel ?? connectionTo(target);- const posix = await conn.exec(POSIX_PROBE);+ const posix = await conn.exec(posixProbe(layout));const identity = parseProbeOutput(posix.stdout);if (identity) return { identity };// The session's output is merged, so ssh's own words arrive as stdout.@@ -162,7 +164,7 @@ export async function detectRemote(error: `${said}\n\nConnections use BatchMode: set up key or agent authentication for that host first.`,};}- const windows = await conn.oneShot(WINDOWS_PROBE, { timeoutMs: 30_000 });+ const windows = await conn.oneShot(windowsProbe(layout), { timeoutMs: 30_000 });const identityWin = parseProbeOutput(windows.stdout);if (identityWin) return { identity: identityWin };if (windows.code !== 0 && looksLikeAuthFailure(windows)) {@@ -216,15 +218,17 @@ export async function installOnRemote(opts: {* what puts the machine back within reach.*/forceInstaller?: boolean;+ /** Which installation on that machine this is: the profile's program directory and root. */+ layout: RemoteLayout;}): Promise<RemoteInstallOutcome> {- const { target, plan } = opts;+ const { target, plan, layout } = opts;const conn = opts.channel ?? connectionTo(target);const say = opts.onProgress ?? (() => {});let identity = opts.identity;if (identity === undefined) {say("Asking what that machine is…");- const detected = await detectRemote(target, conn);+ const detected = await detectRemote(target, layout, conn);if ("error" in detected) return { kind: "failed", step: "connect", detail: detected.error };identity = detected.identity;say(`${identity.platform}-${identity.arch}.`);@@ -297,7 +301,7 @@ export async function installOnRemote(opts: {} else {where = { platform: identity.platform };}- const step = runInstallScriptCommand(`v${plan.baseVersion}`, where);+ const step = runInstallScriptCommand(`v${plan.baseVersion}`, where, layout);// The script rides the session's stdin as a heredoc, and the far side's own progress// is relayed as it arrives rather than after the minutes an install can take. A Windows// host runs its copied script on a connection of its own (no session to ride).@@ -333,7 +337,7 @@ export async function installOnRemote(opts: {detail: packed.stderr.trim() || `tar exited ${packed.code}`,};}- const unpack = unpackStoreCommand(identity.platform);+ const unpack = unpackStoreCommand(identity.platform, layout);const sync =identity.platform === "win32"? await conn.oneShot(unpack, { input: packed.stdout })@@ -358,7 +362,7 @@ export async function installOnRemote(opts: {// syncOutOfDate filters on: the machine is then excluded from the very sweep that would// have tried again. A false success here does not just mislead, it seals itself in.say("Checking what it ended up with…");- const after = await detectRemote(target, conn);+ const after = await detectRemote(target, layout, conn);if ("error" in after) {return {kind: "failed",diff --git a/packages/server/src/machines/layout.ts b/packages/server/src/machines/layout.tsnew file mode 100644index 00000000..65803d37--- /dev/null+++ b/packages/server/src/machines/layout.ts@@ -0,0 +1,63 @@+/**+ * Where PenguinHarness lives on a machine, as a function of this instance's PROFILE.+ *+ * The desktop shell runs as one of two profiles — release, or the dev instance that runs+ * beside it on its own data root (`packages/desktop/src/app-identity.ts`) — and the shell+ * hands that choice to its server as `PENGUIN_PROFILE`. A profile names a data-root family,+ * and it holds on every machine the instance touches: a dev instance installs to, starts,+ * probes and connects to a machine's DEV installation, never the release one there — so a+ * connect from the dev instance cannot stop the release server a person is using on that+ * machine, and the two keep separate Agents, Sessions and pushed versions on both ends.+ *+ * Both the program directory and the data root are separate per profile, so an install+ * from the dev instance never replaces the program the release server there is running.+ * The data root sits inside the program directory as the installer lays it out+ * (`<program>/data`), and each profile's server is told its root explicitly rather than+ * left to the default — the remote's own overrides are invisible over a non-interactive ssh.+ *+ * The port is fixed per profile for the reason the release one is (core's ports.ts): a+ * forward's local port equals its remote port, so the two profiles need distinct numbers.+ *+ * One thing on a machine is NOT per profile: the `penguin` command a person types there+ * (`~/.local/bin/penguin`, or the user Path on Windows). It belongs to the release+ * installation, so only the release layout lets the installer register it.+ *+ * Pure, and the only place either path is spelled: every command in this directory takes a+ * layout rather than naming `~/.penguin` itself.+ */+import { DEFAULT_DEV_SERVER_PORT, DEFAULT_SERVER_PORT } from "@prismshadow/penguin-core";++export type Profile = "release" | "dev";++export interface RemoteLayout {+ profile: Profile;+ /** The installer's target (`PENGUIN_INSTALL_DIR`), in each shell's own spelling. */+ programDir: { posix: string; win: string };+ /** The server's data root there (`PENGUIN_HOME`), in each shell's own spelling. */+ dataRoot: { posix: string; win: string };+ /** The port the server is started on when this side has not remembered one. */+ defaultPort: number;+ /** Whether an install from this profile registers the machine's `penguin` command. */+ ownsCommand: boolean;+}++/** `PENGUIN_PROFILE=dev` selects the dev profile; anything else is release. */+export function profileFromEnv(env: NodeJS.ProcessEnv): Profile {+ return env.PENGUIN_PROFILE?.trim() === "dev" ? "dev" : "release";+}++export function remoteLayoutFor(profile: Profile): RemoteLayout {+ const dir = profile === "dev" ? ".penguin-dev" : ".penguin";+ return {+ profile,+ programDir: { posix: `$HOME/${dir}`, win: `%USERPROFILE%\\${dir}` },+ dataRoot: { posix: `$HOME/${dir}/data`, win: `%USERPROFILE%\\${dir}\\data` },+ defaultPort: profile === "dev" ? DEFAULT_DEV_SERVER_PORT : DEFAULT_SERVER_PORT,+ ownsCommand: profile === "release",+ };+}++/** The layout this process reaches machines with. */+export function currentRemoteLayout(env: NodeJS.ProcessEnv = process.env): RemoteLayout {+ return remoteLayoutFor(profileFromEnv(env));+}diff --git a/packages/server/src/machines/remote-token.ts b/packages/server/src/machines/remote-token.tsindex 48fd71ad..d867de8e 100644--- a/packages/server/src/machines/remote-token.ts+++ b/packages/server/src/machines/remote-token.ts@@ -7,7 +7,8 @@* whose admin password a person has set. One command over the shared connection.*/import { execFailureText } from "./transport/index.js";-import { REMOTE_PENGUIN } from "./commands.js";+import { remotePenguin } from "./commands.js";+import type { RemoteLayout } from "./layout.js";import type { RemoteTarget } from "./commands.js";import type { ExecResult } from "./transport/index.js";@@ -24,11 +25,11 @@ type RemoteTokenOutcome =* The command that asks for a token. `--ttl-seconds` is deliberately short: this is used* immediately, and a token still lying in a log an hour from now is worth nothing.*/-export function authTokenCommand(ttlSeconds = 3600): string {+export function authTokenCommand(layout: RemoteLayout, ttlSeconds = 3600): string {if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) throw new Error(`bad ttl ${ttlSeconds}`);// `--mark` is what makes the output parseable: without it the CLI prints the bare token,// and parseToken has no anchor to find it by in a shell that may print a banner of its own.- return `${REMOTE_PENGUIN} auth token --ttl-seconds ${ttlSeconds} --mark 2>&1`;+ return `${remotePenguin("linux", layout)} auth token --ttl-seconds ${ttlSeconds} --mark 2>&1`;}/**@@ -50,6 +51,7 @@ export function parseToken(output: string): string | null {/** Asks a machine's CLI for a session token, over the connection that is already open. */export async function mintTokenOnRemote(target: RemoteTarget,+ layout: RemoteLayout,runOn: (target: RemoteTarget, command: string) => Promise<ExecResult>,ttlSeconds = 3600,): Promise<RemoteTokenOutcome> {@@ -60,7 +62,7 @@ export async function mintTokenOnRemote(// whose connection dropped answers "internal error" instead of "could not sign in there".let result: ExecResult;try {- result = await runOn(target, authTokenCommand(ttlSeconds));+ result = await runOn(target, authTokenCommand(layout, ttlSeconds));} catch (err) {return { kind: "failed", detail: err instanceof Error ? err.message : String(err) };}diff --git a/packages/server/src/machines/server-control.ts b/packages/server/src/machines/server-control.tsindex a95b4d39..14a6aeed 100644--- a/packages/server/src/machines/server-control.ts+++ b/packages/server/src/machines/server-control.ts@@ -9,7 +9,14 @@* The remote server is a plain `penguin server` process, never supervised from here. A* machine that reboots simply reads as "not running" on the next probe.*/-import { REMOTE_PENGUIN, SERVER_LOG_TAIL, startServerCommand } from "./commands.js";+import {+ isAliveCommand,+ launchedPid,+ remotePenguin,+ serverLogTail,+ startServerCommand,+} from "./commands.js";+import type { RemoteLayout } from "./layout.js";import type { RemoteTarget } from "./commands.js";import type { ExecResult } from "./transport/index.js";import { probeServerState } from "./server-state.js";@@ -21,27 +28,45 @@ const START_TIMEOUT_MS = 30_000;const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));/**- * Starts the remote server on the given port and waits until it answers there. Failure- * carries the far side's own words — its server log's last lines when the process came up- * and died, which say more about a port collision or a broken install than "did not start".+ * Starts the remote server on the given port and waits until a server answers for that data+ * root. Failure carries the far side's own words — its server log's last lines when the+ * process came up and died, which say more about a port collision or a broken install than+ * "did not start".+ *+ * The wait ends as soon as the launched process is gone: a port collision kills it within a+ * second, and waiting out the full timeout would only delay the failure reaching a person. "A+ * server answers" is not "on this port" — the data root admits one server, so a slower+ * start still holding it is what answers; the caller reads the port from its own probe.*/export async function startRemoteServer(target: RemoteTarget,port: number,+ layout: RemoteLayout,exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,): Promise<{ ok: true } | { ok: false; detail: string }> {- const started = await exec(target, startServerCommand(port));+ const started = await exec(target, startServerCommand(port, layout));if (started.code !== 0) {return { ok: false, detail: started.stdout.trim() || "the machine could not start it." };}+ const pid = launchedPid(started.stdout);+ let exited = false;const deadline = Date.now() + START_TIMEOUT_MS;while (Date.now() < deadline) {- await sleep(500);- const probed = await probeServerState(target, exec);+ // Each probe is a full Node start on the far side (`penguin-hmr.js server status`), so+ // the interval is what bounds the CPU this wait costs there; a server that is coming up+ // takes a few seconds anyway.+ await sleep(1500);+ const probed = await probeServerState(target, layout, exec);if (probed.state.kind === "running") return { ok: true };+ // Only an explicit `gone` ends the wait: a check that failed to run says nothing.+ if (pid !== null && (await exec(target, isAliveCommand(pid))).stdout.includes("gone")) {+ exited = true;+ break;+ }}- const tail = (await exec(target, SERVER_LOG_TAIL)).stdout.trim();- return { ok: false, detail: tail || "it did not answer within 30s." };+ const tail = (await exec(target, serverLogTail(layout))).stdout.trim();+ const fallback = exited ? "it exited before answering." : "it did not answer within 30s.";+ return { ok: false, detail: tail || fallback };}/**@@ -50,14 +75,15 @@ export async function startRemoteServer(* `penguin server stop` and not a request to the server itself: the machine that needs* stopping is usually the one whose PLATFORM is behind, and a platform route only exists* once it is already running the build that has it. The CLI comes from the store this side- * pushed (commands.ts's REMOTE_PENGUIN), so it speaks the current protocol whatever the+ * pushed (commands.ts's remotePenguin), so it speaks the current protocol whatever the* running platform is.*/export async function stopRemoteServer(target: RemoteTarget,+ layout: RemoteLayout,exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,): Promise<{ ok: true } | { ok: false; detail: string }> {- const result = await exec(target, `${REMOTE_PENGUIN} server stop 2>&1`);+ const result = await exec(target, `${remotePenguin("linux", layout)} server stop 2>&1`);const answer = jsonAnswer<{ ok: boolean; detail?: string }>(result.stdout, "ok");if (answer?.ok === true) return { ok: true };const said = answer?.detail ?? result.stdout.trim();diff --git a/packages/server/src/machines/server-state.ts b/packages/server/src/machines/server-state.tsindex 8343496d..5e9ac236 100644--- a/packages/server/src/machines/server-state.ts+++ b/packages/server/src/machines/server-state.ts@@ -7,6 +7,7 @@* it IS the answer "cannot reach this machine", carrying OpenSSH's diagnostic.*/import { remotePenguin } from "./commands.js";+import type { RemoteLayout } from "./layout.js";import { jsonAnswer } from "./answer.js";import type { RemoteTarget } from "./commands.js";import type { RemotePlatform } from "./detect.js";@@ -18,8 +19,8 @@ import type { MachineStatus } from "../machine-status.js";* that is not there) comes back as text rather than being swallowed by the shared shell,* which merges the streams and reports an empty stderr.*/-export function readServerStateCommand(platform: RemotePlatform): string {- return `${remotePenguin(platform)} server status 2>&1`;+export function readServerStateCommand(platform: RemotePlatform, layout: RemoteLayout): string {+ return `${remotePenguin(platform, layout)} server status 2>&1`;}type MachineServerState =@@ -86,6 +87,7 @@ export function parseProbe(stdout: string): MachineProbe {*/export async function probeServerState(target: RemoteTarget,+ layout: RemoteLayout,exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,/*** The dialect to ask in — what the install found the machine to be. Null when nothing is@@ -95,18 +97,19 @@ export async function probeServerState(*/platform: RemotePlatform | null = null,): Promise<MachineProbe> {- const first = await probeIn(target, exec, platform ?? "linux");+ const first = await probeIn(target, layout, exec, platform ?? "linux");if (platform !== null || first.state.kind !== "unreachable") return first;- const second = await probeIn(target, exec, "win32");+ const second = await probeIn(target, layout, exec, "win32");return second.state.kind === "unreachable" ? first : second;}async function probeIn(target: RemoteTarget,+ layout: RemoteLayout,exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,platform: RemotePlatform,): Promise<MachineProbe> {- const result = await exec(target, readServerStateCommand(platform));+ const result = await exec(target, readServerStateCommand(platform, layout));if (result.code !== 0) {// stdout as the fallback, not just stderr: over the shared shell the two streams are// merged and stderr arrives empty (ssh-session.ts), so reading only stderr threw awaydiff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.tsindex 9de627f3..66efdc50 100644--- a/packages/server/src/machines/service.ts+++ b/packages/server/src/machines/service.ts@@ -25,12 +25,7 @@*/import fs from "node:fs";import os from "node:os";-import {- DEFAULT_PROJECT_ID,- DEFAULT_SERVER_PORT,- VERSION,- loadProjectConfig,-} from "@prismshadow/penguin-core";+import { DEFAULT_PROJECT_ID, VERSION, loadProjectConfig } from "@prismshadow/penguin-core";import type { ProjectConfig } from "@prismshadow/penguin-core";import type { MachineInfo, MachineJob, MachineServerStatus } from "../api/types.js";import { readServerLock } from "../lock.js";@@ -68,6 +63,8 @@ import { Hono } from "hono";import { MachinesRepo } from "../db/repos/machines.js";import type { DatabaseSync } from "node:sqlite";import type { Db, Hmr, Paths } from "../hmr/capabilities.js";+import { currentRemoteLayout } from "./layout.js";+import type { RemoteLayout } from "./layout.js";/** Why an install was refused before any ssh ran. */type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";@@ -96,6 +93,10 @@ export interface MachinesEffects {/** An http.Agent that dials that machine's server through its session. */agent: (target: RemoteTarget, remotePort: number) => http.Agent;stopServer: (target: RemoteTarget) => ReturnType<typeof stopRemoteServer>;+ mintToken: (+ target: RemoteTarget,+ runOn: MachinesEffects["runOn"],+ ) => ReturnType<typeof mintTokenOnRemote>;upgrade: typeof upgradeRemote;/** This server's own Project config, credentials in plaintext — the source of a model sync. */loadConfig: (projectId: string) => Promise<ProjectConfig>;@@ -147,6 +148,8 @@ export class MachinesService {readonly #effects: MachinesEffects;readonly #assets: () => string | null;readonly #machineId: string;+ /** Which installation on each machine this instance reaches — its profile's (layout.ts). */+ readonly #layout: RemoteLayout;constructor(private readonly dataRoot: string,@@ -154,20 +157,23 @@ export class MachinesService {private readonly repo: MachinesRepo,effects: Partial<MachinesEffects> = {},assets: () => string | null = () => null,+ layout: RemoteLayout = currentRemoteLayout(),) {this.#assets = assets;this.#machineId = machineId;+ this.#layout = layout;this.#effects = {listAliases: listHostAliases,resolvePlan: resolvePushPlan,install: installOnRemote,probe: probeServerState,runOn: (target, command) => connectionTo(target).exec(command),- startServer: (target, port) => startRemoteServer(target, port, this.#effects.runOn),+ startServer: (target, port) => startRemoteServer(target, port, layout, this.#effects.runOn),hold: (target) => connectionTo(target).hold(),session: (address) => sessionOf(address),agent: (target, remotePort) => connectionTo(target).agent(remotePort),- stopServer: (target) => stopRemoteServer(target, this.#effects.runOn),+ stopServer: (target) => stopRemoteServer(target, layout, this.#effects.runOn),+ mintToken: (target, runOn) => mintTokenOnRemote(target, layout, runOn),upgrade: upgradeRemote,loadConfig: (projectId) => loadProjectConfig(dataRoot, projectId),now: () => new Date(),@@ -254,7 +260,7 @@ export class MachinesService {const address = `ssh:${target.alias}`;const held = this.#sessions.get(address);if (held !== undefined && Date.now() - held.at < SESSION_REUSE_MS) return held;- const minted = await mintTokenOnRemote(target, this.#effects.runOn);+ const minted = await this.#effects.mintToken(target, this.#effects.runOn);if (minted.kind !== "minted") return { detail: minted.detail };const session = { cookie: `${SESSION_COOKIE}=${minted.token}`, at: Date.now() };this.#sessions.set(address, session);@@ -518,6 +524,7 @@ export class MachinesService {#probe(address: string, target: RemoteTarget): ReturnType<MachinesEffects["probe"]> {return this.#effects.probe(target,+ this.#layout,this.#effects.runOn,this.repo.get(address)?.platform ?? null,);@@ -595,7 +602,7 @@ export class MachinesService {// Only the machine can say whether this alias is this host under another name.// Unreachable is not a refusal — a host with nothing installed yet answers exactly// that — this server's own id is.- const heard = await this.#effects.probe(target, this.#effects.runOn, null);+ const heard = await this.#effects.probe(target, this.#layout, this.#effects.runOn, null);this.#rememberMachineId(address, heard.machineId);if (heard.machineId !== null && heard.machineId === this.#machineId) {return {@@ -610,6 +617,7 @@ export class MachinesService {plan,onProgress: say,assets: this.#assets,+ layout: this.#layout,...(replaceProgram ? { forceInstaller: true } : {}),});if (outcome.kind === "failed") {@@ -761,13 +769,17 @@ export class MachinesService {remotePort = probed.state.port;say(`Its server is already up on port ${remotePort}.`);} else {- remotePort = this.repo.get(address)?.remotePort ?? DEFAULT_SERVER_PORT;+ remotePort = this.repo.get(address)?.remotePort ?? this.#layout.defaultPort;say(`Starting its server on port ${remotePort}…`);const started = await this.#effects.startServer(target, remotePort);if (!started.ok) return { ok: false, step: "start its server", message: started.detail };// A machine mints its id when its server starts, so one that was down had none — and- // its port and pid are now the freshest fact about it.- this.#recordProbe(address, await this.#probe(address, target));+ // its port and pid are now the freshest fact about it. The port is taken from what the+ // machine says, not from what was asked for: the two differ when an earlier, slower+ // start is the server that answered.+ const after = await this.#probe(address, target);+ this.#recordProbe(address, after);+ if (after.state.kind === "running") remotePort = after.state.port;}say("Opening the connection…");@@ -916,6 +928,7 @@ export class MachinesService {): Promise<UpgradeOutcome> {const probed = await this.#effects.probe(target,+ this.#layout,this.#effects.runOn,this.repo.get(address)?.platform ?? null,);@@ -957,6 +970,7 @@ export class MachinesService {): Promise<{ ok: true; port: number } | { ok: false; detail: string }> {const before = await this.#effects.probe(target,+ this.#layout,this.#effects.runOn,this.repo.get(address)?.platform ?? null,);@@ -1015,6 +1029,7 @@ export class MachinesService {): Promise<{ ok: true } | { ok: false; detail: string }> {const before = await this.#effects.probe(target,+ this.#layout,this.#effects.runOn,this.repo.get(address)?.platform ?? null,);diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.tsindex 018bf780..b9f098a9 100644--- a/packages/server/test/machines-api.test.ts+++ b/packages/server/test/machines-api.test.ts@@ -19,6 +19,8 @@ import { openDatabase } from "../src/db/database.js";import { MachinesRepo } from "../src/db/repos/machines.js";import { MachinesService } from "../src/machines/service.js";import type { MachinesEffects } from "../src/machines/service.js";+import { remoteLayoutFor } from "../src/machines/layout.js";+import type { RemoteLayout } from "../src/machines/layout.js";import type { RemoteInstallOutcome } from "../src/machines/install-server.js";import type { RemoteIdentity } from "../src/machines/detect.js";import {@@ -99,7 +101,7 @@ describe("machines API", () => {let machinesRepo: MachinesRepo;let store: DatabaseSync;- const boot = async (over: Partial<MachinesEffects> = {}) => {+ const boot = async (over: Partial<MachinesEffects> = {}, layout?: RemoteLayout) => {connected.clear();machinesRoot = await makeTempRoot();// The store is the service's own here, not the App's, so it needs the Project row the@@ -115,7 +117,14 @@ describe("machines API", () => {.run("default_project", "admin", "2026-08-24T00:00:00.000Z");machinesRepo = new MachinesRepo(store);t = await createTestApp({- machines: new MachinesService(machinesRoot, LOCAL_ID, machinesRepo, effects(over)),+ machines: new MachinesService(+ machinesRoot,+ LOCAL_ID,+ machinesRepo,+ effects(over),+ undefined,+ layout,+ ),});admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);};@@ -314,7 +323,7 @@ describe("machines API", () => {output: "",identity: { ...IDENTITY, platform: "win32" as const },}),- probe: async (_target, _run, platform) => {+ probe: async (_target, _layout, _run, platform) => {dialects.push(platform ?? null);return { state: { kind: "stopped" as const }, machineId: null };},@@ -829,6 +838,76 @@ describe("machines API", () => {expect(t.deps.machines.job()?.log.join(" ")).toContain("Starting its server");});+ it("a remembered port that does not take is the failure, not a cue to try another", async () => {+ // The row's port is the only one tried: this side does not guess at numbers on a+ // machine other people use, and the far side's own words are what a person reads.+ const starts: number[] = [];+ await boot({+ probe: async () => ({ state: { kind: "stopped" as const }, machineId: null }),+ startServer: async (_t, port) => {+ starts.push(port);+ return { ok: false, detail: "EADDRINUSE" };+ },+ });+ installed("9.9.9");+ machinesRepo.patch("ssh:nas", { remotePort: 7376 });+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toMatchObject({+ ok: false,+ step: "start its server",+ message: "EADDRINUSE",+ });+ expect(starts).toEqual([7376]);+ expect(machinesRepo.get("ssh:nas")?.remotePort).toBe(7376);+ });++ it("a machine never reached before starts on the profile's own default port", async () => {+ const starts: number[] = [];+ let up = false;+ await boot(+ {+ probe: async () =>+ up+ ? { state: { kind: "running" as const, port: 7371, pid: 4242 }, machineId: null }+ : { state: { kind: "stopped" as const }, machineId: null },+ startServer: async (_t, port) => {+ starts.push(port);+ up = true;+ return { ok: true };+ },+ },+ remoteLayoutFor("dev"),+ );+ installed("9.9.9");+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toEqual({ ok: true, connected: true });+ expect(starts).toEqual([7371]);+ expect(machinesRepo.get("ssh:nas")?.remotePort).toBe(7371);+ });++ it("remembers the port the machine says it serves on, not the one that was asked for", async () => {+ // The data root admits one server, so the server that answers after a start can be an+ // earlier one on another port. The connection has to go where it actually listens.+ let up = false;+ await boot({+ probe: async () =>+ up+ ? { state: { kind: "running" as const, port: 7376, pid: 4242 }, machineId: null }+ : { state: { kind: "stopped" as const }, machineId: null },+ startServer: async () => {+ up = true;+ return { ok: true };+ },+ });+ installed("9.9.9");+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");+ await waitFor(() => t.deps.machines.job()?.running === false);+ expect(t.deps.machines.job()?.result).toEqual({ ok: true, connected: true });+ expect(machinesRepo.get("ssh:nas")?.remotePort).toBe(7376);+ });+it("reconnecting over a live connection to an answering server starts nothing new", async () => {// hold() is idempotent in the transport: it promotes the session in place. What must// not happen is a start — the server is up — and the record must name the held session.diff --git a/packages/server/test/machines-auth-token.test.ts b/packages/server/test/machines-auth-token.test.tsindex 8461fb9c..a96efcc0 100644--- a/packages/server/test/machines-auth-token.test.ts+++ b/packages/server/test/machines-auth-token.test.ts@@ -14,10 +14,13 @@*/import { describe, expect, it } from "vitest";import { authTokenCommand, mintTokenOnRemote, parseToken } from "../src/machines/remote-token.js";+import { remoteLayoutFor } from "../src/machines/layout.js";import type { ExecResult } from "../src/machines/transport/index.js";const ok = (stdout: string): ExecResult => ({ code: 0, stdout, stderr: "", timedOut: false });+const RELEASE = remoteLayoutFor("release");+describe("parseToken", () => {it("takes the first line after the marker, not a shell banner before it", () => {// The command runs through a shell whose profile may print anything; a banner is not a@@ -28,13 +31,13 @@ describe("parseToken", () => {});it("asks for a bounded lifetime, and refuses a nonsensical one", () => {- expect(authTokenCommand(60)).toContain("--ttl-seconds 60");+ expect(authTokenCommand(RELEASE, 60)).toContain("--ttl-seconds 60");// The command the CLI actually has, and `--mark` — without it the token comes back bare// and parseToken has nothing to anchor on.- expect(authTokenCommand(60)).toContain("auth token");- expect(authTokenCommand(60)).toContain("--mark");- expect(authTokenCommand(60)).not.toContain("server auth-token");- expect(() => authTokenCommand(0)).toThrow();+ expect(authTokenCommand(RELEASE, 60)).toContain("auth token");+ expect(authTokenCommand(RELEASE, 60)).toContain("--mark");+ expect(authTokenCommand(RELEASE, 60)).not.toContain("server auth-token");+ expect(() => authTokenCommand(RELEASE, 0)).toThrow();});});@@ -42,14 +45,14 @@ describe("mintTokenOnRemote", () => {it("reads a machine too old to know the command as 'ask another way'", async () => {// Separate from a failure on purpose: the caller still has the seeded-password path, and// treating this as fatal would strand every machine carrying an older build.- const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, async () =>+ const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, RELEASE, async () =>ok("penguin: unknown command 'auth-token'"),);expect(outcome.kind).toBe("unsupported");});it("does not read a timeout as an old build", async () => {- const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, async () => ({+ const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, RELEASE, async () => ({code: 255,stdout: "",stderr: "",@@ -63,7 +66,7 @@ describe("mintTokenOnRemote", () => {// token is a returned outcome, and signInOn reads outcomes to decide whether to fall back// to the password path — a throw skips that fallback and surfaces as a 500 on a machine// that merely lost its tunnel.- const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, () => {+ const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, RELEASE, () => {throw new Error("write after end");});expect(outcome).toEqual({ kind: "failed", detail: "write after end" });diff --git a/packages/server/test/machines-push.test.ts b/packages/server/test/machines-push.test.tsindex 64864667..360695b0 100644--- a/packages/server/test/machines-push.test.ts+++ b/packages/server/test/machines-push.test.ts@@ -12,9 +12,12 @@ import os from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { installOnRemote } from "../src/machines/install-server.js";+import { remoteLayoutFor } from "../src/machines/layout.js";import type { PushPlan } from "../src/machines/install-server.js";import type { ExecResult, MachineChannel } from "../src/machines/transport/index.js";+const RELEASE = remoteLayoutFor("release");+interface Call {verb: "exec" | "stream" | "oneShot" | "copyTo";command: string;@@ -125,6 +128,7 @@ describe("installOnRemote", () => {const progress: string[] = [];const outcome = await installOnRemote({target,+ layout: RELEASE,plan: plan(),assets,channel,@@ -159,7 +163,13 @@ describe("installOnRemote", () => {// and syncOutOfDate filters on exactly that: the machine is excluded from the sweep that// would have tried again. A false success here seals itself in.const channel = scripted({ probe: "Linux x86_64\\n---penguin---\\n---penguin---\\n" });- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "failed", step: "verify the install" });expect((outcome as { detail: string }).detail).toContain("still has no install");@@ -175,7 +185,13 @@ describe("installOnRemote", () => {probe: "Linux x86_64\\n---penguin---\\n---penguin---\\n",afterInstall: 'Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n',});- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "failed", step: "verify the install" });expect((outcome as { detail: string }).detail).toContain("no pushed state");@@ -187,7 +203,13 @@ describe("installOnRemote", () => {afterInstall: `Windows_NT AMD64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n${HARNESS}`,windows: true,});- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "installed" });const { calls } = channel;@@ -220,7 +242,13 @@ describe("installOnRemote", () => {const channel = scripted({probe: 'Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n',});- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "state-only" });// The probe, and nothing else: no installer, and no store either.expect(channel.calls).toHaveLength(1);@@ -230,7 +258,13 @@ describe("installOnRemote", () => {const channel = scripted({probe: `Linux x86_64\\n---penguin---\\n{"version":"0.2.4"}\\n---penguin---\\n${HARNESS}\\n`,});- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "already-installed", version: "0.2.4+hmr.cafe01234567" });expect(channel.calls).toHaveLength(1); // the probe, and nothing else});@@ -242,6 +276,7 @@ describe("installOnRemote", () => {});const outcome = await installOnRemote({target,+ layout: RELEASE,plan: plan({ harness: null, hmrDir: null, version: "0.2.4" }),assets,channel,@@ -255,7 +290,13 @@ describe("installOnRemote", () => {probe: 'Linux x86_64\\n---penguin---\\n{"version":"0.0.1"}\\n---penguin---\\n',installExit: 3,});- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "failed", step: "install" });expect((outcome as { detail: string }).detail).toContain("PenguinHarness 0.2.4 installed");});@@ -269,7 +310,13 @@ describe("installOnRemote", () => {stderr: "",timedOut: false,});- const outcome = await installOnRemote({ target, plan: plan(), assets, channel });+ const outcome = await installOnRemote({+ target,+ plan: plan(),+ assets,+ channel,+ layout: RELEASE,+ });expect(outcome).toMatchObject({ kind: "failed", step: "connect" });expect((outcome as { detail: string }).detail).toContain("Permission denied");expect((outcome as { detail: string }).detail).toContain("BatchMode");@@ -282,6 +329,7 @@ describe("installOnRemote", () => {});const outcome = await installOnRemote({target,+ layout: RELEASE,plan: plan({ baseVersion: "0.0.0-hmr.cafe", version: "0.0.0-hmr.cafe" }),assets,channel,diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.tsindex 9f585951..d53b1310 100644--- a/packages/server/test/machines.test.ts+++ b/packages/server/test/machines.test.ts@@ -10,7 +10,7 @@ import zlib from "node:zlib";import os from "node:os";import path from "node:path";import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { classifyUpgradeAnswer, readPushedBuild, refusalDetail } from "../src/machines/upgrade.js";import { machineIdentity, parseHostAliases } from "../src/machines/ssh-config.js";import {@@ -18,10 +18,15 @@ import {probeServerState,readServerStateCommand,} from "../src/machines/server-state.js";-import { parseProbeOutput, POSIX_PROBE, WINDOWS_PROBE } from "../src/machines/detect.js";+import { parseProbeOutput, posixProbe, windowsProbe } from "../src/machines/detect.js";+import { profileFromEnv, remoteLayoutFor } from "../src/machines/layout.js";+import { startRemoteServer } from "../src/machines/server-control.js";import {cmdQuote,+ isAliveCommand,+ launchedPid,runInstallScriptCommand,+ startServerCommand,unpackStoreCommand,scpArgs,shQuote,@@ -30,6 +35,9 @@ import {} from "../src/machines/commands.js";import { resolvePushPlan } from "../src/machines/install-server.js";+const RELEASE = remoteLayoutFor("release");+const DEV = remoteLayoutFor("dev");+describe("parseHostAliases", () => {const noIncludes = () => [];@@ -87,13 +95,18 @@ describe("machineIdentity", () => {describe("identity probe", () => {it("asks in each shell's own dialect — sh cannot read the Windows one and vice versa", () => {- expect(POSIX_PROBE).toContain("uname -s -m");- expect(POSIX_PROBE).toContain('"$HOME/.penguin/lib/package.json"');- expect(POSIX_PROBE).toContain(".penguin/data/hmr/harness.json");- expect(WINDOWS_PROBE).toContain("%PROCESSOR_ARCHITECTURE%");- expect(WINDOWS_PROBE).toContain("%USERPROFILE%\\.penguin\\lib\\package.json");- expect(WINDOWS_PROBE).toContain("%USERPROFILE%\\.penguin\\data\\hmr\\harness.json");- expect(WINDOWS_PROBE).not.toContain(";");+ expect(posixProbe(RELEASE)).toContain("uname -s -m");+ expect(posixProbe(RELEASE)).toContain('"$HOME/.penguin/lib/package.json"');+ expect(posixProbe(RELEASE)).toContain(".penguin/data/hmr/harness.json");+ expect(windowsProbe(RELEASE)).toContain("%PROCESSOR_ARCHITECTURE%");+ expect(windowsProbe(RELEASE)).toContain("%USERPROFILE%\\.penguin\\lib\\package.json");+ expect(windowsProbe(RELEASE)).toContain("%USERPROFILE%\\.penguin\\data\\hmr\\harness.json");+ expect(windowsProbe(RELEASE)).not.toContain(";");+ // The dev profile asks after ITS installation, never the release one beside it.+ expect(posixProbe(DEV)).toContain('"$HOME/.penguin-dev/lib/package.json"');+ expect(posixProbe(DEV)).toContain('"$HOME/.penguin-dev/data/hmr/harness.json"');+ expect(posixProbe(DEV)).not.toContain("$HOME/.penguin/");+ expect(windowsProbe(DEV)).toContain("%USERPROFILE%\\.penguin-dev\\lib\\package.json");});it("reads identity, installed version and pushed state from the three sections", () => {@@ -243,20 +256,46 @@ describe("ssh / scp invocations", () => {});it("takes the installer on stdin, so a POSIX install costs ONE ssh handshake", () => {- expect(runInstallScriptCommand("v0.2.4", { platform: "linux" })).toEqual({- command: "PENGUIN_VERSION='v0.2.4' sh -s",+ expect(runInstallScriptCommand("v0.2.4", { platform: "linux" }, RELEASE)).toEqual({+ command: `PENGUIN_INSTALL_DIR="$HOME/.penguin" PENGUIN_VERSION='v0.2.4' sh -s`,scriptOnStdin: true,});+ // The dev profile installs beside the release program, never over it.+ expect(runInstallScriptCommand("v0.2.4", { platform: "linux" }, DEV).command).toContain(+ 'PENGUIN_INSTALL_DIR="$HOME/.penguin-dev"',+ );+ });++ it("a dev-profile install leaves the machine's `penguin` command with the release one", () => {+ // The installer repoints ~/.local/bin/penguin (or extends the user Path) at whatever it+ // just installed; from the dev profile that would hand a person typing `penguin` the dev+ // program, run against the release data root.+ expect(runInstallScriptCommand("v0.2.4", { platform: "linux" }, DEV).command).toBe(+ `PENGUIN_INSTALL_DIR="$HOME/.penguin-dev" PENGUIN_VERSION='v0.2.4' sh -s -- --no-modify-path`,+ );+ expect(+ runInstallScriptCommand("v0.2.4", { platform: "win32", scriptPath: "%TEMP%\\p.ps1" }, DEV)+ .command,+ ).toContain(' -Version "v0.2.4" -NoModifyPath & del /q ');+ // The release profile owns the command, so its install is the installer's default.+ expect(runInstallScriptCommand("v0.2.4", { platform: "linux" }, RELEASE).command).not.toContain(+ "no-modify-path",+ );});it("runs a Windows remote's copy from a path, and deletes it in the same command", () => {expect(- runInstallScriptCommand("v0.2.4", {- platform: "win32",- scriptPath: "%USERPROFILE%\\penguin-ab12.ps1",- }),+ runInstallScriptCommand(+ "v0.2.4",+ {+ platform: "win32",+ scriptPath: "%USERPROFILE%\\penguin-ab12.ps1",+ },+ RELEASE,+ ),).toEqual({command:+ 'set "PENGUIN_INSTALL_DIR=%USERPROFILE%\\.penguin" & ' +'powershell -NoProfile -ExecutionPolicy Bypass -File "%USERPROFILE%\\penguin-ab12.ps1"' +' -Version "v0.2.4" & del /q "%USERPROFILE%\\penguin-ab12.ps1"',scriptOnStdin: false,@@ -268,10 +307,13 @@ describe("ssh / scp invocations", () => {// from THERE. Extracting into the data root instead lands them one directory above where// hmr/host.ts reads them: the machine keeps answering with whatever it already had, and// the replication reports success while achieving nothing.- expect(unpackStoreCommand("linux")).toBe(+ expect(unpackStoreCommand("linux", RELEASE)).toBe('mkdir -p "$HOME/.penguin/data/hmr" && tar -xzf - -C "$HOME/.penguin/data/hmr"',);- expect(unpackStoreCommand("win32")).toBe(+ expect(unpackStoreCommand("linux", DEV)).toBe(+ 'mkdir -p "$HOME/.penguin-dev/data/hmr" && tar -xzf - -C "$HOME/.penguin-dev/data/hmr"',+ );+ expect(unpackStoreCommand("win32", RELEASE)).toBe('(if not exist "%USERPROFILE%\\.penguin\\data\\hmr" mkdir "%USERPROFILE%\\.penguin\\data\\hmr") & tar -xzf - -C "%USERPROFILE%\\.penguin\\data\\hmr"',);});@@ -395,17 +437,36 @@ describe("asking `penguin server status` in the machine's own dialect", () => {};it("speaks cmd.exe to a Windows machine: no $HOME, node.exe, backslashes", () => {- const command = readServerStateCommand("win32");+ const command = readServerStateCommand("win32", RELEASE);expect(command).toContain("%USERPROFILE%\\.penguin\\node\\node.exe");expect(command).toContain("lib\\dist\\penguin-hmr.js");expect(command).not.toContain("$HOME");- expect(readServerStateCommand("linux")).toContain("$HOME/.penguin/node/bin/node");+ expect(readServerStateCommand("linux", RELEASE)).toContain("$HOME/.penguin/node/bin/node");+ // Each profile's CLI acts on that profile's root, on either kind of machine.+ expect(readServerStateCommand("linux", DEV)).toContain(+ 'PENGUIN_HOME="$HOME/.penguin-dev/data"',+ );+ expect(readServerStateCommand("win32", DEV)).toContain(+ 'set "PENGUIN_HOME=%USERPROFILE%\\.penguin-dev\\data"',+ );+ });++ it("carries the profile to the far side, so a server started there reaches on in the same one", () => {+ // That server has a machines service of its own, and it reads its layout from+ // PENGUIN_PROFILE. Without the variable a dev-profile server would reach the NEXT+ // machine's release installation — the profile would hold for exactly one hop.+ expect(readServerStateCommand("linux", DEV)).toContain(" PENGUIN_PROFILE=dev ");+ expect(readServerStateCommand("win32", DEV)).toContain('set "PENGUIN_PROFILE=dev" & ');+ // Named for release too: an account exporting the variable cannot flip a release server.+ expect(readServerStateCommand("linux", RELEASE)).toContain(" PENGUIN_PROFILE=release ");+ expect(startServerCommand(7371, DEV)).toContain(" PENGUIN_PROFILE=dev ");});it("a machine whose platform is on record is asked once, in that dialect", async () => {const asked: string[] = [];const probe = await probeServerState(target,+ RELEASE,async (_t, command) => {asked.push(command);return answered;@@ -421,6 +482,7 @@ describe("asking `penguin server status` in the machine's own dialect", () => {const asked: string[] = [];const probe = await probeServerState(target,+ RELEASE,async (_t, command) => {asked.push(command);return command.includes("%USERPROFILE%") ? answered : cmdSaid;@@ -438,7 +500,7 @@ describe("asking `penguin server status` in the machine's own dialect", () => {stderr: "ssh: connect to host nas port 22: Connection refused",timedOut: false,};- const probe = await probeServerState(target, async () => refused, null);+ const probe = await probeServerState(target, RELEASE, async () => refused, null);expect(probe.state).toMatchObject({kind: "unreachable",detail: expect.stringContaining("Connection refused"),@@ -485,6 +547,119 @@ describe("reading what `penguin server status` answered", () => {});});+describe("startServerCommand", () => {+ it("survives nohup: the data root rides on `env`, never as a bare assignment nohup would run", () => {+ const command = startServerCommand(7371, DEV);+ expect(command).toContain('nohup env PENGUIN_HOME="$HOME/.penguin-dev/data" ');+ expect(command).not.toMatch(/nohup PENGUIN_HOME=/);+ expect(command).toContain("server --host 127.0.0.1 --port 7371");+ expect(command).toContain('"$HOME/.penguin-dev/data/server.log"');+ });++ it("prints the launched pid, and nothing else reads as one", () => {+ expect(startServerCommand(7371, DEV).endsWith("& echo $!")).toBe(true);+ expect(launchedPid("4242\n")).toBe(4242);+ expect(launchedPid("Welcome to build-box!\n4242\n")).toBe(4242);+ expect(launchedPid("")).toBeNull();+ expect(launchedPid("nohup: ignoring input\n")).toBeNull();+ expect(launchedPid("0\n")).toBeNull();+ });+});++describe("startRemoteServer", () => {+ const target = { alias: "nas", user: "" };+ const said = (stdout: string) => ({ code: 0, stdout, stderr: "", timedOut: false });+ const status = (o: Record<string, unknown>) => said(`${JSON.stringify(o)}\n`);+ /** Runs a start with the wait's sleeps collapsed; the probe interval is not under test. */+ async function settled<T>(work: Promise<T>): Promise<T> {+ await vi.runAllTimersAsync();+ return work;+ }+ afterEach(() => vi.useRealTimers());++ it("stops waiting once the launched process is gone, and hands back the log's words", async () => {+ // A port collision kills the server within a second. Waiting out the whole timeout+ // would keep the failure from a person for half a minute for nothing.+ vi.useFakeTimers();+ const asked: string[] = [];+ const result = await settled(+ startRemoteServer(target, 7376, DEV, async (_t, command) => {+ asked.push(command);+ if (command.includes("server --host")) return said("4242\n");+ if (command.includes("server status")) return status({ running: false });+ if (command === isAliveCommand(4242)) return said("gone\n");+ return said("Error: listen EADDRINUSE: address already in use 127.0.0.1:7376\n");+ }),+ );+ expect(result).toEqual({ ok: false, detail: expect.stringContaining("EADDRINUSE") });+ expect(asked.filter((c) => c.includes("server status"))).toHaveLength(1);+ });++ it("keeps waiting while the process is alive, and succeeds when a server answers", async () => {+ vi.useFakeTimers();+ let probes = 0;+ const result = await settled(+ startRemoteServer(target, 7371, DEV, async (_t, command) => {+ if (command.includes("server --host")) return said("4242\n");+ if (command.includes("server status")) {+ probes++;+ return probes < 2+ ? status({ running: false })+ : status({ running: true, port: 7371, pid: 4242 });+ }+ return said("alive\n");+ }),+ );+ expect(result).toEqual({ ok: true });+ expect(probes).toBe(2);+ });++ it("a liveness check that could not run is not a death", async () => {+ vi.useFakeTimers();+ let probes = 0;+ const result = await settled(+ startRemoteServer(target, 7371, DEV, async (_t, command) => {+ if (command.includes("server --host")) return said("4242\n");+ if (command.includes("server status")) {+ probes++;+ return probes < 2+ ? status({ running: false })+ : status({ running: true, port: 7371, pid: 4242 });+ }+ return { code: 255, stdout: "", stderr: "", timedOut: true };+ }),+ );+ expect(result).toEqual({ ok: true });+ });+});++describe("remote layout", () => {+ it("is the release installation unless PENGUIN_PROFILE says dev", () => {+ expect(profileFromEnv({})).toBe("release");+ expect(profileFromEnv({ PENGUIN_PROFILE: "release" })).toBe("release");+ expect(profileFromEnv({ PENGUIN_PROFILE: "dev" })).toBe("dev");+ expect(profileFromEnv({ PENGUIN_PROFILE: "anything-else" })).toBe("release");+ });++ it("keeps the two profiles apart on every axis: program, data root, port", () => {+ expect(RELEASE.programDir.posix).not.toBe(DEV.programDir.posix);+ expect(RELEASE.dataRoot.posix).not.toBe(DEV.dataRoot.posix);+ expect(RELEASE.programDir.win).not.toBe(DEV.programDir.win);+ expect(RELEASE.defaultPort).not.toBe(DEV.defaultPort);+ // The release layout is the installer's own default, so an install this side made and+ // one a person made by hand are the same installation.+ expect(RELEASE.programDir.posix).toBe("$HOME/.penguin");+ expect(RELEASE.dataRoot.posix).toBe("$HOME/.penguin/data");+ expect(RELEASE.defaultPort).toBe(7364);+ expect(DEV.defaultPort).toBe(7371);+ });++ it("only the release profile registers the machine's `penguin` command", () => {+ expect(RELEASE.ownsCommand).toBe(true);+ expect(DEV.ownsCommand).toBe(false);+ });+});+describe("readPushedBuild", () => {it("hands on the native assets and the provenance, not only the three bundles", () => {// A platform resolves node-pty out of its assets directory and nowhere else; a hand-overdiff --git a/scripts/test-installer.ps1 b/scripts/test-installer.ps1index 374ffab8..a700373d 100644--- a/scripts/test-installer.ps1+++ b/scripts/test-installer.ps1@@ -242,6 +242,15 @@ try {$Version = & (Join-Path $InstallDir "bin\penguin.cmd") --versionAssert-True ($Version -eq "fixture-old") "previous Windows installation was not restored"+ # --- A second installation beside the first leaves `penguin` with the first: with+ # -NoModifyPath its bin directory is not put on the Path. ---+ $SecondDir = Join-Path $WorkDir "offline-second"+ $SecondBin = Join-Path $SecondDir "bin"+ & $Installer -InstallDir $SecondDir -ArchivePath $GoodArchive -NoModifyPath *>&1 | Out-Null+ $Version = & (Join-Path $SecondBin "penguin.cmd") --version+ Assert-True ($Version -eq "fixture-old") "second Windows installation did not produce a working command"+ Assert-True (($env:Path -split ";") -notcontains $SecondBin) "-NoModifyPath still put the second installation on the Path"+# --- Canonical bundle fixtures: flat outer layer sealing payload.zip + checksum + installers. ---$BundleDir = Join-Path $WorkDir "bundle"New-Item -ItemType Directory -Path $BundleDir | Out-Nulldiff --git a/scripts/test-installer.sh b/scripts/test-installer.shindex a4af6dda..35d14b6f 100755--- a/scripts/test-installer.sh+++ b/scripts/test-installer.sh@@ -297,6 +297,24 @@ HOME="$TEST_HOME" PENGUIN_INSTALL_DIR="$OFFLINE_INSTALL" PATH="$STUB_BIN:$PATH"[ "$("$OFFLINE_INSTALL/bin/penguin" --version)" = "fixture-old" ] \|| fail_test "offline install did not produce a working command"+# A second installation beside the first leaves `penguin` with the first: with+# --no-modify-path the ~/.local/bin symlink is not repointed.+SECOND_INSTALL="$WORK_DIR/offline-second-install"+HOME="$TEST_HOME" PENGUIN_INSTALL_DIR="$SECOND_INSTALL" PATH="$STUB_BIN:$PATH" \+ sh "$OFFLINE_DIR/install.sh" --no-modify-path >/dev/null \+ || fail_test "second install with --no-modify-path failed"+[ "$("$SECOND_INSTALL/bin/penguin" --version)" = "fixture-old" ] \+ || fail_test "second install did not produce a working command"+[ "$(readlink "$TEST_HOME/.local/bin/penguin")" = "$OFFLINE_INSTALL/bin/penguin" ] \+ || fail_test "--no-modify-path repointed the penguin symlink at the second installation"+# The same flag arrives through `sh -s --`, which is how a machine install passes it.+THIRD_INSTALL="$WORK_DIR/offline-third-install"+HOME="$TEST_HOME" PENGUIN_INSTALL_DIR="$THIRD_INSTALL" PENGUIN_ARCHIVE="$ARTIFACT_DIR/$HOST_ASSET" \+ PATH="$STUB_BIN:$PATH" sh -s -- --no-modify-path < "$OFFLINE_DIR/install.sh" >/dev/null \+ || fail_test "install over stdin with --no-modify-path failed"+[ "$(readlink "$TEST_HOME/.local/bin/penguin")" = "$OFFLINE_INSTALL/bin/penguin" ] \+ || fail_test "--no-modify-path over stdin repointed the penguin symlink"+# The stamped installer inside a released bundle must still prefer its sibling payload and# never resolve metadata or download an online asset.STAMPED_OFFLINE_DIR="$WORK_DIR/offline-stamped"