Skip to content

fix(mobile): hold the Japanese IME reading off the terminal until it commits - #13070

Closed
makoto-developer wants to merge 2 commits into
stablyai:mainfrom
makoto-developer:fix/mobile-japanese-preedit-terminal-leak
Closed

makoto-developer wants to merge 2 commits into
stablyai:mainfrom
makoto-developer:fix/mobile-japanese-preedit-terminal-leak

Conversation

@makoto-developer

Copy link
Copy Markdown
Contributor

Summary

Partial fix for #7427 — the kana/reading half, on Android. Romaji-to-kanji conversion now works end to end; the native-side gap is called out under Notes.

Orca Mobile's direct terminal input (the default for a first-seen terminal tab) mirrors every TextInput change to the PTY. React Native exposes no composition events, so terminal-live-hangul-mirror.ts infers preedit from the trailing code points — but it only recognised Hangul. Gboard's Japanese IME writes the reading into the field itself, so every intermediate reading was forwarded to the PTY and erased again.

Captured on an Android 16 emulator with Gboard 日本語 (romaji) against a mock host that logs the exact bytes reaching terminal.send. Typing a single 差:

step bytes reaching the PTY
tap s "s" — U+FF53, still uncommitted
tap a "\x7fさ"
pick 差 "\x7f差"

Three sends and two erases for one character, with the reading sitting on the PTY the whole time. That is the sあ corruption in the issue: over a relayed link the echo and the erases interleave, and any TUI that reacts to keystrokes sees the reading before the erase arrives.

The fix. Hold the whole trailing run of Japanese reading code points rather than a single syllable, and let only a display-final Hangul syllable settle on the pause timer. A reading is discarded the moment a candidate is picked (にほんご → 日本語), so committing it on a pause is the leak — Japanese now waits for a real boundary (candidate pick, Enter, accessory key). Kanji is excluded from the held run because it only appears once the user has already picked a candidate.

Same trace after the fix, same device, same taps:

step bytes reaching the PTY
tap s —
tap a —
pick 差 "差"
Enter (IME 確定) —
Enter (submit) "さ", then "\r"

One send of the committed text, no erases, and Enter still flushes the reading before the carriage return.

The module now covers two scripts, so it is renamed terminal-live-hangul-mirror.ts → terminal-live-composition-mirror.ts per the naming rule in AGENTS.md. Hangul behavior is byte-identical; its existing tests are unchanged.

Mock host fix. mock-server-terminal-stream.ts answered terminal.send with { ok: true } while the client gates follow-up controls on accepted (isTerminalSendRpcAccepted). Every live send therefore read as rejected, and the carriage return after a flushed composition was silently dropped. The native-chat scenario already returns accepted; this aligns the terminal scenario with it and with the real runtime. Without it the harness cannot exercise Enter at all.

Screenshots

No visual change. The behavioral difference is in the bytes reaching the PTY, tabulated above.

Testing

  • pnpm lint (mobile oxlint, clean)
  • pnpm typecheck (repo root, and tsc --noEmit in mobile/)
  • pnpm test — mobile/ 3401 passed. One pre-existing unrelated failure, src/mock-server-key-pair.test.ts > makes concurrent creators converge on the persisted winner, which fails identically on an unmodified tree.
  • pnpm build — not run; the change is confined to mobile/ and touches no Electron main/renderer code.
  • Added regression tests that would catch this

Tests replay the captured device traces at two levels: the mirror step (terminal-live-composition-mirror.test.ts) and the commit hook with fake timers (use-terminal-live-input-commit.test.ts). I verified they fail against the pre-fix logic — reverting the held-run change alone fails 5 of them, including the s→a→差 trace and the settle-timer case.

Device verification: Android 16 (API 36, Google Play, arm64) emulator, Gboard 日本語 romaji QWERTY, dev-client build, mock host. Before/after traces above are from that rig, not from reasoning about the source.

AI Review Report

Reviewed with Claude. What it checked and what changed as a result:

  • Correctness of the held run. First iteration still leaked, because the 300 ms settle timer committed the reading during a typing pause. Device testing caught it; the timer is now opt-in per script (heldCommitsOnPause) rather than firing for any held text.
  • Cross-language regression. The full-width range started as U+FF01–FF5E, which swallows the full-width punctuation Chinese IMEs emit as committed text — that would have regressed [Bug]: Chinese IME input does not work in the mobile app #7495, which composes correctly today. Narrowed to full-width letters only (U+FF21–FF3A, U+FF41–FF5A) and pinned with a test.
  • Korean regression. Hangul keeps its single-code-point hold and its pause commit; all pre-existing Hangul tests pass untouched.
  • ASCII / other scripts. ASCII, Chinese and Vietnamese still mirror immediately with no held text; verified by unit test and, for ASCII, on the emulator.
  • Cross-platform. No platform branches added or changed. The module is pure code-point logic with no platform, path, shell, or shortcut dependency; nothing here is macOS/Linux/Windows specific. iOS shares the same mirror and gets the same behavior — the ranges describe Unicode, not a keyboard.
  • SSH / remote. No assumption about where the PTY runs. The change strictly reduces the number of terminal.send round trips per composed character, which helps most on a relayed or SSH-backed session.
  • Providers / agents. Untouched.
  • Performance. measureHeldRun walks only the trailing run and short-circuits on the first non-reading code point; the previous code inspected one code point. Bounded by the length of the composing reading, on a path that already allocates a code-point array.
  • Resource cleanup. No new timers or listeners; the existing settle timer is now armed strictly less often.

Security Audit

Reviewed with Claude. This changes which locally composed characters are forwarded to an existing, already-authenticated terminal.send channel, and when.

  • Input handling. Pure Unicode range checks on text the user typed into their own field. No parsing, no escaping, no injection surface; the bytes are unchanged, only their timing.
  • Command execution. The change withholds bytes until commit, so it cannot cause a command to execute that would not have executed. Enter still flushes the held reading before the carriage return, verified on device.
  • Path / secrets / auth / IPC / dependencies. Untouched. No new dependencies.
  • Data exposure. Strictly reduces what leaves the device: intermediate readings no longer reach the host at all.
  • Mock host change. Test-only fixture (mobile/scripts/), not shipped in the app.

Notes

@nwparker

nwparker commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Heads-up, and apologies for the timing — this needs a rebase and the ground moved under it.

17b3dff returned IME composition ownership to xterm and deleted the first-party composition layer. Three of the four files here went with it: terminal-live-hangul-mirror.ts, terminal-live-composition-mirror.ts and use-terminal-live-pending-input-flush.ts are all gone from main. Only use-terminal-live-input-commit.test.ts survives.

Worth checking before you spend time rebasing: the behavior you are fixing may now be native. The rule you want — a reading/preedit must not reach the terminal until it commits — is what the mounted-composition path now gives for free, because we stopped mirroring composition state ourselves. I landed a test on main that pins the Korean form of exactly this (terminal-live-native-ime-accessory-order.test.ts): an Android composing-region trace where no jamo reaches the host and an accessory keystroke cannot overtake the committed syllable.

So the useful first step is to check whether your Japanese repro still reproduces on current main. If it does, the shape that survives is a test against the current useTerminalLiveInputCommit hook rather than a reintroduced mirror — happy to help with that. If it does not, this closes itself.

One thing we learned the hard way and that applies directly: the deferral mechanism this layer used was itself the bug. On 1.4.171 it would write a Shift+Enter payload to the PTY with no Enter pressed, 10/10, and Japanese phrase-level preedits stay open far longer than any timeout bound we picked. Timers lost to letting the IME finish.

Thanks for the report and the fix attempt — the diagnosis is sound even where the code no longer applies.

…commits

Orca Mobile's direct terminal input mirrors every TextInput change to the PTY.
React Native exposes no composition events, so the mirror infers preedit from
the trailing code points — but it only recognised Hangul. Gboard's Japanese IME
writes the reading into the field itself (pending romaji as full-width Latin,
then kana), so every intermediate reading was forwarded and erased again.

Captured on an Android 16 emulator with Gboard 日本語 (romaji), typing one 差:

  tap s  -> terminal.send "s"          (U+FF53, uncommitted)
  tap a  -> terminal.send "\x7fさ"
  pick 差 -> terminal.send "\x7f差"

Three sends and two erases for a single character, with the reading visible on
the PTY the whole time. Over a relayed link the echo and the erases interleave,
which is the `sあ` corruption reported in the issue.

Hold the whole trailing run of Japanese reading code points instead of a single
syllable, and let only a display-final Hangul syllable settle on the pause timer:
a reading is discarded the moment a candidate is picked, so committing it on a
pause is the leak itself. Kanji is excluded from the held run because it only
appears once the user has picked a candidate. The same trace now sends "差" once,
with no erases, and Enter still flushes the reading before the carriage return.

Full-width punctuation is deliberately not held. Chinese IMEs compose in the
candidate bar and emit it as committed text, and that path works today.

The mock host answered terminal.send with `ok` rather than `accepted`, so the
client read every live send as rejected and dropped the carriage return after a
flushed composition. Align it with the real runtime so the harness can exercise
the path at all.
@makoto-developer
makoto-developer force-pushed the fix/mobile-japanese-preedit-terminal-leak branch from 9f25c50 to 7d5478c Compare August 9, 2026 18:37
@makoto-developer

