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