Skip to content

fix(terminal): stop cancelled IME compositions replaying stale preedit - #11938

Closed
Him188 wants to merge 1 commit into
stablyai:mainfrom
Him188:fix/ime-composition-cancel-stale-preedit
Closed

Him188 wants to merge 1 commit into
stablyai:mainfrom
Him188:fix/ime-composition-cancel-stale-preedit

Conversation

@Him188

@Him188 Him188 commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Fixes #11936.

Root cause

Backspacing away an entire preedit (e.g. macOS Simplified Chinese Pinyin: type ceshi, press Backspace 5 times) ends the composition with empty compositionend data, an empty textarea, and no input/keypress events. _sendPendingComposition (added in #11293) then falls back to the last non-empty compositionupdate data — the stale preedit remnant c — and emits it to the PTY as if it were committed text. Committing normally is unaffected because compositionend carries the candidate, so the fallback chain never reaches the stale value.

Fix

One-line semantic change in the patched CompositionHelper._sendPendingComposition: only fall back to pending.compositionData when observed input evidence (input/keypress data) corroborates that the composition actually committed. A composition that ends with no evidence in any channel — textarea, end data, input, keypress — was cancelled, and nothing is emitted. Applied to lib/xterm.js, lib/xterm.mjs, and the reference src/browser/input/CompositionHelper.ts in the existing @xterm/xterm patch; the patch file was regenerated by pnpm patch-commit, which also normalized some formatting-only hunks (hence the net line-count drop).

The same cancellation shape exists on Linux IBus/fcitx (Backspace over the whole preedit fires compositionend with empty data after a deleteContentBackward), so this covers that path too.

Tests

New terminal-ime-xterm-composition-cancel.test.ts drives the real patched xterm build (same harness style as terminal-ime-xterm-composition-deduplication.test.ts):

  • Backspace-cancel of a full Pinyin preedit emits nothing — fails with expected [ 'c' ] to deeply equal [] without the fix, reproducing the report exactly;
  • cancel variant without observed input events emits nothing;
  • control: an empty-end commit that delivers text via a following bare insertText (IBus Hangul shape) still emits, guarding against an over-broad fix.

All four existing IME suites pass (72/72): terminal-ime-xterm-composition-deduplication, terminal-ime-xterm-transaction-events, keyboard-handlers-ime, plus the new file. Manually verified on macOS 26.2 with the built-in Pinyin IME: Backspace over the preedit leaves the shell line clean, and candidate commits are unchanged.

🤖 Generated with Claude Code

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]>
@Him188
Him188 marked this pull request as ready for review August 1, 2026 12:05
@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 657e8a14-359a-4ee1-a0e2-4555f9c5d4c2

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and 28f034b.

⛔ 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-composition-cancel.test.ts

📝 Walkthrough

Walkthrough

Added a happy-dom Vitest suite for xterm IME composition behavior. The suite provides terminal and event helpers, mocks canvas measurement, and cleans up terminals and DOM state. Tests cover Pinyin preedit deletion followed by cancellation, cancellation without textarea input events, and an empty composition end followed by insertText. The tests assert that cancelled preedit text emits no data and committed input emits the committed character.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the root cause, fix, and tests, but it omits several required template sections and checklist items. Add the required Screenshots, AI Review Report, Security Audit, and Notes sections, and complete the Testing checklist.
Linked Issues check ❓ Inconclusive The described tests target the linked bug, but the reviewable summary does not verify the required CompositionHelper implementation change. Include the CompositionHelper and patched xterm source changes in the reviewable diff, or provide evidence that stale preedit emission is prevented.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the fix for cancelled IME compositions replaying stale preedit text.
Out of Scope Changes check ✅ Passed The reviewable change adds IME composition cancellation tests that directly support the linked issue and stated objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a bug where cancelling an IME composition by backspacing away the entire preedit (e.g. macOS Simplified Chinese Pinyin) would cause the stale last compositionupdate data to be emitted to the PTY as committed text. The root cause was in _sendPendingComposition, which unconditionally fell back to pending.compositionData when all other channels — textarea, compositionend data, observed input — were empty.

  • One-line fix in _sendPendingComposition: the compositionData fallback is now gated behind observedInput, so it is only used when an input or keypress event corroborates a real commit; an empty-evidence composition end is treated as a cancellation and emits nothing.
  • Three new test cases cover: the exact reported Pinyin backspace scenario, a cancel with no observed input events, and a regression guard for the IBus Hangul shape (empty compositionend followed by a bare insertText that should still emit).
  • Patch regenerated via pnpm patch-commit, applying the semantic change consistently to lib/xterm.js, lib/xterm.mjs, and the reference TypeScript source src/browser/input/CompositionHelper.ts.

