Skip to content

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

fix(chat): copy the current message edit draft

yuxino54f46413d702
diff --git a/apps/desktop/src/components/ContextMenu.tsx b/apps/desktop/src/components/ContextMenu.tsx
index e6d2493c9..748d9abd3 100644
--- a/apps/desktop/src/components/ContextMenu.tsx
+++ b/apps/desktop/src/components/ContextMenu.tsx
@@ -85,6 +85,15 @@ function pointForEvent(event: ReactMouseEvent<HTMLElement>): ContextMenuPoint {
* starts in this row still belongs to Copy here.
*/
function snapshotSelection(root: EventTarget): string {
+ // Textarea ranges are not represented by the document Selection.
+ const editor = document.activeElement;
+ if (
+ root instanceof Node &&
+ editor instanceof HTMLTextAreaElement &&
+ root.contains(editor)
+ ) {
+ return editor.value.slice(editor.selectionStart, editor.selectionEnd);
+ }
const live = window.getSelection();
if (!live || live.rangeCount === 0 || live.isCollapsed) return "";
const text = live.toString();
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
index 82fc0f9d6..7902c378b 100644
--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
@@ -99,12 +99,13 @@ export const MessageRow = memo(function MessageRow({
label: t("chat.messageMenu"),
items: userMessageMenuItems({
t,
- text: message.content || "",
- selectTarget:
- event.currentTarget.querySelector<HTMLElement>(".message-bubble"),
- editable: editableUserMessage,
+ text: editing ? editValue : message.content || "",
+ selectTarget: event.currentTarget.querySelector<HTMLElement>(
+ editing ? ".message-edit-input" : ".message-bubble",
+ ),
+ editable: editableUserMessage && !editing,
running: isRunning,
- revision: showRevisionPager
+ revision: !editing && showRevisionPager
? { count: revisionCount, active: activeRevision }
: null,
actions: { copyText, selectText },
diff --git a/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsx b/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsx
index 169c28efd..8edf5fea9 100644
--- a/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsx
+++ b/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsx
@@ -85,6 +85,11 @@ export function useChatTextActions() {
and the row is already on screen, so nothing needs measuring.
*/
const selectText = useCallback((element: HTMLElement | null) => {
+ if (element instanceof HTMLTextAreaElement) {
+ element.focus();
+ element.select();
+ return;
+ }
const selection = window.getSelection();
if (!element || !selection) return;
const range = document.createRange();
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index dcbb67c58..bec306927 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1850,7 +1850,10 @@ message its checkpoint covers.
Home / End navigation, Escape / Tab / outside-press / scroll-behind
dismissal, and an accessible name (`chat.messageMenu` or
`chat.conversationMenu`). Focus returns to whatever the right-click
- interrupted.
+ interrupted. While editing a user message, Copy uses the selected draft text
+ (or the whole draft if the caret is collapsed), and Select message text selects
+ the draft. Saved-message Edit, Delete, and revision actions are not offered
+ until editing ends.
### 8.6 MVP constraints
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 1f9a9f6b7..fe553e47d 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -3532,7 +3532,9 @@ identify the platform validation still needed.
choose Copy. 4) Right-click the assistant turn and choose Copy.
5) Right-click empty space below the last turn and choose Copy
conversation. 6) Press Escape on an open menu, then Tab. 7) Right-click
- a markdown link in the answer.
+ a markdown link in the answer. 8) Edit the user message, replace its content,
+ select a phrase, and right-click Copy. Repeat with a collapsed caret and
+ Select message text, then cancel editing and copy the saved message.
- **Expected**: The user menu lists Copy, Select message text, Edit, and
a separated Delete; the assistant menu lists Copy, Select message text,
Regenerate, and Branch. Copy writes the live selection in the
@@ -3544,7 +3546,11 @@ identify the platform validation still needed.
A link still offers Open in default browser, Open in work panel, and
Copy link address. Quote, Annotate, and Open side chat are absent
(ADR 0268). The surface is a viewport-fixed body-level layer and does
- not resize the transcript.
+ not resize the transcript. During editing, Copy uses the selected draft text
+ or the full draft with a collapsed caret; Select message text selects the
+ draft. Edit, Delete, and revision actions are absent until editing ends.
+ Cancel preserves the original message. Automated Chromium component check:
+ `node scripts/e2e-message-edit-copy.mjs`.
- **Specs linked**: `04-ux/08-component-spec.md` §8.3 / §8.5,
`04-ux/09-interaction-patterns.md` (floating dropdown surfaces),
ADR 0268
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 dd447e675..520c7143f 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -1328,7 +1328,7 @@ row 而不是在转录本中添加树镶边。
因此一旦弹框伸入面板列就会被覆盖,与其 z-index 无关。当会话面板比弹框
窄时,弹框随面板收窄,而不是越过该边界。
- 时间戳:`aria-label` 带有完整时间字符串,视觉显示相对时间
-- 右键菜单为 `role="menu"`、行项为 `role="menuitem"`,支持方向键 / Home / End,Escape / Tab / 外部按下 / 背后滚动关闭,并带有可访问名称(`chat.messageMenu` 或 `chat.conversationMenu`)。焦点回到被右键打断的控件。
+- 右键菜单为 `role="menu"`、行项为 `role="menuitem"`,支持方向键 / Home / End,Escape / Tab / 外部按下 / 背后滚动关闭,并带有可访问名称(`chat.messageMenu` 或 `chat.conversationMenu`)。焦点回到被右键打断的控件。编辑用户消息时,复制读取草稿选区(无选区时复制整份草稿),选中消息文本会选中草稿;结束编辑前不提供针对已保存消息的编辑、删除或版本切换操作。
### 8.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 94a4a91e0..cb86ab75d 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
@@ -2214,7 +2214,7 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的
#### E2E-CHAT-transcript-context-menu:右键消息或记录
- **前提条件**:会话中有一条完成的用户提示和一条完成的助手回答;对话面板已聚焦。
-- **步骤**:1)右键用户板。2)选择复制,再选择选中消息文本。3)在用户板里选中一段文字,再右键该板并选择复制;收起选区后再右键复制一次。4)右键助手回合并选择复制。5)右键最后一回合下方空白处,选择复制整个对话。6)在打开的菜单上按 Escape,再按 Tab。7)右键回答里的 markdown 链接。
+- **步骤**:1)右键用户板。2)选择复制,再选择选中消息文本。3)在用户板里选中一段文字,再右键该板并选择复制;收起选区后再右键复制一次。4)右键助手回合并选择复制。5)右键最后一回合下方空白处,选择复制整个对话。6)在打开的菜单上按 Escape,再按 Tab。7)右键回答里的 markdown 链接。8)编辑用户消息、替换内容、选中一段草稿并右键复制;再验证无选区复制、选中消息文本和取消编辑后的复制。
- **预期**:用户菜单列出复制、选中消息文本、编辑,以及分隔后的删除;助手菜单列出复制、选中消息文本、重新生成和分叉。复制写入打开菜单时该行内的选中文本;光标折叠或选区在行外时退回整段。复制整个对话仍写入带说话人标签的整段对话。两者都显示 toast。选中文本会高亮气泡。Escape 和 Tab 关闭菜单且不执行项。链接仍提供在默认浏览器打开、在工作面板打开、复制链接地址。引用、批注、打开侧边聊天不出现(ADR 0268)。表面是视口固定的文档级层,不会改变记录高度。
- **链接规格**:`04-ux/08-component-spec.md` §8.3 / §8.5,
`04-ux/09-interaction-patterns.md`(浮动下拉表面),
@@ -2225,6 +2225,8 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的
`chat-context-menu-items.test.mjs`、`chat-context-menu-surface.test.mjs`);
完整 UI 场景草稿
+- 编辑时复制应使用草稿选区,无选区时复制整份草稿;选中消息文本应选中草稿。菜单不提供编辑、删除或版本切换;取消后原消息及其菜单保持不变。自动化验证:`node scripts/e2e-message-edit-copy.mjs`。
+
#### E2E-060b:镀铬中性灰色调
- **先决条件**:应用程序在深色和浅色主题中运行;插件页面和
diff --git a/scripts/e2e-message-edit-copy.mjs b/scripts/e2e-message-edit-copy.mjs
new file mode 100644
index 000000000..475dd2858
--- /dev/null
+++ b/scripts/e2e-message-edit-copy.mjs
@@ -0,0 +1,38 @@
+#!/usr/bin/env node
+// Real Chromium selection and production message components; no host or provider.
+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/message-edit-copy");
+await mkdir(cache, { recursive: true });
+const temp = await mkdtemp(join(cache, "run-"));
+await require("esbuild").build({
+ entryPoints: [join(root, "scripts/e2e/message-edit-copy.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.messageEditCopyProbe()'));
+ 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/message-edit-copy.tsx b/scripts/e2e/message-edit-copy.tsx
new file mode 100644
index 000000000..214e532e9
--- /dev/null
+++ b/scripts/e2e/message-edit-copy.tsx
@@ -0,0 +1,69 @@
+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 { MessageRow } from "../../apps/desktop/src/features/chat/transcript/MessageRow";
+import { TranscriptMenuProvider } from "../../apps/desktop/src/features/chat/transcript/TranscriptMenu";
+
+const check = (ok: boolean, label: string) => { if (!ok) throw new Error(label); };
+const settle = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+const find = <T extends HTMLElement>(selector: string) => {
+ const node = document.querySelector<T>(selector);
+ if (!node) throw new Error(`Missing ${selector}`);
+ return node;
+};
+const click = async (selector: string) => {
+ flushSync(() => find(selector).click());
+ await settle();
+};
+const menu = async (node: HTMLElement) => {
+ flushSync(() => node.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 10, clientY: 10 })));
+ await settle();
+};
+
+Object.assign(globalThis, { messageEditCopyProbe: async () => {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ let copied = "";
+ // Mock only the external clipboard write, keeping native textarea selection.
+ Object.defineProperty(navigator, "clipboard", { value: { writeText: async (text: string) => { copied = text; } } });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><TranscriptMenuProvider>
+ <MessageRow message={{ id: "message", role: "user", content: "Original saved message", createdAt: "2026-09-21T00:00:00Z" }} isRunning={false} />
+ </TranscriptMenuProvider></I18nextProvider>));
+ await menu(find('[role="article"]'));
+ await click('[data-context-menu-item="edit"]');
+ const editor = find<HTMLTextAreaElement>("textarea");
+ editor.focus();
+ editor.select();
+ document.execCommand("insertText", false, "Fresh draft: ORANGE-927");
+ await settle();
+ editor.setSelectionRange(13, 23);
+ await menu(editor);
+ await click('[data-context-menu-item="copy"]');
+ check(copied === "ORANGE-927", `Selected draft copy returned ${JSON.stringify(copied)}`);
+ editor.focus();
+ editor.setSelectionRange(0, 0);
+ await menu(editor);
+ check(!document.querySelector('[data-context-menu-item="edit"]'), "Editing menu can reset the unsaved draft");
+ check(!document.querySelector('[data-context-menu-item="delete"]'), "Editing menu exposes saved-message deletion");
+ await click('[data-context-menu-item="copy"]');
+ check(copied === editor.value, "Collapsed selection copied the saved message instead of the draft");
+ await menu(editor);
+ await click('[data-context-menu-item="select-text"]');
+ check(editor.selectionStart === 0 && editor.selectionEnd === editor.value.length, "Select text did not select the draft");
+ await menu(editor);
+ await click('[data-context-menu-item="copy"]');
+ check(copied === "Fresh draft: ORANGE-927", "Select text then Copy lost draft content");
+ await click(".message-edit-cancel");
+ await menu(find('[role="article"]'));
+ check(!!document.querySelector('[data-context-menu-item="edit"]'), "Normal message lost Edit");
+ check(!!document.querySelector('[data-context-menu-item="delete"]'), "Normal message lost Delete");
+ await click('[data-context-menu-item="copy"]');
+ check(copied === "Original saved message", "Cancel changed the saved message");
+ root.unmount();
+ return "PASS: partial draft copy, whole draft copy, select text, editing actions, cancel and saved-message copy";
+} });