fix(terminal): forward synthesized/dictated text dropped under kitty keyboard protocol (#6513) (#6575)

* fix(terminal): forward synthesized/dictated text dropped under kitty keyboard protocol

With xterm's kitty keyboard protocol active, xterm encodes a printable key
on keydown and preventDefaults it, which cancels Chromium's native
insertText on the helper textarea. The IME punctuation forwarder added in
#6417 was gated to CJK input sources (isEnabled), so on a non-CJK (e.g. U.S.
Latin) input source it never armed and any synthesized text — dictation,
text expanders, accessibility / CGEvent injection — was silently dropped
before reaching the PTY.

Part A: drop the CJK-only gate so the forwarder arms on macOS regardless of
input source (the drop affects every locale, not just CJK punctuation).

Part B: forward a standalone non-composing insertText that no key event
produced. Injected prose/words never satisfy the punctuation-keydown claim
path, so recover them from the helper-textarea input event, guarded against
double-send (key-activity attribution, unresolved claimed press), against
composition (insertCompositionText + composition-commit), and via
stopImmediatePropagation so xterm's own _inputEvent cannot also forward.

Fixes #6513

Co-authored-by: Orca <help@stably.ai>

* fix: broaden terminal injected text forwarding

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-06-28 16:18:56 -07:00
committed by GitHub
co-authored by Orca
parent cea920a3e4
commit 863a5ec09c
3 changed files with 337 additions and 55 deletions
@@ -127,16 +127,26 @@ describe('installTerminalImePunctuationForwarder', () => {
expect(sendInput).toHaveBeenCalledExactlyOnceWith(',')
})
it('does not forward input when no candidate keydown was claimed', () => {
it('forwards a standalone injected insertText that no key event produced', () => {
// Why: dictation / text expanders / accessibility / emoji-picker inserts
// arrive as a bare non-composing insertText with no preceding key event.
// With kitty mode active xterm would drop them on keydown preventDefault,
// so the forwarder recovers them (issue #6513).
const sendInput = vi.fn()
const laterInputListener = vi.fn()
installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
element.addEventListener('input', laterInputListener, true)
textarea.value = '😀'
dispatchInsertText(textarea, '😀')
expect(sendInput).not.toHaveBeenCalled()
expect(sendInput).toHaveBeenCalledExactlyOnceWith('😀')
expect(laterInputListener).not.toHaveBeenCalled()
expect(textarea.value).toBe('')
})
it('does not claim composing keystrokes', () => {
@@ -292,35 +302,173 @@ describe('installTerminalImePunctuationForwarder', () => {
expect(() => forwarder.dispose()).not.toThrow()
})
it('is disabled outside the macOS IME workaround path', () => {
// Part A (issue #6513): the forwarder is no longer gated to CJK input sources,
// so a claimed punctuation insert is forwarded on any (e.g. U.S. Latin) source.
it('forwards a claimed punctuation insert without any input-source gate', () => {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput,
isEnabled: () => false
sendInput
})
expect(forwarder.claimKeyEvent(keyEvent({ key: ',' }))).toBe(false)
dispatchInsertText(textarea, ',')
expect(sendInput).not.toHaveBeenCalled()
})
it('can become enabled after the input source changes to a CJK IME', () => {
const sendInput = vi.fn()
let enabled = false
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput,
isEnabled: () => enabled
})
expect(forwarder.claimKeyEvent(keyEvent({ key: ',' }))).toBe(false)
enabled = true
expect(forwarder.claimKeyEvent(keyEvent({ key: ',' }))).toBe(true)
dispatchInsertText(textarea, '、')
expect(sendInput).toHaveBeenCalledExactlyOnceWith('、')
dispatchInsertText(textarea, ',')
expect(sendInput).toHaveBeenCalledExactlyOnceWith(',')
})
// Part B (issue #6513): arbitrary injected prose, not just punctuation.
describe('injected text with no preceding key event', () => {
it('forwards a multi-character injected phrase exactly once', () => {
const sendInput = vi.fn()
const laterInputListener = vi.fn()
installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
element.addEventListener('input', laterInputListener, true)
textarea.value = 'hello world'
dispatchInsertText(textarea, 'hello world')
expect(sendInput).toHaveBeenCalledExactlyOnceWith('hello world')
expect(laterInputListener).not.toHaveBeenCalled()
expect(textarea.value).toBe('')
})
it('does not forward an insertText that a normally-typed key produced', () => {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
// Letters are not punctuation candidates, so xterm owns the keystroke;
// the keydown→keypress→input sequence must not be re-forwarded.
expect(forwarder.claimKeyEvent(keyEvent({ key: 'a' }))).toBe(false)
expect(forwarder.claimKeyEvent(keyEvent({ type: 'keypress', key: 'a' }))).toBe(false)
dispatchInsertText(textarea, 'a')
expect(sendInput).not.toHaveBeenCalled()
})
it('does not forward when a plain keydown produced the same insert without keypress', () => {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
expect(forwarder.claimKeyEvent(keyEvent({ key: 'a' }))).toBe(false)
dispatchInsertText(textarea, 'a')
expect(sendInput).not.toHaveBeenCalled()
})
it('forwards injected text after a placeholder keydown with no printable key', () => {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
expect(forwarder.claimKeyEvent(keyEvent({ key: 'Unidentified' }))).toBe(false)
dispatchInsertText(textarea, 'dictated text')
expect(sendInput).toHaveBeenCalledExactlyOnceWith('dictated text')
})
it('does not forward an immediate insert after a printable keydown with different text', () => {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
expect(forwarder.claimKeyEvent(keyEvent({ key: 'a' }))).toBe(false)
dispatchInsertText(textarea, 'dictated text')
expect(sendInput).not.toHaveBeenCalled()
})
it('forwards a later injected insert after a printable keydown produced no input', () => {
vi.useFakeTimers()
try {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
expect(forwarder.claimKeyEvent(keyEvent({ key: 'a' }))).toBe(false)
vi.runOnlyPendingTimers()
dispatchInsertText(textarea, 'dictated text')
expect(sendInput).toHaveBeenCalledExactlyOnceWith('dictated text')
} finally {
vi.useRealTimers()
}
})
it('does not forward a composition commit as injected text', () => {
const sendInput = vi.fn()
installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
// compositionupdate fires insertCompositionText; the resolving insertText
// carries the committed glyph but belongs to the IME, not injection.
textarea.dispatchEvent(
new InputEvent('input', { data: 'にほ', inputType: 'insertCompositionText', bubbles: true })
)
dispatchInsertText(textarea, '日本')
expect(sendInput).not.toHaveBeenCalled()
})
it('does not forward while a composition is active', () => {
const sendInput = vi.fn()
installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => true,
sendInput
})
dispatchInsertText(textarea, '日本')
expect(sendInput).not.toHaveBeenCalled()
})
it('forwards a later injected insert after an earlier key press resolved', () => {
const sendInput = vi.fn()
const forwarder = installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
// First a normal typed key (owned by xterm), then a standalone injection.
expect(forwarder.claimKeyEvent(keyEvent({ key: 'a' }))).toBe(false)
dispatchInsertText(textarea, 'a')
dispatchInsertText(textarea, 'dictated')
expect(sendInput).toHaveBeenCalledExactlyOnceWith('dictated')
})
it('does not forward a non-text input type', () => {
const sendInput = vi.fn()
installTerminalImePunctuationForwarder({
terminalElement: element,
isComposing: () => false,
sendInput
})
textarea.dispatchEvent(
new InputEvent('input', { data: null, inputType: 'deleteContentBackward', bubbles: true })
)
expect(sendInput).not.toHaveBeenCalled()
})
})
})
@@ -1,12 +1,23 @@
import type { IDisposable } from '@xterm/xterm'
// Why: many macOS Chinese IMEs commit full-width punctuation (",。?!") via a
// plain `insertText` input event whose preceding keydown still reports the
// half-width ASCII symbol. With xterm's kitty keyboard protocol active, xterm
// encodes+sends that ASCII on keydown and preventDefaults it, so the input
// event carrying the real glyph is dropped and the user gets "," instead of
// ",". We bypass those keydowns so the native input pipeline runs, then forward
// the committed glyph from the input event straight to the PTY.
// Why: with xterm's kitty keyboard protocol active, xterm encodes+sends a
// printable key on keydown and preventDefaults it, which cancels Chromium's
// native `insertText` on the helper textarea. That breaks two related cases on
// macOS:
// 1. CJK IMEs that commit full-width punctuation (",。?!") via a plain
// `insertText` whose preceding keydown still reports the half-width ASCII
// symbol — the user gets "," instead of ",". We bypass those punctuation
// keydowns (claimKeyEvent) so the native input pipeline runs, then forward
// the committed glyph from the input event straight to the PTY.
// 2. OS-level text injection (dictation, text expanders, accessibility,
// CGEvent keyboardSetUnicodeString) that arrives as non-composing
// `insertText` without an immediate printable keyboard text path. xterm's
// preventDefault-on-keydown would otherwise drop it silently. We forward
// that injected text from the input event too.
// In both cases we stopImmediatePropagation so xterm's own `_inputEvent`
// handler cannot also forward the same glyph (it sits on the textarea, a
// descendant, so our capture-phase listener on the terminal element runs
// first).
export type ImePunctuationKeyEvent = {
type: string
@@ -68,11 +79,17 @@ export function isImePunctuationCandidate(
return isAsciiPunctuationKey(event.key)
}
function textFromKeyboardEvent(event: ImePunctuationKeyEvent): string | null {
if (event.ctrlKey || event.altKey || event.metaKey || event.isComposing === true) {
return null
}
return Array.from(event.key).length === 1 ? event.key : null
}
export function installTerminalImePunctuationForwarder(args: {
terminalElement: HTMLElement | null | undefined
isComposing: () => boolean
sendInput: (data: string) => void
isEnabled?: () => boolean
}): TerminalImePunctuationForwarder {
if (!args.terminalElement) {
return {
@@ -84,15 +101,78 @@ export function installTerminalImePunctuationForwarder(args: {
const terminalElement = args.terminalElement
let pendingForward = false
let claimedPress = false
// Why: normal typing can still emit an immediate textarea `insertText`; that
// must not be re-forwarded after xterm already handled the keydown. Track the
// actual printable key briefly instead of treating every key event as ownership
// so arrows/placeholders/stale keydowns do not suppress later OS injection.
let keyboardTextSinceInput: string | null = null
let keypressSinceInput = false
let keyboardAttributionTimer: number | null = null
let suppressNextClaimedInsert = false
let suppressClaimedInsertTimer: number | null = null
// Why: a composition emits `insertCompositionText` (preedit) and resolves with
// a final `insertText` whose committed text belongs to the IME, not injection.
// Mark composition so that resolving commit is not mistaken for injected text.
let compositionInProgress = false
const clearKeyboardAttribution = (): void => {
keyboardTextSinceInput = null
keypressSinceInput = false
if (keyboardAttributionTimer !== null) {
window.clearTimeout(keyboardAttributionTimer)
keyboardAttributionTimer = null
}
}
const scheduleKeyboardAttributionClear = (): void => {
if (keyboardAttributionTimer !== null) {
window.clearTimeout(keyboardAttributionTimer)
}
keyboardAttributionTimer = window.setTimeout(() => {
keyboardAttributionTimer = null
keyboardTextSinceInput = null
keypressSinceInput = false
}, 0)
}
const clearClaimedInsertSuppression = (): void => {
suppressNextClaimedInsert = false
if (suppressClaimedInsertTimer !== null) {
window.clearTimeout(suppressClaimedInsertTimer)
suppressClaimedInsertTimer = null
}
}
const scheduleClaimedInsertSuppressionClear = (): void => {
if (suppressClaimedInsertTimer !== null) {
window.clearTimeout(suppressClaimedInsertTimer)
}
suppressClaimedInsertTimer = window.setTimeout(() => {
suppressClaimedInsertTimer = null
suppressNextClaimedInsert = false
}, 0)
}
const recordKeyboardAttribution = (event: ImePunctuationKeyEvent): void => {
if (event.type !== 'keydown' && event.type !== 'keypress') {
return
}
const keyboardText = textFromKeyboardEvent(event)
if (keyboardText === null) {
clearKeyboardAttribution()
return
}
keyboardTextSinceInput = keyboardText
keypressSinceInput = event.type === 'keypress'
scheduleKeyboardAttributionClear()
}
const claimKeyEvent = (event: ImePunctuationKeyEvent): boolean => {
recordKeyboardAttribution(event)
if (!isImePunctuationCandidate(event, args.isComposing())) {
return false
}
if (event.type === 'keydown') {
if (args.isEnabled?.() === false) {
return false
}
// Arm forwarding so the upcoming input event is sent to the PTY.
pendingForward = true
claimedPress = true
@@ -107,6 +187,11 @@ export function installTerminalImePunctuationForwarder(args: {
// Also bypass so the kitty release sequence for the swallowed press cannot
// leak.
pendingForward = false
clearKeyboardAttribution()
// The claimed press ended without an input commit. Ignore only an
// immediate trailing insert; a later standalone injection should recover.
suppressNextClaimedInsert = true
scheduleClaimedInsertSuppressionClear()
return true
}
if (event.type === 'keypress') {
@@ -117,30 +202,75 @@ export function installTerminalImePunctuationForwarder(args: {
return false
}
const forwardCommittedText = (event: Event): void => {
if (!pendingForward || !(event instanceof InputEvent)) {
return
}
if (event.inputType !== 'insertText') {
pendingForward = false
return
}
pendingForward = false
const sendAndResetTextarea = (event: InputEvent): void => {
if (event.data) {
args.sendInput(event.data)
}
event.stopImmediatePropagation()
// The glyph only landed in xterm's helper textarea because we let the
// keydown reach the native pipeline; clear it back to its empty resting
// state so it cannot accumulate across keystrokes.
// native input pipeline run; clear it back to its empty resting state so it
// cannot accumulate across keystrokes.
if (event.target instanceof HTMLTextAreaElement) {
event.target.value = ''
}
}
const forwardCommittedText = (event: Event): void => {
if (!(event instanceof InputEvent)) {
return
}
const keyboardText = keyboardTextSinceInput
const sawKeypress = keypressSinceInput
const suppressedClaimInsert = suppressNextClaimedInsert
clearKeyboardAttribution()
clearClaimedInsertSuppression()
const wasComposing = compositionInProgress
// Composition inserts belong to xterm's CompositionHelper / the IME preedit;
// leave them alone in every path.
if (event.inputType === 'insertCompositionText') {
pendingForward = false
compositionInProgress = true
return
}
// The composition resolved with this commit; clear the marker so the next
// press starts fresh.
compositionInProgress = false
if (pendingForward) {
pendingForward = false
if (event.inputType !== 'insertText') {
return
}
sendAndResetTextarea(event)
return
}
// Injected text (dictation, text expanders, accessibility, CGEvent
// keyboardSetUnicodeString) arrives as non-composing `insertText` that does
// not belong to the immediate printable keyboard path. With kitty mode active
// xterm would drop it on keydown preventDefault, so forward it here. Skip it
// when xterm (or our claimed punctuation press, still open until keyup)
// already owns this `insertText` to avoid a double-send.
if (
sawKeypress ||
keyboardText !== null ||
suppressedClaimInsert ||
claimedPress ||
wasComposing ||
event.inputType !== 'insertText'
) {
return
}
if (args.isComposing()) {
return
}
sendAndResetTextarea(event)
}
const cancelPending = (): void => {
pendingForward = false
claimedPress = false
clearKeyboardAttribution()
clearClaimedInsertSuppression()
compositionInProgress = false
}
terminalElement.addEventListener('input', forwardCommittedText, true)
@@ -149,6 +279,8 @@ export function installTerminalImePunctuationForwarder(args: {
return {
claimKeyEvent,
dispose: () => {
clearKeyboardAttribution()
clearClaimedInsertSuppression()
terminalElement.removeEventListener('input', forwardCommittedText, true)
terminalElement.removeEventListener('blur', cancelPending, true)
}
@@ -56,7 +56,6 @@ import { showOsc52ClipboardBlockedToast } from './osc52-clipboard-blocked-toast'
import { parseOsc7 } from './parse-osc7'
import { resolveTerminalJisYenInput } from './terminal-jis-yen-input'
import { installTerminalImeCompositionTracker } from './terminal-ime-composition-tracker'
import { getMacCjkInputSourceTracker } from './terminal-ime-input-source'
import { installTerminalImePunctuationForwarder } from './terminal-ime-punctuation-forwarder'
import {
shouldBypassXtermKeyboardEvent,
@@ -733,19 +732,22 @@ export function useTerminalPaneLifecycle({
// See xterm-bypass-policy.ts for the rule derivation.
let pendingTerminalInterruptKeyup = false
const isMac = navigator.userAgent.includes('Mac')
const macCjkInputSourceTracker = isMac ? getMacCjkInputSourceTracker() : null
const imeCompositionTracker = installTerminalImeCompositionTracker(pane.terminal.element)
imeCompositionDisposablesRef.current.set(pane.id, imeCompositionTracker)
// Why: this workaround is for macOS IMEs; elsewhere it can bypass
// xterm's kitty CSI-u encoding for ordinary punctuation. Gate it to CJK
// input sources so direct Japanese/Chinese punctuation works without
// changing plain US/European terminal key handling.
// Why: macOS-only. With xterm's kitty CSI-u encoding active, the
// keydown preventDefault cancels Chromium's native insertText, dropping
// any synthesized printable text — CJK IME punctuation commits AND
// OS-level injection (dictation, text expanders, accessibility). The
// forwarder recovers that text from the helper-textarea input event.
// Not gated to CJK input sources: the drop affects every locale (see
// #6513). Safe for ordinary typing because claimKeyEvent only bypasses
// unmodified ASCII punctuation keydowns, and the injected-text path
// skips the immediate insertText already attributable to keyboard text.
const imePunctuationForwarder = isMac
? installTerminalImePunctuationForwarder({
terminalElement: pane.terminal.element,
isComposing: () => imeCompositionTracker.isActive(),
sendInput: (data) => pane.terminal.input(data),
isEnabled: () => macCjkInputSourceTracker?.isActive() === true
sendInput: (data) => pane.terminal.input(data)
})
: {
claimKeyEvent: () => false,