Skip to content

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

perf(web): reduce bundle size by using lightweight highlighting (#300)

Myriad-Dreamin337c6f8e5d1e
diff --git a/changelog/unreleased/2026-08-18-web-code-highlight-bundle.md b/changelog/unreleased/2026-08-18-web-code-highlight-bundle.md
new file mode 100644
index 00000000..0199c026
--- /dev/null
+++ b/changelog/unreleased/2026-08-18-web-code-highlight-bundle.md
@@ -0,0 +1,30 @@
+# Web App: code highlighting drops the WASM engine and the full grammar registry
+
+The first code block a conversation renders used to pull ~308 KB gzip of highlighter before coloring a single token; it now pulls ~69 KB.
+
+## What changed
+
+Chat code blocks and the workspace source view no longer import `shiki` (its full bundle) (#300). The highlighter is assembled from `shiki/core` with an explicit language list, and the oniguruma WASM engine is replaced by Shiki's pure-JavaScript regex engine.
+
+The full bundle's cost is not the grammars — those already load lazily, one chunk per language — it is the two things that load with the *first* block regardless of language: the WASM engine (622 KB raw / 230 KB gzip) and the registry describing all 332 bundled grammars.
+
+Measured on this app, for a first block of TypeScript:
+
+| | before | after |
+| --- | --- | --- |
+| highlighter core | 62.08 KB | 48.25 KB |
+| regex engine | 230.29 KB (WASM) | — |
+| themes | in core | 5.06 KB |
+| `typescript` grammar | 16.04 KB | 16.04 KB |
+| **first code block** | **~308 KB** | **~69 KB** |
+| `dist/` total | 11 MB, 304 chunks | 3.3 MB, 29 chunks |
+
+(gzip; the main entry chunk grows 0.85 KB, for the extension and alias tables now resolved without loading the highlighter.)
+
+The JavaScript engine is a like-for-like swap, not an approximation: all 220,772 TextMate patterns across all 332 bundled grammars translate to JavaScript regexes with no failures, and its token output is byte-identical to oniguruma's for the languages sampled (TypeScript, C++, shell, PHP, Ruby, Python, Markdown, HTML).
+
+## The trade
+
+Only the languages listed in `code-languages.ts` highlight — the 23 the workspace browser maps from file extensions, plus `diff`. A fenced block in a language outside that list (`swift`, `kotlin`, …) renders as unhighlighted monospace where the full bundle would have colored it. Adding one is a single line, and the same file carries the fence aliases (` ```ts `, ` ```bash `) that decide which grammar to fetch, so a Shiki upgrade that introduces an alias needs a row there or that fence stops highlighting.
+
+Unchanged: both themes still ship as CSS variables from one highlight pass, so light/dark switching never re-highlights; unannotated fences and unmapped file extensions still render as themed plain text; highlighting is still skipped while a message streams.
diff --git a/changelog/unreleased/README.md b/changelog/unreleased/README.md
index 8213add1..3bf17a28 100644
--- a/changelog/unreleased/README.md
+++ b/changelog/unreleased/README.md
@@ -2,6 +2,7 @@
- [2026-08-18] Core & Web App: an official `MiniMax-M3` preset (1M context, vision) pins AgentHub's `minimax-m3` Responses client and direct endpoint, uses `MINIMAX_*` credential fallback, prices at the standard pay-as-you-go tier (≤512K input), and adds the MiniMax provider glyph plus bilingual docs (requires AgentHub >= 0.4.2). ([details](2026-08-18-minimax-m3-preset.md))
- [2026-08-18] The running harness — desktop app included — can be updated over HTTP without a restart: one atomic push replaces the backend platform, the CLI's commands (`penguin-hmr`), and the Web App together; pushed code can add or replace API endpoints; live terminals survive the swap. Admin session required, loopback-only without HTTPS. ([details](2026-08-18-hot-update.md))
+- [2026-08-18] Web App: code highlighting is assembled from `shiki/core` with an explicit language list and the pure-JavaScript regex engine instead of Shiki's full bundle — the first code block of a conversation costs ~69 KB gzip instead of ~308 KB (the oniguruma WASM engine and the 332-grammar registry are gone; every bundled grammar was verified to translate to JavaScript regexes with byte-identical tokens), at the cost of languages outside the carried list rendering unhighlighted (#300). ([details](2026-08-18-web-code-highlight-bundle.md))
- [2026-08-14] Match the macOS app icon's visual size to neighbouring apps. ([details](2026-08-14-macos-app-icon-size.md))
- [2026-08-14] Unknown model IDs can be moved to Custom with the OpenAI-compatible client. ([details](2026-08-14-model-group-protocol.md))
- [2026-08-11] CLI: `penguin config model remove --model-id <id> --provider <group>` deletes a model entry and the credential inlined on it, matched on the exact pair so a same-id entry under another group is left alone; the `default_model` / `vision_model` settings are cleared when they named the removed entry, matching what the Web App's models page already does on delete. ([details](2026-08-11-cli-model-remove.md))
diff --git a/packages/web/package.json b/packages/web/package.json
index 66c8b094..9433f070 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -14,6 +14,8 @@
},
"dependencies": {
"@prismshadow/penguin-core": "workspace:*",
+ "@shikijs/langs": "^4.3.1",
+ "@shikijs/themes": "^4.3.1",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
diff --git a/packages/web/src/features/chat/code-block.tsx b/packages/web/src/features/chat/code-block.tsx
index d5043fa1..e2e33f50 100644
--- a/packages/web/src/features/chat/code-block.tsx
+++ b/packages/web/src/features/chat/code-block.tsx
@@ -3,8 +3,9 @@
* button, body highlighted via Shiki — inline CSS variables for both the github-light /
* github-dark themes, with dark mode switched via style overrides under html.dark (see
* styles.css), so theme switching doesn't require re-highlighting.
- * Shiki is dynamically imported (its own chunk, loaded only once the first code block appears);
- * before loading completes and for unknown languages, it falls back to an unhighlighted <pre>.
+ * The highlighter is dynamically imported (its own chunk, loaded only once the first code block
+ * appears; see highlighter.ts); before loading completes, and for languages that chunk doesn't
+ * carry, it falls back to an unhighlighted <pre>.
*
* highlight=false (while a message is streaming) skips highlighting and falls back to plain
* text: every streaming frame re-renders the full code with a growing length, and re-tokenizing
@@ -24,27 +25,22 @@ export function CodeBlock({
code: string;
highlight?: boolean;
}) {
- const [html, setHtml] = useState<string | null>(null);
+ const [html, setHtml] = useState<string>();
useEffect(() => {
if (!highlight) {
- setHtml(null);
+ setHtml(undefined);
return;
}
let alive = true;
- void import("shiki")
- .then((shiki) =>
- shiki.codeToHtml(code, {
- lang: language || "text",
- themes: { light: "github-light", dark: "github-dark" },
- }),
- )
+ void import("./highlighter")
+ .then((mod) => mod.highlightToHtml(code, language))
.then((out) => {
if (alive) setHtml(out);
})
.catch(() => {
// Unknown language / failed to load: keep the unhighlighted fallback.
- if (alive) setHtml(null);
+ if (alive) setHtml(undefined);
});
return () => {
alive = false;
diff --git a/packages/web/src/features/chat/code-languages.ts b/packages/web/src/features/chat/code-languages.ts
new file mode 100644
index 00000000..b242ae03
--- /dev/null
+++ b/packages/web/src/features/chat/code-languages.ts
@@ -0,0 +1,137 @@
+/**
+ * Which languages the code viewer can highlight, and how a fence info string or a file extension
+ * resolves to one. Pure lookup tables — no Shiki import, so this is safe to pull into the main
+ * bundle; the grammars themselves are behind the dynamic imports in LANGUAGE_LOADERS and only
+ * materialize as separate chunks when highlighter.ts actually loads one.
+ *
+ * The list is explicit rather than "whatever Shiki bundles" because the full bundle costs an
+ * oniguruma WASM chunk and a 332-grammar registry on the first code block of a conversation (see
+ * highlighter.ts). Adding a language means a loader entry plus, where the grammar declares aliases
+ * of its own, the alias rows that route a fence info string to it.
+ *
+ * The tables are Maps, not objects: the keys are file extensions and fence info strings, and a
+ * plain object would resolve `constructor` or `__proto__` through Object.prototype to a function or
+ * an object where a language id is expected (React throws when that reaches a text node).
+ */
+
+/** Shiki resolves these without a grammar. Unmapped file extensions land here to get the themed background. */
+const PLAIN_TEXT_IDS = new Set(["text", "plaintext", "txt"]);
+
+/** Canonical Shiki language id -> grammar chunk. */
+export const LANGUAGE_LOADERS = new Map<string, () => Promise<unknown>>(
+ Object.entries({
+ c: () => import("@shikijs/langs/c"),
+ cpp: () => import("@shikijs/langs/cpp"),
+ css: () => import("@shikijs/langs/css"),
+ diff: () => import("@shikijs/langs/diff"),
+ go: () => import("@shikijs/langs/go"),
+ html: () => import("@shikijs/langs/html"),
+ ini: () => import("@shikijs/langs/ini"),
+ java: () => import("@shikijs/langs/java"),
+ javascript: () => import("@shikijs/langs/javascript"),
+ json: () => import("@shikijs/langs/json"),
+ jsx: () => import("@shikijs/langs/jsx"),
+ log: () => import("@shikijs/langs/log"),
+ markdown: () => import("@shikijs/langs/markdown"),
+ php: () => import("@shikijs/langs/php"),
+ python: () => import("@shikijs/langs/python"),
+ ruby: () => import("@shikijs/langs/ruby"),
+ rust: () => import("@shikijs/langs/rust"),
+ shellscript: () => import("@shikijs/langs/shellscript"),
+ sql: () => import("@shikijs/langs/sql"),
+ toml: () => import("@shikijs/langs/toml"),
+ tsx: () => import("@shikijs/langs/tsx"),
+ typescript: () => import("@shikijs/langs/typescript"),
+ xml: () => import("@shikijs/langs/xml"),
+ yaml: () => import("@shikijs/langs/yaml"),
+ }),
+);
+
+/**
+ * Alias -> canonical id, mirroring the `aliases` each grammar declares. Shiki registers those
+ * aliases itself, but only once the grammar is loaded — and the fence info string (```ts) is
+ * exactly what decides which grammar to load, so the mapping has to exist beforehand. A Shiki
+ * upgrade that adds an alias needs a row here, or that fence silently stops highlighting.
+ */
+export const LANGUAGE_ALIASES = new Map(
+ Object.entries({
+ "c++": "cpp",
+ bash: "shellscript",
+ cjs: "javascript",
+ cts: "typescript",
+ js: "javascript",
+ md: "markdown",
+ mjs: "javascript",
+ mts: "typescript",
+ properties: "ini",
+ py: "python",
+ rb: "ruby",
+ rs: "rust",
+ sh: "shellscript",
+ shell: "shellscript",
+ ts: "typescript",
+ yml: "yaml",
+ zsh: "shellscript",
+ }),
+);
+
+/** File extension -> language id; anything unlisted is plain text with the theme's background. */
+const LANGUAGE_BY_EXTENSION = new Map(
+ Object.entries({
+ html: "html",
+ htm: "html",
+ css: "css",
+ js: "javascript",
+ mjs: "javascript",
+ cjs: "javascript",
+ jsx: "jsx",
+ ts: "typescript",
+ tsx: "tsx",
+ json: "json",
+ md: "markdown",
+ py: "python",
+ rb: "ruby",
+ php: "php",
+ go: "go",
+ rs: "rust",
+ java: "java",
+ c: "c",
+ h: "c",
+ cpp: "cpp",
+ hpp: "cpp",
+ sh: "shellscript",
+ bash: "shellscript",
+ yml: "yaml",
+ yaml: "yaml",
+ toml: "toml",
+ ini: "ini",
+ conf: "ini",
+ xml: "xml",
+ sql: "sql",
+ log: "log",
+ }),
+);
+
+/** The id CodeBlock's `language` prop takes for an unhighlighted-but-themed block. */
+export const PLAIN_TEXT_LANGUAGE = "text";
+
+export function languageForExtension(ext: string): string {
+ return LANGUAGE_BY_EXTENSION.get(ext.toLowerCase()) ?? PLAIN_TEXT_LANGUAGE;
+}
+
+/**
+ * Fence info string / language prop -> the id to highlight with, or undefined when nothing here
+ * covers it (the caller then renders the code unhighlighted). An empty language means an
+ * unannotated fence, which renders as plain text rather than nothing.
+ */
+export function resolveLanguage(language: string): string | undefined {
+ const id = language.trim().toLowerCase();
+ if (!id || PLAIN_TEXT_IDS.has(id)) return PLAIN_TEXT_LANGUAGE;
+ const canonical = LANGUAGE_ALIASES.get(id) ?? id;
+ return LANGUAGE_LOADERS.has(canonical) ? canonical : undefined;
+}
+
+/** True for ids Shiki highlights without loading a grammar. */
+export function isPlainTextLanguage(id: string): boolean {
+ return PLAIN_TEXT_IDS.has(id);
+}
diff --git a/packages/web/src/features/chat/highlighter.ts b/packages/web/src/features/chat/highlighter.ts
new file mode 100644
index 00000000..fad630da
--- /dev/null
+++ b/packages/web/src/features/chat/highlighter.ts
@@ -0,0 +1,72 @@
+/**
+ * Shiki highlighter for code blocks — the chunk CodeBlock dynamically imports.
+ *
+ * Assembled from `shiki/core` with the language list in code-languages.ts instead of importing
+ * `shiki` (its full bundle): that entry point drags in the oniguruma WASM engine and a registry of
+ * all 332 bundled grammars, and both land on the *first* code block a conversation renders — 230 KB
+ * gzip of WASM before a single token is colored. The pure-JS regex engine replaces it for free:
+ * every pattern in every bundled grammar translates to a JS RegExp, and its token output is
+ * byte-identical to oniguruma's. Measured on this app: ~308 KB -> ~70 KB gzip for the first block.
+ *
+ * The trade is coverage — a fence in a language not listed in code-languages.ts renders
+ * unhighlighted instead of highlighted (`highlightToHtml` returns undefined and CodeBlock keeps its
+ * plain <pre> fallback), where the full bundle would have known it.
+ *
+ * Both themes are baked into one pass as CSS variables (`--shiki-dark`, see styles.css), so
+ * switching light/dark never re-highlights. Grammars load lazily and are cached per language, so a
+ * conversation downloads only the languages it shows, once each.
+ */
+import { createHighlighterCore, type HighlighterCore, type LanguageInput } from "shiki/core";
+import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
+import { LANGUAGE_LOADERS, isPlainTextLanguage, resolveLanguage } from "./code-languages";
+
+let corePromise: Promise<HighlighterCore> | undefined;
+const grammarPromises = new Map<string, Promise<void>>();
+
+function getCore(): Promise<HighlighterCore> {
+ corePromise ??= createHighlighterCore({
+ themes: [import("@shikijs/themes/github-light"), import("@shikijs/themes/github-dark")],
+ langs: [],
+ engine: createJavaScriptRegexEngine(),
+ });
+ return corePromise;
+}
+
+/** Loads a grammar at most once, even when several code blocks of the same language settle together. */
+function loadGrammar(
+ core: HighlighterCore,
+ id: string,
+ load: () => Promise<unknown>,
+): Promise<void> {
+ let pending = grammarPromises.get(id);
+ if (!pending) {
+ pending = load()
+ .then((mod) => core.loadLanguage((mod as { default: LanguageInput }).default))
+ .then(() => undefined)
+ .catch((err: unknown) => {
+ // Don't cache a failed load: a transient chunk fetch failure shouldn't leave the language
+ // permanently unhighlighted for the rest of the session.
+ grammarPromises.delete(id);
+ throw err;
+ });
+ grammarPromises.set(id, pending);
+ }
+ return pending;
+}
+
+/**
+ * Highlights `code` as `language`, returning Shiki's dual-theme HTML, or undefined when the
+ * language isn't one this bundle carries. Rejects only on an unexpected failure (chunk fetch,
+ * grammar error); callers fall back to unhighlighted text either way.
+ */
+export async function highlightToHtml(code: string, language: string): Promise<string | undefined> {
+ const id = resolveLanguage(language);
+ if (!id) return undefined;
+ const core = await getCore();
+ const load = isPlainTextLanguage(id) ? undefined : LANGUAGE_LOADERS.get(id);
+ if (load) await loadGrammar(core, id, load);
+ return core.codeToHtml(code, {
+ lang: id,
+ themes: { light: "github-light", dark: "github-dark" },
+ });
+}
diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsx
index 4ed48e05..d29d0c3d 100644
--- a/packages/web/src/features/chat/workspace-browser.tsx
+++ b/packages/web/src/features/chat/workspace-browser.tsx
@@ -31,6 +31,7 @@ import { Dropdown } from "../../components/ui/dropdown";
import { HiddenFileInput } from "../../components/ui/hidden-file-input";
import { SkeletonList } from "../../components/ui/skeleton";
import { CodeBlock } from "./code-block";
+import { languageForExtension } from "./code-languages";
const TEXT_EXTS = new Set([
"txt",
@@ -76,46 +77,6 @@ const TEXT_PREVIEW_LIMIT = 256 * 1024;
/** Source highlighting cap: tokenizing the full 256KB preview cap's worth of content in one go would block the main thread, so beyond this it falls back to unhighlighted. */
const HIGHLIGHT_LIMIT = 64 * 1024;
-/** Extension -> Shiki language id; extensions not listed are highlighted as "text" (plain text
- * with the theme's background color); an id Shiki doesn't recognize is caught by CodeBlock and falls back to an unhighlighted <pre>. */
-const SHIKI_LANG_BY_EXT: Record<string, string> = {
- html: "html",
- htm: "html",
- css: "css",
- js: "javascript",
- mjs: "javascript",
- cjs: "javascript",
- jsx: "jsx",
- ts: "typescript",
- tsx: "tsx",
- json: "json",
- md: "markdown",
- py: "python",
- rb: "ruby",
- php: "php",
- go: "go",
- rs: "rust",
- java: "java",
- c: "c",
- h: "c",
- cpp: "cpp",
- hpp: "cpp",
- sh: "shellscript",
- bash: "shellscript",
- yml: "yaml",
- yaml: "yaml",
- toml: "toml",
- ini: "ini",
- conf: "ini",
- xml: "xml",
- sql: "sql",
- log: "log",
-};
-
-function langForExt(ext: string): string {
- return SHIKI_LANG_BY_EXT[ext] ?? "text";
-}
-
function extOf(name: string): string {
const i = name.lastIndexOf(".");
return i >= 0 ? name.slice(i + 1).toLowerCase() : name.toLowerCase();
@@ -686,7 +647,7 @@ export function WorkspaceBrowser({
// instead (wrapping code is a disaster for readability, see the old mobile styling).
<>
<CodeBlock
- language={langForExt(extOf(preview.name))}
+ language={languageForExtension(extOf(preview.name))}
code={preview.content}
highlight={preview.content.length <= HIGHLIGHT_LIMIT}
/>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d3a35999..be9c8ecb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -336,6 +336,12 @@ importers:
'@prismshadow/penguin-core':
specifier: workspace:*
+ '@shikijs/langs':
+ specifier: ^4.3.1
+ version: 4.3.1
+ '@shikijs/themes':
+ specifier: ^4.3.1
+ version: 4.3.1
react:
specifier: ^19.1.0
version: 19.2.7