integration_tests.rs

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