remote_client.rs

   1use crate::{
   2    SshConnectionOptions,
   3    protocol::MessageId,
   4    proxy::ProxyLaunchError,
   5    transport::{
   6        ssh::SshRemoteConnection,
   7        wsl::{WslConnectionOptions, WslRemoteConnection},
   8    },
   9};
  10use anyhow::{Context as _, Result, anyhow};
  11use async_trait::async_trait;
  12use collections::HashMap;
  13use futures::{
  14    Future, FutureExt as _, StreamExt as _,
  15    channel::{
  16        mpsc::{self, Sender, UnboundedReceiver, UnboundedSender},
  17        oneshot,
  18    },
  19    future::{BoxFuture, Shared},
  20    select, select_biased,
  21};
  22use gpui::{
  23    App, AppContext as _, AsyncApp, BackgroundExecutor, BorrowAppContext, Context, Entity,
  24    EventEmitter, Global, SemanticVersion, Task, WeakEntity,
  25};
  26use parking_lot::Mutex;
  27
  28use release_channel::ReleaseChannel;
  29use rpc::{
  30    AnyProtoClient, ErrorExt, ProtoClient, ProtoMessageHandlerSet, RpcError,
  31    proto::{self, Envelope, EnvelopedMessage, PeerId, RequestMessage, build_typed_envelope},
  32};
  33use std::{
  34    collections::VecDeque,
  35    fmt,
  36    ops::ControlFlow,
  37    path::PathBuf,
  38    sync::{
  39        Arc, Weak,
  40        atomic::{AtomicU32, AtomicU64, Ordering::SeqCst},
  41    },
  42    time::{Duration, Instant},
  43};
  44use util::{
  45    ResultExt,
  46    paths::{PathStyle, RemotePathBuf},
  47};
  48
  49#[derive(Copy, Clone, Debug)]
  50pub struct RemotePlatform {
  51    pub os: &'static str,
  52    pub arch: &'static str,
  53}
  54
  55#[derive(Clone, Debug)]
  56pub struct CommandTemplate {
  57    pub program: String,
  58    pub args: Vec<String>,
  59    pub env: HashMap<String, String>,
  60}
  61
  62pub trait RemoteClientDelegate: Send + Sync {
  63    fn ask_password(&self, prompt: String, tx: oneshot::Sender<String>, cx: &mut AsyncApp);
  64    fn get_download_params(
  65        &self,
  66        platform: RemotePlatform,
  67        release_channel: ReleaseChannel,
  68        version: Option<SemanticVersion>,
  69        cx: &mut AsyncApp,
  70    ) -> Task<Result<Option<(String, String)>>>;
  71    fn download_server_binary_locally(
  72        &self,
  73        platform: RemotePlatform,
  74        release_channel: ReleaseChannel,
  75        version: Option<SemanticVersion>,
  76        cx: &mut AsyncApp,
  77    ) -> Task<Result<PathBuf>>;
  78    fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp);
  79}
  80
  81const MAX_MISSED_HEARTBEATS: usize = 5;
  82const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
  83const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(5);
  84
  85const MAX_RECONNECT_ATTEMPTS: usize = 3;
  86
  87enum State {
  88    Connecting,
  89    Connected {
  90        ssh_connection: Arc<dyn RemoteConnection>,
  91        delegate: Arc<dyn RemoteClientDelegate>,
  92
  93        multiplex_task: Task<Result<()>>,
  94        heartbeat_task: Task<Result<()>>,
  95    },
  96    HeartbeatMissed {
  97        missed_heartbeats: usize,
  98
  99        ssh_connection: Arc<dyn RemoteConnection>,
 100        delegate: Arc<dyn RemoteClientDelegate>,
 101
 102        multiplex_task: Task<Result<()>>,
 103        heartbeat_task: Task<Result<()>>,
 104    },
 105    Reconnecting,
 106    ReconnectFailed {
 107        ssh_connection: Arc<dyn RemoteConnection>,
 108        delegate: Arc<dyn RemoteClientDelegate>,
 109
 110        error: anyhow::Error,
 111        attempts: usize,
 112    },
 113    ReconnectExhausted,
 114    ServerNotRunning,
 115}
 116
 117impl fmt::Display for State {
 118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 119        match self {
 120            Self::Connecting => write!(f, "connecting"),
 121            Self::Connected { .. } => write!(f, "connected"),
 122            Self::Reconnecting => write!(f, "reconnecting"),
 123            Self::ReconnectFailed { .. } => write!(f, "reconnect failed"),
 124            Self::ReconnectExhausted => write!(f, "reconnect exhausted"),
 125            Self::HeartbeatMissed { .. } => write!(f, "heartbeat missed"),
 126            Self::ServerNotRunning { .. } => write!(f, "server not running"),
 127        }
 128    }
 129}
 130
 131impl State {
 132    fn remote_connection(&self) -> Option<Arc<dyn RemoteConnection>> {
 133        match self {
 134            Self::Connected { ssh_connection, .. } => Some(ssh_connection.clone()),
 135            Self::HeartbeatMissed { ssh_connection, .. } => Some(ssh_connection.clone()),
 136            Self::ReconnectFailed { ssh_connection, .. } => Some(ssh_connection.clone()),
 137            _ => None,
 138        }
 139    }
 140
 141    fn can_reconnect(&self) -> bool {
 142        match self {
 143            Self::Connected { .. }
 144            | Self::HeartbeatMissed { .. }
 145            | Self::ReconnectFailed { .. } => true,
 146            State::Connecting
 147            | State::Reconnecting
 148            | State::ReconnectExhausted
 149            | State::ServerNotRunning => false,
 150        }
 151    }
 152
 153    fn is_reconnect_failed(&self) -> bool {
 154        matches!(self, Self::ReconnectFailed { .. })
 155    }
 156
 157    fn is_reconnect_exhausted(&self) -> bool {
 158        matches!(self, Self::ReconnectExhausted { .. })
 159    }
 160
 161    fn is_server_not_running(&self) -> bool {
 162        matches!(self, Self::ServerNotRunning)
 163    }
 164
 165    fn is_reconnecting(&self) -> bool {
 166        matches!(self, Self::Reconnecting { .. })
 167    }
 168
 169    fn heartbeat_recovered(self) -> Self {
 170        match self {
 171            Self::HeartbeatMissed {
 172                ssh_connection,
 173                delegate,
 174                multiplex_task,
 175                heartbeat_task,
 176                ..
 177            } => Self::Connected {
 178                ssh_connection,
 179                delegate,
 180                multiplex_task,
 181                heartbeat_task,
 182            },
 183            _ => self,
 184        }
 185    }
 186
 187    fn heartbeat_missed(self) -> Self {
 188        match self {
 189            Self::Connected {
 190                ssh_connection,
 191                delegate,
 192                multiplex_task,
 193                heartbeat_task,
 194            } => Self::HeartbeatMissed {
 195                missed_heartbeats: 1,
 196                ssh_connection,
 197                delegate,
 198                multiplex_task,
 199                heartbeat_task,
 200            },
 201            Self::HeartbeatMissed {
 202                missed_heartbeats,
 203                ssh_connection,
 204                delegate,
 205                multiplex_task,
 206                heartbeat_task,
 207            } => Self::HeartbeatMissed {
 208                missed_heartbeats: missed_heartbeats + 1,
 209                ssh_connection,
 210                delegate,
 211                multiplex_task,
 212                heartbeat_task,
 213            },
 214            _ => self,
 215        }
 216    }
 217}
 218
 219/// The state of the ssh connection.
 220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 221pub enum ConnectionState {
 222    Connecting,
 223    Connected,
 224    HeartbeatMissed,
 225    Reconnecting,
 226    Disconnected,
 227}
 228
 229impl From<&State> for ConnectionState {
 230    fn from(value: &State) -> Self {
 231        match value {
 232            State::Connecting => Self::Connecting,
 233            State::Connected { .. } => Self::Connected,
 234            State::Reconnecting | State::ReconnectFailed { .. } => Self::Reconnecting,
 235            State::HeartbeatMissed { .. } => Self::HeartbeatMissed,
 236            State::ReconnectExhausted => Self::Disconnected,
 237            State::ServerNotRunning => Self::Disconnected,
 238        }
 239    }
 240}
 241
 242pub struct RemoteClient {
 243    client: Arc<ChannelClient>,
 244    unique_identifier: String,
 245    connection_options: RemoteConnectionOptions,
 246    path_style: PathStyle,
 247    state: Option<State>,
 248}
 249
 250#[derive(Debug)]
 251pub enum RemoteClientEvent {
 252    Disconnected,
 253}
 254
 255impl EventEmitter<RemoteClientEvent> for RemoteClient {}
 256
 257// Identifies the socket on the remote server so that reconnects
 258// can re-join the same project.
 259pub enum ConnectionIdentifier {
 260    Setup(u64),
 261    Workspace(i64),
 262}
 263
 264static NEXT_ID: AtomicU64 = AtomicU64::new(1);
 265
 266impl ConnectionIdentifier {
 267    pub fn setup() -> Self {
 268        Self::Setup(NEXT_ID.fetch_add(1, SeqCst))
 269    }
 270
 271    // This string gets used in a socket name, and so must be relatively short.
 272    // The total length of:
 273    //   /home/{username}/.local/share/zed/server_state/{name}/stdout.sock
 274    // Must be less than about 100 characters
 275    //   https://unix.stackexchange.com/questions/367008/why-is-socket-path-length-limited-to-a-hundred-chars
 276    // So our strings should be at most 20 characters or so.
 277    fn to_string(&self, cx: &App) -> String {
 278        let identifier_prefix = match ReleaseChannel::global(cx) {
 279            ReleaseChannel::Stable => "".to_string(),
 280            release_channel => format!("{}-", release_channel.dev_name()),
 281        };
 282        match self {
 283            Self::Setup(setup_id) => format!("{identifier_prefix}setup-{setup_id}"),
 284            Self::Workspace(workspace_id) => {
 285                format!("{identifier_prefix}workspace-{workspace_id}",)
 286            }
 287        }
 288    }
 289}
 290
 291impl RemoteClient {
 292    pub fn ssh(
 293        unique_identifier: ConnectionIdentifier,
 294        connection_options: SshConnectionOptions,
 295        cancellation: oneshot::Receiver<()>,
 296        delegate: Arc<dyn RemoteClientDelegate>,
 297        cx: &mut App,
 298    ) -> Task<Result<Option<Entity<Self>>>> {
 299        Self::new(
 300            unique_identifier,
 301            RemoteConnectionOptions::Ssh(connection_options),
 302            cancellation,
 303            delegate,
 304            cx,
 305        )
 306    }
 307
 308    pub fn new(
 309        unique_identifier: ConnectionIdentifier,
 310        connection_options: RemoteConnectionOptions,
 311        cancellation: oneshot::Receiver<()>,
 312        delegate: Arc<dyn RemoteClientDelegate>,
 313        cx: &mut App,
 314    ) -> Task<Result<Option<Entity<Self>>>> {
 315        let unique_identifier = unique_identifier.to_string(cx);
 316        cx.spawn(async move |cx| {
 317            let success = Box::pin(async move {
 318                let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 319                let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 320                let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 321
 322                let client =
 323                    cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "client"))?;
 324
 325                let ssh_connection = cx
 326                    .update(|cx| {
 327                        cx.update_default_global(|pool: &mut ConnectionPool, cx| {
 328                            pool.connect(connection_options.clone(), &delegate, cx)
 329                        })
 330                    })?
 331                    .await
 332                    .map_err(|e| e.cloned())?;
 333
 334                let path_style = ssh_connection.path_style();
 335                let this = cx.new(|_| Self {
 336                    client: client.clone(),
 337                    unique_identifier: unique_identifier.clone(),
 338                    connection_options,
 339                    path_style,
 340                    state: Some(State::Connecting),
 341                })?;
 342
 343                let io_task = ssh_connection.start_proxy(
 344                    unique_identifier,
 345                    false,
 346                    incoming_tx,
 347                    outgoing_rx,
 348                    connection_activity_tx,
 349                    delegate.clone(),
 350                    cx,
 351                );
 352
 353                let multiplex_task = Self::monitor(this.downgrade(), io_task, cx);
 354
 355                if let Err(error) = client.ping(HEARTBEAT_TIMEOUT).await {
 356                    log::error!("failed to establish connection: {}", error);
 357                    return Err(error);
 358                }
 359
 360                let heartbeat_task = Self::heartbeat(this.downgrade(), connection_activity_rx, cx);
 361
 362                this.update(cx, |this, _| {
 363                    this.state = Some(State::Connected {
 364                        ssh_connection,
 365                        delegate,
 366                        multiplex_task,
 367                        heartbeat_task,
 368                    });
 369                })?;
 370
 371                Ok(Some(this))
 372            });
 373
 374            select! {
 375                _ = cancellation.fuse() => {
 376                    Ok(None)
 377                }
 378                result = success.fuse() =>  result
 379            }
 380        })
 381    }
 382
 383    pub fn proto_client_from_channels(
 384        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
 385        outgoing_tx: mpsc::UnboundedSender<Envelope>,
 386        cx: &App,
 387        name: &'static str,
 388    ) -> AnyProtoClient {
 389        ChannelClient::new(incoming_rx, outgoing_tx, cx, name).into()
 390    }
 391
 392    pub fn shutdown_processes<T: RequestMessage>(
 393        &mut self,
 394        shutdown_request: Option<T>,
 395        executor: BackgroundExecutor,
 396    ) -> Option<impl Future<Output = ()> + use<T>> {
 397        let state = self.state.take()?;
 398        log::info!("shutting down ssh processes");
 399
 400        let State::Connected {
 401            multiplex_task,
 402            heartbeat_task,
 403            ssh_connection,
 404            delegate,
 405        } = state
 406        else {
 407            return None;
 408        };
 409
 410        let client = self.client.clone();
 411
 412        Some(async move {
 413            if let Some(shutdown_request) = shutdown_request {
 414                client.send(shutdown_request).log_err();
 415                // We wait 50ms instead of waiting for a response, because
 416                // waiting for a response would require us to wait on the main thread
 417                // which we want to avoid in an `on_app_quit` callback.
 418                executor.timer(Duration::from_millis(50)).await;
 419            }
 420
 421            // Drop `multiplex_task` because it owns our ssh_proxy_process, which is a
 422            // child of master_process.
 423            drop(multiplex_task);
 424            // Now drop the rest of state, which kills master process.
 425            drop(heartbeat_task);
 426            drop(ssh_connection);
 427            drop(delegate);
 428        })
 429    }
 430
 431    fn reconnect(&mut self, cx: &mut Context<Self>) -> Result<()> {
 432        let can_reconnect = self
 433            .state
 434            .as_ref()
 435            .map(|state| state.can_reconnect())
 436            .unwrap_or(false);
 437        if !can_reconnect {
 438            log::info!("aborting reconnect, because not in state that allows reconnecting");
 439            let error = if let Some(state) = self.state.as_ref() {
 440                format!("invalid state, cannot reconnect while in state {state}")
 441            } else {
 442                "no state set".to_string()
 443            };
 444            anyhow::bail!(error);
 445        }
 446
 447        let state = self.state.take().unwrap();
 448        let (attempts, remote_connection, delegate) = match state {
 449            State::Connected {
 450                ssh_connection,
 451                delegate,
 452                multiplex_task,
 453                heartbeat_task,
 454            }
 455            | State::HeartbeatMissed {
 456                ssh_connection,
 457                delegate,
 458                multiplex_task,
 459                heartbeat_task,
 460                ..
 461            } => {
 462                drop(multiplex_task);
 463                drop(heartbeat_task);
 464                (0, ssh_connection, delegate)
 465            }
 466            State::ReconnectFailed {
 467                attempts,
 468                ssh_connection,
 469                delegate,
 470                ..
 471            } => (attempts, ssh_connection, delegate),
 472            State::Connecting
 473            | State::Reconnecting
 474            | State::ReconnectExhausted
 475            | State::ServerNotRunning => unreachable!(),
 476        };
 477
 478        let attempts = attempts + 1;
 479        if attempts > MAX_RECONNECT_ATTEMPTS {
 480            log::error!(
 481                "Failed to reconnect to after {} attempts, giving up",
 482                MAX_RECONNECT_ATTEMPTS
 483            );
 484            self.set_state(State::ReconnectExhausted, cx);
 485            return Ok(());
 486        }
 487
 488        self.set_state(State::Reconnecting, cx);
 489
 490        log::info!("Trying to reconnect to ssh server... Attempt {}", attempts);
 491
 492        let unique_identifier = self.unique_identifier.clone();
 493        let client = self.client.clone();
 494        let reconnect_task = cx.spawn(async move |this, cx| {
 495            macro_rules! failed {
 496                ($error:expr, $attempts:expr, $ssh_connection:expr, $delegate:expr) => {
 497                    return State::ReconnectFailed {
 498                        error: anyhow!($error),
 499                        attempts: $attempts,
 500                        ssh_connection: $ssh_connection,
 501                        delegate: $delegate,
 502                    };
 503                };
 504            }
 505
 506            if let Err(error) = remote_connection
 507                .kill()
 508                .await
 509                .context("Failed to kill ssh process")
 510            {
 511                failed!(error, attempts, remote_connection, delegate);
 512            };
 513
 514            let connection_options = remote_connection.connection_options();
 515
 516            let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 517            let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 518            let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 519
 520            let (ssh_connection, io_task) = match async {
 521                let ssh_connection = cx
 522                    .update_global(|pool: &mut ConnectionPool, cx| {
 523                        pool.connect(connection_options, &delegate, cx)
 524                    })?
 525                    .await
 526                    .map_err(|error| error.cloned())?;
 527
 528                let io_task = ssh_connection.start_proxy(
 529                    unique_identifier,
 530                    true,
 531                    incoming_tx,
 532                    outgoing_rx,
 533                    connection_activity_tx,
 534                    delegate.clone(),
 535                    cx,
 536                );
 537                anyhow::Ok((ssh_connection, io_task))
 538            }
 539            .await
 540            {
 541                Ok((ssh_connection, io_task)) => (ssh_connection, io_task),
 542                Err(error) => {
 543                    failed!(error, attempts, remote_connection, delegate);
 544                }
 545            };
 546
 547            let multiplex_task = Self::monitor(this.clone(), io_task, cx);
 548            client.reconnect(incoming_rx, outgoing_tx, cx);
 549
 550            if let Err(error) = client.resync(HEARTBEAT_TIMEOUT).await {
 551                failed!(error, attempts, ssh_connection, delegate);
 552            };
 553
 554            State::Connected {
 555                ssh_connection,
 556                delegate,
 557                multiplex_task,
 558                heartbeat_task: Self::heartbeat(this.clone(), connection_activity_rx, cx),
 559            }
 560        });
 561
 562        cx.spawn(async move |this, cx| {
 563            let new_state = reconnect_task.await;
 564            this.update(cx, |this, cx| {
 565                this.try_set_state(cx, |old_state| {
 566                    if old_state.is_reconnecting() {
 567                        match &new_state {
 568                            State::Connecting
 569                            | State::Reconnecting
 570                            | State::HeartbeatMissed { .. }
 571                            | State::ServerNotRunning => {}
 572                            State::Connected { .. } => {
 573                                log::info!("Successfully reconnected");
 574                            }
 575                            State::ReconnectFailed {
 576                                error, attempts, ..
 577                            } => {
 578                                log::error!(
 579                                    "Reconnect attempt {} failed: {:?}. Starting new attempt...",
 580                                    attempts,
 581                                    error
 582                                );
 583                            }
 584                            State::ReconnectExhausted => {
 585                                log::error!("Reconnect attempt failed and all attempts exhausted");
 586                            }
 587                        }
 588                        Some(new_state)
 589                    } else {
 590                        None
 591                    }
 592                });
 593
 594                if this.state_is(State::is_reconnect_failed) {
 595                    this.reconnect(cx)
 596                } else if this.state_is(State::is_reconnect_exhausted) {
 597                    Ok(())
 598                } else {
 599                    log::debug!("State has transition from Reconnecting into new state while attempting reconnect.");
 600                    Ok(())
 601                }
 602            })
 603        })
 604        .detach_and_log_err(cx);
 605
 606        Ok(())
 607    }
 608
 609    fn heartbeat(
 610        this: WeakEntity<Self>,
 611        mut connection_activity_rx: mpsc::Receiver<()>,
 612        cx: &mut AsyncApp,
 613    ) -> Task<Result<()>> {
 614        let Ok(client) = this.read_with(cx, |this, _| this.client.clone()) else {
 615            return Task::ready(Err(anyhow!("SshRemoteClient lost")));
 616        };
 617
 618        cx.spawn(async move |cx| {
 619            let mut missed_heartbeats = 0;
 620
 621            let keepalive_timer = cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse();
 622            futures::pin_mut!(keepalive_timer);
 623
 624            loop {
 625                select_biased! {
 626                    result = connection_activity_rx.next().fuse() => {
 627                        if result.is_none() {
 628                            log::warn!("ssh heartbeat: connection activity channel has been dropped. stopping.");
 629                            return Ok(());
 630                        }
 631
 632                        if missed_heartbeats != 0 {
 633                            missed_heartbeats = 0;
 634                            let _ =this.update(cx, |this, cx| {
 635                                this.handle_heartbeat_result(missed_heartbeats, cx)
 636                            })?;
 637                        }
 638                    }
 639                    _ = keepalive_timer => {
 640                        log::debug!("Sending heartbeat to server...");
 641
 642                        let result = select_biased! {
 643                            _ = connection_activity_rx.next().fuse() => {
 644                                Ok(())
 645                            }
 646                            ping_result = client.ping(HEARTBEAT_TIMEOUT).fuse() => {
 647                                ping_result
 648                            }
 649                        };
 650
 651                        if result.is_err() {
 652                            missed_heartbeats += 1;
 653                            log::warn!(
 654                                "No heartbeat from server after {:?}. Missed heartbeat {} out of {}.",
 655                                HEARTBEAT_TIMEOUT,
 656                                missed_heartbeats,
 657                                MAX_MISSED_HEARTBEATS
 658                            );
 659                        } else if missed_heartbeats != 0 {
 660                            missed_heartbeats = 0;
 661                        } else {
 662                            continue;
 663                        }
 664
 665                        let result = this.update(cx, |this, cx| {
 666                            this.handle_heartbeat_result(missed_heartbeats, cx)
 667                        })?;
 668                        if result.is_break() {
 669                            return Ok(());
 670                        }
 671                    }
 672                }
 673
 674                keepalive_timer.set(cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse());
 675            }
 676        })
 677    }
 678
 679    fn handle_heartbeat_result(
 680        &mut self,
 681        missed_heartbeats: usize,
 682        cx: &mut Context<Self>,
 683    ) -> ControlFlow<()> {
 684        let state = self.state.take().unwrap();
 685        let next_state = if missed_heartbeats > 0 {
 686            state.heartbeat_missed()
 687        } else {
 688            state.heartbeat_recovered()
 689        };
 690
 691        self.set_state(next_state, cx);
 692
 693        if missed_heartbeats >= MAX_MISSED_HEARTBEATS {
 694            log::error!(
 695                "Missed last {} heartbeats. Reconnecting...",
 696                missed_heartbeats
 697            );
 698
 699            self.reconnect(cx)
 700                .context("failed to start reconnect process after missing heartbeats")
 701                .log_err();
 702            ControlFlow::Break(())
 703        } else {
 704            ControlFlow::Continue(())
 705        }
 706    }
 707
 708    fn monitor(
 709        this: WeakEntity<Self>,
 710        io_task: Task<Result<i32>>,
 711        cx: &AsyncApp,
 712    ) -> Task<Result<()>> {
 713        cx.spawn(async move |cx| {
 714            let result = io_task.await;
 715
 716            match result {
 717                Ok(exit_code) => {
 718                    if let Some(error) = ProxyLaunchError::from_exit_code(exit_code) {
 719                        match error {
 720                            ProxyLaunchError::ServerNotRunning => {
 721                                log::error!("failed to reconnect because server is not running");
 722                                this.update(cx, |this, cx| {
 723                                    this.set_state(State::ServerNotRunning, cx);
 724                                })?;
 725                            }
 726                        }
 727                    } else if exit_code > 0 {
 728                        log::error!("proxy process terminated unexpectedly");
 729                        this.update(cx, |this, cx| {
 730                            this.reconnect(cx).ok();
 731                        })?;
 732                    }
 733                }
 734                Err(error) => {
 735                    log::warn!("ssh io task died with error: {:?}. reconnecting...", error);
 736                    this.update(cx, |this, cx| {
 737                        this.reconnect(cx).ok();
 738                    })?;
 739                }
 740            }
 741
 742            Ok(())
 743        })
 744    }
 745
 746    fn state_is(&self, check: impl FnOnce(&State) -> bool) -> bool {
 747        self.state.as_ref().is_some_and(check)
 748    }
 749
 750    fn try_set_state(&mut self, cx: &mut Context<Self>, map: impl FnOnce(&State) -> Option<State>) {
 751        let new_state = self.state.as_ref().and_then(map);
 752        if let Some(new_state) = new_state {
 753            self.state.replace(new_state);
 754            cx.notify();
 755        }
 756    }
 757
 758    fn set_state(&mut self, state: State, cx: &mut Context<Self>) {
 759        log::info!("setting state to '{}'", &state);
 760
 761        let is_reconnect_exhausted = state.is_reconnect_exhausted();
 762        let is_server_not_running = state.is_server_not_running();
 763        self.state.replace(state);
 764
 765        if is_reconnect_exhausted || is_server_not_running {
 766            cx.emit(RemoteClientEvent::Disconnected);
 767        }
 768        cx.notify();
 769    }
 770
 771    pub fn shell(&self) -> Option<String> {
 772        Some(self.remote_connection()?.shell())
 773    }
 774
 775    pub fn shares_network_interface(&self) -> bool {
 776        self.remote_connection()
 777            .map_or(false, |connection| connection.shares_network_interface())
 778    }
 779
 780    pub fn build_command(
 781        &self,
 782        program: Option<String>,
 783        args: &[String],
 784        env: &HashMap<String, String>,
 785        working_dir: Option<String>,
 786        port_forward: Option<(u16, String, u16)>,
 787    ) -> Result<CommandTemplate> {
 788        let Some(connection) = self.remote_connection() else {
 789            return Err(anyhow!("no ssh connection"));
 790        };
 791        connection.build_command(program, args, env, working_dir, port_forward)
 792    }
 793
 794    pub fn upload_directory(
 795        &self,
 796        src_path: PathBuf,
 797        dest_path: RemotePathBuf,
 798        cx: &App,
 799    ) -> Task<Result<()>> {
 800        let Some(connection) = self.remote_connection() else {
 801            return Task::ready(Err(anyhow!("no ssh connection")));
 802        };
 803        connection.upload_directory(src_path, dest_path, cx)
 804    }
 805
 806    pub fn proto_client(&self) -> AnyProtoClient {
 807        self.client.clone().into()
 808    }
 809
 810    pub fn connection_options(&self) -> RemoteConnectionOptions {
 811        self.connection_options.clone()
 812    }
 813
 814    pub fn connection_state(&self) -> ConnectionState {
 815        self.state
 816            .as_ref()
 817            .map(ConnectionState::from)
 818            .unwrap_or(ConnectionState::Disconnected)
 819    }
 820
 821    pub fn is_disconnected(&self) -> bool {
 822        self.connection_state() == ConnectionState::Disconnected
 823    }
 824
 825    pub fn path_style(&self) -> PathStyle {
 826        self.path_style
 827    }
 828
 829    #[cfg(any(test, feature = "test-support"))]
 830    pub fn simulate_disconnect(&self, client_cx: &mut App) -> Task<()> {
 831        let opts = self.connection_options();
 832        client_cx.spawn(async move |cx| {
 833            let connection = cx
 834                .update_global(|c: &mut ConnectionPool, _| {
 835                    if let Some(ConnectionPoolEntry::Connecting(c)) = c.connections.get(&opts) {
 836                        c.clone()
 837                    } else {
 838                        panic!("missing test connection")
 839                    }
 840                })
 841                .unwrap()
 842                .await
 843                .unwrap();
 844
 845            connection.simulate_disconnect(cx);
 846        })
 847    }
 848
 849    #[cfg(any(test, feature = "test-support"))]
 850    pub fn fake_server(
 851        client_cx: &mut gpui::TestAppContext,
 852        server_cx: &mut gpui::TestAppContext,
 853    ) -> (RemoteConnectionOptions, AnyProtoClient) {
 854        let port = client_cx
 855            .update(|cx| cx.default_global::<ConnectionPool>().connections.len() as u16 + 1);
 856        let opts = RemoteConnectionOptions::Ssh(SshConnectionOptions {
 857            host: "<fake>".to_string(),
 858            port: Some(port),
 859            ..Default::default()
 860        });
 861        let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
 862        let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
 863        let server_client =
 864            server_cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server"));
 865        let connection: Arc<dyn RemoteConnection> = Arc::new(fake::FakeRemoteConnection {
 866            connection_options: opts.clone(),
 867            server_cx: fake::SendableCx::new(server_cx),
 868            server_channel: server_client.clone(),
 869        });
 870
 871        client_cx.update(|cx| {
 872            cx.update_default_global(|c: &mut ConnectionPool, cx| {
 873                c.connections.insert(
 874                    opts.clone(),
 875                    ConnectionPoolEntry::Connecting(
 876                        cx.background_spawn({
 877                            let connection = connection.clone();
 878                            async move { Ok(connection.clone()) }
 879                        })
 880                        .shared(),
 881                    ),
 882                );
 883            })
 884        });
 885
 886        (opts, server_client.into())
 887    }
 888
 889    #[cfg(any(test, feature = "test-support"))]
 890    pub async fn fake_client(
 891        opts: RemoteConnectionOptions,
 892        client_cx: &mut gpui::TestAppContext,
 893    ) -> Entity<Self> {
 894        let (_tx, rx) = oneshot::channel();
 895        client_cx
 896            .update(|cx| {
 897                Self::new(
 898                    ConnectionIdentifier::setup(),
 899                    opts,
 900                    rx,
 901                    Arc::new(fake::Delegate),
 902                    cx,
 903                )
 904            })
 905            .await
 906            .unwrap()
 907            .unwrap()
 908    }
 909
 910    fn remote_connection(&self) -> Option<Arc<dyn RemoteConnection>> {
 911        self.state
 912            .as_ref()
 913            .and_then(|state| state.remote_connection())
 914    }
 915}
 916
 917enum ConnectionPoolEntry {
 918    Connecting(Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>>),
 919    Connected(Weak<dyn RemoteConnection>),
 920}
 921
 922#[derive(Default)]
 923struct ConnectionPool {
 924    connections: HashMap<RemoteConnectionOptions, ConnectionPoolEntry>,
 925}
 926
 927impl Global for ConnectionPool {}
 928
 929impl ConnectionPool {
 930    pub fn connect(
 931        &mut self,
 932        opts: RemoteConnectionOptions,
 933        delegate: &Arc<dyn RemoteClientDelegate>,
 934        cx: &mut App,
 935    ) -> Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>> {
 936        let connection = self.connections.get(&opts);
 937        match connection {
 938            Some(ConnectionPoolEntry::Connecting(task)) => {
 939                let delegate = delegate.clone();
 940                cx.spawn(async move |cx| {
 941                    delegate.set_status(Some("Waiting for existing connection attempt"), cx);
 942                })
 943                .detach();
 944                return task.clone();
 945            }
 946            Some(ConnectionPoolEntry::Connected(ssh)) => {
 947                if let Some(ssh) = ssh.upgrade()
 948                    && !ssh.has_been_killed()
 949                {
 950                    return Task::ready(Ok(ssh)).shared();
 951                }
 952                self.connections.remove(&opts);
 953            }
 954            None => {}
 955        }
 956
 957        let task = cx
 958            .spawn({
 959                let opts = opts.clone();
 960                let delegate = delegate.clone();
 961                async move |cx| {
 962                    let connection = match opts.clone() {
 963                        RemoteConnectionOptions::Ssh(opts) => {
 964                            SshRemoteConnection::new(opts, delegate, cx)
 965                                .await
 966                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
 967                        }
 968                        RemoteConnectionOptions::Wsl(opts) => {
 969                            WslRemoteConnection::new(opts, delegate, cx)
 970                                .await
 971                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
 972                        }
 973                    };
 974
 975                    cx.update_global(|pool: &mut Self, _| {
 976                        debug_assert!(matches!(
 977                            pool.connections.get(&opts),
 978                            Some(ConnectionPoolEntry::Connecting(_))
 979                        ));
 980                        match connection {
 981                            Ok(connection) => {
 982                                pool.connections.insert(
 983                                    opts.clone(),
 984                                    ConnectionPoolEntry::Connected(Arc::downgrade(&connection)),
 985                                );
 986                                Ok(connection)
 987                            }
 988                            Err(error) => {
 989                                pool.connections.remove(&opts);
 990                                Err(Arc::new(error))
 991                            }
 992                        }
 993                    })?
 994                }
 995            })
 996            .shared();
 997
 998        self.connections
 999            .insert(opts.clone(), ConnectionPoolEntry::Connecting(task.clone()));
1000        task
1001    }
1002}
1003
1004#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1005pub enum RemoteConnectionOptions {
1006    Ssh(SshConnectionOptions),
1007    Wsl(WslConnectionOptions),
1008}
1009
1010impl RemoteConnectionOptions {
1011    pub fn display_name(&self) -> String {
1012        match self {
1013            RemoteConnectionOptions::Ssh(opts) => opts.host.clone(),
1014            RemoteConnectionOptions::Wsl(opts) => opts.distro_name.clone(),
1015        }
1016    }
1017}
1018
1019impl From<SshConnectionOptions> for RemoteConnectionOptions {
1020    fn from(opts: SshConnectionOptions) -> Self {
1021        RemoteConnectionOptions::Ssh(opts)
1022    }
1023}
1024
1025impl From<WslConnectionOptions> for RemoteConnectionOptions {
1026    fn from(opts: WslConnectionOptions) -> Self {
1027        RemoteConnectionOptions::Wsl(opts)
1028    }
1029}
1030
1031#[async_trait(?Send)]
1032pub(crate) trait RemoteConnection: Send + Sync {
1033    fn start_proxy(
1034        &self,
1035        unique_identifier: String,
1036        reconnect: bool,
1037        incoming_tx: UnboundedSender<Envelope>,
1038        outgoing_rx: UnboundedReceiver<Envelope>,
1039        connection_activity_tx: Sender<()>,
1040        delegate: Arc<dyn RemoteClientDelegate>,
1041        cx: &mut AsyncApp,
1042    ) -> Task<Result<i32>>;
1043    fn upload_directory(
1044        &self,
1045        src_path: PathBuf,
1046        dest_path: RemotePathBuf,
1047        cx: &App,
1048    ) -> Task<Result<()>>;
1049    async fn kill(&self) -> Result<()>;
1050    fn has_been_killed(&self) -> bool;
1051    fn shares_network_interface(&self) -> bool {
1052        false
1053    }
1054    fn build_command(
1055        &self,
1056        program: Option<String>,
1057        args: &[String],
1058        env: &HashMap<String, String>,
1059        working_dir: Option<String>,
1060        port_forward: Option<(u16, String, u16)>,
1061    ) -> Result<CommandTemplate>;
1062    fn connection_options(&self) -> RemoteConnectionOptions;
1063    fn path_style(&self) -> PathStyle;
1064    fn shell(&self) -> String;
1065
1066    #[cfg(any(test, feature = "test-support"))]
1067    fn simulate_disconnect(&self, _: &AsyncApp) {}
1068}
1069
1070type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
1071
1072struct ChannelClient {
1073    next_message_id: AtomicU32,
1074    outgoing_tx: Mutex<mpsc::UnboundedSender<Envelope>>,
1075    buffer: Mutex<VecDeque<Envelope>>,
1076    response_channels: ResponseChannels,
1077    message_handlers: Mutex<ProtoMessageHandlerSet>,
1078    max_received: AtomicU32,
1079    name: &'static str,
1080    task: Mutex<Task<Result<()>>>,
1081}
1082
1083impl ChannelClient {
1084    fn new(
1085        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1086        outgoing_tx: mpsc::UnboundedSender<Envelope>,
1087        cx: &App,
1088        name: &'static str,
1089    ) -> Arc<Self> {
1090        Arc::new_cyclic(|this| Self {
1091            outgoing_tx: Mutex::new(outgoing_tx),
1092            next_message_id: AtomicU32::new(0),
1093            max_received: AtomicU32::new(0),
1094            response_channels: ResponseChannels::default(),
1095            message_handlers: Default::default(),
1096            buffer: Mutex::new(VecDeque::new()),
1097            name,
1098            task: Mutex::new(Self::start_handling_messages(
1099                this.clone(),
1100                incoming_rx,
1101                &cx.to_async(),
1102            )),
1103        })
1104    }
1105
1106    fn start_handling_messages(
1107        this: Weak<Self>,
1108        mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1109        cx: &AsyncApp,
1110    ) -> Task<Result<()>> {
1111        cx.spawn(async move |cx| {
1112            let peer_id = PeerId { owner_id: 0, id: 0 };
1113            while let Some(incoming) = incoming_rx.next().await {
1114                let Some(this) = this.upgrade() else {
1115                    return anyhow::Ok(());
1116                };
1117                if let Some(ack_id) = incoming.ack_id {
1118                    let mut buffer = this.buffer.lock();
1119                    while buffer.front().is_some_and(|msg| msg.id <= ack_id) {
1120                        buffer.pop_front();
1121                    }
1122                }
1123                if let Some(proto::envelope::Payload::FlushBufferedMessages(_)) = &incoming.payload
1124                {
1125                    log::debug!(
1126                        "{}:ssh message received. name:FlushBufferedMessages",
1127                        this.name
1128                    );
1129                    {
1130                        let buffer = this.buffer.lock();
1131                        for envelope in buffer.iter() {
1132                            this.outgoing_tx
1133                                .lock()
1134                                .unbounded_send(envelope.clone())
1135                                .ok();
1136                        }
1137                    }
1138                    let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
1139                    envelope.id = this.next_message_id.fetch_add(1, SeqCst);
1140                    this.outgoing_tx.lock().unbounded_send(envelope).ok();
1141                    continue;
1142                }
1143
1144                this.max_received.store(incoming.id, SeqCst);
1145
1146                if let Some(request_id) = incoming.responding_to {
1147                    let request_id = MessageId(request_id);
1148                    let sender = this.response_channels.lock().remove(&request_id);
1149                    if let Some(sender) = sender {
1150                        let (tx, rx) = oneshot::channel();
1151                        if incoming.payload.is_some() {
1152                            sender.send((incoming, tx)).ok();
1153                        }
1154                        rx.await.ok();
1155                    }
1156                } else if let Some(envelope) =
1157                    build_typed_envelope(peer_id, Instant::now(), incoming)
1158                {
1159                    let type_name = envelope.payload_type_name();
1160                    let message_id = envelope.message_id();
1161                    if let Some(future) = ProtoMessageHandlerSet::handle_message(
1162                        &this.message_handlers,
1163                        envelope,
1164                        this.clone().into(),
1165                        cx.clone(),
1166                    ) {
1167                        log::debug!("{}:ssh message received. name:{type_name}", this.name);
1168                        cx.foreground_executor()
1169                            .spawn(async move {
1170                                match future.await {
1171                                    Ok(_) => {
1172                                        log::debug!(
1173                                            "{}:ssh message handled. name:{type_name}",
1174                                            this.name
1175                                        );
1176                                    }
1177                                    Err(error) => {
1178                                        log::error!(
1179                                            "{}:error handling message. type:{}, error:{:#}",
1180                                            this.name,
1181                                            type_name,
1182                                            format!("{error:#}").lines().fold(
1183                                                String::new(),
1184                                                |mut message, line| {
1185                                                    if !message.is_empty() {
1186                                                        message.push(' ');
1187                                                    }
1188                                                    message.push_str(line);
1189                                                    message
1190                                                }
1191                                            )
1192                                        );
1193                                    }
1194                                }
1195                            })
1196                            .detach()
1197                    } else {
1198                        log::error!("{}:unhandled ssh message name:{type_name}", this.name);
1199                        if let Err(e) = AnyProtoClient::from(this.clone()).send_response(
1200                            message_id,
1201                            anyhow::anyhow!("no handler registered for {type_name}").to_proto(),
1202                        ) {
1203                            log::error!(
1204                                "{}:error sending error response for {type_name}:{e:#}",
1205                                this.name
1206                            );
1207                        }
1208                    }
1209                }
1210            }
1211            anyhow::Ok(())
1212        })
1213    }
1214
1215    fn reconnect(
1216        self: &Arc<Self>,
1217        incoming_rx: UnboundedReceiver<Envelope>,
1218        outgoing_tx: UnboundedSender<Envelope>,
1219        cx: &AsyncApp,
1220    ) {
1221        *self.outgoing_tx.lock() = outgoing_tx;
1222        *self.task.lock() = Self::start_handling_messages(Arc::downgrade(self), incoming_rx, cx);
1223    }
1224
1225    fn request<T: RequestMessage>(
1226        &self,
1227        payload: T,
1228    ) -> impl 'static + Future<Output = Result<T::Response>> {
1229        self.request_internal(payload, true)
1230    }
1231
1232    fn request_internal<T: RequestMessage>(
1233        &self,
1234        payload: T,
1235        use_buffer: bool,
1236    ) -> impl 'static + Future<Output = Result<T::Response>> {
1237        log::debug!("ssh request start. name:{}", T::NAME);
1238        let response =
1239            self.request_dynamic(payload.into_envelope(0, None, None), T::NAME, use_buffer);
1240        async move {
1241            let response = response.await?;
1242            log::debug!("ssh request finish. name:{}", T::NAME);
1243            T::Response::from_envelope(response).context("received a response of the wrong type")
1244        }
1245    }
1246
1247    async fn resync(&self, timeout: Duration) -> Result<()> {
1248        smol::future::or(
1249            async {
1250                self.request_internal(proto::FlushBufferedMessages {}, false)
1251                    .await?;
1252
1253                for envelope in self.buffer.lock().iter() {
1254                    self.outgoing_tx
1255                        .lock()
1256                        .unbounded_send(envelope.clone())
1257                        .ok();
1258                }
1259                Ok(())
1260            },
1261            async {
1262                smol::Timer::after(timeout).await;
1263                anyhow::bail!("Timed out resyncing remote client")
1264            },
1265        )
1266        .await
1267    }
1268
1269    async fn ping(&self, timeout: Duration) -> Result<()> {
1270        smol::future::or(
1271            async {
1272                self.request(proto::Ping {}).await?;
1273                Ok(())
1274            },
1275            async {
1276                smol::Timer::after(timeout).await;
1277                anyhow::bail!("Timed out pinging remote client")
1278            },
1279        )
1280        .await
1281    }
1282
1283    fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
1284        log::debug!("ssh send name:{}", T::NAME);
1285        self.send_dynamic(payload.into_envelope(0, None, None))
1286    }
1287
1288    fn request_dynamic(
1289        &self,
1290        mut envelope: proto::Envelope,
1291        type_name: &'static str,
1292        use_buffer: bool,
1293    ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
1294        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1295        let (tx, rx) = oneshot::channel();
1296        let mut response_channels_lock = self.response_channels.lock();
1297        response_channels_lock.insert(MessageId(envelope.id), tx);
1298        drop(response_channels_lock);
1299
1300        let result = if use_buffer {
1301            self.send_buffered(envelope)
1302        } else {
1303            self.send_unbuffered(envelope)
1304        };
1305        async move {
1306            if let Err(error) = &result {
1307                log::error!("failed to send message: {error}");
1308                anyhow::bail!("failed to send message: {error}");
1309            }
1310
1311            let response = rx.await.context("connection lost")?.0;
1312            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
1313                return Err(RpcError::from_proto(error, type_name));
1314            }
1315            Ok(response)
1316        }
1317    }
1318
1319    pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
1320        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1321        self.send_buffered(envelope)
1322    }
1323
1324    fn send_buffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1325        envelope.ack_id = Some(self.max_received.load(SeqCst));
1326        self.buffer.lock().push_back(envelope.clone());
1327        // ignore errors on send (happen while we're reconnecting)
1328        // assume that the global "disconnected" overlay is sufficient.
1329        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1330        Ok(())
1331    }
1332
1333    fn send_unbuffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1334        envelope.ack_id = Some(self.max_received.load(SeqCst));
1335        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1336        Ok(())
1337    }
1338}
1339
1340impl ProtoClient for ChannelClient {
1341    fn request(
1342        &self,
1343        envelope: proto::Envelope,
1344        request_type: &'static str,
1345    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1346        self.request_dynamic(envelope, request_type, true).boxed()
1347    }
1348
1349    fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
1350        self.send_dynamic(envelope)
1351    }
1352
1353    fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
1354        self.send_dynamic(envelope)
1355    }
1356
1357    fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
1358        &self.message_handlers
1359    }
1360
1361    fn is_via_collab(&self) -> bool {
1362        false
1363    }
1364}
1365
1366#[cfg(any(test, feature = "test-support"))]
1367mod fake {
1368    use super::{ChannelClient, RemoteClientDelegate, RemoteConnection, RemotePlatform};
1369    use crate::remote_client::{CommandTemplate, RemoteConnectionOptions};
1370    use anyhow::Result;
1371    use async_trait::async_trait;
1372    use collections::HashMap;
1373    use futures::{
1374        FutureExt, SinkExt, StreamExt,
1375        channel::{
1376            mpsc::{self, Sender},
1377            oneshot,
1378        },
1379        select_biased,
1380    };
1381    use gpui::{App, AppContext as _, AsyncApp, SemanticVersion, Task, TestAppContext};
1382    use release_channel::ReleaseChannel;
1383    use rpc::proto::Envelope;
1384    use std::{path::PathBuf, sync::Arc};
1385    use util::paths::{PathStyle, RemotePathBuf};
1386
1387    pub(super) struct FakeRemoteConnection {
1388        pub(super) connection_options: RemoteConnectionOptions,
1389        pub(super) server_channel: Arc<ChannelClient>,
1390        pub(super) server_cx: SendableCx,
1391    }
1392
1393    pub(super) struct SendableCx(AsyncApp);
1394    impl SendableCx {
1395        // SAFETY: When run in test mode, GPUI is always single threaded.
1396        pub(super) fn new(cx: &TestAppContext) -> Self {
1397            Self(cx.to_async())
1398        }
1399
1400        // SAFETY: Enforce that we're on the main thread by requiring a valid AsyncApp
1401        fn get(&self, _: &AsyncApp) -> AsyncApp {
1402            self.0.clone()
1403        }
1404    }
1405
1406    // SAFETY: There is no way to access a SendableCx from a different thread, see [`SendableCx::new`] and [`SendableCx::get`]
1407    unsafe impl Send for SendableCx {}
1408    unsafe impl Sync for SendableCx {}
1409
1410    #[async_trait(?Send)]
1411    impl RemoteConnection for FakeRemoteConnection {
1412        async fn kill(&self) -> Result<()> {
1413            Ok(())
1414        }
1415
1416        fn has_been_killed(&self) -> bool {
1417            false
1418        }
1419
1420        fn build_command(
1421            &self,
1422            program: Option<String>,
1423            args: &[String],
1424            env: &HashMap<String, String>,
1425            _: Option<String>,
1426            _: Option<(u16, String, u16)>,
1427        ) -> Result<CommandTemplate> {
1428            let ssh_program = program.unwrap_or_else(|| "sh".to_string());
1429            let mut ssh_args = Vec::new();
1430            ssh_args.push(ssh_program);
1431            ssh_args.extend(args.iter().cloned());
1432            Ok(CommandTemplate {
1433                program: "ssh".into(),
1434                args: ssh_args,
1435                env: env.clone(),
1436            })
1437        }
1438
1439        fn upload_directory(
1440            &self,
1441            _src_path: PathBuf,
1442            _dest_path: RemotePathBuf,
1443            _cx: &App,
1444        ) -> Task<Result<()>> {
1445            unreachable!()
1446        }
1447
1448        fn connection_options(&self) -> RemoteConnectionOptions {
1449            self.connection_options.clone()
1450        }
1451
1452        fn simulate_disconnect(&self, cx: &AsyncApp) {
1453            let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
1454            let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
1455            self.server_channel
1456                .reconnect(incoming_rx, outgoing_tx, &self.server_cx.get(cx));
1457        }
1458
1459        fn start_proxy(
1460            &self,
1461            _unique_identifier: String,
1462            _reconnect: bool,
1463            mut client_incoming_tx: mpsc::UnboundedSender<Envelope>,
1464            mut client_outgoing_rx: mpsc::UnboundedReceiver<Envelope>,
1465            mut connection_activity_tx: Sender<()>,
1466            _delegate: Arc<dyn RemoteClientDelegate>,
1467            cx: &mut AsyncApp,
1468        ) -> Task<Result<i32>> {
1469            let (mut server_incoming_tx, server_incoming_rx) = mpsc::unbounded::<Envelope>();
1470            let (server_outgoing_tx, mut server_outgoing_rx) = mpsc::unbounded::<Envelope>();
1471
1472            self.server_channel.reconnect(
1473                server_incoming_rx,
1474                server_outgoing_tx,
1475                &self.server_cx.get(cx),
1476            );
1477
1478            cx.background_spawn(async move {
1479                loop {
1480                    select_biased! {
1481                        server_to_client = server_outgoing_rx.next().fuse() => {
1482                            let Some(server_to_client) = server_to_client else {
1483                                return Ok(1)
1484                            };
1485                            connection_activity_tx.try_send(()).ok();
1486                            client_incoming_tx.send(server_to_client).await.ok();
1487                        }
1488                        client_to_server = client_outgoing_rx.next().fuse() => {
1489                            let Some(client_to_server) = client_to_server else {
1490                                return Ok(1)
1491                            };
1492                            server_incoming_tx.send(client_to_server).await.ok();
1493                        }
1494                    }
1495                }
1496            })
1497        }
1498
1499        fn path_style(&self) -> PathStyle {
1500            PathStyle::current()
1501        }
1502
1503        fn shell(&self) -> String {
1504            "sh".to_owned()
1505        }
1506    }
1507
1508    pub(super) struct Delegate;
1509
1510    impl RemoteClientDelegate for Delegate {
1511        fn ask_password(&self, _: String, _: oneshot::Sender<String>, _: &mut AsyncApp) {
1512            unreachable!()
1513        }
1514
1515        fn download_server_binary_locally(
1516            &self,
1517            _: RemotePlatform,
1518            _: ReleaseChannel,
1519            _: Option<SemanticVersion>,
1520            _: &mut AsyncApp,
1521        ) -> Task<Result<PathBuf>> {
1522            unreachable!()
1523        }
1524
1525        fn get_download_params(
1526            &self,
1527            _platform: RemotePlatform,
1528            _release_channel: ReleaseChannel,
1529            _version: Option<SemanticVersion>,
1530            _cx: &mut AsyncApp,
1531        ) -> Task<Result<Option<(String, String)>>> {
1532            unreachable!()
1533        }
1534
1535        fn set_status(&self, _: Option<&str>, _: &mut AsyncApp) {}
1536    }
1537}