Skip to content

feat(mobile): sync native text selection to terminal cursor - #10123

Closed
bbingz wants to merge 2 commits into
stablyai:mainfrom
bbingz:feat/mobile-ios-trackpad-cursor
Closed

bbingz wants to merge 2 commits into
stablyai:mainfrom
bbingz:feat/mobile-ios-trackpad-cursor

Conversation

@bbingz

@bbingz bbingz commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Sync native TextInput selection changes to the live terminal cursor, enabling iOS keyboard-trackpad cursor movement.
  • Keep middle insertions and deletions consistent by restoring, rewriting, and reseating the PTY cursor in one queued payload.
  • Preserve Hangul composition and serialize mirror, control, submit, and external-flush sends to avoid state-loss races.
  • Avoid duplicate ArrowLeft/ArrowRight bytes when hardware keypress and native selection events both fire.

Screenshots

No visual change.

Testing

  • pnpm lint — not run through pnpm because the local minimum-release-age policy rejects two newly published lockfile entries; the installed mobile oxlint binary passed instead.
  • pnpm typecheck — not run through pnpm for the same policy reason; mobile/node_modules/.bin/tsc --noEmit passed.
  • pnpm test — not run through pnpm for the same policy reason; mobile/node_modules/.bin/vitest run passed 317 files, 2,337 tests, with 2 skipped.
  • pnpm build — not run; this checkout has no generated native iOS project and no physical iOS device was online.
  • Added or updated high-quality tests that would catch regressions, including UTF-16 selection mapping, middle edits, Hangul composition, duplicate arrow suppression, stale handles, and deferred-send ordering.

Additional checks:

  • mobile/node_modules/.bin/oxlint
  • mobile/node_modules/.bin/oxfmt --check . (949 files)
  • node config/scripts/check-max-lines-ratchet.mjs
  • git diff HEAD^..HEAD --check

AI Review Report

Claude reviewed the exact change read-only in three gates: pure selection/control logic, React hook and queue integration, then the combined 13-file commit. All three gates ended with NO ACTIONABLE FINDINGS. The review traced UTF-16/code-point boundaries, collapsed versus ranged selection, middle rewrite ordering, Hangul held-syllable behavior, hardware/accessory controls, stale handles, deferred sends, React Native event ordering, and Android shared-path behavior. An earlier queue/state-clear race was identified during implementation and fixed before these final gates by serializing controls on the mirror chain and clearing the prior field session synchronously.

Cross-platform review confirmed this mobile-only change does not touch desktop shortcuts, labels, filesystem paths, shell spawning, or Electron behavior. The shared React Native path and Android selection-event ordering were reviewed; no actionable Android regression was found.

Security Audit

No dependencies, auth, secrets, filesystem paths, shell commands, native modules, or IPC schemas are added. Terminal output remains limited to normalized field text and existing mapped control bytes. Active-handle and terminal-tab guards reject stale selection/control sends, and all sends use the existing serialized terminal input channel. No security follow-up was identified.

Notes

  • Physical-device behavior remains the main residual validation gap because no iOS device was online; deterministic hook and payload tests cover the event sequences.
  • This complements fix(mobile): keep terminal caret visible without focus #10101: that PR improves the visible mobile terminal accessory bar, while this PR adds native TextInput selection-to-PTY cursor synchronization.

ELI5

On iOS, moving the cursor with the keyboard trackpad (or by selecting text) now moves the real terminal cursor too. Insertions and deletions stay in the right place, and Hangul composition is not broken. Hardware arrow keys and trackpad moves no longer send the same key twice.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ab42730d-08ef-42a3-a1c3-c1c4f0e7d7cc

📥 Commits

Reviewing files that changed from the base of the PR and between 05ad0d467eb89cf7ef5eb7268fe5bba0ebcfb12d and 6ff9380.

📒 Files selected for processing (13)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/terminal/terminal-live-control-payload.ts
  • mobile/src/terminal/terminal-live-selection-cursor.test.ts
  • mobile/src/terminal/terminal-live-selection-cursor.ts
  • mobile/src/terminal/terminal-live-selection-event-routing.test.ts
  • mobile/src/terminal/terminal-live-selection-event-routing.ts
  • mobile/src/terminal/terminal-live-text-commit.test.ts
  • mobile/src/terminal/terminal-live-text-commit.ts
  • mobile/src/terminal/use-terminal-live-accessory-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-accessory-input-commit.ts
  • mobile/src/terminal/use-terminal-live-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-input-commit.ts
  • mobile/src/terminal/use-terminal-live-pending-input-flush.ts
