From 80a0be8d3ab93829c2418d326a6c1731a452ab0a Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:35:11 -0500 Subject: [PATCH 01/10] Launch and debug Go AppHosts from the VS Code extension The extension sent every non-Rust, non-Java, non-Node AppHost to the .NET debugger, so apphost.go was never debugged. Route .go AppHosts to the Go extension's Delve adapter, launching the AppHost package with the environment the CLI provides, and fail with a localized message when the Go extension is missing or the launch command is not `go run `. The extension advertises a versioned go-apphost.v1 capability for this. The existing `go` capability is not reused because extension builds that only debug Go resources already advertise it. Also localize the Go resource display name and label like the other languages. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/loc/xlf/aspire-vscode.xlf | 12 + extension/package.nls.json | 4 + extension/src/capabilities.ts | 5 + extension/src/debugger/AspireDebugSession.ts | 43 +++- extension/src/debugger/languages/go.ts | 36 +++ extension/src/loc/strings.ts | 6 +- extension/src/test/goDebugger.test.ts | 246 ++++++++++++++++++- extension/src/test/strings.test.ts | 25 ++ 8 files changed, 366 insertions(+), 11 deletions(-) diff --git a/extension/loc/xlf/aspire-vscode.xlf b/extension/loc/xlf/aspire-vscode.xlf index 7fb7f07b5c6..ca6e149848c 100644 --- a/extension/loc/xlf/aspire-vscode.xlf +++ b/extension/loc/xlf/aspire-vscode.xlf @@ -484,9 +484,18 @@ Get started with Aspire + + Go + + + Go AppHosts require Go debugger support. Set up {0} in the Extensions view, then start the AppHost again. + Go from a workspace to a running, observable distributed app. + + Go: {0} + How to start the AppHost: 'run' starts it without attaching the debugger, 'debug' starts it with the debugger attached. @@ -1051,6 +1060,9 @@ The Deno AppHost command does not contain the required 'run' subcommand. + + The Go AppHost launch command was not recognized and cannot be debugged. + The Java AppHost launch command was not recognized and cannot be debugged. diff --git a/extension/package.nls.json b/extension/package.nls.json index df6b001a9fc..f235cec5dce 100644 --- a/extension/package.nls.json +++ b/extension/package.nls.json @@ -365,6 +365,10 @@ "aspire-vscode.strings.javaAttachNotSupported": "Java resources are started by the IDE rather than attached to, and the app host requested an attach session. Aspire cannot start one because no debug address is available.", "aspire-vscode.strings.javaDebuggerExtensionNotInstalled": "Java AppHosts require Java debugger support. Set up {0} in the Extensions view, then start the AppHost again.", "aspire-vscode.strings.rustDebuggerExtensionNotInstalled": "Rust AppHosts require native debugger support. Set up {0} in the Extensions view, then start the AppHost again.", + "aspire-vscode.strings.goDisplayName": "Go: {0}", + "aspire-vscode.strings.goLabel": "Go", + "aspire-vscode.strings.goDebuggerExtensionNotInstalled": "Go AppHosts require Go debugger support. Set up {0} in the Extensions view, then start the AppHost again.", + "aspire-vscode.strings.goAppHostCommandNotRecognized": "The Go AppHost launch command was not recognized and cannot be debugged.", "aspire-vscode.strings.javaDisplayName": "Java: {0}", "aspire-vscode.strings.javaLabel": "Java", "aspire-vscode.strings.codeLensSpringBootDashboardBypassesAspire": "⚠️ Do not start this app from the Spring Boot Dashboard; it bypasses Aspire", diff --git a/extension/src/capabilities.ts b/extension/src/capabilities.ts index f8d5acd8bc0..28feba12256 100644 --- a/extension/src/capabilities.ts +++ b/extension/src/capabilities.ts @@ -16,6 +16,7 @@ export type Capability = | 'ms-python.python' // Older AppHost versions used this extension identifier instead of python | 'go' // Support for running Go projects | 'golang.go' // Older AppHost versions used this extension identifier instead of go + | 'go-apphost.v1' // Support for debugging Go AppHosts through the Go extension's Delve adapter | 'rust' // Support for running Rust projects | 'ms-vscode.cpptools' // Rust debug adapter extension identifier on Windows (cppvsdbg) | 'vadimcn.vscode-lldb' // Rust debug adapter extension identifier on macOS/Linux (CodeLLDB) @@ -245,6 +246,10 @@ export function getSupportedCapabilities(platform: NodeJS.Platform = process.pla if (isGoInstalled()) { capabilities.push("go"); capabilities.push("golang.go"); + // `go` only means "can debug Go resources", and extension builds that cannot launch a Go AppHost + // advertise it too. The CLI gates AppHost launching on this separate versioned name so those + // builds are never asked to start apphost.go (they would hand it to the .NET debugger). + capabilities.push("go-apphost.v1"); } if (isRustInstalled(platform)) { diff --git a/extension/src/debugger/AspireDebugSession.ts b/extension/src/debugger/AspireDebugSession.ts index 84c46834f80..3bad544bcfa 100644 --- a/extension/src/debugger/AspireDebugSession.ts +++ b/extension/src/debugger/AspireDebugSession.ts @@ -2,17 +2,18 @@ import * as vscode from "vscode"; import { EventEmitter } from "vscode"; import { promises as fs } from "fs"; import { createDebugAdapterTracker, AppHostTrackerOptions } from "./adapterTracker"; -import { AspireResourceExtendedDebugConfiguration, AspireResourceDebugSession, EnvVar, AspireExtendedDebugConfiguration, NodeLaunchConfiguration, ProcessRestartedNotification, ProjectLaunchConfiguration, JavaLaunchConfiguration, RustLaunchConfiguration, SessionTerminatedNotification, StartAppHostOptions, AspireOperationKind } from "../dcp/types"; +import { AspireResourceExtendedDebugConfiguration, AspireResourceDebugSession, EnvVar, AspireExtendedDebugConfiguration, GoLaunchConfiguration, NodeLaunchConfiguration, ProcessRestartedNotification, ProjectLaunchConfiguration, JavaLaunchConfiguration, RustLaunchConfiguration, SessionTerminatedNotification, StartAppHostOptions, AspireOperationKind } from "../dcp/types"; import { extensionLogOutputChannel } from "../utils/logging"; import AspireDcpServer, { generateDcpIdPrefix } from "../dcp/AspireDcpServer"; import { redactCliArgsForLogging, spawnCliProcess, terminateCliProcess } from "../utils/process/cliProcess"; -import { disconnectingFromSession, launchingWithAppHost, launchingWithDirectory, processExceptionOccurred, processExitedWithCode, appHostSessionTerminated, debugSessionsFailedToStop, debugSessionStartTimedOut, debugSessionStopTimedOut, rustDebuggerExtensionNotInstalled, javaDebuggerExtensionNotInstalled, javaAppHostCommandNotRecognized } from "../loc/strings"; +import { disconnectingFromSession, launchingWithAppHost, launchingWithDirectory, processExceptionOccurred, processExitedWithCode, appHostSessionTerminated, debugSessionsFailedToStop, debugSessionStartTimedOut, debugSessionStopTimedOut, rustDebuggerExtensionNotInstalled, javaDebuggerExtensionNotInstalled, javaAppHostCommandNotRecognized, goDebuggerExtensionNotInstalled, goAppHostCommandNotRecognized } from "../loc/strings"; import { isExtensionInstalled } from "../capabilities"; import { projectDebuggerExtension } from "./languages/dotnet"; import { AnsiColors } from "../utils/AspireTerminalProvider"; import { applyTextStyle } from "../utils/strings"; import { nodeDebuggerExtension } from "./languages/node"; import { createDefaultRustDebuggerExtension } from "./languages/rust"; +import { goDebuggerExtension, parseGoAppHostCommand } from "./languages/go"; import { javaDebuggerExtension, parseJavaAppHostCommand, resolveJavaClassPaths } from "./languages/java"; import { cleanupRun } from "./runCleanupRegistry"; import { BrowserDebugSessionTermination } from "./browserDebugSessionTermination"; @@ -1442,6 +1443,7 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche private static readonly _dotnetAppHostExtensions = ['.cs', '.csproj', '.fsproj', '.vbproj']; private static readonly _rustAppHostExtensions = ['.rs']; private static readonly _javaAppHostExtensions = ['.java']; + private static readonly _goAppHostExtensions = ['.go']; private _appHostRestartRequested = false; private _appHostTerminationRequested = false; @@ -1461,6 +1463,7 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche const isDotNetAppHost = AspireDebugSession._dotnetAppHostExtensions.includes(fileExtension); const isRustAppHost = AspireDebugSession._rustAppHostExtensions.includes(fileExtension); const isJavaAppHost = AspireDebugSession._javaAppHostExtensions.includes(fileExtension); + const isGoAppHost = AspireDebugSession._goAppHostExtensions.includes(fileExtension); // The CLI only routes an AppHost here when the language declares ExtensionLaunchCapability, so // this is parsed before choosing a debugger: an unrecognised command means we cannot build a @@ -1471,13 +1474,23 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche throw new Error(javaAppHostCommandNotRecognized()); } + // Parsed up front for the same reason as Java: a command that is not `go run ` cannot be + // turned into a launch configuration, and passing it through would debug the wrong program. + const goCommand = isGoAppHost ? parseGoAppHostCommand(args) : null; + + if (isGoAppHost && !goCommand) { + throw new Error(goAppHostCommandNotRecognized()); + } + const debuggerExtension = isNodeAppHost ? nodeDebuggerExtension : isRustAppHost ? createDefaultRustDebuggerExtension() : isJavaAppHost ? javaDebuggerExtension - : projectDebuggerExtension; + : isGoAppHost + ? goDebuggerExtension + : projectDebuggerExtension; // Resource launches are gated by getResourceDebuggerExtensions, which omits Rust when no native // debugger extension is installed. This path builds the descriptor directly, so without the same @@ -1494,6 +1507,12 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche throw new Error(javaDebuggerExtensionNotInstalled(debuggerExtension.extensionId)); } + // And for Go: the `go` debug type belongs to the Go extension, so without it VS Code would fail + // the session with the same raw "configured debug type is not supported" error. + if (isGoAppHost && debuggerExtension.extensionId && !isExtensionInstalled(debuggerExtension.extensionId)) { + throw new Error(goDebuggerExtensionNotInstalled(debuggerExtension.extensionId)); + } + // Register the adapter tracker with an app host restart handler. // When the user clicks "restart" on the app host child session, // we suppress VS Code's automatic child restart and restart the @@ -1503,10 +1522,9 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche // The .NET debugger (`coreclr`) emits a lot of `console`-category chatter // (module loads, exception-thrown notifications, the debugger banner, etc.) // into the parent debug console, and `Microsoft.Extensions.Logging` lines need - // correlation and severity styling. Other languages (Node, and future - // additions like Python/Go) use different debug adapters that don't produce - // that noise, so we pass their output through unmodified until/unless they - // explicitly opt in to filtering. + // correlation and severity styling. Other languages (Node, Rust, Java and Go) use different + // debug adapters that don't produce that noise, so we pass their output through unmodified + // until/unless they explicitly opt in to filtering. this.createDebugAdapterTrackerCore( debuggerExtension.debugAdapter, { @@ -1569,6 +1587,17 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche ...(javaCommand!.vmArgs.length > 0 ? { vm_args: javaCommand!.vmArgs } : {}) } as JavaLaunchConfiguration; } + else if (isGoAppHost) { + // The program is the AppHost directory, not apphost.go: `go run .` compiles every file in the + // package, and a single-file program would leave out the AppHost's sibling .go files. A package + // path other than "." resolves against the same directory the CLI starts `go run` in. + appHostArgs = goCommand!.appHostArgs; + launchConfig = { + type: 'go', + program: path.resolve(path.dirname(projectFile), goCommand!.packagePath), + working_directory: path.dirname(projectFile) + } as GoLaunchConfiguration; + } else { // The CLI sends the full dotnet CLI args (e.g., ["run", "--no-build", "--project", "...", "--", ...appHostArgs]). // Since we launch the apphost directly via the debugger (not via dotnet run), extract only the args after "--". diff --git a/extension/src/debugger/languages/go.ts b/extension/src/debugger/languages/go.ts index 96dc5e934d4..422c98efc9c 100644 --- a/extension/src/debugger/languages/go.ts +++ b/extension/src/debugger/languages/go.ts @@ -54,3 +54,39 @@ export const goDebuggerExtension: ResourceDebuggerExtension = { debugConfiguration.args = args ?? []; } }; + +// Splits the Go AppHost launch command the CLI sends into the pieces the debug adapter needs. +// +// GoLanguageSupport starts the AppHost with `go run .` from the AppHost directory, and the CLI +// prepends the resolved executable, so the command arrives as: +// +// ["C:\\Program Files\\Go\\bin\\go.exe", "run", "."] +// ["/usr/local/go/bin/go", "run", ".", ...appHostArgs] +// +// The Go debug adapter builds and starts the package itself, so the executable and the `run` verb are +// dropped and only the package and the AppHost's own arguments are kept. The executable is checked +// rather than launched: the adapter finds the toolchain through the Go extension's own settings. +// +// Returns null for any other shape, including `go run` flags such as -tags or -race. A launch +// configuration has no place for them on this path, and forwarding one would hand a flag to the +// adapter as the program to debug. +export function parseGoAppHostCommand(args: string[]): { packagePath: string; appHostArgs: string[] } | null { + if (args.length < 3) { + return null; + } + + // Split on both separators so the name is found whichever path flavour the CLI reported. + const executable = args[0].split(/[\\/]/).pop()?.toLowerCase(); + if (executable !== 'go' && executable !== 'go.exe') { + return null; + } + + if (args[1] !== 'run' || args[2].startsWith('-')) { + return null; + } + + return { + packagePath: args[2], + appHostArgs: args.slice(3) + }; +} diff --git a/extension/src/loc/strings.ts b/extension/src/loc/strings.ts index 9a022b16e91..94d0f7bc697 100644 --- a/extension/src/loc/strings.ts +++ b/extension/src/loc/strings.ts @@ -206,8 +206,10 @@ export const unsupportedBrowserDebugTargetWithoutUrl = (browser: string, support export const csharpExtensionMissingForBlazorDebugging = (extensionId: string, minimumVersion: string) => vscode.l10n.t('Debugging this Blazor client requires {0} version {1} or later. Install the C# extension, then start debugging again.', extensionId, minimumVersion); export const csharpExtensionOutdatedForBlazorDebugging = (extensionId: string, installedVersion: string, minimumVersion: string) => vscode.l10n.t('Debugging this Blazor client requires {0} version {2} or later. Installed version: {1}. Update the C# extension, then start debugging again.', extensionId, installedVersion, minimumVersion); export const missingBlazorClientProject = (projectPath: string) => vscode.l10n.t("The Blazor client project '{0}' does not exist. Restore or rebuild the AppHost, then start debugging again.", projectPath); -export const goDisplayName = (program: string) => `Go: ${program}`; -export const goLabel = 'Go'; +export const goDisplayName = (program: string) => vscode.l10n.t('Go: {0}', program); +export const goLabel = vscode.l10n.t('Go'); +export const goDebuggerExtensionNotInstalled = (extensionId: string) => vscode.l10n.t('Go AppHosts require Go debugger support. Set up {0} in the Extensions view, then start the AppHost again.', extensionId); +export const goAppHostCommandNotRecognized = () => vscode.l10n.t('The Go AppHost launch command was not recognized and cannot be debugged.'); export const rustDisplayName = (program: string) => vscode.l10n.t('Rust: {0}', program); export const rustLabel = vscode.l10n.t('Rust'); export const rustBuildFailedWithError = (workingDirectory: string, error: string) => vscode.l10n.t('cargo build failed in {0} with error: {1}.', workingDirectory, error); diff --git a/extension/src/test/goDebugger.test.ts b/extension/src/test/goDebugger.test.ts index 770db293e16..f4183ceb617 100644 --- a/extension/src/test/goDebugger.test.ts +++ b/extension/src/test/goDebugger.test.ts @@ -1,11 +1,14 @@ import * as assert from 'assert'; +import * as path from 'path'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import { getSupportedCapabilities } from '../capabilities'; import { AspireDebugSession } from '../debugger/AspireDebugSession'; +import * as debuggerExtensionsModule from '../debugger/debuggerExtensions'; import { getResourceDebuggerExtensions } from '../debugger/debuggerExtensions'; -import { goDebuggerExtension } from '../debugger/languages/go'; -import { AspireResourceExtendedDebugConfiguration, GoLaunchConfiguration } from '../dcp/types'; +import { goDebuggerExtension, parseGoAppHostCommand } from '../debugger/languages/go'; +import { AspireExtendedDebugConfiguration, AspireResourceExtendedDebugConfiguration, EnvVar, GoLaunchConfiguration } from '../dcp/types'; +import { goAppHostCommandNotRecognized, goDebuggerExtensionNotInstalled } from '../loc/strings'; suite('Go Debugger Extension Tests', () => { const fakeAspireDebugSession = {} as AspireDebugSession; @@ -20,9 +23,22 @@ suite('Go Debugger Extension Tests', () => { const capabilities = getSupportedCapabilities(); assert.ok(capabilities.includes('go')); assert.ok(capabilities.includes('golang.go')); + assert.ok(capabilities.includes('go-apphost.v1')); assert.ok(getResourceDebuggerExtensions().some(extension => extension.resourceType === 'go')); }); + test('does not advertise Go support when the Go extension is missing', () => { + sinon.stub(vscode.extensions, 'getExtension').returns(undefined); + + const capabilities = getSupportedCapabilities(); + assert.ok(!capabilities.includes('go')); + assert.ok(!capabilities.includes('golang.go')); + // The CLI only hands apphost.go to the extension when this is advertised, so it has to disappear + // with the Go extension or the CLI would ask for a debugger that is not there. + assert.ok(!capabilities.includes('go-apphost.v1')); + assert.ok(!getResourceDebuggerExtensions().some(extension => extension.resourceType === 'go')); + }); + test('configures VS Code Go debugger with dlv-dap', async () => { const launchConfig: GoLaunchConfiguration = { type: 'go', @@ -87,6 +103,232 @@ suite('Go Debugger Extension Tests', () => { }); }); +suite('Go AppHost Command Parsing Tests', () => { + // The CLI starts every Go AppHost as `go run .`, so the extension can recover the package to debug + // from the command line instead of re-deriving the module layout. + test('parses the go run command the CLI sends', () => { + assert.deepStrictEqual(parseGoAppHostCommand(['go', 'run', '.']), { packagePath: '.', appHostArgs: [] }); + }); + + test('accepts a toolchain referenced by an absolute path', () => { + for (const executable of ['/usr/local/go/bin/go', 'C:\\Program Files\\Go\\bin\\go.exe']) { + assert.deepStrictEqual( + parseGoAppHostCommand([executable, 'run', '.']), + { packagePath: '.', appHostArgs: [] }, + executable); + } + }); + + test('matches the toolchain name regardless of case', () => { + // Windows reports the executable with whatever casing the file system stored. + assert.deepStrictEqual( + parseGoAppHostCommand(['C:\\Go\\bin\\GO.EXE', 'run', '.']), + { packagePath: '.', appHostArgs: [] }); + }); + + test('keeps every argument after the package for the AppHost', () => { + // Anything after the package belongs to the program, including values that look like go flags. + assert.deepStrictEqual( + parseGoAppHostCommand(['go', 'run', '.', '--operation', 'run', '-tags=ignored']), + { packagePath: '.', appHostArgs: ['--operation', 'run', '-tags=ignored'] }); + }); + + test('keeps a package path other than the current directory', () => { + assert.strictEqual(parseGoAppHostCommand(['go', 'run', './cmd/apphost'])?.packagePath, './cmd/apphost'); + }); + + test('returns null when go run flags precede the package', () => { + // The launch configuration has no place for them on this path, and the flag would otherwise be + // taken as the program to debug. + assert.strictEqual(parseGoAppHostCommand(['go', 'run', '-tags=dev', '.']), null); + assert.strictEqual(parseGoAppHostCommand(['go', 'run', '-race', '.']), null); + }); + + test('returns null when the command is not go run', () => { + assert.strictEqual(parseGoAppHostCommand(['go', 'build', '.']), null); + assert.strictEqual(parseGoAppHostCommand(['go', 'test', '.']), null); + assert.strictEqual(parseGoAppHostCommand(['go', 'tool', 'dlv']), null); + }); + + test('returns null when the executable is not the go toolchain', () => { + assert.strictEqual(parseGoAppHostCommand(['dotnet', 'run', '.']), null); + assert.strictEqual(parseGoAppHostCommand(['gofmt', 'run', '.']), null); + // The name is read from the last path segment, not from a directory on the way to the executable. + assert.strictEqual(parseGoAppHostCommand(['/usr/local/go/bin/air', 'run', '.']), null); + }); + + test('returns null when the command is too short to name a package', () => { + assert.strictEqual(parseGoAppHostCommand([]), null); + assert.strictEqual(parseGoAppHostCommand(['go']), null); + assert.strictEqual(parseGoAppHostCommand(['go', 'run']), null); + }); +}); + +suite('Go AppHost Launch Tests', () => { + const appHostPath = '/workspace/apphost.go'; + + teardown(() => sinon.restore()); + + function createAppHostDebugSession(configuration: Partial = {}): AspireDebugSession { + const parentDebugSession = { + id: 'aspire-session', + type: 'aspire', + name: 'Aspire', + configuration: { + type: 'aspire', + request: 'launch', + name: 'Aspire', + program: appHostPath, + command: 'run', + ...configuration + }, + }; + + return new AspireDebugSession( + parentDebugSession as unknown as vscode.DebugSession, + {} as any, + {} as any, + {} as any, + () => { }); + } + + test('stops a Go AppHost launch with install guidance when the Go extension is not installed', async () => { + // startAppHost builds the debugger descriptor directly instead of going through + // getResourceDebuggerExtensions, so without its own gate VS Code fails the session with the raw + // "configured debug type is not supported" rather than naming the extension to install. + stubInstalledExtensions([]); + const showErrorMessage = sinon.stub(vscode.window, 'showErrorMessage'); + sinon.stub(vscode.debug, 'stopDebugging').resolves(); + const createDebugSessionConfiguration = sinon.stub(debuggerExtensionsModule, 'createDebugSessionConfiguration'); + const debugSession = createAppHostDebugSession(); + sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + + await debugSession.startAppHost(appHostPath, ['go', 'run', '.'], [], true, { forceBuild: false }); + + sinon.assert.notCalled(createDebugSessionConfiguration); + sinon.assert.calledOnce(showErrorMessage); + assert.strictEqual(showErrorMessage.firstCall.args[0], goDebuggerExtensionNotInstalled(goDebuggerExtension.extensionId!)); + }); + + test('stops a Go AppHost launch when the command is not go run with a package', async () => { + // Debugging the wrong program would be the alternative to failing loudly. + stubInstalledExtensions(['golang.go']); + const showErrorMessage = sinon.stub(vscode.window, 'showErrorMessage'); + sinon.stub(vscode.debug, 'stopDebugging').resolves(); + const createDebugSessionConfiguration = sinon.stub(debuggerExtensionsModule, 'createDebugSessionConfiguration'); + const debugSession = createAppHostDebugSession(); + const trackerStub = sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + + await debugSession.startAppHost(appHostPath, ['go', 'run', '-race', '.'], [], true, { forceBuild: false }); + + sinon.assert.notCalled(trackerStub); + sinon.assert.notCalled(createDebugSessionConfiguration); + sinon.assert.calledOnce(showErrorMessage); + assert.strictEqual(showErrorMessage.firstCall.args[0], goAppHostCommandNotRecognized()); + }); + + test('debugs the AppHost package with Delve and forwards the AppHost server environment', async () => { + stubInstalledExtensions(['golang.go']); + const debugSession = createAppHostDebugSession(); + sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + const startAndGetDebugSession = sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + const environment: EnvVar[] = [ + { name: 'REMOTE_APP_HOST_SOCKET_PATH', value: '/tmp/aspire-remote.sock' }, + { name: 'ASPIRE_APPHOST_FILEPATH', value: appHostPath } + ]; + + await debugSession.startAppHost( + appHostPath, + ['/usr/local/go/bin/go', 'run', '.', '--operation', 'run'], + environment, + true, + { forceBuild: false }); + + sinon.assert.calledOnce(startAndGetDebugSession); + const debugConfig = startAndGetDebugSession.firstCall.args[0]; + assert.strictEqual(debugConfig.type, 'go'); + assert.strictEqual(debugConfig.request, 'launch'); + assert.strictEqual(debugConfig.mode, 'debug'); + assert.strictEqual(debugConfig.debugAdapter, 'dlv-dap'); + // `go run .` compiles every file in the package, so the program is the AppHost directory rather + // than apphost.go, which would leave out its sibling files. + assert.strictEqual(debugConfig.program, path.resolve('/workspace')); + assert.strictEqual(debugConfig.cwd, '/workspace'); + assert.deepStrictEqual(debugConfig.args, ['--operation', 'run']); + assert.strictEqual(debugConfig.noDebug, false); + assert.strictEqual(debugConfig.isApphost, true); + assert.strictEqual(debugConfig.resourceType, 'go'); + assert.strictEqual(debugConfig.env?.REMOTE_APP_HOST_SOCKET_PATH, '/tmp/aspire-remote.sock'); + assert.strictEqual(debugConfig.env?.ASPIRE_APPHOST_FILEPATH, appHostPath); + assert.strictEqual(debugConfig.buildFlags, undefined); + }); + + test('starts the AppHost without debugging when debugging is off', async () => { + stubInstalledExtensions(['golang.go']); + const debugSession = createAppHostDebugSession(); + sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + const startAndGetDebugSession = sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + + await debugSession.startAppHost(appHostPath, ['go', 'run', '.'], [], false, { forceBuild: false }); + + const debugConfig = startAndGetDebugSession.firstCall.args[0]; + assert.strictEqual(debugConfig.type, 'go'); + assert.strictEqual(debugConfig.noDebug, true); + }); + + test('resolves a package path other than the current directory against the AppHost directory', async () => { + stubInstalledExtensions(['golang.go']); + const debugSession = createAppHostDebugSession(); + sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + const startAndGetDebugSession = sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + + await debugSession.startAppHost(appHostPath, ['go', 'run', './cmd/apphost'], [], true, { forceBuild: false }); + + const debugConfig = startAndGetDebugSession.firstCall.args[0]; + assert.strictEqual(debugConfig.program, path.resolve('/workspace', 'cmd', 'apphost')); + assert.strictEqual(debugConfig.cwd, '/workspace'); + }); + + test('keeps the build flags configured for the AppHost debugger', async () => { + // The AppHost command carries no build flags, so aspire.config.json and launch.json are the only + // place to ask for them. + stubInstalledExtensions(['golang.go']); + const debugSession = createAppHostDebugSession({ + debuggers: { apphost: { buildFlags: '-tags=integration' } } + }); + sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + const startAndGetDebugSession = sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + + await debugSession.startAppHost(appHostPath, ['go', 'run', '.'], [], true, { forceBuild: false }); + + const debugConfig = startAndGetDebugSession.firstCall.args[0]; + assert.strictEqual(debugConfig.buildFlags, '-tags=integration'); + }); + + test('tracks the Go debug session so the toolbar restart restarts the whole Aspire session', async () => { + stubInstalledExtensions(['golang.go']); + const debugSession = createAppHostDebugSession(); + const trackerStub = sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + + await debugSession.startAppHost(appHostPath, ['go', 'run', '.'], [], true, { forceBuild: false }); + + sinon.assert.calledOnce(trackerStub); + assert.strictEqual(trackerStub.firstCall.args[0], 'go'); + const restartHandler = trackerStub.firstCall.args[1]?.onRestartRequested; + assert.ok(restartHandler); + // Returning true suppresses VS Code's own restart of the child session; the Aspire session is + // restarted instead. + assert.strictEqual(restartHandler(debugSession.debugSessionId), true); + }); +}); + +function stubInstalledExtensions(extensionIds: string[]): void { + sinon.stub(vscode.extensions, 'getExtension').callsFake((extensionId: string) => { + return extensionIds.includes(extensionId) ? { id: extensionId } as vscode.Extension : undefined; + }); +} + function createDebugConfig(): AspireResourceExtendedDebugConfiguration { return { runId: '1', diff --git a/extension/src/test/strings.test.ts b/extension/src/test/strings.test.ts index f6330c3211b..e4c5a37c816 100644 --- a/extension/src/test/strings.test.ts +++ b/extension/src/test/strings.test.ts @@ -258,6 +258,28 @@ suite('utils/strings tests', () => { assert.deepStrictEqual(missingFromXlf, [], 'Regenerate loc/xlf/aspire-vscode.xlf with "yarn run localize" after adding package.nls.json entries.'); }); + test('Go loc strings are present in package.nls.json and the generated XLF catalog', () => { + // Same guard as the Rust and Java strings: package.nls.json is the only input to the XLF + // catalog (see gulpfile.js), so a Go string that only exists in strings.ts ships untranslated. + const extensionRoot = path.resolve(__dirname, '..', '..'); + const stringsSource = fs.readFileSync(path.join(extensionRoot, 'src', 'loc', 'strings.ts'), 'utf8'); + const packageNls = JSON.parse(fs.readFileSync(path.join(extensionRoot, 'package.nls.json'), 'utf8')) as Record; + const xlf = fs.readFileSync(path.join(extensionRoot, 'loc', 'xlf', 'aspire-vscode.xlf'), 'utf8'); + + // The capital letter keeps the scan to goXxx names and away from unrelated words that start with "go". + const declarationPattern = /export\s+const\s+(go[A-Z][A-Za-z0-9_]*)\s*=\s*(?:\([^)]*\)\s*=>\s*)?vscode\.l10n\.t\(/g; + const names = [...stringsSource.matchAll(declarationPattern)].map(match => match[1]); + for (const expectedName of ['goDisplayName', 'goLabel', 'goDebuggerExtensionNotInstalled', 'goAppHostCommandNotRecognized']) { + assert.ok(names.includes(expectedName), `Expected ${expectedName} to be declared in strings.ts.`); + } + + const missingFromNls = names.filter(name => packageNls[`aspire-vscode.strings.${name}`] === undefined); + assert.deepStrictEqual(missingFromNls, [], 'Every Go loc string needs an aspire-vscode.strings.* entry in package.nls.json.'); + + const missingFromXlf = names.filter(name => !xlf.includes(``)); + assert.deepStrictEqual(missingFromXlf, [], 'Regenerate loc/xlf/aspire-vscode.xlf with "yarn run localize" after adding package.nls.json entries.'); + }); + test('debugger setup strings use neutral wording for missing or disabled extensions', () => { const extensionRoot = path.resolve(__dirname, '..', '..'); const packageNls = JSON.parse(fs.readFileSync(path.join(extensionRoot, 'package.nls.json'), 'utf8')) as Record; @@ -270,6 +292,9 @@ suite('utils/strings tests', () => { assert.strictEqual( locStrings.javaDebuggerExtensionNotInstalled('vscjava.vscode-java-debug'), 'Java AppHosts require Java debugger support. Set up vscjava.vscode-java-debug in the Extensions view, then start the AppHost again.'); + assert.strictEqual( + locStrings.goDebuggerExtensionNotInstalled('golang.go'), + 'Go AppHosts require Go debugger support. Set up golang.go in the Extensions view, then start the AppHost again.'); }); }); From 91a648d2128cfeaa3745e8ce39975db98c49b67e Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:35:23 -0500 Subject: [PATCH 02/10] Recognize apphost.go in the VS Code extension Classify apphost.go as a Go AppHost for language summaries and launch-failure telemetry, watch it during AppHost discovery, activate the extension when a workspace contains it, and show the AppHost explorer actions on .go files. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/package.json | 5 ++-- extension/src/services/launchFailureStore.ts | 2 ++ .../src/test-e2e/packageSurface.e2e.test.ts | 1 + extension/src/test/appHostDiscovery.test.ts | 14 +++++++++ extension/src/test/appHostLanguage.test.ts | 29 +++++++++++++++++++ extension/src/test/launchFailureStore.test.ts | 17 +++++++++++ extension/src/test/packageManifest.test.ts | 9 +++++- extension/src/utils/appHostDiscovery.ts | 1 + extension/src/utils/appHostLanguage.ts | 25 ++++++++++++++-- 9 files changed, 98 insertions(+), 5 deletions(-) diff --git a/extension/package.json b/extension/package.json index a2724701d34..ec1eda5361e 100644 --- a/extension/package.json +++ b/extension/package.json @@ -49,6 +49,7 @@ "workspaceContains:**/apphost.mjs", "workspaceContains:**/apphost.cjs", "workspaceContains:**/apphost.rs", + "workspaceContains:**/apphost.go", "workspaceContains:**/AppHost.java", "workspaceContains:**/apphost.java", "workspaceContains:**/src/main/java/AppHost.java", @@ -820,12 +821,12 @@ "explorer/context": [ { "command": "aspire-vscode.runAppHostFromExplorer", - "when": "resourceFilename =~ /apphost\\.(cs|ts|mts|cts|js|mjs|cjs|rs|java)$/i", + "when": "resourceFilename =~ /apphost\\.(cs|ts|mts|cts|js|mjs|cjs|rs|java|go)$/i", "group": "aspire_actions@1" }, { "command": "aspire-vscode.debugAppHostFromExplorer", - "when": "resourceFilename =~ /apphost\\.(cs|ts|mts|cts|js|mjs|cjs|rs|java)$/i", + "when": "resourceFilename =~ /apphost\\.(cs|ts|mts|cts|js|mjs|cjs|rs|java|go)$/i", "group": "aspire_actions@2" } ], diff --git a/extension/src/services/launchFailureStore.ts b/extension/src/services/launchFailureStore.ts index 7dfe5378b6f..890c5d0ad14 100644 --- a/extension/src/services/launchFailureStore.ts +++ b/extension/src/services/launchFailureStore.ts @@ -73,6 +73,8 @@ export function getLaunchFailureProviderKindForAppHostPath(appHostPath: string | return 'node'; case 'java': return 'java'; + case 'go': + return 'go'; case 'rust': return 'rust'; default: diff --git a/extension/src/test-e2e/packageSurface.e2e.test.ts b/extension/src/test-e2e/packageSurface.e2e.test.ts index 85ba7fb9ca7..93bd4de8772 100644 --- a/extension/src/test-e2e/packageSurface.e2e.test.ts +++ b/extension/src/test-e2e/packageSurface.e2e.test.ts @@ -560,6 +560,7 @@ const expectedActivationEvents = [ 'workspaceContains:**/apphost.mjs', 'workspaceContains:**/apphost.cjs', 'workspaceContains:**/apphost.rs', + 'workspaceContains:**/apphost.go', 'workspaceContains:**/AppHost.java', 'workspaceContains:**/apphost.java', 'workspaceContains:**/src/main/java/AppHost.java', diff --git a/extension/src/test/appHostDiscovery.test.ts b/extension/src/test/appHostDiscovery.test.ts index a423bec463b..7c3f3d67d13 100644 --- a/extension/src/test/appHostDiscovery.test.ts +++ b/extension/src/test/appHostDiscovery.test.ts @@ -143,6 +143,19 @@ suite('AppHost discovery', () => { assert.strictEqual(candidate ? getDebugTargetForCandidate(candidate) : undefined, appHostPath); }); + test('keeps Go AppHost candidate as source file', () => { + const appHostPath = buildPath('workspace', 'AppHost', 'apphost.go'); + + const candidate = findCandidateForEditorFile(appHostPath, [{ + path: appHostPath, + language: 'go', + status: 'buildable', + }]); + + assert.strictEqual(candidate?.path, appHostPath); + assert.strictEqual(candidate ? getDebugTargetForCandidate(candidate) : undefined, appHostPath); + }); + test('returns undefined when no discovered candidate contains C# source file', () => { const programPath = buildPath('workspace', 'Web', 'Program.cs'); @@ -474,6 +487,7 @@ suite('AppHost discovery', () => { assert.ok(watchedPatterns.includes('**/apphost.mjs')); assert.ok(watchedPatterns.includes('**/apphost.cjs')); assert.ok(watchedPatterns.includes('**/apphost.rs')); + assert.ok(watchedPatterns.includes('**/apphost.go')); // Case matters: watcher globs are case-sensitive on Linux and the file is AppHost.java. assert.ok(watchedPatterns.includes('**/AppHost.java')); } diff --git a/extension/src/test/appHostLanguage.test.ts b/extension/src/test/appHostLanguage.test.ts index 03b67f6fa95..b67870fcda8 100644 --- a/extension/src/test/appHostLanguage.test.ts +++ b/extension/src/test/appHostLanguage.test.ts @@ -36,6 +36,10 @@ suite('appHostLanguage.summarizeAppHostLanguages', () => { assert.strictEqual(summarizeAppHostLanguages([c('rust'), c('Rust'), c('rust/cargo')]), 'rust'); }); + test('returns go when every candidate is Go', () => { + assert.strictEqual(summarizeAppHostLanguages([c('go'), c('Go'), c('go/modules')]), 'go'); + }); + test('returns polyglot for a mix of csharp and typescript', () => { assert.strictEqual(summarizeAppHostLanguages([c('csharp'), c('typescript')]), 'polyglot'); }); @@ -46,6 +50,12 @@ suite('appHostLanguage.summarizeAppHostLanguages', () => { assert.strictEqual(summarizeAppHostLanguages([c('java'), c('rust')]), 'polyglot'); }); + test('returns polyglot when Go is mixed with another known language', () => { + assert.strictEqual(summarizeAppHostLanguages([c('csharp'), c('go')]), 'polyglot'); + assert.strictEqual(summarizeAppHostLanguages([c('typescript'), c('go')]), 'polyglot'); + assert.strictEqual(summarizeAppHostLanguages([c('rust'), c('go')]), 'polyglot'); + }); + test('returns polyglot when an unknown language is mixed with a known one', () => { assert.strictEqual(summarizeAppHostLanguages([c('csharp'), c('python')]), 'polyglot'); }); @@ -91,6 +101,11 @@ suite('appHostLanguage.classifyAppHostPath', () => { assert.strictEqual(classifyAppHostPath('/abs/path/apphost.rs'), 'rust'); }); + test('classifies Go source files', () => { + assert.strictEqual(classifyAppHostPath('/abs/path/apphost.go'), 'go'); + assert.strictEqual(classifyAppHostPath('C:\\repos\\app\\apphost.go'), 'go'); + }); + test('returns unknown for unrecognized file extensions and directories', () => { assert.strictEqual(classifyAppHostPath('/repo/apphost.py'), 'unknown'); assert.strictEqual(classifyAppHostPath('/repo/apphost'), 'unknown'); @@ -100,6 +115,7 @@ suite('appHostLanguage.classifyAppHostPath', () => { assert.strictEqual(classifyAppHostPath('APPHOST.CSPROJ'), 'csharp'); assert.strictEqual(classifyAppHostPath('AppHost.TS'), 'typescript'); assert.strictEqual(classifyAppHostPath('AppHost.RS'), 'rust'); + assert.strictEqual(classifyAppHostPath('AppHost.GO'), 'go'); assert.strictEqual(classifyAppHostPath('/abs/path/AppHost.java'), 'java'); }); }); @@ -171,6 +187,19 @@ suite('appHostLanguage.classifyAppHostDirectory', () => { assert.strictEqual(await classifyAppHostDirectory(dir), 'rust'); }); + test('classifies directory containing an apphost.go as go', async () => { + const dir = makeTempDir(); + writeFileSync(join(dir, 'apphost.go'), 'package main'); + assert.strictEqual(await classifyAppHostDirectory(dir), 'go'); + }); + + test('does not classify an ordinary Go module without an AppHost as go', async () => { + const dir = makeTempDir(); + writeFileSync(join(dir, 'go.mod'), 'module example.com/app'); + writeFileSync(join(dir, 'main.go'), 'package main'); + assert.strictEqual(await classifyAppHostDirectory(dir), 'unknown'); + }); + test('classifies directory containing an AppHost.java as java', async () => { const dir = makeTempDir(); writeFileSync(join(dir, 'AppHost.java'), 'class AppHost {}'); diff --git a/extension/src/test/launchFailureStore.test.ts b/extension/src/test/launchFailureStore.test.ts index 3814903a351..358d00abc4f 100644 --- a/extension/src/test/launchFailureStore.test.ts +++ b/extension/src/test/launchFailureStore.test.ts @@ -8,6 +8,7 @@ import { resetLaunchFailureStore, LaunchFailureStore, getLaunchFailureMode, + getLaunchFailureProviderKindForAppHostPath, launchFailureCategories, launchFailureControllers, launchFailureExitCodeBuckets, @@ -310,6 +311,22 @@ suite('Editor assistance AppHost services', () => { } }); + test('derives the provider kind from the AppHost file language', () => { + const appHostPaths = [ + ['/workspace/AppHost/AppHost.csproj', 'dotnet'], + ['/workspace/AppHost/apphost.ts', 'node'], + ['/workspace/AppHost/AppHost.java', 'java'], + ['/workspace/AppHost/apphost.go', 'go'], + ['/workspace/AppHost/apphost.rs', 'rust'], + ['/workspace/AppHost/apphost.py', 'other'], + [undefined, 'other'], + ] as const; + + for (const [appHostPath, expected] of appHostPaths) { + assert.strictEqual(getLaunchFailureProviderKindForAppHostPath(appHostPath), expected, String(appHostPath)); + } + }); + test('prunes failures after the thirty minute window on reads', () => { let now = 1_000; const store = new LaunchFailureStore({ now: () => now }); diff --git a/extension/src/test/packageManifest.test.ts b/extension/src/test/packageManifest.test.ts index b7d62abb9d3..33d3c348c16 100644 --- a/extension/src/test/packageManifest.test.ts +++ b/extension/src/test/packageManifest.test.ts @@ -280,6 +280,13 @@ suite('extension/package.json', () => { assert.ok(activationEvents.includes('workspaceContains:**/apphost.rs')); }); + test('Go AppHost files activate the extension', () => { + const manifest = readManifest(); + const activationEvents = manifest.activationEvents ?? []; + + assert.ok(activationEvents.includes('workspaceContains:**/apphost.go')); + }); + // A Java-only workspace contains no project file the other activation events match: no .csproj, // and `.aspire/` only exists once a restore has already run. Without an explicit Java event the // extension never activates on a fresh clone, so the AppHost never appears in the Aspire view @@ -311,7 +318,7 @@ suite('extension/package.json', () => { 'aspire-vscode.runAppHostFromExplorer', 'aspire-vscode.debugAppHostFromExplorer', ]; - const expectedAppHostFiles = ['apphost.ts', 'apphost.mts', 'apphost.cts', 'apphost.js', 'apphost.mjs', 'apphost.cjs', 'apphost.rs', 'apphost.java']; + const expectedAppHostFiles = ['apphost.ts', 'apphost.mts', 'apphost.cts', 'apphost.js', 'apphost.mjs', 'apphost.cjs', 'apphost.rs', 'apphost.java', 'apphost.go']; assert.deepStrictEqual(explorerMenus.map(item => item.command), expectedExplorerCommands); assert.deepStrictEqual( diff --git a/extension/src/utils/appHostDiscovery.ts b/extension/src/utils/appHostDiscovery.ts index cbfe31db4a7..1605584b8a8 100644 --- a/extension/src/utils/appHostDiscovery.ts +++ b/extension/src/utils/appHostDiscovery.ts @@ -479,6 +479,7 @@ export class AppHostDiscoveryService implements vscode.Disposable { '**/apphost.mjs', '**/apphost.cjs', '**/apphost.rs', + '**/apphost.go', // Java requires the file name to match the public class name, so this is always // AppHost.java. Watcher globs are case-sensitive on Linux, so the pattern has to // carry the real casing rather than the lowercase form used by the other entries. diff --git a/extension/src/utils/appHostLanguage.ts b/extension/src/utils/appHostLanguage.ts index 8a4dba746a2..094226eacd8 100644 --- a/extension/src/utils/appHostLanguage.ts +++ b/extension/src/utils/appHostLanguage.ts @@ -12,13 +12,14 @@ import { CandidateAppHostDisplayInfo } from './appHostCandidateTypes'; * - `csharp` : every detected AppHost reports a C# variant. * - `typescript` : every detected AppHost reports a TypeScript / Node variant. * - `rust` : every detected AppHost reports Rust. + * - `go` : every detected AppHost reports Go. * - `polyglot` : more than one language family is present, * or an unknown language is mixed with a known one. This is * the headline signal Damian asked us to capture. * - `unknown` : we found AppHosts but couldn't classify any of them. * - `none` : no AppHosts were detected at all. */ -export type AppHostLanguage = 'csharp' | 'typescript' | 'rust' | 'java' | 'unknown'; +export type AppHostLanguage = 'csharp' | 'typescript' | 'rust' | 'java' | 'go' | 'unknown'; export type AppHostLanguageSummary = Exclude | 'polyglot' | 'unknown' | 'none'; export function formatAppHostLanguage(language: string): string | undefined { @@ -60,6 +61,9 @@ function languageFamily(raw: string | null | undefined): AppHostLanguage | 'othe if (value === 'java' || value.startsWith('java/')) { return 'java'; } + if (value === 'go' || value.startsWith('go/')) { + return 'go'; + } return 'other'; } @@ -72,6 +76,7 @@ export function summarizeAppHostLanguages(candidates: readonly CandidateAppHostD let sawTypescript = false; let sawRust = false; let sawJava = false; + let sawGo = false; let sawOther = false; for (const candidate of candidates) { @@ -88,12 +93,15 @@ export function summarizeAppHostLanguages(candidates: readonly CandidateAppHostD else if (family === 'java') { sawJava = true; } + else if (family === 'go') { + sawGo = true; + } else { sawOther = true; } } - const distinctFamilies = Number(sawCsharp) + Number(sawTypescript) + Number(sawRust) + Number(sawJava) + Number(sawOther); + const distinctFamilies = Number(sawCsharp) + Number(sawTypescript) + Number(sawRust) + Number(sawJava) + Number(sawGo) + Number(sawOther); if (distinctFamilies > 1) { return 'polyglot'; } @@ -109,6 +117,9 @@ export function summarizeAppHostLanguages(candidates: readonly CandidateAppHostD if (sawJava) { return 'java'; } + if (sawGo) { + return 'go'; + } return 'unknown'; } @@ -140,6 +151,9 @@ export function classifyAppHostPath(appHostPath: string | undefined): AppHostLan if (lower.endsWith('.java')) { return 'java'; } + if (lower.endsWith('.go')) { + return 'go'; + } return 'unknown'; } @@ -169,6 +183,7 @@ export async function classifyAppHostDirectory(directoryPath: string | undefined let sawTypescript = false; let sawRust = false; let sawJava = false; + let sawGo = false; for (const entry of entries) { if (await isCsharpAppHostMarker(directoryPath, entry)) { sawCsharp = true; @@ -182,6 +197,9 @@ export async function classifyAppHostDirectory(directoryPath: string | undefined else if (await isJavaAppHostMarker(directoryPath, entry)) { sawJava = true; } + else if (entry.toLowerCase() === 'apphost.go') { + sawGo = true; + } } if (sawCsharp && sawTypescript) { // Highly unusual; prefer csharp because Aspire's reference AppHost @@ -201,6 +219,9 @@ export async function classifyAppHostDirectory(directoryPath: string | undefined if (sawJava) { return 'java'; } + if (sawGo) { + return 'go'; + } return 'unknown'; } From 019cf870be217a8eeac399ff1f5cea143173bab8 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:35:33 -0500 Subject: [PATCH 03/10] Document Go AppHost debugging in the extension README Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extension/README.md b/extension/README.md index 16eab69d75f..48f9e5fe1f6 100644 --- a/extension/README.md +++ b/extension/README.md @@ -19,7 +19,7 @@ An **AppHost** defines your app in code: services, containers, databases, front ## A better inner dev loop - **Run your apps:** Start, debug, and stop an Aspire application, or use the available start, stop, and restart actions for individual resources, from the Aspire view. -- **Debug across your stack:** Aspire debug sessions support C#, JavaScript, Python, Go, Java, and Rust application resources when the corresponding debugger is available. Java and Rust debugging require Aspire 13.6 or later. +- **Debug across your stack:** Aspire debug sessions support C#, JavaScript, Python, Go, Java, and Rust application resources when the corresponding debugger is available. Java and Rust debugging require Aspire 13.6 or later. Go AppHosts (`apphost.go`) are debugged with the Go extension's Delve adapter when the Go extension is installed. - **See live health and analytics:** Open the Aspire dashboard for resource health, endpoints, console logs, structured logs, distributed traces, and metrics. - **Monitor without leaving VS Code:** See resource health summaries and quick actions beside resource definitions in your AppHost. - **Move toward production.** Deploy, publish artifacts, and run pipeline steps using the Aspire view. From 5c5c42629052d0a50aebeed5e68bb94ce3da2492 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:40:10 -0500 Subject: [PATCH 04/10] Advertise the Go AppHost extension launch capability Let aspire run hand a Go AppHost to the VS Code extension for debugging when the extension reports go-apphost.v1. Without the capability the CLI keeps starting go run . directly, so CLI-only runs and older extensions are unaffected. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- .../GoLanguageSupport.cs | 5 +++ .../GoLanguageSupportTests.cs | 32 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/Aspire.Hosting.CodeGeneration.Go.Tests/GoLanguageSupportTests.cs diff --git a/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs b/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs index 39ff4db2f06..13bae3877a2 100644 --- a/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs +++ b/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs @@ -137,6 +137,11 @@ public RuntimeSpec GetRuntimeSpec() CodeGenLanguage = CodeGenTarget, DetectionPatterns = s_detectionPatterns, InstallDependencies = null, + // Debugging the AppHost itself goes through the extension's Go debug adapter. The capability is + // versioned instead of the plain "go" because extension builds that can only debug Go resources + // already advertise "go"; routing apphost.go to them would hand it to the .NET debugger. The CLI + // only takes this path when the extension reports the capability, so a CLI-only run is unaffected. + ExtensionLaunchCapability = "go-apphost.v1", Execute = new CommandSpec { Command = "go", diff --git a/tests/Aspire.Hosting.CodeGeneration.Go.Tests/GoLanguageSupportTests.cs b/tests/Aspire.Hosting.CodeGeneration.Go.Tests/GoLanguageSupportTests.cs new file mode 100644 index 00000000000..34502208302 --- /dev/null +++ b/tests/Aspire.Hosting.CodeGeneration.Go.Tests/GoLanguageSupportTests.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Aspire.Hosting.CodeGeneration.Go.Tests; + +public class GoLanguageSupportTests +{ + private readonly GoLanguageSupport _languageSupport = new(); + + [Fact] + public void GetRuntimeSpec_UsesGoRun() + { + var runtimeSpec = _languageSupport.GetRuntimeSpec(); + + Assert.Equal("go", runtimeSpec.Language); + Assert.Equal("Go", runtimeSpec.DisplayName); + Assert.Equal("Go", runtimeSpec.CodeGenLanguage); + Assert.Equal(["apphost.go"], runtimeSpec.DetectionPatterns); + Assert.Equal("go", runtimeSpec.Execute.Command); + Assert.Equal(["run", "."], runtimeSpec.Execute.Args); + } + + [Fact] + public void GetRuntimeSpec_RequiresTheVersionedGoAppHostExtensionCapability() + { + var runtimeSpec = _languageSupport.GetRuntimeSpec(); + + // The plain "go" capability is advertised by extension builds that only debug Go resources, so + // gating AppHost launches on it would route apphost.go to a build that hands it to the .NET debugger. + Assert.Equal("go-apphost.v1", runtimeSpec.ExtensionLaunchCapability); + } +} From 1f107edbf23b129e35789a8e77de5c636c639adf Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:41:14 -0500 Subject: [PATCH 05/10] Cover Go AppHost command arguments that contain spaces Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/src/test/goDebugger.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extension/src/test/goDebugger.test.ts b/extension/src/test/goDebugger.test.ts index f4183ceb617..55ae2974319 100644 --- a/extension/src/test/goDebugger.test.ts +++ b/extension/src/test/goDebugger.test.ts @@ -137,6 +137,13 @@ suite('Go AppHost Command Parsing Tests', () => { assert.strictEqual(parseGoAppHostCommand(['go', 'run', './cmd/apphost'])?.packagePath, './cmd/apphost'); }); + test('does not re-split arguments that contain spaces', () => { + // The CLI has already tokenized the command line, so a value with a space is still one argument. + assert.deepStrictEqual( + parseGoAppHostCommand(['C:\\Program Files\\Go\\bin\\go.exe', 'run', '.', '--name', 'my app']), + { packagePath: '.', appHostArgs: ['--name', 'my app'] }); + }); + test('returns null when go run flags precede the package', () => { // The launch configuration has no place for them on this path, and the flag would otherwise be // taken as the program to debug. From 5fd76f542bcb1722f3434eb64763448782ba47cd Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:16:06 -0500 Subject: [PATCH 06/10] Route Go AppHost restarts through the ordered Aspire restart path Delve advertises supportsRestartRequest, so VS Code restarts a Go AppHost with a DAP restart request. That request only restarts the Go process and never reaches the ordered Aspire shutdown and relaunch, which is driven by disconnect with restart: true. The shared tracker now clears the capability in the initialize response of an owned Go AppHost session (AppHostTrackerOptions.disableDirectRestart), so the toolbar restart takes the disconnect route that onRestartRequested handles. Resource sessions and AppHosts in other languages keep the adapter's capabilities. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/src/debugger/AspireDebugSession.ts | 4 +- extension/src/debugger/adapterTracker.ts | 19 +++ extension/src/test/adapterTracker.test.ts | 132 +++++++++++++++++++ extension/src/test/goDebugger.test.ts | 23 ++++ 4 files changed, 177 insertions(+), 1 deletion(-) diff --git a/extension/src/debugger/AspireDebugSession.ts b/extension/src/debugger/AspireDebugSession.ts index 3bad544bcfa..e3e8f6a513f 100644 --- a/extension/src/debugger/AspireDebugSession.ts +++ b/extension/src/debugger/AspireDebugSession.ts @@ -1541,7 +1541,9 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche if (debugSessionId === this.debugSessionId) { this._appHostTerminationRequested = true; } - } + }, + // Delve advertises supportsRestartRequest, which would bypass onRestartRequested (see the tracker). + disableDirectRestart: isGoAppHost } ); diff --git a/extension/src/debugger/adapterTracker.ts b/extension/src/debugger/adapterTracker.ts index e577ee52684..60cdcfe370b 100644 --- a/extension/src/debugger/adapterTracker.ts +++ b/extension/src/debugger/adapterTracker.ts @@ -29,6 +29,9 @@ export interface AppHostTrackerOptions { onRestartRequested?: AppHostRestartHandler; onOutput?: AppHostOutputHandler; onTerminationRequested?: AppHostTerminationRequestHandler; + // Hides the adapter's `supportsRestartRequest` capability from VS Code for the AppHost session, so + // the toolbar restart arrives as disconnect with `restart: true` and reaches onRestartRequested. + disableDirectRestart?: boolean; } export function createDebugAdapterTracker(dcpServer: AspireDcpServer, debugAdapter: string, appHostTracker?: AppHostTrackerOptions): vscode.Disposable { @@ -74,6 +77,22 @@ export function createDebugAdapterTracker(dcpServer: AspireDcpServer, debugAdapt } }, onDidSendMessage: message => { + if (isOwnedAppHostSession + && appHostTracker?.disableDirectRestart + && message.type === 'response' + && message.command === 'initialize' + && message.body) { + // Delve advertises supportsRestartRequest. With that capability VS Code restarts + // the session with a DAP restart request instead of disconnect with + // restart: true, and only the disconnect reaches the ordered restart path in + // onWillReceiveMessage. The extension host passes this same message object on + // to VS Code after the tracker runs, so clearing the capability here makes the + // toolbar restart take the disconnect route. + // https://github.com/go-delve/delve/blob/master/service/dap/server.go + // https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/debug/browser/debugService.ts + message.body.supportsRestartRequest = false; + } + if (message.type === 'event' && message.event === 'process') { // A new debuggee process invalidates exit state captured from a prior run. // Reset before the DCP-session guard: AppHost child sessions do not have a diff --git a/extension/src/test/adapterTracker.test.ts b/extension/src/test/adapterTracker.test.ts index 091cc53b403..e6f49d11c55 100644 --- a/extension/src/test/adapterTracker.test.ts +++ b/extension/src/test/adapterTracker.test.ts @@ -41,6 +41,24 @@ suite('Debug Adapter Tracker Tests', () => { sinon.restore(); }); + function createAppHostSession(): vscode.DebugSession { + return { + ...debugSession, + configuration: { ...debugSession.configuration, isApphost: true } + }; + } + + function createInitializeResponse() { + return { + type: 'response', + seq: 2, + request_seq: 1, + success: true, + command: 'initialize', + body: { supportsConfigurationDoneRequest: true, supportsRestartRequest: true } + }; + } + test('exit code 0 is sent as 0', async () => { const disposable = createDebugAdapterTracker(dcpServer as any, 'coreclr'); const factory = registerFactoryStub.lastCall.args[1]; @@ -739,6 +757,120 @@ suite('Debug Adapter Tracker Tests', () => { unrelatedDisposable.dispose(); }); + test('apphost sessions that disable direct restart advertise no restart request support', () => { + const disposable = createDebugAdapterTracker(dcpServer as any, 'go', { + debugSessionId: 'debug-456', + disableDirectRestart: true + }); + const factory = registerFactoryStub.lastCall.args[1]; + const tracker = factory.createDebugAdapterTracker(createAppHostSession()); + const initializeResponse = createInitializeResponse(); + + tracker.onDidSendMessage(initializeResponse); + + assert.deepStrictEqual(initializeResponse.body, { + supportsConfigurationDoneRequest: true, + supportsRestartRequest: false + }); + + disposable.dispose(); + }); + + test('apphost sessions keep the adapter restart request support unless direct restart is disabled', () => { + const disposable = createDebugAdapterTracker(dcpServer as any, 'coreclr', { + debugSessionId: 'debug-456' + }); + const factory = registerFactoryStub.lastCall.args[1]; + const tracker = factory.createDebugAdapterTracker(createAppHostSession()); + const initializeResponse = createInitializeResponse(); + + tracker.onDidSendMessage(initializeResponse); + + assert.strictEqual(initializeResponse.body.supportsRestartRequest, true); + + disposable.dispose(); + }); + + test('apphost direct restart is only disabled for the tracker that owns its debug session', () => { + const owningDisposable = createDebugAdapterTracker(dcpServer as any, 'go', { + debugSessionId: 'debug-456', + disableDirectRestart: true + }); + const owningFactory = registerFactoryStub.lastCall.args[1]; + const unrelatedDisposable = createDebugAdapterTracker(dcpServer as any, 'go', { + debugSessionId: 'other-session', + disableDirectRestart: true + }); + const unrelatedFactory = registerFactoryStub.lastCall.args[1]; + const appHostSession = createAppHostSession(); + const unrelatedResponse = createInitializeResponse(); + const owningResponse = createInitializeResponse(); + + unrelatedFactory.createDebugAdapterTracker(appHostSession)?.onDidSendMessage(unrelatedResponse); + owningFactory.createDebugAdapterTracker(appHostSession).onDidSendMessage(owningResponse); + + assert.strictEqual(unrelatedResponse.body.supportsRestartRequest, true); + assert.strictEqual(owningResponse.body.supportsRestartRequest, false); + + owningDisposable.dispose(); + unrelatedDisposable.dispose(); + }); + + test('resource sessions keep the adapter restart request support when the apphost disables direct restart', () => { + // The tracker for an adapter type is shared by the AppHost and the resources that use the same + // adapter, and DCP tracks a resource restart through the adapter's process event. + const disposable = createDebugAdapterTracker(dcpServer as any, 'go', { + debugSessionId: 'debug-456', + disableDirectRestart: true + }); + const factory = registerFactoryStub.lastCall.args[1]; + const tracker = factory.createDebugAdapterTracker(debugSession); + const initializeResponse = createInitializeResponse(); + + tracker.onDidSendMessage(initializeResponse); + + assert.strictEqual(initializeResponse.body.supportsRestartRequest, true); + + disposable.dispose(); + }); + + test('apphost direct restart handling leaves every other message untouched', () => { + const restartRequested = sinon.stub().returns(true); + const disposable = createDebugAdapterTracker(dcpServer as any, 'go', { + debugSessionId: 'debug-456', + disableDirectRestart: true, + onRestartRequested: restartRequested + }); + const factory = registerFactoryStub.lastCall.args[1]; + const tracker = factory.createDebugAdapterTracker(createAppHostSession()); + const adapterMessages = [ + { type: 'response', seq: 3, request_seq: 2, success: true, command: 'launch', body: { supportsRestartRequest: true } }, + { type: 'response', seq: 4, request_seq: 1, success: false, command: 'initialize', message: 'adapter failed to start' }, + { type: 'event', seq: 5, event: 'initialized' }, + { type: 'event', seq: 6, event: 'process', body: { name: 'apphost', systemProcessId: 4242 } }, + { type: 'request', seq: 7, command: 'runInTerminal', arguments: { args: ['apphost'] } } + ]; + const clientRequests = [ + { type: 'request', seq: 1, command: 'initialize', arguments: { adapterID: 'go' } }, + { type: 'request', seq: 2, command: 'launch', arguments: { mode: 'debug' } } + ]; + + for (const message of adapterMessages) { + const expected = JSON.parse(JSON.stringify(message)); + tracker.onDidSendMessage(message); + assert.deepStrictEqual(message, expected); + } + + for (const request of clientRequests) { + const expected = JSON.parse(JSON.stringify(request)); + tracker.onWillReceiveMessage(request); + assert.deepStrictEqual(request, expected); + } + + sinon.assert.notCalled(restartRequested); + disposable.dispose(); + }); + test('apphost lifecycle events are not sent as DCP run-session notifications', async () => { const unrelatedDcpServer = sinon.createStubInstance(AspireDcpServer); const owningDisposable = createDebugAdapterTracker(dcpServer as any, 'coreclr', { diff --git a/extension/src/test/goDebugger.test.ts b/extension/src/test/goDebugger.test.ts index 55ae2974319..db115941cc4 100644 --- a/extension/src/test/goDebugger.test.ts +++ b/extension/src/test/goDebugger.test.ts @@ -328,6 +328,29 @@ suite('Go AppHost Launch Tests', () => { // restarted instead. assert.strictEqual(restartHandler(debugSession.debugSessionId), true); }); + + test('hides the Delve restart request capability so the toolbar restart reaches the tracker', async () => { + stubInstalledExtensions(['golang.go']); + const debugSession = createAppHostDebugSession(); + const trackerStub = sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + + await debugSession.startAppHost(appHostPath, ['go', 'run', '.'], [], true, { forceBuild: false }); + + sinon.assert.calledOnce(trackerStub); + assert.strictEqual(trackerStub.firstCall.args[1]?.disableDirectRestart, true); + }); + + test('keeps the restart request capability of an AppHost in another language', async () => { + const debugSession = createAppHostDebugSession({ program: '/workspace/apphost.ts' }); + const trackerStub = sinon.stub(debugSession, 'createDebugAdapterTrackerCore'); + sinon.stub(debugSession, 'startAndGetDebugSession').resolves(undefined); + + await debugSession.startAppHost('/workspace/apphost.ts', ['node', 'apphost.ts'], [], true, { forceBuild: false }); + + sinon.assert.calledOnce(trackerStub); + assert.ok(!trackerStub.firstCall.args[1]?.disableDirectRestart); + }); }); function stubInstalledExtensions(extensionIds: string[]): void { From ea008ceb4cfb23781230d17ffec990a88b57475a Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Tue, 20 Oct 2026 04:52:34 -0500 Subject: [PATCH 07/10] Stop the AppHost child that VS Code relaunches during a restart VS Code restarts a session whose adapter does not advertise supportsRestartRequest by terminating it and, about 300 ms later, relaunching the same session id with its old configuration (debugService.ts restartSession). The adapter tracker only clears the DAP restart flag of the outgoing request, so nothing in the Aspire parent stopped that relaunch, and the ordered shutdown skips an AppHost child that has already terminated. Make the termination handler idempotent per restarted child, so a repeat termination of the same id cannot start a second replacement session or retry the stop after an aborted restart. Watch for the relaunch for 10 s after a handled restart and stop a session that starts with the restarted child's id. The watch matches only that id, so the replacement AppHost is never affected, and it applies to every language that restarts through the tracker. Covered by extension-host unit tests that drive the event sequence by hand. Not verified in a live VS Code session with Delve. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/src/debugger/AspireDebugSession.ts | 59 ++++- extension/src/debugger/adapterTracker.ts | 8 +- extension/src/test/aspireDebugSession.test.ts | 214 ++++++++++++++++++ 3 files changed, 275 insertions(+), 6 deletions(-) diff --git a/extension/src/debugger/AspireDebugSession.ts b/extension/src/debugger/AspireDebugSession.ts index e3e8f6a513f..72f59f3da42 100644 --- a/extension/src/debugger/AspireDebugSession.ts +++ b/extension/src/debugger/AspireDebugSession.ts @@ -165,6 +165,14 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche * enough that a wedged CLI does not keep the AppHost alive indefinitely. */ private static readonly _cliCooperativeStopGraceMs = 10_000; + /** + * How long to watch for VS Code relaunching an AppHost child that terminated for a restart. VS Code + * schedules the relaunch about 300 ms after the termination, but the session start event is raised + * only once the launch request completes, which takes seconds when the adapter builds first (for + * example Delve building a Go AppHost). A relaunch that VS Code cancels never raises a start event, + * so the watch has to end on its own. + */ + private static readonly _relaunchedAppHostWatchMs = 10_000; private readonly _onDidSendMessage = new EventEmitter(); private readonly _onDidSendDebugConsoleOutput = new EventEmitter(); private _messageSeq = 1; @@ -1514,9 +1522,10 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche } // Register the adapter tracker with an app host restart handler. - // When the user clicks "restart" on the app host child session, - // we suppress VS Code's automatic child restart and restart the - // entire Aspire debug session instead. + // When the user clicks "restart" on the app host child session, the tracker clears the DAP + // `restart` flag of the request sent to the adapter so it shuts down completely, and we restart + // the entire Aspire debug session instead. VS Code relaunches the terminated child by itself, + // and stopRelaunchedAppHostSession stops that relaunch. // // The output filter is intentionally a positive opt-in for .NET AppHosts only. // The .NET debugger (`coreclr`) emits a lot of `console`-category chatter @@ -1532,7 +1541,7 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche onRestartRequested: () => { this._appHostRestartRequested = true; this.configuration[appHostRestartSourceSessionIdConfigKey] = this._session.id; - return true; // suppress VS Code's child restart + return true; // the whole Aspire session restarts, so the adapter must not prepare for a relaunch }, onOutput: isDotNetAppHost ? (output, category) => this.sendAppHostMessage(output, category) @@ -1642,8 +1651,17 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche this._appHostDebugSession = appHostDebugSession; this._trackAppHostDebugSession(this, projectFile, appHostDebugSession); + // VS Code can report the restarted child as terminated more than once, for example when the + // relaunch it scheduled is canceled or stopped. Only the first termination restarts the Aspire + // session. An aborted restart leaves this listener subscribed, so the guard also keeps a later + // termination from retrying the stop and starting a replacement after the abort. + let restartHandled = false; const disposable = vscode.debug.onDidTerminateDebugSession(async session => { if (this._appHostDebugSession && session.id === this._appHostDebugSession.id) { + if (restartHandled) { + return; + } + // Emit whatever was still being assembled before the banner, so a record the // AppHost logged on its way out is not lost and still reads in order. this.flushAppHostLogOutput(); @@ -1677,6 +1695,8 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche // they are stopped before the AppHost entry and the Aspire parent, and so a resource that // refuses to stop is reported rather than silently dropped by dispose(). if (shouldRestart) { + restartHandled = true; + this.stopRelaunchedAppHostSession(session); // The ordered shutdown finalizes this session before VS Code reuses its configuration // for the replacement. Keep the source ID long enough for the terminating parent to // suppress optimistic stopping without affecting the replacement session. @@ -1756,6 +1776,37 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche } } + /** + * Stops the copy of an AppHost child that VS Code relaunches by itself after the child terminated + * for a restart. + * + * The adapter tracker only clears the DAP `restart` flag of the request sent to the adapter. VS Code + * terminates the child, waits about 300 ms and relaunches the same session id with its old + * configuration. It cancels that launch only when the parent session has already ended: + * https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/debug/browser/debugService.ts + * https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/debug/browser/debugSession.ts + * Without this watch the relaunch would run with the previous configuration next to the replacement + * session, and the ordered shutdown would not stop it because that shutdown skips an AppHost that + * has already terminated. + * + * Only the restarted child's own id is matched, so the replacement AppHost, which gets a new id, is + * never affected. The watch is not tied to the disposables of this session because the ordered + * shutdown disposes those before the relaunch can arrive. + */ + private stopRelaunchedAppHostSession(restartedSession: vscode.DebugSession): void { + const watch = vscode.debug.onDidStartDebugSession(started => { + if (started.id !== restartedSession.id) { + return; + } + + clearTimeout(timer); + watch.dispose(); + extensionLogOutputChannel.info(`Stopping AppHost session ${started.name} that VS Code relaunched during a restart`); + stopSessionInBackground(() => vscode.debug.stopDebugging(started), `relaunched AppHost session ${started.name}`); + }); + const timer = setTimeout(() => watch.dispose(), AspireDebugSession._relaunchedAppHostWatchMs); + } + trackAlreadyStartedResourceSession(debugConfig: AspireResourceExtendedDebugConfiguration, resourceDebugSession: AlreadyStartedResourceDebugSession): AspireResourceDebugSession | undefined { // isShuttingDown rather than _disposed: an ordered shutdown snapshots the resource sessions // before its awaits, so a resource registered after that snapshot would only be stopped by the diff --git a/extension/src/debugger/adapterTracker.ts b/extension/src/debugger/adapterTracker.ts index 60cdcfe370b..70828ad48bb 100644 --- a/extension/src/debugger/adapterTracker.ts +++ b/extension/src/debugger/adapterTracker.ts @@ -7,7 +7,9 @@ import { dcpServerNotInitialized } from '../loc/strings'; /** * Callback invoked when a restart is requested on an app host debug session. - * Return `true` to suppress VS Code's automatic child session restart. + * Return `true` to clear the `restart` flag of the outgoing disconnect or terminate request, so the + * adapter shuts down completely. That does not cancel VS Code's relaunch of the terminated child, + * which the handler has to stop itself. */ export type AppHostRestartHandler = (debugSessionId: string) => boolean; export type AppHostTerminationRequestHandler = (debugSessionId: string) => void; @@ -87,7 +89,9 @@ export function createDebugAdapterTracker(dcpServer: AspireDcpServer, debugAdapt // restart: true, and only the disconnect reaches the ordered restart path in // onWillReceiveMessage. The extension host passes this same message object on // to VS Code after the tracker runs, so clearing the capability here makes the - // toolbar restart take the disconnect route. + // toolbar restart take the disconnect route. VS Code then terminates the child and + // relaunches it itself, which AspireDebugSession stops while it restarts the + // whole Aspire session. // https://github.com/go-delve/delve/blob/master/service/dap/server.go // https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/debug/browser/debugService.ts message.body.supportsRestartRequest = false; diff --git a/extension/src/test/aspireDebugSession.test.ts b/extension/src/test/aspireDebugSession.test.ts index f982c45eedc..d6f5faa9ddd 100644 --- a/extension/src/test/aspireDebugSession.test.ts +++ b/extension/src/test/aspireDebugSession.test.ts @@ -6013,6 +6013,220 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); sinon.assert.calledOnceWithExactly(terminateCliProcessTree, { force: true }); }); + suite('AppHost restart relaunch', () => { + const appHostDebugSession = { + id: 'apphost-session', + type: 'coreclr', + name: 'AppHost', + configuration: { + runId: 'apphost-run', + }, + } as unknown as vscode.DebugSession; + + // When the adapter does not handle a restart itself, VS Code terminates the child session and + // relaunches the same session id with its old configuration about 300 ms later. These tests drive + // the events of that sequence by hand. + async function startRestartableAppHost() { + let restartHandler: ((debugSessionId: string) => boolean) | undefined; + let terminateSessionCallback: ((session: vscode.DebugSession) => unknown) | undefined; + let startSessionCallback: ((session: vscode.DebugSession) => unknown) | undefined; + const disposeStartListener = sinon.stub(); + const parentDebugSession = { + id: 'aspire-session', + type: 'aspire', + name: 'Aspire', + workspaceFolder: undefined, + configuration: { + type: 'aspire', + request: 'launch', + name: 'Aspire', + program: '/workspace/apphost.cs', + command: 'run', + }, + customRequest: sinon.stub(), + getDebugProtocolBreakpoint: sinon.stub(), + }; + sinon.stub(debuggerExtensionsModule, 'createDebugSessionConfiguration').resolves({ + runId: 'apphost-run', + debugSessionId: 'debug-1', + type: 'coreclr', + name: 'AppHost', + request: 'launch', + }); + sinon.stub(vscode.debug, 'onDidTerminateDebugSession').callsFake(callback => { + terminateSessionCallback = callback; + return { dispose: sinon.stub() }; + }); + sinon.stub(vscode.debug, 'onDidStartDebugSession').callsFake(callback => { + startSessionCallback = callback; + return { dispose: disposeStartListener }; + }); + sinon.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); + const startReplacement = sinon.stub(vscode.debug, 'startDebugging').resolves(true); + const stopVsCodeSession = sinon.stub(vscode.debug, 'stopDebugging').resolves(); + const aspireDebugSession = new AspireDebugSession( + parentDebugSession as unknown as vscode.DebugSession, + {} as any, + {} as any, + { isDebugConfigEnvironmentLoggingEnabled: () => false } as any, + () => { }); + sinon.stub(aspireDebugSession, 'createDebugAdapterTrackerCore').callsFake((_debugAdapter, options) => { + restartHandler = options?.onRestartRequested; + }); + sinon.stub(aspireDebugSession, 'startAndGetDebugSession').resolves({ + id: appHostDebugSession.id, + session: appHostDebugSession, + stopSession: sinon.stub().resolves(), + }); + const orderedStop = sinon.stub(aspireDebugSession, 'stopDebugging').resolves(); + + await aspireDebugSession.startAppHost('/workspace/AppHost.csproj', ['run'], [], true, { forceBuild: false }); + // Installed after startup so only the timers created while handling the restart are fake. + const clock = sinon.useFakeTimers({ shouldClearNativeTimers: true }); + + return { + aspireDebugSession, + clock, + orderedStop, + startReplacement, + stopVsCodeSession, + disposeStartListener, + isWatchingForRelaunch: () => startSessionCallback !== undefined, + requestRestart: () => restartHandler?.(aspireDebugSession.debugSessionId), + terminateAppHost: () => terminateSessionCallback?.(appHostDebugSession), + startSession: (session: vscode.DebugSession) => startSessionCallback?.(session), + }; + } + + test('starts one replacement when the restarted child terminates again during the ordered shutdown', async () => { + const restart = await startRestartableAppHost(); + let finishShutdown!: () => void; + restart.orderedStop.returns(new Promise(resolve => { + finishShutdown = resolve; + })); + + assert.strictEqual(restart.requestRestart(), true); + const firstTermination = restart.terminateAppHost(); + // VS Code reports the child as terminated again when the relaunch it scheduled is canceled or stopped. + const repeatTermination = restart.terminateAppHost(); + finishShutdown(); + await Promise.all([firstTermination, repeatTermination]); + + sinon.assert.calledOnce(restart.orderedStop); + sinon.assert.calledOnce(restart.startReplacement); + assert.strictEqual(restart.startReplacement.firstCall.args[0], undefined); + }); + + test('starts one replacement when the restarted child terminates again after the restart was handled', async () => { + const restart = await startRestartableAppHost(); + + restart.requestRestart(); + await restart.terminateAppHost(); + await restart.terminateAppHost(); + + sinon.assert.calledOnce(restart.orderedStop); + sinon.assert.calledOnce(restart.startReplacement); + }); + + test('does not start a replacement when the restarted child terminates again after the restart was aborted', async () => { + const restart = await startRestartableAppHost(); + const cliStop = sinon.stub().resolves(); + (restart.aspireDebugSession as any)._rpcClient = { stopCli: cliStop }; + sinon.stub(restart.aspireDebugSession, 'terminateCliProcessTree').resolves(); + restart.orderedStop.rejects(new Error('Resource stop failed')); + + restart.requestRestart(); + await restart.terminateAppHost(); + // The aborted restart leaves the session subscribed so the stop can be retried. + await restart.terminateAppHost(); + + sinon.assert.calledOnce(restart.orderedStop); + sinon.assert.notCalled(restart.startReplacement); + }); + + test('stops the child that VS Code relaunches while the ordered shutdown is running', async () => { + const restart = await startRestartableAppHost(); + let finishShutdown!: () => void; + restart.orderedStop.returns(new Promise(resolve => { + finishShutdown = resolve; + })); + const relaunched = { ...appHostDebugSession } as vscode.DebugSession; + + restart.requestRestart(); + const termination = restart.terminateAppHost(); + restart.startSession(relaunched); + finishShutdown(); + await termination; + + sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); + sinon.assert.calledOnce(restart.disposeStartListener); + sinon.assert.calledOnce(restart.startReplacement); + }); + + test('stops the child that VS Code relaunches after the replacement session started', async () => { + const restart = await startRestartableAppHost(); + const relaunched = { ...appHostDebugSession } as vscode.DebugSession; + + restart.requestRestart(); + await restart.terminateAppHost(); + restart.startSession(relaunched); + + sinon.assert.calledOnce(restart.startReplacement); + sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); + sinon.assert.calledOnce(restart.disposeStartListener); + }); + + test('starts one replacement when a stopped relaunch reports its termination', async () => { + const restart = await startRestartableAppHost(); + const relaunched = { ...appHostDebugSession } as vscode.DebugSession; + + restart.requestRestart(); + await restart.terminateAppHost(); + restart.startSession(relaunched); + // Stopping the relaunched child ends the same session id that the restart began with. + await restart.terminateAppHost(); + + sinon.assert.calledOnce(restart.orderedStop); + sinon.assert.calledOnce(restart.startReplacement); + sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); + sinon.assert.calledOnce(restart.disposeStartListener); + }); + + test('does not stop other sessions that start while it waits for a relaunch', async () => { + const restart = await startRestartableAppHost(); + + restart.requestRestart(); + await restart.terminateAppHost(); + assert.strictEqual(restart.isWatchingForRelaunch(), true); + restart.startSession({ ...appHostDebugSession, id: 'replacement-apphost-session' } as vscode.DebugSession); + + sinon.assert.notCalled(restart.stopVsCodeSession); + sinon.assert.notCalled(restart.disposeStartListener); + }); + + test('stops waiting for a relaunch once the watch window passes', async () => { + const restart = await startRestartableAppHost(); + + restart.requestRestart(); + await restart.terminateAppHost(); + await restart.clock.tickAsync(9_999); + sinon.assert.notCalled(restart.disposeStartListener); + await restart.clock.tickAsync(1); + + sinon.assert.calledOnce(restart.disposeStartListener); + sinon.assert.notCalled(restart.stopVsCodeSession); + }); + + test('does not wait for a relaunch when the AppHost stops without a restart request', async () => { + const restart = await startRestartableAppHost(); + + await restart.terminateAppHost(); + + assert.strictEqual(restart.isWatchingForRelaunch(), false); + sinon.assert.notCalled(restart.startReplacement); + }); + }); + test('reports AppHost target version in end telemetry', async () => { const fake = new FakeTelemetryReporter(); const restoreReporter = __setReporterForTests(fake as unknown as TelemetryReporter); From e1bb4c11ae05238ff07361b9b73a1c9452c82559 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:26:51 -0500 Subject: [PATCH 08/10] Watch for the relaunched AppHost child until its relaunch ends The watch that stops the AppHost child VS Code relaunches during a restart ended after a fixed 10 s. VS Code raises the start event only after the adapter's launch request completes, which takes longer than that when the adapter builds first (Delve building a Go AppHost), so a relaunch that completed later escaped the watch and ran next to the replacement session. The watch now ends on what VS Code reports instead of elapsed time: a start event for the restarted child's id (the relaunch is stopped) or another termination of that id (the relaunch failed, was canceled or was stopped). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c8717a87-0ee5-4296-a6fd-ea6e2d91a57e --- extension/src/debugger/AspireDebugSession.ts | 45 ++++++----- extension/src/test/aspireDebugSession.test.ts | 79 +++++++++++++------ 2 files changed, 82 insertions(+), 42 deletions(-) diff --git a/extension/src/debugger/AspireDebugSession.ts b/extension/src/debugger/AspireDebugSession.ts index 72f59f3da42..c9d205a58d1 100644 --- a/extension/src/debugger/AspireDebugSession.ts +++ b/extension/src/debugger/AspireDebugSession.ts @@ -165,14 +165,6 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche * enough that a wedged CLI does not keep the AppHost alive indefinitely. */ private static readonly _cliCooperativeStopGraceMs = 10_000; - /** - * How long to watch for VS Code relaunching an AppHost child that terminated for a restart. VS Code - * schedules the relaunch about 300 ms after the termination, but the session start event is raised - * only once the launch request completes, which takes seconds when the adapter builds first (for - * example Delve building a Go AppHost). A relaunch that VS Code cancels never raises a start event, - * so the watch has to end on its own. - */ - private static readonly _relaunchedAppHostWatchMs = 10_000; private readonly _onDidSendMessage = new EventEmitter(); private readonly _onDidSendDebugConsoleOutput = new EventEmitter(); private _messageSeq = 1; @@ -1789,22 +1781,35 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche * session, and the ordered shutdown would not stop it because that shutdown skips an AppHost that * has already terminated. * + * VS Code raises the start event only once the relaunch's launch request has completed, which takes + * seconds when the adapter builds first (for example Delve building a Go AppHost), so no deadline + * can tell a slow relaunch from one that never arrives. The watch ends on what VS Code reports + * instead: a start event for the same id (the relaunch is stopped here), or another termination of + * that id (the relaunch failed, was canceled or was stopped, which VS Code reports as a further end + * of the session). A listener subscribed while an event is being raised does not receive that event, + * so the termination that started the watch does not end it. + * * Only the restarted child's own id is matched, so the replacement AppHost, which gets a new id, is - * never affected. The watch is not tied to the disposables of this session because the ordered - * shutdown disposes those before the relaunch can arrive. + * never affected. The watch subscribes to termination events itself, rather than relying on the + * session's listener, because the ordered shutdown disposes the session's disposables before the + * relaunch can arrive. */ private stopRelaunchedAppHostSession(restartedSession: vscode.DebugSession): void { - const watch = vscode.debug.onDidStartDebugSession(started => { - if (started.id !== restartedSession.id) { - return; - } + const watch = vscode.Disposable.from( + vscode.debug.onDidStartDebugSession(started => { + if (started.id !== restartedSession.id) { + return; + } - clearTimeout(timer); - watch.dispose(); - extensionLogOutputChannel.info(`Stopping AppHost session ${started.name} that VS Code relaunched during a restart`); - stopSessionInBackground(() => vscode.debug.stopDebugging(started), `relaunched AppHost session ${started.name}`); - }); - const timer = setTimeout(() => watch.dispose(), AspireDebugSession._relaunchedAppHostWatchMs); + watch.dispose(); + extensionLogOutputChannel.info(`Stopping AppHost session ${started.name} that VS Code relaunched during a restart`); + stopSessionInBackground(() => vscode.debug.stopDebugging(started), `relaunched AppHost session ${started.name}`); + }), + vscode.debug.onDidTerminateDebugSession(terminated => { + if (terminated.id === restartedSession.id) { + watch.dispose(); + } + })); } trackAlreadyStartedResourceSession(debugConfig: AspireResourceExtendedDebugConfiguration, resourceDebugSession: AlreadyStartedResourceDebugSession): AspireResourceDebugSession | undefined { diff --git a/extension/src/test/aspireDebugSession.test.ts b/extension/src/test/aspireDebugSession.test.ts index d6f5faa9ddd..e6ee28fb2c7 100644 --- a/extension/src/test/aspireDebugSession.test.ts +++ b/extension/src/test/aspireDebugSession.test.ts @@ -6028,8 +6028,24 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); // the events of that sequence by hand. async function startRestartableAppHost() { let restartHandler: ((debugSessionId: string) => boolean) | undefined; - let terminateSessionCallback: ((session: vscode.DebugSession) => unknown) | undefined; - let startSessionCallback: ((session: vscode.DebugSession) => unknown) | undefined; + // Like VS Code's emitters, a disposed listener receives no more events and an event reaches + // only the listeners that were subscribed when it was raised. + const terminateListeners: Array<(session: vscode.DebugSession) => unknown> = []; + const startListeners: Array<(session: vscode.DebugSession) => unknown> = []; + const subscribe = (listeners: Array<(session: vscode.DebugSession) => unknown>, listener: (session: vscode.DebugSession) => unknown, onDispose?: () => void) => { + listeners.push(listener); + return { + dispose: () => { + const index = listeners.indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + onDispose?.(); + } + }, + }; + }; + const raise = (listeners: Array<(session: vscode.DebugSession) => unknown>, session: vscode.DebugSession) => + Promise.all([...listeners].map(listener => listeners.includes(listener) ? listener(session) : undefined)); const disposeStartListener = sinon.stub(); const parentDebugSession = { id: 'aspire-session', @@ -6053,14 +6069,8 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); name: 'AppHost', request: 'launch', }); - sinon.stub(vscode.debug, 'onDidTerminateDebugSession').callsFake(callback => { - terminateSessionCallback = callback; - return { dispose: sinon.stub() }; - }); - sinon.stub(vscode.debug, 'onDidStartDebugSession').callsFake(callback => { - startSessionCallback = callback; - return { dispose: disposeStartListener }; - }); + sinon.stub(vscode.debug, 'onDidTerminateDebugSession').callsFake(callback => subscribe(terminateListeners, callback)); + sinon.stub(vscode.debug, 'onDidStartDebugSession').callsFake(callback => subscribe(startListeners, callback, disposeStartListener)); sinon.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); const startReplacement = sinon.stub(vscode.debug, 'startDebugging').resolves(true); const stopVsCodeSession = sinon.stub(vscode.debug, 'stopDebugging').resolves(); @@ -6081,6 +6091,8 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); const orderedStop = sinon.stub(aspireDebugSession, 'stopDebugging').resolves(); await aspireDebugSession.startAppHost('/workspace/AppHost.csproj', ['run'], [], true, { forceBuild: false }); + // The listener that startAppHost itself keeps; anything above it belongs to a relaunch watch. + const startupTerminateListenerCount = terminateListeners.length; // Installed after startup so only the timers created while handling the restart are fake. const clock = sinon.useFakeTimers({ shouldClearNativeTimers: true }); @@ -6091,10 +6103,11 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); startReplacement, stopVsCodeSession, disposeStartListener, - isWatchingForRelaunch: () => startSessionCallback !== undefined, + isWatchingForRelaunch: () => startListeners.length > 0 || terminateListeners.length > startupTerminateListenerCount, requestRestart: () => restartHandler?.(aspireDebugSession.debugSessionId), - terminateAppHost: () => terminateSessionCallback?.(appHostDebugSession), - startSession: (session: vscode.DebugSession) => startSessionCallback?.(session), + terminateSession: (session: vscode.DebugSession) => raise(terminateListeners, session), + terminateAppHost: () => raise(terminateListeners, appHostDebugSession), + startSession: (session: vscode.DebugSession) => raise(startListeners, session), }; } @@ -6154,7 +6167,7 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); restart.requestRestart(); const termination = restart.terminateAppHost(); - restart.startSession(relaunched); + await restart.startSession(relaunched); finishShutdown(); await termination; @@ -6169,7 +6182,7 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); restart.requestRestart(); await restart.terminateAppHost(); - restart.startSession(relaunched); + await restart.startSession(relaunched); sinon.assert.calledOnce(restart.startReplacement); sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); @@ -6182,7 +6195,7 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); restart.requestRestart(); await restart.terminateAppHost(); - restart.startSession(relaunched); + await restart.startSession(relaunched); // Stopping the relaunched child ends the same session id that the restart began with. await restart.terminateAppHost(); @@ -6192,29 +6205,51 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); sinon.assert.calledOnce(restart.disposeStartListener); }); - test('does not stop other sessions that start while it waits for a relaunch', async () => { + test('keeps waiting for a relaunch while other sessions start and terminate', async () => { const restart = await startRestartableAppHost(); + const otherSession = { ...appHostDebugSession, id: 'replacement-apphost-session' } as vscode.DebugSession; restart.requestRestart(); await restart.terminateAppHost(); assert.strictEqual(restart.isWatchingForRelaunch(), true); - restart.startSession({ ...appHostDebugSession, id: 'replacement-apphost-session' } as vscode.DebugSession); + await restart.startSession(otherSession); + await restart.terminateSession(otherSession); + assert.strictEqual(restart.isWatchingForRelaunch(), true); sinon.assert.notCalled(restart.stopVsCodeSession); sinon.assert.notCalled(restart.disposeStartListener); }); - test('stops waiting for a relaunch once the watch window passes', async () => { + test('stops the child that VS Code relaunches after a slow launch', async () => { const restart = await startRestartableAppHost(); + const relaunched = { ...appHostDebugSession } as vscode.DebugSession; restart.requestRestart(); await restart.terminateAppHost(); - await restart.clock.tickAsync(9_999); - sinon.assert.notCalled(restart.disposeStartListener); - await restart.clock.tickAsync(1); + // The adapter is still building, so VS Code has not raised the start event yet. + await restart.clock.tickAsync(60_000); + assert.strictEqual(restart.isWatchingForRelaunch(), true); + await restart.startSession(relaunched); + + sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); + sinon.assert.calledOnce(restart.disposeStartListener); + assert.strictEqual(restart.isWatchingForRelaunch(), false); + }); + + test('stops waiting for a relaunch that ends without starting', async () => { + const restart = await startRestartableAppHost(); + + restart.requestRestart(); + await restart.terminateAppHost(); + assert.strictEqual(restart.isWatchingForRelaunch(), true); + // A relaunch that fails or is canceled is reported as another termination of the same session id. + await restart.terminateAppHost(); + assert.strictEqual(restart.isWatchingForRelaunch(), false); + await restart.startSession({ ...appHostDebugSession } as vscode.DebugSession); sinon.assert.calledOnce(restart.disposeStartListener); sinon.assert.notCalled(restart.stopVsCodeSession); + sinon.assert.calledOnce(restart.startReplacement); }); test('does not wait for a relaunch when the AppHost stops without a restart request', async () => { From 7a68d6c892c601f8c9e787ff8c70c48a21b99d97 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:42:09 -0500 Subject: [PATCH 09/10] Scope AppHost start matching to the launching parent session Every AppHost child has the empty run ID, so the run ID alone cannot tell a replacement Aspire parent's own AppHost from the child that VS Code relaunches for the outgoing parent. When that relaunch started while the replacement waited for its AppHost (a slow Delve build), the replacement adopted it. The outgoing parent's relaunch watch then stopped that child, and the replacement took the termination for its AppHost exiting and shut itself down. AppHost starts now match on the launching parent's debugSessionId as well as the run ID, so the relaunch is left to the watch. Resource run IDs are unique, so resource starts are unchanged. Covered by a test that drives two parents with real empty AppHost run IDs through the stale child's start and termination before the replacement's own child starts. It fails without the change. Not verified in a live VS Code session with Delve. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6fc8b4b3-4ff4-421a-9a12-adb6fe10f7de --- extension/src/debugger/AspireDebugSession.ts | 14 +++- extension/src/test/aspireDebugSession.test.ts | 79 ++++++++++++++++++- 2 files changed, 87 insertions(+), 6 deletions(-) diff --git a/extension/src/debugger/AspireDebugSession.ts b/extension/src/debugger/AspireDebugSession.ts index c9d205a58d1..fb3162e67c7 100644 --- a/extension/src/debugger/AspireDebugSession.ts +++ b/extension/src/debugger/AspireDebugSession.ts @@ -1790,7 +1790,9 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche * so the termination that started the watch does not end it. * * Only the restarted child's own id is matched, so the replacement AppHost, which gets a new id, is - * never affected. The watch subscribes to termination events itself, rather than relying on the + * never affected. In turn, the replacement parent only adopts an AppHost child that carries its own + * debugSessionId (see startAndGetDebugSessionCore), so it cannot adopt the relaunched child that this + * watch stops. The watch subscribes to termination events itself, rather than relying on the * session's listener, because the ordered shutdown disposes the session's disposables before the * relaunch can arrive. */ @@ -1876,7 +1878,15 @@ export class AspireDebugSession implements vscode.DebugAdapter, DashboardLaunche let resolved = false; const disposable = vscode.debug.onDidStartDebugSession(session => { - if (session.configuration.runId === debugConfig.runId) { + // Every AppHost child has the empty run ID, so the run ID cannot tell this launch's child from the + // child that VS Code relaunches for the outgoing parent after a restart. That relaunch can start + // while the replacement parent waits for its own AppHost, and adopting it would make the old + // parent's relaunch watch stop what the replacement then takes for its AppHost exiting. Scoping + // the match to the launching parent's debugSessionId (stamped on every child configuration) + // leaves the stale child to the watch. Resource run IDs are unique, so they need no such scope. + const isOwnedByThisSession = debugConfig.isApphost !== true + || session.configuration.debugSessionId === debugConfig.debugSessionId; + if (session.configuration.runId === debugConfig.runId && isOwnedByThisSession) { extensionLogOutputChannel.info(`Debug session started: ${session.name} (run id: ${session.configuration.runId})`); disposable.dispose(); this.updateEditorResourceSessionState(debugConfig.runId, 'running'); diff --git a/extension/src/test/aspireDebugSession.test.ts b/extension/src/test/aspireDebugSession.test.ts index e6ee28fb2c7..3540f6adfe4 100644 --- a/extension/src/test/aspireDebugSession.test.ts +++ b/extension/src/test/aspireDebugSession.test.ts @@ -4734,6 +4734,7 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); name: 'AppHost', configuration: { runId: 'apphost-run', + debugSessionId: 'debug-1', }, }; const terminalProvider = { @@ -6062,13 +6063,16 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); customRequest: sinon.stub(), getDebugProtocolBreakpoint: sinon.stub(), }; - sinon.stub(debuggerExtensionsModule, 'createDebugSessionConfiguration').resolves({ - runId: 'apphost-run', - debugSessionId: 'debug-1', + // Copies the launch options like the real function does, so the AppHost child gets the empty + // run ID of a real AppHost and the id of the parent session that launched it. + sinon.stub(debuggerExtensionsModule, 'createDebugSessionConfiguration').callsFake(async (_configuration, _launchConfig, _args, _environment, launchOptions) => ({ + runId: launchOptions.runId, + debugSessionId: launchOptions.debugSessionId, + isApphost: launchOptions.isApphost, type: 'coreclr', name: 'AppHost', request: 'launch', - }); + })); sinon.stub(vscode.debug, 'onDidTerminateDebugSession').callsFake(callback => subscribe(terminateListeners, callback)); sinon.stub(vscode.debug, 'onDidStartDebugSession').callsFake(callback => subscribe(startListeners, callback, disposeStartListener)); sinon.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); @@ -6260,6 +6264,73 @@ var builder = Aspire.Hosting.DistributedApplication.CreateBuilder(args); assert.strictEqual(restart.isWatchingForRelaunch(), false); sinon.assert.notCalled(restart.startReplacement); }); + + test('does not take the child that VS Code relaunches for the outgoing parent as the replacement AppHost', async () => { + const restart = await startRestartableAppHost(); + const trackReplacementAppHost = sinon.spy(); + const replacement = new AspireDebugSession( + { + id: 'replacement-aspire-session', + type: 'aspire', + name: 'Aspire', + workspaceFolder: undefined, + configuration: { + type: 'aspire', + request: 'launch', + name: 'Aspire', + program: '/workspace/apphost.cs', + command: 'run', + }, + customRequest: sinon.stub(), + getDebugProtocolBreakpoint: sinon.stub(), + } as unknown as vscode.DebugSession, + {} as any, + {} as any, + { isDebugConfigEnvironmentLoggingEnabled: () => false } as any, + () => { }, + trackReplacementAppHost, + 'replacement-debug-session'); + sinon.stub(replacement, 'createDebugAdapterTrackerCore'); + // VS Code relaunches the restarted child with its old configuration, so the relaunch names the + // outgoing parent. Every AppHost child has the empty run ID, which does not tell the two apart. + const relaunched = { + id: appHostDebugSession.id, + type: 'coreclr', + name: 'AppHost', + configuration: { runId: '', debugSessionId: restart.aspireDebugSession.debugSessionId, isApphost: true }, + } as unknown as vscode.DebugSession; + const replacementChild = { + id: 'replacement-apphost-session', + type: 'coreclr', + name: 'AppHost', + configuration: { runId: '', debugSessionId: replacement.debugSessionId, isApphost: true }, + } as unknown as vscode.DebugSession; + + restart.requestRestart(); + await restart.terminateAppHost(); + const replacementStart = replacement.startAppHost('/workspace/AppHost.csproj', ['run'], [], true, { forceBuild: false }); + // Lets the replacement subscribe to start events and begin waiting for its own AppHost. + await restart.clock.tickAsync(0); + // A slow adapter (Delve building a Go AppHost) finishes the relaunch only now. + await restart.startSession(relaunched); + await restart.clock.tickAsync(0); + + sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); + sinon.assert.notCalled(trackReplacementAppHost); + + // Stopping the relaunch ends it. The replacement must not read that as its AppHost exiting. + await restart.terminateAppHost(); + await restart.clock.tickAsync(0); + assert.strictEqual(replacement.isShuttingDown, false); + + await restart.startSession(replacementChild); + await replacementStart; + + sinon.assert.calledOnce(trackReplacementAppHost); + assert.strictEqual(trackReplacementAppHost.firstCall.args[2].session, replacementChild); + assert.strictEqual(replacement.isShuttingDown, false); + sinon.assert.calledOnceWithExactly(restart.stopVsCodeSession, relaunched); + }); }); test('reports AppHost target version in end telemetry', async () => { From ac958468c24f43ad8b2192915d29518d880298e1 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:36:51 -0500 Subject: [PATCH 10/10] Accept go shim extensions and require a relative Go AppHost package The CLI resolves go through PATH/PATHEXT, so on Windows a version-manager shim can arrive as go.cmd or go.bat. parseGoAppHostCommand now strips .exe, .cmd and .bat before comparing the name, so F5 no longer fails with "The Go AppHost launch command was not recognized" while aspire run works. The executable is only name-checked, never launched, so accepting the shim is safe. The caller resolves the package against the AppHost directory, which is only valid for a relative directory. An import path such as example.com/apphost was forwarded and silently mis-resolved. The parser now returns null unless the package is ".", ".." or starts with either followed by a path separator. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6fc8b4b3-4ff4-421a-9a12-adb6fe10f7de --- extension/src/debugger/languages/go.ts | 17 ++++++++++------- extension/src/test/goDebugger.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/extension/src/debugger/languages/go.ts b/extension/src/debugger/languages/go.ts index 422c98efc9c..456789b593b 100644 --- a/extension/src/debugger/languages/go.ts +++ b/extension/src/debugger/languages/go.ts @@ -67,21 +67,24 @@ export const goDebuggerExtension: ResourceDebuggerExtension = { // dropped and only the package and the AppHost's own arguments are kept. The executable is checked // rather than launched: the adapter finds the toolchain through the Go extension's own settings. // -// Returns null for any other shape, including `go run` flags such as -tags or -race. A launch -// configuration has no place for them on this path, and forwarding one would hand a flag to the -// adapter as the program to debug. +// Returns null for any other shape, including `go run` flags such as -tags or -race and a package +// that is not a relative directory. A launch configuration has no place for flags on this path, and +// forwarding one would hand a flag to the adapter as the program to debug. export function parseGoAppHostCommand(args: string[]): { packagePath: string; appHostArgs: string[] } | null { if (args.length < 3) { return null; } - // Split on both separators so the name is found whichever path flavour the CLI reported. - const executable = args[0].split(/[\\/]/).pop()?.toLowerCase(); - if (executable !== 'go' && executable !== 'go.exe') { + // Split on both separators so the name is found whichever path flavour the CLI reported. The CLI + // resolves `go` through PATH/PATHEXT, so on Windows a version-manager shim can arrive as go.cmd or go.bat. + const executable = args[0].split(/[\\/]/).pop()?.toLowerCase().replace(/\.(exe|cmd|bat)$/, ''); + if (executable !== 'go') { return null; } - if (args[1] !== 'run' || args[2].startsWith('-')) { + // The caller resolves the package against the AppHost directory, which is only valid for a relative + // directory (".", "./cmd/apphost", "..\apphost"). An import path such as example.com/apphost is not one. + if (args[1] !== 'run' || !/^\.\.?([\\/]|$)/.test(args[2])) { return null; } diff --git a/extension/src/test/goDebugger.test.ts b/extension/src/test/goDebugger.test.ts index db115941cc4..99ac521fa79 100644 --- a/extension/src/test/goDebugger.test.ts +++ b/extension/src/test/goDebugger.test.ts @@ -126,6 +126,16 @@ suite('Go AppHost Command Parsing Tests', () => { { packagePath: '.', appHostArgs: [] }); }); + test('accepts the shim extensions a Windows version manager can resolve go to', () => { + // The CLI looks go up through PATH/PATHEXT, so the first match can be a .cmd or .bat shim. + for (const executable of ['C:\\Users\\dev\\shims\\go.cmd', 'C:\\Users\\dev\\shims\\GO.BAT']) { + assert.deepStrictEqual( + parseGoAppHostCommand([executable, 'run', '.']), + { packagePath: '.', appHostArgs: [] }, + executable); + } + }); + test('keeps every argument after the package for the AppHost', () => { // Anything after the package belongs to the program, including values that look like go flags. assert.deepStrictEqual( @@ -137,6 +147,12 @@ suite('Go AppHost Command Parsing Tests', () => { assert.strictEqual(parseGoAppHostCommand(['go', 'run', './cmd/apphost'])?.packagePath, './cmd/apphost'); }); + test('keeps a relative package directory written with either path separator', () => { + for (const packagePath of ['.\\cmd\\apphost', '../apphost', '..\\apphost', '..']) { + assert.strictEqual(parseGoAppHostCommand(['go', 'run', packagePath])?.packagePath, packagePath, packagePath); + } + }); + test('does not re-split arguments that contain spaces', () => { // The CLI has already tokenized the command line, so a value with a space is still one argument. assert.deepStrictEqual( @@ -151,6 +167,14 @@ suite('Go AppHost Command Parsing Tests', () => { assert.strictEqual(parseGoAppHostCommand(['go', 'run', '-race', '.']), null); }); + test('returns null when the package is not a relative directory', () => { + // The caller resolves the package against the AppHost directory, so an import path would silently + // become a directory under it. + assert.strictEqual(parseGoAppHostCommand(['go', 'run', 'example.com/apphost']), null); + assert.strictEqual(parseGoAppHostCommand(['go', 'run', 'cmd/apphost']), null); + assert.strictEqual(parseGoAppHostCommand(['go', 'run', '.hidden']), null); + }); + test('returns null when the command is not go run', () => { assert.strictEqual(parseGoAppHostCommand(['go', 'build', '.']), null); assert.strictEqual(parseGoAppHostCommand(['go', 'test', '.']), null); @@ -160,6 +184,8 @@ suite('Go AppHost Command Parsing Tests', () => { test('returns null when the executable is not the go toolchain', () => { assert.strictEqual(parseGoAppHostCommand(['dotnet', 'run', '.']), null); assert.strictEqual(parseGoAppHostCommand(['gofmt', 'run', '.']), null); + // The shim extensions are only forgiven for go itself. + assert.strictEqual(parseGoAppHostCommand(['C:\\tools\\air.cmd', 'run', '.']), null); // The name is read from the last path segment, not from a directory on the way to the executable. assert.strictEqual(parseGoAppHostCommand(['/usr/local/go/bin/air', 'run', '.']), null); });