From 45d5c746428c2249c642635766d58d774f3d1cca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fekete=20G=C3=A1bor?= Date: Wed, 2 Sep 2026 16:55:26 +0200 Subject: [PATCH 1/5] feat: support virtual source URI breakpoints --- CHANGELOG.md | 7 +++- README.md | 18 +++++++--- docs/architecture/debugMCPServer.md | 6 ++-- docs/architecture/debuggingHandler.md | 8 +++++ src/debugMCPServer.ts | 17 +++++---- src/debuggingHandler.ts | 23 ++++++------ src/routingDebuggingHandler.ts | 43 ++++++++++++++++------- src/test/debuggingHandler.test.ts | 49 ++++++++++++++++++++++++++ src/test/routing.test.ts | 50 ++++++++++++++++++++++++++- src/test/sourceUri.test.ts | 34 ++++++++++++++++++ src/utils/sourceUri.ts | 21 +++++++++++ 11 files changed, 238 insertions(+), 38 deletions(-) create mode 100644 src/test/sourceUri.test.ts create mode 100644 src/utils/sourceUri.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2082145..bf5d9db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to DebugMCP will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Added +- Breakpoint, logpoint, and removal tools now support VS Code virtual-document URIs, including Business Central `al-preview:` `.dal` sources. An optional `workingDirectory` selects the correct workspace when multiple editor windows are open. + ## [2.3.0] - 2026-07-28 ### Changed @@ -100,4 +105,4 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this - Initial release - Core debugging capabilities via MCP protocol - VS Code Debug Adapter Protocol integration -- Automatic MCP server startup on extension activation \ No newline at end of file +- Automatic MCP server startup on extension activation diff --git a/README.md b/README.md index b4756c3..d84b0c2 100644 --- a/README.md +++ b/README.md @@ -60,9 +60,9 @@ DebugMCP is an MCP server that gives AI coding agents full control over the VS C | **continue_execution** | Continue until next breakpoint | None | | **pause_execution** | Interrupt a freely-running program and stop at its current location (no breakpoint needed) | None | | **restart_debugging** | Restart the current debug session | None | -| **add_breakpoint** | Add a breakpoint at a specific line (optionally conditional) | `fileFullPath` (required)
`line` (required, 1-based)
`condition` (optional) | -| **add_logpoint** | Add a logpoint that logs a message (instead of pausing) when a line is reached | `fileFullPath` (required)
`line` (required, 1-based)
`logMessage` (required, `{expr}` interpolated)
`condition` (optional) | -| **remove_breakpoint** | Remove a breakpoint from a specific line | `fileFullPath` (required)
`line` (required) | +| **add_breakpoint** | Add a breakpoint at a specific line (optionally conditional) | `fileFullPath` (required; path or virtual URI)
`workingDirectory` (optional; identifies the window for virtual URIs)
`line` (required, 1-based)
`condition` (optional) | +| **add_logpoint** | Add a logpoint that logs a message (instead of pausing) when a line is reached | `fileFullPath` (required; path or virtual URI)
`workingDirectory` (optional; identifies the window for virtual URIs)
`line` (required, 1-based)
`logMessage` (required, `{expr}` interpolated)
`condition` (optional) | +| **remove_breakpoint** | Remove a breakpoint from a specific line | `fileFullPath` (required; path or virtual URI)
`workingDirectory` (optional; identifies the window for virtual URIs)
`line` (required) | | **clear_all_breakpoints** | Remove all breakpoints at once | None | | **list_breakpoints** | List all active breakpoints | None | | **list_variable_names** | List names and types of variables in scope, without reading any values | `scope` (optional: 'local', 'global', 'all') | @@ -156,6 +156,16 @@ DebugMCP supports debugging for the following languages with their respective VS | **PHP** | [PHP Debug](https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug) | `.php` | ✅ Fully Supported | | **Ruby** | [Ruby](https://marketplace.visualstudio.com/items?itemName=rebornix.ruby) | `.rb` | ✅ Fully Supported | | **C#/.NET** | [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) | `.cs`, `.csproj` | ✅ Fully Supported | +| **AL (Business Central)** | [AL Language](https://marketplace.visualstudio.com/items?itemName=ms-dynamics-smb.al) | `.al`, virtual `.dal` | ✅ Supported with an AL launch configuration | + +### Virtual source documents + +Breakpoint tools accept native filesystem paths and VS Code virtual-document URIs. This +supports generated or downloaded sources that a language extension exposes without a local +file, including Business Central dependency objects such as +`al-preview://AlLang/.../Table/18/Customer.dal`. When multiple editor windows are open, +pass `workingDirectory` with the virtual URI so DebugMCP routes the operation to the correct +workspace. ## Configuration @@ -499,4 +509,4 @@ If DebugMCP has helped you debug faster, please consider giving it a star on Git MIT License - See [LICENSE](LICENSE.txt) for details -This extension was created by **Oz Zafar**, **Ori Bar-Ilan** and **Karin Brisker**. \ No newline at end of file +This extension was created by **Oz Zafar**, **Ori Bar-Ilan** and **Karin Brisker**. diff --git a/docs/architecture/debugMCPServer.md b/docs/architecture/debugMCPServer.md index eaef45b..8aef03d 100644 --- a/docs/architecture/debugMCPServer.md +++ b/docs/architecture/debugMCPServer.md @@ -50,6 +50,8 @@ extension. To avoid debugging the wrong workspace when several windows are open: operation to that window's `ControlServer`. The target is cached per session so hint-less follow-ups (step/continue/inspect) reach the same window. If the router window closes, a worker window takes over the port on retry. +- Breakpoint tools also accept virtual source URIs. A sole registered window is unambiguous; + with multiple windows, callers provide the optional `workingDirectory` routing hint. `DebugMCPServer` builds one handler **per MCP session** via a handler factory, which is what lets concurrent agent sessions drive debuggers in different repos simultaneously. @@ -117,7 +119,7 @@ error wins: | `continue_execution` | Continue to next breakpoint | | `pause_execution` | Interrupt a running program (no breakpoint needed) | | `restart_debugging` | Restart session | -| `add/remove_breakpoint` | Breakpoint management | +| `add/remove_breakpoint` | Breakpoint management for local paths and virtual source URIs | | `clear_all_breakpoints` | Remove all breakpoints | | `list_breakpoints` | List active breakpoints | | `get_variables_values` | Read the values of specifically named variables | @@ -127,4 +129,4 @@ error wins: ## Configuration - `debugmcp.serverPort`: Port number (default: 3001) -- `debugmcp.timeoutInSeconds`: Operation timeout (default: 180) \ No newline at end of file +- `debugmcp.timeoutInSeconds`: Operation timeout (default: 180) diff --git a/docs/architecture/debuggingHandler.md b/docs/architecture/debuggingHandler.md index 4c737b5..30a4a30 100644 --- a/docs/architecture/debuggingHandler.md +++ b/docs/architecture/debuggingHandler.md @@ -11,6 +11,7 @@ Debugging is inherently asynchronous - when you step over a line, the debugger t ## Responsibility - Orchestrate debugging operations (start, stop, step, breakpoints) +- Preserve language-extension virtual source URIs when opening documents and setting breakpoints - Detect when debugger state has meaningfully changed after commands - Format debug state into human/AI-readable responses - Recursively format explicitly requested structs and arrays @@ -59,6 +60,13 @@ A state change is considered meaningful when any of these change: - Frame name (function/method) - Frame ID +### Virtual source documents + +Breakpoint and logpoint locations may be native paths or VS Code virtual-document URIs. +`src/utils/sourceUri.ts` keeps custom schemes intact instead of converting them into malformed +`file:` URIs. This is required for language-extension sources such as Business Central `.dal` +documents served through the `al-preview:` scheme. + ### Root Cause Analysis When debugging stops, the handler prompts AI agents to consider whether they found the root cause or just a symptom, encouraging deeper investigation. diff --git a/src/debugMCPServer.ts b/src/debugMCPServer.ts index 2ca41d0..daef50d 100644 --- a/src/debugMCPServer.ts +++ b/src/debugMCPServer.ts @@ -263,33 +263,36 @@ export class DebugMCPServer { server.registerTool('add_breakpoint', { description: 'Set a breakpoint to pause execution at a critical line of code. Breakpoints let you inspect variables and control flow at exact moments.', inputSchema: { - fileFullPath: z.string().describe('Full path to the file'), + fileFullPath: z.string().describe('Full path or VS Code virtual-document URI of the source file'), + workingDirectory: z.string().optional().describe('Workspace directory used to select the correct VS Code window. Required for a virtual-document URI when multiple windows are open.'), line: z.number().int().describe('Line number (1-based) where the breakpoint should be set'), condition: z.string().optional().describe('Optional condition expression. When provided, execution only pauses if this expression evaluates to true at the breakpoint location.'), }, - }, async (args: { fileFullPath: string; line: number; condition?: string }) => + }, async (args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }) => this.runTool('add_breakpoint', () => debuggingHandler.handleAddBreakpoint(args))); // Add logpoint tool server.registerTool('add_logpoint', { description: 'Add a logpoint: a breakpoint that logs a message instead of pausing execution. Ideal for tracing values across many iterations or hot paths without stopping, or where a hard pause would distort timing. Embed expressions in curly braces to interpolate runtime values, e.g. "user id={user.id}".', inputSchema: { - fileFullPath: z.string().describe('Full path to the file'), + fileFullPath: z.string().describe('Full path or VS Code virtual-document URI of the source file'), + workingDirectory: z.string().optional().describe('Workspace directory used to select the correct VS Code window. Required for a virtual-document URI when multiple windows are open.'), line: z.number().int().describe('Line number (1-based) where the logpoint should be set'), logMessage: z.string().describe('Message to log when the line is reached. Wrap expressions in {curly braces} to interpolate runtime values.'), condition: z.string().optional().describe('Optional condition expression. When provided, the message is only logged if this expression evaluates to true.'), }, - }, async (args: { fileFullPath: string; line: number; logMessage: string; condition?: string }) => + }, async (args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }) => this.runTool('add_logpoint', () => debuggingHandler.handleAddLogpoint(args))); // Remove breakpoint tool server.registerTool('remove_breakpoint', { description: 'Remove a breakpoint that is no longer needed.', inputSchema: { - fileFullPath: z.string().describe('Full path to the file'), + fileFullPath: z.string().describe('Full path or VS Code virtual-document URI of the source file'), + workingDirectory: z.string().optional().describe('Workspace directory used to select the correct VS Code window. Required for a virtual-document URI when multiple windows are open.'), line: z.number().describe('Line number (1-based)'), }, - }, async (args: { fileFullPath: string; line: number }) => + }, async (args: { fileFullPath: string; workingDirectory?: string; line: number }) => this.runTool('remove_breakpoint', () => debuggingHandler.handleRemoveBreakpoint(args))); // Clear all breakpoints tool @@ -627,4 +630,4 @@ export class DebugMCPServer { isInitialized(): boolean { return this.initialized; } -} \ No newline at end of file +} diff --git a/src/debuggingHandler.ts b/src/debuggingHandler.ts index 8b02616..24a3dde 100644 --- a/src/debuggingHandler.ts +++ b/src/debuggingHandler.ts @@ -5,6 +5,7 @@ import { DebugConfigurationManager, IDebugConfigurationManager } from './utils/d import { DebugState } from './debugState'; import { IDebuggingExecutor } from './debuggingExecutor'; import { logger } from './utils/logger'; +import { toSourceUri } from './utils/sourceUri'; import { isSensitiveExpression, isSensitiveName, @@ -26,9 +27,9 @@ export interface IDebuggingHandler { handleContinue(): Promise; handlePause(): Promise; handleRestart(): Promise; - handleAddBreakpoint(args: { fileFullPath: string; line: number; condition?: string }): Promise; - handleAddLogpoint(args: { fileFullPath: string; line: number; logMessage: string; condition?: string }): Promise; - handleRemoveBreakpoint(args: { fileFullPath: string; line: number }): Promise; + handleAddBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }): Promise; + handleAddLogpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }): Promise; + handleRemoveBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number }): Promise; handleClearAllBreakpoints(): Promise; handleListBreakpoints(): Promise; handleGetVariables(args: { variableNames: string[]; scope?: 'local' | 'global' | 'all' }): Promise; @@ -310,7 +311,7 @@ export class DebuggingHandler implements IDebuggingHandler { * Add a breakpoint at specified location. An optional condition makes it a * conditional breakpoint that only pauses when the expression is true. */ - public async handleAddBreakpoint(args: { fileFullPath: string; line: number; condition?: string }): Promise { + public async handleAddBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }): Promise { const { fileFullPath, line, condition } = args; try { @@ -320,12 +321,12 @@ export class DebuggingHandler implements IDebuggingHandler { // Validate the line exists so we fail clearly instead of setting an // unbound breakpoint past the end of the file. - const document = await vscode.workspace.openTextDocument(vscode.Uri.file(fileFullPath)); + const uri = toSourceUri(fileFullPath); + const document = await vscode.workspace.openTextDocument(uri); if (line > document.lineCount) { throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${document.lineCount} lines.`); } - const uri = vscode.Uri.file(fileFullPath); await this.executor.addBreakpoint(uri, line, condition); const conditionInfo = condition ? ` (condition: ${condition})` : ''; @@ -340,7 +341,7 @@ export class DebuggingHandler implements IDebuggingHandler { * interpolated by the debug adapter) instead of pausing execution. An * optional condition only logs when the expression is true. */ - public async handleAddLogpoint(args: { fileFullPath: string; line: number; logMessage: string; condition?: string }): Promise { + public async handleAddLogpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }): Promise { const { fileFullPath, line, logMessage, condition } = args; try { @@ -353,12 +354,12 @@ export class DebuggingHandler implements IDebuggingHandler { // Validate the line exists so we fail clearly instead of setting an // unbound logpoint past the end of the file. - const document = await vscode.workspace.openTextDocument(vscode.Uri.file(fileFullPath)); + const uri = toSourceUri(fileFullPath); + const document = await vscode.workspace.openTextDocument(uri); if (line > document.lineCount) { throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${document.lineCount} lines.`); } - const uri = vscode.Uri.file(fileFullPath); await this.executor.addBreakpoint(uri, line, condition, logMessage); const conditionInfo = condition ? ` (condition: ${condition})` : ''; @@ -371,11 +372,11 @@ export class DebuggingHandler implements IDebuggingHandler { /** * Remove a breakpoint from specified location */ - public async handleRemoveBreakpoint(args: { fileFullPath: string; line: number }): Promise { + public async handleRemoveBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number }): Promise { const { fileFullPath, line } = args; try { - const uri = vscode.Uri.file(fileFullPath); + const uri = toSourceUri(fileFullPath); // Check if breakpoint exists at this location const breakpoints = this.executor.getBreakpoints(); diff --git a/src/routingDebuggingHandler.ts b/src/routingDebuggingHandler.ts index aacc5d0..5010ef4 100644 --- a/src/routingDebuggingHandler.ts +++ b/src/routingDebuggingHandler.ts @@ -4,6 +4,7 @@ import * as http from 'http'; import { IDebuggingHandler } from './debuggingHandler'; import { WorkspaceRegistry, WindowRegistration } from './utils/workspaceRegistry'; import { logger } from './utils/logger'; +import { isSourceUri } from './utils/sourceUri'; /** * Router-window handler (one instance per MCP session) that forwards every @@ -35,9 +36,15 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { * Resolve (and cache) the target from an optional path hint; a hint always * re-resolves, otherwise the cached target is reused. */ - private resolveTarget(pathHint?: string): WindowRegistration { + private resolveTarget(pathHint?: string, virtualSource = false): WindowRegistration { if (pathHint) { - const found = this.registry.findByPath(pathHint); + let found = virtualSource ? undefined : this.registry.findByPath(pathHint); + if (!found && virtualSource && !this.target) { + const windows = this.registry.list(); + if (windows.length === 1) { + found = windows[0]; + } + } const candidates = this.registry .list() .map((w) => `pid=${w.pid} port=${w.controlPort} folders=[${w.workspaceFolders.join(', ') || 'none'}]`) @@ -51,17 +58,26 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { } } if (!this.target) { - throw new Error(this.noTargetMessage(pathHint)); + throw new Error(this.noTargetMessage(pathHint, virtualSource)); } return this.target; } - private noTargetMessage(pathHint?: string): string { + private noTargetMessage(pathHint?: string, virtualSource = false): string { const windows = this.registry.list(); const openList = windows .map((w) => (w.workspaceFolders.length ? w.workspaceFolders.join(', ') : '(no folder)')) .join('; '); if (pathHint) { + if (virtualSource) { + return ( + `DebugMCP could not select a VS Code window for virtual source URI "${pathHint}". ` + + 'Pass workingDirectory to identify the workspace that owns the debug session. ' + + (openList + ? `Currently registered workspaces: ${openList}.` + : 'No DebugMCP-enabled VS Code windows are currently registered.') + ); + } return ( `DebugMCP could not find an open VS Code window whose workspace contains "${pathHint}". ` + (openList @@ -75,8 +91,8 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { ); } - private async forward(op: string, args: unknown, pathHint?: string): Promise { - const target = this.resolveTarget(pathHint); + private async forward(op: string, args: unknown, pathHint?: string, virtualSource = false): Promise { + const target = this.resolveTarget(pathHint, virtualSource); try { return await this.post(target, op, args); } catch (error) { @@ -200,16 +216,19 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { return this.forward('handleRestart', {}); } - public handleAddBreakpoint(args: { fileFullPath: string; line: number; condition?: string }): Promise { - return this.forward('handleAddBreakpoint', args, args.fileFullPath); + public handleAddBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }): Promise { + const virtualSource = !args.workingDirectory && isSourceUri(args.fileFullPath); + return this.forward('handleAddBreakpoint', args, args.workingDirectory || args.fileFullPath, virtualSource); } - public handleAddLogpoint(args: { fileFullPath: string; line: number; logMessage: string; condition?: string }): Promise { - return this.forward('handleAddLogpoint', args, args.fileFullPath); + public handleAddLogpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }): Promise { + const virtualSource = !args.workingDirectory && isSourceUri(args.fileFullPath); + return this.forward('handleAddLogpoint', args, args.workingDirectory || args.fileFullPath, virtualSource); } - public handleRemoveBreakpoint(args: { fileFullPath: string; line: number }): Promise { - return this.forward('handleRemoveBreakpoint', args, args.fileFullPath); + public handleRemoveBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number }): Promise { + const virtualSource = !args.workingDirectory && isSourceUri(args.fileFullPath); + return this.forward('handleRemoveBreakpoint', args, args.workingDirectory || args.fileFullPath, virtualSource); } public handleClearAllBreakpoints(): Promise { diff --git a/src/test/debuggingHandler.test.ts b/src/test/debuggingHandler.test.ts index c7f1fd0..08a5a60 100644 --- a/src/test/debuggingHandler.test.ts +++ b/src/test/debuggingHandler.test.ts @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. import * as assert from 'assert'; +import * as vscode from 'vscode'; import { DebugState } from '../debugState'; import { DebuggingHandler } from '../debuggingHandler'; import { IDebuggingExecutor } from '../debuggingExecutor'; @@ -205,3 +206,51 @@ suite('DebuggingHandler waitForStateChange (event-driven)', () => { assert.ok(elapsed < 3000, `timeout should bound the wait, took ${elapsed}ms`); }); }); + +suite('DebuggingHandler virtual source breakpoints', () => { + test('passes an AL-style virtual .dal URI to the debug executor unchanged', async () => { + const scheme = `al-preview-test-${Date.now()}`; + const source = `${scheme}://AlLang/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal`; + let breakpointUri: vscode.Uri | undefined; + const provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { + provideTextDocumentContent: () => 'table 18 Customer\n{\n}' + }); + const executor: IDebuggingExecutor = { + startDebugging: async () => true, + debugTestAtCursor: async () => ({ started: true, runComplete: Promise.resolve() }), + stopDebugging: async () => { /* noop */ }, + stepOver: async () => { /* noop */ }, + stepInto: async () => { /* noop */ }, + stepOut: async () => { /* noop */ }, + continue: async () => { /* noop */ }, + pause: async () => { /* noop */ }, + restart: async () => { /* noop */ }, + addBreakpoint: async (uri) => { breakpointUri = uri; }, + removeBreakpoint: async () => { /* noop */ }, + getCurrentDebugState: async () => new DebugState(), + getVariables: async () => ({}), + getVariableChildren: async () => [], + evaluateExpression: async () => ({}), + getBreakpoints: () => [], + clearAllBreakpoints: () => { /* noop */ }, + hasActiveSession: async () => false, + getActiveSession: () => undefined, + waitForDebugSessionReady: async () => 'no-session' + }; + + try { + const handler = new DebuggingHandler(executor, {} as any, 30); + const result = await handler.handleAddBreakpoint({ fileFullPath: source, line: 2 }); + + assert.strictEqual(breakpointUri?.scheme, scheme); + assert.strictEqual(breakpointUri?.authority, 'AlLang'); + assert.strictEqual( + breakpointUri?.path, + '/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal' + ); + assert.match(result, /Breakpoint added/); + } finally { + provider.dispose(); + } + }); +}); diff --git a/src/test/routing.test.ts b/src/test/routing.test.ts index 4732f8b..4419bba 100644 --- a/src/test/routing.test.ts +++ b/src/test/routing.test.ts @@ -146,6 +146,55 @@ suite('Multi-window routing', () => { assert.strictEqual(handlerB.calls.length, 0); }); + test('virtual source breakpoint uses workingDirectory to select its window', async () => { + const repoA = path.join(dir, 'repoA'); + const repoB = path.join(dir, 'repoB'); + const handlerA = new RecordingHandler('A'); + const handlerB = new RecordingHandler('B'); + await startWindow('a.json', [repoA], handlerA); + await startWindow('b.json', [repoB], handlerB); + + const routing = new RoutingDebuggingHandler(new WorkspaceRegistry(process.pid, dir)); + const result = await routing.handleAddBreakpoint({ + fileFullPath: 'al-preview://AlLang/app/Table/18/Customer.dal', + workingDirectory: repoB, + line: 1 + }); + + assert.strictEqual(result, 'B:addBp'); + assert.strictEqual(handlerA.calls.length, 0); + }); + + test('virtual source breakpoint falls back to the sole registered window', async () => { + const repoA = path.join(dir, 'repoA'); + const handlerA = new RecordingHandler('A'); + await startWindow('a.json', [repoA], handlerA); + + const routing = new RoutingDebuggingHandler(new WorkspaceRegistry(process.pid, dir)); + const result = await routing.handleAddBreakpoint({ + fileFullPath: 'al-preview://AlLang/app/Table/18/Customer.dal', + line: 1 + }); + + assert.strictEqual(result, 'A:addBp'); + }); + + test('virtual source breakpoint requires workingDirectory when multiple windows are open', async () => { + const repoA = path.join(dir, 'repoA'); + const repoB = path.join(dir, 'repoB'); + await startWindow('a.json', [repoA], new RecordingHandler('A')); + await startWindow('b.json', [repoB], new RecordingHandler('B')); + + const routing = new RoutingDebuggingHandler(new WorkspaceRegistry(process.pid, dir)); + await assert.rejects( + () => routing.handleAddBreakpoint({ + fileFullPath: 'al-preview://AlLang/app/Table/18/Customer.dal', + line: 1 + }), + /Pass workingDirectory/ + ); + }); + test('throws a helpful error when no window owns the path', async () => { const repoA = path.join(dir, 'repoA'); const repoB = path.join(dir, 'repoB'); @@ -227,4 +276,3 @@ suite('Multi-window routing', () => { ); }); }); - diff --git a/src/test/sourceUri.test.ts b/src/test/sourceUri.test.ts new file mode 100644 index 0000000..e72f2a2 --- /dev/null +++ b/src/test/sourceUri.test.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. + +import * as assert from 'assert'; +import * as path from 'path'; +import { isSourceUri, toSourceUri } from '../utils/sourceUri'; + +suite('Source URI handling', () => { + test('preserves an AL virtual .dal document URI', () => { + const source = 'al-preview://AlLang/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal'; + const uri = toSourceUri(source); + + assert.strictEqual(isSourceUri(source), true); + assert.strictEqual(uri.scheme, 'al-preview'); + assert.strictEqual(uri.authority, 'AlLang'); + assert.strictEqual(uri.path, '/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal'); + assert.strictEqual( + uri.toString(), + 'al-preview://allang/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal' + ); + }); + + test('keeps native filesystem paths as file URIs', () => { + const source = path.join(path.sep, 'workspace', 'src', 'main.ts'); + const uri = toSourceUri(source); + + assert.strictEqual(isSourceUri(source), false); + assert.strictEqual(uri.scheme, 'file'); + assert.strictEqual(uri.fsPath, source); + }); + + test('does not mistake a Windows drive letter for a URI scheme', () => { + assert.strictEqual(isSourceUri('C:\\workspace\\src\\main.ts'), false); + }); +}); diff --git a/src/utils/sourceUri.ts b/src/utils/sourceUri.ts new file mode 100644 index 0000000..6c1fd12 --- /dev/null +++ b/src/utils/sourceUri.ts @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. + +import * as vscode from 'vscode'; + +/** + * True when a source location is a URI rather than a native filesystem path. + * + * The drive letter in a Windows path looks like a URI scheme, so explicitly + * exclude drive-letter paths before applying the generic scheme check. + */ +export function isSourceUri(source: string): boolean { + if (/^[a-zA-Z]:[\\/]/.test(source)) { + return false; + } + return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source); +} + +/** Preserve virtual-document schemes while retaining native path behavior. */ +export function toSourceUri(source: string): vscode.Uri { + return isSourceUri(source) ? vscode.Uri.parse(source, true) : vscode.Uri.file(source); +} From ef46f0e0a559fb62c25f267e2d387a0e06949fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fekete=20G=C3=A1bor?= Date: Mon, 28 Sep 2026 21:27:53 +0200 Subject: [PATCH 2/5] Fix virtual-source test delegation and isolate CLI fixtures on macOS --- src/test/cliAdapterConfig.test.ts | 10 +++++++++- src/test/debuggingHandler.test.ts | 7 ++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/test/cliAdapterConfig.test.ts b/src/test/cliAdapterConfig.test.ts index 4c4c287..642e8ef 100644 --- a/src/test/cliAdapterConfig.test.ts +++ b/src/test/cliAdapterConfig.test.ts @@ -16,13 +16,16 @@ import { suite('CLI adapter configuration', () => { let workspace: string; let originalAppData: string | undefined; + let originalXdgConfigHome: string | undefined; let appData: string; setup(async () => { workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'debugmcp-cli-project-')); appData = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'debugmcp-cli-user-')); originalAppData = process.env.APPDATA; + originalXdgConfigHome = process.env.XDG_CONFIG_HOME; process.env.APPDATA = appData; + process.env.XDG_CONFIG_HOME = appData; }); teardown(async () => { @@ -31,6 +34,11 @@ suite('CLI adapter configuration', () => { } else { process.env.APPDATA = originalAppData; } + if (originalXdgConfigHome === undefined) { + delete process.env.XDG_CONFIG_HOME; + } else { + process.env.XDG_CONFIG_HOME = originalXdgConfigHome; + } await fs.promises.rm(workspace, { recursive: true, force: true }); await fs.promises.rm(appData, { recursive: true, force: true }); }); @@ -104,7 +112,7 @@ suite('CLI adapter configuration', () => { type: 'coreclr', extensions: ['.cs'], launch: { - program: '${workspaceFolder}\\bin\\Calculator.exe', + program: path.join('${workspaceFolder}', 'bin', 'Calculator.exe'), args: ['${file}', '${fileBasenameNoExtension}'], sourceFileMap: { '/source': '${fileDirname}' diff --git a/src/test/debuggingHandler.test.ts b/src/test/debuggingHandler.test.ts index 7068a11..437d5f9 100644 --- a/src/test/debuggingHandler.test.ts +++ b/src/test/debuggingHandler.test.ts @@ -7,7 +7,7 @@ import * as path from 'path'; import * as vscode from 'vscode'; import { DebugState } from '../debugState'; import { DebuggingHandler } from '../debuggingHandler'; -import { IDebuggingExecutor } from '../debuggingExecutor'; +import { DebuggingExecutor, IDebuggingExecutor } from '../debuggingExecutor'; import { IDebugConfigurationManager } from '../utils/debugConfigurationManager'; /** @@ -335,6 +335,7 @@ suite('DebuggingHandler virtual source breakpoints', () => { provideTextDocumentContent: () => 'table 18 Customer\n{\n}' }); const executor: IDebuggingExecutor = { + getFileLineCount: source => DebuggingExecutor.prototype.getFileLineCount(source), startDebugging: async () => true, debugTestAtCursor: async () => ({ started: true, runComplete: Promise.resolve() }), stopDebugging: async () => { /* noop */ }, @@ -359,6 +360,10 @@ suite('DebuggingHandler virtual source breakpoints', () => { try { const handler = new DebuggingHandler(executor, {} as any, 30); + await assert.rejects( + handler.handleAddBreakpoint({ fileFullPath: source, line: 4 }), + /out of range.*has 3 lines/ + ); const breakpointResult = await handler.handleAddBreakpoint({ fileFullPath: source, line: 2 }); const logpointResult = await handler.handleAddLogpoint({ fileFullPath: source, From fedbcf8b91b54190a0758270ee86d5710363bf0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fekete=20G=C3=A1bor?= Date: Tue, 24 Nov 2026 11:59:10 +0100 Subject: [PATCH 3/5] Report stop locations in virtual documents and match their breakpoints A stop in a virtual document (for example a Business Central `al-preview:` `.dal` source) left `fileFullPath`, `fileName`, `currentLine`, `currentLineContent` and `nextLines` empty: the frame's source path is a URI there, and it was opened as a filesystem path. Open it as the URI it is and report the canonical URI string, which the breakpoint tools accept unchanged. `remove_breakpoint` compared the caller's text with the stored URI, so a URI written with literal spaces never matched and only the percent-encoded form worked. The handler now asks the executor for the canonical form of the requested location. `list_breakpoints` shows the decoded file name. `getBreakpoints()` reported `file:///...` for ordinary files, because every URI string has a scheme; `remove_breakpoint` with a native path therefore found nothing. Files on disk are reported by their native path again. Also: - Move the VS Code-bound URI conversions to `utils/vscodeSourceUri.ts` and keep `utils/sourceUri.ts` host-neutral, since the handler is bundled into the standalone CLI. Drop the duplicate helper and misplaced imports above the copyright header in `debuggingExecutor.ts`. - Restore the changelog entries whose inline code was lost, and the upstream end-of-file state of files the fork only touched there. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 6 +- README.md | 6 +- docs/architecture/debugMCPServer.md | 2 +- docs/architecture/debugState.md | 2 +- docs/architecture/debuggingExecutor.md | 7 + docs/architecture/debuggingHandler.md | 8 +- src/debugMCPServer.ts | 2 +- src/debuggingExecutor.ts | 46 ++++--- src/debuggingHandler.ts | 12 +- src/test/sourceUri.test.ts | 33 ++++- src/test/virtualSourceLocation.test.ts | 173 +++++++++++++++++++++++++ src/utils/sourceUri.ts | 23 +++- src/utils/vscodeSourceUri.ts | 17 +++ 13 files changed, 303 insertions(+), 34 deletions(-) create mode 100644 src/test/virtualSourceLocation.test.ts create mode 100644 src/utils/vscodeSourceUri.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 21a5bf3..b9f73c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,12 @@ 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). +- A stop in a virtual document now reports its source location. `fileFullPath` is the document URI in the form the breakpoint tools accept, alongside the file name, current line, and following lines. +- `remove_breakpoint` finds a breakpoint in a virtual document whether its URI is written with literal spaces or percent-encoded, and `list_breakpoints` shows the decoded file name. ### Added -- Breakpoint, logpoint, and removal tools now support VS Code virtual-document URIs, including Business Central sources. An optional selects the correct workspace when multiple editor windows are open. -- **Claude Code auto-registration** - Claude Code is now offered in the agent selection popup and configured via 's user-scope field. Claude Desktop connects via its Custom Connector UI instead of a static config file; the README's manual configuration section covers both. +- Breakpoint, logpoint, and removal tools now support VS Code virtual-document URIs, including Business Central `al-preview:` `.dal` sources. An optional `workingDirectory` selects the correct workspace when multiple editor windows are open. +- **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. ## [2.4.4] - 2026-10-25 diff --git a/README.md b/README.md index 0c303e9..3f5da21 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,9 @@ file, including Business Central dependency objects such as pass `workingDirectory` with the virtual URI so DebugMCP routes the operation to the correct workspace. +When execution stops in a virtual document, the debug state reports the same URI as +`fileFullPath`, so it can be passed back to the breakpoint tools unchanged. + ## Configuration ### MCP Server Configuration (Recommended) @@ -648,5 +651,4 @@ If DebugMCP has helped you debug faster, please consider giving it a star on Git ## License -MIT License - See [LICENSE](LICENSE.txt) for details -This extension was created by **Oz Zafar**, **Ori Bar-Ilan** and **Karin Brisker**. +MIT License - See [LICENSE](LICENSE.txt) for details \ No newline at end of file diff --git a/docs/architecture/debugMCPServer.md b/docs/architecture/debugMCPServer.md index 79029ba..2f76ed5 100644 --- a/docs/architecture/debugMCPServer.md +++ b/docs/architecture/debugMCPServer.md @@ -154,4 +154,4 @@ error wins: ## Configuration - `debugmcp.serverPort`: Port number (default: 3001) -- `debugmcp.timeoutInSeconds`: Operation timeout (default: 180) +- `debugmcp.timeoutInSeconds`: Operation timeout (default: 180) \ No newline at end of file diff --git a/docs/architecture/debugState.md b/docs/architecture/debugState.md index 82d0566..6b67652 100644 --- a/docs/architecture/debugState.md +++ b/docs/architecture/debugState.md @@ -22,7 +22,7 @@ Debugging operations are asynchronous - the debugger takes time to execute and u | `sessionActive` | `boolean` | Whether a debug session exists, running or stopped | | `paused` | `boolean \| null` | Observed execution state, or `null` when unobserved | | `stopSequence` | `number \| null` | Internal executor-local stopped-event marker, independent of frames and source | -| `fileFullPath` | `string \| null` | Full path to current file | +| `fileFullPath` | `string \| null` | Full path to current file, or its URI for a virtual document | | `fileName` | `string \| null` | Just the filename | | `currentLine` | `number \| null` | 1-based line number | | `currentLineContent` | `string \| null` | Content of current line | diff --git a/docs/architecture/debuggingExecutor.md b/docs/architecture/debuggingExecutor.md index a9450aa..f6a695a 100644 --- a/docs/architecture/debuggingExecutor.md +++ b/docs/architecture/debuggingExecutor.md @@ -161,6 +161,13 @@ 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 frame's source path may be a native path or a URI. Adapters for virtual +documents (for example Business Central `al-preview:` `.dal` sources) report a +URI; it is opened through its content provider and reported as the canonical +URI string, the same form `getBreakpoints()` uses and the breakpoint tools +accept. `normalizeSourceLocation()` maps a caller-supplied path or URI to that +form, so different spellings of one URI compare equal. + 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 diff --git a/docs/architecture/debuggingHandler.md b/docs/architecture/debuggingHandler.md index 08d6cd2..c0b2145 100644 --- a/docs/architecture/debuggingHandler.md +++ b/docs/architecture/debuggingHandler.md @@ -115,10 +115,16 @@ the underlying request is not cancelled. Polling stops when the call returns. ### Virtual source documents Breakpoint and logpoint locations may be native paths or VS Code virtual-document URIs. -`src/utils/sourceUri.ts` keeps custom schemes intact instead of converting them into malformed +`src/utils/vscodeSourceUri.ts` keeps custom schemes intact instead of converting them into malformed `file:` URIs. This is required for language-extension sources such as Business Central `.dal` documents served through the `al-preview:` scheme. +The handler stays host-neutral and does not parse URIs itself; it only uses the text helpers in +`src/utils/sourceUri.ts`, which are also bundled into the standalone CLI. Before looking up a breakpoint +to remove, it asks the executor for the canonical form of the requested location, so a URI +written with a literal space matches the same URI written with `%20`. Breakpoint listings +show the decoded file name. + ### Root Cause Analysis When debugging stops, the handler prompts AI agents to consider whether they found the root cause or just a symptom, encouraging deeper investigation. diff --git a/src/debugMCPServer.ts b/src/debugMCPServer.ts index bb24c53..1f3bf93 100644 --- a/src/debugMCPServer.ts +++ b/src/debugMCPServer.ts @@ -668,4 +668,4 @@ export class DebugMCPServer { isInitialized(): boolean { return this.initialized; } -} +} \ No newline at end of file diff --git a/src/debuggingExecutor.ts b/src/debuggingExecutor.ts index 22e3c48..9e66af0 100644 --- a/src/debuggingExecutor.ts +++ b/src/debuggingExecutor.ts @@ -1,12 +1,7 @@ -import * as fs from 'node:fs'; -import { isSourceUri } from './utils/sourceUri'; - -function toSourceUri(source: string): vscode.Uri { - return isSourceUri(source) ? vscode.Uri.parse(source, true) : vscode.Uri.file(source); -} // Copyright (c) Microsoft Corporation. import * as vscode from 'vscode'; +import * as fs from 'node:fs'; import { DebugState, StackFrame } from './debugState'; import { DebugBreakpoint, DebugConfiguration, DebugSessionInfo } from './debugTypes'; import { logger } from './utils/logger'; @@ -14,6 +9,8 @@ import { withTimeout } from './utils/withTimeout'; import { getDebugStartupContext, startDebuggingWithDiagnostics } from './utils/debugStartup'; import { DebugSessionTracker } from './utils/debugSessionTracker'; import { DebugOutputBuffer, IDebugOutputQuery } from './utils/debugOutputBuffer'; +import { isSourceUri } from './utils/sourceUri'; +import { toSourceText, toSourceUri } from './utils/vscodeSourceUri'; /** * Outcome of dispatching `testing.debugAtCursor`. @@ -61,6 +58,7 @@ export interface IDebuggingExecutor { getDebugOutput?(query: IDebugOutputQuery): ReturnType; waitForDebugSessionReady(timeoutMs: number, signal?: AbortSignal): Promise<'stopped' | 'terminated' | 'timeout' | 'no-session' | 'attached'>; getFileLineCount?(fileFullPath: string): Promise; + normalizeSourceLocation?(fileFullPath: string): string; dispose?(): Promise | void; } @@ -102,18 +100,31 @@ export class DebuggingExecutor implements IDebuggingExecutor { } /** - * Start a debugging session + * Count the lines of a source file. Virtual documents are read through + * VS Code so their content provider is used; files on disk are read directly. */ public async getFileLineCount(fileFullPath: string): Promise { if (isSourceUri(fileFullPath)) { - const uri = toSourceUri(fileFullPath); - const document = await vscode.workspace.openTextDocument(uri); + const document = await vscode.workspace.openTextDocument(toSourceUri(fileFullPath)); return document.lineCount; } const content = await fs.promises.readFile(fileFullPath, 'utf8'); return content.length === 0 ? 0 : content.split(/\r?\n/).length; } + /** + * The form in which `getBreakpoints` and the debug state report a source + * location, so a caller-supplied path or URI can be compared with them. + * Different spellings of one virtual-document URI (a literal space versus + * `%20`, authority casing) map to the same text. + */ + public normalizeSourceLocation(fileFullPath: string): string { + return toSourceText(toSourceUri(fileFullPath)); + } + + /** + * Start a debugging session + */ public async startDebugging( workingDirectory: string, config: string | DebugConfiguration @@ -556,9 +567,16 @@ export class DebuggingExecutor implements IDebuggingExecutor { numNextLines: number ): Promise { try { - const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(filePath)); + // Adapters for virtual documents report a URI in `source.path` (for + // example Business Central's `al-preview:` sources). Treating that + // as a filesystem path would point at a file that does not exist. + const virtualSource = isSourceUri(filePath); + const uri = toSourceUri(filePath); + const doc = await vscode.workspace.openTextDocument(uri); const zeroBasedLine = Math.max(0, Math.min(line - 1, doc.lineCount - 1)); - const fileName = filePath.split(/[/\\]/).pop() || ''; + // Report a virtual source in the form the breakpoint tools accept. + const fileFullPath = virtualSource ? toSourceText(uri) : filePath; + const fileName = (virtualSource ? uri.path.split('/') : filePath.split(/[/\\]/)).pop() || ''; const currentLineContent = doc.lineAt(zeroBasedLine).text.trim(); // Collect the next non-empty lines for lookahead context. @@ -572,7 +590,7 @@ export class DebuggingExecutor implements IDebuggingExecutor { lineOffset++; } - state.updateLocation(filePath, fileName, line, currentLineContent, nextLines); + state.updateLocation(fileFullPath, fileName, line, currentLineContent, nextLines); } catch (error) { // Native/library frames or paths VS Code can't open won't resolve to // a document; degrade gracefully and leave location unset. @@ -803,9 +821,7 @@ export class DebuggingExecutor implements IDebuggingExecutor { .filter((breakpoint): breakpoint is vscode.SourceBreakpoint => breakpoint instanceof vscode.SourceBreakpoint) .map(breakpoint => ({ - fileFullPath: isSourceUri(breakpoint.location.uri.toString()) - ? breakpoint.location.uri.toString() - : breakpoint.location.uri.fsPath, + fileFullPath: toSourceText(breakpoint.location.uri), line: breakpoint.location.range.start.line + 1, condition: breakpoint.condition, logMessage: breakpoint.logMessage diff --git a/src/debuggingHandler.ts b/src/debuggingHandler.ts index da73671..22465de 100644 --- a/src/debuggingHandler.ts +++ b/src/debuggingHandler.ts @@ -5,7 +5,7 @@ import { DebugConfigurationManager, IDebugConfigurationManager } from './utils/d import { DebugState } from './debugState'; import { IDebuggingExecutor } from './debuggingExecutor'; import { logger } from './utils/logger'; -import { isSourceUri } from './utils/sourceUri'; +import { sourceFileName } from './utils/sourceUri'; import { withTimeout } from './utils/withTimeout'; import { IDebugOutputQuery } from './utils/debugOutputBuffer'; import { @@ -551,11 +551,13 @@ export class DebuggingHandler implements IDebuggingHandler { const { fileFullPath, line } = args; try { - - // Check if breakpoint exists at this location + // Check if breakpoint exists at this location. Compare in the + // executor's own form: a virtual-document URI can be written with a + // literal space or `%20` and still name the same source. + const location = this.executor.normalizeSourceLocation?.(fileFullPath) ?? fileFullPath; const breakpoints = this.executor.getBreakpoints(); const existingBreakpoint = breakpoints.find(bp => - bp.fileFullPath === fileFullPath && bp.line === line); + bp.fileFullPath === location && bp.line === line); if (!existingBreakpoint) { return `No breakpoint found at ${fileFullPath}:${line}`; @@ -581,7 +583,7 @@ export class DebuggingHandler implements IDebuggingHandler { let breakpointList = 'Active Breakpoints:\n'; breakpoints.forEach((bp, index) => { - const fileName = bp.fileFullPath.split(/[/\\]/).pop(); + const fileName = sourceFileName(bp.fileFullPath); const conditionInfo = bp.condition ? ` (condition: ${bp.condition})` : ''; const kind = bp.logMessage ? 'Logpoint' : 'Breakpoint'; const logInfo = bp.logMessage ? ` (log: ${bp.logMessage})` : ''; diff --git a/src/test/sourceUri.test.ts b/src/test/sourceUri.test.ts index e72f2a2..f614429 100644 --- a/src/test/sourceUri.test.ts +++ b/src/test/sourceUri.test.ts @@ -2,7 +2,8 @@ import * as assert from 'assert'; import * as path from 'path'; -import { isSourceUri, toSourceUri } from '../utils/sourceUri'; +import { isSourceUri, sourceFileName } from '../utils/sourceUri'; +import { toSourceText, toSourceUri } from '../utils/vscodeSourceUri'; suite('Source URI handling', () => { test('preserves an AL virtual .dal document URI', () => { @@ -31,4 +32,34 @@ suite('Source URI handling', () => { test('does not mistake a Windows drive letter for a URI scheme', () => { assert.strictEqual(isSourceUri('C:\\workspace\\src\\main.ts'), false); }); + + test('reports a file on disk by its native path and a virtual document by its URI', () => { + const file = path.join(path.sep, 'workspace', 'src', 'main.ts'); + assert.strictEqual(toSourceText(toSourceUri(file)), file); + assert.strictEqual(toSourceText(toSourceUri(`file://${file.split(path.sep).join('/')}`)), file); + assert.strictEqual( + toSourceText(toSourceUri('al-preview://AlLang/app/Codeunit/51000/EXW Warehouse Service.dal')), + 'al-preview://allang/app/Codeunit/51000/EXW%20Warehouse%20Service.dal' + ); + }); + + test('different spellings of one virtual-document URI have the same text', () => { + const spellings = [ + 'al-preview://AlLang/app/Codeunit/51000/EXW Warehouse Service.dal', + 'al-preview://allang/app/Codeunit/51000/EXW%20Warehouse%20Service.dal', + 'al-preview://allang/app/Codeunit/51000/EXW Warehouse%20Service.dal' + ]; + assert.strictEqual(new Set(spellings.map(spelling => toSourceText(toSourceUri(spelling)))).size, 1); + }); + + test('shows a readable file name for paths and URIs', () => { + assert.strictEqual(sourceFileName('/workspace/src/main.ts'), 'main.ts'); + assert.strictEqual(sourceFileName('C:\\workspace\\src\\main.ts'), 'main.ts'); + assert.strictEqual( + sourceFileName('al-preview://allang/app/Codeunit/51000/EXW%20Warehouse%20Service.dal'), + 'EXW Warehouse Service.dal' + ); + assert.strictEqual(sourceFileName('debug:/generated/eval%20code.js?session=1&ref=7'), 'eval code.js'); + assert.strictEqual(sourceFileName('al-preview://allang/app/Table/18/100%.dal'), '100%.dal'); + }); }); diff --git a/src/test/virtualSourceLocation.test.ts b/src/test/virtualSourceLocation.test.ts new file mode 100644 index 0000000..8149fa3 --- /dev/null +++ b/src/test/virtualSourceLocation.test.ts @@ -0,0 +1,173 @@ +// 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'; + +/** + * Language extensions can serve sources that exist only as virtual documents. + * Business Central is the motivating case: the objects of an installed app are + * shown as `al-preview://allang////.dal`, and object names + * routinely contain spaces. + */ +const documentLines = [ + 'codeunit 51000 "EXW Warehouse Service"', + '{', + ' procedure GetPackageInformation(packageID: Text)', + ' begin', + ' if not Package.Get(packageID) then', + '', + ' Error(PackageNotFoundErr, packageID);', + ' exit(Package.Description);', + ' end;', + '}' +]; + +suite('Virtual source documents (AL .dal)', () => { + let schemeCounter = 0; + let scheme: string; + let spacedSource: string; + let encodedSource: string; + let canonicalSource: string; + let provider: vscode.Disposable; + let sessionDescriptor: PropertyDescriptor; + let stackDescriptor: PropertyDescriptor; + let frameSource: { name?: string; path?: string } | undefined; + + const executor = () => new DebuggingExecutor(); + const handler = (target: DebuggingExecutor = executor()) => + new DebuggingHandler(target, new DebugConfigurationManager(), 5); + // VS Code echoes breakpoint changes back to the extension host, so a + // breakpoint removed by an earlier test can briefly reappear. Every test + // therefore uses its own scheme and only looks at its own breakpoints. + const sourceBreakpoints = () => vscode.debug.breakpoints + .filter((breakpoint): breakpoint is vscode.SourceBreakpoint => breakpoint instanceof vscode.SourceBreakpoint) + .filter(breakpoint => breakpoint.location.uri.scheme === scheme); + const reportedLocations = (target: DebuggingExecutor, own: (location: string) => boolean) => + target.getBreakpoints().map(breakpoint => breakpoint.fileFullPath).filter(own); + + setup(() => { + scheme = `al-preview-test-${Date.now()}-${++schemeCounter}`; + const location = 'dc644a87ff3c480e8a8f668628ae77b7/Codeunit/51000'; + spacedSource = `${scheme}://AlLang/${location}/EXW Warehouse Service.dal`; + encodedSource = `${scheme}://allang/${location}/EXW%20Warehouse%20Service.dal`; + canonicalSource = encodedSource; + provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { + provideTextDocumentContent: () => documentLines.join('\n') + }); + + frameSource = undefined; + const session: vscode.DebugSession = { + id: 'al-virtual-source', + name: 'AL attach', + type: 'al', + configuration: { type: 'al', request: 'attach', name: 'AL attach' }, + workspaceFolder: undefined, + customRequest: async (command: string) => { + assert.equal(command, 'stackTrace'); + return { + stackFrames: [{ id: 3, name: 'GetPackageInformation', line: 5, column: 9, source: frameSource }] + }; + }, + getDebugProtocolBreakpoint: async () => 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: () => ({ frameId: 3, threadId: 1, session }) + }); + }); + + teardown(() => { + Object.defineProperty(vscode.debug, 'activeDebugSession', sessionDescriptor); + Object.defineProperty(vscode.debug, 'activeStackItem', stackDescriptor); + vscode.debug.removeBreakpoints(vscode.debug.breakpoints); + provider.dispose(); + }); + + for (const spelling of ['a literal space', 'percent-encoding'] as const) { + test(`a stop in a virtual document reports its location (source path with ${spelling})`, async () => { + frameSource = { + name: 'EXW Warehouse Service.dal', + path: spelling === 'a literal space' ? spacedSource : encodedSource + }; + + const state = await executor().getCurrentDebugState(2); + + assert.equal(state.isPaused(), true); + assert.equal(state.frameName, 'GetPackageInformation'); + assert.equal(state.fileFullPath, canonicalSource); + assert.equal(state.fileName, 'EXW Warehouse Service.dal'); + assert.equal(state.currentLine, 5); + assert.equal(state.currentLineContent, 'if not Package.Get(packageID) then'); + assert.deepEqual(state.nextLines, [ + 'Error(PackageNotFoundErr, packageID);', + 'exit(Package.Description);' + ]); + }); + } + + test('add_breakpoint accepts the reported location unchanged', async () => { + frameSource = { name: 'EXW Warehouse Service.dal', path: spacedSource }; + const state = JSON.parse(await handler().handleGetDebugStatus()).state; + + const result = await handler().handleAddBreakpoint({ fileFullPath: state.fileFullPath, line: state.currentLine }); + + assert.match(result, /Breakpoint added/); + const [breakpoint] = sourceBreakpoints(); + assert.equal(breakpoint.location.uri.toString(), state.fileFullPath); + assert.equal(breakpoint.location.range.start.line, state.currentLine - 1); + }); + + for (const [added, removed] of [ + ['literal spaces', 'literal spaces'], + ['literal spaces', 'percent-encoding'], + ['percent-encoding', 'literal spaces'] + ] as const) { + test(`remove_breakpoint finds a breakpoint added with ${added} when given ${removed}`, async () => { + const spelled = (spelling: string) => spelling === 'literal spaces' ? spacedSource : encodedSource; + await handler().handleAddBreakpoint({ fileFullPath: spelled(added), line: 7 }); + assert.equal(sourceBreakpoints().length, 1); + + const result = await handler().handleRemoveBreakpoint({ fileFullPath: spelled(removed), line: 7 }); + + assert.match(result, /Breakpoint removed/); + assert.equal(sourceBreakpoints().length, 0); + }); + } + + test('remove_breakpoint still reports a location without a breakpoint', async () => { + await handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: 7 }); + + const result = await handler().handleRemoveBreakpoint({ fileFullPath: spacedSource, line: 8 }); + + assert.match(result, /No breakpoint found/); + assert.equal(sourceBreakpoints().length, 1); + }); + + test('breakpoints are listed with the decoded file name and the canonical URI', async () => { + const target = executor(); + await handler(target).handleAddBreakpoint({ fileFullPath: spacedSource, line: 7 }); + + const listing = await handler(target).handleListBreakpoints(); + + assert.match(listing, /Breakpoint EXW Warehouse Service\.dal:7/); + assert.deepEqual(reportedLocations(target, location => location.startsWith(`${scheme}:`)), [canonicalSource]); + }); + + test('a breakpoint in a file on disk is reported and removed by its native path', async () => { + const target = executor(); + await handler(target).handleAddBreakpoint({ fileFullPath: __filename, line: 1 }); + const onDisk = (location: string) => !location.startsWith('al-preview-test-'); + assert.deepEqual(reportedLocations(target, onDisk), [__filename]); + + const result = await handler(target).handleRemoveBreakpoint({ fileFullPath: __filename, line: 1 }); + + assert.match(result, /Breakpoint removed/); + assert.deepEqual(reportedLocations(target, onDisk), []); + }); +}); diff --git a/src/utils/sourceUri.ts b/src/utils/sourceUri.ts index 4f4d775..e3ec2ee 100644 --- a/src/utils/sourceUri.ts +++ b/src/utils/sourceUri.ts @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. -import type * as vscode from 'vscode'; +// Host-neutral helpers for source locations given as text. This module is also +// bundled into the standalone CLI, so it must not depend on the `vscode` module; +// conversions to and from `vscode.Uri` live in `vscodeSourceUri.ts`. /** * True when a source location is a URI rather than a native filesystem path. @@ -15,8 +17,19 @@ export function isSourceUri(source: string): boolean { return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source); } -/** Preserve virtual-document schemes while retaining native path behavior. */ -export function toSourceUri(source: string): vscode.Uri { - const vscodeModule: typeof import('vscode') = require('vscode'); - return isSourceUri(source) ? vscodeModule.Uri.parse(source, true) : vscodeModule.Uri.file(source); +/** + * File name to display for a source location given as a native path or a URI + * string. Percent-escapes in a URI are decoded, so `My%20Object.dal` reads as + * `My Object.dal`. + */ +export function sourceFileName(source: string): string { + if (!isSourceUri(source)) { + return source.split(/[/\\]/).pop() ?? ''; + } + const name = source.replace(/[?#].*$/, '').split('/').pop() ?? ''; + try { + return decodeURIComponent(name); + } catch { + return name; + } } diff --git a/src/utils/vscodeSourceUri.ts b/src/utils/vscodeSourceUri.ts new file mode 100644 index 0000000..d39d3a7 --- /dev/null +++ b/src/utils/vscodeSourceUri.ts @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. + +import * as vscode from 'vscode'; +import { isSourceUri } from './sourceUri'; + +/** Preserve virtual-document schemes while retaining native path behavior. */ +export function toSourceUri(source: string): vscode.Uri { + return isSourceUri(source) ? vscode.Uri.parse(source, true) : vscode.Uri.file(source); +} + +/** + * The text DebugMCP reports for a source location and accepts back unchanged: + * the native path for a file on disk, the canonical URI string for anything else. + */ +export function toSourceText(uri: vscode.Uri): string { + return uri.scheme === 'file' ? uri.fsPath : uri.toString(); +} From 0318c8a2838480e15440b715ebb814434ba61075 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fekete=20G=C3=A1bor?= Date: Tue, 24 Nov 2026 12:37:03 +0100 Subject: [PATCH 4/5] Allow breakpoints in virtual documents that cannot be opened yet `add_breakpoint` and `add_logpoint` open the source to reject a line past its end. For a Business Central `.dal` source that fails until the debug session has stopped: the content is served through the session, and before the first stop the server answers `al/previewDocument` with "An unexpected error occurred invoking 'GetSourceContent'". In a workspace without the symbols, no breakpoint could be set before something else had already stopped the session. An unreadable virtual source is now left unchecked: the breakpoint is set and the result notes that the line was not validated. A readable document is validated as before, and a missing file on disk is still an error. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 1 + README.md | 4 +++ docs/architecture/debuggingHandler.md | 5 +++ src/debuggingHandler.ts | 50 ++++++++++++++++++++------ src/test/virtualSourceLocation.test.ts | 24 +++++++++++++ 5 files changed, 73 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b9f73c2..b78f4a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this - 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). - A stop in a virtual document now reports its source location. `fileFullPath` is the document URI in the form the breakpoint tools accept, alongside the file name, current line, and following lines. - `remove_breakpoint` finds a breakpoint in a virtual document whether its URI is written with literal spaces or percent-encoded, and `list_breakpoints` shows the decoded file name. +- `add_breakpoint` and `add_logpoint` accept a virtual document that cannot be opened yet instead of failing. The line is then not checked, and the result says so. Business Central serves a `.dal` source only once its session has stopped, which made it impossible to set a breakpoint there before the first stop. ### Added - Breakpoint, logpoint, and removal tools now support VS Code virtual-document URIs, including Business Central `al-preview:` `.dal` sources. An optional `workingDirectory` selects the correct workspace when multiple editor windows are open. diff --git a/README.md b/README.md index 3f5da21..ddcc40e 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,10 @@ workspace. When execution stops in a virtual document, the debug state reports the same URI as `fileFullPath`, so it can be passed back to the breakpoint tools unchanged. +Some debuggers serve a virtual source only once the session has stopped. A breakpoint can +still be set in it beforehand: the line is not validated in that case, and the tool result +says so. + ## Configuration ### MCP Server Configuration (Recommended) diff --git a/docs/architecture/debuggingHandler.md b/docs/architecture/debuggingHandler.md index c0b2145..d48beef 100644 --- a/docs/architecture/debuggingHandler.md +++ b/docs/architecture/debuggingHandler.md @@ -125,6 +125,11 @@ to remove, it asks the executor for the canonical form of the requested location written with a literal space matches the same URI written with `%20`. Breakpoint listings show the decoded file name. +A breakpoint's line is validated against the source when it can be read. A virtual document +that cannot be opened yet (Business Central serves `.dal` sources only once the session has +stopped) still takes the breakpoint, with a note that the line was not checked; a missing file +on disk remains an error. + ### Root Cause Analysis When debugging stops, the handler prompts AI agents to consider whether they found the root cause or just a symptom, encouraging deeper investigation. diff --git a/src/debuggingHandler.ts b/src/debuggingHandler.ts index 22465de..818561d 100644 --- a/src/debuggingHandler.ts +++ b/src/debuggingHandler.ts @@ -5,7 +5,7 @@ import { DebugConfigurationManager, IDebugConfigurationManager } from './utils/d import { DebugState } from './debugState'; import { IDebuggingExecutor } from './debuggingExecutor'; import { logger } from './utils/logger'; -import { sourceFileName } from './utils/sourceUri'; +import { isSourceUri, sourceFileName } from './utils/sourceUri'; import { withTimeout } from './utils/withTimeout'; import { IDebugOutputQuery } from './utils/debugOutputBuffer'; import { @@ -475,20 +475,51 @@ export class DebuggingHandler implements IDebuggingHandler { // Validate the line exists so we fail clearly instead of setting an // unbound breakpoint past the end of the file. - const lineCount = await this.getFileLineCount(fileFullPath); - if (line > lineCount) { - throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${lineCount} lines.`); - } + const lineCaveat = await this.checkLineInSource(fileFullPath, line); await this.executor.addBreakpoint(fileFullPath, line, condition); const conditionInfo = condition ? ` (condition: ${condition})` : ''; - return `Breakpoint added at ${fileFullPath}:${line}${conditionInfo}${await this.sessionCaveat()}`; + return `Breakpoint added at ${fileFullPath}:${line}${conditionInfo}${lineCaveat}${await this.sessionCaveat()}`; } catch (error) { throw new Error(`Error adding breakpoint: ${error}`); } } + /** + * Reject a line past the end of the source, returning a note for the caller + * when the line could not be checked. + * + * A virtual document is not always readable when a breakpoint is set: + * Business Central serves a `.dal` source only once its debug session has + * stopped. Refusing the breakpoint then would make it impossible to arm one + * before the first stop, so an unreadable virtual source is left unchecked + * and reported as such. A missing file on disk is still an error. + */ + private async checkLineInSource(fileFullPath: string, line: number): Promise { + let lineCount: number; + try { + lineCount = await this.getFileLineCount(fileFullPath); + } catch (error) { + if (!isSourceUri(fileFullPath)) { + throw error; + } + logger.warn( + `Could not open ${fileFullPath} to validate line ${line}: ` + + `${error instanceof Error ? error.message : String(error)}` + ); + return ( + `\n\nNOTE: the virtual document could not be opened, so line ${line} was not checked against it. ` + + 'Some debuggers only serve such sources once the session has stopped. ' + + 'If the URI or line is wrong, this breakpoint will never be hit.' + ); + } + if (line > lineCount) { + throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${lineCount} lines.`); + } + return ''; + } + /** * Warn when a breakpoint is registered with no debug session attached. * @@ -530,15 +561,12 @@ export class DebuggingHandler implements IDebuggingHandler { // Validate the line exists so we fail clearly instead of setting an // unbound logpoint past the end of the file. - const lineCount = await this.getFileLineCount(fileFullPath); - if (line > lineCount) { - throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${lineCount} lines.`); - } + const lineCaveat = await this.checkLineInSource(fileFullPath, line); await this.executor.addBreakpoint(fileFullPath, line, condition, logMessage); const conditionInfo = condition ? ` (condition: ${condition})` : ''; - return `Logpoint added at ${fileFullPath}:${line}${conditionInfo}${await this.sessionCaveat()}`; + return `Logpoint added at ${fileFullPath}:${line}${conditionInfo}${lineCaveat}${await this.sessionCaveat()}`; } catch (error) { throw new Error(`Error adding logpoint: ${error}`); } diff --git a/src/test/virtualSourceLocation.test.ts b/src/test/virtualSourceLocation.test.ts index 8149fa3..bd8e57c 100644 --- a/src/test/virtualSourceLocation.test.ts +++ b/src/test/virtualSourceLocation.test.ts @@ -140,6 +140,30 @@ suite('Virtual source documents (AL .dal)', () => { }); } + test('a virtual document that cannot be opened yet still takes a breakpoint, with a note', async () => { + // Business Central serves a .dal source only once the session has stopped. + provider.dispose(); + provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { + provideTextDocumentContent: () => { throw new Error('GetSourceContent failed on the server'); } + }); + + const breakpoint = await handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: 81 }); + const logpoint = await handler().handleAddLogpoint({ fileFullPath: spacedSource, line: 82, logMessage: 'reached' }); + + assert.match(breakpoint, /Breakpoint added at .*:81/); + assert.match(breakpoint, /could not be opened, so line 81 was not checked/); + assert.match(logpoint, /Logpoint added at .*:82/); + assert.match(logpoint, /could not be opened, so line 82 was not checked/); + assert.deepEqual(sourceBreakpoints().map(item => item.location.range.start.line + 1).sort(), [81, 82]); + }); + + test('a missing file on disk is still rejected', async () => { + await assert.rejects( + handler().handleAddBreakpoint({ fileFullPath: `${__filename}.missing`, line: 1 }), + /Error adding breakpoint/ + ); + }); + test('remove_breakpoint still reports a location without a breakpoint', async () => { await handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: 7 }); From 860bdc63f7d8648bca3e9629b959f9bbab5a2cea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fekete=20G=C3=A1bor?= Date: Tue, 24 Nov 2026 12:55:24 +0100 Subject: [PATCH 5/5] Trim the virtual-source tests to the cases that catch a real regression Remove tests that duplicated another test's coverage or only restated what `vscode.Uri` does: - `debuggingHandler.test.ts`: drop the pass-through test with a hand-written fake executor; the same operations are covered against the real executor in `virtualSourceLocation.test.ts`, which also keeps the out-of-range check. - `sourceUri.test.ts`: keep the Windows drive-letter guard and the file-name helper; the URI conversions are exercised end to end by the breakpoint tests. - `virtualSourceLocation.test.ts`: one case per behaviour instead of several spellings of the same URI. Co-Authored-By: Claude Fable 5.2 --- src/test/debuggingHandler.test.ts | 67 +------------------ src/test/sourceUri.test.ts | 45 +------------ src/test/virtualSourceLocation.test.ts | 93 +++++++++++--------------- 3 files changed, 40 insertions(+), 165 deletions(-) diff --git a/src/test/debuggingHandler.test.ts b/src/test/debuggingHandler.test.ts index 437d5f9..075e0f3 100644 --- a/src/test/debuggingHandler.test.ts +++ b/src/test/debuggingHandler.test.ts @@ -4,10 +4,9 @@ import * as assert from 'assert'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import * as vscode from 'vscode'; import { DebugState } from '../debugState'; import { DebuggingHandler } from '../debuggingHandler'; -import { DebuggingExecutor, IDebuggingExecutor } from '../debuggingExecutor'; +import { IDebuggingExecutor } from '../debuggingExecutor'; import { IDebugConfigurationManager } from '../utils/debugConfigurationManager'; /** @@ -324,70 +323,6 @@ suite('DebuggingHandler waitForStateChange (event-driven)', () => { }); }); -suite('DebuggingHandler virtual source breakpoints', () => { - test('passes an AL-style virtual .dal URI through breakpoint, logpoint, and removal operations', async () => { - const scheme = `al-preview-test-${Date.now()}`; - const source = `${scheme}://AlLang/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal`; - const added: Array<{ fileFullPath: string; line: number; logMessage?: string }> = []; - let removedPath: string | undefined; - let breakpoints: any[] = []; - const provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { - provideTextDocumentContent: () => 'table 18 Customer\n{\n}' - }); - const executor: IDebuggingExecutor = { - getFileLineCount: source => DebuggingExecutor.prototype.getFileLineCount(source), - startDebugging: async () => true, - debugTestAtCursor: async () => ({ started: true, runComplete: Promise.resolve() }), - stopDebugging: async () => { /* noop */ }, - stepOver: async () => { /* noop */ }, - stepInto: async () => { /* noop */ }, - stepOut: async () => { /* noop */ }, - continue: async () => { /* noop */ }, - pause: async () => { /* noop */ }, - restart: async () => { /* noop */ }, - addBreakpoint: async (fileFullPath, line, _condition, logMessage) => { added.push({ fileFullPath, line, logMessage }); }, - removeBreakpoint: async (fileFullPath) => { removedPath = fileFullPath; }, - getCurrentDebugState: async () => new DebugState(), - getVariables: async () => ({}), - getVariableChildren: async () => [], - evaluateExpression: async () => ({}), - getBreakpoints: () => breakpoints, - clearAllBreakpoints: () => { /* noop */ }, - hasActiveSession: async () => false, - getActiveSession: () => undefined, - waitForDebugSessionReady: async () => 'no-session' - }; - - try { - const handler = new DebuggingHandler(executor, {} as any, 30); - await assert.rejects( - handler.handleAddBreakpoint({ fileFullPath: source, line: 4 }), - /out of range.*has 3 lines/ - ); - const breakpointResult = await handler.handleAddBreakpoint({ fileFullPath: source, line: 2 }); - const logpointResult = await handler.handleAddLogpoint({ - fileFullPath: source, - line: 1, - logMessage: 'Customer {Rec.SystemId}' - }); - breakpoints = [{ fileFullPath: source, line: 2 }]; - const removalResult = await handler.handleRemoveBreakpoint({ fileFullPath: source, line: 2 }); - - assert.strictEqual(added[0].fileFullPath, source); - assert.strictEqual(added[0].line, 2); - assert.strictEqual(added[1].fileFullPath, source); - assert.strictEqual(added[1].line, 1); - assert.strictEqual(added[1].logMessage, 'Customer {Rec.SystemId}'); - assert.strictEqual(removedPath, source); - assert.match(breakpointResult, /Breakpoint added/); - assert.match(logpointResult, /Logpoint added/); - assert.match(removalResult, /Breakpoint removed/); - } finally { - provider.dispose(); - } - }); -}); - /** * Regression tests for continue against a process that resumes and keeps * running (a server, an event loop) rather than stopping again. diff --git a/src/test/sourceUri.test.ts b/src/test/sourceUri.test.ts index f614429..175abd3 100644 --- a/src/test/sourceUri.test.ts +++ b/src/test/sourceUri.test.ts @@ -1,55 +1,12 @@ // Copyright (c) Microsoft Corporation. import * as assert from 'assert'; -import * as path from 'path'; import { isSourceUri, sourceFileName } from '../utils/sourceUri'; -import { toSourceText, toSourceUri } from '../utils/vscodeSourceUri'; suite('Source URI handling', () => { - test('preserves an AL virtual .dal document URI', () => { - const source = 'al-preview://AlLang/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal'; - const uri = toSourceUri(source); - - assert.strictEqual(isSourceUri(source), true); - assert.strictEqual(uri.scheme, 'al-preview'); - assert.strictEqual(uri.authority, 'AlLang'); - assert.strictEqual(uri.path, '/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal'); - assert.strictEqual( - uri.toString(), - 'al-preview://allang/437dbf0e84ff417a965ded2bb9650972/Table/18/Customer.dal' - ); - }); - - test('keeps native filesystem paths as file URIs', () => { - const source = path.join(path.sep, 'workspace', 'src', 'main.ts'); - const uri = toSourceUri(source); - - assert.strictEqual(isSourceUri(source), false); - assert.strictEqual(uri.scheme, 'file'); - assert.strictEqual(uri.fsPath, source); - }); - test('does not mistake a Windows drive letter for a URI scheme', () => { assert.strictEqual(isSourceUri('C:\\workspace\\src\\main.ts'), false); - }); - - test('reports a file on disk by its native path and a virtual document by its URI', () => { - const file = path.join(path.sep, 'workspace', 'src', 'main.ts'); - assert.strictEqual(toSourceText(toSourceUri(file)), file); - assert.strictEqual(toSourceText(toSourceUri(`file://${file.split(path.sep).join('/')}`)), file); - assert.strictEqual( - toSourceText(toSourceUri('al-preview://AlLang/app/Codeunit/51000/EXW Warehouse Service.dal')), - 'al-preview://allang/app/Codeunit/51000/EXW%20Warehouse%20Service.dal' - ); - }); - - test('different spellings of one virtual-document URI have the same text', () => { - const spellings = [ - 'al-preview://AlLang/app/Codeunit/51000/EXW Warehouse Service.dal', - 'al-preview://allang/app/Codeunit/51000/EXW%20Warehouse%20Service.dal', - 'al-preview://allang/app/Codeunit/51000/EXW Warehouse%20Service.dal' - ]; - assert.strictEqual(new Set(spellings.map(spelling => toSourceText(toSourceUri(spelling)))).size, 1); + assert.strictEqual(isSourceUri('al-preview://allang/app/Table/18/Customer.dal'), true); }); test('shows a readable file name for paths and URIs', () => { diff --git a/src/test/virtualSourceLocation.test.ts b/src/test/virtualSourceLocation.test.ts index bd8e57c..c85c337 100644 --- a/src/test/virtualSourceLocation.test.ts +++ b/src/test/virtualSourceLocation.test.ts @@ -9,8 +9,9 @@ import { DebugConfigurationManager } from '../utils/debugConfigurationManager'; /** * Language extensions can serve sources that exist only as virtual documents. * Business Central is the motivating case: the objects of an installed app are - * shown as `al-preview://allang////.dal`, and object names - * routinely contain spaces. + * shown as `al-preview://allang////.dal`, and object + * names routinely contain spaces. The stack frame below is what its debug + * adapter reports for a stop in such a document. */ const documentLines = [ 'codeunit 51000 "EXW Warehouse Service"', @@ -29,12 +30,10 @@ suite('Virtual source documents (AL .dal)', () => { let schemeCounter = 0; let scheme: string; let spacedSource: string; - let encodedSource: string; let canonicalSource: string; let provider: vscode.Disposable; let sessionDescriptor: PropertyDescriptor; let stackDescriptor: PropertyDescriptor; - let frameSource: { name?: string; path?: string } | undefined; const executor = () => new DebuggingExecutor(); const handler = (target: DebuggingExecutor = executor()) => @@ -50,15 +49,12 @@ suite('Virtual source documents (AL .dal)', () => { setup(() => { scheme = `al-preview-test-${Date.now()}-${++schemeCounter}`; - const location = 'dc644a87ff3c480e8a8f668628ae77b7/Codeunit/51000'; - spacedSource = `${scheme}://AlLang/${location}/EXW Warehouse Service.dal`; - encodedSource = `${scheme}://allang/${location}/EXW%20Warehouse%20Service.dal`; - canonicalSource = encodedSource; + spacedSource = `${scheme}://allang/debug-app/Codeunit/51000/EXW Warehouse Service.dal`; + canonicalSource = `${scheme}://allang/debug-app/Codeunit/51000/EXW%20Warehouse%20Service.dal`; provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { provideTextDocumentContent: () => documentLines.join('\n') }); - frameSource = undefined; const session: vscode.DebugSession = { id: 'al-virtual-source', name: 'AL attach', @@ -68,7 +64,13 @@ suite('Virtual source documents (AL .dal)', () => { customRequest: async (command: string) => { assert.equal(command, 'stackTrace'); return { - stackFrames: [{ id: 3, name: 'GetPackageInformation', line: 5, column: 9, source: frameSource }] + stackFrames: [{ + id: 0, + name: 'GetPackageInformation', + source: { name: 'EXW Warehouse Service', path: spacedSource, sourceReference: 0 }, + line: 5, + column: 9 + }] }; }, getDebugProtocolBreakpoint: async () => undefined @@ -78,7 +80,7 @@ suite('Virtual source documents (AL .dal)', () => { Object.defineProperty(vscode.debug, 'activeDebugSession', { configurable: true, get: () => session }); Object.defineProperty(vscode.debug, 'activeStackItem', { configurable: true, - get: () => ({ frameId: 3, threadId: 1, session }) + get: () => ({ frameId: 0, threadId: 1, session }) }); }); @@ -89,30 +91,20 @@ suite('Virtual source documents (AL .dal)', () => { provider.dispose(); }); - for (const spelling of ['a literal space', 'percent-encoding'] as const) { - test(`a stop in a virtual document reports its location (source path with ${spelling})`, async () => { - frameSource = { - name: 'EXW Warehouse Service.dal', - path: spelling === 'a literal space' ? spacedSource : encodedSource - }; - - const state = await executor().getCurrentDebugState(2); - - assert.equal(state.isPaused(), true); - assert.equal(state.frameName, 'GetPackageInformation'); - assert.equal(state.fileFullPath, canonicalSource); - assert.equal(state.fileName, 'EXW Warehouse Service.dal'); - assert.equal(state.currentLine, 5); - assert.equal(state.currentLineContent, 'if not Package.Get(packageID) then'); - assert.deepEqual(state.nextLines, [ - 'Error(PackageNotFoundErr, packageID);', - 'exit(Package.Description);' - ]); - }); - } + test('a stop in a virtual document reports its location', async () => { + const state = await executor().getCurrentDebugState(2); + + assert.equal(state.fileFullPath, canonicalSource); + assert.equal(state.fileName, 'EXW Warehouse Service.dal'); + assert.equal(state.currentLine, 5); + assert.equal(state.currentLineContent, 'if not Package.Get(packageID) then'); + assert.deepEqual(state.nextLines, [ + 'Error(PackageNotFoundErr, packageID);', + 'exit(Package.Description);' + ]); + }); test('add_breakpoint accepts the reported location unchanged', async () => { - frameSource = { name: 'EXW Warehouse Service.dal', path: spacedSource }; const state = JSON.parse(await handler().handleGetDebugStatus()).state; const result = await handler().handleAddBreakpoint({ fileFullPath: state.fileFullPath, line: state.currentLine }); @@ -123,22 +115,13 @@ suite('Virtual source documents (AL .dal)', () => { assert.equal(breakpoint.location.range.start.line, state.currentLine - 1); }); - for (const [added, removed] of [ - ['literal spaces', 'literal spaces'], - ['literal spaces', 'percent-encoding'], - ['percent-encoding', 'literal spaces'] - ] as const) { - test(`remove_breakpoint finds a breakpoint added with ${added} when given ${removed}`, async () => { - const spelled = (spelling: string) => spelling === 'literal spaces' ? spacedSource : encodedSource; - await handler().handleAddBreakpoint({ fileFullPath: spelled(added), line: 7 }); - assert.equal(sourceBreakpoints().length, 1); - - const result = await handler().handleRemoveBreakpoint({ fileFullPath: spelled(removed), line: 7 }); - - assert.match(result, /Breakpoint removed/); - assert.equal(sourceBreakpoints().length, 0); - }); - } + test('add_breakpoint rejects a line past the end of a readable virtual document', async () => { + await assert.rejects( + handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: documentLines.length + 1 }), + /out of range.*has 10 lines/ + ); + assert.equal(sourceBreakpoints().length, 0); + }); test('a virtual document that cannot be opened yet still takes a breakpoint, with a note', async () => { // Business Central serves a .dal source only once the session has stopped. @@ -152,7 +135,6 @@ suite('Virtual source documents (AL .dal)', () => { assert.match(breakpoint, /Breakpoint added at .*:81/); assert.match(breakpoint, /could not be opened, so line 81 was not checked/); - assert.match(logpoint, /Logpoint added at .*:82/); assert.match(logpoint, /could not be opened, so line 82 was not checked/); assert.deepEqual(sourceBreakpoints().map(item => item.location.range.start.line + 1).sort(), [81, 82]); }); @@ -164,13 +146,14 @@ suite('Virtual source documents (AL .dal)', () => { ); }); - test('remove_breakpoint still reports a location without a breakpoint', async () => { + test('remove_breakpoint finds a breakpoint by the URI text it was added with', async () => { await handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: 7 }); + assert.equal(sourceBreakpoints().length, 1); - const result = await handler().handleRemoveBreakpoint({ fileFullPath: spacedSource, line: 8 }); + const result = await handler().handleRemoveBreakpoint({ fileFullPath: spacedSource, line: 7 }); - assert.match(result, /No breakpoint found/); - assert.equal(sourceBreakpoints().length, 1); + assert.match(result, /Breakpoint removed/); + assert.equal(sourceBreakpoints().length, 0); }); test('breakpoints are listed with the decoded file name and the canonical URI', async () => { @@ -185,8 +168,8 @@ suite('Virtual source documents (AL .dal)', () => { test('a breakpoint in a file on disk is reported and removed by its native path', async () => { const target = executor(); - await handler(target).handleAddBreakpoint({ fileFullPath: __filename, line: 1 }); const onDisk = (location: string) => !location.startsWith('al-preview-test-'); + await handler(target).handleAddBreakpoint({ fileFullPath: __filename, line: 1 }); assert.deepEqual(reportedLocations(target, onDisk), [__filename]); const result = await handler(target).handleRemoveBreakpoint({ fileFullPath: __filename, line: 1 });