Skip to content

fix(terminal): reconcile Windows IME deletion and Shift toggle - #11550

Closed
yoke233 wants to merge 3 commits into
stablyai:mainfrom
yoke233:fix/windows-ime-preedit-deletion
Closed

yoke233 wants to merge 3 commits into
stablyai:mainfrom
yoke233:fix/windows-ime-preedit-deletion

Conversation

@yoke233

@yoke233 yoke233 commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #11293, based on native Microsoft Pinyin traces captured in Electron on Windows.

The native events differ from the synthetic model used by the first revision of this PR:

  • Backspace during a one-letter preedit arrives as keydown key=Process code=Backspace keyCode=229, followed by an empty composition update/input, then keyup Process/229 and keyup Backspace/8.
  • Pressing Shift to toggle the IME arrives as Process code=ShiftLeft keyCode=229 plus the ordinary Shift events. It does not emit Enter. The previous predicate checked key=Process, modifier state, and keyCode=229, but not code, so it could misclassify this Shift-owned Process event as Shift+Enter and submit a newline.

This revision:

  • recognizes deletion from both the native key=Process/code=Backspace|Delete shape and the logical key=Backspace|Delete compatibility shape;
  • lets only tracked composition deletion keydowns reach xterm, then reconciles the preedit without emitting PTY data;
  • scopes empty composition updates to a one-shot deletion token that expires on native progress, fallback completion, finalization, cancellation, restart, or disposal;
  • consumes the ordinary Backspace/Delete keyup paired with the IME transaction so Kitty keyboard event reporting cannot leak it to the PTY;
  • requires code=Enter|NumpadEnter before treating Process/229 as a modified Enter, so code=ShiftLeft cannot create a newline;
  • keeps the transaction ownership, stale-event rejection, native-progress precedence, and bounded timer behavior introduced by fix(terminal): reconcile cross-platform IME composition lifecycle #11293.

Upstream main was checked before the update and remains the direct base of this PR; no later upstream commit fixes these native Windows event shapes.

Screenshots

No visual change.

Testing

  • pnpm lint (full repository lint not run)
  • pnpm typecheck
  • pnpm test (full repository suite not run)
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

Additional verification:

  • 124 focused IME, xterm, deletion-release, newline, and keyboard-policy tests passed across 5 files.
  • Electron-headless Windows IME E2E: 2 passed; the separately tagged real-Codex test was skipped by design.
  • The E2E asserts one-letter preedit deletion emits zero PTY input and Shift toggle commits only s, with no newline.
  • The xterm adversarial test enables Kitty event reporting (CSI > 10 u) and proves the paired Backspace/8 keyup emits nothing.
  • Changed TypeScript files passed oxlint, React Doctor lint, and oxfmt through the commit hook.
  • Regenerated ESM/CJS bundles and source maps retain XTERM_VERSION = 6.1.0-beta.287; the patch contains no 6.0.0 marker.

AI Review Report

Independent reviews checked implementation quality, state lifetime, generated artifacts, test fidelity, and cross-platform regressions.

They flagged four issues in the earlier revision, all addressed here:

  1. Generated xterm bundles accidentally reported 6.0.0; all artifacts were regenerated with src/common/Version.ts from 6.1.0-beta.287.
  2. Switching entirely from key to code regressed events with an unavailable physical code; both shapes are now accepted and tested.
  3. The deletion transaction id could remain stale after deferred fallback; it is now a data-bound one-shot token cleared on every completion/cancellation path.
  4. The ordinary Backspace/8 keyup could leak under Kitty event-type reporting; a narrow, expiring paired-release guard and Kitty-mode regression test were added.

Cross-platform review confirmed the new release guard only arms from keyCode=229 during an active composition. macOS and Linux standalone-229 behavior, Linux/Sogou candidate guards, folder workspaces, SSH transports, shortcut labels, paths, and shell behavior are unchanged.

Security Audit

No auth, secrets, IPC contracts, command execution, or production path handling were added. The CDP event dispatch and PTY log parsing live only in E2E helpers and operate on test-created files. The production change is limited to renderer keyboard-event classification and the existing pinned xterm patch; no dependency version changed.

