Skip to content

fix(mobile): deliver Android keyboard chords to the live terminal input - #23418

Closed
kargnas wants to merge 5 commits into
stablyai:mainfrom
kargnas:fix/mobile-android-hardware-key-chords
Closed

kargnas wants to merge 5 commits into
stablyai:mainfrom
kargnas:fix/mobile-android-hardware-key-chords

Conversation

@kargnas

@kargnas kargnas commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

On Android, the keys a terminal needs most (Ctrl+C, Esc, Tab, arrows) never reached the terminal on the computer when they were typed on a keyboard app like Unexpected Keyboard or on a Bluetooth keyboard. Only the on-screen accessory buttons worked. Now keys from a keyboard app go through to the terminal the same way the accessory buttons do. Bluetooth keyboards take the same code path, but that path has not been tested on a device yet.

What Changed

Before (Android, live input mode): Ctrl chords, Esc, Tab, arrows, Home/End, PageUp/PageDown and F-keys from a keyboard app or a hardware keyboard never reached the terminal (the hidden field dropped them, or used Tab and arrows for its own focus and cursor). Ctrl+C/A/X/Z/V could instead run as copy / select-all / cut / undo / paste on the hidden text field.

After: those keys reach the terminal as the bytes a terminal expects:

  • Ctrl+C sends \x03, Esc sends \x1b, Up sends \x1b[A.
  • Shift+Tab sends \x1b[Z, Alt+b sends \x1bb, Ctrl+Up sends \x1b[1;5A.
  • Ctrl+V now sends \x16 (quoted-insert, as in any terminal) instead of pasting. Paste stays on Ctrl+Shift+V and the Paste button.
  • Ctrl+Space sends NUL (\x00).

Plain typing, Enter and Backspace work exactly as before.

Also on iOS and the web page: the shared shortcut table gained xterm's control codes for Ctrl+2 to Ctrl+8 and Ctrl+/. That table also builds custom keys in the "add custom key" dialog on every platform. Before, those chords built to nothing and Save did nothing; now they can be saved as custom keys. This is the only change outside Android.

Mechanism:

  • Live input is a hidden React Native TextInput. On Android, React Native's input connection forwards only Backspace, Enter and digits to onKeyPress. Every other key event went to TextView, which either dropped it or ran a text-editing shortcut.
  • A new local Expo module, mobile/modules/orca-terminal-key-capture, adds an Android-only view that wraps only the live-input field. It is the field's parent on the focus path, so its dispatchKeyEvent sees each key before TextView and before shortcut handling. This works the same for keys a keyboard app sends through its input connection and for hardware keys.
  • TerminalKeyChord.kt is a pure function that decides which keys the view takes. It has a JVM unit test.
  • When the view takes a key-down, it also swallows the matching key-up. Otherwise the key-up still reaches the field: ReactEditText hides the soft keyboard on Enter's key-up (so Alt+Enter would close it), and a hardware Escape key-up would fall through to Back.
  • On the JS side, terminal-key-chord-input.ts converts the key to bytes with the existing buildTerminalShortcutKey and sends them through handleAccessoryKey, the same path the accessory bar uses. There is no new byte table and no new send path.
  • TerminalKeyCapture.tsx renders its children unchanged on iOS and the web page. On Android it falls back to plain children when the native view is missing, for example on a dev client built before this module.
  • Buffered input mode is not wrapped. It is an ordinary text editor, so the field keeps its normal shortcuts there.
  • The dock's JSX changed; mobile-session-route-parity.test.ts used to pin that, and upstream removed the whole parity test in test: remove junk tests that assert source text instead of behavior #23815 along with the other source-text assertions.

Keys the capture deliberately leaves to the field:

  • Backspace (KEYCODE_DEL), including Ctrl+Backspace (Unexpected Keyboard's delete-word key). The field already turns every Backspace into a terminal erase, so taking it here would erase twice.
  • Bare Enter and bare Space, so Enter still submits and Space is still text.
  • Plain characters with no Ctrl or Alt.
  • Anything with Meta, so Cmd/Win shortcuts stay with the system.
  • Right Alt when the keyboard layout maps a character to it. That is AltGr, so AltGr layouts can still type their characters. Left Alt is always an Esc prefix.
  • Ctrl+Shift+V, which stays the field's paste, as in Linux terminals.

On Cyrillic or Greek layouts, Ctrl+C still sends \x03, because the letter is read from the key code.

Why

Alternatives considered:

  • Patching ReactEditText or its input-connection wrapper: React Native Android ships as a prebuilt AAR, so a source patch does not reach the build.
  • Handling keys in ReactActivity.onKeyDown: only keys the view tree left unhandled get there. TextView handles arrows itself while the field holds text, so arrows would never arrive.
  • Filtering to physical keyboards only: this misses the main case. Keyboard apps like Unexpected Keyboard send chords with InputConnection.sendKeyEvent(KEYCODE_x, META_CTRL_ON) from the virtual keyboard device with FLAG_SOFT_KEYBOARD set.

A wrapper view is the smallest place that sees both keyboard-app and hardware key events before TextView, and it reuses the existing byte encoding and send path.

Two choices a reviewer may want to weigh in on:

Linked Issue

Fixes #25496

That issue is item C of #9702, "CTRL+C doesn't work on the keyboard, only on the UI button" (Android + Bluetooth keyboard), filed on its own. This PR leaves #9702 open: items A, B and D, and the iOS/iPadOS side, are out of scope.

Draft #18901 overlaps on the physical-keyboard half. Its capture view rejects keyboard-app events (isPhysicalKeyboardEvent excludes FLAG_SOFT_KEYBOARD and VIRTUAL_KEYBOARD), so it does not cover the Unexpected Keyboard path. This PR stands on its own and is much narrower: key capture on Android only, and only for the live-input field.

Visual Proof

No recording or screenshot is attached; attachments could not be uploaded from the environment this PR was prepared in.

What a reviewer would see on an Android phone with Unexpected Keyboard, in live input mode:

  • Before: Ctrl+C while a command runs does nothing, and Up does not recall shell history.
  • After: Ctrl+C interrupts the command and Up recalls the previous command, as the accessory buttons already did.

I verified this at the byte level against a mock server, not against a real shell; see Testing.

Testing

  • I manually tested these changes locally (Android emulator and a Galaxy Z Fold7; see below)
  • Automated tests added/updated, or explained why not below

Prebuilt APK for trying this on a phone: https://github.com/kargnas/orca/releases/tag/preview-mobile-20261005-f1d7719. It contains this PR and my other open mobile PRs on top of main 40f9e7a3fc, and installs next to the regular app as "Orca Preview". On an Android 13 emulator it launched, paired with mobile/scripts/mock-server.ts and painted the terminal, and Ctrl+C and Up sent with adb shell input in live input reached the mock host as \x03 and \x1b[A.

End to end (keyboard-app path): a headless Android emulator (API 33) with Unexpected Keyboard 2.1.0 as the active keyboard, paired with mobile/scripts/mock-server.ts, with a terminal open in live input mode. The mock server logged:

[SEND] terminal=term-1 text="\^C"    <- Ctrl+C
[SEND] terminal=term-1 text="\^["    <- Esc
[SEND] terminal=term-1 text="\t"        <- Tab
[SEND] terminal=term-1 text="\^[[A"  <- Up arrow
[SEND] terminal=term-1 text="a"         <- plain letter (unchanged)
[SEND] terminal=term-1 text="\u007f"    <- Backspace, sent once (unchanged)

The soft keyboard stayed open throughout. I did not record a run without this change; the "before" above comes from the issue report and React Native's source.

Physical device, on ea7df33d (the same code as d524b8397c, rebased onto main 21f8e0f: the dock conflict was main switching the keyboard type to hostOs(), and the route-parity pins were re-measured): a release APK (arm64) installed on a Galaxy Z Fold7 (SM-F966N, Android 16) next to the existing Orca app under a separate application id, paired with the same mock server over adb reverse, cover screen, live input mode:

  • Unexpected Keyboard (Korean layout), Ctrl then a digit: Ctrl+3 sent "\^[", Ctrl+4 sent "\^\", Ctrl+8 sent "\u007f". Ctrl with a Hangul letter does not produce a chord: the keyboard composes the letter instead, which is the keyboard's behavior, so Ctrl+C through the keyboard app is covered only by the emulator run above.
  • Key events injected with adb shell input (the path a hardware keyboard takes, though from Android's virtual keyboard device rather than a Bluetooth one): Ctrl+C "\^C", Ctrl+D "\^D", Esc "\^[", Up "\^[[A", Alt+B "\^[b". After Esc the soft keyboard was still shown and the app stayed in front.

Automated, on the final commit:

  • After rebasing onto main 21f8e0f: mobile tsc --noEmit, check:tests-typecheck, pnpm test (9755 passed, 6 skipped), the session-terminal closure test, and check:code-quality:changed pass.
  • After the review follow-up (7b62fe83f9, consumes modifier-less key repeats of a taken chord): ./gradlew --no-daemon :orca-terminal-key-capture:compileDebugKotlin passes.
  • After the rebase onto main 31012ae (feature e2078ac1b9, repeat fix 5b9e42aca9): upstream's test: remove junk tests that assert source text instead of behavior #23815 cleanup deleted mobile-session-route-parity.test.ts, which was the only conflict. Mobile tsc --noEmit, check:tests-typecheck, pnpm test (9650 passed, 6 skipped), and check:code-quality:changed pass.
  • After the greptile review fixes (340bbfaa4e): the taken-key record moved into TerminalKeyDispatchTracker, which clearChildFocus and onDetachedFromWindow clear, closing the stale-key repeat leak; the same class is covered by the new TerminalKeyDispatchTrackerTest JVM suite, which pins each dispatch decision (chord taken, repeat swallowed, matching key-up consumed, focus-loss clear). ./gradlew --no-daemon :orca-terminal-key-capture:compileDebugKotlin and testDebugUnitTest pass.
  • After the second review round (e35b382a30): records no longer die on focus loss at all — pending presses are keyed by (keyCode, deviceId) and survive focus changes, so a key-up returning after refocus is still consumed, and two devices holding the same key each get their own key-up swallowed. A device's next fresh down retires its previous record, which keeps the earlier over-swallow fix intact on every focus-loss path (clearFocus, requestChildFocus, detach). TerminalKeyDispatchTrackerTest grew to six cases covering both ends. ./gradlew --no-daemon :orca-terminal-key-capture:compileDebugKotlin and testDebugUnitTest pass.
  • After the third review round (f15e6fe75d): onKeyUp no longer swallows a key-up just because the key code has a pending record — the up is consumed only when the record for that device was actually removed, so an up whose down the field received (e.g. an IME plain Enter while a hardware Ctrl+Enter is still held) reaches the field instead of leaving it holding a down that never ends. TerminalKeyDispatchTrackerTest added aKeyUpFromADeviceWhoseDownWasNotTakenPasses. ./gradlew --no-daemon :orca-terminal-key-capture:compileDebugKotlin and testDebugUnitTest pass.
  • cd mobile && pnpm exec tsc --noEmit passes.
  • cd mobile && pnpm run check:tests-typecheck passes.
  • cd mobile && ORCA_BACKGROUND_LAUNCH=1 pnpm test passes: 892 files, 9631 tests passed, 6 skipped. New and updated tests:
    • terminal-key-chord-input.test.ts covers the chord-to-bytes conversion.
    • terminal-accessory-keys.test.ts pins every Ctrl+2 to Ctrl+8 control code; Ctrl+1 still builds nothing.
  • cd mobile && pnpm lint && pnpm format:check pass, and so do oxlint / oxfmt --check on the changed files.
  • pnpm run check:code-quality:changed at the repo root reports 0 new findings.

Earlier on this branch (the code is identical; only the new digit-row test was added since):

  • cd mobile && npx expo prebuild --platform android --no-install, then cd android && ./gradlew --no-daemon :orca-terminal-key-capture:testDebugUnitTest passes. TerminalKeyChordTest covers which keys are taken and which are left to the field. This ran locally only: no PR workflow runs Gradle unit tests (the only Gradle step in CI is assembleRelease in the Android release workflow), and the same is true of the existing orca-mobile-web-shell Kotlin tests.
  • ./gradlew --no-daemon :app:assembleDebug, installed on the emulator for the end-to-end check above.
  • The web page bundle still builds and verifies: node config/scripts/build-mobile-web-app-bundle.mjs, node config/scripts/verify-mobile-web-app-bundle.mjs, and config/scripts/build-mobile-web-app-bundle.test.mjs (47/47). config/scripts/mobile-web-app-session-terminal-closure.test.mjs also passes.

Not verified:

  • A real Bluetooth or USB keyboard. Only adb-injected key events were used for the hardware path.
  • The key-up swallowing for a taken Enter chord (Alt+Enter), and non-Latin hardware layouts.
  • The custom-key dialog on iOS and the web page, beyond the unit test of the shared builder.
  • Platforms tested: Android emulator and a Galaxy Z Fold7 (cover screen).

Unchanged pre-existing behavior: keyboard chords go through handleAccessoryKey, so they share the accessory bar's existing ordering. If a batch of typed text is still in flight to the terminal, an accessory key or keyboard chord pressed right after it can arrive first. This PR does not change that.

AI Disclosure

Developed with Claude Code (Claude Opus 5.5).

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Scope: key capture is Android-only and wraps only the live-input field. iOS, the web page and buffered input mode keep the plain field. The one cross-platform effect is the custom-key dialog described in What Changed.
  • Backwards compatibility / remote: no RPC or wire change; the bytes travel over the existing terminal.send. SSH and remote hosts receive the same bytes the accessory bar already sends. A dev client built without the new native module still loads this bundle and simply behaves as before.
  • Security / performance: the view only looks at key events delivered to the focused live-input field, and it sends only bytes the user could already send from the accessory bar. It adds one small native view in the live-input path and no per-frame work.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason (no attachments; see Visual Proof for what a reviewer would see and the byte-level evidence)
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred). This is a mobile-only change, so the mobile equivalents and the root changed-code gate were run locally; the desktop suites are left to CI.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Android key capture module — a new Android-only local Expo module (orca-terminal-key-capture) wraps the hidden live-input field on the focus path so dispatchKeyEvent sees IME and hardware keys before TextView. It takes chords (and swallows their key-up) decisions via the pure TerminalKeyChord.from, falling back to plain children when the module is absent.
  • JS chord→bytes bridge — createTerminalKeyChordInput reuses buildTerminalShortcutKey and the accessory-bar send path (handleAccessoryKey), so no new byte table or transport path is introduced.
  • Cross-platform shortcut table — CTRL_PRINTABLE_BYTES gains xterm's Ctrl+2…Ctrl+8 and Ctrl+/ codes, which also lets the custom-key dialog build those chords on iOS/web.
  • Dock wiring and tests — the live TextInput now sits inside TerminalKeyCapture; route-parity pins moved (leaf 61→62, style refs 172→173) and new unit tests pin the chord bytes.

I checked the load-bearing claims against AOSP sources: META_CTRL_MASK | META_ALT_MASK | META_META_MASK do include the *_ON bits, so readChord's getUnicodeChar(metaState and chordModifiers.inv()) does strip ctrl/alt/meta while keeping shift; and TextView.onKeyShortcut handles META_CTRL_ON | META_SHIFT_ON + V as paste-as-plain-text, so leaving Ctrl+Shift+V to the field still pastes on Android (the UI Paste button remains the primary path). The two choices the author flagged — Ctrl+V → \x16 and Ctrl+Space → NUL — are both consistent with terminal semantics and the accessory bar, so I have no objection to either; the Ctrl+Space cost (hardware layout switch) is worth a maintainer call only if that gesture matters to this audience. The author's documented gaps (hardware/Bluetooth device path, Alt+Enter key-up, non-Latin hardware layouts, and the local-only Gradle tests) are accurate and understood.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds an Android native view that captures selected physical keyboard chords and emits their key and modifier data. Adds conversion from captured chords to terminal accessory inputs, including additional Ctrl byte mappings. Wraps the live-input field with platform-specific key capture and dispatches converted inputs through the existing accessory-key handler.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to 340bb

Android keyboard chords should generally reach the terminal as intended. Two edge cases remain. If two input devices send the same key at once, a stray key-up can reach the text field. The native key-event path also has no automated test coverage. Both are bounded, so this is mergeable, but the owner should be aware of them.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 340bb

Keyboard chords gain a new route to the active terminal, but the route uses the existing command controls. No security bypass was established. Hardware-keyboard and interrupted-key behavior remain uncertain.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new input route can issue bytes to the selected, connected terminal with the user's existing send authority. The inspected route does not establish broader terminal or service authority.

Trust Boundaries and Controls

  • observed — Native capture does not select a session or send commands itself. Its callback enters the existing accessory handler, where send eligibility is checked before raw terminal transmission.

Resilience and Maintainability Implications

  • inferred — Key ownership is stored by key code, so the inspected code alone cannot establish pairing if a press is interrupted without key-up or focus cleanup. No resulting security bypass is established.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR still adds shared CTRL_PRINTABLE_BYTES mappings for Ctrl+2 through Ctrl+8 and Ctrl+/. These mappings change custom-key behavior on Android, iOS, and the web page. Issue [#9702] item C covers … Remove the Ctrl+2 through Ctrl+8 and Ctrl+/ mappings and their tests, or link these changes to a separate active coding requirement.
Docstring Coverage ⚠️ Warning Docstring coverage is 17.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 16 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue [#9702] item C requires keyboard Ctrl+C to reach the terminal in Android live-input mode. TerminalKeyCapture.android.tsx wraps the live input with the native capture view. `TerminalKeyDispatch…
Title check ✅ Passed The title clearly describes the main change: routing Android keyboard chords to live terminal input.
Description check ✅ Passed The description is detailed and covers the change, rationale, linked issue, testing, platform scope, and checklist. The Visual Proof section explains the expected behavior but does not include the req…
Full details: Out of Scope Changes check

Explanation

The PR still adds shared CTRL_PRINTABLE_BYTES mappings for Ctrl+2 through Ctrl+8 and Ctrl+/. These mappings change custom-key behavior on Android, iOS, and the web page. Issue [#9702] item C covers Android live-input Ctrl+C. The mapping changes and their tests do not support that requirement.

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/OrcaTerminalKeyCaptureView.kt (1)

40-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Add an event-path test for OrcaTerminalKeyCaptureView.

TerminalKeyChordTest.kt tests only TerminalKeyChord.from() with hand-built character values. It does not construct a KeyEvent or exercise dispatchKeyEvent, so the Ctrl/Alt/Meta masking, AltGr detection, and combining-accent extraction remain untested.

Add a focused Robolectric or instrumented test that sends Ctrl+C and modifier combinations through dispatchKeyEvent and asserts the resulting chord payload. Add the required test setup, since this module currently declares only JUnit.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: db606396-b33c-405f-9769-1ddb4b25fc25

📥 Commits

Reviewing files that changed from the base of the PR and between 27b823f and ea7df33d441d2806f0513138fb65964038c2867a.

📒 Files selected for processing (19)
  • mobile/modules/orca-terminal-key-capture/android/.gitignore
  • mobile/modules/orca-terminal-key-capture/android/build.gradle
  • mobile/modules/orca-terminal-key-capture/android/src/main/AndroidManifest.xml
  • mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/OrcaTerminalKeyCaptureModule.kt
  • mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/OrcaTerminalKeyCaptureView.kt
  • mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/TerminalKeyChord.kt
  • mobile/modules/orca-terminal-key-capture/android/src/test/java/expo/modules/orcaterminalkeycapture/TerminalKeyChordTest.kt
  • mobile/modules/orca-terminal-key-capture/expo-module.config.json
  • mobile/modules/orca-terminal-key-capture/package.json
  • mobile/modules/orca-terminal-key-capture/src/index.ts
  • mobile/src/session/MobileSessionCommandDock.tsx
  • mobile/src/session/mobile-session-command-input-styles.ts
  • mobile/src/session/mobile-session-route-parity.test.ts
  • mobile/src/terminal/TerminalKeyCapture.android.tsx
  • mobile/src/terminal/TerminalKeyCapture.tsx
  • mobile/src/terminal/terminal-accessory-keys.test.ts
  • mobile/src/terminal/terminal-accessory-keys.ts
  • mobile/src/terminal/terminal-key-chord-input.test.ts
  • mobile/src/terminal/terminal-key-chord-input.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@kargnas

kargnas commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

About the CodeRabbit nitpick asking for an event-path test of OrcaTerminalKeyCaptureView: no PR workflow runs Gradle unit tests, so a Robolectric test would add a test dependency that only ever runs locally, and I left it out. The Ctrl path through dispatchKeyEvent was checked end to end on an emulator with Unexpected Keyboard (see Testing), while AltGr and dead-key handling have no automated test.

@kargnas
kargnas force-pushed the fix/mobile-android-hardware-key-chords branch 2 times, most recently from 23e1bb8 to d524b83 Compare September 28, 2026 11:27

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Rebased the branch onto the newer main (21f8e0f9) and re-recorded the mobile-session-route-parity.test.ts pins against it: hook/callback/effect/host-JSX/leaf/style/capability hashes moved, while the counts stay at the PR's intended values (hooks 281, callbacks 80, leaf 62, style refs 174).
  • No functional PR content changed since the previous review; the dock's hostOs/useKeyboardPersistingTaps lines present in a raw branch-vs-prior-sha diff come from main, not this PR.

I re-ran the changed tests on head: mobile-session-route-parity.test.ts, terminal-key-chord-input.test.ts and terminal-accessory-keys.test.ts all pass (18 tests). The pin moves are consistent with the tree, so the parity guard is not masking a regression.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Match repeated key-downs to the consumed key event. · OrcaTerminalKeyCaptureView.kt:25-38

mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/OrcaTerminalKeyCaptureView.kt:25-38
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Match repeated key-downs to the consumed key event.

If the user presses Ctrl+C, releases Ctrl while holding C, and waits for key repeat, Android can send a repeat ACTION_DOWN for C without Ctrl. readChord returns null, so the nested TextInput receives that key-down. The following C ACTION_UP still removes KEYCODE_C from takenKeyCodes and is swallowed. The editable field can therefore receive a bare repeated character without its matching key-up.

Track the consumed event identity and consume repeats for that event.

Suggested fix
-  private val takenKeyCodes = mutableSetOf<Int>()
+  private data class TakenKeyDown(
+    val keyCode: Int,
+    val deviceId: Int,
+    val scanCode: Int,
+    val downTime: Long
+  )
+
+  private val takenKeyDowns = mutableSetOf<TakenKeyDown>()
+
+  private fun keyDownIdentity(event: KeyEvent) = TakenKeyDown(
+    keyCode = event.keyCode,
+    deviceId = event.deviceId,
+    scanCode = event.scanCode,
+    downTime = event.downTime
+  )

   override fun dispatchKeyEvent(event: KeyEvent): Boolean {
     when (event.action) {
       KeyEvent.ACTION_DOWN -> {
+        val identity = keyDownIdentity(event)
+        if (event.repeatCount > 0 && identity in takenKeyDowns) return true
         val chord = readChord(event)
         if (chord != null) {
-          takenKeyCodes.add(event.keyCode)
+          takenKeyDowns.add(identity)
           onTerminalKey(chord.toPayload())
           return true
         }
       }
-      KeyEvent.ACTION_UP -> if (takenKeyCodes.remove(event.keyCode)) return true
+      KeyEvent.ACTION_UP -> if (takenKeyDowns.remove(keyDownIdentity(event))) return true
     }
     return super.dispatchKeyEvent(event)
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 51284656-67d9-4b63-993f-75b3fd5bc894

📥 Commits

Reviewing files that changed from the base of the PR and between 23e1bb86d813690b131430febb8732f7c20cb1a1 and d524b8397c07207e7e0b481058eb673c4f31bbe4.

📒 Files selected for processing (2)
  • mobile/src/session/MobileSessionCommandDock.tsx
  • mobile/src/session/mobile-session-route-parity.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@kargnas

kargnas commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Repeat key-down matching (accepted, narrower fix in 7b62fe8)

Real edge: Ctrl+C, release Ctrl while still holding C → Android emits repeat ACTION_DOWNs for C without Ctrl, readChord returns null, the nested field receives key-downs whose ACTION_UP is then consumed by takenKeyCodes — a key-down with no matching key-up.

I did not take the suggested TakenKeyDown identity diff verbatim: it checks repeatCount > 0 && identity in takenKeyDowns before readChord, which also swallows repeats while the modifier is still held — and held-chord repeat (e.g. keeping Ctrl+key down to repeat it in the terminal) is behavior this view relies on today, since a repeat ACTION_DOWN with the modifier still pressed still carries the same downTime identity.

Instead the repeat guard runs only after readChord has had its chance: repeatCount > 0 && keyCode in takenKeyCodes consumes the stray modifier-less repeats, while chord repeats still match readChord first and resend normally. :orca-terminal-key-capture:compileDebugKotlin passes; the Kotlin path has no CI test coverage, same as before.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Consume repeats of a captured chord's key — OrcaTerminalKeyCaptureView.dispatchKeyEvent now swallows an ACTION_DOWN repeat whose key code was already taken as a chord when the chord no longer matches (the modifier was released while the key is still held), so the hidden live field no longer receives an orphan key-down whose key-up the view consumes on ACTION_UP. The chord still re-matches and resends while its modifier is held.

I checked the new guard against AOSP key-repeat behavior: repeats reuse the captured metaState (InputDispatcher::synthesizeKeyRepeatLocked), so chord repeats re-enter readChord and resend as before, and the KeyEvent contract does permit repeatCount > 0 downs. The residual edge — a keyCode-only match can over-swallow after a lost ACTION_UP or with two same-key devices — is rare, low-impact, and identical in spirit to the identity-matching suggestion already raised from another reviewer, so I'm not re-raising it. No Pullfrog review threads were open to retire.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Android IMEs such as Unexpected Keyboard, and hardware keyboards, send Ctrl
chords, Esc, Tab, arrows and F-keys as KeyEvents rather than text. The live
terminal input is a hidden React Native TextInput, and React Native's Android
input connection forwards only Backspace, Enter and digits to onKeyPress, so
TextView dropped the rest or ran them as copy/paste/select-all shortcuts and
nothing reached the PTY.

A local Android-only Expo view now wraps the live-input field. It sits above
ReactEditText on the focus path, so dispatchKeyEvent sees each key-down before
TextView and before shortcut handling. The pure TerminalKeyChord decision picks
which keys to take; the JS side maps the chord through the existing
buildTerminalShortcutKey and sends it through handleAccessoryKey, the same
path the accessory bar uses.

xterm's Ctrl+/ and digit-row control codes (Ctrl+2 to Ctrl+8) are added to the
shared shortcut table. That table also feeds the custom-key builder on every
platform, so these chords, which used to build to nothing, can now be saved as
custom keys on iOS and the web page as well. The key-capture wrapper itself is
Android-only and wraps only the live-input field, so iOS, the web page and
buffered input mode keep the plain field.

Constraint: React Native Android ships as a prebuilt AAR, so patching ReactEditText sources does not reach the build
Constraint: Unexpected Keyboard sends chords via InputConnection.sendKeyEvent(KEYCODE_x, META_CTRL_ON) with the VIRTUAL_KEYBOARD device id
Rejected: ReactActivityHandler.onKeyDown hook | only keys the view tree left unhandled reach it, so arrows never arrive while the field holds text
Rejected: taking KEYCODE_DEL | the field already turns every Backspace into PTY erases, so Ctrl+Backspace would erase twice
Directive: consume the key-up of every taken key-down; ReactEditText hides the keyboard on Enter's key-up
Directive: keep buffered input mode unwrapped and leave Ctrl+Shift+V to the field's paste
Directive: right Alt is AltGr when the layout maps a character to it; only left Alt is an Esc prefix
Tested: headless API 33 emulator with Unexpected Keyboard 2.1.0 against the mock server: Ctrl+C, Esc, Tab and Up arrive as \u0003, \u001b, \t, \u001b[A; a plain letter and Backspace (\u007f, once) are unchanged
Tested: ./gradlew :orca-terminal-key-capture:testDebugUnitTest (local only; no PR workflow runs it), mobile tsc --noEmit, check:tests-typecheck, full mobile vitest (892 files), mobile lint and format:check, root check:code-quality:changed
Not-tested: physical Bluetooth keyboards and non-Latin hardware layouts on a real device
Ctrl+C를 누른 뒤 Ctrl만 떼고 C를 계속 누르면 Android가 modifier 없는
repeat ACTION_DOWN을 보낸다. readChord가 null을 반환해 그 repeat이
TextInput으로 새고, 이어지는 ACTION_UP은 takenKeyCodes에 의해 소비되어
필드가 key-up 없는 key-down을 받는다. repeatCount>0이고 keyCode가
이미 소비된 키면 조용히 삼킨다. modifier를 유지한 chord 리피트는
readChord가 먼저 처리하므로 계속 재전송된다.
@kargnas
kargnas force-pushed the fix/mobile-android-hardware-key-chords branch from 7b62fe8 to 5b9e42a Compare September 29, 2026 11:19
@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Adds Android keyboard input handling for the terminal.

The PR appears safe to merge; the latest change addresses the unmatched key-up behavior without an identified new defect.

Summary

The PR adds Android live-terminal key capture and routes captured chords through the existing terminal shortcut and accessory-input path. The change since the previous review makes key-up consumption device-specific, so a release from an uncaptured press can reach the field.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Android key event] --> B[Capture view]
  B -->|Captured chord| C[Shortcut encoding]
  C --> D[Terminal input]
  B -->|Uncaptured event| E[TextInput]
  B -->|Key-up from captured device| F[Consume]
Loading

Reviews (4) · Last reviewed commit: "fix: 기록 없는 디바이스의 키업 통과"

코드의 key-down을 가로챈 뒤 key-up 전에 필드가 포커스를 잃으면 기록이
남아, 포커스 복귀 후 수식어 없이 같은 키를 길게 누르면 첫 입력 이후의
반복이 조용히 삼켜졌다. 포커스 상실과 뷰 분리 시 기록을 지운다. 소비
결정 상태 기계를 TerminalKeyDispatchTracker로 분리해 디스패치 판정
(코드 획득, 반복 삼킴, key-up 소비, 포커스 해제)를 JVM 테스트가 직접
검증하게 했다.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: a0e6a7f2-dc7b-46eb-b365-9685b8cd20b1

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9e42a and 340bbfa.

📒 Files selected for processing (3)
  • mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/OrcaTerminalKeyCaptureView.kt
  • mobile/modules/orca-terminal-key-capture/android/src/main/java/expo/modules/orcaterminalkeycapture/TerminalKeyDispatchTracker.kt
  • mobile/modules/orca-terminal-key-capture/android/src/test/java/expo/modules/orcaterminalkeycapture/TerminalKeyDispatchTrackerTest.kt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one coverage detail on the new focus-loss hook is noted inline.

Reviewed changes

Since the prior pullfrog review (7b62fe83), the branch was rebased onto main 31012ae and gained one commit (340bbfaa):

  • Extracted the consume state machine — OrcaTerminalKeyCaptureView's inline takenKeyCodes set became TerminalKeyDispatchTracker, a pure class with a new JVM test (TerminalKeyDispatchTrackerTest) covering chord capture, repeat swallowing, key-up consumption, and focus-loss clearing.
  • Clear taken keys on focus loss — clearChildFocus and onDetachedFromWindow now drop the record, so a stale key code can no longer swallow a later plain key's repeats after focus returns.
  • Dropped the route-parity test — mobile/src/session/mobile-session-route-parity.test.ts left the PR because upstream #23815 deleted it on main.

I read the new commit against the full PR diff. The extraction is behavior-preserving, the new test genuinely exercises the added clearing, and the focus-loss clearing is a net improvement over the previous unconditional record retention. I checked the trigger against AOSP (View.java:8143-8204, ViewGroup.java:851-873); one path it does not cover is detailed inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

키를 가로챈 뒤 포커스 상실로 기록을 지우면, 포커스가 복귀한 뒤 도착하는
key-up이 필드로 새서 Enter key-up이 키보드를 숨길 수 있었다. 기록을
포커스 변화와 무관하게 유지해 돌아온 key-up과 리피트를 계속 소비한다.
대신 같은 디바이스의 다음 fresh down이 이전 프레스의 기록을 폐기해,
key-up이 다른 뷰로 배달된 프레스의 기록도 새 눌림을 가리지 않는다.
기록을 (keyCode, deviceId) 단위로 바꿔 하드웨어 키보드와 IME가 같은
키를 동시에 눌러도 각각의 key-up을 소비한다.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The new per-device key-up tracking in TerminalKeyDispatchTracker swallows a key-up from a device that never took a press, as long as some other device holds the same key code. The fix is one membership check.

Reviewed changes

Since the prior pullfrog review (340bbfaa), one commit (e35b382a) reworked how the capture view keeps and retires taken presses:

  • Retired records on the next fresh down — the clearChildFocus override and onFocusLoss() are gone; a taken press now survives focus loss and is retired by onKeyDown on that device's next non-repeat down, so every focus-loss path is covered rather than only Android's propagate = true route.
  • Keyed pending presses by (keyCode, deviceId) — two devices holding the same key code each get their own key-up swallowed, and repeat suppression checks the device too.
  • Reset on detach — onDetachedFromWindow clears the map through the new onReset().
  • Expanded the JVM tracker test — six cases now cover a returning key-up after focus, fresh-down retirement of a stale record, and per-device key-ups.

I read the new Kotlin against the full PR diff and traced the dispatch flow. The focus-loss rework is sound: a fresh down always retires the device's previous record before readChord, so a stale record cannot shadow a new plain press. The gap is in onKeyUp's return, detailed inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

onKeyUp이 pendingUps에 같은 keyCode가 있으면 deviceId 기록 없이도 true를
반환해, 필드가 실제로 받은 down의 key-up(예: IME가 보낸 plain Enter)까지
삼켜 필드가 끝나지 않는 down을 붙드는 문제를 수정했다. 이제 자기 디바이스의
기록을 소비한 경우에만 삼키고, 기록 없는 디바이스의 key-up은 필드에 전달된다.

Tested: :orca-terminal-key-capture:testDebugUnitTest

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Since the prior pullfrog review (e35b382a), one commit (f15e6fe7) closes the per-device key-up gap that review flagged:

  • Fixed onKeyUp over-swallow — TerminalKeyDispatchTracker.onKeyUp now returns whether devices.remove(deviceId) actually removed that device's record (val consumed = devices.remove(deviceId); return consumed) instead of returning true whenever the key code had any pending device. An up from a device whose down was never taken now falls through to the field.
  • Added a regression test — TerminalKeyDispatchTrackerTest.aKeyUpFromADeviceWhoseDownWasNotTakenPasses takes Enter on the hardware device, asserts the IME's up passes, and asserts the hardware up is still consumed.

I traced the dispatch flow against the fix: onKeyDown retires the same device's prior record on every fresh down before readChord, and onChordTaken re-adds only a taken device, so the only behavior change is that a non-member device's up is no longer swallowed — exactly the reported bug. The new test exercises the fixed branch (it would fail against the previous return true). No other files changed in this delta, and no new findings.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@kargnas

kargnas commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Hi @Jinwoo-H, gentle nudge on this one when you have a moment. It now fixes its own issue, #25496 (item C of #9702, which stays open), and I've posted a prebuilt APK in #9702 so someone with a Bluetooth keyboard can check the hardware path.

My other open mobile PRs are small and linked to issues too, in case they fit the same pass: #19599 (terminal follows the phone's light/dark setting), #23419 (optional keyboard resize), #25502 (recover a missed web-ready) and #25503 (slice large terminal writes).

@nwparker

Copy link
Copy Markdown
Contributor

Merged the Android terminal keyboard fix in #31666, adapted to the current OTA input architecture and existing ordered send queue. Thank you, @kargnas, for the original keyboard capture work. Sangrak Choi is credited as a co-author on the merged commit.

Closing this source PR as superseded. The merged implementation covers the Android control-key behavior and shared shortcut mappings; physical Bluetooth keyboard coverage remains an explicit validation gap.

@nwparker nwparker closed this Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Android: Ctrl chords, Esc, Tab and arrows from keyboard apps and hardware keyboards don't reach the terminal

2 participants