From b3e4bd63f13ebc7d6a733ac8fac33fcebc245ec5 Mon Sep 17 00:00:00 2001 From: RuyimgByCN <45452808+RuyimgByCN@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:20:59 +0800 Subject: [PATCH] feat(debug): reload classes after Recompile and builds, and sync exploded Tomcat deployments (#5601) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 '.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 <45452808+RuyimgByCN@users.noreply.github.com> --- crates/ide-core/src/workflow_settings.rs | 28 +++++++ src/bindings.ts | 5 ++ src/features/build/build.test.tsx | 24 ++++++ src/features/build/store.ts | 16 +++- .../debugger/__tests__/hotswap.test.ts | 54 ++++++++++++- src/features/debugger/actions.ts | 1 + src/features/debugger/hotswap.ts | 81 ++++++++++++++++--- src/features/debugger/index.ts | 3 +- src/features/run/applicationUpdate.test.ts | 47 +++++++++++ src/features/run/applicationUpdate.ts | 39 +++++++++ src/features/run/index.ts | 8 +- src/features/run/tomcat.ts | 8 +- src/features/settings/pages/execution.tsx | 18 ++++- src/platform/clientSettings.ts | 1 + src/platform/locales/text/en.json | 7 +- src/platform/locales/text/zh.json | 7 +- src/platform/workflowSettings.test.ts | 9 +++ src/platform/workflowSettings.ts | 4 + src/workbench/contributions.ts | 23 ++++++ 19 files changed, 362 insertions(+), 21 deletions(-) diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index a7ec7814c..c4c50b5e4 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -460,6 +460,16 @@ impl Default for ConsoleSettings { } } +/// Whether compiled classes are reloaded into running Java debug sessions after compilation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum HotSwapPolicy { + #[default] + Ask, + Always, + Never, +} + /// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] @@ -487,6 +497,8 @@ pub struct DebuggerSettings { pub debug_server_page: bool, /// Flutter: saving a Dart file of a running debug session hot reloads the app. pub flutter_hot_reload_on_save: bool, + /// Java: whether to reload changed classes into running debug sessions after compilation. + pub hot_swap_after_compile: HotSwapPolicy, pub python: PythonDebuggerSettings, } @@ -508,6 +520,7 @@ impl Default for DebuggerSettings { skip_library_code: true, debug_server_page: false, flutter_hot_reload_on_save: true, + hot_swap_after_compile: HotSwapPolicy::Ask, python: PythonDebuggerSettings::default(), } } @@ -718,4 +731,19 @@ mod tests { let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap(); assert!(!off.sync_branch_operations); } + + #[test] + fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() { + let missing: DebuggerSettings = serde_json::from_str("{}").unwrap(); + assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask); + for (raw, expected) in + [("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)] + { + let parsed: DebuggerSettings = + serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap(); + assert_eq!(parsed.hot_swap_after_compile, expected); + let serialized = serde_json::to_value(&parsed).unwrap(); + assert_eq!(serialized["hotSwapAfterCompile"], raw); + } + } } diff --git a/src/bindings.ts b/src/bindings.ts index 091b3caa0..1dfdc3114 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -5671,6 +5671,8 @@ export type DebuggerSettings = { debugServerPage?: boolean, /** Flutter: saving a Dart file of a running debug session hot reloads the app. */ flutterHotReloadOnSave?: boolean, + /** Java: whether to reload changed classes into running debug sessions after compilation. */ + hotSwapAfterCompile?: HotSwapPolicy, python?: PythonDebuggerSettings, }; @@ -7922,6 +7924,9 @@ export type HistoryTip = { /** What triggered a hot reload; `flutter debug_adapter` takes it as `reason`. */ export type HotReloadReason = "manual" | "save"; +/** Whether compiled classes are reloaded into running Java debug sessions after compilation. */ +export type HotSwapPolicy = "ask" | "always" | "never"; + /** Result of [`DebugManager::redefine_classes`]. */ export type HotSwapResult = { /** Fully qualified names of the classes reloaded (empty: nothing had changed). */ diff --git a/src/features/build/build.test.tsx b/src/features/build/build.test.tsx index 65fffa077..2f3a4f0c5 100644 --- a/src/features/build/build.test.tsx +++ b/src/features/build/build.test.tsx @@ -7,10 +7,12 @@ import { IpcError, type BuildEvent, type BuildMessage, type BuildResult } from " import { useProject } from "@/platform/project"; import { menuGroupItems, + onBuildCompleted, provideEditorService, provideNotificationService, provideToolWindowService, useContributions, + type BuildCompletedEvent, type EditorService, type NotificationService, type ToolWindowService, @@ -574,6 +576,28 @@ describe("build feature", () => { }); }); + it("publishes onBuildCompleted only when a build finishes successfully", async () => { + const events: BuildCompletedEvent[] = []; + const off = onBuildCompleted((e) => events.push(e)); + try { + const single = startCompileFile("/p/core/src/A.java", true); + await act(async () => {}); + fake.resolve(result([], true)); + await single; + expect(events).toEqual([ + { kind: "compileFile", file: "/p/core/src/A.java", system: "maven", userInitiated: true }, + ]); + + const failed = startCompileFile("/p/core/src/Broken.java", true); + await act(async () => {}); + fake.resolve(result([err("/p/core/src/Broken.java", 3)], false)); + await failed; + expect(events).toHaveLength(1); + } finally { + off(); + } + }); + it("gates Recompile to local Java files and offers context menu labels", () => { const compileFile = getAction("build.compileFile")!; let currentPath: string | null = "/p/core/src/A.java"; diff --git a/src/features/build/store.ts b/src/features/build/store.ts index 716356982..a7bf60f49 100644 --- a/src/features/build/store.ts +++ b/src/features/build/store.ts @@ -26,7 +26,7 @@ import { } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { workflowSettings, type BuildToolWindowWhen } from "@/platform/workflowSettings"; -import { maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions"; +import { maybeEditorService, notifications, notifyBuildCompleted, toolWindowService } from "@/workbench/contributions"; import { cancelTask, removeTask, upsertTask, useTasks } from "@/workbench/tasks"; import { appendOutput, finishSummary, firstError, messageFiles, type BuildStatus, type ConsoleLine } from "./model"; @@ -178,6 +178,7 @@ export async function startBuild( return executeBuild( request, taskTitle, + { kind, file, userInitiated: activate }, (files, onEvent) => backend.run(kind, file, request, files, onEvent, cmake), cancel, ); @@ -201,6 +202,7 @@ export async function startCompileFile(file: string, activate = true): Promise backend.compileFile(file, request, files, onEvent), cancel, ); @@ -210,6 +212,7 @@ export async function startCompileFile(file: string, activate = true): Promise void) => Promise, cancel: () => void, ): Promise { @@ -266,7 +269,16 @@ async function executeBuild( ? undefined : [{ label: "Show Build", run: () => toolWindowService().show("build", true) }], }); - if (!result.success) showFailure(); + if (result.success) { + notifyBuildCompleted({ + kind: meta.kind, + file: meta.file, + system: result.system, + userInitiated: meta.userInitiated, + }); + } else { + showFailure(); + } } catch (e) { if (!ownsBuild()) return null; flush(); diff --git a/src/features/debugger/__tests__/hotswap.test.ts b/src/features/debugger/__tests__/hotswap.test.ts index 87ace58f2..411e1dcb1 100644 --- a/src/features/debugger/__tests__/hotswap.test.ts +++ b/src/features/debugger/__tests__/hotswap.test.ts @@ -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(); + } + }); }); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index ea358e07f..f16641f65 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -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, ), }, { diff --git a/src/features/debugger/hotswap.ts b/src/features/debugger/hotswap.ts index 1b319313f..4d28151fd 100644 --- a/src/features/debugger/hotswap.ts +++ b/src/features/debugger/hotswap.ts @@ -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 { +export async function reloadChangedClasses(build = true, configId?: string, allowBuildErrors = false): Promise { 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) { 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 void reloadChangedClasses(false) }], }); break; + } case "ERROR": case "WARNING": if (obsoleteMethods(event.message)) { diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index bbc7e2ccd..acaa8ecc0 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -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); diff --git a/src/features/run/applicationUpdate.test.ts b/src/features/run/applicationUpdate.test.ts index 73228cef9..8984a4ce1 100644 --- a/src/features/run/applicationUpdate.test.ts +++ b/src/features/run/applicationUpdate.test.ts @@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({ data: { build: "succeeded", classPaths: ["/p/app/bin/main"], pathListSeparator: ":" }, })), runBuild: vi.fn(async () => {}), + buildListeners: new Set<(event: unknown) => void>(), state: { configs: [] as RunSession["config"][], sessions: [] as RunSession[], activeSession: null as string | null }, })); vi.mock("@/platform/actions", () => ({ executeAction: mocks.action, getAction: () => ({}) })); @@ -35,6 +36,10 @@ vi.mock("@/platform/ipc", () => ({ vi.mock("@/workbench/contributions", () => ({ maybeEditorService: () => ({ saveAll: async () => {} }), notifications: () => ({ notify: mocks.notify }), + onBuildCompleted: (listener: (event: unknown) => void) => { + mocks.buildListeners.add(listener); + return () => mocks.buildListeners.delete(listener); + }, useDebugRunSessions: { getState: () => ({ sessions: mocks.debug ? [{ configId: "tomcat:one" }, { configId: "boot" }] : [], @@ -60,6 +65,8 @@ vi.mock("./store", () => ({ useRun: { setState: vi.fn(), getState: () => mocks.state }, })); import { + installBuildTomcatSync, + syncTomcatOnBuildCompleted, updateApplication as updateTomcat, showApplicationUpdate, updateOnDeactivation, @@ -235,4 +242,44 @@ describe("Spring Boot application updates", () => { ]; expect(updatableSessions().map((s) => s.id)).toEqual([boot.id]); }); + + it("syncs exploded Tomcat artifact deployments after user Java builds without redundant notifications while debugging", async () => { + const tomcatSession = { + id: "run-tomcat", + status: "running", + config: { id: "tomcat:one", kind: "tomcat", params: { deployment: "artifact" } }, + } as unknown as RunSession; + const warSession = { + id: "run-war", + status: "running", + config: { id: "tomcat:war", kind: "tomcat", params: { deployment: "war" } }, + } as unknown as RunSession; + mocks.state.sessions = [tomcatSession, warSession]; + mocks.sync.mockResolvedValue(true); + + // Non-debugged running Tomcat notifies that outputs were synced; WAR deployments are untouched. + mocks.debug = false; + const off = installBuildTomcatSync(); + try { + for (const listener of mocks.buildListeners) { + listener({ kind: "compileFile", file: "/p/app/src/A.java", system: "maven", userInitiated: true }); + } + await vi.waitFor(() => expect(mocks.sync).toHaveBeenCalledTimes(1)); + expect(mocks.sync).toHaveBeenCalledWith(tomcatSession.config, false, "noBuild"); + expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Tomcat classes updated" })); + + // Debugged Tomcat syncs silently so HotSwap owns the notification; non-user or non-Java builds skip sync. + mocks.notify.mockClear(); + mocks.debug = true; + await syncTomcatOnBuildCompleted({ kind: "build", file: null, system: "gradle", userInitiated: true }); + expect(mocks.sync).toHaveBeenCalledTimes(2); + expect(mocks.notify).not.toHaveBeenCalled(); + + await syncTomcatOnBuildCompleted({ kind: "build", file: null, system: "maven", userInitiated: false }); + await syncTomcatOnBuildCompleted({ kind: "build", file: null, system: "cargo", userInitiated: true }); + expect(mocks.sync).toHaveBeenCalledTimes(2); + } finally { + off(); + } + }); }); diff --git a/src/features/run/applicationUpdate.ts b/src/features/run/applicationUpdate.ts index 0895f81d7..1b3d269a6 100644 --- a/src/features/run/applicationUpdate.ts +++ b/src/features/run/applicationUpdate.ts @@ -7,7 +7,9 @@ import { parseJavaArgs, resolveJavaModule } from "@/platform/javaLaunch"; import { maybeEditorService, notifications, + onBuildCompleted, useDebugRunSessions, + type BuildCompletedEvent, type DebugServiceSession, } from "@/workbench/contributions"; import { showContextMenu } from "@/ui"; @@ -20,6 +22,8 @@ export type UpdateSession = Pick & { debug?: DebugS export const useApplicationUpdates = create<{ ids: ReadonlySet }>(() => ({ ids: new Set() })); const updatingConfigs = new Set(); +const JAVA_BUILD_SYSTEMS = new Set(["maven", "gradle", "javac"]); + export function updatableSessions(): UpdateSession[] { const runs = useRun.getState().sessions.filter((s) => isUpdatable(s.config) && s.status === "running"); const debug = useDebugRunSessions @@ -160,3 +164,38 @@ export function listenForApplicationDeactivation(): () => void { void listener.then((unlisten) => unlisten()); }; } + +/** Syncs compiled classes and web resources into running exploded-artifact Tomcat deployments after a user Java build. */ +export async function syncTomcatOnBuildCompleted(event: BuildCompletedEvent): Promise { + if (!event.userInitiated || !JAVA_BUILD_SYSTEMS.has(event.system)) return; + const sessions = updatableSessions().filter( + (s) => + s.config.kind === "tomcat" && + (s.config.params?.deployment ?? "artifact") === "artifact" && + !updatingConfigs.has(s.config.id), + ); + for (const session of sessions) { + updatingConfigs.add(session.config.id); + useApplicationUpdates.setState((st) => ({ ids: new Set([...st.ids, session.id]) })); + try { + const synced = await syncTomcatOutputs(session.config, false, "noBuild"); + if (!synced) continue; + const debugging = + !!session.debug || useDebugRunSessions.getState().sessions.some((d) => d.configId === session.config.id); + if (!debugging) { + notifications().notify({ group: "run", level: "info", key: "tomcat-sync", title: "Tomcat classes updated" }); + } + } catch { + // Unrelated modules or stopped deployments leave the user's explicit build result undisturbed. + } finally { + updatingConfigs.delete(session.config.id); + useApplicationUpdates.setState((st) => ({ ids: new Set([...st.ids].filter((id) => id !== session.id)) })); + } + } +} + +export function installBuildTomcatSync(): () => void { + return onBuildCompleted((event) => { + void syncTomcatOnBuildCompleted(event); + }); +} diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 7f5e5856f..82629bc68 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -70,7 +70,12 @@ import { debugInContainer } from "./containerDebug"; import { isDebugOnly, registerBuiltinTypes } from "./types"; import { isZigBuildStep, zigDebugTarget } from "./zigDebug"; import { junitType } from "./junitType"; -import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate"; +import { + installBuildTomcatSync, + listenForApplicationDeactivation, + showApplicationUpdate, + updatableSessions, +} from "./applicationUpdate"; import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload"; import { npmGutter } from "./npmGutter"; import { launchSettingsGutter } from "./launchSettingsGutter"; @@ -481,6 +486,7 @@ export function activate(): () => void { registerExternalTools(), activateStackTrace(), listenForApplicationDeactivation(), + installBuildTomcatSync(), trackRecentConfigurations(), trackFailedTestSelection(), useDebugRunSessions.subscribe(() => setContext("run.updatableRunning", updatableSessions().length > 0)), diff --git a/src/features/run/tomcat.ts b/src/features/run/tomcat.ts index 65556532c..93ab4da1a 100644 --- a/src/features/run/tomcat.ts +++ b/src/features/run/tomcat.ts @@ -155,13 +155,17 @@ export async function buildTomcatArtifact(config: RunConfig): Promise { * `false` when that isn't possible (other deployment kinds, no Java language server, a changed * dependency module): the caller rebuilds the WAR. */ -export async function syncTomcatOutputs(config: RunConfig, resourcesOnly: boolean): Promise { +export async function syncTomcatOutputs( + config: RunConfig, + resourcesOnly: boolean, + buildPolicy: "make" | "noBuild" = "make", +): Promise { const p = config.params ?? {}; if ((p.deployment ?? "artifact") !== "artifact") return false; const artifacts = await call(commands.runTomcatArtifacts()); const artifact = p.artifact ? artifacts.find((a) => a.id === p.artifact) : artifacts[0]; if (!artifact) return false; - const info = await call(commands.javaResolveLaunch(artifact.module, false, "make", nextRequestId())).catch( + const info = await call(commands.javaResolveLaunch(artifact.module, false, buildPolicy, nextRequestId())).catch( () => null, ); if (!info) return false; diff --git a/src/features/settings/pages/execution.tsx b/src/features/settings/pages/execution.tsx index 146319c2a..76f30b35a 100644 --- a/src/features/settings/pages/execution.tsx +++ b/src/features/settings/pages/execution.tsx @@ -316,7 +316,7 @@ export const EXECUTION_PAGES: PageSpec[] = [ group: BUILD_GROUP, order: 361, projectScope: true, - keywords: ["debug", "breakpoint"], + keywords: ["debug", "breakpoint", "hotswap", "hot swap", "reload classes", "recompile"], sections: [ { options: [ @@ -325,6 +325,22 @@ export const EXECUTION_PAGES: PageSpec[] = [ { kind: "toggle", key: "debugger.hideOnTermination", label: "Hide debug window on process termination" }, ], }, + { + title: "HotSwap", + options: [ + { + kind: "select", + key: "debugger.hotSwapAfterCompile", + label: "Reload classes after compilation", + options: [ + { value: "always", label: "Always" }, + { value: "ask", label: "Ask" }, + { value: "never", label: "Never" }, + ], + hint: "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.", + }, + ], + }, { title: "JavaScript", options: [ diff --git a/src/platform/clientSettings.ts b/src/platform/clientSettings.ts index 68004e241..660f529f4 100644 --- a/src/platform/clientSettings.ts +++ b/src/platform/clientSettings.ts @@ -83,6 +83,7 @@ export const CLIENT_SETTINGS_KEYS = [ "debugger.variablesOnBreakpoint", "debugger.runToCursorInlay", "debugger.flutterHotReloadOnSave", + "debugger.hotSwapAfterCompile", "debugger.inlineValues", "debugger.sortValues", "debugger.valueTooltip", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index ebae40742..3c497e6b2 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3904,5 +3904,10 @@ "Could not load the list of PyPI package names. Type a package's exact name to look it up.": "Could not load the list of PyPI package names. Type a package's exact name to look it up.", "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.", "Recompile": "Recompile", - "Recompile '{name}'": "Recompile '{name}'" + "Recompile '{name}'": "Recompile '{name}'", + "HotSwap": "HotSwap", + "Reload classes after compilation": "Reload classes after compilation", + "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.": "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.", + "Reload '{fileName}' into the running debug session?": "Reload '{fileName}' into the running debug session?", + "Tomcat classes updated": "Tomcat classes updated" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index ec122fadd..40cdf5892 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10134,5 +10134,10 @@ "Could not load the list of PyPI package names. Type a package's exact name to look it up.": "无法加载 PyPI 软件包名称列表。请输入软件包的准确名称进行查询。", "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "只列出前 50 个 PyPI 匹配项。请输入更完整的名称以缩小范围。", "Recompile": "重新编译", - "Recompile '{name}'": "重新编译 '{name}'" + "Recompile '{name}'": "重新编译 '{name}'", + "HotSwap": "HotSwap", + "Reload classes after compilation": "编译后重新加载类", + "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.": "在 Build Project、Build Module 或 Recompile 编译成功后,将修改的类重新加载到运行中的 Java 调试会话。", + "Reload '{fileName}' into the running debug session?": "要将 '{fileName}' 重新加载到正在运行的调试会话中吗?", + "Tomcat classes updated": "Tomcat 类已更新" } diff --git a/src/platform/workflowSettings.test.ts b/src/platform/workflowSettings.test.ts index f248b8777..9b4bb4715 100644 --- a/src/platform/workflowSettings.test.ts +++ b/src/platform/workflowSettings.test.ts @@ -103,6 +103,15 @@ describe("validateWorkflow", () => { ); }); + it("defaults debugger hotSwapAfterCompile to ask and validates enum options", () => { + expect(DEFAULT_WORKFLOW.debugger.hotSwapAfterCompile).toBe("ask"); + expect(validateWorkflow({ debugger: { hotSwapAfterCompile: "always" } }).debugger.hotSwapAfterCompile).toBe( + "always", + ); + expect(validateWorkflow({ debugger: { hotSwapAfterCompile: "never" } }).debugger.hotSwapAfterCompile).toBe("never"); + expect(validateWorkflow({ debugger: { hotSwapAfterCompile: "invalid" } }).debugger.hotSwapAfterCompile).toBe("ask"); + }); + it("falls back to defaults for missing or malformed values", () => { expect(validateWorkflow(undefined)).toEqual(DEFAULT_WORKFLOW); const v = validateWorkflow({ diff --git a/src/platform/workflowSettings.ts b/src/platform/workflowSettings.ts index 78f0cacad..925ff3006 100644 --- a/src/platform/workflowSettings.ts +++ b/src/platform/workflowSettings.ts @@ -8,6 +8,7 @@ import type { FetchTagsMode, GitAnnotateMovement, GitSaveChangesPolicy, + HotSwapPolicy, StashDiffTarget, } from "@/bindings"; import { useProject } from "./project"; @@ -153,6 +154,7 @@ export interface DebuggerSettingsValid { skipLibraryCode: boolean; debugServerPage: boolean; flutterHotReloadOnSave: boolean; + hotSwapAfterCompile: HotSwapPolicy; python: { attachSubprocess: boolean; gevent: boolean }; } @@ -406,6 +408,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = { skipLibraryCode: true, debugServerPage: false, flutterHotReloadOnSave: true, + hotSwapAfterCompile: "ask", python: { attachSubprocess: true, gevent: false }, }, run: { @@ -617,6 +620,7 @@ export function validateDebugger(raw: unknown): DebuggerSettingsValid { skipLibraryCode: bool(v.skipLibraryCode, d.skipLibraryCode), debugServerPage: bool(v.debugServerPage, d.debugServerPage), flutterHotReloadOnSave: bool(v.flutterHotReloadOnSave, d.flutterHotReloadOnSave), + hotSwapAfterCompile: oneOf(v.hotSwapAfterCompile, ["ask", "always", "never"] as const, d.hotSwapAfterCompile), python: { attachSubprocess: bool(py.attachSubprocess, d.python.attachSubprocess), gevent: bool(py.gevent, d.python.gevent), diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 513249ddf..437c0d1db 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -18,6 +18,7 @@ import { type RefObject, } from "react"; import type { + BuildKind, CommitSelection, ConsoleRule, FileMatches, @@ -2384,3 +2385,25 @@ export function registerSearchCategory(category: SearchCategory): () => void { searchCategoriesChanged(); }; } + +export interface BuildCompletedEvent { + kind: "compileFile" | BuildKind; + file: string | null; + system: string; + userInitiated: boolean; +} + +const buildCompletedListeners = new Set<(event: BuildCompletedEvent) => void>(); + +/** Subscribes to successful Build / Rebuild / Recompile completions across workbench features. */ +export function onBuildCompleted(listener: (event: BuildCompletedEvent) => void): () => void { + buildCompletedListeners.add(listener); + return () => { + buildCompletedListeners.delete(listener); + }; +} + +/** Publishes a successful build completion to listeners (debugger HotSwap, server deployment sync…). */ +export function notifyBuildCompleted(event: BuildCompletedEvent): void { + notifyEach(buildCompletedListeners, (listener) => listener(event), "build completed"); +}