From 846794450a4ed2dc759e624e3e8f52104f3fbb59 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Thu, 19 Nov 2026 18:03:44 +0900 Subject: [PATCH] fix(agents): let Send to Agent reference files of non-primary workspace projects (#4459) Send to Agent resolved paths against the primary project only, so files of other workspace projects were dropped silently. It now goes through referenceOf with the target composer's roots (the task's cwd/project, or the project picked on the New Task page), keeps folders as folder references, maps only the task's own project into a worktree, and shows the existing notice for paths outside every project. Closes #4438 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/agents/HomeEditor.tsx | 4 + src/features/agents/index.ts | 10 +- src/features/agents/references.ts | 25 +---- src/features/agents/sendToAgent.test.ts | 138 ++++++++++++++++++++++++ src/features/agents/store.ts | 54 ++++++++-- 5 files changed, 197 insertions(+), 34 deletions(-) create mode 100644 src/features/agents/sendToAgent.test.ts diff --git a/src/features/agents/HomeEditor.tsx b/src/features/agents/HomeEditor.tsx index 712190c5a..7fc08c2eb 100644 --- a/src/features/agents/HomeEditor.tsx +++ b/src/features/agents/HomeEditor.tsx @@ -47,6 +47,10 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input? ); const members = project?.workspace?.projects ?? []; const root = members.includes(selected ?? "") ? selected! : (members[0] ?? project?.root ?? ""); + // Send to Agent resolves references against the project picked here. + useEffect(() => { + if (members.length && draft.projectRoot !== root) updateDraft({ projectRoot: root }); + }, [members.length, root, draft.projectRoot]); // A window without a project yet has no fact to show: the where row stays empty until it does. const projectLabel = members.length ? basename(root) : project?.name; const [repoState, setRepoState] = useState<{ diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index 1f7383e50..6e4f01083 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -165,9 +165,15 @@ export function activate(): () => void { id: "agents.send", menus: ["editor", "projectView"], order: 80, - items: (menu, { paths }) => + items: (menu, { paths, dirs }) => paths.length && !paths.some(isVirtualUri) - ? [{ kind: "action", action: "agents.sendToAgent", arg: menu === "projectView" ? paths : undefined }] + ? [ + { + kind: "action", + action: "agents.sendToAgent", + arg: menu === "projectView" ? paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)) : undefined, + }, + ] : [], }), registerActions([ diff --git a/src/features/agents/references.ts b/src/features/agents/references.ts index c533dd10f..81e06a5eb 100644 --- a/src/features/agents/references.ts +++ b/src/features/agents/references.ts @@ -1,40 +1,23 @@ /** "Send to Agent": the editor selection or Project view files as `@` references. */ import { activeEditor, useEditorRegistry } from "@/editor/api"; import { noteCopySource } from "@/platform/clipboardSource"; -import { useProject } from "@/platform/project"; import { isVirtualUri } from "@/platform/virtualDocs"; -import { mentionOf } from "./composerModel"; import { addReferences } from "./store"; -const relTo = (root: string, path: string) => (path.startsWith(`${root}/`) ? path.slice(root.length + 1) : null); - /** The active editor's file, with the selected lines when there is a selection. */ export function sendSelection(): boolean { const handle = activeEditor(); - const root = useProject.getState().project?.root; - if (!handle || !root || isVirtualUri(handle.ctx.path)) return false; - const rel = relTo(root, handle.ctx.path); - if (!rel) return false; + if (!handle || isVirtualUri(handle.ctx.path)) return false; const { state } = handle.view; const sel = state.selection.main; // A selection ending at a line start does not include that line. const end = sel.to > sel.from && state.doc.lineAt(sel.to).from === sel.to ? sel.to - 1 : sel.to; const lines = sel.empty ? undefined : { from: state.doc.lineAt(sel.from).number, to: state.doc.lineAt(end).number }; - addReferences([{ path: handle.ctx.path, rel, mention: mentionOf(rel, lines) }]); - return true; + return addReferences([{ path: handle.ctx.path, lines }]) > 0; } -/** Files and folders from the Project view. */ -export function sendPaths(paths: readonly string[]): boolean { - const root = useProject.getState().project?.root; - if (!root) return false; - const refs = paths.flatMap((path) => { - const rel = relTo(root, path); - return rel ? [{ path, rel, mention: mentionOf(rel) }] : []; - }); - if (refs.length) addReferences(refs); - return refs.length > 0; -} +/** Files and folders (with a trailing slash) from the Project view. */ +export const sendPaths = (paths: readonly string[]): boolean => addReferences(paths.map((path) => ({ path }))) > 0; /** * Notes the lines an editor's copy takes (the whole line when nothing is selected), so pasting diff --git a/src/features/agents/sendToAgent.test.ts b/src/features/agents/sendToAgent.test.ts new file mode 100644 index 000000000..3e05b76f2 --- /dev/null +++ b/src/features/agents/sendToAgent.test.ts @@ -0,0 +1,138 @@ +import { EditorSelection, EditorState } from "@codemirror/state"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { AgentTask, ProjectInfo } from "@/bindings"; +import { useProject } from "@/platform/project"; +import { sendPaths, sendSelection } from "./references"; +import { HOME, composerDraft, useAgents } from "./store"; + +const mocks = vi.hoisted(() => ({ notify: vi.fn(), editor: null as unknown })); +vi.mock("@/editor/api", async (original) => ({ + ...(await original()), + activeEditor: () => mocks.editor, +})); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + editorService: () => ({ openInput: vi.fn(), openTabs: () => [], activePath: () => null }), + notifications: () => ({ notify: mocks.notify }), +})); + +const BACK = "/w/backend"; +const FRONT = "/w/frontend"; +const NOTICE = "Only files of this window's projects can be referenced"; + +const task = (cwd: string, projectRoot: string, isolation: AgentTask["isolation"]) => + ({ id: "t", cwd, projectRoot, isolation, title: "t", status: "ready" }) as AgentTask; + +function setup(opts: { members?: string[]; homeRoot?: string; task?: AgentTask }) { + useProject.setState({ + project: { + root: BACK, + trusted: true, + workspace: opts.members ? { projects: opts.members } : null, + } as unknown as ProjectInfo, + }); + useAgents.setState({ + tasks: new Map(opts.task ? [["t", opts.task]] : []), + composers: new Map(), + lastComposer: opts.task ? "t" : HOME, + sessionLocation: "editor", + draft: { provider: "codex", config: {}, isolation: "local", base: null, projectRoot: opts.homeRoot ?? null }, + }); +} + +const sent = (key = HOME) => { + const { text, files } = composerDraft(key); + return { text: text.trim(), files: files.map((f) => [f.rel, f.path]) }; +}; + +beforeEach(() => { + mocks.notify.mockReset(); + mocks.editor = null; +}); + +describe("Send to Agent from the Project view", () => { + it("single project: files and folders as before", () => { + setup({}); + expect(sendPaths([`${BACK}/pom.xml`, `${BACK}/src/`])).toBe(true); + expect(sent()).toEqual({ + text: "@pom.xml @src/", + files: [ + ["pom.xml", `${BACK}/pom.xml`], + ["src/", `${BACK}/src`], + ], + }); + expect(mocks.notify).not.toHaveBeenCalled(); + }); + + it("a file and folder of a non-primary project, named by that project (#4438)", () => { + setup({ members: [BACK, FRONT], homeRoot: BACK }); + expect(sendPaths([`${FRONT}/package.json`, `${FRONT}/src/`])).toBe(true); + expect(sent()).toEqual({ + text: "@frontend/package.json @frontend/src/", + files: [ + ["frontend/package.json", `${FRONT}/package.json`], + ["frontend/src/", `${FRONT}/src`], + ], + }); + }); + + it("a selection across both projects keeps every file", () => { + setup({ members: [BACK, FRONT], homeRoot: BACK }); + sendPaths([`${BACK}/pom.xml`, `${FRONT}/package.json`]); + expect(sent().text).toBe("@pom.xml @frontend/package.json"); + }); + + it("the New Task page's picked project is the one files are relative to", () => { + setup({ members: [BACK, FRONT], homeRoot: FRONT }); + sendPaths([`${FRONT}/package.json`, `${BACK}/pom.xml`]); + expect(sent().text).toBe("@package.json @backend/pom.xml"); + }); + + it("a worktree task maps its own project into the worktree, not another project", () => { + setup({ members: [BACK, FRONT], task: task("/wt/t", BACK, "worktree") }); + sendPaths([`${BACK}/pom.xml`, `${FRONT}/package.json`]); + expect(sent("t").files).toEqual([ + ["pom.xml", "/wt/t/pom.xml"], + ["frontend/package.json", `${FRONT}/package.json`], + ]); + }); + + it("a path outside every project shows the notice instead of doing nothing", () => { + setup({ members: [BACK, FRONT], homeRoot: BACK }); + expect(sendPaths(["/etc/hosts"])).toBe(false); + expect(sent().files).toEqual([]); + expect(mocks.notify).toHaveBeenCalledWith({ level: "info", title: NOTICE }); + + mocks.notify.mockReset(); + expect(sendPaths(["/etc/hosts", `${FRONT}/package.json`])).toBe(true); + expect(sent().text).toBe("@frontend/package.json"); + expect(mocks.notify).toHaveBeenCalledTimes(1); + }); +}); + +describe("Send to Agent from the editor", () => { + const openEditor = (path: string, from = 0, to = 0) => { + const state = EditorState.create({ doc: "a\nb\nc\n", selection: EditorSelection.single(from, to) }); + mocks.editor = { ctx: { path }, view: { state } }; + }; + + it("a non-primary project's file, with the selected lines", () => { + setup({ members: [BACK, FRONT], homeRoot: BACK }); + openEditor(`${FRONT}/src/App.vue`, 2, 6); + expect(sendSelection()).toBe(true); + expect(sent()).toEqual({ + text: "@frontend/src/App.vue:2-3", + files: [["frontend/src/App.vue", `${FRONT}/src/App.vue`]], + }); + }); + + it("the whole file without a selection; a file outside the projects shows the notice", () => { + setup({ members: [BACK, FRONT], homeRoot: BACK }); + openEditor(`${BACK}/pom.xml`); + sendSelection(); + expect(sent().text).toBe("@pom.xml"); + openEditor("/tmp/scratch.txt"); + expect(sendSelection()).toBe(false); + expect(mocks.notify).toHaveBeenCalledWith({ level: "info", title: NOTICE }); + }); +}); diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 001432ab0..95013c00b 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -38,6 +38,8 @@ import { emptyDraft, isMentioned, isPerModelOption, + mentionOf, + referenceOf, toPrompt, withIdeContext, type ComposerDraft, @@ -1556,27 +1558,57 @@ function activeComposerKey(): string { return s.lastComposer !== HOME && s.tasks.has(s.lastComposer) ? s.lastComposer : HOME; } +/** The project a New Task started now would run in (the New Task page's project picker). */ +export function homeProjectRoot(): string | null { + const project = useProject.getState().project; + const members = project?.workspace?.projects ?? []; + const last = useAgents.getState().draft.projectRoot; + return last && members.includes(last) ? last : (members[0] ?? project?.root ?? null); +} + +/** A file or folder (trailing slash) to reference, with the lines meant. */ +export interface ReferenceTarget { + path: string; + lines?: { from: number; to: number }; +} + /** * 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". + * typed in last) and shows it: IDEA-style "send this to the chat". Paths resolve like the + * composer's own drops: inside the task's folder, or named by their workspace project. Returns + * how many were added; a path outside every project shows a notice. */ -export function addReferences(refs: Array<{ path: string; rel: string; mention: string }>) { +export function addReferences(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 current = composerDraft(key); - // A worktree task sees the same files under its own directory. - const root = task?.isolation === "worktree" ? task.cwd : null; - const files: FileRef[] = refs.map((r) => ({ - path: root ? `${root}/${r.rel}` : r.path, - rel: r.rel, - })); - const mentions = refs.map((r) => r.mention).join(" "); - const text = - current.text && !/\s$/.test(current.text) ? `${current.text} ${mentions} ` : `${current.text}${mentions} `; + const files: FileRef[] = []; + const mentions: string[] = []; + for (const { path, lines } of targets) { + const ref = 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; + files.push({ path: ref.path, rel }); + mentions.push(mentionOf(rel, lines)); + } + if (files.length < targets.length) + notifications().notify({ level: "info", title: tx("Only files of this window's projects can be referenced") }); + if (!files.length) return 0; + const joined = mentions.join(" "); + const text = current.text && !/\s$/.test(current.text) ? `${current.text} ${joined} ` : `${current.text}${joined} `; updateComposer(key, { text, files: [...current.files, ...files] }); if (task) openTask(task.id); else openHome(); + return files.length; } /** Stops the task's turn, or with `subagent` only that subagent's work. */