Repository navigation
fix(terminal): reconcile cross-platform IME composition lifecycle - #11293
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds terminal IME composition-session routing, deferred newline handling, modified-Enter processing, and PTY-safe captured-input dispatch. Expands xterm and browser E2E coverage with IME event probes, byte readers, observed event sequences, exact-byte scenarios, and macOS-style Enter tests. Adds native IBus Hangul tests with isolated X11 lifecycle management and evidence capture. Adds a GitHub Actions workflow, package script, and workflow validation test. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
Greptile SummaryThis PR reconciles three overlapping IME fixes (#11011, #11052, #11177) into a single unified branch, addressing Korean/IBus composition lifecycle, IME Enter and newline ordering, and Korean ₩/backtick native-text routing. The integration resolves ownership-model conflicts exposed by combined, native, and adversarial testing.
Confidence Score: 5/5Safe to merge; all findings are edge-case defensive improvements rather than regressions on any tested path. The change is backed by an unusually extensive validation suite (2,791 unit tests, 233 combined IME scenarios, 60 native IBus sequences, and 27 adversarial cases), and the code correctly disposes all listeners, timers, and session state across blur, reconnect, and pane lifecycle events. The one structural concern — Files Needing Attention:
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/terminal-pane/terminal-ime-composition-route.ts | New module owning xterm composition-session events per transport; event.preventDefault() is called before the session-lookup, which can silently drop composition data for sessions started before the route was installed. |
| src/renderer/src/components/terminal-pane/keyboard-handlers.ts | Major refactor: modifiers tracked via Set, onModifierUp merged into onKeyUp, modifier-Enter chord ownership wired through new IME primitives. Logic is complex but consistent with the documented design. |
| src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts | New module for deferred Enter dispatch after composition ends; state keyed by (code, timeStamp), with 200 ms fallback timer. Side-effect of clearCreditsForCode on failed absorb already noted in previous review thread. |
| src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.ts | Adds compositionTransactionPending boolean flag gated on accepted/settled custom events; suppresses insertText input events during an active xterm composition transaction. |
| src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts | New helper that validates transport identity (captured vs current PTY ID) before dispatching input; straightforward and correct. |
| src/renderer/src/components/terminal-pane/pty-connection.ts | Integrates the new composition route: installed at connection time, disposed in the cleanup path. |
| src/renderer/src/components/terminal-pane/terminal-ime-native-text-candidates.ts | Adds ₩ to CJK_DIRECT_PUNCTUATION_KEYS so macOS DefaultKeyBinding.dict remaps can emit backtick instead. |
| config/patches/@[email protected] | Large minified-bundle patch; adds XTERM_COMPOSITION_SESSION_START/END custom events that the new composition route depends on. Previously flagged as unauditable — no change to that concern. |
| .github/workflows/terminal-ime-e2e.yml | New CI workflow running Linux X11 IBus Hangul exact-byte E2E tests on PR and daily schedule; structure is correct. |
| test-results/pr-11293-11177-integration-r1.md | Integration audit logs committed as permanent repo artifacts; not a bug but adds permanent history noise. |
Sequence Diagram
sequenceDiagram
participant User
participant Chromium
participant KeyboardHandlers as keyboard-handlers.ts
participant DeferredNewline as IME deferred-newline
participant ChordOwner as ModifiedEnterChordOwner
participant CompRoute as composition-route.ts
participant xterm
participant PTY
User->>Chromium: Shift down (modifier)
Chromium->>KeyboardHandlers: keydown(Shift)
KeyboardHandlers->>KeyboardHandlers: heldImeEnterModifiers.add('shift')
User->>Chromium: Enter down (during composition)
Chromium->>KeyboardHandlers: "keydown(Process/Enter, isComposing=true)"
KeyboardHandlers->>ChordOwner: "claim({kind:'shift', code, ts})"
KeyboardHandlers->>DeferredNewline: defer(enter, element, sendFn)
Note over DeferredNewline: waits for compositionend / session-end
Chromium->>xterm: compositionend
xterm->>CompRoute: XTERM_COMPOSITION_SESSION_END_EVENT
CompRoute->>CompRoute: sessions.get(id) captured
CompRoute->>xterm: terminal.input(data)
CompRoute->>DeferredNewline: "session-end fires -> finish()"
DeferredNewline->>PTY: sendFn() (Shift+Enter sequence)
Chromium->>KeyboardHandlers: "keydown(Enter, isComposing=false) re-dispatch"
KeyboardHandlers->>ChordOwner: "absorb({kind:'shift'}) -> true"
KeyboardHandlers->>KeyboardHandlers: preventDefault, stopImmediatePropagation
Chromium->>KeyboardHandlers: keyup(Enter)
KeyboardHandlers->>ChordOwner: "absorb -> true -> release"
KeyboardHandlers->>DeferredNewline: releaseRedispatchedEnter
Chromium->>KeyboardHandlers: keyup(Shift)
KeyboardHandlers->>KeyboardHandlers: heldImeEnterModifiers.delete('shift')
KeyboardHandlers->>ChordOwner: "release({kind:'shift'})"
Reviews (6): Last reviewed commit: "test(terminal): harden IME workflow cove..." | Re-trigger Greptile
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (7)
src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts (2)
137-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSame non-parameterized
it.eachpattern as Lines 61-70."terminal close" and "tab unmount" both just call
route.dispose(); the labels suggest coverage that isn't there.
61-70: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
it.eachcases in this file don't use their parameters, so each label runs identical code. The root cause is the same in both blocks: the case list describes distinct lifecycle scenarios but the callback ignores the argument.
src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts#L61-L70: drive the described blur/tab-switch/split-pane transition per case, or collapse to a singleit.src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts#L137-L148: same — either simulate close vs unmount distinctly or collapse to a singleit.src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts (1)
336-351: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winInterpolate the
it.eachcase into these titles.Both blocks emit identical test names for every case, so a failure doesn't identify which modifier combination broke.
♻️ Proposed titles
it.each([{ shiftKey: true }, { shiftKey: false, ctrlKey: true }])( - 'recognizes a Windows IME modifier Enter reported as Process', + 'recognizes a Windows IME modifier Enter reported as Process (%o)', (modifiers) => {- ])('rejects a non-IME or ambiguous Process key', (override) => { + ])('rejects a non-IME or ambiguous Process key (%o)', (override) => {src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts (1)
16-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
it.eachlabels imply SSH coverage the fixtures don't provide.Both cases run byte-identical code (
createTransport('pty-original')); no SSH-specific transport shape is exercised, so the "SSH remote runtime" name overstates coverage. Either vary the fixture (e.g. a remote-runtime PTY id) or dropit.each.♻️ Vary the fixture per case
- it.each(['local IPC', 'SSH remote runtime'])( - 'sends on the captured %s route while its PTY still owns the mounted pane', - () => { - const transport = createTransport('pty-original') + it.each([ + ['local IPC', 'pty-original'], + ['SSH remote runtime', 'ssh:host:pty-original'] + ])( + 'sends on the captured %s route while its PTY still owns the mounted pane', + (_label, ptyId) => { + const transport = createTransport(ptyId)src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts (1)
473-488: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
toBeLessThanOrEqual(1)can never fail here.
getPendingFinalizationCount(Line 131) returnspending === undefined ? 0 : 1, so the bound is structural, not observed. To actually assert turnover behavior, expose the real pending set size (or asserttoBe(1)during the loop andtoBe(0)after the flush).tests/e2e/terminal-ime-byte-reader.ts (1)
46-56: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReader invocation is POSIX-shaped; document or guard the Windows case.
node ${JSON.stringify(scriptPath)}emits JSON backslash escaping ("C:\\repo\\.orca-...cjs"), which cmd.exe/PowerShell do not unescape, so this helper only works under a POSIX shell. Today the only consumer (tests/e2e/terminal-ime-exact-byte.spec.ts) is Linux-gated, but the module reads as generic. Either note the POSIX-only contract here or normalize the path per platform. As per coding guidelines, "code, commands, and scripts must work on macOS, Linux, and Windows".Source: Coding guidelines
.github/workflows/terminal-ime-e2e.yml (1)
58-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAd-hoc global
npm installoutside the lockfile.Static analysis flags installing
node-gypglobally vianpm install -gas an ad-hoc package install outside the lockfile. It's pinned to an exact version (11.5.0), so risk is limited, but consider usingpnpm add -g(for consistency with the rest of the workflow's package manager) or vendoring via a dev dependency if this becomes a recurring pattern.Source: Linters/SAST tools
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2aef5b15-cec2-48dc-8b95-4468b1266da2
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (21)
.github/workflows/terminal-ime-e2e.ymlconfig/patches/@[email protected]config/scripts/run-terminal-ibus-hangul-e2e.mjsconfig/scripts/terminal-ime-e2e-workflow.test.mjspackage.jsonsrc/renderer/src/components/terminal-pane/keyboard-handlers.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.tssrc/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.tssrc/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.tssrc/renderer/src/components/terminal-pane/terminal-ime-composition-route.tssrc/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.tssrc/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.tssrc/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.tstests/e2e/korean-ime-terminal-shift-enter-commit.spec.tstests/e2e/terminal-ibus-hangul-native.spec.tstests/e2e/terminal-ime-boundary-probe.tstests/e2e/terminal-ime-byte-reader.tstests/e2e/terminal-ime-exact-byte.spec.tstests/e2e/terminal-ime-observed-event-sequences.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
config/patches/@[email protected] (1)
41-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
instanceof CompositionHelperchecks throughoutCoreBrowserTerminalsuggest an interface/implementation split that isn't reflected in the type system here.Repeated
this._compositionHelper instanceof CompositionHelperguards (forblur,compositionend,dispose,keypress) imply_compositionHelper's declared type is a broader interface with optional members, forcing runtime type checks instead of relying on the type checker. If there is truly only one implementation, consider typing_compositionHelperasCompositionHelperdirectly and dropping the guards; if multiple implementations exist, consider adding the new methods (blur,dispose,keypress,input) to the shared interface as optional members so call sites don't needinstanceof.Also applies to: 55-61, 68-74, 289-301
src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx (1)
31-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHarness teardown isn't guaranteed on assertion failure.
dispose()(route disposal +scope.remove()) is only invoked manually as the last statement in each test. If anexpect(...)throws earlier,scope's DOM nodes and the composition route's listeners leak intodocument.bodyfor the remainder of thedescribeblock, sinceafterEachonly calls testing-library'scleanup()and timer/mock restoration — it never touchesscopeorroute. This can cause confusing cascading failures in laterit.eachiterations/tests (duplicate.xterm-helper-textareanodes, stray listeners).Register teardown so it always runs, e.g. via Vitest's
onTestFinished, instead of relying on the last line of each test body.♻️ Suggested fix
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'const route = installTerminalImeCompositionRoute({ ... }) + onTestFinished(() => { + route.dispose() + scope.remove() + }) const deps: KeyboardHandlersDeps = { ... } return { deps, editable, terminalInput, - startComposition: () => { ... }, - dispose: () => { - route.dispose() - scope.remove() - } + startComposition: () => { ... } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9ad8ac14-2176-41fa-8621-ebf7c3524ebe
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (5)
config/patches/@[email protected]src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsxsrc/renderer/src/components/terminal-pane/keyboard-handlers.tssrc/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.tstests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
- tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts
- src/renderer/src/components/terminal-pane/keyboard-handlers.ts
- Add deterministic xterm boundary tests and a Linux/X11 native IBus Hangul E2E runner - Patch xterm composition handling and expand unit coverage for commit deduplication and retention - Wire a scheduled GitHub Action to install IME tooling, run the new suites, and archive evidence
macOS Korean input sources put ₩ (U+20A9) on Backquote, so users remap it to ` via ~/Library/KeyBindings/DefaultKeyBinding.dict. AppKit applies that substitution in the text input path, and Chromium surfaces it only on the keypress/input events — keydown still carries the raw ₩. xterm derives the PTY payload from keydown.key and preventDefault()s, which suppresses the Char event, so the remapped ` never reaches the shell. ₩ fell through every existing guard: CJK_DIRECT_PUNCTUATION_KEYS has ¥ (U+FFE5) but not ₩, the non-ASCII xterm bypass is scoped to shifted keys, and the JIS Yen rewrite is scoped to code === 'IntlYen'. Claiming it as a native-text candidate routes the keydown around xterm so the committed glyph is forwarded from the input event. Fixes #11170
Backspacing away an entire Pinyin preedit ended the composition with empty data, no textarea residue, and no input/keypress events — yet _sendPendingComposition fell back to the last non-empty compositionupdate data and typed its first character into the PTY. Only trust that fallback when observed input evidence corroborates it; a composition with no evidence in any channel was cancelled. Fixes the macOS Pinyin regression from stablyai#11293 (stray letter left after deleting a preedit); same fix covers IBus/fcitx Backspace cancellation. Co-Authored-By: Claude Fable 5 <[email protected]>
…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.
Backspacing away an entire Pinyin preedit ended the composition with empty data, no textarea residue, and no input/keypress events — yet _sendPendingComposition fell back to the last non-empty compositionupdate data and typed its first character into the PTY. Only trust that fallback when observed input evidence corroborates it; a composition with no evidence in any channel was cancelled. Fixes the macOS Pinyin regression from #11293 (stray letter left after deleting a preedit); same fix covers IBus/fcitx Backspace cancellation. Co-Authored-By: Claude Fable 5 <[email protected]>
Backspacing away an entire Pinyin preedit ended the composition with empty data, no textarea residue, and no input/keypress events — yet _sendPendingComposition fell back to the last non-empty compositionupdate data and typed its first character into the PTY. Only trust that fallback when observed input evidence corroborates it; a composition with no evidence in any channel was cancelled. Fixes the macOS Pinyin regression from #11293 (stray letter left after deleting a preedit); same fix covers IBus/fcitx Backspace cancellation. Co-Authored-By: Claude Fable 5 <[email protected]>
…ablyai#11293) Co-authored-by: Jinjing <[email protected]> Co-authored-by: Neil <[email protected]> Co-authored-by: JeongUk Park <[email protected]>
Backspacing away an entire Pinyin preedit ended the composition with empty data, no textarea residue, and no input/keypress events — yet _sendPendingComposition fell back to the last non-empty compositionupdate data and typed its first character into the PTY. Only trust that fallback when observed input evidence corroborates it; a composition with no evidence in any channel was cancelled. Fixes the macOS Pinyin regression from stablyai#11293 (stray letter left after deleting a preedit); same fix covers IBus/fcitx Backspace cancellation. Co-Authored-By: Claude Fable 5 <[email protected]>
Summary
This unifies the terminal IME fixes from:
All contributor commits and authorship are preserved. The integration then reconciles the overlapping xterm and renderer ownership models exposed by combined, native, and adversarial testing.
What changed
compositionendevents until their transaction can be reconciledRoot causes
The three fixes overlapped at the composition boundary:
compositionendafter the next transaction has updated the textarea, requiring transaction-owned textarea progress rather than global current/previous state.keydown, composition, and native text events, so forwarding must be owned until composition finalization instead of decided by one event in isolation.Validation
Final landing branch:
Independent source-built Linux/X11 IBus validation produced exact PTY bytes for 60/60 sequences: 30
한abc글repetitions and 30 sentence-stress repetitions. A pristine xterm rebuild was byte-identical for CJS, ESM, and both source maps.Exact-parent red controls, real installed CJS/ESM DOM and PTY-byte oracles, rapid restarts, stale ends, duplicate ends, repeated commits, blur, disposal, transport replacement, SSH reconnect, and bounded transaction bursts were also verified.
Remaining native coverage
Physical macOS and Windows input-source runs, native Japanese and Chinese engines, and live native SSH/folder-workspace journeys were not repeated on the final landing hash. Their event, transport, and workspace invariants are covered deterministically, and the final branch passed the platform CI listed above.
This PR supersedes #11011, #11052, and #11177.