fix(app): restore physical arrow keys in Android terminals (#9407)

* fix(app): send hardware arrow keys to the terminal on Android

TextInput.onKeyPress is built from the IME input connection, so physical arrows never reach it and fell through to the hidden input as caret movement. The hardware module now claims arrows while the terminal input (nativeID) has focus, and the input forwards them to the PTY with their modifiers.

* test(app): guard Android terminal hardware arrow delivery

Exercise physical arrow ownership through a real Android window and editable, including repeats, modifiers and ordinary text-field editing. The terminal case fails on main because Left moves the hidden caret; the following typed character is then discarded as a replacement.

Co-authored-by: moevis <moevery@gmail.com>

---------

Co-authored-by: moevis <moevery@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
This commit is contained in:
paseo-bot[bot]andmoevis authored and GitHub committed 2026-11-12 14:09:19 +00:00
1 parent 68818067f2
commit 9e607a3aa3
11 files changed
+199 -46

No files matched your search

+9
View File
@@ -112,6 +112,15 @@ need an artifact. `android:clear` removes the generated Android project.
Run `npm run test:android --workspace=@getpaseo/app` explicitly with a local Android toolchain to prebuild Android and run native module unit tests. Ordinary CI does not prebuild Android or run these tests.
With an emulator or device connected, run the hardware keyboard's window-dispatch regression tests
from `packages/app/android`:
```bash
./gradlew :paseo-hardware-keyboard:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
```
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
### Diagnostic logs without ADB
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
+5
View File
@@ -85,6 +85,11 @@ Escape interrupts an agent only in the message input or an unclaimed surface.
A focused terminal excludes that binding. The source leaves terminal Escape alone;
terminal Escape/Ctrl forwarding is a separate feature.
Terminal arrows never pass through the shortcut pipeline. The Android hardware
module claims them while the terminal's hidden input (`nativeID`) owns the focus.
`TextInput.onKeyPress` only sees IME keys, and an arrow that falls through moves
the hidden caret and desyncs the next text change, so the pipeline cannot own them.
## Keys shared with text editing
A binding on a key the platform already uses for editing, such as Cmd/Ctrl+Z for
@@ -8,9 +8,12 @@ android {
defaultConfig {
versionCode 1
versionName '0.1.0'
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
}
dependencies {
implementation 'com.facebook.react:react-android'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity android:name="android.app.Activity" android:exported="false" />
</application>
</manifest>
@@ -0,0 +1,81 @@
package sh.paseo.keyboard
import android.app.Activity
import android.content.Intent
import android.view.KeyEvent
import android.widget.EditText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/** Exercises the real Android window and editable that receive physical keys. */
@RunWith(AndroidJUnit4::class)
class TerminalArrowTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private var activity: Activity? = null
@After fun finish() {
instrumentation.runOnMainSync {
activity?.let {
HardwareKeyboard.release(it.window)
it.finish()
}
}
}
@Test fun physicalArrowsDoNotMoveTheTerminalInputCaret() {
withInput(terminal = true) { input, host ->
for (code in listOf(KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN)) {
for (modifiers in listOf(0, KeyEvent.META_SHIFT_ON, KeyEvent.META_ALT_ON, KeyEvent.META_CTRL_ON)) {
input.setSelection(3)
for (repeat in 0..2) {
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_DOWN, code, repeat, modifiers)))
assertEquals("Physical arrows must leave the hidden input caret at the end", 3, input.selectionStart)
}
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_UP, code, 0, modifiers)))
}
}
host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_X))
host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_X))
assertEquals("abcx", input.text.toString())
}
}
@Test fun physicalArrowsStillEditOtherTextFields() {
withInput(terminal = false) { input, host ->
host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT))
assertEquals(2, input.selectionStart)
host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_X))
host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_X))
assertEquals("abxc", input.text.toString())
}
}
private fun withInput(terminal: Boolean, check: (EditText, Activity) -> Unit) {
val host = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = host
lateinit var input: EditText
instrumentation.runOnMainSync {
input = EditText(host)
if (terminal) input.setTag(com.facebook.react.R.id.view_tag_native_id, "paseo-terminal-input")
host.setContentView(input)
input.setText("abc")
input.requestFocus()
input.setSelection(3)
HardwareKeyboard.observe(host.window)
}
instrumentation.waitForIdleSync()
instrumentation.runOnMainSync {
assertSame("The editable must own window focus before keys are dispatched", input, host.window.currentFocus)
check(input, host)
}
}
}
@@ -10,18 +10,24 @@ import android.view.KeyEvent
import android.view.Window
import android.widget.EditText
import android.view.inputmethod.BaseInputConnection
import com.facebook.react.R
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.bridge.ReactContext
import com.facebook.react.interfaces.ExtraWindowEventListener
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
// Matched against the hidden terminal input's `nativeID`
// (TERMINAL_INPUT_NATIVE_ID in terminal-input.native.tsx).
private const val TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"
internal object HardwareKeyboard {
var module: PaseoHardwareKeyboardModule? = null
@Volatile var overlayKeys: Set<String> = emptySet()
private val windows = mutableMapOf<Window, KeyboardWindowCallback>()
val dispatcher = WindowKeyDispatcher<KeyEvent>()
private val consumedPresses = mutableSetOf<Int>()
private val terminalArrowCodes = setOf("ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight")
fun observe(window: Window) {
if (windows.containsKey(window)) return
@@ -38,7 +44,7 @@ internal object HardwareKeyboard {
consumedPresses.clear()
}
fun dispatch(event: KeyEvent, composing: Boolean): Boolean {
fun dispatch(event: KeyEvent, composing: Boolean, terminalFocused: Boolean): Boolean {
if (event.flags and KeyEvent.FLAG_SOFT_KEYBOARD != 0) return false
if (event.action != KeyEvent.ACTION_DOWN && event.action != KeyEvent.ACTION_UP) return false
val code = code(event.keyCode)
@@ -64,8 +70,12 @@ internal object HardwareKeyboard {
))
if (event.action == KeyEvent.ACTION_UP) return consumedPresses.remove(event.keyCode)
val overlayOwnsKey = key != "Dead" && key in overlayKeys && !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed && !composing
if (overlayOwnsKey) consumedPresses.add(event.keyCode)
return overlayOwnsKey
// Without this the hidden input consumes the arrows as caret movement and
// its next text change stops being a plain append. Modifiers stay
// forwarded: Alt/Shift+arrow are terminal editing keys.
val terminalOwnsKey = terminalFocused && !composing && code in terminalArrowCodes
if (overlayOwnsKey || terminalOwnsKey) consumedPresses.add(event.keyCode)
return overlayOwnsKey || terminalOwnsKey
}
private fun code(keyCode: Int): String = when (keyCode) {
@@ -107,9 +117,15 @@ internal object HardwareKeyboard {
private class KeyboardWindowCallback(private val window: Window, val previous: Window.Callback) : Window.Callback by previous {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val editable = (window.currentFocus as? EditText)?.text
val focus = window.currentFocus
val editable = (focus as? EditText)?.text
val composing = editable != null && BaseInputConnection.getComposingSpanStart(editable) >= 0
return HardwareKeyboard.dispatcher.dispatch(event, { HardwareKeyboard.dispatch(event, composing) }, { previous.dispatchKeyEvent(event) })
val terminalFocused = focus?.getTag(R.id.view_tag_native_id) == TERMINAL_INPUT_NATIVE_ID
return HardwareKeyboard.dispatcher.dispatch(
event,
{ HardwareKeyboard.dispatch(event, composing, terminalFocused) },
{ previous.dispatchKeyEvent(event) },
)
}
}
@@ -51,10 +51,7 @@ import {
TERMINAL_SELECTION_GRIP_SIZE,
} from "../terminal/native-renderer/terminal-selection-controller";
import { resolveNativeTerminalMountAction } from "../terminal/native-renderer/terminal-mount-policy";
import {
forwardNativeTerminalKey,
type NativeTerminalKey,
} from "../terminal/native-renderer/terminal-key-events";
import { type NativeTerminalKeyEvent } from "../terminal/native-renderer/terminal-key-events";
import {
TerminalInput,
type TerminalInputHandle,
@@ -511,9 +508,9 @@ function NativeTerminalEmulator({
);
const handleNativeTerminalKey = useCallback(
(key: NativeTerminalKey) => {
(event: NativeTerminalKeyEvent) => {
claimActiveTerminalSizeForAction("key");
forwardNativeTerminalKey({ key, onTerminalKey: callbacksRef.current.onTerminalKey });
callbacksRef.current.onTerminalKey?.(event);
},
[claimActiveTerminalSizeForAction],
);
+2
View File
@@ -8,6 +8,8 @@ export {
subscribeOverlays,
} from "./internal/overlay-dispatch";
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
@@ -6,7 +6,7 @@ import {
TERMINAL_INPUT_CONTEXT_MENU_HIDDEN,
TERMINAL_INPUT_HITBOX_SIZE,
} from "./terminal-input.native";
import { forwardNativeTerminalKey, type NativeTerminalKeyEvent } from "./terminal-key-events";
import { createNativeTerminalKeyEvent, resolveHardwareTerminalKey } from "./terminal-key-events";
describe("native terminal typed input", () => {
function inputData(change: { data: string; shouldClear: boolean }): string {
@@ -149,25 +149,18 @@ describe("native terminal typed input", () => {
});
});
it("forwards native arrow key events to the terminal key path", () => {
const events: NativeTerminalKeyEvent[] = [];
forwardNativeTerminalKey({
key: "ArrowUp",
onTerminalKey: (event) => {
events.push(event);
},
it("identifies hardware arrows by code and keeps their modifiers", () => {
// UIKit leaves `key` as a sentinel for Left/Right, so the code leads.
expect(resolveHardwareTerminalKey({ key: "\uF702", code: "ArrowLeft" })).toBe("ArrowLeft");
expect(resolveHardwareTerminalKey({ key: "ArrowUp", code: "" })).toBe("ArrowUp");
expect(resolveHardwareTerminalKey({ key: "a", code: "KeyA" })).toBeNull();
expect(createNativeTerminalKeyEvent("ArrowDown", { shift: true, alt: true })).toEqual({
key: "ArrowDown",
ctrl: false,
shift: true,
alt: true,
meta: false,
});
expect(events).toEqual([
{
key: "ArrowUp",
ctrl: false,
shift: false,
alt: false,
meta: false,
},
]);
});
it("keeps the hidden input from owning terminal long-press selection", () => {
@@ -1,5 +1,6 @@
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
import {
Platform,
StyleSheet,
type NativeSyntheticEvent,
type StyleProp,
@@ -10,10 +11,19 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { resolveNativeTerminalKey, type NativeTerminalKey } from "./terminal-key-events";
import { hasActiveOverlay, subscribeHardwareKeyboard } from "@/keyboard";
import {
createNativeTerminalKeyEvent,
resolveHardwareTerminalKey,
resolveNativeTerminalKey,
type NativeTerminalKey,
type NativeTerminalKeyEvent,
} from "./terminal-key-events";
export const TERMINAL_INPUT_CONTEXT_MENU_HIDDEN = true;
export const TERMINAL_INPUT_HITBOX_SIZE = 1;
/** Matched by the Android hardware keyboard module to claim arrow keys for this input. */
export const TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input";
export interface TerminalTextInputChange {
data: string;
@@ -39,7 +49,7 @@ interface TerminalInputProps {
isKeyboardVisible: boolean;
onFocus?: () => void;
onInput?: (data: string) => void;
onTerminalKey?: (key: NativeTerminalKey) => void;
onTerminalKey?: (event: NativeTerminalKeyEvent) => void;
style?: StyleProp<TextStyle>;
}
@@ -187,6 +197,8 @@ export const TerminalInput = forwardRef<TerminalInputHandle, TerminalInputProps>
const inputRef = useRef<EditingTextInputHandle>(null);
const isFocusedRef = useRef(false);
const pendingFocusFrameRef = useRef<number | null>(null);
const onTerminalKeyRef = useRef(onTerminalKey);
onTerminalKeyRef.current = onTerminalKey;
const inputState = useMemo(() => createTerminalTextInputState(), []);
const inputStyle = useMemo(() => [styles.input, style], [style]);
@@ -250,6 +262,27 @@ export const TerminalInput = forwardRef<TerminalInputHandle, TerminalInputProps>
useEffect(() => clearPendingFocus, [clearPendingFocus]);
useEffect(() => {
// Physical arrows arrive through the native key stream, never through
// TextInput.onKeyPress (RN builds that event from the IME connection).
// The native module claims them for this input so the hidden buffer
// cannot move its caret, then re-emits them here for the PTY.
if (Platform.OS !== "android") return;
return subscribeHardwareKeyboard((event) => {
if (!isFocusedRef.current || event.phase !== "down" || event.isComposing) return;
if (hasActiveOverlay()) return;
const key = resolveHardwareTerminalKey(event);
if (!key) return;
onTerminalKeyRef.current?.({
key,
ctrl: event.ctrlKey,
shift: event.shiftKey,
alt: event.altKey,
meta: event.metaKey,
});
});
}, []);
useImperativeHandle(
ref,
() => ({
@@ -293,7 +326,7 @@ export const TerminalInput = forwardRef<TerminalInputHandle, TerminalInputProps>
(event: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
const change = inputState.receiveKeyPress(event.nativeEvent.key);
if (change.key) {
onTerminalKey?.(change.key);
onTerminalKey?.(createNativeTerminalKeyEvent(change.key));
}
if (change.data.length > 0) {
onInput?.(change.data);
@@ -321,6 +354,7 @@ export const TerminalInput = forwardRef<TerminalInputHandle, TerminalInputProps>
blurOnSubmit={false}
importantForAutofill="no"
multiline={true}
nativeID={TERMINAL_INPUT_NATIVE_ID}
onChangeText={handleChangeText}
onBlur={handleBlur}
onFocus={handleFocus}
@@ -22,19 +22,26 @@ export function resolveNativeTerminalKey(key: string): NativeTerminalKey | null
}
}
export function createNativeTerminalKeyEvent(key: NativeTerminalKey): NativeTerminalKeyEvent {
return {
key,
ctrl: false,
shift: false,
alt: false,
meta: false,
};
/**
* Physical keyboards report the DOM `code`. UIKit leaves `key` as a sentinel
* for Left/Right, so the code is the only reliable identifier there.
*/
export function resolveHardwareTerminalKey(input: {
key?: string;
code?: string;
}): NativeTerminalKey | null {
return resolveNativeTerminalKey(input.code ?? "") ?? resolveNativeTerminalKey(input.key ?? "");
}
export function forwardNativeTerminalKey(input: {
key: NativeTerminalKey;
onTerminalKey?: NativeTerminalKeyHandler;
}): void {
input.onTerminalKey?.(createNativeTerminalKeyEvent(input.key));
export function createNativeTerminalKeyEvent(
key: NativeTerminalKey,
modifiers: { ctrl?: boolean; shift?: boolean; alt?: boolean; meta?: boolean } = {},
): NativeTerminalKeyEvent {
return {
key,
ctrl: modifiers.ctrl ?? false,
shift: modifiers.shift ?? false,
alt: modifiers.alt ?? false,
meta: modifiers.meta ?? false,
};
}