xterm.js icon indicating copy to clipboard operation
xterm.js copied to clipboard

Ctrl+<letter> and Escape are silently dropped under a CJK IME (keyCode 229)

Open openwong2kim opened this issue 4 months ago • 1 comments

Details

  • xterm.js version: 6.0.0, also reproducible on current master
  • Browser/Environment: Chromium on Windows 11 (hit in an Electron app, reproduced in plain Chromium via the built lib/xterm.mjs)
  • OS: Windows 11
  • IME: Korean (Microsoft IME). The same mechanism applies to any CJK IME (Japanese, Chinese) that reports keyCode === 229 for claimed keys.

Summary

While a CJK IME is active, control inputs that never begin a composition — Ctrl+<letter>, Ctrl+Space, and a bare Escape — are silently dropped. Nothing reaches onData, so nothing reaches the PTY. The clearest user-visible symptoms inside an in-pane TUI:

  • Ctrl+J (insert-newline in readline / Claude Code / codex editors) does nothing.
  • Ctrl+C does not interrupt.
  • Escape does not cancel (e.g. a dialog whose footer says "Esc to cancel" can only be dismissed by killing the process).

Turn the IME off and the exact same keys work. Native terminals (Windows Terminal / conhost) are unaffected because they don't route through a browser textarea + composition events — this is specific to the xterm.js renderer.

Steps to reproduce

  1. On Windows, switch to a CJK IME (e.g. Korean Microsoft IME) so it is active (not in alphanumeric passthrough).
  2. Open any xterm.js instance and focus it.
  3. Press Ctrl+J, Ctrl+C, or Escape.
  4. Observe term.onData — nothing is emitted.

A self-contained dynamic repro (Node + playwright-core, drives the real built bundle and dispatches keydowns with keyCode forced to 229 the way a CJK IME does) is attached at the bottom.

Measured (stock 6.0.0)

keydown code ctrl keyCode onData
Ctrl+J (IME) KeyJ yes 229 (nothing)
Ctrl+C (IME) KeyC yes 229 (nothing)
Ctrl+Space (IME) Space yes 229 (nothing)
Escape (IME) Escape no 229 (nothing)
Ctrl+J (no IME) KeyJ yes 74 0a
Escape (no IME) Escape no 27 1b

Root cause

When a CJK IME claims a key, Windows/Chromium delivers the keydown with keyCode === 229 (the "Process" code) instead of the real value, even for control chords that never open a composition. Two keyCode-based code paths then combine to drop the event:

1. CompositionHelper.keydown swallows every 229 keydown. For a non-composing keydown it hits:

if (ev.keyCode === 229) {
  // non-composition character (eg. numbers and punctuation) with IME active
  this._handleAnyTextareaChanges();
  return false;
}

return false makes CoreBrowserTerminal._keyDown bail before ever calling the keyboard encoder. That path assumes any 229 keydown resolves through a later input/composition event — which is true for printable characters but not for control chords (Ctrl+J, Escape): they produce no input event and no composition, so they're lost.

2. evaluateKeyboardEvent is keyed entirely on keyCode. Even if the event reached it, the switch (ev.keyCode) never matches: Escape is case 27, and Ctrl+<letter> is derived in the default branch from ev.keyCode >= 65 && ev.keyCode <= 90 → String.fromCharCode(ev.keyCode - 64). With keyCode === 229 both fail and no byte is produced.

