Skip to content

The agent that grows with you

fix(desktop): teach the torn-bundle guard to see missing lazy chunks

Tekniumc7f1f4d6e91e
diff --git a/apps/desktop/electron/renderer-bundle.test.ts b/apps/desktop/electron/renderer-bundle.test.ts
index 1e12389f162..827d6418873 100644
--- a/apps/desktop/electron/renderer-bundle.test.ts
+++ b/apps/desktop/electron/renderer-bundle.test.ts
@@ -3,7 +3,12 @@ import path from 'node:path'
import { test } from 'vitest'
-import { missingRendererAssets, parseModuleAssetRefs, type RendererBundleDeps } from './renderer-bundle'
+import {
+ missingRendererAssets,
+ parseLazyChunkRefs,
+ parseModuleAssetRefs,
+ type RendererBundleDeps
+} from './renderer-bundle'
// A production-shaped index.html: the module entry Vite emits plus a
// modulepreload for a lazy chunk. These are the refs the browser fetches
@@ -133,3 +138,121 @@ test('missingRendererAssets: an index naming nothing checkable is not torn', ()
assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), [])
})
+
+// ---------------------------------------------------------------------------
+// Lazy-chunk (__vite__mapDeps) awareness — #93479. index.html only names the
+// boot-critical modules; the chunks behind React.lazy() routes (syntax-diff-*,
+// shiki-*, mermaid-embed-*) live in each chunk's inline __vite__mapDeps table.
+// A torn install whose preloads are intact but whose lazy chunks are missing
+// used to pass the generation check and die on the first lazy import.
+// ---------------------------------------------------------------------------
+
+// Production-shaped Vite output: the deps table definition plus an index-only
+// call site that must NOT be misread as a filename list.
+const ENTRY_JS = [
+ 'const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=[',
+ '"assets/syntax-diff-Bo0962zh.js","assets/shiki-block-COiz1pEN.js","assets/mermaid-embed-Cq7Xw2aa.js"',
+ '])))=>i.map(i=>d[i]);',
+ 'const load=()=>import("./syntax-diff").then(m=>m.default);',
+ '__vite__mapDeps([0,1])'
+].join('\n')
+
+test('parseLazyChunkRefs reads the __vite__mapDeps filename table, not call sites', () => {
+ assert.deepEqual(parseLazyChunkRefs(ENTRY_JS), [
+ 'assets/syntax-diff-Bo0962zh.js',
+ 'assets/shiki-block-COiz1pEN.js',
+ 'assets/mermaid-embed-Cq7Xw2aa.js'
+ ])
+})
+
+test('parseLazyChunkRefs returns [] for chunk-free/nullish js', () => {
+ assert.deepEqual(parseLazyChunkRefs(''), [])
+ assert.deepEqual(parseLazyChunkRefs(undefined as unknown as string), [])
+ assert.deepEqual(parseLazyChunkRefs('console.log("no deps table here")'), [])
+})
+
+// deps helper for the graph walk: per-file contents, not one shared html.
+function graphDepsFor(indexDir: string, files: Record<string, string>): RendererBundleDeps {
+ const byPath = new Map(Object.entries(files).map(([rel, content]) => [path.join(indexDir, rel), content]))
+
+ return {
+ readFileSync: (file: string) => {
+ const content = byPath.get(file)
+
+ if (content === undefined) {
+ throw new Error(`ENOENT: ${file}`)
+ }
+
+ return content
+ },
+ existsSync: (file: string) => byPath.has(file)
+ }
+}
+
+const GRAPH_INDEX_HTML = [
+ '<!doctype html>',
+ '<script type="module" crossorigin src="./assets/index-a1b2c3.js"></script>'
+].join('\n')
+
+test('missingRendererAssets: generation with all lazy chunks present is intact', () => {
+ const deps = graphDepsFor(INDEX_DIR, {
+ 'index.html': GRAPH_INDEX_HTML,
+ 'assets/index-a1b2c3.js': ENTRY_JS,
+ 'assets/syntax-diff-Bo0962zh.js': '// present',
+ 'assets/shiki-block-COiz1pEN.js': '// present',
+ 'assets/mermaid-embed-Cq7Xw2aa.js': '// present'
+ })
+
+ assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), [])
+})
+
+test('missingRendererAssets: torn lazy chunk is detected even when every preload exists', () => {
+ // The exact #93479 shape: index.html's own module list checks out, but the
+ // syntax-diff chunk behind React.lazy() never landed. Loading this copy
+ // boots fine and then blanks the workspace on the first diff render.
+ const deps = graphDepsFor(INDEX_DIR, {
+ 'index.html': GRAPH_INDEX_HTML,
+ 'assets/index-a1b2c3.js': ENTRY_JS,
+ 'assets/shiki-block-COiz1pEN.js': '// present',
+ 'assets/mermaid-embed-Cq7Xw2aa.js': '// present'
+ })
+
+ assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), ['assets/syntax-diff-Bo0962zh.js'])
+})
+
+test('missingRendererAssets: walks transitive map-deps without looping on cycles', () => {
+ // A lazy chunk can carry its own deps table (shiki language chunks do).
+ // The walk must follow it — and a mutual reference must not hang the boot.
+ const deps = graphDepsFor(INDEX_DIR, {
+ 'index.html': GRAPH_INDEX_HTML,
+ 'assets/index-a1b2c3.js': [
+ 'const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/level-one-aaa.js"])))=>i.map(i=>d[i]);'
+ ].join('\n'),
+ 'assets/level-one-aaa.js': [
+ 'const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=[',
+ '"assets/index-a1b2c3.js","assets/level-two-bbb.js"',
+ '])))=>i.map(i=>d[i]);'
+ ].join('\n')
+ })
+
+ assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), ['assets/level-two-bbb.js'])
+})
+
+test('missingRendererAssets: a lazy-chunk-torn copy loses to an intact copy end to end', () => {
+ // The resolver contract: the same generation check that orders app.asar vs
+ // app.asar.unpacked must now see lazy-chunk tears too, so a torn candidate
+ // is skipped instead of shipping a delayed "Failed to fetch dynamically
+ // imported module" crash.
+ const files = {
+ 'index.html': GRAPH_INDEX_HTML,
+ 'assets/index-a1b2c3.js': ENTRY_JS,
+ 'assets/shiki-block-COiz1pEN.js': '// present',
+ 'assets/mermaid-embed-Cq7Xw2aa.js': '// present'
+ }
+
+ const torn = graphDepsFor(INDEX_DIR, files)
+ const intact = graphDepsFor(INDEX_DIR, { ...files, 'assets/syntax-diff-Bo0962zh.js': '// present' })
+
+ assert.notDeepEqual(missingRendererAssets(INDEX_PATH, torn), [])
+ assert.deepEqual(missingRendererAssets(INDEX_PATH, intact), [])
+})
diff --git a/apps/desktop/electron/renderer-bundle.ts b/apps/desktop/electron/renderer-bundle.ts
index f977729e8db..e9d3705022b 100644
--- a/apps/desktop/electron/renderer-bundle.ts
+++ b/apps/desktop/electron/renderer-bundle.ts
@@ -43,13 +43,46 @@ export function parseModuleAssetRefs(html: string): string[] {
return refs
}
+// Vite bakes each chunk's lazy-import filenames into an inline
+// `__vite__mapDeps` table — `…(m.f || (m.f = ["assets/syntax-diff-….js", …]))` —
+// and call sites reference the table by index (`__vite__mapDeps([0,1])`).
+// The quoted filenames in that table are the chunks the generation will
+// dynamically import at runtime (syntax-diff-*, shiki-*, mermaid-embed-*, …):
+// exactly the files a torn update leaves dangling AFTER index.html's own
+// preload list checks out. The index-only call sites contain no quoted
+// strings, so this scan matches only the definition's filename table.
+const MAP_DEPS_ARRAY = /__vite__mapDeps[^[\]]{0,300}\[([^\]]*)\]/g
+const QUOTED_REF = /["']([^"']+)["']/g
+
+export function parseLazyChunkRefs(js: string): string[] {
+ const refs = new Set<string>()
+
+ for (const [, body] of String(js ?? '').matchAll(MAP_DEPS_ARRAY)) {
+ for (const [, ref] of body.matchAll(QUOTED_REF)) {
+ // Absolute/CDN URLs aren't part of this bundle's generation.
+ if (!/^[a-z]+:|^\/\//i.test(ref)) {
+ refs.add(ref.replace(/^\.\//, '').split(/[?#]/)[0])
+ }
+ }
+ }
+
+ return [...refs]
+}
+
export interface RendererBundleDeps {
readFileSync?: (file: string, encoding: 'utf8') => string
existsSync?: (file: string) => boolean
}
/**
- * The module files `indexPath` declares but that do not exist beside it.
+ * The module files `indexPath`'s generation declares but that do not exist
+ * beside it — both the boot-critical refs named by index.html itself AND the
+ * lazy chunks those modules will dynamically import later (their inline
+ * `__vite__mapDeps` tables). A torn update can pass the index-level check —
+ * index.html's own preloads all present — and still die minutes later on the
+ * first `React.lazy()` route (#93479: syntax-diff-*, shiki-*,
+ * mermaid-embed-*). Walking the map-deps graph lets the loader skip that
+ * candidate up front instead of shipping a delayed crash.
*
* Empty ⇒ a complete generation (or an index naming nothing checkable — the
* caller's own existence gate owns unreadable/missing files). Non-empty ⇒ torn:
@@ -67,5 +100,60 @@ export function missingRendererAssets(indexPath: string, deps: RendererBundleDep
return []
}
- return parseModuleAssetRefs(html).filter(ref => !existsSync(path.join(dir, ref)))
+ const missing: string[] = []
+ const seen = new Set<string>()
+ const queue = [...parseModuleAssetRefs(html)]
+
+ while (queue.length > 0) {
+ const ref = queue.shift()!
+
+ if (seen.has(ref)) {
+ continue
+ }
+
+ seen.add(ref)
+
+ const file = path.join(dir, ref)
+
+ if (!existsSync(file)) {
+ missing.push(ref)
+ continue
+ }
+
+ // A present JS chunk may still name lazy imports of its own. Read its
+ // __vite__mapDeps table and queue those refs relative to the dir that
+ // owns them (map-deps entries are emitted relative to the chunk's own
+ // directory in older Vite output, and base-relative in newer output —
+ // normalize both to index-dir-relative before the existence check).
+ if (!/\.m?js$/i.test(ref)) {
+ continue
+ }
+
+ let js: string
+
+ try {
+ js = readFileSync(file, 'utf8')
+ } catch {
+ // Unreadable-but-present is the existence gate's concern, same contract
+ // as an unreadable index.html above.
+ continue
+ }
+
+ for (const lazyRef of parseLazyChunkRefs(js)) {
+ const chunkDirRelative = path.join(path.dirname(ref), lazyRef).split(path.sep).join('/')
+
+ // Prefer whichever interpretation lands on a real file; when neither
+ // does, report the index-dir-relative spelling (matches how the
+ // boot-critical refs above are reported).
+ if (existsSync(path.join(dir, lazyRef))) {
+ queue.push(lazyRef)
+ } else if (existsSync(path.join(dir, chunkDirRelative))) {
+ queue.push(chunkDirRelative)
+ } else {
+ queue.push(lazyRef)
+ }
+ }
+ }
+
+ return missing
}