diff --git a/extension/README.md b/extension/README.md index dac63bd750a..94c6334a3c4 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. - **Attach to running resources:** Attach to .NET and Go resources from the Aspire view. If a debugger extension is missing or disabled, open Extensions from the notification, install or enable it, and retry without restarting the AppHost. - **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. diff --git a/extension/loc/xlf/aspire-vscode.xlf b/extension/loc/xlf/aspire-vscode.xlf index 38788d08125..3bef477c47d 100644 --- a/extension/loc/xlf/aspire-vscode.xlf +++ b/extension/loc/xlf/aspire-vscode.xlf @@ -526,9 +526,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. @@ -1102,6 +1111,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.json b/extension/package.json index 54aec1a4de8..f9f9f640c23 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", @@ -869,12 +870,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/package.nls.json b/extension/package.nls.json index 05fae83d699..49a1d70391e 100644 --- a/extension/package.nls.json +++ b/extension/package.nls.json @@ -376,6 +376,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 d0aa2e8cbd3..94fcf582840 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"; @@ -1462,6 +1463,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; @@ -1481,6 +1483,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 @@ -1491,13 +1494,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 @@ -1514,19 +1527,25 @@ 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 - // 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 // (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, { @@ -1534,7 +1553,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) @@ -1543,7 +1562,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 } ); @@ -1589,6 +1610,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 "--". @@ -1631,8 +1663,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(); @@ -1666,6 +1707,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. @@ -1745,6 +1788,52 @@ 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. + * + * 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. 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. + */ + private stopRelaunchedAppHostSession(restartedSession: vscode.DebugSession): void { + const watch = vscode.Disposable.from( + vscode.debug.onDidStartDebugSession(started => { + if (started.id !== restartedSession.id) { + return; + } + + 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 { // 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 @@ -1818,7 +1907,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/debugger/adapterTracker.ts b/extension/src/debugger/adapterTracker.ts index 5f0fe6566c5..a45e8d3dcca 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; @@ -30,6 +32,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( @@ -80,6 +85,24 @@ export function createDebugAdapterTracker( } }, 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. 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; + } + 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/debugger/languages/go.ts b/extension/src/debugger/languages/go.ts index 14f9cc38c92..aa94be5d13f 100644 --- a/extension/src/debugger/languages/go.ts +++ b/extension/src/debugger/languages/go.ts @@ -76,6 +76,45 @@ export const goDebuggerExtension: ResourceDebuggerExtension = { } }; +// 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 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. 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; + } + + // 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; + } + + return { + packagePath: args[2], + appHostArgs: args.slice(3) + }; +} + export function createGoResourceAttachProvider(processResolver: GoApplicationProcessResolver): ResourceAttachProvider { return { id: 'go', diff --git a/extension/src/loc/strings.ts b/extension/src/loc/strings.ts index 9f00738cc95..b122bcaaac6 100644 --- a/extension/src/loc/strings.ts +++ b/extension/src/loc/strings.ts @@ -216,8 +216,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/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 47d48870f15..91f800ba0fa 100644 --- a/extension/src/test-e2e/packageSurface.e2e.test.ts +++ b/extension/src/test-e2e/packageSurface.e2e.test.ts @@ -584,6 +584,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/adapterTracker.test.ts b/extension/src/test/adapterTracker.test.ts index e19f88c98f3..6baf9aca485 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]; @@ -779,6 +797,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/appHostDiscovery.test.ts b/extension/src/test/appHostDiscovery.test.ts index 32708d823a0..dec60328c4b 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'); @@ -478,6 +491,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/aspireDebugSession.test.ts b/extension/src/test/aspireDebugSession.test.ts index 4a2d54b6f39..ce909f80744 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 = { @@ -6013,6 +6014,325 @@ 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; + // 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', + 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(), + }; + // 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); + 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 }); + // 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 }); + + return { + aspireDebugSession, + clock, + orderedStop, + startReplacement, + stopVsCodeSession, + disposeStartListener, + isWatchingForRelaunch: () => startListeners.length > 0 || terminateListeners.length > startupTerminateListenerCount, + requestRestart: () => restartHandler?.(aspireDebugSession.debugSessionId), + terminateSession: (session: vscode.DebugSession) => raise(terminateListeners, session), + terminateAppHost: () => raise(terminateListeners, appHostDebugSession), + startSession: (session: vscode.DebugSession) => raise(startListeners, 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(); + await 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(); + await 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(); + await 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('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); + 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 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(); + // 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 () => { + const restart = await startRestartableAppHost(); + + await restart.terminateAppHost(); + + 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 () => { const fake = new FakeTelemetryReporter(); const restoreReporter = __setReporterForTests(fake as unknown as TelemetryReporter); diff --git a/extension/src/test/goDebugger.test.ts b/extension/src/test/goDebugger.test.ts index 2f527ee4ecc..4bf61e6144c 100644 --- a/extension/src/test/goDebugger.test.ts +++ b/extension/src/test/goDebugger.test.ts @@ -1,13 +1,16 @@ 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 { createGoResourceAttachProvider, goDebuggerExtension, goResourceAttachProvider } from '../debugger/languages/go'; +import { createGoResourceAttachProvider, goDebuggerExtension, goResourceAttachProvider, parseGoAppHostCommand } from '../debugger/languages/go'; import { extensionResourceAttachProviders } from '../debugger/resourceAttachProviders'; import type { ResourceAttachProvider, ResourceDebugResourceSnapshot } from '../debugger/resourceDebugContracts'; -import { AspireResourceExtendedDebugConfiguration, GoLaunchConfiguration } from '../dcp/types'; +import { AspireExtendedDebugConfiguration, AspireResourceExtendedDebugConfiguration, EnvVar, GoLaunchConfiguration } from '../dcp/types'; +import { goAppHostCommandNotRecognized, goDebuggerExtensionNotInstalled } from '../loc/strings'; interface GoProcessResolver { resolveApplicationPid(parentPid: number, cancellationToken?: vscode.CancellationToken): Promise; @@ -154,9 +157,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', @@ -221,6 +237,288 @@ 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('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( + 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('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( + 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. + assert.strictEqual(parseGoAppHostCommand(['go', 'run', '-tags=dev', '.']), null); + 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); + 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 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); + }); + + 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); + }); + + 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 { + 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/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 3939c404a62..bc8e1561140 100644 --- a/extension/src/test/packageManifest.test.ts +++ b/extension/src/test/packageManifest.test.ts @@ -294,6 +294,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 @@ -325,7 +332,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/test/strings.test.ts b/extension/src/test/strings.test.ts index 437dd960d27..1a52c5bd100 100644 --- a/extension/src/test/strings.test.ts +++ b/extension/src/test/strings.test.ts @@ -275,6 +275,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; @@ -287,6 +309,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.'); }); }); diff --git a/extension/src/utils/appHostDiscovery.ts b/extension/src/utils/appHostDiscovery.ts index 13a0a3c96f6..83b36ccab8b 100644 --- a/extension/src/utils/appHostDiscovery.ts +++ b/extension/src/utils/appHostDiscovery.ts @@ -513,6 +513,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'; } diff --git a/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs b/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs index 7233e671f6f..045f644094f 100644 --- a/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs +++ b/src/Aspire.Hosting.CodeGeneration.Go/GoLanguageSupport.cs @@ -151,6 +151,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); + } +}