This is the same underlying issue reported for character loss/duplication under keyCode-229 IMEs (#5887, #6045), but for control keys the failure mode is a total drop rather than a mangled character. The physical ev.code is populated correctly throughout (KeyJ, Escape), so it can be used to recover the intended key.

Impact

Any CJK user (Korean/Japanese/Chinese) running an in-pane TUI that relies on Ctrl+<letter>, Ctrl+Space, or a bare Escape — which is most of them: readline, vim insert→normal, fzf, less, and AI coding TUIs (Claude Code, codex) that use Ctrl+J/Ctrl+Enter for newline-without-submit. The keys work with the IME off and break with it on, which is a confusing, hard-to-attribute failure for end users.

Suggested fix

Recover the intended key from the physical ev.code for exactly the control inputs that get masked, leaving printable/composable keys on the composition path untouched:

  1. In CompositionHelper.keydown, for a non-composing keyCode === 229 keydown, let control inputs (ev.ctrlKey && !ev.altKey && !ev.metaKey, or ev.code === 'Escape') continue to the normal key handler instead of being swallowed.
  2. In evaluateKeyboardEvent, when keyCode === 229, recover the real keyCode from ev.code (Escape → 27, KeyA..KeyZ → 65..90, Space → 32) before the switch, so Escape and the Ctrl+<letter>/Ctrl+Space derivations resolve normally.

Both are gated on the control-key conditions above, so genuine IME composition (which never involves Ctrl and, for a bare key, produces an input/composition event) is unaffected. Happy to put up a PR — a working branch with unit tests and the dynamic repro is ready.

Notes

  • Scoped deliberately to Ctrl+<letter>, Ctrl+Space, and Escape, the inputs with confirmed field reports. Alt/Meta chords are derived from keyCode in the same default branch and are plausibly affected too, but were left out of the initial fix to keep it conservative; they can be added if there's demand.
Standalone dynamic repro (Node + playwright-core)

Run from an xterm.js checkout with lib/xterm.mjs built (npm run esbuild-package) and playwright-core in node_modules:

node repro-ime-229.mjs

On stock 6.0.0 every 229 row prints (nothing); with the fix, Ctrl+J→0a, Ctrl+C→03, Ctrl+Space→00, Escape→1b, while a plain composing key still emits nothing.

/**
 * Dynamic repro for the CJK-IME keyCode-229 control-key drop in xterm.js.
 *
 * Serves a page that loads the built ESM bundle (repo/lib/xterm.mjs), creates a
 * real Terminal, then dispatches synthetic keydown events to the real hidden
 * textarea with keyCode forced to 229 (the value a CJK IME reports) and records
 * what term.onData emits.
 *
 * Run from the xterm.js checkout root (needs lib/xterm.mjs + node_modules):
 *   node <path>/repro-ime-229.mjs
 *
 * Expected on a FIXED build:
 *   Ctrl+J  (keyCode 229, code KeyJ)  -> onData "\n"    (0x0a)
 *   Ctrl+C  (keyCode 229, code KeyC)  -> onData "\x03"  (0x03)
 *   Escape  (keyCode 229, code Escape)-> onData "\x1b"  (0x1b)
 *   plain j (keyCode 229, code KeyJ, no ctrl) -> nothing (left to composition)
 * On STOCK (unfixed) xterm every 229 row emits nothing.
 */
import { createRequire } from 'module';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';
import http from 'http';

// Resolve modules and assets from the checkout root (current working dir).
const root = process.cwd();
const require = createRequire(resolve(root, 'package.json'));
const { chromium } = require('playwright-core');
const xtermMjs = readFileSync(resolve(root, 'lib/xterm.mjs'), 'utf8');
const xtermCss = readFileSync(resolve(root, 'css/xterm.css'), 'utf8');

const PAGE = `<!doctype html><meta charset="utf-8"><style>${xtermCss}
#t{width:800px;height:300px}</style>
<body><div id="t"></div>
<script type="module">
  import { Terminal } from './xterm.mjs';
  const term = new Terminal({ allowProposedApi: true });
  term.open(document.getElementById('t'));
  window.__data = [];
  term.onData(d => window.__data.push(d));
  window.__term = term;
  window.__textarea = term.textarea;
  window.__ready = true;
</script>`;

const server = http.createServer((req, res) => {
  if (req.url.startsWith('/xterm.mjs')) {
    res.setHeader('Content-Type', 'text/javascript');
    res.end(xtermMjs);
    return;
  }
  res.setHeader('Content-Type', 'text/html');
  res.end(PAGE);
});

function hex(s) {
  return [...s].map(c => c.charCodeAt(0).toString(16).padStart(2, '0')).join(' ');
}

await new Promise(r => server.listen(0, r));
const port = server.address().port;

const browser = await chromium.launch();
const page = await browser.newPage();
page.on('console', m => { if (m.type() === 'error') console.log('[page error]', m.text()); });
await page.goto(`http://127.0.0.1:${port}/`);
await page.waitForFunction('window.__ready === true', { timeout: 10000 });
await page.evaluate(() => window.__textarea.focus());

const cases = [
  { name: 'Ctrl+J  (IME)', code: 'KeyJ',  ctrlKey: true,  keyCode: 229 },
  { name: 'Ctrl+C  (IME)', code: 'KeyC',  ctrlKey: true,  keyCode: 229 },
  { name: 'Ctrl+Space(IME)', code: 'Space', ctrlKey: true, keyCode: 229 },
  { name: 'Escape  (IME)', code: 'Escape', ctrlKey: false, keyCode: 229 },
  { name: 'plain j (IME, composing)', code: 'KeyJ', ctrlKey: false, keyCode: 229 },
  // Sanity: real keyCodes still work (regression guard)
  { name: 'Ctrl+J  (no IME)', code: 'KeyJ', ctrlKey: true, keyCode: 74 },
  { name: 'Escape  (no IME)', code: 'Escape', ctrlKey: false, keyCode: 27 }
];

const rows = [];
for (const c of cases) {
  const emitted = await page.evaluate((c) => {
    window.__data.length = 0;
    const ta = window.__textarea;
    const ev = new KeyboardEvent('keydown', {
      bubbles: true, cancelable: true, code: c.code, key: 'Process',
      ctrlKey: c.ctrlKey
    });
    // keyCode is read-only via the constructor; force it like a CJK IME does.
    Object.defineProperty(ev, 'keyCode', { get: () => c.keyCode });
    Object.defineProperty(ev, 'isComposing', { get: () => false });
    ta.dispatchEvent(ev);
    return window.__data.join('');
  }, c);
  rows.push({ name: c.name, emitted });
}

await browser.close();
server.close();

console.log('\n  case                       onData (hex)   onData (repr)');
console.log('  ' + '-'.repeat(60));
for (const r of rows) {
  const h = r.emitted ? hex(r.emitted) : '(nothing)';
  const repr = r.emitted ? JSON.stringify(r.emitted) : '';
  console.log('  ' + r.name.padEnd(26) + ' ' + h.padEnd(14) + ' ' + repr);
}
console.log('');

openwong2kim avatar Jul 24 '26 07:07 openwong2kim

Duplicate of #6065 (same report, opened in error). Closing in favor of #6065, which is already linked to PR #6066.

openwong2kim avatar Jul 24 '26 07:07 openwong2kim