Fix mobile TUI scroll gestures (#1940)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-05-15 13:17:35 -07:00
committed by GitHub
co-authored by Orca
parent 79838275a4
commit 9217cf625d
10 changed files with 1028 additions and 132 deletions
+184 -2
View File
@@ -48,6 +48,7 @@ import {
type TerminalModes,
type TerminalWebViewHandle
} from '../../../../src/terminal/TerminalWebView'
import { countTerminalGestureInputSequences } from '../../../../src/terminal/terminal-gesture-input'
import { StatusDot } from '../../../../src/components/StatusDot'
import { ActionSheetModal } from '../../../../src/components/ActionSheetModal'
import { TextInputModal } from '../../../../src/components/TextInputModal'
@@ -205,6 +206,28 @@ const STATUS_LABELS: Record<ConnectionState, string> = {
'auth-failed': 'Auth failed'
}
const TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY = 64
const TERMINAL_GESTURE_INPUT_REFILL_PER_SECOND = 120
const TERMINAL_GESTURE_INPUT_FLUSH_DELAY_MS = 16
const TERMINAL_GESTURE_INPUT_MAX_PENDING_SEQUENCES = 32
const TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS = 250
type TerminalGestureInputBucket = {
tokens: number
lastRefillMs: number
}
type TerminalGestureInputQueue = {
bytes: string
sequenceCount: number
timer: ReturnType<typeof setTimeout> | null
lastUpdatedMs: number
}
function isWheelMouseTrackingMode(mode: TerminalModes['mouseTrackingMode'] | undefined): boolean {
return mode === 'vt200' || mode === 'drag' || mode === 'any'
}
function TerminalPaneView({
handle,
active,
@@ -216,7 +239,8 @@ function TerminalPaneView({
onSelectionEvicted,
onModesChanged,
onKeyboardAvoidanceMetrics,
onHaptic
onHaptic,
onTerminalInput
}: {
handle: string
active: boolean
@@ -229,6 +253,7 @@ function TerminalPaneView({
onModesChanged: (handle: string, modes: TerminalModes) => void
onKeyboardAvoidanceMetrics: (handle: string, metrics: TerminalKeyboardAvoidanceMetrics) => void
onHaptic: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void
onTerminalInput: (handle: string, bytes: string) => void
}) {
const setRef = useCallback(
(ref: TerminalWebViewHandle | null) => {
@@ -256,6 +281,7 @@ function TerminalPaneView({
onModesChanged={(m) => onModesChanged(handle, m)}
onKeyboardAvoidanceMetrics={(m) => onKeyboardAvoidanceMetrics(handle, m)}
onHaptic={onHaptic}
onTerminalInput={(bytes) => onTerminalInput(handle, bytes)}
/>
</View>
)
@@ -466,9 +492,13 @@ export default function SessionScreen() {
// Why: WebView pushes terminal modes (bracketed-paste, alt-screen) on every
// change so paste reads a synchronous snapshot — no round-trip required.
const ptyModesRef = useRef<Map<string, TerminalModes>>(new Map())
const terminalGestureInputBucketsRef = useRef<Map<string, TerminalGestureInputBucket>>(new Map())
const terminalGestureInputQueuesRef = useRef<Map<string, TerminalGestureInputQueue>>(new Map())
const terminalGestureInputInFlightRef = useRef<Set<string>>(new Set())
const initialModesSeenRef = useRef<Set<string>>(new Set())
const deviceTokenRef = useRef<string | null>(null)
const clientRef = useRef<RpcClient | null>(null)
const connStateRef = useRef<ConnectionState>(connState)
// Why: measured once from TerminalWebView on mount, then passed with every
// subscribe call so the server can auto-fit the PTY to phone dimensions.
const viewportRef = useRef<{ cols: number; rows: number } | null>(null)
@@ -1295,6 +1325,16 @@ export default function SessionScreen() {
clientRef.current = client
}, [client])
useEffect(() => {
connStateRef.current = connState
if (connState === 'connected') return
for (const queued of terminalGestureInputQueuesRef.current.values()) {
if (queued.timer) clearTimeout(queued.timer)
}
terminalGestureInputQueuesRef.current.clear()
terminalGestureInputInFlightRef.current.clear()
}, [connState])
// Why: only clear terminal cache on actual unmount. Running it whenever
// `client` changes — including the initial null → real-client transition
// from useHostClient's async open path — would unsubscribe terminals and
@@ -1432,6 +1472,11 @@ export default function SessionScreen() {
activeSessionTabTypeRef.current = null
pendingActiveSessionTabIdRef.current = null
pendingActiveTerminalHandleRef.current = null
for (const queued of terminalGestureInputQueuesRef.current.values()) {
if (queued.timer) clearTimeout(queued.timer)
}
terminalGestureInputQueuesRef.current.clear()
terminalGestureInputInFlightRef.current.clear()
setActiveHandle(null)
setTerminals([])
terminalsRef.current = []
@@ -1654,6 +1699,13 @@ export default function SessionScreen() {
terminalRefs.current.set(handle, ref)
} else {
terminalRefs.current.delete(handle)
terminalGestureInputBucketsRef.current.delete(handle)
const queued = terminalGestureInputQueuesRef.current.get(handle)
if (queued?.timer) {
clearTimeout(queued.timer)
}
terminalGestureInputQueuesRef.current.delete(handle)
terminalGestureInputInFlightRef.current.delete(handle)
}
}, [])
@@ -1754,6 +1806,132 @@ export default function SessionScreen() {
}
}
const allowTerminalGestureInput = useCallback(
(handle: string, sequenceCount: number): boolean => {
const now = Date.now()
const current = terminalGestureInputBucketsRef.current.get(handle) ?? {
tokens: TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY,
lastRefillMs: now
}
const elapsedSeconds = Math.max(0, now - current.lastRefillMs) / 1000
const tokens = Math.min(
TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY,
current.tokens + elapsedSeconds * TERMINAL_GESTURE_INPUT_REFILL_PER_SECOND
)
// Why: tokens represent terminal control sequences, not WebView messages;
// one legitimate gesture message may batch up to 32 wheel/key reports.
if (tokens < sequenceCount) {
terminalGestureInputBucketsRef.current.set(handle, { tokens, lastRefillMs: now })
return false
}
terminalGestureInputBucketsRef.current.set(handle, {
tokens: tokens - sequenceCount,
lastRefillMs: now
})
return true
},
[]
)
const flushTerminalGestureInput = useCallback(async (handle: string) => {
const queued = terminalGestureInputQueuesRef.current.get(handle)
if (!queued) return
if (queued.timer) {
clearTimeout(queued.timer)
queued.timer = null
}
if (terminalGestureInputInFlightRef.current.has(handle)) return
terminalGestureInputQueuesRef.current.delete(handle)
const isActive =
handle === activeHandleRef.current && activeSessionTabTypeRef.current === 'terminal'
const isFresh = Date.now() - queued.lastUpdatedMs <= TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS
const rpc = clientRef.current
if (!rpc || connStateRef.current !== 'connected' || !isActive || !isFresh) return
terminalGestureInputInFlightRef.current.add(handle)
try {
await rpc.sendRequest('terminal.send', {
terminal: handle,
text: queued.bytes,
enter: false,
...(deviceTokenRef.current
? { client: { id: deviceTokenRef.current, type: 'mobile' as const } }
: {})
})
} catch {
// Transient failure
} finally {
terminalGestureInputInFlightRef.current.delete(handle)
const next = terminalGestureInputQueuesRef.current.get(handle)
if (next) {
if (Date.now() - next.lastUpdatedMs > TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS) {
if (next.timer) clearTimeout(next.timer)
terminalGestureInputQueuesRef.current.delete(handle)
} else {
void flushTerminalGestureInput(handle)
}
}
}
}, [])
const enqueueTerminalGestureInput = useCallback(
(handle: string, bytes: string, sequenceCount: number) => {
const now = Date.now()
const current = terminalGestureInputQueuesRef.current.get(handle)
if (
current &&
current.sequenceCount + sequenceCount <= TERMINAL_GESTURE_INPUT_MAX_PENDING_SEQUENCES
) {
current.bytes += bytes
current.sequenceCount += sequenceCount
current.lastUpdatedMs = now
return
}
if (current) {
if (current.timer) clearTimeout(current.timer)
if (!terminalGestureInputInFlightRef.current.has(handle)) {
void flushTerminalGestureInput(handle)
} else {
terminalGestureInputQueuesRef.current.delete(handle)
}
}
const queued: TerminalGestureInputQueue = {
bytes,
sequenceCount,
timer: null,
lastUpdatedMs: now
}
queued.timer = setTimeout(() => {
queued.timer = null
void flushTerminalGestureInput(handle)
}, TERMINAL_GESTURE_INPUT_FLUSH_DELAY_MS)
terminalGestureInputQueuesRef.current.set(handle, queued)
},
[flushTerminalGestureInput]
)
const handleTerminalInput = useCallback(
async (handle: string, bytes: string) => {
if (!client || connState !== 'connected' || bytes.length === 0) return
if (handle !== activeHandleRef.current || activeSessionTabTypeRef.current !== 'terminal')
return
const modes = ptyModesRef.current.get(handle)
// Why: WebView messages can become PTY input here. Only TUI scroll paths
// generate gesture input, and the bridge is rate-limited for SSH safety.
if (!modes?.altScreen && !isWheelMouseTrackingMode(modes?.mouseTrackingMode)) return
const sequenceCount = countTerminalGestureInputSequences(bytes)
if (sequenceCount == null) return
if (!allowTerminalGestureInput(handle, sequenceCount)) return
enqueueTerminalGestureInput(handle, bytes, sequenceCount)
},
[allowTerminalGestureInput, client, connState, enqueueTerminalGestureInput]
)
async function handleClearTerminal(target: Terminal) {
if (!client) return
getTerminalRef(target.handle)?.clear()
@@ -1890,7 +2068,10 @@ export default function SessionScreen() {
if (text.length === 0) return
const modes = ptyModesRef.current.get(activeHandle) || {
bracketedPasteMode: false,
altScreen: false
altScreen: false,
mouseTrackingMode: 'none',
sgrMouseMode: false,
sgrMousePixelsMode: false
}
const wrap = modes.bracketedPasteMode && !modes.altScreen
// Why: strip embedded bracketed-paste markers from clipboard text so a
@@ -2335,6 +2516,7 @@ export default function SessionScreen() {
onModesChanged={handleModesChanged}
onKeyboardAvoidanceMetrics={handleKeyboardAvoidanceMetrics}
onHaptic={handleHaptic}
onTerminalInput={handleTerminalInput}
/>
))}
{toastMessage && (
+388 -116
View File
@@ -4,9 +4,14 @@ import { WebView } from 'react-native-webview'
import type { WebViewMessageEvent } from 'react-native-webview'
import { colors } from '../theme/mobile-theme'
type TerminalMouseTrackingMode = 'none' | 'x10' | 'vt200' | 'drag' | 'any'
export type TerminalModes = {
bracketedPasteMode: boolean
altScreen: boolean
mouseTrackingMode: TerminalMouseTrackingMode
sgrMouseMode: boolean
sgrMousePixelsMode: boolean
}
export type TerminalKeyboardAvoidanceMetrics = {
@@ -22,6 +27,7 @@ export type TerminalSelectionEvents = {
onModesChanged?: (modes: TerminalModes) => void
onKeyboardAvoidanceMetrics?: (metrics: TerminalKeyboardAvoidanceMetrics) => void
onHaptic?: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void
onTerminalInput?: (bytes: string) => void
}
export type TerminalWebViewHandle = {
@@ -178,6 +184,8 @@ const XTERM_HTML = `<!DOCTYPE html>
(function() {
var surface = document.getElementById('terminal-surface');
var ESC = String.fromCharCode(27);
var C1_CSI = String.fromCharCode(155);
var PRIVATE_MODE_SCAN_TAIL_LIMIT = 4096;
var term = null;
var writeQueue = [];
var writesDraining = false;
@@ -190,6 +198,10 @@ const XTERM_HTML = `<!DOCTYPE html>
var initRows = 24;
var terminalGeneration = 0;
var activeAltScreenSnapshot = false;
var trackedMouseTrackingMode = 'none';
var sgrMouseMode = false;
var sgrMousePixelsMode = false;
var mouseModeScanTail = '';
var handledMessageIds = [];
// Why: after init() the initial scrollback applyFitScale may have run
// against an empty buffer (or one without the widest line yet). Re-fit
@@ -406,6 +418,58 @@ const XTERM_HTML = `<!DOCTYPE html>
return on > 0 ? data.slice(on) : data;
}
function updateMouseModeFromData(data) {
if (typeof data !== 'string' || data.length === 0) return;
var input = mouseModeScanTail + data;
mouseModeScanTail = extractMouseModeScanTail(input);
var re = new RegExp(ESC + 'c|' + ESC + '\\\\[\\\\?([0-9;]+)([hl])|' + C1_CSI + '\\\\?([0-9;]+)([hl])', 'g');
var match;
while ((match = re.exec(input)) !== null) {
if (match[0] === ESC + 'c') {
trackedMouseTrackingMode = 'none';
sgrMouseMode = false;
sgrMousePixelsMode = false;
continue;
}
var enabled = (match[2] || match[4]) === 'h';
var params = (match[1] || match[3]).split(';');
for (var i = 0; i < params.length; i++) {
if (params[i] === '') continue;
var param = Number(params[i]);
if (!Number.isInteger(param)) continue;
if (param === 9) trackedMouseTrackingMode = enabled ? 'x10' : 'none';
if (param === 1000) trackedMouseTrackingMode = enabled ? 'vt200' : 'none';
if (param === 1002) trackedMouseTrackingMode = enabled ? 'drag' : 'none';
if (param === 1003) trackedMouseTrackingMode = enabled ? 'any' : 'none';
if (param === 1006) {
sgrMouseMode = enabled;
sgrMousePixelsMode = false;
}
if (param === 1016) {
sgrMouseMode = false;
sgrMousePixelsMode = enabled;
}
}
}
}
function extractMouseModeScanTail(input) {
var start = Math.max(input.lastIndexOf(ESC), input.lastIndexOf(C1_CSI));
if (start === -1) return '';
var tail = input.slice(start);
// Why: PTY/SSH chunks can split a long combined DECSET before the final h/l.
// Keep parser state far beyond normal mode lists while still bounding memory.
if (tail.length > PRIVATE_MODE_SCAN_TAIL_LIMIT) return '';
if (tail === ESC || tail === ESC + '[' || tail === C1_CSI) return tail;
if (tail.indexOf(ESC + '[?') === 0) {
return /^[0-9;]*$/.test(tail.slice(3)) ? tail : '';
}
if (tail.indexOf(C1_CSI + '?') === 0) {
return /^[0-9;]*$/.test(tail.slice(2)) ? tail : '';
}
return '';
}
function pumpWrites(gen) {
if (!ready || !term || writesDraining || gen !== terminalGeneration) return;
var next = writeQueue.shift();
@@ -439,7 +503,21 @@ const XTERM_HTML = `<!DOCTYPE html>
afterDrainCallbacks = [];
initRows = rows || 24;
firstDataPending = true;
mouseModeScanTail = '';
trackedMouseTrackingMode = 'none';
sgrMouseMode = false;
sgrMousePixelsMode = false;
lastEmittedModes = {
bracketedPasteMode: false,
altScreen: false,
mouseTrackingMode: 'none',
sgrMouseMode: false,
sgrMousePixelsMode: false
};
var replayData = normalizeInitialData(initialData);
// Why: normalizeInitialData can discard pre-alt-screen bytes. Keep the
// mirrored modes aligned with exactly what this mobile xterm replays.
updateMouseModeFromData(replayData);
activeAltScreenSnapshot = isAltScreenActive(replayData);
var oldTerm = term;
var oldSurface = surface;
@@ -453,6 +531,7 @@ const XTERM_HTML = `<!DOCTYPE html>
nextSurface.style.top = '0';
document.getElementById('terminal-container').appendChild(nextSurface);
surface = nextSurface;
attachSurfaceEventHandlers(surface);
oldSurface.removeAttribute('id');
}
@@ -522,6 +601,7 @@ const XTERM_HTML = `<!DOCTYPE html>
}
function write(data) {
updateMouseModeFromData(data);
writeQueue.push(data);
pumpWrites(terminalGeneration);
// Why: first live data chunk after init may widen the buffer past
@@ -623,7 +703,12 @@ const XTERM_HTML = `<!DOCTYPE html>
writeQueue = [];
afterDrainCallbacks = [];
writesDraining = false;
mouseModeScanTail = '';
trackedMouseTrackingMode = 'none';
sgrMouseMode = false;
sgrMousePixelsMode = false;
if (term) { term.clear(); term.reset(); }
emitModesIfChanged();
resetEvictionCounter();
if (selMode === 'select') {
notify({ type: 'selection-evicted' });
@@ -715,13 +800,39 @@ const XTERM_HTML = `<!DOCTYPE html>
if (!term) return;
var bp = !!(term.modes && term.modes.bracketedPasteMode);
var alt = false;
var mouseTrackingMode = getMouseTrackingMode();
try { alt = term.buffer && term.buffer.active && term.buffer.active.type === 'alternate'; } catch (e) {}
if (bp !== lastEmittedModes.bracketedPasteMode || alt !== lastEmittedModes.altScreen) {
lastEmittedModes = { bracketedPasteMode: bp, altScreen: alt };
notify({ type: 'modes', bracketedPasteMode: bp, altScreen: alt });
if (
bp !== lastEmittedModes.bracketedPasteMode ||
alt !== lastEmittedModes.altScreen ||
mouseTrackingMode !== lastEmittedModes.mouseTrackingMode ||
sgrMouseMode !== lastEmittedModes.sgrMouseMode ||
sgrMousePixelsMode !== lastEmittedModes.sgrMousePixelsMode
) {
lastEmittedModes = {
bracketedPasteMode: bp,
altScreen: alt,
mouseTrackingMode: mouseTrackingMode,
sgrMouseMode: sgrMouseMode,
sgrMousePixelsMode: sgrMousePixelsMode
};
notify({
type: 'modes',
bracketedPasteMode: bp,
altScreen: alt,
mouseTrackingMode: mouseTrackingMode,
sgrMouseMode: sgrMouseMode,
sgrMousePixelsMode: sgrMousePixelsMode
});
}
}
var lastEmittedModes = { bracketedPasteMode: false, altScreen: false };
var lastEmittedModes = {
bracketedPasteMode: false,
altScreen: false,
mouseTrackingMode: 'none',
sgrMouseMode: false,
sgrMousePixelsMode: false
};
function emitKeyboardAvoidanceMetrics() {
if (!term) return;
@@ -772,6 +883,147 @@ const XTERM_HTML = `<!DOCTYPE html>
return { col: col, row: viewportRow + viewportY };
}
function viewportToMouseReportCell(clientX, clientY) {
if (!term) return null;
var cellW = getCellWidth();
var cellH = getCellHeight();
if (cellW <= 0 || cellH <= 0) return null;
if (typeof clientX !== 'number') clientX = window.innerWidth / 2;
if (typeof clientY !== 'number') clientY = window.innerHeight / 2;
var total = getTotalScale();
if (total <= 0) total = 1;
var sx = (clientX - panX) / total;
var sy = (clientY - panY) / total;
var maxX = Math.max(0, term.cols * cellW - 1);
var maxY = Math.max(0, term.rows * cellH - 1);
if (sx < 0) sx = 0;
if (sx > maxX) sx = maxX;
if (sy < 0) sy = 0;
if (sy > maxY) sy = maxY;
var col = Math.floor(sx / cellW);
var row = Math.floor(sy / cellH);
if (col < 0) col = 0;
if (col > term.cols - 1) col = term.cols - 1;
if (row < 0) row = 0;
if (row > term.rows - 1) row = term.rows - 1;
return { col: col, row: row, x: Math.floor(sx), y: Math.floor(sy) };
}
function isAlternateBufferActive() {
try {
return !!(term && term.buffer && term.buffer.active && term.buffer.active.type === 'alternate');
} catch (e) {
return false;
}
}
function getMouseTrackingMode() {
try {
if (term && term.modes && typeof term.modes.mouseTrackingMode === 'string') {
var mode = term.modes.mouseTrackingMode;
if (mode === 'x10' || mode === 'vt200' || mode === 'drag' || mode === 'any') return mode;
return 'none';
}
} catch (e) {}
if (
trackedMouseTrackingMode === 'x10' ||
trackedMouseTrackingMode === 'vt200' ||
trackedMouseTrackingMode === 'drag' ||
trackedMouseTrackingMode === 'any'
) {
return trackedMouseTrackingMode;
}
return 'none';
}
function repeatSequence(sequence, count) {
var out = '';
for (var i = 0; i < count; i++) out += sequence;
return out;
}
function buildArrowScrollSequence(lines) {
var prefix = '[';
try {
if (term && term.modes && term.modes.applicationCursorKeysMode) prefix = 'O';
} catch (e) {}
return ESC + prefix + (lines < 0 ? 'A' : 'B');
}
function buildMouseWheelSequence(lines, clientX, clientY) {
var cell = viewportToMouseReportCell(clientX, clientY);
if (!cell) return '';
var eventCode = lines < 0 ? 64 : 65;
if (sgrMousePixelsMode) {
return ESC + '[<' + eventCode + ';' + cell.x + ';' + cell.y + 'M';
}
if (sgrMouseMode) {
// Why: xterm increments zero-based mouse cells before encoding reports.
return ESC + '[<' + eventCode + ';' + (cell.col + 1) + ';' + (cell.row + 1) + 'M';
}
// Why: xterm increments zero-based mouse cells before encoding reports.
var button = eventCode + 32;
var col = cell.col + 1 + 32;
var row = cell.row + 1 + 32;
// Why: non-SGR mouse bytes above ASCII are not preserved reliably through
// the mobile JSON/RPC string path. Fall back to keys for wide terminals.
if (button > 126 || col > 126 || row > 126) return '';
return ESC + '[M' + String.fromCharCode(button) + String.fromCharCode(col) + String.fromCharCode(row);
}
function isWheelMouseTrackingMode(mode) {
return mode !== 'none' && mode !== 'x10';
}
function buildMouseWheelScrollInput(lines, clientX, clientY) {
var count = Math.min(Math.abs(lines), 32);
if (count === 0) return '';
var sequence = buildMouseWheelSequence(lines, clientX, clientY);
if (!sequence) return '';
return repeatSequence(sequence, count);
}
function buildTuiScrollInput(lines, clientX, clientY) {
var count = Math.min(Math.abs(lines), 32);
if (count === 0) return '';
var mouseTrackingMode = getMouseTrackingMode();
var sequence = '';
if (isWheelMouseTrackingMode(mouseTrackingMode)) {
sequence = buildMouseWheelSequence(lines, clientX, clientY);
}
if (!sequence) sequence = buildArrowScrollSequence(lines);
return repeatSequence(sequence, count);
}
function routeScrollLines(lines, clientX, clientY) {
if (!term || lines === 0) return;
var mouseTrackingMode = getMouseTrackingMode();
var alternateBufferActive = isAlternateBufferActive();
if (isWheelMouseTrackingMode(mouseTrackingMode)) {
// Why: xterm sends wheel events to mouse-aware TUIs before considering
// scrollback, even if the app stays on the normal buffer.
var mouseInput = buildMouseWheelScrollInput(lines, clientX, clientY);
if (mouseInput) {
notify({ type: 'terminal-input', bytes: mouseInput });
return;
}
// Why: default mouse encoding can be unrepresentable in our ASCII-safe
// RPC path on wide terminals. Send bounded arrows instead of local
// scrollback/no-op while a mouse-aware app owns scroll gestures.
var fallbackInput = buildTuiScrollInput(lines, clientX, clientY);
if (fallbackInput) notify({ type: 'terminal-input', bytes: fallbackInput });
return;
}
if (alternateBufferActive) {
// Why: alternate-screen TUIs own their scroll state and xterm has no
// scrollback there, so mobile scroll gestures must become terminal input.
var input = buildTuiScrollInput(lines, clientX, clientY);
if (input) notify({ type: 'terminal-input', bytes: input });
return;
}
term.scrollLines(lines);
}
function cellToViewportPx(col, absRow) {
if (!term) return { x: 0, y: 0 };
var cellW = getCellWidth();
@@ -1134,12 +1386,6 @@ const XTERM_HTML = `<!DOCTYPE html>
} catch (err) {}
});
// Why: event listeners are registered once here (not inside init()) so
// they don't accumulate on re-init. They close over the mutable 'term'
// variable, so they always reference the current terminal instance.
surface.addEventListener('mousedown', function(e) { e.preventDefault(); e.stopPropagation(); }, true);
surface.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); }, true);
var ts = {
lastX: 0, lastY: 0, lastTime: 0, velY: 0,
accumDelta: 0, momentumId: null, isPinching: false,
@@ -1151,121 +1397,132 @@ const XTERM_HTML = `<!DOCTYPE html>
return Math.sqrt(dx * dx + dy * dy);
}
surface.addEventListener('touchstart', function(e) {
if (dispatcherShouldBlockSurface()) return;
if (ts.momentumId) {
cancelAnimationFrame(ts.momentumId);
ts.momentumId = null;
}
if (e.touches.length === 2) {
ts.isPinching = true;
ts.pinchDist = getDistance(e.touches[0], e.touches[1]);
ts.pinchScale = userScale;
var mx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
var my = (e.touches[0].clientY + e.touches[1].clientY) / 2;
var total = getTotalScale();
ts.pinchSurfX = (mx - panX) / total;
ts.pinchSurfY = (my - panY) / total;
} else if (e.touches.length === 1) {
ts.isPinching = false;
ts.lastX = e.touches[0].clientX;
ts.lastY = e.touches[0].clientY;
ts.lastTime = Date.now();
ts.velY = 0;
ts.accumDelta = 0;
}
}, { capture: true, passive: true });
function attachSurfaceEventHandlers(targetSurface) {
if (!targetSurface || targetSurface.__orcaSurfaceHandlersAttached) return;
targetSurface.__orcaSurfaceHandlersAttached = true;
// Why: init() swaps in a new hidden surface to avoid flicker; each
// replacement needs gesture handlers or tab-switch replays stop scrolling.
targetSurface.addEventListener('mousedown', function(e) { e.preventDefault(); e.stopPropagation(); }, true);
targetSurface.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); }, true);
surface.addEventListener('touchmove', function(e) {
if (dispatcherShouldBlockSurface()) return;
if (!term) return;
e.preventDefault();
e.stopPropagation();
if (e.touches.length === 2) {
ts.isPinching = true;
var dist = getDistance(e.touches[0], e.touches[1]);
var mx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
var my = (e.touches[0].clientY + e.touches[1].clientY) / 2;
var ratio = dist / ts.pinchDist;
userScale = Math.max(1, Math.min(5, ts.pinchScale * ratio));
var total = getTotalScale();
panX = mx - ts.pinchSurfX * total;
panY = my - ts.pinchSurfY * total;
clampPan();
updateTransform();
} else if (e.touches.length === 1 && !ts.isPinching) {
var x = e.touches[0].clientX;
var y = e.touches[0].clientY;
var now = Date.now();
var dt = now - ts.lastTime;
if (userScale > 1.05) {
panX += x - ts.lastX;
panY += y - ts.lastY;
clampPan();
updateTransform();
} else {
var deltaY = ts.lastY - y;
if (dt > 0) ts.velY = deltaY / dt;
ts.lastTime = now;
var effectiveCellH = getCellHeight() * currentScale;
ts.accumDelta += deltaY;
var lines = Math.trunc(ts.accumDelta / effectiveCellH);
if (lines !== 0) {
ts.accumDelta -= lines * effectiveCellH;
term.scrollLines(lines);
}
targetSurface.addEventListener('touchstart', function(e) {
if (dispatcherShouldBlockSurface()) return;
if (ts.momentumId) {
cancelAnimationFrame(ts.momentumId);
ts.momentumId = null;
}
ts.lastX = x;
ts.lastY = y;
}
}, { capture: true, passive: false });
surface.addEventListener('touchend', function(e) {
if (dispatcherShouldBlockSurface()) return;
if (!term) return;
if (ts.isPinching && e.touches.length < 2) {
ts.isPinching = false;
if (userScale < 1.15) {
userScale = 1; panX = 0; panY = 0;
updateTransform();
}
if (e.touches.length === 1) {
if (e.touches.length === 2) {
ts.isPinching = true;
ts.pinchDist = getDistance(e.touches[0], e.touches[1]);
ts.pinchScale = userScale;
var mx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
var my = (e.touches[0].clientY + e.touches[1].clientY) / 2;
var total = getTotalScale();
ts.pinchSurfX = (mx - panX) / total;
ts.pinchSurfY = (my - panY) / total;
} else if (e.touches.length === 1) {
ts.isPinching = false;
ts.lastX = e.touches[0].clientX;
ts.lastY = e.touches[0].clientY;
ts.lastTime = Date.now();
ts.velY = 0;
ts.accumDelta = 0;
}
return;
}
}, { capture: true, passive: true });
if (e.touches.length === 0 && userScale <= 1.05) {
var vel = ts.velY;
var FRICTION = 0.95;
var MIN_VEL = 0.02;
function momentumStep() {
vel *= FRICTION;
if (Math.abs(vel) < MIN_VEL) { ts.momentumId = null; return; }
var effectiveCellH = getCellHeight() * currentScale;
ts.accumDelta += vel * 16;
var lines = Math.trunc(ts.accumDelta / effectiveCellH);
if (lines !== 0) {
ts.accumDelta -= lines * effectiveCellH;
term.scrollLines(lines);
targetSurface.addEventListener('touchmove', function(e) {
if (dispatcherShouldBlockSurface()) return;
if (!term) return;
e.preventDefault();
e.stopPropagation();
if (e.touches.length === 2) {
ts.isPinching = true;
var dist = getDistance(e.touches[0], e.touches[1]);
var mx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
var my = (e.touches[0].clientY + e.touches[1].clientY) / 2;
var ratio = dist / ts.pinchDist;
userScale = Math.max(1, Math.min(5, ts.pinchScale * ratio));
var total = getTotalScale();
panX = mx - ts.pinchSurfX * total;
panY = my - ts.pinchSurfY * total;
clampPan();
updateTransform();
} else if (e.touches.length === 1 && !ts.isPinching) {
var x = e.touches[0].clientX;
var y = e.touches[0].clientY;
var now = Date.now();
var dt = now - ts.lastTime;
if (userScale > 1.05) {
panX += x - ts.lastX;
panY += y - ts.lastY;
clampPan();
updateTransform();
} else {
var deltaY = ts.lastY - y;
if (dt > 0) ts.velY = deltaY / dt;
ts.lastTime = now;
var effectiveCellH = getCellHeight() * currentScale;
ts.accumDelta += deltaY;
var lines = Math.trunc(ts.accumDelta / effectiveCellH);
if (lines !== 0) {
ts.accumDelta -= lines * effectiveCellH;
routeScrollLines(lines, x, y);
}
}
ts.momentumId = requestAnimationFrame(momentumStep);
ts.lastX = x;
ts.lastY = y;
}
if (Math.abs(vel) > MIN_VEL) {
ts.momentumId = requestAnimationFrame(momentumStep);
}, { capture: true, passive: false });
targetSurface.addEventListener('touchend', function(e) {
if (dispatcherShouldBlockSurface()) return;
if (!term) return;
if (ts.isPinching && e.touches.length < 2) {
ts.isPinching = false;
if (userScale < 1.15) {
userScale = 1; panX = 0; panY = 0;
updateTransform();
}
if (e.touches.length === 1) {
ts.lastX = e.touches[0].clientX;
ts.lastY = e.touches[0].clientY;
ts.lastTime = Date.now();
ts.velY = 0;
ts.accumDelta = 0;
}
return;
}
}
}, { capture: true, passive: true });
if (e.touches.length === 0 && userScale <= 1.05) {
var vel = ts.velY;
var FRICTION = 0.95;
var MIN_VEL = 0.02;
function momentumStep() {
vel *= FRICTION;
if (Math.abs(vel) < MIN_VEL) { ts.momentumId = null; return; }
var effectiveCellH = getCellHeight() * currentScale;
ts.accumDelta += vel * 16;
var lines = Math.trunc(ts.accumDelta / effectiveCellH);
if (lines !== 0) {
ts.accumDelta -= lines * effectiveCellH;
routeScrollLines(lines, ts.lastX, ts.lastY);
}
ts.momentumId = requestAnimationFrame(momentumStep);
}
if (Math.abs(vel) > MIN_VEL) {
ts.momentumId = requestAnimationFrame(momentumStep);
}
}
}, { capture: true, passive: true });
}
attachSurfaceEventHandlers(surface);
window.addEventListener('message', function(e) {
try {
@@ -1310,7 +1567,8 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(function
onSelectionEvicted,
onModesChanged,
onKeyboardAvoidanceMetrics,
onHaptic
onHaptic,
onTerminalInput
},
ref
) {
@@ -1395,10 +1653,23 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(function
} else if (msg.type === 'selection-evicted') {
onSelectionEvicted?.()
} else if (msg.type === 'modes') {
const mouseTrackingMode =
msg.mouseTrackingMode === 'x10' ||
msg.mouseTrackingMode === 'vt200' ||
msg.mouseTrackingMode === 'drag' ||
msg.mouseTrackingMode === 'any'
? msg.mouseTrackingMode
: 'none'
onModesChanged?.({
bracketedPasteMode: !!msg.bracketedPasteMode,
altScreen: !!msg.altScreen
altScreen: !!msg.altScreen,
mouseTrackingMode,
sgrMouseMode: !!msg.sgrMouseMode,
sgrMousePixelsMode: !!msg.sgrMousePixelsMode
})
} else if (msg.type === 'terminal-input') {
const bytes = typeof msg.bytes === 'string' ? msg.bytes : ''
if (bytes.length > 0) onTerminalInput?.(bytes)
} else if (msg.type === 'keyboard-avoidance-metrics') {
const cursorY = typeof msg.cursorY === 'number' ? msg.cursorY : 0
const rows = typeof msg.rows === 'number' ? msg.rows : 0
@@ -1430,7 +1701,8 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(function
onSelectionEvicted,
onModesChanged,
onKeyboardAvoidanceMetrics,
onHaptic
onHaptic,
onTerminalInput
]
)
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import {
countTerminalGestureInputSequences,
isTerminalGestureInput
} from './terminal-gesture-input'
const ESC = '\x1b'
describe('isTerminalGestureInput', () => {
it('accepts repeated arrow scroll sequences', () => {
expect(isTerminalGestureInput(`${ESC}[A${ESC}[B${ESC}OA${ESC}OB`)).toBe(true)
expect(isTerminalGestureInput(`${ESC}[A`.repeat(32))).toBe(true)
expect(countTerminalGestureInputSequences(`${ESC}[A${ESC}[B${ESC}OA${ESC}OB`)).toBe(4)
expect(countTerminalGestureInputSequences(`${ESC}[A`.repeat(32))).toBe(32)
})
it('accepts repeated SGR wheel sequences', () => {
expect(isTerminalGestureInput(`${ESC}[<64;1;1M${ESC}[<65;120;40M`)).toBe(true)
expect(isTerminalGestureInput(`${ESC}[<64;0;0M`)).toBe(true)
})
it('accepts repeated default mouse wheel sequences', () => {
expect(
isTerminalGestureInput(
`${ESC}[M${String.fromCharCode(96, 97, 33)}${ESC}[M${String.fromCharCode(97, 126, 126)}`
)
).toBe(true)
})
it('rejects shell text and other terminal input', () => {
expect(isTerminalGestureInput('rm -rf .\r')).toBe(false)
expect(isTerminalGestureInput(`${ESC}[200~paste${ESC}[201~`)).toBe(false)
})
it('rejects malformed or oversized sequences', () => {
expect(isTerminalGestureInput(`${ESC}[<63;0;1M`)).toBe(false)
expect(isTerminalGestureInput(`${ESC}[M` + String.fromCharCode(97, 32, 33))).toBe(false)
expect(isTerminalGestureInput(`${ESC}[A`.repeat(33))).toBe(false)
expect(countTerminalGestureInputSequences(`${ESC}[A`.repeat(33))).toBeNull()
expect(isTerminalGestureInput(`${ESC}[A`.repeat(700))).toBe(false)
})
})
@@ -0,0 +1,71 @@
const ESC = '\x1b'
const MAX_TERMINAL_GESTURE_INPUT_LENGTH = 2048
const MAX_TERMINAL_GESTURE_INPUT_SEQUENCES = 32
const SGR_MOUSE_WHEEL_SEQUENCE_RE = new RegExp(`^${ESC}\\[<(64|65);[0-9]{1,4};[0-9]{1,4}M$`)
function isDefaultMouseWheelSequence(bytes: string, offset: number): number | null {
if (!bytes.startsWith(`${ESC}[M`, offset) || offset + 6 > bytes.length) {
return null
}
const button = bytes.charCodeAt(offset + 3)
const col = bytes.charCodeAt(offset + 4)
const row = bytes.charCodeAt(offset + 5)
if ((button === 96 || button === 97) && col >= 33 && col <= 126 && row >= 33 && row <= 126) {
return offset + 6
}
return null
}
function isSgrMouseWheelSequence(bytes: string, offset: number): number | null {
if (!bytes.startsWith(`${ESC}[<`, offset)) {
return null
}
const end = bytes.indexOf('M', offset)
if (end === -1) {
return null
}
const sequence = bytes.slice(offset, end + 1)
return SGR_MOUSE_WHEEL_SEQUENCE_RE.test(sequence) ? end + 1 : null
}
function isArrowScrollSequence(bytes: string, offset: number): number | null {
const sequence = bytes.slice(offset, offset + 3)
if (
sequence === `${ESC}[A` ||
sequence === `${ESC}[B` ||
sequence === `${ESC}OA` ||
sequence === `${ESC}OB`
) {
return offset + 3
}
return null
}
export function countTerminalGestureInputSequences(bytes: string): number | null {
if (bytes.length === 0 || bytes.length > MAX_TERMINAL_GESTURE_INPUT_LENGTH) {
return null
}
let offset = 0
let sequenceCount = 0
while (offset < bytes.length) {
const next =
isArrowScrollSequence(bytes, offset) ??
isSgrMouseWheelSequence(bytes, offset) ??
isDefaultMouseWheelSequence(bytes, offset)
if (next == null) {
return null
}
sequenceCount += 1
if (sequenceCount > MAX_TERMINAL_GESTURE_INPUT_SEQUENCES) {
return null
}
offset = next
}
return sequenceCount
}
export function isTerminalGestureInput(bytes: string): boolean {
return countTerminalGestureInputSequences(bytes) != null
}
+191
View File
@@ -160,6 +160,162 @@ describe('HeadlessEmulator', () => {
await emulator.write('\x1b[?1049l')
expect(emulator.getSnapshot().modes.alternateScreen).toBe(false)
})
it('tracks mouse reporting mode', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
expect(emulator.getSnapshot().modes.mouseTracking).toBe(false)
await emulator.write('\x1b[?1002;1006h')
expect(emulator.getSnapshot().modes.mouseTracking).toBe(true)
expect(emulator.getSnapshot().modes.mouseTrackingMode).toBe('drag')
expect(emulator.getSnapshot().modes.sgrMouseMode).toBe(true)
expect(emulator.getSnapshot().modes.sgrMousePixelsMode).toBe(false)
await emulator.write('\x1b[?1002;1006l')
expect(emulator.getSnapshot().modes.mouseTracking).toBe(false)
expect(emulator.getSnapshot().modes.sgrMouseMode).toBe(false)
})
it('tracks split SGR mouse reporting sequences', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?1002;100')
await emulator.write('6h')
expect(emulator.getSnapshot().modes.mouseTrackingMode).toBe('drag')
expect(emulator.getSnapshot().modes.sgrMouseMode).toBe(true)
await emulator.write('\x1b[?100')
await emulator.write('6l')
expect(emulator.getSnapshot().modes.sgrMouseMode).toBe(false)
})
it('tracks long split private mouse mode sequences', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
const fillerModes = Array.from({ length: 40 }, (_, i) => String(3000 + i)).join(';')
await emulator.write(`\x1b[?1002;${fillerModes};100`)
await emulator.write('6h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTrackingMode).toBe('drag')
expect(snapshot.modes.sgrMouseMode).toBe(true)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
})
it('tracks private mouse modes with leading zero params', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?01002;01006h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTrackingMode).toBe('drag')
expect(snapshot.modes.sgrMouseMode).toBe(true)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
})
it('tracks C1 CSI private mouse mode sequences', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x9b?1002;1006h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTrackingMode).toBe('drag')
expect(snapshot.modes.sgrMouseMode).toBe(true)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
})
it('tracks split C1 CSI private mouse mode sequences', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x9b?1002;100')
await emulator.write('6h')
await emulator.write('\x9b?1002l')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTracking).toBe(false)
expect(snapshot.modes.sgrMouseMode).toBe(true)
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
})
it('tracks C1 CSI split before private marker', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x9b')
await emulator.write('?1002;1006h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTrackingMode).toBe('drag')
expect(snapshot.modes.sgrMouseMode).toBe(true)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
})
it('does not retain complete private CSI queries as scan tail', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?2004$p')
await emulator.write('1002;1006h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTracking).toBe(false)
expect(snapshot.modes.sgrMouseMode).toBe(false)
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1006h')
})
it('does not expose mouse modes before xterm applies the same write', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
const writePromise = emulator.write('\x1b[?1049h\x1b[?1002;1006h')
const snapshot = emulator.getSnapshot()
await writePromise
expect(snapshot.modes.alternateScreen).toBe(false)
expect(snapshot.modes.mouseTracking).toBe(false)
expect(snapshot.modes.sgrMouseMode).toBe(false)
expect(snapshot.rehydrateSequences).toBe('')
const after = emulator.getSnapshot()
expect(after.modes.alternateScreen).toBe(true)
expect(after.modes.mouseTrackingMode).toBe('drag')
expect(after.modes.sgrMouseMode).toBe(true)
expect(after.rehydrateSequences).toContain('\x1b[?1049h')
expect(after.rehydrateSequences).toContain('\x1b[?1002h')
expect(after.rehydrateSequences).toContain('\x1b[?1006h')
})
it('clears SGR mouse reporting on full terminal reset', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?1002;1006h')
await emulator.write('\x1bc')
await emulator.write('\x1b[?1002h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTrackingMode).toBe('drag')
expect(snapshot.modes.sgrMouseMode).toBe(false)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1006h')
})
it('tracks SGR-pixels mouse reporting as a separate active encoding', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?1002;1006h')
await emulator.write('\x1b[?1016h')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTrackingMode).toBe('drag')
expect(snapshot.modes.sgrMouseMode).toBe(false)
expect(snapshot.modes.sgrMousePixelsMode).toBe(true)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1016h')
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1006h')
})
})
describe('rehydration sequences', () => {
@@ -178,6 +334,41 @@ describe('HeadlessEmulator', () => {
const snapshot = emulator.getSnapshot()
expect(snapshot.rehydrateSequences).toBe('')
})
it('rehydrates mouse reporting after alternate screen activation', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?1049h\x1b[?1002;1006h')
const snapshot = emulator.getSnapshot()
expect(snapshot.rehydrateSequences).toContain('\x1b[?1049h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1002h')
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
expect(snapshot.rehydrateSequences.indexOf('\x1b[?1049h')).toBeLessThan(
snapshot.rehydrateSequences.indexOf('\x1b[?1002h')
)
})
it('preserves mouse modes after mobile normalizes an alternate-screen replay', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('normal buffer\r\n\x1b[?1049h\x1b[?2004h\x1b[?1002;1006halternate')
const snapshot = emulator.getSnapshot()
const payload = snapshot.rehydrateSequences + snapshot.snapshotAnsi
expect(payload.split('\x1b[?1049h')).toHaveLength(2)
expect(payload.slice(payload.lastIndexOf('\x1b[?1049h'))).toContain('\x1b[?1002h')
expect(payload.slice(payload.lastIndexOf('\x1b[?1049h'))).toContain('\x1b[?1006h')
})
it('rehydrates mouse encoding independently from reporting mode', async () => {
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
await emulator.write('\x1b[?1002;1006h')
await emulator.write('\x1b[?1002l')
const snapshot = emulator.getSnapshot()
expect(snapshot.modes.mouseTracking).toBe(false)
expect(snapshot.modes.sgrMouseMode).toBe(true)
expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h')
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1002h')
})
})
describe('dispose', () => {
+136 -5
View File
@@ -14,6 +14,10 @@ export type HeadlessSnapshotOptions = {
}
const DEFAULT_SCROLLBACK = 5000
// Why: PTY/SSH chunks can split a long combined DECSET before the final h/l.
// Keep parser state far beyond normal mode lists while still bounding memory.
const PRIVATE_MODE_SCAN_TAIL_LIMIT = 4096
type MouseTrackingMode = NonNullable<TerminalModes['mouseTrackingMode']>
function parseFileUriPath(uri: string): string | null {
try {
@@ -47,6 +51,10 @@ export class HeadlessEmulator {
private terminal: Terminal
private serializer: SerializeAddon
private cwd: string | null = null
private privateModeScanTail = ''
private mouseTrackingMode: MouseTrackingMode = 'none'
private sgrMouseMode = false
private sgrMousePixelsMode = false
private disposed = false
constructor(opts: HeadlessEmulatorOptions) {
@@ -80,7 +88,12 @@ export class HeadlessEmulator {
this.scanOsc7(data)
return new Promise<void>((resolve) => {
this.terminal.write(data, resolve)
this.terminal.write(data, () => {
// Why: snapshots combine serialized xterm state with mirrored mouse
// modes. Commit the mirror only after xterm has parsed the same bytes.
this.scanPrivateModes(data)
resolve()
})
})
}
@@ -93,8 +106,12 @@ export class HeadlessEmulator {
getSnapshot(opts: HeadlessSnapshotOptions = {}): TerminalSnapshot {
const modes = this.getModes()
const snapshotAnsi = this.normalizeSnapshotAnsiForModes(
this.serializer.serialize({ scrollback: opts.scrollbackRows }),
modes
)
return {
snapshotAnsi: this.serializer.serialize({ scrollback: opts.scrollbackRows }),
snapshotAnsi,
scrollbackAnsi: '',
rehydrateSequences: this.buildRehydrateSequences(modes),
cwd: this.cwd,
@@ -133,6 +150,93 @@ export class HeadlessEmulator {
}
}
private scanPrivateModes(data: string): void {
const input = this.privateModeScanTail + data
this.privateModeScanTail = this.extractPrivateModeScanTail(input)
// oxlint-disable-next-line no-control-regex -- terminal escape sequences require control chars
const privateModeRe = /\x1bc|\x1b\[\?([0-9;]+)([hl])|\x9b\?([0-9;]+)([hl])/g
let match: RegExpExecArray | null
while ((match = privateModeRe.exec(input)) !== null) {
if (match[0] === '\x1bc') {
this.mouseTrackingMode = 'none'
this.sgrMouseMode = false
this.sgrMousePixelsMode = false
continue
}
const params = match[1] ?? match[3]
const enabled = (match[2] ?? match[4]) === 'h'
for (const rawParam of params.split(';')) {
if (rawParam === '') {
continue
}
const param = Number(rawParam)
if (!Number.isInteger(param)) {
continue
}
if (param === 9) {
this.mouseTrackingMode = enabled ? 'x10' : 'none'
}
if (param === 1000) {
this.mouseTrackingMode = enabled ? 'vt200' : 'none'
}
if (param === 1002) {
this.mouseTrackingMode = enabled ? 'drag' : 'none'
}
if (param === 1003) {
this.mouseTrackingMode = enabled ? 'any' : 'none'
}
if (param === 1006) {
this.sgrMouseMode = enabled
this.sgrMousePixelsMode = false
}
if (param === 1016) {
this.sgrMouseMode = false
this.sgrMousePixelsMode = enabled
}
}
}
}
private extractPrivateModeScanTail(input: string): string {
const start = Math.max(input.lastIndexOf('\x1b'), input.lastIndexOf('\x9b'))
if (start === -1) {
return ''
}
const tail = input.slice(start)
if (tail.length > PRIVATE_MODE_SCAN_TAIL_LIMIT) {
return ''
}
if (tail === '\x1b' || tail === '\x1b[' || tail === '\x9b') {
return tail
}
if (tail.startsWith('\x1b[?')) {
return this.isIncompletePrivateModeParams(tail.slice(3)) ? tail : ''
}
if (tail.startsWith('\x9b?')) {
return this.isIncompletePrivateModeParams(tail.slice(2)) ? tail : ''
}
return ''
}
private isIncompletePrivateModeParams(params: string): boolean {
return /^[0-9;]*$/.test(params)
}
private normalizeSnapshotAnsiForModes(snapshotAnsi: string, modes: TerminalModes): string {
if (!modes.alternateScreen) {
return snapshotAnsi
}
const alternateScreenMarker = '\x1b[?1049h'
const start = snapshotAnsi.lastIndexOf(alternateScreenMarker)
if (start === -1) {
return snapshotAnsi
}
// Why: rehydrateSequences already enters the alternate screen and restores
// mouse modes. Dropping SerializeAddon's duplicate ?1049h keeps mobile's
// "slice from last alt-screen marker" replay from discarding those modes.
return snapshotAnsi.slice(start + alternateScreenMarker.length)
}
private parseOsc7Uri(uri: string): void {
const parsed = parseFileUriPath(uri)
if (parsed) {
@@ -142,9 +246,13 @@ export class HeadlessEmulator {
private getModes(): TerminalModes {
const buffer = this.terminal.buffer.active
const mouseTrackingMode = this.mouseTrackingMode
return {
bracketedPaste: this.terminal.modes.bracketedPasteMode,
mouseTracking: this.terminal.modes.mouseTrackingMode !== 'none',
mouseTracking: mouseTrackingMode !== 'none',
mouseTrackingMode,
sgrMouseMode: this.sgrMouseMode,
sgrMousePixelsMode: this.sgrMousePixelsMode,
applicationCursor:
buffer.type === 'normal' ? this.terminal.modes.applicationCursorKeysMode : false,
alternateScreen: buffer.type === 'alternate'
@@ -153,14 +261,37 @@ export class HeadlessEmulator {
private buildRehydrateSequences(modes: TerminalModes): string {
const seqs: string[] = []
if (modes.alternateScreen) {
seqs.push('\x1b[?1049h')
}
if (modes.bracketedPaste) {
seqs.push('\x1b[?2004h')
}
if (modes.applicationCursor) {
seqs.push('\x1b[?1h')
}
if (modes.alternateScreen) {
seqs.push('\x1b[?1049h')
// Why: mobile alt-screen scroll gestures need xterm's mouse mode restored
// from cold snapshots; OpenCode/OpenTUI enables scrollable panes this way.
switch (modes.mouseTracking ? (modes.mouseTrackingMode ?? 'vt200') : 'none') {
case 'x10':
seqs.push('\x1b[?9h')
break
case 'vt200':
seqs.push('\x1b[?1000h')
break
case 'drag':
seqs.push('\x1b[?1002h')
break
case 'any':
seqs.push('\x1b[?1003h')
break
}
// Why: xterm tracks the mouse protocol and SGR encoding as independent
// modes, so snapshots must preserve the encoding even when reporting is off.
if (modes.sgrMousePixelsMode) {
seqs.push('\x1b[?1016h')
} else if (modes.sgrMouseMode) {
seqs.push('\x1b[?1006h')
}
return seqs.join('')
}
+7 -4
View File
@@ -1,10 +1,10 @@
// ─── Protocol Version ────────────────────────────────────────────────
// Why: daemons can survive app updates. Bump for IPC wire-shape changes, or
// when daemon-baked behavior cannot be delivered by on-disk wrapper refresh.
// Why: bumped from 5 -> 6 for OSC 133 shell wrapper changes layered on top of
// OpenCode/Pi overlay restoration, both of which are baked into daemon spawns.
export const PROTOCOL_VERSION = 6
export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2, 3, 4, 5] as const
// Why: bumped from 6 -> 7 so existing daemons restart with the headless
// emulator's mouse-mode snapshot tracking for mobile alternate-screen TUIs.
export const PROTOCOL_VERSION = 7
export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2, 3, 4, 5, 6] as const
// ─── Session State Machine ──────────────────────────────────────────
export type SessionState = 'created' | 'spawning' | 'running' | 'exiting' | 'exited'
@@ -28,6 +28,9 @@ export type TerminalSnapshot = {
export type TerminalModes = {
bracketedPaste: boolean
mouseTracking: boolean
mouseTrackingMode?: 'none' | 'x10' | 'vt200' | 'drag' | 'any'
sgrMouseMode?: boolean
sgrMousePixelsMode?: boolean
applicationCursor: boolean
alternateScreen: boolean
}
@@ -1,9 +1,12 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import { makePaneKey } from '../../../../shared/stable-pane-id'
import type { TerminalTab } from '../../../../shared/types'
import { useWorktreeActivityStatus } from './use-worktree-activity-status'
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
type MockState = {
tabsByWorktree: Record<string, TerminalTab[]>
browserTabsByWorktree: Record<string, { id: string }[]>
@@ -71,6 +74,7 @@ describe('useWorktreeActivityStatus', () => {
it('keeps a restored offscreen working agent yellow from the hook snapshot', () => {
const worktreeId = 'repo1::/path/wt1'
const paneKey = makePaneKey('tab-1', LEAF_ID)
mockState = {
...mockState,
tabsByWorktree: {
@@ -80,7 +84,7 @@ describe('useWorktreeActivityStatus', () => {
'tab-1': ['pty-1']
},
agentStatusByPaneKey: {
'tab-1:1': makeAgentStatusEntry({ paneKey: 'tab-1:1', state: 'working' })
[paneKey]: makeAgentStatusEntry({ paneKey, state: 'working' })
}
}
@@ -49,7 +49,7 @@ export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus {
done = true
}
}
for (const unsupported of Object.values(s.migrationUnsupportedByPtyId)) {
for (const unsupported of Object.values(s.migrationUnsupportedByPtyId ?? {})) {
const entry = migrationUnsupportedToAgentStatusEntry(unsupported)
if (!entry) {
continue
@@ -78,9 +78,9 @@ export function installMode2031Handlers(deps: Mode2031HandlerDeps): IDisposable[
// scrollback (`SerializeAddon.serialize()`) never contain `?2031`:
// SerializeAddon's _serializeModes whitelists only ?1h/?66h/?2004h/
// [4h/?6h/?45h/?1004h/?7l/mouse modes/?25l, and buildRehydrateSequences
// emits only ?2004h/?1h/?1049h. If xterm ever adds ?2031 to that
// whitelist, this guard would start suppressing legitimate
// subscribes during snapshot reattach — revisit then.
// emits only ?1049h/?2004h/?1h/mouse reporting modes. If xterm ever
// adds ?2031 to that whitelist, this guard would start suppressing
// legitimate subscribes during snapshot reattach — revisit then.
if (deps.isReplaying()) {
return false
}