1use crate::{
2 db::{tests::TestDb, UserId},
3 rpc::{Executor, Server, Store},
4 AppState,
5};
6use ::rpc::Peer;
7use anyhow::anyhow;
8use client::{
9 self, proto, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Connection,
10 Credentials, EstablishConnectionError, UserStore, RECEIVE_TIMEOUT,
11};
12use collections::{BTreeMap, HashMap, HashSet};
13use editor::{
14 self, ConfirmCodeAction, ConfirmCompletion, ConfirmRename, Editor, Input, Redo, Rename,
15 ToOffset, ToggleCodeActions, Undo,
16};
17use futures::{channel::mpsc, Future, StreamExt as _};
18use gpui::{
19 executor::{self, Deterministic},
20 geometry::vector::vec2f,
21 ModelHandle, Task, TestAppContext, ViewHandle,
22};
23use language::{
24 range_to_lsp, tree_sitter_rust, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language,
25 LanguageConfig, LanguageRegistry, OffsetRangeExt, Point, Rope,
26};
27use lsp::{self, FakeLanguageServer};
28use parking_lot::Mutex;
29use project::{
30 fs::{FakeFs, Fs as _},
31 search::SearchQuery,
32 worktree::WorktreeHandle,
33 DiagnosticSummary, Project, ProjectPath, WorktreeId,
34};
35use rand::prelude::*;
36use rpc::PeerId;
37use serde_json::json;
38use settings::Settings;
39use sqlx::types::time::OffsetDateTime;
40use std::{
41 cell::RefCell,
42 env,
43 ops::Deref,
44 path::{Path, PathBuf},
45 rc::Rc,
46 sync::{
47 atomic::{AtomicBool, Ordering::SeqCst},
48 Arc,
49 },
50 time::Duration,
51};
52use theme::ThemeRegistry;
53use tokio::sync::RwLockReadGuard;
54use workspace::{Item, SplitDirection, ToggleFollow, Workspace};
55
56#[ctor::ctor]
57fn init_logger() {
58 if std::env::var("RUST_LOG").is_ok() {
59 env_logger::init();
60 }
61}
62
63#[gpui::test(iterations = 10)]
64async fn test_share_project(
65 deterministic: Arc<Deterministic>,
66 cx_a: &mut TestAppContext,
67 cx_b: &mut TestAppContext,
68 cx_b2: &mut TestAppContext,
69) {
70 cx_a.foreground().forbid_parking();
71 let (window_b, _) = cx_b.add_window(|_| EmptyView);
72 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
73 let mut client_a = server.create_client(cx_a, "user_a").await;
74 let mut client_b = server.create_client(cx_b, "user_b").await;
75 server
76 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
77 .await;
78
79 let fs = FakeFs::new(cx_a.background());
80 fs.insert_tree(
81 "/a",
82 json!({
83 ".gitignore": "ignored-dir",
84 "a.txt": "a-contents",
85 "b.txt": "b-contents",
86 "ignored-dir": {
87 "c.txt": "",
88 "d.txt": "",
89 }
90 }),
91 )
92 .await;
93
94 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
95 let project_id = project_a.read_with(cx_a, |project, _| project.remote_id().unwrap());
96
97 // Join that project as client B
98 let client_b_peer_id = client_b.peer_id;
99 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
100 let replica_id_b = project_b.read_with(cx_b, |project, _| {
101 assert_eq!(
102 project
103 .collaborators()
104 .get(&client_a.peer_id)
105 .unwrap()
106 .user
107 .github_login,
108 "user_a"
109 );
110 project.replica_id()
111 });
112
113 deterministic.run_until_parked();
114 project_a.read_with(cx_a, |project, _| {
115 let client_b_collaborator = project.collaborators().get(&client_b_peer_id).unwrap();
116 assert_eq!(client_b_collaborator.replica_id, replica_id_b);
117 assert_eq!(client_b_collaborator.user.github_login, "user_b");
118 });
119 project_b.read_with(cx_b, |project, cx| {
120 let worktree = project.worktrees(cx).next().unwrap().read(cx);
121 assert_eq!(
122 worktree.paths().map(AsRef::as_ref).collect::<Vec<_>>(),
123 [
124 Path::new(".gitignore"),
125 Path::new("a.txt"),
126 Path::new("b.txt"),
127 Path::new("ignored-dir"),
128 Path::new("ignored-dir/c.txt"),
129 Path::new("ignored-dir/d.txt"),
130 ]
131 );
132 });
133
134 // Open the same file as client B and client A.
135 let buffer_b = project_b
136 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
137 .await
138 .unwrap();
139 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
140 project_a.read_with(cx_a, |project, cx| {
141 assert!(project.has_open_buffer((worktree_id, "b.txt"), cx))
142 });
143 let buffer_a = project_a
144 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
145 .await
146 .unwrap();
147
148 let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, None, cx));
149
150 // TODO
151 // // Create a selection set as client B and see that selection set as client A.
152 // buffer_a
153 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
154 // .await;
155
156 // Edit the buffer as client B and see that edit as client A.
157 editor_b.update(cx_b, |editor, cx| {
158 editor.handle_input(&Input("ok, ".into()), cx)
159 });
160 buffer_a
161 .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
162 .await;
163
164 // TODO
165 // // Remove the selection set as client B, see those selections disappear as client A.
166 cx_b.update(move |_| drop(editor_b));
167 // buffer_a
168 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
169 // .await;
170
171 // Client B can join again on a different window because they are already a participant.
172 let client_b2 = server.create_client(cx_b2, "user_b").await;
173 let project_b2 = Project::remote(
174 project_id,
175 client_b2.client.clone(),
176 client_b2.user_store.clone(),
177 client_b2.language_registry.clone(),
178 FakeFs::new(cx_b2.background()),
179 &mut cx_b2.to_async(),
180 )
181 .await
182 .unwrap();
183 deterministic.run_until_parked();
184 project_a.read_with(cx_a, |project, _| {
185 assert_eq!(project.collaborators().len(), 2);
186 });
187 project_b.read_with(cx_b, |project, _| {
188 assert_eq!(project.collaborators().len(), 2);
189 });
190 project_b2.read_with(cx_b2, |project, _| {
191 assert_eq!(project.collaborators().len(), 2);
192 });
193
194 // Dropping client B's first project removes only that from client A's collaborators.
195 cx_b.update(move |_| {
196 drop(client_b.project.take());
197 drop(project_b);
198 });
199 deterministic.run_until_parked();
200 project_a.read_with(cx_a, |project, _| {
201 assert_eq!(project.collaborators().len(), 1);
202 });
203 project_b2.read_with(cx_b2, |project, _| {
204 assert_eq!(project.collaborators().len(), 1);
205 });
206}
207
208#[gpui::test(iterations = 10)]
209async fn test_unshare_project(
210 deterministic: Arc<Deterministic>,
211 cx_a: &mut TestAppContext,
212 cx_b: &mut TestAppContext,
213) {
214 cx_a.foreground().forbid_parking();
215 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
216 let mut client_a = server.create_client(cx_a, "user_a").await;
217 let mut client_b = server.create_client(cx_b, "user_b").await;
218 server
219 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
220 .await;
221
222 let fs = FakeFs::new(cx_a.background());
223 fs.insert_tree(
224 "/a",
225 json!({
226 "a.txt": "a-contents",
227 "b.txt": "b-contents",
228 }),
229 )
230 .await;
231
232 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
233 let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
234 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
235 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
236
237 project_b
238 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
239 .await
240 .unwrap();
241
242 // When client B leaves the project, it gets automatically unshared.
243 cx_b.update(|_| {
244 drop(client_b.project.take());
245 drop(project_b);
246 });
247 deterministic.run_until_parked();
248 assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
249
250 // When client B joins again, the project gets re-shared.
251 let project_b2 = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
252 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
253 project_b2
254 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
255 .await
256 .unwrap();
257
258 // When client A (the host) leaves, the project gets unshared and guests are notified.
259 cx_a.update(|_| {
260 drop(project_a);
261 client_a.project.take();
262 });
263 deterministic.run_until_parked();
264 project_b2.read_with(cx_b, |project, _| {
265 assert!(project.is_read_only());
266 assert!(project.collaborators().is_empty());
267 });
268}
269
270#[gpui::test(iterations = 10)]
271async fn test_host_disconnect(
272 deterministic: Arc<Deterministic>,
273 cx_a: &mut TestAppContext,
274 cx_b: &mut TestAppContext,
275 cx_c: &mut TestAppContext,
276) {
277 cx_a.foreground().forbid_parking();
278 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
279 let mut client_a = server.create_client(cx_a, "user_a").await;
280 let mut client_b = server.create_client(cx_b, "user_b").await;
281 let client_c = server.create_client(cx_c, "user_c").await;
282 server
283 .make_contacts(vec![
284 (&client_a, cx_a),
285 (&client_b, cx_b),
286 (&client_c, cx_c),
287 ])
288 .await;
289
290 let fs = FakeFs::new(cx_a.background());
291 fs.insert_tree(
292 "/a",
293 json!({
294 "a.txt": "a-contents",
295 "b.txt": "b-contents",
296 }),
297 )
298 .await;
299
300 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
301 let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
302 let project_id = project_a.read_with(cx_a, |project, _| project.remote_id().unwrap());
303
304 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
305 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
306
307 project_b
308 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
309 .await
310 .unwrap();
311
312 // Request to join that project as client C
313 let project_c = cx_c.spawn(|mut cx| async move {
314 Project::remote(
315 project_id,
316 client_c.client.clone(),
317 client_c.user_store.clone(),
318 client_c.language_registry.clone(),
319 FakeFs::new(cx.background()),
320 &mut cx,
321 )
322 .await
323 });
324 deterministic.run_until_parked();
325
326 // Drop client A's connection. Collaborators should disappear and the project should not be shown as shared.
327 server.disconnect_client(client_a.current_user_id(cx_a));
328 cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
329 project_a
330 .condition(cx_a, |project, _| project.collaborators().is_empty())
331 .await;
332 project_a.read_with(cx_a, |project, _| assert!(!project.is_shared()));
333 project_b
334 .condition(cx_b, |project, _| project.is_read_only())
335 .await;
336 assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
337 cx_b.update(|_| {
338 drop(project_b);
339 });
340 assert!(matches!(
341 project_c.await.unwrap_err(),
342 project::JoinProjectError::HostWentOffline
343 ));
344
345 // Ensure guests can still join.
346 let project_b2 = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
347 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
348 project_b2
349 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
350 .await
351 .unwrap();
352}
353
354#[gpui::test(iterations = 10)]
355async fn test_decline_join_request(
356 deterministic: Arc<Deterministic>,
357 cx_a: &mut TestAppContext,
358 cx_b: &mut TestAppContext,
359) {
360 cx_a.foreground().forbid_parking();
361 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
362 let mut client_a = server.create_client(cx_a, "user_a").await;
363 let client_b = server.create_client(cx_b, "user_b").await;
364 server
365 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
366 .await;
367
368 let fs = FakeFs::new(cx_a.background());
369 fs.insert_tree("/a", json!({})).await;
370
371 let (project_a, _) = client_a.build_local_project(fs, "/a", cx_a).await;
372 let project_id = project_a.read_with(cx_a, |project, _| project.remote_id().unwrap());
373
374 // Request to join that project as client B
375 let project_b = cx_b.spawn(|mut cx| {
376 let client = client_b.client.clone();
377 let user_store = client_b.user_store.clone();
378 let language_registry = client_b.language_registry.clone();
379 async move {
380 Project::remote(
381 project_id,
382 client,
383 user_store,
384 language_registry,
385 FakeFs::new(cx.background()),
386 &mut cx,
387 )
388 .await
389 }
390 });
391 deterministic.run_until_parked();
392 project_a.update(cx_a, |project, cx| {
393 project.respond_to_join_request(client_b.user_id().unwrap(), false, cx)
394 });
395 assert!(matches!(
396 project_b.await.unwrap_err(),
397 project::JoinProjectError::HostDeclined
398 ));
399
400 // Request to join the project again as client B
401 let project_b = cx_b.spawn(|mut cx| {
402 let client = client_b.client.clone();
403 let user_store = client_b.user_store.clone();
404 async move {
405 Project::remote(
406 project_id,
407 client,
408 user_store,
409 client_b.language_registry.clone(),
410 FakeFs::new(cx.background()),
411 &mut cx,
412 )
413 .await
414 }
415 });
416
417 // Close the project on the host
418 deterministic.run_until_parked();
419 cx_a.update(|_| {
420 drop(project_a);
421 client_a.project.take();
422 });
423 deterministic.run_until_parked();
424 assert!(matches!(
425 project_b.await.unwrap_err(),
426 project::JoinProjectError::HostClosedProject
427 ));
428}
429
430#[gpui::test(iterations = 10)]
431async fn test_cancel_join_request(
432 deterministic: Arc<Deterministic>,
433 cx_a: &mut TestAppContext,
434 cx_b: &mut TestAppContext,
435) {
436 cx_a.foreground().forbid_parking();
437 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
438 let mut client_a = server.create_client(cx_a, "user_a").await;
439 let client_b = server.create_client(cx_b, "user_b").await;
440 server
441 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
442 .await;
443
444 let fs = FakeFs::new(cx_a.background());
445 fs.insert_tree("/a", json!({})).await;
446
447 let (project_a, _) = client_a.build_local_project(fs, "/a", cx_a).await;
448 let project_id = project_a.read_with(cx_a, |project, _| project.remote_id().unwrap());
449
450 let user_b = client_a
451 .user_store
452 .update(cx_a, |store, cx| {
453 store.fetch_user(client_b.user_id().unwrap(), cx)
454 })
455 .await
456 .unwrap();
457
458 let project_a_events = Rc::new(RefCell::new(Vec::new()));
459 project_a.update(cx_a, {
460 let project_a_events = project_a_events.clone();
461 move |_, cx| {
462 cx.subscribe(&cx.handle(), move |_, _, event, _| {
463 project_a_events.borrow_mut().push(event.clone());
464 })
465 .detach();
466 }
467 });
468
469 // Request to join that project as client B
470 let project_b = cx_b.spawn(|mut cx| {
471 let client = client_b.client.clone();
472 let user_store = client_b.user_store.clone();
473 let language_registry = client_b.language_registry.clone();
474 async move {
475 Project::remote(
476 project_id,
477 client,
478 user_store,
479 language_registry.clone(),
480 FakeFs::new(cx.background()),
481 &mut cx,
482 )
483 .await
484 }
485 });
486 deterministic.run_until_parked();
487 assert_eq!(
488 &*project_a_events.borrow(),
489 &[project::Event::ContactRequestedJoin(user_b.clone())]
490 );
491 project_a_events.borrow_mut().clear();
492
493 // Cancel the join request by leaving the project
494 client_b
495 .client
496 .send(proto::LeaveProject { project_id })
497 .unwrap();
498 drop(project_b);
499
500 deterministic.run_until_parked();
501 assert_eq!(
502 &*project_a_events.borrow(),
503 &[project::Event::ContactCancelledJoinRequest(user_b.clone())]
504 );
505}
506
507#[gpui::test(iterations = 10)]
508async fn test_propagate_saves_and_fs_changes(
509 cx_a: &mut TestAppContext,
510 cx_b: &mut TestAppContext,
511 cx_c: &mut TestAppContext,
512) {
513 cx_a.foreground().forbid_parking();
514 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
515 let mut client_a = server.create_client(cx_a, "user_a").await;
516 let mut client_b = server.create_client(cx_b, "user_b").await;
517 let mut client_c = server.create_client(cx_c, "user_c").await;
518 server
519 .make_contacts(vec![
520 (&client_a, cx_a),
521 (&client_b, cx_b),
522 (&client_c, cx_c),
523 ])
524 .await;
525
526 let fs = FakeFs::new(cx_a.background());
527 fs.insert_tree(
528 "/a",
529 json!({
530 "file1": "",
531 "file2": ""
532 }),
533 )
534 .await;
535
536 let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
537 let worktree_a = project_a.read_with(cx_a, |p, cx| p.worktrees(cx).next().unwrap());
538
539 // Join that worktree as clients B and C.
540 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
541 let project_c = client_c.build_remote_project(&project_a, cx_a, cx_c).await;
542 let worktree_b = project_b.read_with(cx_b, |p, cx| p.worktrees(cx).next().unwrap());
543 let worktree_c = project_c.read_with(cx_c, |p, cx| p.worktrees(cx).next().unwrap());
544
545 // Open and edit a buffer as both guests B and C.
546 let buffer_b = project_b
547 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
548 .await
549 .unwrap();
550 let buffer_c = project_c
551 .update(cx_c, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
552 .await
553 .unwrap();
554 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "i-am-b, ")], cx));
555 buffer_c.update(cx_c, |buf, cx| buf.edit([(0..0, "i-am-c, ")], cx));
556
557 // Open and edit that buffer as the host.
558 let buffer_a = project_a
559 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
560 .await
561 .unwrap();
562
563 buffer_a
564 .condition(cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
565 .await;
566 buffer_a.update(cx_a, |buf, cx| {
567 buf.edit([(buf.len()..buf.len(), "i-am-a")], cx)
568 });
569
570 // Wait for edits to propagate
571 buffer_a
572 .condition(cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
573 .await;
574 buffer_b
575 .condition(cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
576 .await;
577 buffer_c
578 .condition(cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
579 .await;
580
581 // Edit the buffer as the host and concurrently save as guest B.
582 let save_b = buffer_b.update(cx_b, |buf, cx| buf.save(cx));
583 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "hi-a, ")], cx));
584 save_b.await.unwrap();
585 assert_eq!(
586 fs.load("/a/file1".as_ref()).await.unwrap(),
587 "hi-a, i-am-c, i-am-b, i-am-a"
588 );
589 buffer_a.read_with(cx_a, |buf, _| assert!(!buf.is_dirty()));
590 buffer_b.read_with(cx_b, |buf, _| assert!(!buf.is_dirty()));
591 buffer_c.condition(cx_c, |buf, _| !buf.is_dirty()).await;
592
593 worktree_a.flush_fs_events(cx_a).await;
594
595 // Make changes on host's file system, see those changes on guest worktrees.
596 fs.rename(
597 "/a/file1".as_ref(),
598 "/a/file1-renamed".as_ref(),
599 Default::default(),
600 )
601 .await
602 .unwrap();
603
604 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref(), Default::default())
605 .await
606 .unwrap();
607 fs.insert_file(Path::new("/a/file4"), "4".into()).await;
608
609 worktree_a
610 .condition(&cx_a, |tree, _| {
611 tree.paths()
612 .map(|p| p.to_string_lossy())
613 .collect::<Vec<_>>()
614 == ["file1-renamed", "file3", "file4"]
615 })
616 .await;
617 worktree_b
618 .condition(&cx_b, |tree, _| {
619 tree.paths()
620 .map(|p| p.to_string_lossy())
621 .collect::<Vec<_>>()
622 == ["file1-renamed", "file3", "file4"]
623 })
624 .await;
625 worktree_c
626 .condition(&cx_c, |tree, _| {
627 tree.paths()
628 .map(|p| p.to_string_lossy())
629 .collect::<Vec<_>>()
630 == ["file1-renamed", "file3", "file4"]
631 })
632 .await;
633
634 // Ensure buffer files are updated as well.
635 buffer_a
636 .condition(&cx_a, |buf, _| {
637 buf.file().unwrap().path().to_str() == Some("file1-renamed")
638 })
639 .await;
640 buffer_b
641 .condition(&cx_b, |buf, _| {
642 buf.file().unwrap().path().to_str() == Some("file1-renamed")
643 })
644 .await;
645 buffer_c
646 .condition(&cx_c, |buf, _| {
647 buf.file().unwrap().path().to_str() == Some("file1-renamed")
648 })
649 .await;
650}
651
652#[gpui::test(iterations = 10)]
653async fn test_fs_operations(
654 executor: Arc<Deterministic>,
655 cx_a: &mut TestAppContext,
656 cx_b: &mut TestAppContext,
657) {
658 executor.forbid_parking();
659 let fs = FakeFs::new(cx_a.background());
660
661 // Connect to a server as 2 clients.
662 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
663 let mut client_a = server.create_client(cx_a, "user_a").await;
664 let mut client_b = server.create_client(cx_b, "user_b").await;
665 server
666 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
667 .await;
668
669 // Share a project as client A
670 fs.insert_tree(
671 "/dir",
672 json!({
673 "a.txt": "a-contents",
674 "b.txt": "b-contents",
675 }),
676 )
677 .await;
678
679 let (project_a, worktree_id) = client_a.build_local_project(fs, "/dir", cx_a).await;
680 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
681
682 let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
683 let worktree_b = project_b.read_with(cx_b, |project, cx| project.worktrees(cx).next().unwrap());
684
685 let entry = project_b
686 .update(cx_b, |project, cx| {
687 project
688 .create_entry((worktree_id, "c.txt"), false, cx)
689 .unwrap()
690 })
691 .await
692 .unwrap();
693 worktree_a.read_with(cx_a, |worktree, _| {
694 assert_eq!(
695 worktree
696 .paths()
697 .map(|p| p.to_string_lossy())
698 .collect::<Vec<_>>(),
699 ["a.txt", "b.txt", "c.txt"]
700 );
701 });
702 worktree_b.read_with(cx_b, |worktree, _| {
703 assert_eq!(
704 worktree
705 .paths()
706 .map(|p| p.to_string_lossy())
707 .collect::<Vec<_>>(),
708 ["a.txt", "b.txt", "c.txt"]
709 );
710 });
711
712 project_b
713 .update(cx_b, |project, cx| {
714 project.rename_entry(entry.id, Path::new("d.txt"), cx)
715 })
716 .unwrap()
717 .await
718 .unwrap();
719 worktree_a.read_with(cx_a, |worktree, _| {
720 assert_eq!(
721 worktree
722 .paths()
723 .map(|p| p.to_string_lossy())
724 .collect::<Vec<_>>(),
725 ["a.txt", "b.txt", "d.txt"]
726 );
727 });
728 worktree_b.read_with(cx_b, |worktree, _| {
729 assert_eq!(
730 worktree
731 .paths()
732 .map(|p| p.to_string_lossy())
733 .collect::<Vec<_>>(),
734 ["a.txt", "b.txt", "d.txt"]
735 );
736 });
737
738 let dir_entry = project_b
739 .update(cx_b, |project, cx| {
740 project
741 .create_entry((worktree_id, "DIR"), true, cx)
742 .unwrap()
743 })
744 .await
745 .unwrap();
746 worktree_a.read_with(cx_a, |worktree, _| {
747 assert_eq!(
748 worktree
749 .paths()
750 .map(|p| p.to_string_lossy())
751 .collect::<Vec<_>>(),
752 ["DIR", "a.txt", "b.txt", "d.txt"]
753 );
754 });
755 worktree_b.read_with(cx_b, |worktree, _| {
756 assert_eq!(
757 worktree
758 .paths()
759 .map(|p| p.to_string_lossy())
760 .collect::<Vec<_>>(),
761 ["DIR", "a.txt", "b.txt", "d.txt"]
762 );
763 });
764
765 project_b
766 .update(cx_b, |project, cx| {
767 project
768 .create_entry((worktree_id, "DIR/e.txt"), false, cx)
769 .unwrap()
770 })
771 .await
772 .unwrap();
773 project_b
774 .update(cx_b, |project, cx| {
775 project
776 .create_entry((worktree_id, "DIR/SUBDIR"), true, cx)
777 .unwrap()
778 })
779 .await
780 .unwrap();
781 project_b
782 .update(cx_b, |project, cx| {
783 project
784 .create_entry((worktree_id, "DIR/SUBDIR/f.txt"), false, cx)
785 .unwrap()
786 })
787 .await
788 .unwrap();
789 worktree_a.read_with(cx_a, |worktree, _| {
790 assert_eq!(
791 worktree
792 .paths()
793 .map(|p| p.to_string_lossy())
794 .collect::<Vec<_>>(),
795 [
796 "DIR",
797 "DIR/SUBDIR",
798 "DIR/SUBDIR/f.txt",
799 "DIR/e.txt",
800 "a.txt",
801 "b.txt",
802 "d.txt"
803 ]
804 );
805 });
806 worktree_b.read_with(cx_b, |worktree, _| {
807 assert_eq!(
808 worktree
809 .paths()
810 .map(|p| p.to_string_lossy())
811 .collect::<Vec<_>>(),
812 [
813 "DIR",
814 "DIR/SUBDIR",
815 "DIR/SUBDIR/f.txt",
816 "DIR/e.txt",
817 "a.txt",
818 "b.txt",
819 "d.txt"
820 ]
821 );
822 });
823
824 project_b
825 .update(cx_b, |project, cx| {
826 project
827 .copy_entry(dir_entry.id, Path::new("DIR2"), cx)
828 .unwrap()
829 })
830 .await
831 .unwrap();
832 worktree_a.read_with(cx_a, |worktree, _| {
833 assert_eq!(
834 worktree
835 .paths()
836 .map(|p| p.to_string_lossy())
837 .collect::<Vec<_>>(),
838 [
839 "DIR",
840 "DIR/SUBDIR",
841 "DIR/SUBDIR/f.txt",
842 "DIR/e.txt",
843 "DIR2",
844 "DIR2/SUBDIR",
845 "DIR2/SUBDIR/f.txt",
846 "DIR2/e.txt",
847 "a.txt",
848 "b.txt",
849 "d.txt"
850 ]
851 );
852 });
853 worktree_b.read_with(cx_b, |worktree, _| {
854 assert_eq!(
855 worktree
856 .paths()
857 .map(|p| p.to_string_lossy())
858 .collect::<Vec<_>>(),
859 [
860 "DIR",
861 "DIR/SUBDIR",
862 "DIR/SUBDIR/f.txt",
863 "DIR/e.txt",
864 "DIR2",
865 "DIR2/SUBDIR",
866 "DIR2/SUBDIR/f.txt",
867 "DIR2/e.txt",
868 "a.txt",
869 "b.txt",
870 "d.txt"
871 ]
872 );
873 });
874
875 project_b
876 .update(cx_b, |project, cx| {
877 project.delete_entry(dir_entry.id, cx).unwrap()
878 })
879 .await
880 .unwrap();
881 worktree_a.read_with(cx_a, |worktree, _| {
882 assert_eq!(
883 worktree
884 .paths()
885 .map(|p| p.to_string_lossy())
886 .collect::<Vec<_>>(),
887 [
888 "DIR2",
889 "DIR2/SUBDIR",
890 "DIR2/SUBDIR/f.txt",
891 "DIR2/e.txt",
892 "a.txt",
893 "b.txt",
894 "d.txt"
895 ]
896 );
897 });
898 worktree_b.read_with(cx_b, |worktree, _| {
899 assert_eq!(
900 worktree
901 .paths()
902 .map(|p| p.to_string_lossy())
903 .collect::<Vec<_>>(),
904 [
905 "DIR2",
906 "DIR2/SUBDIR",
907 "DIR2/SUBDIR/f.txt",
908 "DIR2/e.txt",
909 "a.txt",
910 "b.txt",
911 "d.txt"
912 ]
913 );
914 });
915
916 project_b
917 .update(cx_b, |project, cx| {
918 project.delete_entry(entry.id, cx).unwrap()
919 })
920 .await
921 .unwrap();
922 worktree_a.read_with(cx_a, |worktree, _| {
923 assert_eq!(
924 worktree
925 .paths()
926 .map(|p| p.to_string_lossy())
927 .collect::<Vec<_>>(),
928 [
929 "DIR2",
930 "DIR2/SUBDIR",
931 "DIR2/SUBDIR/f.txt",
932 "DIR2/e.txt",
933 "a.txt",
934 "b.txt"
935 ]
936 );
937 });
938 worktree_b.read_with(cx_b, |worktree, _| {
939 assert_eq!(
940 worktree
941 .paths()
942 .map(|p| p.to_string_lossy())
943 .collect::<Vec<_>>(),
944 [
945 "DIR2",
946 "DIR2/SUBDIR",
947 "DIR2/SUBDIR/f.txt",
948 "DIR2/e.txt",
949 "a.txt",
950 "b.txt"
951 ]
952 );
953 });
954}
955
956#[gpui::test(iterations = 10)]
957async fn test_buffer_conflict_after_save(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
958 cx_a.foreground().forbid_parking();
959 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
960 let mut client_a = server.create_client(cx_a, "user_a").await;
961 let mut client_b = server.create_client(cx_b, "user_b").await;
962 server
963 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
964 .await;
965
966 let fs = FakeFs::new(cx_a.background());
967 fs.insert_tree(
968 "/dir",
969 json!({
970 "a.txt": "a-contents",
971 }),
972 )
973 .await;
974
975 let (project_a, worktree_id) = client_a.build_local_project(fs, "/dir", cx_a).await;
976 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
977
978 // Open a buffer as client B
979 let buffer_b = project_b
980 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
981 .await
982 .unwrap();
983
984 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "world ")], cx));
985 buffer_b.read_with(cx_b, |buf, _| {
986 assert!(buf.is_dirty());
987 assert!(!buf.has_conflict());
988 });
989
990 buffer_b.update(cx_b, |buf, cx| buf.save(cx)).await.unwrap();
991 buffer_b
992 .condition(&cx_b, |buffer_b, _| !buffer_b.is_dirty())
993 .await;
994 buffer_b.read_with(cx_b, |buf, _| {
995 assert!(!buf.has_conflict());
996 });
997
998 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "hello ")], cx));
999 buffer_b.read_with(cx_b, |buf, _| {
1000 assert!(buf.is_dirty());
1001 assert!(!buf.has_conflict());
1002 });
1003}
1004
1005#[gpui::test(iterations = 10)]
1006async fn test_buffer_reloading(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1007 cx_a.foreground().forbid_parking();
1008 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1009 let mut client_a = server.create_client(cx_a, "user_a").await;
1010 let mut client_b = server.create_client(cx_b, "user_b").await;
1011 server
1012 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1013 .await;
1014
1015 let fs = FakeFs::new(cx_a.background());
1016 fs.insert_tree(
1017 "/dir",
1018 json!({
1019 "a.txt": "a-contents",
1020 }),
1021 )
1022 .await;
1023
1024 let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/dir", cx_a).await;
1025 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1026
1027 // Open a buffer as client B
1028 let buffer_b = project_b
1029 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1030 .await
1031 .unwrap();
1032 buffer_b.read_with(cx_b, |buf, _| {
1033 assert!(!buf.is_dirty());
1034 assert!(!buf.has_conflict());
1035 });
1036
1037 fs.save(Path::new("/dir/a.txt"), &"new contents".into())
1038 .await
1039 .unwrap();
1040 buffer_b
1041 .condition(&cx_b, |buf, _| {
1042 buf.text() == "new contents" && !buf.is_dirty()
1043 })
1044 .await;
1045 buffer_b.read_with(cx_b, |buf, _| {
1046 assert!(!buf.has_conflict());
1047 });
1048}
1049
1050#[gpui::test(iterations = 10)]
1051async fn test_editing_while_guest_opens_buffer(
1052 cx_a: &mut TestAppContext,
1053 cx_b: &mut TestAppContext,
1054) {
1055 cx_a.foreground().forbid_parking();
1056 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1057 let mut client_a = server.create_client(cx_a, "user_a").await;
1058 let mut client_b = server.create_client(cx_b, "user_b").await;
1059 server
1060 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1061 .await;
1062
1063 let fs = FakeFs::new(cx_a.background());
1064 fs.insert_tree(
1065 "/dir",
1066 json!({
1067 "a.txt": "a-contents",
1068 }),
1069 )
1070 .await;
1071
1072 let (project_a, worktree_id) = client_a.build_local_project(fs, "/dir", cx_a).await;
1073 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1074
1075 // Open a buffer as client A
1076 let buffer_a = project_a
1077 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1078 .await
1079 .unwrap();
1080
1081 // Start opening the same buffer as client B
1082 let buffer_b = cx_b
1083 .background()
1084 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1085
1086 // Edit the buffer as client A while client B is still opening it.
1087 cx_b.background().simulate_random_delay().await;
1088 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "X")], cx));
1089 cx_b.background().simulate_random_delay().await;
1090 buffer_a.update(cx_a, |buf, cx| buf.edit([(1..1, "Y")], cx));
1091
1092 let text = buffer_a.read_with(cx_a, |buf, _| buf.text());
1093 let buffer_b = buffer_b.await.unwrap();
1094 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1095}
1096
1097#[gpui::test(iterations = 10)]
1098async fn test_leaving_worktree_while_opening_buffer(
1099 cx_a: &mut TestAppContext,
1100 cx_b: &mut TestAppContext,
1101) {
1102 cx_a.foreground().forbid_parking();
1103 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1104 let mut client_a = server.create_client(cx_a, "user_a").await;
1105 let mut client_b = server.create_client(cx_b, "user_b").await;
1106 server
1107 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1108 .await;
1109
1110 let fs = FakeFs::new(cx_a.background());
1111 fs.insert_tree(
1112 "/dir",
1113 json!({
1114 "a.txt": "a-contents",
1115 }),
1116 )
1117 .await;
1118
1119 let (project_a, worktree_id) = client_a.build_local_project(fs, "/dir", cx_a).await;
1120 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1121
1122 // See that a guest has joined as client A.
1123 project_a
1124 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1125 .await;
1126
1127 // Begin opening a buffer as client B, but leave the project before the open completes.
1128 let buffer_b = cx_b
1129 .background()
1130 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1131 cx_b.update(|_| {
1132 drop(client_b.project.take());
1133 drop(project_b);
1134 });
1135 drop(buffer_b);
1136
1137 // See that the guest has left.
1138 project_a
1139 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1140 .await;
1141}
1142
1143#[gpui::test(iterations = 10)]
1144async fn test_leaving_project(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1145 cx_a.foreground().forbid_parking();
1146 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1147 let mut client_a = server.create_client(cx_a, "user_a").await;
1148 let mut client_b = server.create_client(cx_b, "user_b").await;
1149 server
1150 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1151 .await;
1152
1153 let fs = FakeFs::new(cx_a.background());
1154 fs.insert_tree(
1155 "/a",
1156 json!({
1157 "a.txt": "a-contents",
1158 "b.txt": "b-contents",
1159 }),
1160 )
1161 .await;
1162
1163 let (project_a, _) = client_a.build_local_project(fs, "/a", cx_a).await;
1164 let _project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1165
1166 // Client A sees that a guest has joined.
1167 project_a
1168 .condition(cx_a, |p, _| p.collaborators().len() == 1)
1169 .await;
1170
1171 // Drop client B's connection and ensure client A observes client B leaving the project.
1172 client_b.disconnect(&cx_b.to_async()).unwrap();
1173 project_a
1174 .condition(cx_a, |p, _| p.collaborators().len() == 0)
1175 .await;
1176
1177 // Rejoin the project as client B
1178 let _project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1179
1180 // Client A sees that a guest has re-joined.
1181 project_a
1182 .condition(cx_a, |p, _| p.collaborators().len() == 1)
1183 .await;
1184
1185 // Simulate connection loss for client B and ensure client A observes client B leaving the project.
1186 client_b.wait_for_current_user(cx_b).await;
1187 server.disconnect_client(client_b.current_user_id(cx_b));
1188 cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
1189 project_a
1190 .condition(cx_a, |p, _| p.collaborators().len() == 0)
1191 .await;
1192}
1193
1194#[gpui::test(iterations = 10)]
1195async fn test_collaborating_with_diagnostics(
1196 deterministic: Arc<Deterministic>,
1197 cx_a: &mut TestAppContext,
1198 cx_b: &mut TestAppContext,
1199 cx_c: &mut TestAppContext,
1200) {
1201 deterministic.forbid_parking();
1202 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1203 let mut client_a = server.create_client(cx_a, "user_a").await;
1204 let mut client_b = server.create_client(cx_b, "user_b").await;
1205 let mut client_c = server.create_client(cx_c, "user_c").await;
1206 server
1207 .make_contacts(vec![
1208 (&client_a, cx_a),
1209 (&client_b, cx_b),
1210 (&client_c, cx_c),
1211 ])
1212 .await;
1213
1214 // Set up a fake language server.
1215 let mut language = Language::new(
1216 LanguageConfig {
1217 name: "Rust".into(),
1218 path_suffixes: vec!["rs".to_string()],
1219 ..Default::default()
1220 },
1221 Some(tree_sitter_rust::language()),
1222 );
1223 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
1224 client_a.language_registry.add(Arc::new(language));
1225
1226 // Connect to a server as 2 clients.
1227
1228 // Share a project as client A
1229 let fs = FakeFs::new(cx_a.background());
1230 fs.insert_tree(
1231 "/a",
1232 json!({
1233 "a.rs": "let one = two",
1234 "other.rs": "",
1235 }),
1236 )
1237 .await;
1238 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
1239 let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1240
1241 // Cause the language server to start.
1242 let _buffer = cx_a
1243 .background()
1244 .spawn(project_a.update(cx_a, |project, cx| {
1245 project.open_buffer(
1246 ProjectPath {
1247 worktree_id,
1248 path: Path::new("other.rs").into(),
1249 },
1250 cx,
1251 )
1252 }))
1253 .await
1254 .unwrap();
1255
1256 // Join the worktree as client B.
1257 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1258
1259 // Simulate a language server reporting errors for a file.
1260 let mut fake_language_server = fake_language_servers.next().await.unwrap();
1261 fake_language_server
1262 .receive_notification::<lsp::notification::DidOpenTextDocument>()
1263 .await;
1264 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
1265 lsp::PublishDiagnosticsParams {
1266 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1267 version: None,
1268 diagnostics: vec![lsp::Diagnostic {
1269 severity: Some(lsp::DiagnosticSeverity::ERROR),
1270 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1271 message: "message 1".to_string(),
1272 ..Default::default()
1273 }],
1274 },
1275 );
1276
1277 // Wait for server to see the diagnostics update.
1278 deterministic.run_until_parked();
1279 {
1280 let store = server.store.read().await;
1281 let project = store.project(project_id).unwrap();
1282 let worktree = project.worktrees.get(&worktree_id.to_proto()).unwrap();
1283 assert!(!worktree.diagnostic_summaries.is_empty());
1284 }
1285
1286 // Ensure client B observes the new diagnostics.
1287 project_b.read_with(cx_b, |project, cx| {
1288 assert_eq!(
1289 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1290 &[(
1291 ProjectPath {
1292 worktree_id,
1293 path: Arc::from(Path::new("a.rs")),
1294 },
1295 DiagnosticSummary {
1296 error_count: 1,
1297 warning_count: 0,
1298 ..Default::default()
1299 },
1300 )]
1301 )
1302 });
1303
1304 // Join project as client C and observe the diagnostics.
1305 let project_c = client_c.build_remote_project(&project_a, cx_a, cx_c).await;
1306 project_c.read_with(cx_c, |project, cx| {
1307 assert_eq!(
1308 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1309 &[(
1310 ProjectPath {
1311 worktree_id,
1312 path: Arc::from(Path::new("a.rs")),
1313 },
1314 DiagnosticSummary {
1315 error_count: 1,
1316 warning_count: 0,
1317 ..Default::default()
1318 },
1319 )]
1320 )
1321 });
1322
1323 // Simulate a language server reporting more errors for a file.
1324 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
1325 lsp::PublishDiagnosticsParams {
1326 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1327 version: None,
1328 diagnostics: vec![
1329 lsp::Diagnostic {
1330 severity: Some(lsp::DiagnosticSeverity::ERROR),
1331 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1332 message: "message 1".to_string(),
1333 ..Default::default()
1334 },
1335 lsp::Diagnostic {
1336 severity: Some(lsp::DiagnosticSeverity::WARNING),
1337 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 13)),
1338 message: "message 2".to_string(),
1339 ..Default::default()
1340 },
1341 ],
1342 },
1343 );
1344
1345 // Clients B and C get the updated summaries
1346 deterministic.run_until_parked();
1347 project_b.read_with(cx_b, |project, cx| {
1348 assert_eq!(
1349 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1350 [(
1351 ProjectPath {
1352 worktree_id,
1353 path: Arc::from(Path::new("a.rs")),
1354 },
1355 DiagnosticSummary {
1356 error_count: 1,
1357 warning_count: 1,
1358 ..Default::default()
1359 },
1360 )]
1361 );
1362 });
1363 project_c.read_with(cx_c, |project, cx| {
1364 assert_eq!(
1365 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1366 [(
1367 ProjectPath {
1368 worktree_id,
1369 path: Arc::from(Path::new("a.rs")),
1370 },
1371 DiagnosticSummary {
1372 error_count: 1,
1373 warning_count: 1,
1374 ..Default::default()
1375 },
1376 )]
1377 );
1378 });
1379
1380 // Open the file with the errors on client B. They should be present.
1381 let buffer_b = cx_b
1382 .background()
1383 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
1384 .await
1385 .unwrap();
1386
1387 buffer_b.read_with(cx_b, |buffer, _| {
1388 assert_eq!(
1389 buffer
1390 .snapshot()
1391 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
1392 .map(|entry| entry)
1393 .collect::<Vec<_>>(),
1394 &[
1395 DiagnosticEntry {
1396 range: Point::new(0, 4)..Point::new(0, 7),
1397 diagnostic: Diagnostic {
1398 group_id: 0,
1399 message: "message 1".to_string(),
1400 severity: lsp::DiagnosticSeverity::ERROR,
1401 is_primary: true,
1402 ..Default::default()
1403 }
1404 },
1405 DiagnosticEntry {
1406 range: Point::new(0, 10)..Point::new(0, 13),
1407 diagnostic: Diagnostic {
1408 group_id: 1,
1409 severity: lsp::DiagnosticSeverity::WARNING,
1410 message: "message 2".to_string(),
1411 is_primary: true,
1412 ..Default::default()
1413 }
1414 }
1415 ]
1416 );
1417 });
1418
1419 // Simulate a language server reporting no errors for a file.
1420 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
1421 lsp::PublishDiagnosticsParams {
1422 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1423 version: None,
1424 diagnostics: vec![],
1425 },
1426 );
1427 deterministic.run_until_parked();
1428 project_a.read_with(cx_a, |project, cx| {
1429 assert_eq!(project.diagnostic_summaries(cx).collect::<Vec<_>>(), [])
1430 });
1431 project_b.read_with(cx_b, |project, cx| {
1432 assert_eq!(project.diagnostic_summaries(cx).collect::<Vec<_>>(), [])
1433 });
1434 project_c.read_with(cx_c, |project, cx| {
1435 assert_eq!(project.diagnostic_summaries(cx).collect::<Vec<_>>(), [])
1436 });
1437}
1438
1439#[gpui::test(iterations = 10)]
1440async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1441 cx_a.foreground().forbid_parking();
1442 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1443 let mut client_a = server.create_client(cx_a, "user_a").await;
1444 let mut client_b = server.create_client(cx_b, "user_b").await;
1445 server
1446 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1447 .await;
1448
1449 // Set up a fake language server.
1450 let mut language = Language::new(
1451 LanguageConfig {
1452 name: "Rust".into(),
1453 path_suffixes: vec!["rs".to_string()],
1454 ..Default::default()
1455 },
1456 Some(tree_sitter_rust::language()),
1457 );
1458 let mut fake_language_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
1459 capabilities: lsp::ServerCapabilities {
1460 completion_provider: Some(lsp::CompletionOptions {
1461 trigger_characters: Some(vec![".".to_string()]),
1462 ..Default::default()
1463 }),
1464 ..Default::default()
1465 },
1466 ..Default::default()
1467 });
1468 client_a.language_registry.add(Arc::new(language));
1469
1470 let fs = FakeFs::new(cx_a.background());
1471 fs.insert_tree(
1472 "/a",
1473 json!({
1474 "main.rs": "fn main() { a }",
1475 "other.rs": "",
1476 }),
1477 )
1478 .await;
1479
1480 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
1481 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1482
1483 // Open a file in an editor as the guest.
1484 let buffer_b = project_b
1485 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
1486 .await
1487 .unwrap();
1488 let (window_b, _) = cx_b.add_window(|_| EmptyView);
1489 let editor_b = cx_b.add_view(window_b, |cx| {
1490 Editor::for_buffer(buffer_b.clone(), Some(project_b.clone()), cx)
1491 });
1492
1493 let fake_language_server = fake_language_servers.next().await.unwrap();
1494 buffer_b
1495 .condition(&cx_b, |buffer, _| !buffer.completion_triggers().is_empty())
1496 .await;
1497
1498 // Type a completion trigger character as the guest.
1499 editor_b.update(cx_b, |editor, cx| {
1500 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1501 editor.handle_input(&Input(".".into()), cx);
1502 cx.focus(&editor_b);
1503 });
1504
1505 // Receive a completion request as the host's language server.
1506 // Return some completions from the host's language server.
1507 cx_a.foreground().start_waiting();
1508 fake_language_server
1509 .handle_request::<lsp::request::Completion, _, _>(|params, _| async move {
1510 assert_eq!(
1511 params.text_document_position.text_document.uri,
1512 lsp::Url::from_file_path("/a/main.rs").unwrap(),
1513 );
1514 assert_eq!(
1515 params.text_document_position.position,
1516 lsp::Position::new(0, 14),
1517 );
1518
1519 Ok(Some(lsp::CompletionResponse::Array(vec![
1520 lsp::CompletionItem {
1521 label: "first_method(…)".into(),
1522 detail: Some("fn(&mut self, B) -> C".into()),
1523 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1524 new_text: "first_method($1)".to_string(),
1525 range: lsp::Range::new(
1526 lsp::Position::new(0, 14),
1527 lsp::Position::new(0, 14),
1528 ),
1529 })),
1530 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1531 ..Default::default()
1532 },
1533 lsp::CompletionItem {
1534 label: "second_method(…)".into(),
1535 detail: Some("fn(&mut self, C) -> D<E>".into()),
1536 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1537 new_text: "second_method()".to_string(),
1538 range: lsp::Range::new(
1539 lsp::Position::new(0, 14),
1540 lsp::Position::new(0, 14),
1541 ),
1542 })),
1543 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1544 ..Default::default()
1545 },
1546 ])))
1547 })
1548 .next()
1549 .await
1550 .unwrap();
1551 cx_a.foreground().finish_waiting();
1552
1553 // Open the buffer on the host.
1554 let buffer_a = project_a
1555 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
1556 .await
1557 .unwrap();
1558 buffer_a
1559 .condition(&cx_a, |buffer, _| buffer.text() == "fn main() { a. }")
1560 .await;
1561
1562 // Confirm a completion on the guest.
1563 editor_b
1564 .condition(&cx_b, |editor, _| editor.context_menu_visible())
1565 .await;
1566 editor_b.update(cx_b, |editor, cx| {
1567 editor.confirm_completion(&ConfirmCompletion { item_ix: Some(0) }, cx);
1568 assert_eq!(editor.text(cx), "fn main() { a.first_method() }");
1569 });
1570
1571 // Return a resolved completion from the host's language server.
1572 // The resolved completion has an additional text edit.
1573 fake_language_server.handle_request::<lsp::request::ResolveCompletionItem, _, _>(
1574 |params, _| async move {
1575 assert_eq!(params.label, "first_method(…)");
1576 Ok(lsp::CompletionItem {
1577 label: "first_method(…)".into(),
1578 detail: Some("fn(&mut self, B) -> C".into()),
1579 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1580 new_text: "first_method($1)".to_string(),
1581 range: lsp::Range::new(lsp::Position::new(0, 14), lsp::Position::new(0, 14)),
1582 })),
1583 additional_text_edits: Some(vec![lsp::TextEdit {
1584 new_text: "use d::SomeTrait;\n".to_string(),
1585 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
1586 }]),
1587 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1588 ..Default::default()
1589 })
1590 },
1591 );
1592
1593 // The additional edit is applied.
1594 buffer_a
1595 .condition(&cx_a, |buffer, _| {
1596 buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
1597 })
1598 .await;
1599 buffer_b
1600 .condition(&cx_b, |buffer, _| {
1601 buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
1602 })
1603 .await;
1604}
1605
1606#[gpui::test(iterations = 10)]
1607async fn test_reloading_buffer_manually(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1608 cx_a.foreground().forbid_parking();
1609 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1610 let mut client_a = server.create_client(cx_a, "user_a").await;
1611 let mut client_b = server.create_client(cx_b, "user_b").await;
1612 server
1613 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1614 .await;
1615
1616 let fs = FakeFs::new(cx_a.background());
1617 fs.insert_tree(
1618 "/a",
1619 json!({
1620 "a.rs": "let one = 1;",
1621 }),
1622 )
1623 .await;
1624
1625 let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
1626 let buffer_a = project_a
1627 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
1628 .await
1629 .unwrap();
1630
1631 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1632
1633 let buffer_b = cx_b
1634 .background()
1635 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
1636 .await
1637 .unwrap();
1638 buffer_b.update(cx_b, |buffer, cx| {
1639 buffer.edit([(4..7, "six")], cx);
1640 buffer.edit([(10..11, "6")], cx);
1641 assert_eq!(buffer.text(), "let six = 6;");
1642 assert!(buffer.is_dirty());
1643 assert!(!buffer.has_conflict());
1644 });
1645 buffer_a
1646 .condition(cx_a, |buffer, _| buffer.text() == "let six = 6;")
1647 .await;
1648
1649 fs.save(Path::new("/a/a.rs"), &Rope::from("let seven = 7;"))
1650 .await
1651 .unwrap();
1652 buffer_a
1653 .condition(cx_a, |buffer, _| buffer.has_conflict())
1654 .await;
1655 buffer_b
1656 .condition(cx_b, |buffer, _| buffer.has_conflict())
1657 .await;
1658
1659 project_b
1660 .update(cx_b, |project, cx| {
1661 project.reload_buffers(HashSet::from_iter([buffer_b.clone()]), true, cx)
1662 })
1663 .await
1664 .unwrap();
1665 buffer_a.read_with(cx_a, |buffer, _| {
1666 assert_eq!(buffer.text(), "let seven = 7;");
1667 assert!(!buffer.is_dirty());
1668 assert!(!buffer.has_conflict());
1669 });
1670 buffer_b.read_with(cx_b, |buffer, _| {
1671 assert_eq!(buffer.text(), "let seven = 7;");
1672 assert!(!buffer.is_dirty());
1673 assert!(!buffer.has_conflict());
1674 });
1675
1676 buffer_a.update(cx_a, |buffer, cx| {
1677 // Undoing on the host is a no-op when the reload was initiated by the guest.
1678 buffer.undo(cx);
1679 assert_eq!(buffer.text(), "let seven = 7;");
1680 assert!(!buffer.is_dirty());
1681 assert!(!buffer.has_conflict());
1682 });
1683 buffer_b.update(cx_b, |buffer, cx| {
1684 // Undoing on the guest rolls back the buffer to before it was reloaded but the conflict gets cleared.
1685 buffer.undo(cx);
1686 assert_eq!(buffer.text(), "let six = 6;");
1687 assert!(buffer.is_dirty());
1688 assert!(!buffer.has_conflict());
1689 });
1690}
1691
1692#[gpui::test(iterations = 10)]
1693async fn test_formatting_buffer(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1694 cx_a.foreground().forbid_parking();
1695 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1696 let mut client_a = server.create_client(cx_a, "user_a").await;
1697 let mut client_b = server.create_client(cx_b, "user_b").await;
1698 server
1699 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1700 .await;
1701
1702 // Set up a fake language server.
1703 let mut language = Language::new(
1704 LanguageConfig {
1705 name: "Rust".into(),
1706 path_suffixes: vec!["rs".to_string()],
1707 ..Default::default()
1708 },
1709 Some(tree_sitter_rust::language()),
1710 );
1711 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
1712 client_a.language_registry.add(Arc::new(language));
1713
1714 let fs = FakeFs::new(cx_a.background());
1715 fs.insert_tree(
1716 "/a",
1717 json!({
1718 "a.rs": "let one = two",
1719 }),
1720 )
1721 .await;
1722
1723 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
1724 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1725
1726 let buffer_b = cx_b
1727 .background()
1728 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
1729 .await
1730 .unwrap();
1731
1732 let fake_language_server = fake_language_servers.next().await.unwrap();
1733 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
1734 Ok(Some(vec![
1735 lsp::TextEdit {
1736 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
1737 new_text: "h".to_string(),
1738 },
1739 lsp::TextEdit {
1740 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
1741 new_text: "y".to_string(),
1742 },
1743 ]))
1744 });
1745
1746 project_b
1747 .update(cx_b, |project, cx| {
1748 project.format(HashSet::from_iter([buffer_b.clone()]), true, cx)
1749 })
1750 .await
1751 .unwrap();
1752 assert_eq!(
1753 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
1754 "let honey = two"
1755 );
1756}
1757
1758#[gpui::test(iterations = 10)]
1759async fn test_definition(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1760 cx_a.foreground().forbid_parking();
1761 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1762 let mut client_a = server.create_client(cx_a, "user_a").await;
1763 let mut client_b = server.create_client(cx_b, "user_b").await;
1764 server
1765 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1766 .await;
1767
1768 let fs = FakeFs::new(cx_a.background());
1769 fs.insert_tree(
1770 "/root-1",
1771 json!({
1772 "a.rs": "const ONE: usize = b::TWO + b::THREE;",
1773 }),
1774 )
1775 .await;
1776 fs.insert_tree(
1777 "/root-2",
1778 json!({
1779 "b.rs": "const TWO: usize = 2;\nconst THREE: usize = 3;",
1780 }),
1781 )
1782 .await;
1783
1784 // Set up a fake language server.
1785 let mut language = Language::new(
1786 LanguageConfig {
1787 name: "Rust".into(),
1788 path_suffixes: vec!["rs".to_string()],
1789 ..Default::default()
1790 },
1791 Some(tree_sitter_rust::language()),
1792 );
1793 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
1794 client_a.language_registry.add(Arc::new(language));
1795
1796 let (project_a, worktree_id) = client_a.build_local_project(fs, "/root-1", cx_a).await;
1797 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1798
1799 // Open the file on client B.
1800 let buffer_b = cx_b
1801 .background()
1802 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
1803 .await
1804 .unwrap();
1805
1806 // Request the definition of a symbol as the guest.
1807 let fake_language_server = fake_language_servers.next().await.unwrap();
1808 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
1809 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
1810 lsp::Location::new(
1811 lsp::Url::from_file_path("/root-2/b.rs").unwrap(),
1812 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
1813 ),
1814 )))
1815 });
1816
1817 let definitions_1 = project_b
1818 .update(cx_b, |p, cx| p.definition(&buffer_b, 23, cx))
1819 .await
1820 .unwrap();
1821 cx_b.read(|cx| {
1822 assert_eq!(definitions_1.len(), 1);
1823 assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
1824 let target_buffer = definitions_1[0].buffer.read(cx);
1825 assert_eq!(
1826 target_buffer.text(),
1827 "const TWO: usize = 2;\nconst THREE: usize = 3;"
1828 );
1829 assert_eq!(
1830 definitions_1[0].range.to_point(target_buffer),
1831 Point::new(0, 6)..Point::new(0, 9)
1832 );
1833 });
1834
1835 // Try getting more definitions for the same buffer, ensuring the buffer gets reused from
1836 // the previous call to `definition`.
1837 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
1838 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
1839 lsp::Location::new(
1840 lsp::Url::from_file_path("/root-2/b.rs").unwrap(),
1841 lsp::Range::new(lsp::Position::new(1, 6), lsp::Position::new(1, 11)),
1842 ),
1843 )))
1844 });
1845
1846 let definitions_2 = project_b
1847 .update(cx_b, |p, cx| p.definition(&buffer_b, 33, cx))
1848 .await
1849 .unwrap();
1850 cx_b.read(|cx| {
1851 assert_eq!(definitions_2.len(), 1);
1852 assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
1853 let target_buffer = definitions_2[0].buffer.read(cx);
1854 assert_eq!(
1855 target_buffer.text(),
1856 "const TWO: usize = 2;\nconst THREE: usize = 3;"
1857 );
1858 assert_eq!(
1859 definitions_2[0].range.to_point(target_buffer),
1860 Point::new(1, 6)..Point::new(1, 11)
1861 );
1862 });
1863 assert_eq!(definitions_1[0].buffer, definitions_2[0].buffer);
1864}
1865
1866#[gpui::test(iterations = 10)]
1867async fn test_references(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1868 cx_a.foreground().forbid_parking();
1869 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1870 let mut client_a = server.create_client(cx_a, "user_a").await;
1871 let mut client_b = server.create_client(cx_b, "user_b").await;
1872 server
1873 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1874 .await;
1875
1876 let fs = FakeFs::new(cx_a.background());
1877 fs.insert_tree(
1878 "/root-1",
1879 json!({
1880 "one.rs": "const ONE: usize = 1;",
1881 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1882 }),
1883 )
1884 .await;
1885 fs.insert_tree(
1886 "/root-2",
1887 json!({
1888 "three.rs": "const THREE: usize = two::TWO + one::ONE;",
1889 }),
1890 )
1891 .await;
1892
1893 // Set up a fake language server.
1894 let mut language = Language::new(
1895 LanguageConfig {
1896 name: "Rust".into(),
1897 path_suffixes: vec!["rs".to_string()],
1898 ..Default::default()
1899 },
1900 Some(tree_sitter_rust::language()),
1901 );
1902 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
1903 client_a.language_registry.add(Arc::new(language));
1904
1905 let (project_a, worktree_id) = client_a.build_local_project(fs, "/root-1", cx_a).await;
1906 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
1907
1908 // Open the file on client B.
1909 let buffer_b = cx_b
1910 .background()
1911 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
1912 .await
1913 .unwrap();
1914
1915 // Request references to a symbol as the guest.
1916 let fake_language_server = fake_language_servers.next().await.unwrap();
1917 fake_language_server.handle_request::<lsp::request::References, _, _>(|params, _| async move {
1918 assert_eq!(
1919 params.text_document_position.text_document.uri.as_str(),
1920 "file:///root-1/one.rs"
1921 );
1922 Ok(Some(vec![
1923 lsp::Location {
1924 uri: lsp::Url::from_file_path("/root-1/two.rs").unwrap(),
1925 range: lsp::Range::new(lsp::Position::new(0, 24), lsp::Position::new(0, 27)),
1926 },
1927 lsp::Location {
1928 uri: lsp::Url::from_file_path("/root-1/two.rs").unwrap(),
1929 range: lsp::Range::new(lsp::Position::new(0, 35), lsp::Position::new(0, 38)),
1930 },
1931 lsp::Location {
1932 uri: lsp::Url::from_file_path("/root-2/three.rs").unwrap(),
1933 range: lsp::Range::new(lsp::Position::new(0, 37), lsp::Position::new(0, 40)),
1934 },
1935 ]))
1936 });
1937
1938 let references = project_b
1939 .update(cx_b, |p, cx| p.references(&buffer_b, 7, cx))
1940 .await
1941 .unwrap();
1942 cx_b.read(|cx| {
1943 assert_eq!(references.len(), 3);
1944 assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
1945
1946 let two_buffer = references[0].buffer.read(cx);
1947 let three_buffer = references[2].buffer.read(cx);
1948 assert_eq!(
1949 two_buffer.file().unwrap().path().as_ref(),
1950 Path::new("two.rs")
1951 );
1952 assert_eq!(references[1].buffer, references[0].buffer);
1953 assert_eq!(
1954 three_buffer.file().unwrap().full_path(cx),
1955 Path::new("three.rs")
1956 );
1957
1958 assert_eq!(references[0].range.to_offset(&two_buffer), 24..27);
1959 assert_eq!(references[1].range.to_offset(&two_buffer), 35..38);
1960 assert_eq!(references[2].range.to_offset(&three_buffer), 37..40);
1961 });
1962}
1963
1964#[gpui::test(iterations = 10)]
1965async fn test_project_search(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1966 cx_a.foreground().forbid_parking();
1967 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1968 let mut client_a = server.create_client(cx_a, "user_a").await;
1969 let mut client_b = server.create_client(cx_b, "user_b").await;
1970 server
1971 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
1972 .await;
1973
1974 let fs = FakeFs::new(cx_a.background());
1975 fs.insert_tree(
1976 "/root-1",
1977 json!({
1978 "a": "hello world",
1979 "b": "goodnight moon",
1980 "c": "a world of goo",
1981 "d": "world champion of clown world",
1982 }),
1983 )
1984 .await;
1985 fs.insert_tree(
1986 "/root-2",
1987 json!({
1988 "e": "disney world is fun",
1989 }),
1990 )
1991 .await;
1992
1993 let (project_a, _) = client_a.build_local_project(fs, "/root-1", cx_a).await;
1994 let (worktree_2, _) = project_a
1995 .update(cx_a, |p, cx| {
1996 p.find_or_create_local_worktree("/root-2", true, cx)
1997 })
1998 .await
1999 .unwrap();
2000 worktree_2
2001 .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2002 .await;
2003
2004 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
2005
2006 // Perform a search as the guest.
2007 let results = project_b
2008 .update(cx_b, |project, cx| {
2009 project.search(SearchQuery::text("world", false, false), cx)
2010 })
2011 .await
2012 .unwrap();
2013
2014 let mut ranges_by_path = results
2015 .into_iter()
2016 .map(|(buffer, ranges)| {
2017 buffer.read_with(cx_b, |buffer, cx| {
2018 let path = buffer.file().unwrap().full_path(cx);
2019 let offset_ranges = ranges
2020 .into_iter()
2021 .map(|range| range.to_offset(buffer))
2022 .collect::<Vec<_>>();
2023 (path, offset_ranges)
2024 })
2025 })
2026 .collect::<Vec<_>>();
2027 ranges_by_path.sort_by_key(|(path, _)| path.clone());
2028
2029 assert_eq!(
2030 ranges_by_path,
2031 &[
2032 (PathBuf::from("root-1/a"), vec![6..11]),
2033 (PathBuf::from("root-1/c"), vec![2..7]),
2034 (PathBuf::from("root-1/d"), vec![0..5, 24..29]),
2035 (PathBuf::from("root-2/e"), vec![7..12]),
2036 ]
2037 );
2038}
2039
2040#[gpui::test(iterations = 10)]
2041async fn test_document_highlights(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2042 cx_a.foreground().forbid_parking();
2043 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2044 let mut client_a = server.create_client(cx_a, "user_a").await;
2045 let mut client_b = server.create_client(cx_b, "user_b").await;
2046 server
2047 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
2048 .await;
2049
2050 let fs = FakeFs::new(cx_a.background());
2051 fs.insert_tree(
2052 "/root-1",
2053 json!({
2054 "main.rs": "fn double(number: i32) -> i32 { number + number }",
2055 }),
2056 )
2057 .await;
2058
2059 // Set up a fake language server.
2060 let mut language = Language::new(
2061 LanguageConfig {
2062 name: "Rust".into(),
2063 path_suffixes: vec!["rs".to_string()],
2064 ..Default::default()
2065 },
2066 Some(tree_sitter_rust::language()),
2067 );
2068 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2069 client_a.language_registry.add(Arc::new(language));
2070
2071 let (project_a, worktree_id) = client_a.build_local_project(fs, "/root-1", cx_a).await;
2072 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
2073
2074 // Open the file on client B.
2075 let buffer_b = cx_b
2076 .background()
2077 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx)))
2078 .await
2079 .unwrap();
2080
2081 // Request document highlights as the guest.
2082 let fake_language_server = fake_language_servers.next().await.unwrap();
2083 fake_language_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
2084 |params, _| async move {
2085 assert_eq!(
2086 params
2087 .text_document_position_params
2088 .text_document
2089 .uri
2090 .as_str(),
2091 "file:///root-1/main.rs"
2092 );
2093 assert_eq!(
2094 params.text_document_position_params.position,
2095 lsp::Position::new(0, 34)
2096 );
2097 Ok(Some(vec![
2098 lsp::DocumentHighlight {
2099 kind: Some(lsp::DocumentHighlightKind::WRITE),
2100 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 16)),
2101 },
2102 lsp::DocumentHighlight {
2103 kind: Some(lsp::DocumentHighlightKind::READ),
2104 range: lsp::Range::new(lsp::Position::new(0, 32), lsp::Position::new(0, 38)),
2105 },
2106 lsp::DocumentHighlight {
2107 kind: Some(lsp::DocumentHighlightKind::READ),
2108 range: lsp::Range::new(lsp::Position::new(0, 41), lsp::Position::new(0, 47)),
2109 },
2110 ]))
2111 },
2112 );
2113
2114 let highlights = project_b
2115 .update(cx_b, |p, cx| p.document_highlights(&buffer_b, 34, cx))
2116 .await
2117 .unwrap();
2118 buffer_b.read_with(cx_b, |buffer, _| {
2119 let snapshot = buffer.snapshot();
2120
2121 let highlights = highlights
2122 .into_iter()
2123 .map(|highlight| (highlight.kind, highlight.range.to_offset(&snapshot)))
2124 .collect::<Vec<_>>();
2125 assert_eq!(
2126 highlights,
2127 &[
2128 (lsp::DocumentHighlightKind::WRITE, 10..16),
2129 (lsp::DocumentHighlightKind::READ, 32..38),
2130 (lsp::DocumentHighlightKind::READ, 41..47)
2131 ]
2132 )
2133 });
2134}
2135
2136#[gpui::test(iterations = 10)]
2137async fn test_project_symbols(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2138 cx_a.foreground().forbid_parking();
2139 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2140 let mut client_a = server.create_client(cx_a, "user_a").await;
2141 let mut client_b = server.create_client(cx_b, "user_b").await;
2142 server
2143 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
2144 .await;
2145
2146 // Set up a fake language server.
2147 let mut language = Language::new(
2148 LanguageConfig {
2149 name: "Rust".into(),
2150 path_suffixes: vec!["rs".to_string()],
2151 ..Default::default()
2152 },
2153 Some(tree_sitter_rust::language()),
2154 );
2155 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2156 client_a.language_registry.add(Arc::new(language));
2157
2158 let fs = FakeFs::new(cx_a.background());
2159 fs.insert_tree(
2160 "/code",
2161 json!({
2162 "crate-1": {
2163 "one.rs": "const ONE: usize = 1;",
2164 },
2165 "crate-2": {
2166 "two.rs": "const TWO: usize = 2; const THREE: usize = 3;",
2167 },
2168 "private": {
2169 "passwords.txt": "the-password",
2170 }
2171 }),
2172 )
2173 .await;
2174
2175 let (project_a, worktree_id) = client_a
2176 .build_local_project(fs, "/code/crate-1", cx_a)
2177 .await;
2178 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
2179
2180 // Cause the language server to start.
2181 let _buffer = cx_b
2182 .background()
2183 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
2184 .await
2185 .unwrap();
2186
2187 let fake_language_server = fake_language_servers.next().await.unwrap();
2188 fake_language_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(|_, _| async move {
2189 #[allow(deprecated)]
2190 Ok(Some(vec![lsp::SymbolInformation {
2191 name: "TWO".into(),
2192 location: lsp::Location {
2193 uri: lsp::Url::from_file_path("/code/crate-2/two.rs").unwrap(),
2194 range: lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2195 },
2196 kind: lsp::SymbolKind::CONSTANT,
2197 tags: None,
2198 container_name: None,
2199 deprecated: None,
2200 }]))
2201 });
2202
2203 // Request the definition of a symbol as the guest.
2204 let symbols = project_b
2205 .update(cx_b, |p, cx| p.symbols("two", cx))
2206 .await
2207 .unwrap();
2208 assert_eq!(symbols.len(), 1);
2209 assert_eq!(symbols[0].name, "TWO");
2210
2211 // Open one of the returned symbols.
2212 let buffer_b_2 = project_b
2213 .update(cx_b, |project, cx| {
2214 project.open_buffer_for_symbol(&symbols[0], cx)
2215 })
2216 .await
2217 .unwrap();
2218 buffer_b_2.read_with(cx_b, |buffer, _| {
2219 assert_eq!(
2220 buffer.file().unwrap().path().as_ref(),
2221 Path::new("../crate-2/two.rs")
2222 );
2223 });
2224
2225 // Attempt to craft a symbol and violate host's privacy by opening an arbitrary file.
2226 let mut fake_symbol = symbols[0].clone();
2227 fake_symbol.path = Path::new("/code/secrets").into();
2228 let error = project_b
2229 .update(cx_b, |project, cx| {
2230 project.open_buffer_for_symbol(&fake_symbol, cx)
2231 })
2232 .await
2233 .unwrap_err();
2234 assert!(error.to_string().contains("invalid symbol signature"));
2235}
2236
2237#[gpui::test(iterations = 10)]
2238async fn test_open_buffer_while_getting_definition_pointing_to_it(
2239 cx_a: &mut TestAppContext,
2240 cx_b: &mut TestAppContext,
2241 mut rng: StdRng,
2242) {
2243 cx_a.foreground().forbid_parking();
2244 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2245 let mut client_a = server.create_client(cx_a, "user_a").await;
2246 let mut client_b = server.create_client(cx_b, "user_b").await;
2247 server
2248 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
2249 .await;
2250
2251 // Set up a fake language server.
2252 let mut language = Language::new(
2253 LanguageConfig {
2254 name: "Rust".into(),
2255 path_suffixes: vec!["rs".to_string()],
2256 ..Default::default()
2257 },
2258 Some(tree_sitter_rust::language()),
2259 );
2260 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2261 client_a.language_registry.add(Arc::new(language));
2262
2263 let fs = FakeFs::new(cx_a.background());
2264 fs.insert_tree(
2265 "/root",
2266 json!({
2267 "a.rs": "const ONE: usize = b::TWO;",
2268 "b.rs": "const TWO: usize = 2",
2269 }),
2270 )
2271 .await;
2272
2273 let (project_a, worktree_id) = client_a.build_local_project(fs, "/root", cx_a).await;
2274 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
2275
2276 let buffer_b1 = cx_b
2277 .background()
2278 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2279 .await
2280 .unwrap();
2281
2282 let fake_language_server = fake_language_servers.next().await.unwrap();
2283 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
2284 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2285 lsp::Location::new(
2286 lsp::Url::from_file_path("/root/b.rs").unwrap(),
2287 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2288 ),
2289 )))
2290 });
2291
2292 let definitions;
2293 let buffer_b2;
2294 if rng.gen() {
2295 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
2296 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
2297 } else {
2298 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
2299 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
2300 }
2301
2302 let buffer_b2 = buffer_b2.await.unwrap();
2303 let definitions = definitions.await.unwrap();
2304 assert_eq!(definitions.len(), 1);
2305 assert_eq!(definitions[0].buffer, buffer_b2);
2306}
2307
2308#[gpui::test(iterations = 10)]
2309async fn test_collaborating_with_code_actions(
2310 cx_a: &mut TestAppContext,
2311 cx_b: &mut TestAppContext,
2312) {
2313 cx_a.foreground().forbid_parking();
2314 cx_b.update(|cx| editor::init(cx));
2315 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2316 let mut client_a = server.create_client(cx_a, "user_a").await;
2317 let mut client_b = server.create_client(cx_b, "user_b").await;
2318 server
2319 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
2320 .await;
2321
2322 // Set up a fake language server.
2323 let mut language = Language::new(
2324 LanguageConfig {
2325 name: "Rust".into(),
2326 path_suffixes: vec!["rs".to_string()],
2327 ..Default::default()
2328 },
2329 Some(tree_sitter_rust::language()),
2330 );
2331 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2332 client_a.language_registry.add(Arc::new(language));
2333
2334 let fs = FakeFs::new(cx_a.background());
2335 fs.insert_tree(
2336 "/a",
2337 json!({
2338 "main.rs": "mod other;\nfn main() { let foo = other::foo(); }",
2339 "other.rs": "pub fn foo() -> usize { 4 }",
2340 }),
2341 )
2342 .await;
2343 let (project_a, worktree_id) = client_a.build_local_project(fs, "/a", cx_a).await;
2344
2345 // Join the project as client B.
2346 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
2347 let (_window_b, workspace_b) = cx_b.add_window(|cx| Workspace::new(project_b.clone(), cx));
2348 let editor_b = workspace_b
2349 .update(cx_b, |workspace, cx| {
2350 workspace.open_path((worktree_id, "main.rs"), true, cx)
2351 })
2352 .await
2353 .unwrap()
2354 .downcast::<Editor>()
2355 .unwrap();
2356
2357 let mut fake_language_server = fake_language_servers.next().await.unwrap();
2358 fake_language_server
2359 .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
2360 assert_eq!(
2361 params.text_document.uri,
2362 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2363 );
2364 assert_eq!(params.range.start, lsp::Position::new(0, 0));
2365 assert_eq!(params.range.end, lsp::Position::new(0, 0));
2366 Ok(None)
2367 })
2368 .next()
2369 .await;
2370
2371 // Move cursor to a location that contains code actions.
2372 editor_b.update(cx_b, |editor, cx| {
2373 editor.change_selections(None, cx, |s| {
2374 s.select_ranges([Point::new(1, 31)..Point::new(1, 31)])
2375 });
2376 cx.focus(&editor_b);
2377 });
2378
2379 fake_language_server
2380 .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
2381 assert_eq!(
2382 params.text_document.uri,
2383 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2384 );
2385 assert_eq!(params.range.start, lsp::Position::new(1, 31));
2386 assert_eq!(params.range.end, lsp::Position::new(1, 31));
2387
2388 Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
2389 lsp::CodeAction {
2390 title: "Inline into all callers".to_string(),
2391 edit: Some(lsp::WorkspaceEdit {
2392 changes: Some(
2393 [
2394 (
2395 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2396 vec![lsp::TextEdit::new(
2397 lsp::Range::new(
2398 lsp::Position::new(1, 22),
2399 lsp::Position::new(1, 34),
2400 ),
2401 "4".to_string(),
2402 )],
2403 ),
2404 (
2405 lsp::Url::from_file_path("/a/other.rs").unwrap(),
2406 vec![lsp::TextEdit::new(
2407 lsp::Range::new(
2408 lsp::Position::new(0, 0),
2409 lsp::Position::new(0, 27),
2410 ),
2411 "".to_string(),
2412 )],
2413 ),
2414 ]
2415 .into_iter()
2416 .collect(),
2417 ),
2418 ..Default::default()
2419 }),
2420 data: Some(json!({
2421 "codeActionParams": {
2422 "range": {
2423 "start": {"line": 1, "column": 31},
2424 "end": {"line": 1, "column": 31},
2425 }
2426 }
2427 })),
2428 ..Default::default()
2429 },
2430 )]))
2431 })
2432 .next()
2433 .await;
2434
2435 // Toggle code actions and wait for them to display.
2436 editor_b.update(cx_b, |editor, cx| {
2437 editor.toggle_code_actions(
2438 &ToggleCodeActions {
2439 deployed_from_indicator: false,
2440 },
2441 cx,
2442 );
2443 });
2444 editor_b
2445 .condition(&cx_b, |editor, _| editor.context_menu_visible())
2446 .await;
2447
2448 fake_language_server.remove_request_handler::<lsp::request::CodeActionRequest>();
2449
2450 // Confirming the code action will trigger a resolve request.
2451 let confirm_action = workspace_b
2452 .update(cx_b, |workspace, cx| {
2453 Editor::confirm_code_action(workspace, &ConfirmCodeAction { item_ix: Some(0) }, cx)
2454 })
2455 .unwrap();
2456 fake_language_server.handle_request::<lsp::request::CodeActionResolveRequest, _, _>(
2457 |_, _| async move {
2458 Ok(lsp::CodeAction {
2459 title: "Inline into all callers".to_string(),
2460 edit: Some(lsp::WorkspaceEdit {
2461 changes: Some(
2462 [
2463 (
2464 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2465 vec![lsp::TextEdit::new(
2466 lsp::Range::new(
2467 lsp::Position::new(1, 22),
2468 lsp::Position::new(1, 34),
2469 ),
2470 "4".to_string(),
2471 )],
2472 ),
2473 (
2474 lsp::Url::from_file_path("/a/other.rs").unwrap(),
2475 vec![lsp::TextEdit::new(
2476 lsp::Range::new(
2477 lsp::Position::new(0, 0),
2478 lsp::Position::new(0, 27),
2479 ),
2480 "".to_string(),
2481 )],
2482 ),
2483 ]
2484 .into_iter()
2485 .collect(),
2486 ),
2487 ..Default::default()
2488 }),
2489 ..Default::default()
2490 })
2491 },
2492 );
2493
2494 // After the action is confirmed, an editor containing both modified files is opened.
2495 confirm_action.await.unwrap();
2496 let code_action_editor = workspace_b.read_with(cx_b, |workspace, cx| {
2497 workspace
2498 .active_item(cx)
2499 .unwrap()
2500 .downcast::<Editor>()
2501 .unwrap()
2502 });
2503 code_action_editor.update(cx_b, |editor, cx| {
2504 assert_eq!(editor.text(cx), "mod other;\nfn main() { let foo = 4; }\n");
2505 editor.undo(&Undo, cx);
2506 assert_eq!(
2507 editor.text(cx),
2508 "mod other;\nfn main() { let foo = other::foo(); }\npub fn foo() -> usize { 4 }"
2509 );
2510 editor.redo(&Redo, cx);
2511 assert_eq!(editor.text(cx), "mod other;\nfn main() { let foo = 4; }\n");
2512 });
2513}
2514
2515#[gpui::test(iterations = 10)]
2516async fn test_collaborating_with_renames(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2517 cx_a.foreground().forbid_parking();
2518 cx_b.update(|cx| editor::init(cx));
2519 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2520 let mut client_a = server.create_client(cx_a, "user_a").await;
2521 let mut client_b = server.create_client(cx_b, "user_b").await;
2522 server
2523 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
2524 .await;
2525
2526 // Set up a fake language server.
2527 let mut language = Language::new(
2528 LanguageConfig {
2529 name: "Rust".into(),
2530 path_suffixes: vec!["rs".to_string()],
2531 ..Default::default()
2532 },
2533 Some(tree_sitter_rust::language()),
2534 );
2535 let mut fake_language_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
2536 capabilities: lsp::ServerCapabilities {
2537 rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
2538 prepare_provider: Some(true),
2539 work_done_progress_options: Default::default(),
2540 })),
2541 ..Default::default()
2542 },
2543 ..Default::default()
2544 });
2545 client_a.language_registry.add(Arc::new(language));
2546
2547 let fs = FakeFs::new(cx_a.background());
2548 fs.insert_tree(
2549 "/dir",
2550 json!({
2551 "one.rs": "const ONE: usize = 1;",
2552 "two.rs": "const TWO: usize = one::ONE + one::ONE;"
2553 }),
2554 )
2555 .await;
2556
2557 let (project_a, worktree_id) = client_a.build_local_project(fs, "/dir", cx_a).await;
2558 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
2559
2560 let (_window_b, workspace_b) = cx_b.add_window(|cx| Workspace::new(project_b.clone(), cx));
2561 let editor_b = workspace_b
2562 .update(cx_b, |workspace, cx| {
2563 workspace.open_path((worktree_id, "one.rs"), true, cx)
2564 })
2565 .await
2566 .unwrap()
2567 .downcast::<Editor>()
2568 .unwrap();
2569 let fake_language_server = fake_language_servers.next().await.unwrap();
2570
2571 // Move cursor to a location that can be renamed.
2572 let prepare_rename = editor_b.update(cx_b, |editor, cx| {
2573 editor.change_selections(None, cx, |s| s.select_ranges([7..7]));
2574 editor.rename(&Rename, cx).unwrap()
2575 });
2576
2577 fake_language_server
2578 .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
2579 assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
2580 assert_eq!(params.position, lsp::Position::new(0, 7));
2581 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
2582 lsp::Position::new(0, 6),
2583 lsp::Position::new(0, 9),
2584 ))))
2585 })
2586 .next()
2587 .await
2588 .unwrap();
2589 prepare_rename.await.unwrap();
2590 editor_b.update(cx_b, |editor, cx| {
2591 let rename = editor.pending_rename().unwrap();
2592 let buffer = editor.buffer().read(cx).snapshot(cx);
2593 assert_eq!(
2594 rename.range.start.to_offset(&buffer)..rename.range.end.to_offset(&buffer),
2595 6..9
2596 );
2597 rename.editor.update(cx, |rename_editor, cx| {
2598 rename_editor.buffer().update(cx, |rename_buffer, cx| {
2599 rename_buffer.edit([(0..3, "THREE")], cx);
2600 });
2601 });
2602 });
2603
2604 let confirm_rename = workspace_b.update(cx_b, |workspace, cx| {
2605 Editor::confirm_rename(workspace, &ConfirmRename, cx).unwrap()
2606 });
2607 fake_language_server
2608 .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
2609 assert_eq!(
2610 params.text_document_position.text_document.uri.as_str(),
2611 "file:///dir/one.rs"
2612 );
2613 assert_eq!(
2614 params.text_document_position.position,
2615 lsp::Position::new(0, 6)
2616 );
2617 assert_eq!(params.new_name, "THREE");
2618 Ok(Some(lsp::WorkspaceEdit {
2619 changes: Some(
2620 [
2621 (
2622 lsp::Url::from_file_path("/dir/one.rs").unwrap(),
2623 vec![lsp::TextEdit::new(
2624 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2625 "THREE".to_string(),
2626 )],
2627 ),
2628 (
2629 lsp::Url::from_file_path("/dir/two.rs").unwrap(),
2630 vec![
2631 lsp::TextEdit::new(
2632 lsp::Range::new(
2633 lsp::Position::new(0, 24),
2634 lsp::Position::new(0, 27),
2635 ),
2636 "THREE".to_string(),
2637 ),
2638 lsp::TextEdit::new(
2639 lsp::Range::new(
2640 lsp::Position::new(0, 35),
2641 lsp::Position::new(0, 38),
2642 ),
2643 "THREE".to_string(),
2644 ),
2645 ],
2646 ),
2647 ]
2648 .into_iter()
2649 .collect(),
2650 ),
2651 ..Default::default()
2652 }))
2653 })
2654 .next()
2655 .await
2656 .unwrap();
2657 confirm_rename.await.unwrap();
2658
2659 let rename_editor = workspace_b.read_with(cx_b, |workspace, cx| {
2660 workspace
2661 .active_item(cx)
2662 .unwrap()
2663 .downcast::<Editor>()
2664 .unwrap()
2665 });
2666 rename_editor.update(cx_b, |editor, cx| {
2667 assert_eq!(
2668 editor.text(cx),
2669 "const THREE: usize = 1;\nconst TWO: usize = one::THREE + one::THREE;"
2670 );
2671 editor.undo(&Undo, cx);
2672 assert_eq!(
2673 editor.text(cx),
2674 "const ONE: usize = 1;\nconst TWO: usize = one::ONE + one::ONE;"
2675 );
2676 editor.redo(&Redo, cx);
2677 assert_eq!(
2678 editor.text(cx),
2679 "const THREE: usize = 1;\nconst TWO: usize = one::THREE + one::THREE;"
2680 );
2681 });
2682
2683 // Ensure temporary rename edits cannot be undone/redone.
2684 editor_b.update(cx_b, |editor, cx| {
2685 editor.undo(&Undo, cx);
2686 assert_eq!(editor.text(cx), "const ONE: usize = 1;");
2687 editor.undo(&Undo, cx);
2688 assert_eq!(editor.text(cx), "const ONE: usize = 1;");
2689 editor.redo(&Redo, cx);
2690 assert_eq!(editor.text(cx), "const THREE: usize = 1;");
2691 })
2692}
2693
2694#[gpui::test(iterations = 10)]
2695async fn test_basic_chat(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2696 cx_a.foreground().forbid_parking();
2697 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2698 let client_a = server.create_client(cx_a, "user_a").await;
2699 let client_b = server.create_client(cx_b, "user_b").await;
2700
2701 // Create an org that includes these 2 users.
2702 let db = &server.app_state.db;
2703 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2704 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2705 .await
2706 .unwrap();
2707 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2708 .await
2709 .unwrap();
2710
2711 // Create a channel that includes all the users.
2712 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2713 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2714 .await
2715 .unwrap();
2716 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2717 .await
2718 .unwrap();
2719 db.create_channel_message(
2720 channel_id,
2721 client_b.current_user_id(&cx_b),
2722 "hello A, it's B.",
2723 OffsetDateTime::now_utc(),
2724 1,
2725 )
2726 .await
2727 .unwrap();
2728
2729 let channels_a =
2730 cx_a.add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2731 channels_a
2732 .condition(cx_a, |list, _| list.available_channels().is_some())
2733 .await;
2734 channels_a.read_with(cx_a, |list, _| {
2735 assert_eq!(
2736 list.available_channels().unwrap(),
2737 &[ChannelDetails {
2738 id: channel_id.to_proto(),
2739 name: "test-channel".to_string()
2740 }]
2741 )
2742 });
2743 let channel_a = channels_a.update(cx_a, |this, cx| {
2744 this.get_channel(channel_id.to_proto(), cx).unwrap()
2745 });
2746 channel_a.read_with(cx_a, |channel, _| assert!(channel.messages().is_empty()));
2747 channel_a
2748 .condition(&cx_a, |channel, _| {
2749 channel_messages(channel)
2750 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2751 })
2752 .await;
2753
2754 let channels_b =
2755 cx_b.add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2756 channels_b
2757 .condition(cx_b, |list, _| list.available_channels().is_some())
2758 .await;
2759 channels_b.read_with(cx_b, |list, _| {
2760 assert_eq!(
2761 list.available_channels().unwrap(),
2762 &[ChannelDetails {
2763 id: channel_id.to_proto(),
2764 name: "test-channel".to_string()
2765 }]
2766 )
2767 });
2768
2769 let channel_b = channels_b.update(cx_b, |this, cx| {
2770 this.get_channel(channel_id.to_proto(), cx).unwrap()
2771 });
2772 channel_b.read_with(cx_b, |channel, _| assert!(channel.messages().is_empty()));
2773 channel_b
2774 .condition(&cx_b, |channel, _| {
2775 channel_messages(channel)
2776 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2777 })
2778 .await;
2779
2780 channel_a
2781 .update(cx_a, |channel, cx| {
2782 channel
2783 .send_message("oh, hi B.".to_string(), cx)
2784 .unwrap()
2785 .detach();
2786 let task = channel.send_message("sup".to_string(), cx).unwrap();
2787 assert_eq!(
2788 channel_messages(channel),
2789 &[
2790 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2791 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2792 ("user_a".to_string(), "sup".to_string(), true)
2793 ]
2794 );
2795 task
2796 })
2797 .await
2798 .unwrap();
2799
2800 channel_b
2801 .condition(&cx_b, |channel, _| {
2802 channel_messages(channel)
2803 == [
2804 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2805 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2806 ("user_a".to_string(), "sup".to_string(), false),
2807 ]
2808 })
2809 .await;
2810
2811 assert_eq!(
2812 server
2813 .state()
2814 .await
2815 .channel(channel_id)
2816 .unwrap()
2817 .connection_ids
2818 .len(),
2819 2
2820 );
2821 cx_b.update(|_| drop(channel_b));
2822 server
2823 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2824 .await;
2825
2826 cx_a.update(|_| drop(channel_a));
2827 server
2828 .condition(|state| state.channel(channel_id).is_none())
2829 .await;
2830}
2831
2832#[gpui::test(iterations = 10)]
2833async fn test_chat_message_validation(cx_a: &mut TestAppContext) {
2834 cx_a.foreground().forbid_parking();
2835 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2836 let client_a = server.create_client(cx_a, "user_a").await;
2837
2838 let db = &server.app_state.db;
2839 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2840 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2841 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2842 .await
2843 .unwrap();
2844 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2845 .await
2846 .unwrap();
2847
2848 let channels_a =
2849 cx_a.add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2850 channels_a
2851 .condition(cx_a, |list, _| list.available_channels().is_some())
2852 .await;
2853 let channel_a = channels_a.update(cx_a, |this, cx| {
2854 this.get_channel(channel_id.to_proto(), cx).unwrap()
2855 });
2856
2857 // Messages aren't allowed to be too long.
2858 channel_a
2859 .update(cx_a, |channel, cx| {
2860 let long_body = "this is long.\n".repeat(1024);
2861 channel.send_message(long_body, cx).unwrap()
2862 })
2863 .await
2864 .unwrap_err();
2865
2866 // Messages aren't allowed to be blank.
2867 channel_a.update(cx_a, |channel, cx| {
2868 channel.send_message(String::new(), cx).unwrap_err()
2869 });
2870
2871 // Leading and trailing whitespace are trimmed.
2872 channel_a
2873 .update(cx_a, |channel, cx| {
2874 channel
2875 .send_message("\n surrounded by whitespace \n".to_string(), cx)
2876 .unwrap()
2877 })
2878 .await
2879 .unwrap();
2880 assert_eq!(
2881 db.get_channel_messages(channel_id, 10, None)
2882 .await
2883 .unwrap()
2884 .iter()
2885 .map(|m| &m.body)
2886 .collect::<Vec<_>>(),
2887 &["surrounded by whitespace"]
2888 );
2889}
2890
2891#[gpui::test(iterations = 10)]
2892async fn test_chat_reconnection(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2893 cx_a.foreground().forbid_parking();
2894 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2895 let client_a = server.create_client(cx_a, "user_a").await;
2896 let client_b = server.create_client(cx_b, "user_b").await;
2897
2898 let mut status_b = client_b.status();
2899
2900 // Create an org that includes these 2 users.
2901 let db = &server.app_state.db;
2902 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2903 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2904 .await
2905 .unwrap();
2906 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2907 .await
2908 .unwrap();
2909
2910 // Create a channel that includes all the users.
2911 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2912 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2913 .await
2914 .unwrap();
2915 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2916 .await
2917 .unwrap();
2918 db.create_channel_message(
2919 channel_id,
2920 client_b.current_user_id(&cx_b),
2921 "hello A, it's B.",
2922 OffsetDateTime::now_utc(),
2923 2,
2924 )
2925 .await
2926 .unwrap();
2927
2928 let channels_a =
2929 cx_a.add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2930 channels_a
2931 .condition(cx_a, |list, _| list.available_channels().is_some())
2932 .await;
2933
2934 channels_a.read_with(cx_a, |list, _| {
2935 assert_eq!(
2936 list.available_channels().unwrap(),
2937 &[ChannelDetails {
2938 id: channel_id.to_proto(),
2939 name: "test-channel".to_string()
2940 }]
2941 )
2942 });
2943 let channel_a = channels_a.update(cx_a, |this, cx| {
2944 this.get_channel(channel_id.to_proto(), cx).unwrap()
2945 });
2946 channel_a.read_with(cx_a, |channel, _| assert!(channel.messages().is_empty()));
2947 channel_a
2948 .condition(&cx_a, |channel, _| {
2949 channel_messages(channel)
2950 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2951 })
2952 .await;
2953
2954 let channels_b =
2955 cx_b.add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2956 channels_b
2957 .condition(cx_b, |list, _| list.available_channels().is_some())
2958 .await;
2959 channels_b.read_with(cx_b, |list, _| {
2960 assert_eq!(
2961 list.available_channels().unwrap(),
2962 &[ChannelDetails {
2963 id: channel_id.to_proto(),
2964 name: "test-channel".to_string()
2965 }]
2966 )
2967 });
2968
2969 let channel_b = channels_b.update(cx_b, |this, cx| {
2970 this.get_channel(channel_id.to_proto(), cx).unwrap()
2971 });
2972 channel_b.read_with(cx_b, |channel, _| assert!(channel.messages().is_empty()));
2973 channel_b
2974 .condition(&cx_b, |channel, _| {
2975 channel_messages(channel)
2976 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2977 })
2978 .await;
2979
2980 // Disconnect client B, ensuring we can still access its cached channel data.
2981 server.forbid_connections();
2982 server.disconnect_client(client_b.current_user_id(&cx_b));
2983 cx_b.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
2984 while !matches!(
2985 status_b.next().await,
2986 Some(client::Status::ReconnectionError { .. })
2987 ) {}
2988
2989 channels_b.read_with(cx_b, |channels, _| {
2990 assert_eq!(
2991 channels.available_channels().unwrap(),
2992 [ChannelDetails {
2993 id: channel_id.to_proto(),
2994 name: "test-channel".to_string()
2995 }]
2996 )
2997 });
2998 channel_b.read_with(cx_b, |channel, _| {
2999 assert_eq!(
3000 channel_messages(channel),
3001 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3002 )
3003 });
3004
3005 // Send a message from client B while it is disconnected.
3006 channel_b
3007 .update(cx_b, |channel, cx| {
3008 let task = channel
3009 .send_message("can you see this?".to_string(), cx)
3010 .unwrap();
3011 assert_eq!(
3012 channel_messages(channel),
3013 &[
3014 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3015 ("user_b".to_string(), "can you see this?".to_string(), true)
3016 ]
3017 );
3018 task
3019 })
3020 .await
3021 .unwrap_err();
3022
3023 // Send a message from client A while B is disconnected.
3024 channel_a
3025 .update(cx_a, |channel, cx| {
3026 channel
3027 .send_message("oh, hi B.".to_string(), cx)
3028 .unwrap()
3029 .detach();
3030 let task = channel.send_message("sup".to_string(), cx).unwrap();
3031 assert_eq!(
3032 channel_messages(channel),
3033 &[
3034 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3035 ("user_a".to_string(), "oh, hi B.".to_string(), true),
3036 ("user_a".to_string(), "sup".to_string(), true)
3037 ]
3038 );
3039 task
3040 })
3041 .await
3042 .unwrap();
3043
3044 // Give client B a chance to reconnect.
3045 server.allow_connections();
3046 cx_b.foreground().advance_clock(Duration::from_secs(10));
3047
3048 // Verify that B sees the new messages upon reconnection, as well as the message client B
3049 // sent while offline.
3050 channel_b
3051 .condition(&cx_b, |channel, _| {
3052 channel_messages(channel)
3053 == [
3054 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3055 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3056 ("user_a".to_string(), "sup".to_string(), false),
3057 ("user_b".to_string(), "can you see this?".to_string(), false),
3058 ]
3059 })
3060 .await;
3061
3062 // Ensure client A and B can communicate normally after reconnection.
3063 channel_a
3064 .update(cx_a, |channel, cx| {
3065 channel.send_message("you online?".to_string(), cx).unwrap()
3066 })
3067 .await
3068 .unwrap();
3069 channel_b
3070 .condition(&cx_b, |channel, _| {
3071 channel_messages(channel)
3072 == [
3073 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3074 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3075 ("user_a".to_string(), "sup".to_string(), false),
3076 ("user_b".to_string(), "can you see this?".to_string(), false),
3077 ("user_a".to_string(), "you online?".to_string(), false),
3078 ]
3079 })
3080 .await;
3081
3082 channel_b
3083 .update(cx_b, |channel, cx| {
3084 channel.send_message("yep".to_string(), cx).unwrap()
3085 })
3086 .await
3087 .unwrap();
3088 channel_a
3089 .condition(&cx_a, |channel, _| {
3090 channel_messages(channel)
3091 == [
3092 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3093 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3094 ("user_a".to_string(), "sup".to_string(), false),
3095 ("user_b".to_string(), "can you see this?".to_string(), false),
3096 ("user_a".to_string(), "you online?".to_string(), false),
3097 ("user_b".to_string(), "yep".to_string(), false),
3098 ]
3099 })
3100 .await;
3101}
3102
3103#[gpui::test(iterations = 10)]
3104async fn test_contacts(
3105 deterministic: Arc<Deterministic>,
3106 cx_a: &mut TestAppContext,
3107 cx_b: &mut TestAppContext,
3108 cx_c: &mut TestAppContext,
3109) {
3110 cx_a.foreground().forbid_parking();
3111 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3112 let mut client_a = server.create_client(cx_a, "user_a").await;
3113 let mut client_b = server.create_client(cx_b, "user_b").await;
3114 let client_c = server.create_client(cx_c, "user_c").await;
3115 server
3116 .make_contacts(vec![
3117 (&client_a, cx_a),
3118 (&client_b, cx_b),
3119 (&client_c, cx_c),
3120 ])
3121 .await;
3122
3123 deterministic.run_until_parked();
3124 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b), (&client_c, &cx_c)] {
3125 client.user_store.read_with(*cx, |store, _| {
3126 assert_eq!(
3127 contacts(store),
3128 [
3129 ("user_a", true, vec![]),
3130 ("user_b", true, vec![]),
3131 ("user_c", true, vec![])
3132 ],
3133 "{} has the wrong contacts",
3134 client.username
3135 )
3136 });
3137 }
3138
3139 // Share a project as client A.
3140 let fs = FakeFs::new(cx_a.background());
3141 fs.create_dir(Path::new("/a")).await.unwrap();
3142 let (project_a, _) = client_a.build_local_project(fs, "/a", cx_a).await;
3143
3144 deterministic.run_until_parked();
3145 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b), (&client_c, &cx_c)] {
3146 client.user_store.read_with(*cx, |store, _| {
3147 assert_eq!(
3148 contacts(store),
3149 [
3150 ("user_a", true, vec![("a", vec![])]),
3151 ("user_b", true, vec![]),
3152 ("user_c", true, vec![])
3153 ],
3154 "{} has the wrong contacts",
3155 client.username
3156 )
3157 });
3158 }
3159
3160 let _project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
3161
3162 deterministic.run_until_parked();
3163 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b), (&client_c, &cx_c)] {
3164 client.user_store.read_with(*cx, |store, _| {
3165 assert_eq!(
3166 contacts(store),
3167 [
3168 ("user_a", true, vec![("a", vec!["user_b"])]),
3169 ("user_b", true, vec![]),
3170 ("user_c", true, vec![])
3171 ],
3172 "{} has the wrong contacts",
3173 client.username
3174 )
3175 });
3176 }
3177
3178 // Add a local project as client B
3179 let fs = FakeFs::new(cx_b.background());
3180 fs.create_dir(Path::new("/b")).await.unwrap();
3181 let (_project_b, _) = client_b.build_local_project(fs, "/b", cx_a).await;
3182
3183 deterministic.run_until_parked();
3184 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b), (&client_c, &cx_c)] {
3185 client.user_store.read_with(*cx, |store, _| {
3186 assert_eq!(
3187 contacts(store),
3188 [
3189 ("user_a", true, vec![("a", vec!["user_b"])]),
3190 ("user_b", true, vec![("b", vec![])]),
3191 ("user_c", true, vec![])
3192 ],
3193 "{} has the wrong contacts",
3194 client.username
3195 )
3196 });
3197 }
3198
3199 project_a
3200 .condition(&cx_a, |project, _| {
3201 project.collaborators().contains_key(&client_b.peer_id)
3202 })
3203 .await;
3204
3205 client_a.project.take();
3206 cx_a.update(move |_| drop(project_a));
3207 deterministic.run_until_parked();
3208 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b), (&client_c, &cx_c)] {
3209 client.user_store.read_with(*cx, |store, _| {
3210 assert_eq!(
3211 contacts(store),
3212 [
3213 ("user_a", true, vec![]),
3214 ("user_b", true, vec![("b", vec![])]),
3215 ("user_c", true, vec![])
3216 ],
3217 "{} has the wrong contacts",
3218 client.username
3219 )
3220 });
3221 }
3222
3223 server.disconnect_client(client_c.current_user_id(cx_c));
3224 server.forbid_connections();
3225 deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
3226 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b)] {
3227 client.user_store.read_with(*cx, |store, _| {
3228 assert_eq!(
3229 contacts(store),
3230 [
3231 ("user_a", true, vec![]),
3232 ("user_b", true, vec![("b", vec![])]),
3233 ("user_c", false, vec![])
3234 ],
3235 "{} has the wrong contacts",
3236 client.username
3237 )
3238 });
3239 }
3240 client_c
3241 .user_store
3242 .read_with(cx_c, |store, _| assert_eq!(contacts(store), []));
3243
3244 server.allow_connections();
3245 client_c
3246 .authenticate_and_connect(false, &cx_c.to_async())
3247 .await
3248 .unwrap();
3249
3250 deterministic.run_until_parked();
3251 for (client, cx) in [(&client_a, &cx_a), (&client_b, &cx_b), (&client_c, &cx_c)] {
3252 client.user_store.read_with(*cx, |store, _| {
3253 assert_eq!(
3254 contacts(store),
3255 [
3256 ("user_a", true, vec![]),
3257 ("user_b", true, vec![("b", vec![])]),
3258 ("user_c", true, vec![])
3259 ],
3260 "{} has the wrong contacts",
3261 client.username
3262 )
3263 });
3264 }
3265
3266 fn contacts(user_store: &UserStore) -> Vec<(&str, bool, Vec<(&str, Vec<&str>)>)> {
3267 user_store
3268 .contacts()
3269 .iter()
3270 .map(|contact| {
3271 let projects = contact
3272 .projects
3273 .iter()
3274 .map(|p| {
3275 (
3276 p.worktree_root_names[0].as_str(),
3277 p.guests.iter().map(|p| p.github_login.as_str()).collect(),
3278 )
3279 })
3280 .collect();
3281 (contact.user.github_login.as_str(), contact.online, projects)
3282 })
3283 .collect()
3284 }
3285}
3286
3287#[gpui::test(iterations = 10)]
3288async fn test_contact_requests(
3289 executor: Arc<Deterministic>,
3290 cx_a: &mut TestAppContext,
3291 cx_a2: &mut TestAppContext,
3292 cx_b: &mut TestAppContext,
3293 cx_b2: &mut TestAppContext,
3294 cx_c: &mut TestAppContext,
3295 cx_c2: &mut TestAppContext,
3296) {
3297 cx_a.foreground().forbid_parking();
3298
3299 // Connect to a server as 3 clients.
3300 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3301 let client_a = server.create_client(cx_a, "user_a").await;
3302 let client_a2 = server.create_client(cx_a2, "user_a").await;
3303 let client_b = server.create_client(cx_b, "user_b").await;
3304 let client_b2 = server.create_client(cx_b2, "user_b").await;
3305 let client_c = server.create_client(cx_c, "user_c").await;
3306 let client_c2 = server.create_client(cx_c2, "user_c").await;
3307
3308 assert_eq!(client_a.user_id().unwrap(), client_a2.user_id().unwrap());
3309 assert_eq!(client_b.user_id().unwrap(), client_b2.user_id().unwrap());
3310 assert_eq!(client_c.user_id().unwrap(), client_c2.user_id().unwrap());
3311
3312 // User A and User C request that user B become their contact.
3313 client_a
3314 .user_store
3315 .update(cx_a, |store, cx| {
3316 store.request_contact(client_b.user_id().unwrap(), cx)
3317 })
3318 .await
3319 .unwrap();
3320 client_c
3321 .user_store
3322 .update(cx_c, |store, cx| {
3323 store.request_contact(client_b.user_id().unwrap(), cx)
3324 })
3325 .await
3326 .unwrap();
3327 executor.run_until_parked();
3328
3329 // All users see the pending request appear in all their clients.
3330 assert_eq!(
3331 client_a.summarize_contacts(&cx_a).outgoing_requests,
3332 &["user_b"]
3333 );
3334 assert_eq!(
3335 client_a2.summarize_contacts(&cx_a2).outgoing_requests,
3336 &["user_b"]
3337 );
3338 assert_eq!(
3339 client_b.summarize_contacts(&cx_b).incoming_requests,
3340 &["user_a", "user_c"]
3341 );
3342 assert_eq!(
3343 client_b2.summarize_contacts(&cx_b2).incoming_requests,
3344 &["user_a", "user_c"]
3345 );
3346 assert_eq!(
3347 client_c.summarize_contacts(&cx_c).outgoing_requests,
3348 &["user_b"]
3349 );
3350 assert_eq!(
3351 client_c2.summarize_contacts(&cx_c2).outgoing_requests,
3352 &["user_b"]
3353 );
3354
3355 // Contact requests are present upon connecting (tested here via disconnect/reconnect)
3356 disconnect_and_reconnect(&client_a, cx_a).await;
3357 disconnect_and_reconnect(&client_b, cx_b).await;
3358 disconnect_and_reconnect(&client_c, cx_c).await;
3359 executor.run_until_parked();
3360 assert_eq!(
3361 client_a.summarize_contacts(&cx_a).outgoing_requests,
3362 &["user_b"]
3363 );
3364 assert_eq!(
3365 client_b.summarize_contacts(&cx_b).incoming_requests,
3366 &["user_a", "user_c"]
3367 );
3368 assert_eq!(
3369 client_c.summarize_contacts(&cx_c).outgoing_requests,
3370 &["user_b"]
3371 );
3372
3373 // User B accepts the request from user A.
3374 client_b
3375 .user_store
3376 .update(cx_b, |store, cx| {
3377 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
3378 })
3379 .await
3380 .unwrap();
3381
3382 executor.run_until_parked();
3383
3384 // User B sees user A as their contact now in all client, and the incoming request from them is removed.
3385 let contacts_b = client_b.summarize_contacts(&cx_b);
3386 assert_eq!(contacts_b.current, &["user_a", "user_b"]);
3387 assert_eq!(contacts_b.incoming_requests, &["user_c"]);
3388 let contacts_b2 = client_b2.summarize_contacts(&cx_b2);
3389 assert_eq!(contacts_b2.current, &["user_a", "user_b"]);
3390 assert_eq!(contacts_b2.incoming_requests, &["user_c"]);
3391
3392 // User A sees user B as their contact now in all clients, and the outgoing request to them is removed.
3393 let contacts_a = client_a.summarize_contacts(&cx_a);
3394 assert_eq!(contacts_a.current, &["user_a", "user_b"]);
3395 assert!(contacts_a.outgoing_requests.is_empty());
3396 let contacts_a2 = client_a2.summarize_contacts(&cx_a2);
3397 assert_eq!(contacts_a2.current, &["user_a", "user_b"]);
3398 assert!(contacts_a2.outgoing_requests.is_empty());
3399
3400 // Contacts are present upon connecting (tested here via disconnect/reconnect)
3401 disconnect_and_reconnect(&client_a, cx_a).await;
3402 disconnect_and_reconnect(&client_b, cx_b).await;
3403 disconnect_and_reconnect(&client_c, cx_c).await;
3404 executor.run_until_parked();
3405 assert_eq!(
3406 client_a.summarize_contacts(&cx_a).current,
3407 &["user_a", "user_b"]
3408 );
3409 assert_eq!(
3410 client_b.summarize_contacts(&cx_b).current,
3411 &["user_a", "user_b"]
3412 );
3413 assert_eq!(
3414 client_b.summarize_contacts(&cx_b).incoming_requests,
3415 &["user_c"]
3416 );
3417 assert_eq!(client_c.summarize_contacts(&cx_c).current, &["user_c"]);
3418 assert_eq!(
3419 client_c.summarize_contacts(&cx_c).outgoing_requests,
3420 &["user_b"]
3421 );
3422
3423 // User B rejects the request from user C.
3424 client_b
3425 .user_store
3426 .update(cx_b, |store, cx| {
3427 store.respond_to_contact_request(client_c.user_id().unwrap(), false, cx)
3428 })
3429 .await
3430 .unwrap();
3431
3432 executor.run_until_parked();
3433
3434 // User B doesn't see user C as their contact, and the incoming request from them is removed.
3435 let contacts_b = client_b.summarize_contacts(&cx_b);
3436 assert_eq!(contacts_b.current, &["user_a", "user_b"]);
3437 assert!(contacts_b.incoming_requests.is_empty());
3438 let contacts_b2 = client_b2.summarize_contacts(&cx_b2);
3439 assert_eq!(contacts_b2.current, &["user_a", "user_b"]);
3440 assert!(contacts_b2.incoming_requests.is_empty());
3441
3442 // User C doesn't see user B as their contact, and the outgoing request to them is removed.
3443 let contacts_c = client_c.summarize_contacts(&cx_c);
3444 assert_eq!(contacts_c.current, &["user_c"]);
3445 assert!(contacts_c.outgoing_requests.is_empty());
3446 let contacts_c2 = client_c2.summarize_contacts(&cx_c2);
3447 assert_eq!(contacts_c2.current, &["user_c"]);
3448 assert!(contacts_c2.outgoing_requests.is_empty());
3449
3450 // Incoming/outgoing requests are not present upon connecting (tested here via disconnect/reconnect)
3451 disconnect_and_reconnect(&client_a, cx_a).await;
3452 disconnect_and_reconnect(&client_b, cx_b).await;
3453 disconnect_and_reconnect(&client_c, cx_c).await;
3454 executor.run_until_parked();
3455 assert_eq!(
3456 client_a.summarize_contacts(&cx_a).current,
3457 &["user_a", "user_b"]
3458 );
3459 assert_eq!(
3460 client_b.summarize_contacts(&cx_b).current,
3461 &["user_a", "user_b"]
3462 );
3463 assert!(client_b
3464 .summarize_contacts(&cx_b)
3465 .incoming_requests
3466 .is_empty());
3467 assert_eq!(client_c.summarize_contacts(&cx_c).current, &["user_c"]);
3468 assert!(client_c
3469 .summarize_contacts(&cx_c)
3470 .outgoing_requests
3471 .is_empty());
3472
3473 async fn disconnect_and_reconnect(client: &TestClient, cx: &mut TestAppContext) {
3474 client.disconnect(&cx.to_async()).unwrap();
3475 client.clear_contacts(cx).await;
3476 client
3477 .authenticate_and_connect(false, &cx.to_async())
3478 .await
3479 .unwrap();
3480 }
3481}
3482
3483#[gpui::test(iterations = 10)]
3484async fn test_following(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3485 cx_a.foreground().forbid_parking();
3486 let fs = FakeFs::new(cx_a.background());
3487
3488 // 2 clients connect to a server.
3489 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3490 let mut client_a = server.create_client(cx_a, "user_a").await;
3491 let mut client_b = server.create_client(cx_b, "user_b").await;
3492 server
3493 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
3494 .await;
3495 cx_a.update(editor::init);
3496 cx_b.update(editor::init);
3497
3498 // Client A shares a project.
3499 fs.insert_tree(
3500 "/a",
3501 json!({
3502 "1.txt": "one",
3503 "2.txt": "two",
3504 "3.txt": "three",
3505 }),
3506 )
3507 .await;
3508 let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
3509
3510 // Client B joins the project.
3511 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
3512
3513 // Client A opens some editors.
3514 let workspace_a = client_a.build_workspace(&project_a, cx_a);
3515 let pane_a = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
3516 let editor_a1 = workspace_a
3517 .update(cx_a, |workspace, cx| {
3518 workspace.open_path((worktree_id, "1.txt"), true, cx)
3519 })
3520 .await
3521 .unwrap()
3522 .downcast::<Editor>()
3523 .unwrap();
3524 let editor_a2 = workspace_a
3525 .update(cx_a, |workspace, cx| {
3526 workspace.open_path((worktree_id, "2.txt"), true, cx)
3527 })
3528 .await
3529 .unwrap()
3530 .downcast::<Editor>()
3531 .unwrap();
3532
3533 // Client B opens an editor.
3534 let workspace_b = client_b.build_workspace(&project_b, cx_b);
3535 let editor_b1 = workspace_b
3536 .update(cx_b, |workspace, cx| {
3537 workspace.open_path((worktree_id, "1.txt"), true, cx)
3538 })
3539 .await
3540 .unwrap()
3541 .downcast::<Editor>()
3542 .unwrap();
3543
3544 let client_a_id = project_b.read_with(cx_b, |project, _| {
3545 project.collaborators().values().next().unwrap().peer_id
3546 });
3547 let client_b_id = project_a.read_with(cx_a, |project, _| {
3548 project.collaborators().values().next().unwrap().peer_id
3549 });
3550
3551 // When client B starts following client A, all visible view states are replicated to client B.
3552 editor_a1.update(cx_a, |editor, cx| {
3553 editor.change_selections(None, cx, |s| s.select_ranges([0..1]))
3554 });
3555 editor_a2.update(cx_a, |editor, cx| {
3556 editor.change_selections(None, cx, |s| s.select_ranges([2..3]))
3557 });
3558 workspace_b
3559 .update(cx_b, |workspace, cx| {
3560 workspace
3561 .toggle_follow(&ToggleFollow(client_a_id), cx)
3562 .unwrap()
3563 })
3564 .await
3565 .unwrap();
3566
3567 let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
3568 workspace
3569 .active_item(cx)
3570 .unwrap()
3571 .downcast::<Editor>()
3572 .unwrap()
3573 });
3574 assert!(cx_b.read(|cx| editor_b2.is_focused(cx)));
3575 assert_eq!(
3576 editor_b2.read_with(cx_b, |editor, cx| editor.project_path(cx)),
3577 Some((worktree_id, "2.txt").into())
3578 );
3579 assert_eq!(
3580 editor_b2.read_with(cx_b, |editor, cx| editor.selections.ranges(cx)),
3581 vec![2..3]
3582 );
3583 assert_eq!(
3584 editor_b1.read_with(cx_b, |editor, cx| editor.selections.ranges(cx)),
3585 vec![0..1]
3586 );
3587
3588 // When client A activates a different editor, client B does so as well.
3589 workspace_a.update(cx_a, |workspace, cx| {
3590 workspace.activate_item(&editor_a1, cx)
3591 });
3592 workspace_b
3593 .condition(cx_b, |workspace, cx| {
3594 workspace.active_item(cx).unwrap().id() == editor_b1.id()
3595 })
3596 .await;
3597
3598 // When client A navigates back and forth, client B does so as well.
3599 workspace_a
3600 .update(cx_a, |workspace, cx| {
3601 workspace::Pane::go_back(workspace, None, cx)
3602 })
3603 .await;
3604 workspace_b
3605 .condition(cx_b, |workspace, cx| {
3606 workspace.active_item(cx).unwrap().id() == editor_b2.id()
3607 })
3608 .await;
3609
3610 workspace_a
3611 .update(cx_a, |workspace, cx| {
3612 workspace::Pane::go_forward(workspace, None, cx)
3613 })
3614 .await;
3615 workspace_b
3616 .condition(cx_b, |workspace, cx| {
3617 workspace.active_item(cx).unwrap().id() == editor_b1.id()
3618 })
3619 .await;
3620
3621 // Changes to client A's editor are reflected on client B.
3622 editor_a1.update(cx_a, |editor, cx| {
3623 editor.change_selections(None, cx, |s| s.select_ranges([1..1, 2..2]));
3624 });
3625 editor_b1
3626 .condition(cx_b, |editor, cx| {
3627 editor.selections.ranges(cx) == vec![1..1, 2..2]
3628 })
3629 .await;
3630
3631 editor_a1.update(cx_a, |editor, cx| editor.set_text("TWO", cx));
3632 editor_b1
3633 .condition(cx_b, |editor, cx| editor.text(cx) == "TWO")
3634 .await;
3635
3636 editor_a1.update(cx_a, |editor, cx| {
3637 editor.change_selections(None, cx, |s| s.select_ranges([3..3]));
3638 editor.set_scroll_position(vec2f(0., 100.), cx);
3639 });
3640 editor_b1
3641 .condition(cx_b, |editor, cx| {
3642 editor.selections.ranges(cx) == vec![3..3]
3643 })
3644 .await;
3645
3646 // After unfollowing, client B stops receiving updates from client A.
3647 workspace_b.update(cx_b, |workspace, cx| {
3648 workspace.unfollow(&workspace.active_pane().clone(), cx)
3649 });
3650 workspace_a.update(cx_a, |workspace, cx| {
3651 workspace.activate_item(&editor_a2, cx)
3652 });
3653 cx_a.foreground().run_until_parked();
3654 assert_eq!(
3655 workspace_b.read_with(cx_b, |workspace, cx| workspace
3656 .active_item(cx)
3657 .unwrap()
3658 .id()),
3659 editor_b1.id()
3660 );
3661
3662 // Client A starts following client B.
3663 workspace_a
3664 .update(cx_a, |workspace, cx| {
3665 workspace
3666 .toggle_follow(&ToggleFollow(client_b_id), cx)
3667 .unwrap()
3668 })
3669 .await
3670 .unwrap();
3671 assert_eq!(
3672 workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
3673 Some(client_b_id)
3674 );
3675 assert_eq!(
3676 workspace_a.read_with(cx_a, |workspace, cx| workspace
3677 .active_item(cx)
3678 .unwrap()
3679 .id()),
3680 editor_a1.id()
3681 );
3682
3683 // Following interrupts when client B disconnects.
3684 client_b.disconnect(&cx_b.to_async()).unwrap();
3685 cx_a.foreground().run_until_parked();
3686 assert_eq!(
3687 workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
3688 None
3689 );
3690}
3691
3692#[gpui::test(iterations = 10)]
3693async fn test_peers_following_each_other(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3694 cx_a.foreground().forbid_parking();
3695 let fs = FakeFs::new(cx_a.background());
3696
3697 // 2 clients connect to a server.
3698 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3699 let mut client_a = server.create_client(cx_a, "user_a").await;
3700 let mut client_b = server.create_client(cx_b, "user_b").await;
3701 server
3702 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
3703 .await;
3704 cx_a.update(editor::init);
3705 cx_b.update(editor::init);
3706
3707 // Client A shares a project.
3708 fs.insert_tree(
3709 "/a",
3710 json!({
3711 "1.txt": "one",
3712 "2.txt": "two",
3713 "3.txt": "three",
3714 "4.txt": "four",
3715 }),
3716 )
3717 .await;
3718 let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
3719
3720 // Client B joins the project.
3721 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
3722
3723 // Client A opens some editors.
3724 let workspace_a = client_a.build_workspace(&project_a, cx_a);
3725 let pane_a1 = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
3726 let _editor_a1 = workspace_a
3727 .update(cx_a, |workspace, cx| {
3728 workspace.open_path((worktree_id, "1.txt"), true, cx)
3729 })
3730 .await
3731 .unwrap()
3732 .downcast::<Editor>()
3733 .unwrap();
3734
3735 // Client B opens an editor.
3736 let workspace_b = client_b.build_workspace(&project_b, cx_b);
3737 let pane_b1 = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
3738 let _editor_b1 = workspace_b
3739 .update(cx_b, |workspace, cx| {
3740 workspace.open_path((worktree_id, "2.txt"), true, cx)
3741 })
3742 .await
3743 .unwrap()
3744 .downcast::<Editor>()
3745 .unwrap();
3746
3747 // Clients A and B follow each other in split panes
3748 workspace_a.update(cx_a, |workspace, cx| {
3749 workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
3750 assert_ne!(*workspace.active_pane(), pane_a1);
3751 });
3752 workspace_a
3753 .update(cx_a, |workspace, cx| {
3754 let leader_id = *project_a.read(cx).collaborators().keys().next().unwrap();
3755 workspace
3756 .toggle_follow(&workspace::ToggleFollow(leader_id), cx)
3757 .unwrap()
3758 })
3759 .await
3760 .unwrap();
3761 workspace_b.update(cx_b, |workspace, cx| {
3762 workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
3763 assert_ne!(*workspace.active_pane(), pane_b1);
3764 });
3765 workspace_b
3766 .update(cx_b, |workspace, cx| {
3767 let leader_id = *project_b.read(cx).collaborators().keys().next().unwrap();
3768 workspace
3769 .toggle_follow(&workspace::ToggleFollow(leader_id), cx)
3770 .unwrap()
3771 })
3772 .await
3773 .unwrap();
3774
3775 workspace_a
3776 .update(cx_a, |workspace, cx| {
3777 workspace.activate_next_pane(cx);
3778 assert_eq!(*workspace.active_pane(), pane_a1);
3779 workspace.open_path((worktree_id, "3.txt"), true, cx)
3780 })
3781 .await
3782 .unwrap();
3783 workspace_b
3784 .update(cx_b, |workspace, cx| {
3785 workspace.activate_next_pane(cx);
3786 assert_eq!(*workspace.active_pane(), pane_b1);
3787 workspace.open_path((worktree_id, "4.txt"), true, cx)
3788 })
3789 .await
3790 .unwrap();
3791 cx_a.foreground().run_until_parked();
3792
3793 // Ensure leader updates don't change the active pane of followers
3794 workspace_a.read_with(cx_a, |workspace, _| {
3795 assert_eq!(*workspace.active_pane(), pane_a1);
3796 });
3797 workspace_b.read_with(cx_b, |workspace, _| {
3798 assert_eq!(*workspace.active_pane(), pane_b1);
3799 });
3800
3801 // Ensure peers following each other doesn't cause an infinite loop.
3802 assert_eq!(
3803 workspace_a.read_with(cx_a, |workspace, cx| workspace
3804 .active_item(cx)
3805 .unwrap()
3806 .project_path(cx)),
3807 Some((worktree_id, "3.txt").into())
3808 );
3809 workspace_a.update(cx_a, |workspace, cx| {
3810 assert_eq!(
3811 workspace.active_item(cx).unwrap().project_path(cx),
3812 Some((worktree_id, "3.txt").into())
3813 );
3814 workspace.activate_next_pane(cx);
3815 assert_eq!(
3816 workspace.active_item(cx).unwrap().project_path(cx),
3817 Some((worktree_id, "4.txt").into())
3818 );
3819 });
3820 workspace_b.update(cx_b, |workspace, cx| {
3821 assert_eq!(
3822 workspace.active_item(cx).unwrap().project_path(cx),
3823 Some((worktree_id, "4.txt").into())
3824 );
3825 workspace.activate_next_pane(cx);
3826 assert_eq!(
3827 workspace.active_item(cx).unwrap().project_path(cx),
3828 Some((worktree_id, "3.txt").into())
3829 );
3830 });
3831}
3832
3833#[gpui::test(iterations = 10)]
3834async fn test_auto_unfollowing(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3835 cx_a.foreground().forbid_parking();
3836
3837 // 2 clients connect to a server.
3838 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3839 let mut client_a = server.create_client(cx_a, "user_a").await;
3840 let mut client_b = server.create_client(cx_b, "user_b").await;
3841 server
3842 .make_contacts(vec![(&client_a, cx_a), (&client_b, cx_b)])
3843 .await;
3844 cx_a.update(editor::init);
3845 cx_b.update(editor::init);
3846
3847 // Client A shares a project.
3848 let fs = FakeFs::new(cx_a.background());
3849 fs.insert_tree(
3850 "/a",
3851 json!({
3852 "1.txt": "one",
3853 "2.txt": "two",
3854 "3.txt": "three",
3855 }),
3856 )
3857 .await;
3858 let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
3859 let project_b = client_b.build_remote_project(&project_a, cx_a, cx_b).await;
3860
3861 // Client A opens some editors.
3862 let workspace_a = client_a.build_workspace(&project_a, cx_a);
3863 let _editor_a1 = workspace_a
3864 .update(cx_a, |workspace, cx| {
3865 workspace.open_path((worktree_id, "1.txt"), true, cx)
3866 })
3867 .await
3868 .unwrap()
3869 .downcast::<Editor>()
3870 .unwrap();
3871
3872 // Client B starts following client A.
3873 let workspace_b = client_b.build_workspace(&project_b, cx_b);
3874 let pane_b = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
3875 let leader_id = project_b.read_with(cx_b, |project, _| {
3876 project.collaborators().values().next().unwrap().peer_id
3877 });
3878 workspace_b
3879 .update(cx_b, |workspace, cx| {
3880 workspace
3881 .toggle_follow(&ToggleFollow(leader_id), cx)
3882 .unwrap()
3883 })
3884 .await
3885 .unwrap();
3886 assert_eq!(
3887 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3888 Some(leader_id)
3889 );
3890 let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
3891 workspace
3892 .active_item(cx)
3893 .unwrap()
3894 .downcast::<Editor>()
3895 .unwrap()
3896 });
3897
3898 // When client B moves, it automatically stops following client A.
3899 editor_b2.update(cx_b, |editor, cx| editor.move_right(&editor::MoveRight, cx));
3900 assert_eq!(
3901 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3902 None
3903 );
3904
3905 workspace_b
3906 .update(cx_b, |workspace, cx| {
3907 workspace
3908 .toggle_follow(&ToggleFollow(leader_id), cx)
3909 .unwrap()
3910 })
3911 .await
3912 .unwrap();
3913 assert_eq!(
3914 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3915 Some(leader_id)
3916 );
3917
3918 // When client B edits, it automatically stops following client A.
3919 editor_b2.update(cx_b, |editor, cx| editor.insert("X", cx));
3920 assert_eq!(
3921 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3922 None
3923 );
3924
3925 workspace_b
3926 .update(cx_b, |workspace, cx| {
3927 workspace
3928 .toggle_follow(&ToggleFollow(leader_id), cx)
3929 .unwrap()
3930 })
3931 .await
3932 .unwrap();
3933 assert_eq!(
3934 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3935 Some(leader_id)
3936 );
3937
3938 // When client B scrolls, it automatically stops following client A.
3939 editor_b2.update(cx_b, |editor, cx| {
3940 editor.set_scroll_position(vec2f(0., 3.), cx)
3941 });
3942 assert_eq!(
3943 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3944 None
3945 );
3946
3947 workspace_b
3948 .update(cx_b, |workspace, cx| {
3949 workspace
3950 .toggle_follow(&ToggleFollow(leader_id), cx)
3951 .unwrap()
3952 })
3953 .await
3954 .unwrap();
3955 assert_eq!(
3956 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3957 Some(leader_id)
3958 );
3959
3960 // When client B activates a different pane, it continues following client A in the original pane.
3961 workspace_b.update(cx_b, |workspace, cx| {
3962 workspace.split_pane(pane_b.clone(), SplitDirection::Right, cx)
3963 });
3964 assert_eq!(
3965 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3966 Some(leader_id)
3967 );
3968
3969 workspace_b.update(cx_b, |workspace, cx| workspace.activate_next_pane(cx));
3970 assert_eq!(
3971 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3972 Some(leader_id)
3973 );
3974
3975 // When client B activates a different item in the original pane, it automatically stops following client A.
3976 workspace_b
3977 .update(cx_b, |workspace, cx| {
3978 workspace.open_path((worktree_id, "2.txt"), true, cx)
3979 })
3980 .await
3981 .unwrap();
3982 assert_eq!(
3983 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
3984 None
3985 );
3986}
3987
3988#[gpui::test(iterations = 100)]
3989async fn test_random_collaboration(
3990 cx: &mut TestAppContext,
3991 deterministic: Arc<Deterministic>,
3992 rng: StdRng,
3993) {
3994 cx.foreground().forbid_parking();
3995 let max_peers = env::var("MAX_PEERS")
3996 .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
3997 .unwrap_or(5);
3998 assert!(max_peers <= 5);
3999
4000 let max_operations = env::var("OPERATIONS")
4001 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4002 .unwrap_or(10);
4003
4004 let rng = Arc::new(Mutex::new(rng));
4005
4006 let guest_lang_registry = Arc::new(LanguageRegistry::test());
4007 let host_language_registry = Arc::new(LanguageRegistry::test());
4008
4009 let fs = FakeFs::new(cx.background());
4010 fs.insert_tree("/_collab", json!({"init": ""})).await;
4011
4012 let mut server = TestServer::start(cx.foreground(), cx.background()).await;
4013 let db = server.app_state.db.clone();
4014 let host_user_id = db.create_user("host", None, false).await.unwrap();
4015 for username in ["guest-1", "guest-2", "guest-3", "guest-4"] {
4016 let guest_user_id = db.create_user(username, None, false).await.unwrap();
4017 server
4018 .app_state
4019 .db
4020 .send_contact_request(guest_user_id, host_user_id)
4021 .await
4022 .unwrap();
4023 server
4024 .app_state
4025 .db
4026 .respond_to_contact_request(host_user_id, guest_user_id, true)
4027 .await
4028 .unwrap();
4029 }
4030
4031 let mut clients = Vec::new();
4032 let mut user_ids = Vec::new();
4033 let mut op_start_signals = Vec::new();
4034
4035 let mut next_entity_id = 100000;
4036 let mut host_cx = TestAppContext::new(
4037 cx.foreground_platform(),
4038 cx.platform(),
4039 deterministic.build_foreground(next_entity_id),
4040 deterministic.build_background(),
4041 cx.font_cache(),
4042 cx.leak_detector(),
4043 next_entity_id,
4044 );
4045 let host = server.create_client(&mut host_cx, "host").await;
4046 let host_project = host_cx.update(|cx| {
4047 Project::local(
4048 host.client.clone(),
4049 host.user_store.clone(),
4050 host_language_registry.clone(),
4051 fs.clone(),
4052 cx,
4053 )
4054 });
4055 let host_project_id = host_project
4056 .update(&mut host_cx, |p, _| p.next_remote_id())
4057 .await;
4058
4059 let (collab_worktree, _) = host_project
4060 .update(&mut host_cx, |project, cx| {
4061 project.find_or_create_local_worktree("/_collab", true, cx)
4062 })
4063 .await
4064 .unwrap();
4065 collab_worktree
4066 .read_with(&host_cx, |tree, _| tree.as_local().unwrap().scan_complete())
4067 .await;
4068
4069 // Set up fake language servers.
4070 let mut language = Language::new(
4071 LanguageConfig {
4072 name: "Rust".into(),
4073 path_suffixes: vec!["rs".to_string()],
4074 ..Default::default()
4075 },
4076 None,
4077 );
4078 let _fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
4079 name: "the-fake-language-server",
4080 capabilities: lsp::LanguageServer::full_capabilities(),
4081 initializer: Some(Box::new({
4082 let rng = rng.clone();
4083 let fs = fs.clone();
4084 let project = host_project.downgrade();
4085 move |fake_server: &mut FakeLanguageServer| {
4086 fake_server.handle_request::<lsp::request::Completion, _, _>(|_, _| async move {
4087 Ok(Some(lsp::CompletionResponse::Array(vec![
4088 lsp::CompletionItem {
4089 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
4090 range: lsp::Range::new(
4091 lsp::Position::new(0, 0),
4092 lsp::Position::new(0, 0),
4093 ),
4094 new_text: "the-new-text".to_string(),
4095 })),
4096 ..Default::default()
4097 },
4098 ])))
4099 });
4100
4101 fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
4102 |_, _| async move {
4103 Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
4104 lsp::CodeAction {
4105 title: "the-code-action".to_string(),
4106 ..Default::default()
4107 },
4108 )]))
4109 },
4110 );
4111
4112 fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
4113 |params, _| async move {
4114 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
4115 params.position,
4116 params.position,
4117 ))))
4118 },
4119 );
4120
4121 fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
4122 let fs = fs.clone();
4123 let rng = rng.clone();
4124 move |_, _| {
4125 let fs = fs.clone();
4126 let rng = rng.clone();
4127 async move {
4128 let files = fs.files().await;
4129 let mut rng = rng.lock();
4130 let count = rng.gen_range::<usize, _>(1..3);
4131 let files = (0..count)
4132 .map(|_| files.choose(&mut *rng).unwrap())
4133 .collect::<Vec<_>>();
4134 log::info!("LSP: Returning definitions in files {:?}", &files);
4135 Ok(Some(lsp::GotoDefinitionResponse::Array(
4136 files
4137 .into_iter()
4138 .map(|file| lsp::Location {
4139 uri: lsp::Url::from_file_path(file).unwrap(),
4140 range: Default::default(),
4141 })
4142 .collect(),
4143 )))
4144 }
4145 }
4146 });
4147
4148 fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>({
4149 let rng = rng.clone();
4150 let project = project.clone();
4151 move |params, mut cx| {
4152 let highlights = if let Some(project) = project.upgrade(&cx) {
4153 project.update(&mut cx, |project, cx| {
4154 let path = params
4155 .text_document_position_params
4156 .text_document
4157 .uri
4158 .to_file_path()
4159 .unwrap();
4160 let (worktree, relative_path) =
4161 project.find_local_worktree(&path, cx)?;
4162 let project_path =
4163 ProjectPath::from((worktree.read(cx).id(), relative_path));
4164 let buffer = project.get_open_buffer(&project_path, cx)?.read(cx);
4165
4166 let mut highlights = Vec::new();
4167 let highlight_count = rng.lock().gen_range(1..=5);
4168 let mut prev_end = 0;
4169 for _ in 0..highlight_count {
4170 let range =
4171 buffer.random_byte_range(prev_end, &mut *rng.lock());
4172
4173 highlights.push(lsp::DocumentHighlight {
4174 range: range_to_lsp(range.to_point_utf16(buffer)),
4175 kind: Some(lsp::DocumentHighlightKind::READ),
4176 });
4177 prev_end = range.end;
4178 }
4179 Some(highlights)
4180 })
4181 } else {
4182 None
4183 };
4184 async move { Ok(highlights) }
4185 }
4186 });
4187 }
4188 })),
4189 ..Default::default()
4190 });
4191 host_language_registry.add(Arc::new(language));
4192
4193 let op_start_signal = futures::channel::mpsc::unbounded();
4194 user_ids.push(host.current_user_id(&host_cx));
4195 op_start_signals.push(op_start_signal.0);
4196 clients.push(host_cx.foreground().spawn(host.simulate_host(
4197 host_project,
4198 op_start_signal.1,
4199 rng.clone(),
4200 host_cx,
4201 )));
4202
4203 let disconnect_host_at = if rng.lock().gen_bool(0.2) {
4204 rng.lock().gen_range(0..max_operations)
4205 } else {
4206 max_operations
4207 };
4208 let mut available_guests = vec![
4209 "guest-1".to_string(),
4210 "guest-2".to_string(),
4211 "guest-3".to_string(),
4212 "guest-4".to_string(),
4213 ];
4214 let mut operations = 0;
4215 while operations < max_operations {
4216 if operations == disconnect_host_at {
4217 server.disconnect_client(user_ids[0]);
4218 cx.foreground().advance_clock(RECEIVE_TIMEOUT);
4219 drop(op_start_signals);
4220 let mut clients = futures::future::join_all(clients).await;
4221 cx.foreground().run_until_parked();
4222
4223 let (host, mut host_cx, host_err) = clients.remove(0);
4224 if let Some(host_err) = host_err {
4225 log::error!("host error - {:?}", host_err);
4226 }
4227 host.project
4228 .as_ref()
4229 .unwrap()
4230 .read_with(&host_cx, |project, _| assert!(!project.is_shared()));
4231 for (guest, mut guest_cx, guest_err) in clients {
4232 if let Some(guest_err) = guest_err {
4233 log::error!("{} error - {:?}", guest.username, guest_err);
4234 }
4235
4236 let contacts = server
4237 .app_state
4238 .db
4239 .get_contacts(guest.current_user_id(&guest_cx))
4240 .await
4241 .unwrap();
4242 let contacts = server
4243 .store
4244 .read()
4245 .await
4246 .build_initial_contacts_update(contacts)
4247 .contacts;
4248 assert!(!contacts
4249 .iter()
4250 .flat_map(|contact| &contact.projects)
4251 .any(|project| project.id == host_project_id));
4252 guest
4253 .project
4254 .as_ref()
4255 .unwrap()
4256 .read_with(&guest_cx, |project, _| assert!(project.is_read_only()));
4257 guest_cx.update(|_| drop(guest));
4258 }
4259 host_cx.update(|_| drop(host));
4260
4261 return;
4262 }
4263
4264 let distribution = rng.lock().gen_range(0..100);
4265 match distribution {
4266 0..=19 if !available_guests.is_empty() => {
4267 let guest_ix = rng.lock().gen_range(0..available_guests.len());
4268 let guest_username = available_guests.remove(guest_ix);
4269 log::info!("Adding new connection for {}", guest_username);
4270 next_entity_id += 100000;
4271 let mut guest_cx = TestAppContext::new(
4272 cx.foreground_platform(),
4273 cx.platform(),
4274 deterministic.build_foreground(next_entity_id),
4275 deterministic.build_background(),
4276 cx.font_cache(),
4277 cx.leak_detector(),
4278 next_entity_id,
4279 );
4280 let guest = server.create_client(&mut guest_cx, &guest_username).await;
4281 let guest_project = Project::remote(
4282 host_project_id,
4283 guest.client.clone(),
4284 guest.user_store.clone(),
4285 guest_lang_registry.clone(),
4286 FakeFs::new(cx.background()),
4287 &mut guest_cx.to_async(),
4288 )
4289 .await
4290 .unwrap();
4291 let op_start_signal = futures::channel::mpsc::unbounded();
4292 user_ids.push(guest.current_user_id(&guest_cx));
4293 op_start_signals.push(op_start_signal.0);
4294 clients.push(guest_cx.foreground().spawn(guest.simulate_guest(
4295 guest_username.clone(),
4296 guest_project,
4297 op_start_signal.1,
4298 rng.clone(),
4299 guest_cx,
4300 )));
4301
4302 log::info!("Added connection for {}", guest_username);
4303 operations += 1;
4304 }
4305 20..=29 if clients.len() > 1 => {
4306 let guest_ix = rng.lock().gen_range(1..clients.len());
4307 log::info!("Removing guest {}", user_ids[guest_ix]);
4308 let removed_guest_id = user_ids.remove(guest_ix);
4309 let guest = clients.remove(guest_ix);
4310 op_start_signals.remove(guest_ix);
4311 server.forbid_connections();
4312 server.disconnect_client(removed_guest_id);
4313 cx.foreground().advance_clock(RECEIVE_TIMEOUT);
4314 let (guest, mut guest_cx, guest_err) = guest.await;
4315 server.allow_connections();
4316
4317 if let Some(guest_err) = guest_err {
4318 log::error!("{} error - {:?}", guest.username, guest_err);
4319 }
4320 guest
4321 .project
4322 .as_ref()
4323 .unwrap()
4324 .read_with(&guest_cx, |project, _| assert!(project.is_read_only()));
4325 for user_id in &user_ids {
4326 let contacts = server.app_state.db.get_contacts(*user_id).await.unwrap();
4327 let contacts = server
4328 .store
4329 .read()
4330 .await
4331 .build_initial_contacts_update(contacts)
4332 .contacts;
4333 for contact in contacts {
4334 if contact.online {
4335 assert_ne!(
4336 contact.user_id, removed_guest_id.0 as u64,
4337 "removed guest is still a contact of another peer"
4338 );
4339 }
4340 for project in contact.projects {
4341 for project_guest_id in project.guests {
4342 assert_ne!(
4343 project_guest_id, removed_guest_id.0 as u64,
4344 "removed guest appears as still participating on a project"
4345 );
4346 }
4347 }
4348 }
4349 }
4350
4351 log::info!("{} removed", guest.username);
4352 available_guests.push(guest.username.clone());
4353 guest_cx.update(|_| drop(guest));
4354
4355 operations += 1;
4356 }
4357 _ => {
4358 while operations < max_operations && rng.lock().gen_bool(0.7) {
4359 op_start_signals
4360 .choose(&mut *rng.lock())
4361 .unwrap()
4362 .unbounded_send(())
4363 .unwrap();
4364 operations += 1;
4365 }
4366
4367 if rng.lock().gen_bool(0.8) {
4368 cx.foreground().run_until_parked();
4369 }
4370 }
4371 }
4372 }
4373
4374 drop(op_start_signals);
4375 let mut clients = futures::future::join_all(clients).await;
4376 cx.foreground().run_until_parked();
4377
4378 let (host_client, mut host_cx, host_err) = clients.remove(0);
4379 if let Some(host_err) = host_err {
4380 panic!("host error - {:?}", host_err);
4381 }
4382 let host_project = host_client.project.as_ref().unwrap();
4383 let host_worktree_snapshots = host_project.read_with(&host_cx, |project, cx| {
4384 project
4385 .worktrees(cx)
4386 .map(|worktree| {
4387 let snapshot = worktree.read(cx).snapshot();
4388 (snapshot.id(), snapshot)
4389 })
4390 .collect::<BTreeMap<_, _>>()
4391 });
4392
4393 host_client
4394 .project
4395 .as_ref()
4396 .unwrap()
4397 .read_with(&host_cx, |project, cx| project.check_invariants(cx));
4398
4399 for (guest_client, mut guest_cx, guest_err) in clients.into_iter() {
4400 if let Some(guest_err) = guest_err {
4401 panic!("{} error - {:?}", guest_client.username, guest_err);
4402 }
4403 let worktree_snapshots =
4404 guest_client
4405 .project
4406 .as_ref()
4407 .unwrap()
4408 .read_with(&guest_cx, |project, cx| {
4409 project
4410 .worktrees(cx)
4411 .map(|worktree| {
4412 let worktree = worktree.read(cx);
4413 (worktree.id(), worktree.snapshot())
4414 })
4415 .collect::<BTreeMap<_, _>>()
4416 });
4417
4418 assert_eq!(
4419 worktree_snapshots.keys().collect::<Vec<_>>(),
4420 host_worktree_snapshots.keys().collect::<Vec<_>>(),
4421 "{} has different worktrees than the host",
4422 guest_client.username
4423 );
4424 for (id, host_snapshot) in &host_worktree_snapshots {
4425 let guest_snapshot = &worktree_snapshots[id];
4426 assert_eq!(
4427 guest_snapshot.root_name(),
4428 host_snapshot.root_name(),
4429 "{} has different root name than the host for worktree {}",
4430 guest_client.username,
4431 id
4432 );
4433 assert_eq!(
4434 guest_snapshot.entries(false).collect::<Vec<_>>(),
4435 host_snapshot.entries(false).collect::<Vec<_>>(),
4436 "{} has different snapshot than the host for worktree {}",
4437 guest_client.username,
4438 id
4439 );
4440 assert_eq!(guest_snapshot.scan_id(), host_snapshot.scan_id());
4441 }
4442
4443 guest_client
4444 .project
4445 .as_ref()
4446 .unwrap()
4447 .read_with(&guest_cx, |project, cx| project.check_invariants(cx));
4448
4449 for guest_buffer in &guest_client.buffers {
4450 let buffer_id = guest_buffer.read_with(&guest_cx, |buffer, _| buffer.remote_id());
4451 let host_buffer = host_project.read_with(&host_cx, |project, cx| {
4452 project.buffer_for_id(buffer_id, cx).expect(&format!(
4453 "host does not have buffer for guest:{}, peer:{}, id:{}",
4454 guest_client.username, guest_client.peer_id, buffer_id
4455 ))
4456 });
4457 let path =
4458 host_buffer.read_with(&host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
4459
4460 assert_eq!(
4461 guest_buffer.read_with(&guest_cx, |buffer, _| buffer.deferred_ops_len()),
4462 0,
4463 "{}, buffer {}, path {:?} has deferred operations",
4464 guest_client.username,
4465 buffer_id,
4466 path,
4467 );
4468 assert_eq!(
4469 guest_buffer.read_with(&guest_cx, |buffer, _| buffer.text()),
4470 host_buffer.read_with(&host_cx, |buffer, _| buffer.text()),
4471 "{}, buffer {}, path {:?}, differs from the host's buffer",
4472 guest_client.username,
4473 buffer_id,
4474 path
4475 );
4476 }
4477
4478 guest_cx.update(|_| drop(guest_client));
4479 }
4480
4481 host_cx.update(|_| drop(host_client));
4482}
4483
4484struct TestServer {
4485 peer: Arc<Peer>,
4486 app_state: Arc<AppState>,
4487 server: Arc<Server>,
4488 foreground: Rc<executor::Foreground>,
4489 notifications: mpsc::UnboundedReceiver<()>,
4490 connection_killers: Arc<Mutex<HashMap<UserId, Arc<AtomicBool>>>>,
4491 forbid_connections: Arc<AtomicBool>,
4492 _test_db: TestDb,
4493}
4494
4495impl TestServer {
4496 async fn start(
4497 foreground: Rc<executor::Foreground>,
4498 background: Arc<executor::Background>,
4499 ) -> Self {
4500 let test_db = TestDb::fake(background);
4501 let app_state = Self::build_app_state(&test_db).await;
4502 let peer = Peer::new();
4503 let notifications = mpsc::unbounded();
4504 let server = Server::new(app_state.clone(), Some(notifications.0));
4505 Self {
4506 peer,
4507 app_state,
4508 server,
4509 foreground,
4510 notifications: notifications.1,
4511 connection_killers: Default::default(),
4512 forbid_connections: Default::default(),
4513 _test_db: test_db,
4514 }
4515 }
4516
4517 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
4518 cx.update(|cx| {
4519 let settings = Settings::test(cx);
4520 cx.set_global(settings);
4521 });
4522
4523 let http = FakeHttpClient::with_404_response();
4524 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
4525 {
4526 user.id
4527 } else {
4528 self.app_state
4529 .db
4530 .create_user(name, None, false)
4531 .await
4532 .unwrap()
4533 };
4534 let client_name = name.to_string();
4535 let mut client = Client::new(http.clone());
4536 let server = self.server.clone();
4537 let db = self.app_state.db.clone();
4538 let connection_killers = self.connection_killers.clone();
4539 let forbid_connections = self.forbid_connections.clone();
4540 let (connection_id_tx, mut connection_id_rx) = mpsc::channel(16);
4541
4542 Arc::get_mut(&mut client)
4543 .unwrap()
4544 .override_authenticate(move |cx| {
4545 cx.spawn(|_| async move {
4546 let access_token = "the-token".to_string();
4547 Ok(Credentials {
4548 user_id: user_id.0 as u64,
4549 access_token,
4550 })
4551 })
4552 })
4553 .override_establish_connection(move |credentials, cx| {
4554 assert_eq!(credentials.user_id, user_id.0 as u64);
4555 assert_eq!(credentials.access_token, "the-token");
4556
4557 let server = server.clone();
4558 let db = db.clone();
4559 let connection_killers = connection_killers.clone();
4560 let forbid_connections = forbid_connections.clone();
4561 let client_name = client_name.clone();
4562 let connection_id_tx = connection_id_tx.clone();
4563 cx.spawn(move |cx| async move {
4564 if forbid_connections.load(SeqCst) {
4565 Err(EstablishConnectionError::other(anyhow!(
4566 "server is forbidding connections"
4567 )))
4568 } else {
4569 let (client_conn, server_conn, killed) =
4570 Connection::in_memory(cx.background());
4571 connection_killers.lock().insert(user_id, killed);
4572 let user = db.get_user_by_id(user_id).await.unwrap().unwrap();
4573 cx.background()
4574 .spawn(server.handle_connection(
4575 server_conn,
4576 client_name,
4577 user,
4578 Some(connection_id_tx),
4579 cx.background(),
4580 ))
4581 .detach();
4582 Ok(client_conn)
4583 }
4584 })
4585 });
4586
4587 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
4588 let app_state = Arc::new(workspace::AppState {
4589 client: client.clone(),
4590 user_store: user_store.clone(),
4591 languages: Arc::new(LanguageRegistry::new(Task::ready(()))),
4592 themes: ThemeRegistry::new((), cx.font_cache()),
4593 fs: FakeFs::new(cx.background()),
4594 build_window_options: || Default::default(),
4595 initialize_workspace: |_, _, _| unimplemented!(),
4596 });
4597
4598 Channel::init(&client);
4599 Project::init(&client);
4600 cx.update(|cx| workspace::init(app_state.clone(), cx));
4601
4602 client
4603 .authenticate_and_connect(false, &cx.to_async())
4604 .await
4605 .unwrap();
4606 let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
4607
4608 let client = TestClient {
4609 client,
4610 peer_id,
4611 username: name.to_string(),
4612 user_store,
4613 language_registry: Arc::new(LanguageRegistry::test()),
4614 project: Default::default(),
4615 buffers: Default::default(),
4616 };
4617 client.wait_for_current_user(cx).await;
4618 client
4619 }
4620
4621 fn disconnect_client(&self, user_id: UserId) {
4622 self.connection_killers
4623 .lock()
4624 .remove(&user_id)
4625 .unwrap()
4626 .store(true, SeqCst);
4627 }
4628
4629 fn forbid_connections(&self) {
4630 self.forbid_connections.store(true, SeqCst);
4631 }
4632
4633 fn allow_connections(&self) {
4634 self.forbid_connections.store(false, SeqCst);
4635 }
4636
4637 async fn make_contacts(&self, mut clients: Vec<(&TestClient, &mut TestAppContext)>) {
4638 while let Some((client_a, cx_a)) = clients.pop() {
4639 for (client_b, cx_b) in &mut clients {
4640 client_a
4641 .user_store
4642 .update(cx_a, |store, cx| {
4643 store.request_contact(client_b.user_id().unwrap(), cx)
4644 })
4645 .await
4646 .unwrap();
4647 cx_a.foreground().run_until_parked();
4648 client_b
4649 .user_store
4650 .update(*cx_b, |store, cx| {
4651 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
4652 })
4653 .await
4654 .unwrap();
4655 }
4656 }
4657 }
4658
4659 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
4660 Arc::new(AppState {
4661 db: test_db.db().clone(),
4662 api_token: Default::default(),
4663 invite_link_prefix: Default::default(),
4664 })
4665 }
4666
4667 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
4668 self.server.store.read().await
4669 }
4670
4671 async fn condition<F>(&mut self, mut predicate: F)
4672 where
4673 F: FnMut(&Store) -> bool,
4674 {
4675 assert!(
4676 self.foreground.parking_forbidden(),
4677 "you must call forbid_parking to use server conditions so we don't block indefinitely"
4678 );
4679 while !(predicate)(&*self.server.store.read().await) {
4680 self.foreground.start_waiting();
4681 self.notifications.next().await;
4682 self.foreground.finish_waiting();
4683 }
4684 }
4685}
4686
4687impl Deref for TestServer {
4688 type Target = Server;
4689
4690 fn deref(&self) -> &Self::Target {
4691 &self.server
4692 }
4693}
4694
4695impl Drop for TestServer {
4696 fn drop(&mut self) {
4697 self.peer.reset();
4698 }
4699}
4700
4701struct TestClient {
4702 client: Arc<Client>,
4703 username: String,
4704 pub peer_id: PeerId,
4705 pub user_store: ModelHandle<UserStore>,
4706 language_registry: Arc<LanguageRegistry>,
4707 project: Option<ModelHandle<Project>>,
4708 buffers: HashSet<ModelHandle<language::Buffer>>,
4709}
4710
4711impl Deref for TestClient {
4712 type Target = Arc<Client>;
4713
4714 fn deref(&self) -> &Self::Target {
4715 &self.client
4716 }
4717}
4718
4719struct ContactsSummary {
4720 pub current: Vec<String>,
4721 pub outgoing_requests: Vec<String>,
4722 pub incoming_requests: Vec<String>,
4723}
4724
4725impl TestClient {
4726 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
4727 UserId::from_proto(
4728 self.user_store
4729 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
4730 )
4731 }
4732
4733 async fn wait_for_current_user(&self, cx: &TestAppContext) {
4734 let mut authed_user = self
4735 .user_store
4736 .read_with(cx, |user_store, _| user_store.watch_current_user());
4737 while authed_user.next().await.unwrap().is_none() {}
4738 }
4739
4740 async fn clear_contacts(&self, cx: &mut TestAppContext) {
4741 self.user_store
4742 .update(cx, |store, _| store.clear_contacts())
4743 .await;
4744 }
4745
4746 fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
4747 self.user_store.read_with(cx, |store, _| ContactsSummary {
4748 current: store
4749 .contacts()
4750 .iter()
4751 .map(|contact| contact.user.github_login.clone())
4752 .collect(),
4753 outgoing_requests: store
4754 .outgoing_contact_requests()
4755 .iter()
4756 .map(|user| user.github_login.clone())
4757 .collect(),
4758 incoming_requests: store
4759 .incoming_contact_requests()
4760 .iter()
4761 .map(|user| user.github_login.clone())
4762 .collect(),
4763 })
4764 }
4765
4766 async fn build_local_project(
4767 &mut self,
4768 fs: Arc<FakeFs>,
4769 root_path: impl AsRef<Path>,
4770 cx: &mut TestAppContext,
4771 ) -> (ModelHandle<Project>, WorktreeId) {
4772 let project = cx.update(|cx| {
4773 Project::local(
4774 self.client.clone(),
4775 self.user_store.clone(),
4776 self.language_registry.clone(),
4777 fs,
4778 cx,
4779 )
4780 });
4781 self.project = Some(project.clone());
4782 let (worktree, _) = project
4783 .update(cx, |p, cx| {
4784 p.find_or_create_local_worktree(root_path, true, cx)
4785 })
4786 .await
4787 .unwrap();
4788 worktree
4789 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
4790 .await;
4791 project
4792 .update(cx, |project, _| project.next_remote_id())
4793 .await;
4794 (project, worktree.read_with(cx, |tree, _| tree.id()))
4795 }
4796
4797 async fn build_remote_project(
4798 &mut self,
4799 host_project: &ModelHandle<Project>,
4800 host_cx: &mut TestAppContext,
4801 guest_cx: &mut TestAppContext,
4802 ) -> ModelHandle<Project> {
4803 let host_project_id = host_project
4804 .read_with(host_cx, |project, _| project.next_remote_id())
4805 .await;
4806 let guest_user_id = self.user_id().unwrap();
4807 let languages = host_project.read_with(host_cx, |project, _| project.languages().clone());
4808 let project_b = guest_cx.spawn(|mut cx| {
4809 let user_store = self.user_store.clone();
4810 let guest_client = self.client.clone();
4811 async move {
4812 Project::remote(
4813 host_project_id,
4814 guest_client,
4815 user_store.clone(),
4816 languages,
4817 FakeFs::new(cx.background()),
4818 &mut cx,
4819 )
4820 .await
4821 .unwrap()
4822 }
4823 });
4824 host_cx.foreground().run_until_parked();
4825 host_project.update(host_cx, |project, cx| {
4826 project.respond_to_join_request(guest_user_id, true, cx)
4827 });
4828 let project = project_b.await;
4829 self.project = Some(project.clone());
4830 project
4831 }
4832
4833 fn build_workspace(
4834 &self,
4835 project: &ModelHandle<Project>,
4836 cx: &mut TestAppContext,
4837 ) -> ViewHandle<Workspace> {
4838 let (window_id, _) = cx.add_window(|_| EmptyView);
4839 cx.add_view(window_id, |cx| Workspace::new(project.clone(), cx))
4840 }
4841
4842 async fn simulate_host(
4843 mut self,
4844 project: ModelHandle<Project>,
4845 op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
4846 rng: Arc<Mutex<StdRng>>,
4847 mut cx: TestAppContext,
4848 ) -> (Self, TestAppContext, Option<anyhow::Error>) {
4849 async fn simulate_host_internal(
4850 client: &mut TestClient,
4851 project: ModelHandle<Project>,
4852 mut op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
4853 rng: Arc<Mutex<StdRng>>,
4854 cx: &mut TestAppContext,
4855 ) -> anyhow::Result<()> {
4856 let fs = project.read_with(cx, |project, _| project.fs().clone());
4857
4858 cx.update(|cx| {
4859 cx.subscribe(&project, move |project, event, cx| {
4860 if let project::Event::ContactRequestedJoin(user) = event {
4861 log::info!("Host: accepting join request from {}", user.github_login);
4862 project.update(cx, |project, cx| {
4863 project.respond_to_join_request(user.id, true, cx)
4864 });
4865 }
4866 })
4867 .detach();
4868 });
4869
4870 while op_start_signal.next().await.is_some() {
4871 let distribution = rng.lock().gen_range::<usize, _>(0..100);
4872 let files = fs.as_fake().files().await;
4873 match distribution {
4874 0..=19 if !files.is_empty() => {
4875 let path = files.choose(&mut *rng.lock()).unwrap();
4876 let mut path = path.as_path();
4877 while let Some(parent_path) = path.parent() {
4878 path = parent_path;
4879 if rng.lock().gen() {
4880 break;
4881 }
4882 }
4883
4884 log::info!("Host: find/create local worktree {:?}", path);
4885 let find_or_create_worktree = project.update(cx, |project, cx| {
4886 project.find_or_create_local_worktree(path, true, cx)
4887 });
4888 if rng.lock().gen() {
4889 cx.background().spawn(find_or_create_worktree).detach();
4890 } else {
4891 find_or_create_worktree.await?;
4892 }
4893 }
4894 20..=79 if !files.is_empty() => {
4895 let buffer = if client.buffers.is_empty() || rng.lock().gen() {
4896 let file = files.choose(&mut *rng.lock()).unwrap();
4897 let (worktree, path) = project
4898 .update(cx, |project, cx| {
4899 project.find_or_create_local_worktree(file.clone(), true, cx)
4900 })
4901 .await?;
4902 let project_path =
4903 worktree.read_with(cx, |worktree, _| (worktree.id(), path));
4904 log::info!(
4905 "Host: opening path {:?}, worktree {}, relative_path {:?}",
4906 file,
4907 project_path.0,
4908 project_path.1
4909 );
4910 let buffer = project
4911 .update(cx, |project, cx| project.open_buffer(project_path, cx))
4912 .await
4913 .unwrap();
4914 client.buffers.insert(buffer.clone());
4915 buffer
4916 } else {
4917 client
4918 .buffers
4919 .iter()
4920 .choose(&mut *rng.lock())
4921 .unwrap()
4922 .clone()
4923 };
4924
4925 if rng.lock().gen_bool(0.1) {
4926 cx.update(|cx| {
4927 log::info!(
4928 "Host: dropping buffer {:?}",
4929 buffer.read(cx).file().unwrap().full_path(cx)
4930 );
4931 client.buffers.remove(&buffer);
4932 drop(buffer);
4933 });
4934 } else {
4935 buffer.update(cx, |buffer, cx| {
4936 log::info!(
4937 "Host: updating buffer {:?} ({})",
4938 buffer.file().unwrap().full_path(cx),
4939 buffer.remote_id()
4940 );
4941
4942 if rng.lock().gen_bool(0.7) {
4943 buffer.randomly_edit(&mut *rng.lock(), 5, cx);
4944 } else {
4945 buffer.randomly_undo_redo(&mut *rng.lock(), cx);
4946 }
4947 });
4948 }
4949 }
4950 _ => loop {
4951 let path_component_count = rng.lock().gen_range::<usize, _>(1..=5);
4952 let mut path = PathBuf::new();
4953 path.push("/");
4954 for _ in 0..path_component_count {
4955 let letter = rng.lock().gen_range(b'a'..=b'z');
4956 path.push(std::str::from_utf8(&[letter]).unwrap());
4957 }
4958 path.set_extension("rs");
4959 let parent_path = path.parent().unwrap();
4960
4961 log::info!("Host: creating file {:?}", path,);
4962
4963 if fs.create_dir(&parent_path).await.is_ok()
4964 && fs.create_file(&path, Default::default()).await.is_ok()
4965 {
4966 break;
4967 } else {
4968 log::info!("Host: cannot create file");
4969 }
4970 },
4971 }
4972
4973 cx.background().simulate_random_delay().await;
4974 }
4975
4976 Ok(())
4977 }
4978
4979 let result =
4980 simulate_host_internal(&mut self, project.clone(), op_start_signal, rng, &mut cx).await;
4981 log::info!("Host done");
4982 self.project = Some(project);
4983 (self, cx, result.err())
4984 }
4985
4986 pub async fn simulate_guest(
4987 mut self,
4988 guest_username: String,
4989 project: ModelHandle<Project>,
4990 op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
4991 rng: Arc<Mutex<StdRng>>,
4992 mut cx: TestAppContext,
4993 ) -> (Self, TestAppContext, Option<anyhow::Error>) {
4994 async fn simulate_guest_internal(
4995 client: &mut TestClient,
4996 guest_username: &str,
4997 project: ModelHandle<Project>,
4998 mut op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
4999 rng: Arc<Mutex<StdRng>>,
5000 cx: &mut TestAppContext,
5001 ) -> anyhow::Result<()> {
5002 while op_start_signal.next().await.is_some() {
5003 let buffer = if client.buffers.is_empty() || rng.lock().gen() {
5004 let worktree = if let Some(worktree) = project.read_with(cx, |project, cx| {
5005 project
5006 .worktrees(&cx)
5007 .filter(|worktree| {
5008 let worktree = worktree.read(cx);
5009 worktree.is_visible()
5010 && worktree.entries(false).any(|e| e.is_file())
5011 })
5012 .choose(&mut *rng.lock())
5013 }) {
5014 worktree
5015 } else {
5016 cx.background().simulate_random_delay().await;
5017 continue;
5018 };
5019
5020 let (worktree_root_name, project_path) =
5021 worktree.read_with(cx, |worktree, _| {
5022 let entry = worktree
5023 .entries(false)
5024 .filter(|e| e.is_file())
5025 .choose(&mut *rng.lock())
5026 .unwrap();
5027 (
5028 worktree.root_name().to_string(),
5029 (worktree.id(), entry.path.clone()),
5030 )
5031 });
5032 log::info!(
5033 "{}: opening path {:?} in worktree {} ({})",
5034 guest_username,
5035 project_path.1,
5036 project_path.0,
5037 worktree_root_name,
5038 );
5039 let buffer = project
5040 .update(cx, |project, cx| {
5041 project.open_buffer(project_path.clone(), cx)
5042 })
5043 .await?;
5044 log::info!(
5045 "{}: opened path {:?} in worktree {} ({}) with buffer id {}",
5046 guest_username,
5047 project_path.1,
5048 project_path.0,
5049 worktree_root_name,
5050 buffer.read_with(cx, |buffer, _| buffer.remote_id())
5051 );
5052 client.buffers.insert(buffer.clone());
5053 buffer
5054 } else {
5055 client
5056 .buffers
5057 .iter()
5058 .choose(&mut *rng.lock())
5059 .unwrap()
5060 .clone()
5061 };
5062
5063 let choice = rng.lock().gen_range(0..100);
5064 match choice {
5065 0..=9 => {
5066 cx.update(|cx| {
5067 log::info!(
5068 "{}: dropping buffer {:?}",
5069 guest_username,
5070 buffer.read(cx).file().unwrap().full_path(cx)
5071 );
5072 client.buffers.remove(&buffer);
5073 drop(buffer);
5074 });
5075 }
5076 10..=19 => {
5077 let completions = project.update(cx, |project, cx| {
5078 log::info!(
5079 "{}: requesting completions for buffer {} ({:?})",
5080 guest_username,
5081 buffer.read(cx).remote_id(),
5082 buffer.read(cx).file().unwrap().full_path(cx)
5083 );
5084 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5085 project.completions(&buffer, offset, cx)
5086 });
5087 let completions = cx.background().spawn(async move {
5088 completions
5089 .await
5090 .map_err(|err| anyhow!("completions request failed: {:?}", err))
5091 });
5092 if rng.lock().gen_bool(0.3) {
5093 log::info!("{}: detaching completions request", guest_username);
5094 cx.update(|cx| completions.detach_and_log_err(cx));
5095 } else {
5096 completions.await?;
5097 }
5098 }
5099 20..=29 => {
5100 let code_actions = project.update(cx, |project, cx| {
5101 log::info!(
5102 "{}: requesting code actions for buffer {} ({:?})",
5103 guest_username,
5104 buffer.read(cx).remote_id(),
5105 buffer.read(cx).file().unwrap().full_path(cx)
5106 );
5107 let range = buffer.read(cx).random_byte_range(0, &mut *rng.lock());
5108 project.code_actions(&buffer, range, cx)
5109 });
5110 let code_actions = cx.background().spawn(async move {
5111 code_actions
5112 .await
5113 .map_err(|err| anyhow!("code actions request failed: {:?}", err))
5114 });
5115 if rng.lock().gen_bool(0.3) {
5116 log::info!("{}: detaching code actions request", guest_username);
5117 cx.update(|cx| code_actions.detach_and_log_err(cx));
5118 } else {
5119 code_actions.await?;
5120 }
5121 }
5122 30..=39 if buffer.read_with(cx, |buffer, _| buffer.is_dirty()) => {
5123 let (requested_version, save) = buffer.update(cx, |buffer, cx| {
5124 log::info!(
5125 "{}: saving buffer {} ({:?})",
5126 guest_username,
5127 buffer.remote_id(),
5128 buffer.file().unwrap().full_path(cx)
5129 );
5130 (buffer.version(), buffer.save(cx))
5131 });
5132 let save = cx.background().spawn(async move {
5133 let (saved_version, _) = save
5134 .await
5135 .map_err(|err| anyhow!("save request failed: {:?}", err))?;
5136 assert!(saved_version.observed_all(&requested_version));
5137 Ok::<_, anyhow::Error>(())
5138 });
5139 if rng.lock().gen_bool(0.3) {
5140 log::info!("{}: detaching save request", guest_username);
5141 cx.update(|cx| save.detach_and_log_err(cx));
5142 } else {
5143 save.await?;
5144 }
5145 }
5146 40..=44 => {
5147 let prepare_rename = project.update(cx, |project, cx| {
5148 log::info!(
5149 "{}: preparing rename for buffer {} ({:?})",
5150 guest_username,
5151 buffer.read(cx).remote_id(),
5152 buffer.read(cx).file().unwrap().full_path(cx)
5153 );
5154 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5155 project.prepare_rename(buffer, offset, cx)
5156 });
5157 let prepare_rename = cx.background().spawn(async move {
5158 prepare_rename
5159 .await
5160 .map_err(|err| anyhow!("prepare rename request failed: {:?}", err))
5161 });
5162 if rng.lock().gen_bool(0.3) {
5163 log::info!("{}: detaching prepare rename request", guest_username);
5164 cx.update(|cx| prepare_rename.detach_and_log_err(cx));
5165 } else {
5166 prepare_rename.await?;
5167 }
5168 }
5169 45..=49 => {
5170 let definitions = project.update(cx, |project, cx| {
5171 log::info!(
5172 "{}: requesting definitions for buffer {} ({:?})",
5173 guest_username,
5174 buffer.read(cx).remote_id(),
5175 buffer.read(cx).file().unwrap().full_path(cx)
5176 );
5177 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5178 project.definition(&buffer, offset, cx)
5179 });
5180 let definitions = cx.background().spawn(async move {
5181 definitions
5182 .await
5183 .map_err(|err| anyhow!("definitions request failed: {:?}", err))
5184 });
5185 if rng.lock().gen_bool(0.3) {
5186 log::info!("{}: detaching definitions request", guest_username);
5187 cx.update(|cx| definitions.detach_and_log_err(cx));
5188 } else {
5189 client
5190 .buffers
5191 .extend(definitions.await?.into_iter().map(|loc| loc.buffer));
5192 }
5193 }
5194 50..=54 => {
5195 let highlights = project.update(cx, |project, cx| {
5196 log::info!(
5197 "{}: requesting highlights for buffer {} ({:?})",
5198 guest_username,
5199 buffer.read(cx).remote_id(),
5200 buffer.read(cx).file().unwrap().full_path(cx)
5201 );
5202 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5203 project.document_highlights(&buffer, offset, cx)
5204 });
5205 let highlights = cx.background().spawn(async move {
5206 highlights
5207 .await
5208 .map_err(|err| anyhow!("highlights request failed: {:?}", err))
5209 });
5210 if rng.lock().gen_bool(0.3) {
5211 log::info!("{}: detaching highlights request", guest_username);
5212 cx.update(|cx| highlights.detach_and_log_err(cx));
5213 } else {
5214 highlights.await?;
5215 }
5216 }
5217 55..=59 => {
5218 let search = project.update(cx, |project, cx| {
5219 let query = rng.lock().gen_range('a'..='z');
5220 log::info!("{}: project-wide search {:?}", guest_username, query);
5221 project.search(SearchQuery::text(query, false, false), cx)
5222 });
5223 let search = cx.background().spawn(async move {
5224 search
5225 .await
5226 .map_err(|err| anyhow!("search request failed: {:?}", err))
5227 });
5228 if rng.lock().gen_bool(0.3) {
5229 log::info!("{}: detaching search request", guest_username);
5230 cx.update(|cx| search.detach_and_log_err(cx));
5231 } else {
5232 client.buffers.extend(search.await?.into_keys());
5233 }
5234 }
5235 60..=69 => {
5236 let worktree = project
5237 .read_with(cx, |project, cx| {
5238 project
5239 .worktrees(&cx)
5240 .filter(|worktree| {
5241 let worktree = worktree.read(cx);
5242 worktree.is_visible()
5243 && worktree.entries(false).any(|e| e.is_file())
5244 && worktree.root_entry().map_or(false, |e| e.is_dir())
5245 })
5246 .choose(&mut *rng.lock())
5247 })
5248 .unwrap();
5249 let (worktree_id, worktree_root_name) = worktree
5250 .read_with(cx, |worktree, _| {
5251 (worktree.id(), worktree.root_name().to_string())
5252 });
5253
5254 let mut new_name = String::new();
5255 for _ in 0..10 {
5256 let letter = rng.lock().gen_range('a'..='z');
5257 new_name.push(letter);
5258 }
5259 let mut new_path = PathBuf::new();
5260 new_path.push(new_name);
5261 new_path.set_extension("rs");
5262 log::info!(
5263 "{}: creating {:?} in worktree {} ({})",
5264 guest_username,
5265 new_path,
5266 worktree_id,
5267 worktree_root_name,
5268 );
5269 project
5270 .update(cx, |project, cx| {
5271 project.create_entry((worktree_id, new_path), false, cx)
5272 })
5273 .unwrap()
5274 .await?;
5275 }
5276 _ => {
5277 buffer.update(cx, |buffer, cx| {
5278 log::info!(
5279 "{}: updating buffer {} ({:?})",
5280 guest_username,
5281 buffer.remote_id(),
5282 buffer.file().unwrap().full_path(cx)
5283 );
5284 if rng.lock().gen_bool(0.7) {
5285 buffer.randomly_edit(&mut *rng.lock(), 5, cx);
5286 } else {
5287 buffer.randomly_undo_redo(&mut *rng.lock(), cx);
5288 }
5289 });
5290 }
5291 }
5292 cx.background().simulate_random_delay().await;
5293 }
5294 Ok(())
5295 }
5296
5297 let result = simulate_guest_internal(
5298 &mut self,
5299 &guest_username,
5300 project.clone(),
5301 op_start_signal,
5302 rng,
5303 &mut cx,
5304 )
5305 .await;
5306 log::info!("{}: done", guest_username);
5307
5308 self.project = Some(project);
5309 (self, cx, result.err())
5310 }
5311}
5312
5313impl Drop for TestClient {
5314 fn drop(&mut self) {
5315 self.client.tear_down();
5316 }
5317}
5318
5319impl Executor for Arc<gpui::executor::Background> {
5320 type Sleep = gpui::executor::Timer;
5321
5322 fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
5323 self.spawn(future).detach();
5324 }
5325
5326 fn sleep(&self, duration: Duration) -> Self::Sleep {
5327 self.as_ref().timer(duration)
5328 }
5329}
5330
5331fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
5332 channel
5333 .messages()
5334 .cursor::<()>()
5335 .map(|m| {
5336 (
5337 m.sender.github_login.clone(),
5338 m.body.clone(),
5339 m.is_pending(),
5340 )
5341 })
5342 .collect()
5343}
5344
5345struct EmptyView;
5346
5347impl gpui::Entity for EmptyView {
5348 type Event = ();
5349}
5350
5351impl gpui::View for EmptyView {
5352 fn ui_name() -> &'static str {
5353 "empty view"
5354 }
5355
5356 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
5357 gpui::Element::boxed(gpui::elements::Empty::new())
5358 }
5359}