perf(mobile): load the terminal engine and the session dock only when needed (#40515)

* perf(mobile): load the terminal engine and the session dock only when needed

Opening a session parsed xterm (with its WebGL addon) and the wide-layout
dock's Source Control and Files panels, even for chat sessions on phones.
The page's terminal now imports its engine when the first terminal mounts,
and the dock lazy-loads its panels behind a frame that paints at once.

The page build anchors lazy modules that share boot code the way it already
anchors routes, so the new lazy chunks don't split the boot chunks.

* fix(mobile): show the terminal start error when replaying queued commands throws
This commit is contained in:
Kelvin Amoaba
2026-11-09 23:46:50 +00:00
committed by GitHub
parent a96a028e3a
commit 2ee151827a
5 changed files with 267 additions and 150 deletions
@@ -24,6 +24,13 @@ import {
routePathnameFromKey
} from '../../mobile-web-app/mobile-web-app-route-manifest.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs'
import {
ROUTE_ENTRY_NAMESPACE,
entryStaticClosure,
isScriptOutput,
lazyModulesToAnchor,
sharedModulesToMerge
} from './mobile-web-app-chunk-grouping.mjs'
const projectDir = fileURLToPath(new URL('../../../..', import.meta.url))
const mobileDir = join(projectDir, 'mobile')
@@ -134,7 +141,7 @@ const HAIRLINE_PLUGIN_NAME = 'orca-hairline-device-pixel'
const ENTRY_CHUNK_NAME = 'entry'
const ROUTE_MANIFEST_MODULE = /web-entry[\\/]route-manifest(\.ts)?$/
const ROUTE_ENTRY_NAMESPACE = 'orca-route-entry'
const LAZY_ENTRY_NAMESPACE = 'orca-lazy-entry'
// The entry's static imports as written, minus the manifest: a route importing it would be an output cycle.
async function entryImportAnchors() {
@@ -160,8 +167,14 @@ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
// Keep typed route-manifest file for TS/Metro resolution; replace only its body for web.
// Routes import the entry's imports first, so esbuild keeps those modules in one chunk instead of one per route subset.
// Routes also import every module in sharedModules, which esbuild then puts in one chunk all routes load.
function routeManifestPlugin(manifestSource, routes, sharedModules) {
// Lazy modules in anchoredLazyModules (path to export names) get the same imports, so they don't split those chunks either.
function routeManifestPlugin(manifestSource, routes, sharedModules, anchoredLazyModules) {
let anchors
const anchoredImports = async () => {
anchors ??= entryImportAnchors()
const shared = sharedModules.map((module) => `import ${JSON.stringify(module)}\n`).join('')
return `${await anchors}${shared}`
}
return {
name: ROUTE_MANIFEST_PLUGIN_NAME,
setup(build) {
@@ -170,26 +183,43 @@ function routeManifestPlugin(manifestSource, routes, sharedModules) {
loader: 'js',
resolveDir: mobileDir
}))
if (routes.length === 0) {
return
}
const routeImport = new RegExp(
`^(?:${routes.map(({ module }) => escapeRegExp(module)).join('|')})$`
)
build.onResolve({ filter: routeImport }, (args) =>
args.kind === 'dynamic-import'
? { path: args.path, namespace: ROUTE_ENTRY_NAMESPACE }
: undefined
)
build.onLoad({ filter: /.*/, namespace: ROUTE_ENTRY_NAMESPACE }, async (args) => {
anchors ??= entryImportAnchors()
const shared = sharedModules.map((module) => `import ${JSON.stringify(module)}\n`).join('')
return {
contents: `${await anchors}${shared}export { default } from ${JSON.stringify(args.path)}\n`,
if (routes.length > 0) {
const routeImport = new RegExp(
`^(?:${routes.map(({ module }) => escapeRegExp(module)).join('|')})$`
)
build.onResolve({ filter: routeImport }, (args) =>
args.kind === 'dynamic-import'
? { path: args.path, namespace: ROUTE_ENTRY_NAMESPACE }
: undefined
)
build.onLoad({ filter: /.*/, namespace: ROUTE_ENTRY_NAMESPACE }, async (args) => ({
contents: `${await anchoredImports()}export { default } from ${JSON.stringify(args.path)}\n`,
loader: 'js',
resolveDir: dirname(entryPoint)
}))
}
if (anchoredLazyModules.size === 0) {
return
}
build.onResolve({ filter: /.*/ }, async (args) => {
if (args.kind !== 'dynamic-import' || args.pluginData === LAZY_ENTRY_NAMESPACE) {
return undefined
}
const { path, errors } = await build.resolve(args.path, {
kind: args.kind,
importer: args.importer,
resolveDir: args.resolveDir,
pluginData: LAZY_ENTRY_NAMESPACE
})
return errors.length === 0 && anchoredLazyModules.has(path)
? { path, namespace: LAZY_ENTRY_NAMESPACE }
: undefined
})
build.onLoad({ filter: /.*/, namespace: LAZY_ENTRY_NAMESPACE }, async (args) => ({
contents: `${await anchoredImports()}export { ${anchoredLazyModules.get(args.path).join(', ')} } from ${JSON.stringify(args.path)}\n`,
loader: 'js',
resolveDir: dirname(entryPoint)
}))
}
}
}
@@ -234,7 +264,11 @@ const hairlineDevicePixelPlugin = {
}
/** Split out so a test can read the options MOBILE_WEB_APP_SHIMS claims, without a build. */
export function mobileWebAppBuildOptions(routes, sharedModules = []) {
export function mobileWebAppBuildOptions(
routes,
sharedModules = [],
anchoredLazyModules = new Map()
) {
return {
// Fixed so no absolute path of this checkout can reach the output.
absWorkingDir: mobileDir,
@@ -267,7 +301,12 @@ export function mobileWebAppBuildOptions(routes, sharedModules = []) {
zod: MOBILE_ZOD_PACKAGE
},
plugins: [
routeManifestPlugin(renderMobileWebAppRouteManifest(routes), routes, sharedModules),
routeManifestPlugin(
renderMobileWebAppRouteManifest(routes),
routes,
sharedModules,
anchoredLazyModules
),
lucideBarrelPlugin,
hairlineDevicePixelPlugin
],
@@ -311,66 +350,6 @@ export function mobileWebAppBuildOptions(routes, sharedModules = []) {
}
}
// Budget entry plus transitive static imports, stopping at dynamic imports; entry-only limits let shared initial chunks grow unseen.
export function entryStaticClosure(metafile, entryOutputPath) {
const reached = new Set([entryOutputPath])
for (const current of reached) {
for (const imported of metafile.outputs[current]?.imports ?? []) {
if (imported.kind !== 'import-statement' || reached.has(imported.path)) {
continue
}
reached.add(imported.path)
}
}
return reached
}
// esbuild cuts a chunk per set of routes sharing a module; one this small costs more as a request than as code every route loads.
const MERGED_SHARED_CHUNK_MAX_BYTES = 16 * 1024
// Small route-shared chunks whose static imports already load at boot or merge too, so merging adds only their own bytes.
// ESM only: a bare import runs a CommonJS module's body at route load, not where its importer first needs it.
function sharedModulesToMerge(metafile, entryOutputPath) {
const { inputs, outputs } = metafile
const boot = entryStaticClosure(metafile, entryOutputPath)
const routeReached = new Set(
Object.entries(outputs)
.filter(([, output]) => output.entryPoint?.startsWith(`${ROUTE_ENTRY_NAMESPACE}:`))
.flatMap(([path]) => [...entryStaticClosure(metafile, path)])
)
const merged = new Set(
Object.entries(outputs)
.filter(
([path, output]) =>
isScriptOutput(path) &&
!output.entryPoint &&
!boot.has(path) &&
routeReached.has(path) &&
output.bytes <= MERGED_SHARED_CHUNK_MAX_BYTES &&
Object.keys(output.inputs).every((input) => inputs[input]?.format === 'esm')
)
.map(([path]) => path)
)
const importsUnmerged = (path) =>
outputs[path].imports.some(
({ kind, path: imported }) =>
kind === 'import-statement' && !boot.has(imported) && !merged.has(imported)
)
for (let dropped = true; dropped;) {
dropped = false
for (const path of merged) {
if (importsUnmerged(path)) {
merged.delete(path)
dropped = true
}
}
}
return [...merged]
.flatMap((path) => Object.keys(outputs[path].inputs))
.sort()
.map((input) => resolve(mobileDir, input))
}
// Hash final output bytes leaf-first, rewriting dependency names before hashing importers.
// esbuild hashes checkout-dependent input paths; renaming makes manifest hashes/import URLs agree and avoids redownloading identical bundles across checkouts.
export function renameOutputsByContent(metafile, outputFiles) {
@@ -438,8 +417,6 @@ export function routeChunkNames(metafile, routes, renamed) {
)
}
const isScriptOutput = (path) => path.endsWith('.js')
// appDir is a seam for the tests, which bundle a scratch route tree; production always uses mobile/app.
// Page closure includes ancestor layouts as entry modules, not just route imports.
export async function mobileWebAppRouteClosure(routeModule) {
@@ -532,10 +509,12 @@ function entryOutput(metafile) {
// The page's scripts as shipped: a first build finds the small shared chunks, a second merges them.
export async function buildMobileWebAppScripts(routes) {
const split = await esbuild.build(mobileWebAppBuildOptions(routes))
const sharedModules = sharedModulesToMerge(split.metafile, entryOutput(split.metafile))
return sharedModules.length === 0
const entryOutputPath = entryOutput(split.metafile)
const sharedModules = sharedModulesToMerge(split.metafile, entryOutputPath)
const anchoredLazyModules = lazyModulesToAnchor(split.metafile, entryOutputPath)
return sharedModules.length === 0 && anchoredLazyModules.size === 0
? split
: esbuild.build(mobileWebAppBuildOptions(routes, sharedModules))
: esbuild.build(mobileWebAppBuildOptions(routes, sharedModules, anchoredLazyModules))
}
export async function bundleMobileWebApp({ appDir = defaultAppDir } = {}) {
@@ -0,0 +1,102 @@
import { realpathSync } from 'node:fs'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url))
export const ROUTE_ENTRY_NAMESPACE = 'orca-route-entry'
export const isScriptOutput = (path) => path.endsWith('.js')
// Budget entry plus transitive static imports, stopping at dynamic imports; entry-only limits let shared initial chunks grow unseen.
export function entryStaticClosure(metafile, entryOutputPath) {
const reached = new Set([entryOutputPath])
for (const current of reached) {
for (const imported of metafile.outputs[current]?.imports ?? []) {
if (imported.kind !== 'import-statement' || reached.has(imported.path)) {
continue
}
reached.add(imported.path)
}
}
return reached
}
// esbuild cuts a chunk per set of routes sharing a module; one this small costs more as a request than as code every route loads.
const MERGED_SHARED_CHUNK_MAX_BYTES = 16 * 1024
// Small route-shared chunks whose static imports already load at boot or merge too, so merging adds only their own bytes.
// ESM only: a bare import runs a CommonJS module's body at route load, not where its importer first needs it.
export function sharedModulesToMerge(metafile, entryOutputPath) {
const { inputs, outputs } = metafile
const boot = entryStaticClosure(metafile, entryOutputPath)
const routeReached = new Set(
Object.entries(outputs)
.filter(([, output]) => output.entryPoint?.startsWith(`${ROUTE_ENTRY_NAMESPACE}:`))
.flatMap(([path]) => [...entryStaticClosure(metafile, path)])
)
const merged = new Set(
Object.entries(outputs)
.filter(
([path, output]) =>
isScriptOutput(path) &&
!output.entryPoint &&
!boot.has(path) &&
routeReached.has(path) &&
output.bytes <= MERGED_SHARED_CHUNK_MAX_BYTES &&
Object.keys(output.inputs).every((input) => inputs[input]?.format === 'esm')
)
.map(([path]) => path)
)
const importsUnmerged = (path) =>
outputs[path].imports.some(
({ kind, path: imported }) =>
kind === 'import-statement' && !boot.has(imported) && !merged.has(imported)
)
for (let dropped = true; dropped;) {
dropped = false
for (const path of merged) {
if (importsUnmerged(path)) {
merged.delete(path)
dropped = true
}
}
}
return [...merged]
.flatMap((path) => Object.keys(outputs[path].inputs))
.sort()
.map((input) => resolve(mobileDir, input))
}
// A lazy module sharing boot code gives those modules a new importer set, so esbuild would split the boot chunks;
// anchor it like a route. Modules boot imports lazily (routes, catalogs) stay as they are: anchoring them is an output cycle.
// esbuild's runtime helper chunk has no inputs and every chunk imports it, so self-contained engines (mermaid) keep their bytes.
export function lazyModulesToAnchor(metafile, entryOutputPath) {
const { outputs } = metafile
const boot = entryStaticClosure(metafile, entryOutputPath)
const bootLoadsLazily = new Set(
[...boot].flatMap((path) =>
outputs[path].imports
.filter(({ kind }) => kind === 'dynamic-import')
.map(({ path: imported }) => imported)
)
)
const sharesBootModules = ({ imports }) =>
imports.some(
({ kind, path }) =>
kind === 'import-statement' &&
boot.has(path) &&
Object.keys(outputs[path].inputs).length > 0
)
return new Map(
Object.entries(outputs)
.filter(
([path, output]) =>
output.entryPoint &&
!boot.has(path) &&
!bootLoadsLazily.has(path) &&
sharesBootModules(output)
)
.map(([, output]) => [realpathSync(resolve(mobileDir, output.entryPoint)), output.exports])
)
}
+19 -52
View File
@@ -1,22 +1,18 @@
import { memo } from 'react'
import { lazy, Suspense } from 'react'
import { View, StyleSheet } from 'react-native'
import { MobileSourceControlRoutePanel } from '../source-control/MobileSourceControlRoutePanel'
import { MobileFileExplorerPanel } from '../files/MobileFileExplorerPanel'
import { mobilePrSidebarStyles } from '../components/pr-sidebar/mobile-pr-sidebar-styles'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { useMobileDockResize } from './use-mobile-dock-resize'
import type { ActivePanel } from './session-panel-host'
import type { SessionDockPanelContentProps } from './SessionDockPanelContent'
type Props = {
activePanel: Exclude<ActivePanel, null>
hostId: string
worktreeId: string
name: string
availableWidth: number
onRequestClose: () => void
}
type Props = SessionDockPanelContentProps & { availableWidth: number }
type DockPanelContentProps = Omit<Props, 'availableWidth'>
// Panels load with the first dock open so phone sessions, which never dock, skip Source Control and Files code.
const SessionDockPanelContent = lazy(() =>
import('./SessionDockPanelContent').then((module) => ({
default: module.SessionDockPanelContent
}))
)
// Keep drag width state in this subtree; terminal refits follow frame onLayout and need no width prop.
export function SessionDockColumn({
@@ -34,49 +30,20 @@ export function SessionDockColumn({
{/* Dedicated drag handle over the dock's left border — a leaf overlay so the
inner ScrollView can't intercept the gesture on Android. */}
<View style={styles.resizeHandle} {...panHandlers} />
<DockPanelContent
activePanel={activePanel}
hostId={hostId}
worktreeId={worktreeId}
name={name}
onRequestClose={onRequestClose}
/>
{/* The column frame paints at once; its panel fills in from local disk with no spinner. */}
<Suspense fallback={null}>
<SessionDockPanelContent
activePanel={activePanel}
hostId={hostId}
worktreeId={worktreeId}
name={name}
onRequestClose={onRequestClose}
/>
</Suspense>
</View>
)
}
// Width-independent panel props let memo skip content rerenders during resize.
const DockPanelContent = memo(function DockPanelContent({
activePanel,
hostId,
worktreeId,
name,
onRequestClose
}: DockPanelContentProps) {
// Reuse the source-control hub so dock icon switches retain commit draft, visited tabs and scroll.
if (activePanel === 'sourceControl' || activePanel === 'pr') {
return (
<MobileSourceControlRoutePanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
initialTab={activePanel === 'pr' ? 'pr' : 'changes'}
onRequestClose={onRequestClose}
/>
)
}
return (
<MobileFileExplorerPanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
onRequestClose={onRequestClose}
/>
)
})
const RESIZE_EDGE_WIDTH = 24
const styles = StyleSheet.create({
@@ -0,0 +1,44 @@
import { memo } from 'react'
import { MobileSourceControlRoutePanel } from '../source-control/MobileSourceControlRoutePanel'
import { MobileFileExplorerPanel } from '../files/MobileFileExplorerPanel'
import type { ActivePanel } from './session-panel-host'
export type SessionDockPanelContentProps = {
activePanel: Exclude<ActivePanel, null>
hostId: string
worktreeId: string
name: string
onRequestClose: () => void
}
// Width-independent panel props let memo skip content rerenders during resize.
export const SessionDockPanelContent = memo(function SessionDockPanelContent({
activePanel,
hostId,
worktreeId,
name,
onRequestClose
}: SessionDockPanelContentProps) {
// Reuse the source-control hub so dock icon switches retain commit draft, visited tabs and scroll.
if (activePanel === 'sourceControl' || activePanel === 'pr') {
return (
<MobileSourceControlRoutePanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
initialTab={activePanel === 'pr' ? 'pr' : 'changes'}
onRequestClose={onRequestClose}
/>
)
}
return (
<MobileFileExplorerPanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
onRequestClose={onRequestClose}
/>
)
})
+38 -13
View File
@@ -6,7 +6,7 @@ import type { TerminalWebViewHandle, TerminalWebViewProps } from './terminal-web
import { TerminalWebViewEngineErrorOverlay } from './terminal-webview-engine-error-state'
import { TERMINAL_WEBVIEW_FRAME_STYLES } from './terminal-webview-frame-styles'
import type { TerminalWebViewCommand } from './terminal-webview-messages'
import { mountTerminalWebDocument, type TerminalWebDocument } from './terminal-web-document-mount'
import type { TerminalWebDocument } from './terminal-web-document-mount'
import { useTerminalWebViewController } from './use-terminal-webview-controller'
type Props = TerminalWebViewProps
@@ -68,27 +68,52 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(
if (!(host instanceof HTMLElement)) {
return
}
let live
try {
live = mountTerminalWebDocument(host, (message) => receiveRef.current?.(message), atMount)
} catch (error) {
let live: TerminalWebDocument | null = null
let disposed = false
const reportStartupFailure = (error: unknown) => {
// Startup failure has no handle or later error notify; report its cause now instead of waiting for readiness timeout.
receiveRef.current?.({
type: 'error',
fatal: true,
message: describeTerminalDocumentStartupError(error)
})
return
}
documentRef.current = live
// Replay the pre-handle ready flush; theme/scale also ride init today, but future commands may not.
for (const command of beforeMountRef.current) {
live.send(command)
}
beforeMountRef.current = []
// Load xterm with the first terminal so chat-only sessions never parse it; posts queue in beforeMountRef meanwhile.
void import('./terminal-web-document-mount').then(
({ mountTerminalWebDocument }) => {
if (disposed) {
return
}
try {
live = mountTerminalWebDocument(
host,
(message) => receiveRef.current?.(message),
atMount
)
documentRef.current = live
// Replay the pre-handle ready flush; theme/scale also ride init today, but future commands may not.
for (const command of beforeMountRef.current) {
live.send(command)
}
beforeMountRef.current = []
} catch (error) {
// A throw here would escape the promise unseen; ready already stopped the watchdog, so show the overlay.
documentRef.current = null
live?.dispose()
live = null
reportStartupFailure(error)
}
},
(error: unknown) => {
if (!disposed) {
reportStartupFailure(error)
}
}
)
return () => {
disposed = true
documentRef.current = null
live.dispose()
live?.dispose()
}
// Mount once per generation; callback-driven controller changes must not discard terminal scrollback.
}, [atMount, generation])