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, 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                    language: None,
4695                },
4696                project::HoverBlock {
4697                    text: "let foo = 42;".to_string(),
4698                    language: Some("Rust".to_string()),
4699                }
4700            ]
4701        );
4702    });
4703}
4704
4705#[gpui::test(iterations = 10)]
4706async fn test_project_symbols(
4707    deterministic: Arc<Deterministic>,
4708    cx_a: &mut TestAppContext,
4709    cx_b: &mut TestAppContext,
4710) {
4711    deterministic.forbid_parking();
4712    let mut server = TestServer::start(&deterministic).await;
4713    let client_a = server.create_client(cx_a, "user_a").await;
4714    let client_b = server.create_client(cx_b, "user_b").await;
4715    server
4716        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4717        .await;
4718    let active_call_a = cx_a.read(ActiveCall::global);
4719
4720    // Set up a fake language server.
4721    let mut language = Language::new(
4722        LanguageConfig {
4723            name: "Rust".into(),
4724            path_suffixes: vec!["rs".to_string()],
4725            ..Default::default()
4726        },
4727        Some(tree_sitter_rust::language()),
4728    );
4729    let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
4730    client_a.language_registry.add(Arc::new(language));
4731
4732    client_a
4733        .fs
4734        .insert_tree(
4735            "/code",
4736            json!({
4737                "crate-1": {
4738                    "one.rs": "const ONE: usize = 1;",
4739                },
4740                "crate-2": {
4741                    "two.rs": "const TWO: usize = 2; const THREE: usize = 3;",
4742                },
4743                "private": {
4744                    "passwords.txt": "the-password",
4745                }
4746            }),
4747        )
4748        .await;
4749    let (project_a, worktree_id) = client_a.build_local_project("/code/crate-1", cx_a).await;
4750    let project_id = active_call_a
4751        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4752        .await
4753        .unwrap();
4754    let project_b = client_b.build_remote_project(project_id, cx_b).await;
4755
4756    // Cause the language server to start.
4757    let _buffer = cx_b
4758        .background()
4759        .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
4760        .await
4761        .unwrap();
4762
4763    let fake_language_server = fake_language_servers.next().await.unwrap();
4764    fake_language_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(|_, _| async move {
4765        #[allow(deprecated)]
4766        Ok(Some(vec![lsp::SymbolInformation {
4767            name: "TWO".into(),
4768            location: lsp::Location {
4769                uri: lsp::Url::from_file_path("/code/crate-2/two.rs").unwrap(),
4770                range: lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
4771            },
4772            kind: lsp::SymbolKind::CONSTANT,
4773            tags: None,
4774            container_name: None,
4775            deprecated: None,
4776        }]))
4777    });
4778
4779    // Request the definition of a symbol as the guest.
4780    let symbols = project_b
4781        .update(cx_b, |p, cx| p.symbols("two", cx))
4782        .await
4783        .unwrap();
4784    assert_eq!(symbols.len(), 1);
4785    assert_eq!(symbols[0].name, "TWO");
4786
4787    // Open one of the returned symbols.
4788    let buffer_b_2 = project_b
4789        .update(cx_b, |project, cx| {
4790            project.open_buffer_for_symbol(&symbols[0], cx)
4791        })
4792        .await
4793        .unwrap();
4794    buffer_b_2.read_with(cx_b, |buffer, _| {
4795        assert_eq!(
4796            buffer.file().unwrap().path().as_ref(),
4797            Path::new("../crate-2/two.rs")
4798        );
4799    });
4800
4801    // Attempt to craft a symbol and violate host's privacy by opening an arbitrary file.
4802    let mut fake_symbol = symbols[0].clone();
4803    fake_symbol.path.path = Path::new("/code/secrets").into();
4804    let error = project_b
4805        .update(cx_b, |project, cx| {
4806            project.open_buffer_for_symbol(&fake_symbol, cx)
4807        })
4808        .await
4809        .unwrap_err();
4810    assert!(error.to_string().contains("invalid symbol signature"));
4811}
4812
4813#[gpui::test(iterations = 10)]
4814async fn test_open_buffer_while_getting_definition_pointing_to_it(
4815    deterministic: Arc<Deterministic>,
4816    cx_a: &mut TestAppContext,
4817    cx_b: &mut TestAppContext,
4818    mut rng: StdRng,
4819) {
4820    deterministic.forbid_parking();
4821    let mut server = TestServer::start(&deterministic).await;
4822    let client_a = server.create_client(cx_a, "user_a").await;
4823    let client_b = server.create_client(cx_b, "user_b").await;
4824    server
4825        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4826        .await;
4827    let active_call_a = cx_a.read(ActiveCall::global);
4828
4829    // Set up a fake language server.
4830    let mut language = Language::new(
4831        LanguageConfig {
4832            name: "Rust".into(),
4833            path_suffixes: vec!["rs".to_string()],
4834            ..Default::default()
4835        },
4836        Some(tree_sitter_rust::language()),
4837    );
4838    let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
4839    client_a.language_registry.add(Arc::new(language));
4840
4841    client_a
4842        .fs
4843        .insert_tree(
4844            "/root",
4845            json!({
4846                "a.rs": "const ONE: usize = b::TWO;",
4847                "b.rs": "const TWO: usize = 2",
4848            }),
4849        )
4850        .await;
4851    let (project_a, worktree_id) = client_a.build_local_project("/root", cx_a).await;
4852    let project_id = active_call_a
4853        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4854        .await
4855        .unwrap();
4856    let project_b = client_b.build_remote_project(project_id, cx_b).await;
4857
4858    let buffer_b1 = cx_b
4859        .background()
4860        .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
4861        .await
4862        .unwrap();
4863
4864    let fake_language_server = fake_language_servers.next().await.unwrap();
4865    fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
4866        Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4867            lsp::Location::new(
4868                lsp::Url::from_file_path("/root/b.rs").unwrap(),
4869                lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
4870            ),
4871        )))
4872    });
4873
4874    let definitions;
4875    let buffer_b2;
4876    if rng.gen() {
4877        definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
4878        buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
4879    } else {
4880        buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
4881        definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
4882    }
4883
4884    let buffer_b2 = buffer_b2.await.unwrap();
4885    let definitions = definitions.await.unwrap();
4886    assert_eq!(definitions.len(), 1);
4887    assert_eq!(definitions[0].target.buffer, buffer_b2);
4888}
4889
4890#[gpui::test(iterations = 10)]
4891async fn test_collaborating_with_code_actions(
4892    deterministic: Arc<Deterministic>,
4893    cx_a: &mut TestAppContext,
4894    cx_b: &mut TestAppContext,
4895) {
4896    deterministic.forbid_parking();
4897    cx_b.update(editor::init);
4898    let mut server = TestServer::start(&deterministic).await;
4899    let client_a = server.create_client(cx_a, "user_a").await;
4900    let client_b = server.create_client(cx_b, "user_b").await;
4901    server
4902        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4903        .await;
4904    let active_call_a = cx_a.read(ActiveCall::global);
4905
4906    // Set up a fake language server.
4907    let mut language = Language::new(
4908        LanguageConfig {
4909            name: "Rust".into(),
4910            path_suffixes: vec!["rs".to_string()],
4911            ..Default::default()
4912        },
4913        Some(tree_sitter_rust::language()),
4914    );
4915    let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
4916    client_a.language_registry.add(Arc::new(language));
4917
4918    client_a
4919        .fs
4920        .insert_tree(
4921            "/a",
4922            json!({
4923                "main.rs": "mod other;\nfn main() { let foo = other::foo(); }",
4924                "other.rs": "pub fn foo() -> usize { 4 }",
4925            }),
4926        )
4927        .await;
4928    let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
4929    let project_id = active_call_a
4930        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4931        .await
4932        .unwrap();
4933
4934    // Join the project as client B.
4935    let project_b = client_b.build_remote_project(project_id, cx_b).await;
4936    let (_window_b, workspace_b) = cx_b.add_window(|cx| Workspace::test_new(project_b.clone(), cx));
4937    let editor_b = workspace_b
4938        .update(cx_b, |workspace, cx| {
4939            workspace.open_path((worktree_id, "main.rs"), None, true, cx)
4940        })
4941        .await
4942        .unwrap()
4943        .downcast::<Editor>()
4944        .unwrap();
4945
4946    let mut fake_language_server = fake_language_servers.next().await.unwrap();
4947    fake_language_server
4948        .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
4949            assert_eq!(
4950                params.text_document.uri,
4951                lsp::Url::from_file_path("/a/main.rs").unwrap(),
4952            );
4953            assert_eq!(params.range.start, lsp::Position::new(0, 0));
4954            assert_eq!(params.range.end, lsp::Position::new(0, 0));
4955            Ok(None)
4956        })
4957        .next()
4958        .await;
4959
4960    // Move cursor to a location that contains code actions.
4961    editor_b.update(cx_b, |editor, cx| {
4962        editor.change_selections(None, cx, |s| {
4963            s.select_ranges([Point::new(1, 31)..Point::new(1, 31)])
4964        });
4965        cx.focus(&editor_b);
4966    });
4967
4968    fake_language_server
4969        .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
4970            assert_eq!(
4971                params.text_document.uri,
4972                lsp::Url::from_file_path("/a/main.rs").unwrap(),
4973            );
4974            assert_eq!(params.range.start, lsp::Position::new(1, 31));
4975            assert_eq!(params.range.end, lsp::Position::new(1, 31));
4976
4977            Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
4978                lsp::CodeAction {
4979                    title: "Inline into all callers".to_string(),
4980                    edit: Some(lsp::WorkspaceEdit {
4981                        changes: Some(
4982                            [
4983                                (
4984                                    lsp::Url::from_file_path("/a/main.rs").unwrap(),
4985                                    vec![lsp::TextEdit::new(
4986                                        lsp::Range::new(
4987                                            lsp::Position::new(1, 22),
4988                                            lsp::Position::new(1, 34),
4989                                        ),
4990                                        "4".to_string(),
4991                                    )],
4992                                ),
4993                                (
4994                                    lsp::Url::from_file_path("/a/other.rs").unwrap(),
4995                                    vec![lsp::TextEdit::new(
4996                                        lsp::Range::new(
4997                                            lsp::Position::new(0, 0),
4998                                            lsp::Position::new(0, 27),
4999                                        ),
5000                                        "".to_string(),
5001                                    )],
5002                                ),
5003                            ]
5004                            .into_iter()
5005                            .collect(),
5006                        ),
5007                        ..Default::default()
5008                    }),
5009                    data: Some(json!({
5010                        "codeActionParams": {
5011                            "range": {
5012                                "start": {"line": 1, "column": 31},
5013                                "end": {"line": 1, "column": 31},
5014                            }
5015                        }
5016                    })),
5017                    ..Default::default()
5018                },
5019            )]))
5020        })
5021        .next()
5022        .await;
5023
5024    // Toggle code actions and wait for them to display.
5025    editor_b.update(cx_b, |editor, cx| {
5026        editor.toggle_code_actions(
5027            &ToggleCodeActions {
5028                deployed_from_indicator: false,
5029            },
5030            cx,
5031        );
5032    });
5033    cx_a.foreground().run_until_parked();
5034    editor_b.read_with(cx_b, |editor, _| assert!(editor.context_menu_visible()));
5035
5036    fake_language_server.remove_request_handler::<lsp::request::CodeActionRequest>();
5037
5038    // Confirming the code action will trigger a resolve request.
5039    let confirm_action = workspace_b
5040        .update(cx_b, |workspace, cx| {
5041            Editor::confirm_code_action(workspace, &ConfirmCodeAction { item_ix: Some(0) }, cx)
5042        })
5043        .unwrap();
5044    fake_language_server.handle_request::<lsp::request::CodeActionResolveRequest, _, _>(
5045        |_, _| async move {
5046            Ok(lsp::CodeAction {
5047                title: "Inline into all callers".to_string(),
5048                edit: Some(lsp::WorkspaceEdit {
5049                    changes: Some(
5050                        [
5051                            (
5052                                lsp::Url::from_file_path("/a/main.rs").unwrap(),
5053                                vec![lsp::TextEdit::new(
5054                                    lsp::Range::new(
5055                                        lsp::Position::new(1, 22),
5056                                        lsp::Position::new(1, 34),
5057                                    ),
5058                                    "4".to_string(),
5059                                )],
5060                            ),
5061                            (
5062                                lsp::Url::from_file_path("/a/other.rs").unwrap(),
5063                                vec![lsp::TextEdit::new(
5064                                    lsp::Range::new(
5065                                        lsp::Position::new(0, 0),
5066                                        lsp::Position::new(0, 27),
5067                                    ),
5068                                    "".to_string(),
5069                                )],
5070                            ),
5071                        ]
5072                        .into_iter()
5073                        .collect(),
5074                    ),
5075                    ..Default::default()
5076                }),
5077                ..Default::default()
5078            })
5079        },
5080    );
5081
5082    // After the action is confirmed, an editor containing both modified files is opened.
5083    confirm_action.await.unwrap();
5084    let code_action_editor = workspace_b.read_with(cx_b, |workspace, cx| {
5085        workspace
5086            .active_item(cx)
5087            .unwrap()
5088            .downcast::<Editor>()
5089            .unwrap()
5090    });
5091    code_action_editor.update(cx_b, |editor, cx| {
5092        assert_eq!(editor.text(cx), "mod other;\nfn main() { let foo = 4; }\n");
5093        editor.undo(&Undo, cx);
5094        assert_eq!(
5095            editor.text(cx),
5096            "mod other;\nfn main() { let foo = other::foo(); }\npub fn foo() -> usize { 4 }"
5097        );
5098        editor.redo(&Redo, cx);
5099        assert_eq!(editor.text(cx), "mod other;\nfn main() { let foo = 4; }\n");
5100    });
5101}
5102
5103#[gpui::test(iterations = 10)]
5104async fn test_collaborating_with_renames(
5105    deterministic: Arc<Deterministic>,
5106    cx_a: &mut TestAppContext,
5107    cx_b: &mut TestAppContext,
5108) {
5109    deterministic.forbid_parking();
5110    cx_b.update(editor::init);
5111    let mut server = TestServer::start(&deterministic).await;
5112    let client_a = server.create_client(cx_a, "user_a").await;
5113    let client_b = server.create_client(cx_b, "user_b").await;
5114    server
5115        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5116        .await;
5117    let active_call_a = cx_a.read(ActiveCall::global);
5118
5119    // Set up a fake language server.
5120    let mut language = Language::new(
5121        LanguageConfig {
5122            name: "Rust".into(),
5123            path_suffixes: vec!["rs".to_string()],
5124            ..Default::default()
5125        },
5126        Some(tree_sitter_rust::language()),
5127    );
5128    let mut fake_language_servers = language
5129        .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
5130            capabilities: lsp::ServerCapabilities {
5131                rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
5132                    prepare_provider: Some(true),
5133                    work_done_progress_options: Default::default(),
5134                })),
5135                ..Default::default()
5136            },
5137            ..Default::default()
5138        }))
5139        .await;
5140    client_a.language_registry.add(Arc::new(language));
5141
5142    client_a
5143        .fs
5144        .insert_tree(
5145            "/dir",
5146            json!({
5147                "one.rs": "const ONE: usize = 1;",
5148                "two.rs": "const TWO: usize = one::ONE + one::ONE;"
5149            }),
5150        )
5151        .await;
5152    let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
5153    let project_id = active_call_a
5154        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5155        .await
5156        .unwrap();
5157    let project_b = client_b.build_remote_project(project_id, cx_b).await;
5158
5159    let (_window_b, workspace_b) = cx_b.add_window(|cx| Workspace::test_new(project_b.clone(), cx));
5160    let editor_b = workspace_b
5161        .update(cx_b, |workspace, cx| {
5162            workspace.open_path((worktree_id, "one.rs"), None, true, cx)
5163        })
5164        .await
5165        .unwrap()
5166        .downcast::<Editor>()
5167        .unwrap();
5168    let fake_language_server = fake_language_servers.next().await.unwrap();
5169
5170    // Move cursor to a location that can be renamed.
5171    let prepare_rename = editor_b.update(cx_b, |editor, cx| {
5172        editor.change_selections(None, cx, |s| s.select_ranges([7..7]));
5173        editor.rename(&Rename, cx).unwrap()
5174    });
5175
5176    fake_language_server
5177        .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
5178            assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
5179            assert_eq!(params.position, lsp::Position::new(0, 7));
5180            Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
5181                lsp::Position::new(0, 6),
5182                lsp::Position::new(0, 9),
5183            ))))
5184        })
5185        .next()
5186        .await
5187        .unwrap();
5188    prepare_rename.await.unwrap();
5189    editor_b.update(cx_b, |editor, cx| {
5190        let rename = editor.pending_rename().unwrap();
5191        let buffer = editor.buffer().read(cx).snapshot(cx);
5192        assert_eq!(
5193            rename.range.start.to_offset(&buffer)..rename.range.end.to_offset(&buffer),
5194            6..9
5195        );
5196        rename.editor.update(cx, |rename_editor, cx| {
5197            rename_editor.buffer().update(cx, |rename_buffer, cx| {
5198                rename_buffer.edit([(0..3, "THREE")], None, cx);
5199            });
5200        });
5201    });
5202
5203    let confirm_rename = workspace_b.update(cx_b, |workspace, cx| {
5204        Editor::confirm_rename(workspace, &ConfirmRename, cx).unwrap()
5205    });
5206    fake_language_server
5207        .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
5208            assert_eq!(
5209                params.text_document_position.text_document.uri.as_str(),
5210                "file:///dir/one.rs"
5211            );
5212            assert_eq!(
5213                params.text_document_position.position,
5214                lsp::Position::new(0, 6)
5215            );
5216            assert_eq!(params.new_name, "THREE");
5217            Ok(Some(lsp::WorkspaceEdit {
5218                changes: Some(
5219                    [
5220                        (
5221                            lsp::Url::from_file_path("/dir/one.rs").unwrap(),
5222                            vec![lsp::TextEdit::new(
5223                                lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
5224                                "THREE".to_string(),
5225                            )],
5226                        ),
5227                        (
5228                            lsp::Url::from_file_path("/dir/two.rs").unwrap(),
5229                            vec![
5230                                lsp::TextEdit::new(
5231                                    lsp::Range::new(
5232                                        lsp::Position::new(0, 24),
5233                                        lsp::Position::new(0, 27),
5234                                    ),
5235                                    "THREE".to_string(),
5236                                ),
5237                                lsp::TextEdit::new(
5238                                    lsp::Range::new(
5239                                        lsp::Position::new(0, 35),
5240                                        lsp::Position::new(0, 38),
5241                                    ),
5242                                    "THREE".to_string(),
5243                                ),
5244                            ],
5245                        ),
5246                    ]
5247                    .into_iter()
5248                    .collect(),
5249                ),
5250                ..Default::default()
5251            }))
5252        })
5253        .next()
5254        .await
5255        .unwrap();
5256    confirm_rename.await.unwrap();
5257
5258    let rename_editor = workspace_b.read_with(cx_b, |workspace, cx| {
5259        workspace
5260            .active_item(cx)
5261            .unwrap()
5262            .downcast::<Editor>()
5263            .unwrap()
5264    });
5265    rename_editor.update(cx_b, |editor, cx| {
5266        assert_eq!(
5267            editor.text(cx),
5268            "const THREE: usize = 1;\nconst TWO: usize = one::THREE + one::THREE;"
5269        );
5270        editor.undo(&Undo, cx);
5271        assert_eq!(
5272            editor.text(cx),
5273            "const ONE: usize = 1;\nconst TWO: usize = one::ONE + one::ONE;"
5274        );
5275        editor.redo(&Redo, cx);
5276        assert_eq!(
5277            editor.text(cx),
5278            "const THREE: usize = 1;\nconst TWO: usize = one::THREE + one::THREE;"
5279        );
5280    });
5281
5282    // Ensure temporary rename edits cannot be undone/redone.
5283    editor_b.update(cx_b, |editor, cx| {
5284        editor.undo(&Undo, cx);
5285        assert_eq!(editor.text(cx), "const ONE: usize = 1;");
5286        editor.undo(&Undo, cx);
5287        assert_eq!(editor.text(cx), "const ONE: usize = 1;");
5288        editor.redo(&Redo, cx);
5289        assert_eq!(editor.text(cx), "const THREE: usize = 1;");
5290    })
5291}
5292
5293#[gpui::test(iterations = 10)]
5294async fn test_language_server_statuses(
5295    deterministic: Arc<Deterministic>,
5296    cx_a: &mut TestAppContext,
5297    cx_b: &mut TestAppContext,
5298) {
5299    deterministic.forbid_parking();
5300
5301    cx_b.update(editor::init);
5302    let mut server = TestServer::start(&deterministic).await;
5303    let client_a = server.create_client(cx_a, "user_a").await;
5304    let client_b = server.create_client(cx_b, "user_b").await;
5305    server
5306        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5307        .await;
5308    let active_call_a = cx_a.read(ActiveCall::global);
5309
5310    // Set up a fake language server.
5311    let mut language = Language::new(
5312        LanguageConfig {
5313            name: "Rust".into(),
5314            path_suffixes: vec!["rs".to_string()],
5315            ..Default::default()
5316        },
5317        Some(tree_sitter_rust::language()),
5318    );
5319    let mut fake_language_servers = language
5320        .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
5321            name: "the-language-server",
5322            ..Default::default()
5323        }))
5324        .await;
5325    client_a.language_registry.add(Arc::new(language));
5326
5327    client_a
5328        .fs
5329        .insert_tree(
5330            "/dir",
5331            json!({
5332                "main.rs": "const ONE: usize = 1;",
5333            }),
5334        )
5335        .await;
5336    let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
5337
5338    let _buffer_a = project_a
5339        .update(cx_a, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
5340        .await
5341        .unwrap();
5342
5343    let fake_language_server = fake_language_servers.next().await.unwrap();
5344    fake_language_server.start_progress("the-token").await;
5345    fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
5346        token: lsp::NumberOrString::String("the-token".to_string()),
5347        value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Report(
5348            lsp::WorkDoneProgressReport {
5349                message: Some("the-message".to_string()),
5350                ..Default::default()
5351            },
5352        )),
5353    });
5354    deterministic.run_until_parked();
5355    project_a.read_with(cx_a, |project, _| {
5356        let status = project.language_server_statuses().next().unwrap();
5357        assert_eq!(status.name, "the-language-server");
5358        assert_eq!(status.pending_work.len(), 1);
5359        assert_eq!(
5360            status.pending_work["the-token"].message.as_ref().unwrap(),
5361            "the-message"
5362        );
5363    });
5364
5365    let project_id = active_call_a
5366        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5367        .await
5368        .unwrap();
5369    deterministic.run_until_parked();
5370    let project_b = client_b.build_remote_project(project_id, cx_b).await;
5371    project_b.read_with(cx_b, |project, _| {
5372        let status = project.language_server_statuses().next().unwrap();
5373        assert_eq!(status.name, "the-language-server");
5374    });
5375
5376    fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
5377        token: lsp::NumberOrString::String("the-token".to_string()),
5378        value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Report(
5379            lsp::WorkDoneProgressReport {
5380                message: Some("the-message-2".to_string()),
5381                ..Default::default()
5382            },
5383        )),
5384    });
5385    deterministic.run_until_parked();
5386    project_a.read_with(cx_a, |project, _| {
5387        let status = project.language_server_statuses().next().unwrap();
5388        assert_eq!(status.name, "the-language-server");
5389        assert_eq!(status.pending_work.len(), 1);
5390        assert_eq!(
5391            status.pending_work["the-token"].message.as_ref().unwrap(),
5392            "the-message-2"
5393        );
5394    });
5395    project_b.read_with(cx_b, |project, _| {
5396        let status = project.language_server_statuses().next().unwrap();
5397        assert_eq!(status.name, "the-language-server");
5398        assert_eq!(status.pending_work.len(), 1);
5399        assert_eq!(
5400            status.pending_work["the-token"].message.as_ref().unwrap(),
5401            "the-message-2"
5402        );
5403    });
5404}
5405
5406#[gpui::test(iterations = 10)]
5407async fn test_contacts(
5408    deterministic: Arc<Deterministic>,
5409    cx_a: &mut TestAppContext,
5410    cx_b: &mut TestAppContext,
5411    cx_c: &mut TestAppContext,
5412    cx_d: &mut TestAppContext,
5413) {
5414    deterministic.forbid_parking();
5415    let mut server = TestServer::start(&deterministic).await;
5416    let client_a = server.create_client(cx_a, "user_a").await;
5417    let client_b = server.create_client(cx_b, "user_b").await;
5418    let client_c = server.create_client(cx_c, "user_c").await;
5419    let client_d = server.create_client(cx_d, "user_d").await;
5420    server
5421        .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
5422        .await;
5423    let active_call_a = cx_a.read(ActiveCall::global);
5424    let active_call_b = cx_b.read(ActiveCall::global);
5425    let active_call_c = cx_c.read(ActiveCall::global);
5426    let _active_call_d = cx_d.read(ActiveCall::global);
5427
5428    deterministic.run_until_parked();
5429    assert_eq!(
5430        contacts(&client_a, cx_a),
5431        [
5432            ("user_b".to_string(), "online", "free"),
5433            ("user_c".to_string(), "online", "free")
5434        ]
5435    );
5436    assert_eq!(
5437        contacts(&client_b, cx_b),
5438        [
5439            ("user_a".to_string(), "online", "free"),
5440            ("user_c".to_string(), "online", "free")
5441        ]
5442    );
5443    assert_eq!(
5444        contacts(&client_c, cx_c),
5445        [
5446            ("user_a".to_string(), "online", "free"),
5447            ("user_b".to_string(), "online", "free")
5448        ]
5449    );
5450    assert_eq!(contacts(&client_d, cx_d), []);
5451
5452    server.disconnect_client(client_c.peer_id().unwrap());
5453    server.forbid_connections();
5454    deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
5455    assert_eq!(
5456        contacts(&client_a, cx_a),
5457        [
5458            ("user_b".to_string(), "online", "free"),
5459            ("user_c".to_string(), "offline", "free")
5460        ]
5461    );
5462    assert_eq!(
5463        contacts(&client_b, cx_b),
5464        [
5465            ("user_a".to_string(), "online", "free"),
5466            ("user_c".to_string(), "offline", "free")
5467        ]
5468    );
5469    assert_eq!(contacts(&client_c, cx_c), []);
5470    assert_eq!(contacts(&client_d, cx_d), []);
5471
5472    server.allow_connections();
5473    client_c
5474        .authenticate_and_connect(false, &cx_c.to_async())
5475        .await
5476        .unwrap();
5477
5478    deterministic.run_until_parked();
5479    assert_eq!(
5480        contacts(&client_a, cx_a),
5481        [
5482            ("user_b".to_string(), "online", "free"),
5483            ("user_c".to_string(), "online", "free")
5484        ]
5485    );
5486    assert_eq!(
5487        contacts(&client_b, cx_b),
5488        [
5489            ("user_a".to_string(), "online", "free"),
5490            ("user_c".to_string(), "online", "free")
5491        ]
5492    );
5493    assert_eq!(
5494        contacts(&client_c, cx_c),
5495        [
5496            ("user_a".to_string(), "online", "free"),
5497            ("user_b".to_string(), "online", "free")
5498        ]
5499    );
5500    assert_eq!(contacts(&client_d, cx_d), []);
5501
5502    active_call_a
5503        .update(cx_a, |call, cx| {
5504            call.invite(client_b.user_id().unwrap(), None, cx)
5505        })
5506        .await
5507        .unwrap();
5508    deterministic.run_until_parked();
5509    assert_eq!(
5510        contacts(&client_a, cx_a),
5511        [
5512            ("user_b".to_string(), "online", "busy"),
5513            ("user_c".to_string(), "online", "free")
5514        ]
5515    );
5516    assert_eq!(
5517        contacts(&client_b, cx_b),
5518        [
5519            ("user_a".to_string(), "online", "busy"),
5520            ("user_c".to_string(), "online", "free")
5521        ]
5522    );
5523    assert_eq!(
5524        contacts(&client_c, cx_c),
5525        [
5526            ("user_a".to_string(), "online", "busy"),
5527            ("user_b".to_string(), "online", "busy")
5528        ]
5529    );
5530    assert_eq!(contacts(&client_d, cx_d), []);
5531
5532    // Client B and client D become contacts while client B is being called.
5533    server
5534        .make_contacts(&mut [(&client_b, cx_b), (&client_d, cx_d)])
5535        .await;
5536    deterministic.run_until_parked();
5537    assert_eq!(
5538        contacts(&client_a, cx_a),
5539        [
5540            ("user_b".to_string(), "online", "busy"),
5541            ("user_c".to_string(), "online", "free")
5542        ]
5543    );
5544    assert_eq!(
5545        contacts(&client_b, cx_b),
5546        [
5547            ("user_a".to_string(), "online", "busy"),
5548            ("user_c".to_string(), "online", "free"),
5549            ("user_d".to_string(), "online", "free"),
5550        ]
5551    );
5552    assert_eq!(
5553        contacts(&client_c, cx_c),
5554        [
5555            ("user_a".to_string(), "online", "busy"),
5556            ("user_b".to_string(), "online", "busy")
5557        ]
5558    );
5559    assert_eq!(
5560        contacts(&client_d, cx_d),
5561        [("user_b".to_string(), "online", "busy")]
5562    );
5563
5564    active_call_b.update(cx_b, |call, _| call.decline_incoming().unwrap());
5565    deterministic.run_until_parked();
5566    assert_eq!(
5567        contacts(&client_a, cx_a),
5568        [
5569            ("user_b".to_string(), "online", "free"),
5570            ("user_c".to_string(), "online", "free")
5571        ]
5572    );
5573    assert_eq!(
5574        contacts(&client_b, cx_b),
5575        [
5576            ("user_a".to_string(), "online", "free"),
5577            ("user_c".to_string(), "online", "free"),
5578            ("user_d".to_string(), "online", "free")
5579        ]
5580    );
5581    assert_eq!(
5582        contacts(&client_c, cx_c),
5583        [
5584            ("user_a".to_string(), "online", "free"),
5585            ("user_b".to_string(), "online", "free")
5586        ]
5587    );
5588    assert_eq!(
5589        contacts(&client_d, cx_d),
5590        [("user_b".to_string(), "online", "free")]
5591    );
5592
5593    active_call_c
5594        .update(cx_c, |call, cx| {
5595            call.invite(client_a.user_id().unwrap(), None, cx)
5596        })
5597        .await
5598        .unwrap();
5599    deterministic.run_until_parked();
5600    assert_eq!(
5601        contacts(&client_a, cx_a),
5602        [
5603            ("user_b".to_string(), "online", "free"),
5604            ("user_c".to_string(), "online", "busy")
5605        ]
5606    );
5607    assert_eq!(
5608        contacts(&client_b, cx_b),
5609        [
5610            ("user_a".to_string(), "online", "busy"),
5611            ("user_c".to_string(), "online", "busy"),
5612            ("user_d".to_string(), "online", "free")
5613        ]
5614    );
5615    assert_eq!(
5616        contacts(&client_c, cx_c),
5617        [
5618            ("user_a".to_string(), "online", "busy"),
5619            ("user_b".to_string(), "online", "free")
5620        ]
5621    );
5622    assert_eq!(
5623        contacts(&client_d, cx_d),
5624        [("user_b".to_string(), "online", "free")]
5625    );
5626
5627    active_call_a
5628        .update(cx_a, |call, cx| call.accept_incoming(cx))
5629        .await
5630        .unwrap();
5631    deterministic.run_until_parked();
5632    assert_eq!(
5633        contacts(&client_a, cx_a),
5634        [
5635            ("user_b".to_string(), "online", "free"),
5636            ("user_c".to_string(), "online", "busy")
5637        ]
5638    );
5639    assert_eq!(
5640        contacts(&client_b, cx_b),
5641        [
5642            ("user_a".to_string(), "online", "busy"),
5643            ("user_c".to_string(), "online", "busy"),
5644            ("user_d".to_string(), "online", "free")
5645        ]
5646    );
5647    assert_eq!(
5648        contacts(&client_c, cx_c),
5649        [
5650            ("user_a".to_string(), "online", "busy"),
5651            ("user_b".to_string(), "online", "free")
5652        ]
5653    );
5654    assert_eq!(
5655        contacts(&client_d, cx_d),
5656        [("user_b".to_string(), "online", "free")]
5657    );
5658
5659    active_call_a
5660        .update(cx_a, |call, cx| {
5661            call.invite(client_b.user_id().unwrap(), None, cx)
5662        })
5663        .await
5664        .unwrap();
5665    deterministic.run_until_parked();
5666    assert_eq!(
5667        contacts(&client_a, cx_a),
5668        [
5669            ("user_b".to_string(), "online", "busy"),
5670            ("user_c".to_string(), "online", "busy")
5671        ]
5672    );
5673    assert_eq!(
5674        contacts(&client_b, cx_b),
5675        [
5676            ("user_a".to_string(), "online", "busy"),
5677            ("user_c".to_string(), "online", "busy"),
5678            ("user_d".to_string(), "online", "free")
5679        ]
5680    );
5681    assert_eq!(
5682        contacts(&client_c, cx_c),
5683        [
5684            ("user_a".to_string(), "online", "busy"),
5685            ("user_b".to_string(), "online", "busy")
5686        ]
5687    );
5688    assert_eq!(
5689        contacts(&client_d, cx_d),
5690        [("user_b".to_string(), "online", "busy")]
5691    );
5692
5693    active_call_a
5694        .update(cx_a, |call, cx| call.hang_up(cx))
5695        .await
5696        .unwrap();
5697    deterministic.run_until_parked();
5698    assert_eq!(
5699        contacts(&client_a, cx_a),
5700        [
5701            ("user_b".to_string(), "online", "free"),
5702            ("user_c".to_string(), "online", "free")
5703        ]
5704    );
5705    assert_eq!(
5706        contacts(&client_b, cx_b),
5707        [
5708            ("user_a".to_string(), "online", "free"),
5709            ("user_c".to_string(), "online", "free"),
5710            ("user_d".to_string(), "online", "free")
5711        ]
5712    );
5713    assert_eq!(
5714        contacts(&client_c, cx_c),
5715        [
5716            ("user_a".to_string(), "online", "free"),
5717            ("user_b".to_string(), "online", "free")
5718        ]
5719    );
5720    assert_eq!(
5721        contacts(&client_d, cx_d),
5722        [("user_b".to_string(), "online", "free")]
5723    );
5724
5725    active_call_a
5726        .update(cx_a, |call, cx| {
5727            call.invite(client_b.user_id().unwrap(), None, cx)
5728        })
5729        .await
5730        .unwrap();
5731    deterministic.run_until_parked();
5732    assert_eq!(
5733        contacts(&client_a, cx_a),
5734        [
5735            ("user_b".to_string(), "online", "busy"),
5736            ("user_c".to_string(), "online", "free")
5737        ]
5738    );
5739    assert_eq!(
5740        contacts(&client_b, cx_b),
5741        [
5742            ("user_a".to_string(), "online", "busy"),
5743            ("user_c".to_string(), "online", "free"),
5744            ("user_d".to_string(), "online", "free")
5745        ]
5746    );
5747    assert_eq!(
5748        contacts(&client_c, cx_c),
5749        [
5750            ("user_a".to_string(), "online", "busy"),
5751            ("user_b".to_string(), "online", "busy")
5752        ]
5753    );
5754    assert_eq!(
5755        contacts(&client_d, cx_d),
5756        [("user_b".to_string(), "online", "busy")]
5757    );
5758
5759    server.forbid_connections();
5760    server.disconnect_client(client_a.peer_id().unwrap());
5761    deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
5762    assert_eq!(contacts(&client_a, cx_a), []);
5763    assert_eq!(
5764        contacts(&client_b, cx_b),
5765        [
5766            ("user_a".to_string(), "offline", "free"),
5767            ("user_c".to_string(), "online", "free"),
5768            ("user_d".to_string(), "online", "free")
5769        ]
5770    );
5771    assert_eq!(
5772        contacts(&client_c, cx_c),
5773        [
5774            ("user_a".to_string(), "offline", "free"),
5775            ("user_b".to_string(), "online", "free")
5776        ]
5777    );
5778    assert_eq!(
5779        contacts(&client_d, cx_d),
5780        [("user_b".to_string(), "online", "free")]
5781    );
5782
5783    // Test removing a contact
5784    client_b
5785        .user_store
5786        .update(cx_b, |store, cx| {
5787            store.remove_contact(client_c.user_id().unwrap(), cx)
5788        })
5789        .await
5790        .unwrap();
5791    deterministic.run_until_parked();
5792    assert_eq!(
5793        contacts(&client_b, cx_b),
5794        [
5795            ("user_a".to_string(), "offline", "free"),
5796            ("user_d".to_string(), "online", "free")
5797        ]
5798    );
5799    assert_eq!(
5800        contacts(&client_c, cx_c),
5801        [("user_a".to_string(), "offline", "free"),]
5802    );
5803
5804    fn contacts(
5805        client: &TestClient,
5806        cx: &TestAppContext,
5807    ) -> Vec<(String, &'static str, &'static str)> {
5808        client.user_store.read_with(cx, |store, _| {
5809            store
5810                .contacts()
5811                .iter()
5812                .map(|contact| {
5813                    (
5814                        contact.user.github_login.clone(),
5815                        if contact.online { "online" } else { "offline" },
5816                        if contact.busy { "busy" } else { "free" },
5817                    )
5818                })
5819                .collect()
5820        })
5821    }
5822}
5823
5824#[gpui::test(iterations = 10)]
5825async fn test_contact_requests(
5826    deterministic: Arc<Deterministic>,
5827    cx_a: &mut TestAppContext,
5828    cx_a2: &mut TestAppContext,
5829    cx_b: &mut TestAppContext,
5830    cx_b2: &mut TestAppContext,
5831    cx_c: &mut TestAppContext,
5832    cx_c2: &mut TestAppContext,
5833) {
5834    deterministic.forbid_parking();
5835
5836    // Connect to a server as 3 clients.
5837    let mut server = TestServer::start(&deterministic).await;
5838    let client_a = server.create_client(cx_a, "user_a").await;
5839    let client_a2 = server.create_client(cx_a2, "user_a").await;
5840    let client_b = server.create_client(cx_b, "user_b").await;
5841    let client_b2 = server.create_client(cx_b2, "user_b").await;
5842    let client_c = server.create_client(cx_c, "user_c").await;
5843    let client_c2 = server.create_client(cx_c2, "user_c").await;
5844
5845    assert_eq!(client_a.user_id().unwrap(), client_a2.user_id().unwrap());
5846    assert_eq!(client_b.user_id().unwrap(), client_b2.user_id().unwrap());
5847    assert_eq!(client_c.user_id().unwrap(), client_c2.user_id().unwrap());
5848
5849    // User A and User C request that user B become their contact.
5850    client_a
5851        .user_store
5852        .update(cx_a, |store, cx| {
5853            store.request_contact(client_b.user_id().unwrap(), cx)
5854        })
5855        .await
5856        .unwrap();
5857    client_c
5858        .user_store
5859        .update(cx_c, |store, cx| {
5860            store.request_contact(client_b.user_id().unwrap(), cx)
5861        })
5862        .await
5863        .unwrap();
5864    deterministic.run_until_parked();
5865
5866    // All users see the pending request appear in all their clients.
5867    assert_eq!(
5868        client_a.summarize_contacts(cx_a).outgoing_requests,
5869        &["user_b"]
5870    );
5871    assert_eq!(
5872        client_a2.summarize_contacts(cx_a2).outgoing_requests,
5873        &["user_b"]
5874    );
5875    assert_eq!(
5876        client_b.summarize_contacts(cx_b).incoming_requests,
5877        &["user_a", "user_c"]
5878    );
5879    assert_eq!(
5880        client_b2.summarize_contacts(cx_b2).incoming_requests,
5881        &["user_a", "user_c"]
5882    );
5883    assert_eq!(
5884        client_c.summarize_contacts(cx_c).outgoing_requests,
5885        &["user_b"]
5886    );
5887    assert_eq!(
5888        client_c2.summarize_contacts(cx_c2).outgoing_requests,
5889        &["user_b"]
5890    );
5891
5892    // Contact requests are present upon connecting (tested here via disconnect/reconnect)
5893    disconnect_and_reconnect(&client_a, cx_a).await;
5894    disconnect_and_reconnect(&client_b, cx_b).await;
5895    disconnect_and_reconnect(&client_c, cx_c).await;
5896    deterministic.run_until_parked();
5897    assert_eq!(
5898        client_a.summarize_contacts(cx_a).outgoing_requests,
5899        &["user_b"]
5900    );
5901    assert_eq!(
5902        client_b.summarize_contacts(cx_b).incoming_requests,
5903        &["user_a", "user_c"]
5904    );
5905    assert_eq!(
5906        client_c.summarize_contacts(cx_c).outgoing_requests,
5907        &["user_b"]
5908    );
5909
5910    // User B accepts the request from user A.
5911    client_b
5912        .user_store
5913        .update(cx_b, |store, cx| {
5914            store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
5915        })
5916        .await
5917        .unwrap();
5918
5919    deterministic.run_until_parked();
5920
5921    // User B sees user A as their contact now in all client, and the incoming request from them is removed.
5922    let contacts_b = client_b.summarize_contacts(cx_b);
5923    assert_eq!(contacts_b.current, &["user_a"]);
5924    assert_eq!(contacts_b.incoming_requests, &["user_c"]);
5925    let contacts_b2 = client_b2.summarize_contacts(cx_b2);
5926    assert_eq!(contacts_b2.current, &["user_a"]);
5927    assert_eq!(contacts_b2.incoming_requests, &["user_c"]);
5928
5929    // User A sees user B as their contact now in all clients, and the outgoing request to them is removed.
5930    let contacts_a = client_a.summarize_contacts(cx_a);
5931    assert_eq!(contacts_a.current, &["user_b"]);
5932    assert!(contacts_a.outgoing_requests.is_empty());
5933    let contacts_a2 = client_a2.summarize_contacts(cx_a2);
5934    assert_eq!(contacts_a2.current, &["user_b"]);
5935    assert!(contacts_a2.outgoing_requests.is_empty());
5936
5937    // Contacts are present upon connecting (tested here via disconnect/reconnect)
5938    disconnect_and_reconnect(&client_a, cx_a).await;
5939    disconnect_and_reconnect(&client_b, cx_b).await;
5940    disconnect_and_reconnect(&client_c, cx_c).await;
5941    deterministic.run_until_parked();
5942    assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
5943    assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
5944    assert_eq!(
5945        client_b.summarize_contacts(cx_b).incoming_requests,
5946        &["user_c"]
5947    );
5948    assert!(client_c.summarize_contacts(cx_c).current.is_empty());
5949    assert_eq!(
5950        client_c.summarize_contacts(cx_c).outgoing_requests,
5951        &["user_b"]
5952    );
5953
5954    // User B rejects the request from user C.
5955    client_b
5956        .user_store
5957        .update(cx_b, |store, cx| {
5958            store.respond_to_contact_request(client_c.user_id().unwrap(), false, cx)
5959        })
5960        .await
5961        .unwrap();
5962
5963    deterministic.run_until_parked();
5964
5965    // User B doesn't see user C as their contact, and the incoming request from them is removed.
5966    let contacts_b = client_b.summarize_contacts(cx_b);
5967    assert_eq!(contacts_b.current, &["user_a"]);
5968    assert!(contacts_b.incoming_requests.is_empty());
5969    let contacts_b2 = client_b2.summarize_contacts(cx_b2);
5970    assert_eq!(contacts_b2.current, &["user_a"]);
5971    assert!(contacts_b2.incoming_requests.is_empty());
5972
5973    // User C doesn't see user B as their contact, and the outgoing request to them is removed.
5974    let contacts_c = client_c.summarize_contacts(cx_c);
5975    assert!(contacts_c.current.is_empty());
5976    assert!(contacts_c.outgoing_requests.is_empty());
5977    let contacts_c2 = client_c2.summarize_contacts(cx_c2);
5978    assert!(contacts_c2.current.is_empty());
5979    assert!(contacts_c2.outgoing_requests.is_empty());
5980
5981    // Incoming/outgoing requests are not present upon connecting (tested here via disconnect/reconnect)
5982    disconnect_and_reconnect(&client_a, cx_a).await;
5983    disconnect_and_reconnect(&client_b, cx_b).await;
5984    disconnect_and_reconnect(&client_c, cx_c).await;
5985    deterministic.run_until_parked();
5986    assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
5987    assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
5988    assert!(client_b
5989        .summarize_contacts(cx_b)
5990        .incoming_requests
5991        .is_empty());
5992    assert!(client_c.summarize_contacts(cx_c).current.is_empty());
5993    assert!(client_c
5994        .summarize_contacts(cx_c)
5995        .outgoing_requests
5996        .is_empty());
5997
5998    async fn disconnect_and_reconnect(client: &TestClient, cx: &mut TestAppContext) {
5999        client.disconnect(&cx.to_async());
6000        client.clear_contacts(cx).await;
6001        client
6002            .authenticate_and_connect(false, &cx.to_async())
6003            .await
6004            .unwrap();
6005    }
6006}
6007
6008#[gpui::test(iterations = 10)]
6009async fn test_basic_following(
6010    deterministic: Arc<Deterministic>,
6011    cx_a: &mut TestAppContext,
6012    cx_b: &mut TestAppContext,
6013    cx_c: &mut TestAppContext,
6014    cx_d: &mut TestAppContext,
6015) {
6016    deterministic.forbid_parking();
6017    cx_a.update(editor::init);
6018    cx_b.update(editor::init);
6019
6020    let mut server = TestServer::start(&deterministic).await;
6021    let client_a = server.create_client(cx_a, "user_a").await;
6022    let client_b = server.create_client(cx_b, "user_b").await;
6023    let client_c = server.create_client(cx_c, "user_c").await;
6024    let client_d = server.create_client(cx_d, "user_d").await;
6025    server
6026        .create_room(&mut [
6027            (&client_a, cx_a),
6028            (&client_b, cx_b),
6029            (&client_c, cx_c),
6030            (&client_d, cx_d),
6031        ])
6032        .await;
6033    let active_call_a = cx_a.read(ActiveCall::global);
6034    let active_call_b = cx_b.read(ActiveCall::global);
6035
6036    client_a
6037        .fs
6038        .insert_tree(
6039            "/a",
6040            json!({
6041                "1.txt": "one\none\none",
6042                "2.txt": "two\ntwo\ntwo",
6043                "3.txt": "three\nthree\nthree",
6044            }),
6045        )
6046        .await;
6047    let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
6048    active_call_a
6049        .update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
6050        .await
6051        .unwrap();
6052
6053    let project_id = active_call_a
6054        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
6055        .await
6056        .unwrap();
6057    let project_b = client_b.build_remote_project(project_id, cx_b).await;
6058    active_call_b
6059        .update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
6060        .await
6061        .unwrap();
6062
6063    let workspace_a = client_a.build_workspace(&project_a, cx_a);
6064    let workspace_b = client_b.build_workspace(&project_b, cx_b);
6065
6066    // Client A opens some editors.
6067    let pane_a = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
6068    let editor_a1 = workspace_a
6069        .update(cx_a, |workspace, cx| {
6070            workspace.open_path((worktree_id, "1.txt"), None, true, cx)
6071        })
6072        .await
6073        .unwrap()
6074        .downcast::<Editor>()
6075        .unwrap();
6076    let editor_a2 = workspace_a
6077        .update(cx_a, |workspace, cx| {
6078            workspace.open_path((worktree_id, "2.txt"), None, true, cx)
6079        })
6080        .await
6081        .unwrap()
6082        .downcast::<Editor>()
6083        .unwrap();
6084
6085    // Client B opens an editor.
6086    let editor_b1 = workspace_b
6087        .update(cx_b, |workspace, cx| {
6088            workspace.open_path((worktree_id, "1.txt"), None, true, cx)
6089        })
6090        .await
6091        .unwrap()
6092        .downcast::<Editor>()
6093        .unwrap();
6094
6095    let peer_id_a = client_a.peer_id().unwrap();
6096    let peer_id_b = client_b.peer_id().unwrap();
6097    let peer_id_c = client_c.peer_id().unwrap();
6098    let peer_id_d = client_d.peer_id().unwrap();
6099
6100    // Client A updates their selections in those editors
6101    editor_a1.update(cx_a, |editor, cx| {
6102        editor.handle_input("a", cx);
6103        editor.handle_input("b", cx);
6104        editor.handle_input("c", cx);
6105        editor.select_left(&Default::default(), cx);
6106        assert_eq!(editor.selections.ranges(cx), vec![3..2]);
6107    });
6108    editor_a2.update(cx_a, |editor, cx| {
6109        editor.handle_input("d", cx);
6110        editor.handle_input("e", cx);
6111        editor.select_left(&Default::default(), cx);
6112        assert_eq!(editor.selections.ranges(cx), vec![2..1]);
6113    });
6114
6115    // When client B starts following client A, all visible view states are replicated to client B.
6116    workspace_b
6117        .update(cx_b, |workspace, cx| {
6118            workspace.toggle_follow(peer_id_a, cx).unwrap()
6119        })
6120        .await
6121        .unwrap();
6122
6123    cx_c.foreground().run_until_parked();
6124    let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
6125        workspace
6126            .active_item(cx)
6127            .unwrap()
6128            .downcast::<Editor>()
6129            .unwrap()
6130    });
6131    assert_eq!(
6132        cx_b.read(|cx| editor_b2.project_path(cx)),
6133        Some((worktree_id, "2.txt").into())
6134    );
6135    assert_eq!(
6136        editor_b2.read_with(cx_b, |editor, cx| editor.selections.ranges(cx)),
6137        vec![2..1]
6138    );
6139    assert_eq!(
6140        editor_b1.read_with(cx_b, |editor, cx| editor.selections.ranges(cx)),
6141        vec![3..2]
6142    );
6143
6144    cx_c.foreground().run_until_parked();
6145    let active_call_c = cx_c.read(ActiveCall::global);
6146    let project_c = client_c.build_remote_project(project_id, cx_c).await;
6147    let workspace_c = client_c.build_workspace(&project_c, cx_c);
6148    active_call_c
6149        .update(cx_c, |call, cx| call.set_location(Some(&project_c), cx))
6150        .await
6151        .unwrap();
6152    drop(project_c);
6153
6154    // Client C also follows client A.
6155    workspace_c
6156        .update(cx_c, |workspace, cx| {
6157            workspace.toggle_follow(peer_id_a, cx).unwrap()
6158        })
6159        .await
6160        .unwrap();
6161
6162    cx_d.foreground().run_until_parked();
6163    let active_call_d = cx_d.read(ActiveCall::global);
6164    let project_d = client_d.build_remote_project(project_id, cx_d).await;
6165    let workspace_d = client_d.build_workspace(&project_d, cx_d);
6166    active_call_d
6167        .update(cx_d, |call, cx| call.set_location(Some(&project_d), cx))
6168        .await
6169        .unwrap();
6170    drop(project_d);
6171
6172    // All clients see that clients B and C are following client A.
6173    cx_c.foreground().run_until_parked();
6174    for (name, active_call, cx) in [
6175        ("A", &active_call_a, &cx_a),
6176        ("B", &active_call_b, &cx_b),
6177        ("C", &active_call_c, &cx_c),
6178        ("D", &active_call_d, &cx_d),
6179    ] {
6180        active_call.read_with(*cx, |call, cx| {
6181            let room = call.room().unwrap().read(cx);
6182            assert_eq!(
6183                room.followers_for(peer_id_a, project_id),
6184                &[peer_id_b, peer_id_c],
6185                "checking followers for A as {name}"
6186            );
6187        });
6188    }
6189
6190    // Client C unfollows client A.
6191    workspace_c.update(cx_c, |workspace, cx| {
6192        workspace.toggle_follow(peer_id_a, cx);
6193    });
6194
6195    // All clients see that clients B is following client A.
6196    cx_c.foreground().run_until_parked();
6197    for (name, active_call, cx) in [
6198        ("A", &active_call_a, &cx_a),
6199        ("B", &active_call_b, &cx_b),
6200        ("C", &active_call_c, &cx_c),
6201        ("D", &active_call_d, &cx_d),
6202    ] {
6203        active_call.read_with(*cx, |call, cx| {
6204            let room = call.room().unwrap().read(cx);
6205            assert_eq!(
6206                room.followers_for(peer_id_a, project_id),
6207                &[peer_id_b],
6208                "checking followers for A as {name}"
6209            );
6210        });
6211    }
6212
6213    // Client C re-follows client A.
6214    workspace_c.update(cx_c, |workspace, cx| {
6215        workspace.toggle_follow(peer_id_a, cx);
6216    });
6217
6218    // All clients see that clients B and C are following client A.
6219    cx_c.foreground().run_until_parked();
6220    for (name, active_call, cx) in [
6221        ("A", &active_call_a, &cx_a),
6222        ("B", &active_call_b, &cx_b),
6223        ("C", &active_call_c, &cx_c),
6224        ("D", &active_call_d, &cx_d),
6225    ] {
6226        active_call.read_with(*cx, |call, cx| {
6227            let room = call.room().unwrap().read(cx);
6228            assert_eq!(
6229                room.followers_for(peer_id_a, project_id),
6230                &[peer_id_b, peer_id_c],
6231                "checking followers for A as {name}"
6232            );
6233        });
6234    }
6235
6236    // Client D follows client C.
6237    workspace_d
6238        .update(cx_d, |workspace, cx| {
6239            workspace.toggle_follow(peer_id_c, cx).unwrap()
6240        })
6241        .await
6242        .unwrap();
6243
6244    // All clients see that D is following C
6245    cx_d.foreground().run_until_parked();
6246    for (name, active_call, cx) in [
6247        ("A", &active_call_a, &cx_a),
6248        ("B", &active_call_b, &cx_b),
6249        ("C", &active_call_c, &cx_c),
6250        ("D", &active_call_d, &cx_d),
6251    ] {
6252        active_call.read_with(*cx, |call, cx| {
6253            let room = call.room().unwrap().read(cx);
6254            assert_eq!(
6255                room.followers_for(peer_id_c, project_id),
6256                &[peer_id_d],
6257                "checking followers for C as {name}"
6258            );
6259        });
6260    }
6261
6262    // Client C closes the project.
6263    cx_c.drop_last(workspace_c);
6264
6265    // Clients A and B see that client B is following A, and client C is not present in the followers.
6266    cx_c.foreground().run_until_parked();
6267    for (name, active_call, cx) in [("A", &active_call_a, &cx_a), ("B", &active_call_b, &cx_b)] {
6268        active_call.read_with(*cx, |call, cx| {
6269            let room = call.room().unwrap().read(cx);
6270            assert_eq!(
6271                room.followers_for(peer_id_a, project_id),
6272                &[peer_id_b],
6273                "checking followers for A as {name}"
6274            );
6275        });
6276    }
6277
6278    // All clients see that no-one is following C
6279    for (name, active_call, cx) in [
6280        ("A", &active_call_a, &cx_a),
6281        ("B", &active_call_b, &cx_b),
6282        ("C", &active_call_c, &cx_c),
6283        ("D", &active_call_d, &cx_d),
6284    ] {
6285        active_call.read_with(*cx, |call, cx| {
6286            let room = call.room().unwrap().read(cx);
6287            assert_eq!(
6288                room.followers_for(peer_id_c, project_id),
6289                &[],
6290                "checking followers for C as {name}"
6291            );
6292        });
6293    }
6294
6295    // When client A activates a different editor, client B does so as well.
6296    workspace_a.update(cx_a, |workspace, cx| {
6297        workspace.activate_item(&editor_a1, cx)
6298    });
6299    deterministic.run_until_parked();
6300    workspace_b.read_with(cx_b, |workspace, cx| {
6301        assert_eq!(workspace.active_item(cx).unwrap().id(), editor_b1.id());
6302    });
6303
6304    // When client A opens a multibuffer, client B does so as well.
6305    let multibuffer_a = cx_a.add_model(|cx| {
6306        let buffer_a1 = project_a.update(cx, |project, cx| {
6307            project
6308                .get_open_buffer(&(worktree_id, "1.txt").into(), cx)
6309                .unwrap()
6310        });
6311        let buffer_a2 = project_a.update(cx, |project, cx| {
6312            project
6313                .get_open_buffer(&(worktree_id, "2.txt").into(), cx)
6314                .unwrap()
6315        });
6316        let mut result = MultiBuffer::new(0);
6317        result.push_excerpts(
6318            buffer_a1,
6319            [ExcerptRange {
6320                context: 0..3,
6321                primary: None,
6322            }],
6323            cx,
6324        );
6325        result.push_excerpts(
6326            buffer_a2,
6327            [ExcerptRange {
6328                context: 4..7,
6329                primary: None,
6330            }],
6331            cx,
6332        );
6333        result
6334    });
6335    let multibuffer_editor_a = workspace_a.update(cx_a, |workspace, cx| {
6336        let editor =
6337            cx.add_view(|cx| Editor::for_multibuffer(multibuffer_a, Some(project_a.clone()), cx));
6338        workspace.add_item(Box::new(editor.clone()), cx);
6339        editor
6340    });
6341    deterministic.run_until_parked();
6342    let multibuffer_editor_b = workspace_b.read_with(cx_b, |workspace, cx| {
6343        workspace
6344            .active_item(cx)
6345            .unwrap()
6346            .downcast::<Editor>()
6347            .unwrap()
6348    });
6349    assert_eq!(
6350        multibuffer_editor_a.read_with(cx_a, |editor, cx| editor.text(cx)),
6351        multibuffer_editor_b.read_with(cx_b, |editor, cx| editor.text(cx)),
6352    );
6353
6354    // When client A navigates back and forth, client B does so as well.
6355    workspace_a
6356        .update(cx_a, |workspace, cx| {
6357            workspace::Pane::go_back(workspace, None, cx)
6358        })
6359        .await
6360        .unwrap();
6361    deterministic.run_until_parked();
6362    workspace_b.read_with(cx_b, |workspace, cx| {
6363        assert_eq!(workspace.active_item(cx).unwrap().id(), editor_b1.id());
6364    });
6365
6366    workspace_a
6367        .update(cx_a, |workspace, cx| {
6368            workspace::Pane::go_back(workspace, None, cx)
6369        })
6370        .await
6371        .unwrap();
6372    deterministic.run_until_parked();
6373    workspace_b.read_with(cx_b, |workspace, cx| {
6374        assert_eq!(workspace.active_item(cx).unwrap().id(), editor_b2.id());
6375    });
6376
6377    workspace_a
6378        .update(cx_a, |workspace, cx| {
6379            workspace::Pane::go_forward(workspace, None, cx)
6380        })
6381        .await
6382        .unwrap();
6383    deterministic.run_until_parked();
6384    workspace_b.read_with(cx_b, |workspace, cx| {
6385        assert_eq!(workspace.active_item(cx).unwrap().id(), editor_b1.id());
6386    });
6387
6388    // Changes to client A's editor are reflected on client B.
6389    editor_a1.update(cx_a, |editor, cx| {
6390        editor.change_selections(None, cx, |s| s.select_ranges([1..1, 2..2]));
6391    });
6392    deterministic.run_until_parked();
6393    editor_b1.read_with(cx_b, |editor, cx| {
6394        assert_eq!(editor.selections.ranges(cx), &[1..1, 2..2]);
6395    });
6396
6397    editor_a1.update(cx_a, |editor, cx| editor.set_text("TWO", cx));
6398    deterministic.run_until_parked();
6399    editor_b1.read_with(cx_b, |editor, cx| assert_eq!(editor.text(cx), "TWO"));
6400
6401    editor_a1.update(cx_a, |editor, cx| {
6402        editor.change_selections(None, cx, |s| s.select_ranges([3..3]));
6403        editor.set_scroll_position(vec2f(0., 100.), cx);
6404    });
6405    deterministic.run_until_parked();
6406    editor_b1.read_with(cx_b, |editor, cx| {
6407        assert_eq!(editor.selections.ranges(cx), &[3..3]);
6408    });
6409
6410    // After unfollowing, client B stops receiving updates from client A.
6411    workspace_b.update(cx_b, |workspace, cx| {
6412        workspace.unfollow(&workspace.active_pane().clone(), cx)
6413    });
6414    workspace_a.update(cx_a, |workspace, cx| {
6415        workspace.activate_item(&editor_a2, cx)
6416    });
6417    deterministic.run_until_parked();
6418    assert_eq!(
6419        workspace_b.read_with(cx_b, |workspace, cx| workspace
6420            .active_item(cx)
6421            .unwrap()
6422            .id()),
6423        editor_b1.id()
6424    );
6425
6426    // Client A starts following client B.
6427    workspace_a
6428        .update(cx_a, |workspace, cx| {
6429            workspace.toggle_follow(peer_id_b, cx).unwrap()
6430        })
6431        .await
6432        .unwrap();
6433    assert_eq!(
6434        workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
6435        Some(peer_id_b)
6436    );
6437    assert_eq!(
6438        workspace_a.read_with(cx_a, |workspace, cx| workspace
6439            .active_item(cx)
6440            .unwrap()
6441            .id()),
6442        editor_a1.id()
6443    );
6444
6445    // Client B activates an external window, which causes a new screen-sharing item to be added to the pane.
6446    let display = MacOSDisplay::new();
6447    active_call_b
6448        .update(cx_b, |call, cx| call.set_location(None, cx))
6449        .await
6450        .unwrap();
6451    active_call_b
6452        .update(cx_b, |call, cx| {
6453            call.room().unwrap().update(cx, |room, cx| {
6454                room.set_display_sources(vec![display.clone()]);
6455                room.share_screen(cx)
6456            })
6457        })
6458        .await
6459        .unwrap();
6460    deterministic.run_until_parked();
6461    let shared_screen = workspace_a.read_with(cx_a, |workspace, cx| {
6462        workspace
6463            .active_item(cx)
6464            .unwrap()
6465            .downcast::<SharedScreen>()
6466            .unwrap()
6467    });
6468
6469    // Client B activates Zed again, which causes the previous editor to become focused again.
6470    active_call_b
6471        .update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
6472        .await
6473        .unwrap();
6474    deterministic.run_until_parked();
6475    workspace_a.read_with(cx_a, |workspace, cx| {
6476        assert_eq!(workspace.active_item(cx).unwrap().id(), editor_a1.id())
6477    });
6478
6479    // Client B activates a multibuffer that was created by following client A. Client A returns to that multibuffer.
6480    workspace_b.update(cx_b, |workspace, cx| {
6481        workspace.activate_item(&multibuffer_editor_b, cx)
6482    });
6483    deterministic.run_until_parked();
6484    workspace_a.read_with(cx_a, |workspace, cx| {
6485        assert_eq!(
6486            workspace.active_item(cx).unwrap().id(),
6487            multibuffer_editor_a.id()
6488        )
6489    });
6490
6491    // Client B activates an external window again, and the previously-opened screen-sharing item
6492    // gets activated.
6493    active_call_b
6494        .update(cx_b, |call, cx| call.set_location(None, cx))
6495        .await
6496        .unwrap();
6497    deterministic.run_until_parked();
6498    assert_eq!(
6499        workspace_a.read_with(cx_a, |workspace, cx| workspace
6500            .active_item(cx)
6501            .unwrap()
6502            .id()),
6503        shared_screen.id()
6504    );
6505
6506    // Following interrupts when client B disconnects.
6507    client_b.disconnect(&cx_b.to_async());
6508    deterministic.advance_clock(RECONNECT_TIMEOUT);
6509    assert_eq!(
6510        workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
6511        None
6512    );
6513}
6514
6515#[gpui::test(iterations = 10)]
6516async fn test_join_call_after_screen_was_shared(
6517    deterministic: Arc<Deterministic>,
6518    cx_a: &mut TestAppContext,
6519    cx_b: &mut TestAppContext,
6520) {
6521    deterministic.forbid_parking();
6522    let mut server = TestServer::start(&deterministic).await;
6523
6524    let client_a = server.create_client(cx_a, "user_a").await;
6525    let client_b = server.create_client(cx_b, "user_b").await;
6526    server
6527        .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b)])
6528        .await;
6529
6530    let active_call_a = cx_a.read(ActiveCall::global);
6531    let active_call_b = cx_b.read(ActiveCall::global);
6532
6533    // Call users B and C from client A.
6534    active_call_a
6535        .update(cx_a, |call, cx| {
6536            call.invite(client_b.user_id().unwrap(), None, cx)
6537        })
6538        .await
6539        .unwrap();
6540    let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
6541    deterministic.run_until_parked();
6542    assert_eq!(
6543        room_participants(&room_a, cx_a),
6544        RoomParticipants {
6545            remote: Default::default(),
6546            pending: vec!["user_b".to_string()]
6547        }
6548    );
6549
6550    // User B receives the call.
6551    let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
6552    let call_b = incoming_call_b.next().await.unwrap().unwrap();
6553    assert_eq!(call_b.calling_user.github_login, "user_a");
6554
6555    // User A shares their screen
6556    let display = MacOSDisplay::new();
6557    active_call_a
6558        .update(cx_a, |call, cx| {
6559            call.room().unwrap().update(cx, |room, cx| {
6560                room.set_display_sources(vec![display.clone()]);
6561                room.share_screen(cx)
6562            })
6563        })
6564        .await
6565        .unwrap();
6566
6567    client_b.user_store.update(cx_b, |user_store, _| {
6568        user_store.clear_cache();
6569    });
6570
6571    // User B joins the room
6572    active_call_b
6573        .update(cx_b, |call, cx| call.accept_incoming(cx))
6574        .await
6575        .unwrap();
6576    let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
6577    assert!(incoming_call_b.next().await.unwrap().is_none());
6578
6579    deterministic.run_until_parked();
6580    assert_eq!(
6581        room_participants(&room_a, cx_a),
6582        RoomParticipants {
6583            remote: vec!["user_b".to_string()],
6584            pending: vec![],
6585        }
6586    );
6587    assert_eq!(
6588        room_participants(&room_b, cx_b),
6589        RoomParticipants {
6590            remote: vec!["user_a".to_string()],
6591            pending: vec![],
6592        }
6593    );
6594
6595    // Ensure User B sees User A's screenshare.
6596    room_b.read_with(cx_b, |room, _| {
6597        assert_eq!(
6598            room.remote_participants()
6599                .get(&client_a.user_id().unwrap())
6600                .unwrap()
6601                .tracks
6602                .len(),
6603            1
6604        );
6605    });
6606}
6607
6608#[gpui::test]
6609async fn test_following_tab_order(
6610    deterministic: Arc<Deterministic>,
6611    cx_a: &mut TestAppContext,
6612    cx_b: &mut TestAppContext,
6613) {
6614    cx_a.update(editor::init);
6615    cx_b.update(editor::init);
6616
6617    let mut server = TestServer::start(&deterministic).await;
6618    let client_a = server.create_client(cx_a, "user_a").await;
6619    let client_b = server.create_client(cx_b, "user_b").await;
6620    server
6621        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
6622        .await;
6623    let active_call_a = cx_a.read(ActiveCall::global);
6624    let active_call_b = cx_b.read(ActiveCall::global);
6625
6626    client_a
6627        .fs
6628        .insert_tree(
6629            "/a",
6630            json!({
6631                "1.txt": "one",
6632                "2.txt": "two",
6633                "3.txt": "three",
6634            }),
6635        )
6636        .await;
6637    let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
6638    active_call_a
6639        .update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
6640        .await
6641        .unwrap();
6642
6643    let project_id = active_call_a
6644        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
6645        .await
6646        .unwrap();
6647    let project_b = client_b.build_remote_project(project_id, cx_b).await;
6648    active_call_b
6649        .update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
6650        .await
6651        .unwrap();
6652
6653    let workspace_a = client_a.build_workspace(&project_a, cx_a);
6654    let pane_a = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
6655
6656    let workspace_b = client_b.build_workspace(&project_b, cx_b);
6657    let pane_b = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
6658
6659    let client_b_id = project_a.read_with(cx_a, |project, _| {
6660        project.collaborators().values().next().unwrap().peer_id
6661    });
6662
6663    //Open 1, 3 in that order on client A
6664    workspace_a
6665        .update(cx_a, |workspace, cx| {
6666            workspace.open_path((worktree_id, "1.txt"), None, true, cx)
6667        })
6668        .await
6669        .unwrap();
6670    workspace_a
6671        .update(cx_a, |workspace, cx| {
6672            workspace.open_path((worktree_id, "3.txt"), None, true, cx)
6673        })
6674        .await
6675        .unwrap();
6676
6677    let pane_paths = |pane: &ViewHandle<workspace::Pane>, cx: &mut TestAppContext| {
6678        pane.update(cx, |pane, cx| {
6679            pane.items()
6680                .map(|item| {
6681                    item.project_path(cx)
6682                        .unwrap()
6683                        .path
6684                        .to_str()
6685                        .unwrap()
6686                        .to_owned()
6687                })
6688                .collect::<Vec<_>>()
6689        })
6690    };
6691
6692    //Verify that the tabs opened in the order we expect
6693    assert_eq!(&pane_paths(&pane_a, cx_a), &["1.txt", "3.txt"]);
6694
6695    //Follow client B as client A
6696    workspace_a
6697        .update(cx_a, |workspace, cx| {
6698            workspace.toggle_follow(client_b_id, cx).unwrap()
6699        })
6700        .await
6701        .unwrap();
6702
6703    //Open just 2 on client B
6704    workspace_b
6705        .update(cx_b, |workspace, cx| {
6706            workspace.open_path((worktree_id, "2.txt"), None, true, cx)
6707        })
6708        .await
6709        .unwrap();
6710    deterministic.run_until_parked();
6711
6712    // Verify that newly opened followed file is at the end
6713    assert_eq!(&pane_paths(&pane_a, cx_a), &["1.txt", "3.txt", "2.txt"]);
6714
6715    //Open just 1 on client B
6716    workspace_b
6717        .update(cx_b, |workspace, cx| {
6718            workspace.open_path((worktree_id, "1.txt"), None, true, cx)
6719        })
6720        .await
6721        .unwrap();
6722    assert_eq!(&pane_paths(&pane_b, cx_b), &["2.txt", "1.txt"]);
6723    deterministic.run_until_parked();
6724
6725    // Verify that following into 1 did not reorder
6726    assert_eq!(&pane_paths(&pane_a, cx_a), &["1.txt", "3.txt", "2.txt"]);
6727}
6728
6729#[gpui::test(iterations = 10)]
6730async fn test_peers_following_each_other(
6731    deterministic: Arc<Deterministic>,
6732    cx_a: &mut TestAppContext,
6733    cx_b: &mut TestAppContext,
6734) {
6735    deterministic.forbid_parking();
6736    cx_a.update(editor::init);
6737    cx_b.update(editor::init);
6738
6739    let mut server = TestServer::start(&deterministic).await;
6740    let client_a = server.create_client(cx_a, "user_a").await;
6741    let client_b = server.create_client(cx_b, "user_b").await;
6742    server
6743        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
6744        .await;
6745    let active_call_a = cx_a.read(ActiveCall::global);
6746    let active_call_b = cx_b.read(ActiveCall::global);
6747
6748    // Client A shares a project.
6749    client_a
6750        .fs
6751        .insert_tree(
6752            "/a",
6753            json!({
6754                "1.txt": "one",
6755                "2.txt": "two",
6756                "3.txt": "three",
6757                "4.txt": "four",
6758            }),
6759        )
6760        .await;
6761    let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
6762    active_call_a
6763        .update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
6764        .await
6765        .unwrap();
6766    let project_id = active_call_a
6767        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
6768        .await
6769        .unwrap();
6770
6771    // Client B joins the project.
6772    let project_b = client_b.build_remote_project(project_id, cx_b).await;
6773    active_call_b
6774        .update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
6775        .await
6776        .unwrap();
6777
6778    // Client A opens some editors.
6779    let workspace_a = client_a.build_workspace(&project_a, cx_a);
6780    let pane_a1 = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
6781    let _editor_a1 = workspace_a
6782        .update(cx_a, |workspace, cx| {
6783            workspace.open_path((worktree_id, "1.txt"), None, true, cx)
6784        })
6785        .await
6786        .unwrap()
6787        .downcast::<Editor>()
6788        .unwrap();
6789
6790    // Client B opens an editor.
6791    let workspace_b = client_b.build_workspace(&project_b, cx_b);
6792    let pane_b1 = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
6793    let _editor_b1 = workspace_b
6794        .update(cx_b, |workspace, cx| {
6795            workspace.open_path((worktree_id, "2.txt"), None, true, cx)
6796        })
6797        .await
6798        .unwrap()
6799        .downcast::<Editor>()
6800        .unwrap();
6801
6802    // Clients A and B follow each other in split panes
6803    workspace_a.update(cx_a, |workspace, cx| {
6804        workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
6805        let pane_a1 = pane_a1.clone();
6806        cx.defer(move |workspace, _| {
6807            assert_ne!(*workspace.active_pane(), pane_a1);
6808        });
6809    });
6810    workspace_a
6811        .update(cx_a, |workspace, cx| {
6812            let leader_id = *project_a.read(cx).collaborators().keys().next().unwrap();
6813            workspace.toggle_follow(leader_id, cx).unwrap()
6814        })
6815        .await
6816        .unwrap();
6817    workspace_b.update(cx_b, |workspace, cx| {
6818        workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
6819        let pane_b1 = pane_b1.clone();
6820        cx.defer(move |workspace, _| {
6821            assert_ne!(*workspace.active_pane(), pane_b1);
6822        });
6823    });
6824    workspace_b
6825        .update(cx_b, |workspace, cx| {
6826            let leader_id = *project_b.read(cx).collaborators().keys().next().unwrap();
6827            workspace.toggle_follow(leader_id, cx).unwrap()
6828        })
6829        .await
6830        .unwrap();
6831
6832    workspace_a.update(cx_a, |workspace, cx| {
6833        workspace.activate_next_pane(cx);
6834    });
6835    // Wait for focus effects to be fully flushed
6836    workspace_a.update(cx_a, |workspace, _| {
6837        assert_eq!(*workspace.active_pane(), pane_a1);
6838    });
6839
6840    workspace_a
6841        .update(cx_a, |workspace, cx| {
6842            workspace.open_path((worktree_id, "3.txt"), None, true, cx)
6843        })
6844        .await
6845        .unwrap();
6846    workspace_b.update(cx_b, |workspace, cx| {
6847        workspace.activate_next_pane(cx);
6848    });
6849
6850    workspace_b
6851        .update(cx_b, |workspace, cx| {
6852            assert_eq!(*workspace.active_pane(), pane_b1);
6853            workspace.open_path((worktree_id, "4.txt"), None, true, cx)
6854        })
6855        .await
6856        .unwrap();
6857    cx_a.foreground().run_until_parked();
6858
6859    // Ensure leader updates don't change the active pane of followers
6860    workspace_a.read_with(cx_a, |workspace, _| {
6861        assert_eq!(*workspace.active_pane(), pane_a1);
6862    });
6863    workspace_b.read_with(cx_b, |workspace, _| {
6864        assert_eq!(*workspace.active_pane(), pane_b1);
6865    });
6866
6867    // Ensure peers following each other doesn't cause an infinite loop.
6868    assert_eq!(
6869        workspace_a.read_with(cx_a, |workspace, cx| workspace
6870            .active_item(cx)
6871            .unwrap()
6872            .project_path(cx)),
6873        Some((worktree_id, "3.txt").into())
6874    );
6875    workspace_a.update(cx_a, |workspace, cx| {
6876        assert_eq!(
6877            workspace.active_item(cx).unwrap().project_path(cx),
6878            Some((worktree_id, "3.txt").into())
6879        );
6880        workspace.activate_next_pane(cx);
6881    });
6882
6883    workspace_a.update(cx_a, |workspace, cx| {
6884        assert_eq!(
6885            workspace.active_item(cx).unwrap().project_path(cx),
6886            Some((worktree_id, "4.txt").into())
6887        );
6888    });
6889
6890    workspace_b.update(cx_b, |workspace, cx| {
6891        assert_eq!(
6892            workspace.active_item(cx).unwrap().project_path(cx),
6893            Some((worktree_id, "4.txt").into())
6894        );
6895        workspace.activate_next_pane(cx);
6896    });
6897
6898    workspace_b.update(cx_b, |workspace, cx| {
6899        assert_eq!(
6900            workspace.active_item(cx).unwrap().project_path(cx),
6901            Some((worktree_id, "3.txt").into())
6902        );
6903    });
6904}
6905
6906#[gpui::test(iterations = 10)]
6907async fn test_auto_unfollowing(
6908    deterministic: Arc<Deterministic>,
6909    cx_a: &mut TestAppContext,
6910    cx_b: &mut TestAppContext,
6911) {
6912    deterministic.forbid_parking();
6913    cx_a.update(editor::init);
6914    cx_b.update(editor::init);
6915
6916    // 2 clients connect to a server.
6917    let mut server = TestServer::start(&deterministic).await;
6918    let client_a = server.create_client(cx_a, "user_a").await;
6919    let client_b = server.create_client(cx_b, "user_b").await;
6920    server
6921        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
6922        .await;
6923    let active_call_a = cx_a.read(ActiveCall::global);
6924    let active_call_b = cx_b.read(ActiveCall::global);
6925
6926    // Client A shares a project.
6927    client_a
6928        .fs
6929        .insert_tree(
6930            "/a",
6931            json!({
6932                "1.txt": "one",
6933                "2.txt": "two",
6934                "3.txt": "three",
6935            }),
6936        )
6937        .await;
6938    let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
6939    active_call_a
6940        .update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
6941        .await
6942        .unwrap();
6943
6944    let project_id = active_call_a
6945        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
6946        .await
6947        .unwrap();
6948    let project_b = client_b.build_remote_project(project_id, cx_b).await;
6949    active_call_b
6950        .update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
6951        .await
6952        .unwrap();
6953
6954    // Client A opens some editors.
6955    let workspace_a = client_a.build_workspace(&project_a, cx_a);
6956    let _editor_a1 = workspace_a
6957        .update(cx_a, |workspace, cx| {
6958            workspace.open_path((worktree_id, "1.txt"), None, true, cx)
6959        })
6960        .await
6961        .unwrap()
6962        .downcast::<Editor>()
6963        .unwrap();
6964
6965    // Client B starts following client A.
6966    let workspace_b = client_b.build_workspace(&project_b, cx_b);
6967    let pane_b = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
6968    let leader_id = project_b.read_with(cx_b, |project, _| {
6969        project.collaborators().values().next().unwrap().peer_id
6970    });
6971    workspace_b
6972        .update(cx_b, |workspace, cx| {
6973            workspace.toggle_follow(leader_id, cx).unwrap()
6974        })
6975        .await
6976        .unwrap();
6977    assert_eq!(
6978        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
6979        Some(leader_id)
6980    );
6981    let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
6982        workspace
6983            .active_item(cx)
6984            .unwrap()
6985            .downcast::<Editor>()
6986            .unwrap()
6987    });
6988
6989    // When client B moves, it automatically stops following client A.
6990    editor_b2.update(cx_b, |editor, cx| editor.move_right(&editor::MoveRight, cx));
6991    assert_eq!(
6992        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
6993        None
6994    );
6995
6996    workspace_b
6997        .update(cx_b, |workspace, cx| {
6998            workspace.toggle_follow(leader_id, cx).unwrap()
6999        })
7000        .await
7001        .unwrap();
7002    assert_eq!(
7003        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7004        Some(leader_id)
7005    );
7006
7007    // When client B edits, it automatically stops following client A.
7008    editor_b2.update(cx_b, |editor, cx| editor.insert("X", cx));
7009    assert_eq!(
7010        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7011        None
7012    );
7013
7014    workspace_b
7015        .update(cx_b, |workspace, cx| {
7016            workspace.toggle_follow(leader_id, cx).unwrap()
7017        })
7018        .await
7019        .unwrap();
7020    assert_eq!(
7021        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7022        Some(leader_id)
7023    );
7024
7025    // When client B scrolls, it automatically stops following client A.
7026    editor_b2.update(cx_b, |editor, cx| {
7027        editor.set_scroll_position(vec2f(0., 3.), cx)
7028    });
7029    assert_eq!(
7030        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7031        None
7032    );
7033
7034    workspace_b
7035        .update(cx_b, |workspace, cx| {
7036            workspace.toggle_follow(leader_id, cx).unwrap()
7037        })
7038        .await
7039        .unwrap();
7040    assert_eq!(
7041        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7042        Some(leader_id)
7043    );
7044
7045    // When client B activates a different pane, it continues following client A in the original pane.
7046    workspace_b.update(cx_b, |workspace, cx| {
7047        workspace.split_pane(pane_b.clone(), SplitDirection::Right, cx)
7048    });
7049    assert_eq!(
7050        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7051        Some(leader_id)
7052    );
7053
7054    workspace_b.update(cx_b, |workspace, cx| workspace.activate_next_pane(cx));
7055    assert_eq!(
7056        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7057        Some(leader_id)
7058    );
7059
7060    // When client B activates a different item in the original pane, it automatically stops following client A.
7061    workspace_b
7062        .update(cx_b, |workspace, cx| {
7063            workspace.open_path((worktree_id, "2.txt"), None, true, cx)
7064        })
7065        .await
7066        .unwrap();
7067    assert_eq!(
7068        workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
7069        None
7070    );
7071}
7072
7073#[gpui::test(iterations = 10)]
7074async fn test_peers_simultaneously_following_each_other(
7075    deterministic: Arc<Deterministic>,
7076    cx_a: &mut TestAppContext,
7077    cx_b: &mut TestAppContext,
7078) {
7079    deterministic.forbid_parking();
7080    cx_a.update(editor::init);
7081    cx_b.update(editor::init);
7082
7083    let mut server = TestServer::start(&deterministic).await;
7084    let client_a = server.create_client(cx_a, "user_a").await;
7085    let client_b = server.create_client(cx_b, "user_b").await;
7086    server
7087        .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
7088        .await;
7089    let active_call_a = cx_a.read(ActiveCall::global);
7090
7091    client_a.fs.insert_tree("/a", json!({})).await;
7092    let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
7093    let workspace_a = client_a.build_workspace(&project_a, cx_a);
7094    let project_id = active_call_a
7095        .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
7096        .await
7097        .unwrap();
7098
7099    let project_b = client_b.build_remote_project(project_id, cx_b).await;
7100    let workspace_b = client_b.build_workspace(&project_b, cx_b);
7101
7102    deterministic.run_until_parked();
7103    let client_a_id = project_b.read_with(cx_b, |project, _| {
7104        project.collaborators().values().next().unwrap().peer_id
7105    });
7106    let client_b_id = project_a.read_with(cx_a, |project, _| {
7107        project.collaborators().values().next().unwrap().peer_id
7108    });
7109
7110    let a_follow_b = workspace_a.update(cx_a, |workspace, cx| {
7111        workspace.toggle_follow(client_b_id, cx).unwrap()
7112    });
7113    let b_follow_a = workspace_b.update(cx_b, |workspace, cx| {
7114        workspace.toggle_follow(client_a_id, cx).unwrap()
7115    });
7116
7117    futures::try_join!(a_follow_b, b_follow_a).unwrap();
7118    workspace_a.read_with(cx_a, |workspace, _| {
7119        assert_eq!(
7120            workspace.leader_for_pane(workspace.active_pane()),
7121            Some(client_b_id)
7122        );
7123    });
7124    workspace_b.read_with(cx_b, |workspace, _| {
7125        assert_eq!(
7126            workspace.leader_for_pane(workspace.active_pane()),
7127            Some(client_a_id)
7128        );
7129    });
7130}
7131
7132#[derive(Debug, Eq, PartialEq)]
7133struct RoomParticipants {
7134    remote: Vec<String>,
7135    pending: Vec<String>,
7136}
7137
7138fn room_participants(room: &ModelHandle<Room>, cx: &mut TestAppContext) -> RoomParticipants {
7139    room.read_with(cx, |room, _| {
7140        let mut remote = room
7141            .remote_participants()
7142            .iter()
7143            .map(|(_, participant)| participant.user.github_login.clone())
7144            .collect::<Vec<_>>();
7145        let mut pending = room
7146            .pending_participants()
7147            .iter()
7148            .map(|user| user.github_login.clone())
7149            .collect::<Vec<_>>();
7150        remote.sort();
7151        pending.sort();
7152        RoomParticipants { remote, pending }
7153    })
7154}