🚧 Files skipped from review as they are similar to previous changes (13)
  • mobile/src/terminal/terminal-live-text-commit.ts
  • mobile/src/terminal/terminal-live-selection-event-routing.test.ts
  • mobile/src/terminal/terminal-live-selection-cursor.test.ts
  • mobile/src/terminal/terminal-live-control-payload.ts
  • mobile/src/terminal/terminal-live-selection-event-routing.ts
  • mobile/src/terminal/use-terminal-live-accessory-input-commit.ts
  • mobile/src/terminal/terminal-live-text-commit.test.ts
  • mobile/src/terminal/terminal-live-selection-cursor.ts
  • mobile/src/terminal/use-terminal-live-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-accessory-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-pending-input-flush.ts
  • mobile/src/terminal/use-terminal-live-input-commit.ts
  • mobile/app/h/[hostId]/session/[worktreeId].tsx

📝 Walkthrough

Walkthrough

Terminal live input now tracks native selection changes and synchronizes cursor movement with mirrored terminal text. New utilities handle UTF-16 and code-point offsets, caret inference, Hangul composition, emoji, and normalized input. Pending input flushing maintains cursor-aware mirror state and queues controls with optional field commits. Keypress, submit, and accessory handling use the queue-based flow, while the session screen adds connection-aware sending, tab reconciliation, recovery handling, attachment support, and expanded selection and deferred-send tests.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes synchronizing native text selection with the terminal cursor.
Description check ✅ Passed The description covers the required sections, user-visible behavior, testing, AI review, security audit, and known validation gaps.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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/src/terminal/use-terminal-live-accessory-input-commit.test.ts (1)

6-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import TerminalLiveQueueControlOptions from terminal-live-control-payload.

TerminalLiveQueueControlOptions is defined in terminal-live-control-payload.ts; use-terminal-live-pending-input-flush.ts only imports it, so using the hook module as the public import path adds an unnecessary coupling. Import the type where it is defined, matching the production source.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 55460670-ac5c-40f6-9c4e-77be4e923bdb

📥 Commits

Reviewing files that changed from the base of the PR and between 2b7aa0a and bebc550.

📒 Files selected for processing (13)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/terminal/terminal-live-control-payload.ts
  • mobile/src/terminal/terminal-live-selection-cursor.test.ts
  • mobile/src/terminal/terminal-live-selection-cursor.ts
  • mobile/src/terminal/terminal-live-selection-event-routing.test.ts
  • mobile/src/terminal/terminal-live-selection-event-routing.ts
  • mobile/src/terminal/terminal-live-text-commit.test.ts
  • mobile/src/terminal/terminal-live-text-commit.ts
  • mobile/src/terminal/use-terminal-live-accessory-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-accessory-input-commit.ts
  • mobile/src/terminal/use-terminal-live-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-input-commit.ts
  • mobile/src/terminal/use-terminal-live-pending-input-flush.ts

@AmethystLiang
AmethystLiang requested a review from OrcaWin July 24, 2026 16:51
@nwparker nwparker added the enhancement New feature or request label Jul 27, 2026
@bbingz
bbingz force-pushed the feat/mobile-ios-trackpad-cursor branch from bebc550 to 05ad0d4 Compare July 31, 2026 01:26

@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 platform limitations.

⚠️ Outside diff range comments (1)
mobile/app/h/[hostId]/session/[worktreeId].tsx (1)

3006-3033: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Resolved send failures still discard the typed command.

The catch only covers rejections. A resolved { ok: false } (or send.accepted === false, which the live path checks via isTerminalSendRpcAccepted) leaves input cleared with no restore and no feedback.

