diff --git a/crates/ide-host/src/ops/nav.rs b/crates/ide-host/src/ops/nav.rs index e2bc3541d..536dc47d7 100644 --- a/crates/ide-host/src/ops/nav.rs +++ b/crates/ide-host/src/ops/nav.rs @@ -77,6 +77,19 @@ pub fn find_symbols( Ok(host.project(window)?.index.find_symbols(&query, filter, limit as usize)) } +/// Index symbols named exactly one of `names` inside `within` (an agent task's folder), +/// at most `SYMBOLS_PER_NAME` each: every name an agent reply shows, in one lookup. +pub async fn find_symbols_named( + host: &Host, + window: &str, + names: Vec, + within: IpcPath, +) -> IdeResult> { + const SYMBOLS_PER_NAME: usize = 50; + let project = host.project(window)?; + blocking(move || Ok(project.index.symbols_named_any(&names, &PathBuf::from(within), SYMBOLS_PER_NAME))).await +} + pub fn mark_recent(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> { host.project(window)?.index.mark_recent(&path); Ok(()) @@ -324,6 +337,9 @@ pub(crate) fn register(d: &mut Dispatcher) { d.add("find_symbols", |c| async move { find_symbols(&c.host, &c.window, c.arg("query")?, c.arg("filter")?, c.arg("limit")?) }); + d.add("find_symbols_named", |c| async move { + find_symbols_named(&c.host, &c.window, c.arg("names")?, c.arg("within")?).await + }); d.add("mark_recent", |c| async move { mark_recent(&c.host, &c.window, c.arg("path")?) }); d.add("remove_recent", |c| async move { remove_recent(&c.host, &c.window, c.arg("path")?) }); d.add("recent_files", |c| async move { recent_files(&c.host, &c.window) }); diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index c263a334e..cdbc7b286 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -500,6 +500,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool { | "find_files_named" | "find_dirs" | "find_symbols" + | "find_symbols_named" | "mark_recent" | "remove_recent" | "recent_files" diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index f1667f5c1..6787a22e9 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -323,6 +323,11 @@ impl ProjectIndex { matching::symbols_named_within(&self.shared.data.read(), name, kind, roots, limit) } + /// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per name. + pub fn symbols_named_any(&self, names: &[String], root: &Path, limit: usize) -> Vec { + matching::symbols_named_any(&self.shared.data.read(), names, root, limit) + } + /// Incrementally re-indexes changed paths (called from the vfs watcher). /// Cheap: the work is queued for the indexing thread. pub fn update(&self, changed: &[PathBuf], removed: &[PathBuf]) { diff --git a/crates/ide-index/src/matching.rs b/crates/ide-index/src/matching.rs index 3089276d7..71f146797 100644 --- a/crates/ide-index/src/matching.rs +++ b/crates/ide-index/src/matching.rs @@ -632,6 +632,41 @@ pub(crate) fn symbols_named_within( out } +/// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per +/// name, by path then position: one walk over the index for every name an agent reply shows. +pub(crate) fn symbols_named_any(data: &IndexData, names: &[String], root: &Path, limit: usize) -> Vec { + let wanted: Vec<(u64, &str)> = names.iter().map(|name| (char_mask(name), name.as_str())).collect(); + let syms = &data.syms; + let mut out: Vec = data + .files + .iter() + .flatten() + .filter(|entry| entry.path.starts_with(root)) + .flat_map(|entry| { + (entry.sym_start..entry.sym_start + entry.sym_len) + .filter(|&at| wanted.iter().any(|&(mask, name)| syms.mask(at) == mask && syms.name(at) == name)) + .map(move |at| SymbolMatch { + name: syms.name(at).to_string(), + kind: syms.kind(at), + container: syms.container(at).map(str::to_owned), + path: entry.path.clone().into(), + rel_path: entry.rel.to_string(), + range: syms.range(at), + score: 0, + indices: Vec::new(), + }) + }) + .collect(); + out.sort_by(|left, right| left.rel_path.cmp(&right.rel_path).then_with(|| left.range.cmp(&right.range))); + let mut kept: HashMap = HashMap::new(); + out.retain(|symbol| { + let count = kept.entry(symbol.name.clone()).or_default(); + *count += 1; + *count <= limit + }); + out +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index 8376d4122..d19a643fc 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -549,6 +549,24 @@ fn symbols_named_within_keeps_out_of_root_matches_from_evicting_a_root() { assert!(idx.symbols_named_within("Decoder", None, &[f.root.join("none")], 3).is_empty()); } +#[test] +fn symbols_named_any_answers_every_name_inside_the_root_in_one_walk() { + let fixture = Fixture::new(&[ + ("app/a.rs", "struct Config;\nfn load() {}\nfn load_all() {}\n"), + ("app/b.rs", "fn load() {}\nfn load() {}\n"), + ("other/c.rs", "struct Config;\n"), + ]); + let idx = fixture.open(); + let names = ["Config".to_string(), "load".to_string(), "missing".to_string()]; + let found: Vec<(String, String)> = idx + .symbols_named_any(&names, &fixture.root.join("app"), 2) + .into_iter() + .map(|symbol| (symbol.name, symbol.rel_path)) + .collect(); + let expected = [("Config", "app/a.rs"), ("load", "app/a.rs"), ("load", "app/b.rs")]; + assert_eq!(found, expected.map(|(name, path)| (name.to_string(), path.to_string()))); +} + #[test] fn content_roots_and_excludes_change_without_reopening() { let fx = Fixture::new(&[("src/main.rs", "fn alpha() {}\n"), ("src/gen/out.rs", "fn generated() {}\n")]); diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 71cfa070d..285c15a14 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -250,6 +250,7 @@ pub fn builder() -> tauri_specta::Builder { nav::find_files_named, nav::find_dirs, nav::find_symbols, + nav::find_symbols_named, nav::mark_recent, nav::recent_files, nav::remove_recent, diff --git a/src-tauri/src/commands/nav.rs b/src-tauri/src/commands/nav.rs index e2351164c..af647784d 100644 --- a/src-tauri/src/commands/nav.rs +++ b/src-tauri/src/commands/nav.rs @@ -63,6 +63,18 @@ pub fn find_symbols( ide_host::ops::nav::find_symbols(&state.host, window.label(), query, filter, limit) } +/// Index symbols named exactly one of `names` inside `within` (an agent task's folder). +#[tauri::command] +#[specta::specta] +pub async fn find_symbols_named( + window: Window, + state: State<'_, AppState>, + names: Vec, + within: IpcPath, +) -> IdeResult> { + ide_host::ops::nav::find_symbols_named(&state.host, window.label(), names, within).await +} + #[tauri::command] #[specta::specta] pub fn mark_recent(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> { diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 28c431da1..604315047 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -220,6 +220,7 @@ find_dirs always project_host bin find_files always project_host bindings sync find_files_named always project_host bindings async find_symbols always project_host bindings sync +find_symbols_named always project_host bindings async fs_compare_directories always project_host bindings async fs_copy always project_host bindings async fs_copy_merge always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index f6c9c4aeb..9dfd0b4bf 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -491,6 +491,8 @@ export const commands = { /** Folders holding indexed files, for `@` references. */ findDirs: (query: string, limit: number) => typedError(__TAURI_INVOKE("find_dirs", { query, limit })), findSymbols: (query: string, filter: SymbolFilter, limit: number) => typedError(__TAURI_INVOKE("find_symbols", { query, filter, limit })), + /** Index symbols named exactly one of `names` inside `within` (an agent task's folder). */ + findSymbolsNamed: (names: string[], within: IpcPath) => typedError(__TAURI_INVOKE("find_symbols_named", { names, within })), markRecent: (path: string) => typedError(__TAURI_INVOKE("mark_recent", { path })), /** Recently opened files, most recent first (⌘E). */ recentFiles: () => typedError(__TAURI_INVOKE("recent_files")), diff --git a/src/editor/core/index.ts b/src/editor/core/index.ts index c2d7be1b3..2706ae334 100644 --- a/src/editor/core/index.ts +++ b/src/editor/core/index.ts @@ -13,6 +13,8 @@ import { import { _provideCodePreview, _provideDocumentAttacher, editorsFor } from "@/editor/api"; import { isUntitledUri } from "@/platform/virtualDocs"; import { formatDocument } from "@/editor/lsp/format"; +import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation"; +import { openPopup } from "@/editor/lsp/popupStore"; import { editorController } from "./controller"; import { attachDocument } from "./model/attachment"; import { previewExtensions } from "./cm/preview"; @@ -64,6 +66,14 @@ export function activate(): void | (() => void) { forgetSavedTabs: () => ctrl.forgetSavedTabs(), keepSavedTabs: () => ctrl.keepSavedTabs(), documentHistory: (command) => ctrl.documentHistory(command), + chooseDeclaration: async (targets, name, anchor) => + openPopup({ + kind: "list", + anchor, + title: chooserTitle("declaration", name, targets.length), + items: await locationItems(targets), + pin: pinToFind(name, targets), + }), reformat: async (path) => { const handle = editorsFor(path)[0]; return !!handle && (await formatDocument(handle.view, { explicit: false, selectionOnly: false })).applied; diff --git a/src/features/agents/Markdown.test.tsx b/src/features/agents/Markdown.test.tsx index 2a7ad522f..2e00dcb79 100644 --- a/src/features/agents/Markdown.test.tsx +++ b/src/features/agents/Markdown.test.tsx @@ -3,17 +3,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { clearMocks, mockIPC } from "@tauri-apps/api/mocks"; import { resetMermaidForTests } from "../viewers/markdown/mermaid"; import { StrictMode } from "react"; +import { useProject } from "@/platform/project"; +import type { SymbolMatch } from "@/platform/ipc"; import { Markdown, markdownBlocks, markdownHtml } from "./Markdown"; -const { openFile, openExternalUrl } = vi.hoisted(() => ({ +const { openFile, chooseDeclaration, openExternalUrl } = vi.hoisted(() => ({ openFile: vi.fn().mockResolvedValue(undefined), + chooseDeclaration: vi.fn().mockResolvedValue(undefined), openExternalUrl: vi.fn().mockResolvedValue(undefined), })); const copyText = vi.hoisted(() => vi.fn()); const readImage = vi.fn<(path: string) => Promise>(); const PIXEL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; vi.mock("@/workbench/contributions", () => ({ - editorService: () => ({ openFile }), + editorService: () => ({ openFile, chooseDeclaration }), })); vi.mock("@/platform/openUrl", () => ({ openExternalUrl })); vi.mock("@/ui", async (importOriginal) => ({ @@ -349,3 +352,86 @@ describe("streamed replies", () => { expect(container.textContent?.trim()).toBe("Something else"); }); }); + +describe("symbol links", () => { + const symbol = (name: string, path: string, line: number): SymbolMatch => ({ + name, + kind: "class", + container: null, + path, + relPath: path.slice("/repo/".length), + range: { start: { line, col: 6 }, end: { line, col: 6 + name.length } }, + score: 0, + indices: [], + }); + const index = [ + symbol("FooView", "/repo/src/view.ts", 4), + symbol("BarView", "/repo/src/bar.ts", 1), + symbol("BarView", "/repo/web/bar.ts", 9), + symbol("StreamView", "/repo/src/stream.ts", 2), + symbol("SinkView", "/repo/src/sink.ts", 1), + symbol("SinkView", "/repo/web/sink.ts", 7), + ]; + let lookups: string[][]; + + beforeEach(() => { + lookups = []; + useProject.setState({ project: { root: "/repo" } as never }); + mockIPC((cmd, args) => { + if (cmd === "fs_probe") throw new Error("missing"); + if (cmd !== "find_symbols_named") return null; + const { names } = args as { names: string[] }; + lookups.push(names); + return index.filter((symbol) => names.includes(symbol.name)); + }); + }); + afterEach(() => useProject.setState({ project: null })); + + const code = (container: HTMLElement, text: string) => + [...container.querySelectorAll("code")].find((span) => span.textContent === text)!; + + it("opens the one definition a name has, and leaves other code plain", async () => { + const { container } = render(); + await waitFor(() => expect(code(container, "FooView").dataset.path).toBe("/repo/src/view.ts")); + expect(code(container, "cargo test").dataset.path).toBeUndefined(); + expect(code(container, "Missing").dataset.path).toBeUndefined(); + expect(lookups).toEqual([["FooView", "Missing"]]); + fireEvent.click(code(container, "FooView")); + expect(openFile).toHaveBeenCalledWith("/repo/src/view.ts", { focus: true, selection: { line: 4, col: 6 } }); + }); + + it("looks a streamed reply's names up once, after its text settles", async () => { + const reply = "First `StreamView`.\n\nThen `SinkView` in `web/sink.ts` and `StreamView` again."; + const { container, rerender } = render(); + for (let end = 12; end <= reply.length; end += 6) rerender(); + rerender(); + await waitFor(() => expect(code(container, "SinkView").dataset.path).toBe("/repo/web/sink.ts")); + expect(lookups).toEqual([["StreamView", "SinkView"]]); + rerender(); + await new Promise((resolve) => setTimeout(resolve, 600)); + expect(lookups).toHaveLength(1); + }); + + it("shows Go to Declaration's chooser when several files define the name", async () => { + const { container } = render(); + await waitFor(() => expect(code(container, "BarView").className).not.toBe("")); + expect(code(container, "BarView").dataset.path).toBeUndefined(); + fireEvent.click(code(container, "BarView")); + expect(openFile).not.toHaveBeenCalled(); + expect(chooseDeclaration).toHaveBeenCalledWith( + [expect.objectContaining({ path: "/repo/src/bar.ts" }), expect.objectContaining({ path: "/repo/web/bar.ts" })], + "BarView", + expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }), + ); + }); + + it("keeps a file a span names over a symbol of the same name", async () => { + mockIPC((cmd, args) => { + if (cmd === "fs_probe") return null; + if (cmd === "find_symbols_named") lookups.push((args as { names: string[] }).names); + return null; + }); + const { container } = render(); + await waitFor(() => expect(code(container, "Config.load").dataset.path).toBe("/repo/three/Config.load")); + }); +}); diff --git a/src/features/agents/Markdown.tsx b/src/features/agents/Markdown.tsx index 157a8f614..cd4f94c11 100644 --- a/src/features/agents/Markdown.tsx +++ b/src/features/agents/Markdown.tsx @@ -1,25 +1,28 @@ /** * Agent messages: Markdown → sanitized HTML (marked + DOMPurify). Fenced code is - * highlighted and gets a Copy button; inline code naming a file of the task opens it. + * highlighted and gets a Copy button; inline code naming a file of the task, or a symbol + * the index has, opens it. * Mermaid fences become `[data-mermaid]` placeholders drawn by the Markdown viewer's * shared renderer after each render; the block keeps a Copy button of its own, since * the drawn diagram hides the code block, and `onDiagramDrawn` lets the conversation * follow the end when a diagram draws after the last streamed chunk. */ -import { useLayoutEffect, useRef, useSyncExternalStore } from "react"; +import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"; import { Marked } from "marked"; import DOMPurify from "dompurify"; import { highlightInto } from "@/editor/lsp/markdown"; import { iconNode } from "@/ui/iconNode"; import { tx } from "@/platform/i18n"; import { openExternalUrl } from "@/platform/openUrl"; +import { useProject } from "@/platform/project"; import { copyText } from "@/ui"; -import { editorService } from "@/workbench/contributions"; +import { editorService, type DeclarationChoice } from "@/workbench/contributions"; import { hasMermaid, renderMermaidIn } from "@/features/viewers/markdown/mermaid"; import { subscribeTheme, themeKey } from "@/platform/themeWatch"; -import { fileHref, pathLink, type PathLink } from "./conversation"; +import { fileHref, pathLink, symbolRef, type PathLink, type SymbolRef } from "./conversation"; import { loadImages, type MessageImages } from "./markdownImages"; import { fileExists } from "./ReferenceChip"; +import { inTaskFolder, lookupSymbols, symbolTargets } from "./symbolLinks"; import styles from "./Session.module.css"; const escapeHtml = (s: string) => @@ -172,6 +175,58 @@ export function openPathLink(link: PathLink) { void editorService().openFile(link.path, { selection, focus: true }); } +/** The symbol each inline code span names. */ +const symbolRefs = new WeakMap(); +/** Whether inline code that names a symbol also names an existing file (which it then opens). */ +const fileChecks = new WeakMap>(); +/** Inline code naming a symbol defined in several places: the chooser's targets. */ +const choices = new WeakMap(); +/** How long a reply's text stays unchanged before its symbols are looked up. */ +const SETTLE_MS = 400; + +function mentionedPaths(root: HTMLElement): string[] { + const codePaths = [...root.querySelectorAll("code")].map((code) => pathLink(code.textContent ?? "", "")?.path); + const linkPaths = [...root.querySelectorAll("a[href]")].map( + (anchor) => fileHref(anchor.getAttribute("href") ?? "", "")?.path, + ); + return [...codePaths, ...linkPaths].filter((path): path is string => !!path); +} + +function markPath(element: HTMLElement, link: PathLink) { + element.classList.add(styles.fileLink!); + element.dataset.path = link.path; + if (link.line !== undefined) element.dataset.line = String(link.line); + if (link.col !== undefined) element.dataset.col = String(link.col); + element.title = tx`Open ${link.path}`; +} + +/** Links `spans` of the reply in `root` to their definitions: one index lookup for all their names. */ +async function linkSymbols(root: HTMLElement, spans: HTMLElement[], cwd: string) { + const projectRoot = useProject.getState().project?.root ?? cwd; + const refs = spans.map((code) => symbolRefs.get(code)!); + const answers = lookupSymbols( + projectRoot, + refs.map((ref) => ref.name), + ); + const mentioned = mentionedPaths(root); + await Promise.all( + spans.map(async (code, at) => { + if (await fileChecks.get(code)) return; + const ref = refs[at]!; + const found = (await answers.get(ref.name)!).map((symbol) => inTaskFolder(symbol, projectRoot, cwd)); + const targets = symbolTargets(ref, found, mentioned, cwd); + if (!code.isConnected || !targets.length) return; + if (targets.length > 1) { + code.classList.add(styles.fileLink!); + choices.set(code, targets); + return; + } + const { path, range } = targets[0]!; + markPath(code, { path, line: range.start.line, col: range.start.col }); + }), + ); +} + /** Highlighting, Copy buttons and file links over freshly rendered `root`. */ function enhance(root: HTMLElement, cwd: string, images: MessageImages): () => void { let alive = true; @@ -197,15 +252,15 @@ function enhance(root: HTMLElement, cwd: string, images: MessageImages): () => v }); root.querySelectorAll("code").forEach((code) => { if (code.parentElement?.tagName === "PRE" || code.closest("a")) return; - const link = pathLink(code.textContent ?? "", cwd); + const text = code.textContent ?? ""; + const ref = symbolRef(text); + if (ref) symbolRefs.set(code, ref); + const link = pathLink(text, cwd); if (!link) return; - void fileExists(link.path).then((exists) => { - if (!alive || !exists) return; - code.classList.add(styles.fileLink!); - code.dataset.path = link.path; - if (link.line !== undefined) code.dataset.line = String(link.line); - if (link.col !== undefined) code.dataset.col = String(link.col); - code.title = tx`Open ${link.path}`; + const exists = fileExists(link.path); + if (ref) fileChecks.set(code, exists); + void exists.then((found) => { + if (alive && found) markPath(code, link); }); }); return () => { @@ -296,6 +351,39 @@ export function Markdown({ const blocks = painted.current; return () => clearBlocks(blocks, 0); }, []); + /** Symbol spans already looked up (or being looked up). */ + const looked = useRef(new WeakSet()); + // Symbols: once the text stops changing (a streamed reply changes its last block on every + // chunk), the spans not looked up yet, as they come into view. + useEffect(() => { + const root = ref.current; + if (!root) return; + let observer: IntersectionObserver | null = null; + const lookUp = (spans: HTMLElement[]) => { + spans.forEach((span) => looked.current.add(span)); + if (spans.length) void linkSymbols(root, spans, cwd); + }; + const timer = setTimeout(() => { + const spans = [...root.querySelectorAll("code")].filter( + (code) => symbolRefs.has(code) && !looked.current.has(code), + ); + if (!spans.length) return; + if (typeof IntersectionObserver === "undefined") { + lookUp(spans); + return; + } + observer = new IntersectionObserver((entries) => { + const shown = entries.filter((entry) => entry.isIntersecting).map((entry) => entry.target as HTMLElement); + shown.forEach((span) => observer!.unobserve(span)); + lookUp(shown); + }); + spans.forEach((span) => observer!.observe(span)); + }, SETTLE_MS); + return () => { + clearTimeout(timer); + observer?.disconnect(); + }; + }, [text, cwd]); // Mermaid diagrams: before paint, so cached ones don't flash their source. Only a // draw that lands after the render needs the follow — cached ones are in place by // the time the conversation's own render pass scrolls. @@ -321,6 +409,14 @@ export function Markdown({ void copyText(copy.dataset.copy ?? ""); return; } + const code = target.closest("code"); + const targets = code && choices.get(code); + if (targets && !window.getSelection()?.toString()) { + const rect = code.getBoundingClientRect(); + const name = symbolRefs.get(code)!.name; + void editorService().chooseDeclaration?.(targets, name, { x: rect.left, y: rect.bottom + 2 }); + return; + } const file = target.closest("code[data-path]"); if (file && !window.getSelection()?.toString()) { const line = file.dataset.line === undefined ? undefined : Number(file.dataset.line); diff --git a/src/features/agents/conversation.test.ts b/src/features/agents/conversation.test.ts index db557ccc3..11573cdeb 100644 --- a/src/features/agents/conversation.test.ts +++ b/src/features/agents/conversation.test.ts @@ -7,6 +7,7 @@ import { isFindRangeShown, pathLink, quoteText, + symbolRef, withQuote, } from "./conversation"; @@ -46,6 +47,44 @@ describe("pathLink", () => { }); }); +describe("symbolRef", () => { + it("reads the forms a reply names a symbol in", () => { + expect(symbolRef("FooView")).toMatchObject({ name: "FooView", kinds: expect.arrayContaining(["class"]) }); + expect(symbolRef("load()")).toMatchObject({ name: "load", kinds: ["function", "method", "constructor"] }); + expect(symbolRef("validate(input)")).toMatchObject({ name: "validate" }); + expect(symbolRef("has_header")).toMatchObject({ name: "has_header", kinds: ["function", "method", "constructor"] }); + expect(symbolRef("loadConfig")).toMatchObject({ name: "loadConfig" }); + expect(symbolRef("Config.load")).toMatchObject({ name: "load", container: "Config" }); + expect(symbolRef("Config::load()")).toMatchObject({ name: "load", container: "Config" }); + expect(symbolRef("lib.rs::has_header")).toMatchObject({ name: "has_header", file: "lib.rs" }); + expect(symbolRef("src/a.ts#load")).toMatchObject({ name: "load", file: "src/a.ts" }); + }); + it("leaves words, keywords, literals, commands and code plain", () => { + for (const text of [ + "true", + "null", + "inventory", + "None", + "False", + "Self", + "Some(x)", + "None.value", + "42", + "1.5", + "cargo test", + "git log --oneline", + "x = 1", + "a && b", + "$HOME", + "foo(bar(1))", + "TODO", + "src/", + ]) { + expect(symbolRef(text)).toBeNull(); + } + }); +}); + describe("fileHref", () => { const cwd = "C:/repo"; it("resolves a link against the task folder", () => { diff --git a/src/features/agents/conversation.ts b/src/features/agents/conversation.ts index 47ab36576..61158e018 100644 --- a/src/features/agents/conversation.ts +++ b/src/features/agents/conversation.ts @@ -1,5 +1,6 @@ -/** Reading an agent conversation: quoting, file links, turn times and finding text. */ +/** Reading an agent conversation: quoting, file and symbol links, turn times and finding text. */ +import type { SymbolKind } from "@/platform/ipc"; import { opensOtherShare } from "@/platform/paths"; /** `text` as a Markdown quote for the composer, followed by an empty line to type in. */ @@ -64,6 +65,48 @@ export function pathLink(text: string, cwd: string): PathLink | null { return out; } +/** A symbol an inline code span names: `name`, inside `container` or `file` when the text says so. */ +export interface SymbolRef { + name: string; + container?: string; + /** The tail of the defining file's path (`lib.rs`, `src/a.ts`). */ + file?: string; + kinds: readonly SymbolKind[]; +} + +const IDENT = "[A-Za-z_$][\\w$]*"; +const CALL = "(\\([^()]*\\))?"; +const SYMBOL = new RegExp(`^(?:(${IDENT})(?:\\.|#|::))?(${IDENT})${CALL}$`); +const FILE_SYMBOL = new RegExp(`^((?:[\\w.@-]+\\/)*[\\w@-]+\\.[A-Za-z]\\w*)(?:#|::)(${IDENT})${CALL}$`); +const TYPE_KINDS: readonly SymbolKind[] = ["class", "interface", "struct", "enum", "trait", "typeAlias", "function"]; +const CALLABLE_KINDS: readonly SymbolKind[] = ["function", "method", "constructor"]; +const MEMBER_KINDS: readonly SymbolKind[] = [...CALLABLE_KINDS, "field", "property", "constant", "enumMember"]; +const ANY_KINDS: readonly SymbolKind[] = [...new Set([...TYPE_KINDS, ...MEMBER_KINDS, "variable"])]; +/** Capitalized keywords and literals that read like a type name. */ +const LITERALS = new Set(["None", "True", "False", "Self", "Some", "Ok", "Err", "Null", "Nil", "NaN", "Infinity"]); + +/** + * The symbol inline code names (`FooView`, `load()`, `has_header`, `Config.load`, + * `lib.rs::has_header`, `a.ts#load`); null for words, keywords, literals and anything + * with spaces or shell syntax (`cargo test`, `true`, `None`, `x = 1`). + */ +export function symbolRef(text: string): SymbolRef | null { + const trimmed = text.trim(); + const inFile = FILE_SYMBOL.exec(trimmed); + if (inFile) return { name: inFile[2]!, file: inFile[1]!, kinds: ANY_KINDS }; + const match = SYMBOL.exec(trimmed); + if (!match) return null; + const [, container, name, call] = match; + if (LITERALS.has(container ?? name!)) return null; + if (container) return { name: name!, container, kinds: MEMBER_KINDS }; + if (call) return { name: name!, kinds: CALLABLE_KINDS }; + if (/^[A-Z]\w*[a-z]/.test(name!)) return { name: name!, kinds: TYPE_KINDS }; + if (/^[a-z]\w*[a-z\d][A-Z]/.test(name!) || /^[a-z][a-z\d]*(?:_[a-z\d]+)+$/.test(name!)) { + return { name: name!, kinds: CALLABLE_KINDS }; + } + return null; +} + /** `850ms`, `12s`, `1m 05s`, `2h 03m`. */ export function formatDuration(ms: number): string { if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`; diff --git a/src/features/agents/symbolLinks.test.ts b/src/features/agents/symbolLinks.test.ts new file mode 100644 index 000000000..6b1d45a04 --- /dev/null +++ b/src/features/agents/symbolLinks.test.ts @@ -0,0 +1,81 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { clearMocks, mockIPC } from "@tauri-apps/api/mocks"; +import type { SymbolKind, SymbolMatch } from "@/platform/ipc"; +import { symbolRef } from "./conversation"; +import { inTaskFolder, lookupSymbols, symbolTargets } from "./symbolLinks"; + +const symbol = ( + name: string, + path: string, + kind: SymbolKind = "class", + container: string | null = null, +): SymbolMatch => ({ + name, + kind, + container, + path, + relPath: path.replace(/^\/repo\//, ""), + range: { start: { line: 3, col: 6 }, end: { line: 3, col: 6 + name.length } }, + score: 0, + indices: [], +}); + +afterEach(clearMocks); + +describe("symbolTargets", () => { + const views = [symbol("FooView", "/repo/web/view.ts"), symbol("FooView", "/repo/app/view.ts")]; + + it("keeps only exact matches of the named kind, container and file", () => { + const found = [ + symbol("load", "/repo/a.ts", "method", "Config"), + symbol("load", "/repo/b.ts", "method", "Loader"), + symbol("load", "/repo/c.ts", "variable"), + ]; + expect(symbolTargets(symbolRef("Config.load")!, found, [], "/repo").map((found) => found.path)).toEqual([ + "/repo/a.ts", + ]); + expect(symbolTargets(symbolRef("b.ts#load")!, found, [], "/repo").map((found) => found.path)).toEqual([ + "/repo/b.ts", + ]); + expect(symbolTargets(symbolRef("load()")!, found, [], "/repo").map((found) => found.path)).toEqual([ + "/repo/a.ts", + "/repo/b.ts", + ]); + expect(symbolTargets(symbolRef("FooView")!, [symbol("FooView", "/repo/x.ts", "variable")], [], "/repo")).toEqual( + [], + ); + }); + + it("prefers a file the reply names, then the task's folder", () => { + const ref = symbolRef("FooView")!; + expect(symbolTargets(ref, views, ["/app/view.ts"], "/repo/web").map((found) => found.path)).toEqual([ + "/repo/app/view.ts", + ]); + expect(symbolTargets(ref, views, [], "/repo/web").map((found) => found.path)).toEqual(["/repo/web/view.ts"]); + expect(symbolTargets(ref, views, ["/other.ts"], "/repo")).toHaveLength(2); + }); + + it("puts a worktree task's targets under its own folder", () => { + const [view] = views; + expect(inTaskFolder(view!, "/repo", "/repo/web").path).toBe("/repo/web/view.ts"); + expect(inTaskFolder(view!, "/repo", "/worktrees/fix").path).toBe("/worktrees/fix/web/view.ts"); + }); +}); + +describe("lookupSymbols", () => { + it("asks the index once per name and folder, in one request", async () => { + const asked: string[][] = []; + mockIPC((cmd, args) => { + if (cmd !== "find_symbols_named") return null; + const { names } = args as { names: string[] }; + asked.push(names); + return names.map((name) => symbol(name, `/repo/${name}.ts`)); + }); + const first = lookupSymbols("/batch", ["FooView", "load", "FooView"]); + expect((await first.get("load"))!.map((found) => found.path)).toEqual(["/repo/load.ts"]); + const second = lookupSymbols("/batch", ["load", "BarView"]); + expect((await second.get("BarView"))!.map((found) => found.name)).toEqual(["BarView"]); + await lookupSymbols("/elsewhere", ["load"]).get("load"); + expect(asked).toEqual([["FooView", "load"], ["BarView"], ["load"]]); + }); +}); diff --git a/src/features/agents/symbolLinks.ts b/src/features/agents/symbolLinks.ts new file mode 100644 index 000000000..e6559e13d --- /dev/null +++ b/src/features/agents/symbolLinks.ts @@ -0,0 +1,73 @@ +/** + * Symbol links in agent replies: the names a reply shows are looked up in the symbol index + * in one batch, and each name only once per task folder. + */ +import { call, commands, type SymbolMatch } from "@/platform/ipc"; +import type { SymbolRef } from "./conversation"; + +/** Index answers by the folder they were asked in, then by name. */ +const answers = new Map>>(); +const NAMES_PER_FOLDER = 2000; + +/** The index's symbols named exactly each of `names` inside `within`; one request for the names not asked before. */ +export function lookupSymbols(within: string, names: Iterable): Map> { + const known = answers.get(within) ?? new Map>(); + answers.set(within, known); + const wanted = new Set(names); + const missing = [...wanted].filter((name) => !known.has(name)); + if (missing.length) { + const found = call(commands.findSymbolsNamed(missing, within)).catch(() => []); + for (const name of missing) { + if (known.size >= NAMES_PER_FOLDER) known.delete(known.keys().next().value!); + known.set( + name, + found.then((symbols) => symbols.filter((symbol) => symbol.name === name)), + ); + } + } + return new Map([...wanted].map((name) => [name, known.get(name)!])); +} + +/** Narrows `symbols` by each preference in turn, skipping one that would leave nothing. */ +function preferred(symbols: SymbolMatch[], ...preferences: Array<(symbol: SymbolMatch) => boolean>): SymbolMatch[] { + return preferences.reduce((pool, prefers) => { + const narrowed = pool.filter(prefers); + return narrowed.length ? narrowed : pool; + }, symbols); +} + +const trimSlash = (path: string) => path.replace(/\/$/, ""); +const under = (folder: string, path: string) => path.startsWith(`${trimSlash(folder)}/`); + +/** + * The definitions `ref` names among `symbols` (same name, kind, container and file), the + * ones in a file the reply names first, then the ones in the task's folder `cwd`. + */ +export function symbolTargets( + ref: SymbolRef, + symbols: readonly SymbolMatch[], + mentioned: readonly string[], + cwd: string, +): SymbolMatch[] { + const exact = symbols.filter( + (symbol) => + symbol.name === ref.name && + ref.kinds.includes(symbol.kind) && + (!ref.container || symbol.container?.split(/\.|::/).pop() === ref.container) && + (!ref.file || symbol.path.endsWith(`/${ref.file}`)), + ); + return preferred( + exact, + (symbol) => mentioned.some((path) => symbol.path.endsWith(`/${path.replace(/^\.?\//, "")}`)), + (symbol) => under(cwd, symbol.path), + ); +} + +/** + * `symbol` as the task sees it: a task in a worktree outside the indexed project root has + * the same file under its own folder. + */ +export function inTaskFolder(symbol: SymbolMatch, projectRoot: string, cwd: string): SymbolMatch { + if (trimSlash(cwd) === trimSlash(projectRoot) || under(projectRoot, cwd)) return symbol; + return { ...symbol, path: `${trimSlash(cwd)}/${symbol.relPath}` }; +} diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 0b66bf5bc..a029e7da5 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -17,7 +17,7 @@ import { type ReactNode, type RefObject, } from "react"; -import type { CommitSelection, FileMatches, SearchQuery, RunConfig, RunId } from "@/bindings"; +import type { CommitSelection, FileMatches, Location, SearchQuery, RunConfig, RunId, SymbolKind } from "@/bindings"; import { notifyEach } from "@/platform/listeners"; import type { ProjectType } from "@/ui/projectType"; import type { MenuItem } from "@/ui/Menu"; @@ -700,6 +700,15 @@ export interface EditorService { keepSavedTabs?(): void; /** Edit › Undo / Redo for a focused custom editor that has its own history; false when none takes it. */ documentHistory?(command: "undo" | "redo"): boolean; + /** Go to Declaration's chooser ("Choose Declaration of `name`") over `targets`, below `anchor`. */ + chooseDeclaration?(targets: DeclarationChoice[], name: string, anchor: { x: number; y: number }): Promise; +} + +/** A target of {@link EditorService.chooseDeclaration}: an index symbol's place, name and container. */ +export interface DeclarationChoice extends Location { + name: string; + kind: SymbolKind; + container: string | null; } /** Custom editor documents held still for a window / project close decision. */