Skip to repository content686 lines · 22.3 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T06:53:18.448Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
wsl.rs
1use crate::{
2 RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
3 remote_client::{CommandTemplate, Interactive, RemoteConnection, RemoteConnectionOptions},
4 transport::{parse_platform, parse_shell},
5};
6use anyhow::{Context, Result, anyhow, bail};
7use async_trait::async_trait;
8use collections::HashMap;
9use futures::channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender};
10use gpui::{App, AppContext as _, AsyncApp, Task};
11use release_channel::{AppVersion, ReleaseChannel};
12use rpc::proto::Envelope;
13use semver::Version;
14use smol::fs;
15use std::{
16 ffi::OsStr,
17 fmt::Write as _,
18 path::{Path, PathBuf},
19 sync::Arc,
20 time::Instant,
21};
22
23use util::{
24 command::Stdio,
25 paths::{PathStyle, RemotePathBuf},
26 rel_path::RelPath,
27 shell::{Shell, ShellKind},
28 shell_builder::ShellBuilder,
29};
30
31#[derive(
32 Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
33)]
34pub struct WslConnectionOptions {
35 pub distro_name: String,
36 pub user: Option<String>,
37}
38
39impl From<settings::WslConnection> for WslConnectionOptions {
40 fn from(val: settings::WslConnection) -> Self {
41 WslConnectionOptions {
42 distro_name: val.distro_name,
43 user: val.user,
44 }
45 }
46}
47
48#[derive(Debug)]
49pub(crate) struct WslRemoteConnection {
50 remote_binary_path: Option<Arc<RelPath>>,
51 platform: RemotePlatform,
52 os_version: Option<String>,
53 shell: String,
54 shell_kind: ShellKind,
55 default_system_shell: String,
56 has_wsl_interop: bool,
57 connection_options: WslConnectionOptions,
58}
59
60impl WslRemoteConnection {
61 pub(crate) async fn new(
62 connection_options: WslConnectionOptions,
63 delegate: Arc<dyn RemoteClientDelegate>,
64 cx: &mut AsyncApp,
65 ) -> Result<Self> {
66 log::info!(
67 "Connecting to WSL distro {} with user {:?}",
68 connection_options.distro_name,
69 connection_options.user
70 );
71 let (release_channel, version) =
72 cx.update(|cx| (ReleaseChannel::global(cx), AppVersion::global(cx)));
73
74 let mut this = Self {
75 connection_options,
76 remote_binary_path: None,
77 platform: RemotePlatform {
78 os: RemoteOs::Linux,
79 arch: RemoteArch::X86_64,
80 },
81 os_version: None,
82 shell: String::new(),
83 shell_kind: ShellKind::Posix,
84 default_system_shell: String::from("/bin/sh"),
85 has_wsl_interop: false,
86 };
87 delegate.set_status(Some("Detecting WSL environment"), cx);
88 this.shell = this
89 .detect_shell()
90 .await
91 .context("failed detecting shell")?;
92 log::info!("Remote shell discovered: {}", this.shell);
93 this.shell_kind = ShellKind::new(&this.shell, false);
94 this.has_wsl_interop = this.detect_has_wsl_interop().await.unwrap_or_default();
95 log::info!(
96 "Remote has wsl interop {}",
97 if this.has_wsl_interop {
98 "enabled"
99 } else {
100 "disabled"
101 }
102 );
103 this.platform = this
104 .detect_platform()
105 .await
106 .context("failed detecting platform")?;
107 log::info!("Remote platform discovered: {:?}", this.platform);
108 this.os_version = this.detect_os_version().await;
109 log::info!("Remote OS version discovered: {:?}", this.os_version);
110 this.remote_binary_path = Some(
111 this.ensure_server_binary(&delegate, release_channel, version, cx)
112 .await
113 .context("failed ensuring server binary")?,
114 );
115 log::debug!("Detected WSL environment: {this:#?}");
116
117 Ok(this)
118 }
119
120 async fn detect_platform(&self) -> Result<RemotePlatform> {
121 let program = self.shell_kind.prepend_command_prefix("uname");
122 let output = self.run_wsl_command_with_output(&program, &["-sm"]).await?;
123 parse_platform(&output)
124 }
125
126 /// Best-effort detection of the remote OS version for telemetry. Failures
127 /// result in `None` rather than failing the connection.
128 async fn detect_os_version(&self) -> Option<String> {
129 let (program, args) = super::os_version_command(self.platform.os);
130 let program = self.shell_kind.prepend_command_prefix(program);
131 match self.run_wsl_command_with_output(&program, args).await {
132 Ok(output) => super::parse_os_version(self.platform.os, &output),
133 Err(error) => {
134 log::warn!("Failed to determine remote OS version: {error:#}");
135 None
136 }
137 }
138 }
139
140 async fn detect_shell(&self) -> Result<String> {
141 const DEFAULT_SHELL: &str = "sh";
142 match self
143 .run_wsl_command_with_output("sh", &["-c", "echo $SHELL"])
144 .await
145 {
146 Ok(output) => Ok(parse_shell(&output, DEFAULT_SHELL)),
147 Err(e) => {
148 log::error!("Failed to detect remote shell: {e}");
149 Ok(DEFAULT_SHELL.to_owned())
150 }
151 }
152 }
153
154 async fn detect_has_wsl_interop(&self) -> Result<bool> {
155 let interop = match self
156 .run_wsl_command_with_output("cat", &["/proc/sys/fs/binfmt_misc/WSLInterop"])
157 .await
158 {
159 Ok(interop) => interop,
160 Err(err) => self
161 .run_wsl_command_with_output("cat", &["/proc/sys/fs/binfmt_misc/WSLInterop-late"])
162 .await
163 .inspect_err(|err2| log::error!("Failed to detect wsl interop: {err}; {err2}"))?,
164 };
165 Ok(interop.contains("enabled"))
166 }
167
168 async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
169 windows_path_to_wsl_path_impl(&self.connection_options, source).await
170 }
171
172 async fn run_wsl_command_with_output(&self, program: &str, args: &[&str]) -> Result<String> {
173 run_wsl_command_with_output_impl(&self.connection_options, program, args).await
174 }
175
176 async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<()> {
177 run_wsl_command_impl(wsl_command_impl(
178 &self.connection_options,
179 program,
180 args,
181 false,
182 ))
183 .await
184 .map(|_| ())
185 }
186
187 async fn ensure_server_binary(
188 &self,
189 delegate: &Arc<dyn RemoteClientDelegate>,
190 release_channel: ReleaseChannel,
191 version: Version,
192 cx: &mut AsyncApp,
193 ) -> Result<Arc<RelPath>> {
194 let version_str = match release_channel {
195 ReleaseChannel::Dev => "build".to_string(),
196 _ => version.to_string(),
197 };
198
199 let binary_name = format!(
200 "zed-remote-server-{}-{}",
201 release_channel.dev_name(),
202 version_str
203 );
204
205 let dst_path =
206 paths::remote_server_dir_relative().join(RelPath::from_unix_str(&binary_name).unwrap());
207
208 if let Some(parent) = dst_path.parent() {
209 let parent = parent.display(PathStyle::Unix);
210 let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
211 self.run_wsl_command(&mkdir, &["-p", &parent])
212 .await
213 .map_err(|e| e.context("Failed to create directory"))?;
214 }
215
216 let binary_exists_on_server = self
217 .run_wsl_command(&dst_path.display(PathStyle::Unix), &["version"])
218 .await
219 .is_ok();
220
221 #[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
222 if let Some(remote_server_path) = super::build_remote_server_from_source(
223 &self.platform,
224 delegate.as_ref(),
225 binary_exists_on_server,
226 cx,
227 )
228 .await?
229 {
230 let tmp_path = paths::remote_server_dir_relative().join(
231 &RelPath::from_unix_str(&format!(
232 "download-{}-{}",
233 std::process::id(),
234 remote_server_path.file_name().unwrap().to_string_lossy()
235 ))
236 .unwrap(),
237 );
238 self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
239 .await?;
240 self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
241 .await?;
242 return Ok(dst_path.into());
243 }
244
245 if binary_exists_on_server {
246 return Ok(dst_path.into());
247 }
248
249 let wanted_version = match release_channel {
250 ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
251 _ => Some(cx.update(|cx| AppVersion::global(cx))),
252 };
253
254 let src_path = delegate
255 .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
256 .await?;
257
258 let tmp_path = format!(
259 "{}.{}.gz",
260 dst_path.display(PathStyle::Unix),
261 std::process::id()
262 );
263 let tmp_path = RelPath::from_unix_str(&tmp_path).unwrap();
264
265 self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
266 self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
267 .await?;
268
269 Ok(dst_path.into())
270 }
271
272 async fn upload_file(
273 &self,
274 src_path: &Path,
275 dst_path: &RelPath,
276 delegate: &Arc<dyn RemoteClientDelegate>,
277 cx: &mut AsyncApp,
278 ) -> Result<()> {
279 delegate.set_status(Some("Uploading remote server"), cx);
280
281 if let Some(parent) = dst_path.parent() {
282 let parent = parent.display(PathStyle::Unix);
283 let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
284 self.run_wsl_command(&mkdir, &["-p", &parent])
285 .await
286 .context("Failed to create directory when uploading file")?;
287 }
288
289 let t0 = Instant::now();
290 let src_stat = fs::metadata(&src_path)
291 .await
292 .with_context(|| format!("source path does not exist: {}", src_path.display()))?;
293 let size = src_stat.len();
294 log::info!(
295 "uploading remote server to WSL {:?} ({}kb)",
296 dst_path,
297 size / 1024
298 );
299
300 let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
301 let cp = self.shell_kind.prepend_command_prefix("cp");
302 self.run_wsl_command(
303 &cp,
304 &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Unix)],
305 )
306 .await
307 .map_err(|e| {
308 anyhow!(
309 "Failed to copy file {}({}) to WSL {:?}: {}",
310 src_path.display(),
311 src_path_in_wsl,
312 dst_path,
313 e
314 )
315 })?;
316
317 log::info!("uploaded remote server in {:?}", t0.elapsed());
318 Ok(())
319 }
320
321 async fn extract_and_install(
322 &self,
323 tmp_path: &RelPath,
324 dst_path: &RelPath,
325 delegate: &Arc<dyn RemoteClientDelegate>,
326 cx: &mut AsyncApp,
327 ) -> Result<()> {
328 delegate.set_status(Some("Extracting remote server"), cx);
329
330 let tmp_path_str = tmp_path.display(PathStyle::Unix);
331 let dst_path_str = dst_path.display(PathStyle::Unix);
332
333 // Build extraction script with proper error handling
334 let script = if tmp_path_str.ends_with(".gz") {
335 let uncompressed = tmp_path_str.trim_end_matches(".gz");
336 format!(
337 "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
338 tmp_path_str, uncompressed, uncompressed, dst_path_str
339 )
340 } else {
341 format!(
342 "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
343 tmp_path_str, tmp_path_str, dst_path_str
344 )
345 };
346
347 self.run_wsl_command("sh", &["-c", &script])
348 .await
349 .map_err(|e| e.context("Failed to extract server binary"))?;
350 Ok(())
351 }
352}
353
354#[async_trait(?Send)]
355impl RemoteConnection for WslRemoteConnection {
356 fn start_proxy(
357 &self,
358 unique_identifier: String,
359 reconnect: bool,
360 incoming_tx: UnboundedSender<Envelope>,
361 outgoing_rx: UnboundedReceiver<Envelope>,
362 connection_activity_tx: Sender<()>,
363 delegate: Arc<dyn RemoteClientDelegate>,
364 cx: &mut AsyncApp,
365 ) -> Task<Result<i32>> {
366 delegate.set_status(Some("Starting proxy"), cx);
367
368 let Some(remote_binary_path) = &self.remote_binary_path else {
369 return Task::ready(Err(anyhow!("Remote binary path not set")));
370 };
371
372 let mut proxy_args = vec![];
373 for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
374 if let Some(value) = std::env::var(env_var).ok() {
375 // We don't quote the value here as it seems excessive and may result in invalid envs for the
376 // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
377 // in the proxy server. Therefore, we pass the env vars as is.
378 proxy_args.push(format!("{}={}", env_var, value));
379 }
380 }
381
382 proxy_args.push(remote_binary_path.display(PathStyle::Unix).into_owned());
383 proxy_args.push("proxy".to_owned());
384 proxy_args.push("--identifier".to_owned());
385 proxy_args.push(unique_identifier);
386
387 if reconnect {
388 proxy_args.push("--reconnect".to_owned());
389 }
390
391 let proxy_process =
392 match wsl_command_impl(&self.connection_options, "env", &proxy_args, true)
393 .kill_on_drop(true)
394 .spawn()
395 {
396 Ok(process) => process,
397 Err(error) => {
398 return Task::ready(Err(
399 anyhow::Error::new(error).context("failed to spawn remote server")
400 ));
401 }
402 };
403
404 super::handle_rpc_messages_over_child_process_stdio(
405 proxy_process,
406 incoming_tx,
407 outgoing_rx,
408 connection_activity_tx,
409 cx,
410 )
411 }
412
413 fn upload_directory(
414 &self,
415 src_path: PathBuf,
416 dest_path: RemotePathBuf,
417 cx: &App,
418 ) -> Task<Result<()>> {
419 cx.background_spawn({
420 let options = self.connection_options.clone();
421 async move {
422 let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path).await?;
423 let command = wsl_command_impl(
424 &options,
425 "cp",
426 &["-r", &wsl_src, &dest_path.to_string()],
427 true,
428 );
429 run_wsl_command_impl(command).await.map_err(|e| {
430 anyhow!(
431 "failed to upload directory {} -> {}: {}",
432 src_path.display(),
433 dest_path,
434 e
435 )
436 })?;
437
438 Ok(())
439 }
440 })
441 }
442
443 async fn kill(&self) -> Result<()> {
444 Ok(())
445 }
446
447 fn has_been_killed(&self) -> bool {
448 false
449 }
450
451 fn shares_network_interface(&self) -> bool {
452 true
453 }
454
455 fn build_command(
456 &self,
457 program: Option<String>,
458 args: &[String],
459 env: &HashMap<String, String>,
460 working_dir: Option<String>,
461 port_forward: Option<(u16, String, u16)>,
462 _interactive: Interactive,
463 ) -> Result<CommandTemplate> {
464 if port_forward.is_some() {
465 bail!("WSL shares the network interface with the host system");
466 }
467
468 let shell_kind = self.shell_kind;
469 let working_dir = working_dir
470 .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Unix).to_string())
471 .unwrap_or("~".to_string());
472
473 let mut exec = String::from("exec env ");
474
475 for (key, value) in env.iter() {
476 let assignment = format!("{key}={value}");
477 let assignment = shell_kind.try_quote(&assignment).context("shell quoting")?;
478 write!(exec, "{assignment} ")?;
479 }
480
481 if let Some(program) = program {
482 write!(
483 exec,
484 "{}",
485 shell_kind
486 .try_quote_prefix_aware(&program)
487 .context("shell quoting")?
488 )?;
489 for arg in args {
490 let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
491 write!(exec, " {}", &arg)?;
492 }
493 } else {
494 write!(&mut exec, "{} -l", self.shell)?;
495 }
496 let (command, args) =
497 ShellBuilder::new(&Shell::Program(self.shell.clone()), false).build(Some(exec), &[]);
498
499 let mut wsl_args = if let Some(user) = &self.connection_options.user {
500 vec![
501 "--distribution".to_string(),
502 self.connection_options.distro_name.clone(),
503 "--user".to_string(),
504 user.clone(),
505 "--cd".to_string(),
506 working_dir,
507 "--".to_string(),
508 command,
509 ]
510 } else {
511 vec![
512 "--distribution".to_string(),
513 self.connection_options.distro_name.clone(),
514 "--cd".to_string(),
515 working_dir,
516 "--".to_string(),
517 command,
518 ]
519 };
520 wsl_args.extend(args);
521
522 Ok(CommandTemplate {
523 program: "wsl.exe".to_string(),
524 args: wsl_args,
525 env: HashMap::default(),
526 })
527 }
528
529 fn build_forward_ports_command(
530 &self,
531 _: Vec<(u16, String, u16)>,
532 ) -> anyhow::Result<CommandTemplate> {
533 Err(anyhow!("WSL shares a network interface with the host"))
534 }
535
536 fn connection_options(&self) -> RemoteConnectionOptions {
537 RemoteConnectionOptions::Wsl(self.connection_options.clone())
538 }
539
540 fn path_style(&self) -> PathStyle {
541 PathStyle::Unix
542 }
543
544 fn remote_platform(&self) -> RemotePlatform {
545 self.platform
546 }
547
548 fn remote_os_version(&self) -> Option<String> {
549 self.os_version.clone()
550 }
551
552 fn shell(&self) -> String {
553 self.shell.clone()
554 }
555
556 fn default_system_shell(&self) -> String {
557 self.default_system_shell.clone()
558 }
559
560 fn has_wsl_interop(&self) -> bool {
561 self.has_wsl_interop
562 }
563}
564
565/// `wslpath` is a executable available in WSL, it's a linux binary.
566/// So it doesn't support Windows style paths.
567async fn sanitize_path(path: &Path) -> Result<String> {
568 let path = smol::fs::canonicalize(path)
569 .await
570 .with_context(|| format!("Failed to canonicalize path {}", path.display()))?;
571 let path_str = path.to_string_lossy();
572
573 let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
574 Ok(sanitized.replace('\\', "/"))
575}
576
577fn run_wsl_command_with_output_impl(
578 options: &WslConnectionOptions,
579 program: &str,
580 args: &[&str],
581) -> impl Future<Output = Result<String>> + use<> {
582 let exec_command = wsl_command_impl(options, program, args, true);
583 let command = wsl_command_impl(options, program, args, false);
584 async move {
585 match run_wsl_command_impl(exec_command).await {
586 Ok(res) => Ok(res),
587 Err(exec_err) => match run_wsl_command_impl(command).await {
588 Ok(res) => Ok(res),
589 Err(e) => Err(e.context(exec_err)),
590 },
591 }
592 }
593}
594
595impl WslConnectionOptions {
596 pub fn abs_windows_path_to_wsl_path(
597 &self,
598 source: &Path,
599 ) -> impl Future<Output = Result<String>> + use<> {
600 let path_str = source.to_string_lossy();
601
602 let source = path_str.strip_prefix(r"\\?\").unwrap_or(&*path_str);
603 let source = source.replace('\\', "/");
604 run_wsl_command_with_output_impl(self, "wslpath", &["-u", &source])
605 }
606}
607
608async fn windows_path_to_wsl_path_impl(
609 options: &WslConnectionOptions,
610 source: &Path,
611) -> Result<String> {
612 let source = sanitize_path(source).await?;
613 run_wsl_command_with_output_impl(options, "wslpath", &["-u", &source]).await
614}
615
616/// Converts a WSL/POSIX path to a Windows path using `wslpath -w`.
617///
618/// For example, `/home/user/project` becomes `\\wsl.localhost\Ubuntu\home\user\project`
619#[cfg(target_os = "windows")]
620pub fn wsl_path_to_windows_path(
621 options: &WslConnectionOptions,
622 wsl_path: &Path,
623) -> impl Future<Output = Result<PathBuf>> + use<> {
624 let wsl_path_str = wsl_path.to_string_lossy().to_string();
625 let command = wsl_command_impl(options, "wslpath", &["-w", &wsl_path_str], true);
626 async move {
627 let windows_path = run_wsl_command_impl(command).await?;
628 Ok(PathBuf::from(windows_path))
629 }
630}
631
632fn run_wsl_command_impl(
633 mut command: util::command::Command,
634) -> impl Future<Output = Result<String>> {
635 async move {
636 let output = command
637 .output()
638 .await
639 .with_context(|| format!("Failed to run command '{:?}'", command))?;
640
641 if !output.status.success() {
642 return Err(anyhow!(
643 "Command '{:?}' failed: {}",
644 command,
645 String::from_utf8_lossy(&output.stderr).trim()
646 ));
647 }
648
649 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
650 }
651}
652
653/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
654///
655/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
656fn wsl_command_impl(
657 options: &WslConnectionOptions,
658 program: &str,
659 args: &[impl AsRef<OsStr>],
660 exec: bool,
661) -> util::command::Command {
662 let mut command = util::command::new_command("wsl.exe");
663
664 if let Some(user) = &options.user {
665 command.arg("--user").arg(user);
666 }
667
668 command
669 .stdin(Stdio::piped())
670 .stdout(Stdio::piped())
671 .stderr(Stdio::piped())
672 .arg("--distribution")
673 .arg(&options.distro_name)
674 .arg("--cd")
675 .arg("~");
676
677 if exec {
678 command.arg("--exec");
679 }
680
681 command.arg(program).args(args);
682
683 log::debug!("wsl {:?}", command);
684 command
685}
686