fix: Android terminal text overflow and stale viewport after unfold

Fix Android terminal text overflow and stale foldable viewport handling.

- Pin terminal WebView textZoom so Android system font scale cannot inflate xterm glyphs past measured cells.
- Refit mobile terminal viewport on window dimension changes for fold/unfold, rotation, and split-screen.
- Harden viewport refit fallback handling for stale async runs and updateViewport responses.

Fixes #4579
This commit is contained in:
gsxdsm
2026-06-04 02:38:57 -04:00
committed by GitHub
parent a044a7cf40
commit a19e16f718
6 changed files with 336 additions and 81 deletions
+17 -79
View File
@@ -64,6 +64,7 @@ import {
type TerminalModes,
type TerminalWebViewHandle
} from '../../../../src/terminal/TerminalWebView'
import { useTerminalViewportRefit } from '../../../../src/terminal/terminal-viewport-refit'
import {
getDefaultTerminalAccessoryBuiltInIds,
getVisibleTerminalAccessoryKeys,
@@ -2295,63 +2296,22 @@ export default function SessionScreen() {
}
}, [])
// Why: re-measure when non-keyboard layout-affecting state changes
// (e.g. tab strip toggling visibility when the terminal count crosses
// 0↔1 — without this, a freshly-created 2nd tab subscribes with a
// stale viewport that doesn't account for the now-visible tab strip,
// and the server phone-fits to dims a few rows too tall).
const refitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const scheduleViewportRefit = useCallback(() => {
if (refitTimerRef.current) {
clearTimeout(refitTimerRef.current)
}
refitTimerRef.current = setTimeout(() => {
const handle = activeHandleRef.current
if (!handle) {
return
}
const ref = terminalRefs.current.get(handle)
if (!ref) {
return
}
void (async () => {
const dims = await ref.measureFitDimensions(terminalFrameHeightRef.current || undefined)
if (!dims) {
return
}
const prev = viewportRef.current
if (prev && prev.cols === dims.cols && prev.rows === dims.rows) {
return
}
viewportRef.current = dims
viewportMeasuredRef.current = true
// Why: prefer the in-place viewport update RPC over the legacy
// unsubscribe → subscribe cycle. This keeps the server-side
// mobile subscriber record alive (no driver=idle blip on the
// desktop banner; no false phone-fit baseline capture on the
// re-subscribe). See docs/mobile-presence-lock.md.
const rpc = clientRef.current
const deviceToken = deviceTokenRef.current
if (rpc && deviceToken) {
try {
const response = await rpc.sendRequest('terminal.updateViewport', {
terminal: handle,
client: { id: deviceToken, type: 'mobile' as const },
viewport: dims
})
if (response.ok) {
return
}
} catch {
// Fall through to legacy resubscribe.
}
}
unsubscribeTerminal(handle)
initializedHandlesRef.current.delete(handle)
subscribeToTerminal(handle)
})()
}, 150)
}, [subscribeToTerminal, unsubscribeTerminal])
// Why: viewport refits for layout changes outside the subscribe path
// (tab strip toggling, fold/unfold, rotation) live in a dedicated hook —
// see terminal-viewport-refit.ts for the full rationale.
useTerminalViewportRefit({
activeHandleRef,
terminalRefs,
terminalFrameHeightRef,
viewportRef,
viewportMeasuredRef,
clientRef,
deviceTokenRef,
initializedHandlesRef,
tabStripVisible: terminals.length > 1,
unsubscribeTerminal,
subscribeToTerminal
})
useEffect(() => {
const onShow = (e: KeyboardEvent) => {
@@ -2365,33 +2325,11 @@ export default function SessionScreen() {
const showSub = Keyboard.addListener(showEvent, onShow)
const hideSub = Keyboard.addListener(hideEvent, onHide)
return () => {
if (refitTimerRef.current) {
clearTimeout(refitTimerRef.current)
}
showSub.remove()
hideSub.remove()
}
}, [])
// Why: the tab strip is hidden when only one terminal exists and shown
// once a second is created. Crossing the 1↔2 boundary changes the
// visible terminal area by ~40px, so the cached viewport dims in
// viewportRef become stale. Mark the viewport as un-measured so the
// next subscribe path's self-correcting loop (init → measure →
// resubscribe-with-fresh-viewport, see the !viewportMeasuredRef branch
// above) re-runs against the new layout. Also schedule an explicit
// refit to cover the case where no new subscribe is happening.
const tabStripVisible = terminals.length > 1
const prevTabStripVisibleRef = useRef(tabStripVisible)
useEffect(() => {
if (prevTabStripVisibleRef.current === tabStripVisible) {
return
}
prevTabStripVisibleRef.current = tabStripVisible
viewportMeasuredRef.current = false
scheduleViewportRefit()
}, [tabStripVisible, scheduleViewportRefit])
useEffect(() => {
if (hostId && worktreeId) {
void AsyncStorage.setItem(
+4 -2
View File
@@ -280,8 +280,7 @@ const XTERM_HTML = `<!DOCTYPE html>
var ready = false;
var currentScale = 1;
var userScale = 1;
var panX = 0;
var panY = 0;
var panX = 0, panY = 0;
var smoothScrollOffsetY = 0;
var pendingNormalScrollDeltaY = 0;
var normalScrollFrameId = null;
@@ -2219,6 +2218,9 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(function
javaScriptEnabled
scrollEnabled={false}
scalesPageToFit={false}
// Why: Android WebView defaults textZoom to the system font scale, inflating
// xterm's DOM glyphs past its canvas-measured cell grid (#4579). iOS ignores it.
textZoom={100}
onLoadStart={handleLoadStart}
onMessage={handleMessage}
/>
@@ -0,0 +1,29 @@
import type { RpcResponse } from '../transport/types'
export type TerminalViewportRefitTargetState = {
activeHandle: string | null
expectedHandle: string
currentRef: unknown
expectedRef: unknown
disposed: boolean
runSeq: number
currentRunSeq: number
}
export function isTerminalUpdateViewportApplied(response: RpcResponse): boolean {
if (!response.ok || typeof response.result !== 'object' || response.result == null) {
return false
}
return (response.result as { updated?: unknown }).updated === true
}
export function isTerminalViewportRefitTargetCurrent(
state: TerminalViewportRefitTargetState
): boolean {
return (
!state.disposed &&
state.runSeq === state.currentRunSeq &&
state.activeHandle === state.expectedHandle &&
state.currentRef === state.expectedRef
)
}
@@ -0,0 +1,95 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import type { RpcResponse } from '../transport/types'
import {
isTerminalUpdateViewportApplied,
isTerminalViewportRefitTargetCurrent
} from './terminal-viewport-refit-state'
const hookSource = readFileSync(new URL('./terminal-viewport-refit.ts', import.meta.url), 'utf8')
const sessionSource = readFileSync(
new URL('../../app/h/[hostId]/session/[worktreeId].tsx', import.meta.url),
'utf8'
)
describe('terminal viewport refit', () => {
it('refits when the window dimensions change (fold/unfold, rotation)', () => {
// Why: a PTY fitted on the folded cover screen must be re-measured when
// the window grows, or the terminal renders in a fraction of the display.
expect(hookSource).toContain('useWindowDimensions()')
const start = hookSource.indexOf('const { width: windowWidth, height: windowHeight }')
expect(start).toBeGreaterThanOrEqual(0)
const resizeEffect = hookSource.slice(start)
expect(resizeEffect).toContain('viewportMeasuredRef.current = false')
expect(resizeEffect).toContain('scheduleViewportRefit()')
expect(resizeEffect).toContain(
'[windowWidth, windowHeight, viewportMeasuredRef, scheduleViewportRefit]'
)
})
it('still refits when the tab strip toggles visibility', () => {
const start = hookSource.indexOf('const prevTabStripVisibleRef')
expect(start).toBeGreaterThanOrEqual(0)
const tabEffect = hookSource.slice(start, hookSource.indexOf('useWindowDimensions()'))
expect(tabEffect).toContain('viewportMeasuredRef.current = false')
expect(tabEffect).toContain('scheduleViewportRefit()')
})
it('is wired into the session screen', () => {
expect(sessionSource).toContain('useTerminalViewportRefit({')
expect(sessionSource).toContain('tabStripVisible: terminals.length > 1')
})
it('prefers the in-place updateViewport RPC over resubscribe', () => {
const rpcIndex = hookSource.indexOf("sendRequest('terminal.updateViewport'")
const resubscribeIndex = hookSource.indexOf('subscribeToTerminal(handle)')
expect(rpcIndex).toBeGreaterThanOrEqual(0)
expect(resubscribeIndex).toBeGreaterThan(rpcIndex)
})
it('only treats updateViewport as applied when the runtime updated the subscriber', () => {
const okUpdated = {
id: '1',
ok: true,
result: { updated: true },
_meta: { runtimeId: 'runtime' }
} satisfies RpcResponse
const okNotUpdated = {
id: '2',
ok: true,
result: { updated: false },
_meta: { runtimeId: 'runtime' }
} satisfies RpcResponse
const failed = {
id: '3',
ok: false,
error: { code: 'missing', message: 'missing subscriber' },
_meta: { runtimeId: 'runtime' }
} satisfies RpcResponse
expect(isTerminalUpdateViewportApplied(okUpdated)).toBe(true)
expect(isTerminalUpdateViewportApplied(okNotUpdated)).toBe(false)
expect(isTerminalUpdateViewportApplied(failed)).toBe(false)
})
it('rejects stale async refits when the active terminal, ref, or run changes', () => {
const expectedRef = { resetZoom: () => {} }
const current = {
activeHandle: 'term-1',
expectedHandle: 'term-1',
currentRef: expectedRef,
expectedRef,
disposed: false,
runSeq: 2,
currentRunSeq: 2
}
expect(isTerminalViewportRefitTargetCurrent(current)).toBe(true)
expect(isTerminalViewportRefitTargetCurrent({ ...current, activeHandle: 'term-2' })).toBe(false)
expect(
isTerminalViewportRefitTargetCurrent({ ...current, currentRef: { resetZoom: () => {} } })
).toBe(false)
expect(isTerminalViewportRefitTargetCurrent({ ...current, currentRunSeq: 3 })).toBe(false)
expect(isTerminalViewportRefitTargetCurrent({ ...current, disposed: true })).toBe(false)
})
})
@@ -0,0 +1,176 @@
import { useCallback, useEffect, useRef, type RefObject } from 'react'
import { useWindowDimensions } from 'react-native'
import type { RpcClient } from '../transport/rpc-client'
import type { TerminalWebViewHandle } from './TerminalWebView'
import {
isTerminalUpdateViewportApplied,
isTerminalViewportRefitTargetCurrent
} from './terminal-viewport-refit-state'
export type TerminalViewportDims = { cols: number; rows: number }
type TerminalViewportRefitOptions = {
activeHandleRef: RefObject<string | null>
terminalRefs: RefObject<Map<string, TerminalWebViewHandle>>
terminalFrameHeightRef: RefObject<number>
viewportRef: RefObject<TerminalViewportDims | null>
viewportMeasuredRef: RefObject<boolean>
clientRef: RefObject<RpcClient | null>
deviceTokenRef: RefObject<string | null>
initializedHandlesRef: RefObject<Set<string>>
tabStripVisible: boolean
unsubscribeTerminal: (handle: string) => void
subscribeToTerminal: (handle: string) => void
}
// Why: re-measure the phone viewport when layout-affecting state changes
// outside the subscribe path — the tab strip toggling visibility, and the
// window itself resizing (fold/unfold on foldables, orientation rotation,
// split-screen). Without the resize trigger, a PTY fitted on the folded
// cover screen stays at cover-screen cols after unfolding and the terminal
// renders in only part of the display (#4579's "cut in half" symptom).
export function useTerminalViewportRefit(options: TerminalViewportRefitOptions): void {
const {
activeHandleRef,
terminalRefs,
terminalFrameHeightRef,
viewportRef,
viewportMeasuredRef,
clientRef,
deviceTokenRef,
initializedHandlesRef,
tabStripVisible,
unsubscribeTerminal,
subscribeToTerminal
} = options
const refitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const refitRunSeqRef = useRef(0)
const disposedRef = useRef(false)
const scheduleViewportRefit = useCallback(() => {
if (refitTimerRef.current) {
clearTimeout(refitTimerRef.current)
}
refitTimerRef.current = setTimeout(() => {
refitTimerRef.current = null
const runSeq = refitRunSeqRef.current + 1
refitRunSeqRef.current = runSeq
const handle = activeHandleRef.current
if (!handle) {
return
}
const ref = terminalRefs.current.get(handle)
if (!ref) {
return
}
const isCurrentTarget = () =>
isTerminalViewportRefitTargetCurrent({
activeHandle: activeHandleRef.current,
expectedHandle: handle,
currentRef: terminalRefs.current.get(handle),
expectedRef: ref,
disposed: disposedRef.current,
runSeq,
currentRunSeq: refitRunSeqRef.current
})
void (async () => {
const dims = await ref.measureFitDimensions(terminalFrameHeightRef.current || undefined)
if (!isCurrentTarget()) {
return
}
if (!dims) {
return
}
const prev = viewportRef.current
if (prev && prev.cols === dims.cols && prev.rows === dims.rows) {
return
}
viewportRef.current = dims
viewportMeasuredRef.current = true
// Why: prefer the in-place viewport update RPC over the legacy
// unsubscribe → subscribe cycle. This keeps the server-side
// mobile subscriber record alive (no driver=idle blip on the
// desktop banner; no false phone-fit baseline capture on the
// re-subscribe). See docs/mobile-presence-lock.md.
const rpc = clientRef.current
const deviceToken = deviceTokenRef.current
if (rpc && deviceToken) {
try {
const response = await rpc.sendRequest('terminal.updateViewport', {
terminal: handle,
client: { id: deviceToken, type: 'mobile' as const },
viewport: dims
})
if (isTerminalUpdateViewportApplied(response)) {
return
}
} catch {
// Fall through to legacy resubscribe.
}
}
if (!isCurrentTarget()) {
return
}
unsubscribeTerminal(handle)
initializedHandlesRef.current.delete(handle)
subscribeToTerminal(handle)
})()
}, 150)
}, [
activeHandleRef,
terminalRefs,
terminalFrameHeightRef,
viewportRef,
viewportMeasuredRef,
clientRef,
deviceTokenRef,
initializedHandlesRef,
unsubscribeTerminal,
subscribeToTerminal
])
// Why: the tab strip is hidden when only one terminal exists and shown
// once a second is created. Crossing the 1↔2 boundary changes the
// visible terminal area by ~40px, so the cached viewport dims in
// viewportRef become stale. Mark the viewport as un-measured so the
// next subscribe path's self-correcting loop (init → measure →
// resubscribe-with-fresh-viewport) re-runs against the new layout.
// Also schedule an explicit refit to cover the case where no new
// subscribe is happening.
const prevTabStripVisibleRef = useRef(tabStripVisible)
useEffect(() => {
if (prevTabStripVisibleRef.current === tabStripVisible) {
return
}
prevTabStripVisibleRef.current = tabStripVisible
viewportMeasuredRef.current = false
scheduleViewportRefit()
}, [tabStripVisible, viewportMeasuredRef, scheduleViewportRefit])
// Why: fold/unfold and rotation change the window dimensions without any
// subscribe or tab-strip transition. The PTY must be re-fitted to the new
// viewport or the terminal keeps the old grid (fit scale is capped at 1,
// so a grown window leaves the surface pinned to a fraction of the screen).
const { width: windowWidth, height: windowHeight } = useWindowDimensions()
const prevWindowDimsRef = useRef({ width: windowWidth, height: windowHeight })
useEffect(() => {
const prev = prevWindowDimsRef.current
if (prev.width === windowWidth && prev.height === windowHeight) {
return
}
prevWindowDimsRef.current = { width: windowWidth, height: windowHeight }
viewportMeasuredRef.current = false
scheduleViewportRefit()
}, [windowWidth, windowHeight, viewportMeasuredRef, scheduleViewportRefit])
useEffect(() => {
disposedRef.current = false
return () => {
disposedRef.current = true
refitRunSeqRef.current += 1
if (refitTimerRef.current) {
clearTimeout(refitTimerRef.current)
}
}
}, [])
}
@@ -0,0 +1,15 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
const source = readFileSync(new URL('./TerminalWebView.tsx', import.meta.url), 'utf8')
describe('TerminalWebView text zoom', () => {
it('pins textZoom to 100 so Android system font scale cannot inflate glyphs past xterm cell metrics', () => {
const start = source.indexOf('<WebView')
expect(start).toBeGreaterThanOrEqual(0)
const end = source.indexOf('/>', start)
expect(end).toBeGreaterThan(start)
const webViewProps = source.slice(start, end)
expect(webViewProps).toContain('textZoom={100}')
})
})