Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this

### Fixed
- Standalone CLI breakpoint tools remain usable between debug sessions. Adding, removing, and clearing breakpoints after termination, stopping, disposal, or failed startup no longer try to synchronize with an inactive adapter; saved changes are applied on the next launch (#161).
- The first state returned after a stop, step, or continue in VS Code includes the frame, call stack, and location. Previously it could be read before VS Code had selected a frame for the stop, reporting a pause with no frame or the previous stop's frame (#201).
- Successful step and continue responses are recognized when the adapter leaves `command` empty or changes its casing, as Business Central's AL adapter does. Such sessions no longer stay marked as paused while running, and a state read overtaken by the end of a step is repeated instead of being returned empty (#202).

### Added
- **Claude Code auto-registration** - Claude Code is now offered in the agent selection popup and configured via `~/.claude.json`'s user-scope `mcpServers` field. Claude Desktop connects via its Custom Connector UI instead of a static config file; the README's manual configuration section covers both.
Expand Down
13 changes: 13 additions & 0 deletions docs/architecture/debuggingExecutor.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,16 @@ necessarily the physical stop at the top of the stack. The call stack retains
adapter order. If the selected frame is absent from the bounded stack response,
its name and source remain unavailable rather than borrowing top-frame metadata.

A stopped event is observed before VS Code has requested the call stack and
selected a frame for it. A state read in that gap waits, bounded, for the frame
selection of the latest stop (`DebugSessionTracker.waitForFrameSelection()`), so
the first state after a stop, step, or continue carries the frame, call stack,
and location rather than an empty or previous-stop context. A stop that never
gets a frame is waited for once and then reported as a frameless pause.
A read that began before a stop and finished after it (a step completed while
the stack request was in flight) holds no frame for that stop; it is repeated,
bounded, instead of being returned as the new stop's state.

Frame/thread context is populated before source lookup. A missing or unreadable
source does not discard that context or mean that execution is running. Paused
status is also independent of frames: an observed stop with an empty stack still
Expand All @@ -173,6 +183,9 @@ not establish a pause.
resume responses. Adapters need not emit `continued` for client-requested
execution. The tracker records outbound resume requests and clears paused state
only on their successful matching responses, respecting thread-specific resumes.
Responses are matched by `request_seq`; an empty or differently cased `command`
does not rule one out, because some adapters (Business Central's AL adapter)
answer `next` and `continue` with `"command": null`.
Failed or unrelated responses do not resume execution. Stops newer than the
request remain observable even if they arrive before its response. Pending
request correlation is bounded and is discarded with the session.
Expand Down
35 changes: 32 additions & 3 deletions src/debuggingExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,19 @@ export class DebuggingExecutor implements IDebuggingExecutor {
// Kept small relative to the router/tool backstops so it fails fast.
private static readonly DAP_REQUEST_TIMEOUT_MS = 30_000;

constructor(private readonly sessionTracker?: DebugSessionTracker) {}
// How long a state read waits for VS Code to select a frame after a stop
// was observed on the wire. Only a stop that never gets a frame pays it in
// full, and only once.
private static readonly FRAME_SELECTION_GRACE_MS = 2_000;

// A state read that a new stop overtakes is repeated; the bound keeps a
// target that keeps moving from holding the caller.
private static readonly MAX_STATE_READS = 3;

constructor(
private readonly sessionTracker?: DebugSessionTracker,
private readonly frameSelectionGraceMs: number = DebuggingExecutor.FRAME_SELECTION_GRACE_MS
) {}

public getDebugOutput(query: IDebugOutputQuery): ReturnType<DebugOutputBuffer['read']> {
if (!this.sessionTracker) {
Expand Down Expand Up @@ -402,14 +414,23 @@ export class DebuggingExecutor implements IDebuggingExecutor {
* Get current debugging state
*/
public async getCurrentDebugState(numNextLines: number = 3): Promise<DebugState> {
return this.readDebugState(numNextLines, 1);
}

private async readDebugState(numNextLines: number, attempt: number): Promise<DebugState> {
const state = new DebugState();

try {
const activeSession = vscode.debug.activeDebugSession;
if (activeSession && !this.sessionTracker?.hasSessionEnded(activeSession)) {
state.sessionActive = true;
state.updateConfigurationName(activeSession.configuration.name ?? null);


// A stop is observed on the wire before VS Code has fetched the
// call stack and selected a frame for it. Reading now would
// report a pause without frame, stack or location.
await this.sessionTracker?.waitForFrameSelection(activeSession.id, this.frameSelectionGraceMs);

const selectedItem = vscode.debug.activeStackItem;
const activeStackItem = selectedItem?.session.id === activeSession.id ? selectedItem : undefined;
const revision = this.sessionTracker?.getRevision(activeSession.id);
Expand Down Expand Up @@ -440,8 +461,16 @@ export class DebuggingExecutor implements IDebuggingExecutor {
const paused = sessionActive && currentSession
? this.sessionTracker?.getPausedState(currentSession.id, currentItem?.threadId) ?? null
: null;
const executionMoved = this.sessionTracker?.getRevision(activeSession.id) !== revision;
if (executionMoved && paused === true && currentSession?.id === activeSession.id &&
attempt < DebuggingExecutor.MAX_STATE_READS) {
// The read began before a stop and finished after it (a step
// completed meanwhile), so it holds no frame for that stop.
// Returning it would present the new stop without a frame.
return await this.readDebugState(numNextLines, attempt + 1);
}
if (!sessionActive || currentSession?.id !== activeSession.id || paused === false ||
this.sessionTracker?.getRevision(activeSession.id) !== revision ||
executionMoved ||
!currentItem || !('frameId' in currentItem) ||
!activeStackItem || !('frameId' in activeStackItem) ||
currentItem.frameId !== activeStackItem.frameId || currentItem.threadId !== activeStackItem.threadId) {
Expand Down
12 changes: 12 additions & 0 deletions src/test/debugSessionTracker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,18 @@ suite('DAP successful resume responses (#177)', () => {
assert.equal(fixture.tracker.getPausedState(session.id, 0), true);
});

// Business Central's AL adapter answers `next` and `continue` with
// `"command": null, "body": null` and lowercases the commands it does name
// (`stacktrace`).
for (const [command, answered] of [['next', null], ['continue', null], ['stepIn', 'stepin']] as const) {
test(`${command} success resumes when the response names the command as ${answered}`, () => {
resumeRequest(adapter, command);
adapter.onDidSendMessage?.({ type: 'response', request_seq: 42, command: answered, success: true, body: null });
assert.equal(fixture.tracker.getPausedState(session.id), false);
assert.equal(fixture.tracker.getStopSequence(session.id), undefined);
});
}

test('uncorrelated, mismatched, malformed, and non-resuming responses do not resume', () => {
resumeResponse(adapter, 'continue');
resumeRequest(adapter, 'continue');
Expand Down
147 changes: 147 additions & 0 deletions src/test/frameSelection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright (c) Microsoft Corporation.

import * as vscode from 'vscode';
import * as assert from 'node:assert/strict';
import { DebuggingExecutor } from '../debuggingExecutor';
import { DebuggingHandler } from '../debuggingHandler';
import { DebugConfigurationManager } from '../utils/debugConfigurationManager';
import { DebugSessionTracker } from '../utils/debugSessionTracker';

type StackItem = vscode.DebugThread | vscode.DebugStackFrame | undefined;

const frame = (id: number, name: string, line: number) =>
({ id, name, line, column: 1, source: { path: __filename } });

/**
* A DAP `stopped` event is observed before VS Code has requested the call
* stack and selected a frame. These tests drive that gap by hand: the adapter
* tracker receives the stop first, the frame selection arrives later.
*/
suite('Debug state right after a stop', () => {
let tracker: DebugSessionTracker;
let selection: vscode.EventEmitter<StackItem>;
let adapter: vscode.DebugAdapterTracker;
let session: vscode.DebugSession;
let stackItem: StackItem;
let sessionDescriptor: PropertyDescriptor;
let stackDescriptor: PropertyDescriptor;

const stopped = () => adapter.onDidSendMessage?.({ type: 'event', event: 'stopped', body: { threadId: 1 } });
const continued = () => adapter.onDidSendMessage?.({ type: 'event', event: 'continued', body: { threadId: 1 } });
/** VS Code publishing the item it focused, as it does after fetching the call stack. */
const select = (frameId?: number) => {
stackItem = frameId === undefined ? { session, threadId: 1 } : { session, threadId: 1, frameId };
selection.fire(stackItem);
};

setup(async () => {
selection = new vscode.EventEmitter<StackItem>();
let factory: vscode.DebugAdapterTrackerFactory | undefined;
tracker = new DebugSessionTracker({
registerDebugAdapterTrackerFactory: (_type, registered) => {
factory = registered;
return new vscode.Disposable(() => { /* noop */ });
},
onDidTerminateDebugSession: () => new vscode.Disposable(() => { /* noop */ }),
onDidChangeActiveStackItem: selection.event
});
session = {
id: 'frame-selection',
name: 'frame-selection',
type: 'node',
configuration: { name: 'frame-selection', type: 'node', request: 'launch' },
workspaceFolder: undefined,
customRequest: async () => ({ stackFrames: [frame(11, 'work', 1)] }),
getDebugProtocolBreakpoint: async () => undefined
};
adapter = (await factory!.createDebugAdapterTracker(session))!;
stackItem = undefined;
sessionDescriptor = Object.getOwnPropertyDescriptor(vscode.debug, 'activeDebugSession')!;
stackDescriptor = Object.getOwnPropertyDescriptor(vscode.debug, 'activeStackItem')!;
Object.defineProperty(vscode.debug, 'activeDebugSession', { configurable: true, get: () => session });
Object.defineProperty(vscode.debug, 'activeStackItem', { configurable: true, get: () => stackItem });
});

teardown(() => {
Object.defineProperty(vscode.debug, 'activeDebugSession', sessionDescriptor);
Object.defineProperty(vscode.debug, 'activeStackItem', stackDescriptor);
tracker.dispose();
selection.dispose();
});

test('the first status after a stop carries the frame, stack and location', async () => {
const handler = new DebuggingHandler(new DebuggingExecutor(tracker, 5_000), new DebugConfigurationManager(), 5);
// The breakpoint is hit: the stop is on the wire, VS Code focuses the
// thread first and the frame only after it has fetched the call stack.
stopped();
select();
setTimeout(() => select(11), 40);

const result = JSON.parse(await handler.handleGetDebugStatus({ waitForPauseSeconds: 5 }));

assert.equal(result.status, 'paused');
assert.equal(result.state.frameId, 11);
assert.equal(result.state.frameName, 'work');
assert.deepEqual(result.state.stackTrace, ['work:1']);
assert.equal(result.state.fileFullPath, __filename);
assert.equal(result.state.currentLine, 1);
});

test('a stop right after a continue does not report the previous frame', async () => {
const executor = new DebuggingExecutor(tracker, 5_000);
stopped();
select(11);
assert.equal((await executor.getCurrentDebugState()).frameId, 11);

// Continue, then stop again before VS Code has replaced the focused frame.
continued();
stopped();
session.customRequest = async () => ({ stackFrames: [frame(12, 'next', 2)] });
setTimeout(() => select(12), 40);

const state = await executor.getCurrentDebugState();

assert.equal(state.frameId, 12);
assert.equal(state.frameName, 'next');
assert.equal(state.currentLine, 2);
});

test('a read overtaken by a step reports the new stop, not an empty pause', async () => {
const executor = new DebuggingExecutor(tracker, 5_000);
stopped();
select(11);
// The adapter answers the stack request only once the step has finished:
// the new stop is observed while the read of the old one is in flight.
let requests = 0;
session.customRequest = async () => {
if (++requests === 1) {
stopped();
setTimeout(() => select(12), 40);
return { stackFrames: [frame(11, 'work', 1)] };
}
return { stackFrames: [frame(12, 'next', 2)] };
};

const state = await executor.getCurrentDebugState();

assert.equal(state.isPaused(), true);
assert.equal(state.frameId, 12);
assert.equal(state.frameName, 'next');
assert.equal(state.currentLine, 2);
});

test('a stop without any frame is reported as paused after one grace period', async () => {
const executor = new DebuggingExecutor(tracker, 80);
stopped();

const started = Date.now();
const state = await executor.getCurrentDebugState();
assert.ok(Date.now() - started >= 60, 'the first read gives VS Code the grace period');
assert.equal(state.isPaused(), true);
assert.equal(state.frameId, null);

const again = Date.now();
assert.equal((await executor.getCurrentDebugState()).isPaused(), true);
assert.ok(Date.now() - again < 60, 'later reads of the same stop return at once');
});
});
Loading