diff --git a/src/features/debugger/__tests__/stopVariables.test.tsx b/src/features/debugger/__tests__/stopVariables.test.tsx new file mode 100644 index 000000000..3f7d20793 --- /dev/null +++ b/src/features/debugger/__tests__/stopVariables.test.tsx @@ -0,0 +1,127 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; + +// CodeLLDB's shape: the frame keeps its id across stops while every variable reference is new. +const adapter = vi.hoisted(() => ({ + stop: 1, + debugScopes: vi.fn(), + debugVariables: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); + adapter.debugScopes.mockImplementation(() => + ok([{ name: "Local", variablesReference: adapter.stop * 100 + 1, expensive: false }]), + ); + adapter.debugVariables.mockImplementation((_s: number, ref: number) => { + const stop = Math.floor(ref / 100); + // A reference from an earlier stop is gone. + if (stop !== adapter.stop) return ok([]); + return ok( + ref % 100 === 1 + ? [ + { + name: "res", + value: "results_t", + typeName: "results_t", + variablesReference: stop * 100 + 2, + evaluateName: "res", + }, + ] + : [ + { + name: "count", + value: `count-${stop}`, + typeName: "int", + variablesReference: 0, + evaluateName: "res.count", + }, + ], + ); + }); + return { + ...real, + isTauri: () => true, + commands: { + ...real.commands, + debugScopes: adapter.debugScopes, + debugVariables: adapter.debugVariables, + debugEvaluateIn: () => ok({ name: "n", value: "1", typeName: "int", variablesReference: 0, evaluateName: "n" }), + debugThreads: () => ok([{ id: 1, name: "main" }]), + debugStackTrace: () => + ok([{ id: 1000, name: "work", path: "/p/big.c", line: 9 + adapter.stop, column: 1, presentationHint: null }]), + }, + }; +}); + +import { handleDebugEvent, useDebug, type DebugSession } from "../state"; +import { DebugToolWindow } from "../ui/DebugToolWindow"; + +const session: DebugSession = { + id: 1, + name: "big", + adapter: "codelldb", + parent: null, + launch: null, + process: null, + status: "paused", + stoppedThread: 1, + stopReason: "breakpoint", + stopDescription: null, + threads: [{ id: 1, name: "main" }], + selectedThread: 1, + frames: [{ id: 1000, name: "work", path: "/p/big.c", line: 10, column: 1, presentationHint: null }], + selectedFrame: 1000, + hits: 1, + stops: 1, + exitCode: null, + caps: null, +}; + +const requested = () => adapter.debugVariables.mock.calls.map((c) => c[1] as number); + +afterEach(() => { + cleanup(); + adapter.debugScopes.mockClear(); + adapter.debugVariables.mockClear(); + useDebug.setState({ watches: [] }); +}); + +describe("variables after a stop (#6170)", () => { + it("expands a node again by this stop's reference, once, and asks for the frame's scope once", async () => { + adapter.stop = 1; + // A watch keeps the tree mounted while the program runs, so its expansion survives the step. + useDebug.setState({ sessions: { 1: session }, active: 1, stopSeq: 1, variablesEpoch: 0, watches: ["n"] }); + render(); + fireEvent.click(screen.getByRole("tab", { name: "Threads & Variables" })); + const tree = screen.getByRole("tree", { name: "Variables" }); + const res = await within(tree).findByText("res"); + expect(res).toBeTruthy(); + tree.focus(); + fireEvent.keyDown(tree, { key: "End" }); + fireEvent.keyDown(tree, { key: "ArrowRight" }); + await within(tree).findByText("count-1"); + expect(requested()).toEqual([101, 102]); + + adapter.debugVariables.mockClear(); + adapter.debugScopes.mockClear(); + adapter.stop = 2; + act(() => handleDebugEvent(1, { kind: "continued", threadId: 1, allThreadsContinued: true })); + act(() => + handleDebugEvent(1, { + kind: "stopped", + reason: "step", + description: null, + threadId: 1, + allThreadsStopped: true, + }), + ); + await within(tree).findByText("count-2"); + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + // Not the last stop's 102, which the adapter no longer knows (or formats again). + expect(requested()).toEqual([201, 202]); + expect(adapter.debugScopes).toHaveBeenCalledTimes(1); + await waitFor(() => expect(within(tree).queryByText("No variables")).toBeNull()); + }); +}); diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 218c969c2..34d6efd3c 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -21,6 +21,7 @@ import { type LaunchConfig, type RunId, type RunConfig, + type Scope, type StackFrame, type ThreadInfo, type Variable, @@ -1347,22 +1348,48 @@ async function loadThreads(id: DebugSessionId) { } } +export interface FrameLocals { + scopes: Scope[]; + /** Variables of the first non-expensive scope. */ + locals: Variable[]; +} + +let frameLocalsMemo: { key: string; frames: readonly StackFrame[] | undefined; value: Promise } | null = + null; + +/** + * Scopes and first-scope variables of `frameId` at the current stop. Inline values and the Variables view + * ask for the same frame on every stop; they share one request, since an adapter may take seconds to + * format a large local (#6170). + */ +export function frameLocals(id: DebugSessionId, frameId: number): Promise { + const { stopSeq, variablesEpoch, sessions } = useDebug.getState(); + const key = `${id}:${frameId}:${stopSeq}:${variablesEpoch}`; + // Every stop loads a new stack: a stop counter that starts over cannot hand out an old answer. + const frames = sessions[id]?.frames; + if (frameLocalsMemo?.key !== key || frameLocalsMemo.frames !== frames) { + const value = (async () => { + const scopes = await call(commands.debugScopes(id, frameId)); + const scope = scopes.find((sc) => !sc.expensive); + const locals = scope ? await call(commands.debugVariables(id, scope.variablesReference)) : []; + return { scopes, locals }; + })(); + frameLocalsMemo = { key, frames, value }; + } + return frameLocalsMemo.value; +} + /** Locals of `frameId` (first non-expensive scope) for inline values. */ async function loadLocals(id: DebugSessionId, frameId: number) { const frames = useDebug.getState().sessions[id]?.frames; const values: Record = Object.create(null); const variables: Record = Object.create(null); try { - const scopes = await call(commands.debugScopes(id, frameId)); - const scope = scopes.find((sc) => !sc.expensive); - if (scope) { - const vars = await call(commands.debugVariables(id, scope.variablesReference)); - for (const v of vars) - if (v.name && !Object.hasOwn(values, v.name)) { - values[v.name] = v.value; - variables[v.name] = v; - } - } + for (const v of (await frameLocals(id, frameId)).locals) + if (v.name && !Object.hasOwn(values, v.name)) { + values[v.name] = v.value; + variables[v.name] = v; + } } catch { // No inline values. } diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index bad91cf98..7aac2a11f 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -39,6 +39,7 @@ import { addWatch, closeSessionTab, evaluate, + frameLocals, isLive, isThreadSuspended, selectFrame, @@ -580,17 +581,21 @@ function VariablesPane({ session }: { session: DebugSession }) { const completion = useExpressionCompletion(evalField, expression, setExpression, session); const [history, setHistory] = useState<{ sessionId: number; stopSeq: number; entries: string[] } | null>(null); const [lastEval, setLastEval] = useState(null); - const [scopeData, setScopeData] = useState<{ frame: number | null; scopes: Scope[]; locals: Variable[] }>({ - frame: null, + // Each carries the generation it was fetched in. Adapters reuse frame ids across stops, so matching the + // frame alone would show the last stop's variables, and the tree would expand them by references the + // adapter has dropped or recomputes (#6170). + const [scopeData, setScopeData] = useState<{ generation: number; scopes: Scope[]; locals: Variable[] }>({ + generation: -1, scopes: [], locals: [], }); - const [watchData, setWatchData] = useState<{ frame: number | null; seq: number; rows: EvalRow[] }>({ - frame: null, - seq: -1, + const [watchData, setWatchData] = useState<{ generation: number; rows: EvalRow[] }>({ + generation: -1, rows: [], }); const frame = session.status === "paused" ? session.selectedFrame : null; + // The stop, refresh and frame the variables are shown for. Variable references are only valid within it. + const generation = (stopSeq * 1000 + (variablesEpoch % 1000)) * 100000 + (frame ?? 0); const historyOpen = frame != null && history?.sessionId === session.id && history.stopSeq === stopSeq; const editor = settings?.editor; const live = liveWatchesApply(session); @@ -603,31 +608,30 @@ function VariablesPane({ session }: { session: DebugSession }) { useEffect(() => { if (frame == null) return; let cancelled = false; + const fetched = generation; void (async () => { let scopes: Scope[] = []; let locals: Variable[] = []; try { - scopes = await call(commands.debugScopes(session.id, frame)); - const first = scopes.find((s) => !s.expensive); - if (first) { - const vars = await call(commands.debugVariables(session.id, first.variablesReference)); - locals = workflowSettings().debugger.sortValues ? sortVariables(vars) : vars; - } + const data = await frameLocals(session.id, frame); + scopes = data.scopes; + locals = workflowSettings().debugger.sortValues ? sortVariables(data.locals) : data.locals; } catch { // Frame went away (resumed). } - if (!cancelled) setScopeData({ frame, scopes, locals }); + if (!cancelled) setScopeData({ generation: fetched, scopes, locals }); })(); return () => { cancelled = true; }; - }, [session.id, frame, stopSeq, variablesEpoch]); + }, [session.id, frame, generation]); // Watches are re-evaluated on every stop / frame change, and when the adapter has new values (kotlin-lsp first // answers "Collecting data…"). useEffect(() => { if (frame == null || !watches.length) return; let cancelled = false; + const fetched = generation; void (async () => { const rows = await Promise.all( watches.map(async (w): Promise => { @@ -638,7 +642,7 @@ function VariablesPane({ session }: { session: DebugSession }) { } }), ); - if (!cancelled) setWatchData({ frame, seq: stopSeq, rows }); + if (!cancelled) setWatchData({ generation: fetched, rows }); })(); return () => { cancelled = true; @@ -658,7 +662,7 @@ function VariablesPane({ session }: { session: DebugSession }) { error: lastEval.error, }); // While the program runs, a debugger that evaluates without suspending gives the values. - const watchRows = frame == null ? liveWatches : watchData.frame === frame ? watchData.rows : []; + const watchRows = frame == null ? liveWatches : watchData.generation === generation ? watchData.rows : []; for (const w of watches) { const r = watchRows.find((x) => x.expression === w); out.push({ @@ -669,7 +673,7 @@ function VariablesPane({ session }: { session: DebugSession }) { error: frame == null && !live ? "Not suspended" : (r?.error ?? null), }); } - if (frame != null && scopeData.frame === frame) { + if (frame != null && scopeData.generation === generation) { const firstScope = scopeData.scopes.find((s) => !s.expensive); const seen = new Map(); for (const v of scopeData.locals) { @@ -694,7 +698,7 @@ function VariablesPane({ session }: { session: DebugSession }) { } } return out; - }, [lastEval, watches, watchData, scopeData, frame, live, liveWatches]); + }, [lastEval, watches, watchData, scopeData, frame, generation, live, liveWatches]); const run = async () => { const e = expression.trim(); @@ -822,7 +826,7 @@ function VariablesPane({ session }: { session: DebugSession }) {