feat(debugger): evaluate watches while a JavaScript program runs (#3318)

js-debug evaluates without suspending, so with Settings › Debugger › Evaluate watches while the program runs (off by default) the watches of a running Node.js program or page are evaluated once a second. Nothing is evaluated while the Debug tool window is hidden or the session is paused or ended, and a slow round isn't joined by another. Other debuggers keep showing "Not suspended".

Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com>
This commit is contained in:
ntbang0901
2026-11-14 16:35:01 +08:00
committed by GitHub
parent 2d00f09393
commit fecbf8ed14
13 changed files with 294 additions and 7 deletions
+3
View File
@@ -266,6 +266,8 @@ pub struct DebuggerSettings {
pub inline_values: bool,
/// Data Views: list variables by name instead of the adapter's order.
pub sort_values: bool,
/// Data Views: evaluate watches while the program runs, where the debugger can (JavaScript).
pub live_watches: bool,
pub value_tooltip: bool,
/// While suspended, selecting an expression shows its value.
pub value_tooltip_on_selection: bool,
@@ -287,6 +289,7 @@ impl Default for DebuggerSettings {
run_to_cursor_inlay: true,
inline_values: true,
sort_values: false,
live_watches: false,
value_tooltip: true,
value_tooltip_on_selection: true,
value_tooltip_delay: 700,
+4
View File
@@ -140,6 +140,8 @@ pub struct DebugCapabilities {
/// The session debugs a page in a browser: js-debug's requests for pages apply
/// ([`DebugManager::js_set_custom_breakpoints`]).
pub js_page: bool,
/// The adapter evaluates expressions while the program runs, without a stack frame.
pub live_evaluate: bool,
}
/// Result of [`DebugManager::redefine_classes`].
@@ -595,6 +597,7 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
jvm_instances: false,
jvm_heap: false,
js_page: false,
live_evaluate: false,
}
}
@@ -605,6 +608,7 @@ pub(crate) fn session_capabilities(session: &Session) -> DebugCapabilities {
caps.jvm_instances = session.jvm_inspector.lock().is_some();
caps.jvm_heap = JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str());
caps.js_page = js_debug::is_page(session);
caps.live_evaluate = session.adapter == js_debug::ADAPTER;
caps
}
+3 -3
View File
@@ -966,16 +966,16 @@ async fn a_browser_page_session_has_the_page_capability() {
let h = harness(Script { start_debugging: true, ..Script::default() });
let browser = h.start(js_config("pwa-chrome")).await.unwrap();
let page = h.manager.capabilities(child_of(&h, browser).await).unwrap();
assert!(page.js_page);
assert!(page.js_page && page.live_evaluate);
assert!(!h.manager.capabilities(browser).unwrap().js_page, "the launch itself is not a page");
let node = h.start(js_config("pwa-node")).await.unwrap();
let process = h.manager.capabilities(child_of(&h, node).await).unwrap();
assert!(!process.js_page);
assert!(!process.js_page && process.live_evaluate);
let python = h.start(config()).await.unwrap();
let script = h.manager.capabilities(child_of(&h, python).await).unwrap();
assert!(!script.js_page);
assert!(!script.js_page && !script.live_evaluate);
}
#[tokio::test]
+4
View File
@@ -3965,6 +3965,8 @@ export type DebugCapabilities = {
* ([`DebugManager::js_set_custom_breakpoints`]).
*/
jsPage: boolean,
/** The adapter evaluates expressions while the program runs, without a stack frame. */
liveEvaluate: boolean,
};
/** A completion the adapter offers for an expression (DAP `completions`). */
@@ -4016,6 +4018,8 @@ export type DebuggerSettings = {
inlineValues?: boolean,
/** Data Views: list variables by name instead of the adapter's order. */
sortValues?: boolean,
/** Data Views: evaluate watches while the program runs, where the debugger can (JavaScript). */
liveWatches?: boolean,
valueTooltip?: boolean,
/** While suspended, selecting an expression shows its value. */
valueTooltipOnSelection?: boolean,
@@ -107,6 +107,7 @@ const caps = (p: Partial<DebugCapabilities> = {}): DebugCapabilities => ({
jvmInstances: false,
jvmHeap: false,
jsPage: false,
liveEvaluate: false,
...p,
});
@@ -0,0 +1,144 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
type Answer = { status: "ok"; data: unknown } | { status: "error"; error: { kind: string; message: string } };
const asked: Array<[number, number | null, string, string | null]> = [];
let answer: (expression: string) => Promise<Answer>;
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
debugEvaluateIn: (session: number, frame: number | null, expression: string, context: string | null) => {
asked.push([session, frame, expression, context]);
return answer(expression);
},
},
};
});
const { useProject } = await import("@/platform/project");
const { LIVE_WATCH_INTERVAL_MS, liveWatchesApply, useLiveWatches } = await import("../js/liveWatches");
type Session = Parameters<typeof useLiveWatches>[0];
const session = (p: Record<string, unknown> = {}): Session =>
({ id: 3, name: "page", status: "running", caps: { liveEvaluate: true }, ...p }) as Session;
const value = (text: string) => ({ status: "ok" as const, data: { value: text, variablesReference: 0 } });
type Settings = ReturnType<typeof useProject.getState>["settings"];
const setLiveWatches = (on: boolean | null) =>
useProject.setState({ settings: (on == null ? {} : { debugger: { liveWatches: on } }) as Settings });
const settle = () => act(async () => void (await vi.advanceTimersByTimeAsync(0)));
beforeEach(() => {
vi.useFakeTimers();
asked.length = 0;
answer = (expression) => Promise.resolve(value(`<${expression}>`));
setLiveWatches(true);
});
afterEach(() => vi.useRealTimers());
describe("watches while the program runs", () => {
it("evaluates each watch without a frame while the session runs", async () => {
const { result } = renderHook(() => useLiveWatches(session(), ["a", "b"], true));
await settle();
expect(asked).toEqual([
[3, null, "a", "watch"],
[3, null, "b", "watch"],
]);
expect(result.current.map((r) => [r.expression, (r.result as { value: string } | null)?.value, r.error])).toEqual([
["a", "<a>", null],
["b", "<b>", null],
]);
});
it("refreshes every second and not faster", async () => {
expect(LIVE_WATCH_INTERVAL_MS).toBe(1000);
renderHook(() => useLiveWatches(session(), ["a"], true));
await settle();
expect(asked).toHaveLength(1);
await act(async () => void (await vi.advanceTimersByTimeAsync(999)));
expect(asked).toHaveLength(1);
await act(async () => void (await vi.advanceTimersByTimeAsync(1)));
expect(asked).toHaveLength(2);
});
it("skips a tick while the previous one is pending", async () => {
answer = () => new Promise(() => {});
renderHook(() => useLiveWatches(session({ id: 90 }), ["slow"], true));
await act(async () => void (await vi.advanceTimersByTimeAsync(3000)));
expect(asked).toHaveLength(1);
});
it("does not start a second round in a session when the watch list changes during a slow one", async () => {
let finish = () => {};
answer = () => new Promise((resolve) => (finish = () => resolve(value("done"))));
const { rerender } = renderHook(({ list }) => useLiveWatches(session({ id: 91 }), list, true), {
initialProps: { list: ["slow"] },
});
await settle();
rerender({ list: ["slow", "other"] });
await act(async () => void (await vi.advanceTimersByTimeAsync(2000)));
expect(asked).toEqual([[91, null, "slow", "watch"]]);
// Once it has answered, the next tick asks for the list as it is now.
answer = (expression) => Promise.resolve(value(`<${expression}>`));
finish();
await act(async () => void (await vi.advanceTimersByTimeAsync(1000)));
expect(asked.slice(1).map((a) => a[2])).toEqual(["slow", "other"]);
});
it("is off until turned on in the settings", () => {
setLiveWatches(null);
expect(liveWatchesApply(session())).toBe(false);
setLiveWatches(true);
expect(liveWatchesApply(session())).toBe(true);
});
it("stops when hidden, paused, terminated, switched off or unsupported", async () => {
const quiet: Array<[Session, boolean]> = [
[session(), false],
[session({ status: "paused" }), true],
[session({ status: "terminated" }), true],
[session({ caps: { liveEvaluate: false } }), true],
[session({ caps: null }), true],
[undefined, true],
];
for (const [s, visible] of quiet) {
const { result, unmount } = renderHook(() => useLiveWatches(s, ["a"], visible));
await act(async () => void (await vi.advanceTimersByTimeAsync(2500)));
expect(result.current).toEqual([]);
unmount();
}
setLiveWatches(false);
expect(liveWatchesApply(session())).toBe(false);
const { result } = renderHook(() => useLiveWatches(session(), ["a"], true));
await act(async () => void (await vi.advanceTimersByTimeAsync(2500)));
expect(result.current).toEqual([]);
expect(asked).toEqual([]);
});
it("an evaluation error becomes the watch's error", async () => {
answer = () =>
Promise.resolve({ status: "error", error: { kind: "internal", message: "ReferenceError: x is not defined" } });
const { result } = renderHook(() => useLiveWatches(session(), ["x"], true));
await settle();
expect(result.current).toEqual([{ expression: "x", result: null, error: "ReferenceError: x is not defined" }]);
});
it("drops a late answer of another session", async () => {
let release: (a: Answer) => void = () => {};
answer = () => new Promise<Answer>((resolve) => (release = resolve));
const { result, rerender } = renderHook(({ s }) => useLiveWatches(s, ["a"], true), {
initialProps: { s: session({ id: 3 }) },
});
await settle();
answer = (expression) => Promise.resolve(value(`new ${expression}`));
rerender({ s: session({ id: 4 }) });
await settle();
await act(async () => {
release(value("old"));
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.map((r) => (r.result as { value: string } | null)?.value)).toEqual(["new a"]);
});
});
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
const adapterData = vi.hoisted(() => ({
@@ -67,6 +68,7 @@ vi.mock("@/workbench/confirmTerminate", () => ({ confirmTerminate }));
import type { RunConfig } from "@/platform/ipc";
import { setLocale } from "@/platform/i18n";
import { ToolWindowShownProvider } from "@/workbench/contributions";
import { handleDebugEvent, setVariableValue, useDebug, type DebugSession } from "../state";
import { DebugTabs, DebugToolWindow } from "../ui/DebugToolWindow";
import { DebuggerOverlays } from "../ui/Overlays";
@@ -389,4 +391,37 @@ describe("variables the adapter computes after the stop", () => {
expect(useDebug.getState().variablesEpoch).toBe(1);
expect(adapterData.memoryClasses).not.toHaveBeenCalled();
});
it("evaluates the watches of a running program only while the tool window is shown", async () => {
const caps = { liveEvaluate: true } as DebugSession["caps"];
const running: DebugSession = { ...session, id: 5, status: "running", frames: [], selectedFrame: null, caps };
useDebug.setState({ sessions: { 5: running }, active: 5, watches: ["count"] });
const settings = useProject.getState().settings;
useProject.setState({
settings: { debugger: { liveWatches: true } } as ReturnType<typeof useProject.getState>["settings"],
});
const watched = () => debugEvaluateIn.mock.calls.filter((c) => c[0] === 5 && c[3] === "watch");
const shown = (value: boolean) => {
const view = render(
<ToolWindowShownProvider value={value}>
<DebugToolWindow />
</ToolWindowShownProvider>,
);
fireEvent.click(screen.getByRole("tab", { name: "Threads & Variables" }));
return view;
};
try {
debugEvaluateIn.mockClear();
// A hidden tool window stays mounted.
const hidden = shown(false);
await tick();
expect(watched()).toEqual([]);
hidden.unmount();
shown(true);
await waitFor(() => expect(watched()).toEqual([[5, null, "count", "watch"]]));
} finally {
useDebug.setState({ watches: [] });
useProject.setState({ settings });
}
});
});
+77
View File
@@ -0,0 +1,77 @@
/**
* Watches of a program that is running: a debugger that evaluates without suspending
* (js-debug, `liveEvaluate`) is asked for them again and again, like a browser's live
* expressions. Elsewhere a watch has a value only while suspended.
*/
import { useEffect, useState } from "react";
import { call, commands, type Variable } from "@/platform/ipc";
import { workflowSettings } from "@/platform/workflowSettings";
import type { DebugSession } from "../state";
/** How often the watches of a running program are evaluated again. */
export const LIVE_WATCH_INTERVAL_MS = 1000;
export interface LiveWatch {
expression: string;
result: Variable | null;
error: string | null;
}
const NONE: LiveWatch[] = [];
/** Sessions whose watches are being evaluated right now. */
const evaluating = new Set<number>();
/** Whether the watches of `session` are evaluated while it runs. */
export function liveWatchesApply(session: DebugSession | undefined): boolean {
return (
!!session && session.status === "running" && !!session.caps?.liveEvaluate && workflowSettings().debugger.liveWatches
);
}
/**
* The current values of `watches` in the running `session`, refreshed every
* `LIVE_WATCH_INTERVAL_MS` while `visible`; empty when they don't apply. A watch with a side
* effect has it again on each refresh.
*/
export function useLiveWatches(
session: DebugSession | undefined,
watches: readonly string[],
visible: boolean,
): LiveWatch[] {
const [data, setData] = useState<{ session: number; rows: LiveWatch[] }>({ session: -1, rows: NONE });
const apply = visible && watches.length > 0 && liveWatchesApply(session);
const id = session?.id ?? -1;
const expressions = watches.join("\n");
useEffect(() => {
if (!apply) return;
let current = true;
const refresh = async () => {
// A slow evaluation isn't joined by a second one, whichever watch list asked for it.
if (evaluating.has(id)) return;
evaluating.add(id);
const rows = await Promise.all(
expressions.split("\n").map(async (expression): Promise<LiveWatch> => {
try {
return {
expression,
result: await call(commands.debugEvaluateIn(id, null, expression, "watch")),
error: null,
};
} catch (e) {
return { expression, result: null, error: e instanceof Error ? e.message : String(e) };
}
}),
);
evaluating.delete(id);
if (current) setData({ session: id, rows });
};
void refresh();
const timer = window.setInterval(() => void refresh(), LIVE_WATCH_INTERVAL_MS);
return () => {
current = false;
window.clearInterval(timer);
};
}, [apply, id, expressions]);
return apply && data.session === id ? data.rows : NONE;
}
+9 -3
View File
@@ -41,12 +41,14 @@ import {
import { remoteWaitingNote } from "../remote";
import { sessionTabs } from "./sessionTabs";
import { stopNote } from "../js/eventBreakpoints";
import { liveWatchesApply, useLiveWatches } from "../js/liveWatches";
import { MemoryView } from "../memory/MemoryView";
import { DebugConsole } from "./DebugConsole";
import { VariablesView, type VarRoot } from "./VariablesView";
import { useExpressionCompletion } from "./ExpressionCompletion";
import { sortVariables } from "../values";
import { workflowSettings } from "@/platform/workflowSettings";
import { useToolWindowShown } from "@/workbench/contributions";
import styles from "./DebugToolWindow.module.css";
import { tx, useTx } from "@/platform/i18n";
@@ -436,6 +438,9 @@ function VariablesPane({ session }: { session: DebugSession }) {
rows: [],
});
const frame = session.status === "paused" ? session.selectedFrame : null;
const live = liveWatchesApply(session);
// A hidden tool window stays mounted: its watches must not go on running in the page.
const liveWatches = useLiveWatches(session, watches, useToolWindowShown());
// Same thread and stack depth across stops: compare like with like.
const changeScope = `${session.id}:${session.selectedThread}:${session.frames.findIndex((f) => f.id === frame)}`;
@@ -497,7 +502,8 @@ function VariablesPane({ session }: { session: DebugSession }) {
variable: lastEval.result,
error: lastEval.error,
});
const watchRows = watchData.frame === frame ? watchData.rows : [];
// While the program runs, a debugger that evaluates without suspending gives the values.
const watchRows = frame == null ? liveWatches : watchData.frame === frame ? watchData.rows : [];
for (const w of watches) {
const r = watchRows.find((x) => x.expression === w);
out.push({
@@ -505,7 +511,7 @@ function VariablesPane({ session }: { session: DebugSession }) {
kind: "watch",
name: w,
variable: r?.result ?? null,
error: frame == null ? "Not suspended" : (r?.error ?? null),
error: frame == null && !live ? "Not suspended" : (r?.error ?? null),
});
}
if (frame != null && scopeData.frame === frame) {
@@ -533,7 +539,7 @@ function VariablesPane({ session }: { session: DebugSession }) {
}
}
return out;
}, [lastEval, watches, watchData, scopeData, frame]);
}, [lastEval, watches, watchData, scopeData, frame, live, liveWatches]);
const run = async () => {
const e = expression.trim();
@@ -305,6 +305,12 @@ export const EXECUTION_PAGES: PageSpec[] = [
hint: "Values of local variables are shown after the lines that use them while suspended.",
},
{ kind: "toggle", key: "debugger.sortValues", label: "Sort values alphabetically" },
{
kind: "toggle",
key: "debugger.liveWatches",
label: "Evaluate watches while the program runs",
hint: "Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.",
},
{
kind: "toggle",
key: "debugger.valueTooltip",
+2
View File
@@ -1647,6 +1647,8 @@
"Debug in Browser": "Debug in Browser",
"Opens a URL in Chrome or Edge with the debugger attached (arg: the URL).": "Opens a URL in Chrome or Edge with the debugger attached (arg: the URL).",
"Debugging a script that starts Vite, Next.js or another dev server also opens its page in Chrome or Edge with the debugger attached.": "Debugging a script that starts Vite, Next.js or another dev server also opens its page in Chrome or Edge with the debugger attached.",
"Evaluate watches while the program runs": "Evaluate watches while the program runs",
"Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.": "Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.",
"Stash Selected Files…": "Stash Selected Files…",
"Select the files to stash in the Commit view first": "Select the files to stash in the Commit view first"
}
+3 -1
View File
@@ -8033,5 +8033,7 @@
"Debug a dev server's page in the browser": "在浏览器中调试开发服务器的页面",
"Debug in Browser": "在浏览器中调试",
"Opens a URL in Chrome or Edge with the debugger attached (arg: the URL).": "在 Chrome 或 Edge 中打开 URL 并附加调试器(参数:URL)。",
"Debugging a script that starts Vite, Next.js or another dev server also opens its page in Chrome or Edge with the debugger attached.": "调试启动 Vite、Next.js 等开发服务器的脚本时,同时在 Chrome 或 Edge 中打开其页面并附加调试器。"
"Debugging a script that starts Vite, Next.js or another dev server also opens its page in Chrome or Edge with the debugger attached.": "调试启动 Vite、Next.js 等开发服务器的脚本时,同时在 Chrome 或 Edge 中打开其页面并附加调试器。",
"Evaluate watches while the program runs": "程序运行时计算监视表达式",
"Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.": "仅适用于无需暂停即可计算的调试器(JavaScript)。带副作用的监视表达式在每次刷新时都会再次执行。"
}
+3
View File
@@ -101,6 +101,7 @@ export interface DebuggerSettingsValid {
runToCursorInlay: boolean;
inlineValues: boolean;
sortValues: boolean;
liveWatches: boolean;
valueTooltip: boolean;
valueTooltipOnSelection: boolean;
valueTooltipDelay: number;
@@ -293,6 +294,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
runToCursorInlay: true,
inlineValues: true,
sortValues: false,
liveWatches: false,
valueTooltip: true,
valueTooltipOnSelection: true,
valueTooltipDelay: 700,
@@ -451,6 +453,7 @@ export function validateDebugger(raw: unknown): DebuggerSettingsValid {
runToCursorInlay: bool(v.runToCursorInlay, d.runToCursorInlay),
inlineValues: bool(v.inlineValues, d.inlineValues),
sortValues: bool(v.sortValues, d.sortValues),
liveWatches: bool(v.liveWatches, d.liveWatches),
valueTooltip: bool(v.valueTooltip, d.valueTooltip),
valueTooltipOnSelection: bool(v.valueTooltipOnSelection, d.valueTooltipOnSelection),
valueTooltipDelay: num(v.valueTooltipDelay, d.valueTooltipDelay, WORKFLOW_LIMITS.tooltipDelay, true),