Files
openchamber/packages/web/vite.config.ts
T
Shyamalan KannanandShyamalan Kannan ecb22e19c3 perf: lazy-load heavy dependencies (MarkdownRenderer + CodeMirror languages) (#997)
* perf: drastically improve cold-start, bundle size, and streaming performance

Cold-start optimizations:
- main.tsx: Remove blocking await on prefs I/O — render immediately with
  defaults, hydrate persisted settings asynchronously. Cuts 50-200ms from
  time-to-first-paint.
- bootstrap.ts: Split directory bootstrap into 3 phases:
  * Phase 1 (blocking): path, config, provider, session status — minimum
    data needed to render UI. Mark status complete after this phase.
    path.get and session.status must both succeed; they have no fallback.
  * Phase 2 (deferred): agents, commands, mcp, lsp, vcs, questions,
    permissions — fetched after first paint without blocking.
  * Phase 3 (lazy): session messages — loaded without blocking init.
- App.tsx: Keep identical provider tree before/after init to prevent
  full subtree remount when isInitialized flips. FireworksProvider and
  VoiceProvider are lightweight shells; overlays deferred until init.

Bundle-size optimizations:
- App.tsx + MainLayout.tsx + VSCodeLayout.tsx: Code-split heavy views
  (SettingsView, GitView, DiffView, TerminalView, FilesView, PlanView,
  OnboardingScreen, SettingsWindow, MultiRunWindow) with React.lazy.
  Views load on demand when user switches panels.
- vite.config.ts: Lower chunkSizeWarningLimit from 1200KB to 500KB.

Streaming render optimizations:
- streaming.ts: Throttle streaming store writes ~60Hz → ~1Hz. Busy-session
  only scan (Set, O(1)).
- MessageList.tsx: Lower virtualization threshold 40 → 15.
- ChatMessage.tsx: React.memo with areRenderRelevantMessagesEqual.
- MarkdownRenderer.tsx: React.memo with explicit prop comparators.

* fix: address Greptile review feedback on bootstrap and provider tree

- bootstrap.ts: Tighten Phase 1 error guard. path.get and session.status
  must both succeed; they have no global fallback.
- bootstrap.ts: Replace dead .catch() on Promise.allSettled() with .then()
  that inspects individual results for errors.
- App.tsx: Keep identical provider tree before/after init to prevent full
  subtree remount when isInitialized flips.

* perf: lazy-load heavy dependencies (MarkdownRenderer + CodeMirror languages)

MarkdownRenderer dynamic import:
- Move heavy implementation (marked, react-markdown, beautiful-mermaid,
  react-syntax-highlighter, ~1500 lines) to MarkdownRendererImpl.tsx
- Replace MarkdownRenderer.tsx with thin lazy wrapper using React.lazy
- All 11 existing imports work unchanged — no consumer code modified
- Full markdown stack loads on first render of markdown content

CodeMirror language lazy loading:
- languageByExtension.ts: remove static imports for 10+ less-common
  language packages (@codemirror/lang-go, lang-rust, lang-sql, etc.)
- Keep only 6 most common languages static: javascript, json, css, html,
  markdown, python, shell
- Less common languages return null from languageByExtension, causing
  callers to fall back to loadLanguageByExtension which dynamically
  loads from @codemirror/language-data
- Reduces initial bundle by ~200KB+ of language parsers

---------

Co-authored-by: Shyamalan Kannan <yabuku@Shyamalans-MacBook-Pro.local>
2026-04-23 12:31:42 +03:00

130 lines
4.3 KiB
TypeScript

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { VitePWA } from 'vite-plugin-pwa';
import { themeStoragePlugin } from '../../vite-theme-plugin';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const packageJson = JSON.parse(readFileSync(path.resolve(__dirname, 'package.json'), 'utf-8'));
const pwaDevEnabled = process.env.OPENCHAMBER_DISABLE_PWA_DEV !== '1';
const reactScanToggle = (process.env.VITE_ENABLE_REACT_SCAN ?? '').toLowerCase();
const enableReactScan = reactScanToggle === '1' || reactScanToggle === 'true' || reactScanToggle === 'on' || reactScanToggle === 'yes';
export default defineConfig({
root: path.resolve(__dirname, '.'),
plugins: [
react({
babel: {
plugins: ['babel-plugin-react-compiler'],
},
}),
{
name: 'inject-react-scan-script',
transformIndexHtml() {
if (!enableReactScan) {
return;
}
return [
{
tag: 'script',
attrs: {
crossorigin: 'anonymous',
src: '//unpkg.com/react-scan/dist/auto.global.js',
},
injectTo: 'head-prepend',
},
];
},
},
themeStoragePlugin(),
VitePWA({
strategies: 'injectManifest',
srcDir: 'src',
filename: 'sw.ts',
registerType: 'autoUpdate',
injectRegister: false,
manifest: false,
injectManifest: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff,woff2,ttf,otf,eot}'],
// iOS Safari/PWA is much more reliable with a classic (non-module) SW bundle.
rollupFormat: 'iife',
// We already keep a custom manifest in index.html
injectionPoint: undefined,
},
devOptions: {
enabled: pwaDevEnabled,
type: 'module',
},
}),
],
resolve: {
alias: [
{ find: '@opencode-ai/sdk/v2', replacement: path.resolve(__dirname, '../../node_modules/@opencode-ai/sdk/dist/v2/client.js') },
{ find: '@openchamber/ui', replacement: path.resolve(__dirname, '../ui/src') },
{ find: '@web', replacement: path.resolve(__dirname, './src') },
{ find: '@', replacement: path.resolve(__dirname, '../ui/src') },
],
},
worker: {
format: 'es',
},
define: {
'process.env': {},
global: 'globalThis',
__APP_VERSION__: JSON.stringify(packageJson.version),
},
optimizeDeps: {
include: ['@opencode-ai/sdk/v2'],
},
server: {
port: 5173,
proxy: {
'/auth': {
target: `http://127.0.0.1:${process.env.OPENCHAMBER_PORT || 3001}`,
changeOrigin: true,
},
'/health': {
target: `http://127.0.0.1:${process.env.OPENCHAMBER_PORT || 3001}`,
changeOrigin: true,
},
'/api': {
target: `http://127.0.0.1:${process.env.OPENCHAMBER_PORT || 3001}`,
changeOrigin: true,
ws: true,
},
},
},
build: {
outDir: path.resolve(__dirname, 'dist'),
emptyOutDir: true,
chunkSizeWarningLimit: 500,
rollupOptions: {
external: ['node:child_process', 'node:fs', 'node:path', 'node:url'],
output: {
manualChunks(id) {
if (!id.includes('node_modules')) return undefined;
const match = id.split('node_modules/')[1];
if (!match) return undefined;
const segments = match.split('/');
const packageName = match.startsWith('@') ? `${segments[0]}/${segments[1]}` : segments[0];
if (packageName === 'react' || packageName === 'react-dom') return 'vendor-react';
if (packageName === 'zustand' || packageName === 'zustand/middleware') return 'vendor-zustand';
if (packageName === '@opencode-ai/sdk') return 'vendor-opencode-sdk';
if (packageName.includes('remark') || packageName.includes('rehype') || packageName === 'react-markdown') return 'vendor-markdown';
if (packageName === '@base-ui/react' || packageName.startsWith('@base-ui')) return 'vendor-base-ui';
if (packageName.includes('react-syntax-highlighter') || packageName.includes('highlight.js')) return 'vendor-syntax';
const sanitized = packageName.replace(/^@/, '').replace(/\//g, '-');
return `vendor-${sanitized}`;
},
},
},
},
});