From c7a4201ce9a1e2a8567f8b813151ac84ff99e766 Mon Sep 17 00:00:00 2001 From: langxp Date: Wed, 2 Dec 2026 18:16:31 +0800 Subject: [PATCH] fix(agents): support context menu and stable selection (#7490) Right-clicking the agent composer offered no editing menu. It now has Cut, Copy and Paste; menu paste goes through the same copied-code, link, project-path and long-text handling as a keyboard paste, and falls back to a clipboard image. A deferred multi-click selection handler no longer moves a selection that already left its conversation row back to it, which scrolled the conversation. Co-authored-by: kradme <17811095+kradme@users.noreply.github.com> --- e2e/agentScroll.spec.ts | 13 ++++ src/features/agents/Composer.tsx | 62 +++++++++++++++++++ src/features/agents/composerFolders.test.tsx | 22 ++++++- .../agents/session/clampSelection.test.ts | 5 +- src/features/agents/session/clampSelection.ts | 8 +-- src/platform/locales/text/zh.json | 1 + 6 files changed, 103 insertions(+), 8 deletions(-) diff --git a/e2e/agentScroll.spec.ts b/e2e/agentScroll.spec.ts index e7de05d5d6..eb4e46a53e 100644 --- a/e2e/agentScroll.spec.ts +++ b/e2e/agentScroll.spec.ts @@ -70,6 +70,19 @@ async function openHistory(page: Page) { return stream; } +// Selecting words in a long conversation must not move the reader away from the clicked text. +test("keeps the conversation position on double-click", async ({ page }) => { + const stream = await openHistory(page); + await stream.evaluate((el) => { + el.scrollTop = el.scrollHeight / 2; + }); + const target = stream.locator("[class*='_conversationRow_']").filter({ hasText: "Reply 40" }).last(); + await target.scrollIntoViewIfNeeded(); + const before = await stream.evaluate((el) => el.scrollTop); + await target.getByText("Reply 40", { exact: true }).dblclick(); + await expect.poll(() => stream.evaluate((el, top) => Math.abs(el.scrollTop - top), before)).toBeLessThanOrEqual(1); +}); + for (const placement of ["editor", "toolWindow"] as const) { test(`lets small upward wheel steps leave the end while replies stream in the ${placement}`, async ({ page }) => { // Streams into an 80-turn conversation for several seconds: close to 30 s on CI runners. diff --git a/src/features/agents/Composer.tsx b/src/features/agents/Composer.tsx index e3a52a9277..cb26839fcd 100644 --- a/src/features/agents/Composer.tsx +++ b/src/features/agents/Composer.tsx @@ -32,6 +32,7 @@ import { isRemoteWindow } from "@/platform/remote"; import { isMacHost, registerKeyClaim } from "@/platform/keymap"; import { isVirtualUri } from "@/platform/virtualDocs"; import { copySourceOf } from "@/platform/clipboardSource"; +import { readClipboardText } from "@/platform/clipboard"; import { blobLink, blobPathCandidates, isRemoteOf, markdownLink, pastedUrl } from "./composerLinks"; import { EDITOR_TAB_MIME, @@ -53,6 +54,7 @@ import { listNavigate, fileIconName, registerDropTarget, + showContextMenu, } from "@/ui"; import { IMAGE_EXTENSIONS, @@ -295,6 +297,7 @@ export function Composer(props: ComposerProps) { // Late-bound handlers: the editor is created once per draft, the props change every render. const onKeyDownRef = useRef<(e: KeyboardEvent, view: EditorView) => boolean>(() => false); const onPasteRef = useRef<(e: ClipboardEvent, view: EditorView) => boolean>(() => false); + const onContextMenuRef = useRef<(e: MouseEvent, view: EditorView) => boolean>(() => false); const onUpdateRef = useRef<(u: ViewUpdate) => void>(() => {}); useLayoutEffect(() => { @@ -319,6 +322,7 @@ export function Composer(props: ComposerProps) { EditorView.domEventHandlers({ keydown: (e, v) => onKeyDownRef.current(e, v), paste: (e, v) => onPasteRef.current(e, v), + contextmenu: (e, v) => onContextMenuRef.current(e, v), }), ), referenceExtensions(), @@ -1106,6 +1110,63 @@ export function Composer(props: ComposerProps) { return false; }; + // Menu actions have no native paste event, so use the same transformations explicitly. + const onContextMenu = (e: MouseEvent, view: EditorView): boolean => { + const hasSelection = !view.state.selection.main.empty; + showContextMenu(e, [ + ...(hasSelection + ? [ + { + label: "Cut", + icon: "cut", + run: () => { + view.focus(); + document.execCommand("cut"); + }, + }, + { + label: "Copy", + icon: "copy", + run: () => { + view.focus(); + document.execCommand("copy"); + }, + }, + ] + : []), + { + label: "Paste", + icon: "paste", + run: () => + void (async () => { + try { + const plain = await readClipboardText(); + if (!view.dom.isConnected) return; + if (plain) { + if ( + !pasteCopied(plain, view) && + !pasteLink(plain, view) && + !pastePath(plain, view) && + !pasteLong(plain, view) + ) { + view.dispatch(view.state.replaceSelection(plain), { userEvent: "input.paste", scrollIntoView: true }); + } + view.focus(); + } else if (isTauri()) { + await pasteClipboardImage(); + } else { + view.focus(); + document.execCommand("paste"); + } + } catch (error) { + notifications().notify({ level: "error", title: tx("Cannot paste"), body: String(error) }); + } + })(), + }, + ]); + return true; + }; + // Files dropped from the OS onto the box: images are inlined when they can be, other files // referenced, or attached by path when outside the project. useEffect(() => { @@ -1284,6 +1345,7 @@ export function Composer(props: ComposerProps) { useLayoutEffect(() => { onUpdateRef.current = onUpdate; onPasteRef.current = onPaste; + onContextMenuRef.current = onContextMenu; onKeyDownRef.current = onKeyDown; }); diff --git a/src/features/agents/composerFolders.test.tsx b/src/features/agents/composerFolders.test.tsx index 138e8cdc62..23f354f07f 100644 --- a/src/features/agents/composerFolders.test.tsx +++ b/src/features/agents/composerFolders.test.tsx @@ -6,7 +6,7 @@ import { trackEditorCopies } from "./references"; import userEvent from "@testing-library/user-event"; import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting"; import chipStyles from "./ReferenceChip.module.css"; -import { FILES_DRAG, dragSession } from "@/ui"; +import { FILES_DRAG, dragSession, useContextMenuStore } from "@/ui"; import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions"; import { useProject } from "@/platform/project"; @@ -97,6 +97,26 @@ beforeEach(() => { ); }); +// Menu paste must take the same path conversion as a keyboard paste. +it("pastes a project path from the context menu", async () => { + const box = renderComposer(); + vi.stubGlobal("navigator", { ...navigator, clipboard: { readText: vi.fn().mockResolvedValue("/p/src/a.ts:3-5") } }); + try { + fireEvent.contextMenu(box); + const item = useContextMenuStore + .getState() + .menu?.items.find((entry) => "label" in entry && entry.label === "Paste"); + expect(item && "run" in item && item.run).toBeTruthy(); + await act(async () => { + if (item && "run" in item) item.run?.(); + }); + expect(textOf(box)).toContain("@src/a.ts:3-5"); + } finally { + vi.unstubAllGlobals(); + useContextMenuStore.setState({ menu: null }); + } +}); + describe("Composer dropped paths", () => { function drop(box: HTMLElement, payload: string) { const restore = document.elementFromPoint; diff --git a/src/features/agents/session/clampSelection.test.ts b/src/features/agents/session/clampSelection.test.ts index c4c40a7529..dbf6ecf24d 100644 --- a/src/features/agents/session/clampSelection.test.ts +++ b/src/features/agents/session/clampSelection.test.ts @@ -36,11 +36,12 @@ describe("clampSelectionToRow", () => { expect(selection.toString()).toBe("Last"); }); - it("collapses a selection made entirely outside the row", () => { + it("leaves a selection moved entirely outside the row in place", () => { const { reply, next } = conversation(); const selection = document.getSelection()!; selection.setBaseAndExtent(next, 0, next, 4); clampSelectionToRow(selection, reply); - expect(selection.isCollapsed).toBe(true); + expect(selection.toString()).toBe("Next"); + expect(selection.anchorNode).toBe(next); }); }); diff --git a/src/features/agents/session/clampSelection.ts b/src/features/agents/session/clampSelection.ts index 40a007f81a..353685cae4 100644 --- a/src/features/agents/session/clampSelection.ts +++ b/src/features/agents/session/clampSelection.ts @@ -13,11 +13,9 @@ export function clampSelectionToRow(selection: Selection | null, row: Element) { const first = texts[0]; const last = texts.at(-1); if (!first || !last) return; - if (!startInside && !endInside) { - // The whole selection went past the row: none of the row's text is in it. - selection.collapse(last, last.length); - return; - } + // A deferred multi-click handler can run after the selection moved elsewhere. Moving it + // back to this row would also make the browser scroll to the stale selection. + if (!startInside && !endInside) return; const [startNode, startOffset] = startInside ? [range.startContainer, range.startOffset] : [first, 0]; const [endNode, endOffset] = endInside ? [range.endContainer, range.endOffset] : [last, last.length]; const backward = selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset; diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 828827a155..d1982f64d2 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -187,6 +187,7 @@ "Abort rebase in {name}?": "要中止 {name} 中的变基吗?", "Rebase stopped for editing": "变基已暂停,等待编辑", "Rebase paused": "变基已暂停", + "Cannot paste": "无法粘贴", "Cannot undo commit": "无法撤销提交", "Cannot edit commit message": "无法编辑提交消息", "Cannot rebase": "无法变基",