Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): defer IME slash normalization until composition commits

Xuese915f636dfeb8
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index c5466ffd8..2850fbda0 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -594,9 +594,9 @@ export function Composer({
onAcceptCompletion={completions.acceptCompletion}
onSubmit={(steering) => void submitFromComposer(steering)}
onInsertNewline={insertNewlineInEditor}
- onInput={(source, caret) => {
+ onInput={(source, caret, composing) => {
inputHistory.exitBrowsing();
- completions.handleInput(source, caret);
+ completions.handleInput(source, caret, composing);
}}
onHistoryNavigate={inputHistory.navigate}
onCompositionStart={() => setComposing(true)}
diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsx
index 434172183..973d50edf 100644
--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx
@@ -37,7 +37,7 @@ export type ComposerInputProps = {
onAcceptCompletion: (index: number) => void;
onSubmit: (steering?: boolean) => void;
onInsertNewline: () => void;
- onInput: (source: string, caret: number) => void;
+ onInput: (source: string, caret: number, composing: boolean) => void;
/** Terminal-style recall; returns true when the arrow key was consumed. */
onHistoryNavigate: (direction: "older" | "newer") => boolean;
onCompositionStart: () => void;
@@ -118,13 +118,20 @@ export function ComposerInput({
const element = event.currentTarget;
const source = readEditorValue(element);
const { start } = editorSelectionRange(element);
+ const native = event.nativeEvent as InputEvent;
// An input outside a composition proves the previous one ended,
// even when the IME never sent compositionend (#929).
- if (!(event.nativeEvent as InputEvent).isComposing) onSettledInput();
- onInput(source, start);
+ if (!native.isComposing) onSettledInput();
+ onInput(source, start, native.isComposing);
}}
onCompositionStart={onCompositionStart}
- onCompositionEnd={onCompositionEnd}
+ onCompositionEnd={(event) => {
+ const element = event.currentTarget;
+ const source = readEditorValue(element);
+ const { start } = editorSelectionRange(element);
+ onCompositionEnd(event);
+ onInput(source, start, false);
+ }}
onFocus={onFocus}
onBlur={onBlur}
onKeyDown={(event: ReactKeyboardEvent<HTMLDivElement>) => {
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
index 2fe54e2a3..0777df7a7 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
@@ -80,7 +80,7 @@ export function useComposerCompletions({
referenceSessionId: string;
fileReferencesRef: RefObject<ComposerFileReference[]>;
applyEditorDraft: (text: string, references: ComposerFileReference[], caret: number) => void;
- handleInput: (source: string, caret: number) => string;
+ handleInput: (source: string, caret: number, composing?: boolean) => string;
invalidateComposerTransforms: () => void;
}) {
const host = useComposerAutocomplete({ value, cursor, composing, enabled });
@@ -225,8 +225,8 @@ export function useComposerCompletions({
};
/** The draft's input handler, noting what the user typed. */
- const handleTypedInput = (source: string, caret: number) => {
- setTypedValue(handleInput(source, caret));
+ const handleTypedInput = (source: string, caret: number, composing = false) => {
+ setTypedValue(handleInput(source, caret, composing));
};
return { ac, acceptCompletion, handleInput: handleTypedInput };
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
index 33e31021a..2961744f0 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
@@ -63,7 +63,7 @@ export type ComposerDraftController = {
cursor: number;
setCursor: Dispatch<SetStateAction<number>>;
composing: boolean;
- setComposing: Dispatch<SetStateAction<boolean>>;
+ setComposing: (next: boolean) => void;
inputFocused: boolean;
setInputFocused: Dispatch<SetStateAction<boolean>>;
placeholderIndex: number;
@@ -75,7 +75,7 @@ export type ComposerDraftController = {
referenceByTokenRef: { current: Map<string, ComposerFileReference> };
removeChipByTokenRef: { current: (token: string) => void };
updateCursor: (next: number) => void;
- handleInput: (source: string, caret: number) => string;
+ handleInput: (source: string, caret: number, composing?: boolean) => string;
readLiveDraft: () => string;
persistDraft: (key?: string) => void;
paintCurrentDraft: (element: HTMLElement, nextValue: string) => void;
@@ -153,7 +153,7 @@ export function useComposerDraft({
// cursor so autocomplete trigger detection stays quiet.
const updateCursor = (next: number) =>
setCursor((current) => (current === next ? current : next));
- const [composing, setComposing] = useState(false);
+ const [composing, setComposingState] = useState(false);
const [inputFocused, setInputFocused] = useState(false);
const [placeholderIndex, setPlaceholderIndex] = useState(0);
const ref = useRef<HTMLDivElement>(null);
@@ -173,6 +173,13 @@ export function useComposerDraft({
const valueRef = useRef(value);
valueRef.current = value;
+ const compositionRef = useRef<{ draftKey: string; empty: boolean } | null>(null);
+ const setComposing = (next: boolean) => {
+ if (next) {
+ compositionRef.current = { draftKey: draftKeyRef.current, empty: valueRef.current === "" };
+ }
+ setComposingState(next);
+ };
const fileReferencesRef = useRef(fileReferences);
fileReferencesRef.current = fileReferences;
@@ -181,6 +188,7 @@ export function useComposerDraft({
const current = valueRef.current;
const next = typeof action === "function" ? action(current) : action;
if (next !== current) {
+ compositionRef.current = null;
markComposerDraftEdited(draftKeyRef.current);
valueRef.current = next;
}
@@ -339,11 +347,18 @@ export function useComposerDraft({
removeChipByTokenRef.current = removeChipByToken;
/** Commit a native contenteditable input while preserving IME correction. */
- const handleInput = (source: string, caret: number): string => {
+ const handleInput = (source: string, caret: number, composingInput = false): string => {
+ if (composingInput && compositionRef.current?.draftKey !== draftKeyRef.current) {
+ compositionRef.current = { draftKey: draftKeyRef.current, empty: valueRef.current === "" };
+ }
+ // Pre-edit updates already change valueRef; retain whether this composition began empty.
+ const startedEmpty =
+ compositionRef.current?.draftKey === draftKeyRef.current && compositionRef.current.empty;
const nextValue =
- valueRef.current === ""
+ !composingInput && (valueRef.current === "" || startedEmpty)
? rewriteIdeographicCommaTrigger(source)
: source;
+ if (!composingInput) compositionRef.current = null;
markComposerDraftEdited(draftKeyRef.current);
invalidateComposerTransforms();
if (nextValue === source) {
@@ -366,6 +381,7 @@ export function useComposerDraft({
if (!element) return;
const nextValue = readEditorValue(element);
const { start } = editorSelectionRange(element);
+ compositionRef.current = null;
markComposerDraftEdited(draftKeyRef.current);
invalidateComposerTransforms();
editorValueRef.current = nextValue;
@@ -397,6 +413,7 @@ export function useComposerDraft({
useEffect(() => {
const previousKey = draftKeyRef.current;
if (previousKey !== draftKey) {
+ compositionRef.current = null;
invalidateComposerTransforms();
persistDraft(previousKey);
if (previousKey === HOME_DRAFT_KEY) flushScheduledHomeDraftAdopt(draftKey);
@@ -472,6 +489,7 @@ export function useComposerDraft({
// A remount restores this workspace's draft; only a real workspace change
// invalidates its relative file references.
if (previousWorkspacePathRef.current === workspacePath) return;
+ compositionRef.current = null;
previousWorkspacePathRef.current = workspacePath;
const current = fileReferencesRef.current;
// Plugin marks carry their text, not a workspace path, and a session
@@ -515,6 +533,7 @@ export function useComposerDraft({
useEffect(() => {
if (!composerPrefill || composerPrefill.sessionId !== activeSessionId) return;
+ compositionRef.current = null;
markComposerDraftEdited(draftKeyForSession(composerPrefill.sessionId));
const prefilledReferences = composerPrefill.fileReferences.map((fileReference) =>
createFileReferenceFromSnapshot(fileReference, composerPrefill.sessionId),
@@ -538,6 +557,7 @@ export function useComposerDraft({
useEffect(() => {
if (!prefill?.text) return;
+ compositionRef.current = null;
markComposerDraftEdited(draftKeyRef.current);
setValue(prefill.text);
setFileReferences([]);
@@ -555,6 +575,7 @@ export function useComposerDraft({
caret: number,
focus = true,
) => {
+ compositionRef.current = null;
const entered = attachImageTokens(nextText, nextReferences, nextChipToken);
nextText = entered.text;
nextReferences = entered.references;
diff --git a/apps/desktop/test/composer-deep-file-search-user-path.test.mjs b/apps/desktop/test/composer-deep-file-search-user-path.test.mjs
index 0f48b018e..b02199a5d 100644
--- a/apps/desktop/test/composer-deep-file-search-user-path.test.mjs
+++ b/apps/desktop/test/composer-deep-file-search-user-path.test.mjs
@@ -87,7 +87,7 @@ function Fixture() {
inputBlocked={false} pasting={false} enterToSend={false} runActive={false}
composerAc={completions.ac} onPaste={noop} onAcceptCompletion={completions.acceptCompletion}
onSubmit={noop} onInsertNewline={noop} onHistoryNavigate={() => false}
- onInput={(source, caret) => completions.handleInput(source, caret)}
+ onInput={(source, caret, composing) => completions.handleInput(source, caret, composing)}
onCompositionStart={() => draft.setComposing(true)}
onCompositionEnd={() => draft.setComposing(false)}
onSettledInput={() => draft.setComposing(false)} onFocus={noop} onBlur={noop} />
diff --git a/apps/desktop/test/composer-ime.test.mjs b/apps/desktop/test/composer-ime.test.mjs
index 583e04ba7..7abbc081f 100644
--- a/apps/desktop/test/composer-ime.test.mjs
+++ b/apps/desktop/test/composer-ime.test.mjs
@@ -97,13 +97,13 @@ test("a dropped compositionend cannot leave the composer composing forever (#929
);
assert.match(
handler,
- /if \(!\(event\.nativeEvent as InputEvent\)\.isComposing\) onSettledInput\(\);/,
+ /if \(!native\.isComposing\) onSettledInput\(\);/,
"a settled input must clear the composing flag",
);
// It has to run before the draft update, so the very same input is judged
// against a cleared flag rather than the stale one.
assert.ok(
- handler.indexOf("onSettledInput()") < handler.indexOf("onInput(source, start)"),
+ handler.indexOf("onSettledInput()") < handler.indexOf("onInput(source, start, native.isComposing)"),
"the recovery must precede the draft update",
);
});
diff --git a/apps/desktop/test/composer-input-history.test.mjs b/apps/desktop/test/composer-input-history.test.mjs
index d2b8bf83d..12cc004c5 100644
--- a/apps/desktop/test/composer-input-history.test.mjs
+++ b/apps/desktop/test/composer-input-history.test.mjs
@@ -317,7 +317,7 @@ test("the composer wires recall, its exits, and the record point (AC3)", async (
assert.match(hook, /loadHistory: \(\) => loadComposerInputHistory\(referenceSessionId\)/);
assert.match(hook, /draft\.draftRevision\(draftKey\) !== appliedRevisionRef\.current/);
assert.match(hook, /useEffect\(\(\) => \{\s*exitBrowsing\(\);\s*\}, \[draftKey\]\);/);
- assert.match(composer, /onInput=\{\(source, caret\) => \{\s*inputHistory\.exitBrowsing\(\);/);
+ assert.match(composer, /onInput=\{\(source, caret, composing\) => \{\s*inputHistory\.exitBrowsing\(\);/);
assert.match(composer, /onHistoryNavigate=\{inputHistory\.navigate\}/);
assert.match(composer, /recordHistory: inputHistory\.record/);
// Both submit entry points — the composer's Enter and the toolbar's Send —
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index d77090493..1135d7308 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -1,5 +1,8 @@
# Unreleased changes
+- Fixed duplicate `/、` when opening slash commands with a Chinese IME in an
+ empty composer. Keep pre-edit text intact and apply the slash alias only
+ after composition commits, preserving recovery from a missing end event.
- Add OpenAI Fast mode (#1657). Allow it per model in Settings → Models for a
ChatGPT subscription or an OpenAI Responses connection, then type `/fast` to
turn it on for the current conversation. Requests ask for the priority
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 4e3d9574e..7a75caa64 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -1547,6 +1547,10 @@ Project drag/drop follows these patterns:
that is not part of a composition also ends the composition, so an IME that
drops `compositionend` (a Windows Chinese IME deleting its composing text)
cannot leave the menu frozen until the composer unmounts (#929).
+- Composing input updates the draft without rewriting the leading `、` or
+ repainting its native text nodes. On `compositionend`, read the final editor
+ text and apply the slash alias once if composition began in an empty draft.
+ This prevents the IME's commit from appending `、` after an already painted `/`.
- Enter that confirms an IME candidate never sends and never accepts a menu
item; ↑/↓ during candidate navigation belong to the IME.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f9695ddb9..55ded6cb5 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -16500,24 +16500,34 @@ plugin-form fixtures in an isolated temporary directory at runtime.
and at least one slash entry exists (builtin alias, template, plugin command,
or Skill).
- **Steps**:
- 1. With the draft empty, type `、` and inspect the composer.
+ 1. With the draft empty, compose `、`, inspect the pre-edit text, then commit.
2. Continue typing a command name and accept the highlighted row.
3. Type a draft that contains `、` between other characters.
4. Send a draft whose first character was typed as `、` without accepting any
row.
+ 5. Cancel a composition, then type `/` again. Also delete text after a
+ dropped `compositionend` and confirm the slash menu still reopens.
- **Expected**: The committed `、` is rewritten to `/` in place, the ordinary
slash menu opens with the same filtering and keyboard behavior as a typed
`/`, and the caret stays after the substituted character. A `、` anywhere
later in the draft stays untouched text, and the `@` file menu never reacts
- to the mark.
+ to the mark. Pre-edit `、` remains unchanged until commit; the result is `/`,
+ never `/、`. Ordinary Chinese composition and punctuation in existing drafts
+ remain unchanged. Cancelling leaves a blank draft, and replacing the draft
+ releases the old composition's empty-draft origin.
- **Specs linked**: `04-ux/04-builtin-commands.md` (§9),
`04-ux/08-component-spec.md` (§11), `08-meta/decisions-log.md` (D405),
ADR 0024, ADR 0231
- **Acceptance**: C (conversation & stream), Localization, Quality
- **Milestone**: M2
-- **Status**: Unit-covered (`packages/shared/src/composer-trigger.test.ts`,
- `apps/desktop/test/composer-ime.test.mjs`); rendered desktop journey Draft
- (run only in a capable environment when this surface changes)
+- **Status**: Partially automated. Unit coverage:
+ `packages/shared/src/composer-trigger.test.ts`,
+ `apps/desktop/test/composer-ime.test.mjs`. Rendered Electron coverage:
+ `node scripts/e2e-composer-ime-stack.mjs` mounts the production input, draft,
+ and completion components, drives Chromium composition through CDP, and
+ covers alias commit, ordinary Chinese text, cancellation, draft replacement,
+ completion acceptance, and lost-end recovery. Sending and a physical OS IME
+ candidate window remain manual checks.
#### E2E-256: Empty-home project name switches among sidebar projects
diff --git a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
index 3b4511e34..83f782fc7 100644
--- a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
+++ b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
@@ -1105,6 +1105,9 @@ Mode/provider/model/permission/shell 配置和新提示仍然存在
也不关闭菜单;状态重新评估 `compositionend`。不属于合成中的输入事件同样
表示合成已结束,因此当 IME 丢失 `compositionend`(Windows 中文输入法删除
正在合成的文本)时,菜单不会被永久冻结到组件卸载为止(#929)。
+- 组字输入同步更新草稿,但不改写开头的「、」,也不重绘输入法正在使用的文本节点。
+ `compositionend` 时读取编辑区最终文本;若本次组字从空草稿开始,再执行一次斜杠别名
+ 转换,避免输入法提交时在提前绘制的 `/` 后追加「、」。
- 输入确认 IME 候选者从不发送且从不接受菜单
项目;候选导航期间的 ↑/↓ 属于 IME。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 18daa323b..76d37dd6c 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -8537,15 +8537,16 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture
- **前提条件**:可用中文输入法;输入框草稿为空;至少存在一条斜杠条目(内置别名、模板、插件命令或 Skill)。
- **步骤**:
- 1. 保持草稿为空,输入「、」并观察输入框。
+ 1. 保持草稿为空,开始组字「、」,观察临时文本,再提交组合输入。
2. 继续输入命令名并确认高亮行。
3. 输入一段在其他字符之间包含「、」的草稿。
4. 发送一段首字符为「、」且未确认任何行的草稿。
-- **预期**:「、」被就地改写为 `/`,普通斜杠菜单以与直接输入 `/` 相同的过滤和键盘行为打开,光标停留在替换后的字符之后。出现在草稿其他位置的「、」保持原样,`@` 文件菜单不会对该标点作出反应。
+ 5. 取消组字后再次输入 `/`;另模拟丢失 `compositionend` 后删除文本,确认斜杠菜单仍能打开。
+- **预期**:提交的「、」被就地改写为 `/`,普通斜杠菜单以与直接输入 `/` 相同的过滤和键盘行为打开,光标停留在替换后的字符之后。出现在草稿其他位置的「、」保持原样,`@` 文件菜单不会对该标点作出反应。组字期间「、」保持原样,提交后结果为 `/`,不会出现 `/、`;普通中文组字和已有草稿中的标点不变。取消组字留下空白草稿,替换草稿会清除原有的空草稿组字起始状态。
- **链接规格**:`04-ux/04-builtin-commands.md`(§9)、`04-ux/08-component-spec.md`(§11)、`08-meta/decisions-log.md`(D405)、ADR 0024、ADR 0231
- **验收**:C(对话与流)、本地化、品质
- **里程碑**:M2
-- **状态**:单元覆盖(`packages/shared/src/composer-trigger.test.ts`、`apps/desktop/test/composer-ime.test.mjs`);渲染桌面旅程为草稿(除非明确要求,不本地运行 E2E)
+- **状态**:部分自动化。单元覆盖:`packages/shared/src/composer-trigger.test.ts`、`apps/desktop/test/composer-ime.test.mjs`。`node scripts/e2e-composer-ime-stack.mjs` 挂载生产输入框、草稿和补全组件,通过 CDP 驱动 Chromium 组合输入,覆盖别名提交、普通中文、取消组字、草稿替换、补全确认及丢失结束事件后的恢复。发送流程和真实操作系统输入法候选窗口仍需手动验证。
#### E2E-CLONE-accepts-a-lan-remote-and-rejects-metadata
diff --git a/scripts/e2e-composer-ime-stack.mjs b/scripts/e2e-composer-ime-stack.mjs
index 771f58032..0e78cbeb9 100644
--- a/scripts/e2e-composer-ime-stack.mjs
+++ b/scripts/e2e-composer-ime-stack.mjs
@@ -1,10 +1,10 @@
#!/usr/bin/env node
/**
- * Real React/Chromium regression for #929: after a Chinese IME leaves "/、" in
- * the composer, deleting it and typing "/" again must reopen the slash menu.
+ * Real React/Chromium regressions: native composition must produce "/", not
+ * "/、", and deleting text after a missing compositionend must reopen the menu.
*
- * The probe drives `useComposerAutocomplete` itself, so a red result is the
- * real hook refusing to reopen, not a stub standing in for it.
+ * Mount production input, draft and completion wiring; drive native Chromium
+ * composition through CDP as well as the lost-end event sequence from #929.
*/
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
@@ -59,13 +59,65 @@ try {
`
const { app, BrowserWindow } = require("electron");
const path = require("node:path");
+const assert = require("node:assert/strict");
app.setPath("userData", path.join(__dirname, "profile"));
app.whenReady().then(async () => {
- const window = new BrowserWindow({ show: false, width: 1040, height: 760, webPreferences: { backgroundThrottling: false, sandbox: true, contextIsolation: true, nodeIntegration: false } });
+ const window = new BrowserWindow({ show: false, width: 1040, height: 760, webPreferences: { offscreen: true, backgroundThrottling: false, sandbox: true, contextIsolation: true, nodeIntegration: false } });
window.webContents.on("console-message", (event) => console.error(event.message));
try {
await window.loadFile(path.join(__dirname, "index.html"));
const result = await window.webContents.executeJavaScript("globalThis.composerImeStackProbe()");
+ assert.equal(result.ok, true, "existing IME recovery and completion paths must pass");
+ window.webContents.debugger.attach("1.3");
+ const js = expression => window.webContents.executeJavaScript(expression);
+ const input = (method, params) => window.webContents.debugger.sendCommand("Input." + method, params);
+ const state = () => js("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(globalThis.composerImeState()))))");
+ const reset = async (text = "") => {
+ await js("globalThis.composerImeSetDraft(" + JSON.stringify(text) + ")");
+ await state();
+ };
+ const expectText = (snapshot, expected, label) => {
+ assert.equal(snapshot.dom, expected, label + " DOM: " + JSON.stringify(snapshot));
+ assert.equal(snapshot.value, expected, label + " draft: " + JSON.stringify(snapshot));
+ };
+ const composed = async (prefix, candidate, committed, expected) => {
+ await reset(prefix);
+ await input("imeSetComposition", { text: candidate, selectionStart: candidate.length, selectionEnd: candidate.length });
+ const pending = await state();
+ expectText(pending, prefix + candidate, "pending composition must keep the native text");
+ assert.equal(pending.composing, true);
+ await input("insertText", { text: committed });
+ const settled = await state();
+ expectText(settled, expected, "committed composition");
+ assert.equal(settled.caret, expected.length, "committed composition must retain the caret");
+ assert.equal(settled.composing, false);
+ return settled;
+ };
+ const slash = await composed("", "、", "、", "/");
+ assert.equal(slash.open, true, "committed comma must open the slash menu");
+ await composed("", "ni", "你", "你");
+ await composed("你好", "、", "、", "你好、");
+ await composed("、原文", "ni", "你", "、原文你");
+ await reset();
+ await input("imeSetComposition", { text: "、", selectionStart: 1, selectionEnd: 1 });
+ await state();
+ await input("imeSetComposition", { text: "", selectionStart: 0, selectionEnd: 0 });
+ const cancelled = await state();
+ assert.equal(cancelled.dom, "", "cancelled composition must leave no visible text");
+ assert.equal(cancelled.value.trim(), "", "cancelled composition must leave a blank draft");
+ assert.equal(cancelled.composing, false);
+ for (const text of ["/", "、"]) {
+ await reset();
+ await input("insertText", { text });
+ expectText(await state(), "/", "direct trigger " + text);
+ }
+ await reset();
+ await input("imeSetComposition", { text: "n", selectionStart: 1, selectionEnd: 1 });
+ await state();
+ await reset("、保留");
+ await input("insertText", { text: "你" });
+ expectText(await state(), "、保留你", "a draft replacement must release the old composition origin");
+ result.nativeComposition = true;
console.log("COMPOSER_IME_STACK_PROBE " + JSON.stringify(result));
app.exit(result && result.ok ? 0 : 1);
} catch (error) {
@@ -109,7 +161,7 @@ app.whenReady().then(async () => {
` step ${String(step.label).padEnd(20)} draft=${JSON.stringify(step.draftValue)} composing=${step.composing} -> open=${step.open} hasItems=${step.hasItems} mode=${step.mode} query=${JSON.stringify(step.query)}`,
);
}
- console.log("COMPOSER_IME_STACK_PROBE " + JSON.stringify({ ok: result.ok }));
+ console.log("COMPOSER_IME_STACK_PROBE " + JSON.stringify({ ok: result.ok, nativeComposition: result.nativeComposition }));
assert.equal(code, 0, output.slice(-6000));
assert.equal(result.ok, true, "the slash menu did not reopen after the IME draft was cleared");
} finally {
diff --git a/scripts/e2e/composer-ime-stack.tsx b/scripts/e2e/composer-ime-stack.tsx
index 64b67f4bb..547de2fe0 100644
--- a/scripts/e2e/composer-ime-stack.tsx
+++ b/scripts/e2e/composer-ime-stack.tsx
@@ -19,10 +19,18 @@ import { useComposerCompletions } from "../../apps/desktop/src/features/chat/com
import { ComposerInput } from "../../apps/desktop/src/features/chat/composer/ComposerInput";
import { ComposerAutocomplete } from "../../apps/desktop/src/components/ComposerAutocomplete";
import { api } from "../../apps/desktop/src/lib/api";
-import { setEditorCaret } from "../../apps/desktop/src/features/chat/composer/editor";
+import { editorSelectionRange, setEditorCaret } from "../../apps/desktop/src/features/chat/composer/editor";
declare global {
var composerImeStackProbe: () => Promise<unknown>;
+ var composerImeSetDraft: (text: string) => void;
+ var composerImeState: () => {
+ value: string;
+ dom: string;
+ caret: number;
+ composing: boolean;
+ open: boolean;
+ };
}
api.composerCommands = async () => ({
@@ -55,7 +63,7 @@ function Fixture() {
composerPrefill: null,
clearComposerPrefill: noop,
t,
- invalidatePromptEnhancement: noop,
+ invalidateComposerTransforms: noop,
inputBlocked: false,
});
const completions = useComposerCompletions({
@@ -67,10 +75,14 @@ function Fixture() {
fileReferencesRef: draft.fileReferencesRef,
applyEditorDraft: draft.applyEditorDraft,
handleInput: draft.handleInput,
- invalidatePromptEnhancement: noop,
+ invalidateComposerTransforms: noop,
});
draftValue = draft.value;
draftComposing = draft.composing;
+ globalThis.composerImeSetDraft = (text) => {
+ draft.setComposing(false);
+ draft.applyEditorDraft(text, [], text.length);
+ };
acState = {
open: completions.ac.open,
hasItems: completions.ac.hasItems,
@@ -93,7 +105,7 @@ function Fixture() {
onSubmit={noop}
onInsertNewline={noop}
onHistoryNavigate={() => false}
- onInput={(source, caret) => completions.handleInput(source, caret)}
+ onInput={(source, caret, composing) => completions.handleInput(source, caret, composing)}
onCompositionStart={() => draft.setComposing(true)}
onCompositionEnd={() => draft.setComposing(false)}
onSettledInput={() => draft.setComposing(false)}
@@ -121,6 +133,14 @@ const settle = async () => {
const editor = () => document.querySelector<HTMLElement>(".composer-input")!;
+globalThis.composerImeState = () => ({
+ value: draftValue,
+ dom: editor().textContent ?? "",
+ caret: editorSelectionRange(editor()).start,
+ composing: draftComposing,
+ open: acState.open,
+});
+
/**
* Replace the editor text and fire the events an IME fires.
* `endComposition: false` models an IME that never reports the end.
diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsx
index cecde6cd6..3374a389a 100644
--- a/scripts/e2e/composer-paste.tsx
+++ b/scripts/e2e/composer-paste.tsx
@@ -64,7 +64,7 @@ function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunct
composerPrefill: null,
clearComposerPrefill: noop,
t,
- invalidatePromptEnhancement: noop,
+ invalidateComposerTransforms: noop,
inputBlocked: false,
});
controller = draft;
@@ -118,7 +118,7 @@ function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunct
onSubmit={(steering) => { latestSubmission = submitFromComposer(steering); }}
onHistoryNavigate={inputHistory.navigate}
onInsertNewline={draft.insertNewlineInEditor}
- onInput={(source, caret) => { inputHistory.exitBrowsing(); draft.handleInput(source, caret); }}
+ onInput={(source, caret, composing) => { inputHistory.exitBrowsing(); draft.handleInput(source, caret, composing); }}
onCompositionStart={noop}
onCompositionEnd={noop}
onSettledInput={() => draft.setComposing(false)}