Skip to content

A full-featured download manager.

perf(build): optimize bundles and desktop deferred loading (#2316)

Dr_rOotad3ea65b2327
diff --git a/.claude/rules/i18n.md b/.claude/rules/i18n.md
index 421ac0cb..83c78e51 100644
--- a/.claude/rules/i18n.md
+++ b/.claude/rules/i18n.md
@@ -20,8 +20,9 @@ locale changes transactional, including rollback on failure.
- `src/shared/locales/en-US.json` is the key-shape source of truth. Add every
logical key to every locale registered in `SUPPORTED_LOCALES`; never update
only a subset.
-- `src/shared/i18n-resources.ts` statically and exhaustively registers those
- locale files. New languages also require a catalog entry in
+- `src/shared/i18n-resources.ts` statically and exhaustively registers loaders for those
+ locale files. Only English and Simplified Chinese are eager; await resource loading before
+ committing a host or renderer language change. New languages also require a catalog entry in
`src/shared/constants/locales.ts` and a matching JSON resource.
- Every translation leaf is a string. Keep readable locale files as UTF-8;
avoid unnecessary `\uXXXX` escapes.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 82cede19..bdbfd3fa 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -59,6 +59,7 @@ jobs:
pnpm exec vitest run
src/shared/constants/locales.test.ts
src/shared/i18n-resources.test.ts
+ src/shared/i18n-resource-loading.test.ts
src/shared/schemas/locale.test.ts
src/shared/protocol/forwardable-events.test.ts
src/core/i18n/locale-coordinator.test.ts
@@ -205,6 +206,7 @@ jobs:
tests/scripts/snap-store-channel.test.ts
tests/scripts/stage-electron-app.test.ts
tests/scripts/audit-server-runtime.test.ts
+ tests/scripts/production-build.test.ts
tests/scripts/docker-server-runtime.test.ts
tests/scripts/server-runtime-workflow.test.ts
tests/scripts/smoke-server-package.test.ts
diff --git a/docs/production-builds.md b/docs/production-builds.md
new file mode 100644
index 00000000..d341b824
--- /dev/null
+++ b/docs/production-builds.md
@@ -0,0 +1,144 @@
+# Production builds
+
+Motrix builds six JavaScript targets: Electron main, preload, the plugin worker,
+the desktop renderer, the web renderer, and the Node server with its operator CLI.
+Their Vite configurations share `scripts/vite-production-output.ts`.
+
+## Output policy
+
+- Production JavaScript is minified, including whitespace in the server's ES
+ library output. Renderer CSS is minified with Lightning CSS.
+- Source documentation and optimizer annotations are removed from emitted
+ JavaScript. Legal comments and the packaged third-party notices are retained.
+- Published builds do not emit source maps. The server preserves function and
+ class names for diagnostics; runtime logging remains available.
+- Only renderer builds copy `public/` icons and images. Host, preload and worker
+ builds exclude these browser assets to avoid duplicate packaged files.
+- Main, preload, and worker entry points remain CommonJS `.cjs` files. Server
+ and CLI entry points remain ES `.mjs` files. Native modules and external
+ dependencies continue to use the existing packaging rules.
+
+## Deferred resources
+
+English and Simplified Chinese translations are loaded with the application.
+The other 24 supported languages are separate chunks shipped inside the desktop
+package and served locally by Motrix Server. Desktop language switching does not
+require an internet connection.
+
+The host and renderer load the requested translation before applying a language
+change. Concurrent requests for the same resource share a load, failed loads can
+be retried, and a slower renderer request cannot overwrite a newer selection.
+The operator CLI loads its selected locale before creating its translator.
+Plugin-provided translations keep their existing lifecycle.
+
+The ELK graph layout engine runs in a dedicated, locally bundled browser Worker.
+Its code stays out of the initial renderer bundle, and parsing and layout do not
+block the UI thread. The engine is shared for the lifetime of the window;
+matching cached graph layouts skip another layout request. Worker errors and
+30-second request timeouts invalidate the engine so the existing Retry action
+can recreate it.
+
+On desktop, entering the plugins page schedules preparation after a 200 ms
+settling delay and an idle opportunity. Pointing at, focusing, or pressing the
+diagnostics link starts preparation immediately. Preparation includes a tiny
+two-node layout and shares initialization with navigation. Leaving the page
+cancels work that has not started; hidden windows skip speculative loading.
+Web clients load the Worker on demand. Dashboard, downloads, settings, and plugin
+routes remain eager; opening the app does not preload every language or feature.
+
+Code splitting reduces the JavaScript parsed at startup. It does not remove
+languages or features from the installed application; extra chunk wrappers can
+slightly increase the total renderer output size.
+
+## Measurement and verification
+
+From the repository root, run:
+
+```bash
+NODE_ENV=production node scripts/measure-production-bundles.mjs
+pnpm exec vitest run tests/scripts/production-build.test.ts
+pnpm build
+pnpm test:e2e e2e/unit-localization.spec.ts e2e/plugin-call-graph.spec.ts
+```
+
+The measurement command builds all six targets in memory and reports raw and
+gzip JavaScript bytes, chunk counts, bundled locales, and startup dependencies.
+Total JavaScript bytes include Worker assets, which Vite emits separately from
+application chunks.
+Initial bytes include all entry chunks and their transitive static imports;
+dynamic imports are excluded. For the server, this is the combined server and
+CLI entry closure, not a measurement of one running process. Gzip bytes sum the
+independently compressed chunks and do not represent an installer size.
+
+CI checks startup and total JavaScript budgets, includes all 26 languages,
+excludes deferred languages and ELK from initial chunks, and rejects emitted
+source maps or public assets copied into host builds. The server fixture test
+also checks that source documentation is removed while legal attribution,
+diagnostic names, and executable behavior survive compression. Platform package
+verification and runtime smoke tests remain the authority for installed sizes
+and native runtime compatibility.
+
+## Desktop navigation comparison
+
+Build each revision with `pnpm build:electron` in a separate checkout with its
+own dependencies. Then run from the candidate checkout:
+
+```bash
+pnpm measure:desktop-navigation --variant baseline=../Motrix-baseline --variant optimized=. --samples 5 --cpu-rates 1,4
+```
+
+The baseline checkout must remain unchanged during the run. Both applications
+run with the same Electron runtime from the candidate checkout. Each observation
+uses a fresh process and temporary profile seeded with the same 48-node,
+90-edge call history. Variant order alternates each round. The report preserves
+all samples at `output/playwright/manual/desktop-navigation/results.json`,
+including application artifact hashes, startup time, settings/downloads/plugins
+navigation, first and repeat graph openings, long tasks, and frame gaps.
+
+Three scenarios distinguish a direct click, pointer intent with 300 ms lead
+time, and 500 ms spent idle on the plugins page. Navigation timing starts at
+programmatic link activation and ends after visible graph nodes and a paint
+opportunity; it excludes automation round trips. The preparation interval is
+measured separately to detect work merely shifted before the click. Renderer
+blocking time sums the portions of long tasks above 50 ms. Frame gaps measure
+`requestAnimationFrame` spacing, not input-to-paint latency.
+
+CPU throttling starts after the shell is ready. It stresses the renderer main
+thread; it does not reproduce slower disks, IPC, or uniformly slower Worker
+execution on a low-end computer. OS file caches are not flushed. Five samples
+per case support a local comparison, not a tail-latency or no-jank guarantee.
+
+Measured on 2026-10-04 with Apple M4 / macOS arm64, Electron 44.5.0 and production
+React. The baseline is `62207e06` (language/code splitting already enabled); the
+candidate adds the dedicated Worker and desktop preparation. There are 60 fresh
+process observations: 5 per variant, CPU rate, and scenario. Times below are
+milliseconds, shown as **median / observed maximum**.
+
+| CPU | First graph scenario | Baseline visible | Optimized visible | Baseline blocking | Optimized blocking |
+| --- | --- | ---: | ---: | ---: | ---: |
+| 1× | Direct click | 145.8 / 145.9 | 129.1 / 129.3 | 12 / 13 | 0 / 0 |
+| 1× | Pointer intent | 169.7 / 172.0 | 95.6 / 103.9 | 13 / 14 | 0 / 0 |
+| 1× | Idle on plugins page | 145.5 / 171.7 | 93.4 / 107.2 | 12 / 15 | 0 / 0 |
+| 4× | Direct click | 488.9 / 491.1 | 241.9 / 256.2 | 213 / 220 | 10 / 11 |
+| 4× | Pointer intent | 490.8 / 491.5 | 191.0 / 192.3 | 211 / 213 | 9 / 11 |
+| 4× | Idle on plugins page | 491.8 / 492.0 | 191.5 / 205.6 | 214 / 221 | 9 / 10 |
+
+Normal pages aggregate 15 observations per variant and CPU rate:
+
+| CPU | Page | Baseline visible | Optimized visible |
+| --- | --- | ---: | ---: |
+| 1× | Settings | 31.9 / 34.8 | 28.9 / 35.0 |
+| 1× | Downloads | 29.4 / 30.6 | 29.5 / 29.9 |
+| 1× | Plugins | 29.1 / 30.7 | 29.2 / 29.8 |
+| 4× | Settings | 35.8 / 41.1 | 34.7 / 50.1 |
+| 4× | Downloads | 57.7 / 75.0 | 57.4 / 77.5 |
+| 4× | Plugins | 39.0 / 41.3 | 40.2 / 44.0 |
+
+No main-thread long tasks were observed during the measured preparation intervals
+or normal-page navigation. Optimized preparation frame gaps peaked at 18.7 ms.
+For direct graph opening under 4× throttle, the median largest frame gap fell
+from 266.8 to 66.6 ms; graph rendering still contributes work on the main thread.
+Repeat graph opening in that scenario fell from 223.7 / 224.0 to 122.9 / 127.1 ms.
+Startup medians stayed around 559–567 ms. This run supports keeping ordinary
+routes eager while moving graph computation off-thread; it does not establish
+zero stutter across all devices.
diff --git a/docs/production-builds.zh-CN.md b/docs/production-builds.zh-CN.md
new file mode 100644
index 00000000..c89acb0a
--- /dev/null
+++ b/docs/production-builds.zh-CN.md
@@ -0,0 +1,118 @@
+# 生产构建
+
+Motrix 构建六类 JavaScript 产物:Electron 主进程、preload、插件 worker、
+桌面渲染器、Web 渲染器,以及包含运维 CLI 的 Node 服务端。
+这些 Vite 配置共用 `scripts/vite-production-output.ts`。
+
+## 产物策略
+
+- 生产 JavaScript 统一压缩,包括服务端 ES library 产物中的空白。
+ 渲染器 CSS 使用 Lightning CSS 压缩。
+- 输出的 JavaScript 移除源码文档注释和优化器注解,保留许可证注释及
+ 安装包中的第三方声明。
+- 发布构建不生成 source map。服务端保留函数名和类名,便于诊断;
+ 运行日志继续保留。
+- 只有渲染器构建复制 `public/` 中的图标和图片。宿主、preload 和 worker
+ 构建不复制这些浏览器资源,避免安装包包含重复文件。
+- 主进程、preload 和 worker 入口仍为 CommonJS `.cjs` 文件,服务端和 CLI
+ 入口仍为 ES `.mjs` 文件。原生模块和外部依赖继续遵循现有打包规则。
+
+## 按需加载的资源
+
+英文和简体中文翻译随应用预加载。其余 24 种语言拆为独立代码块,包含在
+桌面安装包中,由 Motrix Server 本地提供给 Web 界面。桌面端切换语言无需联网。
+
+宿主和渲染器先加载目标翻译,再应用语言变更。同一资源的并发请求共享加载过程,
+加载失败后可以重试;渲染器较慢的旧请求不会覆盖较新的语言选择。
+运维 CLI 在创建翻译器前加载所选语言。插件提供的翻译沿用现有生命周期。
+
+ELK 图布局引擎运行在随包提供的独立浏览器 Worker 中,不进入渲染器初始代码块,
+解析和布局计算也不再阻塞 UI 线程。窗口生命周期内共享一个引擎,复用匹配的图布局
+缓存时无需再次计算。Worker 出错或请求超过 30 秒时使引擎缓存失效,现有重试按钮
+会重新创建引擎。
+
+桌面端进入插件页后,先等待 200 ms,再利用空闲时间准备引擎。指针进入、键盘聚焦
+或按下诊断入口时立即准备。准备过程包含一次两个节点的小型布局,与实际导航共享
+初始化。离开插件页会取消尚未开始的任务,隐藏窗口不执行推测加载。Web 端按需加载
+Worker。仪表盘、下载、设置和插件路由继续预加载;启动应用不会预加载所有语言和功能。
+
+代码拆分减少启动时需要解析的 JavaScript,不会从安装包中删除语言或功能。
+额外的代码块封装可能让渲染器产物总体积略有增加。
+
+## 测量与验证
+
+在仓库根目录运行:
+
+```bash
+NODE_ENV=production node scripts/measure-production-bundles.mjs
+pnpm exec vitest run tests/scripts/production-build.test.ts
+pnpm build
+pnpm test:e2e e2e/unit-localization.spec.ts e2e/plugin-call-graph.spec.ts
+```
+
+测量命令在内存中构建六类产物,报告 JavaScript 原始及 gzip 字节数、代码块数量、
+包含的语言和启动依赖。完整 JavaScript 字节数包含 Vite 单独输出的 Worker 资源。
+初始字节数包含所有入口及其递归静态导入,不计动态导入。
+服务端数值是 Server 和 CLI 两个入口的合集,并非单个运行进程的测量。
+gzip 字节数为各代码块独立压缩后的总和,不代表安装包体积。
+
+CI 检查初始及完整 JavaScript 体积预算,确认 26 种语言均被打包、延迟语言和 ELK
+未进入初始代码块,并拒绝生成 source map 或向宿主产物复制浏览器资源。
+服务端构建夹具还验证压缩后源码文档已移除,而许可证声明、诊断名称和执行行为
+仍然保留。各平台的包验证与运行冒烟测试继续负责检查安装体积及原生运行时兼容性。
+
+## 桌面导航性能对比
+
+在两个各自安装依赖的独立检出目录中,对两个版本分别运行 `pnpm build:electron`,
+然后在待测版本目录执行:
+
+```bash
+pnpm measure:desktop-navigation --variant baseline=../Motrix-baseline --variant optimized=. --samples 5 --cpu-rates 1,4
+```
+
+测试期间保持基线目录不变。两个应用使用待测目录中的同一个 Electron 运行时。
+每个样本都启动全新进程和临时用户目录,预置相同的 48 节点、90 条边调用记录,
+每轮交替两个版本的测试顺序。报告保留全部样本,路径为
+`output/playwright/manual/desktop-navigation/results.json`,包含产物哈希、启动耗时、
+设置/下载/插件页面切换、首次及重复打开诊断图、长任务和帧间隔。
+
+分别测量直接点击、指针进入后等待 300 ms、在插件页空闲停留 500 ms 三种场景。
+导航计时从程序触发链接开始,到图节点可见并经过一次绘制机会结束,不计自动化工具
+往返耗时。准备阶段单独记录,检查是否只是把阻塞移到点击之前。渲染器阻塞时间为
+各长任务超过 50 ms 部分的总和,帧间隔记录 `requestAnimationFrame` 的间距,
+不等于实测输入到绘制延迟。
+
+CPU 节流在应用界面就绪后开启,主要施压渲染器主线程,不模拟慢磁盘、IPC,
+也不代表 Worker 在低端机器上同步变慢。测试不清空系统文件缓存。每种情况的五个
+样本用于本机对比,不能作为尾延迟或完全无卡顿的保证。
+
+2026-10-04 在 Apple M4 / macOS arm64、Electron 44.5.0 和生产 React 下测量。
+基线为 `62207e06`,已包含语言和代码拆分;待测版本增加独立 Worker 和桌面提前准备。
+共 60 个全新进程样本,每个版本、CPU 档位和场景各 5 次。以下单位为毫秒,
+数值表示**中位数 / 观察到的最大值**。
+
+| CPU | 首次打开诊断图的场景 | 基线可见耗时 | 优化后可见耗时 | 基线阻塞 | 优化后阻塞 |
+| --- | --- | ---: | ---: | ---: | ---: |
+| 1× | 直接点击 | 145.8 / 145.9 | 129.1 / 129.3 | 12 / 13 | 0 / 0 |
+| 1× | 指针提前进入 | 169.7 / 172.0 | 95.6 / 103.9 | 13 / 14 | 0 / 0 |
+| 1× | 在插件页空闲停留 | 145.5 / 171.7 | 93.4 / 107.2 | 12 / 15 | 0 / 0 |
+| 4× | 直接点击 | 488.9 / 491.1 | 241.9 / 256.2 | 213 / 220 | 10 / 11 |
+| 4× | 指针提前进入 | 490.8 / 491.5 | 191.0 / 192.3 | 211 / 213 | 9 / 11 |
+| 4× | 在插件页空闲停留 | 491.8 / 492.0 | 191.5 / 205.6 | 214 / 221 | 9 / 10 |
+
+普通页面按版本和 CPU 档位各汇总 15 个样本:
+
+| CPU | 页面 | 基线可见耗时 | 优化后可见耗时 |
+| --- | --- | ---: | ---: |
+| 1× | 设置 | 31.9 / 34.8 | 28.9 / 35.0 |
+| 1× | 下载 | 29.4 / 30.6 | 29.5 / 29.9 |
+| 1× | 插件 | 29.1 / 30.7 | 29.2 / 29.8 |
+| 4× | 设置 | 35.8 / 41.1 | 34.7 / 50.1 |
+| 4× | 下载 | 57.7 / 75.0 | 57.4 / 77.5 |
+| 4× | 插件 | 39.0 / 41.3 | 40.2 / 44.0 |
+
+测量的准备阶段和普通页面切换期间均未观察到主线程长任务,优化后的准备阶段帧间隔
+最大为 18.7 ms。4 倍节流直接打开诊断图时,最大帧间隔的中位数从 266.8 ms 降到
+66.6 ms,图形渲染仍会占用主线程;相同场景再次打开图的耗时从 223.7 / 224.0 ms
+降到 122.9 / 127.1 ms。启动中位耗时维持在约 559–567 ms。本次结果支持普通路由
+继续预加载、图计算移到独立线程的方案,不能推断所有设备都完全无卡顿。
diff --git a/e2e/plugin-call-graph.spec.ts b/e2e/plugin-call-graph.spec.ts
index 9fb71bdb..aaffcce2 100644
--- a/e2e/plugin-call-graph.spec.ts
+++ b/e2e/plugin-call-graph.spec.ts
@@ -229,7 +229,12 @@ test.describe('plugin diagnostics call graph', () => {
const app = await launchMotrix({ userDataDir, rpcPort })
try {
const page = await openMain(app)
+ expect(page.workers()).toHaveLength(0)
+ await page.context().setOffline(true)
await openCallGraph(page)
+ const workers = page.workers()
+ expect(workers).toHaveLength(1)
+ expect(workers[0]?.url()).toMatch(/^file:.*\/elk-worker\.min-[\w-]+\.js$/)
await expect(
page.getByRole('group', { name: 'Call volume legend' })
).toBeVisible()
diff --git a/e2e/unit-localization.spec.ts b/e2e/unit-localization.spec.ts
index 9d1432a9..57d1317c 100644
--- a/e2e/unit-localization.spec.ts
+++ b/e2e/unit-localization.spec.ts
@@ -2,7 +2,7 @@ import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
import { expect, test, waitForEngineReady } from './fixtures/electron-app'
-test('language changes localize speed limits and preserve stored bytes', async ({
+test('offline language changes localize speed limits and preserve stored bytes', async ({
mainWindow,
}, testInfo) => {
await waitForEngineReady(mainWindow)
@@ -17,6 +17,7 @@ test('language changes localize speed limits and preserve stored bytes', async (
})
}, Commands.UpdateSettings)
const badge = mainWindow.locator('[data-slot="downloads-speed-limit"]')
+ await mainWindow.context().setOffline(true)
for (const [locale, expected] of [
['fr', '1,5 Mio/s'],
['ru', '1,5 МиБ/с'],
@@ -32,6 +33,11 @@ test('language changes localize speed limits and preserve stored bytes', async (
{ channel: Commands.UpdateSettings, language: locale }
)
await badge.hover()
+ await expect(mainWindow.locator('html')).toHaveAttribute('lang', locale)
+ await expect(mainWindow.locator('html')).toHaveAttribute(
+ 'dir',
+ locale === 'ar' ? 'rtl' : 'ltr'
+ )
await expect(mainWindow.getByRole('tooltip')).toContainText(expected)
await expect
.poll(() =>
@@ -41,7 +47,7 @@ test('language changes localize speed limits and preserve stored bytes', async (
)
)
.toMatchObject({
- app: { byteUnitSystem: 'binary' },
+ app: { byteUnitSystem: 'binary', language: locale },
speedLimit: { base: { upload: 1_048_576, download: 1_572_864 } },
})
await mainWindow.screenshot({
diff --git a/package.json b/package.json
index f039b206..e7087a36 100644
--- a/package.json
+++ b/package.json
@@ -29,6 +29,7 @@
"smoke:server-package": "node scripts/smoke-server-package.mjs",
"smoke:server-image": "node scripts/smoke-server-image.mjs",
"measure:server-images": "node scripts/measure-server-images.mjs",
+ "measure:desktop-navigation": "node --import tsx scripts/measure-desktop-navigation.mjs",
"build:builtin": "node scripts/fetch-builtins.mjs",
"build:native-host": "node packages/native-host/build.mjs",
"build:finalize-fs": "node packages/finalize-fs/build.mjs",
diff --git a/scripts/measure-desktop-navigation.mjs b/scripts/measure-desktop-navigation.mjs
new file mode 100644
index 00000000..c0a8435d
--- /dev/null
+++ b/scripts/measure-desktop-navigation.mjs
@@ -0,0 +1,341 @@
+import { createHash } from 'node:crypto'
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import net from 'node:net'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseArgs } from 'node:util'
+import { _electron as electron } from 'playwright'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations.ts'
+import { Queries } from '../src/shared/protocol/queries.ts'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const { values } = parseArgs({
+ options: {
+ variant: { type: 'string', multiple: true },
+ samples: { type: 'string', default: '5' },
+ 'cpu-rates': { type: 'string', default: '1,4' },
+ nodes: { type: 'string', default: '48' },
+ out: {
+ type: 'string',
+ default: 'output/playwright/manual/desktop-navigation/results.json',
+ },
+ },
+})
+const samples = Number(values.samples)
+const nodeCount = Number(values.nodes)
+const cpuRates = values['cpu-rates'].split(',').map(Number)
+if (
+ !Number.isInteger(samples) ||
+ samples < 1 ||
+ samples > 100 ||
+ !Number.isInteger(nodeCount) ||
+ nodeCount < 2 ||
+ nodeCount > 200 ||
+ cpuRates.some((rate) => !Number.isFinite(rate) || rate < 1 || rate > 20)
+) {
+ throw new Error('Invalid sample count, node count, or CPU rate')
+}
+const variants = (values.variant ?? ['current=.']).map((value) => {
+ const separator = value.indexOf('=')
+ if (separator < 1) throw new Error('Use --variant label=app-directory')
+ const label = value.slice(0, separator)
+ if (!/^[a-z0-9-]+$/.test(label))
+ throw new Error('Use a portable variant label')
+ return { label, directory: path.resolve(value.slice(separator + 1)) }
+})
+
+async function freePort() {
+ const server = net.createServer()
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const port = server.address().port
+ await new Promise((resolve) => server.close(resolve))
+ return port
+}
+
+async function seed(userData) {
+ await writeFile(
+ path.join(userData, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { language: 'en-US', theme: 'light', warnBeforeQuit: false },
+ tracker: { autoSync: false },
+ onboarding: { disclaimerAccepted: true },
+ })
+ )
+ const audit = path.join(userData, 'plugins', '_audit')
+ await mkdir(audit, { recursive: true })
+ const now = Date.now()
+ const records = []
+ for (let index = 0; index < nodeCount - 1; index += 1) {
+ for (const offset of [1, 5]) {
+ if (index + offset >= nodeCount) continue
+ records.push({
+ ts: now - 1000,
+ type: 'command.invoke',
+ caller: `benchmark.plugin-${index}`,
+ callee: `benchmark.plugin-${index + offset}`,
+ commandId: `benchmark.plugin-${index + offset}.run`,
+ argsSize: 24,
+ resultSize: 48,
+ durMs: 6,
+ depth: 1,
+ ok: true,
+ })
+ }
+ }
+ await writeFile(
+ path.join(audit, 'command-invokes.ndjson'),
+ `${records.map((record) => JSON.stringify(record)).join('\n')}\n`
+ )
+}
+
+// These probes run only in the measurement page, never in shipped application code.
+async function installProbe(page) {
+ await page.evaluate(() => {
+ window.__navigationProbe = {
+ start(readySelector, durationMs = 0) {
+ const start = performance.now()
+ const longTasks = []
+ let previousFrame = start
+ let maxFrameGapMs = 0
+ let readyAt = null
+ let framesAfterReady = 0
+ const observer = new PerformanceObserver((list) => {
+ longTasks.push(...list.getEntries().map((entry) => entry.duration))
+ })
+ observer.observe({ type: 'longtask' })
+ this.result = null
+ const tick = (timestamp) => {
+ maxFrameGapMs = Math.max(maxFrameGapMs, timestamp - previousFrame)
+ previousFrame = timestamp
+ const element = durationMs
+ ? null
+ : document.querySelector(readySelector.selector ?? readySelector)
+ const ready = durationMs
+ ? timestamp - start >= durationMs
+ : Boolean(
+ element &&
+ (!readySelector.text ||
+ element.textContent === readySelector.text) &&
+ element.getBoundingClientRect().height > 0 &&
+ getComputedStyle(element).visibility !== 'hidden'
+ )
+ if (ready && readyAt === null) readyAt = timestamp
+ if (readyAt !== null && ++framesAfterReady >= 2) {
+ setTimeout(() => {
+ longTasks.push(
+ ...observer.takeRecords().map((entry) => entry.duration)
+ )
+ observer.disconnect()
+ this.result = {
+ readyMs: timestamp - start,
+ maxFrameGapMs,
+ longTaskCount: longTasks.length,
+ maxLongTaskMs: Math.max(0, ...longTasks),
+ blockingMs: longTasks.reduce(
+ (total, duration) => total + Math.max(0, duration - 50),
+ 0
+ ),
+ }
+ }, 0)
+ } else requestAnimationFrame(tick)
+ }
+ requestAnimationFrame(tick)
+ },
+ }
+ })
+}
+
+async function finishProbe(page) {
+ await page.waitForFunction(
+ () => window.__navigationProbe.result !== null,
+ null,
+ { timeout: 30_000 }
+ )
+ return page.evaluate(() => window.__navigationProbe.result)
+}
+
+async function navigate(page, href, readySelector) {
+ const link = page.locator(`a[href="${href}"]`).first()
+ await link.waitFor({ state: 'visible' })
+ // DOM activation intentionally excludes pointer-hover lead time and automation
+ // round trips from the cold-click interval. Intent warming is measured separately.
+ await link.evaluate((element, selector) => {
+ window.__navigationProbe.start(selector)
+ element.click()
+ }, readySelector)
+ return finishProbe(page)
+}
+
+async function sample(variant, cpuRate, mode) {
+ const userData = await realpath(
+ await mkdtemp(path.join(os.tmpdir(), 'motrix-navigation-'))
+ )
+ let app
+ try {
+ await seed(userData)
+ const rpcPort = await freePort()
+ const launchedAt = performance.now()
+ app = await electron.launch({
+ args: [variant.directory],
+ cwd: userData,
+ env: {
+ ...process.env,
+ NODE_ENV: 'test',
+ MOTRIX_USER_DATA: userData,
+ MOTRIX_RPC_PORT: String(rpcPort),
+ MOTRIX_DEFAULT_SAVE_DIR: path.join(userData, 'downloads'),
+ },
+ })
+ const page = await app.firstWindow()
+ page.setDefaultTimeout(30_000)
+ await page.getByRole('link', { name: 'Plugins', exact: true }).waitFor()
+ const launchToShellMs = performance.now() - launchedAt
+ await app.evaluate(({ BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ main?.show()
+ main?.focus()
+ })
+ await page.waitForFunction(async (channel) => {
+ try {
+ await window.motrix.invoke(channel)
+ return true
+ } catch {
+ return false
+ }
+ }, Queries.GetEngineStatus)
+ const cdp = await page.context().newCDPSession(page)
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: cpuRate })
+ await installProbe(page)
+ const errors = []
+ page.on('pageerror', (error) => errors.push(error.message))
+ const settings = await navigate(page, '#/settings', {
+ selector: '[data-slot="panel-shell-header"] h1',
+ text: 'Settings',
+ })
+ const downloads = await navigate(
+ page,
+ '#/downloads',
+ '[data-slot="downloads-speed-limit"]'
+ )
+ const plugins = await navigate(
+ page,
+ '#/plugins',
+ '[data-testid="plugins-tool-row"]'
+ )
+ let intent = null
+ if (mode !== 'direct') {
+ await page.evaluate(
+ (duration) => window.__navigationProbe.start(null, duration),
+ mode === 'intent' ? 300 : 500
+ )
+ if (mode === 'intent') {
+ await page
+ .getByRole('link', { name: 'Diagnostics', exact: true })
+ .hover()
+ }
+ intent = await finishProbe(page)
+ }
+ const firstGraph = await navigate(
+ page,
+ '#/plugins/diagnostics',
+ '.react-flow__node'
+ )
+ await navigate(page, '#/plugins', '[data-testid="plugins-tool-row"]')
+ const repeatGraph = await navigate(
+ page,
+ '#/plugins/diagnostics',
+ '.react-flow__node'
+ )
+ if (errors.length) throw new Error(errors.join('; '))
+ return {
+ variant: variant.label,
+ cpuRate,
+ mode,
+ launchToShellMs,
+ settings,
+ downloads,
+ plugins,
+ intent,
+ firstGraph,
+ repeatGraph,
+ }
+ } finally {
+ await app?.close().catch(() => {})
+ await rm(userData, { recursive: true, force: true })
+ }
+}
+
+const report = {
+ schemaVersion: 1,
+ environment: {
+ platform: process.platform,
+ arch: process.arch,
+ cpu: os.cpus()[0]?.model,
+ node: process.versions.node,
+ },
+ methodology: {
+ samples,
+ cpuRates,
+ nodeCount,
+ startup:
+ 'Fresh Electron process and user data; OS file cache is not flushed. CPU throttle begins after shell readiness.',
+ navigation:
+ 'Programmatic link activation to visible DOM readiness followed by a paint opportunity; 300 ms pointer-intent and 500 ms plugin-page idle scenarios reported separately.',
+ throttle:
+ 'CDP renderer CPU throttle is a stress condition, not a low-end hardware emulation.',
+ blocking:
+ 'Sum of renderer long-task duration above 50 ms; frame gap is requestAnimationFrame spacing, not measured input latency.',
+ },
+ variants: await Promise.all(
+ variants.map(async (variant) => ({
+ label: variant.label,
+ mainSha256: createHash('sha256')
+ .update(
+ await readFile(path.join(variant.directory, 'dist/main/index.cjs'))
+ )
+ .digest('hex'),
+ rendererHtmlSha256: createHash('sha256')
+ .update(
+ await readFile(
+ path.join(variant.directory, 'dist/renderer/index.html')
+ )
+ )
+ .digest('hex'),
+ }))
+ ),
+ runs: [],
+}
+const destination = path.resolve(values.out)
+await mkdir(path.dirname(destination), { recursive: true })
+// Alternate variants in each round so cache/temperature drift does not always
+// favor the candidate. Preserve every sample; never discard slow observations.
+for (const cpuRate of cpuRates) {
+ for (const mode of ['direct', 'intent', 'idle']) {
+ for (let index = 0; index < samples; index += 1) {
+ const order = index % 2 ? [...variants].reverse() : variants
+ for (const variant of order) {
+ const result = await sample(variant, cpuRate, mode)
+ report.runs.push({ sample: index + 1, ...result })
+ await writeFile(destination, `${JSON.stringify(report, null, 2)}\n`)
+ process.stdout.write(
+ `${variant.label} ${cpuRate}x ${mode} ${index + 1}/${samples}: graph ${result.firstGraph.readyMs.toFixed(1)} ms, blocking ${result.firstGraph.blockingMs.toFixed(1)} ms\n`
+ )
+ }
+ }
+ }
+}
+process.stdout.write(`Report: ${path.relative(ROOT, destination)}\n`)
diff --git a/scripts/measure-production-bundles.mjs b/scripts/measure-production-bundles.mjs
new file mode 100644
index 00000000..f0f00f2c
--- /dev/null
+++ b/scripts/measure-production-bundles.mjs
@@ -0,0 +1,116 @@
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { gzipSync } from 'node:zlib'
+import { build } from 'vite'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const TARGETS = [
+ 'main',
+ 'preload',
+ 'worker',
+ 'renderer',
+ 'renderer.web',
+ 'server',
+]
+
+function initialChunks(chunks) {
+ const byName = new Map(chunks.map((chunk) => [chunk.fileName, chunk]))
+ const loaded = new Map()
+ function visit(chunk) {
+ if (loaded.has(chunk.fileName)) return
+ loaded.set(chunk.fileName, chunk)
+ for (const name of chunk.imports) {
+ const dependency = byName.get(name)
+ if (dependency) visit(dependency)
+ }
+ }
+ chunks.filter((chunk) => chunk.isEntry).forEach(visit)
+ return [...loaded.values()]
+}
+
+function moduleIds(chunks) {
+ return chunks
+ .flatMap((chunk) => Object.keys(chunk.modules))
+ .map((id) => id.replaceAll('\\', '/'))
+}
+
+function locales(modules) {
+ return [
+ ...new Set(
+ modules.flatMap(
+ (id) => /\/src\/shared\/locales\/(.+)\.json$/.exec(id)?.[1] ?? []
+ )
+ ),
+ ].sort()
+}
+
+export async function measureProductionBundles() {
+ if (process.env.NODE_ENV !== 'production') {
+ throw new Error('Run bundle measurement with NODE_ENV=production')
+ }
+ const report = {}
+ for (const target of TARGETS) {
+ let copiesPublicAssets = false
+ const result = await build({
+ root: ROOT,
+ configFile: path.join(ROOT, `vite.${target}.config.ts`),
+ mode: 'production',
+ logLevel: 'silent',
+ build: { write: false },
+ plugins: [
+ {
+ name: 'measure-production-assets',
+ configResolved(config) {
+ copiesPublicAssets =
+ Boolean(config.publicDir) && config.build.copyPublicDir
+ },
+ },
+ ],
+ })
+ if (!Array.isArray(result) && 'close' in result) {
+ await result.close()
+ throw new Error('unexpected watch build')
+ }
+ const outputs = (Array.isArray(result) ? result : [result]).flatMap(
+ (r) => r.output
+ )
+ const chunks = outputs.filter((item) => item.type === 'chunk')
+ // Vite emits dedicated browser Workers as assets, not application chunks.
+ // Include their code in total bytes so moving work off-thread cannot hide it.
+ const javascriptAssets = outputs.filter(
+ (item) => item.type === 'asset' && /\.[cm]?js$/.test(item.fileName)
+ )
+ const code = (item) => (item.type === 'chunk' ? item.code : item.source)
+ const initial = initialChunks(chunks)
+ const bytes = (items) =>
+ items.reduce((sum, item) => sum + Buffer.byteLength(code(item)), 0)
+ const gzipBytes = (items) =>
+ items.reduce((sum, item) => sum + gzipSync(code(item)).length, 0)
+ const allModules = moduleIds(chunks)
+ const startupModules = moduleIds(initial)
+ report[target] = {
+ copiesPublicAssets,
+ totalBytes: bytes([...chunks, ...javascriptAssets]),
+ totalGzipBytes: gzipBytes([...chunks, ...javascriptAssets]),
+ javascriptAssetBytes: bytes(javascriptAssets),
+ javascriptAssetCount: javascriptAssets.length,
+ initialBytes: bytes(initial),
+ initialGzipBytes: gzipBytes(initial),
+ initialChunks: initial.length,
+ chunkCount: chunks.length,
+ sourceMaps: outputs.filter((item) => item.fileName.endsWith('.map'))
+ .length,
+ initialLocales: locales(startupModules),
+ bundledLocales: locales(allModules),
+ initialElk: startupModules.some((id) => id.includes('/elkjs/')),
+ bundledElk: allModules.some((id) => id.includes('/elkjs/')),
+ }
+ }
+ return report
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ process.stdout.write(
+ `${JSON.stringify(await measureProductionBundles(), null, 2)}\n`
+ )
+}
diff --git a/scripts/vite-production-output.ts b/scripts/vite-production-output.ts
new file mode 100644
index 00000000..b6ed0a4a
--- /dev/null
+++ b/scripts/vite-production-output.ts
@@ -0,0 +1,8 @@
+import type { Rolldown } from 'vite'
+
+// Apply full output minification even to SSR/ES library builds, whose Vite
+// defaults otherwise keep whitespace. Keep distribution attribution in output.
+export const PRODUCTION_OUTPUT = {
+ minify: true,
+ comments: { legal: true, jsdoc: false, annotation: false },
+} satisfies Rolldown.OutputOptions
diff --git a/src/main/index.ts b/src/main/index.ts
index 6d62b4ba..ebf94b11 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -174,7 +174,7 @@ import { setupEventForwarding } from './ipc/events'
import { registerNotificationIpc } from './ipc/notifications'
import { registerQueryHandlers } from './ipc/queries'
import { setupLauncher } from './launcher'
-import { i18n } from './lib/i18n'
+import { applyMainLocale, i18n } from './lib/i18n'
import { setupLogger } from './logger'
import { MainProcessWorkCoordinator } from './main-process-work-coordinator'
import { installAllMenubarContributions } from './menu/contributions'
@@ -1595,19 +1595,19 @@ async function initializeMainProcess(): Promise<void> {
if (targets) {
await targets.registry.setHostLanguageTransaction(locale, {
beforeCommit: async () => {
- await i18n.changeLanguage(locale)
+ await applyMainLocale(locale)
},
commitHostLocale: () => {
targets.capabilityHost.setLocale(locale)
},
rollbackHostLocale: async (previousLanguage) => {
targets.capabilityHost.setLocale(previousLanguage)
- await i18n.changeLanguage(previousLanguage)
+ await applyMainLocale(previousLanguage)
},
shouldCommit: isCurrent,
})
} else {
- await i18n.changeLanguage(locale)
+ await applyMainLocale(locale)
}
if (!isCurrent()) return
localeContextStore?.merge({ locale })
diff --git a/src/main/lib/i18n.ts b/src/main/lib/i18n.ts
index f13fa5fc..4dc21b4f 100644
--- a/src/main/lib/i18n.ts
+++ b/src/main/lib/i18n.ts
@@ -2,12 +2,18 @@ import {
DEFAULT_LOCALE,
FALLBACK_LOCALE,
SUPPORTED_LOCALE_CODES,
+ type SupportedLocale,
} from '@shared/constants/locales'
-import { I18N_RESOURCES } from '@shared/i18n-resources'
+import {
+ ensureI18nLocale,
+ I18N_BACKEND,
+ I18N_RESOURCES,
+} from '@shared/i18n-resources'
import i18n from 'i18next'
-i18n.init({
- resources: I18N_RESOURCES,
+const ready = i18n.use(I18N_BACKEND).init({
+ resources: { ...I18N_RESOURCES },
+ partialBundledLanguages: true,
supportedLngs: SUPPORTED_LOCALE_CODES,
lng: DEFAULT_LOCALE,
fallbackLng: FALLBACK_LOCALE,
@@ -16,4 +22,10 @@ i18n.init({
},
})
+export async function applyMainLocale(locale: SupportedLocale): Promise<void> {
+ await ready
+ await ensureI18nLocale(i18n, locale)
+ await i18n.changeLanguage(locale)
+}
+
export { i18n }
diff --git a/src/renderer/lib/i18n.test.ts b/src/renderer/lib/i18n.test.ts
index ef4d2a93..354fa7fd 100644
--- a/src/renderer/lib/i18n.test.ts
+++ b/src/renderer/lib/i18n.test.ts
@@ -5,10 +5,36 @@ import {
SUPPORTED_LOCALE_CODES,
SUPPORTED_LOCALES,
} from '@shared/constants/locales'
-import { describe, expect, it } from 'vitest'
+import { I18N_RESOURCE_LOADERS } from '@shared/i18n-resources'
+import { describe, expect, it, vi } from 'vitest'
import { applyDocumentLocaleMetadata, applyRendererLocale, i18n } from './i18n'
describe('renderer i18n', () => {
+ it('keeps a newer language selection when an earlier chunk finishes late', async () => {
+ let finish!: (
+ value: Awaited<ReturnType<typeof I18N_RESOURCE_LOADERS.ar>>
+ ) => void
+ const original = I18N_RESOURCE_LOADERS.ar
+ const loader = vi.spyOn(I18N_RESOURCE_LOADERS, 'ar').mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve
+ })
+ )
+ try {
+ const older = applyRendererLocale('ar')
+ await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce())
+ await applyRendererLocale('en-US')
+ finish(await original())
+ await older
+ expect(i18n.resolvedLanguage).toBe('en-US')
+ expect(document.documentElement).toHaveAttribute('lang', 'en-US')
+ expect(document.documentElement).toHaveAttribute('dir', 'ltr')
+ } finally {
+ loader.mockRestore()
+ }
+ })
+
it('derives supported and fallback locales from the shared catalog', () => {
expect(i18n.options.supportedLngs).toEqual(
expect.arrayContaining([...SUPPORTED_LOCALE_CODES])
diff --git a/src/renderer/lib/i18n.ts b/src/renderer/lib/i18n.ts
index 38e6ab68..5820d9dd 100644
--- a/src/renderer/lib/i18n.ts
+++ b/src/renderer/lib/i18n.ts
@@ -7,19 +7,27 @@ import {
SUPPORTED_LOCALE_CODES,
type SupportedLocale,
} from '@shared/constants/locales'
-import { I18N_RESOURCES } from '@shared/i18n-resources'
+import {
+ ensureI18nLocale,
+ I18N_BACKEND,
+ I18N_RESOURCES,
+} from '@shared/i18n-resources'
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
-const i18nReady = i18n.use(initReactI18next).init({
- resources: I18N_RESOURCES,
- supportedLngs: SUPPORTED_LOCALE_CODES,
- lng: DEFAULT_LOCALE,
- fallbackLng: FALLBACK_LOCALE,
- interpolation: {
- escapeValue: false,
- },
-})
+const i18nReady = i18n
+ .use(I18N_BACKEND)
+ .use(initReactI18next)
+ .init({
+ resources: { ...I18N_RESOURCES },
+ partialBundledLanguages: true,
+ supportedLngs: SUPPORTED_LOCALE_CODES,
+ lng: DEFAULT_LOCALE,
+ fallbackLng: FALLBACK_LOCALE,
+ interpolation: {
+ escapeValue: false,
+ },
+ })
export function applyDocumentLocaleMetadata(
locale: Pick<LocaleDefinition, 'code' | 'dir'>
@@ -30,12 +38,18 @@ export function applyDocumentLocaleMetadata(
document.documentElement.dir = locale.dir
}
+let localeRequest = 0
+
export async function applyRendererLocale(
locale: string | null | undefined
): Promise<SupportedLocale> {
+ const request = ++localeRequest
const resolved = resolveSupportedLocale(locale)
await i18nReady
+ await ensureI18nLocale(i18n, resolved)
+ if (request !== localeRequest) return resolved
await i18n.changeLanguage(resolved)
+ if (request !== localeRequest) return resolved
applyDocumentLocaleMetadata(getLocaleDefinition(resolved))
diff --git a/src/renderer/routes/plugins/hooks/use-call-graph-preload.test.ts b/src/renderer/routes/plugins/hooks/use-call-graph-preload.test.ts
new file mode 100644
index 00000000..2c184dba
--- /dev/null
+++ b/src/renderer/routes/plugins/hooks/use-call-graph-preload.test.ts
@@ -0,0 +1,82 @@
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useCallGraphPreload } from './use-call-graph-preload'
+
+const state = vi.hoisted(() => ({ kind: 'electron', preload: vi.fn() }))
+vi.mock('@renderer/platform/services', () => ({
+ usePlatformServices: () => ({ kind: state.kind }),
+}))
+vi.mock('../lib/call-graph-layout', () => ({
+ preloadCallGraphLayout: state.preload,
+}))
+
+describe('desktop diagnostics preloading', () => {
+ let idle: () => void
+ const schedule = vi.fn((callback: () => void) => {
+ idle = callback
+ return 42
+ })
+ const cancel = vi.fn()
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.clearAllMocks()
+ state.kind = 'electron'
+ vi.stubGlobal('requestIdleCallback', schedule)
+ vi.stubGlobal('cancelIdleCallback', cancel)
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible')
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('waits for the page to paint and then for an idle opportunity', () => {
+ const { unmount } = renderHook(useCallGraphPreload)
+ act(() => vi.advanceTimersByTime(199))
+ expect(schedule).not.toHaveBeenCalled()
+ act(() => vi.advanceTimersByTime(1))
+ expect(state.preload).not.toHaveBeenCalled()
+ act(() => idle())
+ expect(state.preload).toHaveBeenCalledOnce()
+ unmount()
+ })
+
+ it('cancels both stages when navigating away', () => {
+ const first = renderHook(useCallGraphPreload)
+ first.unmount()
+ act(() => vi.advanceTimersByTime(200))
+ expect(schedule).not.toHaveBeenCalled()
+ const second = renderHook(useCallGraphPreload)
+ act(() => vi.advanceTimersByTime(200))
+ second.unmount()
+ expect(cancel).toHaveBeenCalledWith(42)
+ expect(state.preload).not.toHaveBeenCalled()
+ })
+
+ it('starts immediately on intent while skipping hidden windows', () => {
+ const { result, unmount } = renderHook(useCallGraphPreload)
+ act(() => result.current())
+ expect(state.preload).toHaveBeenCalledOnce()
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
+ act(() => vi.advanceTimersByTime(200))
+ act(() => {
+ idle()
+ result.current()
+ })
+ expect(state.preload).toHaveBeenCalledOnce()
+ unmount()
+ })
+
+ it('does not speculate in web clients', () => {
+ state.kind = 'web'
+ const { result, unmount } = renderHook(useCallGraphPreload)
+ act(() => {
+ result.current()
+ vi.advanceTimersByTime(2000)
+ })
+ expect(schedule).not.toHaveBeenCalled()
+ expect(state.preload).not.toHaveBeenCalled()
+ unmount()
+ })
+})
diff --git a/src/renderer/routes/plugins/hooks/use-call-graph-preload.ts b/src/renderer/routes/plugins/hooks/use-call-graph-preload.ts
new file mode 100644
index 00000000..c7570058
--- /dev/null
+++ b/src/renderer/routes/plugins/hooks/use-call-graph-preload.ts
@@ -0,0 +1,27 @@
+import { usePlatformServices } from '@renderer/platform/services'
+import { useCallback, useEffect } from 'react'
+import { preloadCallGraphLayout } from '../lib/call-graph-layout'
+
+export function useCallGraphPreload(): () => void {
+ const { kind } = usePlatformServices()
+ const preload = useCallback(() => {
+ if (kind === 'electron' && document.visibilityState === 'visible') {
+ void preloadCallGraphLayout()
+ }
+ }, [kind])
+
+ useEffect(() => {
+ if (kind !== 'electron') return
+ let idle: number | undefined
+ // Let the plugin page paint before spending idle time on its diagnostics.
+ const timer = window.setTimeout(() => {
+ idle = window.requestIdleCallback(preload, { timeout: 1500 })
+ }, 200)
+ return () => {
+ window.clearTimeout(timer)
+ if (idle !== undefined) window.cancelIdleCallback(idle)
+ }
+ }, [kind, preload])
+
+ return preload
+}
diff --git a/src/renderer/routes/plugins/lib/call-graph-engine.test.ts b/src/renderer/routes/plugins/lib/call-graph-engine.test.ts
new file mode 100644
index 00000000..acd21873
--- /dev/null
+++ b/src/renderer/routes/plugins/lib/call-graph-engine.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createCallGraphEngine } from './call-graph-engine'
+
+const { layout, workers } = vi.hoisted(() => ({
+ layout: vi.fn(),
+ workers: [] as Array<EventTarget & { terminate: ReturnType<typeof vi.fn> }>,
+}))
+vi.mock('elkjs/lib/elk-worker.min.js?worker', () => ({
+ default: class extends EventTarget {
+ terminate = vi.fn()
+ constructor() {
+ super()
+ workers.push(this)
+ }
+ },
+}))
+vi.mock('elkjs/lib/elk-api.js', () => ({
+ default: class {
+ layout = layout
+ },
+}))
+
+describe('call graph Worker lifecycle', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ workers.length = 0
+ layout.mockReset().mockImplementation(async (graph) => graph)
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('waits for warmup and releases request timers after successful layout', async () => {
+ let ready!: (value: { id: string }) => void
+ layout.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ ready = resolve
+ })
+ )
+ const initialized = vi.fn()
+ const creating = createCallGraphEngine(vi.fn()).then((engine) => {
+ initialized()
+ return engine
+ })
+ await Promise.resolve()
+ expect(initialized).not.toHaveBeenCalled()
+ ready({ id: 'warmup' })
+ const engine = await creating
+ expect(await engine.layout({ id: 'graph' })).toEqual({ id: 'graph' })
+ expect(vi.getTimerCount()).toBe(0)
+ expect(workers[0]?.terminate).not.toHaveBeenCalled()
+ })
+
+ it('rejects pending layouts on Worker failure and invalidates the cache once', async () => {
+ const invalidate = vi.fn()
+ const engine = await createCallGraphEngine(invalidate)
+ layout.mockImplementation(() => new Promise(() => {}))
+ const first = expect(engine.layout({ id: 'first' })).rejects.toThrow(
+ 'Worker crashed'
+ )
+ const second = expect(engine.layout({ id: 'second' })).rejects.toThrow(
+ 'Worker crashed'
+ )
+ workers[0]?.dispatchEvent(
+ new ErrorEvent('error', { message: 'Worker crashed', cancelable: true })
+ )
+ await Promise.all([first, second])
+ await expect(engine.layout({ id: 'later' })).rejects.toThrow(
+ 'Worker crashed'
+ )
+ expect(invalidate).toHaveBeenCalledOnce()
+ expect(workers[0]?.terminate).toHaveBeenCalledOnce()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('bounds a Worker that never finishes initialization and permits a fresh engine', async () => {
+ layout.mockImplementationOnce(() => new Promise(() => {}))
+ const invalidate = vi.fn()
+ const rejected = expect(createCallGraphEngine(invalidate)).rejects.toThrow(
+ 'timed out'
+ )
+ await vi.advanceTimersByTimeAsync(30_000)
+ await rejected
+ expect(invalidate).toHaveBeenCalledOnce()
+ expect(workers[0]?.terminate).toHaveBeenCalledOnce()
+ const replacement = await createCallGraphEngine(vi.fn())
+ expect(await replacement.layout({ id: 'retry' })).toEqual({ id: 'retry' })
+ expect(workers).toHaveLength(2)
+ })
+
+ it('rejects unreadable Worker messages instead of leaving the graph pending', async () => {
+ layout.mockImplementationOnce(() => new Promise(() => {}))
+ const rejected = expect(createCallGraphEngine(vi.fn())).rejects.toThrow(
+ 'unreadable'
+ )
+ workers[0]?.dispatchEvent(new MessageEvent('messageerror'))
+ await rejected
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/src/renderer/routes/plugins/lib/call-graph-engine.ts b/src/renderer/routes/plugins/lib/call-graph-engine.ts
new file mode 100644
index 00000000..6c4ae75c
--- /dev/null
+++ b/src/renderer/routes/plugins/lib/call-graph-engine.ts
@@ -0,0 +1,81 @@
+import type { ElkNode } from 'elkjs'
+import ELK from 'elkjs/lib/elk-api.js'
+import ElkWorker from 'elkjs/lib/elk-worker.min.js?worker'
+import type { ElkLayoutAdapter } from './call-graph-layout'
+
+const REQUEST_TIMEOUT_MS = 30_000
+
+// Keep parsing and layout off the renderer thread. The bundled ELK entry point
+// otherwise supplies a FakeWorker that executes expensive work on that thread.
+export async function createCallGraphEngine(
+ onFailure: () => void
+): Promise<ElkLayoutAdapter> {
+ const worker = new ElkWorker()
+ const pending = new Set<(error: Error) => void>()
+ let failure: Error | undefined
+ const fail = (error: Error) => {
+ if (failure) return
+ failure = error
+ worker.removeEventListener('error', handleError)
+ worker.removeEventListener('messageerror', handleMessageError)
+ worker.terminate()
+ for (const reject of pending) reject(error)
+ onFailure()
+ }
+ const handleError = (event: ErrorEvent) => {
+ event.preventDefault()
+ fail(new Error(event.message || 'Call graph worker failed'))
+ }
+ const handleMessageError = () => {
+ fail(new Error('Call graph worker returned an unreadable message'))
+ }
+ worker.addEventListener('error', handleError)
+ worker.addEventListener('messageerror', handleMessageError)
+
+ function request<T>(run: () => Promise<T>): Promise<T> {
+ if (failure) return Promise.reject(failure)
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(
+ () => fail(new Error('Call graph worker timed out')),
+ REQUEST_TIMEOUT_MS
+ )
+ const rejectRequest = (error: Error) => {
+ clearTimeout(timer)
+ pending.delete(rejectRequest)
+ reject(error)
+ }
+ pending.add(rejectRequest)
+ Promise.resolve()
+ .then(run)
+ .then((value) => {
+ clearTimeout(timer)
+ pending.delete(rejectRequest)
+ resolve(value)
+ }, rejectRequest)
+ })
+ }
+
+ try {
+ const elk = new ELK({
+ workerFactory: () => worker,
+ algorithms: ['layered'],
+ })
+ // Exercise the algorithm as well as worker registration before declaring it
+ // warm. Use a tiny graph so speculative work has a bounded input size.
+ await request(() =>
+ elk.layout({
+ id: 'warmup',
+ layoutOptions: { 'elk.algorithm': 'layered' },
+ children: [
+ { id: 'a', width: 1, height: 1 },
+ { id: 'b', width: 1, height: 1 },
+ ],
+ edges: [{ id: 'ab', sources: ['a'], targets: ['b'] }],
+ })
+ )
+ return { layout: (graph: ElkNode) => request(() => elk.layout(graph)) }
+ } catch (error) {
+ fail(error instanceof Error ? error : new Error(String(error)))
+ throw error
+ }
+}
diff --git a/src/renderer/routes/plugins/lib/call-graph-layout.test.ts b/src/renderer/routes/plugins/lib/call-graph-layout.test.ts
index ba1f3b49..b431f0aa 100644
--- a/src/renderer/routes/plugins/lib/call-graph-layout.test.ts
+++ b/src/renderer/routes/plugins/lib/call-graph-layout.test.ts
@@ -1,11 +1,55 @@
import type { ElkNode } from 'elkjs'
-import { describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
type CallGraphNodeLayout,
layoutCallGraphNodes,
} from './call-graph-layout'
import { buildCallGraphModel, type CallGraphModel } from './call-graph-model'
+const { createEngine } = vi.hoisted(() => ({ createEngine: vi.fn() }))
+vi.mock('./call-graph-engine', () => ({ createCallGraphEngine: createEngine }))
+
+describe('shared production layout engine', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ createEngine.mockReset().mockResolvedValue({
+ layout: async (graph: ElkNode) => validLayout(graph),
+ })
+ })
+
+ it('shares initialization across preloading and navigation', async () => {
+ const { preloadCallGraphLayout, layoutCallGraphNodes: layout } =
+ await import('./call-graph-layout')
+ const [first, second, result] = await Promise.all([
+ preloadCallGraphLayout(),
+ preloadCallGraphLayout(),
+ layout(model()),
+ ])
+ expect(first).toBeUndefined()
+ expect(second).toBeUndefined()
+ expect(Object.keys(result.positions)).toHaveLength(2)
+ expect(createEngine).toHaveBeenCalledOnce()
+ })
+
+ it('retries a failed speculative load when the graph is opened', async () => {
+ createEngine.mockRejectedValueOnce(new Error('Worker could not load'))
+ const { preloadCallGraphLayout, layoutCallGraphNodes: layout } =
+ await import('./call-graph-layout')
+ await expect(preloadCallGraphLayout()).resolves.toBeUndefined()
+ expect(Object.keys((await layout(model())).positions)).toHaveLength(2)
+ expect(createEngine).toHaveBeenCalledTimes(2)
+ })
+
+ it('replaces an engine that fails after successful initialization', async () => {
+ const { preloadCallGraphLayout, layoutCallGraphNodes: layout } =
+ await import('./call-graph-layout')
+ await preloadCallGraphLayout()
+ createEngine.mock.calls[0]?.[0]()
+ await layout(model())
+ expect(createEngine).toHaveBeenCalledTimes(2)
+ })
+})
+
function model(calls = 3): CallGraphModel {
return buildCallGraphModel(
{
diff --git a/src/renderer/routes/plugins/lib/call-graph-layout.ts b/src/renderer/routes/plugins/lib/call-graph-layout.ts
index c088d08a..cb977845 100644
--- a/src/renderer/routes/plugins/lib/call-graph-layout.ts
+++ b/src/renderer/routes/plugins/lib/call-graph-layout.ts
@@ -1,6 +1,5 @@
import type { XYPosition } from '@xyflow/react'
import type { ElkNode } from 'elkjs'
-import ELK from 'elkjs/lib/elk.bundled.js'
import type { CallGraphModel } from './call-graph-model'
export interface CallGraphNodeLayout {
@@ -21,7 +20,29 @@ const ELK_LAYOUT_OPTIONS = {
'elk.layered.spacing.nodeNodeBetweenLayers': '180',
} as const
-const productionElk: ElkLayoutAdapter = new ELK()
+let productionElk: Promise<ElkLayoutAdapter> | undefined
+
+function loadProductionElk(): Promise<ElkLayoutAdapter> {
+ if (!productionElk) {
+ const reset = () => {
+ if (productionElk === loading) productionElk = undefined
+ }
+ const loading = import('./call-graph-engine')
+ .then(({ createCallGraphEngine }) => createCallGraphEngine(reset))
+ .catch((error) => {
+ reset()
+ throw error
+ })
+ productionElk = loading
+ }
+ return productionElk
+}
+
+export async function preloadCallGraphLayout(): Promise<void> {
+ // Speculation must never surface an unhandled rejection. Actual navigation
+ // retries initialization and uses the graph's existing error/retry UI.
+ await loadProductionElk().catch(() => {})
+}
function compareStrings(left: string, right: string): number {
if (left < right) return -1
@@ -119,7 +140,7 @@ function toElkGraph(
export async function layoutCallGraphNodes(
model: Pick<CallGraphModel, 'nodes' | 'pairEdges' | 'signature'>,
previousLayout: CallGraphNodeLayout | null = null,
- elk: ElkLayoutAdapter = productionElk
+ elk?: ElkLayoutAdapter
): Promise<CallGraphNodeLayout> {
if (
previousLayout?.structuralSignature === model.signature &&
@@ -128,7 +149,8 @@ export async function layoutCallGraphNodes(
return previousLayout
}
- const laidOut = await elk.layout(toElkGraph(model))
+ const layout = elk ?? (await loadProductionElk())
+ const laidOut = await layout.layout(toElkGraph(model))
const positions = mapElkPositions(model.nodes, laidOut.children ?? [])
return {
diff --git a/src/renderer/routes/plugins/plugins-page.test.tsx b/src/renderer/routes/plugins/plugins-page.test.tsx
index 242de385..39619052 100644
--- a/src/renderer/routes/plugins/plugins-page.test.tsx
+++ b/src/renderer/routes/plugins/plugins-page.test.tsx
@@ -22,6 +22,10 @@ vi.mock('@renderer/lib/transport', () => ({
}))
const mockRefresh = vi.fn()
+const mockPreload = vi.fn()
+vi.mock('./hooks/use-call-graph-preload', () => ({
+ useCallGraphPreload: () => mockPreload,
+}))
let mockRefreshing = false
let mockList: PluginListDTO[] = []
let mockRegistry: RegistryPluginDTO[] = []
@@ -125,6 +129,7 @@ describe('PluginsPage', () => {
beforeEach(async () => {
mockRefreshing = false
mockRefresh.mockClear()
+ mockPreload.mockClear()
mockList = []
mockRegistry = []
mockInvoke.mockClear()
@@ -158,6 +163,15 @@ describe('PluginsPage', () => {
expect(mockInvoke).not.toHaveBeenCalledWith(Queries.GetPluginCommandGraph)
})
+ it('prepares diagnostics on pointer and keyboard intent', () => {
+ renderPage()
+ const diagnostics = screen.getByRole('link', { name: 'Diagnostics' })
+ fireEvent.pointerEnter(diagnostics)
+ fireEvent.focus(diagnostics)
+ fireEvent.pointerDown(diagnostics)
+ expect(mockPreload).toHaveBeenCalledTimes(3)
+ })
+
it('uses the first-use guide as the empty state without a duplicate hero', () => {
renderPage()
diff --git a/src/renderer/routes/plugins/plugins-page.tsx b/src/renderer/routes/plugins/plugins-page.tsx
index 64f940c9..9d254e71 100644
--- a/src/renderer/routes/plugins/plugins-page.tsx
+++ b/src/renderer/routes/plugins/plugins-page.tsx
@@ -21,6 +21,7 @@ import { Link } from 'react-router'
import { PluginCard } from './components/plugin-card'
import { PluginGuidance } from './components/plugin-guidance'
import { RegistryPluginCard } from './components/registry-plugin-card'
+import { useCallGraphPreload } from './hooks/use-call-graph-preload'
import { usePlugins } from './hooks/use-plugins'
import { useRegistryPlugins, useRegistryUpdates } from './hooks/use-registry'
import { matchesRegistrySearch } from './lib/registry-text'
@@ -30,6 +31,7 @@ import { usePluginsStore } from './store'
export function PluginsPage() {
const { t, i18n } = useTranslation()
const plugins = usePlugins()
+ const preloadDiagnostics = useCallGraphPreload()
const pluginsLoaded = usePluginsStore((state) => state.loaded)
const [installOpen, setInstallOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
@@ -80,6 +82,9 @@ export function PluginsPage() {
<ToolbarLink
label={diagnosticsLabel}
render={<Link to="/plugins/diagnostics" />}
+ onPointerEnter={preloadDiagnostics}
+ onFocus={preloadDiagnostics}
+ onPointerDown={preloadDiagnostics}
>
<CallGraphIcon aria-hidden="true" />
</ToolbarLink>
diff --git a/src/renderer/routes/settings/cards/settings-form-schemas.test.ts b/src/renderer/routes/settings/cards/settings-form-schemas.test.ts
index 3e6b5271..aebff0f4 100644
--- a/src/renderer/routes/settings/cards/settings-form-schemas.test.ts
+++ b/src/renderer/routes/settings/cards/settings-form-schemas.test.ts
@@ -1,5 +1,6 @@
import { i18n } from '@renderer/lib/i18n'
import { settingsValidationError } from '@renderer/lib/settings-validation'
+import { ensureI18nLocale } from '@shared/i18n-resources'
import {
DEFAULT_APP_SETTINGS,
DEFAULT_ENGINE_SETTINGS,
@@ -171,7 +172,8 @@ describe('Settings form schemas', () => {
['en-US', 'Enter a whole number from 1024 to 65535.'],
['zh-CN', '请输入 1024–65535 之间的整数。'],
['zh-TW', '請輸入 1024–65535 之間的整數。'],
- ])('explains numeric bounds in %s', (locale, message) => {
+ ] as const)('explains numeric bounds in %s', async (locale, message) => {
+ await ensureI18nLocale(i18n, locale)
const result = advancedFormSchema.safeParse(
{ ...DEFAULT_ENGINE_SETTINGS, rpcPort: 1e100 },
{
diff --git a/src/server/operator-admin.ts b/src/server/operator-admin.ts
index 929c81a4..9cceec2d 100644
--- a/src/server/operator-admin.ts
+++ b/src/server/operator-admin.ts
@@ -5,7 +5,7 @@ import {
resolveSupportedLocale,
SUPPORTED_LOCALE_CODES,
} from '@shared/constants/locales'
-import { I18N_RESOURCES } from '@shared/i18n-resources'
+import { I18N_RESOURCES, loadI18nLocale } from '@shared/i18n-resources'
import {
BridgeCommands,
BridgeQueries,
@@ -217,7 +217,10 @@ async function createTranslator(env: NodeJS.ProcessEnv): Promise<Translate> {
const locale = resolveSupportedLocale(env.MOTRIX_HOST_LANGUAGE, env.LANG)
const instance = createInstance()
await instance.init({
- resources: I18N_RESOURCES,
+ resources: {
+ ...I18N_RESOURCES,
+ [locale]: { translation: await loadI18nLocale(locale) },
+ },
supportedLngs: SUPPORTED_LOCALE_CODES,
lng: locale,
fallbackLng: FALLBACK_LOCALE,
diff --git a/src/shared/i18n-resource-loading.test.ts b/src/shared/i18n-resource-loading.test.ts
new file mode 100644
index 00000000..02d3e1e6
--- /dev/null
+++ b/src/shared/i18n-resource-loading.test.ts
@@ -0,0 +1,45 @@
+import { createInstance } from 'i18next'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ ensureI18nLocale,
+ I18N_BACKEND,
+ I18N_RESOURCE_LOADERS,
+ I18N_RESOURCES,
+ loadI18nLocale,
+} from './i18n-resources'
+
+afterEach(() => vi.restoreAllMocks())
+
+describe('on-demand bundled translations', () => {
+ it('starts with English and Simplified Chinese and resolves a requested locale through the backend', async () => {
+ const instance = createInstance().use(I18N_BACKEND)
+ await instance.init({
+ lng: 'en-US',
+ fallbackLng: 'en-US',
+ supportedLngs: ['en-US', 'de'],
+ resources: { ...I18N_RESOURCES },
+ partialBundledLanguages: true,
+ })
+ expect(instance.hasResourceBundle('de', 'translation')).toBe(false)
+ await instance.changeLanguage('de')
+ expect(instance.t('common.retry')).toBe('Erneut versuchen')
+ expect(Object.keys(I18N_RESOURCES)).toEqual(['en-US', 'zh-CN'])
+ })
+
+ it('shares concurrent loads and keeps a failed load retryable', async () => {
+ const instance = createInstance()
+ await instance.init({ lng: 'en-US', resources: { ...I18N_RESOURCES } })
+ const unavailable = new Error('locale chunk unavailable')
+ const loader = vi
+ .spyOn(I18N_RESOURCE_LOADERS, 'fr')
+ .mockRejectedValueOnce(unavailable)
+ const first = loadI18nLocale('fr')
+ expect(loadI18nLocale('fr')).toBe(first)
+ await expect(ensureI18nLocale(instance, 'fr')).rejects.toBe(unavailable)
+ expect(instance.hasResourceBundle('fr', 'translation')).toBe(false)
+ expect(loader).toHaveBeenCalledOnce()
+ await ensureI18nLocale(instance, 'fr')
+ expect(loader).toHaveBeenCalledTimes(2)
+ expect(instance.getFixedT('fr')('common.retry')).toBe('Réessayer')
+ })
+})
diff --git a/src/shared/i18n-resources.test.ts b/src/shared/i18n-resources.test.ts
index d1ee2cac..c2dc5fb7 100644
--- a/src/shared/i18n-resources.test.ts
+++ b/src/shared/i18n-resources.test.ts
@@ -1,4 +1,4 @@
-import { I18N_RESOURCES } from '@shared/i18n-resources'
+import { I18N_RESOURCES } from '@test-utils/i18n-resources'
import { createInstance } from 'i18next'
import { describe, expect, it } from 'vitest'
diff --git a/src/shared/i18n-resources.ts b/src/shared/i18n-resources.ts
index b4fd90c7..77e5f4fc 100644
--- a/src/shared/i18n-resources.ts
+++ b/src/shared/i18n-resources.ts
@@ -1,56 +1,94 @@
-import type { SupportedLocale } from '@shared/constants/locales'
-import ar from '@shared/locales/ar.json'
-import bg from '@shared/locales/bg.json'
-import ca from '@shared/locales/ca.json'
-import de from '@shared/locales/de.json'
-import el from '@shared/locales/el.json'
+import {
+ isSupportedLocale,
+ type SupportedLocale,
+} from '@shared/constants/locales'
import enUS from '@shared/locales/en-US.json'
-import es from '@shared/locales/es.json'
-import fa from '@shared/locales/fa.json'
-import fr from '@shared/locales/fr.json'
-import hu from '@shared/locales/hu.json'
-import id from '@shared/locales/id.json'
-import it from '@shared/locales/it.json'
-import ja from '@shared/locales/ja.json'
-import ko from '@shared/locales/ko.json'
-import nb from '@shared/locales/nb.json'
-import nl from '@shared/locales/nl.json'
-import pl from '@shared/locales/pl.json'
-import ptBR from '@shared/locales/pt-BR.json'
-import ro from '@shared/locales/ro.json'
-import ru from '@shared/locales/ru.json'
-import th from '@shared/locales/th.json'
-import tr from '@shared/locales/tr.json'
-import uk from '@shared/locales/uk.json'
-import vi from '@shared/locales/vi.json'
import zhCN from '@shared/locales/zh-CN.json'
-import zhTW from '@shared/locales/zh-TW.json'
+import type { BackendModule, i18n } from 'i18next'
+// Keep English and Simplified Chinese synchronous; other bundled locales load on demand.
export const I18N_RESOURCES = {
- ar: { translation: ar },
- bg: { translation: bg },
- ca: { translation: ca },
- de: { translation: de },
- el: { translation: el },
'en-US': { translation: enUS },
- es: { translation: es },
- fa: { translation: fa },
- fr: { translation: fr },
- hu: { translation: hu },
- id: { translation: id },
- it: { translation: it },
- ja: { translation: ja },
- ko: { translation: ko },
- nb: { translation: nb },
- nl: { translation: nl },
- pl: { translation: pl },
- 'pt-BR': { translation: ptBR },
- ro: { translation: ro },
- ru: { translation: ru },
- th: { translation: th },
- tr: { translation: tr },
- uk: { translation: uk },
- vi: { translation: vi },
'zh-CN': { translation: zhCN },
- 'zh-TW': { translation: zhTW },
-} satisfies Record<SupportedLocale, { translation: Record<string, unknown> }>
+}
+
+export const I18N_RESOURCE_LOADERS = {
+ ar: () => import('@shared/locales/ar.json'),
+ bg: () => import('@shared/locales/bg.json'),
+ ca: () => import('@shared/locales/ca.json'),
+ de: () => import('@shared/locales/de.json'),
+ el: () => import('@shared/locales/el.json'),
+ 'en-US': async () => ({ default: enUS }),
+ es: () => import('@shared/locales/es.json'),
+ fa: () => import('@shared/locales/fa.json'),
+ fr: () => import('@shared/locales/fr.json'),
+ hu: () => import('@shared/locales/hu.json'),
+ id: () => import('@shared/locales/id.json'),
+ it: () => import('@shared/locales/it.json'),
+ ja: () => import('@shared/locales/ja.json'),
+ ko: () => import('@shared/locales/ko.json'),
+ nb: () => import('@shared/locales/nb.json'),
+ nl: () => import('@shared/locales/nl.json'),
+ pl: () => import('@shared/locales/pl.json'),
+ 'pt-BR': () => import('@shared/locales/pt-BR.json'),
+ ro: () => import('@shared/locales/ro.json'),
+ ru: () => import('@shared/locales/ru.json'),
+ th: () => import('@shared/locales/th.json'),
+ tr: () => import('@shared/locales/tr.json'),
+ uk: () => import('@shared/locales/uk.json'),
+ vi: () => import('@shared/locales/vi.json'),
+ 'zh-CN': async () => ({ default: zhCN }),
+ 'zh-TW': () => import('@shared/locales/zh-TW.json'),
+} satisfies Record<
+ SupportedLocale,
+ () => Promise<{ default: Record<string, unknown> }>
+>
+
+const pending = new Map<SupportedLocale, Promise<Record<string, unknown>>>()
+
+export function loadI18nLocale(
+ locale: SupportedLocale
+): Promise<Record<string, unknown>> {
+ const existing = pending.get(locale)
+ if (existing) return existing
+ const next = I18N_RESOURCE_LOADERS[locale]()
+ .then((module) => module.default)
+ .catch((error) => {
+ pending.delete(locale)
+ throw error
+ })
+ pending.set(locale, next)
+ return next
+}
+
+export async function ensureI18nLocale(
+ instance: i18n,
+ locale: SupportedLocale
+): Promise<void> {
+ if (instance.hasResourceBundle(locale, 'translation')) return
+ const translation = await loadI18nLocale(locale)
+ instance.addResourceBundle(locale, 'translation', translation)
+}
+
+// Also supports i18next consumers that call changeLanguage directly.
+export const I18N_BACKEND: BackendModule = {
+ type: 'backend',
+ init() {},
+ read(language, namespace, callback) {
+ if (!isSupportedLocale(language) || namespace !== 'translation') {
+ callback(
+ new Error(`Unsupported translation resource: ${language}/${namespace}`),
+ false
+ )
+ return
+ }
+ void loadI18nLocale(language).then(
+ (translation) => callback(null, translation),
+ (error: unknown) =>
+ callback(
+ error instanceof Error ? error : new Error(String(error)),
+ false
+ )
+ )
+ },
+}
diff --git a/src/shared/utils/localized-byte-format.test.ts b/src/shared/utils/localized-byte-format.test.ts
index 529c42ea..ee266690 100644
--- a/src/shared/utils/localized-byte-format.test.ts
+++ b/src/shared/utils/localized-byte-format.test.ts
@@ -1,6 +1,6 @@
import { SUPPORTED_LOCALE_CODES } from '@shared/constants/locales'
-import { I18N_RESOURCES } from '@shared/i18n-resources'
import type { ByteUnitSystem } from '@shared/schemas/byte-unit-system'
+import { I18N_RESOURCES } from '@test-utils/i18n-resources'
import { createInstance } from 'i18next'
import { beforeAll, describe, expect, it } from 'vitest'
import { createLocalizedByteFormatter } from './localized-byte-format'
diff --git a/src/test-utils/i18n-resources.ts b/src/test-utils/i18n-resources.ts
new file mode 100644
index 00000000..04c56e32
--- /dev/null
+++ b/src/test-utils/i18n-resources.ts
@@ -0,0 +1,19 @@
+import { I18N_RESOURCE_LOADERS } from '@shared/i18n-resources'
+
+type AllResources = {
+ [Locale in keyof typeof I18N_RESOURCE_LOADERS]: {
+ translation: Awaited<
+ ReturnType<(typeof I18N_RESOURCE_LOADERS)[Locale]>
+ >['default']
+ }
+}
+
+// Translation assertions intentionally preload every language; production does not.
+export const I18N_RESOURCES = Object.fromEntries(
+ await Promise.all(
+ Object.entries(I18N_RESOURCE_LOADERS).map(async ([locale, load]) => [
+ locale,
+ { translation: (await load()).default },
+ ])
+ )
+) as AllResources
diff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.ts
new file mode 100644
index 00000000..3b3371ee
--- /dev/null
+++ b/tests/scripts/production-build.test.ts
@@ -0,0 +1,76 @@
+import { execFileSync } from 'node:child_process'
+import path from 'node:path'
+import { beforeAll, describe, expect, it } from 'vitest'
+
+const MIB = 1024 * 1024
+const ROOT = path.resolve(import.meta.dirname, '../..')
+const TARGETS = [
+ { name: 'main', initial: 2 * MIB, total: 5 * MIB },
+ { name: 'preload', initial: 80 * 1024, total: 80 * 1024 },
+ { name: 'worker', initial: 48 * 1024, total: 48 * 1024 },
+ { name: 'renderer', initial: 2.75 * MIB, total: 8 * MIB },
+ { name: 'renderer.web', initial: 2.75 * MIB, total: 8 * MIB },
+ { name: 'server', initial: 2 * MIB, total: 5 * MIB },
+]
+
+interface BundleMetrics {
+ copiesPublicAssets: boolean
+ totalBytes: number
+ initialBytes: number
+ initialChunks: number
+ sourceMaps: number
+ initialLocales: string[]
+ bundledLocales: string[]
+ initialElk: boolean
+ bundledElk: boolean
+ javascriptAssetBytes: number
+ javascriptAssetCount: number
+}
+
+let report: Record<string, BundleMetrics>
+beforeAll(() => {
+ // Vite respects an inherited NODE_ENV=test even in production mode. Build in
+ // a separate process so these assertions exercise shipped React, not dev React.
+ report = JSON.parse(
+ execFileSync(
+ process.execPath,
+ [path.join(ROOT, 'scripts/measure-production-bundles.mjs')],
+ {
+ cwd: ROOT,
+ env: { ...process.env, NODE_ENV: 'production' },
+ encoding: 'utf8',
+ maxBuffer: MIB,
+ timeout: 60_000,
+ }
+ )
+ )
+}, 65_000)
+
+describe('production bundle loading and size contracts', () => {
+ it.each(TARGETS)(
+ '$name keeps deferred resources out of startup and fits its JS budgets',
+ (target) => {
+ const result = report[target.name]
+ expect(result.copiesPublicAssets).toBe(target.name.startsWith('renderer'))
+ expect(result.initialChunks).toBeGreaterThan(0)
+ expect(result.initialBytes).toBeLessThanOrEqual(target.initial)
+ expect(result.totalBytes).toBeLessThanOrEqual(target.total)
+ expect(result.sourceMaps).toBe(0)
+ if (
+ ['main', 'server', 'renderer', 'renderer.web'].includes(target.name)
+ ) {
+ expect(result.initialLocales).toEqual(['en-US', 'zh-CN'])
+ expect(result.bundledLocales).toHaveLength(26)
+ }
+ if (target.name.startsWith('renderer')) {
+ expect(result.initialElk).toBe(false)
+ expect(result.bundledElk).toBe(true)
+ expect(result.javascriptAssetCount).toBe(1)
+ expect(result.javascriptAssetBytes).toBeGreaterThan(MIB)
+ expect(result.totalBytes).toBeGreaterThan(
+ result.initialBytes + result.javascriptAssetBytes
+ )
+ }
+ }
+ )
+})
diff --git a/vite.main.config.ts b/vite.main.config.ts
index 55612564..731c814e 100644
--- a/vite.main.config.ts
+++ b/vite.main.config.ts
@@ -1,6 +1,7 @@
import { builtinModules, createRequire } from 'node:module'
import path from 'node:path'
import { defineConfig } from 'vite'
+import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const require = createRequire(import.meta.url)
const pkg = require('./package.json') as {
@@ -52,9 +53,12 @@ function isExternal(id: string): boolean {
}
export default defineConfig({
+ publicDir: false,
build: {
outDir: 'dist/main',
emptyOutDir: true,
+ minify: 'oxc',
+ sourcemap: false,
target: 'node20',
lib: {
entry: 'src/main/index.ts',
@@ -62,6 +66,7 @@ export default defineConfig({
fileName: () => 'index.cjs',
},
rollupOptions: {
+ output: PRODUCTION_OUTPUT,
external: isExternal,
},
},
diff --git a/vite.preload.config.ts b/vite.preload.config.ts
index 625c4ec9..7a61087c 100644
--- a/vite.preload.config.ts
+++ b/vite.preload.config.ts
@@ -1,13 +1,17 @@
import { builtinModules } from 'node:module'
import path from 'node:path'
import { defineConfig } from 'vite'
+import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const nodeExternals = builtinModules.flatMap((m) => [m, `node:${m}`])
export default defineConfig({
+ publicDir: false,
build: {
outDir: 'dist/preload',
emptyOutDir: true,
+ minify: 'oxc',
+ sourcemap: false,
target: 'node20',
lib: {
entry: 'src/preload/preload.ts',
@@ -15,6 +19,7 @@ export default defineConfig({
fileName: () => 'preload.cjs',
},
rollupOptions: {
+ output: PRODUCTION_OUTPUT,
external: ['electron', ...nodeExternals],
},
},
diff --git a/vite.renderer.config.ts b/vite.renderer.config.ts
index 318c5d9f..f0722d87 100644
--- a/vite.renderer.config.ts
+++ b/vite.renderer.config.ts
@@ -2,12 +2,14 @@ import path from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import packageJson from './package.json' with { type: 'json' }
+import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
export default defineConfig(({ command }) => ({
// Electron file:// + asar needs relative asset paths; the default
// '/' resolves to the filesystem root, not inside the asar.
base: './',
plugins: [tailwindcss()],
+ worker: { rollupOptions: { output: PRODUCTION_OUTPUT } },
define: {
__MOTRIX_TARGET__: JSON.stringify('electron'),
__MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(
@@ -21,8 +23,12 @@ export default defineConfig(({ command }) => ({
}),
},
build: {
+ cssMinify: 'lightningcss',
+ rollupOptions: { output: PRODUCTION_OUTPUT },
outDir: 'dist/renderer',
emptyOutDir: true,
+ minify: 'oxc',
+ sourcemap: false,
},
resolve: {
alias: {
diff --git a/vite.renderer.web.config.ts b/vite.renderer.web.config.ts
index f57183b5..1a5a1c3e 100644
--- a/vite.renderer.web.config.ts
+++ b/vite.renderer.web.config.ts
@@ -2,10 +2,12 @@ import path from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import packageJson from './package.json' with { type: 'json' }
+import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
export default defineConfig({
base: '/',
plugins: [tailwindcss()],
+ worker: { rollupOptions: { output: PRODUCTION_OUTPUT } },
define: {
__MOTRIX_TARGET__: JSON.stringify('web'),
__MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(false),
@@ -17,8 +19,12 @@ export default defineConfig({
}),
},
build: {
+ cssMinify: 'lightningcss',
+ rollupOptions: { output: PRODUCTION_OUTPUT },
outDir: 'dist/renderer-web',
emptyOutDir: true,
+ minify: 'oxc',
+ sourcemap: false,
},
resolve: {
alias: {
diff --git a/vite.server.config.ts b/vite.server.config.ts
index ccbaf010..5892378c 100644
--- a/vite.server.config.ts
+++ b/vite.server.config.ts
@@ -1,6 +1,7 @@
import { builtinModules, createRequire } from 'node:module'
import path from 'node:path'
import { defineConfig } from 'vite'
+import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const require = createRequire(import.meta.url)
const pkg = require('./package.json') as {
@@ -24,9 +25,12 @@ function isExternal(id: string): boolean {
}
export default defineConfig({
+ publicDir: false,
build: {
outDir: 'dist/server',
emptyOutDir: true,
+ minify: 'oxc',
+ sourcemap: false,
target: 'node22',
ssr: true,
lib: {
@@ -39,11 +43,11 @@ export default defineConfig({
rollupOptions: {
external: isExternal,
output: {
+ ...PRODUCTION_OUTPUT,
+ // Preserve the names used in diagnostics by the previously unminified host.
+ keepNames: true,
entryFileNames: '[name].mjs',
chunkFileNames: 'chunks/[name]-[hash].mjs',
- // Source documentation is not runtime payload. Preserve legal notices
- // and optimization annotations without minifying names or code.
- comments: { jsdoc: false, legal: true, annotation: true },
},
},
},
diff --git a/vite.worker.config.ts b/vite.worker.config.ts
index c4e274ca..90698b45 100644
--- a/vite.worker.config.ts
+++ b/vite.worker.config.ts
@@ -1,6 +1,7 @@
import { builtinModules, createRequire } from 'node:module'
import path from 'node:path'
import { defineConfig } from 'vite'
+import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const require = createRequire(import.meta.url)
const pkg = require('./package.json') as {
@@ -26,9 +27,12 @@ function isExternal(id: string): boolean {
}
export default defineConfig({
+ publicDir: false,
build: {
outDir: 'dist/core/plugin/host',
emptyOutDir: true,
+ minify: 'oxc',
+ sourcemap: false,
target: 'node20',
lib: {
entry: 'src/core/plugin/host/quick-js-worker.ts',
@@ -36,6 +40,7 @@ export default defineConfig({
fileName: () => 'quick-js-worker.cjs',
},
rollupOptions: {
+ output: PRODUCTION_OUTPUT,
external: isExternal,
},
},