mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
perf(mobile): keep three visited terminals mounted and release hidden WebGL
This commit is contained in:
@@ -8,6 +8,7 @@ import { Animated, View, Text, Pressable, ActivityIndicator } from 'react-native
|
||||
import { saveTerminalTextScale } from '../storage/preferences'
|
||||
import { MobileBrowserPane } from '../browser/MobileBrowserPane'
|
||||
import { TerminalPaneView } from '../terminal/session/TerminalPaneView'
|
||||
import { useMountedTerminalHandles } from '../terminal/session/mounted-terminal-lru'
|
||||
import { MobileNativeChatOverlay } from './native-chat/MobileNativeChatOverlay'
|
||||
import { mobileSessionNativeChatHostOutage } from './native-chat/mobile-native-chat-host-outage'
|
||||
import { MobileAgentMessageProvider } from './native-chat/transcript/MobileAgentMessageProvider'
|
||||
@@ -87,6 +88,7 @@ export function MobileSessionActiveContent({
|
||||
discardMarkdownLocalContent,
|
||||
saveMarkdownTab,
|
||||
setTerminalWebViewRef,
|
||||
releaseTerminalDocument,
|
||||
handleTerminalWebReady,
|
||||
notifyTerminalFrame,
|
||||
notifyTerminalCellBoxChange,
|
||||
@@ -114,6 +116,13 @@ export function MobileSessionActiveContent({
|
||||
showEmptyState,
|
||||
createTabBusy
|
||||
} = controller
|
||||
const mountedTerminalHandles = useMountedTerminalHandles(
|
||||
visibleTerminalHandles,
|
||||
terminals.map((terminal) => terminal.handle)
|
||||
)
|
||||
const mountedTerminals = terminals.filter((terminal) =>
|
||||
mountedTerminalHandles.includes(terminal.handle)
|
||||
)
|
||||
const { keyboardLift, activeTerminalKeyboardLift, toastAnimatedStyle } =
|
||||
useMobileSessionContentKeyboardLift(controller)
|
||||
const openUrlInOrca = useOpenUrlInOrca(controller)
|
||||
@@ -258,14 +267,12 @@ export function MobileSessionActiveContent({
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.terminalFrame}>
|
||||
{terminals.map((terminal) => (
|
||||
{mountedTerminals.map((terminal) => (
|
||||
<TerminalPaneView
|
||||
key={terminal.handle}
|
||||
handle={terminal.handle}
|
||||
active={terminal.handle === activeHandle}
|
||||
visible={
|
||||
visibleTerminalHandles?.includes(terminal.handle) ?? terminal.handle === activeHandle
|
||||
}
|
||||
visible={visibleTerminalHandles.includes(terminal.handle)}
|
||||
splitIndex={
|
||||
terminalSplitActive && visibleTerminalHandles.includes(terminal.handle)
|
||||
? visibleTerminalHandles.indexOf(terminal.handle)
|
||||
@@ -304,6 +311,7 @@ export function MobileSessionActiveContent({
|
||||
void saveTerminalTextScale(scale)
|
||||
}}
|
||||
onRef={setTerminalWebViewRef}
|
||||
onDocumentReleased={releaseTerminalDocument}
|
||||
onWebReady={handleTerminalWebReady}
|
||||
onCellBoxChange={notifyTerminalCellBoxChange}
|
||||
onSelectionMode={handleSelectionMode}
|
||||
|
||||
@@ -38,7 +38,7 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(
|
||||
useImperativeHandle(ref, () => handle, [handle])
|
||||
// Seed scale in page source before document startup; Android injected scripts may run too late.
|
||||
const [source] = useState(() =>
|
||||
xtermWebViewSource({ textScale: props.textScale ?? 1, shown: props.shownAtMount ?? true })
|
||||
xtermWebViewSource({ textScale: props.textScale ?? 1, shown: props.shown ?? true })
|
||||
)
|
||||
|
||||
const handleMessage = useCallback(
|
||||
|
||||
@@ -54,7 +54,7 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(
|
||||
// Seed shown/scale before document startup, matching native pre-content state.
|
||||
const [atMount] = useState(() => ({
|
||||
textScale: props.textScale ?? 1,
|
||||
shown: props.shownAtMount ?? true
|
||||
shown: props.shown ?? true
|
||||
}))
|
||||
|
||||
useImperativeHandle(ref, () => handle, [handle])
|
||||
|
||||
@@ -41,6 +41,8 @@ export type TerminalDocumentState = {
|
||||
terminalGeneration: number
|
||||
termObserverDisposables: TerminalDocumentDisposable[]
|
||||
initRows: number
|
||||
// Hidden documents hold no WebGL context: WebKit caps live contexts per page and drops the oldest.
|
||||
shown: boolean
|
||||
webglAddon: TerminalDocumentWebglAddon | null
|
||||
webglRecoveryTimer: ReturnType<typeof setTimeout> | null
|
||||
terminalThemeInput: TerminalDocumentThemeMessage
|
||||
@@ -162,6 +164,7 @@ function createTerminalDocumentState(): TerminalDocumentState {
|
||||
terminalGeneration: 0,
|
||||
termObserverDisposables: [],
|
||||
initRows: 24,
|
||||
shown: true,
|
||||
webglAddon: null,
|
||||
webglRecoveryTimer: null,
|
||||
terminalThemeInput: null,
|
||||
|
||||
@@ -12,10 +12,12 @@ import { resetEvictionCounter } from './selection-state-and-eviction'
|
||||
import { applyTerminalTheme } from './terminal-theme'
|
||||
import { init, resize, write } from './terminal-init'
|
||||
import { applyTextScale } from './text-scaling'
|
||||
import { setWebglShown } from './webgl-recovery'
|
||||
import { afterQueuedWrites, resetWriteQueue } from './write-queue'
|
||||
|
||||
export type TerminalHostMessage = {
|
||||
active?: boolean
|
||||
shown?: boolean
|
||||
id?: number
|
||||
type?: string
|
||||
cols?: number
|
||||
@@ -134,6 +136,10 @@ export function handleMsg(scope: TerminalDocumentScope, msg: TerminalHostMessage
|
||||
suspendSurfaceTouchGestures(scope)
|
||||
}
|
||||
}
|
||||
} else if (msg.type === 'set-shown') {
|
||||
if (typeof msg.shown === 'boolean') {
|
||||
setWebglShown(scope, msg.shown)
|
||||
}
|
||||
} else if (msg.type === 'set-theme') {
|
||||
applyTerminalTheme(scope, msg.terminalTheme)
|
||||
} else if (msg.type === 'cancel-select') {
|
||||
|
||||
@@ -57,7 +57,9 @@ function openTerminal(scope: TerminalDocumentScope, cols: number, rows: number)
|
||||
attachOsc52ClipboardBridge(scope, term)
|
||||
attachProgramStatusQueryReplies(scope, term)
|
||||
term.open(scope.surface!)
|
||||
attachWebglAddon(scope, true)
|
||||
if (scope.shown) {
|
||||
attachWebglAddon(scope, true)
|
||||
}
|
||||
try {
|
||||
const unicodeAddon = scope.createUnicode11Addon()
|
||||
if (unicodeAddon) {
|
||||
|
||||
@@ -97,7 +97,29 @@ function onDocumentVisibilityChange(scope: TerminalDocumentScope) {
|
||||
refreshTerminalSurface(scope)
|
||||
}
|
||||
|
||||
// Release the context while the host hides this document and take a fresh one on show; xterm draws with its DOM renderer in between.
|
||||
export function setWebglShown(scope: TerminalDocumentScope, shown: boolean) {
|
||||
if (scope.shown === shown) {
|
||||
return
|
||||
}
|
||||
scope.shown = shown
|
||||
if (shown) {
|
||||
if (!scope.webglAddon) {
|
||||
attachWebglAddon(scope, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
cancelWebglContextRecovery(scope)
|
||||
const addon = scope.webglAddon
|
||||
// Clear first so the context loss this dispose raises is not taken for a GPU failure.
|
||||
scope.webglAddon = null
|
||||
try {
|
||||
addon?.dispose()
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function startWebglRecovery(scope: TerminalDocumentScope) {
|
||||
scope.shown = scope.start().shown
|
||||
const onVisibilityChange = () => onDocumentVisibilityChange(scope)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
scope.removeWebglRecovery = () => {
|
||||
|
||||
@@ -31,6 +31,8 @@ type TerminalPaneViewProps = {
|
||||
terminalTheme?: MobileTerminalTheme
|
||||
textScale: number
|
||||
onRef: (handle: string, ref: TerminalWebViewHandle | null) => void
|
||||
// Must keep one identity: the pane reports its document gone when it unmounts.
|
||||
onDocumentReleased: (handle: string) => void
|
||||
onWebReady: (handle: string) => void
|
||||
onSelectionMode: (handle: string, active: boolean) => void
|
||||
onSelectionCopy: (handle: string, text: string) => void
|
||||
@@ -63,6 +65,7 @@ export function TerminalPaneView({
|
||||
terminalTheme,
|
||||
textScale,
|
||||
onRef,
|
||||
onDocumentReleased,
|
||||
onWebReady,
|
||||
onSelectionMode,
|
||||
onSelectionCopy,
|
||||
@@ -82,10 +85,7 @@ export function TerminalPaneView({
|
||||
}: TerminalPaneViewProps) {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const [visited, setVisited] = useState(visible)
|
||||
if (visible && !visited) {
|
||||
setVisited(true)
|
||||
}
|
||||
useEffect(() => () => onDocumentReleased(handle), [handle, onDocumentReleased])
|
||||
const [routeFocused, setRouteFocused] = useState(false)
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
@@ -113,13 +113,9 @@ export function TerminalPaneView({
|
||||
? terminalPaneKeyboardLayout(splitFrame, splitDirection, splitIndex, keyboardInset)
|
||||
: null
|
||||
|
||||
if (!visible && !visited) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
// Hidden terminals stay mounted so changing the visible pair preserves scrollback.
|
||||
// Hidden terminals the session keeps mounted preserve scrollback when the visible pair changes.
|
||||
pointerEvents={visible ? 'auto' : 'none'}
|
||||
style={[
|
||||
styles.terminalPane,
|
||||
@@ -178,7 +174,7 @@ export function TerminalPaneView({
|
||||
]}
|
||||
terminalTheme={terminalTheme}
|
||||
textScale={textScale}
|
||||
shownAtMount={visible}
|
||||
shown={visible}
|
||||
interactionActive={visible && appActive && routeFocused}
|
||||
onWebReady={() => onWebReady(handle)}
|
||||
onSelectionMode={(a) => onSelectionMode(handle, a)}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { nextMountedTerminalHandles } from './mounted-terminal-lru'
|
||||
|
||||
describe('mounted terminal LRU', () => {
|
||||
it('unmounts the least recently visible terminal when a fourth one is shown', () => {
|
||||
const live = ['a', 'b', 'c', 'd']
|
||||
let mounted: readonly string[] = []
|
||||
for (const handle of ['a', 'b', 'c', 'b', 'd']) {
|
||||
mounted = nextMountedTerminalHandles(mounted, [handle], live)
|
||||
}
|
||||
expect(mounted).toEqual(['d', 'b', 'c'])
|
||||
})
|
||||
|
||||
it('keeps a split pair mounted with one more and drops closed terminals', () => {
|
||||
expect(nextMountedTerminalHandles(['c', 'b', 'a'], ['a', 'd'], ['a', 'b', 'c', 'd'])).toEqual([
|
||||
'a',
|
||||
'd',
|
||||
'c'
|
||||
])
|
||||
expect(nextMountedTerminalHandles(['a', 'b', 'c'], ['a'], ['a', 'c'])).toEqual(['a', 'c'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
// Each mounted terminal holds an xterm buffer; three covers a split pair plus the last one left.
|
||||
const MOUNTED_TERMINAL_LIMIT = 3
|
||||
|
||||
/** Visible terminals, then the most recently visible others, up to the limit; the rest unmount. */
|
||||
export function nextMountedTerminalHandles(
|
||||
previous: readonly string[],
|
||||
visible: readonly string[],
|
||||
live: readonly string[]
|
||||
): readonly string[] {
|
||||
const next = visible.filter((handle) => live.includes(handle))
|
||||
for (const handle of previous) {
|
||||
if (next.length >= MOUNTED_TERMINAL_LIMIT) {
|
||||
break
|
||||
}
|
||||
if (!next.includes(handle) && live.includes(handle)) {
|
||||
next.push(handle)
|
||||
}
|
||||
}
|
||||
const unchanged =
|
||||
next.length === previous.length && next.every((handle, index) => handle === previous[index])
|
||||
return unchanged ? previous : next
|
||||
}
|
||||
|
||||
export function useMountedTerminalHandles(
|
||||
visible: readonly string[],
|
||||
live: readonly string[]
|
||||
): readonly string[] {
|
||||
const [mounted, setMounted] = useState<readonly string[]>([])
|
||||
const next = nextMountedTerminalHandles(mounted, visible, live)
|
||||
if (next !== mounted) {
|
||||
setMounted(next)
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -42,6 +42,7 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching
|
||||
pendingSelectionRef,
|
||||
activeSessionTab,
|
||||
unsubscribeTerminal,
|
||||
unsubscribeTerminalRef,
|
||||
subscribeToTerminal,
|
||||
nativeChatStream,
|
||||
readMarkdownTab,
|
||||
@@ -107,6 +108,18 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching
|
||||
}
|
||||
}, [])
|
||||
|
||||
// An unmounted pane took its xterm with it; the next mount is a new document that needs a snapshot.
|
||||
const releaseTerminalDocument = useCallback(
|
||||
(handle: string) => {
|
||||
if (terminalUnsubsRef.current.has(handle)) {
|
||||
unsubscribeTerminalRef.current(handle)
|
||||
}
|
||||
webReadyHandlesRef.current.delete(handle)
|
||||
terminalResume.forget(handle)
|
||||
},
|
||||
[terminalResume, terminalUnsubsRef, unsubscribeTerminalRef, webReadyHandlesRef]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// Imperative handles change without layout events; inventory removal owns geometry cleanup.
|
||||
const liveHandles = new Set(terminals.map((terminal) => terminal.handle))
|
||||
@@ -293,6 +306,7 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching
|
||||
sendTerminalUserInput,
|
||||
sendTerminalOrderedInput,
|
||||
setTerminalWebViewRef,
|
||||
releaseTerminalDocument,
|
||||
handleTerminalWebReady,
|
||||
notifyTerminalFrame,
|
||||
notifyTerminalPaneFrame,
|
||||
|
||||
@@ -189,7 +189,7 @@ describe('the cell box xterm laid out', () => {
|
||||
it('tells a document whose view was hidden at mount not to build before ready', () => {
|
||||
let renderer: ReactTestRenderer | undefined
|
||||
act(() => {
|
||||
renderer = create(createElement(TerminalWebView, { shownAtMount: false }))
|
||||
renderer = create(createElement(TerminalWebView, { shown: false }))
|
||||
})
|
||||
renderers.push(renderer!)
|
||||
const webView = renderer!.root.find((node) => typeof node.props.onMessage === 'function')
|
||||
|
||||
@@ -92,8 +92,8 @@ export type TerminalWebViewProps = {
|
||||
terminalTheme?: MobileTerminalTheme
|
||||
// Persistent font-size preset; transient CSS pinch zoom is committed into it on release.
|
||||
textScale?: number
|
||||
// Only initially shown views build pre-ready engines, limiting WebGL context use.
|
||||
shownAtMount?: boolean
|
||||
// Hidden views hold no WebGL context, and only views shown at mount build pre-ready engines.
|
||||
shown?: boolean
|
||||
interactionActive?: boolean
|
||||
onWebReady?: () => void
|
||||
onEngineError?: (message: string) => void
|
||||
|
||||
@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import { TERMINAL_NERD_FONT_CSS, XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated'
|
||||
import { XTERM_ENGINE_JS } from './terminal-webview-engine.generated'
|
||||
import { createTerminalDocumentScope } from './document/document-scope'
|
||||
import { attachWebglAddon, startWebglRecovery } from './document/webgl-recovery'
|
||||
import { attachWebglAddon, setWebglShown, startWebglRecovery } from './document/webgl-recovery'
|
||||
import { XTERM_HTML } from './terminal-webview-html'
|
||||
import { applyTerminalTheme } from './document/terminal-theme'
|
||||
|
||||
@@ -227,6 +227,21 @@ describe('terminal WebView bundled engine', () => {
|
||||
expect(term.refresh).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('gives up its WebGL context while hidden and takes a new one when shown again', () => {
|
||||
const { addons, scope } = createWebglRecoveryHarness()
|
||||
|
||||
setWebglShown(scope, false)
|
||||
expect(addons[0]?.dispose).toHaveBeenCalledTimes(1)
|
||||
expect(scope.webglAddon).toBeNull()
|
||||
// The dispose's own context loss is not a GPU failure to recover from.
|
||||
addons[0]?.fireContextLoss()
|
||||
expect(addons).toHaveLength(1)
|
||||
|
||||
setWebglShown(scope, true)
|
||||
expect(addons).toHaveLength(2)
|
||||
expect(scope.webglAddon).toBe(addons[1])
|
||||
})
|
||||
|
||||
it('reapplies theme, clears the active atlas, and refreshes when visible', () => {
|
||||
const harness = createWebglRecoveryHarness()
|
||||
applyTerminalTheme(harness.scope, harness.scope.terminalThemeInput)
|
||||
|
||||
@@ -5,6 +5,7 @@ export type TerminalFrame = { width: number; height: number }
|
||||
|
||||
export type TerminalWebViewCommand =
|
||||
| { type: 'set-interaction-active'; active: boolean }
|
||||
| { type: 'set-shown'; shown: boolean }
|
||||
| { type: 'ping'; id?: number }
|
||||
// `onParsed` survives only an in-process post; a native bridge drops it.
|
||||
| { type: 'write'; id?: number; data: string; onParsed?: () => void }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { parseTerminalKittyKeyboardFlags } from '../../../src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-flags'
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react'
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react'
|
||||
import { readTerminalCellBox, type TerminalCellBox } from './terminal-cell-box'
|
||||
import { fitDimensionsFromCell } from './terminal-grid-fit'
|
||||
import type {
|
||||
@@ -33,6 +33,7 @@ export function useTerminalWebViewController(
|
||||
) {
|
||||
const {
|
||||
terminalTheme,
|
||||
shown = true,
|
||||
interactionActive = true,
|
||||
textScale = 1,
|
||||
onWebReady,
|
||||
@@ -116,11 +117,13 @@ export function useTerminalWebViewController(
|
||||
onWebReady?.()
|
||||
}
|
||||
// Reload drops commands; readiness must restore the selected theme even if its React value did not change.
|
||||
sendToDocument({ type: 'set-shown', shown })
|
||||
sendToDocument({ type: 'set-interaction-active', active: interactionActive })
|
||||
sendToDocument({ type: 'set-theme', terminalTheme })
|
||||
flushPendingMessages()
|
||||
},
|
||||
[
|
||||
shown,
|
||||
interactionActive,
|
||||
clearEngineError,
|
||||
clearWebReadyWatchdog,
|
||||
@@ -131,6 +134,9 @@ export function useTerminalWebViewController(
|
||||
]
|
||||
)
|
||||
|
||||
// Before paint, so a pane shown again draws its first frame with WebGL.
|
||||
useLayoutEffect(() => postMessage({ type: 'set-shown', shown }), [postMessage, shown])
|
||||
|
||||
useEffect(() => {
|
||||
if (isWebReadyRef.current) {
|
||||
sendToDocument({ type: 'set-interaction-active', active: interactionActive })
|
||||
|
||||
Reference in New Issue
Block a user