perf(webui): avoid redundant diff bundle assets (#6711)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 00:10:38 +08:00
1 parent 995f9e36c1
commit d7e30b403e
4 files changed
+72 -14

No files matched your search

+6 -2
View File
@@ -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() {
<button onClick={toggle}>Toggle theme</button>
<button onClick={() => setChanged(true)}>Change source</button>
<button onClick={() => void setAppLanguage("zh-CN")}>Chinese</button>
{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,
+9
View File
@@ -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");
+1 -1
View File
@@ -89,7 +89,7 @@ async function loadFixture() {
}
case "file-diff": {
const { FileDiffFixture } = await import("./file-diff-fixture");
return <FileDiffFixture />;
return <FileDiffFixture shiki={parameters.has("shiki")} />;
}
case "file-edit-path": {
const { FileEditPathFixture } = await import("./file-edit-path-fixture");
+56 -11
View File
@@ -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<string>();
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,