From 7599d4ac02c0482f05118eb5dfcd2f86cab0f9a4 Mon Sep 17 00:00:00 2001 From: Andrei Sviryd Date: Sun, 4 Oct 2026 20:16:44 +0300 Subject: [PATCH 1/2] fix(ime-guard): trust keyCode 229 only inside a live composition context Synthetic 229 keydowns emitted outside any IME (layout-switcher utilities, e.g. KeyRay's layout swap: backspaces + one keydown carrying the whole converted word via CGEventKeyboardSetUnicodeString, which Chromium reports as keyCode 229 / isComposing=false) were swallowed by the document-capture guard, so only the backspaces landed and the replacement text silently disappeared. Now the legacy 229 signal is trusted only while a composition is live, plus a 50ms grace window after compositionend (covers legacy engines' closing 229 keydown with isComposing === false, e.g. Safari). Real IME composition keys (isComposing === true) are unaffected. --- src/client/ime-guard.ts | 41 +++++++++++++++++++++++++++++-- tests/ime-guard.spec.ts | 53 +++++++++++++++++++++++++++++++++++------ 2 files changed, 85 insertions(+), 9 deletions(-) diff --git a/src/client/ime-guard.ts b/src/client/ime-guard.ts index 9cfdca81..11a88557 100644 --- a/src/client/ime-guard.ts +++ b/src/client/ime-guard.ts @@ -23,14 +23,38 @@ * The composition signal follows the DSH core convention (InputBar's IME * guard, issue #535): `isComposing` for modern engines, keyCode 229 as the * legacy signal engines emit without isComposing. + * + * The legacy 229 signal is only trusted while (or right after) a real + * composition is running. Legacy engines (Safari) emit 229 keydowns with + * `isComposing === false` *during* a composition, and that context is what + * distinguishes them from synthetic 229 keydowns emitted outside any IME — + * layout-switcher utilities (e.g. KeyRay's layout swap) send a keydown + * carrying the whole converted word as a multi-character unicode string, + * Chromium reports it as keyCode 229 / isComposing=false, and swallowing it + * made the backspaces land while the replacement text never did: the word + * silently disappeared instead of being rewritten. */ +/** Live composition context, tracked by the guard's composition listeners. */ +let guardComposing = false +/** Grace window (ms) after compositionend that still counts as composition, + * covering legacy engines' closing 229 keydown with isComposing === false. */ +const GUARD_COMPOSITION_END_GRACE_MS = 50 +let guardComposingUntil = 0 + +function imeCompositionLive(): boolean { + return guardComposing || Date.now() < guardComposingUntil +} + /** The pure decision: is this keyboard event part of an IME composition? * `isComposing` is optional on the input: React's synthetic KeyboardEvent * type does not declare it (the DOM event always carries it), and the - * keyCode 229 fallback covers exactly those callers. */ + * keyCode 229 fallback covers exactly those callers — but only inside a + * live composition context (see the module doc above). */ export function isImeComposition(event: { isComposing?: boolean; keyCode: number }): boolean { - return event.isComposing === true || event.keyCode === 229 + if (event.isComposing === true) return true + if (event.keyCode !== 229) return false + return imeCompositionLive() } /** @@ -41,10 +65,23 @@ export function registerImeGuard(): () => void { const onKey = (event: KeyboardEvent): void => { if (isImeComposition(event)) event.stopPropagation() } + const onCompositionStart = (): void => { + guardComposing = true + } + const onCompositionEnd = (): void => { + guardComposing = false + guardComposingUntil = Date.now() + GUARD_COMPOSITION_END_GRACE_MS + } document.addEventListener('keydown', onKey, true) document.addEventListener('keyup', onKey, true) + document.addEventListener('compositionstart', onCompositionStart, true) + document.addEventListener('compositionend', onCompositionEnd, true) return () => { document.removeEventListener('keydown', onKey, true) document.removeEventListener('keyup', onKey, true) + document.removeEventListener('compositionstart', onCompositionStart, true) + document.removeEventListener('compositionend', onCompositionEnd, true) + guardComposing = false + guardComposingUntil = 0 } } diff --git a/tests/ime-guard.spec.ts b/tests/ime-guard.spec.ts index 43758e20..bc19d999 100644 --- a/tests/ime-guard.spec.ts +++ b/tests/ime-guard.spec.ts @@ -3,8 +3,10 @@ * IME-composition guard tests. * * The guard registers document CAPTURE-phase keydown/keyup listeners that - * stopPropagation() while an input method is composing (isComposing or the - * legacy keyCode 229). These tests pin: + * stopPropagation() while an input method is composing (isComposing, or the + * legacy keyCode 229 *inside a live composition context* — bare synthetic + * 229 keydowns from layout-switcher utilities must pass through). These tests + * pin: * * 1. the pure decision (`isImeComposition`); * 2. the native-listener path — a bubble listener on `document` and a @@ -22,7 +24,7 @@ * production — dispatching on `document` itself would run all listeners in * the target phase where stopPropagation does not stop same-node listeners. */ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' @@ -48,8 +50,11 @@ describe('isImeComposition', () => { expect(isImeComposition({ isComposing: true, keyCode: 0 })).toBe(true) }) - it('treats keyCode 229 as composition (legacy engines without isComposing)', () => { - expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(true) + it('treats keyCode 229 as composition only inside a live composition context', () => { + // No composition events were dispatched, so no composition is live: a bare + // synthetic 229 (layout-switcher utilities emit these) must NOT count. + expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(false) + expect(isImeComposition({ isComposing: true, keyCode: 229 })).toBe(true) }) it('treats both signals together as composition', () => { @@ -108,12 +113,46 @@ describe('registerImeGuard — native listeners', () => { expect(seen).toEqual([]) }) - it('blocks composition keys signalled by keyCode 229 only', () => { + it('blocks a keyCode 229 keydown inside a live composition (legacy engines emit 229 with isComposing=false)', () => { dispose = registerImeGuard() - input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', keyCode: 229 })) + document.dispatchEvent(new Event('compositionstart')) + input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: false, keyCode: 229 })) expect(seen).toEqual([]) }) + it('keeps blocking a keyCode 229 keydown right after compositionend (legacy closing keydown)', () => { + vi.useFakeTimers() + try { + dispose = registerImeGuard() + document.dispatchEvent(new Event('compositionstart')) + document.dispatchEvent(new Event('compositionend')) + input.dispatchEvent(keyEvent('keydown', { key: 'a', isComposing: false, keyCode: 229 })) + expect(seen).toEqual([]) + } finally { + vi.useRealTimers() + } + }) + + it('lets a bare synthetic keyCode 229 keydown through when no composition ever started (KeyRay regression)', () => { + dispose = registerImeGuard() + input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: false, keyCode: 229 })) + expect(seen).toEqual(['input:keydown', 'document:keydown']) + }) + + it('lets a keyCode 229 keydown through after the post-compositionend grace window expires', () => { + vi.useFakeTimers() + try { + dispose = registerImeGuard() + document.dispatchEvent(new Event('compositionstart')) + document.dispatchEvent(new Event('compositionend')) + vi.advanceTimersByTime(51) + input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: false, keyCode: 229 })) + expect(seen).toEqual(['input:keydown', 'document:keydown']) + } finally { + vi.useRealTimers() + } + }) + it('still blocks after the composition signal is gone (guard is per-event)', () => { dispose = registerImeGuard() input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: true })) From 9c4b5dada2f3ad12c377ab6398d0f1a7397e2e1a Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 01:54:17 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(ime-guard):=20capture=20=E5=AE=88?= =?UTF-8?q?=E5=8D=AB=E6=94=B6=E7=AA=84=E5=88=B0=20composition=20=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=EF=BC=8CFileTree=20=E4=BF=9D=E7=95=99=E4=BF=9D?= =?UTF-8?q?=E5=AE=88=E7=9A=84=20229=20=E5=88=A4=E5=AE=9A=EF=BC=88#833?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR #845 把 isImeComposition 从「keyCode === 229 无条件算 IME」改成「229 只在 composition 上下文里算 IME」,修好了 #833(KeyRay 布局切换发出的 229 keydown 被 capture 静默吞掉)。但那同一个谓词还被 FileTree 的两处提交处理器当「非拦截式 早退」用,收窄之后 legacy 引擎在组合期发出的裸 229 Enter 会穿透到处理器:输入法 选字时的回车直接把重命名 / 新建文件夹提交掉。(本树实测探针:同一 4 行处理器 形状,用旧谓词 commits=1,用新谓词 commits=0。) 两处口径本来就该不同,因为假阳性代价不同: - capture 守卫的假阳性 = stopPropagation(),全页所有下游监听器都收不到这个键, 正是毁掉 KeyRay 的那一步 → 必须收窄到 composition 窗口。 - FileTree 的假阳性 = 少处理一个键(它不 stopPropagation),假阴性却会提交一个 半成品名字 → 取过近似更划算。 新导出 isLikelyImeKey(isComposing === true || keyCode === 229)承载后者; isImeComposition 保持现状(守卫仍用它,#833 的修复不受本次改动影响)。 宿主旁证:DSH core 两处都是保守形状、且都不 stopPropagation —— ui-user-questions 的 QuestionComposer 完全没有 composition 跟踪,只有 `isComposing || keyCode === 229`;ui-conversation 的 InputBar(issue #535)把 composition ref 与裸 229 做或。所以「保守析取」是宿主口径,本插件是唯一因为 capture 语义而不能照抄的地方 —— 文件头原来那句 follows the DSH core convention 据此改写为两谓词分工。 改动面: - src/client/ime-guard.ts:新导出 + 文件头两谓词分工说明;isImeComposition 的 「the pure decision」措辞改正(它读模块级 composition 状态),实现未动。 - src/client/FileTree.tsx:1536 / :1567:改用 isLikelyImeKey,两处失真注释改准。 - tests/ime-guard.spec.ts:新谓词用例 + FileTree 处理器形状的回归用例(点明它 守的是 FileTree 语义而非 capture 守卫);顺手去掉 :57 与 :61 重复的同一断言。 Refs #833 --- src/client/FileTree.tsx | 16 ++++++---- src/client/ime-guard.ts | 66 ++++++++++++++++++++++++++++++----------- tests/ime-guard.spec.ts | 59 ++++++++++++++++++++++++++++++++---- 3 files changed, 112 insertions(+), 29 deletions(-) diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 5f9f28f1..8c31b7f2 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -53,7 +53,7 @@ import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, type import { FS_TREES_MAX_PATHS } from '../fs-batch.ts' import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx' import { IconUploadOutline16, IconVscode16 } from './icons.tsx' -import { isImeComposition } from './ime-guard.ts' +import { isLikelyImeKey } from './ime-guard.ts' import { useSubmenuFlip } from './menu-flip.ts' import type { OpenInApp, OpenInAppEntry } from './open-in-app.ts' import type { OpenWithTarget } from './open-with.ts' @@ -1512,8 +1512,12 @@ export function FileTree(props: { /** The inline rename editor replacing one row (dirs and files alike): * same indent/icon/height for a seamless swap, Enter/blur commits, - * Escape cancels, IME composition keys never reach the handlers (the - * shared isImeComposition guard). */ + * Escape cancels. Composition keys must not commit the name; this handler + * is a NON-intercepting early return (no stopPropagation), so it asks the + * conservative isLikelyImeKey — the document capture guard only swallows + * keys inside a live composition window by design (bare legacy 229 + * keydowns pass it, #833), which is right for the guard and not enough + * here. */ const renderRenameRow = (entry: FsEntry, depth: number): ReactNode => (
prev === null ? prev : { ...prev, value: event.target.value }) }} onKeyDown={(event) => { - if (isImeComposition(event)) return + if (isLikelyImeKey(event)) return if (event.key === 'Enter') { event.preventDefault() commitRename(entry.path, renaming?.value ?? '') @@ -1549,7 +1553,7 @@ export function FileTree(props: { /** The inline new-folder editor at the top of one level: the same * interaction contract as the rename editor (Enter commits, Escape - * cancels, blur commits, IME guarded). */ + * cancels, blur commits, conservatively IME-guarded). */ const renderNewFolderRow = (dir: string, depth: number): ReactNode => (
{dirRowIcon(dir, true)} @@ -1564,7 +1568,7 @@ export function FileTree(props: { setNewFolder(prev => prev === null ? prev : { ...prev, value: event.target.value }) }} onKeyDown={(event) => { - if (isImeComposition(event)) return + if (isLikelyImeKey(event)) return if (event.key === 'Enter') { event.preventDefault() commitNewFolder(dir, newFolder?.value ?? '') diff --git a/src/client/ime-guard.ts b/src/client/ime-guard.ts index 11a88557..53a340d3 100644 --- a/src/client/ime-guard.ts +++ b/src/client/ime-guard.ts @@ -20,19 +20,36 @@ * composition keys. The browser's native IME processing is untouched: * stopPropagation only silences page JS, not the default action. * - * The composition signal follows the DSH core convention (InputBar's IME - * guard, issue #535): `isComposing` for modern engines, keyCode 229 as the - * legacy signal engines emit without isComposing. + * TWO predicates, deliberately different, because the two kinds of call site + * pay different prices for a false positive: * - * The legacy 229 signal is only trusted while (or right after) a real - * composition is running. Legacy engines (Safari) emit 229 keydowns with - * `isComposing === false` *during* a composition, and that context is what - * distinguishes them from synthetic 229 keydowns emitted outside any IME — - * layout-switcher utilities (e.g. KeyRay's layout swap) send a keydown - * carrying the whole converted word as a multi-character unicode string, - * Chromium reports it as keyCode 229 / isComposing=false, and swallowing it - * made the backspaces land while the replacement text never did: the word - * silently disappeared instead of being rewritten. + * - `isImeComposition` — the capture guard's decision (narrow). A false + * positive here costs `stopPropagation()`: the key is swallowed for EVERY + * downstream listener, page-wide. Trusting a bare legacy 229 outside a + * composition window did exactly that to layout-switcher utilities (#833, + * see below), so 229 only counts while a composition is live. + * - `isLikelyImeKey` — the conservative disjunction + * `isComposing || keyCode === 229`, for NON-intercepting callers that use + * the answer as an early return (FileTree's rename / new-folder commit + * handlers). A false positive there costs one skipped key while a false + * negative commits a half-composed name, so the over-approximation wins. + * + * The conservative shape is also what DSH core itself uses, but only because + * no core call site stops propagation: `QuestionComposer` (ui-user-questions) + * has no composition tracking at all — just `isComposing || keyCode === 229` — + * and `InputBar` (ui-conversation, issue #535) ORs a live composition ref + * with the bare 229. This module is the one place where the wider rule is + * wrong, which is why the narrow decision lives behind its own name here. + * + * The legacy 229 signal is only trusted by the capture guard while (or right + * after) a real composition is running. Legacy engines (Safari) emit 229 + * keydowns with `isComposing === false` *during* a composition, and that + * context is what distinguishes them from synthetic 229 keydowns emitted + * outside any IME — layout-switcher utilities (e.g. KeyRay's layout swap) + * send a keydown carrying the whole converted word as a multi-character + * unicode string, Chromium reports it as keyCode 229 / isComposing=false, and + * swallowing it made the backspaces land while the replacement text never + * did: the word silently disappeared instead of being rewritten. */ /** Live composition context, tracked by the guard's composition listeners. */ @@ -46,17 +63,30 @@ function imeCompositionLive(): boolean { return guardComposing || Date.now() < guardComposingUntil } -/** The pure decision: is this keyboard event part of an IME composition? - * `isComposing` is optional on the input: React's synthetic KeyboardEvent - * type does not declare it (the DOM event always carries it), and the - * keyCode 229 fallback covers exactly those callers — but only inside a - * live composition context (see the module doc above). */ -export function isImeComposition(event: { isComposing?: boolean; keyCode: number }): boolean { +/** The key-event shape both predicates accept. `isComposing` is optional: + * React's synthetic KeyboardEvent type does not declare it (the DOM event + * always carries it). */ +type ImeKeyEvent = { isComposing?: boolean; keyCode: number } + +/** The CAPTURE guard's decision: is this keyboard event part of an IME + * composition? NOT a pure function of its argument — it consults the + * guard's module-level composition state (above) to scope the legacy 229 + * signal. Never reuse it as a generic "is IME" helper: see the module doc + * for why non-intercepting callers want `isLikelyImeKey` instead. */ +export function isImeComposition(event: ImeKeyEvent): boolean { if (event.isComposing === true) return true if (event.keyCode !== 229) return false return imeCompositionLive() } +/** The CONSERVATIVE decision, for non-intercepting callers where misreading a + * composition key costs more than ignoring an ordinary one: a bare 229 counts + * even outside a composition window. Pure — reads no module state, so it + * answers the same before, during and after a composition. */ +export function isLikelyImeKey(event: ImeKeyEvent): boolean { + return event.isComposing === true || event.keyCode === 229 +} + /** * Register the document-level capture guard. Returns the disposer * (HMR-safe; call through `ctx.effect`). diff --git a/tests/ime-guard.spec.ts b/tests/ime-guard.spec.ts index bc19d999..f695000e 100644 --- a/tests/ime-guard.spec.ts +++ b/tests/ime-guard.spec.ts @@ -8,7 +8,10 @@ * 229 keydowns from layout-switcher utilities must pass through). These tests * pin: * - * 1. the pure decision (`isImeComposition`); + * 1. the decision predicates — the capture guard's narrow `isImeComposition` + * (NOT a pure function: it reads the guard's module-level composition + * state) and the conservative `isLikelyImeKey` that non-intercepting + * callers use; * 2. the native-listener path — a bubble listener on `document` and a * target-phase listener on the input must NOT see composition keys, but * must see every other key; @@ -17,7 +20,11 @@ * document-capture listener wins the ordering race against React's * delegation (the mechanism that inlined third-party UI, e.g. Univer's * InputNumber, uses to hijack ArrowUp/ArrowDown); - * 4. the disposer restores normal flow (HMR-safe). + * 4. the disposer restores normal flow (HMR-safe); + * 5. the FileTree shape — a commit handler that early-returns on the + * conservative predicate must not commit a rename on a bare 229 Enter, + * even though the capture guard's predicate deliberately says "not IME" + * for that same event. * * Events are dispatched on a deep element (an `` in `document.body`) * exactly like the browser does, so capture-phase blocking behaves like in @@ -28,7 +35,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' -import { isImeComposition, registerImeGuard } from '../src/client/ime-guard.ts' +import { isImeComposition, isLikelyImeKey, registerImeGuard } from '../src/client/ime-guard.ts' /** Build a KeyboardEvent the way jsdom allows: keyCode/isComposing via defineProperty. */ function keyEvent( @@ -54,10 +61,11 @@ describe('isImeComposition', () => { // No composition events were dispatched, so no composition is live: a bare // synthetic 229 (layout-switcher utilities emit these) must NOT count. expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(false) - expect(isImeComposition({ isComposing: true, keyCode: 229 })).toBe(true) }) - it('treats both signals together as composition', () => { + it('short-circuits on isComposing even when a 229 keyCode rides along', () => { + // The isComposing branch returns before the composition-context lookup, so + // this is true for the same reason as the isComposing-only case above. expect(isImeComposition({ isComposing: true, keyCode: 229 })).toBe(true) }) @@ -67,6 +75,47 @@ describe('isImeComposition', () => { }) }) +describe('isLikelyImeKey — the conservative predicate', () => { + it('treats isComposing as composition', () => { + expect(isLikelyImeKey({ isComposing: true, keyCode: 0 })).toBe(true) + }) + + it('trusts a bare keyCode 229 with no composition context at all', () => { + // This is the whole difference from isImeComposition, and the reason the + // two names exist: no composition event was ever dispatched here. + expect(isLikelyImeKey({ isComposing: false, keyCode: 229 })).toBe(true) + }) + + it('lets ordinary keys through', () => { + expect(isLikelyImeKey({ isComposing: false, keyCode: 40 })).toBe(false) + expect(isLikelyImeKey({ isComposing: false, keyCode: 13 })).toBe(false) + expect(isLikelyImeKey({ isComposing: false, keyCode: 0 })).toBe(false) + }) + + it('a FileTree-shaped commit handler ignores a bare 229 Enter (rename / new folder)', () => { + let commits = 0 + // The shape of FileTree's rename / new-folder onKeyDown: a NON-intercepting + // early return, so a false positive costs one skipped key while a false + // negative commits a half-composed name. This case guards THAT call site's + // semantics, not the capture guard's — the guardian of the document-wide + // stopPropagation is the `isImeComposition` suite above. + const onKeyDown = (event: { key: string; isComposing?: boolean; keyCode: number }): void => { + if (isLikelyImeKey(event)) return + if (event.key === 'Enter') commits += 1 + } + // Legacy engines report the IME-confirming Enter as keyCode 229 with + // isComposing === false; outside a composition window the capture guard's + // predicate answers false for it by design (#833), so a handler that read + // its safety from there would commit the rename. + expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(false) + onKeyDown({ key: 'Enter', isComposing: false, keyCode: 229 }) + expect(commits).toBe(0) + // A real Enter still commits: the guard must not swallow ordinary typing. + onKeyDown({ key: 'Enter', isComposing: false, keyCode: 13 }) + expect(commits).toBe(1) + }) +}) + describe('registerImeGuard — native listeners', () => { let input: HTMLInputElement let dispose: (() => void) | undefined