diff --git a/changelog.d/1150-session-tree-truth-and-turns.fixed.md b/changelog.d/1150-session-tree-truth-and-turns.fixed.md new file mode 100644 index 00000000..20422667 --- /dev/null +++ b/changelog.d/1150-session-tree-truth-and-turns.fixed.md @@ -0,0 +1 @@ +`start_debugging` and `restart_debugging` now report an already-paused child session directly via `pausedChild` (including its `sessionId`, `location`, `context`, and stop `snapshot`) instead of claiming no breakpoint was reached yet, while keeping tree-wide breakpoint binding, child-debugging opt-out notes, and grandchild release counts truthful across the session tree (#1150). diff --git a/changelog.d/1221-child-release-confirmation.fixed.md b/changelog.d/1221-child-release-confirmation.fixed.md new file mode 100644 index 00000000..4ce15d02 --- /dev/null +++ b/changelog.d/1221-child-release-confirmation.fixed.md @@ -0,0 +1 @@ +Failed child-session adoptions now count in `childrenReleased` and state that the child runs undebugged only when the debug adapter confirms the fallback release; unconfirmed releases are disclosed separately without claiming the child continues running (#1221). diff --git a/changelog.d/1252-js-outer-block-locals.fixed.md b/changelog.d/1252-js-outer-block-locals.fixed.md new file mode 100644 index 00000000..980243a1 --- /dev/null +++ b/changelog.d/1252-js-outer-block-locals.fixed.md @@ -0,0 +1 @@ +JavaScript stop snapshots and `get_local_variables` no longer merge outer lexical `Block` scopes listed after a function's `Local` scope when the function has locals of its own, preventing Vite/Vitest module-wrapper declarations from crowding out method locals (#1252). diff --git a/docs/architecture/session-tree.md b/docs/architecture/session-tree.md index 9b7be53a..4444efd3 100644 --- a/docs/architecture/session-tree.md +++ b/docs/architecture/session-tree.md @@ -129,8 +129,14 @@ exists). The agent then uses `sessionId` for inspection, stepping and continuing ([#849](https://github.com/debugmcp/mcp-debugger/issues/849)) is unchanged. - Every answer on a session that has children carries `children: [{ sessionId, name, state, parentSessionId }]`, the paused and the `pending: true` answers included, so a caller always sees what else is live or - paused and what to wait on next. The `start_debugging` answer carries the same list when a child - was adopted during the launch hold. + paused and what to wait on next. The `start_debugging` and `restart_debugging` answers carry the + same list when a child was adopted during the launch hold — and when an adopted child is already + genuinely `paused` while the launched root is `running`, they end the hold after a short settle + grace, name that paused child directly in `message` instead of claiming no breakpoint was reached + yet, and include `pausedChild: { sessionId, name, state: "paused", reason, location?, threadId?, + context?, note?, snapshot? }` so the agent can inspect, step, or continue the child immediately + without spending an extra `wait_for_stop` turn (issue #1150; `pausedChild` is never set when a + child is in `error` or `stopped`). - A `wait_for_stop` on a child answers for that child and its own descendants only. This was decided over the per-session alternative (each wait answers only its own stops): that @@ -313,14 +319,19 @@ Two bounds keep that sane: - A per-tree cap on live child sessions (`DEBUG_MCP_MAX_CHILD_SESSIONS`, default 32; `0` disables child-session adoption). It excludes js-debug's mandatory first target, which implements the root session and must still be adopted for launch to complete. Beyond the cap the release lever - runs (the child runs undebugged) and the parent's next answer says so (`childrenReleased: n`). - The count is never left unexplained (issue #1137): the cause of each release is recorded with it - (`releasedChildCauses`: child sessions off, the cap, a proxy that cannot host children, a failed - adoption), and every launch, restart and wait answer that carries the number ends its message - with one sentence built from the same record (`describeReleasedChildren`, + runs (the child runs undebugged) and the parent's and every ancestor's next answer says so + (`childrenReleased: n`, subtree-scoped so grandchild releases count on the root as well as on the + child, issue #1150). The count is never left unexplained (issue #1137): the cause of each + confirmed release is recorded with it (`releasedChildCauses`: child sessions off, the cap, a + proxy that cannot host children, a failed adoption whose fallback release the adapter confirmed), + and every launch, restart and wait answer that carries the number ends its message with one + sentence built from the same record (`describeReleasedChildren`, `src/session/execution/tree-settle.ts`): how many, that they run undebugged, why — naming `DEBUG_MCP_MAX_CHILD_SESSIONS` when it decided — and that a breakpoint only such a child reaches - will not hit. + will not hit. When a failed adoption's fallback release is **not** confirmed by the debug adapter + (issue #1221), it is not counted in `childrenReleased` and not called "released to run + undebugged"; `describeReleasedChildren` discloses that the child could not be adopted and whether + it continued running is not known. - Ended children stay listed until closed, as above, and leave with their parent. ## Every adapter, surveyed @@ -487,7 +498,13 @@ A child is a session of its own, and what is read about it is read where it is t debugger on clears the run's decision; a child reads that decision as its root does (while the proof by a verified breakpoint stays each session's own, so for a moment the two can answer differently); and a child's exception arming is the live one, where it was a copy - taken at adoption. One thing does not follow: the notes of the root's launch are seeded into + taken at adoption. In addition (issue #1150), `Run` records `treeVerifiedBreakpointIds` whenever + any session in the tree verifies or hits a breakpoint (so the root's end summary marks child-bound + breakpoints `verified: true` in `unhitBreakpoints` and never warns that they "never bound during + this run"), and `childDebuggingOptedOut` when the launch/attach explicitly turned child adoption + off (`subProcess: false` on Python launch, `autoAttachChildProcesses: false` on JavaScript + launch/attach) so end summaries and unbound warnings qualify that child processes ran undebugged. + One thing does not follow: the notes of the root's launch are seeded into the root's output only. The record is mutated in place and not replaced per run, so a child row that outlives its run reads what its root reads; the readers that are new to children are gated on a live state. diff --git a/docs/tool-reference.md b/docs/tool-reference.md index 6a44ead1..3188dfd4 100644 --- a/docs/tool-reference.md +++ b/docs/tool-reference.md @@ -544,7 +544,7 @@ Two things are outside the hold. A `stopOnEntry` launch is answered at its entry A breakpoint set, removed or cleared while a launch is still starting is delivered to the adapter as soon as the program is launched (issue #851). -**Sessions with children** (the session tree, issues #1081 and #1082): when a child session was adopted during the hold (a Python launch — debugpy's sub-process debugging is on by default; `dapLaunchArgs: { subProcess: false }` opts the launch out — where debugpy reports each process the program starts; a JavaScript launch — js-debug's `autoAttachChildProcesses` is on by default; `dapLaunchArgs: { autoAttachChildProcesses: false }` opts the launch out — where js-debug reports each Node process it forks), the answer carries `children: [{ sessionId, name, state, parentSessionId }]` — every descendant, depth first in adoption order, each with its state and the session that spawned it. `childrenReleased: n` says how many children reported this run were released to run undebugged (beyond `DEBUG_MCP_MAX_CHILD_SESSIONS`, or an adoption that failed) — and the `message` of the same answer says what that means and why (issue #1137), e.g. "1 child process was released to run undebugged (child sessions are off: DEBUG_MCP_MAX_CHILD_SESSIONS=0): a breakpoint only it reaches will not hit.", so a pending answer's "has not reached 1 breakpoint(s) yet" is not read as a promise for a breakpoint only the released child could reach — and `childrenClosed: n` that the start tore down a previous live run and closed its children with it. All three sit at the top level beside `pending` and in `data`, and are absent when there is nothing to say, so a session with no children answers as before. The launch answer is about the launched session itself; a child's stop is collected by [`wait_for_stop`](#wait_for_stop), which answers with `sessionId` naming the child. +**Sessions with children** (the session tree, issues #1081, #1082, #1150 and #1221): when a child session was adopted during the hold (a Python launch — debugpy's sub-process debugging is on by default; `dapLaunchArgs: { subProcess: false }` opts the launch out — where debugpy reports each process the program starts; a JavaScript launch — js-debug's `autoAttachChildProcesses` is on by default; `dapLaunchArgs: { autoAttachChildProcesses: false }` opts the launch out — where js-debug reports each Node process it forks), the answer carries `children: [{ sessionId, name, state, parentSessionId }]` — every descendant, depth first in adoption order, each with its state and the session that spawned it. When an adopted child is already genuinely `paused` while the launched root is `running`, the hold ends after a short settle grace (~50 ms), `message` names the paused child session directly instead of saying no breakpoint was reached yet, and `pausedChild: { sessionId, name, state: "paused", reason, location?, threadId?, context?, note?, snapshot? }` delivers that child's stop landing and bounded snapshot in the same call so you can inspect, step, or continue `pausedChild.sessionId` immediately without spending an extra `wait_for_stop` turn (`pausedChild` is never set for a child in `error` or `stopped`). `childrenReleased: n` says how many children reported anywhere in this session's subtree this run were confirmed released to run undebugged (beyond `DEBUG_MCP_MAX_CHILD_SESSIONS`, or a failed adoption whose fallback release the debug adapter confirmed) — and the `message` of the same answer says what that means and why (issue #1137), e.g. "1 child process was released to run undebugged (child sessions are off: DEBUG_MCP_MAX_CHILD_SESSIONS=0): a breakpoint only it reaches will not hit."; when a failed adoption's fallback release was not confirmed by the adapter (issue #1221), it is not counted in `childrenReleased` and `message` states that whether the child continued running is not known — and `childrenClosed: n` says that the start tore down a previous run and closed its children with it. `children`, `pausedChild`, `childrenReleased` and `childrenClosed` sit at the top level beside `pending` and in `data` (`pausedChild.snapshot` is omitted from `data.pausedChild` just like a root `snapshot`), and are absent when there is nothing to say, so a session with no children answers as before. **JavaScript launch configuration:** Both launch option objects accept js-debug settings; `adapterLaunchConfig` wins when a key appears in both. The effective `stopOnEntry` value controls @@ -587,7 +587,7 @@ See the [JavaScript configuration guide](javascript/README.md#custom-configurati - The sentence distinguishes a clean run (`ran to completion (exit code 0)`), a non-zero exit (`exited with code N`) and a debuggee that reported no code at all (`ended without reporting an exit code` — attach targets, signal-killed debuggees, adapters that send no `exited` event and state the code nowhere else). - `data.exitCode` is present only when the debuggee reported one. `data.unhitBreakpoints` lists every line breakpoint the program ran past (`file`, `line` as bound, `requestedLine` when the adapter moved it, `verified`); logpoints the adapter supports are left out, since they log and run on. Verified line and function breakpoints that were never hit are named in the sentence; breakpoints that never bound keep their #467 `warning`. - When a stop and the exit arrived in the same tick (a breakpoint hit as the program ended), the breakpoints were not all missed: the list is withheld and the sentence names the stop (`after a stop the launch could not report (last stop: breakpoint)`), which `list_debug_sessions` also shows as `lastStop`. -- The same holds for the session's tree (issue #1128): when a child session stopped during the run, the parent can no longer say which breakpoints were missed — each child has its own copy of the breakpoints and its own stops. The list is withheld and the sentence counts the tree's stops instead, every stop the agent could see on a child, whatever its reason (`The program ran to completion (exit code 0). Its child sessions stopped 2 times during this run.`), whether or not the child is still listed. What remains root-only: when children were adopted but none stopped, `unhitBreakpoints[].verified` is the launched process's own flag, so a breakpoint that bound only in a child reads `verified: false` there. +- The same holds for the session's tree (issues #1128, #1150): when a child session stopped during the run, the parent can no longer say which breakpoints were missed — each child has its own copy of the breakpoints and its own stops. The list is withheld and the sentence counts the tree's stops instead, every stop the agent could see on a child, whatever its reason (`The program ran to completion (exit code 0). Its child sessions stopped 2 times during this run.`), whether or not the child is still listed. When children were adopted and none stopped, `unhitBreakpoints[].verified` (and the unbound-at-exit `warning`) reflects whether the breakpoint bound in **any** session of the tree, so a breakpoint that bound only in an adopted child reads `verified: true` and never triggers a false unbound warning; and when child-process debugging was explicitly turned off (`subProcess: false` on a Python launch or `autoAttachChildProcesses: false` on JavaScript), the end summary and any unbound warning qualify that child processes ran undebugged. - `restart_debugging` returns the same fields for a relaunch that ends the same way. **Exit code:** when the debuggee terminates, the exit code reported by the adapter is surfaced as `exitCode` in `list_debug_sessions` (and, for a launch that ended before reporting a pause, as `data.exitCode` above), so a crash (non-zero) is distinguishable from a clean exit. Adapters that never send `exited` still get one where the debugger states the code some other way: js-debug through the launch shim's recorded code (#247), rdbg through the adapter process's own exit status (#258), Delve before 1.27 through its `Process N has exited with status S` console line (#753 — in debug mode Delve prints it only in reply to `disconnect`, so the proxy sends the disconnect before forwarding `terminated`; Delve 1.27+ sends `exited` itself). No line, no code: nothing is guessed. diff --git a/packages/shared/src/interfaces/adapter-policy-js.ts b/packages/shared/src/interfaces/adapter-policy-js.ts index 60117816..3a21f3e3 100644 --- a/packages/shared/src/interfaces/adapter-policy-js.ts +++ b/packages/shared/src/interfaces/adapter-policy-js.ts @@ -714,8 +714,17 @@ export const JsDebugAdapterPolicy = { collectedRefs.push(scope.variablesReference); }; + const firstLocalIndex = frameScopes.findIndex(isLocalScope); const localScopes = frameScopes.filter(isLocalScope); - for (const scope of frameScopes.filter(isLocalLikeScope)) { + // V8 lists inner lexical Block scopes ahead of Local, and enclosing outer + // lexical Block scopes — such as Vite SSR's module wrapper — after Local + // (issue #1252). When Local exists on the frame, only Block scopes inside + // the function (index < firstLocalIndex) belong to the primary merge; outer + // Block scopes join the empty-Local fallback below alongside Closure. + const innerLocalLikeScopes = firstLocalIndex === -1 + ? frameScopes.filter(isLocalLikeScope) + : frameScopes.filter((scope, index) => isLocalScope(scope) || (index < firstLocalIndex && isBlockScope(scope))); + for (const scope of innerLocalLikeScopes) { collect(scope); } // ESM top-level: js-debug gives a `for (let i...)` or `catch (e)` at module @@ -754,7 +763,7 @@ export const JsDebugAdapterPolicy = { // the same frame; try those in usefulness order before the session layer // walks down to a caller. const fallbackGroups: Array<(scope: DebugProtocol.Scope) => boolean> = [ - isClosureScope, + (scope) => isClosureScope(scope) || isBlockScope(scope), isModuleScope ]; for (const matches of fallbackGroups) { diff --git a/packages/shared/tests/unit/adapter-policy-js.spec.ts b/packages/shared/tests/unit/adapter-policy-js.spec.ts index 46ceb3f3..803219fa 100644 --- a/packages/shared/tests/unit/adapter-policy-js.spec.ts +++ b/packages/shared/tests/unit/adapter-policy-js.spec.ts @@ -338,6 +338,50 @@ describe('JsDebugAdapterPolicy', () => { expect(result.scopeRefs).toEqual([100, 200]); }); + it('leaves outer Block scopes listed after Local out of the merge when Local has variables (issue #1252)', () => { + // Vite/Vitest SSR wraps module-level imports and constants in an outer + // lexical Block scope listed after the method's Local scope. + const scopes: Record = { + 1: [ + { name: 'Block', variablesReference: 100, expensive: false }, + { name: 'Local', variablesReference: 200, expensive: false }, + { name: 'Block', variablesReference: 250, expensive: false }, + { name: 'Global', variablesReference: 400, expensive: true }, + ], + }; + const vars: Record = { + 100: [v('innerVar', '1')], + 200: [v('sessionId', "'abc'"), v('childrenClosed', '0')], + 250: [v('UNSET_BREAKPOINT_WARNING_LIMIT', '10'), v('ProxyConfig', 'class ProxyConfig')], + 400: [v('globalThis', '{}')], + }; + + const result = JsDebugAdapterPolicy.extractLocalVariables!([frame], scopes, vars); + + expect(result.variables.map(variable => variable.name)).toEqual(['innerVar', 'sessionId', 'childrenClosed']); + expect(result.scopeRefs).toEqual([100, 200]); + }); + + it('falls back to an outer Block scope listed after Local when Local and inner blocks are empty (issue #1252)', () => { + const scopes: Record = { + 1: [ + { name: 'Local', variablesReference: 100, expensive: false }, + { name: 'Block', variablesReference: 250, expensive: false }, + { name: 'Global', variablesReference: 400, expensive: true }, + ], + }; + const vars: Record = { + 100: [], + 250: [v('loopItem', "'x'")], + 400: [v('globalThis', '{}')], + }; + + const result = JsDebugAdapterPolicy.extractLocalVariables!([frame], scopes, vars); + + expect(result.variables.map(variable => variable.name)).toEqual(['loopItem']); + expect(result.scopeRefs).toEqual([250]); + }); + it("merges a catch (e) binding from a 'Catch Block' scope (issue #558)", () => { const scopes: Record = { 1: [ @@ -479,6 +523,50 @@ describe('JsDebugAdapterPolicy', () => { expect(result.scopeRefs).toEqual([100, 200]); }); + it('leaves outer Block scopes listed after Local out of the merge when Local has variables (issue #1252)', () => { + // Vite/Vitest SSR wraps module-level imports and constants in an outer + // lexical Block scope listed after the method's Local scope. + const scopes: Record = { + 1: [ + { name: 'Block', variablesReference: 100, expensive: false }, + { name: 'Local', variablesReference: 200, expensive: false }, + { name: 'Block', variablesReference: 250, expensive: false }, + { name: 'Global', variablesReference: 400, expensive: true }, + ], + }; + const vars: Record = { + 100: [v('innerVar', '1')], + 200: [v('sessionId', "'abc'"), v('childrenClosed', '0')], + 250: [v('UNSET_BREAKPOINT_WARNING_LIMIT', '10'), v('ProxyConfig', 'class ProxyConfig')], + 400: [v('globalThis', '{}')], + }; + + const result = JsDebugAdapterPolicy.extractLocalVariables!([frame], scopes, vars); + + expect(result.variables.map(variable => variable.name)).toEqual(['innerVar', 'sessionId', 'childrenClosed']); + expect(result.scopeRefs).toEqual([100, 200]); + }); + + it('falls back to an outer Block scope listed after Local when Local and inner blocks are empty (issue #1252)', () => { + const scopes: Record = { + 1: [ + { name: 'Local', variablesReference: 100, expensive: false }, + { name: 'Block', variablesReference: 250, expensive: false }, + { name: 'Global', variablesReference: 400, expensive: true }, + ], + }; + const vars: Record = { + 100: [], + 250: [v('loopItem', "'x'")], + 400: [v('globalThis', '{}')], + }; + + const result = JsDebugAdapterPolicy.extractLocalVariables!([frame], scopes, vars); + + expect(result.variables.map(variable => variable.name)).toEqual(['loopItem']); + expect(result.scopeRefs).toEqual([250]); + }); + it('returns a populated Block-only frame without reaching Global (issue #558)', () => { const scopes: Record = { 1: [ diff --git a/src/proxy/child-connections.ts b/src/proxy/child-connections.ts index 93634864..f884322a 100644 --- a/src/proxy/child-connections.ts +++ b/src/proxy/child-connections.ts @@ -121,12 +121,19 @@ interface ChildConnection { /** Forwarded as-is under the child's session id; `terminated` and `close` have their own handling. */ const FORWARDED_CHILD_EVENTS = ['output', 'stopped', 'continued', 'thread', 'exited', 'breakpoint'] as const; +/** Whether the adapter acknowledged letting a non-adopted child continue running (issue #1221). */ +export type ChildReleaseOutcome = 'confirmed' | 'unconfirmed' | 'closed'; + +const MAX_RECORDED_RELEASE_OUTCOMES = 256; + export class ChildConnections extends EventEmitter { private readonly held = new Map(); /** Adopted child connections by their session id. */ private readonly clients = new Map(); /** Releases own sockets too; shutdown must wait until they have detached. */ private readonly releases = new Set>(); + /** Bounded per-reportId release confirmation outcomes so CHILD_RELEASE_COMMAND can await adopt-failure fallbacks (#1221). */ + private readonly releaseOutcomes = new Map>(); private readonly releaseTimeoutMs: number; private closing = false; /** The policy the connections opened here run (child-safe for an in-session adopter, issue #1082). */ @@ -179,10 +186,37 @@ export class ChildConnections extends EventEmitter { return false; } this.options.logger.info(`[ChildConnections] Releasing child ${held.report.targetId} (${held.report.name}): ${reason}`); - this.giveUp(held, reason); + void this.giveUp(held, reason, reportId); return true; } + /** + * Release a held report — or join the fallback release started by a failed + * `adopt()` — and report whether the debug adapter confirmed letting the + * child process continue running (issue #1221). + */ + async releaseWithConfirmation( + reportId: string, + reason: string + ): Promise<{ held: boolean; released: boolean; closed?: true }> { + const existing = this.releaseOutcomes.get(reportId); + if (existing) { + const outcome = await existing; + return { + held: false, + released: outcome === 'confirmed', + ...(outcome === 'closed' ? { closed: true } : {}) + }; + } + const held = this.takeHeld(reportId); + if (!held) { + return { held: false, released: false }; + } + this.options.logger.info(`[ChildConnections] Releasing child ${held.report.targetId} (${held.report.name}): ${reason}`); + const outcome = await this.giveUp(held, reason, reportId); + return { held: true, released: outcome === 'confirmed' }; + } + /** Release held reports and wait for every throwaway socket before the adapter can be stopped. */ async releaseAllHeld(reason: string): Promise { do { @@ -330,11 +364,17 @@ export class ChildConnections extends EventEmitter { // run on. It is best effort: a target the adapter had not started // yet is not resumed by it, and when nothing acknowledges it the // throwaway attach follows, for a target that is still pending. - this.letGoOnItsConnection(deps, client, held, message); + void this.letGoOnItsConnection(deps, client, held, message, args.reportId); } else { // The report is no longer held, so the server's release command that - // follows finds nothing: let the child go here, by the policy's lever. - this.giveUp(held, `adoption failed: ${message}`); + // follows joins this outcome via `releaseOutcomes`: let the child go + // here, by the policy's lever (including when close() cancelled the + // handshake before the target was bound). + const giveUpOutcome = this.giveUp(held, `adoption failed: ${message}`); + this.recordReleaseOutcome( + args.reportId, + cancelledByClose ? giveUpOutcome.then((): ChildReleaseOutcome => 'closed') : giveUpOutcome + ); if (!cancelledByClose) { // When close() cancelled the handshake it is still awaiting its own // disconnect on connection.client: shutting the client down or @@ -410,6 +450,7 @@ export class ChildConnections extends EventEmitter { await this.close(sessionId, { terminateDebuggee: false }); } await this.releaseAllHeld(reason); + this.releaseOutcomes.clear(); } // ----- internals ----- @@ -463,21 +504,48 @@ export class ChildConnections extends EventEmitter { held.client.respondToReverseRequest?.(held.request, {}, success, message); } + private recordReleaseOutcome(reportId: string, outcome: Promise): Promise { + if (!this.releaseOutcomes.has(reportId) && this.releaseOutcomes.size >= MAX_RECORDED_RELEASE_OUTCOMES) { + const oldest = this.releaseOutcomes.keys().next().value; + if (oldest !== undefined) { + this.releaseOutcomes.delete(oldest); + } + } + this.releaseOutcomes.set(reportId, outcome); + return outcome; + } + /** Let a taken report's child run undebugged, by the policy's lever: refuse the request, or attach and detach. */ - private giveUp(held: HeldReport, reason: string): void { + private giveUp(held: HeldReport, reason: string, reportId?: string): Promise { + let outcomePromise: Promise; if (this.lever() === 'throwaway-attach') { - const releasing = this.releaseByThrowaway(held, reason) - .catch((error: unknown) => { + outcomePromise = this.releaseByThrowaway(held, reason) + .then((released): ChildReleaseOutcome => (released ? 'confirmed' : 'unconfirmed')) + .catch((error: unknown): ChildReleaseOutcome => { this.options.logger.error(`[ChildConnections] Failed to release child ${held.report.targetId}: ${error instanceof Error ? error.message : String(error)}`); - }) + return 'unconfirmed'; + }); + const releasing = outcomePromise + .then(() => undefined) .finally(() => { this.releases.delete(releasing); this.emitEmptyIfSo(); }); this.releases.add(releasing); } else { - held.client.respondToReverseRequest?.(held.request, {}, false, reason); + try { + const responder = held.client.respondToReverseRequest; + if (typeof responder !== 'function') { + outcomePromise = Promise.resolve('unconfirmed'); + } else { + const sent = responder.call(held.client, held.request, {}, false, reason); + outcomePromise = Promise.resolve(sent === false ? 'unconfirmed' : 'confirmed'); + } + } catch { + outcomePromise = Promise.resolve('unconfirmed'); + } } + return reportId !== undefined ? this.recordReleaseOutcome(reportId, outcomePromise) : outcomePromise; } /** @@ -548,12 +616,18 @@ export class ChildConnections extends EventEmitter { * this path releases whatever the old one could. Counted with the * releases, so the worker does not stop the adapter underneath it. */ - private letGoOnItsConnection(deps: ChildAdoptionDeps, client: IDapClient, held: HeldReport, reason: string): void { + private letGoOnItsConnection( + deps: ChildAdoptionDeps, + client: IDapClient, + held: HeldReport, + reason: string, + reportId?: string + ): Promise { const { logger } = this.options; const child = `${held.report.targetId} (${held.report.name})`; - const releasing = deps.connectionManager + const outcomePromise = deps.connectionManager .disconnect(client, false) - .then(async (outcome) => { + .then(async (outcome): Promise => { try { client.shutdown(`child adoption failed: ${reason}`); } catch { @@ -563,21 +637,26 @@ export class ChildConnections extends EventEmitter { logger.warn( `[ChildConnections] Child ${child}: the adapter did not acknowledge the disconnect after a failed adoption (${outcome.error ?? 'no answer'}); trying the throwaway attach in case the target is still pending` ); - await this.releaseByThrowaway(held, `adoption failed: ${reason}`); - return; + const released = await this.releaseByThrowaway(held, `adoption failed: ${reason}`); + return released ? 'confirmed' : 'unconfirmed'; } logger.warn( `[ChildConnections] Child ${child} let go on its own connection (adoption failed: ${reason}) — breakpoints will not bind in that process` ); + return 'confirmed'; }) - .catch((error: unknown) => { + .catch((error: unknown): ChildReleaseOutcome => { logger.error(`[ChildConnections] Failed to release child ${child}: ${error instanceof Error ? error.message : String(error)}`); - }) + return 'unconfirmed'; + }); + const releasing = outcomePromise + .then(() => undefined) .finally(() => { this.releases.delete(releasing); this.emitEmptyIfSo(); }); this.releases.add(releasing); + return reportId !== undefined ? this.recordReleaseOutcome(reportId, outcomePromise) : outcomePromise; } /** @@ -646,13 +725,13 @@ export class ChildConnections extends EventEmitter { * kept. A process the released child reports in that window is held like * any other, stamped with the session the released child was reported on. */ - private async releaseByThrowaway(held: HeldReport, reason: string): Promise { + private async releaseByThrowaway(held: HeldReport, reason: string): Promise { const deps = this.options.adoption; const contract = deps?.policy.childAdoption; const { logger } = this.options; if (!deps || !contract) { logger.warn(`[ChildConnections] Child ${held.report.targetId} (${held.report.name}) cannot be released: this worker opens no connections; it stays parked`); - return; + return false; } const label = held.report.targetId.slice(0, 8); const attachArguments = contract.buildChildAttachArguments(held.report, deps.launchConfig as Readonly> | undefined); @@ -670,6 +749,7 @@ export class ChildConnections extends EventEmitter { `[ChildConnections] Child ${held.report.targetId} (${held.report.name}) released to run UNDEBUGGED (${reason}) — breakpoints will not bind in that process` ); } + return released; } private takeHeld(reportId: string): HeldReport | undefined { diff --git a/src/proxy/dap-proxy-interfaces.ts b/src/proxy/dap-proxy-interfaces.ts index a92c6de6..1272964d 100644 --- a/src/proxy/dap-proxy-interfaces.ts +++ b/src/proxy/dap-proxy-interfaces.ts @@ -268,7 +268,7 @@ export interface IDapClient { * holds unanswered (the session tree, issue #1081). Optional: only * MinimalDapClient implements it. */ - respondToReverseRequest?(request: DebugProtocol.Request, body: unknown, success: boolean, message?: string): void; + respondToReverseRequest?(request: DebugProtocol.Request, body: unknown, success: boolean, message?: string): boolean | void; /** * Record the session's break-on-exception mode so DAP child sessions can * apply the same exception filters (issue #220). Optional: only diff --git a/src/proxy/dap-proxy-worker.ts b/src/proxy/dap-proxy-worker.ts index ed371a7b..be1d656b 100644 --- a/src/proxy/dap-proxy-worker.ts +++ b/src/proxy/dap-proxy-worker.ts @@ -2019,8 +2019,11 @@ export class DapProxyWorker { switch (payload.dapCommand) { case CHILD_RELEASE_COMMAND: { const args = (payload.dapArgs ?? {}) as ChildReleaseArgs; - const released = this.childConnections.release(args.reportId, args.reason ?? 'released by the server'); - this.sendDapResponse(payload.requestId, true, { body: { released } }, undefined, payload.sessionId); + const outcome = await this.childConnections.releaseWithConfirmation( + args.reportId, + args.reason ?? 'released by the server' + ); + this.sendDapResponse(payload.requestId, true, { body: outcome }, undefined, payload.sessionId); return; } case CHILD_ADOPT_COMMAND: { diff --git a/src/proxy/minimal-dap.ts b/src/proxy/minimal-dap.ts index 2e9f0621..16364fcc 100644 --- a/src/proxy/minimal-dap.ts +++ b/src/proxy/minimal-dap.ts @@ -969,13 +969,15 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { }); } - private writeMessage(message: DebugProtocol.ProtocolMessage): void { + private writeMessage(message: DebugProtocol.ProtocolMessage): boolean { const payload = encodeDapMessage(message); this.appendTrace('out', message); - if (this.socket && !this.socket.destroyed) { + if (this.socket && !this.socket.destroyed && !this.isDisconnectingOrDisconnected) { this.socket.write(payload); + return true; } else { logger.error('[MinimalDapClient] Cannot write message, socket not connected/destroyed'); + return false; } } @@ -984,11 +986,11 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { * has held unanswered since (issue #1081): `success: true` once the child * is adopted, `success: false` to release it. */ - public respondToReverseRequest(request: DebugProtocol.Request, body: unknown, success: boolean, message?: string): void { - this.sendResponse(request, body, success, message); + public respondToReverseRequest(request: DebugProtocol.Request, body: unknown, success: boolean, message?: string): boolean { + return this.sendResponse(request, body, success, message); } - private sendResponse(request: DebugProtocol.Request, body: unknown = {}, success: boolean = true, errorMessage?: string): void { + private sendResponse(request: DebugProtocol.Request, body: unknown = {}, success: boolean = true, errorMessage?: string): boolean { const response: DebugProtocol.Response = { type: 'response', seq: this.nextSeq++, @@ -997,7 +999,7 @@ export class MinimalDapClient extends EventEmitter implements IDapClient { success, ...(success ? { body } : { message: errorMessage || DEFAULT_DAP_FAILURE_MESSAGE }) }; - this.writeMessage(response); + return this.writeMessage(response); } public disconnect(): void { diff --git a/src/server/handlers/debuggee-tools.ts b/src/server/handlers/debuggee-tools.ts index 257fec89..5e186c59 100644 --- a/src/server/handlers/debuggee-tools.ts +++ b/src/server/handlers/debuggee-tools.ts @@ -4,7 +4,7 @@ */ import type { ToolHandler } from '../tool-context.js'; import type { HotReloadArgs } from '@debugmcp/shared'; -import { attachRequestFromArgs, childSessionRefusal, hoistStopLanding, hoistTreeFields, successWarning } from './shared.js'; +import { attachRequestFromArgs, childSessionRefusal, hoistPausedChild, hoistStopLanding, hoistTreeFields, successWarning } from './shared.js'; import { assertPlainObjectArg, foldTestRunnerPreset, @@ -70,6 +70,7 @@ export const startDebuggingTool: ToolHandler = async (ctx, args) => { // The session tree (issue #1081): children adopted during the hold, what // a relaunch closed, what ran undebugged. hoistTreeFields(responsePayload, debugResult.data); + await hoistPausedChild(ctx, responsePayload, debugResult.data, 'launch child result'); return jsonResult(responsePayload); } catch (error) { return sessionErrorResultOrThrow(error, { state: 'stopped' }); @@ -112,6 +113,7 @@ export const restartDebuggingTool: ToolHandler = async (ctx, args) => { // And the same landing when it stopped (issue #951). await hoistStopLanding(ctx, responsePayload, debugResult.data, args.sessionId, 'restart result'); hoistTreeFields(responsePayload, debugResult.data); + await hoistPausedChild(ctx, responsePayload, debugResult.data, 'restart child result'); } return jsonResult(responsePayload); } catch (error) { diff --git a/src/server/handlers/shared.ts b/src/server/handlers/shared.ts index 7acef28a..33f5a700 100644 --- a/src/server/handlers/shared.ts +++ b/src/server/handlers/shared.ts @@ -21,7 +21,7 @@ import type { ToolContext } from '../tool-context.js'; import type { ToolArguments } from '../tool-arguments.js'; import { validateBreakOnExceptions } from '../tool-validation.js'; import { debuggerOffWhy } from '../../session/debugger-off.js'; -import type { DebugResult, StopAnswerFields, TreeAnswerFields } from '../../session/session-manager-core.js'; +import type { DebugResult, LaunchResultData, StopAnswerFields, TreeAnswerFields } from '../../session/session-manager-core.js'; import type { AttachRequest } from '../../session/attach/attach-controller.js'; import { runFactsOf, type RunFacts } from '../../session/run-facts.js'; import { ErrorMessages } from '../../utils/error-messages.js'; @@ -240,6 +240,48 @@ export function hoistTreeFields(response: Record, data: TreeAns } } +/** + * Hoist and enrich `pausedChild` on `start_debugging` / `restart_debugging` + * when an adopted child session is already paused while the launched root is + * running (issue #1150). Adds source `context` and stale-build `note` for the + * child's location, and strips the duplicate `snapshot` from `response.data` + * just like `hoistStopLanding` does for a root stop. + */ +export async function hoistPausedChild( + ctx: ToolContext, + response: Record, + data: Pick | undefined, + logLabel: string +): Promise { + if (!data?.pausedChild) { + return; + } + const pausedChild: Record = { ...data.pausedChild }; + const location = data.pausedChild.location; + if (location && !location.unresolvedSource && hasOpenableSourcePath(location.file)) { + const [context, staleBuild] = await Promise.all([ + readLineContext(ctx, location.file, location.line, logLabel), + describeStaleBuild(ctx, data.pausedChild.sessionId, location.file, logLabel) + ]); + if (context) { + pausedChild.context = context; + } + appendNote(pausedChild, staleBuild); + } + response.pausedChild = pausedChild; + if (data.pausedChild.snapshot) { + const embedded = response.data; + if (embedded && typeof embedded === 'object' && 'pausedChild' in embedded) { + const embeddedRecord = embedded as Record; + const inner = embeddedRecord.pausedChild; + if (inner && typeof inner === 'object' && 'snapshot' in inner) { + const { snapshot: _omitted, ...restChild } = inner as Record; + response.data = { ...embeddedRecord, pausedChild: restChild }; + } + } + } +} + /** * Hoist where a stop landed to the top level of a tool answer and annotate * it — the one shape every stop answer has: the step tools, pause_execution, diff --git a/src/session/breakpoints/breakpoint-controller.ts b/src/session/breakpoints/breakpoint-controller.ts index 6f7e3090..d8abcf8e 100644 --- a/src/session/breakpoints/breakpoint-controller.ts +++ b/src/session/breakpoints/breakpoint-controller.ts @@ -41,6 +41,7 @@ import { keepHitProven, keepPendingAnswer, mirrorsBreakpointsToChild, + recordTreeVerifiedBreakpoint, setAdapterMessage, stampRefusalMessage } from './hit-verification.js'; @@ -376,6 +377,7 @@ export class BreakpointController { // Log breakpoint verification with structured logging if (allBpsForFile[i].verified) { + recordTreeVerifiedBreakpoint(session, allBpsForFile[i]); this.ctx.logger.info('debug:breakpoint', { event: 'verified', sessionId: sessionId, @@ -929,6 +931,7 @@ export class BreakpointController { record.boundLine = undefined; } if (allFnBps[i].verified) { + recordTreeVerifiedBreakpoint(session, allFnBps[i]); this.ctx.logger.info('debug:breakpoint', { event: 'verified', sessionId, diff --git a/src/session/breakpoints/hit-verification.ts b/src/session/breakpoints/hit-verification.ts index c91cba9b..6b032b87 100644 --- a/src/session/breakpoints/hit-verification.ts +++ b/src/session/breakpoints/hit-verification.ts @@ -92,6 +92,20 @@ export function resetBinding(record: Breakpoint | FunctionBreakpoint): void { record.boundLine = undefined; } +/** + * Record on the tree's shared `Run` that a breakpoint bound in at least one + * session of this run (issue #1150), so a root's end summary and unbound-exit + * warning reflect bindings in adopted child sessions even after they close. + */ +export function recordTreeVerifiedBreakpoint( + session: Partial> | undefined, + record: Pick +): void { + if (record.verified && session?.run) { + (session.run.treeVerifiedBreakpointIds ??= new Set()).add(record.id); + } +} + /** * The hit-proven rule (issue #673): a stop already proved this record bound, * so an adapter answer of "unbound" for it is not evidence it stopped firing @@ -252,7 +266,7 @@ export interface HitUpgrade { * which of the records). */ export function applyHitBreakpointIds( - session: Pick, + session: Pick & Partial>, hitBreakpointIds: readonly unknown[] ): HitUpgrade[] { const upgraded: HitUpgrade[] = []; @@ -274,14 +288,18 @@ export function applyHitBreakpointIds( settleStoredMessage(line); upgraded.push({ kind: 'line', breakpoint: line, adapterId: id }); } + recordTreeVerifiedBreakpoint(session, line); continue; } const fn = soleHolderOf(functionBreakpoints, id); - if (fn && !fn.verified) { - fn.verified = true; - fn.verifiedBy = 'hit'; - settleStoredMessage(fn); - upgraded.push({ kind: 'function', breakpoint: fn, adapterId: id }); + if (fn) { + if (!fn.verified) { + fn.verified = true; + fn.verifiedBy = 'hit'; + settleStoredMessage(fn); + upgraded.push({ kind: 'function', breakpoint: fn, adapterId: id }); + } + recordTreeVerifiedBreakpoint(session, fn); } } return upgraded; diff --git a/src/session/breakpoints/launch-warnings.ts b/src/session/breakpoints/launch-warnings.ts index ed50339f..e5fb0178 100644 --- a/src/session/breakpoints/launch-warnings.ts +++ b/src/session/breakpoints/launch-warnings.ts @@ -31,6 +31,18 @@ export interface UnhitBreakpointSummary { verified: boolean; } +/** + * Whether a breakpoint bound anywhere in this run's session tree (issue #1150): + * either on `session` itself, or recorded in `session.run.treeVerifiedBreakpointIds` + * when an adopted child verified or hit its copy. + */ +function isVerifiedInTree( + session: Partial>, + bp: { id: string; verified: boolean } +): boolean { + return bp.verified || session.run?.treeVerifiedBreakpointIds?.has(bp.id) === true; +} + /** * Ran-to-completion unbound-breakpoint warning (issue #467). Built only * when the launch ends in STOPPED: at that point an unverified breakpoint @@ -38,11 +50,18 @@ export interface UnhitBreakpointSummary { * zero-false-positive moment to surface the per-breakpoint diagnostics the * store already holds (e.g. the path-remap suggestion CodeLLDB puts in * `message`). + * + * Tree-aware (issue #1150): breakpoints verified in an adopted child session + * bound during this run and are never reported as unbound; when child + * processes ran undebugged (released, unconfirmed, or opted out), the tail + * explains that child-only code could not bind instead of blaming only the + * file path and line. */ export function buildUnboundBreakpointExitWarning( - session: Pick + session: Pick & + Partial> ): string | undefined { - const unbound = Array.from(session.breakpoints.values()).filter(bp => !bp.verified); + const unbound = Array.from(session.breakpoints.values()).filter(bp => !isVerifiedInTree(session, bp)); if (unbound.length === 0) { return undefined; } @@ -52,6 +71,21 @@ export function buildUnboundBreakpointExitWarning( const message = normalizeBreakpointMessage(bp.message, bp.verified); return `${fileLabel(bp.file)}:${bp.line}${message ? ` (${message})` : ''}`; }); + const optedOut = session.run?.childDebuggingOptedOut; + const released = session.releasedChildReports ?? 0; + const unconfirmed = session.unconfirmedChildReleases ?? 0; + if (optedOut !== undefined || released > 0 || unconfirmed > 0) { + const childClause = optedOut !== undefined + ? `child-process debugging was off (${optedOut}), so breakpoints in code only a child process loads could not bind` + : released > 0 + ? `${released} child process${released === 1 ? ' ran' : 'es ran'} undebugged, so breakpoints in code only ${released === 1 ? 'it loads' : 'they load'} could not bind` + : `${unconfirmed} child process${unconfirmed === 1 ? ' could' : 'es could'} not be adopted, so breakpoints in code only ${unconfirmed === 1 ? 'it loads' : 'they load'} could not bind`; + return ( + `${unbound.length} breakpoint(s) never bound in the debugged process during this run: ${parts.join('; ')}. ` + + `The program ran to completion without stopping there — ${childClause}; ` + + `otherwise check the file path and line, or list_breakpoints for the full per-breakpoint state` + ); + } return ( `${unbound.length} breakpoint(s) never bound during this run: ${parts.join('; ')}. ` + `The program ran to completion without stopping there — check the file path and line, ` + @@ -198,7 +232,8 @@ export function describeProgramEnd(exitCode: number | undefined): string { * did pause, so it counts. */ export function buildRunToCompletionSummary( - session: Pick + session: Pick & + Partial> ): RunToCompletionSummary { const base = summarizeProgramEnd(session); // What the adapter read into the end (issue #877: the devices a Flutter launch found when @@ -215,7 +250,8 @@ export function buildRunToCompletionSummary( } function summarizeProgramEnd( - session: Pick + session: Pick & + Partial> ): RunToCompletionSummary { const exitCode = session.exitCode; const ended = describeProgramEnd(exitCode); @@ -250,7 +286,7 @@ function summarizeProgramEnd( file: bp.file, line: bp.line, ...(typeof bp.requestedLine === 'number' && bp.requestedLine !== bp.line ? { requestedLine: bp.requestedLine } : {}), - verified: bp.verified + verified: isVerifiedInTree(session, bp) }); } const unhitFunctions = Array.from(session.functionBreakpoints?.values() ?? []); @@ -261,12 +297,16 @@ function summarizeProgramEnd( } const verifiedNames = [ ...unhitBreakpoints.filter(bp => bp.verified).map(bp => `${fileLabel(bp.file)}:${bp.line}`), - ...unhitFunctions.filter(bp => bp.verified).map(bp => `function '${bp.functionName}'`) + ...unhitFunctions.filter(bp => isVerifiedInTree(session, bp)).map(bp => `function '${bp.functionName}'`) ]; + const optedOut = session.run?.childDebuggingOptedOut; + const optOutClause = optedOut !== undefined + ? ` in the launched process (child-process debugging was off via ${optedOut}, so child processes were not debugged)` + : ''; const verifiedClause = verifiedNames.length > 0 - ? ` Verified but never hit: ${verifiedNames.join(', ')}.` + ? ` Verified${optedOut !== undefined ? ' in the launched process' : ''} but never hit: ${verifiedNames.join(', ')}.` : ''; - return { summary: `${ended} without hitting any breakpoint.${verifiedClause}`, data }; + return { summary: `${ended} without hitting any breakpoint${optOutClause}.${verifiedClause}`, data }; } /** diff --git a/src/session/execution/execution-controller.ts b/src/session/execution/execution-controller.ts index 474fad57..a98d24e6 100644 --- a/src/session/execution/execution-controller.ts +++ b/src/session/execution/execution-controller.ts @@ -1065,6 +1065,7 @@ export class ExecutionController { } break; } + await this.ctx.settleInFlightChildReleases?.(sessionId); const location = landing.location; const tree = () => describeTreeAnswer(session, this.ctx.descendantsOf(sessionId)); // Every answer that carries the run's `childrenReleased` says what it means diff --git a/src/session/execution/tree-settle.ts b/src/session/execution/tree-settle.ts index 057e8b2a..61b1ebd0 100644 --- a/src/session/execution/tree-settle.ts +++ b/src/session/execution/tree-settle.ts @@ -76,27 +76,42 @@ function describeReleaseCause(cause: ChildReleaseCause, cap: number | undefined) * setting by name when one decided it — and what follows for the caller: a * breakpoint only such a child reaches will not hit, whatever a pending * answer says is armed. Built from the same record as the number, so the two - * cannot disagree. Undefined when the run released none. + * cannot disagree. + * + * When a failed adoption's fallback release was not confirmed by the debug + * adapter (issue #1221), `unconfirmedChildReleases` is disclosed separately + * without counting in `childrenReleased` or claiming the child continues + * running. Undefined when neither occurred. */ export function describeReleasedChildren( - session: Pick + session: Pick & + Partial> ): string | undefined { + const sentences: string[] = []; const count = session.releasedChildReports ?? 0; - if (count <= 0) { - return undefined; + if (count > 0) { + const causes = RELEASE_CAUSES.filter((cause) => (session.releasedChildCauses?.[cause] ?? 0) > 0); + const why = causes + .map((cause) => { + const text = describeReleaseCause(cause, session.releasedChildCap); + return causes.length > 1 ? `${session.releasedChildCauses![cause]}: ${text}` : text; + }) + .join('; '); + const one = count === 1; + sentences.push( + `${count} child process${one ? ' was' : 'es were'} released to run undebugged${why ? ` (${why})` : ''}: ` + + `a breakpoint only ${one ? 'it reaches' : 'they reach'} will not hit.` + ); + } + const unconfirmed = session.unconfirmedChildReleases ?? 0; + if (unconfirmed > 0) { + const one = unconfirmed === 1; + sentences.push( + `${unconfirmed} child process${one ? ' could' : 'es could'} not be adopted, and the debug adapter did not confirm ` + + `releasing ${one ? 'it' : 'them'}; whether ${one ? 'it' : 'they'} continued running is not known.` + ); } - const causes = RELEASE_CAUSES.filter((cause) => (session.releasedChildCauses?.[cause] ?? 0) > 0); - const why = causes - .map((cause) => { - const text = describeReleaseCause(cause, session.releasedChildCap); - return causes.length > 1 ? `${session.releasedChildCauses![cause]}: ${text}` : text; - }) - .join('; '); - const one = count === 1; - return ( - `${count} child process${one ? ' was' : 'es were'} released to run undebugged${why ? ` (${why})` : ''}: ` + - `a breakpoint only ${one ? 'it reaches' : 'they reach'} will not hit.` - ); + return sentences.length > 0 ? sentences.join(' ') : undefined; } /** `message` with the released-children sentence after it, when there is one. */ diff --git a/src/session/launch/debug-launcher.ts b/src/session/launch/debug-launcher.ts index 5fb63c27..264574cf 100644 --- a/src/session/launch/debug-launcher.ts +++ b/src/session/launch/debug-launcher.ts @@ -30,11 +30,11 @@ import { ProtocolError } from '@modelcontextprotocol/server'; import { ErrorMessages } from '../../utils/error-messages.js'; import { checkLaunchToolchain } from '../../utils/language-availability.js'; import { setCuratedMessage } from '../breakpoints/hit-verification.js'; -import type { CustomLaunchRequestArguments, DebugResult, LaunchResultData } from '../session-manager-core.js'; +import type { CustomLaunchRequestArguments, DebugResult, LaunchResultData, PausedChildSummary } from '../session-manager-core.js'; import type { ManagedSession, ToolchainValidationState } from '../session-store.js'; import type { LaunchContext } from '../operations-context.js'; import { describeStopLocation, landingFields, type StopLanding } from '../inspection/stop-location.js'; -import { describeReleasedChildren, describeTreeAnswer, withReleasedChildren } from '../execution/tree-settle.js'; +import { describeReleasedChildren, describeTreeAnswer, selectSettledInTree, withReleasedChildren } from '../execution/tree-settle.js'; import { composeStopSnapshot } from '../inspection/stop-snapshot.js'; import type { BreakpointController, ResyncOutcome } from '../breakpoints/breakpoint-controller.js'; import { reresolveAnchors, type AnchorResolution } from '../breakpoints/anchor-resolution.js'; @@ -664,6 +664,10 @@ export class DebugLauncher { } }); + // Ensure any child-release confirmations initiated during the launch hold + // have settled before reading released/unconfirmed counts or exit warnings (#1221). + await this.ctx.settleInFlightChildReleases?.(sessionId); + // Re-fetch session to get the most up-to-date state const finalSession = this.ctx.getSession(sessionId); const finalState = finalSession.state; @@ -831,14 +835,55 @@ export class DebugLauncher { // how long the launch waits; it only words this answer. The stop, if // one comes, is collected with wait_for_stop. let stillRunning: string | undefined; + let pausedChild: PausedChildSummary | undefined; if (readiness === 'running' && finalState === SessionState.RUNNING) { - const arming = describeLaunchArming(finalSession, effectiveLaunchArgs?.stopOnEntry); - stillRunning = ErrorMessages.launchStillRunning( - arming.armed ? arming.summary : undefined, - debuggerOnAnyway ? undefined : debuggerOffWhy(finalSession), - arming.loggingSummary, - arming.noUncaughtStop - ); + const descendants = this.ctx.descendantsOf(sessionId); + const settledInTree = selectSettledInTree(finalSession, descendants); + if (settledInTree && settledInTree !== finalSession && settledInTree.state === SessionState.PAUSED) { + const childLanding = await describeStopLocation(this.ctx, settledInTree.id, 'launch'); + const childSnapshot = await composeStopSnapshot( + this.ctx, + settledInTree.id, + childLanding.stackResult, + 'launch' + ); + if ( + settledInTree.state === SessionState.PAUSED && + this.ctx.descendantsOf(sessionId).includes(settledInTree) + ) { + const childReason = settledInTree.lastStop?.reason ?? 'breakpoint'; + pausedChild = { + sessionId: settledInTree.id, + name: settledInTree.name, + state: SessionState.PAUSED, + reason: childReason, + ...landingFields(childLanding), + ...(childSnapshot ? { snapshot: childSnapshot } : {}) + }; + stillRunning = ErrorMessages.launchRunningWithPausedChild( + settledInTree.name, + settledInTree.id, + childReason, + childLanding.location + ); + } + } else if (settledInTree && settledInTree !== finalSession && settledInTree.state === SessionState.ERROR) { + // Never populate `pausedChild` for an errored child: it is not paused. + stillRunning = ErrorMessages.launchRunningWithErroredChild( + settledInTree.name, + settledInTree.id, + settledInTree.lastProxyError + ); + } + if (!stillRunning) { + const arming = describeLaunchArming(finalSession, effectiveLaunchArgs?.stopOnEntry); + stillRunning = ErrorMessages.launchStillRunning( + arming.armed ? arming.summary : undefined, + debuggerOnAnyway ? undefined : debuggerOffWhy(finalSession), + arming.loggingSummary, + arming.noUncaughtStop + ); + } } return { @@ -872,8 +917,10 @@ export class DebugLauncher { ...landingFields(landing), ...(snapshot ? { snapshot } : {}), // The session tree (issue #1081): the children adopted during the - // hold, the run's released count, and what the relaunch closed. + // hold, the run's released count, any already-paused child snapshot + // (issue #1150), and what the relaunch closed. ...describeTreeAnswer(finalSession, this.ctx.descendantsOf(sessionId)), + ...(pausedChild ? { pausedChild } : {}), ...(childrenClosed > 0 ? { childrenClosed } : {}), }, }; diff --git a/src/session/launch/launch-readiness.ts b/src/session/launch/launch-readiness.ts index f77f3a35..1923e146 100644 --- a/src/session/launch/launch-readiness.ts +++ b/src/session/launch/launch-readiness.ts @@ -25,9 +25,14 @@ import { SessionState, isSettledSessionState, isTerminalSessionState } from '@de import { ErrorMessages } from '../../utils/error-messages.js'; import type { OperationsContext } from '../operations-context.js'; import { waitForSessionState } from '../execution/session-state-wait.js'; +import { selectSettledInTree } from '../execution/tree-settle.js'; + +/** Grace window after a descendant settles so a simultaneous root stop still wins (issue #1150). */ +const DESCENDANT_SETTLE_GRACE_MS = 50; /** The readiness waits read the session's state, subscribe to its changes, and narrate. */ -export type LaunchReadinessContext = Pick; +export type LaunchReadinessContext = Pick & + Partial>; /** * How the launch stands when it is answered: paused at its first stop; over @@ -100,7 +105,11 @@ export async function waitForLaunchReadiness( } } - await waitForSessionState(ctx, sessionId, isSettledSessionState, { timeoutMs: holdMs }); + if (ctx.onSubtreeChange && ctx.descendantsOf) { + await waitForLaunchHoldWithTree(ctx, ctx.onSubtreeChange, ctx.descendantsOf, sessionId, holdMs); + } else { + await waitForSessionState(ctx, sessionId, isSettledSessionState, { timeoutMs: holdMs }); + } const afterHold = settledOutcome(currentState()); if (afterHold) { ctx.logger.info(`[SessionManager] Session ${sessionId} ${afterHold} within the launch hold`); @@ -111,3 +120,86 @@ export async function waitForLaunchReadiness( ); return 'running'; } + +function waitForLaunchHoldWithTree( + ctx: LaunchReadinessContext, + onSubtreeChange: OperationsContext['onSubtreeChange'], + descendantsOf: OperationsContext['descendantsOf'], + sessionId: string, + holdMs: number +): Promise { + if (holdMs <= 0) { + return Promise.resolve(); + } + return new Promise((resolve) => { + let finished = false; + let recheckQueued = false; + let descendantGraceTimer: ReturnType | undefined; + const deadline = Date.now() + holdMs; + + const clearDescendantGrace = () => { + if (descendantGraceTimer !== undefined) { + clearTimeout(descendantGraceTimer); + descendantGraceTimer = undefined; + } + }; + + const disposers: Array<() => void> = []; + const holdTimer = setTimeout(() => finish(), holdMs); + + const finish = () => { + if (finished) { + return; + } + finished = true; + clearTimeout(holdTimer); + clearDescendantGrace(); + for (const dispose of disposers) { + dispose(); + } + resolve(); + }; + + const evaluate = () => { + let root; + try { + root = ctx.getSession(sessionId); + } catch { + finish(); + return; + } + if (isSettledSessionState(root.state)) { + finish(); + return; + } + const settled = selectSettledInTree(root, descendantsOf(sessionId)); + if (settled && settled !== root) { + if (descendantGraceTimer === undefined) { + const remaining = Math.max(0, deadline - Date.now()); + descendantGraceTimer = setTimeout(() => finish(), Math.min(DESCENDANT_SETTLE_GRACE_MS, remaining)); + } + } else { + clearDescendantGrace(); + } + }; + + disposers.push(onSubtreeChange(sessionId, () => { + if (finished || recheckQueued) { + return; + } + recheckQueued = true; + queueMicrotask(() => { + recheckQueued = false; + if (!finished) { + evaluate(); + } + }); + })); + + queueMicrotask(() => { + if (!finished) { + evaluate(); + } + }); + }); +} diff --git a/src/session/launch/proxy-launcher.ts b/src/session/launch/proxy-launcher.ts index 8dfc0acd..14b51919 100644 --- a/src/session/launch/proxy-launcher.ts +++ b/src/session/launch/proxy-launcher.ts @@ -40,6 +40,7 @@ import { ErrorMessages } from '../../utils/error-messages.js'; import type { CustomLaunchRequestArguments } from '../session-manager-core.js'; import type { ManagedSession, ToolchainValidationState, TransformedLaunch } from '../session-store.js'; import type { ProxyLaunchContext } from '../operations-context.js'; +import { detectChildDebuggingOptOut } from '../run-facts.js'; import { callerLaunchInputs, collectLaunchConfigNotices, type CallerLaunchInput, collectAttachTransformNotices } from './launch-config-diagnostics.js'; @@ -154,6 +155,9 @@ export class ProxyLauncher { session.run.launchConfigNotices = []; session.run.attachTransformNotices = undefined; session.run.transformedLaunch = undefined; + session.run.treeVerifiedBreakpointIds = undefined; + session.run.childDebuggingOptedOut = undefined; + session.run.inFlightChildReleases = undefined; // Log entrance for Windows CI debugging this.ctx.logger.info( @@ -202,7 +206,14 @@ export class ProxyLauncher { // program (issue #1151), read the same way from the same config: the // transformed one. The arguments as given are not it: an adapter with // no attach transform turns attach-shaped arguments into a launch. - session.run.programOwnership = launchConfigIsAttach(plan.launchConfig) ? 'borrowed' : 'owned'; + const isBorrowed = launchConfigIsAttach(plan.launchConfig); + session.run.programOwnership = isBorrowed ? 'borrowed' : 'owned'; + session.run.childDebuggingOptedOut = detectChildDebuggingOptOut( + session.language, + isBorrowed, + plan.launchConfig as Record, + inputs.genericLaunchConfig + ); // Set up event handlers // The core must see the same entry-stop intent the worker sees (#791). diff --git a/src/session/operations-context.ts b/src/session/operations-context.ts index 48caacac..deb3609c 100644 --- a/src/session/operations-context.ts +++ b/src/session/operations-context.ts @@ -139,6 +139,8 @@ export interface OperationsContext { closeSessionReporting(sessionId: string, options?: { terminateDebuggee?: boolean }): Promise; /** Block new child adoptions during a complete teardown; returns the release function. */ beginSubtreeClose(sessionId: string): () => void; + /** Wait for any in-flight CHILD_RELEASE_COMMAND round-trips on this session's run (issue #1221). */ + settleInFlightChildReleases(sessionId: string): Promise; /** The detach cascade (issue #1081): release every descendant, deepest first; resolves with how many. */ releaseDescendants(session: ManagedSession): Promise; getStackTrace( @@ -207,10 +209,12 @@ export type LaunchContext = Pick< | 'updateSession' | 'updateState' | 'onStateChange' + | 'onSubtreeChange' | 'selectPolicy' | 'getStackTraceDetailed' | 'stopProxyPreservingSession' | 'descendantsOf' + | 'settleInFlightChildReleases' | 'extractLocalsFromResolved' | 'redactionEnabled' | 'snapshotEnabled' @@ -268,6 +272,7 @@ export type ExecutionContext = Pick< | 'onStateChange' | 'onSubtreeChange' | 'descendantsOf' + | 'settleInFlightChildReleases' | 'getStackTraceDetailed' | 'selectPolicy' | 'tunables' diff --git a/src/session/run-facts.ts b/src/session/run-facts.ts index 601d1e2b..b7311083 100644 --- a/src/session/run-facts.ts +++ b/src/session/run-facts.ts @@ -77,6 +77,28 @@ export function rootOfTree(session: T, get: (sessionId: stri return current; } +/** + * Detect whether a launch or attach configuration explicitly turned off + * child-process adoption on an adapter that otherwise supports it (issue #1150). + * Python attach is excluded because debugpy's subprocess tracing on attach is + * governed by how the target process invoked `debugpy.listen`, not reliably by + * the attach request alone. + */ +export function detectChildDebuggingOptOut( + language: string, + isAttach: boolean, + ...configs: Array> | undefined> +): Run['childDebuggingOptedOut'] { + const hasFalse = (key: string): boolean => configs.some((cfg) => cfg?.[key] === false); + if (language === 'python' && !isAttach && hasFalse('subProcess')) { + return 'subProcess: false'; + } + if (language === 'javascript' && hasFalse('autoAttachChildProcesses')) { + return 'autoAttachChildProcesses: false'; + } + return undefined; +} + /** The facts of the run `session` belongs to, read off its tree's root. */ export function runFactsOf(session: RunFactsSource, get: (sessionId: string) => RunFactsSource | undefined): RunFacts { const root = rootOfTree(session, get); diff --git a/src/session/session-manager-core.ts b/src/session/session-manager-core.ts index 1176360b..14a20cf3 100644 --- a/src/session/session-manager-core.ts +++ b/src/session/session-manager-core.ts @@ -61,6 +61,7 @@ import { applyHitBreakpointIds, keepHitProven, mirrorsBreakpointsToChild, + recordTreeVerifiedBreakpoint, resetBinding, samePath, setAdapterMessage, @@ -272,6 +273,24 @@ export interface ChildSessionSummary { parentSessionId: string; } +/** + * When a launch or restart answers `state: 'running'` on the root while an + * adopted child session is already genuinely `paused`, its stop landing and + * bounded snapshot ride here (issue #1150) so the caller can inspect, step, + * or continue `sessionId` immediately without spending an extra wait_for_stop + * turn. Never set for a child that is running, stopped, or in error. + */ +export interface PausedChildSummary extends StopAnswerFields { + sessionId: string; + name: string; + state: SessionState.PAUSED; + reason: string; + context?: { + lineContent: string; + surrounding: Array<{ line: number; content: string }>; + }; +} + /** * What an answer on a session with a tree carries * (docs/architecture/session-tree.md, "wait_for_stop is tree-aware"). @@ -280,9 +299,10 @@ export interface TreeAnswerFields { /** Every descendant with its state; absent when the session has none. */ children?: ChildSessionSummary[]; /** - * Reports released to run undebugged on this session's connection during - * this run (beyond the cap, or an adoption that failed): a running total, - * never consumed, so concurrent waiters read the same number. + * Reports released to run undebugged in this session's subtree during + * this run (beyond the cap, or a failed adoption whose release the adapter + * confirmed): a running total, never consumed, so concurrent waiters read + * the same number. */ childrenReleased?: number; /** Descendants this operation closed (a relaunch, a close) — when any. */ @@ -316,7 +336,10 @@ export type WaitForStopResultData = DebugResultData & StopAnswerFields & TreeAns * so the answer names the frame the program is paused in and the handler can * read the line and the build behind it. */ -export type LaunchResultData = DebugResultData & StopAnswerFields & TreeAnswerFields; +export type LaunchResultData = DebugResultData & StopAnswerFields & TreeAnswerFields & { + /** Present on launch/restart running answers when an adopted child is already paused (#1150). */ + pausedChild?: PausedChildSummary; +}; /** * What a detach returns on top of the common fields (the session tree, issue @@ -878,6 +901,53 @@ export abstract class SessionManagerCore extends EventEmitter { } } + /** + * Record a confirmed or unconfirmed child-release outcome on `parent` and + * every ancestor (issues #1150, #1221): a root's `childrenReleased` and + * unconfirmed-release disclosure speak for its whole subtree, grandchildren + * included, while a child session's own answer speaks for its subtree. + */ + private recordChildReleaseOnLineage( + parent: ManagedSession, + cause: ChildReleaseCause, + cap: number | undefined, + confirmed: boolean + ): void { + const seen = new Set(); + let current: ManagedSession | undefined = parent; + while (current && !seen.has(current.id)) { + seen.add(current.id); + if (confirmed) { + current.releasedChildReports = (current.releasedChildReports ?? 0) + 1; + current.releasedChildCauses = { + ...current.releasedChildCauses, + [cause]: (current.releasedChildCauses?.[cause] ?? 0) + 1 + }; + if (cap !== undefined && cap > 0) { + current.releasedChildCap = cap; + } + } else { + current.unconfirmedChildReleases = (current.unconfirmedChildReleases ?? 0) + 1; + } + current = current.parentSessionId ? this.sessionStore.get(current.parentSessionId) : undefined; + } + } + + /** Wait for any in-flight CHILD_RELEASE_COMMAND round-trips on `sessionId`'s run (issue #1221). */ + protected async settleInFlightChildReleases(sessionId: string): Promise { + let session: ManagedSession | undefined; + try { + session = this.sessionStore.get(sessionId); + } catch { + return; + } + const inFlight = session?.run.inFlightChildReleases; + if (!inFlight || inFlight.size === 0) { + return; + } + await Promise.all([...inFlight]); + } + /** Tell the subtree listeners of a session and of each of its ancestors. */ private notifySubtreeListeners(session: ManagedSession): void { const seen = new Set(); @@ -1493,30 +1563,38 @@ export abstract class SessionManagerCore extends EventEmitter { parentProxy: IProxyManager, reported: ChildReportedEvent ): Promise { - const release = (reason: string, cause: ChildReleaseCause | undefined): void => { - if (cause) { - // The run's count of children that run undebugged (issue #1081): the - // parent's next answers carry it as `childrenReleased`, with the cause - // beside it so they can say what the number means (issue #1137). A - // release with no cause is one nobody is told about: the tree was - // being closed anyway. - parent.releasedChildReports = (parent.releasedChildReports ?? 0) + 1; - parent.releasedChildCauses = { - ...parent.releasedChildCauses, - [cause]: (parent.releasedChildCauses?.[cause] ?? 0) + 1 - }; - } - parentProxy - .sendDapRequest(CHILD_RELEASE_COMMAND, { reportId: reported.reportId, reason }, { timeoutMs: 5000 }) + let releaseCap: number | undefined; + const release = (reason: string, cause: ChildReleaseCause | undefined): Promise => { + const inFlightSet = (parent.run.inFlightChildReleases ??= new Set()); + const op = parentProxy + .sendDapRequest( + CHILD_RELEASE_COMMAND, + { reportId: reported.reportId, reason }, + { timeoutMs: 5000 } + ) + .then((resp) => { + if (!cause || resp?.body?.closed === true || this.isSubtreeClosing(parent)) { + return; + } + const confirmed = resp?.body?.released !== false; + this.recordChildReleaseOnLineage(parent, cause, releaseCap, confirmed); + }) .catch((err) => { this.logger.warn( `[SessionManager] Releasing reported child ${reported.name} of session ${parent.id} failed: ${err instanceof Error ? err.message : String(err)}` ); + if (cause && !this.isSubtreeClosing(parent)) { + this.recordChildReleaseOnLineage(parent, cause, releaseCap, false); + } }); + inFlightSet.add(op); + return op.finally(() => { + inFlightSet.delete(op); + }); }; if (this.sessionStore.get(parent.id) !== parent || parent.proxyManager !== parentProxy || this.isSubtreeClosing(parent)) { - release('the parent session is closing or its connection has ended', undefined); + await release('the parent session is closing or its connection has ended', undefined); return; } @@ -1529,13 +1607,13 @@ export abstract class SessionManagerCore extends EventEmitter { : `the tree of session ${root.id} is at its child-session cap (${cap})`; this.logger.info(`[SessionManager] Releasing reported child ${reported.name} of session ${parent.id}: ${reason}`); if (cap > 0) { - parent.releasedChildCap = cap; + releaseCap = cap; } - release(reason, cap === 0 ? 'adoption-off' : 'cap'); + await release(reason, cap === 0 ? 'adoption-off' : 'cap'); return; } if (!parentProxy.createChildView) { - release('this session cannot host child sessions', 'unsupported'); + await release('this session cannot host child sessions', 'unsupported'); return; } @@ -1606,13 +1684,15 @@ export abstract class SessionManagerCore extends EventEmitter { this.logger.warn( `[SessionManager] Adopting child ${reported.name} of session ${parent.id} failed: ${message}` ); - release(`adoption failed: ${message}`, this.isSubtreeClosing(parent) ? undefined : 'adoption-failed'); + const closing = this.isSubtreeClosing(parent) || (child ? this.isSubtreeClosing(child) : false); + const releasePromise = release(`adoption failed: ${message}`, closing ? undefined : 'adoption-failed'); if (child && this.sessionStore.get(child.id) === child && !this.isSubtreeClosing(child)) { // Use the normal subtree teardown: a grandchild may already have // been reported, and removing the last child must reap a root whose // worker stop was deferred while this adoption was pending. await this.closeSession(child.id); } + await releasePromise; } } @@ -1771,6 +1851,7 @@ export abstract class SessionManagerCore extends EventEmitter { session.liveUpdateState = undefined; session.programEndExplanation = undefined; session.releasedChildReports = undefined; + session.unconfirmedChildReleases = undefined; session.releasedChildCauses = undefined; session.releasedChildCap = undefined; session.descendantStops = undefined; @@ -2266,6 +2347,7 @@ export abstract class SessionManagerCore extends EventEmitter { } fnTarget.verified = eventBp.verified; fnTarget.verifiedBy = fnTarget.verified ? 'adapter' : undefined; + recordTreeVerifiedBreakpoint(session, fnTarget); if (fnTarget.verified) { if (typeof eventBp.line === 'number') { fnTarget.boundLine = eventBp.line; @@ -2363,6 +2445,7 @@ export abstract class SessionManagerCore extends EventEmitter { } target.verified = eventBp.verified; target.verifiedBy = target.verified ? 'adapter' : undefined; + recordTreeVerifiedBreakpoint(session, target); // Where it bound: the request stays the request; a different file is // reported as boundFile/boundLine, a same-file move lands in `line`. applyBoundLocation(target, eventBp.source?.path, eventBp.line); @@ -2599,6 +2682,7 @@ export abstract class SessionManagerCore extends EventEmitter { } target.verified = result.verified; target.verifiedBy = target.verified ? 'adapter' : undefined; + recordTreeVerifiedBreakpoint(session, target); if (typeof result.id === 'number') { target.adapterId = result.id; } @@ -2650,11 +2734,14 @@ export abstract class SessionManagerCore extends EventEmitter { } if (mirrorsToChild) { target.verified = target.verified || result.verified; + recordTreeVerifiedBreakpoint(session, target); settleStoredMessage(target); continue; } target.verified = result.verified; target.verifiedBy = target.verified ? 'adapter' : undefined; + recordTreeVerifiedBreakpoint(session, target); + recordTreeVerifiedBreakpoint(session, target); if (typeof result.adapterId === 'number') { target.adapterId = result.adapterId; } diff --git a/src/session/session-manager-operations.ts b/src/session/session-manager-operations.ts index 1b25325a..3b5fa393 100644 --- a/src/session/session-manager-operations.ts +++ b/src/session/session-manager-operations.ts @@ -194,6 +194,7 @@ export abstract class SessionManagerOperations extends SessionManagerData { closeSessionReporting: (sessionId, options) => this.closeSessionReporting(sessionId, options), releaseDescendants: (session) => this.releaseDescendants(session), beginSubtreeClose: (sessionId) => this.beginSubtreeClose(sessionId), + settleInFlightChildReleases: (sessionId) => this.settleInFlightChildReleases(sessionId), getStackTrace: (sessionId, threadId, includeInternals) => this.getStackTrace(sessionId, threadId, includeInternals), getStackTraceDetailed: (sessionId, threadId, includeInternals, opts) => diff --git a/src/session/session-store.ts b/src/session/session-store.ts index 04149bfa..a69136dd 100644 --- a/src/session/session-store.ts +++ b/src/session/session-store.ts @@ -234,6 +234,22 @@ export interface Run { // the transform (undefined when there are none), consumed by // attachToProcess for the response warning. attachTransformNotices?: string[]; + /** + * Breakpoint IDs confirmed bound or hit-proven in at least one session of + * this run's tree (issue #1150). Shared across root and adopted children via + * `session.run`, surviving after short-lived child sessions close. + */ + treeVerifiedBreakpointIds?: Set; + /** + * Set when the launch or attach configuration explicitly disabled + * child-process adoption on an adapter that supports it (issue #1150). + */ + childDebuggingOptedOut?: 'subProcess: false' | 'autoAttachChildProcesses: false'; + /** + * In-flight CHILD_RELEASE_COMMAND round-trips awaiting adapter confirmation + * (issue #1221), settled before launch/end/wait answers finalize. + */ + inFlightChildReleases?: Set>; } export interface ManagedSession extends DebugSessionInfo { @@ -331,6 +347,12 @@ export interface ManagedSession extends DebugSessionInfo { * `childrenReleased`; reset per launch. */ releasedChildReports?: number; + /** + * Child reports whose adoption or release failed without adapter confirmation + * that the child process continues running (issue #1221); lineage-scoped and + * never counted in `childrenReleased`. + */ + unconfirmedChildReleases?: number; /** * Why those children were released, by cause, counted in the same call as * `releasedChildReports` (issue #1137): what lets an answer that carries diff --git a/src/utils/error-messages.ts b/src/utils/error-messages.ts index 162fb620..8c9a261a 100644 --- a/src/utils/error-messages.ts +++ b/src/utils/error-messages.ts @@ -655,6 +655,37 @@ export const ErrorMessages = { `either, read get_output, or set breakpoints — they take effect on the running program.`; }, + /** + * A launch answered while the launched root is still running AND an adopted + * child session is already paused (issue #1150): never say "has not reached + * N breakpoint(s) yet", name the paused child session directly, and point at + * `pausedChild` so the caller saves a `wait_for_stop` turn. + */ + launchRunningWithPausedChild: ( + childName: string, + childSessionId: string, + reason: string, + location?: { file: string; line: number } + ) => { + const where = location ? ` at ${location.file}:${location.line}` : ''; + return ( + `The launched process is running, and child session '${childName}' (${childSessionId}) is already paused (${reason})${where}. ` + + `Inspect, step, or continue session ${childSessionId} directly (pausedChild carries its stop snapshot).` + ); + }, + + /** + * A launch answered while the launched root is still running AND an adopted + * child session has already ended in an error state (issue #1150). + */ + launchRunningWithErroredChild: ( + childName: string, + childSessionId: string, + detail?: string + ) => + `The launched process is running, while child session '${childName}' (${childSessionId}) ended in an error state${detail ? `: ${detail}` : ''}. ` + + `Close session ${childSessionId} with close_debug_session to wait past it on the root.`, + /** * The why a session whose current launch runs with the debugger off appends diff --git a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts index bf5f74d5..09bd490b 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-tree.test.ts @@ -47,12 +47,22 @@ interface Stop extends ToolAnswer { sessionId?: string; pending?: boolean; exitCode?: number; - unhitBreakpoints?: unknown[]; + unhitBreakpoints?: Array<{ file: string; line: number; verified: boolean }>; + data?: { unhitBreakpoints?: Array<{ file: string; line: number; verified: boolean }> }; location?: { file: string; line: number }; lastStop?: { line?: number }; children?: ChildSummary[]; childrenClosed?: number; childrenReleased?: number; + pausedChild?: { + sessionId: string; + name: string; + state: string; + reason: string; + location?: { file: string; line: number }; + context?: { lineContent: string }; + snapshot?: { locals?: Record }; + }; } interface Closed extends ToolAnswer { childrenClosed?: number; processEnded?: boolean; released?: boolean } interface Output extends ToolAnswer { @@ -138,6 +148,16 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(childBp.success, JSON.stringify(childBp)).toBe(true); const started = await launch(parentFixture); expect(started.state, JSON.stringify(started)).toBe('running'); + if (started.pausedChild) { + expect(started.message, JSON.stringify(started)).not.toContain('has not reached'); + expect(started.pausedChild, JSON.stringify(started)).toMatchObject({ + state: 'paused', + reason: 'breakpoint', + location: expect.objectContaining({ line: CHILD_BREAKPOINT_LINE }), + context: expect.objectContaining({ lineContent: expect.stringContaining('total += i') }), + snapshot: expect.objectContaining({ locals: expect.objectContaining({ i: '0' }) }) + }); + } let childId: string | undefined; for (let iteration = 0; iteration < 3; iteration += 1) { @@ -540,4 +560,48 @@ describe('JavaScript forks as child sessions (the session tree, issue #1082)', ( expect(rootText).not.toContain('{"n":1}'); expect(childOutput.note).toMatch(/what it writes to a pipe is read by its parent process only/); }, 120_000); + + it('marks a fork-bound unhit breakpoint verified: true with no false unbound warning when the fork never executes that branch (issue #1150)', async () => { + const rootId = await server.createSession('javascript', 'js-tree-fork-verified-unhit'); + // Conditional false so the breakpoint binds in child.js (never loaded by parent.js) without pausing. + const bp = await call('set_breakpoint', { + file: childFixture, + line: CHILD_BREAKPOINT_LINE, + condition: 'i === 999' + }); + expect(bp.success, JSON.stringify(bp)).toBe(true); + const started = await launch(parentFixture); + const ended = started.state === 'stopped' + ? started + : await call('wait_for_stop', { sessionId: rootId, timeout: 30000 }); + expect(ended.state, JSON.stringify(ended)).toBe('stopped'); + expect(ended.warning, JSON.stringify(ended)).toBeUndefined(); + const unhit = ended.unhitBreakpoints ?? ended.data?.unhitBreakpoints; + expect(unhit, JSON.stringify(ended)).toEqual([ + expect.objectContaining({ line: CHILD_BREAKPOINT_LINE, verified: true }) + ]); + expect(ended.message, JSON.stringify(ended)).toContain(`Verified but never hit: child.js:${CHILD_BREAKPOINT_LINE}.`); + }, 120_000); + + it('qualifies the end summary and unbound warning when autoAttachChildProcesses: false turns fork debugging off (issue #1150)', async () => { + const rootId = await server.createSession('javascript', 'js-tree-opt-out'); + const bp = await call('set_breakpoint', { file: childFixture, line: CHILD_BREAKPOINT_LINE }); + expect(bp.success, JSON.stringify(bp)).toBe(true); + const started = await call('start_debugging', { + scriptPath: parentFixture, + breakOnExceptions: 'none', + dapLaunchArgs: { stopOnEntry: false, autoAttachChildProcesses: false } + }); + expect(started.success, JSON.stringify(started)).toBe(true); + const ended = started.state === 'stopped' + ? started + : await call('wait_for_stop', { sessionId: rootId, timeout: 30000 }); + expect(ended.state, JSON.stringify(ended)).toBe('stopped'); + expect(ended.message, JSON.stringify(ended)).toContain( + 'without hitting any breakpoint in the launched process (child-process debugging was off via autoAttachChildProcesses: false, so child processes were not debugged).' + ); + if (ended.warning) { + expect(ended.warning).toContain('autoAttachChildProcesses: false'); + } + }, 120_000); }); diff --git a/tests/adapters/python/integration/python-subprocess-tree.test.ts b/tests/adapters/python/integration/python-subprocess-tree.test.ts index 958c26f8..d5816228 100644 --- a/tests/adapters/python/integration/python-subprocess-tree.test.ts +++ b/tests/adapters/python/integration/python-subprocess-tree.test.ts @@ -237,6 +237,16 @@ describe('Python child processes as child sessions (the session tree, issue #108 }); expect(started.success, JSON.stringify(started)).toBe(true); expect(started.state, JSON.stringify(started)).toBe('running'); + if (started.pausedChild) { + expect(started.message, JSON.stringify(started)).not.toContain('has not reached'); + expect(started.pausedChild, JSON.stringify(started)).toMatchObject({ + state: 'paused', + reason: 'breakpoint', + location: expect.objectContaining({ line: CHILD_BREAKPOINT_LINE }), + context: expect.objectContaining({ lineContent: expect.stringContaining('total += i') }), + snapshot: expect.objectContaining({ locals: expect.objectContaining({ i: '0' }) }) + }); + } let childId: string | undefined; for (let iteration = 0; iteration < 3; iteration += 1) { @@ -379,4 +389,30 @@ describe('Python child processes as child sessions (the session tree, issue #108 const log = fs.existsSync(logFilePath) ? fs.readFileSync(logFilePath, 'utf8') : ''; expect(log).not.toContain('leaked worker'); }, 120000); + + it('qualifies the run-to-completion summary when subProcess: false turns child debugging off (issue #1150)', async () => { + const created = await call('create_debug_session', { language: 'python', name: 'subprocess-tree-opt-out' }); + expect(created.success).toBe(true); + const rootId = created.sessionId as string; + try { + const childBp = await call('set_breakpoint', { sessionId: rootId, file: childFixture, line: CHILD_BREAKPOINT_LINE }); + expect(childBp.success, JSON.stringify(childBp)).toBe(true); + const started = await call('start_debugging', { + sessionId: rootId, + scriptPath: parentFixture, + breakOnExceptions: 'none', + dapLaunchArgs: { stopOnEntry: false, subProcess: false } + }); + expect(started.success, JSON.stringify(started)).toBe(true); + const ended = started.state === 'stopped' + ? started + : await call('wait_for_stop', { sessionId: rootId, timeout: 30000 }); + expect(ended.state, JSON.stringify(ended)).toBe('stopped'); + expect(ended.message, JSON.stringify(ended)).toContain( + 'without hitting any breakpoint in the launched process (child-process debugging was off via subProcess: false, so child processes were not debugged).' + ); + } finally { + await call('close_debug_session', { sessionId: rootId }); + } + }, 120000); }); diff --git a/tests/core/unit/server/handlers/debuggee-tools.test.ts b/tests/core/unit/server/handlers/debuggee-tools.test.ts index 47aca6ac..4b13d6f2 100644 --- a/tests/core/unit/server/handlers/debuggee-tools.test.ts +++ b/tests/core/unit/server/handlers/debuggee-tools.test.ts @@ -131,6 +131,59 @@ describe('debuggee lifecycle tool handlers', () => { expect(payload).not.toHaveProperty('children'); expect(payload).not.toHaveProperty('childrenClosed'); expect(payload).not.toHaveProperty('childrenReleased'); + expect(payload).not.toHaveProperty('pausedChild'); + }); + + it(`${tool} hoists pausedChild with context and stale-build note while stripping duplicate snapshot from data.pausedChild (issue #1150)`, async () => { + ctx.buildStaleness = { check: vi.fn().mockResolvedValue(evidence) }; + const snapshot = { frames: [{ name: 'Main', file: '/app/Program.cs', line: 8 }], locals: { a: '1' } }; + const pausedChild = { + sessionId: 'child-1', + name: 'Subprocess 4242', + state: 'paused' as const, + reason: 'breakpoint', + location, + note: 'anchored', + snapshot + }; + + const payload = JSON.parse( + (await answer({ message: 'child paused', pending: true, children, pausedChild }, 'running')).content[0].text + ); + + expect(payload.pausedChild).toMatchObject({ + sessionId: 'child-1', + name: 'Subprocess 4242', + state: 'paused', + reason: 'breakpoint', + location, + context, + snapshot + }); + expect(payload.pausedChild.note).toMatch(/^anchored The compiled file .* may be stale/); + expect(payload.data.pausedChild).not.toHaveProperty('snapshot'); + expect(payload.data.pausedChild).toMatchObject({ sessionId: 'child-1', state: 'paused', reason: 'breakpoint' }); + // Original session-layer pausedChild object is not mutated. + expect(pausedChild.snapshot).toEqual(snapshot); + }); + + it(`${tool} skips context and staleness reads when pausedChild location is unresolvedSource`, async () => { + const pausedChild = { + sessionId: 'child-1', + name: 'Subprocess 4242', + state: 'paused' as const, + reason: 'breakpoint', + location: { ...location, unresolvedSource: true } + }; + + const payload = JSON.parse( + (await answer({ message: 'child paused', pending: true, children, pausedChild }, 'running')).content[0].text + ); + + expect(payload.pausedChild).toMatchObject({ sessionId: 'child-1', state: 'paused' }); + expect(payload.pausedChild).not.toHaveProperty('context'); + expect(ctx.lineReader.getLineContext).not.toHaveBeenCalled(); + expect(ctx.buildStaleness.check).not.toHaveBeenCalled(); }); } }); diff --git a/tests/core/unit/session/debug-result-data.test.ts b/tests/core/unit/session/debug-result-data.test.ts index c9101c10..d4432cfc 100644 --- a/tests/core/unit/session/debug-result-data.test.ts +++ b/tests/core/unit/session/debug-result-data.test.ts @@ -26,9 +26,9 @@ describe('DebugResultData type contract (issue #590)', () => { >(); }); - it('the launch answer adds only the stop-answer fields — the landing plus the snapshot (issues #951/#982) — and the tree fields (issue #1081)', () => { + it('the launch answer adds only the stop-answer fields — the landing plus the snapshot (issues #951/#982) — and the tree fields (issues #1081/#1150)', () => { expectTypeOf().toEqualTypeOf< - keyof DebugResultData | 'location' | 'threadId' | 'note' | 'snapshot' | 'children' | 'childrenReleased' | 'childrenClosed' + keyof DebugResultData | 'location' | 'threadId' | 'note' | 'snapshot' | 'children' | 'childrenReleased' | 'childrenClosed' | 'pausedChild' >(); }); }); diff --git a/tests/core/unit/session/session-manager-child-sessions.test.ts b/tests/core/unit/session/session-manager-child-sessions.test.ts index da0f4ac6..c813c3ba 100644 --- a/tests/core/unit/session/session-manager-child-sessions.test.ts +++ b/tests/core/unit/session/session-manager-child-sessions.test.ts @@ -1970,3 +1970,220 @@ describe('a child session is read under its own connection (issues #1211, #1220) expect(second.verified).toBe(true); }); }); + +describe('session-tree truthfulness, turn reduction & release confirmation (issues #1150, #1221)', () => { + let sessionManager: SessionManager; + let dependencies: ReturnType; + + function setup(env?: Partial>): void { + dependencies = createMockDependencies(); + if (env) { + dependencies.environment = createMockEnvironment(env); + } + sessionManager = new SessionManager( + { logDirBase: '/tmp/test-sessions', defaultDapLaunchArgs: { stopOnEntry: false, justMyCode: true } }, + dependencies + ); + } + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + setup(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + dependencies.mockProxyManager.reset(); + }); + + const childOf = (parentId: string) => sessionManager.getAllSessions().find((s) => s.parentSessionId === parentId); + + it('surfaces pausedChild with snapshot and truthful message when a child pauses during the launch hold, and waitForStop stays idempotent (#1150 item 1)', async () => { + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + await sessionManager.setBreakpoint(root.id, { file: '/w/child.py', line: 12 }); + + const starting = sessionManager.startDebugging(root.id, '/w/parent.py'); + await vi.advanceTimersByTimeAsync(20); + dependencies.mockProxyManager.simulateEvent('child-reported', report('r-paused', 5151)); + await vi.advanceTimersByTimeAsync(10); + + const child = childOf(root.id)!; + const view = dependencies.mockProxyManager.childViews.get(child.id)!; + view.setDapRequestHandler(async (command) => { + switch (command) { + case 'stackTrace': + return { + success: true, + body: { stackFrames: [{ id: 10, name: 'work', source: { path: '/w/child.py' }, line: 12, column: 1 }] } + }; + case 'scopes': + return { + success: true, + body: { scopes: [{ name: 'Locals', variablesReference: 200, expensive: false }] } + }; + case 'variables': + return { + success: true, + body: { variables: [{ name: 'i', value: '0', type: 'int', variablesReference: 0 }] } + }; + default: + return { success: true, body: {} }; + } + }); + view.simulateStopped(1, 'breakpoint', { reason: 'breakpoint', threadId: 1 }); + await vi.runAllTimersAsync(); + + const started = await starting; + expect(started.success).toBe(true); + expect(started.state).toBe(SessionState.RUNNING); + expect(started.data?.pending).toBe(true); + expect(started.data?.message).not.toContain('has not reached'); + expect(started.data?.message).toContain(`child session 'Subprocess 5151' (${child.id}) is already paused (breakpoint) at /w/child.py:12`); + expect(started.data?.children).toEqual([ + { sessionId: child.id, name: 'Subprocess 5151', state: SessionState.PAUSED, parentSessionId: root.id } + ]); + expect(started.data?.pausedChild).toMatchObject({ + sessionId: child.id, + name: 'Subprocess 5151', + state: SessionState.PAUSED, + reason: 'breakpoint', + location: { file: '/w/child.py', line: 12, column: 1 }, + snapshot: { + frames: [{ name: 'work', file: '/w/child.py', line: 12 }], + locals: { i: '0' } + } + }); + + // A caller that still invokes wait_for_stop(rootId) receives the exact same stop with full locals. + const waited = await sessionManager.waitForStop(root.id, 100); + expect(waited.state).toBe(SessionState.PAUSED); + expect(waited.data?.sessionId).toBe(child.id); + expect(waited.data?.snapshot?.locals).toEqual({ i: '0' }); + }); + + it('omits pausedChild when a child enters ERROR during the launch hold and names the errored child in message (#1150)', async () => { + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + await sessionManager.setBreakpoint(root.id, { file: '/w/child.py', line: 12 }); + + const starting = sessionManager.startDebugging(root.id, '/w/parent.py'); + await vi.advanceTimersByTimeAsync(20); + dependencies.mockProxyManager.simulateEvent('child-reported', report('r-err', 6161)); + await vi.advanceTimersByTimeAsync(10); + + const child = childOf(root.id)!; + const view = dependencies.mockProxyManager.childViews.get(child.id)!; + view.simulateError(new Error('child socket dropped')); + await vi.runAllTimersAsync(); + + const started = await starting; + expect(started.state).toBe(SessionState.RUNNING); + expect(started.data?.pausedChild).toBeUndefined(); + expect(started.data?.message).toContain(`child session 'Subprocess 6161' (${child.id}) ended in an error state`); + expect(started.data?.message).not.toContain('has not reached'); + }); + + it('suppresses root unbound-breakpoint exit warnings and marks unhitBreakpoints verified: true when an adopted child bound the breakpoint (#1150 items 2 & 3)', async () => { + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + const { breakpoint } = await sessionManager.setBreakpoint(root.id, { file: '/w/fork_only.js', line: 14 }); + + const starting = sessionManager.startDebugging(root.id, '/w/parent.js'); + await vi.advanceTimersByTimeAsync(20); + dependencies.mockProxyManager.simulateEvent('child-reported', report('r-fork', 7171)); + await vi.advanceTimersByTimeAsync(10); + + const child = childOf(root.id)!; + const view = dependencies.mockProxyManager.childViews.get(child.id)!; + // Root never verified the fork-only breakpoint; the adopted fork verified it, then exited without hitting it. + expect(sessionManager.getSession(root.id)!.breakpoints.get(breakpoint.id)!.verified).toBe(false); + view.simulateEvent('breakpoints-synced', [ + { id: breakpoint.id, file: '/w/fork_only.js', line: 14, verified: true, adapterId: 3 } + ]); + view.simulateEvent('terminated'); + dependencies.mockProxyManager.simulateEvent('exited', 0); + await vi.runAllTimersAsync(); + + const started = await starting; + expect(started.state).toBe(SessionState.STOPPED); + expect(started.data?.warning).toBeUndefined(); + expect(started.data?.unhitBreakpoints).toEqual([ + { file: '/w/fork_only.js', line: 14, verified: true } + ]); + expect(started.data?.message).toContain('Verified but never hit: fork_only.js:14.'); + }); + + it.each([ + { language: DebugLanguage.PYTHON, flag: { subProcess: false }, expected: 'subProcess: false' }, + { language: DebugLanguage.JAVASCRIPT, flag: { autoAttachChildProcesses: false }, expected: 'autoAttachChildProcesses: false' } + ])('qualifies end summary and unbound exit warning when child debugging was opted out ($expected) (#1150 items 2 & 4)', async ({ language, flag, expected }) => { + const root = await sessionManager.createSession({ language }); + const { breakpoint } = await sessionManager.setBreakpoint(root.id, { file: '/w/child_only.py', line: 9 }); + + const starting = sessionManager.startDebugging(root.id, '/w/parent.py', undefined, flag as never); + await vi.advanceTimersByTimeAsync(20); + // Simulate a breakpoint that remained unbound in the parent (e.g. JS fork-only file) on JS, + // and verified-unhit in the parent on Python. + if (language === DebugLanguage.PYTHON) { + dependencies.mockProxyManager.simulateEvent('breakpoints-synced', [ + { id: breakpoint.id, file: '/w/child_only.py', line: 9, verified: true, adapterId: 1 } + ]); + } + dependencies.mockProxyManager.simulateEvent('exited', 0); + await vi.runAllTimersAsync(); + + const started = await starting; + expect(started.state).toBe(SessionState.STOPPED); + expect(started.data?.message).toContain(`without hitting any breakpoint in the launched process (child-process debugging was off via ${expected}`); + if (language === DebugLanguage.JAVASCRIPT) { + expect(started.data?.warning).toContain(`child-process debugging was off (${expected}), so breakpoints in code only a child process loads could not bind`); + } + }); + + it('propagates grandchild releases up to the root session (#1150 item 5)', async () => { + setup({ [ 'DEBUG_MCP_MAX_CHILD_SESSIONS' ]: '1' }); + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + await sessionManager.setBreakpoint(root.id, { file: '/w/grandchild.py', line: 5 }); + await sessionManager.startDebugging(root.id, '/w/parent.py'); + await vi.runAllTimersAsync(); + + // First child adopts under cap=1. + dependencies.mockProxyManager.simulateEvent('child-reported', report('r-child', 8001)); + await vi.runAllTimersAsync(); + const child = childOf(root.id)!; + const childView = dependencies.mockProxyManager.childViews.get(child.id)!; + + // Grandchild reported on child's connection exceeds cap=1 and is released. + childView.simulateEvent('child-reported', report('r-grandchild', 8002)); + await vi.runAllTimersAsync(); + + const rootWait = await sessionManager.waitForStop(root.id, 50); + const childWait = await sessionManager.waitForStop(child.id, 50); + expect(rootWait.data?.childrenReleased).toBe(1); + expect(rootWait.data?.message).toContain('1 child process was released to run undebugged'); + expect(childWait.data?.childrenReleased).toBe(1); + }); + + it('does not count or claim released to run undebugged when the adapter does not confirm a failed adoption release (#1221)', async () => { + dependencies.mockProxyManager.childReleaseConfirmed = false; + const origCreateChildView = dependencies.mockProxyManager.createChildView.bind(dependencies.mockProxyManager); + vi.spyOn(dependencies.mockProxyManager, 'createChildView').mockImplementation((id) => { + const view = origCreateChildView(id); + vi.spyOn(view, 'adopt').mockRejectedValue(new Error('adapter socket closed')); + return view; + }); + + const root = await sessionManager.createSession({ language: DebugLanguage.MOCK }); + await sessionManager.setBreakpoint(root.id, { file: '/w/child.py', line: 12 }); + const starting = sessionManager.startDebugging(root.id, '/w/parent.py'); + await vi.advanceTimersByTimeAsync(20); + dependencies.mockProxyManager.simulateEvent('child-reported', report('r-unconfirmed', 9001)); + await vi.runAllTimersAsync(); + + const started = await starting; + expect(started.data?.childrenReleased).toBeUndefined(); + expect(started.data?.message).not.toContain('released to run undebugged'); + expect(started.data?.message).toContain( + '1 child process could not be adopted, and the debug adapter did not confirm releasing it; whether it continued running is not known.' + ); + }); +}); diff --git a/tests/proxy/child-connections.test.ts b/tests/proxy/child-connections.test.ts index bc8dae4c..3af98a02 100644 --- a/tests/proxy/child-connections.test.ts +++ b/tests/proxy/child-connections.test.ts @@ -1763,3 +1763,165 @@ describe("ChildConnections: an adopted child's proxy stepper (issue #1130)", () expect(cdpClients).toHaveLength(0); }); }); + +describe('ChildConnections: release confirmation outcomes (issue #1221)', () => { + it('confirms a reject-request release when the reporting client acknowledges it, and marks unconfirmed when the socket cannot write', async () => { + const sent: Array> = []; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const connections = new ChildConnections({ + messageSender: { send: (m) => sent.push(m as unknown as Record) }, + logger, + adoption: { + dapClientFactory: { create: vi.fn() }, + connectionManager: { + initializeSession: vi.fn(), + sendAttachRequest: vi.fn(), + setExceptionBreakpoints: vi.fn(), + setBreakpoints: vi.fn(), + sendConfigurationDone: vi.fn(), + disconnect: vi.fn() + }, + policy: PythonAdapterPolicy, + host: '127.0.0.1', + port: 5678, + adapterId: 'python' + } + }); + const rootClient = new EventEmitter() as EventEmitter & { + respondToReverseRequest: ReturnType; + }; + rootClient.respondToReverseRequest = vi.fn(() => true); + connections.attach(rootClient as never, 'root-1'); + + rootClient.emit('child-report', { + request: { seq: 1, type: 'request', command: 'startDebugging' }, + report: { targetId: '101', name: 'Subprocess 101', configuration: { subProcessId: 101 } } + }); + const firstId = sent.find((m) => m.status === 'child_reported')!.reportId as string; + await expect(connections.releaseWithConfirmation(firstId, 'cap')).resolves.toEqual({ held: true, released: true }); + + rootClient.respondToReverseRequest.mockReturnValueOnce(false); + rootClient.emit('child-report', { + request: { seq: 2, type: 'request', command: 'startDebugging' }, + report: { targetId: '102', name: 'Subprocess 102', configuration: { subProcessId: 102 } } + }); + const secondId = sent.filter((m) => m.status === 'child_reported').at(-1)!.reportId as string; + await expect(connections.releaseWithConfirmation(secondId, 'cap')).resolves.toEqual({ held: true, released: false }); + }); + + it('joins a failed throwaway-attach adoption outcome and reports unconfirmed when the throwaway attach fails', async () => { + const sent: Array> = []; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const adoptClient = new EventEmitter() as EventEmitter & { + connect: ReturnType; + sendRequest: ReturnType; + shutdown: ReturnType; + }; + adoptClient.connect = vi.fn().mockRejectedValue(new Error('connect ECONNREFUSED')); + adoptClient.sendRequest = vi.fn(); + adoptClient.shutdown = vi.fn(); + + const failReleaseClient = new EventEmitter() as EventEmitter & { + connect: ReturnType; + sendRequest: ReturnType; + shutdown: ReturnType; + }; + failReleaseClient.connect = vi.fn().mockRejectedValue(new Error('connect ECONNREFUSED')); + failReleaseClient.sendRequest = vi.fn(); + failReleaseClient.shutdown = vi.fn(); + + const connections = new ChildConnections({ + messageSender: { send: (m) => sent.push(m as unknown as Record) }, + logger, + adoption: { + dapClientFactory: { + create: vi.fn().mockReturnValueOnce(adoptClient).mockReturnValueOnce(failReleaseClient) + }, + connectionManager: { + initializeSession: vi.fn(), + sendAttachRequest: vi.fn(), + setExceptionBreakpoints: vi.fn(), + setBreakpoints: vi.fn(), + sendConfigurationDone: vi.fn(), + disconnect: vi.fn() + }, + policy: JsDebugAdapterPolicy, + host: '127.0.0.1', + port: 9229, + adapterId: 'pwa-node' + } + }); + const rootClient = new EventEmitter() as EventEmitter & { + respondToReverseRequest: ReturnType; + }; + rootClient.respondToReverseRequest = vi.fn(() => true); + connections.attach(rootClient as never, 'root-js'); + + rootClient.emit('child-report', { + request: { seq: 7, type: 'request', command: 'startDebugging' }, + report: { targetId: 't-1', name: 'child.js [99]', configuration: { __pendingTargetId: 't-1' } } + }); + const reportId = sent.find((m) => m.status === 'child_reported')!.reportId as string; + + await expect(connections.adopt('child-js', { reportId, breakpoints: [] })).rejects.toThrow('connect ECONNREFUSED'); + await expect(connections.releaseWithConfirmation(reportId, 'adoption failed')).resolves.toEqual({ + held: false, + released: false + }); + }); + + it('marks the outcome closed: true when close() cancels an in-flight adoption', async () => { + const sent: Array> = []; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const adoptClient = new EventEmitter() as EventEmitter & { + connect: ReturnType; + sendRequest: ReturnType; + shutdown: ReturnType; + }; + adoptClient.connect = vi.fn(() => new Promise(() => {})); + adoptClient.sendRequest = vi.fn(); + adoptClient.shutdown = vi.fn(); + + const connections = new ChildConnections({ + messageSender: { send: (m) => sent.push(m as unknown as Record) }, + logger, + adoption: { + dapClientFactory: { create: vi.fn().mockReturnValue(adoptClient) }, + connectionManager: { + initializeSession: vi.fn(), + sendAttachRequest: vi.fn(), + setExceptionBreakpoints: vi.fn(), + setBreakpoints: vi.fn(), + sendConfigurationDone: vi.fn(), + disconnect: vi.fn().mockResolvedValue({ answered: true }) + }, + policy: PythonAdapterPolicy, + host: '127.0.0.1', + port: 5678, + adapterId: 'python' + } + }); + const rootClient = new EventEmitter() as EventEmitter & { + respondToReverseRequest: ReturnType; + }; + rootClient.respondToReverseRequest = vi.fn(() => true); + connections.attach(rootClient as never, 'root-py'); + + rootClient.emit('child-report', { + request: { seq: 3, type: 'request', command: 'startDebugging' }, + report: { targetId: '103', name: 'Subprocess 103', configuration: { subProcessId: 103 } } + }); + const reportId = sent.find((m) => m.status === 'child_reported')!.reportId as string; + + const adopting = connections.adopt('child-py', { reportId, breakpoints: [] }); + const closedAdoption = expect(adopting).rejects.toThrow('child session closed during adoption'); + await connections.close('child-py', { terminateDebuggee: true }); + await closedAdoption; + + await expect(connections.releaseWithConfirmation(reportId, 'adoption failed')).resolves.toEqual({ + held: false, + released: false, + closed: true + }); + }); +}); diff --git a/tests/test-utils/mocks/mock-proxy-manager.ts b/tests/test-utils/mocks/mock-proxy-manager.ts index f031b439..d5b709ae 100644 --- a/tests/test-utils/mocks/mock-proxy-manager.ts +++ b/tests/test-utils/mocks/mock-proxy-manager.ts @@ -38,6 +38,8 @@ export class MockProxyManager extends EventEmitter implements IProxyManager { public proxyPid: number | null = 4242; /** Reported by getAdapterStderrTail() (issue #897); settable per-test. */ public adapterStderrTail: string[] = []; + /** Test seam for childRelease adapter confirmation (issue #1221); true by default. */ + public childReleaseConfirmed = true; constructor() { super(); @@ -190,6 +192,12 @@ export class MockProxyManager extends EventEmitter implements IProxyManager { body: { closed: true, closedClients: 0 } } as T; + case 'childRelease': + return { + success: true, + body: { held: true, released: this.childReleaseConfirmed } + } as T; + default: return { success: true } as T; } diff --git a/tests/unit/shared/adapter-policy-js.test.ts b/tests/unit/shared/adapter-policy-js.test.ts index 507b3ebf..64f40a20 100644 --- a/tests/unit/shared/adapter-policy-js.test.ts +++ b/tests/unit/shared/adapter-policy-js.test.ts @@ -365,8 +365,8 @@ describe('JsDebugAdapterPolicy', () => { const frames = [{ id: 1 }]; const scopes = { 1: [ - { name: 'Local', variablesReference: 1 }, { name: 'Block', variablesReference: 2 }, + { name: 'Local', variablesReference: 1 }, { name: 'Global', variablesReference: 3 } ] }; @@ -381,7 +381,7 @@ describe('JsDebugAdapterPolicy', () => { // A program's own name that merely looks alike stays. { name: '__vite_config', value: '{}' } ], - // A scope that holds nothing but the transform's bindings supplies nothing. + // An inner block scope that holds nothing but the transform's bindings supplies nothing. 2: [{ name: '__vite_ssr_import_3__', value: 'Module {ErrorMessages: }' }] }; @@ -397,6 +397,38 @@ describe('JsDebugAdapterPolicy', () => { ); }); + it('omits outer Block scopes listed after Local when Local has bindings, while falling back when Local is empty (issue #1252)', () => { + const frames = [{ id: 1 }]; + const scopes = { + 1: [ + { name: 'Local', variablesReference: 1 }, + { name: 'Block', variablesReference: 2 }, + { name: 'Global', variablesReference: 3 } + ] + }; + const nonEmptyLocal = JsDebugAdapterPolicy.extractLocalVariables( + frames as any, + scopes as any, + { + 1: [{ name: 'sessionId', value: "'s1'" }], + 2: [{ name: 'DEFAULT_HOLD_MS', value: '2000' }, { name: 'DebugLauncher', value: 'class DebugLauncher' }] + } as any + ); + expect(nonEmptyLocal.variables.map((variable) => variable.name)).toEqual(['sessionId']); + expect(nonEmptyLocal.scopeRefs).toEqual([1]); + + const emptyLocal = JsDebugAdapterPolicy.extractLocalVariables( + frames as any, + scopes as any, + { + 1: [{ name: 'this', value: 'undefined' }], + 2: [{ name: 'capturedConfig', value: '{ port: 3000 }' }] + } as any + ); + expect(emptyLocal.variables.map((variable) => variable.name)).toEqual(['capturedConfig']); + expect(emptyLocal.scopeRefs).toEqual([2]); + }); + it('does not relabel Global as locals when no Local or block scope exists (#595)', () => { const result = JsDebugAdapterPolicy.extractLocalVariables!( [{ id: 9 }] as any,