From cfe78df67556855b1cf67d47996f0f7f56cc66fd Mon Sep 17 00:00:00 2001 From: Christof Marti Date: Sat, 28 Nov 2026 16:15:15 +0100 Subject: [PATCH 1/2] agentHost: opt into client forwarding with a CLI flag The Dev Container launcher turned on client forwarding by prefixing the spawn command with VSCODE_AGENT_HOST_CLIENT_FORWARDING=1. That was implicit, and since the launcher reuses a running Agent Host of the same quality, it could pick one started without forwarding, for example by a remote editor's server. `code agent host --client-forwarding` now records `clientForwarding` in the Agent Host's endpoint registry entry and sets the variable for its server only with the flag, removing it otherwise. The launcher passes the flag and reuses only Agent Hosts started with it. The client's own CLI, the latest CLI of dev builds and fallback CLIs from 1.149 on have the flag; with an older fallback CLI, the Agent Host does not forward. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- cli/src/commands/agent_host.rs | 57 +++++++++++++++- cli/src/commands/agent_relay.rs | 1 + cli/src/commands/args.rs | 20 +++++- cli/src/tunnels/agent_host.rs | 68 ++++++++++++++++--- cli/src/tunnels/agent_host_registry.rs | 27 ++++++++ src/vs/platform/agentHost/LOCAL_ENDPOINT.md | 1 + .../common/agentHostEndpointRegistry.ts | 10 ++- .../node/agentHostClientForwarding.ts | 5 +- .../node/devContainerAgentHostService.ts | 14 ++-- .../node/remoteAgentHostCliInstaller.ts | 12 ++-- .../agentHost/node/serviceBootstrapping.md | 2 +- .../node/sshRemoteAgentHostHelpers.ts | 27 +++++++- .../node/agentHostEndpointRegistry.test.ts | 10 +++ .../node/devContainerAgentHostService.test.ts | 46 +++++++++++-- .../node/sshRemoteAgentHostHelpers.test.ts | 34 ++++++++-- .../REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md | 2 +- 16 files changed, 295 insertions(+), 41 deletions(-) diff --git a/cli/src/commands/agent_host.rs b/cli/src/commands/agent_host.rs index 4280f5c39df009..dcd7cb950c5a0e 100644 --- a/cli/src/commands/agent_host.rs +++ b/cli/src/commands/agent_host.rs @@ -133,6 +133,7 @@ fn decide_foreground_action( port, token, instance_id, + client_forwarding, } = decision else { return ForegroundAction::SpawnFresh; @@ -148,7 +149,13 @@ fn decide_foreground_action( // matches the running supervisor. If it differs, error out with a // clear message instead of silently sharing a differently-bound // supervisor. - if let Some(conflict) = detect_config_conflict(args, host.as_deref(), port, token.as_deref()) { + if let Some(conflict) = detect_config_conflict( + args, + host.as_deref(), + port, + token.as_deref(), + client_forwarding, + ) { return ForegroundAction::ConflictError(format!( "Agent host already running on {host_str}:{port} (PID {pid}), but {conflict}.\n\ Use `{application_name} agent kill` to stop it, or pass `--replace` to take over.", @@ -325,6 +332,7 @@ async fn run_supervisor(mut ctx: CommandContext, mut args: AgentHostArgs) -> Res without_connection_token: true, connection_token: None, connection_token_file: None, + client_forwarding: args.client_forwarding, }, // The backend counts as activity while it runs, so the idle timeout // can't kill agent sessions that are still working after the last @@ -769,12 +777,22 @@ fn print_manage_banner_line() { /// `running_host` may be `None` when the registry entry doesn't record a /// host; in that case we conservatively skip the host comparison (the /// supervisor is most likely loopback, which is the default). +/// +/// A supervisor started with `--client-forwarding` is still compatible with +/// a request without it: it forwards only to clients offering it. fn detect_config_conflict( args: &AgentHostArgs, running_host: Option<&str>, running_port: u16, running_token: Option<&str>, + running_client_forwarding: bool, ) -> Option { + if args.client_forwarding && !running_client_forwarding { + return Some( + "--client-forwarding conflicts with the running supervisor (started without it)" + .to_string(), + ); + } if let (Some(requested), Some(running)) = (args.host.as_deref(), running_host) { if requested != running { return Some(format!( @@ -1504,12 +1522,17 @@ mod tests { } fn reusable_decision() -> AgentHostReuseDecision { + reusable_decision_with_client_forwarding(false) + } + + fn reusable_decision_with_client_forwarding(client_forwarding: bool) -> AgentHostReuseDecision { AgentHostReuseDecision::Reuse { pid: 4242, host: Some("127.0.0.1".to_string()), port: 9000, token: Some("tok".to_string()), instance_id: "instance-existing".to_string(), + client_forwarding, } } @@ -1592,6 +1615,36 @@ mod tests { } } + #[test] + fn decide_foreground_action_reuses_for_client_forwarding_only_a_forwarding_supervisor() { + let forwarding_args = AgentHostArgs { + client_forwarding: true, + ..Default::default() + }; + let actions = [ + decide_foreground_action(&forwarding_args, reusable_decision()), + decide_foreground_action( + &forwarding_args, + reusable_decision_with_client_forwarding(true), + ), + decide_foreground_action( + &AgentHostArgs::default(), + reusable_decision_with_client_forwarding(true), + ), + ]; + assert!( + matches!( + &actions, + [ + ForegroundAction::ConflictError(message), + ForegroundAction::ReuseBanner { .. }, + ForegroundAction::ReuseBanner { .. }, + ] if message.contains("--client-forwarding") + ), + "{actions:?}" + ); + } + /// The core `--new-instance` contract: it must win over every other /// branch, in particular `--replace`'s kill path, so that passing /// both flags together can never remove an existing entry. @@ -1668,6 +1721,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, }; agent_host_registry::publish_agent_host_endpoint(&log, &user_data_path, &editor).unwrap(); @@ -1696,6 +1750,7 @@ mod tests { port: standalone_port, token: Some("standalone-tok".to_string()), instance_id: "standalone-existing".to_string(), + client_forwarding: false, } ); assert_eq!( diff --git a/cli/src/commands/agent_relay.rs b/cli/src/commands/agent_relay.rs index 2cec653b7b7f95..03d0e84255c8ec 100644 --- a/cli/src/commands/agent_relay.rs +++ b/cli/src/commands/agent_relay.rs @@ -203,6 +203,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, } } diff --git a/cli/src/commands/args.rs b/cli/src/commands/args.rs index 995a04025ed07b..f84a78b8b226ed 100644 --- a/cli/src/commands/args.rs +++ b/cli/src/commands/args.rs @@ -295,13 +295,22 @@ pub struct AgentHostArgs { #[clap(long)] pub foreground: bool, + /// Forward what clients offer, such as their Git credentials and SSH and + /// GPG agents, to the processes the agent host starts. Recorded in the + /// agent host's registry entry; an existing agent host is only reused + /// when it was started with this flag too. Used by the Dev Container + /// launcher. + #[clap(long, hide = true)] + pub client_forwarding: bool, + /// Alias for `code tunnel`: expose remote editor and agent host access. #[clap( long, group = "remote_host", conflicts_with_all = [ "host", "port", "connection_token", "connection_token_file", - "without_connection_token", "replace", "new_instance", "foreground", "idle_timeout" + "without_connection_token", "replace", "new_instance", "foreground", "idle_timeout", + "client_forwarding" ] )] pub tunnel: bool, @@ -313,7 +322,7 @@ pub struct AgentHostArgs { conflicts_with_all = [ "host", "port", "connection_token", "connection_token_file", "without_connection_token", "replace", "new_instance", "idle_timeout", - "random_name", "tunnel_id", "host_token", "cluster", "tunnel_name" + "random_name", "tunnel_id", "host_token", "cluster", "tunnel_name", "client_forwarding" ] )] pub github_environment: bool, @@ -1324,6 +1333,7 @@ mod tests { vec!["--host-token", "token"], vec!["--cluster", "cluster"], vec!["--tunnel-name", "name"], + vec!["--client-forwarding"], ] { let mut argv = command.clone(); argv.push("--github-environment"); @@ -1434,6 +1444,7 @@ mod tests { vec!["--new-instance"], vec!["--foreground"], vec!["--idle-timeout", "300"], + vec!["--client-forwarding"], ] { let mut argv = command.clone(); argv.push("--tunnel"); @@ -1463,6 +1474,7 @@ mod tests { "--foreground", "--idle-timeout", "300", + "--client-forwarding", ]); let args = parse_agent_host_args(&argv); assert_eq!( @@ -1475,6 +1487,7 @@ mod tests { args.new_instance, args.foreground, args.idle_timeout, + args.client_forwarding, ), ( false, @@ -1484,7 +1497,8 @@ mod tests { true, true, true, - Some(300) + Some(300), + true ) ); } diff --git a/cli/src/tunnels/agent_host.rs b/cli/src/tunnels/agent_host.rs index 31301dfcf9cffe..6c4878c2a4a5fe 100644 --- a/cli/src/tunnels/agent_host.rs +++ b/cli/src/tunnels/agent_host.rs @@ -63,6 +63,10 @@ pub const STARTUP_TIMEOUT: Duration = Duration::from_secs(30); /// CLI and may therefore advertise the management RPC method to clients. pub const MANAGEMENT_SOCKET_ENV: &str = "VSCODE_AGENT_HOST_MANAGEMENT_SOCKET"; const GITHUB_ENVIRONMENT_OPTIONS_ENV: &str = "VSCODE_CLI_GITHUB_ENVIRONMENT_OPTIONS"; +/// Set to `1` for the server of an agent host started with +/// `--client-forwarding`, and removed otherwise, so only the flag turns +/// forwarding on. Read and removed by the agent host the server starts. +const AGENT_HOST_CLIENT_FORWARDING_ENV: &str = "VSCODE_AGENT_HOST_CLIENT_FORWARDING"; const GITHUB_ENVIRONMENT_READY_PREFIX: &str = "__VSCODE_GITHUB_ENVIRONMENT_READY__:"; #[derive(Clone, Serialize)] @@ -130,6 +134,9 @@ pub struct AgentHostConfig { pub without_connection_token: bool, pub connection_token: Option, pub connection_token_file: Option, + /// Whether the agent host forwards what clients offer to the processes + /// it starts, see `code agent host --client-forwarding`. + pub client_forwarding: bool, } /// State of the running VS Code server process. The process itself is @@ -353,6 +360,11 @@ impl AgentHostManager { cmd.arg("--connection-token-file"); cmd.arg(ct); } + if self.config.client_forwarding { + cmd.env(AGENT_HOST_CLIENT_FORWARDING_ENV, "1"); + } else { + cmd.env_remove(AGENT_HOST_CLIENT_FORWARDING_ENV); + } cmd.env(MANAGEMENT_SOCKET_ENV, &self.management_socket_path); cmd.env_remove("VSCODE_DEV"); @@ -1263,16 +1275,19 @@ impl AgentHostSidecar { // character-equal without spuriously flagging hostname-vs-IP // equivalents as a config conflict. let host = host_label.unwrap_or_else(|| bound_addr.ip().to_string()); - let entry = AgentHostEndpointMetadata::new_standalone( - pid, - instance_id.clone(), - host, - bound_addr.port(), - public_token.clone().unwrap_or_default(), - AGENT_HOST_PROTOCOL_VERSION.to_string(), - VSCODE_CLI_QUALITY.map(str::to_string), - None, - ); + let entry = AgentHostEndpointMetadata { + client_forwarding: manager.config.client_forwarding, + ..AgentHostEndpointMetadata::new_standalone( + pid, + instance_id.clone(), + host, + bound_addr.port(), + public_token.clone().unwrap_or_default(), + AGENT_HOST_PROTOCOL_VERSION.to_string(), + VSCODE_CLI_QUALITY.map(str::to_string), + None, + ) + }; // Registry publish does blocking filesystem I/O (write a temp file and // atomically rename it into place); run it on a blocking-safe thread so @@ -1516,6 +1531,8 @@ pub enum AgentHostReuseDecision { /// This entry's stable identity within the registry, used by /// `--replace` to scope removal to exactly this instance. instance_id: String, + /// Whether the supervisor was started with `--client-forwarding`. + client_forwarding: bool, }, } @@ -1543,6 +1560,7 @@ pub async fn classify_agent_host( Some(selected.connection_token) }, instance_id: selected.instance_id, + client_forwarding: selected.client_forwarding, }, None => AgentHostReuseDecision::SpawnFresh, } @@ -2388,6 +2406,7 @@ mod tests { without_connection_token: true, connection_token: None, connection_token_file: None, + client_forwarding: false, }, activity, ) @@ -2467,6 +2486,30 @@ mod tests { assert!(!argv.contains("--user-data-dir\n")); } + #[cfg(unix)] + #[tokio::test] + async fn client_forwarding_reaches_only_the_server_of_a_forwarding_agent_host() { + let mut seen = Vec::new(); + for client_forwarding in [true, false] { + let dir = tempfile::tempdir().unwrap(); + let mut manager = make_test_manager(dir.path()); + Arc::get_mut(&mut manager).unwrap().config.client_forwarding = client_forwarding; + let env = dir.path().join("env"); + let server = start_fake_server( + &manager, + dir.path(), + &format!( + "printf '%s' \"${{{AGENT_HOST_CLIENT_FORWARDING_ENV}-unset}}\" > '{}'", + env.display() + ), + ) + .await; + server.await.unwrap(); + seen.push(std::fs::read_to_string(env).unwrap()); + } + assert_eq!(seen, ["1", "unset"]); + } + #[cfg(unix)] #[tokio::test] async fn github_environment_waits_for_remote_readiness_and_forwards_bootstrap() { @@ -3309,6 +3352,7 @@ mod tests { port, token: Some("registry-tok".to_string()), instance_id: "instance-registry".to_string(), + client_forwarding: false, } ); } @@ -3331,6 +3375,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, }; agent_host_registry::publish_agent_host_endpoint( &log::Logger::test(), @@ -3440,6 +3485,7 @@ mod tests { }, quality: Some("stable".to_string()), tunnel_name: None, + client_forwarding: false, } } @@ -3463,6 +3509,7 @@ mod tests { }, quality: Some("stable".to_string()), tunnel_name: None, + client_forwarding: false, } } @@ -3500,6 +3547,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, }; let gw: AgentHostGatewayEndpoint = (&entry).into(); assert_eq!(gw.endpoint_kind, "socket"); diff --git a/cli/src/tunnels/agent_host_registry.rs b/cli/src/tunnels/agent_host_registry.rs index 4cc22d327cd8ea..81b354565f9e92 100644 --- a/cli/src/tunnels/agent_host_registry.rs +++ b/cli/src/tunnels/agent_host_registry.rs @@ -95,6 +95,15 @@ pub struct AgentHostEndpointMetadata { pub quality: Option, #[serde(skip_serializing_if = "Option::is_none")] pub tunnel_name: Option, + /// Whether the agent host forwards what clients offer to the processes it + /// starts (`code agent host --client-forwarding`). Omitted when false, + /// and by writers that predate it. + #[serde(default, skip_serializing_if = "is_false")] + pub client_forwarding: bool, +} + +fn is_false(value: &bool) -> bool { + !*value } /// The subset of [`AgentHostEndpointMetadata`] that identifies a unique @@ -131,6 +140,7 @@ impl AgentHostEndpointMetadata { endpoint: AgentHostEndpointAddress::Tcp { host, port }, quality, tunnel_name, + client_forwarding: false, } } @@ -732,6 +742,8 @@ pub struct LiveStandaloneEndpoint { /// Empty when the standalone host was started with /// `--without-connection-token`. pub connection_token: String, + /// Whether the standalone host was started with `--client-forwarding`. + pub client_forwarding: bool, } /// Reads the registry and returns a live `standalone` `tcp` entry to reuse, if @@ -754,6 +766,7 @@ pub async fn select_live_standalone_endpoint( host, port, connection_token: e.connection_token, + client_forwarding: e.client_forwarding, }), AgentHostEndpointAddress::Socket { .. } => None, }) @@ -872,6 +885,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, }; publish_agent_host_endpoint(&log, dir.path(), &editor).unwrap(); @@ -967,6 +981,7 @@ mod tests { let mut metadata = standalone(42, "instance-a", 8080); metadata.quality = Some("insider".to_string()); metadata.tunnel_name = Some("my-tunnel".to_string()); + metadata.client_forwarding = true; let value = serde_json::to_value(&metadata).unwrap(); assert_eq!(value["schemaVersion"], 2); @@ -980,6 +995,11 @@ mod tests { assert_eq!(value["endpoint"]["port"], 8080); assert_eq!(value["quality"], "insider"); assert_eq!(value["tunnelName"], "my-tunnel"); + assert_eq!(value["clientForwarding"], true); + assert_eq!( + serde_json::from_value::(value).unwrap(), + metadata + ); } #[test] @@ -988,6 +1008,11 @@ mod tests { let value = serde_json::to_value(&metadata).unwrap(); assert!(value.get("quality").is_none()); assert!(value.get("tunnelName").is_none()); + assert!(value.get("clientForwarding").is_none()); + assert_eq!( + serde_json::from_value::(value).unwrap(), + metadata + ); } #[test] @@ -1153,6 +1178,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, }; publish_agent_host_endpoint(&log, dir.path(), &editor).unwrap(); @@ -1482,6 +1508,7 @@ mod tests { }, quality: None, tunnel_name: None, + client_forwarding: false, } } diff --git a/src/vs/platform/agentHost/LOCAL_ENDPOINT.md b/src/vs/platform/agentHost/LOCAL_ENDPOINT.md index 86b7426da05753..cb8ce75fbbe403 100644 --- a/src/vs/platform/agentHost/LOCAL_ENDPOINT.md +++ b/src/vs/platform/agentHost/LOCAL_ENDPOINT.md @@ -76,6 +76,7 @@ The legacy `metadata.json` fallback holds a JSON **array** of these same entry o | `endpoint` | Discriminated union describing how to connect: `{ "type": "socket", "path": string }` for a Windows named pipe or Unix domain socket (used by the editor today), or `{ "type": "tcp", "host": string, "port": number }` for a TCP listener (used by the standalone CLI). | | `quality` | Optional. Product quality of a standalone CLI endpoint. Not part of entry identity. | | `tunnelName` | Optional. Tunnel name associated with a standalone CLI endpoint. Not part of entry identity. | +| `clientForwarding` | Optional. `true` when a standalone CLI endpoint was started with `code agent host --client-forwarding`, so its agent host forwards what clients offer to the processes it starts; omitted otherwise. Not part of entry identity. | Readers must treat every entry and field as untrusted input: diff --git a/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts b/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts index 08b71cc28628d9..dfcc6a7f06eb56 100644 --- a/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts +++ b/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { vEnum, vLiteral, vNumber, vObj, vOptionalProp, vString, vUnion } from '../../../base/common/validation.js'; +import { vBoolean, vEnum, vLiteral, vNumber, vObj, vOptionalProp, vString, vUnion } from '../../../base/common/validation.js'; import type { RemoteAgentHostLocationPreference } from './remoteAgentHostLocationPreference.js'; /** @@ -57,6 +57,12 @@ export interface IAgentHostEndpointMetadata { readonly endpoint: AgentHostEndpointAddress; readonly quality?: string; readonly tunnelName?: string; + /** + * Whether the agent host forwards what clients offer to the processes it + * starts (`code agent host --client-forwarding`). Absent when it does not, + * and from writers that predate it. + */ + readonly clientForwarding?: boolean; } /** @@ -86,6 +92,7 @@ const entryValidator = vObj({ endpoint: endpointAddressValidator, quality: vOptionalProp(vString()), tunnelName: vOptionalProp(vString()), + clientForwarding: vOptionalProp(vBoolean()), }); /** @@ -121,6 +128,7 @@ export function parseAgentHostEndpointMetadataEntry(raw: unknown): IAgentHostEnd endpoint: content.endpoint, quality: content.quality, tunnelName: content.tunnelName, + ...(content.clientForwarding ? { clientForwarding: true } : {}), }; } diff --git a/src/vs/platform/agentHost/node/agentHostClientForwarding.ts b/src/vs/platform/agentHost/node/agentHostClientForwarding.ts index 8ef7d76fd3cbbf..697d3e450fed1e 100644 --- a/src/vs/platform/agentHost/node/agentHostClientForwarding.ts +++ b/src/vs/platform/agentHost/node/agentHostClientForwarding.ts @@ -30,7 +30,10 @@ import { SessionConfigKey } from '../common/sessionConfigKeys.js'; import { ActionType } from '../common/state/sessionActions.js'; import { shellEscape } from './sshRemoteAgentHostHelpers.js'; -/** Set to `1` by a launcher, e.g., for Dev Containers, to have the agent host forward what its clients offer. */ +/** + * Set to `1` by the VS Code CLI for the server of an agent host started with `code agent host --client-forwarding`, as + * the Dev Container launcher does, to have the agent host forward what its clients offer. + */ export const AGENT_HOST_CLIENT_FORWARDING_ENV = 'VSCODE_AGENT_HOST_CLIENT_FORWARDING'; export const IAgentHostClientForwardingService = createDecorator('agentHostClientForwardingService'); diff --git a/src/vs/platform/agentHost/node/devContainerAgentHostService.ts b/src/vs/platform/agentHost/node/devContainerAgentHostService.ts index 46e8d1b93754ae..c99d04a4058999 100644 --- a/src/vs/platform/agentHost/node/devContainerAgentHostService.ts +++ b/src/vs/platform/agentHost/node/devContainerAgentHostService.ts @@ -42,7 +42,6 @@ import { getAppNodeModulesUri } from './appNodeModules.js'; import { toWslcCommand } from './devContainerEngine.js'; import { hasDevContainerEnvironmentVolume, IPreparedDevContainerEnvironment, prepareDevContainerEnvironment, readDevContainerEnvironmentTestConfiguration, removeDevContainerEnvironment } from './devContainerEnvironments.js'; import { checked, getDevContainerSampleVolumeLabel, IPreparedDevContainerSample, prepareDevContainerSample } from './devContainerSamples.js'; -import { AGENT_HOST_CLIENT_FORWARDING_ENV } from './agentHostClientForwarding.js'; import { IDevContainerSandboxConfiguration, isDevContainerSandboxSupported, parseDevContainerSandboxConfiguration, prepareDevContainerSandboxConfiguration } from './devContainerSandbox.js'; import { buildCreateDevContainerCacheCommand, buildLinkDevContainerServerCacheCommand, canAddDevContainerServerCacheMount, devContainerServerCacheMount, getDevContainerCliCachePath, getDevContainerServerCachePath } from './devContainerServerCache.js'; import { DevContainerShell, IDevContainerShellResult } from './devContainerShell.js'; @@ -55,6 +54,7 @@ import { ISshExec, buildAgentHostSpawnCommand, buildAgentRelayCommand, + cliVersionSupportsClientForwarding, filterLiveAgentHostEndpoints, formatAgentHostUrlHost, getRemoteCLIDataDir, @@ -467,18 +467,24 @@ export abstract class DevContainerAgentHostService extends Disposable implements reportCacheStatus: message => this._reportOutput(config.connectionId, `${message}\n`), }); const { cliBin } = cliInstallation; + // The client's own CLI and the latest one dev builds use have the option; an older fallback CLI does not. + const clientForwarding = cliInstallation.fallbackVersion === undefined || cliVersionSupportsClientForwarding(cliInstallation.fallbackVersion); + if (!clientForwarding) { + this._logService.warn(`${LOG_PREFIX} Fallback CLI ${cliInstallation.fallbackVersion} cannot start an Agent Host that forwards Git credentials and agents`); + } const cliDataDir = getRemoteCLIDataDir(serverDataFolderName); const initial = await runAgentEndpoints(exec, cliBin, cliDataDir); const live = await filterLiveAgentHostEndpoints(exec, initial.endpoints); - let endpoint = selectAgentHostEndpoint(live, this._productService.quality, undefined); + // Only an Agent Host started with forwarding forwards, not, e.g., one a remote editor's server started. + let endpoint = selectAgentHostEndpoint(clientForwarding ? live.filter(entry => entry.clientForwarding) : live, this._productService.quality, undefined); if (!endpoint) { const sessionId = this._telemetryService.sessionId; - // Lets the Agent Host forward the Git configuration, identity, credentials and agents of clients offering them. - const spawnCommand = `${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(sessionId)} ${AGENT_HOST_CLIENT_FORWARDING_ENV}=1 ${buildAgentHostSpawnCommand( + const spawnCommand = `${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(sessionId)} ${buildAgentHostSpawnCommand( cliBin, serverDataFolderName, initial.userDataPath, telemetryLevelToAgentHostValue(this._telemetryService.telemetryLevel), + { clientForwarding }, )}`; // The Agent Host keeps this command running, so it cannot share the startup shell. void this._createExec(config.connectionId, execSelector, tokenSource.token, sandboxEnvironment)(spawnCommand, { ignoreExitCode: true }).catch(error => { diff --git a/src/vs/platform/agentHost/node/remoteAgentHostCliInstaller.ts b/src/vs/platform/agentHost/node/remoteAgentHostCliInstaller.ts index 35ce1af1c527bc..61cd9343a5d9b1 100644 --- a/src/vs/platform/agentHost/node/remoteAgentHostCliInstaller.ts +++ b/src/vs/platform/agentHost/node/remoteAgentHostCliInstaller.ts @@ -32,6 +32,8 @@ export interface IRemoteAgentHostCliInstallOptions { export interface IRemoteAgentHostCliInstallResult { readonly cliBin: string; readonly installed: boolean; + /** The `--version` output of a fallback CLI, which is not built from the client's commit. */ + readonly fallbackVersion?: string; } /** @@ -116,8 +118,8 @@ async function ensurePinnedCliInstalled( options.logService.warn(`${logPrefix} Could not install matching CLI for commit ${commit}: ${message}. Looking for a fallback CLI...`); const fallback = await findFallbackCli(exec, options); if (fallback) { - options.logService.warn(`${logPrefix} Using fallback CLI at ${fallback} (does not match desktop commit ${commit}).`); - return { cliBin: fallback, installed: false }; + options.logService.warn(`${logPrefix} Using fallback CLI at ${fallback.cliBin} (${fallback.version}, does not match desktop commit ${commit}).`); + return { cliBin: fallback.cliBin, installed: false, fallbackVersion: fallback.version }; } throw error; } @@ -156,7 +158,7 @@ async function ensureLooseCliInstalled( return { cliBin, installed: true }; } -async function findFallbackCli(exec: ISshExec, options: IRemoteAgentHostCliInstallOptions): Promise { +async function findFallbackCli(exec: ISshExec, options: IRemoteAgentHostCliInstallOptions): Promise<{ readonly cliBin: string; readonly version: string } | undefined> { const logPrefix = options.logPrefix ?? '[RemoteAgentHostCliInstaller]'; const { stdout } = await exec(buildFindFallbackCLICommand(options.serverDataFolderName, options.quality), { ignoreExitCode: true }); const rawCandidates = stdout.split('\n').map(candidate => candidate.trim()).filter(candidate => candidate.length > 0); @@ -165,9 +167,9 @@ async function findFallbackCli(exec: ISshExec, options: IRemoteAgentHostCliInsta options.logService.info(`${logPrefix} Ignoring fallback CLI candidate with unexpected path shape: ${candidate}`); continue; } - const { code } = await exec(`${candidate} --version`, { ignoreExitCode: true }); + const { code, stdout: version } = await exec(`${candidate} --version`, { ignoreExitCode: true }); if (code === 0) { - return candidate; + return { cliBin: candidate, version: version.trim() }; } options.logService.info(`${logPrefix} Fallback CLI candidate ${candidate} failed --version check (exit ${code}).`); } diff --git a/src/vs/platform/agentHost/node/serviceBootstrapping.md b/src/vs/platform/agentHost/node/serviceBootstrapping.md index 816454b609a490..b6d44de15556de 100644 --- a/src/vs/platform/agentHost/node/serviceBootstrapping.md +++ b/src/vs/platform/agentHost/node/serviceBootstrapping.md @@ -57,7 +57,7 @@ The same clients, and remote-editor connections under the same `useHostProxy` ga The Copilot runtime gets proxies from the Agent Host through the SDK's network callbacks rather than proxy environment variables, which would also apply to the tools it runs. The runtime resolves each request's proxy with the `network.resolveProxy` callback, which applies the Agent Host's proxy precedence above and passes on the full PAC-style list, so the runtime can fail over to the fallback proxies a client resolves. When none of `http.noProxy`, `http.proxy`, the proxy environment variables or a connected client decides, for example while no client is connected, or when system proxy discovery is disabled, the callback gives no answer, and the runtime resolves that proxy itself from the environment and the operating system's settings. A PAC-style answer cannot carry credentials, so the callback answers an `http.proxy` setting with credentials without them, and gives no answer for a proxy environment variable with credentials: the runtime inherits the proxy environment variables of the Agent Host unchanged and uses that one itself. The runtime gets Kerberos tokens through the `network.authenticateNegotiate` callback: this machine's ticket for exactly the principal the runtime requests, else one from a client sharing its network. It gets Basic proxy credentials through the `network.authenticateBasic` callback: on the first challenge for the proxy of an `http.proxy` setting with credentials, those of the setting, like the Agent Host's own requests, and after the proxy rejects them, those of the setting again only when they changed since; otherwise from a local renderer, which serves those of the `http.proxy` setting until the proxy rejects them, then its stored credentials or its proxy login dialog, else from a client sharing its network under the restrictions above. Each runtime keeps the credentials it was answered until the proxy rejects them, so after a rejection, the Agent Host first answers a client's current credentials, which a login dialog for another runtime may already have replaced, and asks the client for others only when the proxy rejected those: when the password changes, the runtimes of the local and a WSL Agent Host share one login dialog. Credentials are not written to the runtime's environment or disk. Clients connecting or leaving, or `http.proxy` and `http.noProxy` changing, don't restart the runtime. -An Agent Host its launcher starts with `VSCODE_AGENT_HOST_CLIENT_FORWARDING=1`, as the Dev Container launcher does, forwards what clients advertising the optional `vscode.clientForwarding` capability offer to the processes it starts, such as the Copilot runtime and terminals, like the Dev Containers extension forwards them into a container: the client machine's Git configuration and identity, Git credentials, SSH agent and GPG agent. Only such an Agent Host confirms the capability in its initialize result. Processes get their environment when they start, so it is set up once, when the Agent Host starts: the Agent Host listens on sockets in an owner-only folder, points `SSH_AUTH_SOCK` to its SSH socket, and appends a credential helper to the configuration Git reads from the environment after its files, `GIT_CONFIG_COUNT` or, before Git 2.31, `GIT_CONFIG_PARAMETERS`, so the configured helpers come first and a reset of the helper list in a file does not remove it. It asks each client what it offers with `vscode/forwarding/describe`; the newest client offering something serves it. A connection to the SSH socket goes to that client's agent, else to the agent the Agent Host had, else gets the answers of an agent without keys. The Git helper runs with the Agent Host's Node.js and gets credentials from that client through `vscode/forwarding/gitCredential`, which runs `git credential fill`, `approve` or `reject` in the client machine's shell environment; without a client or an answer, Git continues with its other helpers. For each connection to an agent, the Agent Host opens a client connection with `vscode/forwarding/open`; both sides then send the connection's data and closing as `vscode/forwarding/data` and `vscode/forwarding/close` notifications, which have no flow control, as agents exchange small messages. On Linux and macOS, while a client offers its GPG agent and unless GnuPG there has private keys of its own, the Agent Host listens on GnuPG's standard agent socket and, when the client uses `keyboxd`, on its `keyboxd` socket, enabling `keyboxd` without existing keyrings, and imports the client's public keys, certificates and owner trust from `vscode/forwarding/gpgKeys` once it listens, so no agent of its own starts; after a failed import, the next client retries it. All its processes share this environment, so while one of the Agent Host's sessions has terminal sandboxing on, it forwards none of its clients' agents and credentials: it closes open connections, its SSH socket answers as an agent without keys and the Git helper without credentials, also for a request that was pending when sandboxing turned on. Like the Dev Containers extension's `forward*` resolver properties and `forwardingUse` event, it reports what each client connection forwards as `agentHost.forwardingSetup`, and the first use of each forwarded service per client connection, operation and outcome as `agentHost.forwardingUse`, with fixed values only, such as a category of a credential request's host; its own import of GPG keys is not use. Its protocol debug logs redact forwarded agent data, credentials and Git configuration. +An Agent Host started with `code agent host --client-forwarding`, as the Dev Container launcher does, forwards what clients advertising the optional `vscode.clientForwarding` capability offer to the processes it starts, such as the Copilot runtime and terminals, like the Dev Containers extension forwards them into a container: the client machine's Git configuration and identity, Git credentials, SSH agent and GPG agent. The CLI records the flag as `clientForwarding` in the Agent Host's endpoint registry entry, so a launcher reuses only Agent Hosts started with it, and sets `VSCODE_AGENT_HOST_CLIENT_FORWARDING=1` for the server it starts, which passes it on to its Agent Host; without the flag, the CLI removes the variable. Only such an Agent Host confirms the capability in its initialize result. Processes get their environment when they start, so it is set up once, when the Agent Host starts: the Agent Host listens on sockets in an owner-only folder, points `SSH_AUTH_SOCK` to its SSH socket, and appends a credential helper to the configuration Git reads from the environment after its files, `GIT_CONFIG_COUNT` or, before Git 2.31, `GIT_CONFIG_PARAMETERS`, so the configured helpers come first and a reset of the helper list in a file does not remove it. It asks each client what it offers with `vscode/forwarding/describe`; the newest client offering something serves it. A connection to the SSH socket goes to that client's agent, else to the agent the Agent Host had, else gets the answers of an agent without keys. The Git helper runs with the Agent Host's Node.js and gets credentials from that client through `vscode/forwarding/gitCredential`, which runs `git credential fill`, `approve` or `reject` in the client machine's shell environment; without a client or an answer, Git continues with its other helpers. For each connection to an agent, the Agent Host opens a client connection with `vscode/forwarding/open`; both sides then send the connection's data and closing as `vscode/forwarding/data` and `vscode/forwarding/close` notifications, which have no flow control, as agents exchange small messages. On Linux and macOS, while a client offers its GPG agent and unless GnuPG there has private keys of its own, the Agent Host listens on GnuPG's standard agent socket and, when the client uses `keyboxd`, on its `keyboxd` socket, enabling `keyboxd` without existing keyrings, and imports the client's public keys, certificates and owner trust from `vscode/forwarding/gpgKeys` once it listens, so no agent of its own starts; after a failed import, the next client retries it. All its processes share this environment, so while one of the Agent Host's sessions has terminal sandboxing on, it forwards none of its clients' agents and credentials: it closes open connections, its SSH socket answers as an agent without keys and the Git helper without credentials, also for a request that was pending when sandboxing turned on. Like the Dev Containers extension's `forward*` resolver properties and `forwardingUse` event, it reports what each client connection forwards as `agentHost.forwardingSetup`, and the first use of each forwarded service per client connection, operation and outcome as `agentHost.forwardingUse`, with fixed values only, such as a category of a credential request's host; its own import of GPG keys is not use. Its protocol debug logs redact forwarded agent data, credentials and Git configuration. With `vscode/forwarding/gitConfig`, the Agent Host gets the Git identity the client uses for the workspace folder, following its conditional includes, and, from clients that offer it while none of its sessions is sandboxed, also when the client answers, their global Git configuration and the files in their home folder that settings name, such as allowed signers. Like the Dev Containers extension, it copies the client's `~/.gitconfig` only where it has none or one with only `[filter]`, `[safe]` or `[user]` sections, and only once, marking the copy with a comment, and the client's XDG configuration only where it has none. It then removes from the copied files what cannot work there: editors and programs it lacks, a TLS backend, except on Windows, whose Git supports several, credential helpers whose commands it lacks (with their URL's reset of the helper list), and commit and tag signing that neither an agent the client forwards nor a key of its own supports; GnuPG with keys of its own does not use the client's agent, so the signing key must then be one of them. It sets the client's identity where it has none, and after copying, where the copy's differs because of the client folder's conditional includes or adds a second value. It asks the client only when there is something to do. It answers `initialize` once its environment is in place, waiting at most 10 seconds for its own startup but not for clients: the Git configuration follows in the background. Relay connections never forward. diff --git a/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts b/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts index bf02178ac5e087..089094ef8c6c93 100644 --- a/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts +++ b/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts @@ -372,12 +372,35 @@ export function buildAgentEndpointsCommand(cliBin: string, cliDataDir: string, u * selection path is still relying on. `--new-instance` guarantees a * genuinely new process/registry entry every time this command runs, * leaving all existing standalone/editor entries untouched. + * + * `clientForwarding` passes `--client-forwarding`, which only CLIs that + * {@link cliVersionSupportsClientForwarding} accept. */ -export function buildAgentHostSpawnCommand(cliBin: string, serverDataFolderName: string, userDataPath: string, telemetryLevel: TelemetryConfiguration, idleTimeoutSec = 300): string { +export function buildAgentHostSpawnCommand(cliBin: string, serverDataFolderName: string, userDataPath: string, telemetryLevel: TelemetryConfiguration, options: { readonly idleTimeoutSec?: number; readonly clientForwarding?: boolean } = {}): string { + const idleTimeoutSec = options.idleTimeoutSec ?? 300; if (!Number.isSafeInteger(idleTimeoutSec) || idleTimeoutSec <= 0) { throw new Error(`Unsafe idle timeout value for shell interpolation: ${JSON.stringify(idleTimeoutSec)}`); } - return `${buildAgentHostBaseCommand(cliBin, serverDataFolderName, telemetryLevel)} --new-instance --user-data-dir ${shellEscape(userDataPath)} --idle-timeout ${idleTimeoutSec}`; + return `${buildAgentHostBaseCommand(cliBin, serverDataFolderName, telemetryLevel)} --new-instance --user-data-dir ${shellEscape(userDataPath)} --idle-timeout ${idleTimeoutSec}${options.clientForwarding ? ' --client-forwarding' : ''}`; +} + +/** + * Whether a CLI that prints `version` for `--version`, e.g., + * `code-insiders 1.149.0 (commit )`, accepts `agent host --client-forwarding`: + * CLIs from 1.149 on and those built from sources, which print `dev`, do. + * Builds of an Insiders version share it, so this treats all 1.149 builds as + * supporting it. + */ +export function cliVersionSupportsClientForwarding(version: string): boolean { + const match = /^\S+ (?:(?\d+)\.(?\d+)\.\d+|(?dev)) \(commit /.exec(version.trim()); + if (!match?.groups) { + return false; + } + const { major, minor, dev } = match.groups; + if (dev) { + return true; + } + return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 149); } /** diff --git a/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts b/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts index 8d4ebddd840eab..92904eb2c035f1 100644 --- a/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts +++ b/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts @@ -84,6 +84,16 @@ suite('Agent Host Endpoint Registry (schema v2)', () => { ); }); + test('keeps whether an endpoint forwards what clients offer', () => { + const entry = createEntry({ type: 'standalone', endpoint: { type: 'tcp', host: '127.0.0.1', port: 12345 } }); + assert.deepStrictEqual([ + parseAgentHostEndpointMetadataEntry({ ...entry, clientForwarding: true })?.clientForwarding, + Object.hasOwn(parseAgentHostEndpointMetadataEntry({ ...entry, clientForwarding: false })!, 'clientForwarding'), + Object.hasOwn(parseAgentHostEndpointMetadataEntry(entry)!, 'clientForwarding'), + parseAgentHostEndpointMetadataEntry({ ...entry, clientForwarding: 'true' }), + ], [true, false, false, undefined]); + }); + test('ignores unsupported schema versions without failing the whole array', () => { const current = createEntry({ instanceId: 'current' }); const raw = [ diff --git a/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts b/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts index 4dee989cbe170c..38e5314c674dd5 100644 --- a/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts +++ b/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts @@ -118,6 +118,7 @@ class TestDevContainerAgentHostMainService extends DevContainerAgentHostMainServ protocolVersion: '1', connectionToken: 'token', endpoint: { type: 'tcp', host: '127.0.0.1', port: 1234 }, + clientForwarding: true, }]; containerSessionIds: string[] = [NullTelemetryService.sessionId]; endpointPollsBeforeAvailable = 0; @@ -154,6 +155,8 @@ class TestDevContainerAgentHostMainService extends DevContainerAgentHostMainServ linkedBeforeLifecycle: boolean | undefined; cacheSetupError: Error | undefined; cliCacheSetupError: Error | undefined; + /** The `--version` output of a fallback CLI, used because installing the client's own CLI fails. */ + fallbackCliVersion: string | undefined; cacheMountConfigured = false; hostDirectoryOwnedByCurrentUser = true; readonly checkedHostDirectories: string[] = []; @@ -449,6 +452,20 @@ class TestDevContainerAgentHostMainService extends DevContainerAgentHostMainServ if (command.includes('/etc/alpine-release')) { return { stdout: this._libc, stderr: '', code: 0 }; } + if (this.fallbackCliVersion !== undefined) { + if (command.startsWith('test -x ')) { + return { stdout: '', stderr: '', code: 1 }; + } + if (command.includes('curl -fsSL')) { + throw new Error('CLI download failed'); + } + if (command.includes('ls -1t')) { + return { stdout: `~/.vscode-server-oss/code-insiders-${'0'.repeat(40)}\n`, stderr: '', code: 0 }; + } + if (command.endsWith(' --version')) { + return { stdout: `${this.fallbackCliVersion}\n`, stderr: '', code: 0 }; + } + } if (this._forceCliInstall && command.includes('--version &&')) { return { stdout: '', stderr: '', code: 1 }; } @@ -1597,11 +1614,30 @@ suite('Dev Container Agent Host Main Service', () => { }, { sharedServer: true, warning: true, cacheCommands: 0, privateDownloads: 1 }); }); - test('starts a new Agent Host that forwards what its clients offer, e.g., their Git identity', async () => { - const service = store.add(new TestDevContainerAgentHostMainService()); - service.endpointPollsBeforeAvailable = 1; - await service.connect({ connectionId: 'forwarding', workspaceFolder: '/workspace', name: 'Project Dev Container' }); - assert.deepStrictEqual(service.separateExecs.map(({ command }) => command.includes(` ${AGENT_HOST_CLIENT_FORWARDING_ENV}=1 `)), [true]); + test('starts or reuses only an Agent Host that forwards what its clients offer, unless an older fallback CLI cannot start one', async () => { + const results: Record = {}; + for (const { label, commit, fallbackCliVersion } of [ + { label: 'own CLI', commit: 'a'.repeat(40), fallbackCliVersion: undefined }, + { label: 'dev build', commit: undefined, fallbackCliVersion: undefined }, + { label: '1.148 fallback', commit: 'a'.repeat(40), fallbackCliVersion: `code-insiders 1.148.0 (commit ${'0'.repeat(40)})` }, + { label: '1.149 fallback', commit: 'a'.repeat(40), fallbackCliVersion: `code-insiders 1.149.0 (commit ${'0'.repeat(40)})` }, + ]) { + const service = store.add(new TestDevContainerAgentHostMainService('', false, undefined, process.env, true, [], new Set(), '/tmp', new NullLogService(), commit)); + service.fallbackCliVersion = fallbackCliVersion; + // E.g., the Agent Host a remote editor's server started. + service.endpoints = [{ ...service.endpoints[0], clientForwarding: undefined }]; + await service.connect({ connectionId: label, workspaceFolder: '/workspace', name: 'Project Dev Container' }); + results[label] = { + spawned: service.separateExecs.map(({ command }) => ({ flag: command.endsWith(' --client-forwarding'), variable: command.includes(AGENT_HOST_CLIENT_FORWARDING_ENV) })), + relaysTo: service.relayCommand?.match(/ agent relay '(?[^']+)'/)?.groups?.instance, + }; + } + assert.deepStrictEqual(results, { + 'own CLI': { spawned: [{ flag: true, variable: false }], relaysTo: 'spawned-instance' }, + 'dev build': { spawned: [{ flag: true, variable: false }], relaysTo: 'spawned-instance' }, + '1.148 fallback': { spawned: [], relaysTo: 'instance' }, + '1.149 fallback': { spawned: [{ flag: true, variable: false }], relaysTo: 'spawned-instance' }, + }); }); test('adds the exact bind-mounted repository root to Git safe.directory only when host-owned', async () => { diff --git a/src/vs/platform/agentHost/test/node/sshRemoteAgentHostHelpers.test.ts b/src/vs/platform/agentHost/test/node/sshRemoteAgentHostHelpers.test.ts index 5afa0b91483a4c..8299b08a45d196 100644 --- a/src/vs/platform/agentHost/test/node/sshRemoteAgentHostHelpers.test.ts +++ b/src/vs/platform/agentHost/test/node/sshRemoteAgentHostHelpers.test.ts @@ -17,6 +17,7 @@ import { buildCLIDownloadUrl, buildCleanupOldCLIsCommand, buildFindFallbackCLICommand, + cliVersionSupportsClientForwarding, filterLiveAgentHostEndpoints, findNewAgentHostEndpoint, formatAgentHostUrlHost, @@ -497,11 +498,14 @@ suite('SSH Remote Agent Host Helpers', () => { ); }); - test('honors a custom idle timeout', () => { - assert.strictEqual( - buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/home/user/.vscode-remote', TelemetryConfiguration.ON, 60), + test('honors a custom idle timeout and client forwarding', () => { + assert.deepStrictEqual([ + buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/home/user/.vscode-remote', TelemetryConfiguration.ON, { idleTimeoutSec: 60 }), + buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/home/user/.vscode-remote', TelemetryConfiguration.ON, { clientForwarding: true }), + ], [ '~/.vscode-server/code --cli-data-dir ~/.vscode-server/cli --telemetry-level all agent host --port 0 --server-data-dir ~/.vscode-server --new-instance --user-data-dir \'/home/user/.vscode-remote\' --idle-timeout 60', - ); + '~/.vscode-server/code --cli-data-dir ~/.vscode-server/cli --telemetry-level all agent host --port 0 --server-data-dir ~/.vscode-server --new-instance --user-data-dir \'/home/user/.vscode-remote\' --idle-timeout 300 --client-forwarding', + ]); }); test('propagates telemetry disablement to a new dedicated agent host', () => { @@ -512,9 +516,9 @@ suite('SSH Remote Agent Host Helpers', () => { }); test('rejects unsafe idle timeout values', () => { - assert.throws(() => buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/x', TelemetryConfiguration.ON, 0), /Unsafe idle timeout/); - assert.throws(() => buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/x', TelemetryConfiguration.ON, -1), /Unsafe idle timeout/); - assert.throws(() => buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/x', TelemetryConfiguration.ON, 1.5), /Unsafe idle timeout/); + assert.throws(() => buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/x', TelemetryConfiguration.ON, { idleTimeoutSec: 0 }), /Unsafe idle timeout/); + assert.throws(() => buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/x', TelemetryConfiguration.ON, { idleTimeoutSec: -1 }), /Unsafe idle timeout/); + assert.throws(() => buildAgentHostSpawnCommand('~/.vscode-server/code', '.vscode-server', '/x', TelemetryConfiguration.ON, { idleTimeoutSec: 1.5 }), /Unsafe idle timeout/); }); test('always includes --new-instance so an existing standalone is never silently reused', () => { @@ -523,6 +527,22 @@ suite('SSH Remote Agent Host Helpers', () => { }); }); + suite('cliVersionSupportsClientForwarding', () => { + test('accepts CLIs from 1.149 on and those built from sources', () => { + const commit = 'd8b0b6fc93e3027e3dae61d348d73f8b3f33c59c'; + assert.deepStrictEqual([ + `code-insiders 1.148.0 (commit ${commit})`, + `code-insiders 1.149.0 (commit ${commit})\n`, + `code 1.149.2 (commit ${commit})`, + `code-insiders 1.150.0 (commit ${commit})`, + `code 2.0.0 (commit ${commit})`, + 'code-oss dev (commit unknown)', + '0.9.149.0', + '', + ].map(cliVersionSupportsClientForwarding), [false, true, true, true, true, true, false, false]); + }); + }); + suite('formatAgentHostUrlHost', () => { test('dials loopback for wildcards and brackets IPv6 literals', () => { assert.deepStrictEqual(['127.0.0.1', '0.0.0.0', '::', '::1', '[::1]', 'localhost', undefined].map(formatAgentHostUrlHost), ['127.0.0.1', '127.0.0.1', '127.0.0.1', '[::1]', '[::1]', 'localhost', '127.0.0.1']); diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md index 733a05ce854e45..136e5464344a36 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md @@ -214,7 +214,7 @@ Desktop-local containers honor the user setting `dev.containers.dockerPath` for Windows hosts can also run containers in WSL containers (`wslc.exe`), as a second engine next to that Docker executable. The CLI drives WSLc through `--docker-path`; the launcher runs its own Docker commands with WSLc too, evaluating their Go-template `--format` arguments on WSLc's JSON output, since WSLc formats only JSON and tables. A host reports its available engines, and the engine that already has a source's container or volume, through `vscode/devContainers/getEngines` behind the `vscode.devContainerEngines` capability; older hosts run only Docker. A source's existing container, or a workspace's state volume, keeps its engine, because it holds its Agent Host's sessions, and relay reconnects keep the engine of the first connection. A workspace's lookup matches the ID labels of the configuration that `up` selects, so another configuration's container does not decide. Environments and stored workspace connections also remember the engine their connection reported, and connections, including the connection factory's rebuilds, request it, so a lookup that fails, for example while WSL starts, can neither create the container again in the other engine nor ask. Removing a workspace's container forgets its engine, so a new container gets the setting's engine. Deleting an environment removes it with the engine that has its volume, and fails rather than guess when another engine could not be checked. Only a new container gets the engine of `chat.agentHost.devContainer.containerEngine`, or the other available engine when that one is missing; with `ask`, the user picks one when both are available, and dismissing the pick cancels connecting. Folder container discovery lists the containers of the Docker engine, so its connections without user action use Docker and never ask. WSLc has no security options or devices for nested sandboxing, so its containers never receive the sandbox override below and report the support as unavailable. -The connector starts a new Agent Host in the container to forward what its clients offer, and the client advertises the `vscode.clientForwarding` protocol extension (see the Agent Host's `serviceBootstrapping.md`). The Agent Host sets the Git user name and email of the machine the client runs on, for a local workspace those Git uses for its folder, where the container has none. Without terminal sandboxing, and unless the experimental `chat.agentHost.devContainer.credentialForwarding.enabled` setting is off, the container also gets the Git setup of the Dev Containers extension from the machine the client runs on, including for SSH, Tunnel and WSL Docker hosts: the Agent Host copies the client's Git configuration where the container has none of its own, and forwards its Git credentials, SSH agent and GPG agent to the processes it starts. Turning the setting off closes forwarded connections and stops forwarding to open connections, including credentials a credential manager is still signing in for; turning it on applies to a container's next connection. With sandboxing, the container gets only the identity, as before, and while any of its sessions is sandboxed, the Agent Host forwards nothing else to any of them, as they share its environment. Docker credentials, displays and ports are not forwarded. +The connector starts the container's Agent Host with `code agent host --client-forwarding` to forward what its clients offer, reusing only one the endpoint registry lists as started that way, and the client advertises the `vscode.clientForwarding` protocol extension (see the Agent Host's `serviceBootstrapping.md`). A fallback CLI older than 1.149, which the connector uses only when it cannot install the CLI of its own commit, lacks the flag; the connector then starts or reuses an Agent Host without forwarding. The Agent Host sets the Git user name and email of the machine the client runs on, for a local workspace those Git uses for its folder, where the container has none. Without terminal sandboxing, and unless the experimental `chat.agentHost.devContainer.credentialForwarding.enabled` setting is off, the container also gets the Git setup of the Dev Containers extension from the machine the client runs on, including for SSH, Tunnel and WSL Docker hosts: the Agent Host copies the client's Git configuration where the container has none of its own, and forwards its Git credentials, SSH agent and GPG agent to the processes it starts. Turning the setting off closes forwarded connections and stops forwarding to open connections, including credentials a credential manager is still signing in for; turning it on applies to a container's next connection. With sandboxing, the container gets only the identity, as before, and while any of its sessions is sandboxed, the Agent Host forwards nothing else to any of them, as they share its environment. Docker credentials, displays and ports are not forwarded. When terminal sandboxing is selected for a new Copilot Dev Container session, startup uses a generated configuration override to add `seccomp=unconfined`, `apparmor=unconfined`, `systempaths=unconfined`, and `/dev/net/tun` device access. Image/Dockerfile containers receive Docker run arguments; user-defined `securityOpt` values retain their existing CLI precedence. Compose containers receive an additional Compose file for the configured workspace service, preserving implicit file discovery, workspace `.env` behavior, and the source version for legacy Compose. Samples receive the same run arguments. The workspace's source configuration is not modified, and relative paths retain their original base. No extra capabilities or privileged mode are added. These options relax the outer container's isolation so terminal commands can run inside a nested sandbox. An information icon after the "Sandboxing in Dev Container" toggle label draws attention to the hover explaining this tradeoff; the permission control retains its usual label. From fe2d18bd77a3ffc05302b45627e77c3f2f3c9327 Mon Sep 17 00:00:00 2001 From: Christof Marti Date: Sat, 28 Nov 2026 16:28:56 +0100 Subject: [PATCH 2/2] agentHost: let editor windows turn on client forwarding The Dev Container launcher again reuses the Agent Host running in the container however it was started, so the endpoint registry no longer records client forwarding. Instead, an editor window connected to a Dev Container asks its server, with the new `clientForwarding` connection option, to start its Agent Host with forwarding, since the launcher may reuse that one. The launcher now stops waiting for a new Agent Host to register as soon as its start command fails, and starts it again without `--client-forwarding` when a 1.149 CLI from before the flag rejects it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- cli/src/commands/agent_host.rs | 56 +------------------ cli/src/commands/agent_relay.rs | 1 - cli/src/commands/args.rs | 6 +- cli/src/tunnels/agent_host.rs | 31 ++++------ cli/src/tunnels/agent_host_registry.rs | 27 --------- src/vs/platform/agentHost/LOCAL_ENDPOINT.md | 1 - .../common/agentHostEndpointRegistry.ts | 10 +--- .../platform/agentHost/common/agentService.ts | 10 ++++ .../node/agentHostClientForwarding.ts | 13 ++--- .../node/devContainerAgentHostService.ts | 52 ++++++++--------- .../agentHost/node/serviceBootstrapping.md | 2 +- .../node/sshRemoteAgentHostHelpers.ts | 52 ++++++++++++++++- .../node/agentHostClientForwarding.test.ts | 9 +-- .../node/agentHostEndpointRegistry.test.ts | 10 ---- .../node/devContainerAgentHostService.test.ts | 46 ++++++++++----- src/vs/server/node/agentHostChannel.ts | 3 +- .../server/node/serverAgentHostEnvironment.ts | 8 ++- .../server/test/node/agentHostChannel.test.ts | 6 +- .../node/serverAgentHostEnvironment.test.ts | 12 ++++ .../REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md | 2 +- .../editorRemoteAgentHostServiceClient.ts | 11 +++- ...editorRemoteAgentHostServiceClient.test.ts | 21 +++---- 22 files changed, 187 insertions(+), 202 deletions(-) diff --git a/cli/src/commands/agent_host.rs b/cli/src/commands/agent_host.rs index dcd7cb950c5a0e..2361b18fec481c 100644 --- a/cli/src/commands/agent_host.rs +++ b/cli/src/commands/agent_host.rs @@ -133,7 +133,6 @@ fn decide_foreground_action( port, token, instance_id, - client_forwarding, } = decision else { return ForegroundAction::SpawnFresh; @@ -149,13 +148,7 @@ fn decide_foreground_action( // matches the running supervisor. If it differs, error out with a // clear message instead of silently sharing a differently-bound // supervisor. - if let Some(conflict) = detect_config_conflict( - args, - host.as_deref(), - port, - token.as_deref(), - client_forwarding, - ) { + if let Some(conflict) = detect_config_conflict(args, host.as_deref(), port, token.as_deref()) { return ForegroundAction::ConflictError(format!( "Agent host already running on {host_str}:{port} (PID {pid}), but {conflict}.\n\ Use `{application_name} agent kill` to stop it, or pass `--replace` to take over.", @@ -777,22 +770,12 @@ fn print_manage_banner_line() { /// `running_host` may be `None` when the registry entry doesn't record a /// host; in that case we conservatively skip the host comparison (the /// supervisor is most likely loopback, which is the default). -/// -/// A supervisor started with `--client-forwarding` is still compatible with -/// a request without it: it forwards only to clients offering it. fn detect_config_conflict( args: &AgentHostArgs, running_host: Option<&str>, running_port: u16, running_token: Option<&str>, - running_client_forwarding: bool, ) -> Option { - if args.client_forwarding && !running_client_forwarding { - return Some( - "--client-forwarding conflicts with the running supervisor (started without it)" - .to_string(), - ); - } if let (Some(requested), Some(running)) = (args.host.as_deref(), running_host) { if requested != running { return Some(format!( @@ -1522,17 +1505,12 @@ mod tests { } fn reusable_decision() -> AgentHostReuseDecision { - reusable_decision_with_client_forwarding(false) - } - - fn reusable_decision_with_client_forwarding(client_forwarding: bool) -> AgentHostReuseDecision { AgentHostReuseDecision::Reuse { pid: 4242, host: Some("127.0.0.1".to_string()), port: 9000, token: Some("tok".to_string()), instance_id: "instance-existing".to_string(), - client_forwarding, } } @@ -1615,36 +1593,6 @@ mod tests { } } - #[test] - fn decide_foreground_action_reuses_for_client_forwarding_only_a_forwarding_supervisor() { - let forwarding_args = AgentHostArgs { - client_forwarding: true, - ..Default::default() - }; - let actions = [ - decide_foreground_action(&forwarding_args, reusable_decision()), - decide_foreground_action( - &forwarding_args, - reusable_decision_with_client_forwarding(true), - ), - decide_foreground_action( - &AgentHostArgs::default(), - reusable_decision_with_client_forwarding(true), - ), - ]; - assert!( - matches!( - &actions, - [ - ForegroundAction::ConflictError(message), - ForegroundAction::ReuseBanner { .. }, - ForegroundAction::ReuseBanner { .. }, - ] if message.contains("--client-forwarding") - ), - "{actions:?}" - ); - } - /// The core `--new-instance` contract: it must win over every other /// branch, in particular `--replace`'s kill path, so that passing /// both flags together can never remove an existing entry. @@ -1721,7 +1669,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, }; agent_host_registry::publish_agent_host_endpoint(&log, &user_data_path, &editor).unwrap(); @@ -1750,7 +1697,6 @@ mod tests { port: standalone_port, token: Some("standalone-tok".to_string()), instance_id: "standalone-existing".to_string(), - client_forwarding: false, } ); assert_eq!( diff --git a/cli/src/commands/agent_relay.rs b/cli/src/commands/agent_relay.rs index 03d0e84255c8ec..2cec653b7b7f95 100644 --- a/cli/src/commands/agent_relay.rs +++ b/cli/src/commands/agent_relay.rs @@ -203,7 +203,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, } } diff --git a/cli/src/commands/args.rs b/cli/src/commands/args.rs index f84a78b8b226ed..126301a66a7ff1 100644 --- a/cli/src/commands/args.rs +++ b/cli/src/commands/args.rs @@ -296,10 +296,8 @@ pub struct AgentHostArgs { pub foreground: bool, /// Forward what clients offer, such as their Git credentials and SSH and - /// GPG agents, to the processes the agent host starts. Recorded in the - /// agent host's registry entry; an existing agent host is only reused - /// when it was started with this flag too. Used by the Dev Container - /// launcher. + /// GPG agents, to the processes the agent host starts. Used by the Dev + /// Container launcher. #[clap(long, hide = true)] pub client_forwarding: bool, diff --git a/cli/src/tunnels/agent_host.rs b/cli/src/tunnels/agent_host.rs index 6c4878c2a4a5fe..be91fc380a49dd 100644 --- a/cli/src/tunnels/agent_host.rs +++ b/cli/src/tunnels/agent_host.rs @@ -1275,19 +1275,16 @@ impl AgentHostSidecar { // character-equal without spuriously flagging hostname-vs-IP // equivalents as a config conflict. let host = host_label.unwrap_or_else(|| bound_addr.ip().to_string()); - let entry = AgentHostEndpointMetadata { - client_forwarding: manager.config.client_forwarding, - ..AgentHostEndpointMetadata::new_standalone( - pid, - instance_id.clone(), - host, - bound_addr.port(), - public_token.clone().unwrap_or_default(), - AGENT_HOST_PROTOCOL_VERSION.to_string(), - VSCODE_CLI_QUALITY.map(str::to_string), - None, - ) - }; + let entry = AgentHostEndpointMetadata::new_standalone( + pid, + instance_id.clone(), + host, + bound_addr.port(), + public_token.clone().unwrap_or_default(), + AGENT_HOST_PROTOCOL_VERSION.to_string(), + VSCODE_CLI_QUALITY.map(str::to_string), + None, + ); // Registry publish does blocking filesystem I/O (write a temp file and // atomically rename it into place); run it on a blocking-safe thread so @@ -1531,8 +1528,6 @@ pub enum AgentHostReuseDecision { /// This entry's stable identity within the registry, used by /// `--replace` to scope removal to exactly this instance. instance_id: String, - /// Whether the supervisor was started with `--client-forwarding`. - client_forwarding: bool, }, } @@ -1560,7 +1555,6 @@ pub async fn classify_agent_host( Some(selected.connection_token) }, instance_id: selected.instance_id, - client_forwarding: selected.client_forwarding, }, None => AgentHostReuseDecision::SpawnFresh, } @@ -3352,7 +3346,6 @@ mod tests { port, token: Some("registry-tok".to_string()), instance_id: "instance-registry".to_string(), - client_forwarding: false, } ); } @@ -3375,7 +3368,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, }; agent_host_registry::publish_agent_host_endpoint( &log::Logger::test(), @@ -3485,7 +3477,6 @@ mod tests { }, quality: Some("stable".to_string()), tunnel_name: None, - client_forwarding: false, } } @@ -3509,7 +3500,6 @@ mod tests { }, quality: Some("stable".to_string()), tunnel_name: None, - client_forwarding: false, } } @@ -3547,7 +3537,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, }; let gw: AgentHostGatewayEndpoint = (&entry).into(); assert_eq!(gw.endpoint_kind, "socket"); diff --git a/cli/src/tunnels/agent_host_registry.rs b/cli/src/tunnels/agent_host_registry.rs index 81b354565f9e92..4cc22d327cd8ea 100644 --- a/cli/src/tunnels/agent_host_registry.rs +++ b/cli/src/tunnels/agent_host_registry.rs @@ -95,15 +95,6 @@ pub struct AgentHostEndpointMetadata { pub quality: Option, #[serde(skip_serializing_if = "Option::is_none")] pub tunnel_name: Option, - /// Whether the agent host forwards what clients offer to the processes it - /// starts (`code agent host --client-forwarding`). Omitted when false, - /// and by writers that predate it. - #[serde(default, skip_serializing_if = "is_false")] - pub client_forwarding: bool, -} - -fn is_false(value: &bool) -> bool { - !*value } /// The subset of [`AgentHostEndpointMetadata`] that identifies a unique @@ -140,7 +131,6 @@ impl AgentHostEndpointMetadata { endpoint: AgentHostEndpointAddress::Tcp { host, port }, quality, tunnel_name, - client_forwarding: false, } } @@ -742,8 +732,6 @@ pub struct LiveStandaloneEndpoint { /// Empty when the standalone host was started with /// `--without-connection-token`. pub connection_token: String, - /// Whether the standalone host was started with `--client-forwarding`. - pub client_forwarding: bool, } /// Reads the registry and returns a live `standalone` `tcp` entry to reuse, if @@ -766,7 +754,6 @@ pub async fn select_live_standalone_endpoint( host, port, connection_token: e.connection_token, - client_forwarding: e.client_forwarding, }), AgentHostEndpointAddress::Socket { .. } => None, }) @@ -885,7 +872,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, }; publish_agent_host_endpoint(&log, dir.path(), &editor).unwrap(); @@ -981,7 +967,6 @@ mod tests { let mut metadata = standalone(42, "instance-a", 8080); metadata.quality = Some("insider".to_string()); metadata.tunnel_name = Some("my-tunnel".to_string()); - metadata.client_forwarding = true; let value = serde_json::to_value(&metadata).unwrap(); assert_eq!(value["schemaVersion"], 2); @@ -995,11 +980,6 @@ mod tests { assert_eq!(value["endpoint"]["port"], 8080); assert_eq!(value["quality"], "insider"); assert_eq!(value["tunnelName"], "my-tunnel"); - assert_eq!(value["clientForwarding"], true); - assert_eq!( - serde_json::from_value::(value).unwrap(), - metadata - ); } #[test] @@ -1008,11 +988,6 @@ mod tests { let value = serde_json::to_value(&metadata).unwrap(); assert!(value.get("quality").is_none()); assert!(value.get("tunnelName").is_none()); - assert!(value.get("clientForwarding").is_none()); - assert_eq!( - serde_json::from_value::(value).unwrap(), - metadata - ); } #[test] @@ -1178,7 +1153,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, }; publish_agent_host_endpoint(&log, dir.path(), &editor).unwrap(); @@ -1508,7 +1482,6 @@ mod tests { }, quality: None, tunnel_name: None, - client_forwarding: false, } } diff --git a/src/vs/platform/agentHost/LOCAL_ENDPOINT.md b/src/vs/platform/agentHost/LOCAL_ENDPOINT.md index cb8ce75fbbe403..86b7426da05753 100644 --- a/src/vs/platform/agentHost/LOCAL_ENDPOINT.md +++ b/src/vs/platform/agentHost/LOCAL_ENDPOINT.md @@ -76,7 +76,6 @@ The legacy `metadata.json` fallback holds a JSON **array** of these same entry o | `endpoint` | Discriminated union describing how to connect: `{ "type": "socket", "path": string }` for a Windows named pipe or Unix domain socket (used by the editor today), or `{ "type": "tcp", "host": string, "port": number }` for a TCP listener (used by the standalone CLI). | | `quality` | Optional. Product quality of a standalone CLI endpoint. Not part of entry identity. | | `tunnelName` | Optional. Tunnel name associated with a standalone CLI endpoint. Not part of entry identity. | -| `clientForwarding` | Optional. `true` when a standalone CLI endpoint was started with `code agent host --client-forwarding`, so its agent host forwards what clients offer to the processes it starts; omitted otherwise. Not part of entry identity. | Readers must treat every entry and field as untrusted input: diff --git a/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts b/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts index dfcc6a7f06eb56..08b71cc28628d9 100644 --- a/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts +++ b/src/vs/platform/agentHost/common/agentHostEndpointRegistry.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { vBoolean, vEnum, vLiteral, vNumber, vObj, vOptionalProp, vString, vUnion } from '../../../base/common/validation.js'; +import { vEnum, vLiteral, vNumber, vObj, vOptionalProp, vString, vUnion } from '../../../base/common/validation.js'; import type { RemoteAgentHostLocationPreference } from './remoteAgentHostLocationPreference.js'; /** @@ -57,12 +57,6 @@ export interface IAgentHostEndpointMetadata { readonly endpoint: AgentHostEndpointAddress; readonly quality?: string; readonly tunnelName?: string; - /** - * Whether the agent host forwards what clients offer to the processes it - * starts (`code agent host --client-forwarding`). Absent when it does not, - * and from writers that predate it. - */ - readonly clientForwarding?: boolean; } /** @@ -92,7 +86,6 @@ const entryValidator = vObj({ endpoint: endpointAddressValidator, quality: vOptionalProp(vString()), tunnelName: vOptionalProp(vString()), - clientForwarding: vOptionalProp(vBoolean()), }); /** @@ -128,7 +121,6 @@ export function parseAgentHostEndpointMetadataEntry(raw: unknown): IAgentHostEnd endpoint: content.endpoint, quality: content.quality, tunnelName: content.tunnelName, - ...(content.clientForwarding ? { clientForwarding: true } : {}), }; } diff --git a/src/vs/platform/agentHost/common/agentService.ts b/src/vs/platform/agentHost/common/agentService.ts index 5dd956e7fb9117..f07d8e48c70a3e 100644 --- a/src/vs/platform/agentHost/common/agentService.ts +++ b/src/vs/platform/agentHost/common/agentService.ts @@ -106,6 +106,8 @@ export interface IAgentHostIpcConnectionOptions { readonly env?: Readonly>; /** Kept separate so the server can apply resolver precedence using its own environment casing. */ readonly debugEnv?: Readonly>; + /** Asks a server to start its agent host with {@link AgentHostClientForwardingEnvVar}. */ + readonly clientForwarding?: boolean; } /** Configuration key that controls whether AHP JSONL logs are written for agent host transports. */ @@ -284,6 +286,14 @@ export const AgentHostSessionReleaseRetryMsEnvVar = 'VSCODE_AGENT_HOST_SESSION_R /** Overrides how long a changeset read waits for the file snapshots of a running Codex turn. Primarily used by integration tests. */ export const AgentHostCodexTurnEditsWaitMsEnvVar = 'VSCODE_AGENT_HOST_CODEX_TURN_EDITS_WAIT_MS'; +/** + * Set to `1` to have the agent host forward what clients advertising `vscode.clientForwarding` offer to the processes + * it starts. The VS Code CLI sets it for the server of `code agent host --client-forwarding`, as the Dev Container + * launcher starts it, and a server for the agent host it starts when an editor window asks for it with + * {@link IAgentHostIpcConnectionOptions.clientForwarding}. The agent host removes it from its environment. + */ +export const AgentHostClientForwardingEnvVar = 'VSCODE_AGENT_HOST_CLIENT_FORWARDING'; + /** * Resolves the effective enable state for a Claude/Codex provider from the * env-var value forwarded by the starter. Recognized values (case- and diff --git a/src/vs/platform/agentHost/node/agentHostClientForwarding.ts b/src/vs/platform/agentHost/node/agentHostClientForwarding.ts index 697d3e450fed1e..f0f146d65e37dc 100644 --- a/src/vs/platform/agentHost/node/agentHostClientForwarding.ts +++ b/src/vs/platform/agentHost/node/agentHostClientForwarding.ts @@ -20,6 +20,7 @@ import { createDecorator } from '../../instantiation/common/instantiation.js'; import { ILogService } from '../../log/common/log.js'; import { ITelemetryService } from '../../telemetry/common/telemetry.js'; import { clientGitCredentialOperationValidator, type ClientForwardingDescription, type ClientForwardingSocket, type ClientGitConfig, type ClientGitCredentialOperation, type ClientGpgKeys } from '../common/clientForwardingProtocol.js'; +import { AgentHostClientForwardingEnvVar } from '../common/agentService.js'; import { ClientForwardingTelemetry, getClientForwardingSetup, getGitCredentialOutcome, type ClientForwardingGitConfigSetup, type ClientForwardingGitIdentitySetup, type ClientForwardingSocketOutcome, type IClientForwardingSetupState } from './agentHostClientForwardingTelemetry.js'; import { parseGpgDirs, useKeyboxdPattern } from './clientForwardingHost.js'; import { applyClientGitConfig, IClientGitConfigTarget } from './clientGitConfig.js'; @@ -30,12 +31,6 @@ import { SessionConfigKey } from '../common/sessionConfigKeys.js'; import { ActionType } from '../common/state/sessionActions.js'; import { shellEscape } from './sshRemoteAgentHostHelpers.js'; -/** - * Set to `1` by the VS Code CLI for the server of an agent host started with `code agent host --client-forwarding`, as - * the Dev Container launcher does, to have the agent host forward what its clients offer. - */ -export const AGENT_HOST_CLIENT_FORWARDING_ENV = 'VSCODE_AGENT_HOST_CLIENT_FORWARDING'; - export const IAgentHostClientForwardingService = createDecorator('agentHostClientForwardingService'); /** @@ -45,7 +40,7 @@ export const IAgentHostClientForwardingService = createDecorator { for (const connection of this._connections.values()) { diff --git a/src/vs/platform/agentHost/node/devContainerAgentHostService.ts b/src/vs/platform/agentHost/node/devContainerAgentHostService.ts index c99d04a4058999..aa48b948c620fe 100644 --- a/src/vs/platform/agentHost/node/devContainerAgentHostService.ts +++ b/src/vs/platform/agentHost/node/devContainerAgentHostService.ts @@ -49,6 +49,7 @@ import { IDevContainerSecurityOptions, IDevContainerStateErrorValues, IDevContai import { prepareOwnerOnlyDirectory } from './localAgentHostMetadata.js'; import { ensureRemoteAgentHostCliInstalled } from './remoteAgentHostCliInstaller.js'; import { + AgentHostStartError, COLD_AGENT_HOST_REGISTRATION_TIMEOUT_MS, DETECT_MUSL_COMMAND, ISshExec, @@ -61,7 +62,7 @@ import { resolveRemotePlatform, runAgentEndpoints, shellEscape, - waitForNewStandaloneEndpoint, + waitForStartedStandaloneEndpoint, } from './sshRemoteAgentHostHelpers.js'; const LOG_PREFIX = '[DevContainerAgentHost]'; @@ -467,42 +468,41 @@ export abstract class DevContainerAgentHostService extends Disposable implements reportCacheStatus: message => this._reportOutput(config.connectionId, `${message}\n`), }); const { cliBin } = cliInstallation; - // The client's own CLI and the latest one dev builds use have the option; an older fallback CLI does not. - const clientForwarding = cliInstallation.fallbackVersion === undefined || cliVersionSupportsClientForwarding(cliInstallation.fallbackVersion); - if (!clientForwarding) { - this._logService.warn(`${LOG_PREFIX} Fallback CLI ${cliInstallation.fallbackVersion} cannot start an Agent Host that forwards Git credentials and agents`); - } const cliDataDir = getRemoteCLIDataDir(serverDataFolderName); const initial = await runAgentEndpoints(exec, cliBin, cliDataDir); const live = await filterLiveAgentHostEndpoints(exec, initial.endpoints); - // Only an Agent Host started with forwarding forwards, not, e.g., one a remote editor's server started. - let endpoint = selectAgentHostEndpoint(clientForwarding ? live.filter(entry => entry.clientForwarding) : live, this._productService.quality, undefined); + let endpoint = selectAgentHostEndpoint(live, this._productService.quality, undefined); if (!endpoint) { - const sessionId = this._telemetryService.sessionId; - const spawnCommand = `${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(sessionId)} ${buildAgentHostSpawnCommand( + // The Agent Host keeps this command running, so it cannot share the startup shell. + const start = (forwarding: boolean) => this._createExec(config.connectionId, execSelector, tokenSource.token, sandboxEnvironment)(`${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(this._telemetryService.sessionId)} ${buildAgentHostSpawnCommand( cliBin, serverDataFolderName, initial.userDataPath, telemetryLevelToAgentHostValue(this._telemetryService.telemetryLevel), - { clientForwarding }, - )}`; - // The Agent Host keeps this command running, so it cannot share the startup shell. - void this._createExec(config.connectionId, execSelector, tokenSource.token, sandboxEnvironment)(spawnCommand, { ignoreExitCode: true }).catch(error => { - this._logService.warn(`${LOG_PREFIX} Agent Host spawn command failed`, error); - }); - this._logService.info(`${LOG_PREFIX} Waiting for the new agent host to register...`); - endpoint = await waitForNewStandaloneEndpoint( - exec, - cliBin, - cliDataDir, - initial.userDataPath, - live, - { + { clientForwarding: forwarding }, + )}`, { ignoreExitCode: true }); + const waitForRegistration = (started: ReturnType) => { + this._logService.info(`${LOG_PREFIX} Waiting for the new agent host to register...`); + return waitForStartedStandaloneEndpoint(started, exec, cliBin, cliDataDir, initial.userDataPath, live, { timeoutMs: COLD_AGENT_HOST_REGISTRATION_TIMEOUT_MS, token: tokenSource.token, progress: elapsedMs => this._logService.info(`${LOG_PREFIX} Waiting for the new agent host to register... (${Math.floor(elapsedMs / 1000)} seconds elapsed)`), - }, - ); + }); + }; + // The client's own CLI and the latest one dev builds use have the option; an older fallback CLI does not. + const clientForwarding = cliInstallation.fallbackVersion === undefined || cliVersionSupportsClientForwarding(cliInstallation.fallbackVersion); + if (!clientForwarding) { + this._logService.warn(`${LOG_PREFIX} Fallback CLI ${cliInstallation.fallbackVersion} cannot start an Agent Host that forwards Git credentials and agents`); + } + try { + endpoint = await waitForRegistration(start(clientForwarding)); + } catch (error) { + if (!clientForwarding || !(error instanceof AgentHostStartError) || !error.rejectsClientForwarding) { + throw error; + } + this._logService.warn(`${LOG_PREFIX} The CLI does not support --client-forwarding; starting an Agent Host that does not forward Git credentials and agents`); + endpoint = await waitForRegistration(start(false)); + } } const relayCommand = `${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(this._telemetryService.sessionId)} ${buildAgentRelayCommand(cliBin, cliDataDir, endpoint.instanceId, initial.userDataPath)}`; diff --git a/src/vs/platform/agentHost/node/serviceBootstrapping.md b/src/vs/platform/agentHost/node/serviceBootstrapping.md index b6d44de15556de..fa353c71401a90 100644 --- a/src/vs/platform/agentHost/node/serviceBootstrapping.md +++ b/src/vs/platform/agentHost/node/serviceBootstrapping.md @@ -57,7 +57,7 @@ The same clients, and remote-editor connections under the same `useHostProxy` ga The Copilot runtime gets proxies from the Agent Host through the SDK's network callbacks rather than proxy environment variables, which would also apply to the tools it runs. The runtime resolves each request's proxy with the `network.resolveProxy` callback, which applies the Agent Host's proxy precedence above and passes on the full PAC-style list, so the runtime can fail over to the fallback proxies a client resolves. When none of `http.noProxy`, `http.proxy`, the proxy environment variables or a connected client decides, for example while no client is connected, or when system proxy discovery is disabled, the callback gives no answer, and the runtime resolves that proxy itself from the environment and the operating system's settings. A PAC-style answer cannot carry credentials, so the callback answers an `http.proxy` setting with credentials without them, and gives no answer for a proxy environment variable with credentials: the runtime inherits the proxy environment variables of the Agent Host unchanged and uses that one itself. The runtime gets Kerberos tokens through the `network.authenticateNegotiate` callback: this machine's ticket for exactly the principal the runtime requests, else one from a client sharing its network. It gets Basic proxy credentials through the `network.authenticateBasic` callback: on the first challenge for the proxy of an `http.proxy` setting with credentials, those of the setting, like the Agent Host's own requests, and after the proxy rejects them, those of the setting again only when they changed since; otherwise from a local renderer, which serves those of the `http.proxy` setting until the proxy rejects them, then its stored credentials or its proxy login dialog, else from a client sharing its network under the restrictions above. Each runtime keeps the credentials it was answered until the proxy rejects them, so after a rejection, the Agent Host first answers a client's current credentials, which a login dialog for another runtime may already have replaced, and asks the client for others only when the proxy rejected those: when the password changes, the runtimes of the local and a WSL Agent Host share one login dialog. Credentials are not written to the runtime's environment or disk. Clients connecting or leaving, or `http.proxy` and `http.noProxy` changing, don't restart the runtime. -An Agent Host started with `code agent host --client-forwarding`, as the Dev Container launcher does, forwards what clients advertising the optional `vscode.clientForwarding` capability offer to the processes it starts, such as the Copilot runtime and terminals, like the Dev Containers extension forwards them into a container: the client machine's Git configuration and identity, Git credentials, SSH agent and GPG agent. The CLI records the flag as `clientForwarding` in the Agent Host's endpoint registry entry, so a launcher reuses only Agent Hosts started with it, and sets `VSCODE_AGENT_HOST_CLIENT_FORWARDING=1` for the server it starts, which passes it on to its Agent Host; without the flag, the CLI removes the variable. Only such an Agent Host confirms the capability in its initialize result. Processes get their environment when they start, so it is set up once, when the Agent Host starts: the Agent Host listens on sockets in an owner-only folder, points `SSH_AUTH_SOCK` to its SSH socket, and appends a credential helper to the configuration Git reads from the environment after its files, `GIT_CONFIG_COUNT` or, before Git 2.31, `GIT_CONFIG_PARAMETERS`, so the configured helpers come first and a reset of the helper list in a file does not remove it. It asks each client what it offers with `vscode/forwarding/describe`; the newest client offering something serves it. A connection to the SSH socket goes to that client's agent, else to the agent the Agent Host had, else gets the answers of an agent without keys. The Git helper runs with the Agent Host's Node.js and gets credentials from that client through `vscode/forwarding/gitCredential`, which runs `git credential fill`, `approve` or `reject` in the client machine's shell environment; without a client or an answer, Git continues with its other helpers. For each connection to an agent, the Agent Host opens a client connection with `vscode/forwarding/open`; both sides then send the connection's data and closing as `vscode/forwarding/data` and `vscode/forwarding/close` notifications, which have no flow control, as agents exchange small messages. On Linux and macOS, while a client offers its GPG agent and unless GnuPG there has private keys of its own, the Agent Host listens on GnuPG's standard agent socket and, when the client uses `keyboxd`, on its `keyboxd` socket, enabling `keyboxd` without existing keyrings, and imports the client's public keys, certificates and owner trust from `vscode/forwarding/gpgKeys` once it listens, so no agent of its own starts; after a failed import, the next client retries it. All its processes share this environment, so while one of the Agent Host's sessions has terminal sandboxing on, it forwards none of its clients' agents and credentials: it closes open connections, its SSH socket answers as an agent without keys and the Git helper without credentials, also for a request that was pending when sandboxing turned on. Like the Dev Containers extension's `forward*` resolver properties and `forwardingUse` event, it reports what each client connection forwards as `agentHost.forwardingSetup`, and the first use of each forwarded service per client connection, operation and outcome as `agentHost.forwardingUse`, with fixed values only, such as a category of a credential request's host; its own import of GPG keys is not use. Its protocol debug logs redact forwarded agent data, credentials and Git configuration. +An Agent Host started with `code agent host --client-forwarding`, as the Dev Container launcher does, forwards what clients advertising the optional `vscode.clientForwarding` capability offer to the processes it starts, such as the Copilot runtime and terminals, like the Dev Containers extension forwards them into a container: the client machine's Git configuration and identity, Git credentials, SSH agent and GPG agent. So does the Agent Host that the server of an editor window connected to a Dev Container starts, which the launcher reuses: the window asks for it with the `clientForwarding` connection option. The CLI with the flag, or the server, starts the Agent Host with `VSCODE_AGENT_HOST_CLIENT_FORWARDING=1`; without the flag, the CLI removes the variable. Only such an Agent Host confirms the capability in its initialize result. Processes get their environment when they start, so it is set up once, when the Agent Host starts: the Agent Host listens on sockets in an owner-only folder, points `SSH_AUTH_SOCK` to its SSH socket, and appends a credential helper to the configuration Git reads from the environment after its files, `GIT_CONFIG_COUNT` or, before Git 2.31, `GIT_CONFIG_PARAMETERS`, so the configured helpers come first and a reset of the helper list in a file does not remove it. It asks each client what it offers with `vscode/forwarding/describe`; the newest client offering something serves it. A connection to the SSH socket goes to that client's agent, else to the agent the Agent Host had, else gets the answers of an agent without keys. The Git helper runs with the Agent Host's Node.js and gets credentials from that client through `vscode/forwarding/gitCredential`, which runs `git credential fill`, `approve` or `reject` in the client machine's shell environment; without a client or an answer, Git continues with its other helpers. For each connection to an agent, the Agent Host opens a client connection with `vscode/forwarding/open`; both sides then send the connection's data and closing as `vscode/forwarding/data` and `vscode/forwarding/close` notifications, which have no flow control, as agents exchange small messages. On Linux and macOS, while a client offers its GPG agent and unless GnuPG there has private keys of its own, the Agent Host listens on GnuPG's standard agent socket and, when the client uses `keyboxd`, on its `keyboxd` socket, enabling `keyboxd` without existing keyrings, and imports the client's public keys, certificates and owner trust from `vscode/forwarding/gpgKeys` once it listens, so no agent of its own starts; after a failed import, the next client retries it. All its processes share this environment, so while one of the Agent Host's sessions has terminal sandboxing on, it forwards none of its clients' agents and credentials: it closes open connections, its SSH socket answers as an agent without keys and the Git helper without credentials, also for a request that was pending when sandboxing turned on. Like the Dev Containers extension's `forward*` resolver properties and `forwardingUse` event, it reports what each client connection forwards as `agentHost.forwardingSetup`, and the first use of each forwarded service per client connection, operation and outcome as `agentHost.forwardingUse`, with fixed values only, such as a category of a credential request's host; its own import of GPG keys is not use. Its protocol debug logs redact forwarded agent data, credentials and Git configuration. With `vscode/forwarding/gitConfig`, the Agent Host gets the Git identity the client uses for the workspace folder, following its conditional includes, and, from clients that offer it while none of its sessions is sandboxed, also when the client answers, their global Git configuration and the files in their home folder that settings name, such as allowed signers. Like the Dev Containers extension, it copies the client's `~/.gitconfig` only where it has none or one with only `[filter]`, `[safe]` or `[user]` sections, and only once, marking the copy with a comment, and the client's XDG configuration only where it has none. It then removes from the copied files what cannot work there: editors and programs it lacks, a TLS backend, except on Windows, whose Git supports several, credential helpers whose commands it lacks (with their URL's reset of the helper list), and commit and tag signing that neither an agent the client forwards nor a key of its own supports; GnuPG with keys of its own does not use the client's agent, so the signing key must then be one of them. It sets the client's identity where it has none, and after copying, where the copy's differs because of the client folder's conditional includes or adds a second value. It asks the client only when there is something to do. It answers `initialize` once its environment is in place, waiting at most 10 seconds for its own startup but not for clients: the Git configuration follows in the background. Relay connections never forward. diff --git a/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts b/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts index 089094ef8c6c93..ea635851b6b25f 100644 --- a/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts +++ b/src/vs/platform/agentHost/node/sshRemoteAgentHostHelpers.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { timeout } from '../../../base/common/async.js'; -import { CancellationToken } from '../../../base/common/cancellation.js'; -import { CancellationError } from '../../../base/common/errors.js'; +import { CancellationToken, CancellationTokenSource } from '../../../base/common/cancellation.js'; +import { CancellationError, isCancellationError } from '../../../base/common/errors.js'; import { vArray, vObj, vString, vUnknown } from '../../../base/common/validation.js'; import { TelemetryConfiguration } from '../../telemetry/common/telemetry.js'; import { getAgentHostEndpointIdentityKey, IAgentHostEndpointMetadata, parseAgentHostEndpointRegistry } from '../common/agentHostEndpointRegistry.js'; @@ -597,3 +597,51 @@ export async function waitForNewStandaloneEndpoint( } } } + +/** The command that starts an agent host, e.g., {@link buildAgentHostSpawnCommand}, exited with an error. */ +export class AgentHostStartError extends Error { + constructor(readonly code: number, readonly stderr: string) { + super(`The agent host start command failed (exit code ${code})${stderr.trim() ? `: ${stderr.trim()}` : ''}`); + } + + /** Whether the CLI does not know `--client-forwarding`, as 1.149 builds from before it do not. */ + get rejectsClientForwarding(): boolean { + return this.stderr.includes('unexpected argument \'--client-forwarding\''); + } +} + +/** + * Like {@link waitForNewStandaloneEndpoint}, but stops waiting as soon as `start`, the command starting the agent + * host, fails: when it exits with an error, with an {@link AgentHostStartError}. The command may also end + * successfully before the agent host registers, once the CLI started it in the background. + */ +export async function waitForStartedStandaloneEndpoint( + start: ReturnType, + exec: ISshExec, + cliBin: string, + cliDataDir: string, + userDataPath: string, + before: readonly IAgentHostEndpointMetadata[], + options?: IWaitForNewEndpointOptions, +): Promise { + const waiting = new CancellationTokenSource(options?.token); + const failed = new Promise((_resolve, reject) => { + void start.then(({ code, stderr }) => { + if (code !== 0) { + reject(new AgentHostStartError(code, stderr)); + } + }, error => { + if (!isCancellationError(error)) { + reject(error); + } + }); + }); + try { + return await Promise.race([ + waitForNewStandaloneEndpoint(exec, cliBin, cliDataDir, userDataPath, before, { ...options, token: waiting.token }), + failed, + ]); + } finally { + waiting.dispose(true); + } +} diff --git a/src/vs/platform/agentHost/test/node/agentHostClientForwarding.test.ts b/src/vs/platform/agentHost/test/node/agentHostClientForwarding.test.ts index db537dced188b5..d41350691cb625 100644 --- a/src/vs/platform/agentHost/test/node/agentHostClientForwarding.test.ts +++ b/src/vs/platform/agentHost/test/node/agentHostClientForwarding.test.ts @@ -17,7 +17,8 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/c import { mock } from '../../../../base/test/common/mock.js'; import { NullLogService } from '../../../log/common/log.js'; import { ITelemetryData, ITelemetryService, TelemetryLevel } from '../../../telemetry/common/telemetry.js'; -import { AGENT_HOST_CLIENT_FORWARDING_ENV, AgentHostClientForwardingService, IAgentHostForwardingClient } from '../../node/agentHostClientForwarding.js'; +import { AgentHostClientForwardingService, IAgentHostForwardingClient } from '../../node/agentHostClientForwarding.js'; +import { AgentHostClientForwardingEnvVar } from '../../common/agentService.js'; import { AgentHostClientForwardingMainService } from '../../node/agentHostClientForwardingMainService.js'; import { categorizeGitHost, categorizeProtocol, getClientForwardingSetup, parseGitCredentialRequest } from '../../node/agentHostClientForwardingTelemetry.js'; import { AgentConfigurationService } from '../../node/agentConfigurationService.js'; @@ -156,7 +157,7 @@ suite('AgentHostClientForwarding', () => { // Isolated from the machine's Git configuration, whose helpers could prompt. const environment: NodeJS.ProcessEnv = { ...process.env, - [AGENT_HOST_CLIENT_FORWARDING_ENV]: '1', + [AgentHostClientForwardingEnvVar]: '1', HOME: folder, XDG_CONFIG_HOME: join(folder, '.config'), GIT_CONFIG_NOSYSTEM: '1', @@ -273,7 +274,7 @@ suite('AgentHostClientForwarding', () => { const afterClient = { sshAuthSock: environment.SSH_AUTH_SOCK === sshAuthSock, reply: [...await request(requestIdentities)] }; const use = (clientId: string | undefined, forwarded: string, operation: string, outcome: string, protocol?: string, hostCategory?: string) => ({ eventName: 'agentHost.forwardingUse', data: { clientId, service: forwarded, operation, outcome, protocol, hostCategory } }); assert.deepStrictEqual({ - launcherVariable: environment[AGENT_HOST_CLIENT_FORWARDING_ENV], + launcherVariable: environment[AgentHostClientForwardingEnvVar], gitConfig: [environment.GIT_CONFIG_KEY_0, environment.GIT_CONFIG_VALUE_0, environment.GIT_CONFIG_KEY_1], withoutClient, agentReply, @@ -317,7 +318,7 @@ suite('AgentHostClientForwarding', () => { test('reports a connection that sandboxing closed while the client was connecting to its agent as sandboxed', async () => { const folder = await mkdtemp(join(tmpdir(), 'vscode-ah-fwd-test-')); - const environment: NodeJS.ProcessEnv = { ...process.env, [AGENT_HOST_CLIENT_FORWARDING_ENV]: '1', HOME: folder, XDG_CONFIG_HOME: join(folder, '.config'), GIT_CONFIG_NOSYSTEM: '1' }; + const environment: NodeJS.ProcessEnv = { ...process.env, [AgentHostClientForwardingEnvVar]: '1', HOME: folder, XDG_CONFIG_HOME: join(folder, '.config'), GIT_CONFIG_NOSYSTEM: '1' }; delete environment.SSH_AUTH_SOCK; delete environment.GIT_CONFIG_GLOBAL; const stateManager = store.add(new AgentHostStateManager(new NullLogService())); diff --git a/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts b/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts index 92904eb2c035f1..8d4ebddd840eab 100644 --- a/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts +++ b/src/vs/platform/agentHost/test/node/agentHostEndpointRegistry.test.ts @@ -84,16 +84,6 @@ suite('Agent Host Endpoint Registry (schema v2)', () => { ); }); - test('keeps whether an endpoint forwards what clients offer', () => { - const entry = createEntry({ type: 'standalone', endpoint: { type: 'tcp', host: '127.0.0.1', port: 12345 } }); - assert.deepStrictEqual([ - parseAgentHostEndpointMetadataEntry({ ...entry, clientForwarding: true })?.clientForwarding, - Object.hasOwn(parseAgentHostEndpointMetadataEntry({ ...entry, clientForwarding: false })!, 'clientForwarding'), - Object.hasOwn(parseAgentHostEndpointMetadataEntry(entry)!, 'clientForwarding'), - parseAgentHostEndpointMetadataEntry({ ...entry, clientForwarding: 'true' }), - ], [true, false, false, undefined]); - }); - test('ignores unsupported schema versions without failing the whole array', () => { const current = createEntry({ instanceId: 'current' }); const raw = [ diff --git a/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts b/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts index 38e5314c674dd5..b7ab7aa6628120 100644 --- a/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts +++ b/src/vs/platform/agentHost/test/node/devContainerAgentHostService.test.ts @@ -42,7 +42,7 @@ import { URI } from '../../../../base/common/uri.js'; import { DevContainerAgentHostMainService, getDevContainerCliPath, getDevContainerExecArgs, IDevContainerRelay, IDevContainerShellExec, parseDevContainerFolderContainers, parseDevContainerMounts, parseDevContainerUpResult, RemoteDevContainerAgentHostService, waitForDevContainerRelayConnection } from '../../node/devContainerAgentHostService.js'; import { getDefaultDevContainerIdLabels, getDevContainerSecurityOptions, getDevContainerStateVolumeLabels, IDevContainerSecurityOptions } from '../../node/devContainerState.js'; import { ISshExec, shellEscape } from '../../node/sshRemoteAgentHostHelpers.js'; -import { AGENT_HOST_CLIENT_FORWARDING_ENV } from '../../node/agentHostClientForwarding.js'; +import { AgentHostClientForwardingEnvVar } from '../../common/agentService.js'; import { devContainerServerCacheMount } from '../../node/devContainerServerCache.js'; import { DevContainerSample } from '../../common/devContainerSamples.js'; import { IPreparedDevContainerSample } from '../../node/devContainerSamples.js'; @@ -118,7 +118,6 @@ class TestDevContainerAgentHostMainService extends DevContainerAgentHostMainServ protocolVersion: '1', connectionToken: 'token', endpoint: { type: 'tcp', host: '127.0.0.1', port: 1234 }, - clientForwarding: true, }]; containerSessionIds: string[] = [NullTelemetryService.sessionId]; endpointPollsBeforeAvailable = 0; @@ -157,6 +156,8 @@ class TestDevContainerAgentHostMainService extends DevContainerAgentHostMainServ cliCacheSetupError: Error | undefined; /** The `--version` output of a fallback CLI, used because installing the client's own CLI fails. */ fallbackCliVersion: string | undefined; + /** The exit code and error output of a failing Agent Host start command. */ + startFailure: ((command: string) => { readonly code: number; readonly stderr: string } | undefined) | undefined; cacheMountConfigured = false; hostDirectoryOwnedByCurrentUser = true; readonly checkedHostDirectories: string[] = []; @@ -494,6 +495,10 @@ class TestDevContainerAgentHostMainService extends DevContainerAgentHostMainServ }; } if (command.includes(`${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=`)) { + const failure = this.startFailure?.(command); + if (failure) { + return { stdout: '', ...failure }; + } this._spawnedAgentHost = true; } return { stdout: '', stderr: '', code: 0 }; @@ -1614,32 +1619,47 @@ suite('Dev Container Agent Host Main Service', () => { }, { sharedServer: true, warning: true, cacheCommands: 0, privateDownloads: 1 }); }); - test('starts or reuses only an Agent Host that forwards what its clients offer, unless an older fallback CLI cannot start one', async () => { + test('starts an Agent Host that forwards what its clients offer, unless the CLI cannot', async () => { + const commit = 'a'.repeat(40); + const version = (minor: number) => `code-insiders 1.${minor}.0 (commit ${'0'.repeat(40)})`; + const rejectsFlag = (command: string) => command.endsWith(' --client-forwarding') ? { code: 2, stderr: 'error: unexpected argument \'--client-forwarding\' found\n' } : undefined; const results: Record = {}; - for (const { label, commit, fallbackCliVersion } of [ - { label: 'own CLI', commit: 'a'.repeat(40), fallbackCliVersion: undefined }, - { label: 'dev build', commit: undefined, fallbackCliVersion: undefined }, - { label: '1.148 fallback', commit: 'a'.repeat(40), fallbackCliVersion: `code-insiders 1.148.0 (commit ${'0'.repeat(40)})` }, - { label: '1.149 fallback', commit: 'a'.repeat(40), fallbackCliVersion: `code-insiders 1.149.0 (commit ${'0'.repeat(40)})` }, + for (const { label, commit: productCommit, fallbackCliVersion, startFailure } of [ + { label: 'own CLI', commit }, + { label: 'dev build' }, + { label: '1.148 fallback', commit, fallbackCliVersion: version(148) }, + { label: '1.149 fallback', commit, fallbackCliVersion: version(149) }, + { label: '1.149 fallback without the flag', commit, fallbackCliVersion: version(149), startFailure: rejectsFlag }, ]) { - const service = store.add(new TestDevContainerAgentHostMainService('', false, undefined, process.env, true, [], new Set(), '/tmp', new NullLogService(), commit)); + const service = store.add(new TestDevContainerAgentHostMainService('', false, undefined, process.env, true, [], new Set(), '/tmp', new NullLogService(), productCommit)); service.fallbackCliVersion = fallbackCliVersion; - // E.g., the Agent Host a remote editor's server started. - service.endpoints = [{ ...service.endpoints[0], clientForwarding: undefined }]; + service.startFailure = startFailure; + service.endpoints = [{ ...service.endpoints[0], quality: 'stable' }]; await service.connect({ connectionId: label, workspaceFolder: '/workspace', name: 'Project Dev Container' }); results[label] = { - spawned: service.separateExecs.map(({ command }) => ({ flag: command.endsWith(' --client-forwarding'), variable: command.includes(AGENT_HOST_CLIENT_FORWARDING_ENV) })), + spawned: service.separateExecs.map(({ command }) => ({ flag: command.endsWith(' --client-forwarding'), variable: command.includes(AgentHostClientForwardingEnvVar) })), relaysTo: service.relayCommand?.match(/ agent relay '(?[^']+)'/)?.groups?.instance, }; } assert.deepStrictEqual(results, { 'own CLI': { spawned: [{ flag: true, variable: false }], relaysTo: 'spawned-instance' }, 'dev build': { spawned: [{ flag: true, variable: false }], relaysTo: 'spawned-instance' }, - '1.148 fallback': { spawned: [], relaysTo: 'instance' }, + '1.148 fallback': { spawned: [{ flag: false, variable: false }], relaysTo: 'spawned-instance' }, '1.149 fallback': { spawned: [{ flag: true, variable: false }], relaysTo: 'spawned-instance' }, + '1.149 fallback without the flag': { spawned: [{ flag: true, variable: false }, { flag: false, variable: false }], relaysTo: 'spawned-instance' }, }); }); + test('stops waiting for the Agent Host to register as soon as its start command fails', async () => { + const service = store.add(new TestDevContainerAgentHostMainService()); + service.endpoints = [{ ...service.endpoints[0], quality: 'stable' }]; + service.startFailure = () => ({ code: 1, stderr: 'error: No space left on device\n' }); + const stages: string[] = []; + store.add(service.onDidFailConnect(failure => stages.push(failure.stage))); + await assert.rejects(service.connect({ connectionId: 'failing', workspaceFolder: '/workspace', name: 'Project' }), /exit code 1\): error: No space left on device$/); + assert.deepStrictEqual({ stages, starts: service.separateExecs.length }, { stages: ['agentHostStart'], starts: 1 }); + }); + test('adds the exact bind-mounted repository root to Git safe.directory only when host-owned', async () => { const configured = store.add(new TestDevContainerAgentHostMainService()); configured.remoteWorkspaceFolder = '/workspaces/project/folder'; diff --git a/src/vs/server/node/agentHostChannel.ts b/src/vs/server/node/agentHostChannel.ts index 4c7887b283d510..afbae0d360b93d 100644 --- a/src/vs/server/node/agentHostChannel.ts +++ b/src/vs/server/node/agentHostChannel.ts @@ -43,7 +43,8 @@ function isConnectionOptions(value: unknown): value is IAgentHostIpcConnectionOp return isObject(value) && (!('env' in value) || isEnvironment(value.env)) && (!('debugEnv' in value) || isEnvironment(value.debugEnv)) - && (!('preferredAgentLocation' in value) || value.preferredAgentLocation === undefined || isRemoteAgentHostLocationPreference(value.preferredAgentLocation)); + && (!('preferredAgentLocation' in value) || value.preferredAgentLocation === undefined || isRemoteAgentHostLocationPreference(value.preferredAgentLocation)) + && (!('clientForwarding' in value) || value.clientForwarding === undefined || typeof value.clientForwarding === 'boolean'); } function isEnvironment(value: unknown): value is IAgentHostIpcConnectionOptions['env'] { diff --git a/src/vs/server/node/serverAgentHostEnvironment.ts b/src/vs/server/node/serverAgentHostEnvironment.ts index 561268c55c8b50..80cd3b5842f8b1 100644 --- a/src/vs/server/node/serverAgentHostEnvironment.ts +++ b/src/vs/server/node/serverAgentHostEnvironment.ts @@ -9,7 +9,7 @@ import { CancellationError, getErrorCode } from '../../base/common/errors.js'; import { Disposable } from '../../base/common/lifecycle.js'; import { isAbsolute, join } from '../../base/common/path.js'; import { isWindows } from '../../base/common/platform.js'; -import type { IAgentHostIpcConnectionOptions } from '../../platform/agentHost/common/agentService.js'; +import { AgentHostClientForwardingEnvVar, type IAgentHostIpcConnectionOptions } from '../../platform/agentHost/common/agentService.js'; import { ILogService } from '../../platform/log/common/log.js'; import type { RemoteAgentConnectionContext } from '../../platform/remote/common/remoteAgentEnvironment.js'; @@ -22,6 +22,8 @@ export class ServerAgentHostEnvironment extends Disposable { private readonly _updates = new Sequencer(); private _directory: string | undefined; private readonly _targets = new Map(); + /** Kept once a window asked for it: other clients, e.g., the Agents window's Dev Container connections, may still use a restarted agent host. */ + private _clientForwarding = false; constructor( private readonly _setLaunchEnvironment: (env: Environment, debugEnv?: Environment) => void, @@ -38,6 +40,7 @@ export class ServerAgentHostEnvironment extends Disposable { if (options?.env || options?.debugEnv) { this._windows.set(ctx, options); } + this._clientForwarding ||= options?.clientForwarding === true; return this._updates.queue(() => this._refresh()); } @@ -59,6 +62,9 @@ export class ServerAgentHostEnvironment extends Disposable { } } } + if (this._clientForwarding) { + env[AgentHostClientForwardingEnvVar] = '1'; + } this._setLaunchEnvironment(env, latest?.debugEnv); } diff --git a/src/vs/server/test/node/agentHostChannel.test.ts b/src/vs/server/test/node/agentHostChannel.test.ts index 849946e6e781cf..bc6b0c4f556ef8 100644 --- a/src/vs/server/test/node/agentHostChannel.test.ts +++ b/src/vs/server/test/node/agentHostChannel.test.ts @@ -179,14 +179,14 @@ suite('AgentHostChannel', () => { debugEnv: { Github_Token: 'debug-token' }, preferredAgentLocation: 'editor', }); - await channel.call('second', 'connect', { env: { GITHUB_TOKEN: 'refreshed-codespace-token' }, preferredAgentLocation: 'dedicated' }); + await channel.call('second', 'connect', { env: { GITHUB_TOKEN: 'refreshed-codespace-token' }, preferredAgentLocation: 'dedicated', clientForwarding: true }); await channel.call('third', 'connect'); assert.deepStrictEqual({ beforeConnect, options: Object.fromEntries(options) }, { beforeConnect: 0, options: { first: { env: { GITHUB_TOKEN: 'codespace-token', GH_TOKEN: null, EMPTY: '' }, debugEnv: { Github_Token: 'debug-token' }, preferredAgentLocation: 'editor' }, - second: { env: { GITHUB_TOKEN: 'refreshed-codespace-token' }, preferredAgentLocation: 'dedicated' }, + second: { env: { GITHUB_TOKEN: 'refreshed-codespace-token' }, preferredAgentLocation: 'dedicated', clientForwarding: true }, third: undefined, }, }); @@ -212,7 +212,7 @@ suite('AgentHostChannel', () => { () => ds.add(new FakeUpstream()), )); - for (const options of [null, [], 'secret', { env: null }, { env: [] }, { env: 'secret' }, { env: { GITHUB_TOKEN: 123 } }, { debugEnv: null }, { debugEnv: [] }, { debugEnv: 'secret' }, { debugEnv: { GITHUB_TOKEN: 123 } }, { preferredAgentLocation: null }, { preferredAgentLocation: 'standalone' }, { preferredAgentLocation: {} }, { preferredAgentLocation: 1 }]) { + for (const options of [null, [], 'secret', { env: null }, { env: [] }, { env: 'secret' }, { env: { GITHUB_TOKEN: 123 } }, { debugEnv: null }, { debugEnv: [] }, { debugEnv: 'secret' }, { debugEnv: { GITHUB_TOKEN: 123 } }, { preferredAgentLocation: null }, { preferredAgentLocation: 'standalone' }, { preferredAgentLocation: {} }, { preferredAgentLocation: 1 }, { clientForwarding: null }, { clientForwarding: 'true' }]) { await assert.rejects(channel.call('renderer', 'connect', options), /Invalid agent host connection options/); } assert.strictEqual(resolveCount, 0); diff --git a/src/vs/server/test/node/serverAgentHostEnvironment.test.ts b/src/vs/server/test/node/serverAgentHostEnvironment.test.ts index 81789cd707e195..707d6447433290 100644 --- a/src/vs/server/test/node/serverAgentHostEnvironment.test.ts +++ b/src/vs/server/test/node/serverAgentHostEnvironment.test.ts @@ -8,6 +8,7 @@ import { readlink } from 'fs/promises'; import { isWindows } from '../../../base/common/platform.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { NullLogService } from '../../../platform/log/common/log.js'; +import { AgentHostClientForwardingEnvVar } from '../../../platform/agentHost/common/agentService.js'; import { ServerAgentHostEnvironment } from '../../node/serverAgentHostEnvironment.js'; suite('ServerAgentHostEnvironment', () => { @@ -28,6 +29,17 @@ suite('ServerAgentHostEnvironment', () => { assert.deepStrictEqual(snapshots, [first, { ...second, debugEnv: undefined }, first, { env: {}, debugEnv: undefined }]); }); + test('starts the agent host forwarding what clients offer once a window asked for it, also after it left', async () => { + const launches: Readonly>[] = []; + const environment = store.add(new ServerAgentHostEnvironment(env => launches.push(env), new NullLogService())); + await environment.update(agents, undefined); + await environment.update(editor, { clientForwarding: true }); + await environment.remove(editor); + await environment.update(agents, { env: { OTHER: 'value' } }); + + assert.deepStrictEqual(launches, [{}, { [AgentHostClientForwardingEnvVar]: '1' }, { [AgentHostClientForwardingEnvVar]: '1', OTHER: 'value' }]); + }); + (isWindows ? test.skip : test)('inherited socket paths follow a live resolver across connects, removals and restarts', async () => { let launch: Readonly> = {}; const environment = store.add(new ServerAgentHostEnvironment(env => launch = env, new NullLogService())); diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md index 136e5464344a36..f39a00f0882282 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md @@ -214,7 +214,7 @@ Desktop-local containers honor the user setting `dev.containers.dockerPath` for Windows hosts can also run containers in WSL containers (`wslc.exe`), as a second engine next to that Docker executable. The CLI drives WSLc through `--docker-path`; the launcher runs its own Docker commands with WSLc too, evaluating their Go-template `--format` arguments on WSLc's JSON output, since WSLc formats only JSON and tables. A host reports its available engines, and the engine that already has a source's container or volume, through `vscode/devContainers/getEngines` behind the `vscode.devContainerEngines` capability; older hosts run only Docker. A source's existing container, or a workspace's state volume, keeps its engine, because it holds its Agent Host's sessions, and relay reconnects keep the engine of the first connection. A workspace's lookup matches the ID labels of the configuration that `up` selects, so another configuration's container does not decide. Environments and stored workspace connections also remember the engine their connection reported, and connections, including the connection factory's rebuilds, request it, so a lookup that fails, for example while WSL starts, can neither create the container again in the other engine nor ask. Removing a workspace's container forgets its engine, so a new container gets the setting's engine. Deleting an environment removes it with the engine that has its volume, and fails rather than guess when another engine could not be checked. Only a new container gets the engine of `chat.agentHost.devContainer.containerEngine`, or the other available engine when that one is missing; with `ask`, the user picks one when both are available, and dismissing the pick cancels connecting. Folder container discovery lists the containers of the Docker engine, so its connections without user action use Docker and never ask. WSLc has no security options or devices for nested sandboxing, so its containers never receive the sandbox override below and report the support as unavailable. -The connector starts the container's Agent Host with `code agent host --client-forwarding` to forward what its clients offer, reusing only one the endpoint registry lists as started that way, and the client advertises the `vscode.clientForwarding` protocol extension (see the Agent Host's `serviceBootstrapping.md`). A fallback CLI older than 1.149, which the connector uses only when it cannot install the CLI of its own commit, lacks the flag; the connector then starts or reuses an Agent Host without forwarding. The Agent Host sets the Git user name and email of the machine the client runs on, for a local workspace those Git uses for its folder, where the container has none. Without terminal sandboxing, and unless the experimental `chat.agentHost.devContainer.credentialForwarding.enabled` setting is off, the container also gets the Git setup of the Dev Containers extension from the machine the client runs on, including for SSH, Tunnel and WSL Docker hosts: the Agent Host copies the client's Git configuration where the container has none of its own, and forwards its Git credentials, SSH agent and GPG agent to the processes it starts. Turning the setting off closes forwarded connections and stops forwarding to open connections, including credentials a credential manager is still signing in for; turning it on applies to a container's next connection. With sandboxing, the container gets only the identity, as before, and while any of its sessions is sandboxed, the Agent Host forwards nothing else to any of them, as they share its environment. Docker credentials, displays and ports are not forwarded. +The connector reuses the Agent Host running in the container, or starts one with `code agent host --client-forwarding` to forward what its clients offer, and the client advertises the `vscode.clientForwarding` protocol extension (see the Agent Host's `serviceBootstrapping.md`). The Agent Host that the server of an editor window connected to the container starts forwards too. A CLI without the flag starts an Agent Host that does not forward: the connector leaves the flag out for a fallback CLI older than 1.149, which it uses only when it cannot install the CLI of its own commit, and starts the Agent Host again without the flag when a 1.149 build from before the flag rejects it. When the start command fails otherwise, connecting fails right away instead of waiting for the Agent Host to register. The Agent Host sets the Git user name and email of the machine the client runs on, for a local workspace those Git uses for its folder, where the container has none. Without terminal sandboxing, and unless the experimental `chat.agentHost.devContainer.credentialForwarding.enabled` setting is off, the container also gets the Git setup of the Dev Containers extension from the machine the client runs on, including for SSH, Tunnel and WSL Docker hosts: the Agent Host copies the client's Git configuration where the container has none of its own, and forwards its Git credentials, SSH agent and GPG agent to the processes it starts. Turning the setting off closes forwarded connections and stops forwarding to open connections, including credentials a credential manager is still signing in for; turning it on applies to a container's next connection. With sandboxing, the container gets only the identity, as before, and while any of its sessions is sandboxed, the Agent Host forwards nothing else to any of them, as they share its environment. Docker credentials, displays and ports are not forwarded. When terminal sandboxing is selected for a new Copilot Dev Container session, startup uses a generated configuration override to add `seccomp=unconfined`, `apparmor=unconfined`, `systempaths=unconfined`, and `/dev/net/tun` device access. Image/Dockerfile containers receive Docker run arguments; user-defined `securityOpt` values retain their existing CLI precedence. Compose containers receive an additional Compose file for the configured workspace service, preserving implicit file discovery, workspace `.env` behavior, and the source version for legacy Compose. Samples receive the same run arguments. The workspace's source configuration is not modified, and relative paths retain their original base. No extra capabilities or privileged mode are added. These options relax the outer container's isolation so terminal commands can run inside a nested sandbox. An information icon after the "Sandboxing in Dev Container" toggle label draws attention to the hover explaining this tradeoff; the permission control retains its usual label. diff --git a/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts b/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts index 5576b4cc49a61d..b2face4074d3ea 100644 --- a/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts +++ b/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts @@ -131,17 +131,22 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA async () => { const hostKey = getSSHRemoteAuthorityConnectionKey(connection.remoteAuthority); const preferredAgentLocation = hostKey ? locationPreferenceService.getPreference(hostKey) : undefined; - const preference = preferredAgentLocation === undefined ? undefined : { preferredAgentLocation }; + // The Agents window's Dev Container connections may reuse the Agent Host this window's server starts. + const clientForwarding = ['dev-container', 'attached-container'].includes(getRemoteName(connection.remoteAuthority)); + const options = preferredAgentLocation === undefined && !clientForwarding ? undefined : { + ...preferredAgentLocation === undefined ? {} : { preferredAgentLocation }, + ...clientForwarding ? { clientForwarding } : {}, + }; this._useHostProxy = (await this._remoteAgentService.getRawEnvironment())?.useHostProxy === true; let resolverResult: ResolverResult; try { resolverResult = await remoteAuthorityResolverService.resolveAuthority(connection.remoteAuthority); } catch { this._logService.warn(`${LOG_PREFIX} Unable to resolve the remote environment; connecting without environment overrides.`); - return preference; + return options; } return { - ...preference, + ...options, env: resolverResult.options?.extensionHostEnv ?? {}, debugEnv: environmentService.debugExtensionHost.env, }; diff --git a/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts b/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts index 1e4275de5b9ce0..c186f8327b6ec0 100644 --- a/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts +++ b/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts @@ -162,15 +162,16 @@ suite('EditorRemoteAgentHostServiceClient', () => { return protocolClientCall?.args[2] as () => IClientTransport; } - for (const [remoteAuthority, expectedKey] of [ - ['ssh-remote+myhost', 'ssh:myhost'], - [`ssh-remote+${encodeHex(VSBuffer.fromString(JSON.stringify({ hostName: 'MyHost' })))}`, 'ssh:MyHost'], - [`ssh-remote+${encodeHex(VSBuffer.fromString(JSON.stringify({ hostName: 'myhost', user: 'me', port: 2222 })))}`, 'me@myhost:2222'], - ['ssh-remote+me@myhost:2222', 'me@myhost:2222'], - ['ssh-remote+myhost:2222', undefined], - ['tunnel+my-tunnel', undefined], - ['wsl+test', undefined], - ['dev-container+test', undefined], + for (const [remoteAuthority, expectedKey, forwarding] of [ + ['ssh-remote+myhost', 'ssh:myhost', undefined], + [`ssh-remote+${encodeHex(VSBuffer.fromString(JSON.stringify({ hostName: 'MyHost' })))}`, 'ssh:MyHost', undefined], + [`ssh-remote+${encodeHex(VSBuffer.fromString(JSON.stringify({ hostName: 'myhost', user: 'me', port: 2222 })))}`, 'me@myhost:2222', undefined], + ['ssh-remote+me@myhost:2222', 'me@myhost:2222', undefined], + ['ssh-remote+myhost:2222', undefined, undefined], + ['tunnel+my-tunnel', undefined, undefined], + ['wsl+test', undefined, undefined], + ['dev-container+test', undefined, { clientForwarding: true }], + ['attached-container+test', undefined, { clientForwarding: true }], ] as const) { test(`reads the stored location on each connection for ${remoteAuthority}, even if environment resolution fails`, async () => { const calls: unknown[] = []; @@ -191,7 +192,7 @@ suite('EditorRemoteAgentHostServiceClient', () => { await disposables.add(createTransport()).connect(); assert.deepStrictEqual({ keys, calls }, { keys: expectedKey ? [expectedKey, expectedKey, expectedKey] : [], - calls: expectedKey ? [{ preferredAgentLocation: 'editor' }, { preferredAgentLocation: 'dedicated' }, undefined] : [undefined, undefined, undefined], + calls: expectedKey ? [{ preferredAgentLocation: 'editor' }, { preferredAgentLocation: 'dedicated' }, undefined] : [forwarding, forwarding, forwarding], }); }); }