remote_connections.rs

  1use std::{
  2    path::{Path, PathBuf},
  3    sync::Arc,
  4};
  5
  6use anyhow::{Context as _, Result};
  7use askpass::EncryptedPassword;
  8use auto_update::AutoUpdater;
  9use editor::Editor;
 10use extension_host::ExtensionStore;
 11use futures::channel::oneshot;
 12use gpui::{
 13    AnyWindowHandle, App, AsyncApp, DismissEvent, Entity, EventEmitter, Focusable, FontFeatures,
 14    ParentElement as _, PromptLevel, Render, SharedString, Task, TextStyleRefinement, WeakEntity,
 15};
 16
 17use language::{CursorShape, Point};
 18use markdown::{Markdown, MarkdownElement, MarkdownStyle};
 19use project::trusted_worktrees;
 20use release_channel::ReleaseChannel;
 21use remote::{
 22    ConnectionIdentifier, DockerConnectionOptions, RemoteClient, RemoteConnection,
 23    RemoteConnectionOptions, RemotePlatform, SshConnectionOptions,
 24};
 25use semver::Version;
 26pub use settings::SshConnection;
 27use settings::{DevContainerConnection, ExtendingVec, RegisterSetting, Settings, WslConnection};
 28use theme::ThemeSettings;
 29use ui::{
 30    ActiveTheme, Color, CommonAnimationExt, Context, InteractiveElement, IntoElement, KeyBinding,
 31    LabelCommon, ListItem, Styled, Window, prelude::*,
 32};
 33use util::paths::PathWithPosition;
 34use workspace::{AppState, ModalView, Workspace};
 35
 36#[derive(RegisterSetting)]
 37pub struct SshSettings {
 38    pub ssh_connections: ExtendingVec<SshConnection>,
 39    pub wsl_connections: ExtendingVec<WslConnection>,
 40    /// Whether to read ~/.ssh/config for ssh connection sources.
 41    pub read_ssh_config: bool,
 42}
 43
 44impl SshSettings {
 45    pub fn ssh_connections(&self) -> impl Iterator<Item = SshConnection> + use<> {
 46        self.ssh_connections.clone().0.into_iter()
 47    }
 48
 49    pub fn wsl_connections(&self) -> impl Iterator<Item = WslConnection> + use<> {
 50        self.wsl_connections.clone().0.into_iter()
 51    }
 52
 53    pub fn fill_connection_options_from_settings(&self, options: &mut SshConnectionOptions) {
 54        for conn in self.ssh_connections() {
 55            if conn.host == options.host.to_string()
 56                && conn.username == options.username
 57                && conn.port == options.port
 58            {
 59                options.nickname = conn.nickname;
 60                options.upload_binary_over_ssh = conn.upload_binary_over_ssh.unwrap_or_default();
 61                options.args = Some(conn.args);
 62                options.port_forwards = conn.port_forwards;
 63                break;
 64            }
 65        }
 66    }
 67
 68    pub fn connection_options_for(
 69        &self,
 70        host: String,
 71        port: Option<u16>,
 72        username: Option<String>,
 73    ) -> SshConnectionOptions {
 74        let mut options = SshConnectionOptions {
 75            host: host.into(),
 76            port,
 77            username,
 78            ..Default::default()
 79        };
 80        self.fill_connection_options_from_settings(&mut options);
 81        options
 82    }
 83}
 84
 85#[derive(Clone, PartialEq)]
 86pub enum Connection {
 87    Ssh(SshConnection),
 88    Wsl(WslConnection),
 89    DevContainer(DevContainerConnection),
 90}
 91
 92impl From<Connection> for RemoteConnectionOptions {
 93    fn from(val: Connection) -> Self {
 94        match val {
 95            Connection::Ssh(conn) => RemoteConnectionOptions::Ssh(conn.into()),
 96            Connection::Wsl(conn) => RemoteConnectionOptions::Wsl(conn.into()),
 97            Connection::DevContainer(conn) => {
 98                RemoteConnectionOptions::Docker(DockerConnectionOptions {
 99                    name: conn.name.to_string(),
100                    container_id: conn.container_id.to_string(),
101                    upload_binary_over_docker_exec: false,
102                })
103            }
104        }
105    }
106}
107
108impl From<SshConnection> for Connection {
109    fn from(val: SshConnection) -> Self {
110        Connection::Ssh(val)
111    }
112}
113
114impl From<WslConnection> for Connection {
115    fn from(val: WslConnection) -> Self {
116        Connection::Wsl(val)
117    }
118}
119
120impl Settings for SshSettings {
121    fn from_settings(content: &settings::SettingsContent) -> Self {
122        let remote = &content.remote;
123        Self {
124            ssh_connections: remote.ssh_connections.clone().unwrap_or_default().into(),
125            wsl_connections: remote.wsl_connections.clone().unwrap_or_default().into(),
126            read_ssh_config: remote.read_ssh_config.unwrap(),
127        }
128    }
129}
130
131pub struct RemoteConnectionPrompt {
132    connection_string: SharedString,
133    nickname: Option<SharedString>,
134    is_wsl: bool,
135    is_devcontainer: bool,
136    status_message: Option<SharedString>,
137    prompt: Option<(Entity<Markdown>, oneshot::Sender<EncryptedPassword>)>,
138    cancellation: Option<oneshot::Sender<()>>,
139    editor: Entity<Editor>,
140}
141
142impl Drop for RemoteConnectionPrompt {
143    fn drop(&mut self) {
144        if let Some(cancel) = self.cancellation.take() {
145            cancel.send(()).ok();
146        }
147    }
148}
149
150pub struct RemoteConnectionModal {
151    pub prompt: Entity<RemoteConnectionPrompt>,
152    paths: Vec<PathBuf>,
153    finished: bool,
154}
155
156impl RemoteConnectionPrompt {
157    pub(crate) fn new(
158        connection_string: String,
159        nickname: Option<String>,
160        is_wsl: bool,
161        is_devcontainer: bool,
162        window: &mut Window,
163        cx: &mut Context<Self>,
164    ) -> Self {
165        Self {
166            connection_string: connection_string.into(),
167            nickname: nickname.map(|nickname| nickname.into()),
168            is_wsl,
169            is_devcontainer,
170            editor: cx.new(|cx| Editor::single_line(window, cx)),
171            status_message: None,
172            cancellation: None,
173            prompt: None,
174        }
175    }
176
177    pub fn set_cancellation_tx(&mut self, tx: oneshot::Sender<()>) {
178        self.cancellation = Some(tx);
179    }
180
181    fn set_prompt(
182        &mut self,
183        prompt: String,
184        tx: oneshot::Sender<EncryptedPassword>,
185        window: &mut Window,
186        cx: &mut Context<Self>,
187    ) {
188        let theme = ThemeSettings::get_global(cx);
189
190        let refinement = TextStyleRefinement {
191            font_family: Some(theme.buffer_font.family.clone()),
192            font_features: Some(FontFeatures::disable_ligatures()),
193            font_size: Some(theme.buffer_font_size(cx).into()),
194            color: Some(cx.theme().colors().editor_foreground),
195            background_color: Some(gpui::transparent_black()),
196            ..Default::default()
197        };
198
199        self.editor.update(cx, |editor, cx| {
200            if prompt.contains("yes/no") {
201                editor.set_masked(false, cx);
202            } else {
203                editor.set_masked(true, cx);
204            }
205            editor.set_text_style_refinement(refinement);
206            editor.set_cursor_shape(CursorShape::Block, cx);
207        });
208
209        let markdown = cx.new(|cx| Markdown::new_text(prompt.into(), cx));
210        self.prompt = Some((markdown, tx));
211        self.status_message.take();
212        window.focus(&self.editor.focus_handle(cx), cx);
213        cx.notify();
214    }
215
216    pub fn set_status(&mut self, status: Option<String>, cx: &mut Context<Self>) {
217        self.status_message = status.map(|s| s.into());
218        cx.notify();
219    }
220
221    pub fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
222        if let Some((_, tx)) = self.prompt.take() {
223            self.status_message = Some("Connecting".into());
224
225            self.editor.update(cx, |editor, cx| {
226                let pw = editor.text(cx);
227                if let Ok(secure) = EncryptedPassword::try_from(pw.as_ref()) {
228                    tx.send(secure).ok();
229                }
230                editor.clear(window, cx);
231            });
232        }
233    }
234}
235
236impl Render for RemoteConnectionPrompt {
237    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
238        let theme = ThemeSettings::get_global(cx);
239
240        let mut text_style = window.text_style();
241        let refinement = TextStyleRefinement {
242            font_family: Some(theme.buffer_font.family.clone()),
243            font_features: Some(FontFeatures::disable_ligatures()),
244            font_size: Some(theme.buffer_font_size(cx).into()),
245            color: Some(cx.theme().colors().editor_foreground),
246            background_color: Some(gpui::transparent_black()),
247            ..Default::default()
248        };
249
250        text_style.refine(&refinement);
251        let markdown_style = MarkdownStyle {
252            base_text_style: text_style,
253            selection_background_color: cx.theme().colors().element_selection_background,
254            ..Default::default()
255        };
256
257        v_flex()
258            .key_context("PasswordPrompt")
259            .p_2()
260            .size_full()
261            .text_buffer(cx)
262            .when_some(self.status_message.clone(), |el, status_message| {
263                el.child(
264                    h_flex()
265                        .gap_2()
266                        .child(
267                            Icon::new(IconName::ArrowCircle)
268                                .color(Color::Muted)
269                                .with_rotate_animation(2),
270                        )
271                        .child(
272                            div()
273                                .text_ellipsis()
274                                .overflow_x_hidden()
275                                .child(format!("{}", status_message)),
276                        ),
277                )
278            })
279            .when_some(self.prompt.as_ref(), |el, prompt| {
280                el.child(
281                    div()
282                        .size_full()
283                        .overflow_hidden()
284                        .child(MarkdownElement::new(prompt.0.clone(), markdown_style))
285                        .child(self.editor.clone()),
286                )
287                .when(window.capslock().on, |el| {
288                    el.child(Label::new("⚠️ ⇪ is on"))
289                })
290            })
291    }
292}
293
294impl RemoteConnectionModal {
295    pub fn new(
296        connection_options: &RemoteConnectionOptions,
297        paths: Vec<PathBuf>,
298        window: &mut Window,
299        cx: &mut Context<Self>,
300    ) -> Self {
301        let (connection_string, nickname, is_wsl, is_devcontainer) = match connection_options {
302            RemoteConnectionOptions::Ssh(options) => (
303                options.connection_string(),
304                options.nickname.clone(),
305                false,
306                false,
307            ),
308            RemoteConnectionOptions::Wsl(options) => {
309                (options.distro_name.clone(), None, true, false)
310            }
311            RemoteConnectionOptions::Docker(options) => (options.name.clone(), None, false, true),
312        };
313        Self {
314            prompt: cx.new(|cx| {
315                RemoteConnectionPrompt::new(
316                    connection_string,
317                    nickname,
318                    is_wsl,
319                    is_devcontainer,
320                    window,
321                    cx,
322                )
323            }),
324            finished: false,
325            paths,
326        }
327    }
328
329    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
330        self.prompt
331            .update(cx, |prompt, cx| prompt.confirm(window, cx))
332    }
333
334    pub fn finished(&mut self, cx: &mut Context<Self>) {
335        self.finished = true;
336        cx.emit(DismissEvent);
337    }
338
339    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
340        if let Some(tx) = self
341            .prompt
342            .update(cx, |prompt, _cx| prompt.cancellation.take())
343        {
344            tx.send(()).ok();
345        }
346        self.finished(cx);
347    }
348}
349
350pub(crate) struct SshConnectionHeader {
351    pub(crate) connection_string: SharedString,
352    pub(crate) paths: Vec<PathBuf>,
353    pub(crate) nickname: Option<SharedString>,
354    pub(crate) is_wsl: bool,
355    pub(crate) is_devcontainer: bool,
356}
357
358impl RenderOnce for SshConnectionHeader {
359    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
360        let theme = cx.theme();
361
362        let mut header_color = theme.colors().text;
363        header_color.fade_out(0.96);
364
365        let (main_label, meta_label) = if let Some(nickname) = self.nickname {
366            (nickname, Some(format!("({})", self.connection_string)))
367        } else {
368            (self.connection_string, None)
369        };
370
371        let icon = if self.is_wsl {
372            IconName::Linux
373        } else if self.is_devcontainer {
374            IconName::Box
375        } else {
376            IconName::Server
377        };
378
379        h_flex()
380            .px(DynamicSpacing::Base12.rems(cx))
381            .pt(DynamicSpacing::Base08.rems(cx))
382            .pb(DynamicSpacing::Base04.rems(cx))
383            .rounded_t_sm()
384            .w_full()
385            .gap_1p5()
386            .child(Icon::new(icon).size(IconSize::Small))
387            .child(
388                h_flex()
389                    .gap_1()
390                    .overflow_x_hidden()
391                    .child(
392                        div()
393                            .max_w_96()
394                            .overflow_x_hidden()
395                            .text_ellipsis()
396                            .child(Headline::new(main_label).size(HeadlineSize::XSmall)),
397                    )
398                    .children(
399                        meta_label.map(|label| {
400                            Label::new(label).color(Color::Muted).size(LabelSize::Small)
401                        }),
402                    )
403                    .child(div().overflow_x_hidden().text_ellipsis().children(
404                        self.paths.into_iter().map(|path| {
405                            Label::new(path.to_string_lossy().into_owned())
406                                .size(LabelSize::Small)
407                                .color(Color::Muted)
408                        }),
409                    )),
410            )
411    }
412}
413
414impl Render for RemoteConnectionModal {
415    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
416        let nickname = self.prompt.read(cx).nickname.clone();
417        let connection_string = self.prompt.read(cx).connection_string.clone();
418        let is_wsl = self.prompt.read(cx).is_wsl;
419        let is_devcontainer = self.prompt.read(cx).is_devcontainer;
420
421        let theme = cx.theme().clone();
422        let body_color = theme.colors().editor_background;
423
424        v_flex()
425            .elevation_3(cx)
426            .w(rems(34.))
427            .border_1()
428            .border_color(theme.colors().border)
429            .key_context("SshConnectionModal")
430            .track_focus(&self.focus_handle(cx))
431            .on_action(cx.listener(Self::dismiss))
432            .on_action(cx.listener(Self::confirm))
433            .child(
434                SshConnectionHeader {
435                    paths: self.paths.clone(),
436                    connection_string,
437                    nickname,
438                    is_wsl,
439                    is_devcontainer,
440                }
441                .render(window, cx),
442            )
443            .child(
444                div()
445                    .w_full()
446                    .bg(body_color)
447                    .border_y_1()
448                    .border_color(theme.colors().border_variant)
449                    .child(self.prompt.clone()),
450            )
451            .child(
452                div().w_full().py_1().child(
453                    ListItem::new("li-devcontainer-go-back")
454                        .inset(true)
455                        .spacing(ui::ListItemSpacing::Sparse)
456                        .start_slot(Icon::new(IconName::Close).color(Color::Muted))
457                        .child(Label::new("Cancel"))
458                        .end_slot(
459                            KeyBinding::for_action_in(&menu::Cancel, &self.focus_handle(cx), cx)
460                                .size(rems_from_px(12.)),
461                        )
462                        .on_click(cx.listener(|this, _, window, cx| {
463                            this.dismiss(&menu::Cancel, window, cx);
464                        })),
465                ),
466            )
467    }
468}
469
470impl Focusable for RemoteConnectionModal {
471    fn focus_handle(&self, cx: &gpui::App) -> gpui::FocusHandle {
472        self.prompt.read(cx).editor.focus_handle(cx)
473    }
474}
475
476impl EventEmitter<DismissEvent> for RemoteConnectionModal {}
477
478impl ModalView for RemoteConnectionModal {
479    fn on_before_dismiss(
480        &mut self,
481        _window: &mut Window,
482        _: &mut Context<Self>,
483    ) -> workspace::DismissDecision {
484        workspace::DismissDecision::Dismiss(self.finished)
485    }
486
487    fn fade_out_background(&self) -> bool {
488        true
489    }
490}
491
492#[derive(Clone)]
493pub struct RemoteClientDelegate {
494    window: AnyWindowHandle,
495    ui: WeakEntity<RemoteConnectionPrompt>,
496    known_password: Option<EncryptedPassword>,
497}
498
499impl remote::RemoteClientDelegate for RemoteClientDelegate {
500    fn ask_password(
501        &self,
502        prompt: String,
503        tx: oneshot::Sender<EncryptedPassword>,
504        cx: &mut AsyncApp,
505    ) {
506        let mut known_password = self.known_password.clone();
507        if let Some(password) = known_password.take() {
508            tx.send(password).ok();
509        } else {
510            self.window
511                .update(cx, |_, window, cx| {
512                    self.ui.update(cx, |modal, cx| {
513                        modal.set_prompt(prompt, tx, window, cx);
514                    })
515                })
516                .ok();
517        }
518    }
519
520    fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
521        self.update_status(status, cx)
522    }
523
524    fn download_server_binary_locally(
525        &self,
526        platform: RemotePlatform,
527        release_channel: ReleaseChannel,
528        version: Option<Version>,
529        cx: &mut AsyncApp,
530    ) -> Task<anyhow::Result<PathBuf>> {
531        let this = self.clone();
532        cx.spawn(async move |cx| {
533            AutoUpdater::download_remote_server_release(
534                release_channel,
535                version.clone(),
536                platform.os.as_str(),
537                platform.arch.as_str(),
538                move |status, cx| this.set_status(Some(status), cx),
539                cx,
540            )
541            .await
542            .with_context(|| {
543                format!(
544                    "Downloading remote server binary (version: {}, os: {}, arch: {})",
545                    version
546                        .as_ref()
547                        .map(|v| format!("{}", v))
548                        .unwrap_or("unknown".to_string()),
549                    platform.os,
550                    platform.arch,
551                )
552            })
553        })
554    }
555
556    fn get_download_url(
557        &self,
558        platform: RemotePlatform,
559        release_channel: ReleaseChannel,
560        version: Option<Version>,
561        cx: &mut AsyncApp,
562    ) -> Task<Result<Option<String>>> {
563        cx.spawn(async move |cx| {
564            AutoUpdater::get_remote_server_release_url(
565                release_channel,
566                version,
567                platform.os.as_str(),
568                platform.arch.as_str(),
569                cx,
570            )
571            .await
572        })
573    }
574}
575
576impl RemoteClientDelegate {
577    fn update_status(&self, status: Option<&str>, cx: &mut AsyncApp) {
578        self.window
579            .update(cx, |_, _, cx| {
580                self.ui.update(cx, |modal, cx| {
581                    modal.set_status(status.map(|s| s.to_string()), cx);
582                })
583            })
584            .ok();
585    }
586}
587
588pub fn connect(
589    unique_identifier: ConnectionIdentifier,
590    connection_options: RemoteConnectionOptions,
591    ui: Entity<RemoteConnectionPrompt>,
592    window: &mut Window,
593    cx: &mut App,
594) -> Task<Result<Option<Entity<RemoteClient>>>> {
595    let window = window.window_handle();
596    let known_password = match &connection_options {
597        RemoteConnectionOptions::Ssh(ssh_connection_options) => ssh_connection_options
598            .password
599            .as_deref()
600            .and_then(|pw| pw.try_into().ok()),
601        _ => None,
602    };
603    let (tx, rx) = oneshot::channel();
604    ui.update(cx, |ui, _cx| ui.set_cancellation_tx(tx));
605
606    let delegate = Arc::new(RemoteClientDelegate {
607        window,
608        ui: ui.downgrade(),
609        known_password,
610    });
611
612    cx.spawn(async move |cx| {
613        let connection = remote::connect(connection_options, delegate.clone(), cx).await?;
614        cx.update(|cx| remote::RemoteClient::new(unique_identifier, connection, rx, delegate, cx))?
615            .await
616    })
617}
618
619pub async fn open_remote_project(
620    connection_options: RemoteConnectionOptions,
621    paths: Vec<PathBuf>,
622    app_state: Arc<AppState>,
623    open_options: workspace::OpenOptions,
624    cx: &mut AsyncApp,
625) -> Result<()> {
626    let created_new_window = open_options.replace_window.is_none();
627    let window = if let Some(window) = open_options.replace_window {
628        window
629    } else {
630        let workspace_position = cx
631            .update(|cx| {
632                // todo: These paths are wrong they may have column and line information
633                workspace::remote_workspace_position_from_db(connection_options.clone(), &paths, cx)
634            })?
635            .await
636            .context("fetching ssh workspace position from db")?;
637
638        let mut options =
639            cx.update(|cx| (app_state.build_window_options)(workspace_position.display, cx))?;
640        options.window_bounds = workspace_position.window_bounds;
641
642        cx.open_window(options, |window, cx| {
643            let project = project::Project::local(
644                app_state.client.clone(),
645                app_state.node_runtime.clone(),
646                app_state.user_store.clone(),
647                app_state.languages.clone(),
648                app_state.fs.clone(),
649                None,
650                false,
651                cx,
652            );
653            cx.new(|cx| {
654                let mut workspace = Workspace::new(None, project, app_state.clone(), window, cx);
655                workspace.centered_layout = workspace_position.centered_layout;
656                workspace
657            })
658        })?
659    };
660
661    loop {
662        let (cancel_tx, cancel_rx) = oneshot::channel();
663        let delegate = window.update(cx, {
664            let paths = paths.clone();
665            let connection_options = connection_options.clone();
666            move |workspace, window, cx| {
667                window.activate_window();
668                workspace.toggle_modal(window, cx, |window, cx| {
669                    RemoteConnectionModal::new(&connection_options, paths, window, cx)
670                });
671
672                let ui = workspace
673                    .active_modal::<RemoteConnectionModal>(cx)?
674                    .read(cx)
675                    .prompt
676                    .clone();
677
678                ui.update(cx, |ui, _cx| {
679                    ui.set_cancellation_tx(cancel_tx);
680                });
681
682                Some(Arc::new(RemoteClientDelegate {
683                    window: window.window_handle(),
684                    ui: ui.downgrade(),
685                    known_password: if let RemoteConnectionOptions::Ssh(options) =
686                        &connection_options
687                    {
688                        options
689                            .password
690                            .as_deref()
691                            .and_then(|pw| EncryptedPassword::try_from(pw).ok())
692                    } else {
693                        None
694                    },
695                }))
696            }
697        })?;
698
699        let Some(delegate) = delegate else { break };
700
701        let remote_connection =
702            match remote::connect(connection_options.clone(), delegate.clone(), cx).await {
703                Ok(connection) => connection,
704                Err(e) => {
705                    window
706                        .update(cx, |workspace, _, cx| {
707                            if let Some(ui) = workspace.active_modal::<RemoteConnectionModal>(cx) {
708                                ui.update(cx, |modal, cx| modal.finished(cx))
709                            }
710                        })
711                        .ok();
712                    log::error!("Failed to open project: {e:#}");
713                    let response = window
714                        .update(cx, |_, window, cx| {
715                            window.prompt(
716                                PromptLevel::Critical,
717                                match connection_options {
718                                    RemoteConnectionOptions::Ssh(_) => "Failed to connect over SSH",
719                                    RemoteConnectionOptions::Wsl(_) => "Failed to connect to WSL",
720                                    RemoteConnectionOptions::Docker(_) => {
721                                        "Failed to connect to Dev Container"
722                                    }
723                                },
724                                Some(&format!("{e:#}")),
725                                &["Retry", "Cancel"],
726                                cx,
727                            )
728                        })?
729                        .await;
730
731                    if response == Ok(0) {
732                        continue;
733                    }
734
735                    if created_new_window {
736                        window
737                            .update(cx, |_, window, _| window.remove_window())
738                            .ok();
739                    }
740                    break;
741                }
742            };
743
744        let (paths, paths_with_positions) =
745            determine_paths_with_positions(&remote_connection, paths.clone()).await;
746
747        let opened_items = cx
748            .update(|cx| {
749                workspace::open_remote_project_with_new_connection(
750                    window,
751                    remote_connection,
752                    cancel_rx,
753                    delegate.clone(),
754                    app_state.clone(),
755                    paths.clone(),
756                    cx,
757                )
758            })?
759            .await;
760
761        window
762            .update(cx, |workspace, _, cx| {
763                if let Some(ui) = workspace.active_modal::<RemoteConnectionModal>(cx) {
764                    ui.update(cx, |modal, cx| modal.finished(cx))
765                }
766            })
767            .ok();
768
769        match opened_items {
770            Err(e) => {
771                log::error!("Failed to open project: {e:#}");
772                let response = window
773                    .update(cx, |_, window, cx| {
774                        window.prompt(
775                            PromptLevel::Critical,
776                            match connection_options {
777                                RemoteConnectionOptions::Ssh(_) => "Failed to connect over SSH",
778                                RemoteConnectionOptions::Wsl(_) => "Failed to connect to WSL",
779                                RemoteConnectionOptions::Docker(_) => {
780                                    "Failed to connect to Dev Container"
781                                }
782                            },
783                            Some(&format!("{e:#}")),
784                            &["Retry", "Cancel"],
785                            cx,
786                        )
787                    })?
788                    .await;
789                if response == Ok(0) {
790                    continue;
791                }
792
793                window
794                    .update(cx, |workspace, window, cx| {
795                        if created_new_window {
796                            window.remove_window();
797                        }
798                        trusted_worktrees::track_worktree_trust(
799                            workspace.project().read(cx).worktree_store(),
800                            None,
801                            None,
802                            None,
803                            cx,
804                        );
805                    })
806                    .ok();
807            }
808
809            Ok(items) => {
810                for (item, path) in items.into_iter().zip(paths_with_positions) {
811                    let Some(item) = item else {
812                        continue;
813                    };
814                    let Some(row) = path.row else {
815                        continue;
816                    };
817                    if let Some(active_editor) = item.downcast::<Editor>() {
818                        window
819                            .update(cx, |_, window, cx| {
820                                active_editor.update(cx, |editor, cx| {
821                                    let row = row.saturating_sub(1);
822                                    let col = path.column.unwrap_or(0).saturating_sub(1);
823                                    editor.go_to_singleton_buffer_point(
824                                        Point::new(row, col),
825                                        window,
826                                        cx,
827                                    );
828                                });
829                            })
830                            .ok();
831                    }
832                }
833            }
834        }
835
836        window
837            .update(cx, |workspace, _, cx| {
838                if let Some(client) = workspace.project().read(cx).remote_client() {
839                    ExtensionStore::global(cx)
840                        .update(cx, |store, cx| store.register_remote_client(client, cx));
841                }
842            })
843            .ok();
844
845        break;
846    }
847
848    // Already showed the error to the user
849    Ok(())
850}
851
852pub(crate) async fn determine_paths_with_positions(
853    remote_connection: &Arc<dyn RemoteConnection>,
854    mut paths: Vec<PathBuf>,
855) -> (Vec<PathBuf>, Vec<PathWithPosition>) {
856    let mut paths_with_positions = Vec::<PathWithPosition>::new();
857    for path in &mut paths {
858        if let Some(path_str) = path.to_str() {
859            let path_with_position = PathWithPosition::parse_str(&path_str);
860            if path_with_position.row.is_some() {
861                if !path_exists(&remote_connection, &path).await {
862                    *path = path_with_position.path.clone();
863                    paths_with_positions.push(path_with_position);
864                    continue;
865                }
866            }
867        }
868        paths_with_positions.push(PathWithPosition::from_path(path.clone()))
869    }
870    (paths, paths_with_positions)
871}
872
873async fn path_exists(connection: &Arc<dyn RemoteConnection>, path: &Path) -> bool {
874    let Ok(command) = connection.build_command(
875        Some("test".to_string()),
876        &["-e".to_owned(), path.to_string_lossy().to_string()],
877        &Default::default(),
878        None,
879        None,
880    ) else {
881        return false;
882    };
883    let Ok(mut child) = util::command::new_smol_command(command.program)
884        .args(command.args)
885        .envs(command.env)
886        .spawn()
887    else {
888        return false;
889    };
890    child.status().await.is_ok_and(|status| status.success())
891}