Repository navigation
fix(terminal): stop reading a modifier-held IME keydown as Enter, and defer every IME-owned key - #11273
fix(terminal): stop reading a modifier-held IME keydown as Enter, and defer every IME-owned key#11273kunsanglee wants to merge 8 commits into
Conversation
A macOS IME delivers one Shift+Enter pressed mid-composition as two keydowns: a committing press that ends the composition, then the real press. Both satisfy the terminal shortcut rules, so the shortcut fired twice, and because xterm only queues the committed glyph on a setTimeout(0) taken at compositionend, both line breaks reached the PTY ahead of it. Typing 안녕 and pressing Shift+Enter while 녕 was still composing put 녕 after the line break. The lower IME guard already covers this, but the shortcut layer runs at window capture and calls stopImmediatePropagation, so neither that guard nor xterm's own synchronous composition flush ever sees the keydown. Track composition state at the shortcut layer, leave keys the IME owns during a live composition alone — reusing the key set the xterm bypass policy already defines — and order the follow-up press's direct PTY write behind the flush compositionend queued. The write is wrapped once around the whole sendInput branch, so Ctrl+Backspace, Cmd+Delete and the Option+Arrow rules are covered without per-chord handling. Composition state comes from the layer's own listeners rather than the keyCode 229 marker: an IME reports 229 outside any composition too, and claiming those would drop the shortcut with no second press to redo it.
📝 WalkthroughWalkthroughAdds an IME shortcut guard that tracks composition lifecycle, classifies keydowns, and defers post-composition PTY writes when needed. Terminal keyboard handling now skips IME-owned events, preserves ordered shortcut dispatch, and disposes the guard during cleanup. New tests cover classification, disposal, write timing, and Shift+Enter composition ordering. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/terminal-ime-shortcut-guard.ts (1)
4-10: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTrim the multi-line "Why" comments per repo comment guideline.
Several blocks here (module header, the capture-options note, the 229-marker note, and the setTimeout-vs-microtask note) are 4-7 lines explaining implementation rationale. As per coding guidelines,
**/*.{ts,tsx,js,jsx}: "Comments must be concise, limited to non-obvious information, and preferably one line; do not explain obvious code or walk through implementation details." Consider condensing each to a single sentence and moving the deeper rationale into the PR description or a linked doc if it needs to be preserved.Also applies to: 41-44, 50-54, 81-86
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e15a354e-452b-441b-8da4-651c2269fcbf
📒 Files selected for processing (5)
src/renderer/src/components/terminal-pane/keyboard-handlers.tssrc/renderer/src/components/terminal-pane/terminal-ime-shift-enter-composition-order.test.tssrc/renderer/src/components/terminal-pane/terminal-ime-shortcut-guard.test.tssrc/renderer/src/components/terminal-pane/terminal-ime-shortcut-guard.tssrc/renderer/src/components/terminal-pane/xterm-bypass-policy.ts
Greptile SummaryThis PR fixes two related IME keydown bugs in the terminal pane. First, it corrects
Confidence Score: 5/5Safe to merge. The changes are renderer-only, touch no IPC or native modules, and can only reduce or reorder bytes written to the PTY — they cannot introduce, synthesize, or duplicate writes beyond what was already happening. Both fixes are narrowly scoped and each has a new test that fails without the guard it covers. The code-field check in isTerminalImeProcessEnter is provably correct against the existing observed-event fixtures. The modifiedEnterChord narrowing to Enter-only is verified by the Ctrl+Backspace/Ctrl+Enter ordering test, which would silently drop the Ctrl+Enter without the guard. The deferral widening is gated on TERMINAL_IME_OWNED_KEYS, a set already used by the suppression layer. No cross-file or cross-platform side-effects were found in the changed paths. Files Needing Attention: No files require special attention. The only acknowledged limitation — Windows re-dispatch drift still doubles non-Enter IME-owned keys — is pre-existing and explicitly documented in the PR notes.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts | Adds code-field guard to isTerminalImeProcessEnter (rejects non-Enter physical codes while keeping blank/Unidentified codes accepted) and exports new isTerminalImeRedispatchableKey predicate that gates absorption on TERMINAL_IME_OWNED_KEYS with keyCode!=229. |
| src/renderer/src/components/terminal-pane/keyboard-handlers.ts | Narrows modifiedEnterChord computation to Enter-only (prevents Backspace from claiming the chord owner slot), widens deferral condition from Enter to all TERMINAL_IME_OWNED_KEYS, and guards absorbRedispatchedEnter with isTerminalImeRedispatchableKey. |
| src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts | Single-line change: exports TERMINAL_IME_OWNED_KEYS so terminal-ime-deferred-newline.ts and keyboard-handlers.ts can share the set without restating it. |
| src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx | Harness now captures both PTY write paths (composition route and shortcut layer) into one ordered array; adds 4 new test cases: shifted-jamo rejection, Enter-slot protection for a Ctrl+Backspace/Ctrl+Enter sequence, Ctrl+Backspace deferral, and Ctrl+Backspace straight-through outside composition. |
| src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts | isTerminalImeProcessEnter fixture gains the code field; adds NumpadEnter/blank/Unidentified acceptance cases and KeyQ/ArrowLeft rejection cases. New isTerminalImeRedispatchableKey describe block covers the keyCode!=229 guard and non-owned key rejection. |
Reviews (5): Last reviewed commit: "test(terminal): pin a Japanese conversio..." | Re-trigger Greptile
Greptile: a compositionstart with no keydown between it and the previous compositionend left the mark set, so the next shortcut write was deferred behind a flush that had already run. Clearing it on start makes the state machine self-consistent, and the new test fails without the reset. Dispose the guard the integration test creates, and condense the four rationale comments per the repo's one-line comment guideline while keeping the facts that a later cleanup would otherwise undo.
main landed stablyai#11293, which fixes the committing-Enter double dispatch this branch targeted, and does it more carefully: it waits for the terminal's real compositionend and the xterm session-end event with a 200ms fallback, where this branch used a bare setTimeout(0) after seeing a compositionend. So the branch's own terminal-ime-shortcut-guard is dropped rather than merged alongside — keeping it would have preempted main's deferral from the top of onKeyDown and replaced it with the weaker ordering. The one thing it covered that main does not, deferring every IME-owned key instead of Enter alone, follows in the next commit on top of main's machinery. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01EnMabSU7QxCeHwtropbTUq
main's deferral only covers Enter, but the committing press repeats and the direct shortcut write races xterm's flush for every key the IME consumes mid-composition. Ctrl+Backspace (\x17), Cmd+Backspace (\x15), Cmd+Delete (\x0b) and the Alt/Ctrl+Arrow word motions all doubled and landed ahead of the syllable they committed. Widens the two Enter-shaped conditions to TERMINAL_IME_OWNED_KEYS, reusing the set xterm-bypass-policy already defines. The Windows Enter-chord owner stays Enter-only on purpose: getModifiedEnterChord keys off the held modifier alone, so claiming its single slot on a non-Enter key would block the real chord. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01EnMabSU7QxCeHwtropbTUq
…ing Enter Windows reports every IME-consumed keydown as key 'Process' with keyCode 229, so isTerminalImeProcessEnter also matched a shifted jamo (ㅃ, ㄲ, ㅆ) typed mid-composition. keyboard-handlers then rewrote that keydown to key: 'Enter', the Shift+Enter rule matched, and \x1b\r reached the PTY right behind the committed syllable. Only `code` separates the two shapes, and the predicate never read it. The repo's own fixtures already record both: the committing press as Process/Enter/229, and an observed IBus jamo keydown as Process/KeyG/229.
…rejection stablyai#11293 records the Windows Process sequence arriving with a blank `code` (see "owns one Windows Process sequence across changing timestamps and blank codes"), so requiring code Enter/NumpadEnter would have dropped a real committing Enter on that path. An undeterminable code now keeps its previous verdict; only a known non-Enter physical code, which is what a shifted jamo carries, is refused. Also pins the two guards this branch relies on and had left untested: the Windows chord slot stays free for a Ctrl+Enter behind a deferred Ctrl+Backspace, and the composition marker is never read as its own re-dispatch. Both were verified to fail without the guard they cover.
…er predicate Shift+Left/Right resizing the conversion segment is a standard Japanese IME operation, and on Windows it arrives mid-composition as Process/229 with Shift held — the same shape as a shifted jamo, and the same rewrite into Enter. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HL8CxXZYghUKJEQpYhKeGg
# Conflicts: # src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx # src/renderer/src/components/terminal-pane/keyboard-handlers.ts # src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts # src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts
|
Thank you for tackling this difficult IME/terminal-input edge case. We reproduced the behavior on a native Windows 2 host in headed Orca using Microsoft Japanese IME through the real renderer → native daemon → OpenConsole/ConPTY → PowerShell topology. The current base, published head Because neither the PR nor the bounded strict correction can distinguish IME-owned composition from genuine terminal input safely, this cannot land without risking either duplicate input or lost user commands. A reopenable direction would add delayed, authoritative IME ownership with bounded cleanup, then pass the same native Japanese matrix plus a physical Korean-layout control for blank-code navigation/editing and genuine Ctrl+Enter. We appreciate the contribution and the useful starting point; closing this version because the native evidence is decisive, not because the problem lacks value. |
Adapted from stablyai#11273 commits c690ee6, 5065240, and cc69fa7.
Summary
mainclassifies IME keydowns as Enter incorrectly in both directions, and this PR fixes both. Three commits, separable.1. A modifier-held IME keydown is read as the committing Enter
On Windows, typing ㅃ, ㄲ, ㄸ, ㅆ, ㅒ or ㅖ mid-composition sends a Shift+Enter newline to the shell. Ordinary Korean typing injects
\x1b\r, which at a shell prompt submits whatever line is pending.This is not Korean-specific. Nothing on the path reads a character —
TERMINAL_IME_OWNED_KEYSholds physical key names,getTerminalImeModifiedEnterKindreads modifiers alone, and the predicate never looks at a character value. The condition is any keydown Windows consumes for an IME while a composition is open with exactly one of Shift or Ctrl held. Resizing the conversion segment with Shift+Left/Right is a standard Japanese IME operation and produces the identical event, so it lands on the identical rewrite — and unlike a shifted jamo it is pressed repeatedly on purpose.isTerminalImeProcessEnterrecognizes the Windows committing Enter bykey === 'Process',keyCode === 229, and exactly one of Shift or Ctrl. It never readscode. But Windows reports every IME-consumed keydown asProcess/229, so a jamo typed with Shift held satisfies all three conditions.keyboard-handlers.tsthen rewrites that keydown into{ key: 'Enter', ... },terminal-shortcut-policy.tsmatches its Shift+Enter rule onevent.key === 'Enter', and the byte is deferred and written to the PTY behind the committed syllable.codeis the field that separates the two shapes, and this repo already records the jamo side:tests/e2e/terminal-ime-observed-event-sequences.ts:44replays an observed IBus Hangul jamo keydown askeydown('Process', 'KeyG', 229, true), physical code preserved.It does not always record
Enteron the other side. #11293's own chord-owner test —owns one Windows Process sequence across changing timestamps and blank codes— sends the Windows Process sequence withcode: ''and only putscode: 'Enter'on the re-dispatch. So the predicate refuses a known non-Enter physical code and keeps its previous verdict whenever the code is absent or'Unidentified'. A shifted jamo is rejected; a blank-code committing Enter is not. The predicate cannot lose a keystrokemaindelivers today.2. Only Enter is deferred, but every IME-owned key doubles
This is what the PR was originally opened for, rewritten on top of
main.#11293 landed the cross-platform IME composition lifecycle work, and its e2e spec
tests/e2e/korean-ime-terminal-shift-enter-commit.spec.tsreproduces the same macOS double dispatch this branch first measured: the committing Enter askeyCode 229 / isComposing=true, then the re-dispatch askeyCode 13 / isComposing=falseabout 2 ms later. Its deferral is stricter than what this branch originally had —sendTerminalInputAfterCompositionwaits for the terminal element's realcompositionendand for xterm's composition-session-end event, with a 200 ms fallback, where this branch scheduled a baresetTimeout(0).So this PR no longer adds a second guard.
terminal-ime-shortcut-guard.tsand its two tests are deleted rather than merged alongsidemain's mechanism. Keeping both would have been a regression: the guard sat at the top ofonKeyDownand returned early on the committing press, sodeferredNewlineSender.defernever ran and the weaker ordering took its place.What remains is the one thing
maindoes not cover.maindefers Enter alone, but the committing press repeats and the direct shortcut write races xterm's flush for every key the IME consumes mid-composition.Ctrl+Backspace(\x17),Cmd+Backspace(\x15),Cmd+Delete(\x0b) and the Alt/Ctrl+Arrow word motions double and land ahead of the syllable they commit, exactly as Enter did. This widensmain's two Enter-shaped conditions toTERMINAL_IME_OWNED_KEYS, the setxterm-bypass-policy.tsalready defines, and exports that set for reuse instead of restating it.The Windows Enter-chord owner stays Enter-only on purpose.
getModifiedEnterChordkeys off the held modifier alone and never checks the key, so claiming its single slot on a non-Enter key would take ownership away from the real chord. Removing that one narrowing makes aCtrl+Enterbehind a deferredCtrl+Backspacedisappear — measured, and now pinned by a test.The two halves meet in one place. With the narrowed predicate a shifted jamo no longer sets
imeProcessEnter, so the widened deferral condition falls through toTERMINAL_IME_OWNED_KEYS.has('Process'), which is false, and the keydown takes the ordinary path.Net effect: the original 329 lines across 5 files became 208 across 5, with no new module.
Screenshots
No visual change. No layout, token, component, or styling change, so
docs/STYLEGUIDE.mddoes not apply. The user-visible effect is the order and count of bytes reaching the shell.Testing
pnpm lintpnpm typecheckpnpm testpnpm build— not run, see belowpnpmis not installed on this machine, so the gates ran through the underlying binaries innode_modules/.binrather than through thepnpm runwrappers.oxlintexits 0 repo-wide.oxlint --config config/oxlint-code-quality-native-plugins.json src/renderer/src/components/terminal-pane --deny-warningsand the same directory under--type-aware --config config/oxlint-code-quality-type-aware.json --deny-warningsboth exit 0.check:max-lines-ratchetreports no new bypasses (nomax-linesdisable was added; the one at the top ofkeyboard-handlers.tspredates this branch).check:reliability-gatespasses for 55 gates.check:changed-code-qualityshells out topnpm exec oxlintand dies onspawnSync pnpm ENOENT, so its scans were run directly as listed.tsconfig.node.json,tsconfig.tc.cli.json, andtsconfig.tc.web.json.src/renderer/src/components/terminal-paneis 214 files / 2,840 tests; 210 files pass. The four that fail —terminal-ime-xterm-adversarial,terminal-ime-xterm-transaction-events,terminal-ime-xterm-composition-deduplication,terminal-ime-won-composition-order, 59 tests — assert against the installed patched@xterm/xterm, and fix(terminal): reconcile cross-platform IME composition lifecycle #11293 rewroteconfig/patches/@[email protected]. The repo's patch expects post-image bloba85075dcbea89c342500838a66b40f2ff6c21c0f; the installedlib/xterm.jshashes toeecf435886d866a838430b9f81f713deed3eb8c1. A cleanmaincheckout sharing the samenode_modulesreproduces the identical 4 files / 59 failures, so this is a stale local install that a freshpnpm installclears, not a regression. None of those four files import anything this PR touches.pnpm run build:*, unavailable here for the reason above. CI covers it.keyboard-handlers-ime.test.tsxis the only test in the repo that mountsuseTerminalKeyboardShortcuts, so the behavior is pinned against the real handler rather than a replayed control flow. Its harness now records both PTY writers — the composition route's committed glyph and the shortcut layer's directsendInput— into one ordered array, so the assertions are on byte order, not on a predicate.does not read a shifted jamo as the committing Enter→ asserts['ㅃ']. Without thecodecheck it readsexpected [ 'ㅃ', '\x1b\r' ] to deeply equal [ 'ㅃ' ], the bug's exact byte in its exact position.leaves the Enter chord slot free for a Ctrl+Enter behind a deferred Ctrl+Backspace→ asserts['녕', '\x17', '\x1b[13;5u']. Without the Windows narrowing it readsexpected [ '녕', '\x17' ]: the Ctrl+Enter is silently lost. This is the risk the widening itself creates, and it had no coverage before.sends one Ctrl+Backspace, behind the syllable it committed→ asserts['녕', '\x17']plusdefaultPreventedon the re-dispatch.sends Ctrl+Backspace straight through outside a compositionis the negative control that keeps the deferral from spreading to ordinary presses.terminal-ime-deferred-newline.test.tsrejectscode: 'ArrowLeft'alongsidecode: 'KeyQ'in the predicate fixtures, so the Japanese conversion-segment case is pinned by name and not only by the Korean one.terminal-ime-deferred-newline.test.ts— theisTerminalImeProcessEnterfixture gains thecodefield it was missing, acceptsNumpadEnterand the undeterminable''/'Unidentified', and rejectsKeyQ.isTerminalImeRedispatchableKeygains the unit block it was missing, covering the 229 composition marker it must not mistake for a re-dispatch.AI Review Report
Reviewed with Claude Code across four independent axes run without sight of each other or of my own conclusions: simplicity, impact radius, adversarial compatibility, and test quality. What they changed:
code === 'Enter' || 'NumpadEnter'. The compatibility pass measured that acode: ''committing Enter is then dropped whenever the commit precedes the balancing keyup (the keyup fallback atkeyboard-handlers.ts:765-802requires a still-pending composition, so it only rescues the other ordering). The test pass found the corroborating fixture: fix(terminal): reconcile cross-platform IME composition lifecycle #11293's own chord-owner test is named for blank codes and sends them. The predicate now treats an undeterminable code as "cannot tell" and keepsmain's verdict.isWindows && (e.key === 'Enter' || imeProcessEnter)narrowing broke nothing in the suite, yet loses a realCtrl+Enter. That case is now pinned by bytes.isTerminalImeRedispatchableKeyhad no unit block. ItskeyCode !== 229clause is not new defense:main's condition wase.key === 'Enter' && e.keyCode === 13 && !e.isComposing, so the keyCode test is the part being generalized to a key set, not something added. It is now covered directly.isRedispatchedEnterlocal was folded into the chord ternary, which restoresmain'sifshape; the comment above it dropped a key list thatTERMINAL_IME_OWNED_KEYSalready states; two duplicate test rows that exercised the same branch were collapsed.isWindows; macOS delivers the jamo inkeyrather than as the literalProcess(seedispatchHangulProcessKeyin the Korean IME e2e), sokey === 'Process'was already false there. Linux IBus does reportProcess/229 for jamo per the observed-sequence fixture and was protected only by thatisWindowsgate — this change makes the predicate itself correct rather than leaning on the gate. The absorb path the widening touches is platform-independent, keyed on(code, timeStamp); the modifier-kind path is Windows-only.TERMINAL_IME_OWNED_KEYSis the same set everywhere. No shortcut label, menu accelerator, or path handling is touched.isTerminalImeProcessEnteris the only symbol whose signature changed and it has one production caller. Everything the PR touches is renderer-only; no main-process, preload, relay, CLI, or native-module counterpart is needed. The mobile package keeps its own key table and does not import this set.deferredNewlineSender,hasPendingTerminalImeCompositionandcreateCapturedInputSenderare used as they already exist, and the key set is imported rather than restated. The only addition is one predicate, placed next to the module's existing IME predicates.Set.hasper keydown on a 12-element set, plus a few string comparisons short-circuited behindkey === 'Process'. Without a pending composition nothing defers, sotests/e2e/terminal-typing-latency.spec.tsis unaffected.Security Audit
key,codeandkeyCodeoff keyboard events the renderer already handles. No parsing, no deserialization, no new trust boundary.terminal-shortcut-policy.tsalready produced; this change decides only when they are written and whether a spurious or duplicate one is dropped, never what.(code, timeStamp)and cannot queue faster than the user types.Notes
Known limitations, all measured during review and none of them regressions against
main:timeStampby comparing the modifier kind alone;absorbRedispatchedEnterrequires an exact(code, timeStamp)match. On the Windows path this repo models withredispatchTimestampOffset: 0.01, a deferredCtrl+Backspacetherefore still goes out twice.mainalso sent it twice, in the worse order (\x17, \x17, 녕becomes녕, \x17, \x17), so this PR improves the ordering without closing the duplication. Closing it needs the chord owner generalized beyond one Enter slot, which is a larger change than this PR should carry.createCapturedInputSenderrefuses to write once the pty id changes, so an SSH or relay reconnect during a composition discards the shortcut byte. That refusal is deliberate — writing a stray\x17into a freshly reconnected shell is worse than dropping it — but the window is new for these keys, since they previously went out synchronously.mainestablishes that Chromium re-dispatches the committing press with the same nativecodeandtimeStamp, and its real-IME e2e validates that for Enter. This PR assumes the same holds for the other IME-owned keys; the unit tests encode that assumption rather than prove it. Extendingtests/e2e/korean-ime-terminal-shift-enter-commit.spec.tswith aCtrl+Backspacecase would settle it, andinstallImeKeyEventLogthere already records thecodeof every keydown.mainand watch the prompt submit.deferredNewlineSender.absorbRedispatchedEnteris now called forBackspaceand the arrows, so its name is narrower than its behavior, as arereleaseRedispatchedEnter,clearRedispatchedEntersandTerminalImeEnterIdentity. Renaming is mechanical and type-checked but churnsterminal-ime-deferred-newline.test.ts, which fix(terminal): reconcile cross-platform IME composition lifecycle #11293 landed recently, so it was left out of a PR whose point is to shrink.pnpm installto pick up fix(terminal): reconcile cross-platform IME composition lifecycle #11293's rewritten xterm patch. Nothing in this PR changes that.X (Twitter): @kunsanglee
🤖 Generated with Claude Code