diff --git a/.gitignore b/.gitignore index 3bee4d9f..646d9065 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,12 @@ tests/**/*.js.map # negation, `git add` silently skips new fixtures (how PR #252 lost one) !tests/fixtures/debug-scripts/*.js !tests/fixtures/javascript/subprocess-tree/*.js +# The JavaScript stepper's bundle fixture (issue #1130): an esbuild bundle, its +# source map, and both of its sources, the dependency under node_modules/ where +# the bundler found it. Hand-written fixtures, not build output. +!tests/fixtures/javascript/step-skipped-code/bundle/node_modules/ +!tests/fixtures/javascript/step-skipped-code/bundle/**/*.js +!tests/fixtures/javascript/step-skipped-code/bundle/**/*.js.map # Package source compilation artifacts packages/*/src/**/*.js diff --git a/changelog.d/1130.fixed.md b/changelog.d/1130.fixed.md new file mode 100644 index 00000000..71d8404a --- /dev/null +++ b/changelog.d/1130.fixed.md @@ -0,0 +1 @@ +**A JavaScript step lands where your code next runs, and is no longer lost in Node's own code.** `step_into` on a line that calls a Node builtin took about 6 s on a Linux host and answered `pending`, blaming "a long-running call"; on the first `console.log` of a process it never landed at all and the program ran to its end. js-debug's own "smart stepper" was deciding where such a step ends: while the step was in skipped code it stepped again by itself, one engine step per statement (131 for one `console.log`), with a flag that moves the step to a later task and loses it. That stepper is now off for every session, and the server steps through skipped code itself, over js-debug's raw CDP socket, for `step_into`, `step_over` and `step_out` alike. A `step_into` that lands in skipped code walks on, one engine step at a time, until your code is on top again or the walk has taken 512 engine steps; then it steps out. The walk has no time bound, so a step lands in the same place on every host. A `step_into` on a line that calls your own function through skipped code (an `on` or `once` event listener behind `emitter.emit`, an array callback, a route handler from inside express) lands in that function when the walk reaches it within 512 engine steps; on a line whose call stays in skipped code (`console.log`) it lands where the call returned, and when the walk took all 512 engine steps first, the step's answer says so (`Stepped into. step_into walked 512 engine steps into the call, its limit, and was still in skipped code … so it stepped out …`; on Linux such a walk answers `pending` first, and the `wait_for_stop` answer after it carries the sentence in `lastStop.text`) and that code of yours the call runs further in or only schedules did not stop the step; a pause in your code on the line the step started from is where it stops (the line's next statement, or a one-line loop's header in its first iteration); on a line that only starts a later task (`setTimeout`) it lands on the next line instead of inside the callback some time later. A `step_over` or `step_out` that returns into skipped code steps out to the nearest frame of your program below; when nothing of your program called or awaits the function (the last line of a request handler, a timer callback, a `.then` callback) the program is resumed rather than walked through the internals of later tasks (a callback of yours already queued behind a `.then` callback is where V8's own step stops), and the pending answer then says the step left its frame, on an attach with `smartStep: true` too (a step still executing, such as a `step_over` of a long call, gets no such sentence). What counts as skipped is still js-debug's own verdict, asked at every landing, so `justMyCode`, your `skipFiles` and source maps decide it as before, and in a bundle your own lines stay program code after a stop in a bundled dependency; `justMyCode: false` (or `smartStep: false`) still lands every step where V8 lands. A forked child steps the way its root session does, launched or attached. Changed on purpose: a pause asked for while a step is still pending is reported as the pause, where the program is, and is not stepped away from (one case is not yet so, #1208: when a `step_into` is pending because the program is blocked in native code or idle, the pause stops inside the expression the server evaluates to wake the program before a pause); and the sentence a pending step carries no longer mentions js-debug's stepper. On Linux every engine step costs about 44 ms whoever sends it (#1163): the steps land in the same places there, and a long walk answers `pending: true` first, with a sentence saying the stepper is walking through skipped code in place of the one that blamed "a long-running call", after which `wait_for_stop` answers where it lands (measured on an Ubuntu 24.04 host with 2 vCPUs under Node 22: the first `console.log` of a process lands on the next line after about 17 s, a later one after about 5.5 s; a custom `util.inspect` function behind `console.log` is entered at once, in about 4.7 s). Not fixed here: a `step_into` on a `require` line does not land where the call returned (Node's loader returns through `try … finally`, one of the steps V8 itself loses, #1161): the first load of a module of yours is lost, and in the measured cases of a built-in or already loaded module the step stops further down the same function, with the lines between run, as before; `step_over` on such a line lands on the next one. (#1130) diff --git a/changelog.d/1173.changed.md b/changelog.d/1173.changed.md new file mode 100644 index 00000000..17170bde --- /dev/null +++ b/changelog.d/1173.changed.md @@ -0,0 +1 @@ +**The JavaScript guide says where V8's fix for the steps it loses stands.** V8 16.0 fixes the lost step out of a function that returns through `try … finally` (V8 issue 569814973); no Node release has it yet. On a runtime with it, these steps land in the caller, and a `step_over` off the end of a `finally` block first stops once more at the end of the `return`, with the value it returns. (#1173) diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 670a02c9..c56537f3 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -86,6 +86,23 @@ pause on raised exceptions in Ruby — it will also stop on caught ones. (Attach sessions never apply a language default; their `breakOnExceptions` default is `"none"` for every language.) +## JavaScript: a step that leaves a function through `finally` is lost + +V8 loses a step that leaves a function through a `return` that runs a `finally` first: a +`return` inside `try … finally`, a `return` out of a `for … of` loop, a function with a +`using` declaration, and every async generator (#1161; in `async` functions and generators, +#1174). That is a `step_out` of such a function, or a `step_over` / `step_into` off its last +statement; a step that crosses an `await` first is not lost. Measured on Node 22.23.2, 24.14.1 +and 26.9.0 (Node 16.3.0 lands these steps, 16.4.0 and later do not). The step either never +lands, and the program runs on or ends (`pending: true`, or `Step completed as session +exited.`), or, for a `step_over` off the end of a `finally` block, can stop in the next call +of the same function instead of the caller. mcp-debugger does not rescue these steps. + +Workaround: set a breakpoint on the line where you expect execution to come back, then +`continue_execution`. The fix is in V8 16.0 (V8 issue 569814973, tracked here as #1173). No +Node release has it yet: it reaches you only through a Node release whose V8 has it. See the +[JavaScript guide](./javascript/README.md). + ## Dart/Flutter: what the SDK debug adapter does differently The Dart adapter drives the SDK's own `dart debug_adapter` / `flutter debug-adapter`, so diff --git a/docs/javascript/README.md b/docs/javascript/README.md index 5b3b0e39..90d2cd93 100644 --- a/docs/javascript/README.md +++ b/docs/javascript/README.md @@ -97,41 +97,117 @@ The JavaScript adapter automatically configures: ### Stepping and pausing inside dependencies (`justMyCode`, `skipFiles`) -js-debug has no `justMyCode` key of its own; the launch transform turns the intent into two js-debug keys: -`skipFiles` (V8 blackboxing — `node_modules` is on the list while `justMyCode` is true, Node internals always) and -`smartStep`, whose stepper **keeps stepping while the program is in a skipped frame** — in the direction you asked -for, falling back to step-out — instead of reporting the stop. On a server every pause lands in Node internals, and -a request path enters your code by calls, not returns, so with the stepper on neither a pause nor a `step_over` / -`step_out` issued from a skipped frame lands (issue #678); a `step_into` still reaches the next call into your -code. `justMyCode: false` turns the stepper off and takes `node_modules` off the list. What that means in practice: - -| Launch | `skipFiles` sent | `smartStep` | A breakpoint inside a dependency | `step_over` from that breakpoint | `pause_execution` on an idle server | -|---|---|---|---|---|---| -| default (`justMyCode: true`) | `/**`, `**/node_modules/**` | `true` | fires; frame 0 is the dependency frame | may never land on a request path (`pending: true`; the message names the skipped frame, the stepper and the remedy) | may never land (`pending: true`; the message names the stepper and the remedy) | -| `dapLaunchArgs: { justMyCode: false }` | `/**` | `false` | fires | lands on the next line of the dependency | lands as soon as any JavaScript runs (the next request or timer), in an internal frame if that is where it is (the stack response marks it). With the smart-stepper off, steps also stop in unmapped generated helpers it used to skip | -| `dapLaunchArgs: { skipFiles: [...] }` | exactly your list | follows `justMyCode` unless set | fires | lands unless the frame is on your list and the stepper is on | may never land while the stepper is on and `/**` is on your list | -| `adapterLaunchConfig: { smartStep: false }` (default list) | `/**`, `**/node_modules/**` | `false` | fires | lands in the next frame V8 does not skip (an internals frame on a request path) | lands, in an internals frame | +js-debug has no `justMyCode` key of its own; the launch transform turns the intent into two keys: `skipFiles`, the +code a step does not stop in (Node internals always, `node_modules` while `justMyCode` is true), and `smartStep`, +whether steps step through skipped code at all. `justMyCode: false` takes `node_modules` off the list and turns +that stepping off. + +**The server steps through skipped code itself** (issue #1130). js-debug's own smart stepper did it before, and is +now off for every session whatever `smartStep` says: it re-stepped with a flag that moves the step to a later task +and loses it (a `step_into` on the first `console.log` of a process ended the session), and it took one engine step +per statement of the skipped code (131 for one `console.log`, about 6 s on a Linux host). `smartStep` is read as the +session's choice instead, and a session that chose it has its steps served by the server over js-debug's raw CDP +socket. What "skipped" means is still js-debug's own verdict on the frame, so `justMyCode`, your own `skipFiles` and +source maps (an unmapped helper of a source-mapped file) all count. It is asked at every landing, so in a bundle the +dependency's lines are skipped and your own lines of the same script are not; only a module of Node's own, one source +per script, is not asked about twice. + +A `step_into` that lands in skipped code walks on, one engine step at a time, until your code is on top again or the +walk has taken 512 engine steps in skipped code; then it steps out. The walk has no time bound: where a step lands +is decided by the program, never by the clock, so the same step lands in the same place on any host. What the host +changes is how long the walk takes. An engine step costs about 1.6 to 2.5 ms through the server on Windows and +about 44 ms on Linux (issue #1163), so on Linux a long walk outlasts the step's 5 s grace window: the step answers +`pending: true` with a sentence saying the stepper is walking through skipped code, and +[`wait_for_stop`](../tool-reference.md#wait_for_stop) answers where it lands (the first `console.log` of a process: +`pending`, then the next line after about 17 s; measured times below). + +What a step does when the session steps through skipped code (the launch default): + +| Step | From | Lands | +|---|---|---| +| `step_into` | a line that calls your function through skipped code (`emitter.emit` to an `on` or `once` listener, an array callback, a route handler from inside express) | in that function, when the walk reaches it within 512 engine steps, on Windows and Linux alike. Measured through the server on Windows: 11 engine steps to an `on` listener, 35 to a `once` listener, 84 to a custom `util.inspect` function behind a later `console.log`. A function of yours that the call reaches only further in is not entered: the step steps out, as in the next row | +| `step_into` | a line whose call stays in skipped code (`console.log`) | where the call returned: the next line, or the line's next statement. A walk that comes back out by itself is a plain `Stepped into`. One that takes all 512 engine steps steps out, and the step's answer says so, and that code of yours the call runs further in or only schedules (a timer callback) did not stop the step; where that walk outlasts the 5 s window (Linux) the step's answer is the `pending` one, and the sentence comes with the landing instead: the `wait_for_stop` answer that follows says `Paused (step) at …` and carries it in `lastStop.text`. Measured through the server on Windows, the walk comes back out by itself: about 390 engine steps for the first `console.log` of a process, 130 for a later one. On Linux the same walks take longer and answer `pending` first (below) | +| `step_into` | a line that goes on after the call (`console.log(a); console.log(b);`, a one-line `for … of` loop) | at the next position on that line where your code runs: the next statement, or the loop header's next position, in the first iteration. `step_into` again goes on | +| `step_into` | a `require` line | not where the call returned, on today's Node versions: Node's loader returns through `try … finally`, so stepping back out of it is one of the steps V8 loses (issue #1161, below). The first load of a module of yours is lost and the program runs on. In the measured cases of a built-in module or one already loaded (`require('node:fs')`, a second `require` of a loaded file, on Windows), the walk ended on its step bound inside the loader and the step stopped further down the same function, with the lines between run, as without the server's stepper. Use `step_over` on a `require` line (it lands on the next line), or set a breakpoint in the module | +| `step_into` | a line that calls native code only (`JSON.stringify`) | on the next line, as a plain `Stepped into`: there is nothing to walk into | +| `step_into` | a line that only starts a later task (`setTimeout`, a `.then` callback) | on the next line, never in the callback some time later; a breakpoint in the callback stops there | +| `step_over`, `step_out` | a frame whose caller is skipped code, with your code further down the stack | in that frame of yours | +| `step_out` | an `async` function the event loop resumed | in the function that awaits it, in the call that awaited (V8's own step). Not for TypeScript compiled for a target below ES2017 (issue #1165): there the step does not land in the awaiting function, and the program runs on to the next breakpoint or its end | +| `step_over`, `step_out` | the last line of a function that nothing of yours called or awaits (a request handler, a timer callback, a `.then` callback) | nowhere of its own: nothing of your program is on the stack. If another callback of yours is already queued behind a `.then` callback, V8's step stops in it; otherwise the program is resumed, and the answer is the next stop if one comes while the step waits (a breakpoint, the program's end), or `pending: true` if none does (with a sentence saying the step left its frame, on an attach with `smartStep: true` too) | +| any step | skipped code (a breakpoint inside a dependency) | `step_into` walks on, into your handler when the walk reaches it within 512 engine steps. `step_over` and `step_out`: when your code called the dependency, in your caller at once, where the call returned; when nothing of yours is on the stack (a request path inside a framework), the program runs on, as in the row above. `justMyCode: false` steps inside that code | + +A breakpoint or an exception reached during a step stops as itself. A `debugger;` statement reached during a step is +reported as the step's landing: V8 reports the two alike, and it is where the program stopped. (A `debugger;` in +skipped code does not stop at all, with or without a step in flight.) A pause asked for while a step +is still pending is the caller's: the next stop is reported as the pause, where the program is, in Node's own code +if that is where it is (the stack response marks the frame). A step never steps away from it. One case is not yet +so (issue #1208): when a `step_into` is pending because the program is blocked in native code or idle, the pause +stops inside the expression the server evaluates to wake the program before a pause, and is reported as a step at +`repl:1`. A pending `step_over` of a call of your own that blocks or loops is not affected: the pause stops in it. + +| Launch | `skipFiles` sent | Steps through skipped code | `step_over` from a breakpoint inside a dependency | +|---|---|---|---| +| default (`justMyCode: true`) | `/**`, `**/node_modules/**` | yes | lands in your caller when your code called the dependency; runs on when nothing of yours is on the stack (`pending: true`; the message names the skipped frame and the remedy) | +| `dapLaunchArgs: { justMyCode: false }` | `/**` | no | lands on the next line of the dependency | +| `dapLaunchArgs: { skipFiles: [...] }` | exactly your list | follows `justMyCode` unless `smartStep` is set | lands unless the frame is on your list | +| `adapterLaunchConfig: { smartStep: false }` (default list) | `/**`, `**/node_modules/**` | no | lands in the next frame V8 does not skip (an internals frame on a request path) | A caller-supplied `skipFiles` **replaces** the default list (VS Code's launch.json semantics); include -`/**` yourself if you still want internals skipped. An explicit `smartStep` always wins over the +`/**` yourself if you still want internals skipped. Without it Node's own code is program code to a +step: a `step_out` of a timer callback lands in Node's timer code. An explicit `smartStep` always wins over the derived value. Attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513) — see -`attach_to_process` in the tool reference. - -Why launch keeps the stepper on by default while attach turns it off (issue #687, measured on js-debug 1.112): -js-debug's V8 blackbox patterns for `/**` cover `node:internal/*` but not top-level builtins such -as `node:url` or `node:events` (the per-builtin patterns are built with a `.js` suffix the live URLs do not -carry), so with the stepper off a `step_into` from a dependency frame stops in those internals one line at a -time (`/url`) instead of in your handler, which the stepper reaches in one press; and `step_into` -an `async` callee in TypeScript compiled for a target below ES2017 costs four unmapped `__awaiter` stops before -the callee's first line. `step_over` across an `await` is unchanged either way. Those costs have no hint -mechanism, while the two pending cases in the default row name their remedy — so the default stays, and -`justMyCode: false` (or `smartStep: false`) is the switch when a pause or a step from a dependency matters more -than stepping into one. +`attach_to_process` in the tool reference. With the stepping off, a step lands where V8 lands: a `step_into` on a +`console.log` line stops in ``, and an `async` callee in TypeScript compiled for a target below +ES2017 costs four unmapped `__awaiter` stops before its first line (issue #687). + +**Steps V8 itself loses** (issue #1161; in `async` functions and generators, issue #1174). V8 loses a step that +leaves a function through a `return` that runs a `finally` first: a `return` inside `try … finally`, a `return` out +of a `for … of` loop, a function with a `using` declaration, and every async generator. The steps lost are a +`step_out` of such a function, and a `step_over` or `step_into` off its last statement. Measured on Node 22.23.2, +24.14.1 and 26.9.0; Node 16.3.0 lands these steps, 16.4.0 and later do not. A step that crosses an `await` first +is not lost. + +Such a step shows one of two symptoms: + +- It never lands, and the program runs on or ends: the step answers `pending: true` while the program keeps + running, or `Step completed as session exited.` when it ends first. +- A `step_over` off the end of a `finally` block can instead stop in the next call of the same function, not in + the caller. Check the stack before you take that stop for the caller. + +The server does not rescue these steps and sets no temporary breakpoints for them: a breakpoint hit in the caller +cannot be told from a hit in a later call of the caller, so the step is V8's own. To get past such a return, set a +breakpoint on the line where you expect execution to come back, then `continue_execution`. The fix is in V8 16.0 +(V8 issue 569814973, tracked here as issue #1173). No Node release has it yet: it reaches you only through a Node +release whose V8 has it. With it these steps land in the caller, and a `step_over` off the end of a `finally` block +first stops once more at the end of the `return`, with the value it returns, as V8 stops at any `return`. + +A different loss, in js-debug: a `step_over` across the first load of a module that has a breakpoint in it runs on +(issue #1162). js-debug pauses at the module's entry to bind the breakpoint and resumes that pause itself while the +step is in flight, and the step is lost with it. + +On Linux every engine step costs about 44 ms whoever sends it (the inspector's socket; issue #1163), against about +1.6 to 2.5 ms through the server on Windows. The steps land in the same places there; they take longer, and a long +walk answers `pending` first. Measured (time from the step's call to its landing, the `pending` answer and the +`wait_for_stop` after it included; three runs each; Windows under Node 24 through the server, Linux on an Ubuntu +24.04 host with 2 vCPUs under Node 22): + +| `step_into` on | Windows | Linux | +|---|---|---| +| the first `console.log` of a process | the next line, at once, 0.7 s | `pending`, then the next line, 16.8 to 17.2 s | +| a later `console.log` (issue #1130's own case) | the next line, at once, 0.3 s | `pending`, then the next line, 5.4 to 5.9 s | +| `console.log` of an object with a custom `util.inspect` function | in that function, at once, 0.2 s | in that function, at once, 4.6 to 4.7 s | +| `emitter.emit` to an `on` / a `once` listener | in the listener, at once, 0.1 s | in the listener, at once, 0.8 to 1.0 s / 2.0 to 2.1 s | +| express `next()` | in the next middleware, at once, 0.1 s | in the next middleware, at once, 1.0 to 1.1 s | +| `setTimeout(...)` | the next line, at once, 0.3 s | `pending`, then the next line, 7.2 to 7.7 s | +| `require('node:fs')`, a built-in | 512 engine steps, then the step out V8 loses: further down the same function, the lines between run, 0.8 to 1.0 s | the same place, `pending` first, about 25 s | +| `require('./mod')`, its first load | lost: the program runs to its end, 1.1 to 1.2 s | the same, `pending` first, about 25 s | + +The two `require` rows are where they were before the server's stepper too (issue #1161, above). A step whose stop is a breakpoint or an exception rather than the step itself is reported as `Stepped over; stopped on 'breakpoint' rather than on the step itself (see stopReason)` — true both when the next -line carries a breakpoint and when a lost step's next request re-hit the same breakpoint; in the second case the -program is back at the line you stepped from, and the message says so. +line carries a breakpoint and when a step that ran on re-hit the same breakpoint on the next request; in the second +case the program is back at the line you stepped from, and the message says so. ### Custom Configuration diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 41ff339d..41b08621 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -490,7 +490,7 @@ Starts debugging a script. - `args` (array of strings, optional): Command line arguments for the script. - `dapLaunchArgs` (object, optional): Standard DAP launch arguments: - `stopOnEntry` (boolean): Stop at first line (default `false` — the opposite of attach, which pauses unless `stopOnEntry` is `false`) - - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` blackboxes `node_modules` through js-debug's `skipFiles` and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, `node_modules`) is stepped through and may never land (`pending: true`, with an explanation); `false` drops `node_modules` from the skip list and turns the stepper off, so steps land inside dependencies and `pause_execution` lands as soon as any JavaScript runs (issue #678). A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) + - `justMyCode` (boolean): Debug only user code (default `true`). JavaScript launch: `true` puts `node_modules` on js-debug's `skipFiles` beside Node internals, and a step does not stop in skipped code: the server steps through it itself, so `step_into` follows a call through skipped code into your own function when its walk reaches it within 512 engine steps, and otherwise steps out and says so (issue #1130; see [`step_into`](#step_into)). The walk has no time bound, so a step lands in the same place on every host; where an engine step is slow (about 44 ms on Linux, issue #1163) a long walk answers `pending: true` first, saying it is walking through skipped code, and `wait_for_stop` answers where it lands. `false` takes `node_modules` off the list and turns that stepping off, so every step lands where V8 lands, inside dependencies and Node internals. A pause lands where the program is either way. A caller `skipFiles` replaces the default list. Source maps are on for every JavaScript launch, `.js` programs included — stops report `src/*.ts` when maps and sources are present; `adapterLaunchConfig: { sourceMaps: false }` opts out (issue #684) - `noDebug` (boolean): DAP's "launch without enabling debugging" flag (default `false`). What it does depends on the adapter, and the response says which case you are in. **Honoured** — the debugger is off: no breakpoint binds, no exception filter arms, no entry stop lands, and no breakpoint, exception or entry stop ever arrives, so a short script ends `stopped` and a server stays `running`. That is a legitimate plain run and says nothing by itself; when the session has breakpoints (line or function), an explicit `breakOnExceptions` other than `"none"`, or `stopOnEntry`, the `warning` says the debugger is off for this launch and names what will not fire — not that no stop of any kind can come — in place of the unbound-breakpoint diagnostics that would otherwise send you to check paths that are fine (issue #710). js-debug, debugpy, Delve and CodeLLDB honour it (debugpy and Delve open no configuration phase at all, so the launch is complete on the launch response; CodeLLDB refuses the configuration requests, and the refusal reaches the `warning` and `get_output` — issue #746). The run ends `stopped` with the program's output and, where the adapter reports one, the exit code (Delve states it as a console line, `Process N has exited with status S`, which is read back as `exitCode` — issue #753). Under the flag Delve runs the program through Go's `exec`, so on Windows the binary needs its `.exe` extension. **Ignored** — rdbg, netcoredbg and the Java bridge run the debugger regardless, and the rust launch transform never forwards the flag: the `warning` says the flag had no effect and everything works as usual. The same warning comes back from `restart_debugging` and from a `dryRunSpawn` check. While such a launch runs, the session remembers the decision (`list_debug_sessions` reports `debuggerDisabled: true`) and every later surface says why: `set_breakpoint` and `list_breakpoints` keep the adapter's own answer (still sent — e.g. js-debug's "Unbound breakpoint", or CodeLLDB's refusal echoed onto each pre-launch breakpoint) and add "the debugger is off for this launch (noDebug is true)…", `pause_execution` is still sent and the same sentence explains a pause that never lands or one the adapter refused, and `step_*`/`continue_execution`/`get_stack_trace`/`get_local_variables`/`evaluate_expression` append it to their "not paused" answers. A `stopped` event only a live debugger produces — a breakpoint the adapter itself reports (or names in `hitBreakpointIds`), an exception stop, an entry stop — proves the debugger on for that adapter build and clears the decision, and so does a breakpoint the adapter verified (every honouring adapter refuses or unbinds one under the flag, so a bound one can only come from a build that ignores it); a pause, a step taken from one, or a `debugger;` statement do not (js-debug lands all three under the flag while its breakpoints stay unbound; an uncaught throw does not stop). On a paused session the sentence keeps only the clause still true of it — breakpoints cannot bind — and outside a live launch (`initializing`/`running`/`paused`) the decision is neither reported nor consulted (issue #749). - Additional DAP launch keys (`program`, `cwd`, `env`, language-specific options) pass through to the adapter. For Python, `module` (`python -m `) or `code` (`python -c`) replaces `program`: debugpy takes exactly one target, so the launch goes out without `program` and the response's `warning` says so (`dapLaunchArgs.module: launched as a module (python -m); program is not sent …`); `scriptPath` still has to name an existing file, and `cwd` is what `-m` puts on `sys.path`: for these launches it defaults to the directory above the top-most package containing `scriptPath` (the `warning` names it), and a module launch of a project sets it to the project root explicitly (issue #985). `dryRunSpawn` reports such a launch's `data.script` as `module: ` or `code: …`. Top-level parameters do **not** belong here: a nested `breakOnExceptions` is honored as an alias (the top-level value wins if both are given) and reported via a `warning` in the response; other misplaced top-level keys (`dryRunSpawn`, `sessionId`, `scriptPath`, `adapterLaunchConfig`) are stripped with a warning instead of silently riding into the launch config. - `adapterLaunchConfig` (object, optional): Adapter-specific launch configuration overrides. Use this for language-specific settings that go beyond standard DAP arguments (e.g., `mainClass` and `classpath` for Java, `buildCommand` for Rust). For Rust, `_adapterSettings` passes through to CodeLLDB (issue #441) — e.g. `{"_adapterSettings": {"scriptConfig": {"lang": {"rust": {"sysroot": "/path"}}}}}` points the Rust formatter lookup at an explicit sysroot; the `CODELLDB_RUST_SYSROOT` env var does the same without per-launch config (a user-supplied `_adapterSettings` value wins over the env var). @@ -703,9 +703,40 @@ ended by a `pause` from elsewhere is read as a pause and may. The step is not cancelled: the session becomes `"paused"` on its own when it completes — call [`wait_for_stop`](#wait_for_stop) to block until it does (or poll `list_debug_sessions`), or call `pause_execution` to interrupt it. -The adapter may append one sentence to that message explaining why the step may never land — the JavaScript adapter -does so for a step issued from a frame its `skipFiles` blackbox while `smartStep` is on (issue #678) — so match a -pending step by its `pending: true` flag, not by the message text. +The adapter may append one sentence to that message saying what the step is waiting for. The JavaScript adapter +does so for a session whose steps the server's stepper serves (issues #678, #1130), from what the stepper last +recorded of the step. When that latest record is that the step is walking, or that it left the stack, the step is +known not to be a long-running call, and nothing promises it will pause, so the message opens differently: `Step +dispatched; it has not landed after 5s. The session is 'running': wait_for_stop blocks until the program next +stops or ends, and pause_execution interrupts it.`, followed by the sentence: + +- **Walking.** A `step_into` the stepper is walking through skipped code, one engine step at a time (a long walk + where an engine step is slow: about 44 ms on Linux, issue #1163): `The stepper's last record of this step is that + it is walking through skipped code (Node internals, node_modules, or files on skipFiles) one engine step at a time: + it stops the step when your program's code is next on top, and if the walk reaches its limit of 512 engine steps + first, it steps out toward the nearest frame of your program (with none below it, the program is resumed). A + breakpoint reached on the way stops the program there, and if the engine loses the step on the way the program + runs on.` (`pause_execution` while the walk is taking engine steps is answered as your pause. While the program + is blocked in native code or idle under the pending `step_into`, it stops inside the server's own wake evaluation + and is reported as a step at `repl:1`: issue #1208.) A walk that reached its limit and is + stepping out, or one during which js-debug resumed a pause of its own (the step may have been lost with it, issue + #1162), is no longer recorded as walking and gets no such sentence. +- **Left its frame.** The stepper ended the step by resuming the program: the step left the frame it started in and + reached skipped code with nothing of your program below it (a function Node called, such as a timer or event + callback, returned to the event loop), so it will not land, and `wait_for_stop` answers at the next breakpoint or + when the program ends. + +On a launch, a step issued from skipped code that is not recorded as walking instead names the frame and says a step +does not stop there (that sentence follows the `Step dispatched; it has not landed after 5s. …` lead when the stepper +also recorded that it left the stack, and otherwise follows the generic `Step dispatched; the program is still +executing after 5s …` lead above). + +A step still executing (a `step_over` of a long call in the function's own frame) gets no sentence. Neither does a +step V8 itself lost (issues #1161, #1174: one that leaves a function through a `return` inside `try … finally`, out of +a `for … of` loop, from a function with a `using` declaration, or from an async generator): the server cannot tell it +from a step still executing, so set a breakpoint where you expect execution to come back. An attach whose steps the +stepper serves (`smartStep: true`) gets the walking and left-its-frame sentences too. +So match a pending step by its `pending: true` flag, not by the message text. Once a stop has been observed, the stop path owns the answer — a step that demonstrably landed is never reported as pending afterwards, at the cost of the response then being bounded by the stack-trace round trip rather than by the ~5s window. If the debuggee ends while the step is in flight the result is still a success, with a terminal `state` and a message such as `"Step completed as session terminated."`. @@ -732,6 +763,48 @@ Steps into function calls on the current line. Same ~5s wait and `pending: true` contract as step_over — see [Pending steps](#pending-steps). +**JavaScript** (a launch that steps through skipped code, the default; issue #1130): + +- A `step_into` that lands in skipped code (Node internals, `node_modules`, files on `skipFiles`) walks on, one + engine step at a time, until your code is on top again or the walk has taken 512 engine steps in skipped code; + then it steps out. The walk has no time bound: the same step lands in the same place on every host. On Linux, + at about 44 ms an engine step (issue #1163), a long walk outlasts the ~5 s window: the step answers + `pending: true` with the walking sentence (see [Pending steps](#pending-steps)), and `wait_for_stop` answers + where it lands. Measured on an Ubuntu 24.04 host with 2 vCPUs under Node 22: the first `console.log` of a process + lands on the next line after 16.8 to 17.2 s, a later one after 5.4 to 5.9 s, both `pending` first; a custom + `util.inspect` function behind `console.log` is entered at once, in 4.6 to 4.7 s (on Windows each of these + answers at once, in under 1 s). +- A line that calls your own function through skipped code lands in that function when the walk reaches it within + 512 engine steps: an `on` or `once` event listener behind `emitter.emit`, an array callback, a route handler from + inside express, a custom `util.inspect` function behind `console.log`. +- A line whose call stays in skipped code lands where the call returned: the next line, or the line's next + statement. A walk that came back out by itself answers a plain `Stepped into`; one that took all of its engine + steps says what is known: `Stepped into. step_into walked 512 engine steps into the call, its limit, and was + still in skipped code (Node internals, node_modules, or files on skipFiles), so it stepped out. Code of yours + that the call runs further in, or only schedules (a timer or promise callback), did not stop the step: a + breakpoint there stops in it. To stop inside the skipped code instead, turn stepping through it off: + justMyCode: false on a launch, smartStep: false on a launch or an attach.` Where the walk ends inside the ~5 s + window (Windows) that sentence is in the step's own message. On Linux a 512-step walk answers `pending` with the + walking sentence first, and the `wait_for_stop` answer that follows (`Paused (step) at …`) carries it in + `lastStop.text`. A `console.log` line comes back out by itself (measured through the server on Windows: + about 390 engine steps for the first `console.log` of a process, 130 for a later one). + A `require` line does not land where the call returned: Node's loader returns through `try … finally`, so + stepping back out of it is one of the steps V8 loses (issue #1161). The first load of a module of yours is lost + and the program runs on. On a built-in module or one already loaded (`require('node:fs')`, a second `require` of + a loaded file) the walk takes its 512 engine steps inside the loader, and the step stops further down the same + function, with the lines between run, as without the server's stepper (Windows: under 1 s; Linux: `pending` + first, about 25 s). + Use `step_over` on a `require` line, or a breakpoint in the module. +- A pause in your code is the landing, on the line the step started from too: on `console.log(a); console.log(b);` + the step stops at the second statement, and on a one-line `for … of` loop at the header's next position, in the + first iteration. +- A line that calls native code only (`JSON.stringify`) has nothing to walk into: a plain `Stepped into` on the + next line. +- A call that only starts a later task (`setTimeout`, a `.then` callback) is not followed: the step lands on the + next line. Set a breakpoint in the callback to stop there. + +See [Stepping and pausing inside dependencies](javascript/README.md#stepping-and-pausing-inside-dependencies-justmycode-skipfiles). + --- ### step_out @@ -753,6 +826,24 @@ Steps out of the current function. Same ~5s wait and `pending: true` contract as step_over — see [Pending steps](#pending-steps). +**JavaScript** (a launch that steps through skipped code, the default; issues #1130, #1161): + +- Out of an `async` function the event loop resumed, the step lands in the function that awaits it, in the + call that awaited: that is the engine's own step. Not for TypeScript compiled for a target below ES2017 (issue + #1165): there the step does not land in the awaiting function, and the program runs on to the next breakpoint + or its end. +- The engine loses a step that leaves a function through a `return` that runs a `finally` first: a `return` + inside `try … finally`, a `return` out of `for … of`, a function with a `using` declaration, and every async + generator (issues #1161, #1174). The server does not rescue it and sets no temporary breakpoint: the step answers + `pending: true`, or `Step completed as session exited.` when the program ends first, and a `step_over` off the + end of a `finally` block can stop in the next call of the same function instead of the caller. Set a breakpoint + on the line where you expect execution to come back, then `continue_execution`. +- Out of a function that nothing of your program called or awaits (a timer callback, a `.then` callback, a + request handler) there is nowhere of its own to land: the program is resumed, and the answer is the next stop or + `pending: true`. + +See [Stepping and pausing inside dependencies](javascript/README.md#stepping-and-pausing-inside-dependencies-justmycode-skipfiles). + --- ### continue_execution @@ -981,9 +1072,11 @@ A frame is program code when the adapter's policy does not call it internal **an } ``` -The adapter may append one sentence explaining why the pause may never land — the JavaScript adapter does so for a -launch whose `smartStep` is on and whose `skipFiles` blackbox Node internals (issue #678) — so match a pending pause -by its `pending: true` flag, not by the message text. +An adapter may append a sentence to that message, so match a pending pause by its `pending: true` flag, not by the +message text. (The JavaScript adapter used to add one about js-debug's own stepper stepping away from a pause that +landed in skipped code; that stepper is off since issue #1130, and a pause lands where the program is, also when +it is asked for while a step is still pending — except when a `step_into` is pending because the program is blocked +in native code or idle, where it stops inside the server's wake evaluation at `repl:1`, issue #1208.) **Notes:** - The `"state"` field is the session state at the moment the tool answers: `"paused"` once the stop has been observed, and `"running"` **only on the pending path** — the request was delivered but the program has not stopped yet. On that path, call [`wait_for_stop`](#wait_for_stop) to block until the state flips to `"paused"` when the target next executes code (or poll `list_debug_sessions`). @@ -1640,9 +1733,9 @@ When the requested pause has not landed by the time the tool answers (a Ruby pro - The initial stop of an attach is reported as `lastStop.reason: "pause"` (`stopReason: "pause"` in `get_stack_trace`) by every adapter, whether the debugger paused the target on request or, as CodeLLDB does, stopped it itself. On Windows, CodeLLDB reports that stop as the `DebugBreakProcess` break-in — an `0x80000003` exception on a helper thread — so the adapter's own words stay beside the pause as `lastStop.rawReason: "exception"` and `description: "Exception 0x80000003 encountered at address …"` (issue #817). Only the first stop of an attach that did not pass `stopOnEntry: false` is read this way: a break-in met later, or first by an attach that opted out of the initial stop, is a real `__debugbreak()` and keeps `reason: "exception"`. - When `processId` was used, the message reads `Attached to process PID ` instead. - The response `warning` reports two distinct `adapterConfig` key outcomes (issues #450/#466): keys the adapter's attach transform genuinely drops (e.g. Python's ptvsd-era `localRoot`/`remoteRoot` — use `pathMappings`) are named as **ignored**, while keys mcp-debugger doesn't recognize are **forwarded to the adapter as-is** and named with an edit-distance suggestion for near-misses (`pathMapping (did you mean pathMappings?)`) — "ignored" means dropped, "forwarded as-is" means the adapter still sees them. The same field also carries the launch-style warning for function breakpoints still unverified at attach (issue #308), and the adapter's own attach-transform notes (issue #908): Dart's note that a `host`/`port` attach built a no-auth `ws://…/ws` URI (and that a `deviceId` is ignored on a Dart runner), COBOL's build options given without `sources` and its C-view-only note. -- js-debug attach honors `adapterConfig` too: `localRoot`/`remoteRoot`/`sourceMaps`/`skipFiles`/`continueOnAttach` and other js-debug attach options reach the debugger (issue #466). Two keys are defaulted when absent (issue #655): `resolveSourceMapLocations: ["**", "!**/node_modules/**"]` (js-debug's own attach default collapses to "resolve everywhere", which applied every dependency's `.js.map` and produced phantom `../src/*.ts` frames) and `cwd` (the server's working directory, or the workspace root in container mode — js-debug needs a base path before it resolves any source map's relative `sources`, even ones next to the generated file). Pass your own value, including `resolveSourceMapLocations: null`, to override. `skipFiles` is deliberately left at js-debug's default: blackboxing `node_modules` would turn a `pause_execution` that lands in framework code on an idle server into the endless step-chase of issue #513 — `get_stack_trace` hides those frames instead. +- js-debug attach honors `adapterConfig` too: `localRoot`/`remoteRoot`/`sourceMaps`/`skipFiles`/`continueOnAttach` and other js-debug attach options reach the debugger (issue #466). Two keys are defaulted when absent (issue #655): `resolveSourceMapLocations: ["**", "!**/node_modules/**"]` (js-debug's own attach default collapses to "resolve everywhere", which applied every dependency's `.js.map` and produced phantom `../src/*.ts` frames) and `cwd` (the server's working directory, or the workspace root in container mode — js-debug needs a base path before it resolves any source map's relative `sources`, even ones next to the generated file). Pass your own value, including `resolveSourceMapLocations: null`, to override. `skipFiles` is deliberately left at js-debug's default: an attach leaves it unset so the target's own files and dependencies are not silently skipped unless requested — `get_stack_trace` hides internal frames instead. - js-debug child auto-attach defaults on only for a target that can read both a temporary probe file created by the server and the installed js-debug bootloader files. Every attach form, including `processId`, is checked: a sidecar can share PIDs without sharing files, and an SSH or `kubectl` port forward can use a loopback address without sharing the server's filesystem. When locality cannot be verified, including a failed probe, `autoAttachChildProcesses` defaults to `false` and the response warns, preventing the injected server-local bootloader path from breaking later forks. An explicit boolean in `adapterConfig.autoAttachChildProcesses` is preserved; use `true` only when the target and its children can load the server's js-debug bootloader and reach its debugger endpoint. -- `justMyCode` has no effect on a JavaScript attach: js-debug has no such key, and the attach transform derives nothing from it (a launch derives `skipFiles` and `smartStep` from it — see [start_debugging](#start_debugging)). Set `adapterConfig.skipFiles` / `adapterConfig.smartStep` yourself; attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513), so pauses and steps land where the program is (issue #678). +- `justMyCode` has no effect on a JavaScript attach: js-debug has no such key, and the attach transform derives nothing from it (a launch derives `skipFiles` and `smartStep` from it — see [start_debugging](#start_debugging)). Set `adapterConfig.skipFiles` / `adapterConfig.smartStep` yourself; attach defaults `smartStep` to `false` and leaves `skipFiles` unset (issue #513), so pauses and steps land where the program is (issue #678). `smartStep: true` there turns on the server's stepping through skipped code, as on a launch (issue #1130); js-debug's own stepper stays off either way. - Breakpoints set before the attach are re-sent once the debuggee-owning session is provably live, so their verified state in `list_breakpoints` is authoritative. - Languages whose adapter has no attach implementation (`rust`, `go`, `mock`) fail fast with a clear error. - A failed attach reports `success: false` with the reason in `message` (`Failed to attach: ...`) and tears the proxy down, so no live proxy is left behind; `state` is then `"error"` (or `"stopped"` if the session was already gone). When the adapter answers the handshake's attach request with its own error response, the attach fails at once in its words (issue #896): `Failed to attach: The javascript debug adapter rejected the attach request: …`. When the adapter itself ended the session while the attach was being verified — it exited, or dropped its DAP connection as js-debug does after failing to reach the inspector — the message says which and quotes the adapter's last stderr line (issue #897): `Failed to attach: The debug adapter ended the session during attach verification: it closed its DAP connection; its last stderr line: "Error: Could not connect to debug target at http://localhost:5678: Could not find any debuggable target"`. When the failure happened during proxy initialization, `data` carries `proxyLogPath`, `proxyLogResource`, and `initProgress` diagnostics. Session-lifecycle failures (unknown or terminated session) return the standard application-level `error` payload instead — see [Error Handling](#error-handling). diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index b6a57e3d..c1c25f49 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -57,6 +57,38 @@ const TS_GENERATED_EXTENSION: Readonly> = { '.cts': '.cjs' }; const DECLARATION_FILE = /\.d\.[mc]?ts$/i; + +/** + * A pending step the proxy's stepper (issue #1130) ended by resuming the + * program: it reached skipped code with nothing of the program below it. + */ +const JS_STEP_LEFT_STACK_SENTENCE = + 'The step left the frame it started in and reached skipped code with nothing of your program below it ' + + '(a function that Node called, such as a timer or event callback, returned to the event loop), so the ' + + 'program was resumed and this step will not land. The program is running; wait_for_stop answers when a ' + + 'breakpoint is hit or the program ends.'; + +/** + * A pending step_into the proxy's stepper last recorded as walking through + * skipped code (round 3, decision 2). Worded as that record and the rule the + * walk follows, never as a promise: the walk can still reach the program's + * code, step out at its limit, resume the program when nothing of it is + * below, or be lost by the engine (issue #1161), and the server cannot see + * which until it happens. How to wait for the step or interrupt it is the + * lead's to say (`ErrorMessages.stepNotLanded`, which a recorded step gets + * in place of the generic "still executing ... a long-running call"). + */ +function jsStepWalkingSentence(stepLimit: number | undefined): string { + const limit = typeof stepLimit === 'number' && Number.isInteger(stepLimit) && stepLimit > 0 + ? `its limit of ${stepLimit} engine steps` + : 'its step limit'; + return 'The stepper\'s last record of this step is that it is walking through skipped code (Node internals, ' + + 'node_modules, or files on skipFiles) one engine step at a time: it stops the step when your program\'s code ' + + `is next on top, and if the walk reaches ${limit} first, it steps out toward the nearest frame of your ` + + 'program (with none below it, the program is resumed). A breakpoint reached on the way stops the program ' + + 'there, and if the engine loses the step on the way the program runs on.'; +} + /** * js-debug's `_createPausedDetails` fallback for a CDP pause it has no * breakpoint for: a real `debugger;` statement, and (issue #1097) its own @@ -407,58 +439,73 @@ export const JsDebugAdapterPolicy = { hasNoSource(frame.file || '') && (frame.line ?? 0) === 0, /** - * Why a launch-mode pause or step may never stop (issue #678). js-debug's - * smart-stepper (`smartStep`, on by default while justMyCode is true) keeps - * stepping — in the direction that was asked for, step-out after 256 tries — - * while the program is in a frame the skip list blackboxes, and Node - * internals are on the default list: on an idle server every pause lands - * there, and a request path enters user code by calls, not returns, so - * neither the pause nor a step issued from a skipped frame lands. Measured - * on the #686 build: default skip list + smartStep:false → the pause landed; - * internals-only skip list + smartStep:true → the chase, with node_modules - * NOT blackboxed. So the hints key on the effective smartStep plus whether - * the frame in question is skipped, both from the helpers the launch - * transform uses. A caller's own glob (`**\/vendor/**`) is not matched — this - * package has no glob matcher, and an over-match would be a false hint — so - * a step from such a frame gets silence. Attach sessions default neither key - * (#513) and get nothing here. + * What a launch-mode step that has not landed is waiting for (issues #678, + * #1130). The proxy's own stepper serves the steps of a session whose + * effective `smartStep` is on: it never stops in skipped code, it steps out + * toward the nearest frame of the program below, and with none below it + * resumes the program (the stack the step started on is gone). A step + * issued from skipped code (a breakpoint inside a dependency) gets the + * sentence that names the frame and the switch that steps inside that + * code; the frame is matched with the helpers the launch transform uses, + * and a caller's own glob (`**\/vendor/**`) is not matched, since this + * package has no glob matcher. Any other step gets the sentence that it + * left its frame only when the stepper recorded that it ended the step by + * resuming the program (`stepLeftStack`): a step still executing (a + * `step_over` of a long call in its own frame) gets the generic wording. + * A step_into whose latest record is that the stepper is walking it + * through skipped code (`stepWalking`) gets the sentence that says so, + * worded as the stepper's last record (round 3, decision 2): a walk that + * outlasts the grace window is no long-running call of the program's. + * A pause gets nothing: js-debug's stepper, which stepped away from a pause + * that landed in skipped code, is off (the pending pause has its own + * wording, issue #1146). Attach sessions default neither key (#513), and + * their skip configuration is the target's: they get only what the + * stepper recorded, which it records only for a step it served (an attach + * with `smartStep: true`). */ describePendingStop: (info: PendingStopContext): string | undefined => { - if (info.attachMode) { + // A pause is never stepped away from any more: it lands where the + // program is, in Node's own code if that is where it is. + if (info.operation === 'pause') { return undefined; } + if (info.attachMode) { + if (info.stepWalking) { + return jsStepWalkingSentence(info.stepWalking.stepLimit); + } + return info.stepLeftStack === true ? JS_STEP_LEFT_STACK_SENTENCE : undefined; + } const merged = { ...(info.launch?.dapLaunchArgs ?? {}), ...(info.launch?.adapterLaunchConfig ?? {}) }; if (!resolveJsLaunchSmartStep(merged)) { return undefined; } - const internalsSkipped = jsLaunchSkipsNodeInternals(merged); - if (info.operation === 'pause') { - return internalsSkipped - ? "js-debug's smart-stepper is on for this launch (smartStep: true, the default while justMyCode is true) and " + - 'Node internals are skipped, so a pause that lands in internals — where an idle server always is — is ' + - 'stepped through instead of reported and may never land. Set a breakpoint in your own code, or relaunch ' + - 'with dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to pause where the program is.' - : undefined; + // What the step is doing, by the stepper's own record: it comes before + // what the frame the step was issued from suggests. + if (info.stepWalking) { + return jsStepWalkingSentence(info.stepWalking.stepLimit); } const frame = info.fromFrame; - if (!frame) { - return undefined; - } - const file = frame.file || ''; - const where = `${file}:${frame.line}`; - if (internalsSkipped && (file.includes('') || file.startsWith('node:'))) { - return `The step was issued from a skipped frame in Node internals (${where}); js-debug's smart-stepper keeps ` + - 'stepping while the program is in skipped code, so on a request path the step may never land. Use ' + - 'continue_execution with a breakpoint in your own code, or relaunch with adapterLaunchConfig.smartStep: false ' + - 'to stop in the next frame V8 does not skip.'; + const file = frame?.file || ''; + const fromSkippedCode = frame !== undefined && ( + (jsLaunchSkipsNodeInternals(merged) && (file.includes('') || file.startsWith('node:'))) || + (jsLaunchBlackboxesNodeModules(merged) && NODE_MODULES_SEGMENT.test(file)) + ); + if (fromSkippedCode) { + return `The step was issued from skipped code (${file}:${frame.line}), and a step does not stop in skipped code: ` + + "it runs until your program's code is on top again. That has not happened: either nothing of your program " + + "was below that frame, so the step ended in Node's event loop and the program is running, or the call is " + + 'still in flight. It stops at the next breakpoint in your own code. Relaunch with ' + + 'dapLaunchArgs.justMyCode: false (or adapterLaunchConfig.smartStep: false) to step inside that code.'; } - if (jsLaunchBlackboxesNodeModules(merged) && NODE_MODULES_SEGMENT.test(file)) { - return `The step was issued from a skipped frame (${where}); this launch blackboxes node_modules ` + - "(justMyCode: true) and js-debug's smart-stepper keeps stepping while the program is in skipped code, so on " + - 'a request path the step may never land. Relaunch with dapLaunchArgs.justMyCode: false to step through ' + - 'dependencies.'; + // Only what the stepper recorded: a step it did not end by leaving the + // stack may still be executing in the frame it started in (I3). + if (info.stepLeftStack !== true) { + return undefined; } - return undefined; + // What the record means, and no more: the stepper resumed the program, so + // this step is over. (A step V8 itself lost, issue #1161, leaves no + // record and cannot be told from one still executing.) + return JS_STEP_LEFT_STACK_SENTENCE; }, /** @@ -1428,6 +1475,9 @@ export const JsDebugAdapterPolicy = { // JavaScript-specific child session behaviors mirrorBreakpointsToChild: true, pauseAfterChildAttach: true, + // js-debug's smart stepper stays off; the proxy's own stepper serves + // the steps of a session whose effective `smartStep` is on (issue #1130). + stepsThroughSkippedCode: true, // js-debug's only word on a condition (or compiled logpoint) that // does not parse is a stderr output line during setBreakpoints or // the child attach; the proxy correlates it (issue #853) diff --git a/packages/shared/src/interfaces/adapter-policy.ts b/packages/shared/src/interfaces/adapter-policy.ts index 50c8d597..d07354f2 100644 --- a/packages/shared/src/interfaces/adapter-policy.ts +++ b/packages/shared/src/interfaces/adapter-policy.ts @@ -230,6 +230,23 @@ export interface PendingStopContext { }; /** The raw top frame the step was issued from — step only, and only when it could be read. */ fromFrame?: StackFrame; + /** + * Step only: the proxy's own stepper (issue #1130) ended this step by + * resuming the program, by the time the grace window elapsed. The step had + * reached skipped code with nothing of the program below it, so the stack + * it started on is gone. Absent for a step that is still executing. + */ + stepLeftStack?: boolean; + /** + * Step only: the latest record of the proxy's own stepper (issue #1130), + * by the time the grace window elapsed, is that it is walking this + * step_into through skipped code, one engine step at a time, and nothing + * since says the walk may have stopped (it reached its limit, or js-debug + * resumed a pause of its own during it). `stepLimit` is the engine steps + * the walk may take before it steps out, when the stepper said. Absent + * otherwise. + */ + stepWalking?: { stepLimit?: number }; } /** Context passed to AdapterPolicy.describeUnresolvedSource (issue #816). */ @@ -602,8 +619,10 @@ export interface AdapterPolicy { * `skipFiles` blackboxes, so a pause on an idle server or a step issued from * inside a dependency is swallowed with nothing to distinguish it from a * slow one. The session layer appends the sentence to the generic pending - * message; undefined leaves that message exactly as it is. Optional — absent - * means the adapter has nothing to add. + * message; undefined leaves that message exactly as it is. A step the + * proxy's stepper has a record of (`stepWalking`, `stepLeftStack`) gets the + * sentence after a lead that says only that the step has not landed (issue + * #1130). Optional — absent means the adapter has nothing to add. */ describePendingStop?(info: PendingStopContext): string | undefined; diff --git a/packages/shared/src/interfaces/dap-client-behavior.ts b/packages/shared/src/interfaces/dap-client-behavior.ts index 679b89b5..4f580320 100644 --- a/packages/shared/src/interfaces/dap-client-behavior.ts +++ b/packages/shared/src/interfaces/dap-client-behavior.ts @@ -122,6 +122,19 @@ export interface DapClientBehavior { * child session is available instead of falling back to the parent. */ childRequiredCommands?: Set; + + /** + * The proxy steps through skipped code itself, and the adapter's own + * stepper that would do it is kept off (issue #1130). js-debug's smart + * stepper re-steps with `breakOnAsyncCall`, which loses the step, and takes + * one engine step per statement of the skipped code. With this set, the + * `smartStep` of the start request is read as the session's choice (step + * through skipped code, or land where the engine lands), the adapter is + * always sent `smartStep: false`, and `stepIn` / `next` / `stepOut` for a + * session that chose it are served by the proxy's stepper over the + * adapter's raw CDP socket. + */ + stepsThroughSkippedCode?: boolean; } /** diff --git a/src/proxy/cdp-function-breakpoint-bridge.ts b/src/proxy/cdp-function-breakpoint-bridge.ts index 9a2e3b62..53fef4aa 100644 Binary files a/src/proxy/cdp-function-breakpoint-bridge.ts and b/src/proxy/cdp-function-breakpoint-bridge.ts differ diff --git a/src/proxy/child-connections.ts b/src/proxy/child-connections.ts index cd795c9e..ad8ab74d 100644 --- a/src/proxy/child-connections.ts +++ b/src/proxy/child-connections.ts @@ -25,6 +25,8 @@ import { resolveExceptionFilters } from '@debugmcp/shared'; import type { AdapterPolicy, ChildAdoptionContract, ChildReport, LanguageSpecificLaunchConfig } from '@debugmcp/shared'; import type { DapConnectionManager } from './dap-proxy-connection-manager.js'; import { createChildSafePolicy } from './child-safe-policy.js'; +import { CdpProxyClient } from './cdp-proxy-client.js'; +import { JsStepper } from './js-stepper.js'; import { releaseByThrowawayAttach } from './throwaway-release.js'; import type { BreakpointSyncResult, @@ -57,6 +59,12 @@ export interface ChildAdoptionDeps { breakOnExceptions?: 'uncaught' | 'all' | 'none'; launchConfig?: LanguageSpecificLaunchConfig; initializedTimeoutMs?: number; + /** + * Whether the root session steps through skipped code (issue #1130), as its + * own start request said: a launch's or an attach's. A child's stepper + * takes that choice over. Undefined (or absent) when the root cannot say. + */ + stepsThroughSkippedCode?: () => boolean | undefined; } export interface ChildConnectionsOptions { @@ -66,6 +74,8 @@ export interface ChildConnectionsOptions { releaseTimeoutMs?: number; /** Absent for a worker whose policy reports no children: adopt() then refuses. */ adoption?: ChildAdoptionDeps; + /** DI seam for tests: the CDP socket of a child whose steps the proxy serves (issue #1130). */ + cdpClientFactory?: () => CdpProxyClient; } /** The worker's answer to CHILD_ADOPT_COMMAND. */ @@ -92,6 +102,10 @@ interface ChildConnection { closed: boolean; /** Cancel a handshake that is still opening this connection. */ cancelAdoption?: (reason: string) => void; + /** The proxy's own stepper for this child, when the adapter's is kept off (issue #1130). */ + stepper?: JsStepper; + /** That stepper's CDP socket: the child's own, from `requestCDPProxy`. */ + cdp?: CdpProxyClient; } /** Forwarded as-is under the child's session id; `terminated` and `close` have their own handling. */ @@ -248,6 +262,9 @@ export class ChildConnections extends EventEmitter { connection.cancelAdoption = undefined; this.answer(held, true); + // Not awaited: the child is adopted either way, and the socket's replay + // covers a pause that comes before it is open. + void this.openStepper(deps, connection); logger.info(`[ChildConnections] Child ${held.report.targetId} adopted as session ${childSessionId}`); return { sessionId: childSessionId, capabilities }; } catch (error) { @@ -300,6 +317,7 @@ export class ChildConnections extends EventEmitter { connection.closed = true; this.clients.delete(sessionId); connection.cancelAdoption?.('child session closed during adoption'); + this.closeStepper(connection); const deps = this.options.adoption; try { await deps?.connectionManager.disconnect(connection.client, options.terminateDebuggee); @@ -396,6 +414,85 @@ export class ChildConnections extends EventEmitter { } } + /** + * A step the child's proxy stepper serves now, or null when it goes to the + * adapter as it is (issue #1130). + */ + stepRequest(sessionId: string, command: string, args?: unknown): Promise | null { + const stepper = this.clients.get(sessionId)?.stepper; + return stepper?.handles(command, args) ? stepper.request(command, args) : null; + } + + /** Any other request for the child: one that resumes or ends it ends a step still in flight. */ + async beforeRequest(sessionId: string, command: string): Promise { + await this.clients.get(sessionId)?.stepper?.beforeRequest(command); + } + + /** + * A child of an adapter whose own stepper is kept off gets the proxy's + * (issue #1130), over that child's own CDP socket: the adapter hands one + * out per target. Not fatal: without it the child's steps are the engine's + * plain ones, and a landing in skipped code is shown as such. + */ + private async openStepper(deps: ChildAdoptionDeps, connection: ChildConnection): Promise { + if (!deps.policy.getDapClientBehavior().stepsThroughSkippedCode) { + return; + } + const { client, sessionId } = connection; + const { logger } = this.options; + const stepper = new JsStepper({ + target: { sendRequest: (command, args, timeoutMs) => client.sendRequest(command, args, timeoutMs) as Promise }, + deliver: (event) => this.sendEvent(sessionId, event.event, event.body) + }); + // The session's choice is the root's: its start request's `smartStep`, a + // launch's or an attach's. The launch configuration is the fallback for a + // root that cannot say. + stepper.setEnabled( + deps.stepsThroughSkippedCode?.() ?? (deps.launchConfig as { smartStep?: unknown } | undefined)?.smartStep === true + ); + connection.stepper = stepper; + let cdp: CdpProxyClient | undefined; + try { + const response = (await client.sendRequest('requestCDPProxy', {}, 5000)) as { body?: { host?: string; port?: number; path?: string } }; + if (connection.closed) { + return; + } + const info = response?.body; + if (!info?.host || !info.port || !info.path) { + throw new Error(`requestCDPProxy returned no address: ${JSON.stringify(info)}`); + } + cdp = this.options.cdpClientFactory?.() ?? new CdpProxyClient(); + stepper.attachCdp(cdp); + await cdp.connect(info.host, info.port, info.path); + if (connection.closed) { + stepper.detachCdp(); + cdp.dispose(); + return; + } + connection.cdp = cdp; + await cdp.send('JsDebug.subscribe', { events: ['Debugger.paused', 'Debugger.resumed'] }); + // Re-enabling the (already enabled) domain makes the proxy replay the + // pause the target is in, if any. + await cdp.send('Debugger.enable', {}); + logger.info(`[ChildConnections] Child session ${sessionId}: the proxy stepper is on its CDP socket`); + } catch (error) { + stepper.detachCdp(); + cdp?.dispose(); + if (connection.cdp === cdp) { + connection.cdp = undefined; + } + logger.warn( + `[ChildConnections] Child session ${sessionId}: no CDP socket for the proxy stepper, its steps stay the adapter's: ${error instanceof Error ? error.message : String(error)}` + ); + } + } + + private closeStepper(connection: ChildConnection): void { + connection.stepper?.detachCdp(); + connection.cdp?.dispose(); + connection.cdp = undefined; + } + /** The policy for a connection opened here: never an in-session adopter (issue #1082). */ private policyForConnections(deps: ChildAdoptionDeps): AdapterPolicy { this.connectionPolicy ??= createChildSafePolicy(deps.policy); @@ -447,7 +544,15 @@ export class ChildConnections extends EventEmitter { private wireChildEvents(connection: ChildConnection): void { const { client, sessionId } = connection; for (const event of FORWARDED_CHILD_EVENTS) { - client.on(event, (body: unknown) => this.sendEvent(sessionId, event, body)); + client.on(event, (body: unknown) => { + // A step's own pauses and resumes are the stepper's (issue #1130): of + // their `stopped` events it reports one itself. + if ((event === 'stopped' || event === 'continued') && + connection.stepper?.withholds({ seq: 0, type: 'event', event, body } as DebugProtocol.Event)) { + return; + } + this.sendEvent(sessionId, event, body); + }); } client.on('terminated', (body: unknown) => { connection.terminatedSeen = true; @@ -465,6 +570,7 @@ export class ChildConnections extends EventEmitter { } private onConnectionClosed(connection: ChildConnection): void { + this.closeStepper(connection); if (this.clients.get(connection.sessionId) !== connection) { // Closed by this worker already (close()/closeAll()), reported then. return; diff --git a/src/proxy/child-session-manager.ts b/src/proxy/child-session-manager.ts index 8c31425c..d08233d1 100644 --- a/src/proxy/child-session-manager.ts +++ b/src/proxy/child-session-manager.ts @@ -16,6 +16,8 @@ import { createLogger } from '../utils/logger.js'; import { createChildSafePolicy } from './child-safe-policy.js'; import type { MinimalDapClient } from './minimal-dap.js'; import { CdpFunctionBreakpointBridge } from './cdp-function-breakpoint-bridge.js'; +import { CdpProxyClient } from './cdp-proxy-client.js'; +import { JsStepper } from './js-stepper.js'; import { sendSetBreakpointsStamping, watchConditionSyntaxErrors, matchStoredBreakpoint } from './breakpoint-condition-errors.js'; import path from 'path'; @@ -44,6 +46,8 @@ export interface ChildSessionOptions { port: number; /** DI seam for tests; only consulted when the policy delivers function breakpoints via CDP (issue #295). */ cdpBridgeFactory?: () => CdpFunctionBreakpointBridge; + /** DI seam for tests: the CDP socket the default bridge opens, which the proxy stepper shares (issue #1130). */ + cdpClientFactory?: () => CdpProxyClient; /** * Read once per adoption (#712). Start intent never modifies parentConfig (#730). */ @@ -151,6 +155,12 @@ export class ChildSessionManager extends EventEmitter { // CDP-delivered function breakpoints (issue #295); present only when the // policy declares functionBreakpointsVia 'cdp' (js-debug) private cdpBridge: CdpFunctionBreakpointBridge | null = null; + /** + * The proxy's own stepper for the program's target (issue #1130); present + * when the policy keeps the adapter's stepper off. It shares the CDP socket + * the bridge opens, and every event of the target passes it first. + */ + private stepper: JsStepper | null = null; // Serializes child event forwarding so a stopped event held by the bridge // (correlation/bind window) cannot be overtaken by later events private childEventChain: Promise = Promise.resolve(); @@ -188,8 +198,29 @@ export class ChildSessionManager extends EventEmitter { this.port = options.port; this.getParentStart = options.getParentStart; this.instanceId = createInstanceId(); + if (this.dapBehavior.stepsThroughSkippedCode) { + this.stepper = new JsStepper({ + target: { + sendRequest: (command, args, timeoutMs) => { + const child = this.activeChild; + if (!child) { + return Promise.reject(new Error(`No active child session for '${command}'`)); + } + return child.sendRequest(command, args, timeoutMs) as Promise; + } + }, + deliver: (evt) => this.forwardChildEvent(evt) + }); + } if (options.policy.functionBreakpointsVia === 'cdp') { - this.cdpBridge = options.cdpBridgeFactory?.() ?? new CdpFunctionBreakpointBridge(); + // One CDP socket per target: the bridge opens it, the stepper listens on it too. + this.cdpBridge = options.cdpBridgeFactory?.() ?? new CdpFunctionBreakpointBridge({ + clientFactory: () => { + const client = options.cdpClientFactory?.() ?? new CdpProxyClient(); + this.stepper?.attachCdp(client); + return client; + } + }); this.cdpBridge.on('breakpointEvent', (evt: DebugProtocol.Event) => { this.emit('childEvent', evt); }); @@ -289,6 +320,38 @@ export class ChildSessionManager extends EventEmitter { return state; } + /** + * The session's choice, read from its start request's `smartStep`: step + * through skipped code (the proxy's stepper serves the steps), or land + * where the engine lands (issue #1130). + */ + setStepThroughSkippedCode(enabled: boolean): void { + this.stepper?.setEnabled(enabled); + logger.info(`[ChildSessionManager:${this.instanceId}] stepping through skipped code: ${enabled ? 'the proxy stepper' : 'off'}`); + } + + /** + * The session's choice as it stands, for a forked child's stepper to take + * over. Undefined when this manager has no stepper (another adapter). + */ + isSteppingThroughSkippedCode(): boolean | undefined { + return this.stepper?.isEnabled(); + } + + /** + * A step the proxy's stepper serves now, or null when it goes to the + * adapter as it is (the session chose plain steps, no CDP socket, a step + * into a named target). + */ + stepRequest(command: string, args?: unknown): Promise | null { + return this.stepper?.handles(command, args) ? this.stepper.request(command, args) : null; + } + + /** Any other request for the target: one that resumes or ends it ends a step still in flight. */ + async beforeChildRequest(command: string): Promise { + await this.stepper?.beforeRequest(command); + } + /** * Route a command to the appropriate child session if needed */ @@ -931,36 +994,12 @@ export class ChildSessionManager extends EventEmitter { if (evt.event === 'initialized') { this.childInitializedCount++; } - const bridge = this.cdpBridge; - if (!bridge) { - // Forward child events through parent - this.emit('childEvent', evt); + // The stepper's own pauses and resumes are its business (issue #1130): + // of a step's many `stopped` events one is forwarded, by the stepper. + if (this.stepper?.withholds(evt)) { return; } - // Serialize through the chain so a stopped event the bridge holds - // (bind/correlation window) keeps its place in the event order. Every - // event first waits for the adoption's bridge attach to settle (issue - // #850); not on adoptionInProgress, which flushEvents() below awaits - // through this very chain. - this.childEventChain = this.childEventChain.then(async () => { - await this.bridgeAttachSettled; - let out = evt; - if (evt.event === 'stopped') { - // An entry stop always goes through the bridge: with nothing armed - // it can still be a late entry inside a function (issue #858). - const reason = (evt.body as { reason?: string } | undefined)?.reason; - if (bridge.hasArmedOrPending() || reason === 'entry') { - try { - out = await bridge.processStoppedEvent(evt); - } catch (err) { - logger.warn(`[ChildSessionManager:${this.instanceId}] bridge stop processing failed, forwarding original: ${String(err)}`); - } - } else { - logger.info(`[ChildSessionManager:${this.instanceId}] stopped event bypassed the CDP bridge (no armed or pending function breakpoints)`); - } - } - this.emit('childEvent', out); - }); + this.forwardChildEvent(evt); }); child.on('error', (err: Error) => { @@ -970,6 +1009,7 @@ export class ChildSessionManager extends EventEmitter { child.on('close', () => { logger.info(`[ChildSessionManager:${this.instanceId}] [child] DAP client connection closed (current count=${this.childSessions.size})`); + this.stepper?.detachCdp(); this.cdpBridge?.detach(); this.emit('childClosed'); this.childSessions.clear(); @@ -979,6 +1019,43 @@ export class ChildSessionManager extends EventEmitter { }); } + /** + * Forward one event of the program's target to the parent connection: the + * target's own events, and the one `stopped` the stepper reports for a step. + */ + private forwardChildEvent(evt: DebugProtocol.Event): void { + const bridge = this.cdpBridge; + if (!bridge) { + // Forward child events through parent + this.emit('childEvent', evt); + return; + } + // Serialize through the chain so a stopped event the bridge holds + // (bind/correlation window) keeps its place in the event order. Every + // event first waits for the adoption's bridge attach to settle (issue + // #850); not on adoptionInProgress, which flushEvents() below awaits + // through this very chain. + this.childEventChain = this.childEventChain.then(async () => { + await this.bridgeAttachSettled; + let out = evt; + if (evt.event === 'stopped') { + // An entry stop always goes through the bridge: with nothing armed + // it can still be a late entry inside a function (issue #858). + const reason = (evt.body as { reason?: string } | undefined)?.reason; + if (bridge.hasArmedOrPending() || reason === 'entry') { + try { + out = await bridge.processStoppedEvent(evt); + } catch (err) { + logger.warn(`[ChildSessionManager:${this.instanceId}] bridge stop processing failed, forwarding original: ${String(err)}`); + } + } else { + logger.info(`[ChildSessionManager:${this.instanceId}] stopped event bypassed the CDP bridge (no armed or pending function breakpoints)`); + } + } + this.emit('childEvent', out); + }); + } + /** * Wait until the child has emitted more 'initialized' events than * `baseline`. The count is latched in wireChildEvents from connect time, so @@ -1059,6 +1136,7 @@ export class ChildSessionManager extends EventEmitter { */ async shutdown(): Promise { logger.info(`[ChildSessionManager:${this.instanceId}] Shutting down child sessions`); + this.stepper?.detachCdp(); this.cdpBridge?.detach(); for (const [id, child] of this.childSessions) { diff --git a/src/proxy/dap-proxy-interfaces.ts b/src/proxy/dap-proxy-interfaces.ts index a59d9042..a92c6de6 100644 --- a/src/proxy/dap-proxy-interfaces.ts +++ b/src/proxy/dap-proxy-interfaces.ts @@ -282,6 +282,12 @@ export interface IDapClient { * has no child sessions — nothing to flush (issue #378). */ flushChildEvents?(): Promise | undefined; + /** + * Whether the session steps through skipped code, as its start request + * said (issue #1130). Optional: only MinimalDapClient implements it, and + * it answers undefined for an adapter with no proxy stepper. + */ + stepsThroughSkippedCode?(): boolean | undefined; } /** @@ -415,6 +421,37 @@ export interface DapProxyDependencies { export const MIRROR_EXPOSE_COMMAND = 'mirrorExpose'; export const MIRROR_UNEXPOSE_COMMAND = 'mirrorUnexpose'; +// The proxy's JavaScript stepper (issue #1130) ended a step by resuming the +// program: the step reached skipped code with nothing of the program below +// it, so the stack it started on is gone and the step will not land. A DAP +// event of the proxy's own, sent to the parent process only (the mirror does +// not forward it); a pending step's answer reads it. +export const PROXY_STEP_LEFT_STACK_EVENT = 'proxyStepLeftStack'; + +// The proxy's JavaScript stepper (issue #1130) is walking a step_into through +// skipped code: sent just before the walk's first engine step there, and again +// when a walk whose record was withdrawn goes on. Body: `{ threadId, stepLimit }`, +// the engine steps the walk may take before it steps out. +export const PROXY_STEP_WALK_STARTED_EVENT = 'proxyStepWalkStarted'; + +// The walk recorded by PROXY_STEP_WALK_STARTED_EVENT is no longer known to be +// going: it reached its step limit and the step is stepping out (`why: 'limit'`, +// sent just before the step-out), or js-debug resumed a pause of its own during +// the walk, after which whether V8 still carries the step is not known +// (`why: 'resumed'`). Body: `{ threadId, why }`. +export const PROXY_STEP_WALK_ENDED_EVENT = 'proxyStepWalkEnded'; + +/** + * Every record the proxy's stepper sends of a step: forwarded to the parent + * process, never to a mirror client. The latest one a pending step has seen + * says what the step was doing when the grace window ended. + */ +export const PROXY_STEP_RECORD_EVENTS: readonly string[] = [ + PROXY_STEP_WALK_STARTED_EVENT, + PROXY_STEP_WALK_ENDED_EVENT, + PROXY_STEP_LEFT_STACK_EVENT +]; + // The session tree (issue #1081): the parent process's answers to a // 'child_reported' status, and the close of an adopted child's connection. // They ride the `dap` envelope too; the envelope's sessionId names the diff --git a/src/proxy/dap-proxy-worker.ts b/src/proxy/dap-proxy-worker.ts index 1bb818c3..e94cfb5e 100644 --- a/src/proxy/dap-proxy-worker.ts +++ b/src/proxy/dap-proxy-worker.ts @@ -24,6 +24,7 @@ import { BreakpointSyncResult, MIRROR_EXPOSE_COMMAND, MIRROR_UNEXPOSE_COMMAND, + PROXY_STEP_RECORD_EVENTS, CHILD_ADOPT_COMMAND, CHILD_RELEASE_COMMAND, CHILD_CLOSE_COMMAND, @@ -357,7 +358,8 @@ export class DapProxyWorker { // handlers (post threadId-backfill); this generic-channel forwarder covers // everything else. initialized is per-client handshake, never replicated. private readonly mirrorEventForwarder = (evt: DebugProtocol.Event): void => { - if (evt.event === 'stopped' || evt.event === 'continued' || evt.event === 'initialized') { + // The proxy stepper's records (issue #1130) are the proxy's own, not the adapter's. + if (evt.event === 'stopped' || evt.event === 'continued' || evt.event === 'initialized' || PROXY_STEP_RECORD_EVENTS.includes(evt.event)) { return; } this.mirrorServer?.broadcastEvent(evt.event, evt.body); @@ -766,7 +768,9 @@ export class DapProxyWorker { port: spawnConfig.port, adapterId: this.adapterPolicy.getDapAdapterConfiguration().type, breakOnExceptions: payload.breakOnExceptions, - launchConfig: payload.launchConfig + launchConfig: payload.launchConfig, + // The root's own start request decides, a launch's or an attach's (issue #1130). + stepsThroughSkippedCode: () => this.dapClient?.stepsThroughSkippedCode?.() } }); this.childConnections.attach(this.dapClient, payload.sessionId); @@ -1200,6 +1204,16 @@ export class DapProxyWorker { this.sendDapEvent(name, body as DebugProtocol.Event['body']); }); } + // The proxy stepper's records of a step (issue #1130): its walk through + // skipped code started or ended, or it ended the step by resuming the + // program. The pending step's answer reads the latest. A child + // connection's stepper sends its own straight to the parent + // (child-connections.ts). + for (const name of PROXY_STEP_RECORD_EVENTS) { + this.dapClient.on(name, (body: unknown) => { + this.sendDapEvent(name, body as DebugProtocol.Event['body']); + }); + } this.connectionManager.setupEventHandlers(this.dapClient, { onInitialized: async () => { @@ -2038,7 +2052,15 @@ export class DapProxyWorker { /** A child session's DAP request, answered on the child's envelope (issue #1081). */ private async forwardToChild(childClient: IDapClient, payload: DapCommandPayload): Promise { try { - const response = await childClient.sendRequest(payload.dapCommand, payload.dapArgs, payload.timeoutMs); + // A step of a child that steps through skipped code is its proxy + // stepper's (issue #1130); any other request may end a step in flight. + const stepped = this.childConnections?.stepRequest(payload.sessionId, payload.dapCommand, payload.dapArgs); + if (!stepped) { + await this.childConnections?.beforeRequest(payload.sessionId, payload.dapCommand); + } + const response = stepped + ? await stepped + : await childClient.sendRequest(payload.dapCommand, payload.dapArgs, payload.timeoutMs); this.sendDapResponse(payload.requestId, true, response, undefined, payload.sessionId); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/src/proxy/js-stepper.ts b/src/proxy/js-stepper.ts new file mode 100644 index 00000000..768060cf --- /dev/null +++ b/src/proxy/js-stepper.ts @@ -0,0 +1,1055 @@ +/** + * The server's own JavaScript stepper (issue #1130). + * + * js-debug has a "smart stepper": while a step lands in code the session + * skips (Node internals, node_modules, an unmapped helper of a source-mapped + * file) it steps again by itself. It does so with `breakOnAsyncCall`, which + * moves the step to a later task and loses it, and it takes one V8 step per + * statement of the skipped code (131 for one `console.log`). Three issues + * (#513, #678/#687, #1130) were that stepper deciding where a step ends. + * + * So js-debug's stepper is off for every session, and this one decides. It + * sits on one js-debug target: that target's DAP connection, and the raw CDP + * socket js-debug hands out with `requestCDPProxy`. One `stepIn`, `next` or + * `stepOut` comes in, one `stopped` goes out. + * + * One CDP command per engine step. `Debugger.stepInto` never carries + * `breakOnAsyncCall`. + * + * The verdict on a landing is js-debug's own mark on frame 0 + * (`stackTrace { levels: 1 }`: `presentationHint: "deemphasize"`), asked at + * once after the CDP `paused`. It is the session's one definition of + * skipped code: it follows `justMyCode`, a caller's `skipFiles` and source + * maps. js-debug's `stopped` for the pause is never waited for: it is sent + * a timer tick later, which costs 12 ms a landing on Windows. + * + * STEPS V8 LOSES STAY LOST. V8 loses a step that leaves a function + * through a `return` that runs a `finally` first: a `return` inside + * try...finally, a `return` out of for...of, a function with a `using` + * declaration, every async generator (issue #1161; V8 issue 569814973). + * js-debug resuming its own module-entry pause while a step is in flight + * loses one too (issue #1162). The stepper does not rescue these: the + * step is V8's own, and the program runs on (or, for a `step_over` off the + * end of a `finally` block, V8 can stop in the next call of the same + * function). There is no rescue because a breakpoint hit in the caller + * cannot be told from a hit in a later call of the caller: CDP names no + * single activation. + * + * Skipped code on top: `step_into` steps in again (that is how a call + * through Node's own code reaches a callback of the program's) until the + * walk has taken its limit of engine steps in skipped code, then steps + * out; `step_over` and `step_out` step out at once. The walk has no time + * bound: where a step lands is the program's to decide, never the clock's, + * so two runs of one program land a step in the same place on any host + * (an engine step costs about 2 ms on Windows and 44 ms on Linux, #1163). + * The stepper records the walk for the step's pending answer: a proxy + * event when it starts, and one when it is no longer known to be going (it + * reached its limit and steps out, or js-debug resumed a pause of its own + * during it). A pause in the program's code is the + * landing, on the line the step started from too: in the measured traces + * V8's step-out lands on the caller's next break position (11:17 after a + * call at 11:1), never back on the call it left, and a first step-in on a + * one-line for...of lands on the header's next position (9:17 to 9:12): + * where the program's code next runs. With nothing + * of the program below (no frame, no awaiter), the stack the step started + * on is gone: the program is resumed, and the only word of it is the + * proxy's own `proxyStepLeftStack` event, for the pending answer (stepping + * out of the bottom frame would land in the next task's internals instead). + * + * A pause that is not the stepper's (another breakpoint, an exception) is + * js-debug's to decide. Resumed by js-debug, the chain waits on. Kept, the + * chain ends and that stop is forwarded as itself. js-debug says "kept" + * with a DAP `stopped`, and says "resumed" with the CDP `resumed` it + * forwards: two sockets, and the `stopped` for a later pause can overtake + * the `resumed` of this one (measured under Node 22 on Linux). So before a + * `stopped` is read as "kept", the CDP stream catches up: one request V8 + * answers, on the socket the events travel on. A pause the caller + * asks for during a chain makes the next stop theirs, wherever it is: V8 + * reports it as the step, so only the request tells them apart. (For the + * same reason a `debugger;` statement reached during a step is reported + * as the step's landing, as js-debug's own stepper reports it.) + * + * js-debug's `stopped` and `continued` events are withheld by count: it + * sends one `stopped` per pause it keeps, out of order with the + * `continued` of the next resume. The last one is forwarded: as reason + * `step` on a landing (it arrives as `pause`, or `step`), unchanged on a + * real stop. + */ +import type { DebugProtocol } from '@vscode/debugprotocol'; +import { createLogger } from '../utils/logger.js'; +import { ErrorMessages } from '../utils/error-messages.js'; +import { + PROXY_STEP_LEFT_STACK_EVENT, + PROXY_STEP_WALK_ENDED_EVENT, + PROXY_STEP_WALK_STARTED_EVENT +} from './dap-proxy-interfaces.js'; + +// redirectable: re-pointed into the per-session proxy log at worker init (#519) +const logger = createLogger('js-stepper', { redirectable: true }); + +/** The slice of the target's DAP connection the stepper needs. */ +export interface StepperTarget { + sendRequest(command: string, args?: unknown, timeoutMs?: number): Promise; +} + +/** The slice of the CDP proxy client the stepper needs. */ +export interface StepperCdp { + send(method: string, params?: object, timeoutMs?: number): Promise; + isConnected(): boolean; + on(event: 'cdp-event', listener: (method: string, params: unknown) => void): unknown; + off(event: 'cdp-event', listener: (method: string, params: unknown) => void): unknown; +} + +export interface JsStepperTunables { + /** + * Engine steps a step-in may take in skipped code before it steps out: the + * walk's only bound. A walk that outlasts the step's grace window (about + * 5 s; measured, a step_into on `require('node:fs')`, whose walk takes + * all 512 engine steps: about 1 s on Windows, about 25 s on Linux) + * answers `pending`, and lands later in the same place. + */ + walkBudgetSteps: number; + /** CDP step commands in one chain, all told: a backstop above the walk's bound. */ + commandCap: number; + /** How long a finished chain waits for js-debug's `stopped` events before it reports without them. */ + settleCeilingMs: number; + /** How long `stackTrace` may answer "not paused" for a pause js-debug keeps. */ + verdictCeilingMs: number; +} + +export const DEFAULT_JS_STEPPER_TUNABLES: JsStepperTunables = { + walkBudgetSteps: 512, + commandCap: 2048, + settleCeilingMs: 2000, + verdictCeilingMs: 2000 +}; + +export interface JsStepperOptions { + target: StepperTarget; + /** Hands an event to whoever forwards this target's events. */ + deliver: (event: DebugProtocol.Event) => void; + tunables?: Partial; + /** Test seam. */ + sleep?: (ms: number) => Promise; +} + +/** + * The CDP request that makes the stream catch up: answered by V8 itself + * (js-debug's proxy passes it on), with no effect on the program. Measured + * answered under Node 22.23.2 and 24.14.1. + */ +const CATCH_UP_METHOD = 'Runtime.getIsolateId'; + +export type StepKind = 'in' | 'over' | 'out'; + +const STEP_OF_COMMAND: Record = { stepIn: 'in', next: 'over', stepOut: 'out' }; +const CDP_COMMAND: Record = { in: 'Debugger.stepInto', over: 'Debugger.stepOver', out: 'Debugger.stepOut' }; + +/** Requests that resume or end the target: a chain still in flight must give it up first. */ +const CHAIN_ENDING_REQUESTS = new Set(['continue', 'disconnect', 'terminate', 'restart', 'goto', 'reverseContinue', 'restartFrame']); + +/** The reasons of a pause that is the step's own, when it hits no breakpoint; any other reason is a real stop. */ +const STEP_REASONS = new Set(['step', 'ambiguous']); + +interface CdpLocation { + scriptId: string; + lineNumber: number; + columnNumber?: number; +} + +interface CdpCallFrame { + functionName?: string; + functionLocation?: CdpLocation; + location: CdpLocation; +} + +interface CdpAsyncFrame { + functionName?: string; + scriptId: string; + lineNumber: number; + columnNumber: number; +} + +interface CdpPaused { + callFrames: CdpCallFrame[]; + reason: string; + hitBreakpoints?: string[]; + asyncStackTrace?: CdpAsyncTrace; +} + +/** One link of V8's async stack. `description` names it: `await`, `Promise.then`, `Timeout`, ... */ +interface CdpAsyncTrace { + description?: string; + callFrames?: CdpAsyncFrame[]; + parent?: CdpAsyncTrace; +} + +type Inbox = + | { type: 'paused'; pause: CdpPaused } + | { type: 'resumed' }; + +/** What the code on top of a pause returns to. */ +type ReturnTarget = + /** A frame of the program on the stack, at this index. */ + | { kind: 'frame'; index: number } + /** The function of the program awaiting it, which is not on the stack. */ + | { kind: 'awaiter'; parent: CdpAsyncFrame } + /** Nothing of the program's. */ + | { kind: 'nothing' } + /** js-debug did not say, or the stack is deeper than was asked about. */ + | { kind: 'unknown' }; + +/** How many frames of a stack js-debug is asked to mark, at most. */ +const MAX_MARKED_FRAMES = 200; + +/** How far past the sync frames js-debug is asked: the labels of the async segments and the awaiter's frame. */ +const ASYNC_MARKS = 12; + +interface Chain { + kind: StepKind; + threadId: number | undefined; + originDepth: number; + originFn: string; + inbox: Inbox[]; + wake: (() => void) | null; + cancelled: string | null; + /** Pauses js-debug keeps, each of which it reports with one `stopped`. */ + kept: number; + /** `stopped` events of this chain seen so far. */ + stoppedSeen: number; + lastStopped: DebugProtocol.Event | null; + commands: string[]; + /** Step-ins sent from a landing in skipped code: the walk's engine steps. */ + spent: number; + /** The walk took all of its engine steps and the step-in stepped out. */ + walkEnded: boolean; + /** The last walk record sent says the walk is going (and nothing since says it may not be). */ + walkRecorded: boolean; + /** Every command the chain may send is spent and skipped code is still on top. */ + capped: boolean; + /** The caller asked for a pause during the chain: the next stop is theirs. */ + pauseRequested: boolean; + /** That pause was taken on no breakpoint of js-debug's: it is reported as the pause it is. */ + pauseTaken: boolean; + /** Whether this chain's uncollected `stopped` events have already been moved to `this.owed`. */ + owedAccounted: boolean; + /** + * The chain ended by resuming the program (the stack it started on is + * gone) and the resume is out: a `stopped` beyond the chain's kept pauses + * is the program's next stop, never the chain's. + */ + leaving: boolean; + /** + * Those next stops, and any `continued` after the first of them (never the + * chain's own: its resume's `continued` comes before the program's next + * pause), held in order until the chain's own record is out, then + * delivered as they are. Dropped if the chain is given up meanwhile: the + * request that gave it up is the caller's, and V8 has moved on (review 10). + */ + afterLeaving: DebugProtocol.Event[]; + startedAt: number; +} + +/** A record of the walk to send just before the command a verdict leads to. */ +type WalkRecord = { record: 'started' } | { record: 'ended'; why: 'limit' }; + +type Verdict = + | { kind: 'wait' } + | ({ kind: 'command'; command: string } & ({ record?: undefined } | WalkRecord)) + | { kind: 'landing'; by: string } + | { kind: 'real-stop' } + | { kind: 'left-stack' }; + +function fnKey(frame: CdpCallFrame): string { + const l = frame.functionLocation ?? frame.location; + return `${l.scriptId}:${l.lineNumber}:${l.columnNumber ?? 0}`; +} + +function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** A pause as V8 reported it, for the debug log: its reason, the breakpoints it hit, its top frame. */ +function describePause(pause: CdpPaused): string { + const top = pause.callFrames[0]; + const where = top ? `${top.functionName || '(anonymous)'} ${top.location.scriptId}:${top.location.lineNumber}:${top.location.columnNumber ?? 0}` : 'no frame'; + return `reason=${pause.reason} hitBreakpoints=${JSON.stringify(pause.hitBreakpoints ?? [])} top=${where} depth=${pause.callFrames.length}`; +} + +/** + * js-debug's mark on a frame. `deemphasize` is its own value for a frame of + * skipped code (skipFiles, or an unmapped position of a source-mapped file); + * the DAP type does not list it. + */ +function markOf(frame: DebugProtocol.StackFrame): string | undefined { + return frame.presentationHint as string | undefined; +} + +export class JsStepper { + private readonly target: StepperTarget; + private readonly deliver: (event: DebugProtocol.Event) => void; + private readonly tunables: JsStepperTunables; + private readonly sleep: (ms: number) => Promise; + + private cdp: StepperCdp | null = null; + private readonly onCdpEvent = (method: string, params: unknown): void => this.handleCdpEvent(method, params); + + /** Whether this session steps through skipped code (the effective `smartStep`). */ + private enabled = false; + /** The pause V8 is in now, as CDP reported it; null while running. */ + private current: CdpPaused | null = null; + private chain: Chain | null = null; + /** `stopped` events of a finished chain still on their way; dropped when they arrive, until the deadline. */ + private owed = 0; + private owedUntil = 0; + /** + * Scripts of Node's own that js-debug marked "Skipped by skipFiles", not + * asked about again. js-debug decides per original source; a Node module + * is one script and one source (`/...`), so its verdict + * holds at every position. A bundle or a node_modules file is not + * remembered: some of its lines can be the program's. + */ + private readonly skippedScripts = new Set(); + /** What each pause's top frame returns to: asked of js-debug once per pause. */ + private readonly targets = new WeakMap(); + + constructor(options: JsStepperOptions) { + this.target = options.target; + this.deliver = options.deliver; + this.tunables = { ...DEFAULT_JS_STEPPER_TUNABLES, ...(options.tunables ?? {}) }; + this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + } + + /** The session's choice: step through skipped code (on), or land where V8 lands (off). */ + setEnabled(enabled: boolean): void { + this.enabled = enabled; + } + + /** The session's choice as it stands: a forked child's stepper takes it over. */ + isEnabled(): boolean { + return this.enabled; + } + + /** Listen on the target's CDP socket. Safe before it is connected. */ + attachCdp(cdp: StepperCdp): void { + this.detachCdp(); + this.cdp = cdp; + cdp.on('cdp-event', this.onCdpEvent); + } + + /** The socket is gone (the target ended): a chain in flight is given up. */ + detachCdp(): void { + this.cdp?.off('cdp-event', this.onCdpEvent); + this.cdp = null; + this.current = null; + this.owed = 0; + this.skippedScripts.clear(); + const chain = this.chain; + if (chain) { + this.chain = null; + chain.owedAccounted = true; + chain.cancelled = 'the CDP connection closed'; + chain.wake?.(); + } + } + + /** Whether this request is one the stepper serves now. */ + handles(command: string, args?: unknown): boolean { + if (!this.enabled || !(command in STEP_OF_COMMAND)) { + return false; + } + // A step into a named target is js-debug's own feature. + if (command === 'stepIn' && (args as { targetId?: number } | undefined)?.targetId !== undefined) { + return false; + } + return this.cdp?.isConnected() === true && this.current !== null && this.current.callFrames.length > 0; + } + + /** + * Serve one step. Resolves when V8 has taken the first command; the one + * `stopped` of the chain is delivered later. + */ + async request(command: string, args?: unknown): Promise { + const kind = STEP_OF_COMMAND[command]; + const origin = this.current; + if (!kind || !origin || !this.cdp) { + throw new Error(`The JavaScript stepper cannot serve '${command}' now`); + } + await this.abandonChain('another step was requested'); + + const top = origin.callFrames[0]; + const chain: Chain = { + kind, + threadId: (args as { threadId?: number } | undefined)?.threadId, + originDepth: origin.callFrames.length, + originFn: fnKey(top), + inbox: [], + wake: null, + cancelled: null, + kept: 0, + stoppedSeen: 0, + lastStopped: null, + commands: [], + spent: 0, + walkEnded: false, + walkRecorded: false, + capped: false, + pauseRequested: false, + pauseTaken: false, + owedAccounted: false, + leaving: false, + afterLeaving: [], + startedAt: Date.now() + }; + this.chain = chain; + this.owed = 0; + + try { + // js-debug's mark on the frame the step starts from: a module of Node's + // own it skips is then not asked about again at a landing. + await this.isSkipped(chain, origin); + await this.sendStep(chain, CDP_COMMAND[kind]); + } catch (err) { + this.chain = null; + throw err; + } + void this.run(chain); + return { type: 'response', seq: 0, request_seq: -1, command, success: true, body: {} } as DebugProtocol.Response; + } + + /** + * A request for the target that is not a step. One that resumes or ends + * the target ends a chain still in flight first. + */ + async beforeRequest(command: string): Promise { + if (CHAIN_ENDING_REQUESTS.has(command)) { + await this.abandonChain(`a '${command}' request`); + } else if (command === 'pause' && this.chain) { + // An explicit pause wins over a step in flight: wherever V8 stops next + // is the caller's pause, in skipped code too. V8 reports a pause taken + // while a step is in flight as the step, so only this tells them apart. + this.chain.pauseRequested = true; + } + } + + /** + * Every event of the target passes here first. True means the stepper + * keeps it: the caller must not forward it. + */ + withholds(event: DebugProtocol.Event): boolean { + const chain = this.chain; + if (event.event === 'stopped') { + if (chain?.leaving && chain.stoppedSeen >= chain.kept) { + // js-debug reports pauses in order, so once every kept pause of the + // chain is reported, a `stopped` after its resume is the program's + // next stop (a breakpoint the resumed program reached while V8's + // answer to the resume was still on its way: review 9, M1). It goes + // out as itself, after the chain's record that it resumed. + logger.debug(`[JsStepper] DAP stopped after the step resumed the program (reason=${(event.body as { reason?: string } | undefined)?.reason}): held until the step's record is out`); + chain.afterLeaving.push(event); + return true; + } + if (chain) { + chain.stoppedSeen++; + chain.lastStopped = event; + const body = (event.body ?? {}) as { reason?: string; description?: string }; + logger.debug( + `[JsStepper] DAP stopped during a step ${chain.kind} (reason=${body.reason}, description=${body.description}): ` + + `${chain.stoppedSeen} seen, ${chain.kept} pauses kept` + ); + chain.wake?.(); + return true; + } + if (this.owed > 0) { + if (Date.now() > this.owedUntil) { + this.owed = 0; + } else if (this.looksOwed(event)) { + // A late report of one of the finished step's own pauses. + this.owed--; + return true; + } + } + return false; + } + if (event.event === 'continued' && chain?.leaving && chain.afterLeaving.length > 0) { + // A resume of a stop held above, not the chain's: it goes out after that stop. + chain.afterLeaving.push(event); + return true; + } + // One `continued` per resume: a chain's are its own business. The caller + // was told the program resumed when the step was answered. + return event.event === 'continued' && chain !== null; + } + + /** For the log and the tests. */ + describe(): { enabled: boolean; chain: boolean; owed: number; paused: boolean } { + return { enabled: this.enabled, chain: this.chain !== null, owed: this.owed, paused: this.current !== null }; + } + + // ----- CDP events ----- + + private handleCdpEvent(method: string, params: unknown): void { + if (method === 'Debugger.paused') { + const pause = params as CdpPaused; + this.current = pause; + const chain = this.chain; + if (chain) { + logger.debug(`[JsStepper] CDP Debugger.paused during a step ${chain.kind}: ${describePause(pause)}`); + chain.inbox.push({ type: 'paused', pause }); + chain.wake?.(); + } + } else if (method === 'Debugger.resumed') { + this.current = null; + const chain = this.chain; + if (chain) { + logger.debug(`[JsStepper] CDP Debugger.resumed during a step ${chain.kind}`); + chain.inbox.push({ type: 'resumed' }); + chain.wake?.(); + } + } + } + + // ----- the chain ----- + + private async run(chain: Chain): Promise { + try { + for (;;) { + const pause = await this.nextPause(chain); + if (!pause) { + await this.finish(chain, 'cancelled'); + return; + } + const verdict = await this.judge(chain, pause); + if (verdict.kind === 'wait') { + continue; + } + if (verdict.kind === 'command') { + if (chain.commands.length >= this.tunables.commandCap) { + // Still in skipped code after every command the chain may send: + // stop here and say so rather than run on. + chain.capped = true; + await this.finish(chain, 'landing', 'the command cap, still in skipped code'); + return; + } + if (chain.cancelled) { + // Given up while the landing was being judged: nothing more is sent. + await this.finish(chain, 'cancelled'); + return; + } + if (chain.pauseRequested) { + // The caller asked for a pause while this landing was being + // judged: V8 is paused, and this stop is theirs. + chain.pauseTaken = true; + await this.finish(chain, 'real-stop'); + return; + } + if (verdict.record === 'started') { + this.recordWalkStarted(chain); + } else if (verdict.record === 'ended') { + this.recordWalkEnded(chain, verdict.why); + } + await this.sendStep(chain, verdict.command); + continue; + } + if (verdict.kind === 'left-stack' && chain.cancelled) { + // Given up while what the stack returns to was being asked: the + // request that gave it up is the caller's, and the chain neither + // resumes the program nor records anything (review 8). + await this.finish(chain, 'cancelled'); + return; + } + if (verdict.kind === 'left-stack' && chain.pauseRequested) { + // The stack is gone, but the caller asked for a pause while that + // was being found out: V8 is paused, and the stop is theirs. + chain.pauseTaken = true; + await this.finish(chain, 'real-stop'); + return; + } + await this.finish(chain, verdict.kind, verdict.kind === 'landing' ? verdict.by : undefined); + return; + } + } catch (err) { + logger.warn(`[JsStepper] chain failed: ${errorText(err)}`); + // If V8 is paused, the caller must hear of the stop it can see: where + // the step is now, as the step it is. + const paused = this.current !== null && !chain.cancelled; + await this.finish(chain, paused ? 'landing' : 'error', paused ? 'where it was when the chain failed' : undefined).catch( + (failure) => logger.warn(`[JsStepper] could not end a failed chain: ${errorText(failure)}`) + ); + } + } + + private async sendStep(chain: Chain, command: string): Promise { + const cdp = this.cdp; + if (!cdp) { + throw new Error('the CDP connection closed'); + } + chain.commands.push(command); + await cdp.send(command, command === CDP_COMMAND.in ? { breakOnAsyncCall: false } : {}); + } + + private waitForInbox(chain: Chain): Promise { + return new Promise((resolve) => { + chain.wake = () => { + chain.wake = null; + resolve(); + }; + }); + } + + /** The next CDP pause of the chain, or null when the chain was given up. */ + private async nextPause(chain: Chain): Promise { + for (;;) { + if (chain.cancelled) { + return null; + } + const next = chain.inbox.shift(); + if (next?.type === 'paused') { + return next.pause; + } + if (!next) { + await this.waitForInbox(chain); + } + } + } + + private async judge(chain: Chain, pause: CdpPaused): Promise { + // Every breakpoint V8 reports is js-debug's: the stepper sets none. + const foreignHit = (pause.hitBreakpoints ?? []).length > 0; + const ours = !chain.pauseRequested && !foreignHit && STEP_REASONS.has(pause.reason); + + if (!ours) { + // Another breakpoint, an exception, a pause the caller asked for: + // js-debug decides. Resumed by js-debug, or the chain given up, the run + // loop goes back to waiting. + const decided = await this.jsDebugDecides(chain); + logger.debug(`[JsStepper] a pause not the step's own (${describePause(pause)}): ${decided}`); + if (decided === 'resumed' && chain.walkRecorded) { + // js-debug resumed a pause of its own during the walk: whether V8 + // still carries the step is not known (issue #1162 is one it lost), + // so the record of a walk in progress is withdrawn. A landing of the + // step's own in skipped code later records it again. + this.recordWalkEnded(chain, 'resumed'); + } + if (decided !== 'kept') { + return { kind: 'wait' }; + } + chain.kept++; + chain.pauseTaken = chain.pauseRequested && !foreignHit; + return { kind: 'real-stop' }; + } + chain.kept++; + + const skipped = await this.isSkipped(chain, pause); + if (chain.cancelled) { + // Given up while js-debug was being asked: nothing more is sent. + return { kind: 'wait' }; + } + + if (skipped) { + // A step-in walks on until it has taken its limit of engine steps in + // skipped code, with or without anything below: a step issued inside a + // dependency reaches the program's handler by calls, not returns (issue + // #687). Steps only, never time: how long the skipped code runs, or + // what an engine step costs over the inspector link, does not move + // where the step lands. A walk that outlasts the step's grace window + // answers `pending` and says it is walking (the record). + let endingWalk = false; + if (chain.kind === 'in' && !chain.walkEnded) { + if (chain.spent < this.tunables.walkBudgetSteps) { + chain.spent++; + return chain.walkRecorded + ? { kind: 'command', command: CDP_COMMAND.in } + : { kind: 'command', command: CDP_COMMAND.in, record: 'started' }; + } + chain.walkEnded = true; + endingWalk = true; + } + // It has to step out now. With nothing of the program below (no frame, + // no awaiter), the stack the step started on is gone. + if ((await this.returnTarget(chain, pause)).kind === 'nothing') { + return { kind: 'left-stack' }; + } + return endingWalk && chain.walkRecorded + ? { kind: 'command', command: CDP_COMMAND.out, record: 'ended', why: 'limit' } + : { kind: 'command', command: CDP_COMMAND.out }; + } + + // Program code on top: V8's step landed. On the line the step started + // from too: a new position there (after a step-out, the caller's next + // break position on the line; in a one-line loop, the header's next + // position, as the traces show), where the program's code next runs. + return { kind: 'landing', by: 'V8 step' }; + } + + /** + * A pause that is not the stepper's: either js-debug resumes it itself (a + * `resumed` the stepper did not send), or it keeps it and sends one more + * `stopped` than the chain's kept pauses account for. The `stopped` comes + * on js-debug's DAP connection and the `resumed` on the CDP socket, and a + * `stopped` for a LATER pause can arrive before the CDP `resumed` of this + * one (measured under Node 22 on Linux: two pauses js-debug takes and + * resumes itself, then the step's landing, whose `stopped` overtook both + * CDP events). So a `stopped` is read as "kept" only after the CDP stream + * has caught up with it: see `catchUp`. + */ + private async jsDebugDecides(chain: Chain): Promise<'kept' | 'resumed' | 'cancelled'> { + /** The `stopped` count the CDP stream last caught up with. */ + let caughtUpWith = -1; + for (;;) { + if (chain.cancelled) { + return 'cancelled'; + } + const next = chain.inbox[0]; + if (next?.type === 'resumed') { + // The stepper has sent nothing since this pause: js-debug resumed it. + chain.inbox.shift(); + return 'resumed'; + } + if (next?.type === 'paused') { + // A newer pause already: the one being judged was resumed. + return 'resumed'; + } + if (chain.stoppedSeen > chain.kept) { + if (caughtUpWith === chain.stoppedSeen) { + // The stream has caught up and says nothing newer: js-debug kept it. + return 'kept'; + } + caughtUpWith = chain.stoppedSeen; + await this.catchUp(chain); + continue; + } + await this.waitForInbox(chain); + } + } + + /** + * Make the CDP stream catch up with js-debug's DAP events: one request V8 + * answers, sent over js-debug's CDP proxy, the socket the forwarded events + * travel on. That socket is ordered, so every CDP event js-debug forwarded + * before the answer is in the inbox when the answer comes. A failure costs + * only the catch-up: the inbox is read as it stands. + */ + private async catchUp(chain: Chain): Promise { + const before = this.describeInbox(chain); + const started = Date.now(); + let answer: string; + try { + const cdp = this.cdp; + if (!cdp) { + throw new Error('the CDP connection closed'); + } + const result = await cdp.send<{ id?: string }>(CATCH_UP_METHOD, {}); + answer = `isolate ${result?.id ?? '?'}`; + } catch (err) { + answer = `failed: ${errorText(err)}`; + logger.warn(`[JsStepper] the CDP stream could not catch up (${errorText(err)}); the inbox is read as it stands`); + } + logger.debug( + `[JsStepper] CDP stream catch-up (${CATCH_UP_METHOD}, ${answer}) in ${Date.now() - started} ms for ` + + `${chain.stoppedSeen} stopped seen, ${chain.kept} pauses kept: inbox before [${before}], after [${this.describeInbox(chain)}]` + ); + } + + /** The chain's unread CDP events, for the log. */ + private describeInbox(chain: Chain): string { + return chain.inbox.map((item) => (item.type === 'paused' ? `paused(${item.pause.reason})` : 'resumed')).join(', '); + } + + /** The walk is going: the parent process's pending answer may say so (round 3, decision 2). */ + private recordWalkStarted(chain: Chain): void { + chain.walkRecorded = true; + this.deliver({ + seq: 0, + type: 'event', + event: PROXY_STEP_WALK_STARTED_EVENT, + body: { threadId: chain.threadId ?? 0, stepLimit: this.tunables.walkBudgetSteps } + }); + } + + /** The walk is no longer known to be going: the record of it is withdrawn. */ + private recordWalkEnded(chain: Chain, why: 'limit' | 'resumed' | 'failed'): void { + chain.walkRecorded = false; + this.deliver({ seq: 0, type: 'event', event: PROXY_STEP_WALK_ENDED_EVENT, body: { threadId: chain.threadId ?? 0, why } }); + } + + /** js-debug's mark on frame 0 of the current pause. */ + private async isSkipped(chain: Chain, pause: CdpPaused): Promise { + const top = pause.callFrames[0]; + if (!top) { + return false; + } + const scriptId = top.location.scriptId; + const plainLanding = pause.reason === 'step' && (pause.hitBreakpoints ?? []).length === 0; + if (plainLanding && this.skippedScripts.has(scriptId)) { + return true; + } + const marks = await this.marks(chain, 1); + if (typeof marks === 'string') { + logger.warn(`[JsStepper] no verdict for a landing (${marks}); treating it as program code`); + return false; + } + const skipped = markOf(marks[0]) === 'deemphasize'; + // Remembered only for a module of Node's own, by js-debug's own name for + // its source: one script, one source, no source map (C1). + if (skipped && /skipFiles/i.test(marks[0].source?.origin ?? '') && (marks[0].source?.path ?? '').startsWith('')) { + this.skippedScripts.add(scriptId); + } + return skipped; + } + + /** + * js-debug's frames for the pause V8 is in, with its marks; or, as a + * string, why there are none. js-debug answers "not paused" until it has + * taken the pause in, so the question is asked again until the ceiling. + */ + private async marks(chain: Chain, levels: number): Promise { + const deadline = Date.now() + this.tunables.verdictCeilingMs; + for (;;) { + let failure: string; + try { + const answer = await this.target.sendRequest( + 'stackTrace', + { threadId: chain.threadId ?? 0, startFrame: 0, levels }, + 5000 + ); + const frames = answer?.body?.stackFrames; + if (answer?.success !== false && frames && frames.length > 0) { + return frames; + } + failure = answer?.message ?? 'no frame'; + } catch (err) { + failure = errorText(err); + } + if (chain.cancelled || Date.now() >= deadline) { + return failure; + } + await this.sleep(1); + } + } + + private async finish(chain: Chain, ended: 'landing' | 'real-stop' | 'left-stack' | 'cancelled' | 'error', why?: string): Promise { + let ender = ended; + let by = why; + // Where the step is, for what its answer may say about it. + const landed = this.current; + const backInOriginFrame = landed !== null && landed.callFrames.length === chain.originDepth && + fnKey(landed.callFrames[0]) === chain.originFn; + if (ender === 'left-stack') { + // Nothing of the program is below: resume, and report nothing. From + // here on, what the resumed program stops at is not the chain's. + chain.leaving = true; + try { + chain.commands.push('Debugger.resume'); + await this.cdp?.send('Debugger.resume', {}); + } catch (err) { + logger.warn(`[JsStepper] resume after leaving the stack failed: ${errorText(err)}`); + if (!chain.cancelled && this.current !== null && this.current === landed) { + // V8 is still paused where the chain left it: the caller hears of + // the stop it can see. (Paused anywhere else, V8 took the resume + // and the answer was lost: the stop it is in now is the program's + // next, held above or still to come, review 10.) + ender = 'landing'; + by = 'where it was: V8 refused the resume'; + } + } + } + const reports = ender === 'landing' || ender === 'real-stop'; + if (reports) { + // One `stopped` per kept pause; the last is this chain's. + const deadline = Date.now() + this.tunables.settleCeilingMs; + while (chain.stoppedSeen < chain.kept && !chain.cancelled && Date.now() < deadline) { + await Promise.race([this.waitForInbox(chain), this.sleep(5)]); + } + } + if (this.chain === chain) { + this.chain = null; + this.accountOwed(chain); + } + if (ender === 'left-stack' && !chain.cancelled) { + // The program runs on and the step will not land: no stop to report. + // The record goes to the parent process, whose pending answer may then + // say the step left its frame (I3). A chain given up while its resume + // was being answered records nothing: the request that gave it up is + // the caller's (as in review 8's case, before the resume). + this.deliver({ seq: 0, type: 'event', event: PROXY_STEP_LEFT_STACK_EVENT, body: { threadId: chain.threadId ?? 0 } }); + } else if (ender === 'error' && chain.walkRecorded) { + // The chain failed with V8 running: nothing walks any more. + this.recordWalkEnded(chain, 'failed'); + } + const count = (name: string): number => chain.commands.filter((c) => c === name).length; + logger.info( + `[JsStepper] step ${chain.kind} ended: ${ender}${by ? ` (${by})` : ''}${chain.cancelled ? ` [${chain.cancelled}]` : ''}; ` + + `${count(CDP_COMMAND.in)} in, ${count(CDP_COMMAND.over)} over, ${count(CDP_COMMAND.out)} out; ` + + `${chain.kept} pauses kept, ${chain.stoppedSeen} stopped seen; ${Date.now() - chain.startedAt} ms` + ); + if (!chain.cancelled) { + if (ender === 'landing') { + const body = { ...((chain.lastStopped?.body ?? {}) as Record) }; + delete body.hitBreakpointIds; + delete body.text; + this.deliver({ + seq: 0, + type: 'event', + event: 'stopped', + body: { + allThreadsStopped: false, + ...body, + threadId: (body.threadId as number | undefined) ?? chain.threadId ?? 0, + reason: 'step', + description: 'Paused', + ...this.landingNote(chain, backInOriginFrame) + } + }); + } else if (ender === 'real-stop' && chain.pauseTaken) { + // The pause the caller asked for. js-debug may report it under another + // reason, or may not have reported it yet: it leaves as the pause it is. + const body = { ...((chain.lastStopped?.body ?? {}) as Record) }; + delete body.hitBreakpointIds; + delete body.text; + this.deliver({ + seq: 0, + type: 'event', + event: 'stopped', + body: { + allThreadsStopped: false, + ...body, + threadId: (body.threadId as number | undefined) ?? chain.threadId ?? 0, + reason: 'pause', + description: 'Paused' + } + }); + } else if (ender === 'real-stop' && chain.lastStopped) { + this.deliver(chain.lastStopped); + } + } + // The program's own next stops, reached after the chain's resume: never + // lost, and after the chain's record; stale, and dropped, once the chain + // was given up (a continue or a new step has moved V8 on). + const after = chain.afterLeaving.splice(0); + if (chain.cancelled) { + if (after.length > 0) { + logger.debug(`[JsStepper] ${after.length} event(s) after the step's resume dropped: the step was given up (${chain.cancelled})`); + } + } else { + for (const next of after) { + this.deliver(next); + } + } + } + + /** + * What a landing says beyond where it is. Only what is known: the sentence + * on a step-in that reached nothing of the program's is for one that came + * back to the frame it left, not one that went on into program code. + */ + private landingNote(chain: Chain, backInOriginFrame: boolean): { text?: string } { + if (chain.capped) { + return { text: ErrorMessages.stepStillInSkippedCode(chain.commands.length) }; + } + if (chain.walkEnded && backInOriginFrame) { + return { text: ErrorMessages.stepIntoReachedNoProgramCode(this.tunables.walkBudgetSteps) }; + } + return {}; + } + + /** + * Whether a `stopped` that arrives after a chain ended can be the late + * report of one of that chain's own pauses: js-debug reports a step it did + * not request as `pause` (or `step`). Anything else is somebody else's + * stop and goes on. + */ + private looksOwed(event: DebugProtocol.Event): boolean { + const body = (event.body ?? {}) as { reason?: string }; + return body.reason === 'pause' || body.reason === 'step'; + } + + /** Move any uncollected `stopped` events of `chain` into `this.owed`, at most once. */ + private accountOwed(chain: Chain): void { + if (chain.owedAccounted) { + return; + } + chain.owedAccounted = true; + if (Date.now() > this.owedUntil) { + this.owed = 0; + } + const missing = Math.max(0, chain.kept - chain.stoppedSeen); + if (missing > 0) { + this.owed += missing; + this.owedUntil = Date.now() + this.tunables.settleCeilingMs; + } + } + + private async abandonChain(why: string): Promise { + const chain = this.chain; + if (!chain) { + return; + } + chain.cancelled = why; + chain.wake?.(); + // The run loop ends the chain; the caller goes on without waiting for it. + if (this.chain === chain) { + this.chain = null; + this.accountOwed(chain); + } + } + + /** What the top frame of `pause` returns to; js-debug is asked once per pause. Never throws. */ + private async returnTarget(chain: Chain, pause: CdpPaused): Promise { + const known = this.targets.get(pause); + if (known) { + return known; + } + let target: ReturnTarget = { kind: 'unknown' }; + try { + target = await this.findReturnTarget(chain, pause); + } catch (err) { + logger.warn(`[JsStepper] could not tell what the stack returns to: ${errorText(err)}`); + } + this.targets.set(pause, target); + return target; + } + + /** + * The nearest frame of the program below the top one, by js-debug's marks. + * With none on the stack, the function awaiting an async one the event + * loop resumed: the first frame of V8's async stack, when every link down + * to it is an `await` (a `Promise.then` or timer link only scheduled the + * code on top) and js-debug marks it program code. An awaiter only says + * the stack is not gone; V8's own step leads to it. + */ + private async findReturnTarget(chain: Chain, pause: CdpPaused): Promise { + const frames = pause.callFrames; + const asked = Math.min(frames.length + ASYNC_MARKS, MAX_MARKED_FRAMES); + const marks = await this.marks(chain, asked); + if (typeof marks === 'string') { + logger.warn(`[JsStepper] could not read the stack's marks (${marks})`); + return { kind: 'unknown' }; + } + // js-debug lists the sync frames, then a label frame per async segment and that segment's frames. + const firstLabel = marks.findIndex((frame) => markOf(frame) === 'label'); + const sync = firstLabel === -1 ? marks : marks.slice(0, firstLabel); + for (let i = 1; i < Math.min(sync.length, frames.length); i++) { + if (markOf(sync[i]) !== 'deemphasize') { + return { kind: 'frame', index: i }; + } + } + if (firstLabel === -1) { + // No async part was listed: the stack ends here, unless it is deeper than was asked about. + return marks.length >= asked ? { kind: 'unknown' } : { kind: 'nothing' }; + } + let link = pause.asyncStackTrace; + while (link && link.description === 'await' && !link.callFrames?.length) { + link = link.parent; + } + const parent = link?.description === 'await' ? link.callFrames?.[0] : undefined; + if (!parent) { + return { kind: 'nothing' }; + } + const awaiter = marks.slice(firstLabel).find((frame) => markOf(frame) !== 'label'); + if (!awaiter) { + return { kind: 'unknown' }; + } + return markOf(awaiter) === 'deemphasize' ? { kind: 'nothing' } : { kind: 'awaiter', parent }; + } +} diff --git a/src/proxy/minimal-dap.ts b/src/proxy/minimal-dap.ts index 6d278f0d..e8d80106 100644 --- a/src/proxy/minimal-dap.ts +++ b/src/proxy/minimal-dap.ts @@ -209,6 +209,16 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { return this.childSessionManager?.flushEvents(); } + /** + * Whether this session steps through skipped code, as its start request + * said (a launch's or an attach's `smartStep`, issue #1130). A forked + * child's stepper takes the root's choice over. Undefined when this client + * has no proxy stepper to ask: the caller falls back to what it knows. + */ + stepsThroughSkippedCode(): boolean | undefined { + return this.childSessionManager?.isSteppingThroughSkippedCode(); + } + /** * Handle raw data using the same algorithm as vscode's ProtocolServer * (extracted to DapFrameDecoder). This ensures compatibility and proper @@ -554,6 +564,21 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { // only carries {type, name, __pendingTargetId} — request mode and // stopOnEntry never round-trip through the adapter (issue #124). if (command === 'attach' || command === 'launch') { + // The start request's `smartStep` is the session's choice, not the + // adapter's setting (issue #1130): the proxy's stepper steps through + // skipped code, and the adapter's own stepper stays off whatever was + // asked, because it loses steps and re-steps a statement at a time. + // Before the snapshot below: an attach's child session sends these + // arguments again, and they must not turn that stepper back on. Applied + // on non-root child connections too (forked children run a child-safe + // policy with no ChildSessionManager, and an attach root's config still + // carries `smartStep: true`). + if (this.dapBehavior.stepsThroughSkippedCode && args !== null && typeof args === 'object') { + const start = args as Record; + this.childSessionManager?.setStepThroughSkippedCode(start.smartStep === true); + args = { ...start, smartStep: false }; + } + const { request: _request, stopOnEntry, ...attachArguments } = (args as Record | undefined) ?? {}; void _request; @@ -683,6 +708,14 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { if (this.activeChild) { try { + // A step of a session that steps through skipped code is the proxy + // stepper's (issue #1130); any other request may end a step in flight. + const stepped = manager?.stepRequest(command, args); + if (stepped) { + logger.info(`[MinimalDapClient] '${command}' served by the proxy stepper`); + return (await stepped) as T; + } + await manager?.beforeChildRequest(command); logger.info(`[MinimalDapClient] Dispatching '${command}' to child session`); return await this.activeChild.sendRequest(command, args as unknown, timeoutMs); } catch (err) { diff --git a/src/server/tool-schemas.ts b/src/server/tool-schemas.ts index d0e889ea..0229970e 100644 --- a/src/server/tool-schemas.ts +++ b/src/server/tool-schemas.ts @@ -159,7 +159,7 @@ export function buildToolDefinitions(options: BuildToolDefinitionsOptions): Tool description: 'DAP launch arguments. Beyond the three below, adapter keys pass through (program, cwd, env, …). Python: module runs `python -m ` instead of scriptPath (the pytest shape: module "pytest", args [::, "-x"]) and code runs a code string; scriptPath then only names the file the launch is about, and cwd — which `python -m` puts on sys.path — defaults to the directory above the top-most package containing scriptPath', properties: { stopOnEntry: { type: 'boolean', description: 'Pause at the first line before running. Default false — the opposite of attach, which pauses unless stopOnEntry is false' }, - justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug\'s smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies' }, + justMyCode: { type: 'boolean', description: 'Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way' }, noDebug: { type: 'boolean', description: 'DAP\'s launch-without-debugging flag (default false). Where the adapter honours it (js-debug, debugpy, Delve, CodeLLDB and the Dart SDK adapters) no breakpoint binds, no exception filter arms, no entry stop lands and no breakpoint, exception or entry stop ever arrives (a pause may still land where the runtime allows one) — the response warns when breakpoints, an explicit breakOnExceptions or stopOnEntry are set alongside it, and while the launch runs the session reports debuggerDisabled and every later surface says the debugger is off. rdbg, netcoredbg and the Java bridge ignore the flag, and the rust launch never forwards it: their debugger stays on and the response says so' } }, additionalProperties: true diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 6facdd20..548d4efa 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -53,6 +53,11 @@ import { import { DebugProtocol } from '@vscode/debugprotocol'; import { ProxyNotRunningError, SessionTerminatedError } from '../../errors/debug-errors.js'; import { ErrorMessages } from '../../utils/error-messages.js'; +import { + PROXY_STEP_LEFT_STACK_EVENT, + PROXY_STEP_RECORD_EVENTS, + PROXY_STEP_WALK_STARTED_EVENT +} from '../../proxy/dap-proxy-interfaces.js'; import type { ManagedSession } from '../session-store.js'; import type { DebugResult, @@ -123,11 +128,15 @@ export interface StepOperationOptions { exitedMessage?: string; /** * The adapter policy's explanation for a step that may never land (issue - * #678), appended to the grace-window message. Computed by the step preamble - * before the request is sent, because it depends on the frame the step was - * issued from. + * #678), appended to the grace-window message. Built by the step preamble + * over the frame the step was issued from, and asked when the window + * elapses, with the latest record the proxy's stepper sent of this step + * (issue #1130): its walk through skipped code started or ended, or it + * ended the step by resuming the program. When that record is the walk's + * start or the left stack, the explanation follows + * `ErrorMessages.stepNotLanded` instead of the generic lead. */ - pendingHint?: string; + describePending?: (record: StepperRecord | undefined) => string | undefined; /** * Where the step was issued from (issue #678), when the preamble read it — * only for policies with `describePendingStop`, which need the frame anyway. @@ -144,6 +153,12 @@ export interface StepOperationOptions { onLanding?: (landing: StopLanding) => void; } +/** One record of the proxy's JavaScript stepper (issue #1130): the event's name and body. */ +export interface StepperRecord { + event: string; + body: unknown; +} + /** * The most DAP steps one step_over sends for an adapter that stops once per * token position (issue #879). The longest measured line took three. @@ -234,7 +249,8 @@ export class ExecutionController { kind === 'stepOver' && this.ctx.selectPolicy(session.language).stepsByTokenPosition === true; const origin = await this.readStepOrigin(session, sessionId, threadId, repeatsOnSameLine); const fromFrame = origin?.frame; - const pendingHint = await this.describePendingStop(session, sessionId, 'step', fromFrame); + const describePending = (record: StepperRecord | undefined): string | undefined => + this.describePendingStop(session, sessionId, 'step', fromFrame, record); // Re-check after the awaits — the origin read is a real DAP round trip // — in the order and spirit of pause()'s re-check (#574): a @@ -264,7 +280,7 @@ export class ExecutionController { threadId, logTag, successMessage, - ...(pendingHint ? { pendingHint } : {}), + describePending, ...(fromFrame ? { origin: { file: fromFrame.file, line: fromFrame.line, column: fromFrame.column } } : {}), onLanding: (landing) => { finalLanding = landing; }, }; @@ -327,6 +343,18 @@ export class ExecutionController { // it or something else did (issue #678) — the same discipline pause uses. const lastStopBefore = session.lastStop; + // The latest record the proxy's JavaScript stepper sent of this step + // (issue #1130): its walk through skipped code started, or ended without + // a landing, or it ended the step by resuming the program. The pending + // answer says what the latest one means. Only records that arrive while + // this step waits. + let latestRecord: StepperRecord | undefined; + const onDapEvent = (event: string, body: unknown): void => { + if (PROXY_STEP_RECORD_EVENTS.includes(event)) { + latestRecord = { event, body }; + } + }; + return new Promise((resolve) => { let settled = false; // Rule 1's flag: "a stop has been observed, the stop path owns the @@ -339,6 +367,7 @@ export class ExecutionController { proxyManager.off('terminated', onTerminated); proxyManager.off('exited', onExited); proxyManager.off('exit', onExit); + proxyManager.off('dap-event', onDapEvent); clearTimeout(timeout); }; @@ -396,7 +425,11 @@ export class ExecutionController { success(message, landing, stop); return; } - success(options.successMessage, landing); + // What the step itself has to say about how it landed (the JavaScript + // stepper: how far a step-in walked without reaching the program's + // code, or that every command it may send was spent there; issue #1130). + const stepNote = ownStop?.reason === 'step' ? ownStop.text : undefined; + success(stepNote ? `${options.successMessage}. ${stepNote}` : options.successMessage, landing); }; const onTerminated = () => success(terminatedMessage); @@ -421,12 +454,22 @@ export class ExecutionController { this.ctx.logger.info( `[SM ${options.logTag} ${sessionId}] Step still running after ${this.ctx.tunables.stepGraceMs}ms grace window; completing asynchronously` ); - const stillRunning = ErrorMessages.stepStillRunning(this.ctx.tunables.stepGraceMs / 1000); + const graceSeconds = this.ctx.tunables.stepGraceMs / 1000; + const pendingHint = options.describePending?.(latestRecord); + // A step the stepper has a record of, worded by the policy, is known + // not to be "stepping over a long-running call" (issue #1130's + // complaint), and nothing promises it will pause: the lead says only + // that it has not landed. Any other step keeps the generic lead: no + // record, a walk that ended, or a record the policy says nothing of. + const recorded = pendingHint !== undefined && ( + latestRecord?.event === PROXY_STEP_WALK_STARTED_EVENT || latestRecord?.event === PROXY_STEP_LEFT_STACK_EVENT + ); + const lead = recorded ? ErrorMessages.stepNotLanded(graceSeconds) : ErrorMessages.stepStillRunning(graceSeconds); settle({ success: true, state: session.state, data: { - message: options.pendingHint ? `${stillRunning} ${options.pendingHint}` : stillRunning, + message: pendingHint ? `${lead} ${pendingHint}` : lead, pending: true, }, }); @@ -436,6 +479,7 @@ export class ExecutionController { proxyManager.on('terminated', onTerminated); proxyManager.on('exited', onExited); proxyManager.on('exit', onExit); + proxyManager.on('dap-event', onDapEvent); this.ctx.updateState(session, SessionState.RUNNING); @@ -692,7 +736,7 @@ export class ExecutionController { this.ctx.logger.info( `[SessionManager pause] No stopped event within ${this.ctx.tunables.pauseGraceMs}ms grace window in session ${sessionId}; completing asynchronously` ); - const hint = await this.describePendingStop(session, sessionId, 'pause'); + const hint = this.describePendingStop(session, sessionId, 'pause'); // With the debugger off for this launch the why is known (issue #749): // one message that promises no stop, with the policy's own explanation // kept — on js-debug a pause can land under the flag, and #678's @@ -1086,12 +1130,13 @@ export class ExecutionController { * (issue #678), or undefined when it has none. A throwing hook only costs * the explanation. */ - private async describePendingStop( + private describePendingStop( session: ManagedSession, sessionId: string, operation: 'pause' | 'step', - fromFrame?: StackFrame - ): Promise { + fromFrame?: StackFrame, + record?: StepperRecord + ): string | undefined { const policy = this.ctx.selectPolicy(session.language); if (!policy.describePendingStop) { return undefined; @@ -1106,11 +1151,18 @@ export class ExecutionController { adapterLaunchConfig: session.lastLaunch.adapterLaunchConfig } : undefined; + // What the latest record says, and only that one: a walk that ended + // is not walking, and a walk followed by a resume left the stack. + const stepLimit = (record?.body as { stepLimit?: unknown } | undefined)?.stepLimit; return policy.describePendingStop({ operation, attachMode: session.attachMode === true, launch, - ...(fromFrame ? { fromFrame } : {}) + ...(fromFrame ? { fromFrame } : {}), + ...(record?.event === PROXY_STEP_LEFT_STACK_EVENT ? { stepLeftStack: true } : {}), + ...(record?.event === PROXY_STEP_WALK_STARTED_EVENT + ? { stepWalking: typeof stepLimit === 'number' ? { stepLimit } : {} } + : {}) }) || undefined; } catch (error) { this.ctx.logger.debug(`[SM ${operation} ${sessionId}] Pending-stop explanation failed:`, error); diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 5397eae8..ef1bde67 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -267,6 +267,27 @@ export const ErrorMessages = { `remains 'running' and will become 'paused' when it completes. Call wait_for_stop to ` + `block until then, or pause_execution to interrupt.`, + /** + * The lead of a pending step's answer when the proxy's JavaScript stepper has a record of the step (issue #1130) + * Occurs when: the grace window ends and the latest record the stepper sent + * of this step says what it is doing (walking through skipped code) or how + * it ended (the program was resumed), and the adapter policy words that + * record. Such a step is known not to be "stepping over a long-running + * call", and nothing promises it will pause, so this lead says only what the + * server knows: the step has not landed, the session is running, and how to + * wait for it or interrupt it (measured: pause_execution during a walk that + * is taking engine steps is answered as the caller's pause; while the + * program is blocked in native code or idle under a pending step_into, it + * stops inside the server's own wake evaluation instead, issue #1208). The + * policy's sentence follows it. A step with no record keeps + * `stepStillRunning`. + * Used in: src/session/execution/execution-controller.ts + * @param graceSeconds - The grace window duration in seconds + */ + stepNotLanded: (graceSeconds: number) => + `Step dispatched; it has not landed after ${graceSeconds}s. The session is 'running': ` + + 'wait_for_stop blocks until the program next stops or ends, and pause_execution interrupts it.', + /** * A step whose recorded stop is a breakpoint or an exception rather than * the step (issue #678). Neutral by design: js-debug and debugpy both report @@ -305,6 +326,43 @@ export const ErrorMessages = { 'step_over again to go on, or set a breakpoint on the next line.' : `${stepped} in ${steps} steps: this adapter stops once per expression on a line, so the step was repeated until the line changed.`, + /** + * The sentence on a step_into that reached no code of the program (issue #1130) + * Occurs when: the proxy's JavaScript stepper walked into the call on the + * line, was still in skipped code when the walk reached its limit of + * engine steps taken in skipped code (the walk's only bound: where a step + * lands is the program's to decide, never the clock's), stepped out and + * landed in the frame the step started in: usually where the call + * returned to (on the same line, when the line goes on), further down when + * V8 lost the step out (a `require` line, issue #1161). It says what is + * known: the walk took all of its engine steps. Not that the call reaches + * nothing of the program's: code the call runs further in, or only + * schedules, ran during the step out. The remedy is worded for a launch + * and an attach alike. + * Used in: src/proxy/js-stepper.ts (the `text` of the step's stopped + * event), appended to the step's message by + * src/session/execution/execution-controller.ts + * @param limit - The engine steps a walk may take in skipped code, all of which this one took + */ + stepIntoReachedNoProgramCode: (limit: number) => + `step_into walked ${limit} engine steps into the call, its limit, and was still in skipped code ` + + '(Node internals, node_modules, or files on skipFiles), so it stepped out. Code of yours that the ' + + 'call runs further in, or only schedules (a timer or promise callback), did not stop the step: a breakpoint ' + + 'there stops in it. To stop inside the skipped code instead, turn ' + + 'stepping through it off: justMyCode: false on a launch, smartStep: false on a launch or an attach.', + + /** + * The sentence on a step that is still in skipped code after every engine + * step its chain may take (issue #1130) + * Occurs when: the proxy's JavaScript stepper reached its command cap. + * It stops where it is rather than run on. + * Used in: src/proxy/js-stepper.ts + * @param commands - How many engine steps the chain took + */ + stepStillInSkippedCode: (commands: number) => + `The step is still in skipped code after ${commands} engine steps, so it stopped here rather than run on. ` + + 'step_out or continue_execution goes on; a breakpoint in your own code is the reliable way back.', + /** * Informational message for pause requests not yet honored within the grace window * Occurs when: A pause request is acknowledged but no 'stopped' event arrives within the grace diff --git a/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts new file mode 100644 index 00000000..ac363168 --- /dev/null +++ b/tests/adapters/javascript/integration/javascript-step-skipped-code.test.ts @@ -0,0 +1,598 @@ +/** + * The server's own JavaScript stepper, through a real server, the real + * js-debug and a real Node (issues #1130, #1161). + * + * js-debug's smart stepper is off for every session; the server decides + * where a step ends. What that has to hold, as measured: + * + * - a step_into on a line that calls only Node's own code lands on the + * next line. Where it lands is the program's to decide, not the host's: + * the walk is bounded by engine steps only, so where an engine step is + * slow (about 44 ms on Linux, issue #1163) the step first answers + * `pending`, saying it is walking through skipped code, and lands in the + * same place; these tests accept either and assert the line strictly. + * js-debug's stepper lost that step on the first console.log of a + * process (the session ended), and took about 6 s on a Linux host for a + * later one; + * - a call through Node's code into a callback of the program's is + * followed (an on() or once() listener); a call that only starts a later + * task is not; + * - a pause in the program's code is the landing, on the line the step + * started from too: a one-line loop stops at its header's next position; + * - in a bundle, js-debug's verdict is asked at each landing: a stop in a + * bundled dependency does not make the program's lines of the same + * script count as skipped; + * - a step that leaves a function through `return` inside try...finally + * is the engine's own. V8 loses it (issues #1161, #1174; Node 22, 24 + * and 26), sync and async, and the server does not rescue it. V8 16.0 + * has the fix (#1173); no Node release has it yet. Those tests accept + * both a runtime that loses the step and one that lands it in the + * caller (with the fix, a step_over off the finally block first stops + * once more at the end of the return, in the same call), and fail on a + * stop anywhere else (another call of the same function). Every one of + * them is lost on main too (measured: 3 of 3 runs each); every step + * main lands is asserted strictly; + * - a breakpoint reached during a step stops as itself; + * - a step off the last line of a callback Node called has no frame of the + * program to return to: the program is resumed, not walked through the + * internals of later tasks; + * - `justMyCode: false` keeps plain steps: the session chose to see + * everything. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; +import { ErrorMessages } from '../../../../src/utils/error-messages.js'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.resolve(here, '../../../fixtures/javascript/step-skipped-code/steps.cjs'); +const LINES = fs.readFileSync(FIXTURE, 'utf8').split('\n'); + +/** The 1-based line that carries `// MARK: `. */ +function lineOf(marker: string): number { + const index = LINES.findIndex((line) => line.includes(`// MARK: ${marker}`)); + if (index === -1) { + throw new Error(`no line marked "${marker}" in the fixture`); + } + return index + 1; +} + +type StopAnswer = ToolAnswer & { + pending?: boolean; + stopReason?: string; + location?: { file: string; line: number }; + snapshot?: { + frames?: Array<{ name: string; line: number }>; + changedVariables?: Record; + locals?: Record; + }; + /** wait_for_stop's record of the stop. */ + lastStop?: { reason?: string }; +}; + +/** + * Inside the 5 s window after which a step answers `pending` (the step + * grace window), with room for the answer's own stack reads: a step that + * answers under this bound landed by itself. + */ +const PROMPT_MS = 4500; + +/** + * The sentence a step_into carries when its walk through skipped code took + * all of its 512 engine steps and it stepped out. The walk's only bound: + * where it lands does not depend on what an engine step costs on the host. + */ +function expectWalkEnded(message: string | undefined): void { + expect(message).toBe(`Stepped into. ${ErrorMessages.stepIntoReachedNoProgramCode(512)}`); +} + +/** + * The sentence a pending step_into carries while the stepper is walking it + * through skipped code (round 3, decision 2). + */ +const WALKING = /The stepper's last record of this step is that it is walking through skipped code/; + +/** + * How long a step whose walk outlasted the grace window may take to land: + * 512 engine steps at about 44 ms each on Linux (issue #1163) is about 23 s, + * and the step-outs after it more. A harness bound, not the step's. + */ +const WALK_WAIT_MS = 90000; + +/** + * A step V8 loses (issues #1161, #1174) is the engine's own, and the server + * does not rescue it. On a runtime that loses it the step does not land: the + * program runs on (`pending: true`, state `running`) or ends. On one that + * does not, it lands in the caller. Either passes; a stop anywhere else + * fails, another call of the function left included. Every caller these + * tests name runs once, so a line of it identifies the call. + */ +function expectInCallerOrLost(answer: StopAnswer & { ms: number }, file: RegExp, callerLines: number[], options: { walked?: boolean } = {}): void { + expect(answer.success, JSON.stringify(answer)).toBe(true); + if (answer.state !== 'paused') { + // Lost: the program ran on, or ended. + return; + } + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(file); + expect(callerLines, JSON.stringify(answer)).toContain(answer.location?.line); + if (answer.lastStop) { + // Read by wait_for_stop after a pending answer: the stop is the step's. + expect(answer.lastStop.reason, JSON.stringify(answer)).toBe('step'); + } + // A step that walked through skipped code takes as long as its engine + // steps take on the host: only a step that did not walk is held to the window. + if (!options.walked) { + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } +} + +/** + * Whether a step_over off the end of a finally block stopped where a runtime + * with V8's fix (#1173; V8 16.0) stops it first: once more at the end of the + * `return`, in the same call, as V8 stops at any `return`. The step after it + * lands in the caller. A stop on the return's line is this one only when the + * frame under it is the call the test paused in, not a later call. + */ +function isAtTheReturn(answer: StopAnswer, returnLine: number, callerLine: number): boolean { + return answer.state === 'paused' && answer.location?.line === returnLine && answer.snapshot?.frames?.[1]?.line === callerLine; +} + +/** The stop at the end of the `return` is a plain step landing, with the value it returns. */ +function expectAtTheReturn(answer: StopAnswer & { ms: number }, file: RegExp): void { + expect(answer.success, JSON.stringify(answer)).toBe(true); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(file); + const vars = answer.snapshot?.changedVariables ?? answer.snapshot?.locals ?? {}; + expect(Object.keys(vars), JSON.stringify(answer)).toContain('Return value'); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); +} + +describe('The server\'s JavaScript stepper against a real js-debug (issues #1130, #1161) @requires-node', () => { + let server: StdioClientHandle | undefined; + + afterEach(async () => { + await server?.close(); + server = undefined; + }); + + async function pausedAt( + marker: string, + launchArgs?: Record, + extraBreakpoints: string[] = [], + programArgs?: string[] + ): Promise { + server = await startStdioClient({ name: 'js-stepper', callTimeoutMs: WALK_WAIT_MS + 10_000 }); + await server.createSession('javascript', 'js-stepper'); + for (const at of [marker, ...extraBreakpoints]) { + const set = await server.call('set_breakpoint', { file: FIXTURE, line: lineOf(at) }); + expect(set.success, JSON.stringify(set)).toBe(true); + } + let stop = await server.call('start_debugging', { + scriptPath: FIXTURE, + ...(programArgs ? { args: programArgs } : {}), + ...(launchArgs ? { dapLaunchArgs: launchArgs } : {}) + }); + expect(stop.success, JSON.stringify(stop)).toBe(true); + if (stop.state !== 'paused') { + stop = await server.call('wait_for_stop', { timeout: 20000 }); + } + expect(stop, JSON.stringify(stop)).toMatchObject({ success: true, state: 'paused' }); + expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf(marker)); + return stop; + } + + async function step(tool: 'step_into' | 'step_over' | 'step_out'): Promise { + const started = Date.now(); + const answer = await server!.call(tool, {}); + return { ...answer, ms: Date.now() - started }; + } + + function expectLanding(answer: StopAnswer & { ms: number }, marker: string, options: { walked?: boolean } = {}): void { + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/steps\.cjs$/); + expect(answer.location?.line, JSON.stringify(answer)).toBe(lineOf(marker)); + if (answer.lastStop) { + // Read by wait_for_stop after a pending answer: the stop is the step's. + expect(answer.lastStop.reason, JSON.stringify(answer)).toBe('step'); + } + // A step that walked through skipped code takes as long as its engine + // steps take on the host: only a step that did not walk is held to the window. + if (!options.walked) { + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } + } + + /** + * A step whose walk through skipped code can outlast the grace window on a + * slow inspector link (round 3, decision 6): it answers where it landed at + * once, or `pending` with the stepper's walking sentence, and then + * wait_for_stop answers where it landed. The landing is what is returned + * (`first` keeps the first answer); the caller asserts its line strictly + * either way. + */ + async function walkingStep( + tool: 'step_into' | 'step_over' | 'step_out', + options: { walkingWhenPending?: boolean } = {} + ): Promise { + const started = Date.now(); + const first = await server!.call(tool, {}); + if (!first.pending) { + return { ...first, ms: Date.now() - started, first }; + } + if (options.walkingWhenPending !== false) { + expect(first.message ?? '', JSON.stringify(first)).toMatch(WALKING); + // Issue #1130's complaint: the pending answer blamed "a long-running + // call" and promised a pause. A step recorded as walking does neither. + expect(first.message ?? '', JSON.stringify(first)).toMatch(/^Step dispatched; it has not landed after 5s\./); + expect(first.message ?? '', JSON.stringify(first)).not.toMatch(/long-running call|will become 'paused'/); + } + const landed = await server!.call('wait_for_stop', { timeout: WALK_WAIT_MS }); + return { ...landed, ms: Date.now() - started, first }; + } + + /** Removes the breakpoint on a marked line, so a later call through that line does not stop on it. */ + async function removeBreakpointAt(marker: string): Promise { + const removed = await server!.call('remove_breakpoint', { file: FIXTURE, line: lineOf(marker) }); + expect(removed.success, JSON.stringify(removed)).toBe(true); + } + + describe('step_into (issue #1130)', () => { + it('lands on the next line when the walk into the call stays in Node\'s own code: the first console.log of the process', async () => { + await pausedAt('the first console.log'); + const answer = await walkingStep('step_into'); + // js-debug's own stepper lost this step: "Step completed as session exited." + expectLanding(answer, 'after the first console.log', { walked: true }); + // Measured through the server on Windows: 391 engine steps, back out by + // step-ins (a plain landing) in about 1 s. At about 44 ms an engine step + // (Linux) the same walk outlasts the grace window: the first answer is + // pending and says the step is walking, and it lands on the same line. + if (!answer.first.pending && answer.message !== 'Stepped into') { + expectWalkEnded(answer.message); + } + }, 150000); + + it('lands on the next line of a later console.log: issue #1130\'s own case', async () => { + await pausedAt('a later console.log'); + const answer = await walkingStep('step_into'); + expectLanding(answer, 'after a later console.log', { walked: true }); + // 130 engine steps through the server on Windows, walked back out by + // step-ins (a plain landing); pending first, then the same landing, where + // an engine step costs about 44 ms. + if (!answer.first.pending && answer.message !== 'Stepped into') { + expectWalkEnded(answer.message); + } + }, 150000); + + it('stays in the first iteration of a one-line loop: the header\'s next position on the same line is the landing', async () => { + await pausedAt('a one-line loop'); + const answer = await step('step_into'); + expectLanding(answer, 'a one-line loop'); + expect(answer.message).toBe('Stepped into'); + // The loop variable is not bound yet, or holds the first item. + const item = await server!.call('evaluate_expression', { + expression: "(() => { try { return String(item); } catch (e) { return 'TDZ'; } })()" + }); + expect(['\'TDZ\'', 'TDZ', '\'1\'', '1'], JSON.stringify(item)).toContain(item.result); + }, 60000); + + it('enters a function of the program that a builtin calls', async () => { + await pausedAt('a builtin calls the program'); + const answer = await step('step_into'); + expectLanding(answer, 'in the mapper'); + expect(answer.message).toBe('Stepped into'); + }, 60000); + + it('follows a call through Node\'s own code into the program\'s listener', async () => { + await pausedAt('Node code calls the program'); + const answer = await step('step_into'); + expectLanding(answer, 'in the listener'); + expect(answer.message).toBe('Stepped into'); + }, 60000); + + it('follows a call through Node\'s once-wrapper into the program\'s listener: a walk longer than 24 engine steps', async () => { + await pausedAt('emits to a once listener'); + const answer = await walkingStep('step_into'); + expectLanding(answer, 'in the once listener', { walked: true }); + if (!answer.first.pending) { + expect(answer.message).toBe('Stepped into'); + } + }, 150000); + + it('enters the program\'s listener however long Node\'s code before it runs: a walk is counted in engine steps, never the clock (review 8, C1)', async () => { + await pausedAt('emits after a slow listener', undefined, [], ['slow-listener']); + const answer = await walkingStep('step_into'); + expectLanding(answer, 'in the listener after a slow one', { walked: true }); + // The listener before it blocked for 3.5 s: a clock bound of the walk + // (3 s, before round 3) gave up there and landed on the next line. + expect(answer.ms, JSON.stringify(answer)).toBeGreaterThanOrEqual(3000); + }, 150000); + + it('does not follow a call into a later task: the next line, not the timer\'s callback', async () => { + await pausedAt('starts a later task'); + // The walk through Node's timer code outlasts the grace window where an + // engine step costs about 44 ms (measured on a Linux host): pending + // first, then the same landing. + expectLanding(await walkingStep('step_into'), 'after setTimeout', { walked: true }); + }, 150000); + + it('lands on the next line of a require of a module not yet loaded, or V8 loses the step (the loader returns through try...finally, issue #1161)', async () => { + await pausedAt('first load of a module'); + // The loader is a long walk through Node's code: on a slow inspector + // link the first answer is pending, and what follows is judged the same + // way. A pending answer need not say the step is walking: js-debug's + // own module-entry pause withdraws that record (the step may be lost + // with it, issue #1162), and a walk at its limit is stepping out. + const answer = await walkingStep('step_into', { walkingWhenPending: false }); + expectInCallerOrLost(answer, /steps\.cjs$/, [lineOf('after the require')], { walked: true }); + }, 150000); + }); + + describe('step_out and step_over', () => { + it('step_out of a callback Node called lands back in the program, past Node\'s frames', async () => { + await pausedAt('in the listener'); + expectLanding(await step('step_out'), 'after emit'); + }, 60000); + + it('a breakpoint reached during a step_over stops as itself', async () => { + await pausedAt('calls a function with a breakpoint', undefined, ['a breakpoint in a callee']); + const answer = await step('step_over'); + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused', stopReason: 'breakpoint' }); + expect(answer.location?.line, JSON.stringify(answer)).toBe(lineOf('a breakpoint in a callee')); + expect(answer.message).toMatch(/stopped on 'breakpoint' rather than on the step itself/); + }, 60000); + + it('a step off the last line of a callback Node called resumes the program: the next breakpoint is what stops', async () => { + await pausedAt('last line of a callback Node called', undefined, ['a later task']); + // V8 stops once more in the callback, on its closing brace. + const brace = await step('step_over'); + expect(brace, JSON.stringify(brace)).toMatchObject({ success: true, state: 'paused' }); + expect(brace.location?.line, JSON.stringify(brace)).toBe(lineOf('last line of a callback Node called') + 1); + const answer = await step('step_over'); + // Nothing of the program is below the timer's callback: the stack the + // step started on is gone. The stepper resumes instead of stepping out + // of the bottom frame, which would walk the internals of later tasks. + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused', stopReason: 'breakpoint' }); + expect(answer.location?.line, JSON.stringify(answer)).toBe(lineOf('a later task')); + expect(answer.ms, JSON.stringify(answer)).toBeLessThan(PROMPT_MS); + }, 60000); + }); + + describe('a step that leaves a function through return inside try...finally (issues #1161, #1174)', () => { + // withFinally is called twice: from syncPart, where these tests pause, + // and later from main. Its caller here is syncPart, which runs once. + const CALLER = (): number[] => [lineOf('calls withFinally'), lineOf('after withFinally')]; + + it('step_out lands in the caller, or V8 loses it: never in another call', async () => { + await pausedAt('return inside try-finally'); + // So main's later call of withFinally does not stop on it. + await removeBreakpointAt('return inside try-finally'); + // The call's own line too: V8's step-out can stop there once more. + expectInCallerOrLost(await step('step_out'), /steps\.cjs$/, CALLER()); + }, 60000); + + it('step_over reaches the finally block; the step off it is V8\'s: the return then the caller, lost, or the known stop in the next call of the function (#1161, #1173)', async () => { + await pausedAt('return inside try-finally'); + await removeBreakpointAt('return inside try-finally'); + expectLanding(await step('step_over'), 'the finally block'); + // The step that leaves the function is V8's own, and the server does not + // rescue it. A runtime with V8's fix (#1173) stops once more at the end + // of the return, in this call, and the step after that lands in the + // caller; one without it loses the step and runs on, or does a third + // thing, the known defect that docs/javascript/README.md states ("can + // instead stop in the next call of the same function"): it stops on the + // first statement of main's later call of withFinally and reports that + // as the step. This test names both stops on that line, the frame under + // each included, so any other stop fails. + const answer = await step('step_over'); + if (isAtTheReturn(answer, lineOf('return inside try-finally'), lineOf('calls withFinally'))) { + expectAtTheReturn(answer, /steps\.cjs$/); + const next = await step('step_over'); + expect(next.state, JSON.stringify(next)).toBe('paused'); + expectInCallerOrLost(next, /steps\.cjs$/, CALLER()); + return; + } + const inTheNextCall = answer.state === 'paused' && answer.location?.line === lineOf('return inside try-finally'); + if (inTheNextCall) { + expect(answer.success, JSON.stringify(answer)).toBe(true); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/steps\.cjs$/); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.snapshot?.frames?.[1]?.line, JSON.stringify(answer)).toBe(lineOf('calls withFinally from an async function')); + return; + } + expectInCallerOrLost(answer, /steps\.cjs$/, CALLER()); + }, 60000); + + it('step_out into an async caller lands in that caller, or V8 loses it (#1174)', async () => { + await pausedAt('return inside try-finally', undefined, ['calls withFinally from an async function']); + // The first stop is the call from the plain caller: run to the second. + let stop = await server!.call('continue_execution', {}); + stop = await server!.call('wait_for_stop', { timeout: 20000 }); + expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf('calls withFinally from an async function')); + stop = await server!.call('step_into', {}); + expect(stop.location?.line, JSON.stringify(stop)).toBe(lineOf('return inside try-finally')); + // main runs once; withFinally is not called again after this. + expectInCallerOrLost(await step('step_out'), /steps\.cjs$/, [ + lineOf('calls withFinally from an async function'), + lineOf('after withFinally from an async function') + ]); + }, 60000); + + it('step_out of an async function with that shape lands in the function that awaits it, or V8 loses it (#1174)', async () => { + await pausedAt('async return inside try-finally'); + // A runtime with V8's fix (#1173) lands it. + expectInCallerOrLost(await step('step_out'), /steps\.cjs$/, [lineOf('awaits workWithFinally'), lineOf('after the await')]); + }, 60000); + }); + + describe('a bundle: one script, a dependency\'s lines and the program\'s (C1)', () => { + const BUNDLE = path.resolve(here, '../../../fixtures/javascript/step-skipped-code/bundle'); + const SCRIPT = path.join(BUNDLE, 'out', 'bundle.js'); + const APP = path.join(BUNDLE, 'src', 'app.js'); + const LIB = path.join(BUNDLE, 'node_modules', 'blib', 'index.js'); + /** The 1-based line of `file` that carries `// `. */ + const markerLine = (file: string, marker: string): number => { + const index = fs.readFileSync(file, 'utf8').split('\n').findIndex((line) => new RegExp(`// ${marker}(?![A-Z-])`).test(line)); + if (index === -1) { + throw new Error(`no line marked "${marker}" in ${file}`); + } + return index + 1; + }; + + function expectInApp(answer: StopAnswer & { ms: number }, marker: string): void { + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.stopReason, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/app\.js$/); + expect(answer.location?.line, JSON.stringify(answer)).toBe(markerLine(APP, marker)); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } + + it('steps on through the program\'s lines after a stop inside the bundled dependency', async () => { + server = await startStdioClient({ name: 'js-stepper-bundle' }); + await server.createSession('javascript', 'js-stepper-bundle'); + const set = await server.call('set_breakpoint', { file: LIB, line: markerLine(LIB, 'BLIB-WORK') }); + expect(set.success, JSON.stringify(set)).toBe(true); + let stop = await server.call('start_debugging', { scriptPath: SCRIPT }); + expect(stop.success, JSON.stringify(stop)).toBe(true); + if (stop.state !== 'paused') { + stop = await server.call('wait_for_stop', { timeout: 20000 }); + } + expect(stop, JSON.stringify(stop)).toMatchObject({ success: true, state: 'paused' }); + expect(stop.location?.file ?? '', JSON.stringify(stop)).toMatch(/blib[\\/]index\.js$/); + // The dependency's code is skipped: step_over comes back to the caller's next line. + expectInApp(await step('step_over'), 'B-AFTER-LIBWORK'); + // The program's lines of the same script are program code to the steps after it. + expectInApp(await step('step_over'), 'B-CALLS-MINE'); + expectInApp(await step('step_into'), 'B-IN-MINE'); + }, 60000); + }); + + describe('a session that chose plain steps', () => { + it('justMyCode: false lands in Node\'s own code, where V8 lands', async () => { + await pausedAt('the first console.log', { justMyCode: false }); + const answer = await step('step_into'); + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/node_internals|^node:/); + expect(answer.message).toBe('Stepped into'); + }, 60000); + }); + + describe('async functions, callbacks the program only scheduled, and a caller\'s own skip list', () => { + const ASYNC_FIXTURE = path.resolve(here, '../../../fixtures/javascript/step-skipped-code/async-steps.cjs'); + const ASYNC_LINES = fs.readFileSync(ASYNC_FIXTURE, 'utf8').split('\n'); + const at = (marker: string): number => { + const index = ASYNC_LINES.findIndex((line) => line.includes(`// MARK: ${marker}`)); + if (index === -1) { + throw new Error(`no line marked "${marker}" in the async fixture`); + } + return index + 1; + }; + + async function asyncPausedAt(marker: string, options: { condition?: string; launchArgs?: Record } = {}): Promise { + server = await startStdioClient({ name: 'js-stepper-async' }); + await server.createSession('javascript', 'js-stepper-async'); + const set = await server.call('set_breakpoint', { + file: ASYNC_FIXTURE, + line: at(marker), + ...(options.condition ? { condition: options.condition } : {}) + }); + expect(set.success, JSON.stringify(set)).toBe(true); + let stop = await server.call('start_debugging', { + scriptPath: ASYNC_FIXTURE, + ...(options.launchArgs ? { dapLaunchArgs: options.launchArgs } : {}) + }); + expect(stop.success, JSON.stringify(stop)).toBe(true); + if (stop.state !== 'paused') { + stop = await server.call('wait_for_stop', { timeout: 20000 }); + } + expect(stop, JSON.stringify(stop)).toMatchObject({ success: true, state: 'paused' }); + expect(stop.location?.line, JSON.stringify(stop)).toBe(at(marker)); + } + + function expectAsyncLanding(answer: StopAnswer & { ms: number }, marker: string): void { + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.pending, JSON.stringify(answer)).toBeUndefined(); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/async-steps\.cjs$/); + expect(answer.location?.line, JSON.stringify(answer)).toBe(at(marker)); + expect(answer.ms, `took ${answer.ms} ms: ${JSON.stringify(answer)}`).toBeLessThan(PROMPT_MS); + } + + it('step_out of an async function lands in the call that awaited it, with other calls of the same function in flight', async () => { + await asyncPausedAt('in inner, after the gate', { condition: 'id === 2' }); + const answer = await step('step_out'); + expectAsyncLanding(answer, 'the continuation of handler'); + // Three calls of handler are in flight, handler(1)'s continuation + // queued first: V8's own step finds handler(2), the one that awaited. + const id = await server!.call('evaluate_expression', { expression: 'id' }); + expect(id.result, JSON.stringify(id)).toBe('2'); + expect(answer.message).toBe('Stepped out'); + }, 60000); + + it('step_over on an await lands on the next line of the same function, though the function has a finally clause', async () => { + await asyncPausedAt('an await before the try'); + // None of these steps leaves the function without crossing an await first: V8 does not lose them. + expectAsyncLanding(await step('step_over'), 'an await inside the try'); + expectAsyncLanding(await step('step_over'), 'the return inside the try'); + expectAsyncLanding(await step('step_over'), 'the finally block of an async function'); + // Off the finally block of an async function V8 loses the step, and the + // server does not rescue it (#1174). A runtime with V8's fix (#1173) + // stops once more at the end of the return, then lands in main. + // closing is called once, from main. + const off = await step('step_over'); + if (isAtTheReturn(off, at('the return inside the try'), at('awaits closing'))) { + expectAtTheReturn(off, /async-steps\.cjs$/); + const next = await step('step_over'); + expect(next.state, JSON.stringify(next)).toBe('paused'); + expectInCallerOrLost(next, /async-steps\.cjs$/, [at('awaits closing'), at('after closing')]); + return; + } + expectInCallerOrLost(off, /async-steps\.cjs$/, [at('awaits closing'), at('after closing')]); + }, 60000); + + it('step_over on a statement that awaits on a later line stays in the function: its caller runs on, and is not where the step stops', async () => { + await asyncPausedAt('a statement that awaits on later lines'); + // The function has a finally clause above, and the paused line itself + // awaits nothing: the step crosses the await on the next line and stays + // in the function while its caller runs on. + const answer = await step('step_over'); + expectAsyncLanding(answer, 'the second await of the statement'); + expect(answer.message).toBe('Stepped over'); + }, 60000); + + it('step_out of an async function still in its first run lands in the call that awaits it, with other calls in flight', async () => { + await asyncPausedAt('in early, before its first await', { condition: 'id === 2' }); + const answer = await step('step_out'); + expectAsyncLanding(answer, 'the continuation of relay'); + // Three calls of relay are in flight: the id says the step landed in + // relay(2), the one that awaited this early. + const id = await server!.call('evaluate_expression', { expression: 'id' }); + expect(id.result, JSON.stringify(id)).toBe('2'); + expect(answer.message).toBe('Stepped out'); + }, 60000); + + it('step_out of a .then callback resumes the program: what registered the callback is not what it returns to', async () => { + await asyncPausedAt('in a then callback'); + const answer = await step('step_out'); + // Nothing of the program is on the stack and nothing awaits the + // callback: the program runs to its end, 150 ms later. + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true }); + expect(answer.state, JSON.stringify(answer)).not.toBe('paused'); + }, 60000); + + it('steps with V8 alone where Node\'s own code is program code: a skip list without ', async () => { + await asyncPausedAt('in a timer callback', { launchArgs: { skipFiles: ['**/node_modules/**'] } }); + const answer = await step('step_out'); + // Node's own code is program code to this step: V8's step-out lands + // in the timer code it returns to. + expect(answer, JSON.stringify(answer)).toMatchObject({ success: true, state: 'paused' }); + expect(answer.location?.file ?? '', JSON.stringify(answer)).toMatch(/timers/); + }, 60000); + }); +}); diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json index 8153145e..0f1a1bca 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json index 4c84b648..3b3e4d72 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-explicit.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json index fe912a77..bbe4cc3a 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json index ac5bfb57..d548f282 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-open.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json index fe912a77..bbe4cc3a 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-true.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json index ac5bfb57..d548f282 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-assert.va-unset.container-unset.json @@ -240,7 +240,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json index a3517044..7088cf0a 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json index 2f05191e..92815187 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json index c4b0dda8..674e1277 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json index 9190ad60..8447d824 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json index c4b0dda8..674e1277 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json index 9190ad60..8447d824 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-content.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json index 9d724300..760cfaa0 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json index 763b75fa..b5840b1e 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-explicit.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json index 1a56f34c..a3ab675c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json index 6e4ced0f..dc027745 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-open.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json index 1a56f34c..a3ab675c 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-true.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json index 6e4ced0f..dc027745 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-line.va-unset.container-unset.json @@ -236,7 +236,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json index a3517044..7088cf0a 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json index 2f05191e..92815187 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-explicit.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json index c4b0dda8..674e1277 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json index 9190ad60..8447d824 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-open.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json index c4b0dda8..674e1277 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-true.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json index 9190ad60..8447d824 100644 --- a/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json +++ b/tests/core/unit/server/__snapshots__/tool-list/bp-unset.va-unset.container-unset.json @@ -250,7 +250,7 @@ }, "justMyCode": { "type": "boolean", - "description": "Only debug user code (default true). JavaScript launch: true blackboxes node_modules via skipFiles and keeps js-debug's smart-stepper on, so a pause or step that lands in skipped code (Node internals, node_modules) is stepped through and may never land; false drops node_modules from skipFiles and turns the stepper off, so pauses and steps land inside dependencies" + "description": "Only debug user code (default true). JavaScript launch: true skips node_modules and Node internals when stepping (step_into follows a call through them into your own code when its walk reaches it within 512 engine steps, or else steps out and says so; no time bound, so a step lands in the same place on every host, and a long walk where an engine step is slow answers pending first, saying it is walking); false lands every step where the engine lands, inside dependencies and Node internals. A pause lands where the program is either way" }, "noDebug": { "type": "boolean", diff --git a/tests/core/unit/session/session-manager-dap.test.ts b/tests/core/unit/session/session-manager-dap.test.ts index 5b73c3fb..73633184 100644 --- a/tests/core/unit/session/session-manager-dap.test.ts +++ b/tests/core/unit/session/session-manager-dap.test.ts @@ -25,6 +25,11 @@ import { threadStacksHandler } from '../../../test-utils/mocks/thread-stacks.js' import { ErrorMessages } from '../../../../src/utils/error-messages.js'; import { ProxyNotRunningError } from '../../../../src/errors/debug-errors.js'; import { DapResponseError } from '../../../../src/proxy/dap-response-error.js'; +import { + PROXY_STEP_LEFT_STACK_EVENT, + PROXY_STEP_WALK_ENDED_EVENT, + PROXY_STEP_WALK_STARTED_EVENT +} from '../../../../src/proxy/dap-proxy-interfaces.js'; /** * A `breakpoint` event body as the proxy delivers it for a CHILD session event. @@ -1745,6 +1750,245 @@ describe('SessionManager - DAP Operations', () => { expect(data.message).toMatch(/back at the line the step was issued from/); }); + // I3 (issue #1130): the JavaScript policy's "left the frame" sentence is + // true only for a step the proxy's stepper ended by resuming the program, + // which it records with an event of its own. A step still executing in + // its own frame (a step_over of a long call) gets the generic wording. + describe('the pending wording of a step the proxy stepper ended by leaving the stack (I3)', () => { + const LEFT = 'Left its frame, by the stepper\'s own record.'; + + function withLeftStackHook(manager: SessionManager): ReturnType { + const hook = vi.fn((info: { stepLeftStack?: boolean }) => (info.stepLeftStack ? LEFT : undefined)); + const original = (manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }).selectPolicy.bind(manager); + vi.spyOn(manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }, 'selectPolicy') + .mockImplementation((language: string) => ({ ...original(language), describePendingStop: hook })); + return hook; + } + + async function pendingStepOver(sessionId: string, events: Array<[string, unknown]>) { + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (command: string) => { + if (command === 'next') { + process.nextTick(() => { + for (const [event, body] of events) { + dependencies.mockProxyManager.emit('dap-event', event, body); + } + }); + } + if (command === 'stackTrace') { + const frame = { id: 1, name: 'main', source: { path: '/app/main.js' }, line: 12, column: 3 }; + return { success: true, body: { stackFrames: [frame], totalFrames: 1 } }; + } + return { success: true }; + }); + const stepPromise = sessionManager.stepOver(sessionId); + await vi.advanceTimersByTimeAsync(6000); + return (await stepPromise).data as { message?: string; pending?: boolean }; + } + + it('carries the sentence when the stepper recorded that the step left the stack', async () => { + const session = await createPausedSession(sessionManager, dependencies); + const hook = withLeftStackHook(sessionManager); + const data = await pendingStepOver(session.id, [[PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }]]); + expect(data.pending).toBe(true); + expect(data.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${LEFT}`); + expect(hook).toHaveBeenCalledWith(expect.objectContaining({ operation: 'step', stepLeftStack: true })); + }); + + /** The session is paused again (the pending step landed later), so the next step can go out. */ + async function pausedAgain(): Promise { + dependencies.mockProxyManager.simulateStopped(1, 'step'); + await vi.advanceTimersByTimeAsync(10); + } + + it('carries the generic wording for a step with no such record, and the sentence for the next step, which has one', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withLeftStackHook(sessionManager); + // Another custom event is not the record. + const first = await pendingStepOver(session.id, [['flutter.appStarted', {}]]); + expect(first.pending).toBe(true); + expect(first.message).toBe(ErrorMessages.stepStillRunning(5)); + await pausedAgain(); + // The record itself is. + const second = await pendingStepOver(session.id, [[PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }]]); + expect(second.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${LEFT}`); + }); + + it('reads the record of this step only: the one a finished step left behind does not carry over', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withLeftStackHook(sessionManager); + // This step's record is read. + const first = await pendingStepOver(session.id, [[PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }]]); + expect(first.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${LEFT}`); + await pausedAgain(); + // A record that arrives while no step is waiting (the last step had already answered) is nobody's. + dependencies.mockProxyManager.emit('dap-event', PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }); + const second = await pendingStepOver(session.id, []); + expect(second.message).toBe(ErrorMessages.stepStillRunning(5)); + }); + + it('stops listening for the records once the step has answered, pending or landed', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withLeftStackHook(sessionManager); + const before = dependencies.mockProxyManager.listenerCount('dap-event'); + await pendingStepOver(session.id, []); + expect(dependencies.mockProxyManager.listenerCount('dap-event')).toBe(before); + await pausedAgain(); + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (command: string) => { + if (command === 'next') { + process.nextTick(() => dependencies.mockProxyManager.simulateStopped(1, 'step')); + } + return { success: true }; + }); + const landed = sessionManager.stepOver(session.id); + await vi.advanceTimersByTimeAsync(100); + expect((await landed).data).toMatchObject({ message: 'Stepped over' }); + expect(dependencies.mockProxyManager.listenerCount('dap-event')).toBe(before); + }); + }); + + // Round 3, decision 2 (issue #1130): a step_into the proxy's stepper is + // walking through skipped code when the grace window ends says so. The + // stepper records when the walk starts and when it ends without a landing; + // the controller keeps the latest record of the step and hands the policy + // what it says at the 5 s mark. + describe('the pending wording of a step_into the proxy stepper is walking through skipped code', () => { + const WALKING = 'Walking, by the stepper\'s own record.'; + const LEFT = 'Left its frame, by the stepper\'s own record.'; + + function withRecordHook(manager: SessionManager): ReturnType { + const hook = vi.fn((info: { stepLeftStack?: boolean; stepWalking?: { stepLimit?: number } }) => + (info.stepWalking ? `${WALKING} limit=${info.stepWalking.stepLimit}` : info.stepLeftStack ? LEFT : undefined)); + const original = (manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }).selectPolicy.bind(manager); + vi.spyOn(manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }, 'selectPolicy') + .mockImplementation((language: string) => ({ ...original(language), describePendingStop: hook })); + return hook; + } + + async function pendingStepIn(sessionId: string, events: Array<[string, unknown]>) { + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (command: string) => { + if (command === 'stepIn') { + process.nextTick(() => { + for (const [event, body] of events) { + dependencies.mockProxyManager.emit('dap-event', event, body); + } + }); + } + if (command === 'stackTrace') { + const frame = { id: 1, name: 'main', source: { path: '/app/main.js' }, line: 12, column: 3 }; + return { success: true, body: { stackFrames: [frame], totalFrames: 1 } }; + } + return { success: true }; + }); + const stepPromise = sessionManager.stepInto(sessionId); + await vi.advanceTimersByTimeAsync(6000); + return (await stepPromise).data as { message?: string; pending?: boolean }; + } + + it('says the step is walking when the latest record is the walk\'s start, with the limit the stepper sent', async () => { + const session = await createPausedSession(sessionManager, dependencies); + const hook = withRecordHook(sessionManager); + const data = await pendingStepIn(session.id, [[PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }]]); + expect(data.pending).toBe(true); + expect(data.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${WALKING} limit=512`); + expect(hook).toHaveBeenCalledWith(expect.objectContaining({ operation: 'step', stepWalking: { stepLimit: 512 } })); + expect(hook).not.toHaveBeenCalledWith(expect.objectContaining({ stepLeftStack: true })); + }); + + it('says nothing of a walk that ended at its limit and is stepping out: the latest record wins', async () => { + const session = await createPausedSession(sessionManager, dependencies); + const hook = withRecordHook(sessionManager); + const data = await pendingStepIn(session.id, [ + [PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }], + [PROXY_STEP_WALK_ENDED_EVENT, { threadId: 1 }] + ]); + expect(data.message).toBe(ErrorMessages.stepStillRunning(5)); + expect(hook).toHaveBeenCalledWith(expect.not.objectContaining({ stepWalking: expect.anything() })); + }); + + it('says the step left its frame when that is the latest record, after a walk', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withRecordHook(sessionManager); + const data = await pendingStepIn(session.id, [ + [PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }], + [PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }] + ]); + expect(data.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${LEFT}`); + }); + + it('reads only the stepper\'s records: another event after the walk\'s start leaves it walking', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withRecordHook(sessionManager); + const data = await pendingStepIn(session.id, [ + [PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }], + ['flutter.appStarted', {}] + ]); + expect(data.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${WALKING} limit=512`); + }); + + it('says the step is walking again when the walk was withdrawn and then went on', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withRecordHook(sessionManager); + const data = await pendingStepIn(session.id, [ + [PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }], + [PROXY_STEP_WALK_ENDED_EVENT, { threadId: 1 }], + [PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }] + ]); + expect(data.message).toBe(`${ErrorMessages.stepNotLanded(5)} ${WALKING} limit=512`); + }); + + // Issue #1130's complaint was the lead itself: a walk through skipped + // code "still executing ... (e.g. stepping over a long-running call)", + // promised to "become 'paused' when it completes". A step the stepper + // has a record of is known to be neither, so the lead says only that it + // has not landed. Without a record nothing is known, and the generic + // lead stays (its promise is issue #1178's). + describe('the lead of the pending answer', () => { + /** A policy that explains every pending step, whatever was recorded. */ + function withTalkativeHook(manager: SessionManager, text: string | undefined): void { + const original = (manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }).selectPolicy.bind(manager); + vi.spyOn(manager as unknown as { selectPolicy: (language: string) => AdapterPolicy }, 'selectPolicy') + .mockImplementation((language: string) => ({ ...original(language), describePendingStop: () => text })); + } + + it('blames no long-running call and promises no pause for a step recorded as walking, or as having left the stack', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withRecordHook(sessionManager); + const walking = await pendingStepIn(session.id, [[PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }]]); + expect(walking.message).not.toMatch(/long-running call/); + expect(walking.message).not.toMatch(/will become 'paused'/); + expect(walking.message).toMatch(/^Step dispatched; it has not landed after 5s\./); + dependencies.mockProxyManager.simulateStopped(1, 'step'); + await vi.advanceTimersByTimeAsync(10); + const left = await pendingStepIn(session.id, [[PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }]]); + expect(left.message).not.toMatch(/long-running call/); + expect(left.message).not.toMatch(/will become 'paused'/); + expect(left.message).toMatch(/^Step dispatched; it has not landed after 5s\./); + }); + + it('keeps the generic lead for an explanation no record backs', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withTalkativeHook(sessionManager, 'Explained by the policy.'); + const none = await pendingStepIn(session.id, []); + expect(none.message).toBe(`${ErrorMessages.stepStillRunning(5)} Explained by the policy.`); + dependencies.mockProxyManager.simulateStopped(1, 'step'); + await vi.advanceTimersByTimeAsync(10); + // A walk that ended is no longer known to be anything. + const ended = await pendingStepIn(session.id, [ + [PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }], + [PROXY_STEP_WALK_ENDED_EVENT, { threadId: 1, why: 'limit' }] + ]); + expect(ended.message).toBe(`${ErrorMessages.stepStillRunning(5)} Explained by the policy.`); + }); + + it('keeps the generic lead for a recorded step the policy says nothing of', async () => { + const session = await createPausedSession(sessionManager, dependencies); + withTalkativeHook(sessionManager, undefined); + const data = await pendingStepIn(session.id, [[PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }]]); + expect(data.message).toBe(ErrorMessages.stepStillRunning(5)); + }); + }); + }); + // Issue #879: the Dart SDK adapter's `next` stops once per token position // (measured: app.dart:29 took three step_overs, columns 16, 26, 32). describe('an adapter that steps by token position (issue #879)', () => { @@ -1927,6 +2171,66 @@ describe('SessionManager - DAP Operations', () => { expect(data.message).toBe('Stepped over'); }); + // The JavaScript stepper reports a landing as reason `step` and puts what + // it has to say about it (the line called only skipped code) in the + // event's `text`. A literal here: the sentence is the stepper's, and any + // text a `step` stop carries is appended. + const STEP_NOTE = 'The line called only code this session skips; the step is back in the frame it started in.'; + + it.each([ + ['step_over', 'next', 'Stepped over', (id: string) => sessionManager.stepOver(id)], + ['step_into', 'stepIn', 'Stepped into', (id: string) => sessionManager.stepInto(id)], + ['step_out', 'stepOut', 'Stepped out', (id: string) => sessionManager.stepOut(id)] + ] as const)('%s appends what the step itself says about its landing to the completion wording (issue #1130)', async (_tool, command, stepped, step) => { + const session = await createPausedSession(sessionManager, dependencies); + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (sent: string) => { + if (sent === command) { + process.nextTick(() => { + dependencies.mockProxyManager.simulateStopped(1, 'step', { reason: 'step', threadId: 1, text: STEP_NOTE }); + }); + } + return { success: true }; + }); + + const stepPromise = step(session.id); + await vi.runAllTimersAsync(); + const result = await stepPromise; + + expect(result.success).toBe(true); + const data = result.data as { message?: string; stopReason?: string; pending?: boolean }; + expect(data.pending).toBeUndefined(); + // Still the step's own stop: no stopReason, the note after the wording. + expect(data.stopReason).toBeUndefined(); + expect(data.message).toBe(`${stepped}. ${STEP_NOTE}`); + }); + + it.each([ + // A breakpoint or an exception names itself; its text is not the step's to repeat. + ['breakpoint', ErrorMessages.stepStoppedOn('Stepped over', 'breakpoint')], + ['exception', ErrorMessages.stepStoppedOn('Stepped over', 'exception')], + // Any other stop keeps the plain wording. + ['pause', 'Stepped over'] + ])("appends the text of the step's own stop only: a '%s' stop that carries one keeps its wording (issue #1130)", async (reason, wording) => { + const session = await createPausedSession(sessionManager, dependencies); + dependencies.mockProxyManager.sendDapRequest = vi.fn().mockImplementation(async (sent: string) => { + if (sent === 'next') { + process.nextTick(() => { + dependencies.mockProxyManager.simulateStopped(1, reason, { reason, threadId: 1, text: STEP_NOTE }); + }); + } + return { success: true }; + }); + + const stepPromise = sessionManager.stepOver(session.id); + await vi.runAllTimersAsync(); + const result = await stepPromise; + + const data = result.data as { message?: string; stopReason?: string }; + expect(data.stopReason).toBe(reason); + expect(data.message).toBe(wording); + expect(data.message).not.toContain(STEP_NOTE); + }); + it('should treat termination during step as a successful completion', async () => { const session = await createPausedSession(sessionManager, dependencies); diff --git a/tests/e2e/mcp-server-smoke-javascript.test.ts b/tests/e2e/mcp-server-smoke-javascript.test.ts index 4cc5e7ba..e0298943 100644 --- a/tests/e2e/mcp-server-smoke-javascript.test.ts +++ b/tests/e2e/mcp-server-smoke-javascript.test.ts @@ -419,12 +419,16 @@ describe('JavaScript Debugging - Simple Smoke Tests', () => { const step = parseSdkToolResult(await mcpClient!.callTool({ name: 'step_over', arguments: { sessionId } })); expect(step.success, JSON.stringify(step)).toBe(true); - // js-debug steps out of the blackboxed frame and the request completes - // without ever reaching unskipped code: the step is lost, and the - // response says why and what to do about it. + // A step does not stop in skipped code: the server's stepper steps out + // toward the nearest frame of the program below, and here there is none + // (express was called by Node), so the program is resumed and the request + // completes. The response says what happened and what steps inside that + // code (issue #1130; it used to blame js-debug's own stepper). expect(step.pending, JSON.stringify(step)).toBe(true); - expect(step.message).toMatch(/skipped frame/); + expect(step.message).toMatch(/issued from skipped code/); + expect(step.message).toMatch(/application\.js:\d+/); expect(step.message).toMatch(/justMyCode: false/); + expect(step.message).not.toMatch(/smart-stepper/); console.log(`[JS Simple Smoke] ✓ Lost dependency step explained (${label})`); }, 60000); diff --git a/tests/fixtures/javascript/step-skipped-code/async-steps.cjs b/tests/fixtures/javascript/step-skipped-code/async-steps.cjs new file mode 100644 index 00000000..5fcec555 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/async-steps.cjs @@ -0,0 +1,105 @@ +/** + * Fixture for the server's JavaScript stepper: async functions, callbacks + * the program only scheduled, and a caller's own skip list (issues #1130, + * #1161). + * + * Every line a test steps from carries a marker comment; the tests find + * lines by marker, so this file can be edited without renumbering them. + */ +let release; +const gate = new Promise((resolve) => { + release = resolve; +}); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function inner(id) { + await gate; + const tag = id; // MARK: in inner, after the gate + return tag; +} + +async function handler(id) { + const got = await inner(id); + const out = got * 10; // MARK: the continuation of handler + return out; +} + +async function closing() { + const opened = await sleep(5); // MARK: an await before the try + try { + const row = await sleep(5); // MARK: an await inside the try + return [opened, row]; // MARK: the return inside the try + } finally { + globalThis.closed = true; // MARK: the finally block of an async function + } +} + +async function getUser(id) { + await sleep(5); + return { id }; +} + +async function load(id) { + try { + globalThis.loading = id; + } finally { + globalThis.loading = 0; + } + const first = id + 1; + return { // MARK: a statement that awaits on later lines + user: await getUser(first), + posts: await getUser(first + 1), // MARK: the second await of the statement + }; +} + +let releaseEarly; +const earlyGate = new Promise((resolve) => { + releaseEarly = resolve; +}); + +async function early(id) { + const tag = id; // MARK: in early, before its first await + await earlyGate; + return tag; +} + +async function relay(id) { + const got = await early(id); + const out = got * 10; // MARK: the continuation of relay + return out; +} + +function onDone(value) { + const seen = value; // MARK: in a then callback + return seen; +} + +function onTimer() { + globalThis.ticked = true; // MARK: in a timer callback +} + +async function main() { + // Three calls of handler in flight at once, each awaiting its own inner. + const all = Promise.all([handler(1), handler(2), handler(3)]); + release(); + await all; + await closing(); // MARK: awaits closing + const afterClosing = 1; // MARK: after closing + // The caller does not await the call at once: it runs on while load is suspended. + const loading = load(1); + const marker = 2; // MARK: the statement of the caller after load + await loading; + // Three calls of relay in flight at once, each awaiting its own early. + const relays = Promise.all([relay(1), relay(2), relay(3)]); + releaseEarly(); + await relays; + globalThis.marker = marker; + Promise.resolve(7).then(onDone); + setTimeout(onTimer, 10); + await sleep(150); + return afterClosing; +} + +main().then(() => { + console.log('done'); +}); diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js b/tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js new file mode 100644 index 00000000..8e7cadad --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/node_modules/blib/index.js @@ -0,0 +1,11 @@ +// A dependency bundled into the program's single script. +'use strict'; +function libWork(n) { + let t = n; // BLIB-WORK + t += 1; + return t; // BLIB-LAST +} +function libCall(fn) { + return fn(2); // BLIB-CALL +} +module.exports = { libWork, libCall }; diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js new file mode 100644 index 00000000..236b3908 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js @@ -0,0 +1,43 @@ +var __getOwnPropNames = Object.getOwnPropertyNames; +var __commonJS = (cb, mod) => function __require() { + try { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + } catch (e) { + throw mod = 0, e; + } +}; + +// node_modules/blib/index.js +var require_blib = __commonJS({ + "node_modules/blib/index.js"(exports2, module2) { + "use strict"; + function libWork2(n) { + let t = n; + t += 1; + return t; + } + function libCall2(fn) { + return fn(2); + } + module2.exports = { libWork: libWork2, libCall: libCall2 }; + } +}); + +// src/app.js +var { libWork, libCall } = require_blib(); +function mine(v) { + const w = v * 3; + return w; +} +function run() { + const a = libWork(1); + const b = a + 1; + const c = mine(b); + const d = c + 1; + const e = libCall(mine); + const f = e + 1; + return f; +} +var out = run(); +console.log("bundle done", out); +//# sourceMappingURL=bundle.js.map diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map new file mode 100644 index 00000000..fa5cddb2 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/out/bundle.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../node_modules/blib/index.js", "../src/app.js"], + "sourcesContent": ["// A dependency bundled into the program's single script.\n'use strict';\nfunction libWork(n) {\n let t = n; // BLIB-WORK\n t += 1;\n return t; // BLIB-LAST\n}\nfunction libCall(fn) {\n return fn(2); // BLIB-CALL\n}\nmodule.exports = { libWork, libCall };\n", "// The program, bundled with its dependency into out/bundle.js (one V8 script, one source map).\nconst { libWork, libCall } = require('blib');\nfunction mine(v) {\n const w = v * 3; // B-IN-MINE\n return w; // B-MINE-RETURN\n}\nfunction run() {\n const a = libWork(1); // B-CALLS-LIBWORK\n const b = a + 1; // B-AFTER-LIBWORK\n const c = mine(b); // B-CALLS-MINE\n const d = c + 1; // B-AFTER-MINE\n const e = libCall(mine); // B-CALLS-LIBCALL\n const f = e + 1; // B-AFTER-LIBCALL\n return f; // B-RUN-RETURN\n}\nconst out = run(); // B-CALLS-RUN\nconsole.log('bundle done', out); // B-END\n"], + "mappings": ";;;;;;;;;;AAAA;AAAA,+BAAAA,UAAAC,SAAA;AAAA;AAEA,aAASC,SAAQ,GAAG;AAClB,UAAI,IAAI;AACR,WAAK;AACL,aAAO;AAAA,IACT;AACA,aAASC,SAAQ,IAAI;AACnB,aAAO,GAAG,CAAC;AAAA,IACb;AACA,IAAAF,QAAO,UAAU,EAAE,SAAAC,UAAS,SAAAC,SAAQ;AAAA;AAAA;;;ACTpC,IAAM,EAAE,SAAS,QAAQ,IAAI;AAC7B,SAAS,KAAK,GAAG;AACf,QAAM,IAAI,IAAI;AACd,SAAO;AACT;AACA,SAAS,MAAM;AACb,QAAM,IAAI,QAAQ,CAAC;AACnB,QAAM,IAAI,IAAI;AACd,QAAM,IAAI,KAAK,CAAC;AAChB,QAAM,IAAI,IAAI;AACd,QAAM,IAAI,QAAQ,IAAI;AACtB,QAAM,IAAI,IAAI;AACd,SAAO;AACT;AACA,IAAM,MAAM,IAAI;AAChB,QAAQ,IAAI,eAAe,GAAG;", + "names": ["exports", "module", "libWork", "libCall"] +} diff --git a/tests/fixtures/javascript/step-skipped-code/bundle/src/app.js b/tests/fixtures/javascript/step-skipped-code/bundle/src/app.js new file mode 100644 index 00000000..f17e0d09 --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/bundle/src/app.js @@ -0,0 +1,17 @@ +// The program, bundled with its dependency into out/bundle.js (one V8 script, one source map). +const { libWork, libCall } = require('blib'); +function mine(v) { + const w = v * 3; // B-IN-MINE + return w; // B-MINE-RETURN +} +function run() { + const a = libWork(1); // B-CALLS-LIBWORK + const b = a + 1; // B-AFTER-LIBWORK + const c = mine(b); // B-CALLS-MINE + const d = c + 1; // B-AFTER-MINE + const e = libCall(mine); // B-CALLS-LIBCALL + const f = e + 1; // B-AFTER-LIBCALL + return f; // B-RUN-RETURN +} +const out = run(); // B-CALLS-RUN +console.log('bundle done', out); // B-END diff --git a/tests/fixtures/javascript/step-skipped-code/lazy.cjs b/tests/fixtures/javascript/step-skipped-code/lazy.cjs new file mode 100644 index 00000000..a28627ab --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/lazy.cjs @@ -0,0 +1,7 @@ +/** + * Loaded for the first time by the line the stepper fixture steps into + * (issue #1161): Node's loader returns through try...finally, the shape V8 + * loses a step-out on. + */ +const value = 1; +module.exports = { value }; diff --git a/tests/fixtures/javascript/step-skipped-code/steps.cjs b/tests/fixtures/javascript/step-skipped-code/steps.cjs new file mode 100644 index 00000000..043bf08c --- /dev/null +++ b/tests/fixtures/javascript/step-skipped-code/steps.cjs @@ -0,0 +1,117 @@ +/** + * Fixture for the server's JavaScript stepper (issues #1130, #1161). + * + * Every line a test steps from carries a marker comment; the tests find + * lines by marker, so this file can be edited without renumbering them. + */ +const { EventEmitter } = require('node:events'); + +const emitter = new EventEmitter(); +function listener(value) { + const doubled = value * 2; // MARK: in the listener + return doubled; +} +emitter.on('x', listener); + +// Node's once-wrapper calls this one: a longer walk through Node's code than on(). +const onceEmitter = new EventEmitter(); +function onceListener(value) { + const tripled = value * 3; // MARK: in the once listener + return tripled; +} +onceEmitter.once('y', onceListener); + +// Node's own code first calls a function of Node's that runs 3.5 s (a bound +// builtin blocking in Atomics.wait), then the program's listener. A walk is +// counted in engine steps, so how long the code before the listener runs does +// not decide whether the step enters it (review 8, C1). Emitted only when the +// program is started with the argument `slow-listener`. +const slowRun = process.argv.includes('slow-listener'); +const slowEmitter = new EventEmitter(); +slowEmitter.on('z', Atomics.wait.bind(Atomics, new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3500)); +function afterSlowListener(value) { + const quadrupled = value * 4; // MARK: in the listener after a slow one + return quadrupled; +} +slowEmitter.on('z', afterSlowListener); + +function mapper(value) { + return value + 1; // MARK: in the mapper +} + +function callee() { + const inside = 1; // MARK: a breakpoint in a callee + return inside; +} + +function inner() { + return 1; +} + +function withFinally() { + try { + return inner(); // MARK: return inside try-finally + } finally { + globalThis.cleaned = true; // MARK: the finally block + } +} + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function workWithFinally() { + try { + await sleep(5); + return 2; // MARK: async return inside try-finally + } finally { + globalThis.asyncCleaned = true; + } +} + +function timerCallback() { + globalThis.fired = true; // MARK: last line of a callback Node called +} + +function laterCallback() { + globalThis.later = true; // MARK: a later task +} + +// A plain function, called once: a step that V8 does not lose returns into +// this one call (issue #1161). The same call from an async function is #1174. +function syncPart() { + const guarded = withFinally(); // MARK: calls withFinally + const afterFinally = 4; // MARK: after withFinally + const lazy = require('./lazy.cjs'); // MARK: first load of a module + const afterRequire = lazy.value + 6; // MARK: after the require + return [guarded, afterFinally, afterRequire]; +} + +async function main() { + console.log('first line printed'); // MARK: the first console.log + const afterLog = 1; // MARK: after the first console.log + console.log('a later line printed'); // MARK: a later console.log + const afterLaterLog = 1; // MARK: after a later console.log + for (const item of [1, 2, 3]) console.log('item', item); // MARK: a one-line loop + const mapped = [1, 2].map(mapper); // MARK: a builtin calls the program + emitter.emit('x', 1); // MARK: Node code calls the program + const afterEmit = 2; // MARK: after emit + onceEmitter.emit('y', 1); // MARK: emits to a once listener + if (slowRun) { + slowEmitter.emit('z', 1); // MARK: emits after a slow listener + } + setTimeout(() => {}, 0); // MARK: starts a later task + const afterTimeout = 3; // MARK: after setTimeout + const called = callee(); // MARK: calls a function with a breakpoint + const fromSync = syncPart(); + const awaited = await workWithFinally(); // MARK: awaits workWithFinally + const afterAwait = 5; // MARK: after the await + const again = withFinally(); // MARK: calls withFinally from an async function + const afterAgain = 7; // MARK: after withFinally from an async function + setTimeout(timerCallback, 0); + setTimeout(laterCallback, 30); + await sleep(120); + return [afterLog, afterLaterLog, mapped, afterEmit, afterTimeout, called, fromSync, awaited, afterAwait, again, afterAgain]; +} + +main().then(() => { + console.log('done'); +}); diff --git a/tests/proxy/cdp-function-breakpoint-bridge.test.ts b/tests/proxy/cdp-function-breakpoint-bridge.test.ts index 978be0e8..7e8216be 100644 --- a/tests/proxy/cdp-function-breakpoint-bridge.test.ts +++ b/tests/proxy/cdp-function-breakpoint-bridge.test.ts @@ -11,6 +11,8 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { EventEmitter } from 'events'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; import type { DebugProtocol } from '@vscode/debugprotocol'; import { CdpFunctionBreakpointBridge, MAX_SCRIPT_URLS } from '../../src/proxy/cdp-function-breakpoint-bridge.js'; import { JS_LOGPOINT_BINDING } from '@debugmcp/shared'; @@ -778,4 +780,14 @@ describe('CdpFunctionBreakpointBridge', () => { expect(urls.get(`s${MAX_SCRIPT_URLS + overshoot - 1}`)).toBe(`file:///f${MAX_SCRIPT_URLS + overshoot - 1}.js`); }); }); + + describe('the source file', () => { + it('holds no raw NUL byte: the key separator is written as an escape', () => { + // A literal NUL made git treat the file as binary (no diff, no blame) + // and made text tools refuse to edit it. The separator is the same + // character at run time; the keyed cases above pin that. + const source = readFileSync(fileURLToPath(new URL('../../src/proxy/cdp-function-breakpoint-bridge.ts', import.meta.url)), 'utf8'); + expect(source.includes(String.fromCharCode(0))).toBe(false); + }); + }); }); diff --git a/tests/proxy/child-connections.test.ts b/tests/proxy/child-connections.test.ts index 31dd1944..75f9491f 100644 --- a/tests/proxy/child-connections.test.ts +++ b/tests/proxy/child-connections.test.ts @@ -5,8 +5,10 @@ * the child itself); a report nobody answers is released by a safety timer. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { EventEmitter } from 'events'; import type { DebugProtocol } from '@vscode/debugprotocol'; import { ChildConnections, type ChildAdoptionDeps } from '../../src/proxy/child-connections.js'; +import type { CdpProxyClient } from '../../src/proxy/cdp-proxy-client.js'; import type { IDapClientFactory, StatusMessage } from '../../src/proxy/dap-proxy-interfaces.js'; import { createMockDapClient } from '../test-utils/mocks/dap-client.js'; import { JsDebugAdapterPolicy, PythonAdapterPolicy, type AdapterPolicy } from '@debugmcp/shared'; @@ -824,3 +826,308 @@ describe('ChildConnections under the throwaway-attach lever (js-debug, issue #10 expect(connections.liveCount()).toBe(0); }); }); + +/** + * The proxy's own stepper for an adopted child (issue #1130): js-debug's is + * kept off, so a child of that adapter gets a JsStepper over its own CDP + * socket. The stepper here is the real one; the socket is the fake below, + * handed in through `cdpClientFactory`, and the test plays V8 and js-debug. + */ +describe("ChildConnections: an adopted child's proxy stepper (issue #1130)", () => { + /** The child's CDP socket (js-debug's `requestCDPProxy`): every command is answered, the test sends V8's events. */ + class FakeCdpClient extends EventEmitter { + readonly sent: string[] = []; + connectedTo: { host: string; port: number; path: string } | null = null; + disposed = false; + + async connect(host: string, port: number, path: string): Promise { + this.connectedTo = { host, port, path }; + } + + async send(method: string): Promise { + this.sent.push(method); + return {}; + } + + isConnected(): boolean { + return this.connectedTo !== null && !this.disposed; + } + + dispose(): void { + this.disposed = true; + } + + /** V8 pauses in `f`, as CDP reports it. */ + paused(reason: string, line: number): void { + this.emit('cdp-event', 'Debugger.paused', { + reason, + callFrames: [{ functionName: 'f', location: { scriptId: '1', lineNumber: line, columnNumber: 0 } }] + }); + } + + resumed(): void { + this.emit('cdp-event', 'Debugger.resumed', {}); + } + } + + interface StepperSetup { + policy?: AdapterPolicy; + launchConfig?: Record; + /** What the root's own start request said. Left out: nothing is wired to ask the root. */ + rootSteps?: () => boolean | undefined; + } + + const sent: Array> = []; + const logger = { info: vi.fn(), error: vi.fn(), debug: vi.fn(), warn: vi.fn() }; + const cdpAddress = { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-child' }; + const jsConfiguration = { type: 'pwa-node', name: 'child.js [4242]', __pendingTargetId: 'a1b2c3d4e5f60718293a4b5c' }; + const jsReport = { targetId: 'a1b2c3d4e5f60718293a4b5c', name: 'child.js [4242]', configuration: jsConfiguration }; + const STEP = { threadId: 1 }; + let root: ReturnType; + let childClient: ReturnType; + let cdpClients: FakeCdpClient[]; + let connections: ChildConnections; + + /** The child's events the parent process was sent, in order. */ + const childEvents = () => + sent.filter((m) => m.type === 'dapEvent' && m.sessionId === 'child-1').map((m) => ({ event: m.event, body: m.body })); + + function build(setup: StepperSetup = {}): void { + sent.length = 0; + cdpClients = []; + root = createMockDapClient(); + childClient = createMockDapClient(); + childClient.sendRequest.mockImplementation(async (command: string) => { + if (command === 'requestCDPProxy') { + return { body: cdpAddress }; + } + if (command === 'stackTrace') { + // js-debug's frame for the pause, unmarked: program code. + return { success: true, body: { stackFrames: [{ id: 1, name: 'f', line: 3, column: 1 }] } }; + } + return { body: {} }; + }); + let resolveAttach: () => void = () => undefined; + const connectionManager = { + initializeSession: vi.fn(async () => ({ supportsConfigurationDoneRequest: true })), + sendAttachRequest: vi.fn(() => new Promise((resolve) => { resolveAttach = resolve; })), + setExceptionBreakpoints: vi.fn(async () => ({ body: {} })), + setBreakpoints: vi.fn(async () => ({ body: { breakpoints: [] } })), + sendConfigurationDone: vi.fn(async () => { resolveAttach(); }), + disconnect: vi.fn(async () => {}) + }; + connections = new ChildConnections({ + messageSender: { send: (message: unknown) => { sent.push(message as Record); } }, + logger, + cdpClientFactory: () => { + const cdp = new FakeCdpClient(); + cdpClients.push(cdp); + return cdp as unknown as CdpProxyClient; + }, + adoption: { + dapClientFactory: { create: vi.fn(() => childClient) } as unknown as IDapClientFactory, + connectionManager: connectionManager as unknown as ChildAdoptionDeps['connectionManager'], + policy: setup.policy ?? JsDebugAdapterPolicy, + host: '127.0.0.1', + port: 9229, + adapterId: 'pwa-node', + breakOnExceptions: 'none', + ...(setup.launchConfig ? { launchConfig: setup.launchConfig as never } : {}), + ...(setup.rootSteps ? { stepsThroughSkippedCode: setup.rootSteps } : {}) + } + }); + connections.attach(root, 'js-root'); + } + + /** Report a child on the root and adopt it as `child-1`. */ + async function adoptChild(reported: { request: DebugProtocol.Request; report: typeof jsReport | typeof report } = { + request: { seq: 7, type: 'request', command: 'startDebugging', arguments: { request: 'launch', configuration: jsConfiguration } }, + report: jsReport + }): Promise { + root.emit('child-report', reported); + const reportId = sent.filter((m) => m.status === 'child_reported').at(-1)!.reportId as string; + const adopting = connections.adopt('child-1', { reportId, breakpoints: [] }); + await new Promise((resolve) => setImmediate(resolve)); + childClient.emit('initialized'); + await adopting; + } + + /** The stepper is opened after the adoption answers: wait until it is listening on the child's socket. */ + async function stepperOnItsSocket(): Promise { + await vi.waitFor(() => expect(cdpClients[0]?.sent).toContain('Debugger.enable')); + return cdpClients[0]; + } + + /** An adopted child whose stepper is on its socket and has seen V8 pause in program code. */ + async function pausedChild(setup: StepperSetup = { rootSteps: () => true }): Promise { + build(setup); + await adoptChild(); + const cdp = await stepperOnItsSocket(); + cdp.paused('other', 1); + return cdp; + } + + it("opens the stepper on the child's own CDP socket, and it serves the child's steps", async () => { + build({ rootSteps: () => true }); + await adoptChild(); + const cdp = await stepperOnItsSocket(); + + // The socket is the one js-debug hands out for this target, subscribed to V8's pauses. + expect(childClient.sendRequest).toHaveBeenCalledWith('requestCDPProxy', {}, 5000); + expect(cdpClients).toHaveLength(1); + expect(cdp.connectedTo).toEqual(cdpAddress); + expect(cdp.sent).toEqual(['JsDebug.subscribe', 'Debugger.enable']); + // Running, there is nothing to step from: the request is the adapter's. + expect(connections.stepRequest('child-1', 'next', STEP)).toBeNull(); + + cdp.paused('other', 1); + const stepped = connections.stepRequest('child-1', 'next', STEP); + + expect(stepped).not.toBeNull(); + await expect(stepped).resolves.toMatchObject({ type: 'response', command: 'next', success: true }); + // One engine step over the CDP socket; js-debug is never sent the `next`. + expect(cdp.sent).toContain('Debugger.stepOver'); + expect(childClient.sendRequest).not.toHaveBeenCalledWith('next', expect.anything(), expect.anything()); + // Not a step, or not a session of this worker: the adapter's as it is. + expect(connections.stepRequest('child-1', 'evaluate', { expression: 'x' })).toBeNull(); + expect(connections.stepRequest('nobody', 'next', STEP)).toBeNull(); + }); + + it('opens no stepper for a child of an adapter that does its own stepping', async () => { + build({ policy: PythonAdapterPolicy, rootSteps: () => true }); + await adoptChild({ request: startDebugging(7), report }); + + expect(connections.has('child-1')).toBe(true); + expect(childClient.sendRequest).not.toHaveBeenCalledWith('requestCDPProxy', expect.anything(), expect.anything()); + expect(cdpClients).toHaveLength(0); + expect(connections.stepRequest('child-1', 'next', STEP)).toBeNull(); + }); + + // The child's stepper takes the root's choice over: the root's own start + // request (a launch's or an attach's `smartStep`), and the launch + // configuration only when the root cannot say. + it.each<[string, StepperSetup, boolean]>([ + ['the root steps through skipped code and the configuration has no smartStep (an attach root)', { rootSteps: () => true, launchConfig: { request: 'attach', port: 9229 } }, true], + ['the root does not, though the configuration asked for smartStep', { rootSteps: () => false, launchConfig: { smartStep: true } }, false], + ['the root cannot say and the configuration asked for smartStep', { rootSteps: () => undefined, launchConfig: { smartStep: true } }, true], + ['the root cannot say and the configuration did not ask', { rootSteps: () => undefined, launchConfig: { smartStep: false } }, false], + ['nothing is wired to ask the root and the configuration asked for smartStep', { launchConfig: { smartStep: true } }, true], + ['nothing is wired to ask the root and there is no configuration', {}, false] + ])("takes the session's choice from the root: %s", async (_case, setup, serves) => { + await pausedChild(setup); + + const stepped = connections.stepRequest('child-1', 'next', STEP); + + expect(stepped !== null).toBe(serves); + await stepped; + }); + + it("withholds the child's stopped and continued events while a step is in flight, and reports one stopped for the step", async () => { + const cdp = await pausedChild(); + await connections.stepRequest('child-1', 'next', STEP); + + // V8 resumes and lands on the next line; js-debug reports both, the + // landing as a pause it did not ask for. + cdp.resumed(); + childClient.emit('continued', { threadId: 1, allThreadsContinued: false }); + cdp.paused('step', 2); + childClient.emit('stopped', { reason: 'pause', description: 'Paused on debugger statement', threadId: 1 }); + await vi.waitFor(() => expect(childEvents()).not.toHaveLength(0)); + + // One `stopped`, the stepper's, under the child's session; nothing of js-debug's. + expect(childEvents()).toEqual([ + { event: 'stopped', body: expect.objectContaining({ reason: 'step', threadId: 1 }) } + ]); + + // With no step in flight the child's events are forwarded as they are. + sent.length = 0; + childClient.emit('continued', { threadId: 1, allThreadsContinued: true }); + childClient.emit('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + expect(childEvents()).toEqual([ + { event: 'continued', body: { threadId: 1, allThreadsContinued: true } }, + { event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] } } + ]); + }); + + it('a request that resumes the child ends a step in flight; any other request leaves it', async () => { + await pausedChild(); + await connections.stepRequest('child-1', 'next', STEP); + + await connections.beforeRequest('child-1', 'threads'); + childClient.emit('stopped', { reason: 'pause', threadId: 1 }); + // Still the step's: withheld. + expect(childEvents()).toEqual([]); + + await connections.beforeRequest('child-1', 'continue'); + childClient.emit('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + // The step was given up: the stop is the program's own. + expect(childEvents()).toEqual([ + { event: 'stopped', body: { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] } } + ]); + // A session this worker does not know has nothing to end. + await expect(connections.beforeRequest('nobody', 'continue')).resolves.toBeUndefined(); + }); + + it("close() takes the stepper off the child's CDP socket and closes the socket", async () => { + const cdp = await pausedChild(); + expect(cdp.listenerCount('cdp-event')).toBe(1); + + await connections.close('child-1', { terminateDebuggee: true }); + + // By close() itself: this client never reports its connection closed. + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(cdp.disposed).toBe(true); + }); + + it("a child connection that closes by itself takes its stepper and CDP socket down with it", async () => { + const cdp = await pausedChild(); + expect(cdp.listenerCount('cdp-event')).toBe(1); + + childClient.emit('close'); + + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(cdp.disposed).toBe(true); + expect(connections.has('child-1')).toBe(false); + }); + + it('disposes the child\'s CDP socket when subscribe or Debugger.enable fails after connect', async () => { + build({ rootSteps: () => true }); + const origFactory = (connections as unknown as { options: { cdpClientFactory?: () => CdpProxyClient } }).options.cdpClientFactory!; + (connections as unknown as { options: { cdpClientFactory?: () => CdpProxyClient } }).options.cdpClientFactory = () => { + const cdp = origFactory() as unknown as FakeCdpClient; + cdp.send = async (method: string): Promise => { + cdp.sent.push(method); + if (method === 'Debugger.enable') { + throw new Error('Debugger.enable failed'); + } + return {}; + }; + return cdp as unknown as CdpProxyClient; + }; + + await adoptChild(); + await vi.waitFor(() => expect(cdpClients[0]?.disposed).toBe(true)); + + expect(cdpClients[0].listenerCount('cdp-event')).toBe(0); + expect(connections.stepRequest('child-1', 'next', STEP)).toBeNull(); + }); + + it('does not open a CDP socket when the child closes while requestCDPProxy is still in flight', async () => { + build({ rootSteps: () => true }); + let resolveProxy!: (value: unknown) => void; + childClient.sendRequest.mockImplementation(async (command: string) => { + if (command === 'requestCDPProxy') { + return new Promise((resolve) => { resolveProxy = resolve; }); + } + return { body: {} }; + }); + + await adoptChild(); + await vi.waitFor(() => expect(resolveProxy).toBeDefined()); + await connections.close('child-1', { terminateDebuggee: true }); + resolveProxy({ body: cdpAddress }); + await new Promise((resolve) => setImmediate(resolve)); + + expect(cdpClients).toHaveLength(0); + }); +}); diff --git a/tests/proxy/child-session-manager.test.ts b/tests/proxy/child-session-manager.test.ts index f92c7923..ed81df4d 100644 --- a/tests/proxy/child-session-manager.test.ts +++ b/tests/proxy/child-session-manager.test.ts @@ -9,6 +9,7 @@ import type { AdapterPolicy, ParentStart, ReverseRequestResult } from '@debugmcp import { JsDebugAdapterPolicy, PythonAdapterPolicy, DefaultAdapterPolicy } from '@debugmcp/shared'; import { ChildSessionManager } from '../../src/proxy/child-session-manager.js'; import type { CdpFunctionBreakpointBridge } from '../../src/proxy/cdp-function-breakpoint-bridge.js'; +import type { CdpProxyClient } from '../../src/proxy/cdp-proxy-client.js'; // Mock MinimalDapClient class MockMinimalDapClient extends EventEmitter { // Knobs for death-aware adoption tests (issue #248); reset in beforeEach @@ -48,6 +49,13 @@ class MockMinimalDapClient extends EventEmitter { // compiles the breakpoints it buffered on a pending-target connection while // answering attach, and reports their syntax errors then (issue #853) static stderrOnAttach: string[] = []; + // When set, returned verbatim for 'requestCDPProxy': the address js-debug + // hands out for the target's raw CDP socket. Unset, the answer is `{}` and + // the CDP bridge finds no socket to open. + static cdpProxyResponse: unknown | undefined = undefined; + // When set, returned verbatim for 'stackTrace' (js-debug's frames, with its + // marks, for the pause the target is in; the proxy stepper asks, issue #1130) + static stackTraceResponse: unknown | undefined = undefined; host: string; port: number; @@ -114,6 +122,12 @@ class MockMinimalDapClient extends EventEmitter { } return { body: { threads: [{ id: 1, name: 'main' }] } }; } + if (command === 'requestCDPProxy' && MockMinimalDapClient.cdpProxyResponse !== undefined) { + return MockMinimalDapClient.cdpProxyResponse; + } + if (command === 'stackTrace' && MockMinimalDapClient.stackTraceResponse !== undefined) { + return MockMinimalDapClient.stackTraceResponse; + } if (command === 'setBreakpoints') { for (const output of MockMinimalDapClient.stderrOnSetBreakpoints) { this.emit('output', { category: 'stderr', output }); @@ -199,6 +213,8 @@ describe('ChildSessionManager', () => { MockMinimalDapClient.shutdownThrows = false; MockMinimalDapClient.stderrOnSetBreakpoints = []; MockMinimalDapClient.stderrOnAttach = []; + MockMinimalDapClient.cdpProxyResponse = undefined; + MockMinimalDapClient.stackTraceResponse = undefined; }); describe('JavaScript policy (multi-session)', () => { @@ -1601,6 +1617,279 @@ describe('ChildSessionManager', () => { }); }); + /** + * The proxy's own stepper for the program's target (issue #1130): js-debug's + * is kept off, and a session that asked for `smartStep` has its steps served + * over the target's CDP socket, the one the function-breakpoint bridge + * opens. The stepper and the bridge are the real ones here; the socket is + * the fake below, handed in through `cdpClientFactory`, and the test plays + * V8 (the socket's events) and js-debug (the child's DAP events). + */ + describe('the proxy stepper of the program target (issue #1130)', () => { + class FakeCdpClient extends EventEmitter { + readonly sent: string[] = []; + /** Results by method; any other command is answered `{}`. */ + answers: Record = {}; + private open = false; + + async connect(): Promise { + this.open = true; + } + + async send(method: string): Promise { + this.sent.push(method); + return this.answers[method] ?? {}; + } + + isConnected(): boolean { + return this.open; + } + + dispose(): void { + this.open = false; + } + + /** V8 pauses, as CDP reports it: in `fn` (default `f`), which `f` called when it is another. */ + paused(pause: { reason: string; line: number; fn?: string; hitBreakpoints?: string[] }): void { + const frame = (functionName: string, lineNumber: number) => + ({ functionName, location: { scriptId: '1', lineNumber, columnNumber: 0 } }); + this.emit('cdp-event', 'Debugger.paused', { + reason: pause.reason, + ...(pause.hitBreakpoints ? { hitBreakpoints: pause.hitBreakpoints } : {}), + callFrames: pause.fn ? [frame(pause.fn, pause.line), frame('f', 1)] : [frame('f', pause.line)] + }); + } + + resumed(): void { + this.emit('cdp-event', 'Debugger.resumed', {}); + } + } + + const STEP = { threadId: 1 }; + const dapEvent = (event: string, body: Record): DebugProtocol.Event => ({ seq: 0, type: 'event', event, body }); + /** js-debug's sessions and CDP bridge, with an adapter that does its own stepping. */ + const ownStepperPolicy: AdapterPolicy = { + ...JsDebugAdapterPolicy, + getDapClientBehavior: () => ({ ...JsDebugAdapterPolicy.getDapClientBehavior(), stepsThroughSkippedCode: undefined }) + }; + let cdpClients: FakeCdpClient[]; + + function makeManager(policy: AdapterPolicy = JsDebugAdapterPolicy): ChildSessionManager { + return new ChildSessionManager({ + policy, + host: 'localhost', + port: 9229, + cdpClientFactory: () => { + const cdp = new FakeCdpClient(); + cdpClients.push(cdp); + return cdp as unknown as CdpProxyClient; + } + }); + } + + /** Adopt the program's target: its CDP socket is open when this returns. */ + async function adoptTarget(mgr: ChildSessionManager): Promise<{ child: MockMinimalDapClient; cdp: FakeCdpClient }> { + vi.useFakeTimers(); + try { + const adoption = mgr.createChildSession({ + pendingId: 'stepper-target', + host: 'localhost', + port: 9229, + parentConfig: { type: 'pwa-node' } + }); + await vi.advanceTimersByTimeAsync(20000); + await adoption; + } finally { + vi.useRealTimers(); + } + return { child: MockMinimalDapClient.lastInstance!, cdp: cdpClients[cdpClients.length - 1] }; + } + + /** + * A session that chose to step through skipped code, its target adopted + * and paused in program code. `forwarded` is what the parent connection is + * handed from here on. + */ + async function steppingTarget(): Promise<{ + mgr: ChildSessionManager; + child: MockMinimalDapClient; + cdp: FakeCdpClient; + forwarded: DebugProtocol.Event[]; + }> { + const mgr = makeManager(); + // The start request comes before the target exists. + mgr.setStepThroughSkippedCode(true); + const { child, cdp } = await adoptTarget(mgr); + const forwarded: DebugProtocol.Event[] = []; + mgr.on('childEvent', (evt: DebugProtocol.Event) => forwarded.push(evt)); + cdp.paused({ reason: 'other', line: 1 }); + return { mgr, child, cdp, forwarded }; + } + + beforeEach(() => { + cdpClients = []; + MockMinimalDapClient.cdpProxyResponse = { body: { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-target' } }; + // js-debug's frame for a pause, unmarked: program code. + MockMinimalDapClient.stackTraceResponse = { success: true, body: { stackFrames: [{ id: 1, name: 'f', line: 3, column: 1 }] } }; + }); + + it("serves the target's steps over the CDP socket the bridge opens, once the session chose to step through skipped code", async () => { + const mgr = makeManager(); + // A stepper from the start, not asked for yet. + expect(mgr.isSteppingThroughSkippedCode()).toBe(false); + mgr.setStepThroughSkippedCode(true); + expect(mgr.isSteppingThroughSkippedCode()).toBe(true); + + const { child, cdp } = await adoptTarget(mgr); + // One CDP socket per target: the bridge's, and the stepper listens on it too. + expect(cdpClients).toHaveLength(1); + expect(cdp.listenerCount('cdp-event')).toBe(2); + // Running, there is nothing to step from: the request is the adapter's. + expect(mgr.stepRequest('next', STEP)).toBeNull(); + + cdp.paused({ reason: 'other', line: 1 }); + const stepped = mgr.stepRequest('next', STEP); + + expect(stepped).not.toBeNull(); + await expect(stepped).resolves.toMatchObject({ type: 'response', command: 'next', success: true }); + // One engine step over the CDP socket; js-debug is never sent the `next`. + expect(cdp.sent).toContain('Debugger.stepOver'); + expect(child.requests.map((r) => r.command)).not.toContain('next'); + // Not a step: the adapter's as it is. + expect(mgr.stepRequest('evaluate', { expression: 'x' })).toBeNull(); + }); + + it("leaves the steps to js-debug until the session asks, and again when it stops asking", async () => { + const mgr = makeManager(); + const { cdp } = await adoptTarget(mgr); + cdp.paused({ reason: 'other', line: 1 }); + + // Never asked: plain steps. + expect(mgr.stepRequest('next', STEP)).toBeNull(); + expect(cdp.sent).not.toContain('Debugger.stepOver'); + + mgr.setStepThroughSkippedCode(true); + await mgr.stepRequest('next', STEP); + expect(cdp.sent).toContain('Debugger.stepOver'); + + mgr.setStepThroughSkippedCode(false); + expect(mgr.isSteppingThroughSkippedCode()).toBe(false); + expect(mgr.stepRequest('next', STEP)).toBeNull(); + }); + + it('builds no stepper for a policy whose adapter does its own stepping', async () => { + // No child sessions of this kind at all (Python): nothing to ask, nothing to serve. + const python = makeManager(PythonAdapterPolicy); + python.setStepThroughSkippedCode(true); + expect(python.isSteppingThroughSkippedCode()).toBeUndefined(); + expect(python.stepRequest('next', STEP)).toBeNull(); + await expect(python.beforeChildRequest('continue')).resolves.toBeUndefined(); + + // js-debug's sessions and bridge without the pin: the socket is the bridge's alone. + const ownStepper = makeManager(ownStepperPolicy); + ownStepper.setStepThroughSkippedCode(true); + const { cdp } = await adoptTarget(ownStepper); + cdp.paused({ reason: 'other', line: 1 }); + expect(cdp.listenerCount('cdp-event')).toBe(1); + expect(ownStepper.isSteppingThroughSkippedCode()).toBeUndefined(); + expect(ownStepper.stepRequest('next', STEP)).toBeNull(); + }); + + it("withholds the target's stopped and continued events while a step is in flight, and reports one stopped for the step", async () => { + const { mgr, child, cdp, forwarded } = await steppingTarget(); + await mgr.stepRequest('next', STEP); + + // V8 resumes and lands on the next line; js-debug reports both, the + // landing as a pause it did not ask for. + cdp.resumed(); + child.emit('event', dapEvent('continued', { threadId: 1, allThreadsContinued: false })); + cdp.paused({ reason: 'step', line: 2 }); + child.emit('event', dapEvent('stopped', { reason: 'pause', description: 'Paused on debugger statement', threadId: 1 })); + await vi.waitFor(() => expect(forwarded).not.toHaveLength(0)); + await mgr.flushEvents(); + + // One `stopped`, the stepper's; nothing of js-debug's. + expect(forwarded).toEqual([ + expect.objectContaining({ event: 'stopped', body: expect.objectContaining({ reason: 'step', threadId: 1 }) }) + ]); + + // With no step in flight the target's events are forwarded as they are. + forwarded.length = 0; + const resumed = dapEvent('continued', { threadId: 1, allThreadsContinued: true }); + const breakpointStop = dapEvent('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + child.emit('event', resumed); + child.emit('event', breakpointStop); + await mgr.flushEvents(); + expect(forwarded).toEqual([resumed, breakpointStop]); + }); + + it('a request that resumes the target ends a step in flight; any other request leaves it', async () => { + const { mgr, child, forwarded } = await steppingTarget(); + await mgr.stepRequest('next', STEP); + + await mgr.beforeChildRequest('threads'); + child.emit('event', dapEvent('stopped', { reason: 'pause', threadId: 1 })); + await mgr.flushEvents(); + // Still the step's: withheld. + expect(forwarded).toEqual([]); + + await mgr.beforeChildRequest('continue'); + const breakpointStop = dapEvent('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + child.emit('event', breakpointStop); + await mgr.flushEvents(); + // The step was given up: the stop is the program's own. + expect(forwarded).toEqual([breakpointStop]); + }); + + it("hands the stepper's own report to the function-breakpoint bridge like any stop of the target", async () => { + const { mgr, child, cdp, forwarded } = await steppingTarget(); + cdp.answers = { + 'Runtime.evaluate': { result: { type: 'function', objectId: 'greet-object' } }, + 'Debugger.setBreakpointOnFunctionCall': { breakpointId: 'fn-call:1' } + }; + const { breakpoints: [armed] } = await mgr.syncFunctionBreakpoints([{ name: 'greet' }]); + expect(armed).toMatchObject({ verified: true }); + await mgr.stepRequest('next', STEP); + + // The step runs into the armed function: V8 pauses on the bridge's + // breakpoint, which js-debug reports as a breakpoint that names none. + // The step ends there, and the stop the stepper hands on is that one. + cdp.resumed(); + cdp.paused({ reason: 'other', line: 10, fn: 'greet', hitBreakpoints: ['fn-call:1'] }); + child.emit('event', dapEvent('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [] })); + await vi.waitFor(() => expect(forwarded).not.toHaveLength(0)); + await mgr.flushEvents(); + + // Through the bridge: named as the function breakpoint it is. + expect(forwarded).toHaveLength(1); + expect(forwarded[0]).toMatchObject({ + event: 'stopped', + body: { reason: 'function breakpoint', threadId: 1, hitBreakpointIds: [armed.id] } + }); + }); + + it("takes the stepper off the target's CDP socket when the target's connection closes", async () => { + const { mgr, child, cdp } = await steppingTarget(); + expect(cdp.listenerCount('cdp-event')).toBe(2); + + child.emit('close'); + + // The bridge's listener and the stepper's are both gone. + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(mgr.stepRequest('next', STEP)).toBeNull(); + }); + + it("takes the stepper off the target's CDP socket on shutdown", async () => { + const { mgr, cdp } = await steppingTarget(); + expect(cdp.listenerCount('cdp-event')).toBe(2); + + await mgr.shutdown(); + + expect(cdp.listenerCount('cdp-event')).toBe(0); + expect(mgr.stepRequest('next', STEP)).toBeNull(); + }); + }); + describe('adoption edges and the child-safe policy (coverage sprint)', () => { const childConfig = { pendingId: 'edge-pending-1', diff --git a/tests/proxy/dap-proxy-worker-child-sessions.test.ts b/tests/proxy/dap-proxy-worker-child-sessions.test.ts index 50275a6c..ae9dcaf3 100644 --- a/tests/proxy/dap-proxy-worker-child-sessions.test.ts +++ b/tests/proxy/dap-proxy-worker-child-sessions.test.ts @@ -66,16 +66,19 @@ describe('DapProxyWorker child sessions (issue #1081)', () => { adapterCommand: { command: 'python', args: ['-m', 'debugpy.adapter'] } }; - async function connectUnder(policy: typeof PythonAdapterPolicy | typeof JsDebugAdapterPolicy): Promise { + async function connectUnder( + policy: typeof PythonAdapterPolicy | typeof JsDebugAdapterPolicy, + init: ProxyInitPayload = payload + ): Promise { (worker as any).logger = mockLogger; (worker as any).processManager = processStub; (worker as any).connectionManager = connectionStub; (worker as any).adapterPolicy = policy; (worker as any).adapterState = policy.createInitialState(); - (worker as any).currentInitPayload = payload; - (worker as any).currentSessionId = payload.sessionId; + (worker as any).currentInitPayload = init; + (worker as any).currentSessionId = init.sessionId; (worker as any).state = ProxyState.INITIALIZING; - await (worker as any).startAdapterAndConnect(payload); + await (worker as any).startAdapterAndConnect(init); } const statuses = (status: string): StatusMessage[] => @@ -412,4 +415,147 @@ describe('DapProxyWorker child sessions (issue #1081)', () => { expect(processStub.shutdown).toHaveBeenCalledTimes(1); expect(responseTo('failed-adopt')).toMatchObject({ success: false, sessionId: 'child-1', error: 'child exited during attach' }); }); + + /** + * The proxy's own stepper for a js-debug child (issue #1130), through the + * worker's real ChildConnections and the real stepper. The worker has no + * seam for the child's CDP socket (ChildConnections opens a CdpProxyClient, + * which opens the Node global WebSocket), so the global is the fake here: + * it answers every command, and the test sends V8's events. + */ + describe("a js-debug child's steps and its proxy stepper (issue #1130)", () => { + class FakeCdpSocket { + static opened: FakeCdpSocket[] = []; + onopen: (() => void) | null = null; + onmessage: ((event: { data: unknown }) => void) | null = null; + onclose: (() => void) | null = null; + onerror: ((event: { message?: string }) => void) | null = null; + readonly sent: string[] = []; + + constructor(readonly url: string) { + FakeCdpSocket.opened.push(this); + queueMicrotask(() => this.onopen?.()); + } + + send(data: string): void { + const { id, method } = JSON.parse(data) as { id: number; method: string }; + this.sent.push(method); + queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ id, result: {} }) })); + } + + close(): void { + this.onclose?.(); + } + + /** V8 pauses in `f`, as CDP reports it. */ + paused(): void { + this.onmessage?.({ + data: JSON.stringify({ + method: 'Debugger.paused', + params: { reason: 'other', callFrames: [{ functionName: 'f', location: { scriptId: '1', lineNumber: 1, columnNumber: 0 } }] } + }) + }); + } + } + + const forkConfiguration = { type: 'pwa-node', name: 'child.js [7]', __pendingTargetId: 'fork-1' }; + + /** The child's `stopped` events the parent process was sent. */ + const childStops = (): unknown[] => + send.mock.calls + .map(([m]) => m) + .filter((m): m is DapEventMessage => m.type === 'dapEvent' && m.sessionId === 'child-1' && m.event === 'stopped') + .map((m) => m.body); + + beforeEach(() => { + FakeCdpSocket.opened = []; + vi.stubGlobal('WebSocket', FakeCdpSocket); + childClient.sendRequest.mockImplementation(async (command: string) => + command === 'requestCDPProxy' + ? { body: { host: '127.0.0.1', port: 9333, path: '/cdp-of-the-fork' } } + : { type: 'response', success: true, command, body: {} }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + /** + * A js-debug root, a fork adopted as `child-1`, its stepper on the fork's + * CDP socket, and V8 paused in the fork's program code. + */ + async function pausedFork(start: { rootSteps?: boolean; smartStep?: boolean }): Promise { + if (start.rootSteps !== undefined) { + // What MinimalDapClient answers from the root's own start request. + rootClient.stepsThroughSkippedCode = () => start.rootSteps; + } + await connectUnder( + JsDebugAdapterPolicy, + start.smartStep === undefined ? payload : { ...payload, launchConfig: { smartStep: start.smartStep } } + ); + rootClient.emit('child-report', { + request: { seq: 9, type: 'request', command: 'startDebugging', arguments: { request: 'launch', configuration: forkConfiguration } }, + report: { targetId: 'fork-1', name: 'child.js [7]', configuration: forkConfiguration } + }); + const reportId = statuses('child_reported')[0].reportId as string; + const adopting = worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId: 'adopt-fork', dapCommand: CHILD_ADOPT_COMMAND, dapArgs: { reportId } }); + await new Promise((resolve) => setImmediate(resolve)); + childClient.emit('initialized'); + await adopting; + // The stepper is opened after the adoption answers. + await vi.waitFor(() => expect(FakeCdpSocket.opened[0]?.sent).toContain('Debugger.enable')); + const socket = FakeCdpSocket.opened[0]; + socket.paused(); + return socket; + } + + const stepTheFork = (requestId: string): Promise => + worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId, dapCommand: 'next', dapArgs: { threadId: 1 } }); + + // The child's stepper takes over the choice of the root's own start + // request, which the root's client answers; the init payload's launch + // configuration only when that client cannot say. + it.each<[string, { rootSteps?: boolean; smartStep?: boolean }]>([ + ['the root steps through skipped code (an attach root: no smartStep in the payload)', { rootSteps: true }], + ["the root's client cannot say and the payload's launch configuration asked for smartStep", { smartStep: true }] + ])("the child's stepper serves its step over the child's CDP socket when %s", async (_case, start) => { + const socket = await pausedFork(start); + expect(socket.url).toBe('ws://127.0.0.1:9333/cdp-of-the-fork'); + + await stepTheFork('step-1'); + + // One engine step over CDP, answered on the child's envelope; js-debug is never sent the `next`. + expect(socket.sent).toContain('Debugger.stepOver'); + expect(childClient.sendRequest).not.toHaveBeenCalledWith('next', expect.anything(), expect.anything()); + expect(responseTo('step-1')).toMatchObject({ success: true, sessionId: 'child-1', response: { command: 'next', success: true } }); + }); + + it("the child's step is js-debug's own when the root does not step through skipped code, whatever the payload asked", async () => { + const socket = await pausedFork({ rootSteps: false, smartStep: true }); + + await stepTheFork('step-2'); + + expect(childClient.sendRequest).toHaveBeenCalledWith('next', { threadId: 1 }, undefined); + expect(socket.sent).not.toContain('Debugger.stepOver'); + expect(responseTo('step-2')).toMatchObject({ success: true, sessionId: 'child-1' }); + }); + + it("any other request for the child passes its stepper first: a continue ends a step in flight, an evaluate does not", async () => { + await pausedFork({ rootSteps: true }); + await stepTheFork('step-3'); + + await worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId: 'eval-3', dapCommand: 'evaluate', dapArgs: { expression: 'x' } }); + childClient.emit('stopped', { reason: 'pause', threadId: 1 }); + // Still the step's own pause: withheld. + expect(childClient.sendRequest).toHaveBeenCalledWith('evaluate', { expression: 'x' }, undefined); + expect(childStops()).toEqual([]); + + await worker.handleCommand({ cmd: 'dap', sessionId: 'child-1', requestId: 'continue-3', dapCommand: 'continue', dapArgs: { threadId: 1 } }); + childClient.emit('stopped', { reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }); + // The step was given up before the continue went out: this stop is the program's own. + expect(childClient.sendRequest).toHaveBeenCalledWith('continue', { threadId: 1 }, undefined); + expect(childStops()).toEqual([{ reason: 'breakpoint', threadId: 1, hitBreakpointIds: [4] }]); + expect(responseTo('continue-3')).toMatchObject({ success: true, sessionId: 'child-1' }); + }); + }); }); diff --git a/tests/proxy/dap-proxy-worker-live-update.test.ts b/tests/proxy/dap-proxy-worker-live-update.test.ts index fdfdbec0..3b6b30a7 100644 --- a/tests/proxy/dap-proxy-worker-live-update.test.ts +++ b/tests/proxy/dap-proxy-worker-live-update.test.ts @@ -9,7 +9,14 @@ import path from 'path'; import { describe, it, expect, beforeEach, vi } from 'vitest'; import { DefaultAdapterPolicy, type AdapterPolicy } from '@debugmcp/shared'; import { DapProxyWorker } from '../../src/proxy/dap-proxy-worker.js'; -import type { DapProxyDependencies, ProxyInitPayload } from '../../src/proxy/dap-proxy-interfaces.js'; +import { + PROXY_STEP_LEFT_STACK_EVENT, + PROXY_STEP_RECORD_EVENTS, + PROXY_STEP_WALK_ENDED_EVENT, + PROXY_STEP_WALK_STARTED_EVENT, + type DapProxyDependencies, + type ProxyInitPayload +} from '../../src/proxy/dap-proxy-interfaces.js'; import { createMockDapClient } from '../test-utils/mocks/dap-client.js'; import { createMockLogger } from '../test-utils/helpers/test-dependencies.js'; import { createMockFileSystem, createMockProcessSpawner } from '../test-utils/mocks/dap-proxy-doubles.js'; @@ -111,6 +118,43 @@ describe('DapProxyWorker live update events and resumes (issue #876)', () => { expect(forwardedEvents()).toEqual([]); }); + // Not a live-update event, forwarded the same way: the proxy stepper's + // record that it ended a step by resuming the program (issue #1130, I3), + // which the pending step's answer reads. + it("forwards the proxy stepper's left-stack record to the session, with its body", async () => { + await configure({ ...DefaultAdapterPolicy, name: 'plain' } as AdapterPolicy); + mockDapClient.emit(PROXY_STEP_LEFT_STACK_EVENT, { threadId: 1 }); + expect(forwardedEvents()).toEqual([PROXY_STEP_LEFT_STACK_EVENT]); + expect(sent().find((m) => m.event === PROXY_STEP_LEFT_STACK_EVENT)?.body).toEqual({ threadId: 1 }); + }); + + // Round 3, decision 2: the records of a step_into's walk through skipped code ride the same way. + it("forwards the proxy stepper's walk records to the session, in order, with their bodies", async () => { + await configure({ ...DefaultAdapterPolicy, name: 'plain' } as AdapterPolicy); + mockDapClient.emit(PROXY_STEP_WALK_STARTED_EVENT, { threadId: 1, stepLimit: 512 }); + mockDapClient.emit(PROXY_STEP_WALK_ENDED_EVENT, { threadId: 1, why: 'limit' }); + expect(forwardedEvents()).toEqual([PROXY_STEP_WALK_STARTED_EVENT, PROXY_STEP_WALK_ENDED_EVENT]); + expect(sent().find((m) => m.event === PROXY_STEP_WALK_STARTED_EVENT)?.body).toEqual({ threadId: 1, stepLimit: 512 }); + }); + + // Review 8 (K02): the records are the proxy's own, for the session; an IDE + // on the read-only mirror sees the adapter's events only. + it("keeps the proxy stepper's records off the mirror, and broadcasts the adapter's own events there", async () => { + await configure({ ...DefaultAdapterPolicy, name: 'plain' } as AdapterPolicy); + const broadcastEvent = vi.fn(); + const w = worker as unknown as { mirrorServer: unknown; mirrorEventForwarder: (evt: unknown) => void }; + w.mirrorServer = { broadcastEvent }; + const records = [PROXY_STEP_LEFT_STACK_EVENT, PROXY_STEP_WALK_STARTED_EVENT, PROXY_STEP_WALK_ENDED_EVENT]; + for (const event of records) { + w.mirrorEventForwarder({ seq: 0, type: 'event', event, body: { threadId: 1 } }); + } + expect(broadcastEvent).not.toHaveBeenCalled(); + // One list names them for the worker and the mirror alike. + expect([...PROXY_STEP_RECORD_EVENTS].sort()).toEqual([...records].sort()); + w.mirrorEventForwarder({ seq: 0, type: 'event', event: 'output', body: { output: 'x' } }); + expect(broadcastEvent).toHaveBeenCalledWith('output', { output: 'x' }); + }); + it("clears the last stop when one of the feature's resume commands goes out", async () => { await configure(liveUpdatePolicy()); mockDapClient.emit('stopped', { reason: 'breakpoint', threadId: 1 }); diff --git a/tests/proxy/js-stepper.test.ts b/tests/proxy/js-stepper.test.ts new file mode 100644 index 00000000..29f50785 --- /dev/null +++ b/tests/proxy/js-stepper.test.ts @@ -0,0 +1,1863 @@ +/** + * The proxy's own JavaScript stepper (issue #1130), against a scripted V8 + * and a scripted js-debug. + * + * The engine below plays what was measured through the real pair (the spike + * notes of the issue): every step command is answered, then `Debugger.resumed` + * and the next scripted `Debugger.paused` arrive; js-debug marks frame 0 of a + * `stackTrace` answer `deemphasize` for skipped code; and for every pause it + * keeps it sends one DAP `stopped` (reason `pause` for a step it did not + * request, `breakpoint` for a breakpoint hit) a moment later, and one + * `continued` per resume. + */ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { EventEmitter } from 'events'; +import * as winston from 'winston'; +import type { DebugProtocol } from '@vscode/debugprotocol'; +import { JsStepper, DEFAULT_JS_STEPPER_TUNABLES, type JsStepperTunables } from '../../src/proxy/js-stepper.js'; +import { + PROXY_STEP_LEFT_STACK_EVENT, + PROXY_STEP_WALK_ENDED_EVENT, + PROXY_STEP_WALK_STARTED_EVENT +} from '../../src/proxy/dap-proxy-interfaces.js'; +import { ErrorMessages } from '../../src/utils/error-messages.js'; + +interface Frame { + fn: string; + script?: string; + /** 0-based line of the frame's position. */ + line: number; + col?: number; + /** js-debug marks it skipped code. */ + skipped?: boolean; + /** The mark's wording, js-debug's `source.origin`: "Skipped by skipFiles" (the default) or "Skipped by smartStep". */ + origin?: string; + /** + * The source js-debug names for the frame. By default: `/…` + * for a `node:` script (with a sourceReference, as js-debug answers for + * Node's own modules), `/app/