A local-first multi-agent app development platform, built on PenguinHarness
fix(server): the SPA gets a caching contract, so a web push is actually visible (#444)
Myriad-Dreamin5012411166d8
diff --git a/changelog/unreleased/2026-08-24-spa-caching.md b/changelog/unreleased/2026-08-24-spa-caching.mdnew file mode 100644index 00000000..987871f9--- /dev/null+++ b/changelog/unreleased/2026-08-24-spa-caching.md@@ -0,0 +1,18 @@+# The SPA gets a caching contract, so a new build is actually visible++- **Date:** 2026-08-24+- **Type:** fix+- **Scope:** `server`++[中文版](2026-08-24-spa-caching.zh.md)++The built frontend was served with no caching headers at all, so what a browser did with it was+the browser's own business. A hot update could land, the server could be running the new build,+and a window could go on running the old one — with nothing on either side saying so.++Now the two kinds of file are served the way their names already promise:++- `index.html` is `no-cache` with an ETag. It is revalidated on every navigation and costs a 304+ when nothing changed, which is what makes a new build visible immediately.+- `assets/*` is `immutable`, cached for a year. Those filenames carry a content hash, so a+ changed file is a different URL and the old one can never be wrong.diff --git a/changelog/unreleased/2026-08-24-spa-caching.zh.md b/changelog/unreleased/2026-08-24-spa-caching.zh.mdnew file mode 100644index 00000000..5934442d--- /dev/null+++ b/changelog/unreleased/2026-08-24-spa-caching.zh.md@@ -0,0 +1,16 @@+# 前端有了明确的缓存约定,新构建才真的可见++- **日期:** 2026-08-24+- **类型:** fix+- **范围:** `server`++[English](2026-08-24-spa-caching.md)++打包后的前端此前不带任何缓存头,浏览器怎么处理全凭自己。结果是:热更新已经落地、服务端已经在跑新构建,+而窗口里仍然是旧代码——两边都没有任何提示。++现在两类文件按各自文件名早已承诺的方式来发:++- `index.html` 用 `no-cache` 加 ETag。每次导航都会重新校验,没变化时只花一个 304,这正是新构建能立刻+ 生效的原因。+- `assets/*` 用 `immutable`,缓存一年。这些文件名带内容哈希,内容变了 URL 就变了,旧的那份永远不会错。diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 72bea8ef..925f9a75 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -16,11 +16,12 @@* than with this build. Swap semantics for anything they hold that is not parked is a* HARD STOP: approvals deny, runs abort, the scheduler dies with its App.*/+import { createHash } from "node:crypto";import fs from "node:fs";import fsp from "node:fs/promises";import path from "node:path";import { Hono } from "hono";-import type { MiddlewareHandler } from "hono";+import type { Context, MiddlewareHandler } from "hono";import { bodyLimit } from "hono/body-limit";import { bodyLimitBytes } from "./services/attachment-limits.js";import type { DatabaseSync } from "node:sqlite";@@ -487,11 +488,79 @@ const CONTENT_TYPES: Record<string, string> = {/** Where registerStaticRoutes reads a request's bytes from, resolved fresh per request. */export type WebSource = { kind: "mem"; files: Map<string, Buffer> } | { kind: "dir"; dir: string };+/**+ * The SPA's caching contract, without which a hot-pushed web is invisible to returning+ * clients until they happen to hard-refresh:+ *+ * - Vite's `assets/*` files are content-hashed, so their bytes can never change under+ * their name → cache forever, never revalidate.+ * - Everything else — `index.html` above all, including every SPA-fallback answer — must+ * revalidate on each navigation (`no-cache` means "store, but ask first"), and the ETag+ * makes that ask a 304 instead of a re-download. A web push changes the ETag, so the+ * very next load anywhere picks the new app up.+ */+function cacheControlFor(servedPath: string): string {+ return servedPath.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-cache";+}++/** Content ETags for the in-memory dist, computed once per Buffer (pushes swap the Buffers). */+const memEtags = new WeakMap<Buffer, string>();++function etagOfBuffer(content: Buffer): string {+ let etag = memEtags.get(content);+ if (etag === undefined) {+ etag = `"${createHash("sha256").update(content).digest("base64url").slice(0, 16)}"`;+ memEtags.set(content, etag);+ }+ return etag;+}++/**+ * Whether `If-None-Match` claims this exact representation, per RFC 9110's rules rather than+ * by string equality — both of which a real deployment hits:+ *+ * - It is a LIST. A client holding several validators sends `"a", "b"`.+ * - Comparison is WEAK, so `W/"x"` and `"x"` are the same tag. A proxy that re-encodes a+ * response (nginx's gzip module is the common one) downgrades a strong ETag to weak on the+ * way out, and the client sends back what it was given.+ *+ * Getting this wrong costs only 304s — the bytes are still correct — which is exactly why it+ * would never be noticed, and why it is worth a few lines rather than a string compare.+ */+function ifNoneMatchHits(header: string | undefined, etag: string): boolean {+ if (header === undefined) return false;+ const bare = (tag: string) => tag.trim().replace(/^W\//, "");+ // `*` means "any current representation": for a resource that exists, that is a match.+ if (header.trim() === "*") return true;+ const want = bare(etag);+ return header.split(",").some((tag) => bare(tag) === want);+}++/** The static response for one resolved file: 304 on an ETag match, the bytes otherwise. */+function staticResponse(+ c: Context<AppEnv>,+ content: Buffer,+ servedPath: string,+ etag: string,+): Response {+ const headers: Record<string, string> = {+ "Cache-Control": cacheControlFor(servedPath),+ ETag: etag,+ };+ if (ifNoneMatchHits(c.req.header("if-none-match"), etag)) {+ return new Response(null, { status: 304, headers });+ }+ headers["Content-Type"] =+ CONTENT_TYPES[path.extname(servedPath).toLowerCase()] ?? "application/octet-stream";+ return new Response(new Uint8Array(content), { status: 200, headers });+}+/*** Minimal static file server (avoiding an extra dependency): path traversal* protection + SPA fallback, over either an in-memory pushed/restored dist (the* hot host's primary path — no filesystem at all) or the packaged webDist- * directory on disk.+ * directory on disk. Serves the caching contract above, so pushes take effect+ * on the next navigation and hashed assets stop re-downloading.*/function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<WebSource>): void {app.get("*", async (c) => {@@ -511,12 +580,7 @@ function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<Weif (content === undefined) {return c.json(errorBody("not_found", "Resource does not exist."), 404);}- const type =- CONTENT_TYPES[path.extname(servedPath).toLowerCase()] ?? "application/octet-stream";- return new Response(new Uint8Array(content), {- status: 200,- headers: { "Content-Type": type },- });+ return staticResponse(c, content, servedPath, etagOfBuffer(content));}const webDist = source.dir;@@ -539,16 +603,26 @@ function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<Wefile = path.join(base, "index.html"); // SPA fallback}let content: Buffer;+ let mtimeMs = 0;try {- content = await fsp.readFile(file);+ // ONE handle for both, not stat-then-read: a handle names an inode, so the validator+ // is guaranteed to describe the bytes being sent. Read and stat as separate lookups+ // can straddle a file replacement and tag old bytes with a new mtime — after which+ // the client revalidates, matches, and keeps the stale copy indefinitely.+ const handle = await fsp.open(file, "r");+ try {+ mtimeMs = (await handle.stat()).mtimeMs;+ content = await handle.readFile();+ } finally {+ await handle.close();+ }} catch {return c.json(errorBody("not_found", "Resource does not exist."), 404);}- const type = CONTENT_TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream";- return new Response(new Uint8Array(content), {- status: 200,- headers: { "Content-Type": type },- });+ // A weak size+mtime validator, the classic disk-file shape — hashing every+ // response would cost more than the 304s save.+ const etag = `W/"${content.byteLength}-${Math.round(mtimeMs)}"`;+ return staticResponse(c, content, path.relative(base, file).split(path.sep).join("/"), etag);});}diff --git a/packages/server/test/web-static-caching.test.ts b/packages/server/test/web-static-caching.test.tsnew file mode 100644index 00000000..86ace5ae--- /dev/null+++ b/packages/server/test/web-static-caching.test.ts@@ -0,0 +1,194 @@+/**+ * The SPA's caching contract — the piece that makes a hot-pushed web VISIBLE: without it,+ * whether a returning client ever saw a new push was left to browser heuristics. index.html+ * (and every SPA-fallback answer) must revalidate per navigation and flip on a push;+ * content-hashed assets must cache forever.+ */+import zlib from "node:zlib";+import fs from "node:fs/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const MINIMAL_CLI = "export async function cli(argv) { return 0; }\n";+// Any bundle that boots will do — the subject here is the WEB half of the same push, and+// this is the fixture the seam tests already keep working.+const PLATFORM_BUNDLE_FILE = fileURLToPath(+ new URL("./fixtures/platform-http.bundle.mjs", import.meta.url),+);++const webFiles = (marker: string) => ({+ "index.html": Buffer.from(`<html>${marker}</html>`).toString("base64"),+ "assets/index-abc123.js": Buffer.from(`console.log("${marker}")`).toString("base64"),+});++async function pushWeb(t: TestApp, cookie: string, marker: string) {+ const platform = await fs.readFile(PLATFORM_BUNDLE_FILE, "utf8");+ const gz = zlib.gzipSync(+ Buffer.from(+ JSON.stringify({+ platform,+ cli: MINIMAL_CLI,+ web: { files: webFiles(marker) },+ }),+ ),+ );+ return t.app.request("/api/hmr/upgrade", {+ method: "POST",+ headers: { cookie, "content-type": "application/gzip" },+ body: gz,+ });+}++describe("web static caching", () => {+ let t: TestApp;+ let cookie: string;++ beforeEach(async () => {+ t = await createTestApp();+ cookie = (await loginAdmin(t.app)).cookie;+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("index.html revalidates per navigation; hashed assets cache forever", async () => {+ expect((await pushWeb(t, cookie, "v1")).status).toBe(200);++ const index = await t.app.request("/");+ expect(index.status).toBe(200);+ expect(index.headers.get("cache-control")).toBe("no-cache");+ const etag = index.headers.get("etag");+ expect(etag).toBeTruthy();++ // The SPA fallback is index.html under another name: same contract.+ const fallback = await t.app.request("/chat/new");+ expect(fallback.headers.get("cache-control")).toBe("no-cache");+ expect(fallback.headers.get("etag")).toBe(etag);++ const asset = await t.app.request("/assets/index-abc123.js");+ expect(asset.status).toBe(200);+ expect(asset.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");+ });++ it("a matching ETag answers 304 with no body", async () => {+ expect((await pushWeb(t, cookie, "v1")).status).toBe(200);+ const first = await t.app.request("/");+ const etag = first.headers.get("etag")!;+ const revalidated = await t.app.request("/", { headers: { "if-none-match": etag } });+ expect(revalidated.status).toBe(304);+ expect(await revalidated.text()).toBe("");+ // Still carries the contract, so the client keeps revalidating next time.+ expect(revalidated.headers.get("cache-control")).toBe("no-cache");+ });++ it("a new push changes the ETag, so the next navigation gets the new app", async () => {+ expect((await pushWeb(t, cookie, "v1")).status).toBe(200);+ const v1 = await t.app.request("/");+ const v1Etag = v1.headers.get("etag")!;++ expect((await pushWeb(t, cookie, "v2")).status).toBe(200);+ // The old ETag no longer matches: full 200 with the new bytes, not a 304.+ const after = await t.app.request("/", { headers: { "if-none-match": v1Etag } });+ expect(after.status).toBe(200);+ expect(await after.text()).toContain("v2");+ expect(after.headers.get("etag")).not.toBe(v1Etag);+ });+});++describe("If-None-Match, as clients and proxies actually send it", () => {+ let t: TestApp;++ beforeEach(async () => {+ t = await createTestApp();+ const cookie = (await loginAdmin(t.app)).cookie;+ expect((await pushWeb(t, cookie, "v1")).status).toBe(200);+ });+ afterEach(async () => {+ await t.cleanup();+ });++ const etagOfIndex = async () => (await t.app.request("/")).headers.get("etag")!;++ it("matches one tag out of a list", async () => {+ // RFC 9110 allows a list, and a client holding several validators sends one.+ const etag = await etagOfIndex();+ const res = await t.app.request("/", {+ headers: { "if-none-match": `"stale-one", ${etag}, W/"another"` },+ });+ expect(res.status).toBe(304);+ });++ it("matches weakly, so a proxy's W/ downgrade still revalidates", async () => {+ // A re-encoding proxy (nginx's gzip module is the usual one) turns a strong ETag weak on+ // the way out; the client returns what it was given. A string compare misses this and+ // silently re-downloads the app on every navigation.+ const etag = await etagOfIndex();+ const res = await t.app.request("/", { headers: { "if-none-match": `W/${etag}` } });+ expect(res.status).toBe(304);+ });++ it("treats * as a match, and an unrelated tag as a miss", async () => {+ expect((await t.app.request("/", { headers: { "if-none-match": "*" } })).status).toBe(304);+ expect((await t.app.request("/", { headers: { "if-none-match": '"nope"' } })).status).toBe(200);+ });+});++describe("web static caching, served from disk", () => {+ // The packaged install's path, and a SECOND implementation of the same contract: the disk+ // branch derives a weak size+mtime validator instead of hashing. Nothing above exercises+ // it, so without this the shipped half of the feature has no assertions on it at all.+ let t: TestApp;+ let webDist: string;++ beforeEach(async () => {+ webDist = path.join(await makeTempRoot(), "web");+ await fs.mkdir(path.join(webDist, "assets"), { recursive: true });+ await fs.writeFile(path.join(webDist, "index.html"), "<html>disk v1</html>");+ await fs.writeFile(path.join(webDist, "assets", "index-abc123.js"), 'console.log("v1")');+ t = await createTestApp({ config: { webDist } });+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("applies the same contract, with a weak validator", async () => {+ const index = await t.app.request("/");+ expect(index.status).toBe(200);+ expect(index.headers.get("cache-control")).toBe("no-cache");+ // Weak on purpose: size+mtime describes the file without reading it twice.+ expect(index.headers.get("etag")).toMatch(/^W\/"\d+-\d+"$/);++ const asset = await t.app.request("/assets/index-abc123.js");+ expect(asset.status).toBe(200);+ expect(asset.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");+ // The asset rule keys off the SERVED path, which on this branch is rebuilt from the+ // filesystem path — on Windows with backslashes, if nothing normalizes it.+ expect(asset.headers.get("etag")).toBeTruthy();+ });++ it("revalidates the SPA fallback as index.html", async () => {+ const index = await t.app.request("/");+ const fallback = await t.app.request("/chat/new");+ expect(fallback.status).toBe(200);+ expect(fallback.headers.get("cache-control")).toBe("no-cache");+ expect(fallback.headers.get("etag")).toBe(index.headers.get("etag"));+ });++ it("answers 304 on a match, and 200 once the file changes", async () => {+ const etag = (await t.app.request("/")).headers.get("etag")!;+ const same = await t.app.request("/", { headers: { "if-none-match": etag } });+ expect(same.status).toBe(304);+ expect(await same.text()).toBe("");++ // A different length moves the validator without depending on clock resolution — an+ // mtime-only change can land inside the same millisecond on a fast filesystem.+ await fs.writeFile(path.join(webDist, "index.html"), "<html>disk v2 (longer)</html>");+ const after = await t.app.request("/", { headers: { "if-none-match": etag } });+ expect(after.status).toBe(200);+ expect(await after.text()).toContain("v2");+ expect(after.headers.get("etag")).not.toBe(etag);+ });+});