Skip to content

fix(terminal): deliver an IME commit the deferred textarea diff missed - #15198

Merged
nwparker merged 1 commit into
mainfrom
nwparker/ime-consumed-keydown-commit
Aug 18, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/ime-consumed-keydown-commit

Conversation

@nwparker

@nwparker nwparker commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​194 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​194
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​159 $\color{#cf222e}{\Huge{\mathbf{−}}}$​59 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​100

Fixes #12099, reported by @xdewx: in the terminal, picking a single Chinese character from the candidate window with a number key loses it. The character flashes on screen and disappears. Picking the same candidate with the mouse works. Picking multi-character words with number keys works.

Those three outcomes are the whole diagnosis, and no capture from the reporter was needed to get there.

The mechanism

There are two paths that can deliver an IME commit, and this bug falls between them.

A keydown the input method consumed (keyCode 229) is routed into _handleAnyTextareaChanges(), which schedules a setTimeout(0) diff of the helper textarea. That diff is the path that normally delivers the commit. Upstream's guard in _inputEvent:

if (ev.data && ev.inputType === 'insertText' && (!ev.composed || !this._keyDownSeen) && …)

is therefore not "block IME text" — trusted events are always composed: true, so it collapses to "deliver only if no key is down", which in practice means defer to the diff.

When the commit arrives after that timer has already run, neither path delivers and the character is gone. That is specifically an input method whose commit round-trips asynchronously and which shows no in-application preedit — ibus with Rime, or fcitx5 with application preedit disabled. One that commits synchronously beats the timer and is unaffected.

This accounts for all three reported outcomes exactly:

reported why
mouse selection works no key is down, so the guard admits the input event directly
multi-character words work a real composition session is open, which takes a different path entirely
single char + number key is lost the consumed keydown armed the diff, and the async commit arrived after it

The character "appears briefly" because the preedit overlay is drawn locally. It never reached the pty, so when the overlay clears there is nothing underneath.

This is not only ours. The same report exists upstream against a plain library demo — xtermjs/xterm.js#6036 — reproducing in other terminals built on it, with the trigger stated as "application preedit is disabled."

Why the three obvious fixes are wrong — measured, not argued

The tempting repairs all target _keyDownSeen itself: don't set it, clear it on a consumed keydown, or set it after the composition short-circuit. Emulated against a real Terminal, all three produce:

emitted ["好","好"]

They unblock the input path without retiring the diff, so any synchronous commit is delivered twice. xterm-bypass-policy.ts:127 deliberately lets standalone 229 keydowns through on macOS and Linux precisely so that diff can arm, so both platforms are exposed. Windows suppresses them and is unaffected either way.

So this instead tracks that a consumed keydown is still owing its commit, and delivers only when the diff did not. The upstream guard and its single read site are untouched, which is what keeps the duplicate-commit behaviour it was originally added for sealed.

Why new state is justified

The standing preference here is minimal code, so the added field has to earn its place. It is one boolean plus a short private method, because this is an arbitration problem between two delivery paths and no existing field expresses "the consumed keydown still owes its commit". The zero-new-field variants were checked and rejected:

  • reusing _textareaChangeTimer as the marker overloads one field with two meanings and breaks the re-arm guard, so later consumed keydowns stop re-baselining
  • _dataAlreadySent is written by the diff and never read by it

Tests

terminal-ime-xterm-consumed-key-commit.test.ts, six cases against a real Terminal:

✓ sends a candidate picked with the mouse, with no key down
✓ sends a candidate committed by a real composition session exactly once
✓ sends a commit that arrives after the deferred diff while the consumed key is down   ← the bug
✓ sends a commit that arrives before the deferred diff exactly once
✓ sends one commit when the IME fires both compositionend and insertText
✓ does not double an upper-case letter typed after a consumed keydown that never committed

Case 3 is the only one that fails against unmodified main (expected '' to be '好'); the before-run was a genuine revert — patch stashed and pnpm install re-run, confirmed with grep -c _claimImeKeydownCommit node_modules/@xterm/xterm/lib/xterm.mjs returning 0.

Worth being precise about what each case does: the duplicate-commit case passes in both directions — it is a guard, not a discriminator. The cases that actually discriminate against the wrong fixes are case 4 (emits 好好 under any of the three _keyDownSeen variants) and case 6 (emits AA if the disarm is dropped).

One trap worth recording

@xterm/xterm ships both src/ and a minified lib/, and everything at runtime and under vitest resolves to lib/xterm.mjs via the package module field. A TS-only edit to the vendored patch is inert — it would leave tests passing while changing nothing. The change is applied to src/, lib/xterm.js and lib/xterm.mjs.

Verification

  • terminal-pane suite: 372 files / 3646 tests pass, including the recorded ibus and fcitx5 native trace replays
  • other xterm-dependent suites (lib/pane-manager/, dashboard-popout/, terminal search decoration): 108 files / 1082 pass, 1 skipped
  • oxlint, oxfmt clean; max-lines ratchet OK with no new bypasses and no disable added
  • npm run typecheck reports two errors in src/renderer/src/components/tab-bar/open-tab-search-retention.test.ts, proven pre-existing by stashing and re-running to byte-identical output — unrelated and not fixed here

Not verified

No real hardware. ibus+Rime panel-only preedit could not be reproduced on this machine, so the async commit ordering is modelled rather than observed live. The reporter has been given an inline-preedit experiment that doubles as a workaround; if it does not help them, the model of their setup is wrong and that should block this.

lib/*.map are now slightly stale, since sourcemaps were not regenerated. Devtools-only.

@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Updated xterm composition handling to track IME transactions, reconcile composition and input events, suppress duplicate commits, and clean up pending state during blur or disposal. Composition rendering now supports preedit row tails, themed backgrounds, and cancellable repositioning. Added a happy-dom Vitest regression suite for direct, composition-based, deferred, duplicate, and stale IME commit scenarios.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The patch includes an unrelated SortedList.delete retry change that is not required by issue #12099. Remove the unrelated SortedList.delete change or link a separate issue that requires it.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description thoroughly explains the issue, mechanism, fix, linked issue, tests, limitations, and verification, but omits required visual proof and template checklist sections. Add the required Visual Proof entry or an explicit N/A justification, then complete the template checklist and other required sections.
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes and regression tests directly address issue #12099 by preserving delayed single-character IME commits after consumed number-key events.
Title check ✅ Passed The title clearly and concisely identifies the terminal IME fix for missed deferred textarea commits.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/terminal-ime-xterm-consumed-key-commit.test.ts (1)

2-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce the test commentary.

The test names and dispatched events already describe the scenarios. Keep only short comments that state a non-obvious precondition or ordering constraint. Move defect history and xterm control-flow detail to the issue or commit description.

Suggested reduction
-// The reporter's failing case. ibus answers over DBus, so the commit lands after the deferred
-// textarea diff has already run against an unchanged textarea — and the number key is still down.
+// The sessionless commit arrives after the deferred textarea diff.

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

Also applies to: 135-136, 150-151, 164-166, 179-181

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 82deca9a-1dac-4544-b6c6-f00a1f99c379

📥 Commits

Reviewing files that changed from the base of the PR and between 6ee265e and 501d9ab20a8cbca0cbbe412c310bae34a894db7e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • config/patches/@[email protected]
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-consumed-key-commit.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 4 remain after this review.

@nwparker

Copy link
Copy Markdown
Contributor Author

Disclosure: this patch hand-edits the minified bundles, against a documented rule

Flagging this myself rather than letting a reviewer find it.

docs/reference/ime-architecture.md:420 says, inline:

Never hand-edit the bundles in the patch. See xterm-patch-regeneration.md.

This patch does exactly that. The five semantic edits live in the src/browser/input/CompositionHelper.ts hunks and are complete and reviewable; the bundle hunks are a mechanical transcription of those same five edits — 12 single-occurrence string replacements, each asserted unique. The bundles have to change, because everything at runtime and under vitest resolves to lib/xterm.mjs via the package module field, so a src-only edit is inert.

Why the rule could not be followed

The document it points at does not exist on HEAD, and neither does the tooling:

status
docs/reference/xterm-patch-regeneration.md missing
config/scripts/regenerate-xterm-patches.mjs (727 lines) missing
config/scripts/regenerate-xterm-patches.test.mjs (478 lines) missing
config/patches/@[email protected] missing
config/patches/xterm-upstream.json missing
the pr.yml job verifying shipped patches match the pinned build missing

All of it landed in 29117bf7767 ("build(xterm): land the patch regeneration harness") and was deleted by 17cfc968cf5 ("Revert the terminal IME composition-ownership change (#13282)") on 2026-08-08 — collateral of a functional revert, not a decision about the harness. The rule survived; its tooling and its enforcement job did not.

This is not specific to this PR

Every xterm patch merged since that date is in the same position: a47b9d1167d (#13284, 08-09), 17ef6ccce68 (#14758, 08-16), 453237cc57c (#15014, 08-17). Two of those are mine.

Cost, stated plainly

The bundle hunks cannot be reproduced by a future regeneration, and lib/*.map are stale (devtools-only). Nothing is failing, and no safety net would have caught this because the safety net was deleted.

Recommendation

Restore the harness from 29117bf7767 as separate work, not inside a bug fix. There is one trap for whoever does it: that commit's .src.patch is 247 lines against roughly 1000 in today's shipped patch, so regenerating from it as-is would silently revert #13284, #14758, #15014 and this change. The src patch has to be re-derived from the current patch first.

Happy to hold this PR if a maintainer would rather see the harness restored first — say so and I will.

Picking a single Chinese character from the candidate window with a
number key loses it. The character flashes and disappears. Picking the
same candidate with the mouse works, and picking multi-character words
with number keys works.

Two paths can deliver an IME commit, and this falls between them. A
keydown the input method consumed routes into a setTimeout(0) diff of
the helper textarea, and that diff is what normally delivers the commit;
xterm's _keyDownSeen guard exists to defer to it. When the commit
arrives after that timer has already run, neither path delivers. Mouse
selection works because no key is down, and a real composition session
works because it takes a different path entirely. That narrows it to an
input method whose commit round-trips asynchronously and which shows no
in-application preedit.

Track that a consumed keydown still owes its commit, and deliver only
when the diff did not. The upstream guard and its single read site are
untouched, which is what keeps the duplicate-commit behaviour it was
added for sealed.

Not doing the obvious repairs deliberately: clearing the flag, skipping
it for keyCode 229, or setting it after the composition short-circuit
each unblock the input path without retiring the diff, and all three
were measured emitting the character twice.

The patch and the lockfile hash here are generated. Review
config/patches/xterm-src/@[email protected], which
is the hand-written source of the change; the shipped patch and both
minified bundles are the regenerator's output from the pinned upstream
build, so nothing in this change was hand-transcribed into a bundle.

Refs xtermjs/xterm.js#6036
Closes #12099
@nwparker
nwparker force-pushed the nwparker/ime-consumed-keydown-commit branch from 501d9ab to dfaa6fb Compare August 18, 2026 04:49

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
config/patches/xterm-src/@[email protected] (2)

819-823: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Guard the suffix subtraction, as the two sibling helpers do.

_composedRegionLength subtracts _compositionSuffix.length without checking that the value still ends with the suffix. _getPendingTextareaInput and _getCompositionInput both check value.endsWith(...) first. If the textarea tail changed, the computed end is too small, the method returns 0, and _deferPreeditResync cancels an active composition.

🐛 Proposed fix
   private _composedRegionLength(): number {
-    const end = this._textarea.value.length - this._compositionSuffix.length;
+    const value = this._textarea.value;
+    const end = this._compositionSuffix.length > 0 && value.endsWith(this._compositionSuffix)
+      ? value.length - this._compositionSuffix.length
+      : value.length;
     return Math.max(0, end - this._compositionPosition.start);
   }

757-778: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Wire _endPendingCompositionSession into pending-session finalization.

The method is never called, so sessionEnded remains false and dataPendingReconciliation: true is never dispatched. This prevents terminal-ime-composition-route.ts from handling pending session data correctly.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d261653-33e8-43da-addd-c7f6b8dcaad3

📥 Commits

Reviewing files that changed from the base of the PR and between 501d9ab20a8cbca0cbbe412c310bae34a894db7e and dfaa6fb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)

Included review availability: Your plan includes up to 10 reviews per rolling hour; 4 remain after this review.

@nwparker

Copy link
Copy Markdown
Contributor Author

Merging this, with a debt recorded against it

An audit of the recent terminal input work landed while this was in review, and it is worth writing down what it found before this merges, because this change is the third patch to the same guard.

The guard is asking the wrong question. Printable bytes are emitted from the key event, and _keyDownSeen / _keyPressHandled are then used as a proxy for "the text system did not also deliver this text." That proxy is wrong in both directions, and the recent regressions here are each an instance of it:

Same question, opposite failures. Other terminals resolve it structurally rather than by inference: they hand the event to the platform's input context first, let the text system call back with the committed or marked text, and only then ask whether the raw key should still produce bytes. The equivalent flag there is the return value of having asked, not a guess derived from "a key went down."

So the honest framing of this change: it is a fourth arbiter between two delivery paths that arguably should not both exist. The right fix is to stop emitting printable bytes from the key path and make the text system the sole source, letting the existing textarea diff own it — which would delete considerably more code than it adds.

I am still merging it, deliberately: #12099 is a real bug that users are hitting today, this fix is correct and tested for it, and the rework above is a much larger piece of work that should not gate a live bug fix. But it does make that guard load-bearing in one more place, and if a fourth regression appears in this area, this comment is the reason to stop patching and do the rework instead.

Two things did improve in the meantime:

  • The patch here is now generated, not hand-edited. This is the first xterm patch since 2026-08-08 whose minified bundles came from a real build of the pinned upstream rather than hand transcription, and the reviewable artifact is the source patch rather than a 7 MB blob.
  • The IME e2e suite is being wired to run on terminal input source changes. Every IME fix in this window, this one included, shipped without triggering the suite that already covers it, because PR e2e only ran specs whose own file changed.

@nwparker
nwparker merged commit d143922 into main Aug 18, 2026
46 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
stablyai#15198)

Picking a single Chinese character from the candidate window with a
number key loses it. The character flashes and disappears. Picking the
same candidate with the mouse works, and picking multi-character words
with number keys works.

Two paths can deliver an IME commit, and this falls between them. A
keydown the input method consumed routes into a setTimeout(0) diff of
the helper textarea, and that diff is what normally delivers the commit;
xterm's _keyDownSeen guard exists to defer to it. When the commit
arrives after that timer has already run, neither path delivers. Mouse
selection works because no key is down, and a real composition session
works because it takes a different path entirely. That narrows it to an
input method whose commit round-trips asynchronously and which shows no
in-application preedit.

Track that a consumed keydown still owes its commit, and deliver only
when the diff did not. The upstream guard and its single read site are
untouched, which is what keeps the duplicate-commit behaviour it was
added for sealed.

Not doing the obvious repairs deliberately: clearing the flag, skipping
it for keyCode 229, or setting it after the composition short-circuit
each unblock the input path without retiring the diff, and all three
were measured emitting the character twice.

The patch and the lockfile hash here are generated. Review
config/patches/xterm-src/@[email protected], which
is the hand-written source of the change; the shipped patch and both
minified bundles are the regenerator's output from the pinned upstream
build, so nothing in this change was hand-transcribed into a bundle.

Refs xtermjs/xterm.js#6036
Closes stablyai#12099
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
stablyai#15198)

Picking a single Chinese character from the candidate window with a
number key loses it. The character flashes and disappears. Picking the
same candidate with the mouse works, and picking multi-character words
with number keys works.

Two paths can deliver an IME commit, and this falls between them. A
keydown the input method consumed routes into a setTimeout(0) diff of
the helper textarea, and that diff is what normally delivers the commit;
xterm's _keyDownSeen guard exists to defer to it. When the commit
arrives after that timer has already run, neither path delivers. Mouse
selection works because no key is down, and a real composition session
works because it takes a different path entirely. That narrows it to an
input method whose commit round-trips asynchronously and which shows no
in-application preedit.

Track that a consumed keydown still owes its commit, and deliver only
when the diff did not. The upstream guard and its single read site are
untouched, which is what keeps the duplicate-commit behaviour it was
added for sealed.

Not doing the obvious repairs deliberately: clearing the flag, skipping
it for keyCode 229, or setting it after the composition short-circuit
each unblock the input path without retiring the diff, and all three
were measured emitting the character twice.

The patch and the lockfile hash here are generated. Review
config/patches/xterm-src/@[email protected], which
is the hand-written source of the change; the shipped patch and both
minified bundles are the regenerator's output from the pinned upstream
build, so nothing in this change was hand-transcribed into a bundle.

Refs xtermjs/xterm.js#6036
Closes stablyai#12099
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#15198)

Picking a single Chinese character from the candidate window with a
number key loses it. The character flashes and disappears. Picking the
same candidate with the mouse works, and picking multi-character words
with number keys works.

Two paths can deliver an IME commit, and this falls between them. A
keydown the input method consumed routes into a setTimeout(0) diff of
the helper textarea, and that diff is what normally delivers the commit;
xterm's _keyDownSeen guard exists to defer to it. When the commit
arrives after that timer has already run, neither path delivers. Mouse
selection works because no key is down, and a real composition session
works because it takes a different path entirely. That narrows it to an
input method whose commit round-trips asynchronously and which shows no
in-application preedit.

Track that a consumed keydown still owes its commit, and deliver only
when the diff did not. The upstream guard and its single read site are
untouched, which is what keeps the duplicate-commit behaviour it was
added for sealed.

Not doing the obvious repairs deliberately: clearing the flag, skipping
it for keyCode 229, or setting it after the composition short-circuit
each unblock the input path without retiring the diff, and all three
were measured emitting the character twice.

The patch and the lockfile hash here are generated. Review
config/patches/xterm-src/@[email protected], which
is the hand-written source of the change; the shipped patch and both
minified bundles are the regenerator's output from the pinned upstream
build, so nothing in this change was hand-transcribed into a bundle.

Refs xtermjs/xterm.js#6036
Closes stablyai#12099
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]: Terminal — selecting a single Chinese char by number key is wiped; mouse selection works

1 participant