A local-first multi-agent app development platform, built on PenguinHarness
fix(server,desktop): check the web dist on start up (#547)
Myriad-Dreamin786b7a0c55bd
diff --git a/changelog/unreleased/2026-08-29-web-dist-diagnostics.md b/changelog/unreleased/2026-08-29-web-dist-diagnostics.mdnew file mode 100644index 00000000..1c9ff822--- /dev/null+++ b/changelog/unreleased/2026-08-29-web-dist-diagnostics.md@@ -0,0 +1,16 @@+# The server names its web dist, and refuses a restored web version without index.html++- **Date:** 2026-08-29+- **Type:** fix+- **Scope:** `server`, `desktop`+- **PR:** [#547](https://github.com/Prism-Shadow/penguin-harness/pull/547)++[中文版](2026-08-29-web-dist-diagnostics.zh.md)++A server whose static tail had nothing to serve answered 404 on every page and said nothing about it. Three changes name the condition instead.++## Details++- Startup prints `Web dist: <path>` beside `Data root:` and `SQLite:`, and warns when that directory has no `index.html` — a wrong `PENGUIN_WEB_DIST` or a missing `packages/web` build now shows up in the log rather than as a bare 404.+- The packaged desktop app pins the embedded server to its own `web-dist` (`PENGUIN_WEB_DIST`, an explicit value still winning) and checks for its `index.html` before the fork; a build packed without the web assets now fails at startup with the path named, instead of opening a window on a 404. A source run pins nothing and keeps the server's fallback to `packages/web/dist`.+- Restoring a persisted hot-pushed version now requires the stored web dist to contain `index.html`, the same floor a push is held to. A store file without it fails the restore with the ordinary `persisted version failed to restore` warning naming the file, and the packaged web dist is served instead of an in-memory version that 404s everywhere.diff --git a/changelog/unreleased/2026-08-29-web-dist-diagnostics.zh.md b/changelog/unreleased/2026-08-29-web-dist-diagnostics.zh.mdnew file mode 100644index 00000000..30c8c392--- /dev/null+++ b/changelog/unreleased/2026-08-29-web-dist-diagnostics.zh.md@@ -0,0 +1,16 @@+# server 启动时报出 web dist 路径,并拒绝还原缺少 index.html 的 web 版本++- **Date:** 2026-08-29+- **Type:** fix+- **Scope:** `server`, `desktop`+- **PR:** [#547](https://github.com/Prism-Shadow/penguin-harness/pull/547)++[English](2026-08-29-web-dist-diagnostics.md)++静态文件无物可服时,server 对每个页面都答 404,却什么也不说。三处修改把这个状况点出来。++## 细节++- 启动时在 `Data root:`、`SQLite:` 旁边打印 `Web dist: <path>`,该目录没有 `index.html` 时发出警告——错误的 `PENGUIN_WEB_DIST` 或缺失的 `packages/web` 构建现在会出现在日志里,而不是只表现为一个光秃秃的 404。+- 打包的桌面应用把内嵌 server 钉到自己的 `web-dist`(`PENGUIN_WEB_DIST`,显式设置的值仍然优先),并在 fork 之前检查其中的 `index.html`;没带 web 资源的构建现在会在启动时报错并给出路径,而不是打开一个 404 的窗口。源码运行不钉任何值,保留 server 回退到 `packages/web/dist` 的行为。+- 还原持久化的热推版本时,要求存储的 web dist 包含 `index.html`,与推送时的底线一致。缺少它的存储文件会让还原失败,并以常规的 `persisted version failed to restore` 警告点名该文件,随后改为提供打包的 web dist,而不是一个处处 404 的内存版本。diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex 5aadf79d..9fdc2158 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -27,12 +27,14 @@* `DESKTOP-SMOKE-RESULT {json}` line (+ screenshot when PENGUIN_DESKTOP_SMOKE_SHOT is* set) and quit through the regular quit path, exercising the graceful server stop.*/+import fs from "node:fs";import os from "node:os";import path from "node:path";import { app, BrowserWindow, dialog, shell } from "electron";import { resolveRoot } from "@prismshadow/penguin-core";import { liveServerLock } from "@prismshadow/penguin-server/lock";import { appIdentity, desktopDataRoot } from "./app-identity.js";+import { webDistEntry, webDistFor } from "./web-dist.js";import { resolveWindowIcon } from "./app-icon.js";import { installCliCommand, ensureCliCommand, currentCliInstallKind } from "./cli-install.js";import { applyLoginShellEnv } from "./login-shell-env.js";@@ -166,8 +168,22 @@ function wireUpdaterRelay(child: EmbeddedServer["child"]): void {/** Starts (or restarts) the embedded server and points the window at the claim link. */async function startServerAndWindow(dataRoot: string): Promise<void> {+ const webDist = webDistFor({+ isPackaged: app.isPackaged,+ appPath: app.getAppPath(),+ env: process.env,+ });+ // Checked here, not left to the server: a server with nothing to serve still starts,+ // and the window would open on a 404 with no line in the log naming the directory.+ if (webDist !== null && !fs.existsSync(webDistEntry(webDist))) {+ throw new Error(+ `The Web App is missing: ${webDistEntry(webDist)} does not exist. ` ++ `This build was packed without the web assets, or PENGUIN_WEB_DIST points elsewhere.`,+ );+ }const started = await startEmbeddedServer({dataRoot,+ webDist,portFile: path.join(app.getPath("userData"), "server-port"),preferredPortFile: path.join(app.getPath("userData"), "preferred-port"),log: (chunk) => process.stdout.write(`[server] ${chunk}`),diff --git a/packages/desktop/src/server-process.ts b/packages/desktop/src/server-process.tsindex 425d123f..8a9e5fa9 100644--- a/packages/desktop/src/server-process.ts+++ b/packages/desktop/src/server-process.ts@@ -103,6 +103,8 @@ async function waitForHttp(origin: string, exited: () => boolean): Promise<void>*/export async function startEmbeddedServer(opts: {dataRoot: string;+ /** Pinned web dist (packaged app), or null to leave it to the server's default lookup. */+ webDist: string | null;portFile: string;preferredPortFile: string;log: (chunk: string) => void;@@ -121,6 +123,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,+ ...(opts.webDist !== null ? { PENGUIN_WEB_DIST: opts.webDist } : {}),HOST: "127.0.0.1",PORT: String(requestedPort),PENGUIN_DESKTOP_TOKEN: token,diff --git a/packages/desktop/src/web-dist.ts b/packages/desktop/src/web-dist.tsnew file mode 100644index 00000000..a866b873--- /dev/null+++ b/packages/desktop/src/web-dist.ts@@ -0,0 +1,34 @@+/**+ * Where the embedded server serves the Web App from — pure, no Electron imports, so it+ * unit-tests under plain vitest.+ *+ * A packaged app carries the web build at `<app>/web-dist` (electron-builder.yml maps+ * `../web/dist` there), which is also the first place the server's own default lookup+ * tries — so pinning it explicitly changes nothing in a healthy install. What it buys is+ * failing loudly: a build packed without the web assets, or one whose lookup lands+ * elsewhere, used to open a window on a server that answered 404 to every page and said+ * nothing about why. The shell now names the directory and checks it before the fork.+ *+ * An explicit `PENGUIN_WEB_DIST` still wins, as it does for the server itself: it is the+ * hook for serving a different build against an installed app.+ *+ * A source run pins nothing — `packages/desktop/web-dist` does not exist there, and the+ * server's fallback to `packages/web/dist` is what `pnpm desktop` relies on.+ */+import path from "node:path";++/** The web dist the embedded server should serve, or null to leave it to the server's default. */+export function webDistFor(opts: {+ isPackaged: boolean;+ appPath: string;+ env: NodeJS.ProcessEnv;+}): string | null {+ const explicit = opts.env.PENGUIN_WEB_DIST?.trim();+ if (explicit) return explicit;+ return opts.isPackaged ? path.join(opts.appPath, "web-dist") : null;+}++/** The entry page a usable web dist must contain; the check the shell runs before the fork. */+export function webDistEntry(webDist: string): string {+ return path.join(webDist, "index.html");+}diff --git a/packages/desktop/test/web-dist.test.ts b/packages/desktop/test/web-dist.test.tsnew file mode 100644index 00000000..c8e14de0--- /dev/null+++ b/packages/desktop/test/web-dist.test.ts@@ -0,0 +1,34 @@+import path from "node:path";+import { describe, expect, it } from "vitest";+import { webDistEntry, webDistFor } from "../src/web-dist.js";++describe("webDistFor", () => {+ it("pins a packaged app to its own web-dist", () => {+ expect(webDistFor({ isPackaged: true, appPath: "/opt/app/resources/app", env: {} })).toBe(+ path.join("/opt/app/resources/app", "web-dist"),+ );+ });++ it("leaves a source run to the server's default lookup", () => {+ // packages/desktop/web-dist does not exist in a checkout; the server falls back to+ // packages/web/dist on its own, which is what `pnpm desktop` relies on.+ expect(webDistFor({ isPackaged: false, appPath: "/src/packages/desktop", env: {} })).toBeNull();+ });++ it("an explicit PENGUIN_WEB_DIST wins in both forms; blank counts as unset", () => {+ for (const isPackaged of [true, false]) {+ expect(webDistFor({ isPackaged, appPath: "/x", env: { PENGUIN_WEB_DIST: "/srv/web" } })).toBe(+ "/srv/web",+ );+ }+ expect(webDistFor({ isPackaged: true, appPath: "/x", env: { PENGUIN_WEB_DIST: " " } })).toBe(+ path.join("/x", "web-dist"),+ );+ });+});++describe("webDistEntry", () => {+ it("is the dist's index.html", () => {+ expect(webDistEntry("/srv/web")).toBe(path.join("/srv/web", "index.html"));+ });+});diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.tsindex ab6a5983..b0738b53 100644--- a/packages/server/src/hmr/host.ts+++ b/packages/server/src/hmr/host.ts@@ -304,6 +304,13 @@ export class HmrHost {const bundle = await this.importBundleFile(path.join(this.hmrDir, manifest.platform.bundle));const gz = await fsp.readFile(path.join(this.hmrDir, manifest.web.manifest));const webMem = filesMapFromGzip(gz);+ // The same floor a push is held to (doUpgradeAll): a web version without its entry+ // page would be committed as "restored" and then answer 404 to every navigation,+ // with nothing in the log to say why. Failing here lands on the packaged default+ // instead, and names the reason.+ if (!webMem.has("index.html")) {+ throw new Error(`web dist '${manifest.web.manifest}' has no index.html`);+ }// Everything validated: commit together. boot() runs last so a boot failure// leaves nothing partially applied either.const instance = (await boot(diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex db8fd349..a7ac529f 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -267,6 +267,16 @@ class PenguinServer {console.log(`penguin-server started: http://${this.appHost()}:${port}`);console.log(`Data root: ${this.config.root}`);console.log(`SQLite: ${this.config.dbPath}`);+ // Named for the same reason the data root is: it is the one path the static tail+ // serves from when no pushed web version is restored, and the only trace of a wrong+ // PENGUIN_WEB_DIST or a missing build is otherwise a 404 on every page.+ console.log(`Web dist: ${this.config.webDist}`);+ if (!fs.existsSync(path.join(this.config.webDist, "index.html"))) {+ console.warn(+ `[server] Web dist has no index.html; the Web App answers 404 unless a pushed web ` ++ `version is restored. Build packages/web or point PENGUIN_WEB_DIST at a build.`,+ );+ }if (this.config.desktopToken !== null) console.log("Desktop mode: enabled");// PORT=0 asked for an ephemeral port: record the real one so everything derived from// the server's own port is correct — Workspace preview URLs above all, which are builtdiff --git a/packages/server/test/hmr-host.test.ts b/packages/server/test/hmr-host.test.tsindex fe5e1a0b..34b86f7a 100644--- a/packages/server/test/hmr-host.test.ts+++ b/packages/server/test/hmr-host.test.ts@@ -154,6 +154,52 @@ describe("HmrHost.ensure(): single-flight first boot", () => {freshRoot = undefined;});+ it("refuses to restore a web version without index.html, and says so", async () => {+ // A push is held to "the web dist has an index.html"; a restart restoring the same+ // artifact was not, so a store file damaged after the push came back as a version+ // that 404s on every page with nothing in the log. The restore now fails the same+ // way a bad push does: a warning naming the file, and the packaged default served.+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;+ expect(+ (await pushPlatform(t.app, cookie, platformServing(["/api/demo/x"], "webless"))).status,+ ).toBe(200);+ const root = t.root;+ freshRoot = root;+ t.deps.hmr.dispose();+ t.deps.channels.dispose();+ t.deps.db.close();+ t = undefined;++ const webDir = path.join(root, "hmr", "store", "web");+ const [webz] = (await fs.readdir(webDir)).filter((name) => name.endsWith(".webz"));+ if (webz === undefined) throw new Error("push left no .webz in the store");+ await fs.writeFile(+ path.join(webDir, webz),+ zlib.gzipSync(Buffer.from(JSON.stringify({ files: { "app.js": "Lw==" } }))),+ );++ const warnings: string[] = [];+ const spy = vi.spyOn(process.stderr, "write").mockImplementation(((+ chunk: string | Uint8Array,+ ) => {+ warnings.push(String(chunk));+ return true;+ }) as typeof process.stderr.write);+ const fresh = new HmrHost(root);+ try {+ // Restore refused, the host goes on to boot the packaged default — which this bare+ // host cannot (it publishes no runtime resources). That rejection is the fixture's,+ // and it comes after the refusal under test has already been logged.+ await fresh.ensure().catch(() => undefined);+ expect(fresh.resolveWebSource()).toBeNull();+ expect(warnings.join("")).toMatch(/failed to restore.*has no index\.html/s);+ } finally {+ spy.mockRestore();+ fresh.dispose();+ }+ });+it("concurrent ensure() calls on a fresh host share one init and all resolve to the restored (pushed) instance", async () => {// Push a version and let it persist, then tear down that host WITHOUT touching the// root directory — simulating a restart of the same data root.