remote_connections.rs

  1use std::collections::BTreeSet;
  2use std::{path::PathBuf, sync::Arc};
  3
  4use anyhow::{Context as _, Result};
  5use auto_update::AutoUpdater;
  6use editor::Editor;
  7use extension_host::ExtensionStore;
  8use futures::channel::oneshot;
  9use gpui::{
 10    AnyWindowHandle, App, AsyncApp, DismissEvent, Entity, EventEmitter, Focusable, FontFeatures,
 11    ParentElement as _, PromptLevel, Render, SemanticVersion, SharedString, Task,
 12    TextStyleRefinement, WeakEntity,
 13};
 14
 15use language::CursorShape;
 16use markdown::{Markdown, MarkdownElement, MarkdownStyle};
 17use release_channel::ReleaseChannel;
 18use remote::{
 19    ConnectionIdentifier, RemoteClient, RemoteConnectionOptions, RemotePlatform,
 20    SshConnectionOptions, SshPortForwardOption,
 21};
 22use schemars::JsonSchema;
 23use serde::{Deserialize, Serialize};
 24use settings::{Settings, SettingsSources, SettingsUi};
 25use theme::ThemeSettings;
 26use ui::{
 27    ActiveTheme, Color, CommonAnimationExt, Context, Icon, IconName, IconSize, InteractiveElement,
 28    IntoElement, Label, LabelCommon, Styled, Window, prelude::*,
 29};
 30use util::serde::default_true;
 31use workspace::{AppState, ModalView, Workspace};
 32
 33#[derive(Deserialize)]
 34pub struct SshSettings {
 35    pub ssh_connections: Option<Vec<SshConnection>>,
 36    /// Whether to read ~/.ssh/config for ssh connection sources.
 37    #[serde(default = "default_true")]
 38    pub read_ssh_config: bool,
 39}
 40
 41impl SshSettings {
 42    pub fn ssh_connections(&self) -> impl Iterator<Item = SshConnection> + use<> {
 43        self.ssh_connections.clone().into_iter().flatten()
 44    }
 45
 46    pub fn fill_connection_options_from_settings(&self, options: &mut SshConnectionOptions) {
 47        for conn in self.ssh_connections() {
 48            if conn.host == options.host
 49                && conn.username == options.username
 50                && conn.port == options.port
 51            {
 52                options.nickname = conn.nickname;
 53                options.upload_binary_over_ssh = conn.upload_binary_over_ssh.unwrap_or_default();
 54                options.args = Some(conn.args);
 55                options.port_forwards = conn.port_forwards;
 56                break;
 57            }
 58        }
 59    }
 60
 61    pub fn connection_options_for(
 62        &self,
 63        host: String,
 64        port: Option<u16>,
 65        username: Option<String>,
 66    ) -> SshConnectionOptions {
 67        let mut options = SshConnectionOptions {
 68            host,
 69            port,
 70            username,
 71            ..Default::default()
 72        };
 73        self.fill_connection_options_from_settings(&mut options);
 74        options
 75    }
 76}
 77
 78#[derive(Clone, Default, Serialize, Deserialize, PartialEq, JsonSchema)]
 79pub struct SshConnection {
 80    pub host: SharedString,
 81    #[serde(skip_serializing_if = "Option::is_none")]
 82    pub username: Option<String>,
 83    #[serde(skip_serializing_if = "Option::is_none")]
 84    pub port: Option<u16>,
 85    #[serde(skip_serializing_if = "Vec::is_empty")]
 86    #[serde(default)]
 87    pub args: Vec<String>,
 88    #[serde(default)]
 89    pub projects: BTreeSet<SshProject>,
 90    /// Name to use for this server in UI.
 91    #[serde(skip_serializing_if = "Option::is_none")]
 92    pub nickname: Option<String>,
 93    // By default Zed will download the binary to the host directly.
 94    // If this is set to true, Zed will download the binary to your local machine,
 95    // and then upload it over the SSH connection. Useful if your SSH server has
 96    // limited outbound internet access.
 97    #[serde(skip_serializing_if = "Option::is_none")]
 98    pub upload_binary_over_ssh: Option<bool>,
 99
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub port_forwards: Option<Vec<SshPortForwardOption>>,
102}
103
104impl From<SshConnection> for SshConnectionOptions {
105    fn from(val: SshConnection) -> Self {
106        SshConnectionOptions {
107            host: val.host.into(),
108            username: val.username,
109            port: val.port,
110            password: None,
111            args: Some(val.args),
112            nickname: val.nickname,
113            upload_binary_over_ssh: val.upload_binary_over_ssh.unwrap_or_default(),
114            port_forwards: val.port_forwards,
115        }
116    }
117}
118
119#[derive(Clone, Default, Serialize, PartialEq, Eq, PartialOrd, Ord, Deserialize, JsonSchema)]
120pub struct SshProject {
121    pub paths: Vec<String>,
122}
123
124#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, SettingsUi)]
125pub struct RemoteSettingsContent {
126    pub ssh_connections: Option<Vec<SshConnection>>,
127    pub read_ssh_config: Option<bool>,
128}
129
130impl Settings for SshSettings {
131    const KEY: Option<&'static str> = None;
132
133    type FileContent = RemoteSettingsContent;
134
135    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
136        sources.json_merge()
137    }
138
139    fn import_from_vscode(_vscode: &settings::VsCodeSettings, _current: &mut Self::FileContent) {}
140}
141
142pub struct RemoteConnectionPrompt {
143    connection_string: SharedString,
144    nickname: Option<SharedString>,
145    status_message: Option<SharedString>,
146    prompt: Option<(Entity<Markdown>, oneshot::Sender<String>)>,
147    cancellation: Option<oneshot::Sender<()>>,
148    editor: Entity<Editor>,
149}
150
151impl Drop for RemoteConnectionPrompt {
152    fn drop(&mut self) {
153        if let Some(cancel) = self.cancellation.take() {
154            cancel.send(()).ok();
155        }
156    }
157}
158
159pub struct RemoteConnectionModal {
160    pub(crate) prompt: Entity<RemoteConnectionPrompt>,
161    paths: Vec<PathBuf>,
162    finished: bool,
163}
164
165impl RemoteConnectionPrompt {
166    pub(crate) fn new(
167        connection_string: String,
168        nickname: Option<String>,
169        window: &mut Window,
170        cx: &mut Context<Self>,
171    ) -> Self {
172        Self {
173            connection_string: connection_string.into(),
174            nickname: nickname.map(|nickname| nickname.into()),
175            editor: cx.new(|cx| Editor::single_line(window, cx)),
176            status_message: None,
177            cancellation: None,
178            prompt: None,
179        }
180    }
181
182    pub fn set_cancellation_tx(&mut self, tx: oneshot::Sender<()>) {
183        self.cancellation = Some(tx);
184    }
185
186    pub fn set_prompt(
187        &mut self,
188        prompt: String,
189        tx: oneshot::Sender<String>,
190        window: &mut Window,
191        cx: &mut Context<Self>,
192    ) {
193        let theme = ThemeSettings::get_global(cx);
194
195        let refinement = TextStyleRefinement {
196            font_family: Some(theme.buffer_font.family.clone()),
197            font_features: Some(FontFeatures::disable_ligatures()),
198            font_size: Some(theme.buffer_font_size(cx).into()),
199            color: Some(cx.theme().colors().editor_foreground),
200            background_color: Some(gpui::transparent_black()),
201            ..Default::default()
202        };
203
204        self.editor.update(cx, |editor, cx| {
205            if prompt.contains("yes/no") {
206                editor.set_masked(false, cx);
207            } else {
208                editor.set_masked(true, cx);
209            }
210            editor.set_text_style_refinement(refinement);
211            editor.set_cursor_shape(CursorShape::Block, cx);
212        });
213
214        let markdown = cx.new(|cx| Markdown::new_text(prompt.into(), cx));
215        self.prompt = Some((markdown, tx));
216        self.status_message.take();
217        window.focus(&self.editor.focus_handle(cx));
218        cx.notify();
219    }
220
221    pub fn set_status(&mut self, status: Option<String>, cx: &mut Context<Self>) {
222        self.status_message = status.map(|s| s.into());
223        cx.notify();
224    }
225
226    pub fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
227        if let Some((_, tx)) = self.prompt.take() {
228            self.status_message = Some("Connecting".into());
229            self.editor.update(cx, |editor, cx| {
230                tx.send(editor.text(cx)).ok();
231                editor.clear(window, cx);
232            });
233        }
234    }
235}
236
237impl Render for RemoteConnectionPrompt {
238    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
239        let theme = ThemeSettings::get_global(cx);
240
241        let mut text_style = window.text_style();
242        let refinement = TextStyleRefinement {
243            font_family: Some(theme.buffer_font.family.clone()),
244            font_features: Some(FontFeatures::disable_ligatures()),
245            font_size: Some(theme.buffer_font_size(cx).into()),
246            color: Some(cx.theme().colors().editor_foreground),
247            background_color: Some(gpui::transparent_black()),
248            ..Default::default()
249        };
250
251        text_style.refine(&refinement);
252        let markdown_style = MarkdownStyle {
253            base_text_style: text_style,
254            selection_background_color: cx.theme().colors().element_selection_background,
255            ..Default::default()
256        };
257
258        v_flex()
259            .key_context("PasswordPrompt")
260            .py_2()
261            .px_3()
262            .size_full()
263            .text_buffer(cx)
264            .when_some(self.status_message.clone(), |el, status_message| {
265                el.child(
266                    h_flex()
267                        .gap_1()
268                        .child(
269                            Icon::new(IconName::ArrowCircle)
270                                .size(IconSize::Medium)
271                                .with_rotate_animation(2),
272                        )
273                        .child(
274                            div()
275                                .text_ellipsis()
276                                .overflow_x_hidden()
277                                .child(format!("{}", status_message)),
278                        ),
279                )
280            })
281            .when_some(self.prompt.as_ref(), |el, prompt| {
282                el.child(
283                    div()
284                        .size_full()
285                        .overflow_hidden()
286                        .child(MarkdownElement::new(prompt.0.clone(), markdown_style))
287                        .child(self.editor.clone()),
288                )
289                .when(window.capslock().on, |el| {
290                    el.child(Label::new("⚠️ ⇪ is on"))
291                })
292            })
293    }
294}
295
296impl RemoteConnectionModal {
297    pub(crate) fn new(
298        connection_options: &RemoteConnectionOptions,
299        paths: Vec<PathBuf>,
300        window: &mut Window,
301        cx: &mut Context<Self>,
302    ) -> Self {
303        let (connection_string, nickname) = match connection_options {
304            RemoteConnectionOptions::Ssh(options) => {
305                (options.connection_string(), options.nickname.clone())
306            }
307            RemoteConnectionOptions::Wsl(options) => (options.distro_name.clone(), None),
308        };
309        Self {
310            prompt: cx
311                .new(|cx| RemoteConnectionPrompt::new(connection_string, nickname, window, cx)),
312            finished: false,
313            paths,
314        }
315    }
316
317    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
318        self.prompt
319            .update(cx, |prompt, cx| prompt.confirm(window, cx))
320    }
321
322    pub fn finished(&mut self, cx: &mut Context<Self>) {
323        self.finished = true;
324        cx.emit(DismissEvent);
325    }
326
327    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
328        if let Some(tx) = self
329            .prompt
330            .update(cx, |prompt, _cx| prompt.cancellation.take())
331        {
332            tx.send(()).ok();
333        }
334        self.finished(cx);
335    }
336}
337
338pub(crate) struct SshConnectionHeader {
339    pub(crate) connection_string: SharedString,
340    pub(crate) paths: Vec<PathBuf>,
341    pub(crate) nickname: Option<SharedString>,
342}
343
344impl RenderOnce for SshConnectionHeader {
345    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
346        let theme = cx.theme();
347
348        let mut header_color = theme.colors().text;
349        header_color.fade_out(0.96);
350
351        let (main_label, meta_label) = if let Some(nickname) = self.nickname {
352            (nickname, Some(format!("({})", self.connection_string)))
353        } else {
354            (self.connection_string, None)
355        };
356
357        h_flex()
358            .px(DynamicSpacing::Base12.rems(cx))
359            .pt(DynamicSpacing::Base08.rems(cx))
360            .pb(DynamicSpacing::Base04.rems(cx))
361            .rounded_t_sm()
362            .w_full()
363            .gap_1p5()
364            .child(Icon::new(IconName::Server).size(IconSize::Small))
365            .child(
366                h_flex()
367                    .gap_1()
368                    .overflow_x_hidden()
369                    .child(
370                        div()
371                            .max_w_96()
372                            .overflow_x_hidden()
373                            .text_ellipsis()
374                            .child(Headline::new(main_label).size(HeadlineSize::XSmall)),
375                    )
376                    .children(
377                        meta_label.map(|label| {
378                            Label::new(label).color(Color::Muted).size(LabelSize::Small)
379                        }),
380                    )
381                    .child(div().overflow_x_hidden().text_ellipsis().children(
382                        self.paths.into_iter().map(|path| {
383                            Label::new(path.to_string_lossy().to_string())
384                                .size(LabelSize::Small)
385                                .color(Color::Muted)
386                        }),
387                    )),
388            )
389    }
390}
391
392impl Render for RemoteConnectionModal {
393    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
394        let nickname = self.prompt.read(cx).nickname.clone();
395        let connection_string = self.prompt.read(cx).connection_string.clone();
396
397        let theme = cx.theme().clone();
398        let body_color = theme.colors().editor_background;
399
400        v_flex()
401            .elevation_3(cx)
402            .w(rems(34.))
403            .border_1()
404            .border_color(theme.colors().border)
405            .key_context("SshConnectionModal")
406            .track_focus(&self.focus_handle(cx))
407            .on_action(cx.listener(Self::dismiss))
408            .on_action(cx.listener(Self::confirm))
409            .child(
410                SshConnectionHeader {
411                    paths: self.paths.clone(),
412                    connection_string,
413                    nickname,
414                }
415                .render(window, cx),
416            )
417            .child(
418                div()
419                    .w_full()
420                    .rounded_b_lg()
421                    .bg(body_color)
422                    .border_t_1()
423                    .border_color(theme.colors().border_variant)
424                    .child(self.prompt.clone()),
425            )
426    }
427}
428
429impl Focusable for RemoteConnectionModal {
430    fn focus_handle(&self, cx: &gpui::App) -> gpui::FocusHandle {
431        self.prompt.read(cx).editor.focus_handle(cx)
432    }
433}
434
435impl EventEmitter<DismissEvent> for RemoteConnectionModal {}
436
437impl ModalView for RemoteConnectionModal {
438    fn on_before_dismiss(
439        &mut self,
440        _window: &mut Window,
441        _: &mut Context<Self>,
442    ) -> workspace::DismissDecision {
443        workspace::DismissDecision::Dismiss(self.finished)
444    }
445
446    fn fade_out_background(&self) -> bool {
447        true
448    }
449}
450
451#[derive(Clone)]
452pub struct RemoteClientDelegate {
453    window: AnyWindowHandle,
454    ui: WeakEntity<RemoteConnectionPrompt>,
455    known_password: Option<String>,
456}
457
458impl remote::RemoteClientDelegate for RemoteClientDelegate {
459    fn ask_password(&self, prompt: String, tx: oneshot::Sender<String>, cx: &mut AsyncApp) {
460        let mut known_password = self.known_password.clone();
461        if let Some(password) = known_password.take() {
462            tx.send(password).ok();
463        } else {
464            self.window
465                .update(cx, |_, window, cx| {
466                    self.ui.update(cx, |modal, cx| {
467                        modal.set_prompt(prompt, tx, window, cx);
468                    })
469                })
470                .ok();
471        }
472    }
473
474    fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
475        self.update_status(status, cx)
476    }
477
478    fn download_server_binary_locally(
479        &self,
480        platform: RemotePlatform,
481        release_channel: ReleaseChannel,
482        version: Option<SemanticVersion>,
483        cx: &mut AsyncApp,
484    ) -> Task<anyhow::Result<PathBuf>> {
485        cx.spawn(async move |cx| {
486            let binary_path = AutoUpdater::download_remote_server_release(
487                platform.os,
488                platform.arch,
489                release_channel,
490                version,
491                cx,
492            )
493            .await
494            .with_context(|| {
495                format!(
496                    "Downloading remote server binary (version: {}, os: {}, arch: {})",
497                    version
498                        .map(|v| format!("{}", v))
499                        .unwrap_or("unknown".to_string()),
500                    platform.os,
501                    platform.arch,
502                )
503            })?;
504            Ok(binary_path)
505        })
506    }
507
508    fn get_download_params(
509        &self,
510        platform: RemotePlatform,
511        release_channel: ReleaseChannel,
512        version: Option<SemanticVersion>,
513        cx: &mut AsyncApp,
514    ) -> Task<Result<Option<(String, String)>>> {
515        cx.spawn(async move |cx| {
516            AutoUpdater::get_remote_server_release_url(
517                platform.os,
518                platform.arch,
519                release_channel,
520                version,
521                cx,
522            )
523            .await
524        })
525    }
526}
527
528impl RemoteClientDelegate {
529    fn update_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
530        self.window
531            .update(cx, |_, _, cx| {
532                self.ui.update(cx, |modal, cx| {
533                    modal.set_status(status.map(|s| s.to_string()), cx);
534                })
535            })
536            .ok();
537    }
538}
539
540pub fn connect_over_ssh(
541    unique_identifier: ConnectionIdentifier,
542    connection_options: SshConnectionOptions,
543    ui: Entity<RemoteConnectionPrompt>,
544    window: &mut Window,
545    cx: &mut App,
546) -> Task<Result<Option<Entity<RemoteClient>>>> {
547    let window = window.window_handle();
548    let known_password = connection_options.password.clone();
549    let (tx, rx) = oneshot::channel();
550    ui.update(cx, |ui, _cx| ui.set_cancellation_tx(tx));
551
552    remote::RemoteClient::ssh(
553        unique_identifier,
554        connection_options,
555        rx,
556        Arc::new(RemoteClientDelegate {
557            window,
558            ui: ui.downgrade(),
559            known_password,
560        }),
561        cx,
562    )
563}
564
565pub async fn open_remote_project(
566    connection_options: RemoteConnectionOptions,
567    paths: Vec<PathBuf>,
568    app_state: Arc<AppState>,
569    open_options: workspace::OpenOptions,
570    cx: &mut AsyncApp,
571) -> Result<()> {
572    let window = if let Some(window) = open_options.replace_window {
573        window
574    } else {
575        let workspace_position = cx
576            .update(|cx| {
577                workspace::remote_workspace_position_from_db(connection_options.clone(), &paths, cx)
578            })?
579            .await
580            .context("fetching ssh workspace position from db")?;
581
582        let mut options =
583            cx.update(|cx| (app_state.build_window_options)(workspace_position.display, cx))?;
584        options.window_bounds = workspace_position.window_bounds;
585
586        cx.open_window(options, |window, cx| {
587            let project = project::Project::local(
588                app_state.client.clone(),
589                app_state.node_runtime.clone(),
590                app_state.user_store.clone(),
591                app_state.languages.clone(),
592                app_state.fs.clone(),
593                None,
594                cx,
595            );
596            cx.new(|cx| {
597                let mut workspace = Workspace::new(None, project, app_state.clone(), window, cx);
598                workspace.centered_layout = workspace_position.centered_layout;
599                workspace
600            })
601        })?
602    };
603
604    loop {
605        let (cancel_tx, cancel_rx) = oneshot::channel();
606        let delegate = window.update(cx, {
607            let paths = paths.clone();
608            let connection_options = connection_options.clone();
609            move |workspace, window, cx| {
610                window.activate_window();
611                workspace.toggle_modal(window, cx, |window, cx| {
612                    RemoteConnectionModal::new(&connection_options, paths, window, cx)
613                });
614
615                let ui = workspace
616                    .active_modal::<RemoteConnectionModal>(cx)?
617                    .read(cx)
618                    .prompt
619                    .clone();
620
621                ui.update(cx, |ui, _cx| {
622                    ui.set_cancellation_tx(cancel_tx);
623                });
624
625                Some(Arc::new(RemoteClientDelegate {
626                    window: window.window_handle(),
627                    ui: ui.downgrade(),
628                    known_password: if let RemoteConnectionOptions::Ssh(options) =
629                        &connection_options
630                    {
631                        options.password.clone()
632                    } else {
633                        None
634                    },
635                }))
636            }
637        })?;
638
639        let Some(delegate) = delegate else { break };
640
641        let did_open_project = cx
642            .update(|cx| {
643                workspace::open_remote_project_with_new_connection(
644                    window,
645                    connection_options.clone(),
646                    cancel_rx,
647                    delegate.clone(),
648                    app_state.clone(),
649                    paths.clone(),
650                    cx,
651                )
652            })?
653            .await;
654
655        window
656            .update(cx, |workspace, _, cx| {
657                if let Some(ui) = workspace.active_modal::<RemoteConnectionModal>(cx) {
658                    ui.update(cx, |modal, cx| modal.finished(cx))
659                }
660            })
661            .ok();
662
663        if let Err(e) = did_open_project {
664            log::error!("Failed to open project: {e:?}");
665            let response = window
666                .update(cx, |_, window, cx| {
667                    window.prompt(
668                        PromptLevel::Critical,
669                        match connection_options {
670                            RemoteConnectionOptions::Ssh(_) => "Failed to connect over SSH",
671                            RemoteConnectionOptions::Wsl(_) => "Failed to connect to WSL",
672                        },
673                        Some(&e.to_string()),
674                        &["Retry", "Ok"],
675                        cx,
676                    )
677                })?
678                .await;
679
680            if response == Ok(0) {
681                continue;
682            }
683        }
684
685        window
686            .update(cx, |workspace, _, cx| {
687                if let Some(client) = workspace.project().read(cx).remote_client() {
688                    ExtensionStore::global(cx)
689                        .update(cx, |store, cx| store.register_remote_client(client, cx));
690                }
691            })
692            .ok();
693
694        break;
695    }
696
697    // Already showed the error to the user
698    Ok(())
699}