diff --git a/src/features/debugger/__tests__/debugConsoleLinks.test.tsx b/src/features/debugger/__tests__/debugConsoleLinks.test.tsx index 3e0e78ecc6..14e260813f 100644 --- a/src/features/debugger/__tests__/debugConsoleLinks.test.tsx +++ b/src/features/debugger/__tests__/debugConsoleLinks.test.tsx @@ -93,6 +93,8 @@ describe("Debug console links", () => { line: 15, }), "/repo/demo-app", + true, + undefined, ); }); diff --git a/src/features/debugger/ui/DebugConsole.tsx b/src/features/debugger/ui/DebugConsole.tsx index ad16a84e0a..819f5ca3fe 100644 --- a/src/features/debugger/ui/DebugConsole.tsx +++ b/src/features/debugger/ui/DebugConsole.tsx @@ -55,19 +55,22 @@ const DebugLine = memo( marks, rules, cwd, + module, }: { line: ConsoleLine; marks?: readonly SegmentMark[]; rules?: ConsoleRuleMatch; length: number; cwd: string; + /** The run's owning module, which picks between same-named files of a multi-module build. */ + module?: string | null; }) { const spans = rules ? styleSpans(line.spans, rules) : line.spans; const segments = segmentLine(spans, line.category === "system" ? [] : findOutputLinks(line.text), marks); const activate = (e: MouseEvent, link: OutputLink) => { e.preventDefault(); if (window.getSelection()?.toString()) return; - if (link.kind !== "url") void openTarget(link.target, cwd); + if (link.kind !== "url") void openTarget(link.target, cwd, true, module); else if (!debugConsoleUrl(e, link.url)) void openUrl(link.url); }; if (segments.length === 0) return <>{"\u200B"}; @@ -111,7 +114,13 @@ const DebugLine = memo( ); }, - (a, b) => a.line === b.line && a.length === b.length && a.cwd === b.cwd && a.marks === b.marks && a.rules === b.rules, + (a, b) => + a.line === b.line && + a.length === b.length && + a.cwd === b.cwd && + a.module === b.module && + a.marks === b.marks && + a.rules === b.rules, ); export function DebugServiceConsole({ sessionId }: { sessionId: number }) { @@ -194,6 +203,7 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe () => runDirectory(session.launch?.cwd ?? session.runConfig?.cwd), [session.launch?.cwd, session.runConfig?.cwd], ); + const module = session.runConfig?.module; // Find (⌘F): search the whole buffer, not just the rendered rows. const found = useMemo( @@ -495,6 +505,7 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe rules={ruled} length={l.text.length} cwd={cwd} + module={module} /> ); diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx index dd0aa1efa2..e54ffd3056 100644 --- a/src/features/run/ConsoleView.tsx +++ b/src/features/run/ConsoleView.tsx @@ -44,6 +44,7 @@ const Line = memo( marks, rules, cwd, + module, currentLink, }: { line: ConsoleLine; @@ -51,6 +52,8 @@ const Line = memo( rules?: ConsoleRuleMatch; length: number; cwd: string; + /** The run's owning module, which picks between same-named files of a multi-module build. */ + module?: string | null; /** Start of the link Previous / Next Occurrence stepped to on this line. */ currentLink?: number; }) { @@ -60,7 +63,7 @@ const Line = memo( const activate = (e: MouseEvent, link: OutputLink) => { e.preventDefault(); if (window.getSelection()?.toString()) return; - if (link.kind !== "url") void openTarget(link.target, cwd); + if (link.kind !== "url") void openTarget(link.target, cwd, true, module); else if (!debugConsoleUrl(e, link.url)) void openUrl(link.url); }; // A blank line is an empty row: its height comes from CSS, never from a character in the text. @@ -110,6 +113,7 @@ const Line = memo( a.line === b.line && a.length === b.length && a.cwd === b.cwd && + a.module === b.module && a.marks === b.marks && a.rules === b.rules && a.currentLink === b.currentLink, @@ -235,6 +239,8 @@ export interface ConsoleViewProps { onFollowChange: (follow: boolean) => void; /** Directory relative paths in the output resolve against. */ cwd: string; + /** The run's owning module (`RunConfig` module), when it has one. */ + module?: string | null; onClear?: () => void; /** Set while the process accepts input. */ input?: ConsoleInput; @@ -253,6 +259,7 @@ export function ConsoleView({ follow, onFollowChange, cwd, + module, onClear, input, findOpen: controlledFindOpen, @@ -489,7 +496,7 @@ export function ConsoleView({ programmatic.current = true; virtualizer.scrollToIndex(rowOfLine.get(hit.line)!, { align: "center" }); requestAnimationFrame(() => (programmatic.current = false)); - void openTarget(hit.link.target, cwd, focus); + void openTarget(hit.link.target, cwd, focus, module); return { index: index + 1, total: links.length }; }); @@ -755,6 +762,7 @@ export function ConsoleView({ rules={ruled} length={line.text.length} cwd={cwd} + module={module} currentLink={currentLink?.lineId === line.id ? currentLink.start : undefined} /> {row.fold && !row.fold.expanded && foldButton(row.fold, true)} diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx index 58190ea029..c660391ddc 100644 --- a/src/features/run/RunView.tsx +++ b/src/features/run/RunView.tsx @@ -251,6 +251,7 @@ export function SessionPanel({ findOpen={findOpen} onFindOpenChange={setFindOpen} cwd={cwd} + module={session.config.module} onClear={() => clearConsole(session.id)} // A test run's Previous / Next Occurrence go through its failed tests. occurrences={rt.tests ? undefined : showLifecycle ? "run" : SERVICES_WINDOW} @@ -413,6 +414,7 @@ export function SessionPanel({ results={rt.tests} version={version} cwd={cwd} + module={session.config.module} running={testsRunning} name={session.config.name} selected={selectedTest} diff --git a/src/features/run/TestTreeView.test.tsx b/src/features/run/TestTreeView.test.tsx index 800aa0a132..4285ac6186 100644 --- a/src/features/run/TestTreeView.test.tsx +++ b/src/features/run/TestTreeView.test.tsx @@ -85,6 +85,7 @@ describe("TestTreeView", () => { expect.objectContaining({ path: "MathTest.java", line: 9 }), "/p", true, + undefined, ); }); @@ -276,6 +277,7 @@ describe("Previous / Next Failed Test", () => { expect.objectContaining({ path: "DbTest.java", line: 20 }), "/p", false, + undefined, ); go(-1, true); // reads() has no location: nothing to open. diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx index d75e85f500..2d7f381244 100644 --- a/src/features/run/TestTreeView.tsx +++ b/src/features/run/TestTreeView.tsx @@ -199,6 +199,8 @@ export interface TestTreeViewProps { results: TestResults; version: number; cwd: string; + /** The run's owning module, which picks between same-named files of a multi-module build. */ + module?: string | null; selected: string | null; onSelect: (id: string | null) => void; running: boolean; @@ -218,6 +220,7 @@ export function TestTreeView({ results, version, cwd, + module, selected, onSelect, running, @@ -262,13 +265,13 @@ export function TestTreeView({ const jumpToSource = (n: TestNode) => { const target = n.location ?? firstLocated(n)?.location; - if (target) void openTarget(target, cwd, true); + if (target) void openTarget(target, cwd, true, module); }; // The agents feature's action: the failure becomes a draft the user reviews and sends. const diagnose = async (n: TestNode, name: string) => { const located = n.location ?? firstLocated(n)?.location; - const path = located ? await resolveTarget(located, cwd).catch(() => null) : null; + const path = located ? await resolveTarget(located, cwd, module).catch(() => null) : null; // Rust's `left` / `right` don't say which side is expected; the output excerpt shows them as written. const parsed = parseComparison(n.output); const comparison = parsed?.labels ? null : parsed; @@ -424,7 +427,7 @@ export function TestTreeView({ const step = tree.current?.selectOccurrence(dir); if (!step) return null; const n = step.node as TestNode; - if (n.location) void openTarget(n.location, cwd, focus); + if (n.location) void openTarget(n.location, cwd, focus, module); return step; }); const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null; diff --git a/src/features/run/consoleStackTrace.test.tsx b/src/features/run/consoleStackTrace.test.tsx index 1d56892316..40a7b6c695 100644 --- a/src/features/run/consoleStackTrace.test.tsx +++ b/src/features/run/consoleStackTrace.test.tsx @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useState } from "react"; -import { act, cleanup, render, within } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, within } from "@testing-library/react"; import { useProject } from "@/platform/project"; import { occurrenceNavigator } from "@/workbench/contributions"; import { ConsoleModel } from "./console"; @@ -123,7 +123,7 @@ describe("stepFileLink", () => { }); describe("Up / Down the Stack Trace in the console", () => { - function setup(occurrences: string | undefined, text = PANIC.join("\n") + "\n") { + function setup(occurrences: string | undefined, text = PANIC.join("\n") + "\n", module?: string) { const onFollowChange = vi.fn(); const m = model(text); function Run() { @@ -139,6 +139,7 @@ describe("Up / Down the Stack Trace in the console", () => { setFollow(v); }} cwd="/home/me/app" + module={module} occurrences={occurrences} /> ); @@ -156,6 +157,7 @@ describe("Up / Down the Stack Trace in the console", () => { expect.objectContaining({ path: "/home/me/app/parse.go", line: 12 }), "/home/me/app", false, + undefined, ); expect(onFollowChange).toHaveBeenCalledWith(false); expect(scrolled.at(-1)).toBe(4); @@ -168,6 +170,7 @@ describe("Up / Down the Stack Trace in the console", () => { expect.objectContaining({ path: "/home/me/app/main.go", line: 7 }), "/home/me/app", true, + undefined, ); expect(current().map((a) => a.textContent)).toEqual(["/home/me/app/main.go:7"]); @@ -192,6 +195,7 @@ describe("Up / Down the Stack Trace in the console", () => { expect.objectContaining({ path: "/home/me/app/main.go" }), "/home/me/app", false, + undefined, ); }); @@ -221,6 +225,21 @@ describe("Up / Down the Stack Trace in the console", () => { expect.objectContaining({ path: "/home/me/app/b.go" }), "/home/me/app", false, + undefined, + ); + }); + + it("hands the run's module to the link it opens", () => { + const { log } = setup(undefined, undefined, "app"); + const link = [...log.querySelectorAll("a")].find((a) => a.textContent === "/home/me/app/parse.go:12"); + act(() => { + fireEvent.click(link!); + }); + expect(nav.openTarget).toHaveBeenLastCalledWith( + expect.objectContaining({ path: "/home/me/app/parse.go", line: 12 }), + "/home/me/app", + true, + "app", ); }); diff --git a/src/features/run/moduleScope.test.ts b/src/features/run/moduleScope.test.ts new file mode 100644 index 0000000000..6361bd972e --- /dev/null +++ b/src/features/run/moduleScope.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "vitest"; +import type { MavenModel, MavenProject } from "@/platform/ipc"; +import { mavenModuleScope, scopeToRunModule } from "./moduleScope"; + +function project(dir: string, artifactId: string, dependsOn: string[] = []): MavenProject { + return { + pom: dir ? `${dir}/pom.xml` : "pom.xml", + dir, + groupId: "com.example", + artifactId, + version: "1.0", + packaging: "jar", + displayName: artifactId, + parent: null, + modules: [], + aggregated: true, + plugins: [], + dependencies: dependsOn.map((target) => ({ + groupId: "com.example", + artifactId: target, + version: "1.0", + type: "jar", + classifier: null, + scope: "test", + optional: false, + children: [], + })), + profiles: [], + javaVersion: 8, + command: "mvn", + options: [], + env: {}, + }; +} + +const model = (projects: MavenProject[]): { maven: MavenModel } => ({ + maven: { projects, profiles: [], syncedAt: 0, stale: false, syncError: null }, +}); + +/** app → web-common → core; reporting and core-extra depend on nothing shared. */ +const nested = model([ + project("app", "app", ["web-common"]), + project("web-common", "web-common", ["core"]), + project("core", "core"), + project("reporting", "reporting"), + project("core-extra", "core-extra"), +]); + +describe("mavenModuleScope", () => { + it("follows module dependencies transitively", () => { + expect(mavenModuleScope("/p", "app", nested)?.sort()).toEqual(["/p/app", "/p/core", "/p/web-common"]); + }); + + it("counts every dependency scope, so a test run keeps its test-only modules", () => { + expect(mavenModuleScope("/p", "app", nested)).toContain("/p/core"); + }); + + it("is unknown for a module the model doesn't list, or without a model", () => { + expect(mavenModuleScope("/p", "gone", nested)).toBeNull(); + expect(mavenModuleScope("/p", "app", null)).toBeNull(); + expect(mavenModuleScope(null, "app", nested)).toBeNull(); + }); + + it("ignores a linked build's projects: their folders aren't under this root", () => { + const linked = model([ + project("app", "app", ["shared"]), + { ...project("shared", "shared"), projectRoot: "/elsewhere" }, + ]); + expect(mavenModuleScope("/p", "app", linked)).toEqual(["/p/app"]); + }); + + it("takes an absolute module, as imported IDEA configurations carry one", () => { + expect(mavenModuleScope("/p", "/p/core", nested)).toEqual(["/p/core"]); + }); +}); + +describe("scopeToRunModule", () => { + const hits = [ + "/p/reporting/src/main/java/com/example/Task.java", + "/p/core/src/main/java/com/example/Task.java", + "/p/core-extra/src/main/java/com/example/Task.java", + ]; + + it("drops copies from modules the run doesn't depend on", () => { + expect(scopeToRunModule(hits, "/p", "core", nested)).toEqual(["/p/core/src/main/java/com/example/Task.java"]); + }); + + it("doesn't treat a folder whose name starts with the module's as the module", () => { + expect(scopeToRunModule(["/p/core/Task.java", "/p/core-extra/Task.java"], "/p", "core", nested)).toEqual([ + "/p/core/Task.java", + ]); + }); + + it("keeps every candidate when the scope is unknown or matches none", () => { + expect(scopeToRunModule(hits, "/p", null, nested)).toEqual(hits); + expect(scopeToRunModule(hits, "/p", "gone", nested)).toEqual(hits); + expect(scopeToRunModule(["/other/Task.java"], "/p", "core", nested)).toEqual(["/other/Task.java"]); + }); +}); diff --git a/src/features/run/moduleScope.ts b/src/features/run/moduleScope.ts new file mode 100644 index 0000000000..d067ffd15e --- /dev/null +++ b/src/features/run/moduleScope.ts @@ -0,0 +1,72 @@ +/** + * Where a run's JVM stack frames can come from: the module a run configuration belongs to and + * the modules it depends on. A multi-module build compiles the same package and class name in + * several modules, so a frame's file name alone doesn't say which copy ran — only the run's + * classpath does. + */ +import type { BuildModel, MavenModel, MavenProject } from "@/platform/ipc"; + +/** Folders `dir` of the model's projects, as the IDE reports paths: absolute, `/`-separated. */ +function absolute(root: string, dir: string): string { + const base = root.replace(/\/+$/, ""); + const rest = dir.replace(/^\/+/, "").replace(/\/+$/, ""); + return rest ? `${base}/${rest}` : base; +} + +/** The project a run configuration's module refers to (`""` = the project root). */ +function projectOf(projects: MavenProject[], root: string, module: string): MavenProject | undefined { + const wanted = module.startsWith("/") ? module.replace(/\/+$/, "") : absolute(root, module); + return projects.find((p) => absolute(root, p.dir) === wanted); +} + +/** + * Folders (absolute) of the run module and its Maven module dependencies, transitively, or + * `null` when the model doesn't say — no build model, a module it doesn't list — in which case + * callers keep their name-only lookup. + */ +export function mavenModuleScope( + root: string | null, + module: string | null | undefined, + model: BuildModel | null, +): string[] | null { + const maven: MavenModel | null | undefined = model?.maven; + if (!root || !maven) return null; + // Linked builds carry another project's folders: their `dir` isn't relative to this root. + const projects = maven.projects.filter((p) => !p.projectRoot || p.projectRoot === root); + const start = projectOf(projects, root, module ?? ""); + if (!start) return null; + const byCoordinates = new Map(projects.map((p) => [`${p.groupId}:${p.artifactId}`, p])); + const scope = new Set([start]); + const queue = [start]; + while (queue.length) { + const project = queue.pop()!; + for (const dep of project.dependencies) { + // Every scope counts: a test run compiles against test dependencies too, and a folder left + // out here would send a frame to another module's copy of the class. + const next = byCoordinates.get(`${dep.groupId}:${dep.artifactId}`); + if (next && !scope.has(next)) { + scope.add(next); + queue.push(next); + } + } + } + return [...scope].map((p) => absolute(root, p.dir)); +} + +/** + * `hits` narrowed to the run's module scope: a same-named file of a module the run doesn't + * depend on is another module's copy. Unchanged when the scope is unknown or matches nothing, + * so a lookup never gets worse than the name-only one it replaces. + */ +export function scopeToRunModule( + hits: string[], + root: string | null, + module: string | null | undefined, + model: BuildModel | null, +): string[] { + if (module == null) return hits; + const dirs = mavenModuleScope(root, module, model); + if (!dirs) return hits; + const scoped = hits.filter((path) => dirs.some((dir) => path.startsWith(`${dir}/`))); + return scoped.length ? scoped : hits; +} diff --git a/src/features/run/navigate.test.ts b/src/features/run/navigate.test.ts index a32aaaa48b..7b88caf487 100644 --- a/src/features/run/navigate.test.ts +++ b/src/features/run/navigate.test.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { jvmFrameTarget } from "./links"; +import { useBuildModel } from "@/platform/buildModel"; +import type { MavenModel, MavenProject } from "@/platform/ipc"; import { useRemote } from "@/platform/remote"; const files: Record = { @@ -121,3 +123,91 @@ describe("JVM stack frame resolution", () => { expect(await resolveTarget(jvmFrameTarget("java.awt.List$X", "List.java", 1), "/p")).toBeNull(); }); }); + +/** A Maven project of the multi-module fixture: its folder, artifact and the modules it depends on. */ +function moduleProject(dir: string, artifactId: string, dependsOn: string[] = []): MavenProject { + return { + pom: dir ? `${dir}/pom.xml` : "pom.xml", + dir, + groupId: "com.example", + artifactId, + version: "1.0", + packaging: dir ? "jar" : "pom", + displayName: artifactId, + parent: null, + modules: [], + aggregated: !!dir, + plugins: [], + dependencies: dependsOn.map((target) => ({ + groupId: "com.example", + artifactId: target, + version: "1.0", + type: "jar", + classifier: null, + scope: "compile", + optional: false, + children: [], + })), + profiles: [], + javaVersion: 8, + command: "mvn", + options: [], + env: {}, + }; +} + +describe("JVM stack frames of a multi-module build", () => { + afterEach(() => useBuildModel.setState({ root: null, model: null, gradleOffline: false })); + + /** module-a/b/c each hold com.example.task.DoTaskController; app depends on module-c only. */ + const multiModule = (): MavenModel => ({ + projects: [ + moduleProject( + "", + "repro-parent", + ["module-a", "module-b", "module-c", "app"].map((d) => `unused-${d}`), + ), + moduleProject("module-a", "module-a"), + moduleProject("module-b", "module-b"), + moduleProject("module-c", "module-c"), + moduleProject("app", "app", ["module-c"]), + ], + profiles: [], + syncedAt: 0, + stale: false, + syncError: null, + }); + + it("opens the copy the run's module depends on, not the first one the index lists", async () => { + const tail = "src/main/java/com/example/task/DoTaskController.java"; + const dirs = ["module-a", "module-b", "module-c"]; + for (const dir of dirs) files[`/p/${dir}/${tail}`] = "package com.example.task;\nclass DoTaskController {}"; + useBuildModel.setState({ root: "/p", model: { maven: multiModule() }, gradleOffline: false }); + try { + // The frame names module-c's class, whose line 107 throws; module-a's copy is what a + // name-only lookup finds first. + expect( + await resolveTarget( + jvmFrameTarget("com.example.task.DoTaskController", "DoTaskController.java", 107), + "/p/app", + "app", + ), + ).toBe(`/p/module-c/${tail}`); + } finally { + for (const dir of dirs) delete files[`/p/${dir}/${tail}`]; + } + }); + + it("keeps the name-only lookup when the run's module is unknown", async () => { + const tail = "src/main/java/com/example/task/DoTaskController.java"; + for (const dir of ["module-a", "module-c"]) files[`/p/${dir}/${tail}`] = "package com.example.task;"; + useBuildModel.setState({ root: "/p", model: { maven: multiModule() }, gradleOffline: false }); + try { + expect( + await resolveTarget(jvmFrameTarget("com.example.task.DoTaskController", "DoTaskController.java", 107), "/p"), + ).toBe(`/p/module-a/${tail}`); + } finally { + for (const dir of ["module-a", "module-c"]) delete files[`/p/${dir}/${tail}`]; + } + }); +}); diff --git a/src/features/run/navigate.ts b/src/features/run/navigate.ts index bae41f798f..15dbee9482 100644 --- a/src/features/run/navigate.ts +++ b/src/features/run/navigate.ts @@ -5,7 +5,9 @@ import { useProject } from "@/platform/project"; import { useRemote } from "@/platform/remote"; import { editorService, notifications } from "@/workbench/contributions"; import { streamSearch } from "@/platform/textSearch"; +import { useBuildModel } from "@/platform/buildModel"; import { joinPath, type FileTarget } from "./links"; +import { scopeToRunModule } from "./moduleScope"; import { findRubyTest } from "./rubyTests"; import { tx } from "@/platform/i18n"; @@ -35,17 +37,21 @@ async function declaresPackage(path: string, pkg: string): Promise { } } -async function findByName(target: FileTarget): Promise { +async function findByName(target: FileTarget, module?: string | null): Promise { const name = target.path.split("/").pop() ?? target.path; try { const remote = useRemote.getState().session; // Older remote servers only have fuzzy search: request the whole inventory before filtering. - const hits = + const found = remote && !remote.commands.includes("find_files_named") ? (await call(commands.findFiles(name, (await call(commands.indexStatus())).files))) .filter((h) => h.relPath.split("/").pop() === name) .map((h) => h.path) : await call(commands.findFilesNamed(name)); + // A multi-module build compiles the same class in several modules; the run only has the + // one on its classpath, so its module's folder decides before the name does. + const build = useBuildModel.getState(); + const hits = scopeToRunModule(found, build.root, module, build.model); const tail = target.path.replace(/^\.?\//, ""); const exact = hits.find((path) => path === tail || path.endsWith(`/${tail}`)); if (exact) return exact; @@ -86,7 +92,11 @@ export function runDirectory(cwd: string | null | undefined): string { return cwd ? joinPath(root, cwd) : root; } -export async function resolveTarget(target: FileTarget, cwd: string): Promise { +/** + * `cwd` resolves relative paths; `module` is the run configuration's owning module (RunConfig + * `module`), which picks between same-named files of a multi-module build. + */ +export async function resolveTarget(target: FileTarget, cwd: string, module?: string | null): Promise { if (target.resolve === "path") { const candidate = joinPath(cwd, target.path); if (await exists(candidate)) return candidate; @@ -97,7 +107,7 @@ export async function resolveTarget(target: FileTarget, cwd: string): Promise { +export async function openTarget(target: FileTarget, cwd: string, focus = true, module?: string | null): Promise { if (!isTauri()) return; if (target.resolve === "rubyTest") { const site = target.className @@ -151,7 +161,7 @@ export async function openTarget(target: FileTarget, cwd: string, focus = true): await editorService().openFile(site.path, { selection: { line: site.line - 1, col: 0 }, focus }); return; } - const path = await resolveTarget(target, cwd); + const path = await resolveTarget(target, cwd, module); if (!path && target.className) { // A library or JDK frame without sources: nothing to open, which is no error. notifications().notify({