🐛 Restore on rejected sends too
-      await client.sendRequest(
+      const response = await client.sendRequest(
         'terminal.send',
         buildTerminalSendParams({
           terminal: activeHandle,
           text,
           enter: true,
           deviceToken: deviceTokenRef.current
         }),
         TERMINAL_INPUT_SEND_OPTIONS
       )
+      if (!isTerminalSendRpcAccepted(response)) {
+        setInput(text)
+      }
     } catch {
       setInput(text)
🧹 Nitpick comments (1)
mobile/app/h/[hostId]/session/[worktreeId].tsx (1)

3842-3850: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Initial-prompt send skips TERMINAL_INPUT_SEND_OPTIONS.

Every other changed send path passes failWhenDisconnected so a queued send can't replay after reconnect; this one doesn't, so a prompt sent during a drop can execute long after the tab was created. Confirm this is intentional (e.g., tolerating the create→send window) rather than an omission.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5cc12b33-bdbd-4011-aa94-76a3bdd0a33a

📥 Commits

Reviewing files that changed from the base of the PR and between bebc550 and 05ad0d467eb89cf7ef5eb7268fe5bba0ebcfb12d.

📒 Files selected for processing (1)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR wires onSelectionChange from the React Native TextInput into the terminal's PTY cursor, enabling iOS keyboard-trackpad cursor movement to be reflected in the running shell. Selection events are classified as "paired-with-text-change" (triggered by a preceding onChangeText) or "cursor-only" (genuine trackpad/hardware move), and each produces either a no-op or a cursor-move plan consisting of ordered ArrowLeft/ArrowRight escape bytes.

  • New cursor-state machine (terminal-live-selection-cursor.ts): converts UTF-16 native offsets to code-point indices, plans PTY cursor moves for selection changes, and plans restore-rewrite-reseat payloads for mid-field insertions/deletions — all in a single atomic payload to prevent interleaved cursor moves.
  • Serialized control queue (queueLiveInputControl): controls and mirror sends share one ordered chain so Hangul preedit, accessory keys, submit, and external flushes can never race; a commitFieldBeforeControl flag prepends a cursor-restore prefix when the PTY cursor is mid-field.
  • Duplicate-arrow suppression: ArrowLeft/ArrowRight with a non-empty field return 'local-edit', delegating PTY steps entirely to onSelectionChange so hardware-key and selection events cannot both fire arrows for the same move.

Confidence Score: 5/5

Safe to merge. The change is mobile-only and does not touch desktop, Electron, auth, filesystem, or IPC paths.

The cursor-state machine, serialized control queue, and selection-event classifier are each small and pure, with comprehensive deterministic tests covering UTF-16 surrogate boundaries, Hangul composition, mid-field edits, hardware-arrow dedup, stale-handle rejection, and deferred-send ordering. The stale-handle guards (isHandleLive) and session-clear sequencing (clearPendingLiveInputCommitAndSelection called before awaiting the queued send) prevent the races that existed in the prior architecture. No correctness issues were found during review.

Files Needing Attention: No files require special attention. Physical-device validation (noted in the PR) remains the one gap that deterministic tests cannot fully substitute for.

Important Files Changed

Filename Overview
mobile/src/terminal/terminal-live-selection-cursor.ts New core module: UTF-16→code-point converters, planTerminalLiveSelectionMove, and planTerminalLiveFieldTextChange. Logic is sound — surrogate-pair clamping, Hangul flush-before-arrow, and single-payload middle-edit rewrite are all correct and covered by companion tests.
mobile/src/terminal/use-terminal-live-pending-input-flush.ts Major refactor: adds ptyCursorCodePointRef, mirroredFieldTextRef, applyLiveInputSelection, and queueLiveInputControl. The mirror chain now carries both text diffs and control bytes, serializing them correctly. flushPendingLiveInputText extracts handle from the ref and narrows to non-null before passing to queuePayload — type-safe.
mobile/src/terminal/use-terminal-live-input-commit.ts Adds handleLiveInputSelectionChange with correct one-shot paired/cursor-only classification; ArrowLeft/Right with non-empty field now return local-edit to prevent double-step; all clear/flush paths delegate to clearPendingLiveInputCommitAndSelection which also resets the selection session latch.
mobile/src/terminal/terminal-live-control-payload.ts New helper: buildTerminalLiveFieldCommitPrefix (cursor-restore + held-flush) and buildTerminalLiveQueuedControlPayload (conditionally prepend prefix). Small, well-focused, correctly guarded by ownsFieldState.
mobile/src/terminal/terminal-live-selection-event-routing.ts New routing module: classifies selection events as paired-with-text-change vs cursor-only, and decides whether to apply a cursor-only move. Simple, pure functions with full test coverage.
mobile/src/terminal/use-terminal-live-accessory-input-commit.ts Refactored to use queueLiveInputControl instead of flushPendingLiveInputText + direct send. send-now and commit-held-then-send cases now queue atomically through the mirror chain and synchronously clear the session state.
mobile/src/terminal/terminal-live-text-commit.ts Added ArrowLeft/Right guard: returns local-edit when field has text (either held or sent), preventing direct PTY sends that would duplicate the selection-driven arrow bytes.
mobile/app/h/[hostId]/session/[worktreeId].tsx Minimal integration change: destructs and wires handleLiveInputSelectionChange to the TextInput's onSelectionChange prop.
mobile/src/terminal/use-terminal-live-input-commit.test.ts Extensive new tests: trackpad cursor move, mid-field insert/delete, emoji code-point safety, Hangul composition with paired selections, hardware-arrow dedup, stale-handle rejection, submit reset, and deferred-send ordering. Covers all key event sequences documented in the PR.

Reviews (2): Last reviewed commit: "fix(mobile): drop redundant live-input a..." | Re-trigger Greptile

bbingz added 2 commits July 31, 2026 10:35
ArrowLeft/Right with field text already resolve to local-edit via
getTerminalLiveSpecialKeyDecision, and empty mirror state implies a zero
PTY cursor so the extra ownsFieldState check was dead.
@bbingz
bbingz force-pushed the feat/mobile-ios-trackpad-cursor branch from 05ad0d4 to 6ff9380 Compare July 31, 2026 02:35
@bbingz

bbingz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Closing as part of fork PR backlog cleanup.

This branch is long-conflicted (DIRTY) against current main and is not on the active campaign rebase list. Feel free to reopen or cut a fresh PR from an updated branch if the change is still needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants