Skip to content

Fix mobile terminal Korean typing left invisible by the IME deferral model - #7181

Closed
realitsyourman wants to merge 6 commits into
stablyai:mainfrom
realitsyourman:fix/mobile-terminal-hangul-mirror
Closed

realitsyourman wants to merge 6 commits into
stablyai:mainfrom
realitsyourman:fix/mobile-terminal-hangul-mirror

Conversation

@realitsyourman

@realitsyourman realitsyourman commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fix Korean typing on the mobile terminal being completely invisible after Fix mobile terminal Korean IME composition on Android #7011: Hangul was deferred indefinitely (delayMs: null, no settle timer) inside an invisible 1×1 capture field, so nothing reached the PTY while typing and Space never flushed.
  • Replace the deferral model with a mirror model: a pure diff step streams the stable prefix of the capture field to the PTY immediately, holds at most the trailing Hangul code point (Korean composition only ever mutates the last syllable), and commits it via a 300 ms settle timer, Enter/special/accessory flush, or the arrival of a trailing non-Hangul character (Space/punctuation commit composition in Korean IMEs). Premature commits are repaired with \x7f (DEL) corrections.
  • Add an ordered, never-skip send chain for mirror deltas (a skipped delta would desync every later diff), while keeping Fix mobile terminal Korean IME composition on Android #7011's flush barrier and terminal.send acceptance gating for control bytes (\r is still suppressed if the text send is not accepted).
  • Harden the pending-clear effect and the mirror-step guard so a transiently undefined/null active tab type (mobile tab-list lagging the desktop) no longer wipes in-progress composition; explicit non-terminal tab types still clear.

Closes #7183. Follow-up to #7011 (fixes the regression it introduced). ASCII typing remains immediate and unchanged.

Screenshots

  • No visual change; terminal input behavior only.

Testing

  • pnpm lint — mobile-scoped pnpm --dir mobile lint (oxlint) passed for this mobile-only PR; root not run.
  • pnpm typecheck — mobile-scoped pnpm --dir mobile exec tsc --noEmit passed (also proves the session route compiles unchanged — this PR does not touch it).
  • pnpm test — mobile-scoped pnpm --dir mobile test passed: 165 files, 1206 passed, 2 skipped.
  • pnpm build — not run; mobile build requires platform build credentials/devices not available in this environment.
  • Added or updated high-quality tests that would catch regressions: pure mirror-step model (11 cases: single/multi-syllable composition, dubeolsik 간→가나 resplit, timer-commit + DEL correction, Space/ASCII commit, delete-all, non-Hangul IME passthrough), never-skip send chain (runs after failed/throwing predecessor, state reset race), hook-level sent-byte sequences (['하','\x7f','한'], ['한','\r'], ['한 '], acceptance-rejection suppressing \r, unmount timer cleanup), and a re-rendering harness proving a transient undefined tab type preserves composition while 'chat' still clears (real RED/GREEN evidence for both).

Manual device QA checklist (requires a physical Android device with Samsung Keyboard/Gboard Korean IME; not runnable in this environment)

Screenshot_20260703_133159_Orca (1)
  • Korean typing: typing 한글 shows the leading syllable live in the terminal; the trailing syllable appears within ≤300 ms — verified on device (see QA comment)
  • No jamo splitting: isolated jamo such as ㅎ/ㅏ never remain in the terminal — verified on device
  • Space: typing 한글 commits immediately together with the space — verified on device (multi-word sentence)
  • Enter: Enter mid-composition delivers the full text followed by the newline, in order
  • Backspace: while composing and after commit, the field and the terminal echo erase together
  • English/digits: echo immediately (unchanged from before) — verified on device
  • Mixed Korean/English: 한글abc echoes live correctly
  • Japanese/Chinese IME: live mirroring, with DEL corrections on conversion
  • Dictation and paste: pending composed text is committed first when triggered mid-composition
  • Switching terminal tabs and back: mirror state resets, subsequent input works
  • Spot-check the above on an SSH remote terminal

AI Review Report

  • Process: per-commit reviews (spec compliance + code quality) plus a final whole-branch review, with adversarial verification of the implementer's claims against the diffs.
  • Main risks checked: cross-hook async ordering (mirror deltas, explicit flushes, and control-byte barriers all serialize through one flush-promise chain — no out-of-order PTY bytes or double-sends), timer-fired commit racing an explicit flush on the same handle (timer is cleared before every step; no double-send), stale-text timer commits (timer reads refs at fire time and every new step reschedules), submit-path field reset vs late IME onChangeText (mirror state is zeroed before the native clear, so a trailing empty change is a no-op), dictation/paste desync (external sends fully flush + reset the field session first), and preservation of all non-Korean flows (ASCII fast path, special keys on an empty field, Backspace/Delete as local edits so the mirror diff emits the erase without double-erasing).
  • Findings addressed during review: the tab-type guard in the mirror-step runner was hardened to match the pending-clear effect (transient null = unknown, not "left the terminal"; genuine departures remain caught by the handle clauses), the test harness now couples the tab-type ref to the prop so the lag scenario is genuinely exercised, and the send chain's internal await is defensively caught so a future raw rejecting promise cannot silently skip a delta.
  • Cross-platform compatibility was explicitly reviewed for macOS, Linux, and Windows: this PR touches only mobile/src/terminal/* — no desktop shortcuts, shortcut labels, file paths, shell behavior, or Electron accelerators change. The desktop session route is untouched (verified by an empty git diff against main for that file and a clean typecheck).
  • SSH/remote/local compatibility: payloads are plain terminal.send text relying on standard PTY echo (no local-echo assumption); the RPC method, payload shape, and acceptance semantics are unchanged, so local and SSH runtimes behave identically.
  • Known trade-offs (accepted by design, documented for reviewers): the trailing syllable reaches the PTY up to 300 ms after the last keystroke; paused-then-resumed composition emits DEL corrections (rarer than the pre-Fix mobile terminal Korean IME composition on Android #7011 behavior of sending every intermediate); backspacing into a held syllable after a prefix commit briefly blinks the boundary syllable; a rejected mirror delta mid-typing can desync the echo until the next flush resets state (\r stays acceptance-gated, so a desynced line is never silently submitted); Japanese/Chinese IME now mirrors live with corrections instead of the previous 150 ms quiet settle.

Security Audit

  • No new dependencies, native modules, credential handling, network endpoints, auth surfaces, command execution paths, file path handling, or IPC methods. package.json/lockfiles untouched.
  • terminal.send RPC method and payload shape unchanged; the byte-limit guard (isTerminalLiveInputWithinByteLimit) and the send.accepted === true acceptance check are preserved. Mirror payloads consist only of user keystrokes plus \x7f erase bytes.
  • Control bytes remain gated on accepted text sends, so a failed send cannot be followed by a stray Enter.
  • No secrets or tokens added.

Notes

  • The mirror model's real risk surface (IME-specific onChangeText timing, DEL handling by specific shells/TUIs) is not reachable from the vitest harness — the manual QA checklist above should be run on a physical Galaxy device before release.
  • queueTerminalLivePendingFlush in terminal-live-pending-flush-state.ts is now unreferenced by production code (the hooks migrated to the never-skip chain). Left in place per repo guidance against removing pre-existing code beyond the change's scope; can be removed in a follow-up if maintainers prefer.
  • Physical-device manual QA remains unavailable in this environment; automated model/hook/suite coverage is recorded above.

@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 446b2edb-95ab-49b5-b92e-e429516be4b1

📥 Commits

Reviewing files that changed from the base of the PR and between b69ebda99addc4068bdcf0e7dcb315e24e3a83d7 and 137978e.

📒 Files selected for processing (11)
  • mobile/src/terminal/terminal-live-hangul-mirror.test.ts
  • mobile/src/terminal/terminal-live-hangul-mirror.ts
  • mobile/src/terminal/terminal-live-pending-flush-state.test.ts
  • mobile/src/terminal/terminal-live-pending-flush-state.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
📝 Walkthrough

Walkthrough

This PR replaces the previous pending-text/scheduled-commit model for terminal live input mirroring with a held-text/sent-text mirror model. It adds a new Hangul mirror computation utility (terminal-live-hangul-mirror.ts) to detect Hangul code points and compute minimal erase/append PTY updates, holding trailing syllables until committed. A new queueTerminalLiveMirrorSend helper serializes mirror payload sends even after failures. Decision helpers in terminal-live-text-commit.ts are updated to base special-key and accessory-byte decisions on held/sent text rather than pending text, replacing the flush-then-send variant with commit-held-then-send. The useTerminalLivePendingInputFlush, useTerminalLiveInputCommit, and useTerminalLiveAccessoryInputCommit hooks are rewired accordingly, with tab-type-aware pending-state clearing and simplified submit handling. Extensive tests are added/updated to cover the new behaviors.

Related PRs: None identified from the provided information.

Suggested labels: area/terminal, mobile

Suggested reviewers: Reviewers familiar with the mobile terminal live-input subsystem should review this change given its high complexity in core commit/mirror hooks.

🐰 A syllable held, then let it go,
DEL by DEL, corrections flow,
No more waiting, no more delay,
Held and sent text lead the way,
Hangul mirrors, byte by byte, hop hop hooray!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main mobile terminal Hangul IME fix and matches the changeset.
Description check ✅ Passed All required template sections are present and filled with relevant details, including testing, AI review, security, and notes.

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 (2)
mobile/src/terminal/use-terminal-live-pending-input-flush.ts (1)

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

Use useEffectEvent here instead of writing the callback ref during render.

runMirrorStepRef.current = runMirrorStep mutates a ref in the render path. Since this hook is already on React 19.2+, useEffectEvent is the cleaner way to keep the timeout callback on the latest runMirrorStep without a render-time mutation.

mobile/src/terminal/terminal-live-text-commit.ts (1)

69-82: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Confirm intent: accessory Delete is fully swallowed (no PTY bytes) whenever any text is held/sent.

getTerminalLiveAccessoryLocalEditText's delete branch returns fieldText unchanged, so when routed through the accessory hook's local-edit handling, applyLiveInputMirror computes a zero-length diff and nothing is sent to the PTY at all. This is documented as intentional (forward-delete has nothing "after" cursor in this field's own model), but the real shell's cursor position is independent of this hidden field (e.g., after arrow-key navigation), so a forward-delete could legitimately need to reach the PTY even during active composition. There's also no test exercising localEdit: 'delete' combined with non-empty heldText/sentText.

Worth confirming this is the desired behavior (vs. forwarding the raw delete byte), and adding a regression test either way.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7943bbaf-3b6c-486a-9faa-615a14db0e8c

📥 Commits

Reviewing files that changed from the base of the PR and between 0ea354d and b69ebda99addc4068bdcf0e7dcb315e24e3a83d7.

📒 Files selected for processing (11)
  • mobile/src/terminal/terminal-live-hangul-mirror.test.ts
  • mobile/src/terminal/terminal-live-hangul-mirror.ts
  • mobile/src/terminal/terminal-live-pending-flush-state.test.ts
  • mobile/src/terminal/terminal-live-pending-flush-state.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

@realitsyourman

Copy link
Copy Markdown
Contributor Author

Device QA update — verified on a physical Galaxy Z Fold7 (SM-F966N) with Samsung Keyboard Korean IME, running the release APK built from this branch (b69ebda99):

Author reports overall Korean typing now works correctly on device. Checklist items for Enter ordering, Backspace sync, dictation/paste, tab-switch, non-Hangul IME, and SSH remain to be ticked individually. Screenshot will be attached in the conversation.

@AmethystLiang
AmethystLiang requested a review from Jinwoo-H July 3, 2026 08:47
realitsyourman and others added 6 commits July 3, 2026 13:24
탭 상태 지연으로 활성 탭 타입이 일시적으로 null이 될 때 runMirrorStep의 stale-handle 가드가 조합 중 음절을 버리지 않도록 pending-clear 효과와 동일한 null 허용 패턴 적용. 테스트 하네스가 ref와 prop을 동일 소스에서 파생하도록 결합해 실제 경로의 lag 프레임을 검증. queueTerminalLiveMirrorSend의 previousSend await를 catch로 보호.
… the mirror model

The mirror model migrated all live-input sends to queueTerminalLiveMirrorSend,
leaving queueTerminalLivePendingFlush referenced only by its own tests. Remove
the dead function and its three tests.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the fix/mobile-terminal-hangul-mirror branch from b69ebda to 137978e Compare July 3, 2026 20:27
@nwparker

nwparker commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Maintainer takeover — reviewed, trimmed, rebased, verified

I've taken ownership of this PR, audited it line-by-line (with extra scrutiny given the large diff), trimmed dead code, rebased onto latest main, and re-verified. Summary below.

Description

The regression is real and severe. Confirmed directly in the #7011 base code: getTerminalLiveTextChangeDecision returns { kind: 'defer', delayMs: null } for any text containing Hangul, and schedulePendingLiveInputCommit schedules no timer when delayMs === null. Because the whole field value is scanned, '한글 ' (with a trailing space) still counts as Hangul and re-defers forever. Net effect: Korean is invisible while typing and only Enter flushes it — exactly as the issue reports.

The fix (kept): replace the indefinite deferral with a mirror model (terminal-live-hangul-mirror.ts). A pure diff step streams the stable prefix of the capture field to the PTY immediately and holds only the trailing Hangul code point (Korean composition only ever mutates the last syllable). The held syllable commits on a 300 ms settle timer, on Enter/special/accessory flush, or when a trailing non-Hangul char (Space/punctuation/ASCII) arrives. Premature commits are repaired with \x7f (DEL). Mirror deltas go through an ordered, never-skip send chain so a skipped delta can't desync later diffs, while #7011's control-byte acceptance gating is preserved. ASCII stays immediate and unchanged.

Scope verdict — the diff is justified. The headline number looks alarming, but the production surface is a net-neutral swap, not additive bloat:

additions deletions
Production +247 −249 (net −2 lines)
Tests +633 −289
Total 880 538

Every one of the 11 files is under mobile/src/terminal/ on the live-input commit path — no unrelated refactors, no desktop/session-route changes, no deps. The bulk is test coverage. A naive "just add a settle timer to Hangul" fix would be smaller but would reintroduce the #7000 jamo-leak (the exact reason #7011 chose delayMs: null), and clearing the field mid-composition breaks mobile IMEs — the diff-against-what-was-sent mirror model is what makes live echo possible without either failure. So I kept the model and did not rewrite it.

What I changed on takeover:

  • Trimmed dead code: removed queueTerminalLivePendingFlush and its 3 tests — orphaned by this PR's migration to queueTerminalLiveMirrorSend, referenced only by its own tests. (This is the item the author flagged as removable; there is no repo rule against removing code a change orphans, so it's gone. −31 net lines vs the original 911/469.)
  • Rebased the 5 author commits onto latest main (was 39 behind). Clean, no conflicts. Verified the hook's public options/return interface is byte-identical to base, so main's updated session route (which changed +80/−69 but still calls with the same shape and passes activeSessionTabType: activeSessionTab?.type, i.e. possibly undefined — the exact lag case this PR hardens) integrates without a type regression.

Evidence

RED (regression reproduced on the real #7011 base code): materialized the base terminal-live-text-commit.ts and asserted the root cause — getTerminalLiveTextChangeDecision('한글'), '한글 ', and '한글abc' all return defer / delayMs: null (no settle timer → never flushed → invisible), while 'abc' sends immediately. 4/4 pass, proving the buggy state. (Throwaway repro, not committed.)

GREEN (fix + hardening): the hook-level suite drives the exact issue scenarios and asserts the sent-byte sequences:

  • Typing ㅎ→하→한→한ㄱ→한그→한글 → PTY receives ['한'] (stable prefix streamed, trailing syllable held; no jamo leak).
  • 한 then 한 → ['한 '] (Space commits the held syllable — the "space re-defers forever" bug is gone).
  • Timer commit then continued composition 하→한 → ['하', '\x7f', '한'] (DEL correction).
  • Enter on held 한 → ['한', '\r']; rejected send suppresses the \r.
  • Tab type lags to undefined → composition preserved; genuine 'chat' tab → cleared (the compounding-factor fix, with real RED/GREEN in the harness).

Commands (all clean, post-rebase):

  • pnpm --dir mobile lint (oxlint) — clean.
  • pnpm --dir mobile test src/terminal/ — 310 passed / 25 files.
  • Touched-file suites — 50 passed (was 53; −3 dead tests removed).

Per the OOM guard I did not run a full repo typecheck; I verified integration by interface analysis (option + return field sets unchanged) instead.

ELI5

Your phone keyboard builds a Korean letter one piece at a time (ㅎ → 하 → 한). The old code was scared of showing half-built letters, so it hid everything until you pressed Enter — which meant you couldn't see what you were typing at all, and pressing Space never helped. The new code is smarter: it shows every letter that's already finished right away, and only holds the one letter you're still building for a heartbeat (300 ms) before showing it too. If it guesses wrong, it quietly backspaces and fixes it. So Korean now appears as you type, just like English.

Trade-offs / limitations

  • Mobile-only verification limitation (important for the reviewer): Korean IME on the mobile terminal cannot be exercised on desktop Electron, so this was verified via source review + unit/hook tests, not on a device. A mobile reviewer should confirm on a physical Android device with Samsung Keyboard/Gboard Korean IME: (1) 한글 echoes live with the trailing syllable within ~300 ms; (2) no isolated jamo (ㅎ/ㅏ) linger; (3) 한글 commits with the space; (4) Enter mid-composition delivers text then newline (note Samsung's first-Enter-only-commits quirk); (5) Backspace erases field + echo together; (6) mixed 한글abc; (7) spot-check on an SSH remote terminal and with dictation/paste mid-composition.
  • 300 ms tail: the final syllable reaches the PTY up to 300 ms after the last keystroke.
  • DEL corrections: paused-then-resumed composition emits \x7f corrections. One DEL erases one code point; erasing a wide CJK cell relies on the shell/TUI line editor (readline/cooked mode handle this; some raw-mode TUIs may differ) — acceptable and rare.
  • Rejected mid-typing delta can desync the echo until the next flush resets state, but \r stays acceptance-gated so a desynced line is never silently submitted.
  • No behavior change for ASCII or non-Korean flows (Chinese/Vietnamese now mirror live with corrections instead of a 150 ms quiet settle — covered by tests).

Head after takeover: 137978ef12 (rebased onto main, force-pushed with lease). Not merged — leaving the merge decision to maintainers pending the device QA above.

@Jinwoo-H

Jinwoo-H commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Closing this as superseded by #7273, which has now been merged.

#7273 carries forward the Korean IME mirror-model fix from this PR, preserves the device-verified behavior for #7183, and adds the missing live-input keyboard affordance/refocus fix we found during follow-up testing:

  • visible/tappable "Tap to show keyboard" live input target
  • Android blur/refocus path for reopening the keyboard after the IME is dismissed
  • full mobile test/lint/format/typecheck validation
  • Android debug build/install/open on SM_S921W / R3CX105QXRH

Merged via #7273: e8c2b79

Thanks for the original Korean IME work here; it is included in the merged PR.

@Jinwoo-H Jinwoo-H closed this Jul 3, 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]: Mobile terminal Korean IME input is completely invisible after the #7011 deferral model

3 participants