From 8d701da584b47fde7a8ecb6abc726263cbc9579e Mon Sep 17 00:00:00 2001 From: TWINKLE <34811911+H-TWINKLE@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:01:19 +0800 Subject: [PATCH] feat(agents): copy an agent reference for files and selected code (#5469) Co-authored-by: H-TWINKLE <34811911+H-TWINKLE@users.noreply.github.com> --- src/editor/core/controller.test.ts | 36 ++++++++ src/editor/core/controller.ts | 14 ++- src/features/agents/copyReference.test.ts | 103 ++++++++++++++++++++++ src/features/agents/copyReference.ts | 78 ++++++++++++++++ src/features/agents/index.ts | 3 + src/features/agents/store.ts | 27 +++--- src/platform/locales/text/en.json | 2 + src/platform/locales/text/es.json | 4 +- src/platform/locales/text/fr.json | 4 +- src/platform/locales/text/ko.json | 4 +- src/platform/locales/text/pl.json | 4 +- src/platform/locales/text/pt.json | 4 +- src/platform/locales/text/tr.json | 2 + src/platform/locales/text/zh-TW.json | 2 + src/platform/locales/text/zh.json | 2 + 15 files changed, 272 insertions(+), 17 deletions(-) create mode 100644 src/features/agents/copyReference.test.ts create mode 100644 src/features/agents/copyReference.ts diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index 997a528db..9983fb8db 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -543,6 +543,42 @@ describe("EditorController", () => { } }); + it("passes the caret line and the selected line range to Copy Agent Reference", async () => { + const path = "/p/a.ts"; + ctrl = new EditorController(createMemoryBackend({ [path]: "first\nsecond\nthird\n" })); + ctrl.start(); + await ctrl.openFile(path, { focus: false }); + const slot = ctrl.activeSlot!; + const host = document.createElement("div"); + document.body.appendChild(host); + const view = slot.mount(host); + vi.spyOn(view, "posAtCoords").mockReturnValue(null); + try { + for (const [selection, lines] of [ + [{ anchor: 7 }, { from: 2, to: 2 }], + [ + { anchor: 0, head: 13 }, + { from: 1, to: 2 }, + ], + ] as const) { + view.dispatch({ selection }); + ctrl.onContextMenu(slot, new MouseEvent("contextmenu")); + const copy = useContextMenuStore + .getState() + .menu!.items.find((item) => "label" in item && item.label === "Copy / Paste Special"); + expect(copy).toMatchObject({ + submenu: expect.arrayContaining([ + expect.objectContaining({ action: "agents.copyAgentReference", arg: [{ path, lines }] }), + ]), + }); + } + } finally { + hideContextMenu(); + slot.unmount(); + host.remove(); + } + }); + it("builds IDEA's editor tab menu", async () => { useProject.setState({ project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never, diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index d0df959d7..6ccc6daff 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -117,7 +117,7 @@ import { isClassFile } from "@/platform/classFiles"; import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs"; import type { VirtualDocument } from "@/platform/ipc"; import type { Scheduler } from "./sync/DocSync"; -import { selectedLineContext } from "./selectedLines"; +import { selectedLineContext, selectedLines } from "./selectedLines"; export const fileKey = (path: string) => `file:${path}`; export const fileInput = (path: string): EditorInput => ({ kind: "file", key: fileKey(path), path }); @@ -888,6 +888,7 @@ export class EditorController implements SlotHost { view.dispatch({ selection: EditorSelection.cursor(pos) }); const hasSel = !view.state.selection.main.empty; const caretLine = view.state.doc.lineAt(view.state.selection.main.head).number - 1; + const { first, last } = selectedLines(view.state); const hoverItems: MenuItem[] = hoverActionsAt(slot.model.doc, caretLine).map(({ plugin, action }) => ({ label: action.label, verbatim: true, @@ -941,6 +942,17 @@ export class EditorController implements SlotHost { submenu: [ { kind: "action", action: "editor.copyPathReference" }, { kind: "action", action: "editor.copyReference" }, + // A virtual document's `path` is not a file to point an agent at. + ...(slot.model.virtual || isVirtualUri(slot.model.path) + ? [] + : ([ + { + kind: "action", + action: "agents.copyAgentReference", + label: "Copy Agent Reference", + arg: [{ path: slot.model.path, lines: { from: first, to: last } }], + }, + ] as MenuItem[])), { kind: "action", action: "code.pasteAsPlainText" }, { kind: "action", action: "code.pasteFromHistory" }, ], diff --git a/src/features/agents/copyReference.test.ts b/src/features/agents/copyReference.test.ts new file mode 100644 index 000000000..19e883cb6 --- /dev/null +++ b/src/features/agents/copyReference.test.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { registerAction, registerActions } from "@/platform/actions"; +import { useProject } from "@/platform/project"; +import * as contributions from "@/workbench/contributions"; +import type { MenuItem } from "@/ui"; +import { agentReferences, copyAgentReferenceActions, registerCopyAgentReference } from "./copyReference"; +import { useAgents } from "./store"; + +const writeText = vi.fn(async (_text: string) => undefined); +const hint = vi.fn(); +const notify = vi.fn(); +const disposers: Array<() => void> = []; + +type Item = Extract; +const items = (ctx: { paths: string[]; dirs?: boolean[]; line?: number; endLine?: number }) => + contributions + .menuGroupItems("copyPath", ctx) + .filter((i): i is Item => i.kind !== "separator" && "run" in i && i.id === "agents.copyAgentReference"); +const preview = (ctx: { paths: string[]; dirs?: boolean[]; line?: number; endLine?: number }) => items(ctx)[0]?.preview; + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("navigator", { clipboard: { writeText }, userAgent: navigator.userAgent }); + contributions.provideNotificationService({ notify }); + vi.spyOn(contributions, "editorService").mockReturnValue({} as contributions.EditorService); + useProject.setState({ project: { root: "/w/api", workspace: { projects: ["/w/api", "/w/web"] } } as never }); + useAgents.setState({ draft: { ...useAgents.getState().draft, projectRoot: "/w/api" } }); + disposers.push( + registerActions(copyAgentReferenceActions), + registerCopyAgentReference(), + registerAction({ id: "editor.showHint", title: "Hint", run: ({ arg }) => hint(arg) }), + ); +}); + +afterEach(() => { + disposers + .splice(0) + .reverse() + .forEach((dispose) => dispose()); + useProject.setState({ project: null }); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe("Copy Path/Reference… › Agent Reference", () => { + it("copies the file's `@` reference from the project root", async () => { + const ctx = { paths: ["/w/api/internal/server.go"] }; + expect(items(ctx)[0]).toMatchObject({ + id: "agents.copyAgentReference", + label: "Agent Reference", + preview: "@internal/server.go", + }); + items(ctx)[0]!.run!(); + await vi.waitFor(() => expect(hint).toHaveBeenCalledWith({ text: "Copied @internal/server.go" })); + expect(writeText).toHaveBeenCalledExactlyOnceWith("@internal/server.go"); + }); + + it("follows an editor selection with its 1-based line range", async () => { + expect(preview({ paths: ["/w/api/internal/server.go"], line: 11, endLine: 17 })).toBe("@internal/server.go:12-18"); + expect(preview({ paths: ["/w/api/a.go"], line: 4 })).toBe("@a.go:5"); + const ctx = { paths: ["/w/api/a.go"], line: 1, endLine: 3 }; + items(ctx)[0]!.run!(); + await vi.waitFor(() => expect(writeText).toHaveBeenCalledExactlyOnceWith("@a.go:2-4")); + }); + + it("keeps the slash of a folder and lists several paths space-separated", () => { + expect(preview({ paths: ["/w/api/src"], dirs: [true] })).toBe("@src/"); + expect(preview({ paths: ["/w/api/main.go", "/w/web/src/app.ts"] })).toBe("@main.go @web/src/app.ts"); + }); + + it("names another workspace project's files after that project", () => { + expect(agentReferences([{ path: "/w/web/src/app.ts" }])).toBe("@web/src/app.ts"); + }); + + it("qualifies paths from the primary project when the composer works in another workspace member", () => { + useAgents.setState(({ draft }) => ({ draft: { ...draft, projectRoot: "/w/web" } })); + expect(preview({ paths: ["/w/api/main.go", "/w/web/src/app.ts"] })).toBe("@api/main.go @src/app.ts"); + }); + + it("omits virtual documents from the copy chooser", () => { + expect(items({ paths: ["untitled:Untitled-1"], line: 0 })).toEqual([]); + expect(agentReferences([{ path: "jdt://contents/java.jar/Main.class" }])).toBeNull(); + }); + + it("points outside the projects with the path as written", () => { + expect(agentReferences([{ path: "/tmp/notes.md" }])).toBe("@/tmp/notes.md"); + }); + + it("offers nothing without a target", () => { + expect(items({ paths: [] })).toEqual([]); + }); + + it("reports a clipboard it cannot write to", async () => { + writeText.mockRejectedValueOnce(new Error("denied")); + items({ paths: ["/w/api/a.go"] })[0]!.run!(); + await vi.waitFor(() => + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ level: "error", title: "Cannot access the clipboard", body: "denied" }), + ), + ); + expect(hint).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/agents/copyReference.ts b/src/features/agents/copyReference.ts new file mode 100644 index 000000000..5494a1f6f --- /dev/null +++ b/src/features/agents/copyReference.ts @@ -0,0 +1,78 @@ +/** + * Copy Path/Reference… › Agent Reference: the clipboard text of the `@` mentions "Send to Agent" + * writes into the composer, so a selection or a Project view file can be pasted into a terminal + * agent as `@src/app.ts` / `@src/app.ts:12-18`. + */ +import { executeAction, type Action } from "@/platform/actions"; +import { writeClipboardText } from "@/platform/clipboard"; +import { tx } from "@/platform/i18n"; +import { isVirtualUri } from "@/platform/virtualDocs"; +import { notifications, registerMenuGroup } from "@/workbench/contributions"; +import { mentionOf, referenceOf } from "./composerModel"; +import { composerReferenceContext, type ReferenceTarget } from "./store"; + +/** The `@` mentions of `targets`, space-separated as the composer writes them; null for none. */ +export function agentReferences(targets: readonly ReferenceTarget[]): string | null { + const { roots } = composerReferenceContext(); + const mentions = targets + .filter(({ path }) => !isVirtualUri(path)) + .map(({ path, lines }) => { + const ref = referenceOf(roots, path); + if (!ref) return mentionOf(path, lines); + const folder = /[\\/]$/.test(path); + return mentionOf(folder && ref.rel !== "." ? `${ref.rel}/` : ref.rel, lines); + }); + return mentions.length ? mentions.join(" ") : null; +} + +async function copy(text: string) { + try { + await writeClipboardText(text); + void executeAction("editor.showHint", { text: tx`Copied ${text}` }); + } catch (error) { + notifications().notify({ + level: "error", + title: tx("Cannot access the clipboard"), + body: error instanceof Error ? error.message : String(error), + }); + } +} + +export const copyAgentReferenceActions: Action[] = [ + { + id: "agents.copyAgentReference", + title: "Copy Agent Reference", + category: "Edit", + icon: "copy", + hidden: true, + run: ({ arg }) => { + const text = Array.isArray(arg) ? agentReferences(arg as ReferenceTarget[]) : null; + if (text) void copy(text); + }, + }, +]; + +export function registerCopyAgentReference(): () => void { + return registerMenuGroup({ + id: "agents.copyAgentReference", + menus: ["copyPath"], + items: (_menu, { paths, dirs, line, endLine }) => { + if (!paths.length) return []; + const targets: ReferenceTarget[] = paths.map((path, i) => ({ + path: dirs?.[i] ? `${path}/` : path, + // A selection's 1-based range; the caret's line alone when nothing is selected. + lines: line === undefined ? undefined : { from: line + 1, to: (endLine ?? line) + 1 }, + })); + const text = agentReferences(targets); + if (!text) return []; + return [ + { + id: "agents.copyAgentReference", + label: "Agent Reference", + preview: text, + run: () => void executeAction("agents.copyAgentReference", targets), + }, + ]; + }, + }); +} diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index 6254e5585..02b39e54c 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -28,6 +28,7 @@ import { AgentsStatus } from "./AgentsStatus"; import { activateSettingsPages } from "./settingsPages"; import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model"; import { sendPaths, sendSelection, trackEditorCopies } from "./references"; +import { copyAgentReferenceActions, registerCopyAgentReference } from "./copyReference"; import { diagnoseTestFailure, isTestFailure } from "./testFailure"; import { focusedSession, inputSession } from "./sessionFocus"; import { cycleFocusedEffort } from "./effortFocus"; @@ -79,6 +80,8 @@ export function activate(): () => void { trackPromptHistory(), activateSettingsPages(), trackEditorCopies(), + registerActions(copyAgentReferenceActions), + registerCopyAgentReference(), registerAgentContextSource({ id: "changes", title: "Changes", diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 2672a955f..d2d8a8898 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -1691,6 +1691,20 @@ export interface ReferenceTarget { lines?: { from: number; to: number }; } +/** The active composer's task and path roots for agent references. */ +export function composerReferenceContext() { + const key = activeComposerKey(); + const task = key === HOME ? null : (useAgents.getState().tasks.get(key) ?? null); + const project = useProject.getState().project; + const root = (task ? task.cwd : homeProjectRoot()) ?? ""; + const roots = { + root, + projectRoot: (task ? (task.projectRoot ?? project?.root) : null) ?? root, + members: project?.workspace?.projects, + }; + return { key, task, roots }; +} + /** * Adds `@file` references (with an optional line range) to the composer on show (else the one * typed in last) and shows it: IDEA-style "send this to the chat". Paths resolve like the @@ -1714,21 +1728,12 @@ export function appendToComposer( compose: (mentions: readonly string[], text: string) => string, targets: readonly ReferenceTarget[] = [], ): number { - const s = useAgents.getState(); - const key = activeComposerKey(); - const task = key === HOME ? null : s.tasks.get(key)!; - const project = useProject.getState().project; - const root = task ? task.cwd : homeProjectRoot(); - const roots = { - root: root ?? "", - projectRoot: (task ? (task.projectRoot ?? project?.root) : null) ?? root ?? "", - members: project?.workspace?.projects, - }; + const { key, task, roots } = composerReferenceContext(); const current = composerDraft(key); const files: FileRef[] = []; const mentions: string[] = []; for (const { path, lines } of targets) { - const ref = root ? referenceOf(roots, path) : null; + const ref = roots.root ? referenceOf(roots, path) : null; if (!ref) continue; // A folder keeps its trailing slash, so its chip is a folder reference. const rel = /[\\/]$/.test(path) && ref.rel !== "." ? `${ref.rel}/` : ref.rel; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index bdb4d1e50..7c5864401 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1445,6 +1445,8 @@ "1 line": "1 line", "Path From Source Root": "Path From Source Root", "Path From Repository Root": "Path From Repository Root", + "Agent Reference": "Agent Reference", + "Copy Agent Reference": "Copy Agent Reference", "Paste preview": "Paste preview", "Add Imports on Paste": "Add Imports on Paste", "Select imports to add to the pasted code:": "Select imports to add to the pasted code:", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 303eeb92c..d9f240946 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -6100,5 +6100,7 @@ "{length} plugin updates available": "{length} actualizaciones de plugins disponibles", "Updated {updated} plugins": "Se actualizaron {updated} plugins", "This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Esta versión está firmada con una clave diferente a la instalada y la clave anterior del editor no la avala. Continúe solo si sabe que el editor cambió de clave.", - "Select files in the Project view, Commit tool window, or open a file in the editor": "Seleccione archivos en la vista Proyecto, la ventana de Confirmación, o abra un archivo en el editor" + "Select files in the Project view, Commit tool window, or open a file in the editor": "Seleccione archivos en la vista Proyecto, la ventana de Confirmación, o abra un archivo en el editor", + "Agent Reference": "Referencia del agente", + "Copy Agent Reference": "Copiar referencia del agente" } diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index dccd4e41c..e026b023a 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5732,5 +5732,7 @@ "Methods pulled up to an interface are declared abstract there.": "Les méthodes remontées dans une interface y sont déclarées abstraites.", "The file changed; open the dialog again": "Le fichier a changé ; rouvrez la boîte de dialogue", "Replace preview": "Aperçu du remplacement", - "Select files in the Project view, Commit tool window, or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet, la fenêtre Commit, ou ouvrez un fichier dans l'éditeur" + "Select files in the Project view, Commit tool window, or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet, la fenêtre Commit, ou ouvrez un fichier dans l'éditeur", + "Agent Reference": "Référence d'agent", + "Copy Agent Reference": "Copier la référence d'agent" } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 13c5bfe10..f04b5886a 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -6210,5 +6210,7 @@ "The project is mounted here; paths and the working directory are mapped into it.": "프로젝트가 여기에 마운트되며, 경로와 작업 디렉터리가 이 위치로 매핑됩니다.", "Published ports": "게시된 포트", "Run as the image's user, not the project folder's owner (Linux)": "프로젝트 폴더 소유자가 아닌 이미지의 사용자로 실행(Linux)", - "Select files in the Project view, Commit tool window, or open a file in the editor": "프로젝트 뷰나 커밋 도구 창에서 파일을 선택하거나 편집기에서 파일을 여세요" + "Select files in the Project view, Commit tool window, or open a file in the editor": "프로젝트 뷰나 커밋 도구 창에서 파일을 선택하거나 편집기에서 파일을 여세요", + "Agent Reference": "에이전트 참조", + "Copy Agent Reference": "에이전트 참조 복사" } diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index d595d95ff..e2beaab44 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -5908,5 +5908,7 @@ "Default (the module's JDK)": "Domyślnie (zestaw JDK modułu)", "Use classpath of module": "Użyj ścieżki klas modułu", "Find by main class": "Znajdź według klasy głównej", - "Select files in the Project view, Commit tool window, or open a file in the editor": "Wybierz pliki w widoku Projektu, oknie Commit lub otwórz plik w edytorze" + "Select files in the Project view, Commit tool window, or open a file in the editor": "Wybierz pliki w widoku Projektu, oknie Commit lub otwórz plik w edytorze", + "Agent Reference": "Odwołanie do agenta", + "Copy Agent Reference": "Kopiuj odwołanie do agenta" } diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 970f0d861..1d290d813 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -5923,5 +5923,7 @@ "Default (the module's JDK)": "Padrão (JDK do módulo)", "Use classpath of module": "Usar classpath do módulo", "Find by main class": "Localizar por classe principal", - "Select files in the Project view, Commit tool window, or open a file in the editor": "Selecione arquivos na visualização do projeto, na janela Commit, ou abra um arquivo no editor" + "Select files in the Project view, Commit tool window, or open a file in the editor": "Selecione arquivos na visualização do projeto, na janela Commit, ou abra um arquivo no editor", + "Agent Reference": "Referência do agente", + "Copy Agent Reference": "Copiar referência do agente" } diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 123bd0ee1..a05b152f3 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -954,6 +954,8 @@ "1 line": "1 satır", "Path From Source Root": "Kaynak Kökünden Yol", "Path From Repository Root": "Depo Kökünden Yol", + "Agent Reference": "Ajan Referansı", + "Copy Agent Reference": "Ajan Referansını Kopyala", "Paste preview": "Yapıştırma önizlemesi", "Add Imports on Paste": "Yapıştırırken İçe Aktarmaları Ekle", "Select imports to add to the pasted code:": "Yapıştırılan koda eklenecek içe aktarmaları seçin:", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 8dadecdfa..58883833a 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -7380,6 +7380,8 @@ "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "這會清空整個對話,並使用此訊息啟動全新的代理對話。代理已修改的檔案保持不變。", "Path From Source Root": "相對於源根的路徑", "Path From Repository Root": "相對於存放庫根的路徑", + "Agent Reference": "智能體引用", + "Copy Agent Reference": "複製智能體引用", "Paste preview": "貼上預覽", "Filter clipboard history": "篩選剪貼簿歷史", "Add Imports": "新增匯入", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index a300fb511..105b373aa 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -7905,6 +7905,8 @@ "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "这会清空整个对话,并使用此消息启动全新的智能体会话。智能体已修改的文件保持不变。", "Path From Source Root": "相对于源根的路径", "Path From Repository Root": "相对于仓库根的路径", + "Agent Reference": "智能体引用", + "Copy Agent Reference": "复制智能体引用", "Paste preview": "粘贴预览", "Filter clipboard history": "筛选剪贴板历史", "Add Imports": "添加导入",