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