Notes

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change updates Windows IME Enter keyup handling to avoid synthetic newline input during Shift toggles. It adds deletion-release tracking for native composition Backspace and Delete events, allowing keydowns to reach xterm while suppressing paired keyups. Unit, adversarial, and end-to-end tests cover composition editing, native updates, preedit state, terminal output, PTY logging, and Windows IME event simulation.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% 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 explains the change and verification, but it misses required template sections like Summary, Screenshots, AI Review Report, Security Audit, and Notes. Reformat it to the template and add the missing sections, including Summary, Screenshots or No visual change, Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (3 passed)
Check name Status Explanation
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 is concise and accurately summarizes the main Windows IME deletion and Shift-toggle fix.

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 Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes two Windows IME edge cases left uncovered by #11293: (1) a one-letter preedit that couldn't be deleted because keyCode === 229 Backspace/Delete events were suppressed before reaching xterm's CompositionHelper, and (2) a Windows Shift-toggle that emitted an orphan Enter keyup which the fallback handler mistakenly turned into a deferred newline.

  • Deletion reconciliation — a new TerminalImeDeletionReleaseGuard (one-shot, 1 s TTL) lets composition deletion keydowns with keyCode === 229 pass through to xterm, then suppresses only the ordinary paired keyup (keyCode 8/46) while letting the IME-owned 229 keyup pass. The xterm patch reconciles the preedit textarea one event-loop turn later, preferring native IME progress.
  • Shift-toggle fix — isTerminalImeProcessEnter now requires code === 'Enter' | 'NumpadEnter', rejecting events whose physical key is ShiftLeft; the unowned modified-Enter keyup fallback block (which could fire on an orphan Enter keyup accompanying a Shift toggle) is removed entirely.
  • Test coverage — unit tests for the guard, xterm adversarial integration tests for preedit deletion races, and Electron headless E2E tests with raw PTY input-count assertions complete the verification.

Confidence Score: 5/5

Safe to merge; the two targeted Windows IME regressions are fixed without disturbing the transaction model from #11293, and each new code path is covered by unit, integration, and E2E tests.

Both fixes are narrow and surgical: the deletion guard is a simple one-shot state machine with a 1 s TTL, and the fallback removal affects only the unowned-chord case that had no legitimate callers. The new isTerminalImeProcessEnter narrowing correctly gates on physical code rather than logical key, and the existing Shift+Enter deferred-newline path that relies on modifiedEnterChordOwner.absorb returning true is unaffected. The xterm patch is not reviewable at source level, but the adversarial integration tests exercise all the CompositionHelper paths that matter here.

Files Needing Attention: config/patches/@[email protected] — the patch is minified and cannot be code-reviewed directly; the adversarial tests in terminal-ime-xterm-adversarial.test.ts provide the best available confidence in its correctness.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-ime-deletion-release-guard.ts New one-shot guard that tracks a Windows IME composition deletion keydown and suppresses only its paired ordinary keyup; correct one-shot semantics with 1 s TTL and composition-release pass-through.
src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts Adds isTrackedCompositionDeletion early-return to let deletion keydown-229 reach xterm, and an early suppress for pendingCompositionDeletionReleaseActive; both paths are well-guarded and tested.
src/renderer/src/components/terminal-pane/keyboard-handlers.ts Removes the unowned modified-Enter keyup fallback that could fire on a Shift-toggle orphan Enter; legitimate Shift+Enter still routes through the modifiedEnterChordOwner absorb path that is preserved.
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts isTerminalImeProcessEnter now requires code==='Enter'
src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts Correctly wires the deletion release guard: consume fires before arm so consecutive deletions arm a fresh guard, and compositionActive is captured once and reused for both arm and imeKeyboardOptions.
tests/e2e/chinese-ime-chat-input-repro.spec.ts Extends the combined E2E test with Shift-toggle and IME Backspace assertions including raw PTY input-count checks; adds a dedicated Shift-toggle regression test with Windows UA policy.
tests/e2e/helpers/windows-ime-native-events.ts New CDP helper module that faithfully replays Chromium's native Microsoft Pinyin Backspace and Shift-toggle event sequences, plus utilities for reading raw PTY input log files.
config/patches/@[email protected] Updated xterm patch (minified JS); exact diff not reviewable at source level, but the adversarial integration tests exercise the relevant CompositionHelper paths.

Sequence Diagram

