Fix TCP-based debugging in dev containers (#65778)

## Summary

Fix TCP-based debug adapters timing out in dev containers. The adapter
runs inside the container, but Zed connects to a host loopback port
whose forwarding request Docker exec silently ignores.

Add a TCP-to-stdio helper to the existing remote server so the TCP
connection is established inside the container and DAP traffic travels
over Docker exec stdio. Keep adapter logs off the DAP stream, flush
messages promptly, and terminate spawned adapters when the client
disconnects. Child and descendant sessions open new proxy connections to
the existing adapter instead of starting it again. Existing local, SSH,
WSL, and native stdio paths remain in place.

Closes #57021

## Testing

- `ITERATIONS=20 cargo test --locked --offline -p remote -p dap --lib`:
62 remote tests and 7 DAP tests passed, including child/descendant
connection reuse and existing SSH/WSL/Docker tests.
- Seven TCP helper tests passed on Linux using the exact repository
module and the real `util` crate, covering bidirectional forwarding,
flushing, adapter launch/log separation, timeout, early exit, and
cleanup after client disconnect.
- `./script/clippy -p remote -p dap` passed with all targets/features
and warnings denied.
- `cargo check --locked --offline -p project -p remote_server -p
gpui_platform --features gpui_platform/runtime_shaders` passed. The
normal macOS shader build requires the Metal Toolchain, which is
unavailable on this machine; the supported runtime-shaders feature was
used for the check.
- rustfmt checks and `git diff --check` passed.

Manual transport-level verification used Python 3.14 and debugpy 1.8.20
in a Debian-based Docker container without published ports. The previous
host-loopback connection was refused. With the Rust helper, initialize,
launch, breakpoint verification/hit, stackTrace, evaluate (`value ==
41`), continue, exit code 0, and disconnect passed. Connecting to a
separately started adapter without spawning another process also passed.

To verify in Zed, open a Python dev container with debugpy installed and
no published DAP port, start a `Debugpy` launch configuration for the
current file, set a breakpoint, inspect a variable, continue, and stop.
The user subsequently built and launched the patched Zed locally and
confirmed that the debugger works in the dev container through the Zed
GUI. Real JavaScript/SSH/WSL sessions have not been exercised; those
paths were checked through tests and compilation.

## Self-review

- [x] Reviewed the diff for quality, security, reliability, and
performance.
- [x] Tests cover the new or changed behavior.
- No UI layout changes.

## Suggested .rules additions

For the debugger crate's rules: "When adding a remote DAP transport,
preserve child-connection semantics: child and descendant sessions
reconnect to the parent adapter server without starting another adapter
process."

Release Notes:

- Fixed Python debugging with Debugpy in dev containers.

---------

Co-authored-by: Kirill Bulatov <mail4score@gmail.com>
This commit is contained in:
Dmitry Ishutkin
2026-11-27 12:23:12 +00:00
committed by GitHub
parent ae31872139
commit ed8dc1b6ca
17 changed files with 1202 additions and 47 deletions
@@ -1142,6 +1142,24 @@ async fn test_slow_adapter_startup_retries(
cx_a: &mut TestAppContext,
server_cx: &mut TestAppContext,
executor: BackgroundExecutor,
) {
test_remote_debug_session(cx_a, server_cx, executor, false).await;
}
#[gpui::test]
async fn test_remote_debug_session_uses_tcp_proxy(
cx_a: &mut TestAppContext,
server_cx: &mut TestAppContext,
executor: BackgroundExecutor,
) {
test_remote_debug_session(cx_a, server_cx, executor, true).await;
}
async fn test_remote_debug_session(
cx_a: &mut TestAppContext,
server_cx: &mut TestAppContext,
executor: BackgroundExecutor,
tcp_proxy: bool,
) {
cx_a.update(|cx| {
release_channel::init(semver::Version::new(0, 0, 0), cx);
@@ -1154,6 +1172,16 @@ async fn test_slow_adapter_startup_retries(
dap_adapters::init(cx);
});
let (opts, server_ssh, _) = RemoteClient::fake_server(cx_a, server_cx);
if tcp_proxy {
let remote::RemoteConnectionOptions::Mock(options) = &opts else {
panic!("Expected a mock connection");
};
cx_a.update(|cx| {
remote::MockConnectionRegistry::update_global(cx, |registry, _| {
registry.enable_tcp_proxy(options).unwrap();
});
});
}
let remote_fs = FakeFs::new(server_cx.executor());
remote_fs
.insert_tree(
@@ -1196,6 +1224,25 @@ async fn test_slow_adapter_startup_retries(
.build_ssh_project(path!("/code"), client_ssh.clone(), false, cx_a)
.await;
if tcp_proxy {
server_cx.update(|cx| {
SettingsStore::update_global(cx, |store, cx| {
store.update_user_settings(cx, |settings| {
settings
.project
.dap
.entry("fake-adapter".into())
.or_default()
.env = Some(HashMap::from_iter([(
"ADAPTER_TEST".into(),
"wrapped".into(),
)]));
});
});
});
}
let mut async_cx = cx_a.to_async();
let (workspace, cx_a) = client_a.build_workspace(&project_a, cx_a);
let debugger_panel = workspace
@@ -1227,18 +1274,19 @@ async fn test_slow_adapter_startup_retries(
adapter: "fake-adapter".into(),
label: "test".into(),
config: json!({
"request": "launch"
"request": "launch",
"cwd": "/code/project with spaces"
}),
tcp_connection: Some(TcpArgumentsTemplate {
port: None,
port: tcp_proxy.then_some(4567),
host: None,
timeout: None,
timeout: tcp_proxy.then_some(1234),
}),
},
move |client| {
let count = count.clone();
client.on_request_ext::<dap::requests::Initialize, _>(move |_seq, _request| {
if count.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 5 {
if !tcp_proxy && count.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 5 {
return RequestHandling::Exit;
}
RequestHandling::Respond(Ok(Capabilities::default()))
@@ -1252,6 +1300,48 @@ async fn test_slow_adapter_startup_retries(
cx_a,
|session: &mut project::debugger::session::Session, _| session.adapter_client().unwrap(),
);
if tcp_proxy {
let expected = [
"-T",
"-w",
"/code/project with spaces",
"mock-remote-server",
"tcp",
"127.0.0.1:4567",
"1234",
];
let binary = client.binary();
assert_eq!(binary.command.as_deref(), Some("mock"));
assert_eq!(
binary.arguments,
expected
.into_iter()
.chain(["--", "command"])
.collect::<Vec<_>>()
);
assert_eq!(
binary.envs.get("ADAPTER_TEST").map(String::as_str),
Some("wrapped")
);
assert_eq!(binary.cwd, None);
assert!(!client.should_reconnect_for_ssh());
let child = client
.create_child_connection(
dap::client::SessionId(u32::MAX),
binary.clone(),
Box::new(|_| {}),
&mut async_cx,
)
.await
.unwrap();
assert_eq!(child.binary().command.as_deref(), Some("mock"));
assert_eq!(child.binary().arguments, expected);
assert_eq!(child.binary().envs, binary.envs);
assert_eq!(child.binary().cwd, None);
assert!(!child.should_reconnect_for_ssh());
}
client
.fake_event(dap::messages::Events::Stopped(dap::StoppedEvent {
reason: dap::StoppedEventReason::Pause,
+18 -3
View File
@@ -102,6 +102,15 @@ pub struct TcpArguments {
pub host: IpAddr,
pub port: u16,
pub timeout: Option<u64>,
// Child sessions need a fresh proxy connection without restarting the adapter.
#[serde(skip_serializing_if = "Option::is_none")]
pub stdio_proxy: Option<StdioProxy>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StdioProxy {
pub command: String,
pub arguments: Vec<String>,
}
impl TcpArguments {
@@ -111,6 +120,7 @@ impl TcpArguments {
host: host.host.context("missing host")?,
port: host.port.context("missing port")?,
timeout: host.timeout,
stdio_proxy: None,
})
}
@@ -445,7 +455,7 @@ impl DebugAdapter for FakeAdapter {
task_definition: &DebugTaskDefinition,
_: Option<PathBuf>,
_: Option<Vec<String>>,
_: Option<HashMap<String, String>>,
env: Option<HashMap<String, String>>,
_: &mut AsyncApp,
) -> Result<DebugAdapterBinary> {
let connection = task_definition
@@ -455,13 +465,18 @@ impl DebugAdapter for FakeAdapter {
host: connection.host(),
port: connection.port.unwrap_or(17),
timeout: connection.timeout,
stdio_proxy: None,
});
Ok(DebugAdapterBinary {
command: Some("command".into()),
arguments: vec![],
connection,
envs: HashMap::default(),
cwd: None,
envs: env.unwrap_or_default(),
cwd: task_definition
.config
.get("cwd")
.and_then(|cwd| cwd.as_str())
.map(PathBuf::from),
request_args: StartDebuggingRequestArguments {
request: self.request_kind(&task_definition.config).await?,
configuration: task_definition.config.clone(),
+84 -1
View File
@@ -79,7 +79,19 @@ impl DebugAdapterClient {
message_handler: DapMessageHandler,
cx: &mut AsyncApp,
) -> Result<Self> {
let binary = if let Some(connection) = self.transport_delegate.tcp_arguments() {
let binary = if let Some(proxy) = self
.binary
.connection
.as_ref()
.and_then(|connection| connection.stdio_proxy.as_ref())
{
DebugAdapterBinary {
command: Some(proxy.command.clone()),
arguments: proxy.arguments.clone(),
request_args: binary.request_args,
..self.binary.clone()
}
} else if let Some(connection) = self.transport_delegate.tcp_arguments() {
DebugAdapterBinary {
command: None,
arguments: Default::default(),
@@ -282,6 +294,77 @@ mod tests {
});
}
#[gpui::test]
async fn child_connection_reuses_tcp_server(cx: &mut TestAppContext) {
use crate::adapters::{StdioProxy, TcpArguments};
init_test(cx);
for stdio_proxy in [
None,
Some(StdioProxy {
command: "docker".to_owned(),
arguments: vec!["exec".to_owned(), "container".to_owned(), "tcp".to_owned()],
}),
] {
let binary = DebugAdapterBinary {
command: Some("adapter launcher".to_owned()),
arguments: vec!["--start-adapter".to_owned()],
envs: Default::default(),
cwd: None,
connection: Some(TcpArguments {
host: std::net::Ipv4Addr::LOCALHOST.into(),
port: 1234,
timeout: Some(2000),
stdio_proxy: stdio_proxy.clone(),
}),
request_args: StartDebuggingRequestArguments {
configuration: json!({"parent": true}),
request: dap_types::StartDebuggingRequestArgumentsRequest::Launch,
},
};
let parent = DebugAdapterClient::start(
SessionId(1),
binary.clone(),
Box::new(|_| {}),
&mut cx.to_async(),
)
.await
.expect("Parent connection starts");
let mut child_binary = binary.clone();
child_binary.request_args.configuration = json!({"child": true});
let child = parent
.create_child_connection(
SessionId(2),
child_binary.clone(),
Box::new(|_| {}),
&mut cx.to_async(),
)
.await
.expect("Child connection starts");
assert_eq!(child.binary.connection, binary.connection);
assert_eq!(child.binary.request_args, child_binary.request_args);
if let Some(proxy) = &stdio_proxy {
assert_eq!(
child.binary.command.as_deref(),
Some(proxy.command.as_str())
);
assert_eq!(child.binary.arguments, proxy.arguments);
} else {
assert_eq!(child.binary.command, None);
assert!(child.binary.arguments.is_empty());
}
let grandchild = child
.create_child_connection(
SessionId(3),
child_binary,
Box::new(|_| {}),
&mut cx.to_async(),
)
.await
.expect("Grandchild connection starts");
assert_eq!(grandchild.binary, child.binary);
}
}
#[gpui::test]
pub async fn test_initialize_client(cx: &mut TestAppContext) {
#![expect(clippy::result_large_err)]
+182 -22
View File
@@ -17,7 +17,7 @@ use smol::{
net::{TcpListener, TcpStream},
};
use std::{
collections::HashMap,
collections::{HashMap, VecDeque},
net::{IpAddr, SocketAddr},
process::Stdio,
sync::Arc,
@@ -80,16 +80,23 @@ async fn start(
log_handlers: LogHandlers,
cx: &mut AsyncApp,
) -> Result<Box<dyn Transport>> {
let tcp_connection = binary
.connection
.as_ref()
.filter(|connection| connection.stdio_proxy.is_none());
#[cfg(any(test, feature = "test-support"))]
if cfg!(any(test, feature = "test-support")) {
if let Some(connection) = binary.connection.clone() {
return Ok(Box::new(FakeTransport::start_tcp(connection, cx).await?));
if let Some(connection) = tcp_connection {
return Ok(Box::new(
FakeTransport::start_tcp(connection.clone(), cx).await?,
));
} else {
return Ok(Box::new(FakeTransport::start_stdio(cx).await?));
}
}
if binary.connection.is_some() {
if tcp_connection.is_some() {
Ok(Box::new(
TcpTransport::start(binary, log_handlers, cx).await?,
))
@@ -261,12 +268,15 @@ impl TransportDelegate {
// Clean up logs by trimming unnecessary whitespace/newlines before inserting into log.
let line = line.trim();
log::debug!("stderr: {line}");
Self::log_adapter_line(&log_handlers, iokind, line);
}
}
for (kind, handler) in log_handlers.lock().iter_mut() {
if matches!(kind, LogKind::Adapter) {
handler(iokind, None, line);
}
fn log_adapter_line(log_handlers: &LogHandlers, iokind: IoKind, line: &str) {
log::debug!("stderr: {line}");
for (kind, handler) in log_handlers.lock().iter_mut() {
if matches!(kind, LogKind::Adapter) {
handler(iokind, None, line);
}
}
}
@@ -636,6 +646,7 @@ impl Transport for TcpTransport {
host: self.host,
port: self.port,
timeout: Some(self.timeout),
stdio_proxy: None,
})
}
@@ -725,23 +736,91 @@ impl StdioTransport {
let mut process = Child::spawn(command, Stdio::piped(), Stdio::piped(), Stdio::piped())?;
let _stderr_task = process.stderr.take().map(|stderr| {
cx.background_spawn(TransportDelegate::handle_adapter_log(
stderr,
IoKind::StdErr,
log_handlers,
))
});
let stderr = process
.stderr
.take()
.context("Missing debug adapter stderr")?;
let mut transport = Self {
process: Mutex::new(process),
_stderr_task: None,
};
let process = Mutex::new(process);
Ok(Self {
process,
_stderr_task,
})
let mut stderr = BufReader::new(stderr);
if let Some(connection) = binary
.connection
.as_ref()
.filter(|args| args.stdio_proxy.is_some())
{
let timeout = connection
.timeout
.unwrap_or_else(|| cx.update(|cx| DebuggerSettings::get_global(cx).timeout));
let address = SocketAddr::new(connection.host, connection.port);
// Give Docker time to start the helper in addition to the in-container TCP deadline.
let deadline = Duration::from_millis(timeout).saturating_add(Duration::from_secs(5));
let timer = cx.background_executor().timer(deadline);
read_tcp_proxy_startup(&mut stderr, &log_handlers, async move {
timer.await;
anyhow!("Timed out waiting for the TCP debug adapter proxy for {address}")
})
.await?;
}
transport._stderr_task = Some(cx.background_spawn(TransportDelegate::handle_adapter_log(
stderr,
IoKind::StdErr,
log_handlers,
)));
Ok(transport)
}
}
async fn read_tcp_proxy_startup(
stderr: &mut (impl smol::io::AsyncBufRead + Unpin),
log_handlers: &LogHandlers,
timeout: impl Future<Output = anyhow::Error>,
) -> Result<()> {
const STDERR_TAIL_LINES: usize = 20;
// Adapter log handlers attach after startup, so failures need their own copy of recent stderr.
let mut stderr_tail = VecDeque::with_capacity(STDERR_TAIL_LINES);
let read = async {
let mut bytes = Vec::new();
loop {
bytes.clear();
if stderr.read_until(b'\n', &mut bytes).await? == 0 {
bail!("TCP debug adapter proxy exited before reporting startup");
}
let line = String::from_utf8_lossy(&bytes);
let line = line.trim_end_matches(['\r', '\n']);
if let Some(status) = line.strip_prefix(proto::DAP_TCP_PROXY_STARTUP_PREFIX) {
if let Some(error) = serde_json::from_str::<Option<String>>(status)
.context("Invalid TCP debug adapter proxy startup response")?
{
bail!(error);
}
return Ok(());
}
if !line.trim().is_empty() {
if stderr_tail.len() == STDERR_TAIL_LINES {
stderr_tail.pop_front();
}
stderr_tail.push_back(line.to_owned());
}
TransportDelegate::log_adapter_line(log_handlers, IoKind::StdErr, line.trim());
}
};
let result = select! {
result = read.fuse() => result,
error = timeout.fuse() => Err(error),
};
result.map_err(|error| {
if stderr_tail.is_empty() {
error
} else {
let stderr = stderr_tail.make_contiguous().join("\n");
anyhow!("{error:#}\nStartup stderr:\n{stderr}")
}
})
}
impl Transport for StdioTransport {
fn has_adapter_logs(&self) -> bool {
true
@@ -1160,3 +1239,84 @@ mod tests {
assert_eq!(error.to_string(), "plain error");
}
}
#[cfg(test)]
mod tcp_proxy_tests {
use super::*;
use gpui::TestAppContext;
#[gpui::test]
async fn reads_tcp_proxy_startup_error(_cx: &mut TestAppContext) {
let reason = "Debug adapter exited before connecting to 127.0.0.1:7000: exit status: 7";
let status = serde_json::to_string(&Some(reason)).unwrap();
let adapter_error = "ModuleNotFoundError: No module named zr_missing";
let earlier_logs: String = (0..20)
.map(|index| format!("adapter log {index}\n"))
.collect();
let stderr = format!(
"{earlier_logs}{adapter_error}\n\n{}{}\n",
proto::DAP_TCP_PROXY_STARTUP_PREFIX,
status
);
let mut reader = BufReader::new(stderr.as_bytes());
let error =
read_tcp_proxy_startup(&mut reader, &Default::default(), futures::future::pending())
.await
.expect_err("The startup failed");
let expected_tail = earlier_logs.strip_prefix("adapter log 0\n").unwrap();
assert_eq!(
error.to_string(),
format!("{reason}\nStartup stderr:\n{expected_tail}{adapter_error}")
);
}
#[gpui::test]
async fn reads_docker_error_when_proxy_exits_without_status(_cx: &mut TestAppContext) {
let docker_error = "Error response from daemon: No such container: zr65778-missing";
let mut reader = BufReader::new(docker_error.as_bytes());
let error =
read_tcp_proxy_startup(&mut reader, &Default::default(), futures::future::pending())
.await
.expect_err("Docker never started the proxy");
assert_eq!(
error.to_string(),
format!(
"TCP debug adapter proxy exited before reporting startup\nStartup stderr:\n{docker_error}"
)
);
}
#[gpui::test]
async fn preserves_startup_stderr_on_timeout(cx: &mut TestAppContext) {
use futures::{StreamExt as _, TryStreamExt as _, future, stream};
let stderr = stream::once(future::ready(Ok::<_, std::io::Error>(
&b"adapter is starting\n"[..],
)))
.chain(stream::pending())
.into_async_read();
let mut reader = BufReader::new(stderr);
let timeout = cx.executor().timer(Duration::from_secs(1));
let error = read_tcp_proxy_startup(&mut reader, &Default::default(), async {
timeout.await;
anyhow!("Timed out waiting for the TCP debug adapter proxy")
})
.await
.expect_err("The proxy never reported startup");
assert_eq!(
error.to_string(),
"Timed out waiting for the TCP debug adapter proxy\nStartup stderr:\nadapter is starting"
);
}
#[gpui::test]
async fn reads_tcp_proxy_ready_and_preserves_remaining_logs(_cx: &mut TestAppContext) {
let stderr = format!("\n{}null\nmore logs\n", proto::DAP_TCP_PROXY_STARTUP_PREFIX);
let mut reader = BufReader::new(stderr.as_bytes());
read_tcp_proxy_startup(&mut reader, &Default::default(), futures::future::pending())
.await
.unwrap();
let mut remaining = String::new();
reader.read_to_string(&mut remaining).await.unwrap();
assert_eq!(remaining, "more logs\n");
}
}
+1
View File
@@ -528,6 +528,7 @@ impl DebugAdapter for GoDebugAdapter {
host,
port,
timeout,
stdio_proxy: None,
});
} else {
let minidelve_path = self.install_shim(delegate).await?;
+1
View File
@@ -205,6 +205,7 @@ impl JsDebugAdapter {
host,
port,
timeout,
stdio_proxy: None,
}),
request_args: StartDebuggingRequestArguments {
configuration,
+1
View File
@@ -486,6 +486,7 @@ impl PythonDebugAdapter {
host,
port,
timeout,
stdio_proxy: None,
}),
cwd: Some(delegate.worktree_root_path().to_path_buf()),
envs: user_env.unwrap_or_default(),
@@ -142,6 +142,7 @@ impl From<dap::TcpArguments> for extension::TcpArguments {
host: value.host.into(),
port: value.port,
timeout: value.timeout,
stdio_proxy: None,
}
}
}
+52 -1
View File
@@ -47,7 +47,7 @@ use std::{
borrow::Borrow,
collections::BTreeMap,
ffi::OsStr,
net::{IpAddr, Ipv4Addr},
net::{IpAddr, Ipv4Addr, SocketAddr},
path::{Path, PathBuf},
sync::{Arc, Once},
};
@@ -320,6 +320,56 @@ impl DapStore {
let response = request.await?;
let binary = DebugAdapterBinary::from_proto(response)?;
if let Some(connection) = &binary.connection {
let timeout = connection.timeout.unwrap_or_else(|| {
cx.update(|cx| {
dap::debugger_settings::DebuggerSettings::get_global(cx).timeout
})
});
let address = SocketAddr::new(connection.host, connection.port);
let working_dir =
binary.cwd.as_ref().map(|path| path.display().to_string());
let commands = remote.read_with(cx, |remote, _cx| -> Result<_> {
let Some((proxy, child_proxy)) = remote.tcp_proxy_commands(
address,
timeout,
binary.command.as_deref(),
&binary.arguments,
)?
else {
return Ok(None);
};
let build = |proxy: remote::CommandTemplate| {
remote.build_command(
Some(proxy.program),
&proxy.args,
&binary.envs,
working_dir.clone(),
None,
Interactive::No,
)
};
Ok(Some((build(proxy)?, build(child_proxy)?)))
})?;
if let Some((command, child_command)) = commands {
return Ok(DebugAdapterBinary {
command: Some(command.program),
arguments: command.args,
envs: command.env,
cwd: None,
connection: Some(TcpArguments {
timeout: Some(timeout),
stdio_proxy: Some(dap::adapters::StdioProxy {
command: child_command.program,
arguments: child_command.args,
}),
..connection.clone()
}),
request_args: binary.request_args,
});
}
}
let port_forwarding;
let connection;
if let Some(c) = binary.connection {
@@ -336,6 +386,7 @@ impl DapStore {
port,
host,
timeout: c.timeout,
stdio_proxy: None,
})
} else {
port_forwarding = None;
+3
View File
@@ -17,6 +17,9 @@ include!(concat!(env!("OUT_DIR"), "/zed.messages.rs"));
pub const REMOTE_SERVER_PEER_ID: PeerId = PeerId { owner_id: 0, id: 0 };
pub const REMOTE_SERVER_PROJECT_ID: u64 = 0;
// The TCP proxy reports startup on stderr so stdout remains a DAP stream.
pub const DAP_TCP_PROXY_STARTUP_PREFIX: &str = "\0zed-dap-proxy-startup:";
impl Envelope {
#[inline(never)]
pub fn decode_from_slice(buffer: &[u8]) -> Result<Self, DecodeError> {
+23
View File
@@ -40,6 +40,7 @@ use semver::Version;
use std::{
collections::VecDeque,
fmt,
net::SocketAddr,
ops::ControlFlow,
path::PathBuf,
sync::{
@@ -1036,6 +1037,17 @@ impl RemoteClient {
connection.build_stdio_command(command)
}
pub fn tcp_proxy_commands(
&self,
address: SocketAddr,
timeout: u64,
program: Option<&str>,
args: &[String],
) -> Result<Option<(CommandTemplate, CommandTemplate)>> {
let connection = self.remote_connection().context("no remote connection")?;
connection.tcp_proxy_commands(address, timeout, program, args)
}
pub fn build_forward_ports_command(
&self,
forwards: Vec<(u16, String, u16)>,
@@ -1531,6 +1543,17 @@ pub trait RemoteConnection: Send + Sync {
fn shares_network_interface(&self) -> bool {
false
}
/// Returns the launch and attach commands for exposing TCP over stdio.
/// The attach command connects to the existing adapter without starting another one.
fn tcp_proxy_commands(
&self,
_address: SocketAddr,
_timeout: u64,
_program: Option<&str>,
_args: &[String],
) -> Result<Option<(CommandTemplate, CommandTemplate)>> {
Ok(None)
}
fn build_command(
&self,
program: Option<String>,
+118 -11
View File
@@ -7,6 +7,7 @@ use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
use semver::Version as SemanticVersion;
use std::collections::BTreeMap;
use std::fmt::Write;
use std::net::SocketAddr;
use std::time::Instant;
use std::{
path::{Path, PathBuf},
@@ -65,6 +66,18 @@ pub(crate) struct DockerExecConnection {
}
impl DockerExecConnection {
fn remote_binary_path(&self) -> Result<String> {
let relative_path = self
.remote_binary_relpath
.as_ref()
.context("Remote binary path not set")?;
Ok(format!(
"{}/{}",
self.remote_dir_for_server.trim_end_matches('/'),
relative_path.display(PathStyle::Unix),
))
}
pub async fn new(
connection_options: DockerConnectionOptions,
delegate: Arc<dyn RemoteClientDelegate>,
@@ -753,15 +766,47 @@ impl RemoteConnection for DockerExecConnection {
false
}
fn tcp_proxy_commands(
&self,
address: SocketAddr,
timeout: u64,
program: Option<&str>,
args: &[String],
) -> Result<Option<(CommandTemplate, CommandTemplate)>> {
let proxy_program = self.remote_binary_path()?;
let mut arguments = vec!["tcp".to_owned(), address.to_string(), timeout.to_string()];
let attach_arguments = arguments.clone();
if let Some(program) = program {
arguments.extend(["--".to_owned(), program.to_owned()]);
arguments.extend_from_slice(args);
}
Ok(Some((
CommandTemplate {
program: proxy_program.clone(),
args: arguments,
env: Default::default(),
},
CommandTemplate {
program: proxy_program,
args: attach_arguments,
env: Default::default(),
},
)))
}
fn build_command(
&self,
program: Option<String>,
args: &[String],
env: &HashMap<String, String>,
working_dir: Option<String>,
_port_forward: Option<(u16, String, u16)>,
port_forward: Option<(u16, String, u16)>,
interactive: Interactive,
) -> Result<CommandTemplate> {
anyhow::ensure!(
port_forward.is_none(),
"Port forwarding is not supported by docker exec"
);
let mut parsed_working_dir = None;
let path_style = self.path_style();
@@ -825,10 +870,6 @@ impl RemoteConnection for DockerExecConnection {
&self,
mut command: RemoteCommand,
) -> Result<(CommandTemplate, Vec<u8>)> {
let remote_binary_relpath = self
.remote_binary_relpath
.as_ref()
.context("Remote binary path not set")?;
let mut env = self
.connection_options
.remote_env
@@ -849,11 +890,6 @@ impl RemoteConnection for DockerExecConnection {
None => working_dir,
});
}
let remote_binary_path = format!(
"{}/{}",
self.remote_dir_for_server.trim_end_matches('/'),
remote_binary_relpath.display(PathStyle::Unix),
);
let mut args = vec![
String::from("exec"),
String::from("-u"),
@@ -866,7 +902,7 @@ impl RemoteConnection for DockerExecConnection {
args.extend([
String::from("-i"),
self.connection_options.container_id.clone(),
remote_binary_path,
self.remote_binary_path()?,
String::from("exec"),
]);
Ok((
@@ -1087,6 +1123,77 @@ mod tests {
);
}
#[test]
fn tcp_proxy_runs_inside_container() -> Result<()> {
let mut connection = connection(&[("PATH", "/custom/bin")]);
connection.remote_binary_relpath = Some(RelPath::from_unix_str("remote server")?.into());
for use_podman in [false, true] {
connection.connection_options.use_podman = use_podman;
for address in ["127.0.0.1:4567", "[::1]:4567"] {
for program in [Some("/python with spaces"), None] {
let (proxy, attach_proxy) = connection
.tcp_proxy_commands(
address.parse()?,
1234,
program,
&["argument with spaces".to_owned(), "--flag".to_owned()],
)?
.context("Missing proxy")?;
assert_eq!(attach_proxy.program, proxy.program);
assert_eq!(attach_proxy.args, ["tcp", address, "1234"]);
let template = connection.build_command(
Some(proxy.program),
&proxy.args,
&HashMap::default(),
Some("/workspace".to_owned()),
None,
Interactive::No,
)?;
assert_eq!(
template.program,
if use_podman { "podman" } else { "docker" }
);
let mut expected = vec![
"exec",
"-u",
"user",
"-w",
"/workspace",
"-e",
"PATH=/custom/bin",
"-i",
"container_id",
"/tmp/zed/remote server",
"tcp",
address,
"1234",
];
if let Some(program) = program {
expected.extend(["--", program, "argument with spaces", "--flag"]);
}
assert_eq!(template.args, expected);
}
}
}
Ok(())
}
#[test]
fn rejects_unsupported_port_forwarding() {
assert!(
connection(&[])
.build_command(
None,
&[],
&HashMap::default(),
None,
Some((1234, "localhost".to_owned(), 5678)),
Interactive::No,
)
.is_err()
);
}
#[test]
fn test_build_stdio_command() -> Result<()> {
let mut connection = connection(&[("API_KEY", "remote-secret"), ("NAME\0NUL", "dropped")]);
+52 -2
View File
@@ -36,7 +36,7 @@ use crate::{
RemoteConnectionOptions,
},
};
use anyhow::Result;
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use collections::HashMap;
use futures::{
@@ -50,6 +50,7 @@ use futures::{
use gpui::{App, AppContext as _, AsyncApp, Global, Task, TestAppContext};
use rpc::{AnyProtoClient, proto::Envelope};
use std::{
net::SocketAddr,
path::PathBuf,
sync::{
Arc,
@@ -67,6 +68,7 @@ pub struct MockConnectionOptions {
/// A mock implementation of `RemoteConnection` for testing.
pub struct MockRemoteConnection {
options: MockConnectionOptions,
tcp_proxy: bool,
server_channel: Arc<ChannelClient>,
server_cx: SendableCx,
message_interceptors: parking_lot::Mutex<Option<MessageInterceptors>>,
@@ -119,6 +121,17 @@ pub struct MockConnectionRegistry {
impl Global for MockConnectionRegistry {}
impl MockConnectionRegistry {
pub fn enable_tcp_proxy(&mut self, options: &MockConnectionOptions) -> Result<()> {
let (_, connection) = self
.pending
.get_mut(&options.id)
.context("Missing mock connection")?;
Arc::get_mut(connection)
.context("Mock connection already shared")?
.tcp_proxy = true;
Ok(())
}
/// Called by `ConnectionPool::connect` to retrieve a pre-registered mock connection.
pub fn take(
&mut self,
@@ -224,6 +237,7 @@ impl MockConnection {
let connection = Arc::new(MockRemoteConnection {
options: opts.clone(),
tcp_proxy: false,
server_channel: server_client.clone(),
server_cx: SendableCx::new(server_cx),
message_interceptors: parking_lot::Mutex::new(None),
@@ -261,12 +275,43 @@ impl RemoteConnection for MockRemoteConnection {
false
}
fn tcp_proxy_commands(
&self,
address: SocketAddr,
timeout: u64,
program: Option<&str>,
args: &[String],
) -> Result<Option<(CommandTemplate, CommandTemplate)>> {
if !self.tcp_proxy {
return Ok(None);
}
let proxy_program = "mock-remote-server".to_owned();
let mut arguments = vec!["tcp".into(), address.to_string(), timeout.to_string()];
let attach_arguments = arguments.clone();
if let Some(program) = program {
arguments.extend(["--".into(), program.into()]);
arguments.extend_from_slice(args);
}
Ok(Some((
CommandTemplate {
program: proxy_program.clone(),
args: arguments,
env: Default::default(),
},
CommandTemplate {
program: proxy_program,
args: attach_arguments,
env: Default::default(),
},
)))
}
fn build_command(
&self,
program: Option<String>,
args: &[String],
env: &HashMap<String, String>,
_working_dir: Option<String>,
working_dir: Option<String>,
_port_forward: Option<(u16, String, u16)>,
interactive: Interactive,
) -> Result<CommandTemplate> {
@@ -276,6 +321,11 @@ impl RemoteConnection for MockRemoteConnection {
Interactive::Yes => shell_args.push("-t".to_string()),
Interactive::No => shell_args.push("-T".to_string()),
}
if self.tcp_proxy
&& let Some(working_dir) = working_dir
{
shell_args.extend(["-w".into(), working_dir]);
}
shell_args.push(shell_program);
shell_args.extend(args.iter().cloned());
Ok(CommandTemplate {
+2 -2
View File
@@ -57,9 +57,9 @@ fn main() -> anyhow::Result<()> {
} else {
std::io::stderr()
.write_all(if cfg!(unix) {
b"usage: remote <run|proxy|version|exec>\n"
b"usage: remote <run|proxy|version|exec|tcp>\n"
} else {
b"usage: remote <run|proxy|version>\n"
b"usage: remote <run|proxy|version|tcp>\n"
})
.ok();
std::process::exit(1);
+20
View File
@@ -1,5 +1,6 @@
mod global_skills;
mod headless_project;
mod tcp;
#[cfg(test)]
mod remote_editing_tests;
@@ -88,6 +89,12 @@ pub enum Commands {
identifier: String,
},
Version,
Tcp {
address: std::net::SocketAddr,
timeout: u64,
#[arg(last = true)]
command: Vec<String>,
},
#[cfg(unix)]
Exec,
}
@@ -116,6 +123,19 @@ pub fn run(command: Commands) -> anyhow::Result<()> {
} => execute_proxy(identifier, reconnect).context("running proxy on the remote server"),
#[cfg(unix)]
Commands::Exec => execute_command(),
Commands::Tcp {
address,
timeout,
command,
} => smol::block_on(tcp::proxy(
address,
std::time::Duration::from_millis(timeout),
&command,
smol::net::TcpStream::connect,
smol::Unblock::new(std::io::stdin()),
smol::Unblock::new(std::io::stdout()),
tcp::stdin_closed(),
)),
Commands::Version => {
let release_channel = *RELEASE_CHANNEL;
match release_channel {
+469
View File
@@ -0,0 +1,469 @@
use anyhow::{Context as _, Result, bail};
use futures::{
AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, FutureExt as _, select_biased,
};
use smol::net::TcpStream;
#[cfg(unix)]
use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd};
use std::{future::Future, io, io::Write as _, net::SocketAddr, process::Stdio, time::Duration};
use util::{ResultExt as _, process::Child};
#[expect(
clippy::disallowed_methods,
reason = "This stdio helper runs without a GPUI app or dispatcher"
)]
pub(crate) async fn proxy<Connect>(
address: SocketAddr,
timeout: Duration,
command: &[String],
connect: impl Fn(SocketAddr) -> Connect,
mut input: impl AsyncRead + Unpin,
mut output: impl AsyncWrite + Unpin,
disconnected: impl Future<Output = io::Result<()>>,
) -> Result<()>
where
Connect: Future<Output = io::Result<TcpStream>>,
{
let mut process = AdapterProcess(None);
let result = async {
let mut startup_input = Vec::new();
let startup = async {
if let Some((program, arguments)) = command.split_first() {
let mut command = util::command::new_std_command(program);
command.args(arguments);
// Adapter logs must not be mixed with the DAP messages on stdout.
process.0 = Some(Child::spawn(
command,
Stdio::null(),
Stdio::from(io::stderr()),
Stdio::inherit(),
)?);
}
let connect = async {
loop {
if let Ok(stream) = connect(address).await {
return stream;
}
smol::Timer::after(Duration::from_millis(100)).await;
}
};
let exited = async {
match &mut process.0 {
Some(child) => child.status().await,
None => futures::future::pending().await,
}
};
let exited = exited.fuse();
let connect = connect.fuse();
let deadline = smol::Timer::after(timeout).fuse();
futures::pin_mut!(exited, connect, deadline);
let mut buffer = [0; 8192];
loop {
select_biased! {
status = exited => {
let status = status?;
bail!("Debug adapter exited before connecting to {address}: {status}")
}
stream = connect => break Ok(Some(stream)),
_ = deadline => bail!("Connection to TCP DAP timeout {address}"),
length = input.read(&mut buffer).fuse() => {
let length = length.context("Reading DAP input during startup")?;
if length == 0 {
break Ok(None);
}
startup_input.extend_from_slice(&buffer[..length]);
}
}
}
}
.await;
let startup = match startup {
Ok(Some(stream)) => Ok(stream),
Ok(None) => return Ok(()),
Err(error) => Err(error),
};
// A leading newline separates the status even if adapter logs lack a newline.
let error = startup.as_ref().err().map(|error| format!("{error:#}"));
let status = serde_json::to_string(&error)?;
let message = format!("\n{}{status}\n", proto::DAP_TCP_PROXY_STARTUP_PREFIX);
io::stderr()
.lock()
.write_all(message.as_bytes())
.context("Reporting TCP debug adapter startup")?;
let stream = startup?;
let (mut reader, mut writer) = stream.split();
select_biased! {
result = forward(startup_input.as_slice().chain(input), &mut writer).fuse() => {
result.context("Forwarding DAP input")?;
}
result = forward(&mut reader, &mut output).fuse() => {
result.context("Forwarding DAP output")?;
}
result = disconnected.fuse() => {
result.context("Watching DAP client disconnect")?;
}
}
Ok(())
}
.await;
if let Some(mut child) = process.0.take() {
child.kill().log_err();
child.status().await.context("Waiting for debug adapter")?;
}
result
}
pub(crate) async fn stdin_closed() -> io::Result<()> {
#[cfg(unix)]
{
input_closed(io::stdin().as_fd()).await
}
#[cfg(not(unix))]
futures::future::pending().await
}
#[cfg(unix)]
#[expect(
clippy::disallowed_methods,
reason = "This stdio helper runs without a GPUI app or dispatcher"
)]
async fn input_closed(input: BorrowedFd<'_>) -> io::Result<()> {
let mut descriptor = libc::pollfd {
fd: input.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
loop {
if unsafe { libc::poll(&mut descriptor, 1, 0) } < 0 {
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
} else if descriptor.revents & (libc::POLLERR | libc::POLLNVAL) != 0 {
return Err(io::Error::other("DAP input pipe failed"));
} else if descriptor.revents & libc::POLLHUP != 0 {
return Ok(());
}
smol::Timer::after(Duration::from_millis(100)).await;
}
}
async fn forward(
mut reader: impl AsyncRead + Unpin,
mut writer: impl AsyncWrite + Unpin,
) -> std::io::Result<()> {
let mut buffer = [0; 8192];
loop {
let length = reader.read(&mut buffer).await?;
if length == 0 {
return Ok(());
}
writer.write_all(&buffer[..length]).await?;
writer.flush().await?;
}
}
struct AdapterProcess(Option<Child>);
impl Drop for AdapterProcess {
fn drop(&mut self) {
if let Some(process) = &mut self.0 {
process.kill().log_err();
}
}
}
#[cfg(test)]
#[expect(
clippy::disallowed_methods,
reason = "These tests drive real sockets and processes with smol::block_on"
)]
mod tests {
use super::*;
use futures::{StreamExt as _, TryStreamExt as _, future};
use smol::net::TcpListener;
#[cfg(unix)]
use std::io::Read as _;
#[test]
fn attach_forwards_dap_in_both_directions() -> Result<()> {
smol::block_on(async {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?;
let request = b"Content-Length: 2\r\n\r\n{}";
let response = b"Content-Length: 16\r\n\r\n{\"success\":true}";
let (allow_connect, wait_to_connect) = smol::channel::bounded(1);
let (send_body, wait_for_body) = smol::channel::bounded(1);
let (header, body) = request.split_at(request.len() - 2);
let input = futures::stream::once(future::ready(Ok::<_, io::Error>(header)))
.chain(futures::stream::once(async {
allow_connect.send(()).await.map_err(io::Error::other)?;
wait_for_body.recv().await.map_err(io::Error::other)?;
Ok(body)
}))
.chain(futures::stream::pending())
.boxed()
.into_async_read();
let mut output = Vec::new();
let server = async {
let (mut stream, _) = listener.accept().await?;
let mut received = vec![0; request.len()];
let (received_header, received_body) = received.split_at_mut(header.len());
stream.read_exact(received_header).await?;
send_body.send(()).await?;
stream.read_exact(received_body).await?;
assert_eq!(received, request);
stream.write_all(response).await?;
anyhow::Ok(())
};
let exchange = future::try_join(
server,
proxy(
address,
Duration::from_secs(2),
&[],
|address| {
let wait_to_connect = &wait_to_connect;
async move {
wait_to_connect.recv().await.map_err(io::Error::other)?;
TcpStream::connect(address).await
}
},
input,
&mut output,
future::pending(),
),
);
select_biased! {
result = exchange.fuse() => { result?; }
_ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(5))) => bail!("DAP messages were not forwarded"),
}
assert_eq!(output, response);
Ok(())
})
}
#[cfg(unix)]
#[test]
fn stdin_eof_during_startup_terminates_adapter() -> Result<()> {
smol::block_on(async {
let directory = tempfile::tempdir()?;
let marker = directory.path().join("adapter-pid");
let command = disconnect_test_adapter(&marker);
let input = futures::stream::once(async {
while !std::fs::metadata(&marker).is_ok_and(|metadata| metadata.len() > 0) {
smol::Timer::after(Duration::from_millis(10)).await;
}
Ok::<_, io::Error>(&b"early DAP input"[..])
})
.boxed()
.into_async_read();
let address = SocketAddr::from(([127, 0, 0, 1], 0));
select_biased! {
result = proxy(address, Duration::from_secs(60), &command, |_| future::pending(), input, smol::io::sink(), future::pending()).fuse() => result?,
_ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(5))) => bail!("Proxy did not exit after startup stdin EOF"),
}
assert_adapter_reaped(&marker).await
})
}
#[test]
fn connection_timeout() -> Result<()> {
smol::block_on(async {
let address = SocketAddr::from(([127, 0, 0, 1], 0));
let error = proxy(
address,
Duration::from_millis(20),
&[],
|_| future::pending(),
futures::stream::pending::<io::Result<&[u8]>>().into_async_read(),
smol::io::sink(),
future::pending(),
)
.await
.expect_err("There is no TCP server");
assert_eq!(
error.to_string(),
format!("Connection to TCP DAP timeout {address}")
);
Ok(())
})
}
#[cfg(unix)]
#[test]
fn client_disconnect_terminates_adapter() -> Result<()> {
smol::block_on(async {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?;
let directory = tempfile::tempdir()?;
let marker = directory.path().join("adapter-pid");
let command = disconnect_test_adapter(&marker);
let connected = &std::cell::Cell::new(false);
let connect = move |address| async move {
let stream = TcpStream::connect(address).await?;
connected.set(true);
Ok(stream)
};
let input = futures::stream::once(async {
loop {
if connected.get()
&& std::fs::metadata(&marker).is_ok_and(|metadata| metadata.len() > 0)
{
return Ok::<_, std::io::Error>(Vec::<u8>::new());
}
smol::Timer::after(Duration::from_millis(10)).await;
}
})
.boxed_local()
.into_async_read();
select_biased! {
result = proxy(address, Duration::from_secs(2), &command, connect, input, smol::io::sink(), future::pending()).fuse() => result?,
_ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(5))) => bail!("Adapter was not terminated"),
}
assert_adapter_reaped(&marker).await
})
}
#[cfg(unix)]
#[test]
fn pipe_disconnect_terminates_adapter_with_pending_input() -> Result<()> {
smol::block_on(async {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?;
let (stream, (_peer, _)) =
future::try_join(TcpStream::connect(address), listener.accept()).await?;
let directory = tempfile::tempdir()?;
let marker = directory.path().join("adapter-pid");
let command = disconnect_test_adapter(&marker);
let (mut input, mut writer) = io::pipe()?;
writer.write_all(b"unread DAP input")?;
let exchange = future::try_join(
proxy(
address,
Duration::from_secs(2),
&command,
|_| future::ready(Ok(stream.clone())),
smol::io::repeat(0),
smol::io::sink(),
input_closed(input.as_fd()),
),
async {
while !std::fs::metadata(&marker).is_ok_and(|metadata| metadata.len() > 0) {
smol::Timer::after(Duration::from_millis(10)).await;
}
drop(writer);
anyhow::Ok(())
},
);
select_biased! {
result = exchange.fuse() => { result?; }
_ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(5))) => bail!("Proxy did not exit while the adapter stopped reading"),
}
assert_adapter_reaped(&marker).await?;
let mut remaining = Vec::new();
input.read_to_end(&mut remaining)?;
assert_eq!(remaining, b"unread DAP input");
Ok(())
})
}
#[cfg(unix)]
fn disconnect_test_adapter(marker: &std::path::Path) -> Vec<String> {
vec![
"sh".to_owned(),
"-c".to_owned(),
"echo $$ > \"$1\"; exec sleep 60".to_owned(),
"adapter".to_owned(),
marker.to_string_lossy().into_owned(),
]
}
#[cfg(unix)]
async fn assert_adapter_reaped(marker: &std::path::Path) -> Result<()> {
let process_id = std::fs::read_to_string(marker)?;
let status = smol::process::Command::new("sh")
.args(["-c", "kill -0 \"$1\"", "check", process_id.trim()])
.stderr(Stdio::null())
.status()
.await?;
assert!(
!status.success(),
"The adapter must be reaped after stdin closes"
);
Ok(())
}
#[cfg(unix)]
#[test]
fn reports_adapter_exit_before_connecting() -> Result<()> {
smol::block_on(async {
let address = SocketAddr::from(([127, 0, 0, 1], 0));
let error = proxy(
address,
Duration::from_secs(2),
&["sh".to_owned(), "-c".to_owned(), "exit 7".to_owned()],
|_| future::pending(),
futures::stream::pending::<io::Result<&[u8]>>().into_async_read(),
smol::io::sink(),
future::pending(),
)
.await
.expect_err("The adapter exits");
assert_eq!(
error.to_string(),
format!("Debug adapter exited before connecting to {address}: exit status: 7")
);
Ok(())
})
}
#[test]
fn flushes_messages_before_eof() -> Result<()> {
smol::block_on(async {
let (sender, receiver) = smol::channel::bounded(1);
struct Writer(smol::channel::Sender<Vec<u8>>, Vec<u8>);
impl AsyncWrite for Writer {
fn poll_write(
mut self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
bytes: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.1.extend_from_slice(bytes);
std::task::Poll::Ready(Ok(bytes.len()))
}
fn poll_flush(
mut self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
let bytes = std::mem::take(&mut self.1);
self.0.try_send(bytes).expect("The flush is observed");
std::task::Poll::Ready(Ok(()))
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
context: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.poll_flush(context)
}
}
let input =
futures::stream::once(future::ready(Ok::<_, std::io::Error>(&b"message"[..])))
.chain(futures::stream::pending())
.into_async_read();
select_biased! {
message = receiver.recv().fuse() => assert_eq!(message?, b"message"),
result = forward(input, Writer(sender, Vec::new())).fuse() => {
result?;
bail!("Input must remain open");
}
_ = futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(2))) => bail!("Message was not flushed"),
}
Ok(())
})
}
}
+81 -1
View File
@@ -2,18 +2,98 @@
use anyhow::{Context as _, Result};
use collections::HashMap;
use futures::{AsyncReadExt as _, AsyncWriteExt as _};
use futures::{AsyncReadExt as _, AsyncWriteExt as _, future};
use remote::command::{
RemoteCommand, home_relative_path, home_stdio_launcher_command, stdio_launcher_command,
};
use smol::net::TcpListener;
use smol::process::{Command, Stdio};
use std::borrow::Cow;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::fs::PermissionsExt as _;
use std::sync::Arc;
use std::time::Duration;
use util::shell::{Shell, ShellKind};
use util::shell_builder::ShellBuilder;
#[test]
fn tcp_command_keeps_adapter_logs_out_of_dap() -> Result<()> {
let executor = gpui::BackgroundExecutor::new(Arc::new(gpui::ThreadedDispatcher::new()));
smol::block_on(smol::future::race(
async {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?;
let directory = tempfile::tempdir()?;
let marker = directory.path().join("adapter-logged");
let mut child = Command::new(env!("CARGO_BIN_EXE_remote-server"))
.args(["tcp", &address.to_string(), "5000", "--", "/bin/sh", "-c"])
.arg(r#"printf 'adapter log'; : > "$1"; exec sleep 30"#)
.arg("adapter")
.arg(&marker)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut stdin = child.stdin.take().context("Missing proxy stdin")?;
let request = b"Content-Length: 2\r\n\r\n{}";
let response = b"Content-Length: 16\r\n\r\n{\"success\":true}";
let server = async {
let (mut stream, _) = listener.accept().await?;
while !marker.exists() {
executor.timer(Duration::from_millis(10)).await;
}
let mut received = vec![0; request.len()];
stream.read_exact(&mut received).await?;
assert_eq!(received, request);
stream.write_all(response).await?;
anyhow::Ok(())
};
stdin.write_all(request).await?;
let (_, output) = future::try_join(server, async { Ok(child.output().await?) }).await?;
assert!(output.status.success(), "{:?}", output.stderr);
assert_eq!(output.stdout, response);
let stderr = String::from_utf8(output.stderr)?;
assert!(stderr.lines().any(|line| line == "adapter log"));
assert!(stderr.lines().any(|line| {
line.strip_prefix(proto::DAP_TCP_PROXY_STARTUP_PREFIX) == Some("null")
}));
drop(stdin);
Ok(())
},
async {
executor.timer(Duration::from_secs(10)).await;
anyhow::bail!("TCP helper did not finish")
},
))
}
#[test]
fn tcp_command_reports_adapter_spawn_failure() -> Result<()> {
smol::block_on(async {
let directory = tempfile::tempdir()?;
let missing_adapter = directory.path().join("missing-adapter");
let output = Command::new(env!("CARGO_BIN_EXE_remote-server"))
.args(["tcp", "127.0.0.1:0", "5000", "--"])
.arg(missing_adapter)
.output()
.await?;
assert!(!output.status.success());
assert!(output.stdout.is_empty());
let stderr = String::from_utf8(output.stderr)?;
let status = stderr
.lines()
.find_map(|line| line.strip_prefix(proto::DAP_TCP_PROXY_STARTUP_PREFIX))
.context("Missing TCP proxy startup status")?;
let reason: String = serde_json::from_str(status)?;
assert!(reason.contains("failed to spawn command"), "{reason}");
assert!(reason.contains("missing-adapter"), "{reason}");
Ok(())
})
}
#[test]
fn test_remote_command_preserves_agent_stdin() -> Result<()> {
smol::block_on(async {