1use crate::tests::TestServer;
2use call::ActiveCall;
3use collections::HashSet;
4use extension::ExtensionHostProxy;
5use fs::{FakeFs, Fs as _};
6use futures::StreamExt as _;
7use gpui::{BackgroundExecutor, Context as _, SemanticVersion, TestAppContext, UpdateGlobal as _};
8use http_client::BlockedHttpClient;
9use language::{
10 language_settings::{
11 language_settings, AllLanguageSettings, Formatter, FormatterList, PrettierSettings,
12 SelectedFormatter,
13 },
14 tree_sitter_typescript, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher,
15 LanguageRegistry,
16};
17use node_runtime::NodeRuntime;
18use project::{
19 lsp_store::{FormatTarget, FormatTrigger},
20 ProjectPath,
21};
22use remote::SshRemoteClient;
23use remote_server::{HeadlessAppState, HeadlessProject};
24use serde_json::json;
25use settings::SettingsStore;
26use std::{path::Path, sync::Arc};
27
28#[gpui::test(iterations = 10)]
29async fn test_sharing_an_ssh_remote_project(
30 cx_a: &mut TestAppContext,
31 cx_b: &mut TestAppContext,
32 server_cx: &mut TestAppContext,
33) {
34 let executor = cx_a.executor();
35 cx_a.update(|cx| {
36 release_channel::init(SemanticVersion::default(), cx);
37 });
38 server_cx.update(|cx| {
39 release_channel::init(SemanticVersion::default(), cx);
40 });
41 let mut server = TestServer::start(executor.clone()).await;
42 let client_a = server.create_client(cx_a, "user_a").await;
43 let client_b = server.create_client(cx_b, "user_b").await;
44 server
45 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
46 .await;
47
48 // Set up project on remote FS
49 let (opts, server_ssh) = SshRemoteClient::fake_server(cx_a, server_cx);
50 let remote_fs = FakeFs::new(server_cx.executor());
51 remote_fs
52 .insert_tree(
53 "/code",
54 json!({
55 "project1": {
56 ".zed": {
57 "settings.json": r#"{"languages":{"Rust":{"language_servers":["override-rust-analyzer"]}}}"#
58 },
59 "README.md": "# project 1",
60 "src": {
61 "lib.rs": "fn one() -> usize { 1 }"
62 }
63 },
64 "project2": {
65 "README.md": "# project 2",
66 },
67 }),
68 )
69 .await;
70
71 // User A connects to the remote project via SSH.
72 server_cx.update(HeadlessProject::init);
73 let remote_http_client = Arc::new(BlockedHttpClient);
74 let node = NodeRuntime::unavailable();
75 let languages = Arc::new(LanguageRegistry::new(server_cx.executor()));
76 let _headless_project = server_cx.new_model(|cx| {
77 client::init_settings(cx);
78 HeadlessProject::new(
79 HeadlessAppState {
80 session: server_ssh,
81 fs: remote_fs.clone(),
82 http_client: remote_http_client,
83 node_runtime: node,
84 languages,
85 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
86 },
87 cx,
88 )
89 });
90
91 let client_ssh = SshRemoteClient::fake_client(opts, cx_a).await;
92 let (project_a, worktree_id) = client_a
93 .build_ssh_project("/code/project1", client_ssh, cx_a)
94 .await;
95
96 // While the SSH worktree is being scanned, user A shares the remote project.
97 let active_call_a = cx_a.read(ActiveCall::global);
98 let project_id = active_call_a
99 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
100 .await
101 .unwrap();
102
103 // User B joins the project.
104 let project_b = client_b.join_remote_project(project_id, cx_b).await;
105 let worktree_b = project_b
106 .update(cx_b, |project, cx| project.worktree_for_id(worktree_id, cx))
107 .unwrap();
108
109 let worktree_a = project_a
110 .update(cx_a, |project, cx| project.worktree_for_id(worktree_id, cx))
111 .unwrap();
112
113 executor.run_until_parked();
114
115 worktree_a.update(cx_a, |worktree, _cx| {
116 assert_eq!(
117 worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),
118 vec![
119 Path::new(".zed"),
120 Path::new(".zed/settings.json"),
121 Path::new("README.md"),
122 Path::new("src"),
123 Path::new("src/lib.rs"),
124 ]
125 );
126 });
127
128 worktree_b.update(cx_b, |worktree, _cx| {
129 assert_eq!(
130 worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),
131 vec![
132 Path::new(".zed"),
133 Path::new(".zed/settings.json"),
134 Path::new("README.md"),
135 Path::new("src"),
136 Path::new("src/lib.rs"),
137 ]
138 );
139 });
140
141 // User B can open buffers in the remote project.
142 let buffer_b = project_b
143 .update(cx_b, |project, cx| {
144 project.open_buffer((worktree_id, "src/lib.rs"), cx)
145 })
146 .await
147 .unwrap();
148 buffer_b.update(cx_b, |buffer, cx| {
149 assert_eq!(buffer.text(), "fn one() -> usize { 1 }");
150 let ix = buffer.text().find('1').unwrap();
151 buffer.edit([(ix..ix + 1, "100")], None, cx);
152 });
153
154 executor.run_until_parked();
155
156 cx_b.read(|cx| {
157 let file = buffer_b.read(cx).file();
158 assert_eq!(
159 language_settings(Some("Rust".into()), file, cx).language_servers,
160 ["override-rust-analyzer".to_string()]
161 )
162 });
163
164 project_b
165 .update(cx_b, |project, cx| {
166 project.save_buffer_as(
167 buffer_b.clone(),
168 ProjectPath {
169 worktree_id: worktree_id.to_owned(),
170 path: Arc::from(Path::new("src/renamed.rs")),
171 },
172 cx,
173 )
174 })
175 .await
176 .unwrap();
177 assert_eq!(
178 remote_fs
179 .load("/code/project1/src/renamed.rs".as_ref())
180 .await
181 .unwrap(),
182 "fn one() -> usize { 100 }"
183 );
184 cx_b.run_until_parked();
185 cx_b.update(|cx| {
186 assert_eq!(
187 buffer_b
188 .read(cx)
189 .file()
190 .unwrap()
191 .path()
192 .to_string_lossy()
193 .to_string(),
194 "src/renamed.rs".to_string()
195 );
196 });
197}
198
199#[gpui::test]
200async fn test_ssh_collaboration_git_branches(
201 executor: BackgroundExecutor,
202 cx_a: &mut TestAppContext,
203 cx_b: &mut TestAppContext,
204 server_cx: &mut TestAppContext,
205) {
206 cx_a.set_name("a");
207 cx_b.set_name("b");
208 server_cx.set_name("server");
209
210 cx_a.update(|cx| {
211 release_channel::init(SemanticVersion::default(), cx);
212 });
213 server_cx.update(|cx| {
214 release_channel::init(SemanticVersion::default(), cx);
215 });
216
217 let mut server = TestServer::start(executor.clone()).await;
218 let client_a = server.create_client(cx_a, "user_a").await;
219 let client_b = server.create_client(cx_b, "user_b").await;
220 server
221 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
222 .await;
223
224 // Set up project on remote FS
225 let (opts, server_ssh) = SshRemoteClient::fake_server(cx_a, server_cx);
226 let remote_fs = FakeFs::new(server_cx.executor());
227 remote_fs
228 .insert_tree("/project", serde_json::json!({ ".git":{} }))
229 .await;
230
231 let branches = ["main", "dev", "feature-1"];
232 remote_fs.insert_branches(Path::new("/project/.git"), &branches);
233
234 // User A connects to the remote project via SSH.
235 server_cx.update(HeadlessProject::init);
236 let remote_http_client = Arc::new(BlockedHttpClient);
237 let node = NodeRuntime::unavailable();
238 let languages = Arc::new(LanguageRegistry::new(server_cx.executor()));
239 let headless_project = server_cx.new_model(|cx| {
240 client::init_settings(cx);
241 HeadlessProject::new(
242 HeadlessAppState {
243 session: server_ssh,
244 fs: remote_fs.clone(),
245 http_client: remote_http_client,
246 node_runtime: node,
247 languages,
248 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
249 },
250 cx,
251 )
252 });
253
254 let client_ssh = SshRemoteClient::fake_client(opts, cx_a).await;
255 let (project_a, worktree_id) = client_a
256 .build_ssh_project("/project", client_ssh, cx_a)
257 .await;
258
259 // While the SSH worktree is being scanned, user A shares the remote project.
260 let active_call_a = cx_a.read(ActiveCall::global);
261 let project_id = active_call_a
262 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
263 .await
264 .unwrap();
265
266 // User B joins the project.
267 let project_b = client_b.join_remote_project(project_id, cx_b).await;
268
269 // Give client A sometime to see that B has joined, and that the headless server
270 // has some git repositories
271 executor.run_until_parked();
272
273 let root_path = ProjectPath::root_path(worktree_id);
274
275 let branches_b = cx_b
276 .update(|cx| project_b.update(cx, |project, cx| project.branches(root_path.clone(), cx)))
277 .await
278 .unwrap();
279
280 let new_branch = branches[2];
281
282 let branches_b = branches_b
283 .into_iter()
284 .map(|branch| branch.name)
285 .collect::<Vec<_>>();
286
287 assert_eq!(&branches_b, &branches);
288
289 cx_b.update(|cx| {
290 project_b.update(cx, |project, cx| {
291 project.update_or_create_branch(root_path.clone(), new_branch.to_string(), cx)
292 })
293 })
294 .await
295 .unwrap();
296
297 executor.run_until_parked();
298
299 let server_branch = server_cx.update(|cx| {
300 headless_project.update(cx, |headless_project, cx| {
301 headless_project
302 .worktree_store
303 .update(cx, |worktree_store, cx| {
304 worktree_store
305 .current_branch(root_path.clone(), cx)
306 .unwrap()
307 })
308 })
309 });
310
311 assert_eq!(server_branch.as_ref(), branches[2]);
312
313 // Also try creating a new branch
314 cx_b.update(|cx| {
315 project_b.update(cx, |project, cx| {
316 project.update_or_create_branch(root_path.clone(), "totally-new-branch".to_string(), cx)
317 })
318 })
319 .await
320 .unwrap();
321
322 executor.run_until_parked();
323
324 let server_branch = server_cx.update(|cx| {
325 headless_project.update(cx, |headless_project, cx| {
326 headless_project
327 .worktree_store
328 .update(cx, |worktree_store, cx| {
329 worktree_store.current_branch(root_path, cx).unwrap()
330 })
331 })
332 });
333
334 assert_eq!(server_branch.as_ref(), "totally-new-branch");
335}
336
337#[gpui::test]
338async fn test_ssh_collaboration_formatting_with_prettier(
339 executor: BackgroundExecutor,
340 cx_a: &mut TestAppContext,
341 cx_b: &mut TestAppContext,
342 server_cx: &mut TestAppContext,
343) {
344 cx_a.set_name("a");
345 cx_b.set_name("b");
346 server_cx.set_name("server");
347
348 cx_a.update(|cx| {
349 release_channel::init(SemanticVersion::default(), cx);
350 });
351 server_cx.update(|cx| {
352 release_channel::init(SemanticVersion::default(), cx);
353 });
354
355 let mut server = TestServer::start(executor.clone()).await;
356 let client_a = server.create_client(cx_a, "user_a").await;
357 let client_b = server.create_client(cx_b, "user_b").await;
358 server
359 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
360 .await;
361
362 let (opts, server_ssh) = SshRemoteClient::fake_server(cx_a, server_cx);
363 let remote_fs = FakeFs::new(server_cx.executor());
364 let buffer_text = "let one = \"two\"";
365 let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
366 remote_fs
367 .insert_tree("/project", serde_json::json!({ "a.ts": buffer_text }))
368 .await;
369
370 let test_plugin = "test_plugin";
371 let ts_lang = Arc::new(Language::new(
372 LanguageConfig {
373 name: "TypeScript".into(),
374 matcher: LanguageMatcher {
375 path_suffixes: vec!["ts".to_string()],
376 ..LanguageMatcher::default()
377 },
378 ..LanguageConfig::default()
379 },
380 Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
381 ));
382 client_a.language_registry().add(ts_lang.clone());
383 client_b.language_registry().add(ts_lang.clone());
384
385 let languages = Arc::new(LanguageRegistry::new(server_cx.executor()));
386 let mut fake_language_servers = languages.register_fake_lsp(
387 "TypeScript",
388 FakeLspAdapter {
389 prettier_plugins: vec![test_plugin],
390 ..Default::default()
391 },
392 );
393
394 // User A connects to the remote project via SSH.
395 server_cx.update(HeadlessProject::init);
396 let remote_http_client = Arc::new(BlockedHttpClient);
397 let _headless_project = server_cx.new_model(|cx| {
398 client::init_settings(cx);
399 HeadlessProject::new(
400 HeadlessAppState {
401 session: server_ssh,
402 fs: remote_fs.clone(),
403 http_client: remote_http_client,
404 node_runtime: NodeRuntime::unavailable(),
405 languages,
406 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
407 },
408 cx,
409 )
410 });
411
412 let client_ssh = SshRemoteClient::fake_client(opts, cx_a).await;
413 let (project_a, worktree_id) = client_a
414 .build_ssh_project("/project", client_ssh, cx_a)
415 .await;
416
417 // While the SSH worktree is being scanned, user A shares the remote project.
418 let active_call_a = cx_a.read(ActiveCall::global);
419 let project_id = active_call_a
420 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
421 .await
422 .unwrap();
423
424 // User B joins the project.
425 let project_b = client_b.join_remote_project(project_id, cx_b).await;
426 executor.run_until_parked();
427
428 // Opens the buffer and formats it
429 let buffer_b = project_b
430 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.ts"), cx))
431 .await
432 .expect("user B opens buffer for formatting");
433
434 cx_a.update(|cx| {
435 SettingsStore::update_global(cx, |store, cx| {
436 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
437 file.defaults.formatter = Some(SelectedFormatter::Auto);
438 file.defaults.prettier = Some(PrettierSettings {
439 allowed: true,
440 ..PrettierSettings::default()
441 });
442 });
443 });
444 });
445 cx_b.update(|cx| {
446 SettingsStore::update_global(cx, |store, cx| {
447 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
448 file.defaults.formatter = Some(SelectedFormatter::List(FormatterList(
449 vec![Formatter::LanguageServer { name: None }].into(),
450 )));
451 file.defaults.prettier = Some(PrettierSettings {
452 allowed: true,
453 ..PrettierSettings::default()
454 });
455 });
456 });
457 });
458 let fake_language_server = fake_language_servers.next().await.unwrap();
459 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
460 panic!(
461 "Unexpected: prettier should be preferred since it's enabled and language supports it"
462 )
463 });
464
465 project_b
466 .update(cx_b, |project, cx| {
467 project.format(
468 HashSet::from_iter([buffer_b.clone()]),
469 true,
470 FormatTrigger::Save,
471 FormatTarget::Buffer,
472 cx,
473 )
474 })
475 .await
476 .unwrap();
477
478 executor.run_until_parked();
479 assert_eq!(
480 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
481 buffer_text.to_string() + "\n" + prettier_format_suffix,
482 "Prettier formatting was not applied to client buffer after client's request"
483 );
484
485 // User A opens and formats the same buffer too
486 let buffer_a = project_a
487 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.ts"), cx))
488 .await
489 .expect("user A opens buffer for formatting");
490
491 cx_a.update(|cx| {
492 SettingsStore::update_global(cx, |store, cx| {
493 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
494 file.defaults.formatter = Some(SelectedFormatter::Auto);
495 file.defaults.prettier = Some(PrettierSettings {
496 allowed: true,
497 ..PrettierSettings::default()
498 });
499 });
500 });
501 });
502 project_a
503 .update(cx_a, |project, cx| {
504 project.format(
505 HashSet::from_iter([buffer_a.clone()]),
506 true,
507 FormatTrigger::Manual,
508 FormatTarget::Buffer,
509 cx,
510 )
511 })
512 .await
513 .unwrap();
514
515 executor.run_until_parked();
516 assert_eq!(
517 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
518 buffer_text.to_string() + "\n" + prettier_format_suffix + "\n" + prettier_format_suffix,
519 "Prettier formatting was not applied to client buffer after host's request"
520 );
521}