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

Hidden textarea retains IME-committed text until blur; field-replacing input tools (voice IME) then corrupt input

Open openwong2kim opened this issue 5 months ago • 0 comments

xterm version: @xterm/xterm 6.0.0 (stock lib bundle) Browser/OS: Chromium on Windows 11 (hit in an Electron app, reproduced in plain Chromium)

Summary

The hidden helper textarea is only cleared on blur (_handleTextAreaBlur) and on paste. Text committed through an IME composition stays in textarea.value after it has already been sent through onData. So after typing abc with an IME, the application has received abc, but the textarea still contains abc, and it keeps growing for as long as the terminal stays focused.

That leftover value becomes a real problem with input tools that treat the focused element as an ordinary edit field and "replace" its content instead of inserting at the caret. Voice input from the AutoGLM IME on Windows does this, and we got a downstream report of it wiping the user's already-typed shell line: openwong2kim/wmux#167.

What we measured

We drove the real lib/xterm.js bundle in Chromium via CDP Input.imeSetComposition / Input.insertText and recorded onData bytes. Baseline first: plain keystrokes leave no residue (xterm preventDefaults them), IME-composed text does. Then three field-replacement styles against a textarea holding the residue abc, and all three corrupt input:

  1. Backspace-clear, then commit. The injector sends one Backspace key event per leftover char, then commits the new text. xterm forwards \x7f per backspace, so the application's already-typed line is erased and replaced. This matches the user report exactly. (The textarea itself is untouched because xterm preventDefaults Backspace, so the drift compounds.)
  2. Programmatic value swap plus a keyCode 229 keydown. _handleAnyTextareaChanges sees a shorter value and emits a single \x7f. The replacement text is never sent at all.
  3. Composition with a replacement range over the old text (TSF style). _compositionPosition.start was recorded against the stale value length, so the commit gets sliced: committing voice over a 3-char residue sends just ce.

Why it accumulates

compositionend finalizes and sends the composed text but never resets textarea.value. The comment in _handleTextAreaBlur says text can safely be removed on blur, with screen reader announcements as the reason it is not removed earlier.

Suggested direction

Clear the textarea once a composition has finalized and its data has been sent (when isComposing is false, deferred a tick so it cannot race the _handleAnyTextareaChanges diff). The injector then sees an empty field, has nothing to replace, and the committed text simply inserts. We verified that in the same harness: with the residue gone, the same injection appends cleanly with no \x7f emitted.

Happy to put up a PR if that direction sounds right. The open question is screenReaderMode, which seems to be the reason clearing currently waits for blur, so the clear may need to be gated on that option.

Related: #4173 looks like the same residue mechanism surfacing through Android IME deletes.

Standalone repro script (node, playwright-core)

Serves a page with the stock lib bundle, types through the CDP IME pipeline, records onData, and applies the bytes to a shell-line model so the wipe is directly visible. Run from a checkout that has @xterm/xterm and playwright-core in node_modules.

import { createRequire } from 'module';
import { readFileSync } from 'fs';
import http from 'http';

const require = createRequire(import.meta.url);
const { chromium } = require('playwright-core');

const xtermJs = readFileSync('node_modules/@xterm/xterm/lib/xterm.js', 'utf8');
const xtermCss = readFileSync('node_modules/@xterm/xterm/css/xterm.css', 'utf8');

const PAGE = `<!doctype html><meta charset="utf-8"><style>${xtermCss}</style>
<body><div id="t" style="width:800px;height:300px"></div>
<script>${xtermJs}<\/script>
<script>
  window.__bytes = []; window.__line = '';
  const term = new Terminal({ cols: 80, rows: 10 });
  term.open(document.getElementById('t'));
  term.onData((d) => {
    window.__bytes.push(d);
    for (const ch of d) {
      if (ch === '\\x7f' || ch === '\\b') window.__line = window.__line.slice(0, -1);
      else if (ch >= ' ') window.__line += ch;
    }
  });
  term.focus();
  window.__ta = document.querySelector('.xterm-helper-textarea');
<\/script>`;

const server = http.createServer((_q, res) => { res.setHeader('Content-Type', 'text/html'); res.end(PAGE); });
await new Promise((r) => server.listen(0, '127.0.0.1', r));

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:${server.address().port}`);
await page.waitForFunction(() => !!window.__ta);
const cdp = await page.context().newCDPSession(page);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function imeCommit(text) {
  for (let i = 1; i <= text.length; i++)
    await cdp.send('Input.imeSetComposition', { text: text.slice(0, i), selectionStart: i, selectionEnd: i });
  await cdp.send('Input.insertText', { text });
  await sleep(80);
}

// Type "abc" through the IME. The app received "abc" but the textarea keeps it.
await imeCommit('abc');
console.log('after IME typing:', await page.evaluate(() => ({ line: window.__line, textarea: window.__ta.value })));
// => { line: 'abc', textarea: 'abc' }   <- residue

// A voice tool now "replaces the field": one Backspace per leftover char, then the new text.
for (let i = 0; i < 3; i++) {
  await cdp.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
  await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
}
await imeCommit('voice');
console.log('after injection:', await page.evaluate(() => ({ line: window.__line, bytes: JSON.stringify(window.__bytes.join('')) })));
// => line: 'voice'  (the typed "abc" was wiped by three \x7f forwarded to the app)

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

openwong2kim avatar Jun 09 '26 23:06 openwong2kim