fix(run): debug Maven tests from the gutter and attach when Surefire starts the fork (#2684)

The run gutter and context menu offered Debug only for configurations with a debug plan or adapter, so Maven / Gradle tests (debugged through a JDWP agent) had none. Debugging a Maven test attached to the pinned Surefire port right away and java-debug's 30-second retry could run out while Maven recompiled; it now attaches when Maven prints the T E S T S banner just before starting the fork. A failed attach to a JVM started for the debugger now stops that run (as for Python), so its suspended JVM doesn't keep it alive.

Fixes #2656
This commit is contained in:
l0ng-ai
2026-11-11 16:28:14 +08:00
committed by GitHub
parent d7393b53f3
commit 4e86161c3c
7 changed files with 123 additions and 12 deletions
+11 -3
View File
@@ -44,6 +44,7 @@ import {
resumeExecution,
evaluate,
isLive,
justDetached,
rerunSession,
revealFrame,
rootOf,
@@ -454,14 +455,21 @@ export function registerDebugActions(): () => void {
if (isPythonAttachTarget(arg)) launch = pythonAttachConfig(arg, root);
else if (isJavaAttachTarget(arg)) launch = await javaAttachConfig(arg, root);
else return;
const process = (arg.process ?? null) as RunId | null;
// Another JVM of the same run (a Gradle test worker, the one just detached) keeps it.
const shared =
process != null &&
(justDetached(process) ||
Object.values(useDebug.getState().sessions).some((s) => s.process === process && isLive(s)));
const session = await startSession(launch, {
process: (arg.process ?? null) as RunId | null,
process,
runConfig: arg.runConfig,
rerunnable: false,
show: (arg as { show?: boolean }).show,
});
if (session == null && isPythonAttachTarget(arg) && arg.process != null)
await stopAssociatedProcess(arg.process);
// The process was started for this debugger and waits for it (`suspend=y`): without
// the attach it would never go on, and Stop on the finished session can't reach it.
if (session == null && process != null && !shared) await stopAssociatedProcess(process);
})(),
),
},
+1 -1
View File
@@ -291,7 +291,7 @@ function dropFinished() {
* An attach to `process` this soon after a session on it ended may be to such a JVM.
*/
const RELISTEN_MS = 3000;
function justDetached(process: RunId | null | undefined): boolean {
export function justDetached(process: RunId | null | undefined): boolean {
if (process == null) return false;
const now = Date.now();
return Object.values(useDebug.getState().sessions).some(
+20 -1
View File
@@ -3,7 +3,7 @@ import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
import { choiceItems, contextMenuItems } from "./contextRun";
import { canDebugProduced, choiceItems, contextMenuItems } from "./contextRun";
import { OPTIMISTIC, produceContextChoices } from "./producers";
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
import { useRun } from "./store";
@@ -199,3 +199,22 @@ describe("run gutter popup", () => {
expect(gutterTestState({ line: 0, kind: "main", name: "main", path: [] }, path)).toBeNull();
});
});
describe("Debug entry", () => {
const config = (c: Partial<RunConfig>) =>
({ id: "c", name: "c", command: "", args: [], cwd: "", env: {}, ...c }) as RunConfig;
it("is offered for Maven and Gradle tests, which run with a JDWP agent", () => {
const mavenTest = config({ kind: "maven", command: "mvn", args: ["test", "-Dtest=A#b"], isTest: true });
expect(canDebugProduced({ name: "A.b", scope: "element", config: mavenTest })).toBe(true);
const gradleTest = config({
kind: "gradle",
command: "./gradlew",
args: [":app:test", "--tests", "A.b"],
isTest: true,
});
expect(canDebugProduced({ name: "A.b", scope: "element", config: gradleTest })).toBe(true);
expect(
canDebugProduced({ name: "lint", scope: "file", config: config({ kind: "npm", args: ["run", "lint"] }) }),
).toBe(false);
});
});
+10 -2
View File
@@ -32,6 +32,7 @@ import {
hasRelativeImports,
} from "./producers";
import { runWithExecutor } from "./executors";
import { jdwpLaunch } from "./javaDebug";
import { goModulePath, loadGoModules } from "./goModules";
import { isPythonPackage, loadPythonPackages } from "./pythonPackages";
import { remoteDebugBlocked } from "./remote";
@@ -138,6 +139,14 @@ async function buildFirst(build: RunConfig, show?: boolean): Promise<boolean> {
});
}
/**
* Like IDEA, Debug is offered only where a debugger can run it: a debug plan, a debug adapter, or a
* Maven / Gradle configuration whose JVM gets a JDWP agent (a JUnit test run through Surefire).
*/
export function canDebugProduced(p: Produced): boolean {
return !!(p.debug || p.config?.debugAdapter || p.missing || (p.config && jdwpLaunch(p.config)));
}
/** Runs or debugs a production (adopting it as the selected temporary configuration). */
export async function launchProduced(p: Produced, debug: boolean, show?: boolean): Promise<void> {
if (p.missing || !p.config) {
@@ -371,8 +380,7 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
const arg: ContextArg = { path, line, dir, content: dir ? undefined : input.content };
return [
{ kind: "action", action: "run.runContext", arg, label: tx`Run '${p.name}'`, icon: "run" },
// Like IDEA, Debug only where a debugger can run it.
...(p.debug || p.config?.debugAdapter || p.missing
...(canDebugProduced(p)
? ([
{ kind: "action", action: "run.debugContext", arg, label: tx`Debug '${p.name}'`, icon: "debug" },
] as MenuItem[])
+69
View File
@@ -0,0 +1,69 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
const h = vi.hoisted(() => ({
attached: [] as number[],
onLine: null as ((line: string) => void) | null,
}));
vi.mock("@/platform/ipc", async (orig) => {
const ipc = await orig<typeof import("@/platform/ipc")>();
return {
...ipc,
commands: { ...ipc.commands, debugFreePort: () => Promise.resolve({ status: "ok", data: 50123 }) },
call: async () => 50123,
};
});
vi.mock("@/platform/actions", async (orig) => ({
...(await orig<typeof import("@/platform/actions")>()),
executeAction: async (id: string, arg: { port: number }) => {
if (id === "debug.attach") h.attached.push(arg.port);
return true;
},
}));
vi.mock("./store", async (orig) => ({
...(await orig<typeof import("./store")>()),
startRun: async (_config: RunConfig, _reuse: unknown, _base: unknown, options: { onLine: (l: string) => void }) => {
h.onLine = options.onLine;
return { id: "s1" };
},
}));
import { debugWithAgent, isTestForkBanner } from "./javaDebug";
const mavenTest: RunConfig = {
id: "t",
name: "SolutionTest.test_numSquares",
kind: "maven",
command: "mvn",
args: ["test", "-Dtest=SolutionTest#test_numSquares"],
cwd: "",
env: {},
isTest: true,
} as unknown as RunConfig;
beforeEach(() => {
h.attached = [];
h.onLine = null;
});
describe("Maven test debugging", () => {
it("recognizes the banner Surefire prints before it starts the fork, coloured or not", () => {
expect(isTestForkBanner("[INFO] T E S T S")).toBe(true);
expect(isTestForkBanner("[\x1b[1;34mINFO\x1b[m] T E S T S")).toBe(true);
expect(isTestForkBanner(" T E S T S")).toBe(true);
expect(isTestForkBanner("[INFO] Tests run: 1, Failures: 0")).toBe(false);
});
it("attaches to the pinned port when the fork starts, not while Maven still compiles", async () => {
await debugWithAgent(mavenTest);
expect(h.attached).toEqual([]);
h.onLine!("[INFO] --- compiler:3.15.0:testCompile (default-testCompile) @ leetcode-java ---");
expect(h.attached).toEqual([]);
h.onLine!("[INFO] -------------------------------------------------------");
h.onLine!("[INFO] T E S T S");
expect(h.attached).toEqual([50123]);
// The fork's own line, released once the tests run, doesn't attach twice.
h.onLine!("Listening for transport dt_socket at address: 50123");
expect(h.attached).toEqual([50123]);
});
});
+10 -3
View File
@@ -86,6 +86,13 @@ export function jdwpLaunch(config: RunConfig, jdwpPort?: number): RunConfig | nu
return null;
}
/**
* Surefire / Failsafe print this banner just before they start the forked test JVM. It comes from
* Maven itself, so unlike the fork's "Listening" line it is not held back until the tests run.
*/
const SGR = /\x1b\[[0-9;]*m/g; // eslint-disable-line no-control-regex
export const isTestForkBanner = (line: string) => /^(?:\[INFO\])?\s*T E S T S$/.test(line.replace(SGR, "").trim());
/** A Maven test launch: its Surefire / Failsafe fork holds the "Listening" line, so pin its JDWP port. */
function needsPinnedPort(config: RunConfig): boolean {
if (config.kind !== "maven" && !/(^|\/)mvnw?(\.cmd)?$/.test(config.command)) return false;
@@ -119,7 +126,9 @@ export async function debugWithAgent(config: RunConfig, show?: boolean): Promise
launch,
show,
onLine: (line) => {
const port = jdwpListeningPort(line);
// The pinned port is attached when the fork starts: java-debug retries the connect for
// 30 s, which compiling and resolving dependencies before the tests can use up.
const port = jdwpListeningPort(line) ?? (pinned !== null && isTestForkBanner(line) ? pinned : null);
if (port === null) return;
if (sessionId) attach(port);
else waiting.push(port);
@@ -127,8 +136,6 @@ export async function debugWithAgent(config: RunConfig, show?: boolean): Promise
});
if (!session) return true;
sessionId = session.id;
// The pinned port needs no output line: java-debug retries the attach while the fork starts.
if (pinned !== null) attach(pinned);
waiting.splice(0).forEach(attach);
return true;
}
+2 -2
View File
@@ -13,6 +13,7 @@ import { shortcutLabel } from "@/platform/keymap";
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
import { notifications, runExecutors } from "@/workbench/contributions";
import {
canDebugProduced,
choiceItems,
executeContext,
launchProduced,
@@ -105,8 +106,7 @@ export function targetMenuItems(target: RunTarget, path: string, content: string
choices.length > 1
? { submenu: choiceItems(choices, debug).filter((i) => i.kind !== "header") }
: { run: () => void launch(target, path, debug, content) };
// Like IDEA, Debug only where a debugger can run it.
const debuggable = !p || !!(p.debug || p.config?.debugAdapter || p.missing);
const debuggable = !p || canDebugProduced(p);
return [
{ label: tx`Run '${name}'`, icon: "run", shortcut: shortcutLabel("run.runContext"), ...pick(false) } as MenuItem,
...(debuggable