feat(debug): reload classes after Recompile and builds, and sync exploded Tomcat deployments (#5601)

Settings › Build, Execution, Deployment › Debugger › HotSwap › Reload classes after compilation (Ask by default, Always, Never) decides what happens after a successful Build Project, Build Module or Recompile of a Java project while a debug session supports hot code replace: Ask offers "Reload '<file>.java' into the running debug session?", Always reloads at once, Never stays silent. The same setting applies to the language server's build-complete event, and overlapping prompts within two seconds are merged. After a single-file Recompile, classes that compiled cleanly are reloaded even if another file of the module still has errors.

Build completion is published as onBuildCompleted in contributions, and a running Tomcat with an exploded artifact deployment syncs its outputs after such a build (silently while it is debugged).

Co-authored-by: RuyimgByCN <[email protected]>
Цей коміт міститься в:
RuyimgByCN authored and GitHub committed 2026-11-25 01:20:59 +08:00
1 джерело 748e5cee89
коміт b3e4bd63f1
19 files changed
+362 -21

No files matched your search

+53 -1
Переглянути файл
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const executeAction = vi.hoisted(() => vi.fn());
vi.mock("@/platform/actions", async (importOriginal) => ({
@@ -39,11 +39,15 @@ vi.mock("@/workbench/contributions", async (importOriginal) => {
import { IpcError, type DebugCapabilities, type DebugSessionId } from "@/platform/ipc";
import { getContext } from "@/platform/context";
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { notifyBuildCompleted } from "@/workbench/contributions";
import {
cancelHotSwapBuild,
hotSwapMenuItems,
hotSwapMessage,
installBuildHotSwap,
onHotCodeReplace,
onJavaBuildCompleted,
reloadChangedClasses,
} from "../hotswap";
import { publishContext, useDebug, type DebugSession } from "../state";
@@ -83,6 +87,7 @@ function session(id: number, hotCodeReplace: boolean): DebugSession {
describe("HotSwap", () => {
beforeEach(() => {
notes.length = 0;
useProject.setState({ project: null, settings: undefined });
executeAction.mockClear();
ipc.cancelRequest.mockClear();
ipc.javaBuildWorkspace.mockClear();
@@ -94,6 +99,10 @@ describe("HotSwap", () => {
publishContext();
});
afterEach(() => {
vi.restoreAllMocks();
});
it("is enabled only with a session whose adapter can redefine classes", () => {
expect(getContext().debugCanHotSwap).toBe(true);
useDebug.setState({ sessions: { 2: session(2, false) }, active: 2 });
@@ -361,4 +370,47 @@ describe("HotSwap", () => {
onHotCodeReplace(99 as DebugSessionId, { kind: "hotCodeReplace", changeType: "ERROR", message: "not ours" });
expect(notes.length).toBe(before);
});
it("asks or auto-reloads after Recompile or Java build according to debugger.hotSwapAfterCompile", async () => {
vi.spyOn(Date, "now").mockReturnValue(Date.now() + 240_000);
const off = installBuildHotSwap();
try {
// Never policy stays silent on both user builds and JDT BUILD_COMPLETE events.
useProject.setState({ settings: { debugger: { hotSwapAfterCompile: "never" } } as never });
notifyBuildCompleted({ kind: "compileFile", file: "/p/app/src/Main.java", system: "javac", userInitiated: true });
onHotCodeReplace(1 as DebugSessionId, { kind: "hotCodeReplace", changeType: "BUILD_COMPLETE", message: "" });
expect(notes).toEqual([]);
expect(ipc.debugRedefineClasses).not.toHaveBeenCalled();
// Ask policy prompts with the recompiled filename and allows redefineClasses even if JDT sees a sibling error.
useProject.setState({ settings: { debugger: { hotSwapAfterCompile: "ask" } } as never });
notifyBuildCompleted({ kind: "compileFile", file: "/p/app/src/Main.java", system: "maven", userInitiated: true });
expect(notes.at(-1)).toMatchObject({
level: "info",
title: "Classes changed",
body: "Reload 'Main.java' into the running debug session?",
});
ipc.javaBuildWorkspace.mockImplementationOnce(() => ipc.ok("withErrors"));
notes.at(-1)!.actions![0]!.run();
await vi.waitFor(() => expect(ipc.debugRedefineClasses).toHaveBeenCalledWith(1));
expect(notes.at(-1)).toMatchObject({ level: "info", title: "2 classes reloaded" });
// Non-user-initiated or non-Java builds do not prompt.
const before = notes.length;
onJavaBuildCompleted({ kind: "build", file: null, system: "maven", userInitiated: false });
onJavaBuildCompleted({ kind: "build", file: null, system: "cargo", userInitiated: true });
expect(notes.length).toBe(before);
// Always policy reloads immediately without a confirmation prompt.
useProject.setState({ settings: { debugger: { hotSwapAfterCompile: "always" } } as never });
ipc.javaBuildWorkspace.mockClear();
ipc.debugRedefineClasses.mockClear();
vi.spyOn(Date, "now").mockReturnValue(Date.now() + 360_000);
notifyBuildCompleted({ kind: "build", file: null, system: "gradle", userInitiated: true });
await vi.waitFor(() => expect(ipc.debugRedefineClasses).toHaveBeenCalledWith(1));
expect(notes.at(-1)).toMatchObject({ level: "info", title: "2 classes reloaded" });
} finally {
off();
}
});
});
+1
Переглянути файл
@@ -595,6 +595,7 @@ export function registerDebugActions(): () => void {
typeof arg === "object" && arg !== null && "configId" in arg && typeof arg.configId === "string"
? arg.configId
: undefined,
typeof arg === "object" && arg !== null && "allowBuildErrors" in arg && arg.allowBuildErrors === true,
),
},
{
+70 -11
Переглянути файл
@@ -17,12 +17,20 @@ import {
} from "@/platform/ipc";
import { setContext } from "@/platform/context";
import { executeAction } from "@/platform/actions";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { basename } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
import {
maybeEditorService,
notifications,
onBuildCompleted,
type BuildCompletedEvent,
} from "@/workbench/contributions";
import { isLive, selectFrame, selectSession, useDebug, type DebugSession } from "./state";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui/Menu";
const KEY = "debug.hotswap";
const JAVA_BUILD_SYSTEMS = new Set(["maven", "gradle", "javac"]);
/** `BUILD_COMPLETE` events of our own build are not worth a prompt. */
let quietUntil = 0;
/** The compile request HotSwap is waiting on, so it can be cancelled. */
@@ -105,7 +113,7 @@ function obsoleteFrameActions(sessions: DebugSession[]) {
}
/** Compiles (unless `build` is false) and reloads changed classes into every Java debug session. */
export async function reloadChangedClasses(build = true, configId?: string): Promise<void> {
export async function reloadChangedClasses(build = true, configId?: string, allowBuildErrors = false): Promise<void> {
if (reloading) return;
const sessions = hotSwapSessions().filter((s) => !configId || s.runConfig?.id === configId);
if (!sessions.length || !isTauri()) {
@@ -114,6 +122,7 @@ export async function reloadChangedClasses(build = true, configId?: string): Pro
}
reloading = true;
quietUntil = Date.now() + 60_000;
let buildFailed = false;
try {
if (build) {
try {
@@ -159,14 +168,19 @@ export async function reloadChangedClasses(build = true, configId?: string): Pro
return;
}
if (status === "failed" || status === "withErrors" || status === null) {
notifications().notify({
group: "run",
level: "error",
key: KEY,
title: "Hot Swap failed",
body: "Compilation failed: fix the errors and reload again.",
});
return;
if (!allowBuildErrors) {
notifications().notify({
group: "run",
level: "error",
key: KEY,
title: "Hot Swap failed",
body: "Compilation failed: fix the errors and reload again.",
});
return;
}
// Single-file Recompile succeeded with javac; another file in the module may still fail
// in JDT, so continue to redefine any classes compiled cleanly before this error.
buildFailed = true;
}
}
}
@@ -195,6 +209,16 @@ export async function reloadChangedClasses(build = true, configId?: string): Pro
errors.push(e instanceof Error ? e.message : String(e));
}
}
if (buildFailed && changed.size === 0 && errors.length === 0) {
notifications().notify({
group: "run",
level: "error",
key: KEY,
title: "Hot Swap failed",
body: "Compilation failed: fix the errors and reload again.",
});
return;
}
const affected = obsolete.flatMap((id) => useDebug.getState().sessions[id] ?? []);
const m = hotSwapMessage(
changed.size,
@@ -213,12 +237,46 @@ export async function reloadChangedClasses(build = true, configId?: string): Pro
}
}
/** Handles a completed user build (`Build Project`, `Build Module`, `Recompile`) for active Java debug sessions. */
export function onJavaBuildCompleted(event: BuildCompletedEvent): void {
if (!event.userInitiated || !JAVA_BUILD_SYSTEMS.has(event.system) || reloading || !hotSwapSessions().length) return;
const policy = workflowSettings().debugger.hotSwapAfterCompile;
if (policy === "never") return;
quietUntil = Math.max(quietUntil, Date.now() + 2_000);
const allowBuildErrors = event.kind === "compileFile";
if (policy === "always") {
void reloadChangedClasses(true, undefined, allowBuildErrors);
return;
}
const fileName = event.kind === "compileFile" && event.file ? basename(event.file) : "";
notifications().notify({
group: "run",
level: "info",
key: KEY,
title: "Classes changed",
body: fileName
? tx`Reload '${fileName}' into the running debug session?`
: "Reload the changed classes into the running debug session?",
actions: [{ label: "Reload", run: () => void reloadChangedClasses(true, undefined, allowBuildErrors) }],
});
}
export function installBuildHotSwap(): () => void {
return onBuildCompleted(onJavaBuildCompleted);
}
/** java-debug's `hotcodereplace` events of a session this window owns. */
export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEvent, { kind: "hotCodeReplace" }>) {
if (!useDebug.getState().sessions[session]) return;
switch (event.changeType) {
case "BUILD_COMPLETE":
case "BUILD_COMPLETE": {
if (reloading || Date.now() < quietUntil) return;
const policy = workflowSettings().debugger.hotSwapAfterCompile;
if (policy === "never") return;
if (policy === "always") {
void reloadChangedClasses(false);
return;
}
notifications().notify({
group: "run",
level: "info",
@@ -228,6 +286,7 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
actions: [{ label: "Reload", run: () => void reloadChangedClasses(false) }],
});
break;
}
case "ERROR":
case "WARNING":
if (obsoleteMethods(event.message)) {
+2 -1
Переглянути файл
@@ -33,7 +33,7 @@ import { executionPoint } from "./editor/execution";
import { runToCursorInlay } from "./editor/runToCursor";
import { installSmartStepPicking, smartStepTargets } from "./editor/smartStep";
import { exceptionBreakpointIntention } from "./editor/exceptionBreakpointIntention";
import { hotSwapMenuItems, onHotCodeReplace } from "./hotswap";
import { hotSwapMenuItems, installBuildHotSwap, onHotCodeReplace } from "./hotswap";
import { installFlutterHotReloadOnSave } from "./flutterReload";
import {
activeSession,
@@ -162,6 +162,7 @@ export function activate(): () => void {
}),
installSmartStepPicking(),
installFlutterHotReloadOnSave(),
installBuildHotSwap(),
onIdeEvent("debug", (e) => {
if (e.event.kind === "hotCodeReplace") onHotCodeReplace(e.session, e.event);
else handleDebugEvent(e.session, e.event);