Copy link
Copy Markdown
Contributor Author

Thanks — rebased onto 34f2a62cd, and I checked the repro like you asked. Short version: it still reproduces, because #13128 was reverted the day after you wrote this.

The ground moved back. 17cfc968c ("Revert the terminal IME composition-ownership change", #13282, Aug 8) reverted both #13128 and #13168. On current main the first-party composition layer is present again:

your note main @ 34f2a62cd
terminal-live-hangul-mirror.ts gone present
use-terminal-live-pending-input-flush.ts gone present
terminal-live-native-ime-accessory-order.test.ts landed on main not in the tree
react-native-terminal-input (Android Kotlin) — removed by the revert
patches/[email protected] — removed by the revert

terminal-live-composition-mirror.ts is just this PR's rename of the hangul mirror, so its absence from main is expected. No criticism intended — the revert landed after your comment, so the state you described was real at the time.

The repro on current main, unmodified. Android 16 emulator (API 36, Google Play, arm64), Gboard 日本語 romaji QWERTY, dev-client build, mock host logging the exact bytes reaching terminal.send. Typing one 差:

tap s   -> terminal.send "s"        (U+FF53, still uncommitted)
tap a   -> terminal.send "\x7fさ"
pick 差 -> terminal.send "\x7f差"

Byte-for-byte the same trace as before the revert. So this does not close itself.

Same taps on this branch, rebased:

tap s   -> (nothing)
tap a   -> (nothing)
pick 差 -> terminal.send "差"
Enter   -> terminal.send "さ", then "\r"     (separate run, submitting an unconverted reading)

One send of the committed text, no erases, and Enter still flushes the reading before the carriage return.

On the timer point — that matches what I hit, and it is the part of this PR I would most want you to look at. My first attempt kept the existing 300 ms settle timer and it still leaked, because the timer committed the reading during a normal typing pause. Japanese phrase-level preedits are exactly the case you describe: no timeout bound is right, because the reading is discarded when a candidate is picked. So the timer is now opt-in per script — Hangul keeps it (a syllable is display-final, and its existing tests are untouched), Japanese never uses it and waits for a real boundary instead. This PR does not add a new deferral mechanism; it removes the timer from the path where the timer was the bug.

Rebase was clean; the runMirrorStepRef effect change from main is preserved. mobile suite green (494 in src/terminal), tsc and oxlint clean.

Two things I would still like your call on, both in the PR body: whether to keep the file rename (it will conflict with #12341 if that comes back), and whether you would rather close this outright once the native route relands rather than carry both. Happy either way — the traces above are the part worth keeping regardless.

One unrelated thing I hit while building the harness: mobile/scripts/mock-server-terminal-stream.ts answers terminal.send with { ok: true }, but the client gates on accepted (isTerminalSendRpcAccepted), so every live send reads as rejected and the carriage return after a flushed composition is dropped. The native-chat scenario already returns accepted. It is fixed in this PR; if you would rather have it standalone, say so and I will split it out.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The terminal live composition mirror now supports Hangul and Japanese preedit text. It holds Japanese readings until conversion or explicit submission, while Hangul can commit after a pause. The input hooks use the new mirror module and pause-commit flag. Tests cover Japanese romaji, kana, kanji, katakana, submission, deletion, and punctuation behavior. The mock terminal stream now returns acceptance and UTF-8 byte-count fields.

Mergeability Score: 🟡 Moderate · up to f98f8

Whole-line Japanese kana pasted or produced by dictation may not reach the terminal until a later commit boundary, leaving input apparently stuck. This bounded correctness issue should be fixed or explicitly accepted before merge.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: delaying Japanese IME readings until commitment.
Description check ✅ Passed The description clearly explains the problem, implementation, issue, testing, scope, and limitations, although it does not follow every template heading.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3b72e8e7-45b5-4c80-8d42-a4961527f64b

📥 Commits

Reviewing files that changed from the base of the PR and between bd9addb and 7d5478c.

📒 Files selected for processing (6)
  • mobile/scripts/mock-server-terminal-stream.ts
  • mobile/src/terminal/terminal-live-composition-mirror.test.ts
  • mobile/src/terminal/terminal-live-composition-mirror.ts
  • mobile/src/terminal/terminal-live-hangul-mirror.ts
  • mobile/src/terminal/use-terminal-live-input-commit.test.ts
  • mobile/src/terminal/use-terminal-live-pending-input-flush.ts
💤 Files with no reviewable changes (1)
  • mobile/src/terminal/terminal-live-hangul-mirror.ts

Classifying every trailing kana as a reading was wrong for the common case of a
candidate that keeps a kana tail. たべる → 食べる sent 食 and held べる, so the PTY
sat on a partial word until the next boundary, and most Japanese verbs and
adjectives take okurigana.

Script alone cannot separate "picked 食べる" from "typed を after 日本語" — both end
in kana. The text before the trailing run settles it: a conversion rewrites that
prefix, continued typing leaves it untouched. Compare the field against the one
the user was last looking at (sent + held) and commit everything when the prefix
moved. A whole line arriving at once, which is what paste and dictation look
like, also commits rather than stranding a tail.

Also stop re-holding text the PTY already echoed, so typing more kana after a
committed candidate (食べる → 食べるもの) no longer erases and replays べる.

Verified on the Android 16 emulator with Gboard 日本語 romaji: picking 食べる sends
"食べる" once, with no erases.

The mock host reported bytesWritten as UTF-16 units of `text`, which misstates
every CJK send and ignores the enter and interrupt suffixes. Count UTF-8 bytes of
the payload the runtime actually writes, matching buildSendPayload.
@makoto-developer

Copy link
Copy Markdown
Contributor Author

Both review comments were right, and the okurigana one was a real defect — thanks.

Okurigana (🟠 Major). Confirmed before fixing. たべる → 食べる sent 食 and held べる, so the PTY sat on a partial word:

field="たべる"  → send=""    held="たべる"
field="食べる"  → send="食"  held="べる"     ← wrong

Most Japanese verbs and adjectives take okurigana, so this was closer to "broken" than "edge case".

Script alone cannot separate picked 食べる from typed を after 日本語 — both end in kana. What separates them is the text before the trailing run: a conversion rewrites it, continued typing leaves it untouched. The step now compares the field against the one the user was last looking at (sent + held) and commits everything when that prefix moved. Two consequences worth calling out:

  • A whole line arriving at once — paste, dictation — reads as a rewritten prefix and commits, rather than stranding a tail. That is the behaviour you want there anyway.
  • Text the PTY already echoed is never re-held, so 食べる → 食べるもの no longer erases and replays べる.

Re-verified on the Android 16 emulator with Gboard 日本語 romaji: typing tabe sends nothing, and picking the 食べる candidate sends "食べる" once, with no erases.

bytesWritten (🟡 Minor). Correct on both counts. It now builds the payload the way buildSendPayload does in orca-runtime.ts (text, then \r for enter, then \x03 for interrupt) and reports Buffer.byteLength(payload, 'utf8').

Added regressions for the okurigana conversion, for continuing to type after a committed candidate, and for a reading typed after committed kanji (which must still be held). mobile suite green; the one failure, mock-server-key-pair, fails identically on an unmodified tree.

@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/terminal-live-composition-mirror.test.ts (1)

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

Remove redundant BDD phase labels.

The test names and assertions already identify these phases. Keep comments only when they add behavior rationale.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior.”

Also applies to: 227-227, 297-297, 317-317, 330-330

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 92b01ba2-c2aa-4f26-97e5-e46d348513ea

📥 Commits

Reviewing files that changed from the base of the PR and between 7d5478c and f98f8c5.

📒 Files selected for processing (4)
  • mobile/scripts/mock-server-terminal-stream.ts
  • mobile/src/terminal/terminal-live-composition-mirror.test.ts
  • mobile/src/terminal/terminal-live-composition-mirror.ts
  • mobile/src/terminal/use-terminal-live-pending-input-flush.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • mobile/scripts/mock-server-terminal-stream.ts
  • mobile/src/terminal/use-terminal-live-pending-input-flush.ts

@nwparker

Copy link
Copy Markdown
Contributor

Closing — #7427 is fixed on main by #15007 (66b5993), taking a different route.

Your diagnosis of the symptom was right, and the DEL-repair trace in your PR is what made the failure legible. Where this went differently: adding isTerminalLiveJapanesePreeditCodePoint beside the Hangul table makes it two script allowlists, and the counterexample that settles it is Chinese pinyin — n → ni → niha → nihao → 你好. That preedit is plain ASCII, so no codepoint rule of any kind can tell it from someone typing nihao at a shell. That's now a test.

The fix takes the text system's marked-text/composing range instead and deletes the Hangul ranges outright, so it covers kana, kanji, pinyin and anything else without a table to extend.

One thing worth flagging from reviewing yours: it asserts 語 commits immediately, on the reasoning that kanji only appears after the user picks a candidate. That isn't quite true — candidates stay re-convertible, so that assertion would hold a committed character back.

Thanks for the work. If Japanese still misbehaves on a current build, that's a live bug and worth reopening with a capture.

@nwparker nwparker closed this Aug 17, 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.

4 participants