sequenceDiagram
    participant IME as Windows IME
    participant KH as Keyboard Handler
    participant Guard as DeletionReleaseGuard
    participant Policy as BypassPolicy
    participant Xterm as xterm CompositionHelper

    Note over IME,Xterm: Windows Pinyin one-letter preedit deletion
    IME->>KH: "keydown {key:'Process', code:'Backspace', keyCode:229}"
    KH->>Guard: consumeRelease(event) → false (guard empty)
    KH->>Guard: "arm(event, compositionActive=true) → guard armed for 'Backspace'"
    KH->>Policy: "shouldSuppress? → isTrackedCompositionDeletion=true → false (PASS THROUGH)"
    KH->>Xterm: keydown reaches CompositionHelper
    Xterm->>Xterm: defer preedit reconciliation (one event-loop turn)
    IME->>KH: compositionupdate '' / compositionend
    Xterm-->>Xterm: native progress wins — preedit cleared
    IME->>KH: "keyup {key:'Process', code:'Backspace', keyCode:229}"
    KH->>Guard: "consumeRelease → isCompositionRelease=true → false (guard stays armed)"
    KH->>Policy: "shouldSuppress? → keyCode=229, isComposing → true (SUPPRESS)"
    IME->>KH: "keyup {key:'Backspace', code:'Backspace', keyCode:8}"
    KH->>Guard: "consumeRelease → isPairedRelease=true, guard cleared → true"
    KH->>Policy: "pendingCompositionDeletionReleaseActive=true → SUPPRESS"
    Note over KH,Xterm: Backspace keyup never reaches PTY

    Note over IME,Xterm: Windows Shift-toggle spurious newline (fixed)
    IME->>KH: keydown Process/ShiftLeft/229
    IME->>KH: keydown Shift/ShiftLeft/16
    IME->>KH: keyup Process/ShiftLeft/229
    Note over KH: key≠'Enter' → early return, no deferred newline
    IME->>KH: "orphan Enter keyup (key:'Enter', shiftKey=true)"
    KH->>KH: modifiedEnterChordOwner.absorb → false (no owner)
    Note over KH: fallback block REMOVED → falls through to chord release only
Loading

Reviews (2): Last reviewed commit: "docs(terminal): document IME release own..." | Re-trigger Greptile

@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-deletion-release-guard.ts (1)

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

Duplicated Backspace/Delete key-matching predicate. Both sites independently encode "is this event a tracked IME deletion key" (key/code ∈ {Backspace, Delete}); they currently agree but can silently drift since nothing keeps them in sync.

  • src/renderer/src/components/terminal-pane/terminal-ime-deletion-release-guard.ts#L12-L19: export resolveTerminalImeDeletionKey (or a boolean wrapper around it) for reuse.
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts#L125-L135: replace the inline event.key === 'Backspace' || ... || event.code === 'Delete' check with the shared predicate from the guard module.
♻️ Proposed extraction
--- a/src/renderer/src/components/terminal-pane/terminal-ime-deletion-release-guard.ts
+++ b/src/renderer/src/components/terminal-pane/terminal-ime-deletion-release-guard.ts
@@
-function resolveTerminalImeDeletionKey(
+export function resolveTerminalImeDeletionKey(
   event: Pick<XtermBypassEvent, 'key' | 'code'>
 ): TerminalImeDeletionKey | undefined {
--- a/src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts
+++ b/src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts
@@
+import { resolveTerminalImeDeletionKey } from './terminal-ime-deletion-release-guard'
@@
   const isTrackedCompositionDeletion =
     event.type === 'keydown' &&
     compositionActive &&
     event.keyCode === 229 &&
-    (event.key === 'Backspace' ||
-      event.key === 'Delete' ||
-      event.code === 'Backspace' ||
-      event.code === 'Delete')
+    resolveTerminalImeDeletionKey(event) !== undefined

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 71b7f2ae-4a55-448d-a8d9-4023891db0d4

📥 Commits

Reviewing files that changed from the base of the PR and between 0898711 and 072c568.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • config/patches/@[email protected]
  • src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deletion-release-guard.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deletion-release-guard.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-adversarial.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts
  • tests/e2e/chinese-ime-chat-input-repro.spec.ts
  • tests/e2e/helpers/windows-ime-native-events.ts

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Cross-compared this with the fixes now on main: #12265 supersedes the Shift/Enter portion, and #12273 fixes cancelled stale-preedit replay. The Windows Process/229 Backspace/Delete reconciliation and paired Kitty keyup ownership here remain distinct and are not yet landed, so I am leaving this PR open rather than incorrectly marking that work resolved. A current-main extraction should add an explicit Windows gate, adapt around #12265's capture guard, and cover delayed native progress before reuse.

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

The native Windows behaviors covered here are now resolved on main: modified Process events require a physical Enter, cancelled preedits no longer replay stale text, and #12276 preserves the Microsoft Pinyin Shift-commit trace with @yoke233 credited as co-author. #12278 also lands the complementary Hangul syllable-flush fix. Thank you @yoke233 for the native traces and regression coverage.

@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.

3 participants