diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index 8bc0cf4dc..ec7768b39 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -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); })(), ), }, diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 1f0020168..b754dcd48 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -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( diff --git a/src/features/run/contextRun.test.ts b/src/features/run/contextRun.test.ts index 697275955..5435a1740 100644 --- a/src/features/run/contextRun.test.ts +++ b/src/features/run/contextRun.test.ts @@ -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) => + ({ 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); + }); +}); diff --git a/src/features/run/contextRun.ts b/src/features/run/contextRun.ts index 18fb5ac92..d5a1027bc 100644 --- a/src/features/run/contextRun.ts +++ b/src/features/run/contextRun.ts @@ -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 { }); } +/** + * 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 { 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[]) diff --git a/src/features/run/javaDebug.test.ts b/src/features/run/javaDebug.test.ts new file mode 100644 index 000000000..a46c4941f --- /dev/null +++ b/src/features/run/javaDebug.test.ts @@ -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(); + return { + ...ipc, + commands: { ...ipc.commands, debugFreePort: () => Promise.resolve({ status: "ok", data: 50123 }) }, + call: async () => 50123, + }; +}); +vi.mock("@/platform/actions", async (orig) => ({ + ...(await orig()), + 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()), + 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]); + }); +}); diff --git a/src/features/run/javaDebug.ts b/src/features/run/javaDebug.ts index 7502995da..9ad612c87 100644 --- a/src/features/run/javaDebug.ts +++ b/src/features/run/javaDebug.ts @@ -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; } diff --git a/src/features/run/runGutter.ts b/src/features/run/runGutter.ts index c40459484..8b089e5ed 100644 --- a/src/features/run/runGutter.ts +++ b/src/features/run/runGutter.ts @@ -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