The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): render code blocks plain when the highlighter chunk fails to load
Brooklyn Nicholsond0fefc69c370
diff --git a/apps/desktop/src/components/chat/shiki-chunk-boundary.tsx b/apps/desktop/src/components/chat/shiki-chunk-boundary.tsxnew file mode 100644index 00000000000..125a18882d4--- /dev/null+++ b/apps/desktop/src/components/chat/shiki-chunk-boundary.tsx@@ -0,0 +1,70 @@+import { Component, type ReactNode } from 'react'++// Chromium/Electron: "TypeError: Failed to fetch dynamically imported+// module: …". Vite also emits "error loading a dynamically imported module",+// Safari "a module that couldn't be instantiated" — all three are+// transport/packaging failures (missing chunk in the bundle, asar/asar.unpacked+// mismatch, install mid-update), never code bugs. Narrow to every spelling so+// a genuine render throw is never claimed as a chunk failure.+const CHUNK_LOAD_ERROR =+ /Failed to fetch dynamically imported module|error loading a dynamically imported module|Dynamically imported module .*couldn't be instantiated/u++/** A failed lazy-chunk fetch (missing/broken bundle piece), not a code bug. */+export function isChunkLoadError(error: unknown): boolean {+ return error instanceof Error && CHUNK_LOAD_ERROR.test(error.message)+}++interface ShikiChunkBoundaryProps {+ children: ReactNode+ /** Rendered in place of the lazy subtree when its chunk fails to load. */+ fallback: ReactNode+}++/**+ * Error boundary for a lazily-imported renderer whose FAILURE TO LOAD must+ * degrade to plain content instead of unwinding (#95995). React.Suspense+ * covers only the pending import; a rejection re-throws at render and, for+ * chat code fences, reached `markdown-render` (markdown-text.tsx), whose+ * HugeTextFallback collapsed the WHOLE reply into a raw-Markdown panel+ * because one fence couldn't load its highlighter — 229 such catches in one+ * reporter's desktop.log, all `Failed to fetch dynamically imported module:+ * …shiki-block-Dcm1B2nM.js`.+ *+ * Same re-throw pattern as MessageRenderBoundary: it swallows ONLY the+ * chunk-load class. Any other render error re-throws and keeps its trip to+ * the message-level boundary, logged to desktop.log with a component stack —+ * exactly as before this boundary existed.+ */+export class ShikiChunkBoundary extends Component<ShikiChunkBoundaryProps, { error: unknown | null }> {+ state: { error: unknown | null } = { error: null }++ static getDerivedStateFromError(error: unknown) {+ return { error }+ }++ componentDidCatch(error: unknown) {+ if (isChunkLoadError(error)) {+ // One warn per caught block keeps the failure diagnosable. The+ // degraded render below is the handled outcome, not a crash, so this+ // stays a warn — the reporter's 229-error session log was the problem+ // this fix exists to make survivable.+ console.warn('[shiki-block] highlighter chunk failed to load; rendering code unhighlighted', error)+ }+ }++ render() {+ const { error } = this.state++ if (error === null) {+ return this.props.children+ }++ // Only the chunk-load failure is ours to degrade; a real render bug+ // must still reach `markdown-render`.+ if (!isChunkLoadError(error)) {+ throw error+ }++ return this.props.fallback+ }+}diff --git a/apps/desktop/src/components/chat/shiki-highlighter.test.tsx b/apps/desktop/src/components/chat/shiki-highlighter.test.tsxnew file mode 100644index 00000000000..cf5f57afd1b--- /dev/null+++ b/apps/desktop/src/components/chat/shiki-highlighter.test.tsx@@ -0,0 +1,104 @@+import { act, cleanup, render } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++// Regression coverage for #95995: a failed dynamic import of the lazily-loaded+// Shiki code-block chunk (missing from a packaged app bundle — the reporter's+// desktop.log shows 229× `Failed to fetch dynamically imported module:+// …shiki-block-Dcm1B2nM.js`) rejects the `React.lazy()` promise. React.Suspense+// only covers the *pending* state, so the rejection threw past it to the+// `markdown-render` boundary, whose fallback collapses the WHOLE reply into+// the HugeTextFallback raw-Markdown panel. The block-local ShikiChunkBoundary+// now degrades just the fence to plain unhighlighted code.+//+// The mock resolves to a component that throws the fetch error during render —+// the same way React surfaces a rejected lazy payload (a rejected import+// re-throws at render time). Do NOT throw inside the factory itself: a+// throwing factory leaves rejected promises in the vitest mocker registry,+// and under CI load one escapes as an "unhandled error during the test run"+// attributed to whichever sibling test file the worker is running (#94415).+const { chunkError } = vi.hoisted(() => ({+ chunkError: new Error(+ 'Failed to fetch dynamically imported module: file:///Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist/assets/shiki-block-Dcm1B2nM.js'+ )+}))++vi.mock('./shiki-block', () => ({+ default: () => {+ throw chunkError+ }+}))++import { MarkdownTextContent } from '@/components/assistant-ui/markdown-text'++import { LazyShiki } from './shiki-highlighter'++afterEach(cleanup)++const MESSAGE = [+ '# Deploy checklist', '',+ 'Run the migration before swapping traffic:', '',+ '```bash',+ 'psql -f migrate.sql',+ '```', '',+ 'Then watch the logs until the pool is warm.'+].join('\n')++// Renders through the REAL message pipeline (Streamdown + the markdown-render+// boundary), the way the packaged app hit it: prose renders rich, and only the+// code block degrades to plain text — no HugeTextFallback panel.+describe('a reply survives a failed shiki-block chunk load (#95995)', () => {+ it('keeps prose rendered and shows the code block as plain text', async () => {+ // React 19 reports boundary-caught errors through console.error in dev —+ // silence that; what matters is what the boundary logged and rendered.+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ try {+ const { container } = render(<MarkdownTextContent isRunning={false} text={MESSAGE} />)++ // The rejection settles a tick after the initial Suspense-pending render+ // (which coincidentally shows the same plain text already) — give it+ // real time to propagate before asserting nothing regressed.+ await act(() => new Promise(resolve => setTimeout(resolve, 300)))++ // Prose is still rendered rich: a real heading, not raw markdown inside+ // the bordered font-mono HugeTextFallback panel (which renders no <h1>).+ expect(container.querySelector('h1')?.textContent).toBe('Deploy checklist')+ expect(container.textContent).toContain('Run the migration')+ // The raw fence marker is gone — markdown parsed, not passthrough.+ expect(container.textContent).not.toContain('```bash')++ // The fence degraded to plain code: content present, still inside the+ // code card the app renders before highlight lands.+ expect(container.querySelector('[data-slot="code-card"]')).not.toBeNull()+ expect(container.textContent).toContain('psql -f migrate.sql')++ // The failure stays diagnosable: one warn per caught block, not the+ // reporter's 229-error storm.+ expect(warnSpy).toHaveBeenCalledTimes(1)+ } finally {+ errorSpy.mockRestore()+ warnSpy.mockRestore()+ }+ })++ it('re-throws a genuine render error so markdown-render still catches it', () => {+ // Same mock, different error: only the chunk-load failure class is ours to+ // degrade. A real render bug must keep its trip to the message-level+ // boundary (logged with a component stack, HugeTextFallback if it throws+ // again), exactly as before this boundary existed.+ chunkError.message = 'grammar tokenizer exploded'++ const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined)++ try {+ expect(() => render(<LazyShiki code="const a = 1" language="typescript" />)).toThrow(+ 'grammar tokenizer exploded'+ )+ } finally {+ spy.mockRestore()+ chunkError.message =+ 'Failed to fetch dynamically imported module: file:///Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist/assets/shiki-block-Dcm1B2nM.js'+ }+ })+})diff --git a/apps/desktop/src/components/chat/shiki-highlighter.tsx b/apps/desktop/src/components/chat/shiki-highlighter.tsxindex a5a45661203..62f81a3739b 100644--- a/apps/desktop/src/components/chat/shiki-highlighter.tsx+++ b/apps/desktop/src/components/chat/shiki-highlighter.tsx@@ -15,6 +15,7 @@ import { useI18n } from '@/i18n'import { isLikelyProseCodeBlock } from '@/lib/markdown-code'import type { CachedShikiBlockProps } from './shiki-block'+import { isChunkLoadError, ShikiChunkBoundary } from './shiki-chunk-boundary'import { PlainShiki } from './shiki-plain'export { SHIKI_COLOR_REPLACEMENTS, SHIKI_THEME } from '@/components/chat/shiki-config'@@ -47,21 +48,48 @@ const MAX_HIGHLIGHT_LINES = 3_000const CHUNK_LINES = 200const EST_LINE_PX = 16+// A rejected `import('./shiki-block')` re-throws at render time, past+// Suspense (which only covers the pending state), to the nearest boundary —+// for chat messages that's `markdown-render` (markdown-text.tsx), whose+// fallback degrades the WHOLE reply to a raw-Markdown panel because one fence+// couldn't load its highlighter (#95995: 229 such catches in the reporter's+// desktop.log, all `Failed to fetch dynamically imported module:+// …shiki-block-Dcm1B2nM.js`). Chunk-load failures get exactly one retry —+// some are transient (renderer suspending mid-fetch, asar unpack racing the+// first highlight) — and ShikiChunkBoundary below degrades any persistent+// failure to plain code instead of letting it take the message down.+function importShikiBlock() {+ return import('./shiki-block').catch((error: unknown) => {+ if (isChunkLoadError(error)) {+ return import('./shiki-block')+ }++ throw error+ })+}+// shiki (and through it the multi-MB grammar/theme/wasm bundle) is the// heaviest dependency in the renderer. `shiki-block.tsx` is its only static// importer, so this lazy() is the single seam that keeps shiki out of the// entry chunk — it loads on the first highlighted code block, not at boot.// The lazy module is cache-aware (#95595): unchanged blocks paint from a// content-keyed cache instead of re-tokenizing on every mount.-const ShikiBlock = lazy(() => import('./shiki-block'))+const ShikiBlock = lazy(importShikiBlock)/** Suspends on first use and renders the code as plain preformatted text* until the shiki chunk arrives. Highlighted output is cached by- * (theme, language, code), so revisits never re-tokenize (#95595). */+ * (theme, language, code), so revisits never re-tokenize (#95595).+ *+ * A chunk that fails to LOAD (as opposed to render) is caught locally: the+ * fence degrades to the same plain block the Suspense fallback shows, the+ * warn in ShikiChunkBoundary keeps desktop.log diagnosable, and the rest of+ * the message keeps rendering through Streamdown (#95995). */export const LazyShiki: FC<CachedShikiBlockProps> = ({ language, code, theme, colorReplacements }) => (- <Suspense fallback={<PlainShiki code={code} />}>- <ShikiBlock code={code} colorReplacements={colorReplacements} language={language} theme={theme} />- </Suspense>+ <ShikiChunkBoundary fallback={<PlainShiki code={code} />}>+ <Suspense fallback={<PlainShiki code={code} />}>+ <ShikiBlock code={code} colorReplacements={colorReplacements} language={language} theme={theme} />+ </Suspense>+ </ShikiChunkBoundary>)export function exceedsHighlightBudget(code: string): boolean {