From b30716e22c1cb5e5486a2f5daed7ea0c3ed456f4 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Thu, 26 Nov 2026 19:32:35 +0900 Subject: [PATCH] fix(debug): show Java frames when java-debug cannot describe one of them (#6158) On Windows a Java debug session stopped in a Spring request showed no frames: with the project's sourcePaths set, java-debug looks a CGLIB proxy frame's `` source up there, Paths.get throws, and the adapter fails the whole stackTrace request. When that request fails, the frames are now taken one at a time, leaving out the ones the adapter can't describe. A stack trace failure that remains is logged and shown in Threads & Variables with a Retry button instead of an empty list. Fixes #6157 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-dap/src/lib.rs | 35 +++++++++++++--- crates/ide-dap/src/tests.rs | 32 ++++++++++++++ e2e/debugFramesError.spec.ts | 42 +++++++++++++++++++ .../debugger/__tests__/executionState.test.ts | 19 +++++++++ src/features/debugger/state.ts | 10 ++++- .../debugger/ui/DebugToolWindow.module.css | 8 ++++ src/features/debugger/ui/DebugToolWindow.tsx | 9 ++++ src/platform/locales/text/en.json | 3 +- src/platform/locales/text/zh.json | 3 +- 9 files changed, 151 insertions(+), 10 deletions(-) create mode 100644 e2e/debugFramesError.spec.ts diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index b405efb5bd..cff441b2e6 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -1696,16 +1696,39 @@ impl DebugManager { } pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult> { + const MAX_FRAMES: u64 = 400; let session = self.session(s)?; session.check_thread(thread_id)?; - let body = session - .conn - .request_timeout( + let request = |start: u64, levels: u64| { + session.conn.request_timeout( "stackTrace", - json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }), + json!({ "threadId": thread_id, "startFrame": start, "levels": levels }), REQUEST_TIMEOUT, ) - .await?; + }; + let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) { + Some(Value::Array(frames)) => frames, + _ => Vec::new(), + }; + let raw = match request(0, MAX_FRAMES).await { + Ok(body) => frames_of(body), + // java-debug fails the whole request when one frame's source lookup throws (on Windows, + // a CGLIB proxy's `` source against `sourcePaths`): the frames come one at a + // time instead, without the ones it cannot describe. + // ponytail: one request per frame; page around the failing ones if deep stacks get slow. + Err(first @ DapError::Failed { .. }) => { + let Ok(top) = request(0, 1).await else { return Err(first.into()) }; + let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES); + let mut raw = frames_of(top); + for start in 1..total { + if let Ok(body) = request(start, 1).await { + raw.extend(frames_of(body)); + } + } + raw + } + Err(e) => return Err(e.into()), + }; let kotlin_lsp = session.kotlin_lsp_quirks().is_some(); let frame = |f: &Value| { let mut frame = frame_from(f); @@ -1717,7 +1740,7 @@ impl DebugManager { } frame }; - Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default()) + Ok(raw.iter().map(frame).collect()) } pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult> { diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index 5bbaffd84d..e3df0ab145 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -126,6 +126,8 @@ struct Script { child_request: Option, ignore_configuration_done: bool, source_path: Option, + /// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing). + failing_frame: Option, /// Report this process id in the adapter's `process` event (the program being debugged). debuggee_pid: Option, /// java-debug's spelling of the same event. @@ -206,6 +208,7 @@ impl Default for Script { child_request: None, ignore_configuration_done: false, source_path: None, + failing_frame: None, debuggee_pid: None, java_process_id: false, output_after_terminate: false, @@ -520,6 +523,20 @@ async fn fake_adapter(stream ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]})); } } + "stackTrace" if let Some(bad) = script.failing_frame => { + let start = msg["arguments"]["startFrame"].as_u64().unwrap(); + let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3); + if (start..end).contains(&bad) { + send!( + json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\"}) + ); + } else { + let frames: Vec = (start..end) + .map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1})) + .collect(); + ok!(msg, json!({"stackFrames": frames, "totalFrames": 3})); + } + } "stackTrace" => ok!( msg, json!({"stackFrames": [ @@ -2332,6 +2349,21 @@ async fn kotlin_official_release_ten_no_delay_runs() { } } +#[tokio::test] +async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() { + let h = harness(Script { failing_frame: Some(1), ..Script::default() }); + let id = h.start(config()).await.unwrap(); + let frames = h.manager.stack_trace(id, 1).await.unwrap(); + assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::>(), ["f0", "f2"]); + h.manager.stop(id).await.unwrap(); + + let h = harness(Script { failing_frame: Some(0), ..Script::default() }); + let id = h.start(config()).await.unwrap(); + let error = h.manager.stack_trace(id, 1).await.unwrap_err(); + assert!(error.message.contains(""), "{error:?}"); + h.manager.stop(id).await.unwrap(); +} + #[cfg(windows)] #[tokio::test] async fn netcoredbg_windows_source_paths_round_trip() { diff --git a/e2e/debugFramesError.spec.ts b/e2e/debugFramesError.spec.ts new file mode 100644 index 0000000000..87ecd7a002 --- /dev/null +++ b/e2e/debugFramesError.spec.ts @@ -0,0 +1,42 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("shows why the frames did not load and retries them", async ({ workbench: page }) => { + await page.setViewportSize({ width: 940, height: 740 }); + await stubDesktop(page); + await page.evaluate(async () => { + const stateModule = "/src/features/debugger/state.ts"; + const workbenchModule = "/src/workbench/contributions.ts"; + const { adoptSession, handleDebugEvent } = await import(/* @vite-ignore */ stateModule); + const { toolWindowService } = await import(/* @vite-ignore */ workbenchModule); + const handlers = window.__ipc.handlers; + let failures = 1; + handlers.debug_stack_trace = () => { + if (failures-- > 0) + throw { kind: "protocol", message: "debug adapter did not answer `stackTrace` in time", detail: null }; + return [{ id: 7, name: "OrderController.place(Order)", path: null, line: 41, column: 0, presentationHint: null }]; + }; + handlers.debug_threads = () => [{ id: 9, name: "http-nio-8080-exec-9" }]; + handlers.debug_scopes = () => []; + adoptSession(98, { name: "Orders", adapter: "java-debug", status: "running" }); + toolWindowService().show("debug", true); + handleDebugEvent(98, { + kind: "stopped", + threadId: 9, + allThreadsStopped: false, + reason: "breakpoint", + description: null, + }); + }); + + const frames = page.getByRole("region", { name: "Debug", exact: true }).getByRole("listbox", { name: "Frames" }); + const error = frames.getByRole("alert"); + await expect(error).toContainText("Could not load the frames: debug adapter did not answer `stackTrace` in time"); + await page.screenshot({ path: test.info().outputPath("frames-error.png") }); + await error.getByRole("button", { name: "Retry" }).click(); + await expect(frames.getByText("OrderController.place(Order)", { exact: true })).toBeVisible(); + await expect(error).toBeHidden(); + expect(await ipcCalls(page, "debug_stack_trace")).toEqual([ + { session: 98, threadId: 9 }, + { session: 98, threadId: 9 }, + ]); +}); diff --git a/src/features/debugger/__tests__/executionState.test.ts b/src/features/debugger/__tests__/executionState.test.ts index 30ec8d13e7..b9b9ff05f6 100644 --- a/src/features/debugger/__tests__/executionState.test.ts +++ b/src/features/debugger/__tests__/executionState.test.ts @@ -82,6 +82,25 @@ describe("execution point state", () => { expect(useExecutionPoint.getState()).toMatchObject({ path, line: 9 }); }); + it("keeps a failed stack trace's reason for the frames list, and a retry loads the frames", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + ipc.debugStackTrace.mockResolvedValueOnce({ + status: "error", + error: { kind: "timedOut", message: "stackTrace timed out after 30s" }, + } as never); + stopped(); + await settle(); + expect(useDebug.getState().sessions[1]).toMatchObject({ + frames: [], + framesError: "stackTrace timed out after 30s", + }); + expect(error).toHaveBeenCalled(); + await selectThread(1, 5); + expect(useDebug.getState().sessions[1]).toMatchObject({ framesError: null, selectedFrame: 100 }); + expect(useExecutionPoint.getState()).toMatchObject({ path, line: 6840 }); + error.mockRestore(); + }); + it("counts stops per session", async () => { adoptSession(2, { adapter: "java-debug" }); expect(useDebug.getState().sessions[1]!.stops).toBe(0); diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 8d36a62562..218c969c2d 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -3,6 +3,7 @@ * (threads, frames, locals) after each stop. */ import { tx } from "@/platform/i18n"; +import { logError } from "@/platform/errorLog"; import { workflowSettings } from "@/platform/workflowSettings"; import { executeAction, getAction } from "@/platform/actions"; import { create } from "zustand"; @@ -96,6 +97,8 @@ export interface DebugSession { threads: ThreadInfo[]; selectedThread: number | null; frames: StackFrame[]; + /** Why the selected thread's frames could not be loaded (Threads & Variables offers a retry). */ + framesError?: string | null; selectedFrame: number | null; /** Breakpoint hits in this session. */ hits: number; @@ -1296,16 +1299,19 @@ export function selectFrame(id: DebugSessionId, frameId: number, reveal = true) /** `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened. */ async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true) { + if (useDebug.getState().sessions[id]?.framesError) patch(id, { framesError: null }); const before = useDebug.getState().sessions[id]; let frames: StackFrame[] = []; + let framesError: string | null = null; try { frames = await call(commands.debugStackTrace(id, threadId)); } catch (e) { - console.warn("stackTrace failed", e); + logError("Debugger stack trace", e); + framesError = e instanceof Error ? e.message : String(e); } const s = useDebug.getState().sessions[id]; if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return; - patch(id, { frames }); + patch(id, { frames, framesError }); const top = topFrame(frames); if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) { void logSuspendingHit(id, top); diff --git a/src/features/debugger/ui/DebugToolWindow.module.css b/src/features/debugger/ui/DebugToolWindow.module.css index 669fe3677a..049bedeaa7 100644 --- a/src/features/debugger/ui/DebugToolWindow.module.css +++ b/src/features/debugger/ui/DebugToolWindow.module.css @@ -200,6 +200,14 @@ font-size: var(--fs-ui); } +.framesError { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 6px; + overflow-wrap: anywhere; +} + /* variables */ .variables { height: 100%; diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index fb8e10a2d8..bad91cf98e 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -10,6 +10,7 @@ import { formatBinding, hostBinding } from "@/platform/keymap"; import { basename, useProject } from "@/platform/project"; import { call, commands, isTauri, type Scope, type Variable } from "@/platform/ipc"; import { + Button, EmptyState, Icon, IconButton, @@ -476,6 +477,14 @@ function FramesPane({ session }: { session: DebugSession }) { )} {stopNote(session) &&
{stopNote(session)}
} + {paused && session.framesError && session.selectedThread != null && ( +
+ {tx`Could not load the frames: ${session.framesError}`} + +
+ )} {items.map((item) => item.kind === "hidden" ? (