Files
Netcatty/components/terminal/runtime/imeCompositionRewrite.test.ts
T
minmie 10b91f607e fix(terminal): prevent mid-composition IME keydowns from duplicating voice input (#4304)
* fix(terminal): prevent mid-composition IME keydowns from duplicating voice input

Ignore sentinel mid-composition keydowns (keyCode 0 or Unidentified/Process/Dead/Compose) so xterm.js does not call _finalizeComposition(false) before voice ITN/AI polish finishes, preserve early synchronous commit state so trailing compositionend emits only the minimal diff, and track the last committed composition text for in-place consecutive rewrites.

* fix(terminal): invalidate early IME diff on terminal-mutating keys and keep tests ASCII-only

Address PR #4304 review feedback:
- Narrow sentinel keydown detection so non-empty keyCode 0 events (e.g. iOS UIKeyInput arrows) are not swallowed.
- Suppress early-sync backspace diffing and follow-up in-place rewrites when a mid-composition keydown can mutate terminal state or move the PTY cursor (such as ArrowLeft or Home).
- Escape CJK test fixtures as \uXXXX in imeCompositionRewrite.test.ts to preserve ASCII-only source files.
2026-11-23 16:44:31 +08:00

694 lines
22 KiB
TypeScript

import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import {
commitTextareaChange,
continuedCompositionData,
continuedCompositionPrefix,
keepLiveImeTranscriptionSingle,
rememberTextareaCommit,
type ImeCompositionCommitTarget,
} from "./imeCompositionRewrite";
const BACKSPACE = "\x7f";
test("commitTextareaChange appends the new suffix", () => {
assert.equal(commitTextareaChange("\u6211\u662f\u771f\u7684", "\u6211\u662f\u771f\u7684\u725b\u903c"), "\u725b\u903c");
assert.equal(commitTextareaChange("", "\u6211\u662f\u771f\u7684"), "\u6211\u662f\u771f\u7684");
assert.equal(commitTextareaChange("ls ", "ls \uff0c"), "\uff0c");
});
test("commitTextareaChange counts a supplementary-plane character as one grapheme", () => {
const emoji = "\u{1F600}";
const other = "\u{1F601}";
assert.equal(commitTextareaChange(`a${emoji}`, "aX"), `${BACKSPACE}X`);
assert.equal(commitTextareaChange(emoji, other), `${BACKSPACE}${other}`);
assert.equal(commitTextareaChange(`a${emoji}`, "a"), BACKSPACE);
});
test("commitTextareaChange counts only characters forwarded to the terminal", () => {
assert.equal(commitTextareaChange("ab\u200bcd", "abXcd"), `${BACKSPACE}${BACKSPACE}Xcd`);
});
test("commitTextareaChange deletes the whole tail and retypes the new one", () => {
assert.equal(commitTextareaChange("abcd", "abXY"), `${BACKSPACE}${BACKSPACE}XY`);
assert.equal(commitTextareaChange("abcde", "abXde"), `${BACKSPACE}${BACKSPACE}${BACKSPACE}Xde`);
assert.equal(commitTextareaChange("abcd", "ab"), `${BACKSPACE}${BACKSPACE}`);
assert.equal(commitTextareaChange("hello", ""), BACKSPACE);
assert.equal(commitTextareaChange("same", "same"), "");
});
test("rememberTextareaCommit grows a hypothesis and replaces a rewrite", () => {
assert.equal(rememberTextareaCommit("", "", "\u6211\u662f\u771f\u7684"), "\u6211\u662f\u771f\u7684");
assert.equal(rememberTextareaCommit("\u6211\u662f\u771f\u7684", "\u6211\u662f\u771f\u7684", "\u725b\u903c"), "\u6211\u662f\u771f\u7684\u725b\u903c");
assert.equal(
rememberTextareaCommit("abcd", "abcd", `${BACKSPACE}${BACKSPACE}XY`),
"abXY",
);
assert.equal(
rememberTextareaCommit("abcde", "abcde", `${BACKSPACE}${BACKSPACE}${BACKSPACE}Xde`, "abXde"),
"abXde",
);
assert.equal(
rememberTextareaCommit("a\u{1F600}", "a\u{1F600}", `${BACKSPACE}X`),
"aX",
);
assert.equal(rememberTextareaCommit("hello", "hello", BACKSPACE, ""), "");
});
test("continuedCompositionPrefix keeps a new composition after a finished line", () => {
assert.equal(continuedCompositionPrefix(undefined, "\u4f60\u597d"), "");
assert.equal(
continuedCompositionPrefix({
continued: true,
pendingPrevious: "hello\uff0c",
alreadySent: "\uff0c",
textareaAtStart: "hello\uff0c",
}, "\u4f60\u597d"),
"",
);
assert.equal(
continuedCompositionPrefix({
continued: false,
pendingPrevious: "a",
alreadySent: "a",
textareaAtStart: "a",
}, "apple"),
"",
);
assert.equal(
continuedCompositionPrefix({
continued: true,
pendingPrevious: "\u6211",
alreadySent: "\u6211",
textareaAtStart: "\u6211\u771f",
}, "\u6211\u771f"),
"\u6211",
);
});
test("continuedCompositionData rewrites a revised hypothesis instead of appending it", () => {
const marker = {
continued: true,
pendingPrevious: "abcde",
alreadySent: "abcde",
textareaAtStart: "abXde",
};
assert.equal(
continuedCompositionData(marker, "abXde", "abXde", 0),
`${BACKSPACE}${BACKSPACE}${BACKSPACE}Xde`,
);
// The new character starts at the caret after "hello", so this is a new
// composition. The caller sends the slice unchanged.
assert.equal(
continuedCompositionData({
continued: true,
pendingPrevious: "hello",
alreadySent: "",
textareaAtStart: "hello",
}, "\u4f60", "hello\u4f60", 5),
null,
);
// In-place extension of a one-character hypothesis still strips the prefix.
assert.equal(
continuedCompositionData({
continued: true,
pendingPrevious: "\u6211",
alreadySent: "\u6211",
textareaAtStart: "\u6211\u771f",
}, "\u6211\u771f", "\u6211\u771f", 0),
"\u771f",
);
// A new word that merely starts with the finished character is not a prefix.
assert.equal(
continuedCompositionData({
continued: true,
pendingPrevious: "\u6211",
alreadySent: "\u6211",
textareaAtStart: "\u6211\u6211\u4eec",
}, "\u6211\u4eec", "\u6211\u6211\u4eec", 1),
null,
);
});
test("continuedCompositionPrefix returns the hypothesis already on the PTY", () => {
assert.equal(
continuedCompositionPrefix({
continued: true,
pendingPrevious: "\u6211\u662f\u771f\u7684",
alreadySent: "\u6211\u662f\u771f\u7684",
textareaAtStart: "\u6211\u662f\u771f\u7684\u725b\u903c",
}, "\u6211\u662f\u771f\u7684\u725b\u903c"),
"\u6211\u662f\u771f\u7684",
);
assert.equal(
continuedCompositionPrefix({
continued: true,
pendingPrevious: "ls \u6211\u662f\u771f\u7684",
alreadySent: "\u6211\u662f\u771f\u7684",
textareaAtStart: "ls \u6211\u662f\u771f\u7684\u725b\u903c",
}, "ls \u6211\u662f\u771f\u7684\u725b\u903c"),
"ls \u6211\u662f\u771f\u7684",
);
});
type Harness = ImeCompositionCommitTarget & {
compositionstart: () => void;
compositionend: () => void;
keydown: (event: { key?: string; keyCode: number }) => boolean;
sent: string[];
};
function createHarness(): Harness {
const sent: string[] = [];
const helper: Harness = {
_textarea: { value: "" },
_compositionView: { classList: { remove() {} } },
_isComposing: false,
_isSendingComposition: false,
_compositionPosition: { start: 0, end: 0 },
_compositionSuffix: "",
_dataAlreadySent: "",
_coreService: {
triggerDataEvent(data: string) {
sent.push(data);
},
},
sent,
compositionstart() {
this._isComposing = true;
this._compositionPosition = { start: 0, end: this._textarea.value.length };
this._compositionSuffix = "";
this._dataAlreadySent = "";
this._compositionView.classList.remove("active");
},
compositionend() {
this._finalizeComposition?.(true);
},
keydown(event) {
if (this._isComposing || this._isSendingComposition) {
if (event.keyCode === 229 || event.keyCode === 16) return false;
this._finalizeComposition?.(false);
}
if (event.keyCode === 229) {
this._handleAnyTextareaChanges?.();
return false;
}
return true;
},
};
return helper;
}
function install(helper: Harness): void {
keepLiveImeTranscriptionSingle({ _core: { _compositionHelper: helper } });
}
async function flushTimers(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
test("live transcription of one sentence is written once", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211\u662f\u771f\u7684";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211\u662f\u771f\u7684\u725b\u903c";
helper.compositionstart();
helper.compositionend();
await flushTimers();
await flushTimers();
assert.equal(helper.sent.join(""), "\u6211\u662f\u771f\u7684\u725b\u903c");
});
test("a composition range that contains only the new tail is not prefixed again", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ls \u6211\u662f\u771f\u7684";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ls \u6211\u662f\u771f\u7684\u725b\u903c";
helper.compositionstart();
helper._compositionPosition = { start: "ls \u6211\u662f\u771f\u7684".length, end: "ls \u6211\u662f\u771f\u7684\u725b\u903c".length };
helper.compositionend();
await flushTimers();
await flushTimers();
assert.equal(helper.sent.join(""), "ls \u6211\u662f\u771f\u7684\u725b\u903c");
});
test("a composition that only confirms the hypothesis does not append it again", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211\u662f\u771f\u7684\u725b\u903c";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper.compositionstart();
helper.compositionend();
await flushTimers();
await flushTimers();
assert.equal(helper.sent.join(""), "\u6211\u662f\u771f\u7684\u725b\u903c");
});
test("normal compositionend still sends the committed word once", async () => {
const helper = createHarness();
install(helper);
helper._textarea.value = "hello";
helper.keydown({ keyCode: 229 });
helper._textarea.value = "hello\u4f60";
helper.compositionstart();
helper._compositionPosition = { start: 5, end: 6 };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["\u4f60"]);
});
test("punctuation entered through keyCode 229 sends only the new character", async () => {
const helper = createHarness();
install(helper);
helper._textarea.value = "ls ";
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ls \uff0c";
await flushTimers();
assert.deepEqual(helper.sent, ["\uff0c"]);
});
test("keydown text already sent is not repeated on compositionend", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abc";
await flushTimers();
helper._compositionPosition = { start: 0, end: 4 };
helper._textarea.value = "abcd";
helper.compositionend();
await flushTimers();
assert.equal(helper.sent.join(""), "abcd");
});
test("a rewritten hypothesis is not sent again on markerless compositionend", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abcde";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abXde";
await flushTimers();
helper._compositionPosition = { start: 0, end: "abXde".length };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["abcde", BACKSPACE, BACKSPACE, BACKSPACE, "Xde"]);
});
test("an equal-length rewrite does not resend the shared prefix", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abcd";
await flushTimers();
helper.sent.length = 0;
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abXY";
await flushTimers();
assert.deepEqual(helper.sent, [BACKSPACE, BACKSPACE, "XY"]);
});
test("a revised composition replaces the hypothesis already on the PTY", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abcde";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abXde";
helper.compositionstart();
helper.compositionend();
await flushTimers();
await flushTimers();
assert.deepEqual(helper.sent, ["abcde", BACKSPACE, BACKSPACE, BACKSPACE, "Xde"]);
});
test("a one-character hypothesis is not repeated when composition extends it", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211\u771f";
helper.compositionstart();
helper.compositionend();
await flushTimers();
await flushTimers();
assert.equal(helper.sent.join(""), "\u6211\u771f");
});
test("a new word that shares a prefix with a finished character is sent whole", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211\u6211\u4eec";
helper.compositionstart();
helper._compositionPosition = { start: 1, end: "\u6211\u6211\u4eec".length };
helper.compositionend();
await flushTimers();
await flushTimers();
assert.equal(helper.sent.join(""), "\u6211\u6211\u4eec");
});
test("a paused live transcription still extends its previously sent hypothesis", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211\u662f\u771f\u7684";
await flushTimers();
helper.compositionstart();
helper._textarea.value = "\u6211\u662f\u771f\u7684\u725b\u903c";
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["\u6211\u662f\u771f\u7684", "\u725b\u903c"]);
});
test("a later new word with the same prefix is sent whole", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\u6211";
await flushTimers();
helper.compositionstart();
helper._textarea.value = "\u6211\u6211\u4eec";
helper._compositionPosition = { start: 1, end: helper._textarea.value.length };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["\u6211", "\u6211\u4eec"]);
});
test("a sent rewrite is not repeated when its composition later confirms", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ls abcde";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ls abXde";
await flushTimers();
helper.compositionstart();
helper._compositionPosition = { start: 3, end: helper._textarea.value.length };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["ls abcde", BACKSPACE, BACKSPACE, BACKSPACE, "Xde"]);
});
test("an earlier rewrite is delivered when the next composition starts first", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "abcde";
await flushTimers();
helper.compositionstart();
helper._compositionPosition = { start: 0, end: 5 };
helper._textarea.value = "abXde";
helper.compositionend();
helper.compositionstart();
helper._compositionPosition = { start: 5, end: 5 };
helper._textarea.value = "abXdeY";
helper._compositionPosition = { start: 5, end: 6 };
await flushTimers();
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["abcde", BACKSPACE, BACKSPACE, BACKSPACE, "Xde", "Y"]);
});
test("a punctuation commit does not make the next word repeat", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\uff0c";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "\uff0c\u4f60";
await flushTimers();
helper._compositionPosition = { start: 1, end: 2 };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["\uff0c", "\u4f60"]);
});
test("filtered formatting characters do not break final composition deduplication", async () => {
const helper = createHarness();
install(helper);
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ab";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ab\u200b";
await flushTimers();
helper.keydown({ keyCode: 229 });
helper._textarea.value = "ab\u200bX";
await flushTimers();
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, ["ab", "X"]);
});
const VOICE_RAW = "\u6d4b\u8bd5\u7248\u672c\u4e00\u70b9\u4e00\u70b9\u4e5d\u96f6\u4e86";
const VOICE_POLISHED = "\u6d4b\u8bd5\u7248\u672c1.1.90\u4e86";
const VOICE_POLISHED_TAIL = "1.1.90\u4e86";
const VOICE_UTTERANCE = "\u6d4b\u8bd5\u8bed\u97f3\u8f93\u5165\u6587\u672c";
const HELLO = "\u4f60\u597d";
const WORLD = "\u4e16\u754c";
test("mid-composition Unidentified keydown does not prematurely flush before polish", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = VOICE_RAW;
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
assert.equal(helper.keydown({ key: "Unidentified", keyCode: 0 }), false);
assert.deepEqual(helper.sent, []);
helper._textarea.value = VOICE_POLISHED;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [VOICE_POLISHED]);
});
test("mid-composition iOS UIKeyInput arrow with keyCode 0 is not swallowed as a sentinel", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = HELLO;
helper._compositionPosition = { start: 0, end: HELLO.length };
assert.equal(helper.keydown({ key: "UIKeyInputLeftArrow", keyCode: 0 }), true);
assert.deepEqual(helper.sent, [HELLO]);
helper._textarea.value = WORLD;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [HELLO]);
});
test("trailing compositionend after non-terminal early flush emits only the diff", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = VOICE_RAW;
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
// Non-terminal IME mode key that triggers _finalizeComposition(false) without moving PTY cursor
helper.keydown({ key: "Convert", keyCode: 28 });
assert.deepEqual(helper.sent, [VOICE_RAW]);
helper._textarea.value = VOICE_POLISHED;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [
VOICE_RAW,
BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE,
VOICE_POLISHED_TAIL,
]);
});
test("trailing compositionend after non-terminal early flush ignores identical text", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = VOICE_UTTERANCE;
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
helper.keydown({ key: "Convert", keyCode: 28 });
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [VOICE_UTTERANCE]);
});
test("trailing compositionend after ArrowLeft or Home does not emit backspaces against moved cursor", async () => {
for (const keyEvent of [
{ key: "ArrowLeft", keyCode: 37 },
{ key: "Home", keyCode: 36 },
]) {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = VOICE_RAW;
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
assert.equal(helper.keydown(keyEvent), true);
assert.deepEqual(helper.sent, [VOICE_RAW]);
// Final IME text differs after cursor-moving key was handled by xterm
helper._textarea.value = VOICE_POLISHED;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [VOICE_RAW]);
}
});
test("new composition after ArrowLeft early flush does not rewrite the prior utterance", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = HELLO;
helper._compositionPosition = { start: 0, end: HELLO.length };
assert.equal(helper.keydown({ key: "ArrowLeft", keyCode: 37 }), true);
assert.deepEqual(helper.sent, [HELLO]);
// Next composition starts at 0 without a trailing compositionend
helper.compositionstart();
helper._compositionPosition = { start: 0, end: WORLD.length };
helper._textarea.value = WORLD;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [HELLO, WORLD]);
});
test("trailing empty compositionend after Enter cleared textarea sends no backspace", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = HELLO;
helper._compositionPosition = { start: 0, end: HELLO.length };
helper.keydown({ key: "Enter", keyCode: 13 });
helper._textarea.value = "";
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [HELLO]);
});
test("consecutive rewrite composition replaces prior committed utterance in place", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = VOICE_RAW;
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
helper.compositionend();
await flushTimers();
helper.compositionstart();
helper._compositionPosition = { start: 0, end: helper._textarea.value.length };
helper._textarea.value = VOICE_POLISHED;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [
VOICE_RAW,
BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE, BACKSPACE,
VOICE_POLISHED_TAIL,
]);
});
test("consecutive normal compositions starting after committed text still send both words", async () => {
const helper = createHarness();
install(helper);
helper.compositionstart();
helper._textarea.value = HELLO;
helper._compositionPosition = { start: 0, end: HELLO.length };
helper.compositionend();
await flushTimers();
helper.compositionstart();
helper._compositionPosition = { start: HELLO.length, end: HELLO.length };
helper._textarea.value = `${HELLO}${HELLO}`;
helper.compositionend();
await flushTimers();
assert.deepEqual(helper.sent, [HELLO, HELLO]);
});
test("keepLiveImeTranscriptionSingle is a no-op without a composition helper", () => {
assert.doesNotThrow(() => keepLiveImeTranscriptionSingle({}));
const helper = createHarness();
install(helper);
install(helper);
assert.equal(helper.__ncImeCommitInstalled, true);
});
test("createXTermRuntime installs the guard after the composition helper exists", () => {
const source = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "createXTermRuntime.ts"),
"utf8",
);
const openAt = source.indexOf("term.open(ctx.container);");
const installAt = source.indexOf("keepLiveImeTranscriptionSingle(term);");
assert.ok(openAt >= 0);
assert.ok(installAt > openAt);
});