From f2b3a642def7cc876e2f8f58271870fcff26d00e Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Tue, 24 Nov 2026 08:16:48 +0000 Subject: [PATCH 1/4] feat: enable the extension in the VS Code Agents window --- CHANGELOG.md | 6 ++++ package.json | 3 ++ src/extension.ts | 4 ++- src/vscode/agentsWindow.ts | 18 ++++++++++++ test/unit/vscode/agentsWindow.test.ts | 42 +++++++++++++++++++++++++++ 5 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 src/vscode/agentsWindow.ts create mode 100644 test/unit/vscode/agentsWindow.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fa56f31662..277b5045ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ from published versions since it shows up in the VS Code extension changelog tab and is confusing to users. Add it back between releases if needed. --> +## Unreleased + +### Added + +- The extension is now enabled by default in the VS Code Agents window. + ## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03 ### Added diff --git a/package.json b/package.json index cc635265ee..634ae17feb 100644 --- a/package.json +++ b/package.json @@ -926,6 +926,9 @@ }, "icon": "media/logo.png", "capabilities": { + "agentsWindow": { + "supported": true + }, "untrustedWorkspaces": { "supported": true } diff --git a/src/extension.ts b/src/extension.ts index 3cef29c3d2..20bf1732c4 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -27,6 +27,7 @@ import { OAuthSessionManager } from "./oauth/sessionManager"; import { Remote } from "./remote/remote"; import { getRemoteSshExtension } from "./remote/sshExtension"; import { registerUriHandler } from "./uri/uriHandler"; +import { isAgentsWindow } from "./vscode/agentsWindow"; import { initVscodeProposed } from "./vscode/proposed"; import { TasksPanelProvider } from "./webviews/tasks/tasksPanelProvider"; import { WorkspaceActionRunner } from "./webviews/workspaces/workspaceActionRunner"; @@ -76,7 +77,8 @@ async function doActivate( path.join(remoteSshExtension.extensionPath, "package.json"), ); vscodeProposed = extensionRequire("vscode") as typeof vscode; - } else { + } else if (!isAgentsWindow()) { + // The Agents window disables Remote SSH, so its absence there is expected. vscode.window.showErrorMessage( "Remote SSH extension not found, this may not work as expected.\n" + // NB should we link to documentation or marketplace? diff --git a/src/vscode/agentsWindow.ts b/src/vscode/agentsWindow.ts new file mode 100644 index 0000000000..40603a1b56 --- /dev/null +++ b/src/vscode/agentsWindow.ts @@ -0,0 +1,18 @@ +import * as path from "node:path"; +import * as vscode from "vscode"; + +/** + * VS Code opens this workspace in the Agents window and marks a window as the + * Agents window by this path. `workspace.isAgentSessionsWorkspace` exposes the + * same flag but is a proposed API, so extensions cannot read it on Stable. + */ +const AGENTS_WINDOW_WORKSPACE_FILE = "agent-sessions.code-workspace"; + +/** Whether this extension host runs in VS Code's Agents window. */ +export function isAgentsWindow(): boolean { + const workspaceFile = vscode.workspace.workspaceFile; + return ( + workspaceFile?.scheme === "file" && + path.posix.basename(workspaceFile.path) === AGENTS_WINDOW_WORKSPACE_FILE + ); +} diff --git a/test/unit/vscode/agentsWindow.test.ts b/test/unit/vscode/agentsWindow.test.ts new file mode 100644 index 0000000000..a7f92a21f2 --- /dev/null +++ b/test/unit/vscode/agentsWindow.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, it } from "vitest"; +import * as vscode from "vscode"; + +import { isAgentsWindow } from "@/vscode/agentsWindow"; + +const mockWorkspace = vscode.workspace as typeof vscode.workspace & { + workspaceFile: vscode.Uri | undefined; +}; + +describe("isAgentsWindow", () => { + afterEach(() => { + mockWorkspace.workspaceFile = undefined; + }); + + it.each([ + ["/home/me/.config/Code/User/agent-sessions.code-workspace"], + [ + "/c:/Users/me/AppData/Roaming/Code - Insiders/User/agent-sessions.code-workspace", + ], + ])("detects the Agents window workspace at %s", (path) => { + mockWorkspace.workspaceFile = vscode.Uri.file(path); + expect(isAgentsWindow()).toBe(true); + }); + + it.each([ + ["no workspace file", undefined], + [ + "another workspace", + vscode.Uri.file("/home/me/project/app.code-workspace"), + ], + [ + "a remote file with the same name", + vscode.Uri.from({ + scheme: "vscode-remote", + path: "/home/me/agent-sessions.code-workspace", + }), + ], + ])("is false for %s", (_label, workspaceFile) => { + mockWorkspace.workspaceFile = workspaceFile; + expect(isAgentsWindow()).toBe(false); + }); +}); From a47d4e6d8051fbbf29269629e093fb04b2dc62a0 Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Tue, 24 Nov 2026 11:19:13 +0000 Subject: [PATCH 2/4] refactor(remote): extract window-independent connection setup from Remote Move CLI resolution, compatibility checks, workspace readiness and SSH config writing into ConnectionSetup so a window without Remote-SSH can reuse them. The SSH config file and ssh path are now passed in by the caller. --- src/extension.ts | 7 +- src/remote/connectionSetup.ts | 443 +++++++++++++++++++++++ src/remote/remote.ts | 425 +--------------------- test/unit/remote/connectionSetup.test.ts | 427 ++++++++++++++++++++++ test/unit/remote/remote.test.ts | 377 +------------------ 5 files changed, 895 insertions(+), 784 deletions(-) create mode 100644 src/remote/connectionSetup.ts create mode 100644 test/unit/remote/connectionSetup.test.ts diff --git a/src/extension.ts b/src/extension.ts index 20bf1732c4..a62cf69ea1 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -24,6 +24,7 @@ import { type ActivationTracer, } from "./instrumentation/activation"; import { OAuthSessionManager } from "./oauth/sessionManager"; +import { ConnectionSetup } from "./remote/connectionSetup"; import { Remote } from "./remote/remote"; import { getRemoteSshExtension } from "./remote/sshExtension"; import { registerUriHandler } from "./uri/uriHandler"; @@ -206,6 +207,10 @@ async function doActivate( // Register globally available commands. Many of these have visibility // controlled by contexts, see `when` in the package.json. + const connectionSetup = new ConnectionSetup( + serviceContainer, + ctx.extensionMode, + ); const commands = new Commands(serviceContainer, client, deploymentManager); // Placeholder tree view for the coderTasks container when not authenticated. @@ -432,7 +437,7 @@ async function doActivate( commands.supportBundle.bind(commands), ); - const remote = new Remote(serviceContainer, commands, ctx); + const remote = new Remote(serviceContainer, commands, ctx, connectionSetup); // Respond to PINGs and DUPLICATE commands from other windows. const duplicateWorkspaceIpc = serviceContainer.getDuplicateWorkspaceIpc(); diff --git a/src/remote/connectionSetup.ts b/src/remote/connectionSetup.ts new file mode 100644 index 0000000000..d9077ac46d --- /dev/null +++ b/src/remote/connectionSetup.ts @@ -0,0 +1,443 @@ +import { isAxiosError } from "axios"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import * as semver from "semver"; +import * as vscode from "vscode"; + +import { HttpStatusCode } from "../api/httpStatusCode"; +import { version as cliVersion } from "../cli/cliExec"; +import { + escapeCommandArg, + escapeNotificationLinks, + escapeProxyCommandPath, + lowercase, +} from "../common/strings"; +import { raceWithAbort } from "../error/abort"; +import { toError } from "../error/normalize"; +import { + cliFeatureSet, + serverFeatureSet, + type ServerFeatureSet, +} from "../featureSet"; +import { + type CliAuth, + getGlobalShellFlags, + getSshFlags, + resolveCliAuth, +} from "../settings/cli"; +import { vscodeProposed } from "../vscode/proposed"; + +import { type AuthorityParts, hostEditorId } from "./authority"; +import { SESSION_TYPE_ENV } from "./environment"; +import { + getGitForWindowsSshConfigPath, + getSshHomeDir, + includeCoderSshConfig, + type SshValues, + mergeSshConfigValues, + parseCoderSshOptions, + parseSshConfig, + readSshConfig, + validateDeploymentSshOptions, + writeCoderSshConfig, +} from "./sshConfig"; +import { + computeSshProperties, + resolveSshProperties, + SshProxyCommandMissingError, + type SshProperties, +} from "./sshSupport"; +import { createManagedPermissions } from "./windowsAcl"; + +import type { Api } from "coder/site/src/api/api"; +import type { Workspace } from "coder/site/src/api/typesGenerated"; + +import type { CliManager } from "../cli/cliManager"; +import type { ServiceContainer } from "../container"; +import type { Logger } from "../logging/logger"; +import type { MementoManager } from "../storage/mementoManager"; +import type { PathResolver } from "../storage/pathResolver"; +import type { WorkspaceMonitor } from "../workspace/workspaceMonitor"; + +import type { WorkspaceStateMachine } from "./workspaceStateMachine"; + +/** Git's home may be an unreachable share; don't stall the connect on it. */ +const GIT_SSH_CONFIG_TIMEOUT_MS = 5_000; + +export interface Compatibility { + serverFeatures: ServerFeatureSet; + cliAuth: CliAuth; + sessionApp: string; +} + +export interface SshConfigOptions { + workspaceClient: Api; + parts: AuthorityParts; + binaryPath: string; + logDir: string; + cliAuth: CliAuth; + sessionApp: string; + /** Passed to ssh as `-F`; undefined uses `~/.ssh/config`. */ + configFile: string | undefined; + /** The ssh binary that resolves the host; undefined uses `ssh` on PATH. */ + sshPath: string | undefined; +} + +/** + * Steps that prepare a workspace for an SSH connection, independent of the + * window that connects: CLI resolution, compatibility, readiness and the SSH + * config. + */ +export class ConnectionSetup { + private readonly logger: Logger; + private readonly pathResolver: PathResolver; + private readonly cliManager: CliManager; + private readonly mementoManager: MementoManager; + + public constructor( + serviceContainer: ServiceContainer, + private readonly extensionMode: vscode.ExtensionMode, + ) { + this.logger = serviceContainer.getLogger(); + this.pathResolver = serviceContainer.getPathResolver(); + this.cliManager = serviceContainer.getCliManager(); + this.mementoManager = serviceContainer.getMementoManager(); + } + + public async resolveBinary(workspaceClient: Api): Promise { + if (this.extensionMode === vscode.ExtensionMode.Production) { + return this.cliManager.fetchBinary(workspaceClient); + } + // Dev override: use a custom binary at /tmp/coder if it exists. + try { + const binaryPath = path.join(os.tmpdir(), "coder"); + await fs.stat(binaryPath); + return binaryPath; + } catch { + return this.cliManager.fetchBinary(workspaceClient); + } + } + + /** + * Resolve server and CLI capabilities independently, disabling optional CLI + * features when its version can't be read. + */ + public async checkCompatibility(options: { + workspaceClient: Api; + binaryPath: string; + baseUrl: string; + safeHostname: string; + }): Promise { + const { workspaceClient, binaryPath, baseUrl, safeHostname } = options; + const buildInfo = await workspaceClient.getBuildInfo(); + const serverVersion = semver.parse(buildInfo.version); + + let parsedCliVersion: semver.SemVer | null; + try { + parsedCliVersion = semver.parse(await cliVersion(binaryPath)); + } catch { + parsedCliVersion = null; + } + const cliFeatures = cliFeatureSet(parsedCliVersion); + const serverFeatures = serverFeatureSet(serverVersion); + // Report schemes verbatim; normalization and editor families belong to the server. + const sessionApp = + cliFeatures.customSessionAppNames && serverFeatures.customSessionAppNames + ? vscode.env.uriScheme || "vscode" + : "vscode"; + const configDir = this.pathResolver.getGlobalConfigDir(safeHostname); + const cliAuth = resolveCliAuth( + vscode.workspace.getConfiguration(), + cliFeatures, + baseUrl, + configDir, + ); + return { + serverFeatures, + cliAuth, + sessionApp, + }; + } + + public async waitForWorkspaceReady( + workspace: Workspace, + monitor: WorkspaceMonitor, + stateMachine: WorkspaceStateMachine, + ): Promise { + return vscodeProposed.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + cancellable: false, + title: "Connecting to workspace", + }, + async (progress) => { + let inProgress = false; + let pendingWorkspace: Workspace | null = null; + + return new Promise((resolve, reject) => { + const processWorkspace = async (w: Workspace) => { + if (inProgress) { + // Process one workspace at a time, keeping only the last + pendingWorkspace = w; + return; + } + + inProgress = true; + try { + pendingWorkspace = null; + + const isReady = await stateMachine.processWorkspace(w, progress); + if (isReady) { + subscription.dispose(); + resolve(stateMachine.getWorkspace() ?? w); + return; + } + } catch (error: unknown) { + subscription.dispose(); + reject(toError(error)); + return; + } finally { + inProgress = false; + } + + if (pendingWorkspace) { + void processWorkspace(pendingWorkspace); + } + }; + + void processWorkspace(workspace); + const subscription = monitor.onChange.event((w) => { + void processWorkspace(w); + }); + }); + }, + ); + } + + public async writeSshConfig( + options: SshConfigOptions, + ): Promise { + try { + this.logger.info("Updating SSH config..."); + return await this.updateSSHConfig(options); + } catch (error) { + this.logger.warn("Failed to configure SSH", error); + throw error; + } + } + + /** + * Returns the --log-dir argument for the ProxyCommand after making sure it + * has been created. + */ + private async getLogArgs(logDir: string): Promise { + await fs.mkdir(logDir, { recursive: true }); + this.logger.info("SSH proxy diagnostics are being written to", logDir); + return ["--log-dir", escapeProxyCommandPath(logDir), "-v"]; + } + + // updateSSHConfig updates the SSH configuration with a wildcard that handles + // all Coder entries. + private async updateSSHConfig({ + workspaceClient, + parts, + binaryPath, + logDir, + cliAuth, + sessionApp, + configFile, + sshPath, + }: SshConfigOptions): Promise { + // Taken from the authority, so a legacy host keeps working. + const { hostPrefix, safeHostname, sshHost } = parts; + // The user's config gains one shared include. + const userConfigPath = + configFile ?? path.join(getSshHomeDir(), ".ssh", "config"); + // The CLI writes its block to the user's config, so read it from there. + const configSshOptions = parseCoderSshOptions( + await readSshConfig(userConfigPath), + ); + + const userConfigSsh = vscode.workspace + .getConfiguration("coder") + .get("sshConfig", []); + const userConfig = parseSshConfig(userConfigSsh); + + let deploymentSshConfig = {}; + try { + const deploymentConfig = await workspaceClient.getDeploymentSSHConfig(); + const { options, ignored } = validateDeploymentSshOptions( + deploymentConfig.ssh_config_options, + ); + deploymentSshConfig = options; + if (ignored.length > 0) { + this.logger.warn("Ignoring deployment SSH options", ignored); + this.warnIgnoredSshOptions(safeHostname, ignored); + } + } catch (error) { + if (!isAxiosError(error)) { + throw error; + } + switch (error.response?.status) { + case HttpStatusCode.NOT_FOUND: { + // Deployment does not support overriding ssh config yet. Likely an + // older version, just use the default. + break; + } + default: + throw error; + } + } + + const pinnedSshValues = { + ProxyCommand: buildSshProxyCommand({ + pathResolver: this.pathResolver, + binaryPath, + cliAuth, + logArgs: await this.getLogArgs(logDir), + sessionApp, + hostPrefix, + }), + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + PermitLocalCommand: "no", + }; + + // Merge SSH config from three sources (highest to lowest priority): + // 1. User's VS Code coder.sshConfig setting + // 2. coder config-ssh --ssh-option flags from the CLI block + // 3. Deployment SSH config from the coderd API, with the pinned values over it + // Only 3 is allow listed; 1 and 2 are the user's own options. + const sshConfigOverrides = mergeSshConfigValues( + mergeSshConfigValues( + mergeSshConfigValues(deploymentSshConfig, pinnedSshValues), + configSshOptions, + ), + userConfig, + ); + + const sshValues: SshValues = { + Host: hostPrefix + `*`, + ...pinnedSshValues, + ConnectTimeout: "0", + LogLevel: "ERROR", + ServerAliveInterval: "10", + ServerAliveCountMax: "3", + SendEnv: SESSION_TYPE_ENV, + }; + + // One file per (host prefix, deployment). Write it before including it, + // so the include never dangles. + const coderConfigText = await writeCoderSshConfig( + { + path: this.pathResolver.getSshConfigPath( + safeHostname, + hostEditorId(sshHost), + ), + permissions: createManagedPermissions(), + }, + { values: sshValues, overrides: sshConfigOverrides }, + this.logger, + ); + const include = { dir: this.pathResolver.getSshConfigDir(), safeHostname }; + const userConfigText = await includeCoderSshConfig( + userConfigPath, + include, + this.logger, + ); + // Without -F, Git for Windows ssh reads its own home's config. When that + // is the profile's config, the include is already there: no write. + const gitConfigPath = getGitForWindowsSshConfigPath(); + if (!configFile && gitConfigPath) { + try { + await raceWithAbort( + includeCoderSshConfig(gitConfigPath, include, this.logger), + AbortSignal.timeout(GIT_SSH_CONFIG_TIMEOUT_MS), + ); + } catch (error) { + this.logger.warn( + `Failed to include the Coder SSH config in ${gitConfigPath}, so Git for Windows ssh will not find Coder hosts`, + error, + ); + } + } + + try { + return await resolveSshProperties(sshPath, parts.sshHost, configFile); + } catch (error) { + if (error instanceof SshProxyCommandMissingError) { + this.warnCoderSshConfigNotRead(include.dir, error.configFiles); + } + this.logger.warn("ssh -G failed, parsing the SSH config instead", error); + return computeSshProperties( + parts.sshHost, + `${coderConfigText}\n${userConfigText}`, + ); + } + } + + /** Remote-SSH's ssh ran but missed the include, so the connection will fail. */ + private warnCoderSshConfigNotRead( + includeDir: string, + configFiles: string[], + ): void { + const read = configFiles.join(", ") || "no SSH config"; + void vscode.window.showWarningMessage( + escapeNotificationLinks( + `Remote-SSH's ssh did not read the Coder SSH config in ${includeDir}, so it cannot reach Coder workspaces. It read ${read}. Check which ssh Remote-SSH uses and its home directory.`, + ), + ); + } + + /** Stays hidden while every ignored option was already dismissed. */ + private warnIgnoredSshOptions(safeHostname: string, ignored: string[]): void { + const memento = this.mementoManager; + const dismissed = new Set(memento.getDismissedSshOptions(safeHostname)); + const keys = ignored.map(lowercase); + if (keys.every((key) => dismissed.has(key))) { + return; + } + const dontShow = "Don't Show Again"; + void vscode.window + .showWarningMessage( + `Ignored SSH options from the Coder deployment that could expose your machine: ${ignored.join(", ")}. To use them, add them to the "coder.sshConfig" setting.`, + dontShow, + ) + .then((choice) => + choice === dontShow + ? memento.addDismissedSshOptions(safeHostname, keys) + : undefined, + ); + } +} + +interface ProxyCommandOptions { + pathResolver: PathResolver; + binaryPath: string; + cliAuth: CliAuth; + logArgs: string[]; + sessionApp: string; + hostPrefix: string; +} + +/** SSH ProxyCommand using wildcard workspace hosts. */ +export function buildSshProxyCommand(options: ProxyCommandOptions): string { + // Make sure to update the `coder.sshFlags` description if we add more internal flags here! + const internalFlags = [ + "--stdio", + `--usage-app=${escapeCommandArg(options.sessionApp)}`, + "--network-info-dir", + escapeProxyCommandPath(options.pathResolver.getNetworkInfoPath()), + ...options.logArgs, + "--ssh-host-prefix", + options.hostPrefix, + "%h", + ]; + // User SSH flags are included first; internally-managed flags + // are appended last so they take precedence. + const configs = vscode.workspace.getConfiguration(); + const userSshFlags = getSshFlags(configs); + const globalFlags = getGlobalShellFlags(configs, options.cliAuth); + return `${escapeProxyCommandPath(options.binaryPath)} ${globalFlags.join(" ")} ssh ${[...userSshFlags, ...internalFlags].join(" ")}`; +} diff --git a/src/remote/remote.ts b/src/remote/remote.ts index 685684f905..90b9ead9af 100644 --- a/src/remote/remote.ts +++ b/src/remote/remote.ts @@ -1,8 +1,4 @@ import { isAxiosError } from "axios"; -import * as fs from "node:fs/promises"; -import * as os from "node:os"; -import * as path from "node:path"; -import * as semver from "semver"; import * as vscode from "vscode"; import { @@ -15,24 +11,12 @@ import { AuthInterceptor } from "../api/authInterceptor"; import { CoderApi } from "../api/coderApi"; import { HttpStatusCode } from "../api/httpStatusCode"; import { extractAgents } from "../api/models"; -import { version as cliVersion } from "../cli/cliExec"; -import { - escapeCommandArg, - escapeNotificationLinks, - escapeProxyCommandPath, - lowercase, -} from "../common/strings"; import { CONFIG_CHANGE_DEBOUNCE_MS, watchConfigurationChanges, } from "../configWatcher"; import { raceWithAbort, throwIfAborted } from "../error/abort"; import { toError } from "../error/normalize"; -import { - cliFeatureSet, - serverFeatureSet, - type ServerFeatureSet, -} from "../featureSet"; import { Inbox } from "../inbox"; import { AuthTelemetry } from "../instrumentation/auth"; import { @@ -40,13 +24,7 @@ import { type RemoteSetupTracer, } from "../instrumentation/remoteSetup"; import { OAuthSessionManager } from "../oauth/sessionManager"; -import { - type CliAuth, - getExpandedUserGlobalFlags, - getGlobalShellFlags, - getSshFlags, - resolveCliAuth, -} from "../settings/cli"; +import { getExpandedUserGlobalFlags, getSshFlags } from "../settings/cli"; import { getHeaderCommand } from "../settings/headers"; import { createStatusBarItem } from "../ui/statusBar"; import { vscodeProposed } from "../vscode/proposed"; @@ -55,42 +33,17 @@ import { WorkspaceMonitor } from "../workspace/workspaceMonitor"; import { type AuthorityParts, classifySshHost, - hostEditorId, parseRemoteAuthority, sshHostOf, } from "./authority"; -import { - applySshEnvironment, - SESSION_TYPE_ENV, - SSH_PROXY_SETTINGS, -} from "./environment"; +import { applySshEnvironment, SSH_PROXY_SETTINGS } from "./environment"; import { labelFormatterAuthority } from "./labelFormatter"; import { migrateAuthToSecretsStorage } from "./migration"; -import { - getGitForWindowsSshConfigPath, - getSshHomeDir, - includeCoderSshConfig, - type SshValues, - mergeSshConfigValues, - parseCoderSshOptions, - parseSshConfig, - readSshConfig, - validateDeploymentSshOptions, - writeCoderSshConfig, -} from "./sshConfig"; import { getRemoteSshConfigFile, getRemoteSshPath } from "./sshExtension"; import { applySettingOverrides, buildSshOverrides } from "./sshOverrides"; import { SshProcessMonitor } from "./sshProcess"; -import { - computeSshProperties, - resolveSshProperties, - SshProxyCommandMissingError, - type SshProperties, -} from "./sshSupport"; -import { createManagedPermissions } from "./windowsAcl"; import { WorkspaceStateMachine } from "./workspaceStateMachine"; -import type { Api } from "coder/site/src/api/api"; import type { Workspace, WorkspaceAgent, @@ -106,8 +59,7 @@ import type { PathResolver } from "../storage/pathResolver"; import type { SecretsManager, SessionAuth } from "../storage/secretsManager"; import type { ContextManager } from "../vscode/contextManager"; -/** Git's home may be an unreachable share; don't stall the connect on it. */ -const GIT_SSH_CONFIG_TIMEOUT_MS = 5_000; +import type { ConnectionSetup } from "./connectionSetup"; export interface RemoteDetails extends vscode.Disposable { safeHostname: string; @@ -132,15 +84,6 @@ interface RemoteSetupContext { disposables: vscode.Disposable[]; } -interface SshConfigOptions { - workspaceClient: Api; - parts: AuthorityParts; - binaryPath: string; - logDir: string; - cliAuth: CliAuth; - sessionApp: string; -} - /** * What Open Recent shows after the path. VS Code splits the label on the * separator, so "/" would display "/home/kyle [Coder: kyle/workspace]" as @@ -178,6 +121,7 @@ export class Remote { private readonly serviceContainer: ServiceContainer, private readonly commands: Commands, private readonly extensionContext: vscode.ExtensionContext, + private readonly connectionSetup: ConnectionSetup, ) { this.logger = serviceContainer.getLogger(); this.pathResolver = serviceContainer.getPathResolver(); @@ -323,13 +267,13 @@ export class Remote { this.commands.remoteWorkspaceClient = workspaceClient; const binaryPath = await tracer.phase("cli_resolve", () => - this.resolveRemoteBinary(workspaceClient), + this.connectionSetup.resolveBinary(workspaceClient), ); const { serverFeatures, cliAuth, sessionApp } = await tracer.phase( "compatibility_check", () => - this.checkCompatibility({ + this.connectionSetup.checkCompatibility({ workspaceClient, binaryPath, baseUrl, @@ -413,7 +357,11 @@ export class Remote { try { workspace = await tracer.phase("workspace_ready", () => - this.waitForWorkspaceReady(workspace, monitor, stateMachine), + this.connectionSetup.waitForWorkspaceReady( + workspace, + monitor, + stateMachine, + ), ); } finally { stateMachine.dispose(); @@ -433,13 +381,16 @@ export class Remote { const logDir = this.pathResolver.getProxyLogPath(); const computedSshProperties = await tracer.phase("ssh_config_write", () => - this.writeRemoteSshConfig({ + this.connectionSetup.writeSshConfig({ parts: context.parts, workspaceClient, binaryPath, logDir, cliAuth, sessionApp, + // -F skips /etc/ssh/ssh_config, so use it only when Remote-SSH does. + configFile: getRemoteSshConfigFile(), + sshPath: getRemoteSshPath(), }), ); const remoteCommand = computedSshProperties.remotecommand; @@ -609,61 +560,6 @@ export class Remote { } } - private async waitForWorkspaceReady( - workspace: Workspace, - monitor: WorkspaceMonitor, - stateMachine: WorkspaceStateMachine, - ): Promise { - return vscodeProposed.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - cancellable: false, - title: "Connecting to workspace", - }, - async (progress) => { - let inProgress = false; - let pendingWorkspace: Workspace | null = null; - - return new Promise((resolve, reject) => { - const processWorkspace = async (w: Workspace) => { - if (inProgress) { - // Process one workspace at a time, keeping only the last - pendingWorkspace = w; - return; - } - - inProgress = true; - try { - pendingWorkspace = null; - - const isReady = await stateMachine.processWorkspace(w, progress); - if (isReady) { - subscription.dispose(); - resolve(stateMachine.getWorkspace() ?? w); - return; - } - } catch (error: unknown) { - subscription.dispose(); - reject(toError(error)); - return; - } finally { - inProgress = false; - } - - if (pendingWorkspace) { - void processWorkspace(pendingWorkspace); - } - }; - - void processWorkspace(workspace); - const subscription = monitor.onChange.event((w) => { - void processWorkspace(w); - }); - }); - }, - ); - } - private resolveAgent( context: RemoteSetupContext, workspace: Workspace, @@ -689,18 +585,6 @@ export class Remote { return agent; } - private async writeRemoteSshConfig( - options: SshConfigOptions, - ): Promise { - try { - this.logger.info("Updating SSH config..."); - return await this.updateSSHConfig(options); - } catch (error) { - this.logger.warn("Failed to configure SSH", error); - throw error; - } - } - private showSessionExpiredDialog(context: RemoteSetupContext) { return this.loginCoordinator.ensureLoggedInWithDialog({ safeHostname: context.parts.safeHostname, @@ -739,67 +623,6 @@ export class Remote { return undefined; } - private async resolveRemoteBinary(workspaceClient: Api): Promise { - if ( - this.extensionContext.extensionMode === vscode.ExtensionMode.Production - ) { - return this.cliManager.fetchBinary(workspaceClient); - } - // Dev override: use a custom binary at /tmp/coder if it exists. - try { - const binaryPath = path.join(os.tmpdir(), "coder"); - await fs.stat(binaryPath); - return binaryPath; - } catch { - return this.cliManager.fetchBinary(workspaceClient); - } - } - - /** - * Resolve server and CLI capabilities independently, disabling optional CLI - * features when its version can't be read. - */ - private async checkCompatibility(options: { - workspaceClient: Api; - binaryPath: string; - baseUrl: string; - safeHostname: string; - }): Promise<{ - serverFeatures: ServerFeatureSet; - cliAuth: CliAuth; - sessionApp: string; - }> { - const { workspaceClient, binaryPath, baseUrl, safeHostname } = options; - const buildInfo = await workspaceClient.getBuildInfo(); - const serverVersion = semver.parse(buildInfo.version); - - let parsedCliVersion: semver.SemVer | null; - try { - parsedCliVersion = semver.parse(await cliVersion(binaryPath)); - } catch { - parsedCliVersion = null; - } - const cliFeatures = cliFeatureSet(parsedCliVersion); - const serverFeatures = serverFeatureSet(serverVersion); - // Report schemes verbatim; normalization and editor families belong to the server. - const sessionApp = - cliFeatures.customSessionAppNames && serverFeatures.customSessionAppNames - ? vscode.env.uriScheme || "vscode" - : "vscode"; - const configDir = this.pathResolver.getGlobalConfigDir(safeHostname); - const cliAuth = resolveCliAuth( - vscode.workspace.getConfiguration(), - cliFeatures, - baseUrl, - configDir, - ); - return { - serverFeatures, - cliAuth, - sessionApp, - }; - } - /** * Rebind the workspace client when this deployment's stored session changes. * Pending requests survive only a token rotation for the same user and URL. @@ -892,194 +715,6 @@ export class Remote { } } - /** - * Returns the --log-dir argument for the ProxyCommand after making sure it - * has been created. - */ - private async getLogArgs(logDir: string): Promise { - await fs.mkdir(logDir, { recursive: true }); - this.logger.info("SSH proxy diagnostics are being written to", logDir); - return ["--log-dir", escapeProxyCommandPath(logDir), "-v"]; - } - - // updateSSHConfig updates the SSH configuration with a wildcard that handles - // all Coder entries. - private async updateSSHConfig({ - workspaceClient, - parts, - binaryPath, - logDir, - cliAuth, - sessionApp, - }: SshConfigOptions): Promise { - // Taken from the authority, so a legacy host keeps working. - const { hostPrefix, safeHostname, sshHost } = parts; - // -F skips /etc/ssh/ssh_config, so use it only when Remote-SSH does. - const configFile = getRemoteSshConfigFile(); - // The user's config gains one shared include. - const userConfigPath = - configFile ?? path.join(getSshHomeDir(), ".ssh", "config"); - // The CLI writes its block to the user's config, so read it from there. - const configSshOptions = parseCoderSshOptions( - await readSshConfig(userConfigPath), - ); - - const userConfigSsh = vscode.workspace - .getConfiguration("coder") - .get("sshConfig", []); - const userConfig = parseSshConfig(userConfigSsh); - - let deploymentSshConfig = {}; - try { - const deploymentConfig = await workspaceClient.getDeploymentSSHConfig(); - const { options, ignored } = validateDeploymentSshOptions( - deploymentConfig.ssh_config_options, - ); - deploymentSshConfig = options; - if (ignored.length > 0) { - this.logger.warn("Ignoring deployment SSH options", ignored); - this.warnIgnoredSshOptions(safeHostname, ignored); - } - } catch (error) { - if (!isAxiosError(error)) { - throw error; - } - switch (error.response?.status) { - case HttpStatusCode.NOT_FOUND: { - // Deployment does not support overriding ssh config yet. Likely an - // older version, just use the default. - break; - } - default: - throw error; - } - } - - const pinnedSshValues = { - ProxyCommand: buildSshProxyCommand({ - pathResolver: this.pathResolver, - binaryPath, - cliAuth, - logArgs: await this.getLogArgs(logDir), - sessionApp, - hostPrefix, - }), - StrictHostKeyChecking: "no", - UserKnownHostsFile: "/dev/null", - PermitLocalCommand: "no", - }; - - // Merge SSH config from three sources (highest to lowest priority): - // 1. User's VS Code coder.sshConfig setting - // 2. coder config-ssh --ssh-option flags from the CLI block - // 3. Deployment SSH config from the coderd API, with the pinned values over it - // Only 3 is allow listed; 1 and 2 are the user's own options. - const sshConfigOverrides = mergeSshConfigValues( - mergeSshConfigValues( - mergeSshConfigValues(deploymentSshConfig, pinnedSshValues), - configSshOptions, - ), - userConfig, - ); - - const sshValues: SshValues = { - Host: hostPrefix + `*`, - ...pinnedSshValues, - ConnectTimeout: "0", - LogLevel: "ERROR", - ServerAliveInterval: "10", - ServerAliveCountMax: "3", - SendEnv: SESSION_TYPE_ENV, - }; - - // One file per (host prefix, deployment). Write it before including it, - // so the include never dangles. - const coderConfigText = await writeCoderSshConfig( - { - path: this.pathResolver.getSshConfigPath( - safeHostname, - hostEditorId(sshHost), - ), - permissions: createManagedPermissions(), - }, - { values: sshValues, overrides: sshConfigOverrides }, - this.logger, - ); - const include = { dir: this.pathResolver.getSshConfigDir(), safeHostname }; - const userConfigText = await includeCoderSshConfig( - userConfigPath, - include, - this.logger, - ); - // Without -F, Git for Windows ssh reads its own home's config. When that - // is the profile's config, the include is already there: no write. - const gitConfigPath = getGitForWindowsSshConfigPath(); - if (!configFile && gitConfigPath) { - try { - await raceWithAbort( - includeCoderSshConfig(gitConfigPath, include, this.logger), - AbortSignal.timeout(GIT_SSH_CONFIG_TIMEOUT_MS), - ); - } catch (error) { - this.logger.warn( - `Failed to include the Coder SSH config in ${gitConfigPath}, so Git for Windows ssh will not find Coder hosts`, - error, - ); - } - } - - try { - return await resolveSshProperties( - getRemoteSshPath(), - parts.sshHost, - configFile, - ); - } catch (error) { - if (error instanceof SshProxyCommandMissingError) { - this.warnCoderSshConfigNotRead(include.dir, error.configFiles); - } - this.logger.warn("ssh -G failed, parsing the SSH config instead", error); - return computeSshProperties( - parts.sshHost, - `${coderConfigText}\n${userConfigText}`, - ); - } - } - - /** Remote-SSH's ssh ran but missed the include, so the connection will fail. */ - private warnCoderSshConfigNotRead( - includeDir: string, - configFiles: string[], - ): void { - const read = configFiles.join(", ") || "no SSH config"; - void vscode.window.showWarningMessage( - escapeNotificationLinks( - `Remote-SSH's ssh did not read the Coder SSH config in ${includeDir}, so it cannot reach Coder workspaces. It read ${read}. Check which ssh Remote-SSH uses and its home directory.`, - ), - ); - } - - /** Stays hidden while every ignored option was already dismissed. */ - private warnIgnoredSshOptions(safeHostname: string, ignored: string[]): void { - const memento = this.serviceContainer.getMementoManager(); - const dismissed = new Set(memento.getDismissedSshOptions(safeHostname)); - const keys = ignored.map(lowercase); - if (keys.every((key) => dismissed.has(key))) { - return; - } - const dontShow = "Don't Show Again"; - void vscode.window - .showWarningMessage( - `Ignored SSH options from the Coder deployment that could expose your machine: ${ignored.join(", ")}. To use them, add them to the "coder.sshConfig" setting.`, - dontShow, - ) - .then((choice) => - choice === dontShow - ? memento.addDismissedSshOptions(safeHostname, keys) - : undefined, - ); - } - private watchSettings( settings: Array<{ setting: string; @@ -1196,33 +831,3 @@ export class Remote { }); } } - -interface ProxyCommandOptions { - pathResolver: PathResolver; - binaryPath: string; - cliAuth: CliAuth; - logArgs: string[]; - sessionApp: string; - hostPrefix: string; -} - -/** SSH ProxyCommand using wildcard workspace hosts. */ -export function buildSshProxyCommand(options: ProxyCommandOptions): string { - // Make sure to update the `coder.sshFlags` description if we add more internal flags here! - const internalFlags = [ - "--stdio", - `--usage-app=${escapeCommandArg(options.sessionApp)}`, - "--network-info-dir", - escapeProxyCommandPath(options.pathResolver.getNetworkInfoPath()), - ...options.logArgs, - "--ssh-host-prefix", - options.hostPrefix, - "%h", - ]; - // User SSH flags are included first; internally-managed flags - // are appended last so they take precedence. - const configs = vscode.workspace.getConfiguration(); - const userSshFlags = getSshFlags(configs); - const globalFlags = getGlobalShellFlags(configs, options.cliAuth); - return `${escapeProxyCommandPath(options.binaryPath)} ${globalFlags.join(" ")} ssh ${[...userSshFlags, ...internalFlags].join(" ")}`; -} diff --git a/test/unit/remote/connectionSetup.test.ts b/test/unit/remote/connectionSetup.test.ts new file mode 100644 index 0000000000..8801f4d2f2 --- /dev/null +++ b/test/unit/remote/connectionSetup.test.ts @@ -0,0 +1,427 @@ +import { Api } from "coder/site/src/api/api"; +import { vol } from "memfs"; +import { spawnSync } from "node:child_process"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; + +import { version as cliVersion } from "@/cli/cliExec"; +import { parseRemoteAuthority } from "@/remote/authority"; +import { + buildSshProxyCommand, + ConnectionSetup, +} from "@/remote/connectionSetup"; +import { + getGitForWindowsSshConfigPath, + validateDeploymentSshOptions, +} from "@/remote/sshConfig"; +import { + resolveSshProperties, + SshProxyCommandMissingError, +} from "@/remote/sshSupport"; +import { MementoManager } from "@/storage/mementoManager"; +import { PathResolver } from "@/storage/pathResolver"; + +import { + createMockLogger, + createMockServiceContainer, + flush, + InMemoryMemento, + MockConfigurationProvider, + MockUserInteraction, + useEditor, +} from "../../mocks/testHelpers"; +import { isWindows } from "../../utils/platform"; + +import type { CliManager } from "@/cli/cliManager"; +import type { Logger } from "@/logging/logger"; +import type { CliAuth } from "@/settings/cli"; + +vi.mock("node:fs/promises", async () => (await import("memfs")).fs.promises); +vi.mock("@/remote/windowsAcl", () => ({ + createManagedPermissions: () => undefined, +})); +vi.mock(import("@/cli/cliExec"), async (importOriginal) => ({ + ...(await importOriginal()), + version: vi.fn(), +})); +vi.mock(import("@/remote/sshSupport"), async (importOriginal) => ({ + ...(await importOriginal()), + resolveSshProperties: vi.fn(), +})); +vi.mock(import("@/remote/sshConfig"), async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + getGitForWindowsSshConfigPath: vi.fn(), + validateDeploymentSshOptions: vi.fn(original.validateDeploymentSshOptions), + }; +}); + +const SAFE_HOSTNAME = "coder.example.com"; +const REMOTE_AUTHORITY = + "ssh-remote+coder-vscode.coder.example.com--testuser--test-workspace.main"; +const CLI_AUTH: CliAuth = { + store: "extension", + url: "https://coder.example.com", + configDir: "/mock/global", + useKeyring: false, + refuseRedirects: false, +}; + +function createConnectionSetup(logger: Logger = createMockLogger()) { + const config = new MockConfigurationProvider(); + const userInteraction = new MockUserInteraction(); + const serviceContainer = createMockServiceContainer({ + logger, + pathResolver: new PathResolver("/mock/global", "/mock/log"), + mementoManager: new MementoManager(new InMemoryMemento()), + cliManager: {} as CliManager, + }); + return { + connectionSetup: new ConnectionSetup( + serviceContainer, + vscode.ExtensionMode.Production, + ), + config, + userInteraction, + }; +} + +beforeEach(() => { + vi.resetAllMocks(); + vol.reset(); +}); + +interface SshFlagsCase { + name: string; + flags?: string[]; + expected: string; +} + +/** Drops the platform-specific network info path. */ +const elideNetworkInfoDir = (command: string) => + command.replace(/--network-info-dir \S+/, "--network-info-dir "); + +describe("session app", () => { + function mockClient( + version = "2.38.0", + sshConfigOptions: Record = {}, + ) { + const client = new Api(); + vi.spyOn(client, "getBuildInfo").mockResolvedValue({ + version, + external_url: "", + dashboard_url: "", + telemetry: false, + workspace_proxy: false, + agent_api_version: "", + provisioner_api_version: "", + upgrade_message: "", + deployment_id: "", + }); + vi.spyOn(client, "getDeploymentSSHConfig").mockResolvedValue({ + hostname_prefix: "", + hostname_suffix: "", + ssh_config_options: sshConfigOptions, + }); + return client; + } + + async function checkCompatibility(cli: string | Error, server: string) { + const { connectionSetup } = createConnectionSetup(); + if (cli instanceof Error) { + vi.mocked(cliVersion).mockRejectedValue(cli); + } else { + vi.mocked(cliVersion).mockResolvedValue(cli); + } + return connectionSetup.checkCompatibility({ + workspaceClient: mockClient(server), + binaryPath: "/mock/coder", + baseUrl: CLI_AUTH.url, + safeHostname: SAFE_HOSTNAME, + }); + } + + it.each([ + ["cursor", "2.38.0", "2.38.0", "cursor"], + ["future-editor-next", "2.38.0", "2.38.0", "future-editor-next"], + ["", "2.38.0", "2.38.0", "vscode"], + ["cursor", "2.37.99", "2.38.0", "vscode"], + ["cursor", "2.38.0", "2.37.99", "vscode"], + ["cursor", "invalid", "2.38.0", "vscode"], + ["cursor", "2.38.0", "invalid", "vscode"], + ])( + "selects %s with CLI %s and server %s", + async (scheme, cli, server, expected) => { + useEditor(scheme); + expect((await checkCompatibility(cli, server)).sessionApp).toBe(expected); + }, + ); + + it("does not hide an unsupported CLI behind the version-probe fallback", async () => { + await expect(checkCompatibility("2.28.9", "2.38.0")).rejects.toThrow( + "Your Coder CLI is version 2.28.9. This extension requires Coder CLI 2.29.0 or newer. Upgrade your CLI to continue.", + ); + }); + + it.each([new Error("unavailable"), "invalid"])( + "keeps baseline CLI capabilities separate from the server when probing returns %s", + async (cli) => { + useEditor("cursor"); + const { sessionApp, serverFeatures, cliAuth } = await checkCompatibility( + cli, + "2.38.0", + ); + expect(sessionApp).toBe("vscode"); + expect(cliAuth.refuseRedirects).toBe(false); + expect(serverFeatures.onSuccessBuild).toBe(true); + }, + ); + + async function writeConfig( + sshConfigOptions?: Record, + { connectionSetup } = createConnectionSetup(), + configFile?: string, + resolveError = new Error("no ssh"), + ) { + useEditor("cursor"); + vi.mocked(resolveSshProperties).mockRejectedValue(resolveError); + return connectionSetup.writeSshConfig({ + workspaceClient: mockClient(undefined, sshConfigOptions), + parts: parseRemoteAuthority(REMOTE_AUTHORITY)!, + binaryPath: "/mock/coder", + logDir: "/mock/log", + cliAuth: CLI_AUTH, + sessionApp: "future-editor-next", + configFile, + sshPath: undefined, + }); + } + + it("writes the app name and forwards the session type", async () => { + const config = await writeConfig(); + expect(config.proxycommand).toContain("--usage-app=future-editor-next "); + expect(config.sendenv).toBe("CODER_SSH_SESSION_TYPE"); + expect(config.permitlocalcommand).toBe("no"); + }); + + it("keeps Coder's pinned options and host over the deployment's", async () => { + const config = await writeConfig({ + HostName: "other.example.com", + UserKnownHostsFile: "", + StrictHostKeyChecking: "ask", + }); + expect(config).toMatchObject({ + userknownhostsfile: "/dev/null", + stricthostkeychecking: "no", + }); + expect(config).not.toHaveProperty("hostname"); + }); + + it("keeps Coder's pinned options over unfiltered deployment options, not the user's", async () => { + const deployment = { + ProxyCommand: "other", + StrictHostKeyChecking: "ask", + UserKnownHostsFile: "", + PermitLocalCommand: "yes", + }; + vi.mocked(validateDeploymentSshOptions).mockReturnValue({ + options: deployment, + ignored: [], + }); + const context = createConnectionSetup(); + context.config.set("coder.sshConfig", ["StrictHostKeyChecking yes"]); + const config = await writeConfig(deployment, context); + expect(config).toMatchObject({ + proxycommand: expect.stringContaining("--usage-app="), + stricthostkeychecking: "yes", + userknownhostsfile: "/dev/null", + permitlocalcommand: "no", + }); + }); + + it("ignores deployment SetEnv and SendEnv, warning until dismissed", async () => { + const context = createConnectionSetup(); + context.userInteraction.setResponse(/^Ignored SSH/, "Don't Show Again"); + const config = await writeConfig( + { SetEnv: "CODER_SSH_SESSION_TYPE=spoofed", SendEnv: "SECRET" }, + context, + ); + expect(config.setenv).toBeUndefined(); + expect(config.sendenv).toBe("CODER_SSH_SESSION_TYPE"); + await flush(); + + // A dismissed subset stays hidden; a new option warns again. + await writeConfig({ sendenv: "SECRET" }, context); + await writeConfig({ SendEnv: "SECRET", User: "x" }, context); + expect( + context.userInteraction.getMessageCalls().map((call) => call.message), + ).toEqual([ + expect.stringContaining(": SetEnv, SendEnv."), + expect.stringContaining(": SendEnv, User."), + ]); + }); + + describe("Git for Windows ssh config", () => { + const gitConfig = "/h/.ssh/config"; + + /** Writes the config while Git for Windows ssh would read `gitConfig`. */ + async function writeWithGitConfig(configFile?: string) { + vi.mocked(getGitForWindowsSshConfigPath).mockReturnValue(gitConfig); + const logger = createMockLogger(); + const context = createConnectionSetup(logger); + await writeConfig(undefined, context, configFile); + return logger; + } + + interface GitConfigCase { + configFile?: string; + included: boolean; + } + it.each([ + { included: true }, + { configFile: "/mock/ssh/config", included: false }, + ])( + "includes the Coder config: $included with -F $configFile", + async ({ configFile, included }) => { + await writeWithGitConfig(configFile); + expect(vol.existsSync(gitConfig)).toBe(included); + }, + ); + + it("warns and still connects when it cannot be written", async () => { + vol.fromJSON({ "/h": "not a directory" }); + const logger = await writeWithGitConfig(); + expect(logger.warn).toHaveBeenCalledWith( + `Failed to include the Coder SSH config in ${gitConfig}, so Git for Windows ssh will not find Coder hosts`, + expect.any(Error), + ); + }); + }); + + it.each([ + { + configFiles: ["/home/me/.ssh/config"], + read: "It read /home/me/.ssh/config.", + }, + { configFiles: [], read: "It read no SSH config." }, + ])( + "warns when ssh misses the Coder config, listing $configFiles", + async ({ configFiles, read }) => { + const context = createConnectionSetup(); + const error = new SshProxyCommandMissingError( + configFiles + .map((file) => `debug1: Reading configuration data ${file}`) + .join("\n"), + ); + await writeConfig(undefined, context, undefined, error); + const [message] = context.userInteraction + .getMessageCalls() + .map((call) => call.message); + const includeDir = new PathResolver( + "/mock/global", + "/mock/log", + ).getSshConfigDir(); + expect(message).toContain( + `did not read the Coder SSH config in ${includeDir}`, + ); + expect(message).toContain(read); + }, + ); + + it("connects silently when ssh cannot run", async () => { + const context = createConnectionSetup(); + await writeConfig(undefined, context); + expect(context.userInteraction.getMessageCalls()).toEqual([]); + }); +}); + +describe("ProxyCommand", () => { + it.each([ + { + name: "disables autostart by default", + expected: + "ssh --disable-autostart --stdio --usage-app=vscode --network-info-dir --ssh-host-prefix coder-vscode.coder.example.com-- %h", + }, + { + name: "passes the user's flags ahead of the managed ones", + flags: ["--wait=yes"], + expected: + "ssh --wait=yes --stdio --usage-app=vscode --network-info-dir --ssh-host-prefix coder-vscode.coder.example.com-- %h", + }, + ])("$name", ({ flags, expected }) => { + const config = new MockConfigurationProvider(); + if (flags) { + config.set("coder.sshFlags", flags); + } + + const proxyCommand = buildSshProxyCommand({ + pathResolver: new PathResolver("/mock/global", "/mock/log"), + binaryPath: "/mock/coder", + cliAuth: CLI_AUTH, + logArgs: [], + sessionApp: "vscode", + hostPrefix: "coder-vscode.coder.example.com--", + }); + + expect(elideNetworkInfoDir(proxyCommand)).toBe( + `/mock/coder "--token=" --global-config /mock/global --url https://coder.example.com --use-keyring=false ${expected}`, + ); + }); + + // OpenSSH runs the command with `sh -c` on Unix; Win32-OpenSSH passes it + // to CreateProcessW, so the program's argv parser splits it. + it("reaches the CLI unchanged through this platform's OpenSSH", () => { + // A drive path on Windows reaches the CLI with `/`. + const configDir = isWindows() + ? String.raw`C:\Users\John Doe\AppData\coder` + : "/Users/me/Library/Application Support/coder"; + const headerCommand = 'echo "X: $TOKEN" "C:\\a b\\" `id`'; + const pathResolver = new PathResolver("/mock/global", "/mock/log"); + new MockConfigurationProvider().set("coder.headerCommand", headerCommand); + const proxyCommand = buildSshProxyCommand({ + pathResolver, + binaryPath: "coder", + cliAuth: { ...CLI_AUTH, configDir }, + logArgs: [], + sessionApp: "vscode", + hostPrefix: "coder-vscode.coder.example.com--", + }); + + // Swap the CLI for Node printing the arguments it receives. + const printArgv = proxyCommand.replace( + /^coder /, + `-p "JSON.stringify(process.argv.slice(1))" -- `, + ); + const result = isWindows() + ? spawnSync(process.execPath, [printArgv], { + argv0: "node", + encoding: "utf8", + windowsVerbatimArguments: true, + }) + : spawnSync("sh", ["-c", `"$NODE" ${printArgv}`], { + encoding: "utf8", + env: { ...process.env, NODE: process.execPath }, + }); + + expect(JSON.parse(result.stdout)).toStrictEqual([ + "--token=", + "--global-config", + configDir.replaceAll("\\", "/"), + "--url", + CLI_AUTH.url, + "--use-keyring=false", + "--header-command", + headerCommand, + "ssh", + "--disable-autostart", + "--stdio", + "--usage-app=vscode", + "--network-info-dir", + pathResolver.getNetworkInfoPath(), + "--ssh-host-prefix", + "coder-vscode.coder.example.com--", + "%h", + ]); + }); +}); diff --git a/test/unit/remote/remote.test.ts b/test/unit/remote/remote.test.ts index 164d40ca91..6963d7b738 100644 --- a/test/unit/remote/remote.test.ts +++ b/test/unit/remote/remote.test.ts @@ -1,27 +1,12 @@ -import { Api } from "coder/site/src/api/api"; import { vol } from "memfs"; -import { spawnSync } from "node:child_process"; import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import * as vscode from "vscode"; import { AuthInterceptor } from "@/api/authInterceptor"; -import { version as cliVersion } from "@/cli/cliExec"; import { DEFAULT_OAUTH_SCOPES } from "@/oauth/constants"; import { OAuthSessionManager } from "@/oauth/sessionManager"; -import { parseRemoteAuthority } from "@/remote/authority"; -import { - buildSshProxyCommand, - Remote, - workspaceLabelSuffix, -} from "@/remote/remote"; -import { - getGitForWindowsSshConfigPath, - validateDeploymentSshOptions, -} from "@/remote/sshConfig"; -import { - resolveSshProperties, - SshProxyCommandMissingError, -} from "@/remote/sshSupport"; +import { ConnectionSetup } from "@/remote/connectionSetup"; +import { Remote, workspaceLabelSuffix } from "@/remote/remote"; import { MementoManager } from "@/storage/mementoManager"; import { PathResolver } from "@/storage/pathResolver"; import { SecretsManager } from "@/storage/secretsManager"; @@ -43,7 +28,6 @@ import { setupAxiosMockRoutes, useEditor, } from "../../mocks/testHelpers"; -import { isWindows } from "../../utils/platform"; import { createMockClientRegistration, createMockOAuthMetadata, @@ -78,25 +62,6 @@ vi.mock("axios", async () => { }); vi.mock("node:fs/promises", async () => (await import("memfs")).fs.promises); -vi.mock("@/remote/windowsAcl", () => ({ - createManagedPermissions: () => undefined, -})); -vi.mock(import("@/cli/cliExec"), async (importOriginal) => ({ - ...(await importOriginal()), - version: vi.fn(), -})); -vi.mock(import("@/remote/sshSupport"), async (importOriginal) => ({ - ...(await importOriginal()), - resolveSshProperties: vi.fn(), -})); -vi.mock(import("@/remote/sshConfig"), async (importOriginal) => { - const original = await importOriginal(); - return { - ...original, - getGitForWindowsSshConfigPath: vi.fn(), - validateDeploymentSshOptions: vi.fn(original.validateDeploymentSshOptions), - }; -}); const SAFE_HOSTNAME = "coder.example.com"; const REMOTE_AUTHORITY = @@ -118,7 +83,7 @@ const CLI_AUTH: CliAuth = { }; function createRemote(logger: Logger = createMockLogger()) { - const config = new MockConfigurationProvider(); + new MockConfigurationProvider(); const userInteraction = new MockUserInteraction(); const pathResolver = new PathResolver("/mock/global", "/mock/log"); vol.fromJSON({ @@ -157,8 +122,8 @@ function createRemote(logger: Logger = createMockLogger()) { serviceContainer, {} as Commands, {} as vscode.ExtensionContext, + new ConnectionSetup(serviceContainer, vscode.ExtensionMode.Production), ), - config, ensureLoggedInWithDialog, mementoManager, secretsManager, @@ -497,340 +462,6 @@ describe("Remote", () => { ], }); }); - - interface SshFlagsCase { - name: string; - flags?: string[]; - expected: string; - } - - /** Drops the platform-specific network info path. */ - const elideNetworkInfoDir = (command: string) => - command.replace(/--network-info-dir \S+/, "--network-info-dir "); - - describe("session app", () => { - function mockClient( - version = "2.38.0", - sshConfigOptions: Record = {}, - ) { - const client = new Api(); - vi.spyOn(client, "getBuildInfo").mockResolvedValue({ - version, - external_url: "", - dashboard_url: "", - telemetry: false, - workspace_proxy: false, - agent_api_version: "", - provisioner_api_version: "", - upgrade_message: "", - deployment_id: "", - }); - vi.spyOn(client, "getDeploymentSSHConfig").mockResolvedValue({ - hostname_prefix: "", - hostname_suffix: "", - ssh_config_options: sshConfigOptions, - }); - return client; - } - - async function checkCompatibility(cli: string | Error, server: string) { - const { remote } = createRemote(); - if (cli instanceof Error) { - vi.mocked(cliVersion).mockRejectedValue(cli); - } else { - vi.mocked(cliVersion).mockResolvedValue(cli); - } - const method = "checkCompatibility"; - return remote[method]({ - workspaceClient: mockClient(server), - binaryPath: "/mock/coder", - baseUrl: CLI_AUTH.url, - safeHostname: SAFE_HOSTNAME, - }); - } - - it.each([ - ["cursor", "2.38.0", "2.38.0", "cursor"], - ["future-editor-next", "2.38.0", "2.38.0", "future-editor-next"], - ["", "2.38.0", "2.38.0", "vscode"], - ["cursor", "2.37.99", "2.38.0", "vscode"], - ["cursor", "2.38.0", "2.37.99", "vscode"], - ["cursor", "invalid", "2.38.0", "vscode"], - ["cursor", "2.38.0", "invalid", "vscode"], - ])( - "selects %s with CLI %s and server %s", - async (scheme, cli, server, expected) => { - useEditor(scheme); - expect((await checkCompatibility(cli, server)).sessionApp).toBe( - expected, - ); - }, - ); - - it("does not hide an unsupported CLI behind the version-probe fallback", async () => { - await expect(checkCompatibility("2.28.9", "2.38.0")).rejects.toThrow( - "Your Coder CLI is version 2.28.9. This extension requires Coder CLI 2.29.0 or newer. Upgrade your CLI to continue.", - ); - }); - - it.each([new Error("unavailable"), "invalid"])( - "keeps baseline CLI capabilities separate from the server when probing returns %s", - async (cli) => { - useEditor("cursor"); - const { sessionApp, serverFeatures, cliAuth } = - await checkCompatibility(cli, "2.38.0"); - expect(sessionApp).toBe("vscode"); - expect(cliAuth.refuseRedirects).toBe(false); - expect(serverFeatures.onSuccessBuild).toBe(true); - }, - ); - - async function writeConfig( - sshConfigOptions?: Record, - { remote } = createRemote(), - resolveError = new Error("no ssh"), - ) { - useEditor("cursor"); - vi.mocked(resolveSshProperties).mockRejectedValue(resolveError); - const method = "writeRemoteSshConfig"; - return remote[method]({ - workspaceClient: mockClient(undefined, sshConfigOptions), - parts: parseRemoteAuthority(REMOTE_AUTHORITY)!, - binaryPath: "/mock/coder", - logDir: "/mock/log", - cliAuth: CLI_AUTH, - sessionApp: "future-editor-next", - }); - } - - it("writes the app name and forwards the session type", async () => { - const config = await writeConfig(); - expect(config.proxycommand).toContain("--usage-app=future-editor-next "); - expect(config.sendenv).toBe("CODER_SSH_SESSION_TYPE"); - expect(config.permitlocalcommand).toBe("no"); - }); - - it("keeps Coder's pinned options and host over the deployment's", async () => { - const config = await writeConfig({ - HostName: "other.example.com", - UserKnownHostsFile: "", - StrictHostKeyChecking: "ask", - }); - expect(config).toMatchObject({ - userknownhostsfile: "/dev/null", - stricthostkeychecking: "no", - }); - expect(config).not.toHaveProperty("hostname"); - }); - - it("keeps Coder's pinned options over unfiltered deployment options, not the user's", async () => { - const deployment = { - ProxyCommand: "other", - StrictHostKeyChecking: "ask", - UserKnownHostsFile: "", - PermitLocalCommand: "yes", - }; - vi.mocked(validateDeploymentSshOptions).mockReturnValue({ - options: deployment, - ignored: [], - }); - const context = createRemote(); - context.config.set("coder.sshConfig", ["StrictHostKeyChecking yes"]); - const config = await writeConfig(deployment, context); - expect(config).toMatchObject({ - proxycommand: expect.stringContaining("--usage-app="), - stricthostkeychecking: "yes", - userknownhostsfile: "/dev/null", - permitlocalcommand: "no", - }); - }); - - it("ignores deployment SetEnv and SendEnv, warning until dismissed", async () => { - const context = createRemote(); - context.userInteraction.setResponse(/^Ignored SSH/, "Don't Show Again"); - const config = await writeConfig( - { SetEnv: "CODER_SSH_SESSION_TYPE=spoofed", SendEnv: "SECRET" }, - context, - ); - expect(config.setenv).toBeUndefined(); - expect(config.sendenv).toBe("CODER_SSH_SESSION_TYPE"); - await flush(); - - // A dismissed subset stays hidden; a new option warns again. - await writeConfig({ sendenv: "SECRET" }, context); - await writeConfig({ SendEnv: "SECRET", User: "x" }, context); - expect( - context.userInteraction.getMessageCalls().map((call) => call.message), - ).toEqual([ - expect.stringContaining(": SetEnv, SendEnv."), - expect.stringContaining(": SendEnv, User."), - ]); - }); - - describe("Git for Windows ssh config", () => { - const gitConfig = "/h/.ssh/config"; - - /** Connects while Git for Windows ssh would read `gitConfig`. */ - async function writeWithGitConfig(configFile?: string) { - vi.mocked(getGitForWindowsSshConfigPath).mockReturnValue(gitConfig); - const logger = createMockLogger(); - const context = createRemote(logger); - context.config.set("remote.SSH.configFile", configFile); - await writeConfig(undefined, context); - return logger; - } - - interface GitConfigCase { - configFile?: string; - included: boolean; - } - it.each([ - { included: true }, - { configFile: "/mock/ssh/config", included: false }, - ])( - "includes the Coder config: $included with -F $configFile", - async ({ configFile, included }) => { - await writeWithGitConfig(configFile); - expect(vol.existsSync(gitConfig)).toBe(included); - }, - ); - - it("warns and still connects when it cannot be written", async () => { - vol.fromJSON({ "/h": "not a directory" }); - const logger = await writeWithGitConfig(); - expect(logger.warn).toHaveBeenCalledWith( - `Failed to include the Coder SSH config in ${gitConfig}, so Git for Windows ssh will not find Coder hosts`, - expect.any(Error), - ); - }); - }); - - it.each([ - { - configFiles: ["/home/me/.ssh/config"], - read: "It read /home/me/.ssh/config.", - }, - { configFiles: [], read: "It read no SSH config." }, - ])( - "warns when ssh misses the Coder config, listing $configFiles", - async ({ configFiles, read }) => { - const context = createRemote(); - const error = new SshProxyCommandMissingError( - configFiles - .map((file) => `debug1: Reading configuration data ${file}`) - .join("\n"), - ); - await writeConfig(undefined, context, error); - const [message] = context.userInteraction - .getMessageCalls() - .map((call) => call.message); - const includeDir = new PathResolver( - "/mock/global", - "/mock/log", - ).getSshConfigDir(); - expect(message).toContain( - `did not read the Coder SSH config in ${includeDir}`, - ); - expect(message).toContain(read); - }, - ); - - it("connects silently when ssh cannot run", async () => { - const context = createRemote(); - await writeConfig(undefined, context); - expect(context.userInteraction.getMessageCalls()).toEqual([]); - }); - }); - - describe("ProxyCommand", () => { - it.each([ - { - name: "disables autostart by default", - expected: - "ssh --disable-autostart --stdio --usage-app=vscode --network-info-dir --ssh-host-prefix coder-vscode.coder.example.com-- %h", - }, - { - name: "passes the user's flags ahead of the managed ones", - flags: ["--wait=yes"], - expected: - "ssh --wait=yes --stdio --usage-app=vscode --network-info-dir --ssh-host-prefix coder-vscode.coder.example.com-- %h", - }, - ])("$name", ({ flags, expected }) => { - const config = new MockConfigurationProvider(); - if (flags) { - config.set("coder.sshFlags", flags); - } - - const proxyCommand = buildSshProxyCommand({ - pathResolver: new PathResolver("/mock/global", "/mock/log"), - binaryPath: "/mock/coder", - cliAuth: CLI_AUTH, - logArgs: [], - sessionApp: "vscode", - hostPrefix: "coder-vscode.coder.example.com--", - }); - - expect(elideNetworkInfoDir(proxyCommand)).toBe( - `/mock/coder "--token=" --global-config /mock/global --url https://coder.example.com --use-keyring=false ${expected}`, - ); - }); - - // OpenSSH runs the command with `sh -c` on Unix; Win32-OpenSSH passes it - // to CreateProcessW, so the program's argv parser splits it. - it("reaches the CLI unchanged through this platform's OpenSSH", () => { - // A drive path on Windows reaches the CLI with `/`. - const configDir = isWindows() - ? String.raw`C:\Users\John Doe\AppData\coder` - : "/Users/me/Library/Application Support/coder"; - const headerCommand = 'echo "X: $TOKEN" "C:\\a b\\" `id`'; - const pathResolver = new PathResolver("/mock/global", "/mock/log"); - new MockConfigurationProvider().set("coder.headerCommand", headerCommand); - const proxyCommand = buildSshProxyCommand({ - pathResolver, - binaryPath: "coder", - cliAuth: { ...CLI_AUTH, configDir }, - logArgs: [], - sessionApp: "vscode", - hostPrefix: "coder-vscode.coder.example.com--", - }); - - // Swap the CLI for Node printing the arguments it receives. - const printArgv = proxyCommand.replace( - /^coder /, - `-p "JSON.stringify(process.argv.slice(1))" -- `, - ); - const result = isWindows() - ? spawnSync(process.execPath, [printArgv], { - argv0: "node", - encoding: "utf8", - windowsVerbatimArguments: true, - }) - : spawnSync("sh", ["-c", `"$NODE" ${printArgv}`], { - encoding: "utf8", - env: { ...process.env, NODE: process.execPath }, - }); - - expect(JSON.parse(result.stdout)).toStrictEqual([ - "--token=", - "--global-config", - configDir.replaceAll("\\", "/"), - "--url", - CLI_AUTH.url, - "--use-keyring=false", - "--header-command", - headerCommand, - "ssh", - "--disable-autostart", - "--stdio", - "--usage-app=vscode", - "--network-info-dir", - pathResolver.getNetworkInfoPath(), - "--ssh-host-prefix", - "coder-vscode.coder.example.com--", - "%h", - ]); - }); - }); }); describe("workspaceLabelSuffix", () => { From 361252fcf9a8822b48b707f2fa18e26a6696b62e Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Tue, 24 Nov 2026 12:12:33 +0000 Subject: [PATCH 3/4] feat: add a command to open a workspace in the VS Code Agents window Coder: Open Workspace in Agents Window starts the workspace if needed, writes the SSH config to ~/.ssh/config for plain ssh, and opens the template's directory (or the last folder opened on the workspace) in the Agents window. The command shows only where VS Code has the Agents window. --- CHANGELOG.md | 3 + package.json | 9 + src/commands.ts | 190 +++++++++++++++--- src/extension.ts | 16 +- src/instrumentation/EVENTS.md | 43 ++-- src/instrumentation/workspaceOpen.ts | 79 ++++++-- src/remote/agentsWindowConnection.ts | 107 ++++++++++ src/remote/workspaceStateMachine.ts | 10 +- src/vscode/agentsWindow.ts | 20 ++ src/vscode/commandManager.ts | 1 + src/vscode/contextManager.ts | 1 + test/mocks/commands.ts | 2 + test/unit/commands.netcheck.test.ts | 2 + test/unit/commands.openInAgentsWindow.test.ts | 180 +++++++++++++++++ test/unit/commands.supportBundle.test.ts | 2 + test/unit/commands.telemetry.test.ts | 2 + .../remote/agentsWindowConnection.test.ts | 83 ++++++++ .../unit/remote/workspaceStateMachine.test.ts | 7 +- 18 files changed, 694 insertions(+), 63 deletions(-) create mode 100644 src/remote/agentsWindowConnection.ts create mode 100644 test/unit/commands.openInAgentsWindow.test.ts create mode 100644 test/unit/remote/agentsWindowConnection.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 277b5045ba..46e4ec9a3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ ### Added - The extension is now enabled by default in the VS Code Agents window. +- `Coder: Open Workspace in Agents Window` opens a workspace in the VS Code + Agents window, starting it first if needed. It opens the template's + directory, or the folder you last opened on the workspace. ## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03 diff --git a/package.json b/package.json index 634ae17feb..505f94ff11 100644 --- a/package.json +++ b/package.json @@ -442,6 +442,11 @@ "category": "Coder", "icon": "$(play)" }, + { + "command": "coder.openInAgentsWindow", + "title": "Open Workspace in Agents Window", + "category": "Coder" + }, { "command": "coder.openDevContainer", "title": "Open Dev Container", @@ -675,6 +680,10 @@ "command": "coder.openFromSidebar", "when": "false" }, + { + "command": "coder.openInAgentsWindow", + "when": "coder.authenticated && coder.agentsWindowSupported" + }, { "command": "coder.openDevContainer", "when": "false" diff --git a/src/commands.ts b/src/commands.ts index 7d25a9f956..3789209775 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -36,6 +36,7 @@ import { } from "./instrumentation/diagnostics"; import { WorkspaceOperationTelemetry } from "./instrumentation/workspace"; import { + type AgentsWindowOpenTrace, type DevContainerMode, type WorkspaceOpenSource, WorkspaceOpenTelemetry, @@ -44,6 +45,7 @@ import { type WorkspacePickerResult, type WorkspacePickerSource, } from "./instrumentation/workspaceOpen"; +import { prepareAgentsWindowConnection } from "./remote/agentsWindowConnection"; import { LegacyEditorId, currentEditorId, @@ -58,6 +60,7 @@ import { applySettingOverrides, getRecommendedSshSettings, } from "./remote/sshOverrides"; +import { WorkspaceStartCancelledError } from "./remote/workspaceStateMachine"; import { isKeyringEnabled, resolveCliAuth } from "./settings/cli"; import { appendVsCodeLogs } from "./supportBundle/appendVsCodeLogs"; import { @@ -71,6 +74,7 @@ import { withProgress, } from "./ui/progress"; import { maybeAskAgent, maybeAskUrl } from "./ui/prompts"; +import { openAgentsWindow } from "./vscode/agentsWindow"; import { vscodeProposed } from "./vscode/proposed"; import { parseNetcheckReport } from "./webviews/netcheck/types"; import { parseSpeedtestResult } from "./webviews/speedtest/types"; @@ -91,6 +95,7 @@ import type { ServiceContainer } from "./container"; import type { DeploymentManager } from "./deployment/deploymentManager"; import type { Logger } from "./logging/logger"; import type { LoginCoordinator, LoginMethod } from "./login/loginCoordinator"; +import type { ConnectionSetup } from "./remote/connectionSetup"; import type { MementoManager } from "./storage/mementoManager"; import type { PathResolver } from "./storage/pathResolver"; import type { SecretsManager, SessionAuth } from "./storage/secretsManager"; @@ -155,7 +160,14 @@ type SelectedWorkspace = Extract; type OpenWorkspaceResult = | { readonly status: "opened"; readonly handoff: "folder" | "empty_window" } - | { readonly status: "cancelled"; readonly stage: "recent_folder_picker" }; + | { + readonly status: "cancelled"; + readonly stage: "recent_folder_picker" | "start_prompt"; + }; + +type FolderChoice = + | { readonly status: "chosen"; readonly folderPath?: string } + | { readonly status: "cancelled" }; const UPDATE_AND_RESTART_ACTION = "Update and Restart"; @@ -211,9 +223,10 @@ export class Commands { public remoteWorkspaceClient?: CoderApi; public constructor( - serviceContainer: ServiceContainer, + private readonly serviceContainer: ServiceContainer, private readonly extensionClient: CoderApi, private readonly deploymentManager: DeploymentManager, + private readonly connectionSetup: ConnectionSetup, ) { this.telemetryService = serviceContainer.getTelemetryService(); this.authTelemetry = new AuthTelemetry(this.telemetryService); @@ -1199,6 +1212,104 @@ export class Commands { return recordOpenResult(telemetry, selection, result); } + /** + * Open a workspace of the logged-in deployment in the VS Code Agents window, + * starting it first if needed. + */ + public async openInAgentsWindow(): Promise { + return this.workspaceOpenTelemetry.traceAgentsWindow((telemetry) => + this.runOpenInAgentsWindow(telemetry), + ); + } + + private async runOpenInAgentsWindow( + telemetry: AgentsWindowOpenTrace, + ): Promise { + const baseUrl = this.requireExtensionBaseUrl(); + const pick = await this.pickWorkspace("workspace_open"); + if (pick.status === "cancelled") { + telemetry.abort("workspace_picker"); + return false; + } + if (pick.status === "failed") { + telemetry.error(pick.category); + return false; + } + const agents = await this.extractAgentsWithFallback(pick.workspace); + const picked = await maybeAskAgent(agents); + if (!picked) { + telemetry.abort("agent_picker", { workspace: pick.workspace }); + return false; + } + telemetry.select({ workspace: pick.workspace, agent: picked }); + + const remoteAuthority = toRemoteAuthority( + baseUrl, + pick.workspace.owner_name, + pick.workspace.name, + picked.name, + ); + let ready: { workspace: Workspace; agent: WorkspaceAgent }; + try { + ready = await prepareAgentsWindowConnection({ + client: this.extensionClient, + baseUrl, + workspace: pick.workspace, + remoteAuthority, + connectionSetup: this.connectionSetup, + serviceContainer: this.serviceContainer, + trace: telemetry, + }); + } catch (error) { + if (error instanceof WorkspaceStartCancelledError) { + return recordOpenResult( + telemetry, + { workspace: pick.workspace, agent: picked }, + { status: "cancelled", stage: "start_prompt" }, + ); + } + throw error; + } + + const { folders } = await this.recentlyOpened(); + const folder = await this.chooseFolder( + folders, + remoteAuthority, + ready.agent, + ); + if (folder.status === "cancelled") { + return recordOpenResult(telemetry, ready, { + status: "cancelled", + stage: "recent_folder_picker", + }); + } + const { folderPath } = folder; + const handoff = folderPath ? "folder" : "empty_window"; + if (!folderPath) { + void vscode.window.showWarningMessage( + `The template for ${createWorkspaceIdentifier(ready.workspace)} sets no directory and no folder was opened on it before, so the Agents window opens without a folder on it.`, + ); + } + + this.logger.info("Opening workspace in the Agents window", { + remoteAuthority, + handoff, + }); + await openAgentsWindow( + folderPath + ? vscode.Uri.from({ + scheme: "vscode-remote", + authority: remoteAuthority, + path: folderPath, + }) + : undefined, + ); + return recordOpenResult(telemetry, ready, { + status: "opened", + handoff, + }); + } + /** * Open a devcontainer from a workspace belonging to the currently logged-in deployment. * @@ -1703,44 +1814,27 @@ export class Commands { } /** - * Given a workspace and agent, build the host name, find a directory to open, - * and pass both to the Remote SSH plugin in the form of a remote authority - * URI. - * - * If provided, folderPath is always used, otherwise expanded_directory from - * the agent is used. + * The folder to open on the agent: `folderPath`, else the template's default + * directory, else a recently opened folder on this workspace. */ - private async openWorkspace( - baseUrl: string, - workspace: Workspace, + private async chooseFolder( + folders: vscode.Uri[], + remoteAuthority: string, agent: WorkspaceAgent, options: Pick< OpenOptions, "folderPath" | "openRecent" | "useDefaultDirectory" > = {}, - ): Promise { + ): Promise { const { openRecent, useDefaultDirectory } = { ...openDefaults, ...options, }; let { folderPath } = options; - let remoteAuthority = toRemoteAuthority( - baseUrl, - workspace.owner_name, - workspace.name, - agent.name, - ); - - let newWindow = true; - // Open in the existing window if no workspaces are open. - if (!vscode.workspace.workspaceFolders?.length) { - newWindow = false; - } if (!folderPath && useDefaultDirectory) { folderPath = agent.expanded_directory; } - const { folders, entries } = await this.recentlyOpened(); // If the agent had no folder or we have been asked to open the most recent, // we can try to open a recently opened folder/workspace. if (!folderPath || openRecent) { @@ -1764,10 +1858,54 @@ export class Commands { }); if (!folderPath) { // User aborted. - return { status: "cancelled", stage: "recent_folder_picker" }; + return { status: "cancelled" }; } } } + return { status: "chosen", folderPath }; + } + + /** + * Given a workspace and agent, build the host name, find a directory to open, + * and pass both to the Remote SSH plugin in the form of a remote authority + * URI. + * + * If provided, folderPath is always used, otherwise expanded_directory from + * the agent is used. + */ + private async openWorkspace( + baseUrl: string, + workspace: Workspace, + agent: WorkspaceAgent, + options: Pick< + OpenOptions, + "folderPath" | "openRecent" | "useDefaultDirectory" + > = {}, + ): Promise { + let remoteAuthority = toRemoteAuthority( + baseUrl, + workspace.owner_name, + workspace.name, + agent.name, + ); + + let newWindow = true; + // Open in the existing window if no workspaces are open. + if (!vscode.workspace.workspaceFolders?.length) { + newWindow = false; + } + + const { folders, entries } = await this.recentlyOpened(); + const folder = await this.chooseFolder( + folders, + remoteAuthority, + agent, + options, + ); + if (folder.status === "cancelled") { + return { status: "cancelled", stage: "recent_folder_picker" }; + } + const { folderPath } = folder; remoteAuthority = this.reusableAuthority(entries, remoteAuthority); // Only set the memento when opening a new folder/window diff --git a/src/extension.ts b/src/extension.ts index a62cf69ea1..cf61914d93 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -28,7 +28,7 @@ import { ConnectionSetup } from "./remote/connectionSetup"; import { Remote } from "./remote/remote"; import { getRemoteSshExtension } from "./remote/sshExtension"; import { registerUriHandler } from "./uri/uriHandler"; -import { isAgentsWindow } from "./vscode/agentsWindow"; +import { canOpenAgentsWindow, isAgentsWindow } from "./vscode/agentsWindow"; import { initVscodeProposed } from "./vscode/proposed"; import { TasksPanelProvider } from "./webviews/tasks/tasksPanelProvider"; import { WorkspaceActionRunner } from "./webviews/workspaces/workspaceActionRunner"; @@ -198,6 +198,9 @@ async function doActivate( contextManager.set("coder.tasksSupported", supported); }; void updateTasksSupported(); + void canOpenAgentsWindow().then((supported) => + contextManager.set("coder.agentsWindowSupported", supported), + ); ctx.subscriptions.push( deploymentManager.session.onDidChange(() => { @@ -211,7 +214,12 @@ async function doActivate( serviceContainer, ctx.extensionMode, ); - const commands = new Commands(serviceContainer, client, deploymentManager); + const commands = new Commands( + serviceContainer, + client, + deploymentManager, + connectionSetup, + ); // Placeholder tree view for the coderTasks container when not authenticated. // Works around a Cursor bug where containers with all views hidden via `when` @@ -356,6 +364,10 @@ async function doActivate( commands.switchDeployment.bind(commands), ); commandManager.register("coder.open", commands.open.bind(commands)); + commandManager.register( + "coder.openInAgentsWindow", + commands.openInAgentsWindow.bind(commands), + ); commandManager.register( "coder.openDevContainer", commands.openDevContainer.bind(commands), diff --git a/src/instrumentation/EVENTS.md b/src/instrumentation/EVENTS.md index bc1eb3d18a..39c3e4fad5 100644 --- a/src/instrumentation/EVENTS.md +++ b/src/instrumentation/EVENTS.md @@ -6,18 +6,18 @@ new ones live in `CONVENTIONS.md`. ## Event index -| Category | Events | -| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Activation](#activation) | `activation`, `activation.deployment_init` | -| [Auth](#auth) | `auth.login`, `auth.logout`, `auth.login_prompted`, `auth.token_refresh.completed`, `auth.unauthorized_intercepted`, `auth.session_lookup`, `auth.credential.store`, `auth.credential.clear`, `auth.token_refresh.deduped` | -| [CLI](#cli) | `cli.resolve`, `cli.download`, `cli.configure` | -| [Commands](#commands) | `command.invoked`, `command.diagnostic.completed` | -| [Deployment](#deployment) | `deployment.suspended`, `deployment.recovered`, `deployment.cross_window.detected`, `deployment.auth_config.recovery_failed` | -| [Remote setup](#remote-setup) | `remote.setup` | -| [SSH](#ssh) | `ssh.process.discovered`, `ssh.process.lost`, `ssh.process.recovered`, `ssh.process.replaced`, `ssh.process.disposed`, `ssh.network.sampled` | -| [HTTP](#http) | `http.requests` | -| [WebSocket connections](#websocket-connections) | `connection.state_transitioned`, `connection.opened`, `connection.dropped`, `connection.reconnect_resolved`, `connection.unreachable` | -| [Workspace](#workspace) | `workspace.{start,stop,restart,update,delete}.triggered`, `workspace.start.prompted`, `workspace.update.prompted`, `workspace.open`, `workspace.picker.prompted`, `workspace.dev_container.open`, `workspace.state_transitioned`, `workspace.agent.state_transitioned` | +| Category | Events | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [Activation](#activation) | `activation`, `activation.deployment_init` | +| [Auth](#auth) | `auth.login`, `auth.logout`, `auth.login_prompted`, `auth.token_refresh.completed`, `auth.unauthorized_intercepted`, `auth.session_lookup`, `auth.credential.store`, `auth.credential.clear`, `auth.token_refresh.deduped` | +| [CLI](#cli) | `cli.resolve`, `cli.download`, `cli.configure` | +| [Commands](#commands) | `command.invoked`, `command.diagnostic.completed` | +| [Deployment](#deployment) | `deployment.suspended`, `deployment.recovered`, `deployment.cross_window.detected`, `deployment.auth_config.recovery_failed` | +| [Remote setup](#remote-setup) | `remote.setup` | +| [SSH](#ssh) | `ssh.process.discovered`, `ssh.process.lost`, `ssh.process.recovered`, `ssh.process.replaced`, `ssh.process.disposed`, `ssh.network.sampled` | +| [HTTP](#http) | `http.requests` | +| [WebSocket connections](#websocket-connections) | `connection.state_transitioned`, `connection.opened`, `connection.dropped`, `connection.reconnect_resolved`, `connection.unreachable` | +| [Workspace](#workspace) | `workspace.{start,stop,restart,update,delete}.triggered`, `workspace.start.prompted`, `workspace.update.prompted`, `workspace.open`, `workspace.picker.prompted`, `workspace.dev_container.open`, `workspace.agents_window.open`, `workspace.state_transitioned`, `workspace.agent.state_transitioned` | Signal kinds, which each category groups its events by: @@ -485,7 +485,7 @@ resets on a successful open, so a later outage emits again. ## Workspace Emitted by `WorkspaceOperationTelemetry` (start, stop, restart, update, delete), -`WorkspaceOpenTelemetry` (open, picker, dev container), and +`WorkspaceOpenTelemetry` (open, picker, dev container, Agents window), and `recordWorkspaceState` / `recordAgentState` (the state-transition events, from transitions detected by `WorkspaceStateObserver` / `WorkspaceAgentObserver`). @@ -550,6 +550,23 @@ Opening a workspace from any entry point. | `mode` | `dev_container`, `attached_container` | | `error.type` | `error` | +#### `workspace.agents_window.open` + +Opening a workspace in the VS Code Agents window: starting it if needed, +writing its SSH config, and handing it to the Agents window. + +| Attribute | Values | +| --------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| `workspace_status`, `workspace_outdated`, `agent_status`, `agent_lifecycle_state` | as in `workspace.open` | +| `handoff` | `folder`, `empty_window` (whether the Agents window got a folder) | +| `abort_stage` | `workspace_picker`, `agent_picker`, `start_prompt`, `recent_folder_picker` | +| `error.type` | `fetch_error`, `error` | +| `agent.count`, `agent.connected_count` (measurements) | as in `workspace.open` | + +Phases (`workspace.agents_window.open.`): `cli_resolve`, +`compatibility_check`, `cli_configure`, `workspace_monitor_setup`, +`workspace_ready`, `ssh_config_write`. + ### Logs Both state-transition events are sampled from the workspace event stream, so diff --git a/src/instrumentation/workspaceOpen.ts b/src/instrumentation/workspaceOpen.ts index 1a84ae4e59..61d8009dea 100644 --- a/src/instrumentation/workspaceOpen.ts +++ b/src/instrumentation/workspaceOpen.ts @@ -11,6 +11,8 @@ import type { CallerProperties } from "../telemetry/event"; import type { TelemetryReporter } from "../telemetry/reporter"; import type { Span } from "../telemetry/span"; +import type { RemoteSetupPhase } from "./remoteSetup"; + export type WorkspaceOpenSource = | "command" | "sidebar_agent" @@ -32,7 +34,18 @@ export type DevContainerMode = "dev_container" | "attached_container"; export type WorkspaceOpenAbortStage = | "workspace_picker" | "agent_picker" - | "recent_folder_picker"; + | "recent_folder_picker" + | "start_prompt"; +/** `remote.setup` phases that opening in the Agents window shares. */ +export type AgentsWindowPhase = Extract< + RemoteSetupPhase, + | "cli_resolve" + | "compatibility_check" + | "cli_configure" + | "workspace_monitor_setup" + | "workspace_ready" + | "ssh_config_write" +>; export interface WorkspaceOpenSelection { readonly workspace: Workspace; @@ -53,9 +66,14 @@ export interface WorkspaceOpenTrace { handoff(kind: "folder" | "empty_window"): void; } +export interface AgentsWindowOpenTrace extends WorkspaceOpenTrace { + phase(name: AgentsWindowPhase, fn: () => Promise): Promise; +} + /** * Emits the spans around opening a workspace: `workspace.open`, - * `workspace.picker.prompted`, and `workspace.dev_container.open`. + * `workspace.picker.prompted`, `workspace.dev_container.open`, and + * `workspace.agents_window.open`. */ export class WorkspaceOpenTelemetry { public constructor(private readonly telemetry: TelemetryReporter) {} @@ -65,22 +83,13 @@ export class WorkspaceOpenTelemetry { selection: WorkspaceOpenSelection | undefined, fn: (trace: WorkspaceOpenTrace) => Promise, ): Promise { - return this.traceRethrowing( - "workspace.open", - { source }, - false, - async (span) => { - const trace = new SpanWorkspaceOpenTrace(span); - if (selection) { - trace.select(selection); - } - const opened = await fn(trace); - if (!opened) { - span.markAborted(); - } - return opened; - }, - ); + return this.traceOpening("workspace.open", { source }, (span) => { + const trace = new SpanWorkspaceOpenTrace(span); + if (selection) { + trace.select(selection); + } + return fn(trace); + }); } public tracePicker( @@ -106,6 +115,29 @@ export class WorkspaceOpenTelemetry { ); } + public traceAgentsWindow( + fn: (trace: AgentsWindowOpenTrace) => Promise, + ): Promise { + return this.traceOpening("workspace.agents_window.open", {}, (span) => + fn(new SpanAgentsWindowOpenTrace(span)), + ); + } + + /** Like {@link traceRethrowing}, marking the span aborted when nothing opened. */ + private traceOpening( + eventName: string, + properties: CallerProperties, + fn: (span: Span) => Promise, + ): Promise { + return this.traceRethrowing(eventName, properties, false, async (span) => { + const opened = await fn(span); + if (!opened) { + span.markAborted(); + } + return opened; + }); + } + /** * Runs `fn` inside the span, recording a thrown abort as `aborted` and any * other error as a categorized error without its raw details, then rethrows @@ -156,7 +188,7 @@ class SpanWorkspacePickerTrace implements WorkspacePickerTrace { } class SpanWorkspaceOpenTrace implements WorkspaceOpenTrace { - public constructor(private readonly span: Span) {} + public constructor(protected readonly span: Span) {} public select(selection: WorkspaceOpenSelection): void { recordWorkspaceContext(this.span, selection.workspace, selection.agent); @@ -181,6 +213,15 @@ class SpanWorkspaceOpenTrace implements WorkspaceOpenTrace { } } +class SpanAgentsWindowOpenTrace + extends SpanWorkspaceOpenTrace + implements AgentsWindowOpenTrace +{ + public phase(name: AgentsWindowPhase, fn: () => Promise): Promise { + return this.span.phase(name, fn); + } +} + function recordWorkspaceContext( span: Span, workspace: Workspace, diff --git a/src/remote/agentsWindowConnection.ts b/src/remote/agentsWindowConnection.ts new file mode 100644 index 0000000000..f3c6650001 --- /dev/null +++ b/src/remote/agentsWindowConnection.ts @@ -0,0 +1,107 @@ +import { findAgent } from "../api/models"; +import { WorkspaceMonitor } from "../workspace/workspaceMonitor"; + +import { parseRemoteAuthority } from "./authority"; +import { WorkspaceStateMachine } from "./workspaceStateMachine"; + +import type { + Workspace, + WorkspaceAgent, +} from "coder/site/src/api/typesGenerated"; + +import type { CoderApi } from "../api/coderApi"; +import type { ServiceContainer } from "../container"; +import type { AgentsWindowOpenTrace } from "../instrumentation/workspaceOpen"; + +import type { ConnectionSetup } from "./connectionSetup"; + +export interface AgentsWindowConnectionOptions { + client: CoderApi; + baseUrl: string; + workspace: Workspace; + remoteAuthority: string; + connectionSetup: ConnectionSetup; + serviceContainer: ServiceContainer; + trace: AgentsWindowOpenTrace; +} + +/** + * Start the workspace if needed and write the SSH config the Agents window + * connects with. The Agents window has no Remote-SSH and runs plain `ssh` + * against `~/.ssh/config`, so the config goes there. + * + * Returns the workspace and agent once the agent is ready. + */ +export async function prepareAgentsWindowConnection( + options: AgentsWindowConnectionOptions, +): Promise<{ workspace: Workspace; agent: WorkspaceAgent }> { + const { baseUrl, client, connectionSetup, serviceContainer, trace } = options; + const parts = parseRemoteAuthority(options.remoteAuthority); + if (!parts) { + throw new Error(`Not a Coder remote authority: ${options.remoteAuthority}`); + } + + const binaryPath = await trace.phase("cli_resolve", () => + connectionSetup.resolveBinary(client), + ); + const { serverFeatures, cliAuth, sessionApp } = await trace.phase( + "compatibility_check", + () => + connectionSetup.checkCompatibility({ + workspaceClient: client, + binaryPath, + baseUrl, + safeHostname: parts.safeHostname, + }), + ); + await trace.phase("cli_configure", () => + serviceContainer + .getCliManager() + .configure(baseUrl, client.getSessionToken() ?? ""), + ); + + const monitor = await trace.phase("workspace_monitor_setup", () => + WorkspaceMonitor.create(options.workspace, client, serviceContainer), + ); + const stateMachine = new WorkspaceStateMachine( + parts, + client, + "none", + binaryPath, + serverFeatures, + cliAuth, + serviceContainer, + ); + let workspace: Workspace; + try { + workspace = await trace.phase("workspace_ready", () => + connectionSetup.waitForWorkspaceReady( + options.workspace, + monitor, + stateMachine, + ), + ); + } finally { + stateMachine.dispose(); + monitor.dispose(); + } + const agentId = stateMachine.getAgentId(); + const agent = agentId ? findAgent(workspace, agentId) : undefined; + if (!agent) { + throw new Error("Failed to get workspace or agent from state machine"); + } + + await trace.phase("ssh_config_write", () => + connectionSetup.writeSshConfig({ + workspaceClient: client, + parts, + binaryPath, + logDir: serviceContainer.getPathResolver().getProxyLogPath(), + cliAuth, + sessionApp, + configFile: undefined, + sshPath: undefined, + }), + ); + return { workspace, agent }; +} diff --git a/src/remote/workspaceStateMachine.ts b/src/remote/workspaceStateMachine.ts index 8e3613355e..6397e120b6 100644 --- a/src/remote/workspaceStateMachine.ts +++ b/src/remote/workspaceStateMachine.ts @@ -33,6 +33,14 @@ import type { StartupMode } from "../storage/mementoManager"; import type { AuthorityParts } from "./authority"; +/** Thrown when the user dismisses the prompt to start a stopped workspace. */ +export class WorkspaceStartCancelledError extends Error { + constructor() { + super("Workspace start cancelled"); + this.name = "WorkspaceStartCancelledError"; + } +} + /** * Manages workspace and agent state transitions until ready for SSH connection. * Streams build and agent logs, and handles socket lifecycle. @@ -126,7 +134,7 @@ export class WorkspaceStateMachine implements vscode.Disposable { workspace.outdated, ); if (!choice) { - throw new Error(`Workspace start cancelled`); + throw new WorkspaceStartCancelledError(); } this.startupMode = choice; } diff --git a/src/vscode/agentsWindow.ts b/src/vscode/agentsWindow.ts index 40603a1b56..5e393caa4f 100644 --- a/src/vscode/agentsWindow.ts +++ b/src/vscode/agentsWindow.ts @@ -16,3 +16,23 @@ export function isAgentsWindow(): boolean { path.posix.basename(workspaceFile.path) === AGENTS_WINDOW_WORKSPACE_FILE ); } + +/** Missing in VS Code versions and forks without the Agents window. */ +const OPEN_AGENTS_WINDOW_COMMAND = "workbench.action.openAgentsWindow"; + +/** Whether this editor can open the Agents window. */ +export async function canOpenAgentsWindow(): Promise { + const commands = await vscode.commands.getCommands(true); + return commands.includes(OPEN_AGENTS_WINDOW_COMMAND); +} + +/** Open the Agents window on `folderUri`, or on its last folder when undefined. */ +export async function openAgentsWindow( + folderUri: vscode.Uri | undefined, +): Promise { + // Without `reveal`, an Agents window that is already open ignores the folder. + await vscode.commands.executeCommand(OPEN_AGENTS_WINDOW_COMMAND, { + folderUri, + reveal: "new", + }); +} diff --git a/src/vscode/commandManager.ts b/src/vscode/commandManager.ts index a83a87a66b..acfaaffebf 100644 --- a/src/vscode/commandManager.ts +++ b/src/vscode/commandManager.ts @@ -17,6 +17,7 @@ export const CODER_COMMAND_IDS = [ "coder.open", "coder.openDevContainer", "coder.openFromSidebar", + "coder.openInAgentsWindow", "coder.openAppStatus", "coder.workspace.update", "coder.createWorkspace", diff --git a/src/vscode/contextManager.ts b/src/vscode/contextManager.ts index c8ab30ad41..c20a8feb63 100644 --- a/src/vscode/contextManager.ts +++ b/src/vscode/contextManager.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode"; const CONTEXT_DEFAULTS = { + "coder.agentsWindowSupported": false, "coder.authenticated": false, "coder.isOwner": false, "coder.loaded": false, diff --git a/test/mocks/commands.ts b/test/mocks/commands.ts index b35d25f194..5c5327caff 100644 --- a/test/mocks/commands.ts +++ b/test/mocks/commands.ts @@ -9,6 +9,7 @@ import { createMockLogger } from "./testHelpers"; import type { CoderApi } from "@/api/coderApi"; import type { ServiceContainer } from "@/container"; import type { DeploymentManager } from "@/deployment/deploymentManager"; +import type { ConnectionSetup } from "@/remote/connectionSetup"; /** Build `Commands`; services left unnamed stand in as empty objects. */ export function createTestCommands( @@ -33,5 +34,6 @@ export function createTestCommands( }), createTestCoderApi({ baseUrl: options.baseUrl, overrides: options.client }), {} as DeploymentManager, + {} as ConnectionSetup, ); } diff --git a/test/unit/commands.netcheck.test.ts b/test/unit/commands.netcheck.test.ts index 040dcc116e..cd5e8db3b5 100644 --- a/test/unit/commands.netcheck.test.ts +++ b/test/unit/commands.netcheck.test.ts @@ -10,6 +10,7 @@ import { createMockLogger, MockUserInteraction } from "../mocks/testHelpers"; import type { ServiceContainer } from "@/container"; import type { DeploymentManager } from "@/deployment/deploymentManager"; +import type { ConnectionSetup } from "@/remote/connectionSetup"; import type { NetcheckPanelFactory } from "@/webviews/netcheck/netcheckPanelFactory"; vi.mock("@/workspace/workspacesProvider", () => ({ @@ -39,6 +40,7 @@ function setup(options: { extensionBaseUrl?: string } = {}) { serviceContainer, createTestCoderApi({ baseUrl: options.extensionBaseUrl }), {} as DeploymentManager, + {} as ConnectionSetup, ); return { commands, sink }; diff --git a/test/unit/commands.openInAgentsWindow.test.ts b/test/unit/commands.openInAgentsWindow.test.ts new file mode 100644 index 0000000000..ef3e2a7df0 --- /dev/null +++ b/test/unit/commands.openInAgentsWindow.test.ts @@ -0,0 +1,180 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; + +import { prepareAgentsWindowConnection } from "@/remote/agentsWindowConnection"; +import { WorkspaceStartCancelledError } from "@/remote/workspaceStateMachine"; + +import { + agent as createAgent, + resource as createResource, + workspace as createWorkspace, +} from "@repo/mocks"; + +import { createTestCommands } from "../mocks/commands"; +import { createTelemetryHarness } from "../mocks/telemetry"; +import { + MockConfigurationProvider, + mockRecentlyOpened, + useEditor, +} from "../mocks/testHelpers"; + +import type { + Workspace, + WorkspaceAgent, +} from "coder/site/src/api/typesGenerated"; + +vi.mock("@/remote/agentsWindowConnection", () => ({ + prepareAgentsWindowConnection: vi.fn(), +})); +vi.mock("@/workspace/workspacesProvider", () => ({ + AgentTreeItem: class {}, + WorkspaceTreeItem: class {}, +})); + +const BASE_URL = "https://dev.coder.com"; +const AUTHORITY = "ssh-remote+coder-vscode.dev.coder.com--foo--bar.main"; +const FOLDER = "/home/foo/project"; + +function workspaceWith(agent: Partial = {}): Workspace { + return createWorkspace({ + owner_name: "foo", + name: "bar", + latest_build: { + resources: [ + createResource({ agents: [createAgent({ name: "main", ...agent })] }), + ], + }, + }); +} + +/** Stand in for the workspace picker, selecting the first workspace it lists. */ +function selectFirstWorkspace(): void { + let onValue: (value: string) => void = () => {}; + let onSelect: (items: readonly vscode.QuickPickItem[]) => void = () => {}; + const quickPick = { + value: "", + items: [] as readonly vscode.QuickPickItem[], + onDidChangeValue: (cb: typeof onValue) => { + onValue = cb; + return { dispose: vi.fn() }; + }, + onDidChangeSelection: (cb: typeof onSelect) => { + onSelect = cb; + return { dispose: vi.fn() }; + }, + onDidHide: () => ({ dispose: vi.fn() }), + show: () => onValue(quickPick.value), + dispose: vi.fn(), + }; + vi.mocked(vscode.window.createQuickPick).mockReturnValue( + quickPick as unknown as vscode.QuickPick, + ); + void vi + .waitFor(() => expect(quickPick.items).toHaveLength(1)) + .then(() => onSelect(quickPick.items)); +} + +/** Run the command with the workspace the connection reports ready, or its error. */ +async function openInAgentsWindow( + ready: Workspace | Error, + recents: string[] = [], +) { + new MockConfigurationProvider(); + mockRecentlyOpened(recents, FOLDER); + selectFirstWorkspace(); + const picked = workspaceWith(); + if (ready instanceof Error) { + vi.mocked(prepareAgentsWindowConnection).mockRejectedValue(ready); + } else { + vi.mocked(prepareAgentsWindowConnection).mockResolvedValue({ + workspace: ready, + agent: ready.latest_build.resources[0].agents![0], + }); + } + const { sink, service } = createTelemetryHarness(); + const commands = createTestCommands({ + baseUrl: BASE_URL, + services: { getTelemetryService: service }, + client: { + getWorkspaces: vi + .fn() + .mockResolvedValue({ workspaces: [picked], count: 1 }), + }, + }); + const opened = await commands.openInAgentsWindow(); + const [event] = sink.eventsNamed("workspace.agents_window.open"); + return { opened, event }; +} + +function agentsWindowCall(): unknown { + return vi + .mocked(vscode.commands.executeCommand) + .mock.calls.find( + ([command]) => command === "workbench.action.openAgentsWindow", + )?.[1]; +} + +describe("openInAgentsWindow", () => { + beforeEach(() => { + vi.clearAllMocks(); + useEditor("vscode"); + }); + + it("opens the template's directory on the workspace's host", async () => { + const { opened, event } = await openInAgentsWindow( + workspaceWith({ expanded_directory: FOLDER }), + ); + + expect(opened).toBe(true); + expect(prepareAgentsWindowConnection).toHaveBeenCalledWith( + expect.objectContaining({ remoteAuthority: AUTHORITY }), + ); + expect(agentsWindowCall()).toEqual({ + folderUri: expect.objectContaining({ + scheme: "vscode-remote", + authority: AUTHORITY, + path: FOLDER, + }), + reveal: "new", + }); + expect(event.properties).toMatchObject({ + result: "success", + handoff: "folder", + }); + }); + + it("falls back to the folder last opened on the workspace", async () => { + await openInAgentsWindow(workspaceWith(), [AUTHORITY]); + + expect(agentsWindowCall()).toMatchObject({ + folderUri: expect.objectContaining({ path: FOLDER }), + }); + }); + + it("warns and opens without a folder when there is none", async () => { + const { opened, event } = await openInAgentsWindow(workspaceWith()); + + expect(opened).toBe(true); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + expect.stringContaining("foo/bar sets no directory"), + ); + expect(agentsWindowCall()).toEqual({ + folderUri: undefined, + reveal: "new", + }); + expect(event.properties).toMatchObject({ handoff: "empty_window" }); + }); + + it("aborts without an error when the start prompt is dismissed", async () => { + const { opened, event } = await openInAgentsWindow( + new WorkspaceStartCancelledError(), + ); + + expect(opened).toBe(false); + expect(agentsWindowCall()).toBeUndefined(); + expect(event.properties).toMatchObject({ + result: "aborted", + abort_stage: "start_prompt", + }); + }); +}); diff --git a/test/unit/commands.supportBundle.test.ts b/test/unit/commands.supportBundle.test.ts index 903749a22d..bebf3541c5 100644 --- a/test/unit/commands.supportBundle.test.ts +++ b/test/unit/commands.supportBundle.test.ts @@ -24,6 +24,7 @@ import { import type { CoderApi } from "@/api/coderApi"; import type { ServiceContainer } from "@/container"; import type { DeploymentManager } from "@/deployment/deploymentManager"; +import type { ConnectionSetup } from "@/remote/connectionSetup"; vi.mock("@/cli/cliExec", async (importOriginal) => { const actual = await importOriginal(); @@ -118,6 +119,7 @@ function setup(options: { cliVersion?: string } = {}) { serviceContainer, client, {} as DeploymentManager, + {} as ConnectionSetup, ); return { commands, client, logger, interaction, sink }; diff --git a/test/unit/commands.telemetry.test.ts b/test/unit/commands.telemetry.test.ts index 331d9ddc1f..0d00b00d0c 100644 --- a/test/unit/commands.telemetry.test.ts +++ b/test/unit/commands.telemetry.test.ts @@ -16,6 +16,7 @@ import type { ServiceContainer } from "@/container"; import type { DeploymentManager } from "@/deployment/deploymentManager"; import type { Deployment } from "@/deployment/types"; import type { LoginCoordinator, LoginResult } from "@/login/loginCoordinator"; +import type { ConnectionSetup } from "@/remote/connectionSetup"; import type { MementoManager } from "@/storage/mementoManager"; import type { PathResolver } from "@/storage/pathResolver"; import type { SecretsManager, SessionAuth } from "@/storage/secretsManager"; @@ -128,6 +129,7 @@ function setup(options: SetupOptions = {}) { serviceContainer, extensionClient, deploymentManager as DeploymentManager, + {} as ConnectionSetup, ); return { diff --git a/test/unit/remote/agentsWindowConnection.test.ts b/test/unit/remote/agentsWindowConnection.test.ts new file mode 100644 index 0000000000..3dd717146d --- /dev/null +++ b/test/unit/remote/agentsWindowConnection.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from "vitest"; + +import { prepareAgentsWindowConnection } from "@/remote/agentsWindowConnection"; +import { WorkspaceStateMachine } from "@/remote/workspaceStateMachine"; +import { PathResolver } from "@/storage/pathResolver"; +import { WorkspaceMonitor } from "@/workspace/workspaceMonitor"; + +import { + agent as createAgent, + resource as createResource, + workspace as createWorkspace, +} from "@repo/mocks"; + +import { createTestCoderApi } from "../../mocks/coderApi"; +import { + createMockServiceContainer, + MockConfigurationProvider, +} from "../../mocks/testHelpers"; + +import type { CliManager } from "@/cli/cliManager"; +import type { AgentsWindowOpenTrace } from "@/instrumentation/workspaceOpen"; +import type { ConnectionSetup } from "@/remote/connectionSetup"; + +vi.mock("@/workspace/workspaceMonitor", () => ({ + WorkspaceMonitor: { create: vi.fn() }, +})); +vi.mock("@/remote/workspaceStateMachine", () => ({ + WorkspaceStateMachine: vi.fn(), +})); + +const AUTHORITY = "ssh-remote+coder-vscode.dev.coder.com--foo--bar.main"; + +describe("prepareAgentsWindowConnection", () => { + it("starts on prompt and writes the SSH config plain ssh reads", async () => { + new MockConfigurationProvider(); + const agent = createAgent({ id: "agent-1", name: "main" }); + const workspace = createWorkspace({ + owner_name: "foo", + name: "bar", + latest_build: { resources: [createResource({ agents: [agent] })] }, + }); + const monitor = { dispose: vi.fn() }; + vi.mocked(WorkspaceMonitor.create).mockResolvedValue( + monitor as unknown as WorkspaceMonitor, + ); + vi.mocked(WorkspaceStateMachine).mockImplementation(function () { + return { getAgentId: () => agent.id, dispose: vi.fn() }; + }); + const connectionSetup = { + resolveBinary: vi.fn().mockResolvedValue("/bin/coder"), + checkCompatibility: vi.fn().mockResolvedValue({ + serverFeatures: {}, + cliAuth: {}, + sessionApp: "vscode", + }), + waitForWorkspaceReady: vi.fn().mockResolvedValue(workspace), + writeSshConfig: vi.fn().mockResolvedValue({}), + }; + const trace = { + phase: (_name: string, fn: () => Promise) => fn(), + } as AgentsWindowOpenTrace; + + const ready = await prepareAgentsWindowConnection({ + client: createTestCoderApi({ baseUrl: "https://dev.coder.com" }), + baseUrl: "https://dev.coder.com", + workspace, + remoteAuthority: AUTHORITY, + connectionSetup: connectionSetup as unknown as ConnectionSetup, + serviceContainer: createMockServiceContainer({ + cliManager: { configure: vi.fn() } as unknown as CliManager, + pathResolver: new PathResolver("/mock/global", "/mock/log"), + }), + trace, + }); + + expect(ready).toEqual({ workspace, agent }); + expect(vi.mocked(WorkspaceStateMachine).mock.calls[0][2]).toBe("none"); + expect(monitor.dispose).toHaveBeenCalled(); + expect(connectionSetup.writeSshConfig).toHaveBeenCalledWith( + expect.objectContaining({ configFile: undefined, sshPath: undefined }), + ); + }); +}); diff --git a/test/unit/remote/workspaceStateMachine.test.ts b/test/unit/remote/workspaceStateMachine.test.ts index 06b718b138..3db829d935 100644 --- a/test/unit/remote/workspaceStateMachine.test.ts +++ b/test/unit/remote/workspaceStateMachine.test.ts @@ -11,7 +11,10 @@ import { streamBuildLogs, streamAgentLogs, } from "@/api/workspace"; -import { WorkspaceStateMachine } from "@/remote/workspaceStateMachine"; +import { + WorkspaceStartCancelledError, + WorkspaceStateMachine, +} from "@/remote/workspaceStateMachine"; import { maybeAskAgent } from "@/ui/prompts"; import { @@ -343,7 +346,7 @@ describe("WorkspaceStateMachine", () => { const ws = createWorkspace({ latest_build: { status: "stopped" } }); await expect(sm.processWorkspace(ws, progress)).rejects.toThrow( - "Workspace start cancelled", + WorkspaceStartCancelledError, ); }); }); From bee06c26a61346a8192764170137c88bdf9c5597 Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Fri, 4 Dec 2026 17:52:19 +0300 Subject: [PATCH 4/4] fix(remote): name the ssh that missed the Coder SSH config The Agents window runs ssh from PATH rather than Remote-SSH's, so the warning names the ssh that ran instead of blaming Remote-SSH. --- src/remote/connectionSetup.ts | 8 +++++--- test/unit/remote/connectionSetup.test.ts | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/remote/connectionSetup.ts b/src/remote/connectionSetup.ts index d9077ac46d..563baa3646 100644 --- a/src/remote/connectionSetup.ts +++ b/src/remote/connectionSetup.ts @@ -367,7 +367,7 @@ export class ConnectionSetup { return await resolveSshProperties(sshPath, parts.sshHost, configFile); } catch (error) { if (error instanceof SshProxyCommandMissingError) { - this.warnCoderSshConfigNotRead(include.dir, error.configFiles); + this.warnCoderSshConfigNotRead(sshPath, include.dir, error.configFiles); } this.logger.warn("ssh -G failed, parsing the SSH config instead", error); return computeSshProperties( @@ -377,15 +377,17 @@ export class ConnectionSetup { } } - /** Remote-SSH's ssh ran but missed the include, so the connection will fail. */ + /** ssh ran but missed the include, so the connection will fail. */ private warnCoderSshConfigNotRead( + sshPath: string | undefined, includeDir: string, configFiles: string[], ): void { + const ssh = sshPath ? `The ssh at ${sshPath}` : "The ssh on your PATH"; const read = configFiles.join(", ") || "no SSH config"; void vscode.window.showWarningMessage( escapeNotificationLinks( - `Remote-SSH's ssh did not read the Coder SSH config in ${includeDir}, so it cannot reach Coder workspaces. It read ${read}. Check which ssh Remote-SSH uses and its home directory.`, + `${ssh} did not read the Coder SSH config in ${includeDir}, so it cannot reach Coder workspaces. It read ${read}. Check which ssh runs and which home directory it uses.`, ), ); } diff --git a/test/unit/remote/connectionSetup.test.ts b/test/unit/remote/connectionSetup.test.ts index 8801f4d2f2..d6c892d8fa 100644 --- a/test/unit/remote/connectionSetup.test.ts +++ b/test/unit/remote/connectionSetup.test.ts @@ -323,7 +323,7 @@ describe("session app", () => { "/mock/log", ).getSshConfigDir(); expect(message).toContain( - `did not read the Coder SSH config in ${includeDir}`, + `The ssh on your PATH did not read the Coder SSH config in ${includeDir}`, ); expect(message).toContain(read); },