Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

perf(server): compress the static frontend on the way out (#453)

Myriad-Dreaminebb3e1f9d6aa
diff --git a/changelog/unreleased/2026-08-24-static-compression.md b/changelog/unreleased/2026-08-24-static-compression.md
new file mode 100644
index 00000000..5564bfdc
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-static-compression.md
@@ -0,0 +1,34 @@
+# The frontend is compressed on the way out
+
+- **Date:** 2026-08-24
+- **Type:** performance
+- **Scope:** `server`
+
+[中文版](2026-08-24-static-compression.zh.md)
+
+The built app was served uncompressed — over a megabyte of JavaScript on a first load, which is
+the single largest thing that load waits on. It is now negotiated per request: brotli when the
+client offers it, gzip otherwise, and the original bytes for anything that offers neither.
+
+On the current bundle that is **1229 KB → 329 KB**.
+
+Compressed bodies are cached against the ETag, which already identifies one exact
+representation, so a file is compressed once per push rather than once per page load. The cache
+is bounded and evicts oldest-first, since a hot push replaces every file in it.
+
+## What is left alone
+
+Anything already compressed (`png`, `woff2`, `ico`) and anything under 1 KB. Recompressing a PNG
+spends time to send slightly more bytes, and a few hundred bytes rarely shrink past the gzip
+header.
+
+## Correctness notes
+
+- `Accept-Encoding` is parsed rather than substring-matched: `gzip;q=0` is a **refusal**, and
+ reading it as consent would return bytes the client cannot decode.
+- `Vary: Accept-Encoding` is sent on every response that could have varied — including the 304,
+ and including when this particular client took no encoding — so a shared cache cannot hand
+ one client's brotli to another that cannot read it.
+- The compressed form carries a **weak** ETag, as a re-encoding proxy would: it is a different
+ representation of the same thing, which is exactly what a weak validator claims. Revalidation
+ matches from either spelling.
diff --git a/changelog/unreleased/2026-08-24-static-compression.zh.md b/changelog/unreleased/2026-08-24-static-compression.zh.md
new file mode 100644
index 00000000..5b2fede0
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-static-compression.zh.md
@@ -0,0 +1,29 @@
+# 前端资源发送时会压缩了
+
+- **日期:** 2026-08-24
+- **类型:** performance
+- **范围:** `server`
+
+[English](2026-08-24-static-compression.md)
+
+打包后的前端此前不压缩就发出去——首次加载要等一兆多的 JavaScript,这是首屏最大的一笔开销。现在按请求
+协商:客户端支持 brotli 就用 brotli,否则用 gzip,两者都不支持就发原始字节。
+
+以当前的 bundle 计算是 **1229 KB → 329 KB**。
+
+压缩后的内容以 ETag 为键缓存——ETag 本来就精确标识了某一份表示——所以每个文件在每次推送后只压一次,
+而不是每次页面加载压一次。缓存有上限,按最早写入先淘汰,因为一次热推会把里面所有文件全部换掉。
+
+## 不处理的东西
+
+已经压缩过的(`png`、`woff2`、`ico`)和小于 1 KB 的。重压一张 PNG 是花时间换来更多的字节;几百字节的
+内容也很难压过 gzip 头本身。
+
+## 正确性
+
+- `Accept-Encoding` 是解析的,不是字符串包含匹配:`gzip;q=0` 表示**拒绝**,把它当作同意就会返回客户端
+ 解不开的字节。
+- 只要这个响应有可能随编码变化,就会带上 `Vary: Accept-Encoding`——包括 304,也包括这个客户端本次没有
+ 选任何编码的情况——这样共享缓存才不会把一个客户端的 brotli 发给另一个读不了它的客户端。
+- 压缩后的表示带**弱** ETag,和会重新编码的反向代理的做法一致:它是同一内容的另一种表示,而这正是弱
+ 校验符的含义。重新校验时两种写法都能匹配。
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index f2918861..d56799d3 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -17,6 +17,7 @@
* HARD STOP: approvals deny, runs abort, the scheduler dies with its App.
*/
import { createHash } from "node:crypto";
+import zlib from "node:zlib";
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
@@ -561,6 +562,78 @@ function ifNoneMatchHits(header: string | undefined, etag: string): boolean {
return header.split(",").some((tag) => bare(tag) === want);
}
+/**
+ * Extensions worth compressing. Everything absent is either already compressed (png, woff2,
+ * ico) or too small for the round trip to pay for the CPU — recompressing a PNG spends time
+ * to make the response slightly larger.
+ */
+const COMPRESSIBLE = new Set([".html", ".js", ".css", ".json", ".svg", ".map", ".txt"]);
+
+/**
+ * Below this, compression is not worth doing: a few hundred bytes rarely shrink past the
+ * gzip header, and the transfer was never the cost at that size.
+ */
+const COMPRESS_MIN_BYTES = 1024;
+
+/**
+ * The best encoding this client accepts, or null for none.
+ *
+ * Brotli first — on the app bundle it is meaningfully smaller than gzip, and everything that
+ * speaks it also speaks gzip, so the fallback is free. Parsed rather than substring-matched
+ * because `q=0` means REFUSED: a client that sends `gzip;q=0` is saying "not gzip", and a
+ * naive `includes("gzip")` reads that as consent and returns bytes it cannot decode.
+ */
+function pickEncoding(header: string | undefined): "br" | "gzip" | null {
+ if (header === undefined) return null;
+ const accepted = new Set<string>();
+ for (const part of header.split(",")) {
+ const [rawToken, ...params] = part.split(";");
+ const token = (rawToken ?? "").trim().toLowerCase();
+ const q = params.map((p) => /^\s*q=([0-9.]+)\s*$/i.exec(p)).find((m) => m !== null)?.[1];
+ if (q !== undefined && Number.parseFloat(q) === 0) continue;
+ accepted.add(token);
+ }
+ if (accepted.has("br")) return "br";
+ if (accepted.has("gzip")) return "gzip";
+ return null;
+}
+
+/**
+ * Compressed bodies, keyed by `<encoding> <etag>` — the ETag already identifies one exact
+ * representation, so it is the only key this needs, and it changes when the bytes do.
+ *
+ * Cached because the alternative is compressing the same 1.2 MB bundle on every page load.
+ * Bounded and insertion-ordered (oldest evicted first): a dist is tens of files, but a hot
+ * push replaces all of them, and nothing should grow without a ceiling across a long uptime.
+ */
+const COMPRESSED_CACHE_ENTRIES = 128;
+const compressedCache = new Map<string, Buffer>();
+
+function compressedBody(content: Buffer, encoding: "br" | "gzip", etag: string): Buffer {
+ const key = `${encoding} ${etag}`;
+ const hit = compressedCache.get(key);
+ if (hit !== undefined) return hit;
+ const body =
+ encoding === "br"
+ ? zlib.brotliCompressSync(content, {
+ params: {
+ // Text mode and the real size let brotli pick its window; quality 5 is the knee
+ // of the curve — near-max ratio for a fraction of the time of 11, which on a
+ // megabyte is the difference between imperceptible and a visible stall.
+ [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
+ [zlib.constants.BROTLI_PARAM_QUALITY]: 5,
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: content.byteLength,
+ },
+ })
+ : zlib.gzipSync(content, { level: 6 });
+ if (compressedCache.size >= COMPRESSED_CACHE_ENTRIES) {
+ const oldest = compressedCache.keys().next();
+ if (!oldest.done) compressedCache.delete(oldest.value);
+ }
+ compressedCache.set(key, body);
+ return body;
+}
+
/** The static response for one resolved file: 304 on an ETag match, the bytes otherwise. */
function staticResponse(
c: Context<AppEnv>,
@@ -568,16 +641,35 @@ function staticResponse(
servedPath: string,
etag: string,
): Response {
+ const ext = path.extname(servedPath).toLowerCase();
+ const mayCompress = COMPRESSIBLE.has(ext) && content.byteLength >= COMPRESS_MIN_BYTES;
+ // Chosen BEFORE the 304, because it decides which representation is being talked about —
+ // and a 304 has to carry the validator of the one the client would have got.
+ const encoding = mayCompress ? pickEncoding(c.req.header("accept-encoding")) : null;
+ // Weakened when compressed, as a re-encoding proxy would: those bytes are a different
+ // representation of the same thing, and a weak validator is exactly the claim "equivalent,
+ // not identical". Revalidation matches either spelling — ifNoneMatchHits compares weakly.
+ const responseEtag = encoding !== null && !etag.startsWith("W/") ? `W/${etag}` : etag;
const headers: Record<string, string> = {
"Cache-Control": cacheControlFor(servedPath),
- ETag: etag,
+ ETag: responseEtag,
};
+ // Announced whenever the answer COULD have varied — on the 304 too, and even when this
+ // particular client took no encoding: a shared cache keys on what the header says, so
+ // leaving it off is how one client's gzip reaches another that cannot read it.
+ if (mayCompress) headers["Vary"] = "Accept-Encoding";
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 });
+ headers["Content-Type"] = CONTENT_TYPES[ext] ?? "application/octet-stream";
+ if (encoding === null) {
+ return new Response(new Uint8Array(content), { status: 200, headers });
+ }
+ headers["Content-Encoding"] = encoding;
+ return new Response(new Uint8Array(compressedBody(content, encoding, etag)), {
+ status: 200,
+ headers,
+ });
}
/**
diff --git a/packages/server/test/web-static-compression.test.ts b/packages/server/test/web-static-compression.test.ts
new file mode 100644
index 00000000..172dfc00
--- /dev/null
+++ b/packages/server/test/web-static-compression.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Negotiated compression for the static frontend (app.ts).
+ *
+ * The app bundle is over a megabyte of JavaScript and was served uncompressed, which is the
+ * single largest thing a first load waits on. What makes this worth testing rather than
+ * assuming is that every way of getting it wrong produces a response that LOOKS fine:
+ *
+ * - Compressing for a client that did not ask yields bytes it cannot decode — and `q=0` is a
+ * refusal that reads like consent to any substring match.
+ * - Omitting `Vary: Accept-Encoding` lets a shared cache hand one client's gzip to another.
+ * - Recompressing an already-compressed asset spends CPU to send more bytes.
+ */
+import zlib from "node:zlib";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createTestApp, makeTempRoot } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** Comfortably over the compress-worth-it threshold, and highly compressible. */
+const BIG_JS = `console.log("${"x".repeat(4000)}");\n`;
+
+describe("static compression", () => {
+ 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>${"y".repeat(4000)}</html>`);
+ await fs.writeFile(path.join(webDist, "assets", "index-abc123.js"), BIG_JS);
+ // Already compressed, and small: neither should be re-encoded.
+ await fs.writeFile(path.join(webDist, "assets", "logo-abc123.png"), Buffer.alloc(4000, 7));
+ await fs.writeFile(path.join(webDist, "assets", "tiny-abc123.js"), "let a=1;\n");
+ t = await createTestApp({ config: { webDist } });
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ const get = (p: string, accept?: string) =>
+ t.app.request(p, accept === undefined ? undefined : { headers: { "accept-encoding": accept } });
+
+ it("sends brotli when offered, and it round-trips to the original bytes", async () => {
+ const res = await get("/assets/index-abc123.js", "gzip, deflate, br");
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-encoding")).toBe("br");
+ expect(res.headers.get("vary")).toBe("Accept-Encoding");
+ const body = Buffer.from(await res.arrayBuffer());
+ expect(zlib.brotliDecompressSync(body).toString()).toBe(BIG_JS);
+ // The whole point: meaningfully smaller than what was being sent before.
+ expect(body.byteLength).toBeLessThan(BIG_JS.length / 4);
+ });
+
+ it("falls back to gzip, and to nothing at all", async () => {
+ const gz = await get("/assets/index-abc123.js", "gzip");
+ expect(gz.headers.get("content-encoding")).toBe("gzip");
+ expect(zlib.gunzipSync(Buffer.from(await gz.arrayBuffer())).toString()).toBe(BIG_JS);
+
+ const plain = await get("/assets/index-abc123.js");
+ expect(plain.headers.get("content-encoding")).toBeNull();
+ expect(await plain.text()).toBe(BIG_JS);
+ // Vary is still announced: the answer COULD have varied, and a shared cache has to know.
+ expect(plain.headers.get("vary")).toBe("Accept-Encoding");
+ });
+
+ it("reads q=0 as a refusal, not as consent", async () => {
+ // The classic substring bug: `includes("gzip")` returns bytes this client just said it
+ // cannot take, and the failure surfaces as a corrupt script, not as an error.
+ const res = await get("/assets/index-abc123.js", "gzip;q=0");
+ expect(res.headers.get("content-encoding")).toBeNull();
+ expect(await res.text()).toBe(BIG_JS);
+ });
+
+ it("leaves already-compressed and tiny files alone", async () => {
+ const png = await get("/assets/logo-abc123.png", "br, gzip");
+ expect(png.headers.get("content-encoding")).toBeNull();
+ // Not even Vary: this response never depended on Accept-Encoding.
+ expect(png.headers.get("vary")).toBeNull();
+
+ const tiny = await get("/assets/tiny-abc123.js", "br, gzip");
+ expect(tiny.headers.get("content-encoding")).toBeNull();
+ expect(tiny.headers.get("vary")).toBeNull();
+ });
+
+ it("keeps the caching contract, with a weak validator on the compressed form", async () => {
+ const plain = await get("/index.html");
+ const br = await get("/index.html", "br");
+ expect(plain.headers.get("cache-control")).toBe("no-cache");
+ expect(br.headers.get("cache-control")).toBe("no-cache");
+ // Different representations of the same thing, so the compressed one is weak — which is
+ // precisely what a weak validator means.
+ expect(br.headers.get("etag")).toMatch(/^W\//);
+
+ // And revalidation still works from either spelling, including the 304's own tag.
+ const revalidated = await t.app.request("/index.html", {
+ headers: { "accept-encoding": "br", "if-none-match": br.headers.get("etag")! },
+ });
+ expect(revalidated.status).toBe(304);
+ expect(revalidated.headers.get("etag")).toBe(br.headers.get("etag"));
+ expect(revalidated.headers.get("vary")).toBe("Accept-Encoding");
+ });
+});