Confidence Score: 4/5

Safe to merge; the change is narrow and well-tested, touching only IME composition cancellation logic with no impact on normal commits or unrelated input paths.

The one-line semantic change in _sendPendingComposition is clearly targeted and the three new tests reproduce the exact failure mode and guard two related paths. The only noteworthy observation is that _endPendingCompositionSession retains an unguarded compositionData fallback — meaning external session-end listeners can still see stale preedit text for a rapid cancel-then-new-composition sequence, even though the PTY itself is unaffected.

Files Needing Attention: The _endPendingCompositionSession method inside the patch (around line 760–780 of the patch file) retains the old unguarded fallback and could benefit from a matching guard in a follow-up.

Important Files Changed

Filename Overview
config/patches/@[email protected] Core fix applied here: _sendPendingComposition now gates the compositionData fallback behind observedInput, preventing stale preedit from being emitted on cancel. Minor inconsistency: _endPendingCompositionSession retains the unguarded compositionData fallback for its provisional session-end event.
src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-cancel.test.ts New test file covering the exact Pinyin backspace regression, a no-input-events cancel variant, and a regression guard for the IBus Hangul commit pattern.
pnpm-lock.yaml Lockfile updated as a side-effect of pnpm patch-commit normalising patch metadata; no dependency version changes.

Sequence Diagram

sequenceDiagram
    participant IME as IME (Chromium)
    participant CH as CompositionHelper
    participant PTY as PTY

    Note over IME,PTY: Backspace-cancel path (this fix)
    IME->>CH: compositionstart()
    IME->>CH: compositionupdate('c'), compositionupdate('ce'), ...
    Note over CH: _lastCompositionData = 'c'
    IME->>CH: compositionupdate('') + textarea empty + deleteContentBackward
    IME->>CH: compositionend('')
    CH->>CH: _finalizeComposition(true, '') creates pending
    Note over CH: finalizerTimer fires
    CH->>CH: _sendPendingComposition - observedInput is empty
    Note over CH: yields '' (FIXED - was 'c' before)
    CH-->>PTY: nothing emitted

    Note over IME,PTY: Normal commit path (unaffected)
    IME->>CH: compositionstart()
    IME->>CH: compositionupdate('测试')
    IME->>CH: compositionend('测试')
    CH->>CH: _finalizeComposition(true, '测试') creates pending
    Note over CH: finalizerTimer fires
    CH->>CH: "_sendPendingComposition - endData='测试'"
    CH->>PTY: triggerDataEvent('测试')
Loading

Comments Outside Diff (1)

  1. config/patches/@[email protected], line 760-780 (link)

    P2 Inconsistent compositionData fallback in _endPendingCompositionSession

    _endPendingCompositionSession still uses the unguarded pending.compositionData fallback without the observedInput guard introduced in _sendPendingComposition. This method fires the xterm-composition-session-end event with dataPendingReconciliation: true when a new composition starts while the previous one is still pending — a scenario that can occur immediately after a backspace-cancel. In that case the event's detail.data will contain the stale preedit ('c') rather than '', inconsistent with the no-emission outcome the fix produces for PTY output. The dataPendingReconciliation: true flag tells listeners to treat the value as provisional, so no incorrect characters reach the PTY, but external consumers displaying a commit preview based on this event could briefly show stale text.

Reviews (1): Last reviewed commit: "fix(terminal): stop cancelled IME compos..." | Re-trigger Greptile

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Landed via #12273 with the original commit authorship preserved. Thank you for the focused root-cause analysis, regression test, and fix.

@OrcaWin OrcaWin closed this Aug 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]: macOS Pinyin IME — first keystroke leaks into the terminal; Backspace over preedit leaves a stray letter (regression since #11293)

2 participants