integration_tests.rs

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