diff --git a/CHANGELOG.md b/CHANGELOG.md index 6750489..af7ec79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/docs/architecture/debuggingExecutor.md b/docs/architecture/debuggingExecutor.md index a9450aa..5d9fbb2 100644 --- a/docs/architecture/debuggingExecutor.md +++ b/docs/architecture/debuggingExecutor.md @@ -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 @@ -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. diff --git a/src/debuggingExecutor.ts b/src/debuggingExecutor.ts index a2b8fc7..c29be26 100644 --- a/src/debuggingExecutor.ts +++ b/src/debuggingExecutor.ts @@ -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 { if (!this.sessionTracker) { @@ -402,6 +414,10 @@ export class DebuggingExecutor implements IDebuggingExecutor { * Get current debugging state */ public async getCurrentDebugState(numNextLines: number = 3): Promise { + return this.readDebugState(numNextLines, 1); + } + + private async readDebugState(numNextLines: number, attempt: number): Promise { const state = new DebugState(); try { @@ -409,7 +425,12 @@ export class DebuggingExecutor implements IDebuggingExecutor { 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); @@ -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) { diff --git a/src/test/debugSessionTracker.test.ts b/src/test/debugSessionTracker.test.ts index ccd2876..91e6b61 100644 --- a/src/test/debugSessionTracker.test.ts +++ b/src/test/debugSessionTracker.test.ts @@ -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'); diff --git a/src/test/frameSelection.test.ts b/src/test/frameSelection.test.ts new file mode 100644 index 0000000..1f1b41c --- /dev/null +++ b/src/test/frameSelection.test.ts @@ -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; + 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(); + 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'); + }); +}); diff --git a/src/utils/debugSessionTracker.ts b/src/utils/debugSessionTracker.ts index cc23838..afba833 100644 --- a/src/utils/debugSessionTracker.ts +++ b/src/utils/debugSessionTracker.ts @@ -13,6 +13,9 @@ interface ISessionExecutionState { defaultStopSequence?: number; threadStopSequences: Map; pendingResumes: Map; + /** The stop for which VS Code has published a selected frame, or for which waiting was given up. */ + frameSelectionSequence?: number; + frameSelectionWaiters: Set<() => void>; } interface IResumeRequest { @@ -27,7 +30,8 @@ const RESUME_COMMANDS = new Set([ ]); type DebugTrackerApi = Pick; + 'registerDebugAdapterTrackerFactory' | 'onDidTerminateDebugSession'> & + Partial>; function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); @@ -43,8 +47,10 @@ export class DebugSessionTracker implements vscode.Disposable { private readonly subscriptions: vscode.Disposable[]; private revision = 0; private disposed = false; + private readonly observesFrameSelection: boolean; constructor(api: DebugTrackerApi = vscode.debug, public readonly output = new DebugOutputBuffer()) { + this.observesFrameSelection = api.onDidChangeActiveStackItem !== undefined; this.subscriptions = [ api.registerDebugAdapterTrackerFactory('*', { createDebugAdapterTracker: session => { @@ -55,6 +61,7 @@ export class DebugSessionTracker implements vscode.Disposable { threads: new Map(), threadStopSequences: new Map(), pendingResumes: new Map(), + frameSelectionWaiters: new Set(), unscopedStop: false, revision: ++this.revision }; @@ -84,6 +91,10 @@ export class DebugSessionTracker implements vscode.Disposable { }), api.onDidTerminateDebugSession(session => this.endSession(session)) ]; + const frameSelection = api.onDidChangeActiveStackItem?.(item => this.observeFrameSelection(item)); + if (frameSelection) { + this.subscriptions.push(frameSelection); + } } public getPausedState(sessionId: string, threadId?: number): boolean | undefined { @@ -126,14 +137,80 @@ export class DebugSessionTracker implements vscode.Disposable { return this.endedSessions.has(session); } + /** + * Resolve once VS Code has selected a stack frame for the latest observed + * stop, or after `timeoutMs`. + * + * The `stopped` event is observed here before VS Code has requested the + * call stack and focused a frame, so a state read in that window is paused + * with no frame, stack or location, or still carries the previous stop's + * frame. A stop that never gets a frame (no readable stack, or a stop that + * keeps the existing focus) is waited for only once. + */ + public async waitForFrameSelection(sessionId: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const state = this.sessions.get(sessionId); + const stop = state ? this.pendingFrameSelection(sessionId, state) : undefined; + if (!state || stop === undefined) { + return; + } + const remaining = deadline - Date.now(); + if (remaining <= 0) { + state.frameSelectionSequence = stop; + return; + } + await new Promise(resolve => { + const wake = () => { + clearTimeout(timer); + state.frameSelectionWaiters.delete(wake); + resolve(); + }; + const timer = setTimeout(wake, remaining); + state.frameSelectionWaiters.add(wake); + }); + } + } + public dispose(): void { this.disposed = true; this.subscriptions.forEach(subscription => subscription.dispose()); + this.sessions.forEach(state => this.wakeFrameSelectionWaiters(state)); this.sessions.clear(); this.output.clear(); } + /** The stop sequence still waiting for a selected frame, if any. */ + private pendingFrameSelection(sessionId: string, state: ISessionExecutionState): number | undefined { + if (!this.observesFrameSelection || state.stopSequence === undefined || + state.frameSelectionSequence === state.stopSequence || + this.getPausedState(sessionId) !== true) { + return undefined; + } + return state.stopSequence; + } + + private observeFrameSelection(item: vscode.DebugThread | vscode.DebugStackFrame | undefined): void { + if (!item || !('frameId' in item)) { + return; + } + const state = this.sessions.get(item.session.id); + if (!state || state.stopSequence === undefined) { + return; + } + state.frameSelectionSequence = state.stopSequence; + this.wakeFrameSelectionWaiters(state); + } + + private wakeFrameSelectionWaiters(state: ISessionExecutionState): void { + [...state.frameSelectionWaiters].forEach(wake => wake()); + } + private endSession(session: vscode.DebugSession): void { + const state = this.sessions.get(session.id); + if (state) { + this.wakeFrameSelectionWaiters(state); + } this.sessions.delete(session.id); // Do not retain terminated sessions, but reject a lagging active UI session. this.endedSessions.add(session); @@ -203,6 +280,7 @@ export class DebugSessionTracker implements vscode.Disposable { } else if (threadId !== undefined) { state.threads.set(threadId, false); } + this.wakeFrameSelectionWaiters(state); } private observeRequest(state: ISessionExecutionState, message: unknown): void { @@ -240,10 +318,17 @@ export class DebugSessionTracker implements vscode.Disposable { return; } state.pendingResumes.delete(message.request_seq); - if (message.success !== true || message.command !== request.command) { + // The response is already correlated by request_seq. Some adapters leave + // `command` and `body` empty on success or change the command's casing: + // Business Central's AL adapter answers `next` and `continue` with + // `"command": null, "body": null`. Only a command naming another request + // rules the response out. + const command = message.command ?? undefined; + if (message.success !== true || (command !== undefined && + (typeof command !== 'string' || command.toLowerCase() !== request.command.toLowerCase()))) { return; } - const body = message.body; + const body = message.body ?? undefined; if (body !== undefined && !isRecord(body)) { logger.warn('Ignoring malformed DAP resume response.'); return; @@ -280,5 +365,6 @@ export class DebugSessionTracker implements vscode.Disposable { return; } state.revision = ++this.revision; + this.wakeFrameSelectionWaiters(state); } }