From d7e30b403edc58f387486b70515b7dee7411bc84 Mon Sep 17 00:00:00 2001
From: chengyongru <61816729+chengyongru@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:10:38 +0800
Subject: [PATCH] perf(webui): avoid redundant diff bundle assets (#6711)
---
webui/browser/file-diff-fixture.tsx | 8 +++-
webui/browser/file-diff.spec.ts | 9 ++++
webui/browser/fixture.tsx | 2 +-
webui/vite.config.ts | 67 ++++++++++++++++++++++++-----
4 files changed, 72 insertions(+), 14 deletions(-)
diff --git a/webui/browser/file-diff-fixture.tsx b/webui/browser/file-diff-fixture.tsx
index 1ec9edd6f..fe9a79d46 100644
--- a/webui/browser/file-diff-fixture.tsx
+++ b/webui/browser/file-diff-fixture.tsx
@@ -25,7 +25,11 @@ const samples: Array<[string, string]> = [
["truncated.ts", patch("truncated.ts", ["+export const truncated = true;"], 0, 1)],
];
-export function FileDiffFixture() {
+const hjsonSample: [string, string] = ["config.hjson", patch("config.hjson", [
+ " # shared settings", " {", "- host: old-server", "+ host: localhost", " }",
+], 4, 4)];
+
+export function FileDiffFixture({ shiki = false }: { shiki?: boolean }) {
const { theme, toggle } = useTheme();
const [opened, setOpened] = useState("");
const [changed, setChanged] = useState(false);
@@ -38,7 +42,7 @@ export function FileDiffFixture() {
- {samples.map(([path, text]) => {
+ {(shiki ? [hjsonSample] : samples).map(([path, text]) => {
const edit: FileEditSummary = {
key: path, path, absolute_path: `/fixture/${path}`, added: 1, deleted: 1,
approximate: false, binary: false, status: "done", pending: false,
diff --git a/webui/browser/file-diff.spec.ts b/webui/browser/file-diff.spec.ts
index 87d27550f..a7fc62059 100644
--- a/webui/browser/file-diff.spec.ts
+++ b/webui/browser/file-diff.spec.ts
@@ -90,6 +90,15 @@ for (const dark of [false, true]) {
}
}
+test("a language without a built-in lexer receives its grammar in the diff worker", async ({ page }) => {
+ const worker = page.waitForEvent("worker");
+ await page.goto("/browser/fixture.html?case=file-diff&shiki");
+ await worker;
+ const config = page.getByRole("region", { name: "config.hjson", exact: true });
+ await expectTokenColor(config, "# shared settings", "--code-comment");
+ await expect(config.locator("[data-line][data-line-type=change-addition]")).toHaveText("host: localhost");
+});
+
test("custom backgrounds remain visible through diff surfaces in both themes", async ({ page }) => {
await page.goto("/browser/fixture.html?case=file-diff");
const diff = page.getByRole("region", { name: "Status.tsx", exact: true }).getByTestId("file-edit-diff");
diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx
index b52d88739..641905640 100644
--- a/webui/browser/fixture.tsx
+++ b/webui/browser/fixture.tsx
@@ -89,7 +89,7 @@ async function loadFixture() {
}
case "file-diff": {
const { FileDiffFixture } = await import("./file-diff-fixture");
- return ;
+ return ;
}
case "file-edit-path": {
const { FileEditPathFixture } = await import("./file-edit-path-fixture");
diff --git a/webui/vite.config.ts b/webui/vite.config.ts
index a20d26f86..8f1d495a2 100644
--- a/webui/vite.config.ts
+++ b/webui/vite.config.ts
@@ -1,4 +1,4 @@
-import { defineConfig, loadEnv, type Plugin } from "vite";
+import { defineConfig, loadEnv, transformWithEsbuild, type Plugin } from "vite";
import react from "@vitejs/plugin-react";
import { readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
@@ -41,19 +41,56 @@ export function entryLazyFeatureImports(imports: string[]): string[] {
);
}
-function guardWebuiEntryChunk(): Plugin {
+function guardWebuiChunkBoundaries(): Plugin {
return {
- name: "nanobot-guard-webui-entry-chunk",
+ name: "nanobot-guard-webui-chunk-boundaries",
apply: "build",
generateBundle(_options, bundle) {
for (const output of Object.values(bundle)) {
- if (output.type !== "chunk" || !output.isEntry) continue;
- const unexpected = entryLazyFeatureImports(output.imports);
- if (unexpected.length > 0) {
- throw new Error(
- `WebUI entry chunk statically imports lazy features: ${unexpected.join(", ")}`,
- );
+ if (output.type !== "chunk") continue;
+ if (output.isEntry) {
+ const unexpected = entryLazyFeatureImports(output.imports);
+ if (unexpected.length > 0) {
+ this.error(`WebUI entry chunk statically imports lazy features: ${unexpected.join(", ")}`);
+ }
}
+ if (!output.moduleIds.some((id) => /\/(?:PierreFileDiff\.tsx|code-highlighter-grammars\.ts)$/.test(id))) continue;
+ const visited = new Set();
+ const pending = [output.fileName];
+ for (const fileName of pending) {
+ if (visited.has(fileName)) continue;
+ visited.add(fileName);
+ if (path.basename(fileName).startsWith("markdown-vendor-")) {
+ this.error(`${output.fileName} statically loads the Markdown parser via ${fileName}`);
+ }
+ const dependency = bundle[fileName];
+ if (dependency?.type === "chunk") pending.push(...dependency.imports);
+ }
+ }
+ },
+ };
+}
+
+const PIERRE_WORKER_MODULES = "/node_modules/@pierre/diffs/dist/worker/";
+
+function specializePierreDiffWorker(): Plugin {
+ return {
+ name: "nanobot-specialize-pierre-diff-worker",
+ enforce: "pre",
+ transform(code, id) {
+ if (!id.includes(PIERRE_WORKER_MODULES) || !code.includes("__DIFFS_WORKER__")) return;
+ // Pierre's pool resolves grammars and themes on the main thread and sends them to the worker.
+ return transformWithEsbuild(code, id, {
+ loader: "js",
+ define: { __DIFFS_WORKER__: "true" },
+ minifySyntax: true,
+ });
+ },
+ generateBundle(_options, bundle) {
+ const chunks = Object.values(bundle).filter((output) => output.type === "chunk");
+ if (!chunks.some((chunk) => chunk.isEntry && chunk.facadeModuleId?.includes(PIERRE_WORKER_MODULES))) return;
+ if (chunks.some((chunk) => chunk.moduleIds.some((id) => /\/node_modules\/@shikijs\/(?:langs|themes)\//.test(id)))) {
+ this.error("Pierre diff Worker bundles Shiki grammars or themes that should come from the main thread");
}
},
};
@@ -85,6 +122,12 @@ export function gzipWebuiAssets(): Plugin {
};
}
+const HTML_SERIALIZER_PACKAGES = [
+ "hast-util-to-html", "hast-util-whitespace", "property-information", "html-void-elements",
+ "comma-separated-tokens", "space-separated-tokens", "stringify-entities", "ccount",
+ "character-entities-html4", "character-entities-legacy", "zwitch",
+];
+
export function webuiManualChunk(id: string): string | undefined {
const locale = /\/webui\/locales\/([^/]+)\.json$/.exec(id)?.[1]
?? /\/src\/i18n\/locales\/([^/]+)\/common\.json$/.exec(id)?.[1];
@@ -109,6 +152,8 @@ export function webuiManualChunk(id: string): string | undefined {
// Streamdown retains a lazy viewer shell, not the native Mermaid engine.
if (id.includes("node_modules/streamdown/dist/mermaid-")) return "markdown-diagrams";
if (id.includes("node_modules/streamdown/dist/highlighted-body-")) return "markdown-code";
+ // Keep the serializer and its dependencies together so syntax highlighting never loads the Markdown parser.
+ if (HTML_SERIALIZER_PACKAGES.some((name) => id.includes(`/node_modules/${name}/`))) return "html-serializer";
if (
id.includes("node_modules/streamdown")
|| id.includes("node_modules/remend")
@@ -133,7 +178,7 @@ export default defineConfig(({ mode }) => {
const hmrPath = "/__nanobot_vite_hmr";
return {
- plugins: [react(), startupSkeleton(), componentGallery(path.resolve(__dirname, "..")), guardWebuiEntryChunk(), gzipWebuiAssets()],
+ plugins: [react(), startupSkeleton(), componentGallery(path.resolve(__dirname, "..")), guardWebuiChunkBoundaries(), gzipWebuiAssets()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
@@ -155,7 +200,7 @@ export default defineConfig(({ mode }) => {
"pele/lazy", "saxes", "css-tree/parser", "css-tree/walker", "css-tree/generator",
],
},
- worker: { format: "es" },
+ worker: { format: "es", plugins: () => [specializePierreDiffWorker()] },
build: {
outDir: path.resolve(__dirname, "../nanobot/web/dist"),
emptyOutDir: true,