Skip to content

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

fix(chat): preserve editing and search during IME Escape

yuxino0feb4b9ec628
diff --git a/apps/desktop/src/components/SearchDialog.tsx b/apps/desktop/src/components/SearchDialog.tsx
index b514bb9cd..e1b389cbb 100644
--- a/apps/desktop/src/components/SearchDialog.tsx
+++ b/apps/desktop/src/components/SearchDialog.tsx
@@ -321,6 +321,7 @@ export function SearchDialog({ open, onClose }: { open: boolean; onClose: () =>
aria-label={t("nav.search")}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
// Escape must close even when focus left the input (e.g. tabbing).
if (event.key === "Escape") {
event.preventDefault();
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
index 7902c378b..8f9a9748d 100644
--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
@@ -154,6 +154,7 @@ export const MessageRow = memo(function MessageRow({
disabled={retryingEdit}
onChange={(event) => setEditValue(event.target.value)}
onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Escape") {
cancelEdit();
} else if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 12ecac6ad..3054e9715 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1558,7 +1558,8 @@ storage but compose into one assistant turn until the next user message.
Loading and failure states must not masquerade as an empty result.
- Keep page, settings, and command results available. Arrow keys and Enter
navigate session headings, snippets, Load more, and the existing result
- types. IME composition Enter must not activate a result.
+ types. IME composition Enter must not activate a result; Escape during
+ composition must not close search, including events bubbling from its input.
### 7.6 MVP constraints
@@ -1742,7 +1743,8 @@ Single message render — either user (plaintext) or assistant (markdown streami
composer lift would be cut off at the plate edges (D297: in-flow surfaces
use tone, not stroke). Focus paints an inset 2px accent ring. The textarea
is unboxed inside that plate; localized Retry and Cancel sit in a 28px footer
- (Escape cancels, Cmd/Ctrl+Enter retries; slash turns seed the typed
+ (Escape cancels, Cmd/Ctrl+Enter retries; both shortcuts are ignored during
+ IME composition, preserving the draft; slash turns seed the typed
`command` form so retrying re-expands the template). Opening it widens the
user column to the assistant reading width and hides the action toolbar.
Retry runs the Regenerate path with the current text in the same session,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 996981fdb..c91fcad1f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -14286,3 +14286,9 @@ the latest destination. These assertions measure work counts, not device FPS.
- **Expected**: The complete URL, including `(software)`, opens the React software article. The outer prose closing parenthesis and sentence-ending punctuation after the URL parenthesis are not part of the link. Adjacent references remain independently clickable. Nested parentheses, query/fragment parentheses and percent-encoded parentheses remain intact.
- **Coverage**: `chat-links.test.mjs`; native desktop click-through with the normal browser destination.
- **Specs linked**: `04-ux/08-component-spec.md` §8.3.
+
+#### E2E-IME-escape: Composition cancellation preserves drafts
+
+- **Steps**: Edit a user message; type a draft; dispatch composing Escape and Cmd/Ctrl+Enter. Open global search and dispatch composing Escape from its input. Repeat with legacy keyCode 229, then ordinary Escape and retry shortcuts.
+- **Expected**: Composition events neither discard the edit nor close search nor submit a retry. Ordinary Escape still cancels/closes, including search focus outside its input; ordinary Cmd/Ctrl+Enter still retries.
+- **Coverage**: `node scripts/e2e-ime-escape.mjs` exercises production components with bubbling DOM keyboard events and host-boundary fixtures. This does not verify an operating system IME candidate window.
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index bf720f1be..59196c400 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -1239,7 +1239,7 @@ row 而不是在转录本中添加树镶边。
编辑属于用户回合:它将提示气泡替换为与底部输入框同族的
composer 面板(`--ds-bg-composer` 填充、`--ds-composer-radius`,
无描边,无阴影,D297)。文本区域嵌在面板内不加第二层底;底部 28px 工具条放本地化的
- “重试”和“取消”(Escape 取消,Cmd/Ctrl+Enter 重试;斜杠转为种子
+ “重试”和“取消”(Escape 取消,Cmd/Ctrl+Enter 重试;输入法组词期间忽略这两个快捷键并保留草稿;斜杠转为种子
输入 `command` 表单,重试后会重新扩展模板)。打开时把用户列加宽到
助理阅读宽度,并隐藏操作工具栏。重试运行同一会话的
重新生成路径,即使文本没有变化也会执行,因此替换的提示及其整个答案
@@ -2361,7 +2361,7 @@ MainChat 底部的输入区域,用于撰写和发送提示。支持多行输
- 独立的调色板覆盖不再存在;命令是全局搜索对话框的一部分(`role="dialog"`、`aria-label` 和 `nav.search`)。
- “命令”部分使用与其他搜索结果组相同的 `role="listbox"` / `role="option"` 语义。
-- 搜索输入自动聚焦于打开;箭头 up/down 导航,Enter 执行,Escape 关闭。
+- 搜索输入自动聚焦于打开;箭头 up/down 导航,Enter 执行,Escape 关闭。输入法组词期间,搜索框的 Escape(包括从输入框冒泡的事件)不得关闭搜索弹窗。
### 16.6 MVP 约束
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 9a68c4ab5..dde2801f3 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
@@ -8457,3 +8457,9 @@ the latest destination. These assertions measure work counts, not device FPS.
- **预期**:打开包含 `(software)` 的完整网址,进入 React 软件词条;正文外层的右括号和紧跟 URL 右括号的句末标点不属于链接,相邻引用仍能独立点击。嵌套圆括号、查询和片段内的圆括号、百分号编码的圆括号均保持完整。
- **覆盖**:`chat-links.test.mjs`;桌面端通过正常浏览器目标实际点击验证。
- **链接规格**:`04-ux/08-component-spec.md` §8.3。
+
+#### E2E-IME-escape: 取消组词保留草稿
+
+- **步骤**:编辑用户消息并输入草稿,派发组词中的 Escape 和 Cmd/Ctrl+Enter;打开全局搜索,从输入框派发组词中的 Escape。对 legacy keyCode 229 重复检查,再验证普通 Escape 和重试快捷键。
+- **预期**:组词事件不会丢弃编辑、关闭搜索或重试发送;普通 Escape 仍取消或关闭(包括搜索输入框之外的焦点),普通 Cmd/Ctrl+Enter 仍重试。
+- **覆盖**:`node scripts/e2e-ime-escape.mjs` 使用真实组件、冒泡 DOM 键盘事件及宿主边界测试数据;不代表已验证操作系统输入法候选窗口。
diff --git a/scripts/e2e-ime-escape.mjs b/scripts/e2e-ime-escape.mjs
new file mode 100644
index 000000000..3d0650f84
--- /dev/null
+++ b/scripts/e2e-ime-escape.mjs
@@ -0,0 +1,38 @@
+#!/usr/bin/env node
+// Real components and bubbling keyboard events; host APIs are fixtures.
+import { spawnSync } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const desktop = join(root, "apps/desktop");
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const cache = join(root, ".cache/ime-escape");
+await mkdir(cache, { recursive: true });
+const temp = await mkdtemp(join(cache, "run-"));
+await require("esbuild").build({
+ entryPoints: [join(root, "scripts/e2e/ime-escape.tsx")],
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife",
+ loader: { ".css": "empty" }, jsx: "automatic", define: { "process.env.NODE_ENV": '"production"' },
+ alias: { react: join(desktop, "node_modules/react"), "react-dom": join(desktop, "node_modules/react-dom") },
+ nodePaths: [join(desktop, "node_modules")],
+});
+await writeFile(join(temp, "index.html"), '<!doctype html><html><body><script src="renderer.js"></script></body></html>');
+await writeFile(join(temp, "main.cjs"), `
+const {app,BrowserWindow}=require('electron');
+app.setPath('userData',require('node:path').join(__dirname,'profile'));
+app.disableHardwareAcceleration();
+app.whenReady().then(async()=>{
+ try {
+ const win=new BrowserWindow({show:false,webPreferences:{backgroundThrottling:false,sandbox:true,contextIsolation:true}});
+ await win.loadFile(require('node:path').join(__dirname,'index.html'));
+ console.log(await win.webContents.executeJavaScript('globalThis.imeEscapeProbe()'));
+ app.exit(0);
+ } catch(error) { console.error(error); app.exit(1); }
+});`);
+const result = spawnSync(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { stdio: "inherit", timeout: 30000 });
+if (result.error) throw result.error;
+process.exitCode = result.status ?? 1;
diff --git a/scripts/e2e/ime-escape.tsx b/scripts/e2e/ime-escape.tsx
new file mode 100644
index 000000000..7ec253f09
--- /dev/null
+++ b/scripts/e2e/ime-escape.tsx
@@ -0,0 +1,71 @@
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "../../packages/i18n/src/index";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+import { MessageRow } from "../../apps/desktop/src/features/chat/transcript/MessageRow";
+import { SearchDialog } from "../../apps/desktop/src/components/SearchDialog";
+import { useSessionSearchState } from "../../apps/desktop/src/hooks/use-session-search";
+
+const check = (ok: unknown, label: string) => { if (!ok) throw new Error(label); };
+const key = (node: Element, init: KeyboardEventInit) => {
+ const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init });
+ flushSync(() => node.dispatchEvent(event));
+ return event;
+};
+Object.assign(globalThis, { imeEscapeProbe: async () => {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ const sent: string[] = [];
+ useAppStore.setState({ refreshSessions: async () => {}, editUserMessage: async (_id, text) => { sent.push(text); return true; } });
+ Object.assign(api, { searchSessions: async () => ({ hits: [] }), searchCommands: async () => ({ commands: [] }) });
+ const container = document.createElement("div"); document.body.append(container);
+ const root = createRoot(container);
+ const render = (child: React.ReactNode) => flushSync(() => root.render(<I18nextProvider i18n={i18n}>{child}</I18nextProvider>));
+ render(<MessageRow message={{ id: "ime-test", role: "user", content: "Original message", createdAt: "2026-09-21T00:00:00Z", status: "complete" }} isRunning={false} />);
+ const edit = () => flushSync(() => container.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.t("chat.editMessage")}"]`)!.click());
+ edit();
+ const input = container.querySelector<HTMLTextAreaElement>("textarea")!;
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(input, "Edited draft ni");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ for (const composing of [{ isComposing: true }, { keyCode: 229 }]) {
+ check(!key(input, { key: "Escape", ...composing }).defaultPrevented, "IME Escape was consumed");
+ check(container.contains(input) && input.value === "Edited draft ni", "IME Escape discarded message edit");
+ for (const modifier of [{ ctrlKey: true }, { metaKey: true }]) {
+ key(input, { key: "Enter", ...modifier, ...composing });
+ check(sent.length === 0, "IME Enter submitted message edit");
+ }
+ }
+ key(input, { key: "Escape" });
+ check(!container.querySelector("textarea"), "Normal Escape did not cancel editing");
+ for (const modifier of [{ ctrlKey: true }, { metaKey: true }]) {
+ edit();
+ key(container.querySelector("textarea")!, { key: "Enter", ...modifier });
+ for (let frame = 0; frame < 120 && container.querySelector("textarea"); frame++) {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ }
+ check(!container.querySelector("textarea"), "Successful retry did not finish editing");
+ }
+ check(sent.length === 2 && sent.every((text) => text === "Original message"), "Normal retry shortcuts changed");
+ let closed = false;
+ useSessionSearchState.setState({ query: "draft ni" });
+ const openSearch = () => { closed = false; render(<SearchDialog open onClose={() => { closed = true; }} />); };
+ openSearch();
+ const search = container.querySelector<HTMLInputElement>(".search-input")!;
+ check(search, "Search input missing");
+ for (const composing of [{ isComposing: true }, { keyCode: 229 }]) {
+ check(!key(search, { key: "Escape", ...composing }).defaultPrevented, "Search consumed IME Escape");
+ check(!closed && search.value === "draft ni", "Bubbled IME Escape closed search");
+ }
+ key(search, { key: "Escape" });
+ check(closed, "Normal Escape did not close search");
+ openSearch();
+ key(container.querySelector('[role="dialog"]')!, { key: "Escape" });
+ check(closed, "Escape outside search input did not close dialog");
+ root.unmount(); container.remove();
+ return "PASS: composing Escape preserves editing/search; composing retry ignored; normal Escape and retry work";
+} });