fix(run): open a stack frame's file from the run module's scope (#6366)

Clicking a stack frame in the Run console opened another module's copy of a class when several modules of a multi-module Maven build declare the same package and class: the lookup went by file name, and the package check cannot tell same-package copies apart.

Candidates are now narrowed to the run configuration's module and the modules it depends on (transitively, all scopes) before the name and package checks. The module reaches the Run console links, the test tree's Jump to Source and the Debug console links. Without a Maven model, for an unlisted module, or when the scope matches no candidate, the lookup behaves as before.

Closes #6313

Co-authored-by: aconeshana <[email protected]>
Цей коміт міститься в:
aconeshanaтаaconeshana authored and GitHub committed 2026-11-27 14:16:59 +08:00
1 джерело 5bcb37492f
коміт 944b57dead
11 files changed
+333 -15

No files matched your search

+2
Переглянути файл
@@ -93,6 +93,8 @@ describe("Debug console links", () => {
line: 15,
}),
"/repo/demo-app",
true,
undefined,
);
});
+13 -2
Переглянути файл
@@ -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}
/>
</span>
);
+10 -2
Переглянути файл
@@ -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)}
+2
Переглянути файл
@@ -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}
+2
Переглянути файл
@@ -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.
+6 -3
Переглянути файл
@@ -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;
+21 -2
Переглянути файл
@@ -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",
);
});
+99
Переглянути файл
@@ -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"]);
});
});
+72
Переглянути файл
@@ -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<MavenProject>([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;
}
+90
Переглянути файл
@@ -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<string, string> = {
@@ -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}`];
}
});
});
+16 -6
Переглянути файл
@@ -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<boolean> {
}
}
async function findByName(target: FileTarget): Promise<string | null> {
async function findByName(target: FileTarget, module?: string | null): Promise<string | null> {
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<string | null> {
/**
* `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<string | null> {
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<st
if (fromRoot !== candidate && (await exists(fromRoot))) return fromRoot;
}
}
return (await findByName(target)) ?? (target.className ? findLibraryClass(target.className) : null);
return (await findByName(target, module)) ?? (target.className ? findLibraryClass(target.className) : null);
}
/** Regular-expression search over the project's Ruby files (or the given ones). */
@@ -132,7 +142,7 @@ export async function declarationLine(path: string, test: string[]): Promise<num
}
}
export async function openTarget(target: FileTarget, cwd: string, focus = true): Promise<void> {
export async function openTarget(target: FileTarget, cwd: string, focus = true, module?: string | null): Promise<void> {
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({