randomized_integration_tests.rs

   1use crate::{
   2    db::{self, NewUserParams, UserId},
   3    rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
   4    tests::{TestClient, TestServer},
   5};
   6use anyhow::{anyhow, Result};
   7use call::ActiveCall;
   8use client::RECEIVE_TIMEOUT;
   9use collections::BTreeMap;
  10use editor::Bias;
  11use fs::{FakeFs, Fs as _};
  12use futures::StreamExt as _;
  13use gpui::{executor::Deterministic, ModelHandle, Task, TestAppContext};
  14use language::{range_to_lsp, FakeLspAdapter, Language, LanguageConfig, PointUtf16};
  15use lsp::FakeLanguageServer;
  16use parking_lot::Mutex;
  17use project::{search::SearchQuery, Project, ProjectPath};
  18use rand::{
  19    distributions::{Alphanumeric, DistString},
  20    prelude::*,
  21};
  22use serde::{Deserialize, Serialize};
  23use settings::Settings;
  24use std::{
  25    env,
  26    ops::Range,
  27    path::{Path, PathBuf},
  28    rc::Rc,
  29    sync::{
  30        atomic::{AtomicBool, Ordering::SeqCst},
  31        Arc,
  32    },
  33};
  34use util::ResultExt;
  35
  36lazy_static::lazy_static! {
  37    static ref PLAN_LOAD_PATH: Option<PathBuf> = path_env_var("LOAD_PLAN");
  38    static ref PLAN_SAVE_PATH: Option<PathBuf> = path_env_var("SAVE_PLAN");
  39    static ref LOADED_PLAN_JSON: Mutex<Option<Vec<u8>>> = Default::default();
  40    static ref PLAN: Mutex<Option<Arc<Mutex<TestPlan>>>> = Default::default();
  41}
  42
  43#[gpui::test(iterations = 100, on_failure = "on_failure")]
  44async fn test_random_collaboration(
  45    cx: &mut TestAppContext,
  46    deterministic: Arc<Deterministic>,
  47    rng: StdRng,
  48) {
  49    deterministic.forbid_parking();
  50
  51    let max_peers = env::var("MAX_PEERS")
  52        .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
  53        .unwrap_or(3);
  54    let max_operations = env::var("OPERATIONS")
  55        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
  56        .unwrap_or(10);
  57
  58    let mut server = TestServer::start(&deterministic).await;
  59    let db = server.app_state.db.clone();
  60
  61    let mut users = Vec::new();
  62    for ix in 0..max_peers {
  63        let username = format!("user-{}", ix + 1);
  64        let user_id = db
  65            .create_user(
  66                &format!("{username}@example.com"),
  67                false,
  68                NewUserParams {
  69                    github_login: username.clone(),
  70                    github_user_id: (ix + 1) as i32,
  71                    invite_count: 0,
  72                },
  73            )
  74            .await
  75            .unwrap()
  76            .user_id;
  77        users.push(UserTestPlan {
  78            user_id,
  79            username,
  80            online: false,
  81            next_root_id: 0,
  82            operation_ix: 0,
  83        });
  84    }
  85
  86    for (ix, user_a) in users.iter().enumerate() {
  87        for user_b in &users[ix + 1..] {
  88            server
  89                .app_state
  90                .db
  91                .send_contact_request(user_a.user_id, user_b.user_id)
  92                .await
  93                .unwrap();
  94            server
  95                .app_state
  96                .db
  97                .respond_to_contact_request(user_b.user_id, user_a.user_id, true)
  98                .await
  99                .unwrap();
 100        }
 101    }
 102
 103    let plan = Arc::new(Mutex::new(TestPlan::new(rng, users, max_operations)));
 104
 105    if let Some(path) = &*PLAN_LOAD_PATH {
 106        let json = LOADED_PLAN_JSON
 107            .lock()
 108            .get_or_insert_with(|| {
 109                eprintln!("loaded test plan from path {:?}", path);
 110                std::fs::read(path).unwrap()
 111            })
 112            .clone();
 113        plan.lock().deserialize(json);
 114    }
 115
 116    PLAN.lock().replace(plan.clone());
 117
 118    let mut clients = Vec::new();
 119    let mut client_tasks = Vec::new();
 120    let mut operation_channels = Vec::new();
 121
 122    loop {
 123        let Some((next_operation, applied)) = plan.lock().next_server_operation(&clients) else { break };
 124        applied.store(true, SeqCst);
 125        let did_apply = apply_server_operation(
 126            deterministic.clone(),
 127            &mut server,
 128            &mut clients,
 129            &mut client_tasks,
 130            &mut operation_channels,
 131            plan.clone(),
 132            next_operation,
 133            cx,
 134        )
 135        .await;
 136        if !did_apply {
 137            applied.store(false, SeqCst);
 138        }
 139    }
 140
 141    drop(operation_channels);
 142    deterministic.start_waiting();
 143    futures::future::join_all(client_tasks).await;
 144    deterministic.finish_waiting();
 145    deterministic.run_until_parked();
 146
 147    check_consistency_between_clients(&clients);
 148
 149    for (client, mut cx) in clients {
 150        cx.update(|cx| {
 151            cx.clear_globals();
 152            cx.set_global(Settings::test(cx));
 153            drop(client);
 154        });
 155    }
 156
 157    deterministic.run_until_parked();
 158}
 159
 160fn on_failure() {
 161    if let Some(plan) = PLAN.lock().clone() {
 162        if let Some(path) = &*PLAN_SAVE_PATH {
 163            eprintln!("saved test plan to path {:?}", path);
 164            std::fs::write(path, plan.lock().serialize()).unwrap();
 165        }
 166    }
 167}
 168
 169async fn apply_server_operation(
 170    deterministic: Arc<Deterministic>,
 171    server: &mut TestServer,
 172    clients: &mut Vec<(Rc<TestClient>, TestAppContext)>,
 173    client_tasks: &mut Vec<Task<()>>,
 174    operation_channels: &mut Vec<futures::channel::mpsc::UnboundedSender<usize>>,
 175    plan: Arc<Mutex<TestPlan>>,
 176    operation: Operation,
 177    cx: &mut TestAppContext,
 178) -> bool {
 179    match operation {
 180        Operation::AddConnection { user_id } => {
 181            let username;
 182            {
 183                let mut plan = plan.lock();
 184                let mut user = plan.user(user_id);
 185                if user.online {
 186                    return false;
 187                }
 188                user.online = true;
 189                username = user.username.clone();
 190            };
 191            log::info!("Adding new connection for {}", username);
 192            let next_entity_id = (user_id.0 * 10_000) as usize;
 193            let mut client_cx = TestAppContext::new(
 194                cx.foreground_platform(),
 195                cx.platform(),
 196                deterministic.build_foreground(user_id.0 as usize),
 197                deterministic.build_background(),
 198                cx.font_cache(),
 199                cx.leak_detector(),
 200                next_entity_id,
 201                cx.function_name.clone(),
 202            );
 203
 204            let (operation_tx, operation_rx) = futures::channel::mpsc::unbounded();
 205            let client = Rc::new(server.create_client(&mut client_cx, &username).await);
 206            operation_channels.push(operation_tx);
 207            clients.push((client.clone(), client_cx.clone()));
 208            client_tasks.push(client_cx.foreground().spawn(simulate_client(
 209                client,
 210                operation_rx,
 211                plan.clone(),
 212                client_cx,
 213            )));
 214
 215            log::info!("Added connection for {}", username);
 216        }
 217
 218        Operation::RemoveConnection {
 219            user_id: removed_user_id,
 220        } => {
 221            log::info!("Simulating full disconnection of user {}", removed_user_id);
 222            let client_ix = clients
 223                .iter()
 224                .position(|(client, cx)| client.current_user_id(cx) == removed_user_id);
 225            let Some(client_ix) = client_ix else { return false };
 226            let user_connection_ids = server
 227                .connection_pool
 228                .lock()
 229                .user_connection_ids(removed_user_id)
 230                .collect::<Vec<_>>();
 231            assert_eq!(user_connection_ids.len(), 1);
 232            let removed_peer_id = user_connection_ids[0].into();
 233            let (client, mut client_cx) = clients.remove(client_ix);
 234            let client_task = client_tasks.remove(client_ix);
 235            operation_channels.remove(client_ix);
 236            server.forbid_connections();
 237            server.disconnect_client(removed_peer_id);
 238            deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
 239            deterministic.start_waiting();
 240            log::info!("Waiting for user {} to exit...", removed_user_id);
 241            client_task.await;
 242            deterministic.finish_waiting();
 243            server.allow_connections();
 244
 245            for project in client.remote_projects().iter() {
 246                project.read_with(&client_cx, |project, _| {
 247                    assert!(
 248                        project.is_read_only(),
 249                        "project {:?} should be read only",
 250                        project.remote_id()
 251                    )
 252                });
 253            }
 254
 255            for (client, cx) in clients {
 256                let contacts = server
 257                    .app_state
 258                    .db
 259                    .get_contacts(client.current_user_id(cx))
 260                    .await
 261                    .unwrap();
 262                let pool = server.connection_pool.lock();
 263                for contact in contacts {
 264                    if let db::Contact::Accepted { user_id, busy, .. } = contact {
 265                        if user_id == removed_user_id {
 266                            assert!(!pool.is_user_online(user_id));
 267                            assert!(!busy);
 268                        }
 269                    }
 270                }
 271            }
 272
 273            log::info!("{} removed", client.username);
 274            plan.lock().user(removed_user_id).online = false;
 275            client_cx.update(|cx| {
 276                cx.clear_globals();
 277                drop(client);
 278            });
 279        }
 280
 281        Operation::BounceConnection { user_id } => {
 282            log::info!("Simulating temporary disconnection of user {}", user_id);
 283            let user_connection_ids = server
 284                .connection_pool
 285                .lock()
 286                .user_connection_ids(user_id)
 287                .collect::<Vec<_>>();
 288            if user_connection_ids.is_empty() {
 289                return false;
 290            }
 291            assert_eq!(user_connection_ids.len(), 1);
 292            let peer_id = user_connection_ids[0].into();
 293            server.disconnect_client(peer_id);
 294            deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
 295        }
 296
 297        Operation::RestartServer => {
 298            log::info!("Simulating server restart");
 299            server.reset().await;
 300            deterministic.advance_clock(RECEIVE_TIMEOUT);
 301            server.start().await.unwrap();
 302            deterministic.advance_clock(CLEANUP_TIMEOUT);
 303            let environment = &server.app_state.config.zed_environment;
 304            let stale_room_ids = server
 305                .app_state
 306                .db
 307                .stale_room_ids(environment, server.id())
 308                .await
 309                .unwrap();
 310            assert_eq!(stale_room_ids, vec![]);
 311        }
 312
 313        Operation::MutateClients {
 314            user_ids,
 315            batch_id,
 316            quiesce,
 317        } => {
 318            let mut applied = false;
 319            for user_id in user_ids {
 320                let client_ix = clients
 321                    .iter()
 322                    .position(|(client, cx)| client.current_user_id(cx) == user_id);
 323                let Some(client_ix) = client_ix else { continue };
 324                applied = true;
 325                if let Err(err) = operation_channels[client_ix].unbounded_send(batch_id) {
 326                    log::error!("error signaling user {user_id}: {err}");
 327                }
 328            }
 329
 330            if quiesce && applied {
 331                deterministic.run_until_parked();
 332                check_consistency_between_clients(&clients);
 333            }
 334
 335            return applied;
 336        }
 337    }
 338    true
 339}
 340
 341async fn apply_client_operation(
 342    client: &TestClient,
 343    operation: ClientOperation,
 344    cx: &mut TestAppContext,
 345) -> Result<(), TestError> {
 346    match operation {
 347        ClientOperation::AcceptIncomingCall => {
 348            let active_call = cx.read(ActiveCall::global);
 349            if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {
 350                Err(TestError::Inapplicable)?;
 351            }
 352
 353            log::info!("{}: accepting incoming call", client.username);
 354            active_call
 355                .update(cx, |call, cx| call.accept_incoming(cx))
 356                .await?;
 357        }
 358
 359        ClientOperation::RejectIncomingCall => {
 360            let active_call = cx.read(ActiveCall::global);
 361            if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {
 362                Err(TestError::Inapplicable)?;
 363            }
 364
 365            log::info!("{}: declining incoming call", client.username);
 366            active_call.update(cx, |call, _| call.decline_incoming())?;
 367        }
 368
 369        ClientOperation::LeaveCall => {
 370            let active_call = cx.read(ActiveCall::global);
 371            if active_call.read_with(cx, |call, _| call.room().is_none()) {
 372                Err(TestError::Inapplicable)?;
 373            }
 374
 375            log::info!("{}: hanging up", client.username);
 376            active_call.update(cx, |call, cx| call.hang_up(cx)).await?;
 377        }
 378
 379        ClientOperation::InviteContactToCall { user_id } => {
 380            let active_call = cx.read(ActiveCall::global);
 381
 382            log::info!("{}: inviting {}", client.username, user_id,);
 383            active_call
 384                .update(cx, |call, cx| call.invite(user_id.to_proto(), None, cx))
 385                .await
 386                .log_err();
 387        }
 388
 389        ClientOperation::OpenLocalProject { first_root_name } => {
 390            log::info!(
 391                "{}: opening local project at {:?}",
 392                client.username,
 393                first_root_name
 394            );
 395
 396            let root_path = Path::new("/").join(&first_root_name);
 397            client.fs.create_dir(&root_path).await.unwrap();
 398            client
 399                .fs
 400                .create_file(&root_path.join("main.rs"), Default::default())
 401                .await
 402                .unwrap();
 403            let project = client.build_local_project(root_path, cx).await.0;
 404            ensure_project_shared(&project, client, cx).await;
 405            client.local_projects_mut().push(project.clone());
 406        }
 407
 408        ClientOperation::AddWorktreeToProject {
 409            project_root_name,
 410            new_root_path,
 411        } => {
 412            let project = project_for_root_name(client, &project_root_name, cx)
 413                .ok_or(TestError::Inapplicable)?;
 414
 415            log::info!(
 416                "{}: finding/creating local worktree at {:?} to project with root path {}",
 417                client.username,
 418                new_root_path,
 419                project_root_name
 420            );
 421
 422            ensure_project_shared(&project, client, cx).await;
 423            if !client.fs.paths().contains(&new_root_path) {
 424                client.fs.create_dir(&new_root_path).await.unwrap();
 425            }
 426            project
 427                .update(cx, |project, cx| {
 428                    project.find_or_create_local_worktree(&new_root_path, true, cx)
 429                })
 430                .await
 431                .unwrap();
 432        }
 433
 434        ClientOperation::CloseRemoteProject { project_root_name } => {
 435            let project = project_for_root_name(client, &project_root_name, cx)
 436                .ok_or(TestError::Inapplicable)?;
 437
 438            log::info!(
 439                "{}: closing remote project with root path {}",
 440                client.username,
 441                project_root_name,
 442            );
 443
 444            let ix = client
 445                .remote_projects()
 446                .iter()
 447                .position(|p| p == &project)
 448                .unwrap();
 449            cx.update(|_| {
 450                client.remote_projects_mut().remove(ix);
 451                client.buffers().retain(|p, _| *p != project);
 452                drop(project);
 453            });
 454        }
 455
 456        ClientOperation::OpenRemoteProject {
 457            host_id,
 458            first_root_name,
 459        } => {
 460            let active_call = cx.read(ActiveCall::global);
 461            let project = active_call
 462                .update(cx, |call, cx| {
 463                    let room = call.room().cloned()?;
 464                    let participant = room
 465                        .read(cx)
 466                        .remote_participants()
 467                        .get(&host_id.to_proto())?;
 468                    let project_id = participant
 469                        .projects
 470                        .iter()
 471                        .find(|project| project.worktree_root_names[0] == first_root_name)?
 472                        .id;
 473                    Some(room.update(cx, |room, cx| {
 474                        room.join_project(
 475                            project_id,
 476                            client.language_registry.clone(),
 477                            FakeFs::new(cx.background().clone()),
 478                            cx,
 479                        )
 480                    }))
 481                })
 482                .ok_or(TestError::Inapplicable)?;
 483
 484            log::info!(
 485                "{}: joining remote project of user {}, root name {}",
 486                client.username,
 487                host_id,
 488                first_root_name,
 489            );
 490
 491            let project = project.await?;
 492            client.remote_projects_mut().push(project.clone());
 493        }
 494
 495        ClientOperation::CreateWorktreeEntry {
 496            project_root_name,
 497            is_local,
 498            full_path,
 499            is_dir,
 500        } => {
 501            let project = project_for_root_name(client, &project_root_name, cx)
 502                .ok_or(TestError::Inapplicable)?;
 503            let project_path = project_path_for_full_path(&project, &full_path, cx)
 504                .ok_or(TestError::Inapplicable)?;
 505
 506            log::info!(
 507                "{}: creating {} at path {:?} in {} project {}",
 508                client.username,
 509                if is_dir { "dir" } else { "file" },
 510                full_path,
 511                if is_local { "local" } else { "remote" },
 512                project_root_name,
 513            );
 514
 515            ensure_project_shared(&project, client, cx).await;
 516            project
 517                .update(cx, |p, cx| p.create_entry(project_path, is_dir, cx))
 518                .unwrap()
 519                .await?;
 520        }
 521
 522        ClientOperation::OpenBuffer {
 523            project_root_name,
 524            is_local,
 525            full_path,
 526        } => {
 527            let project = project_for_root_name(client, &project_root_name, cx)
 528                .ok_or(TestError::Inapplicable)?;
 529            let project_path = project_path_for_full_path(&project, &full_path, cx)
 530                .ok_or(TestError::Inapplicable)?;
 531
 532            log::info!(
 533                "{}: opening buffer {:?} in {} project {}",
 534                client.username,
 535                full_path,
 536                if is_local { "local" } else { "remote" },
 537                project_root_name,
 538            );
 539
 540            ensure_project_shared(&project, client, cx).await;
 541            let buffer = project
 542                .update(cx, |project, cx| project.open_buffer(project_path, cx))
 543                .await?;
 544            client.buffers_for_project(&project).insert(buffer);
 545        }
 546
 547        ClientOperation::EditBuffer {
 548            project_root_name,
 549            is_local,
 550            full_path,
 551            edits,
 552        } => {
 553            let project = project_for_root_name(client, &project_root_name, cx)
 554                .ok_or(TestError::Inapplicable)?;
 555            let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 556                .ok_or(TestError::Inapplicable)?;
 557
 558            log::info!(
 559                "{}: editing buffer {:?} in {} project {} with {:?}",
 560                client.username,
 561                full_path,
 562                if is_local { "local" } else { "remote" },
 563                project_root_name,
 564                edits
 565            );
 566
 567            ensure_project_shared(&project, client, cx).await;
 568            buffer.update(cx, |buffer, cx| {
 569                let snapshot = buffer.snapshot();
 570                buffer.edit(
 571                    edits.into_iter().map(|(range, text)| {
 572                        let start = snapshot.clip_offset(range.start, Bias::Left);
 573                        let end = snapshot.clip_offset(range.end, Bias::Right);
 574                        (start..end, text)
 575                    }),
 576                    None,
 577                    cx,
 578                );
 579            });
 580        }
 581
 582        ClientOperation::CloseBuffer {
 583            project_root_name,
 584            is_local,
 585            full_path,
 586        } => {
 587            let project = project_for_root_name(client, &project_root_name, cx)
 588                .ok_or(TestError::Inapplicable)?;
 589            let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 590                .ok_or(TestError::Inapplicable)?;
 591
 592            log::info!(
 593                "{}: closing buffer {:?} in {} project {}",
 594                client.username,
 595                full_path,
 596                if is_local { "local" } else { "remote" },
 597                project_root_name
 598            );
 599
 600            ensure_project_shared(&project, client, cx).await;
 601            cx.update(|_| {
 602                client.buffers_for_project(&project).remove(&buffer);
 603                drop(buffer);
 604            });
 605        }
 606
 607        ClientOperation::SaveBuffer {
 608            project_root_name,
 609            is_local,
 610            full_path,
 611            detach,
 612        } => {
 613            let project = project_for_root_name(client, &project_root_name, cx)
 614                .ok_or(TestError::Inapplicable)?;
 615            let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 616                .ok_or(TestError::Inapplicable)?;
 617
 618            log::info!(
 619                "{}: saving buffer {:?} in {} project {}, {}",
 620                client.username,
 621                full_path,
 622                if is_local { "local" } else { "remote" },
 623                project_root_name,
 624                if detach { "detaching" } else { "awaiting" }
 625            );
 626
 627            ensure_project_shared(&project, client, cx).await;
 628            let requested_version = buffer.read_with(cx, |buffer, _| buffer.version());
 629            let save = project.update(cx, |project, cx| project.save_buffer(buffer, cx));
 630            let save = cx.background().spawn(async move {
 631                let (saved_version, _, _) = save
 632                    .await
 633                    .map_err(|err| anyhow!("save request failed: {:?}", err))?;
 634                assert!(saved_version.observed_all(&requested_version));
 635                anyhow::Ok(())
 636            });
 637            if detach {
 638                cx.update(|cx| save.detach_and_log_err(cx));
 639            } else {
 640                save.await?;
 641            }
 642        }
 643
 644        ClientOperation::RequestLspDataInBuffer {
 645            project_root_name,
 646            is_local,
 647            full_path,
 648            offset,
 649            kind,
 650            detach,
 651        } => {
 652            let project = project_for_root_name(client, &project_root_name, cx)
 653                .ok_or(TestError::Inapplicable)?;
 654            let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 655                .ok_or(TestError::Inapplicable)?;
 656
 657            log::info!(
 658                "{}: request LSP {:?} for buffer {:?} in {} project {}, {}",
 659                client.username,
 660                kind,
 661                full_path,
 662                if is_local { "local" } else { "remote" },
 663                project_root_name,
 664                if detach { "detaching" } else { "awaiting" }
 665            );
 666
 667            use futures::{FutureExt as _, TryFutureExt as _};
 668            let offset = buffer.read_with(cx, |b, _| b.clip_offset(offset, Bias::Left));
 669            let request = cx.foreground().spawn(project.update(cx, |project, cx| {
 670                match kind {
 671                    LspRequestKind::Rename => project
 672                        .prepare_rename(buffer, offset, cx)
 673                        .map_ok(|_| ())
 674                        .boxed(),
 675                    LspRequestKind::Completion => project
 676                        .completions(&buffer, offset, cx)
 677                        .map_ok(|_| ())
 678                        .boxed(),
 679                    LspRequestKind::CodeAction => project
 680                        .code_actions(&buffer, offset..offset, cx)
 681                        .map_ok(|_| ())
 682                        .boxed(),
 683                    LspRequestKind::Definition => project
 684                        .definition(&buffer, offset, cx)
 685                        .map_ok(|_| ())
 686                        .boxed(),
 687                    LspRequestKind::Highlights => project
 688                        .document_highlights(&buffer, offset, cx)
 689                        .map_ok(|_| ())
 690                        .boxed(),
 691                }
 692            }));
 693            if detach {
 694                request.detach();
 695            } else {
 696                request.await?;
 697            }
 698        }
 699
 700        ClientOperation::SearchProject {
 701            project_root_name,
 702            is_local,
 703            query,
 704            detach,
 705        } => {
 706            let project = project_for_root_name(client, &project_root_name, cx)
 707                .ok_or(TestError::Inapplicable)?;
 708
 709            log::info!(
 710                "{}: search {} project {} for {:?}, {}",
 711                client.username,
 712                if is_local { "local" } else { "remote" },
 713                project_root_name,
 714                query,
 715                if detach { "detaching" } else { "awaiting" }
 716            );
 717
 718            let search = project.update(cx, |project, cx| {
 719                project.search(SearchQuery::text(query, false, false), cx)
 720            });
 721            drop(project);
 722            let search = cx.background().spawn(async move {
 723                search
 724                    .await
 725                    .map_err(|err| anyhow!("search request failed: {:?}", err))
 726            });
 727            if detach {
 728                cx.update(|cx| search.detach_and_log_err(cx));
 729            } else {
 730                search.await?;
 731            }
 732        }
 733
 734        ClientOperation::WriteFsEntry {
 735            path,
 736            is_dir,
 737            content,
 738        } => {
 739            if !client
 740                .fs
 741                .directories()
 742                .contains(&path.parent().unwrap().to_owned())
 743            {
 744                return Err(TestError::Inapplicable);
 745            }
 746
 747            if is_dir {
 748                log::info!("{}: creating dir at {:?}", client.username, path);
 749                client.fs.create_dir(&path).await.unwrap();
 750            } else {
 751                let exists = client.fs.metadata(&path).await?.is_some();
 752                let verb = if exists { "updating" } else { "creating" };
 753                log::info!("{}: {} file at {:?}", verb, client.username, path);
 754
 755                client
 756                    .fs
 757                    .save(&path, &content.as_str().into(), fs::LineEnding::Unix)
 758                    .await
 759                    .unwrap();
 760            }
 761        }
 762
 763        ClientOperation::WriteGitIndex {
 764            repo_path,
 765            contents,
 766        } => {
 767            if !client.fs.directories().contains(&repo_path) {
 768                return Err(TestError::Inapplicable);
 769            }
 770
 771            log::info!(
 772                "{}: writing git index for repo {:?}: {:?}",
 773                client.username,
 774                repo_path,
 775                contents
 776            );
 777
 778            let dot_git_dir = repo_path.join(".git");
 779            let contents = contents
 780                .iter()
 781                .map(|(path, contents)| (path.as_path(), contents.clone()))
 782                .collect::<Vec<_>>();
 783            if client.fs.metadata(&dot_git_dir).await?.is_none() {
 784                client.fs.create_dir(&dot_git_dir).await?;
 785            }
 786            client.fs.set_index_for_repo(&dot_git_dir, &contents).await;
 787        }
 788    }
 789    Ok(())
 790}
 791
 792fn check_consistency_between_clients(clients: &[(Rc<TestClient>, TestAppContext)]) {
 793    for (client, client_cx) in clients {
 794        for guest_project in client.remote_projects().iter() {
 795            guest_project.read_with(client_cx, |guest_project, cx| {
 796                let host_project = clients.iter().find_map(|(client, cx)| {
 797                    let project = client
 798                        .local_projects()
 799                        .iter()
 800                        .find(|host_project| {
 801                            host_project.read_with(cx, |host_project, _| {
 802                                host_project.remote_id() == guest_project.remote_id()
 803                            })
 804                        })?
 805                        .clone();
 806                    Some((project, cx))
 807                });
 808
 809                if !guest_project.is_read_only() {
 810                    if let Some((host_project, host_cx)) = host_project {
 811                        let host_worktree_snapshots =
 812                            host_project.read_with(host_cx, |host_project, cx| {
 813                                host_project
 814                                    .worktrees(cx)
 815                                    .map(|worktree| {
 816                                        let worktree = worktree.read(cx);
 817                                        (worktree.id(), worktree.snapshot())
 818                                    })
 819                                    .collect::<BTreeMap<_, _>>()
 820                            });
 821                        let guest_worktree_snapshots = guest_project
 822                            .worktrees(cx)
 823                            .map(|worktree| {
 824                                let worktree = worktree.read(cx);
 825                                (worktree.id(), worktree.snapshot())
 826                            })
 827                            .collect::<BTreeMap<_, _>>();
 828
 829                        assert_eq!(
 830                            guest_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
 831                            host_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
 832                            "{} has different worktrees than the host for project {:?}",
 833                            client.username, guest_project.remote_id(),
 834                        );
 835
 836                        for (id, host_snapshot) in &host_worktree_snapshots {
 837                            let guest_snapshot = &guest_worktree_snapshots[id];
 838                            assert_eq!(
 839                                guest_snapshot.root_name(),
 840                                host_snapshot.root_name(),
 841                                "{} has different root name than the host for worktree {}, project {:?}",
 842                                client.username,
 843                                id,
 844                                guest_project.remote_id(),
 845                            );
 846                            assert_eq!(
 847                                guest_snapshot.abs_path(),
 848                                host_snapshot.abs_path(),
 849                                "{} has different abs path than the host for worktree {}, project: {:?}",
 850                                client.username,
 851                                id,
 852                                guest_project.remote_id(),
 853                            );
 854                            assert_eq!(
 855                                guest_snapshot.entries(false).collect::<Vec<_>>(),
 856                                host_snapshot.entries(false).collect::<Vec<_>>(),
 857                                "{} has different snapshot than the host for worktree {:?} and project {:?}",
 858                                client.username,
 859                                host_snapshot.abs_path(),
 860                                guest_project.remote_id(),
 861                            );
 862                            assert_eq!(guest_snapshot.scan_id(), host_snapshot.scan_id(),
 863                                "{} has different scan id than the host for worktree {:?} and project {:?}",
 864                                client.username,
 865                                host_snapshot.abs_path(),
 866                                guest_project.remote_id(),
 867                            );
 868                        }
 869                    }
 870                }
 871
 872                for buffer in guest_project.opened_buffers(cx) {
 873                    let buffer = buffer.read(cx);
 874                    assert_eq!(
 875                        buffer.deferred_ops_len(),
 876                        0,
 877                        "{} has deferred operations for buffer {:?} in project {:?}",
 878                        client.username,
 879                        buffer.file().unwrap().full_path(cx),
 880                        guest_project.remote_id(),
 881                    );
 882                }
 883            });
 884        }
 885
 886        let buffers = client.buffers().clone();
 887        for (guest_project, guest_buffers) in &buffers {
 888            let project_id = if guest_project.read_with(client_cx, |project, _| {
 889                project.is_local() || project.is_read_only()
 890            }) {
 891                continue;
 892            } else {
 893                guest_project
 894                    .read_with(client_cx, |project, _| project.remote_id())
 895                    .unwrap()
 896            };
 897            let guest_user_id = client.user_id().unwrap();
 898
 899            let host_project = clients.iter().find_map(|(client, cx)| {
 900                let project = client
 901                    .local_projects()
 902                    .iter()
 903                    .find(|host_project| {
 904                        host_project.read_with(cx, |host_project, _| {
 905                            host_project.remote_id() == Some(project_id)
 906                        })
 907                    })?
 908                    .clone();
 909                Some((client.user_id().unwrap(), project, cx))
 910            });
 911
 912            let (host_user_id, host_project, host_cx) =
 913                if let Some((host_user_id, host_project, host_cx)) = host_project {
 914                    (host_user_id, host_project, host_cx)
 915                } else {
 916                    continue;
 917                };
 918
 919            for guest_buffer in guest_buffers {
 920                let buffer_id = guest_buffer.read_with(client_cx, |buffer, _| buffer.remote_id());
 921                let host_buffer = host_project.read_with(host_cx, |project, cx| {
 922                    project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| {
 923                        panic!(
 924                            "host does not have buffer for guest:{}, peer:{:?}, id:{}",
 925                            client.username,
 926                            client.peer_id(),
 927                            buffer_id
 928                        )
 929                    })
 930                });
 931                let path = host_buffer
 932                    .read_with(host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
 933
 934                assert_eq!(
 935                    guest_buffer.read_with(client_cx, |buffer, _| buffer.deferred_ops_len()),
 936                    0,
 937                    "{}, buffer {}, path {:?} has deferred operations",
 938                    client.username,
 939                    buffer_id,
 940                    path,
 941                );
 942                assert_eq!(
 943                    guest_buffer.read_with(client_cx, |buffer, _| buffer.text()),
 944                    host_buffer.read_with(host_cx, |buffer, _| buffer.text()),
 945                    "{}, buffer {}, path {:?}, differs from the host's buffer",
 946                    client.username,
 947                    buffer_id,
 948                    path
 949                );
 950
 951                let host_file = host_buffer.read_with(host_cx, |b, _| b.file().cloned());
 952                let guest_file = guest_buffer.read_with(client_cx, |b, _| b.file().cloned());
 953                match (host_file, guest_file) {
 954                    (Some(host_file), Some(guest_file)) => {
 955                        assert_eq!(guest_file.path(), host_file.path());
 956                        assert_eq!(guest_file.is_deleted(), host_file.is_deleted());
 957                        assert_eq!(
 958                            guest_file.mtime(),
 959                            host_file.mtime(),
 960                            "guest {} mtime does not match host {} for path {:?} in project {}",
 961                            guest_user_id,
 962                            host_user_id,
 963                            guest_file.path(),
 964                            project_id,
 965                        );
 966                    }
 967                    (None, None) => {}
 968                    (None, _) => panic!("host's file is None, guest's isn't"),
 969                    (_, None) => panic!("guest's file is None, hosts's isn't"),
 970                }
 971
 972                let host_diff_base =
 973                    host_buffer.read_with(host_cx, |b, _| b.diff_base().map(ToString::to_string));
 974                let guest_diff_base = guest_buffer
 975                    .read_with(client_cx, |b, _| b.diff_base().map(ToString::to_string));
 976                assert_eq!(guest_diff_base, host_diff_base);
 977
 978                let host_saved_version =
 979                    host_buffer.read_with(host_cx, |b, _| b.saved_version().clone());
 980                let guest_saved_version =
 981                    guest_buffer.read_with(client_cx, |b, _| b.saved_version().clone());
 982                assert_eq!(
 983                    guest_saved_version, host_saved_version,
 984                    "guest {} saved version does not match host's for path {path:?} in project {project_id}",
 985                    client.username
 986                );
 987
 988                let host_saved_version_fingerprint =
 989                    host_buffer.read_with(host_cx, |b, _| b.saved_version_fingerprint());
 990                let guest_saved_version_fingerprint =
 991                    guest_buffer.read_with(client_cx, |b, _| b.saved_version_fingerprint());
 992                assert_eq!(
 993                    guest_saved_version_fingerprint, host_saved_version_fingerprint,
 994                    "guest {} saved fingerprint does not match host's for path {path:?} in project {project_id}",
 995                    client.username
 996                );
 997
 998                let host_saved_mtime = host_buffer.read_with(host_cx, |b, _| b.saved_mtime());
 999                let guest_saved_mtime = guest_buffer.read_with(client_cx, |b, _| b.saved_mtime());
1000                assert_eq!(
1001                    guest_saved_mtime, host_saved_mtime,
1002                    "guest {} saved mtime does not match host's for path {path:?} in project {project_id}",
1003                    client.username
1004                );
1005
1006                let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
1007                let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
1008                assert_eq!(guest_is_dirty, host_is_dirty,
1009                    "guest {} dirty status does not match host's for path {path:?} in project {project_id}",
1010                    client.username
1011                );
1012
1013                let host_has_conflict = host_buffer.read_with(host_cx, |b, _| b.has_conflict());
1014                let guest_has_conflict = guest_buffer.read_with(client_cx, |b, _| b.has_conflict());
1015                assert_eq!(guest_has_conflict, host_has_conflict,
1016                    "guest {} conflict status does not match host's for path {path:?} in project {project_id}",
1017                    client.username
1018                );
1019            }
1020        }
1021    }
1022}
1023
1024struct TestPlan {
1025    rng: StdRng,
1026    replay: bool,
1027    stored_operations: Vec<(StoredOperation, Arc<AtomicBool>)>,
1028    max_operations: usize,
1029    operation_ix: usize,
1030    users: Vec<UserTestPlan>,
1031    next_batch_id: usize,
1032    allow_server_restarts: bool,
1033    allow_client_reconnection: bool,
1034    allow_client_disconnection: bool,
1035}
1036
1037struct UserTestPlan {
1038    user_id: UserId,
1039    username: String,
1040    next_root_id: usize,
1041    operation_ix: usize,
1042    online: bool,
1043}
1044
1045#[derive(Clone, Debug, Serialize, Deserialize)]
1046#[serde(untagged)]
1047enum StoredOperation {
1048    Server(Operation),
1049    Client {
1050        user_id: UserId,
1051        batch_id: usize,
1052        operation: ClientOperation,
1053    },
1054}
1055
1056#[derive(Clone, Debug, Serialize, Deserialize)]
1057enum Operation {
1058    AddConnection {
1059        user_id: UserId,
1060    },
1061    RemoveConnection {
1062        user_id: UserId,
1063    },
1064    BounceConnection {
1065        user_id: UserId,
1066    },
1067    RestartServer,
1068    MutateClients {
1069        batch_id: usize,
1070        #[serde(skip_serializing)]
1071        #[serde(skip_deserializing)]
1072        user_ids: Vec<UserId>,
1073        quiesce: bool,
1074    },
1075}
1076
1077#[derive(Clone, Debug, Serialize, Deserialize)]
1078enum ClientOperation {
1079    AcceptIncomingCall,
1080    RejectIncomingCall,
1081    LeaveCall,
1082    InviteContactToCall {
1083        user_id: UserId,
1084    },
1085    OpenLocalProject {
1086        first_root_name: String,
1087    },
1088    OpenRemoteProject {
1089        host_id: UserId,
1090        first_root_name: String,
1091    },
1092    AddWorktreeToProject {
1093        project_root_name: String,
1094        new_root_path: PathBuf,
1095    },
1096    CloseRemoteProject {
1097        project_root_name: String,
1098    },
1099    OpenBuffer {
1100        project_root_name: String,
1101        is_local: bool,
1102        full_path: PathBuf,
1103    },
1104    SearchProject {
1105        project_root_name: String,
1106        is_local: bool,
1107        query: String,
1108        detach: bool,
1109    },
1110    EditBuffer {
1111        project_root_name: String,
1112        is_local: bool,
1113        full_path: PathBuf,
1114        edits: Vec<(Range<usize>, Arc<str>)>,
1115    },
1116    CloseBuffer {
1117        project_root_name: String,
1118        is_local: bool,
1119        full_path: PathBuf,
1120    },
1121    SaveBuffer {
1122        project_root_name: String,
1123        is_local: bool,
1124        full_path: PathBuf,
1125        detach: bool,
1126    },
1127    RequestLspDataInBuffer {
1128        project_root_name: String,
1129        is_local: bool,
1130        full_path: PathBuf,
1131        offset: usize,
1132        kind: LspRequestKind,
1133        detach: bool,
1134    },
1135    CreateWorktreeEntry {
1136        project_root_name: String,
1137        is_local: bool,
1138        full_path: PathBuf,
1139        is_dir: bool,
1140    },
1141    WriteFsEntry {
1142        path: PathBuf,
1143        is_dir: bool,
1144        content: String,
1145    },
1146    WriteGitIndex {
1147        repo_path: PathBuf,
1148        contents: Vec<(PathBuf, String)>,
1149    },
1150}
1151
1152#[derive(Clone, Debug, Serialize, Deserialize)]
1153enum LspRequestKind {
1154    Rename,
1155    Completion,
1156    CodeAction,
1157    Definition,
1158    Highlights,
1159}
1160
1161enum TestError {
1162    Inapplicable,
1163    Other(anyhow::Error),
1164}
1165
1166impl From<anyhow::Error> for TestError {
1167    fn from(value: anyhow::Error) -> Self {
1168        Self::Other(value)
1169    }
1170}
1171
1172impl TestPlan {
1173    fn new(mut rng: StdRng, users: Vec<UserTestPlan>, max_operations: usize) -> Self {
1174        Self {
1175            replay: false,
1176            allow_server_restarts: rng.gen_bool(0.7),
1177            allow_client_reconnection: rng.gen_bool(0.7),
1178            allow_client_disconnection: rng.gen_bool(0.1),
1179            stored_operations: Vec::new(),
1180            operation_ix: 0,
1181            next_batch_id: 0,
1182            max_operations,
1183            users,
1184            rng,
1185        }
1186    }
1187
1188    fn deserialize(&mut self, json: Vec<u8>) {
1189        let stored_operations: Vec<StoredOperation> = serde_json::from_slice(&json).unwrap();
1190        self.replay = true;
1191        self.stored_operations = stored_operations
1192            .iter()
1193            .cloned()
1194            .enumerate()
1195            .map(|(i, mut operation)| {
1196                if let StoredOperation::Server(Operation::MutateClients {
1197                    batch_id: current_batch_id,
1198                    user_ids,
1199                    ..
1200                }) = &mut operation
1201                {
1202                    assert!(user_ids.is_empty());
1203                    user_ids.extend(stored_operations[i + 1..].iter().filter_map(|operation| {
1204                        if let StoredOperation::Client {
1205                            user_id, batch_id, ..
1206                        } = operation
1207                        {
1208                            if batch_id == current_batch_id {
1209                                return Some(user_id);
1210                            }
1211                        }
1212                        None
1213                    }));
1214                    user_ids.sort_unstable();
1215                }
1216                (operation, Arc::new(AtomicBool::new(false)))
1217            })
1218            .collect()
1219    }
1220
1221    fn serialize(&mut self) -> Vec<u8> {
1222        // Format each operation as one line
1223        let mut json = Vec::new();
1224        json.push(b'[');
1225        for (operation, applied) in &self.stored_operations {
1226            if !applied.load(SeqCst) {
1227                continue;
1228            }
1229            if json.len() > 1 {
1230                json.push(b',');
1231            }
1232            json.extend_from_slice(b"\n  ");
1233            serde_json::to_writer(&mut json, operation).unwrap();
1234        }
1235        json.extend_from_slice(b"\n]\n");
1236        json
1237    }
1238
1239    fn next_server_operation(
1240        &mut self,
1241        clients: &[(Rc<TestClient>, TestAppContext)],
1242    ) -> Option<(Operation, Arc<AtomicBool>)> {
1243        if self.replay {
1244            while let Some(stored_operation) = self.stored_operations.get(self.operation_ix) {
1245                self.operation_ix += 1;
1246                if let (StoredOperation::Server(operation), applied) = stored_operation {
1247                    return Some((operation.clone(), applied.clone()));
1248                }
1249            }
1250            None
1251        } else {
1252            let operation = self.generate_server_operation(clients)?;
1253            let applied = Arc::new(AtomicBool::new(false));
1254            self.stored_operations
1255                .push((StoredOperation::Server(operation.clone()), applied.clone()));
1256            Some((operation, applied))
1257        }
1258    }
1259
1260    fn next_client_operation(
1261        &mut self,
1262        client: &TestClient,
1263        current_batch_id: usize,
1264        cx: &TestAppContext,
1265    ) -> Option<(ClientOperation, Arc<AtomicBool>)> {
1266        let current_user_id = client.current_user_id(cx);
1267        let user_ix = self
1268            .users
1269            .iter()
1270            .position(|user| user.user_id == current_user_id)
1271            .unwrap();
1272        let user_plan = &mut self.users[user_ix];
1273
1274        if self.replay {
1275            while let Some(stored_operation) = self.stored_operations.get(user_plan.operation_ix) {
1276                user_plan.operation_ix += 1;
1277                if let (
1278                    StoredOperation::Client {
1279                        user_id, operation, ..
1280                    },
1281                    applied,
1282                ) = stored_operation
1283                {
1284                    if user_id == &current_user_id {
1285                        return Some((operation.clone(), applied.clone()));
1286                    }
1287                }
1288            }
1289            None
1290        } else {
1291            let operation = self.generate_client_operation(current_user_id, client, cx)?;
1292            let applied = Arc::new(AtomicBool::new(false));
1293            self.stored_operations.push((
1294                StoredOperation::Client {
1295                    user_id: current_user_id,
1296                    batch_id: current_batch_id,
1297                    operation: operation.clone(),
1298                },
1299                applied.clone(),
1300            ));
1301            Some((operation, applied))
1302        }
1303    }
1304
1305    fn generate_server_operation(
1306        &mut self,
1307        clients: &[(Rc<TestClient>, TestAppContext)],
1308    ) -> Option<Operation> {
1309        if self.operation_ix == self.max_operations {
1310            return None;
1311        }
1312
1313        Some(loop {
1314            break match self.rng.gen_range(0..100) {
1315                0..=29 if clients.len() < self.users.len() => {
1316                    let user = self
1317                        .users
1318                        .iter()
1319                        .filter(|u| !u.online)
1320                        .choose(&mut self.rng)
1321                        .unwrap();
1322                    self.operation_ix += 1;
1323                    Operation::AddConnection {
1324                        user_id: user.user_id,
1325                    }
1326                }
1327                30..=34 if clients.len() > 1 && self.allow_client_disconnection => {
1328                    let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];
1329                    let user_id = client.current_user_id(cx);
1330                    self.operation_ix += 1;
1331                    Operation::RemoveConnection { user_id }
1332                }
1333                35..=39 if clients.len() > 1 && self.allow_client_reconnection => {
1334                    let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];
1335                    let user_id = client.current_user_id(cx);
1336                    self.operation_ix += 1;
1337                    Operation::BounceConnection { user_id }
1338                }
1339                40..=44 if self.allow_server_restarts && clients.len() > 1 => {
1340                    self.operation_ix += 1;
1341                    Operation::RestartServer
1342                }
1343                _ if !clients.is_empty() => {
1344                    let count = self
1345                        .rng
1346                        .gen_range(1..10)
1347                        .min(self.max_operations - self.operation_ix);
1348                    let batch_id = util::post_inc(&mut self.next_batch_id);
1349                    let mut user_ids = (0..count)
1350                        .map(|_| {
1351                            let ix = self.rng.gen_range(0..clients.len());
1352                            let (client, cx) = &clients[ix];
1353                            client.current_user_id(cx)
1354                        })
1355                        .collect::<Vec<_>>();
1356                    user_ids.sort_unstable();
1357                    Operation::MutateClients {
1358                        user_ids,
1359                        batch_id,
1360                        quiesce: self.rng.gen_bool(0.7),
1361                    }
1362                }
1363                _ => continue,
1364            };
1365        })
1366    }
1367
1368    fn generate_client_operation(
1369        &mut self,
1370        user_id: UserId,
1371        client: &TestClient,
1372        cx: &TestAppContext,
1373    ) -> Option<ClientOperation> {
1374        if self.operation_ix == self.max_operations {
1375            return None;
1376        }
1377
1378        self.operation_ix += 1;
1379        let call = cx.read(ActiveCall::global);
1380        Some(loop {
1381            match self.rng.gen_range(0..100_u32) {
1382                // Mutate the call
1383                0..=29 => {
1384                    // Respond to an incoming call
1385                    if call.read_with(cx, |call, _| call.incoming().borrow().is_some()) {
1386                        break if self.rng.gen_bool(0.7) {
1387                            ClientOperation::AcceptIncomingCall
1388                        } else {
1389                            ClientOperation::RejectIncomingCall
1390                        };
1391                    }
1392
1393                    match self.rng.gen_range(0..100_u32) {
1394                        // Invite a contact to the current call
1395                        0..=70 => {
1396                            let available_contacts =
1397                                client.user_store.read_with(cx, |user_store, _| {
1398                                    user_store
1399                                        .contacts()
1400                                        .iter()
1401                                        .filter(|contact| contact.online && !contact.busy)
1402                                        .cloned()
1403                                        .collect::<Vec<_>>()
1404                                });
1405                            if !available_contacts.is_empty() {
1406                                let contact = available_contacts.choose(&mut self.rng).unwrap();
1407                                break ClientOperation::InviteContactToCall {
1408                                    user_id: UserId(contact.user.id as i32),
1409                                };
1410                            }
1411                        }
1412
1413                        // Leave the current call
1414                        71.. => {
1415                            if self.allow_client_disconnection
1416                                && call.read_with(cx, |call, _| call.room().is_some())
1417                            {
1418                                break ClientOperation::LeaveCall;
1419                            }
1420                        }
1421                    }
1422                }
1423
1424                // Mutate projects
1425                30..=59 => match self.rng.gen_range(0..100_u32) {
1426                    // Open a new project
1427                    0..=70 => {
1428                        // Open a remote project
1429                        if let Some(room) = call.read_with(cx, |call, _| call.room().cloned()) {
1430                            let existing_remote_project_ids = cx.read(|cx| {
1431                                client
1432                                    .remote_projects()
1433                                    .iter()
1434                                    .map(|p| p.read(cx).remote_id().unwrap())
1435                                    .collect::<Vec<_>>()
1436                            });
1437                            let new_remote_projects = room.read_with(cx, |room, _| {
1438                                room.remote_participants()
1439                                    .values()
1440                                    .flat_map(|participant| {
1441                                        participant.projects.iter().filter_map(|project| {
1442                                            if existing_remote_project_ids.contains(&project.id) {
1443                                                None
1444                                            } else {
1445                                                Some((
1446                                                    UserId::from_proto(participant.user.id),
1447                                                    project.worktree_root_names[0].clone(),
1448                                                ))
1449                                            }
1450                                        })
1451                                    })
1452                                    .collect::<Vec<_>>()
1453                            });
1454                            if !new_remote_projects.is_empty() {
1455                                let (host_id, first_root_name) =
1456                                    new_remote_projects.choose(&mut self.rng).unwrap().clone();
1457                                break ClientOperation::OpenRemoteProject {
1458                                    host_id,
1459                                    first_root_name,
1460                                };
1461                            }
1462                        }
1463                        // Open a local project
1464                        else {
1465                            let first_root_name = self.next_root_dir_name(user_id);
1466                            break ClientOperation::OpenLocalProject { first_root_name };
1467                        }
1468                    }
1469
1470                    // Close a remote project
1471                    71..=80 => {
1472                        if !client.remote_projects().is_empty() {
1473                            let project = client
1474                                .remote_projects()
1475                                .choose(&mut self.rng)
1476                                .unwrap()
1477                                .clone();
1478                            let first_root_name = root_name_for_project(&project, cx);
1479                            break ClientOperation::CloseRemoteProject {
1480                                project_root_name: first_root_name,
1481                            };
1482                        }
1483                    }
1484
1485                    // Mutate project worktrees
1486                    81.. => match self.rng.gen_range(0..100_u32) {
1487                        // Add a worktree to a local project
1488                        0..=50 => {
1489                            let Some(project) = client
1490                                .local_projects()
1491                                .choose(&mut self.rng)
1492                                .cloned() else { continue };
1493                            let project_root_name = root_name_for_project(&project, cx);
1494                            let mut paths = client.fs.paths();
1495                            paths.remove(0);
1496                            let new_root_path = if paths.is_empty() || self.rng.gen() {
1497                                Path::new("/").join(&self.next_root_dir_name(user_id))
1498                            } else {
1499                                paths.choose(&mut self.rng).unwrap().clone()
1500                            };
1501                            break ClientOperation::AddWorktreeToProject {
1502                                project_root_name,
1503                                new_root_path,
1504                            };
1505                        }
1506
1507                        // Add an entry to a worktree
1508                        _ => {
1509                            let Some(project) = choose_random_project(client, &mut self.rng) else { continue };
1510                            let project_root_name = root_name_for_project(&project, cx);
1511                            let is_local = project.read_with(cx, |project, _| project.is_local());
1512                            let worktree = project.read_with(cx, |project, cx| {
1513                                project
1514                                    .worktrees(cx)
1515                                    .filter(|worktree| {
1516                                        let worktree = worktree.read(cx);
1517                                        worktree.is_visible()
1518                                            && worktree.entries(false).any(|e| e.is_file())
1519                                            && worktree.root_entry().map_or(false, |e| e.is_dir())
1520                                    })
1521                                    .choose(&mut self.rng)
1522                            });
1523                            let Some(worktree) = worktree else { continue };
1524                            let is_dir = self.rng.gen::<bool>();
1525                            let mut full_path =
1526                                worktree.read_with(cx, |w, _| PathBuf::from(w.root_name()));
1527                            full_path.push(gen_file_name(&mut self.rng));
1528                            if !is_dir {
1529                                full_path.set_extension("rs");
1530                            }
1531                            break ClientOperation::CreateWorktreeEntry {
1532                                project_root_name,
1533                                is_local,
1534                                full_path,
1535                                is_dir,
1536                            };
1537                        }
1538                    },
1539                },
1540
1541                // Query and mutate buffers
1542                60..=90 => {
1543                    let Some(project) = choose_random_project(client, &mut self.rng) else { continue };
1544                    let project_root_name = root_name_for_project(&project, cx);
1545                    let is_local = project.read_with(cx, |project, _| project.is_local());
1546
1547                    match self.rng.gen_range(0..100_u32) {
1548                        // Manipulate an existing buffer
1549                        0..=70 => {
1550                            let Some(buffer) = client
1551                                .buffers_for_project(&project)
1552                                .iter()
1553                                .choose(&mut self.rng)
1554                                .cloned() else { continue };
1555
1556                            let full_path = buffer
1557                                .read_with(cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
1558
1559                            match self.rng.gen_range(0..100_u32) {
1560                                // Close the buffer
1561                                0..=15 => {
1562                                    break ClientOperation::CloseBuffer {
1563                                        project_root_name,
1564                                        is_local,
1565                                        full_path,
1566                                    };
1567                                }
1568                                // Save the buffer
1569                                16..=29 if buffer.read_with(cx, |b, _| b.is_dirty()) => {
1570                                    let detach = self.rng.gen_bool(0.3);
1571                                    break ClientOperation::SaveBuffer {
1572                                        project_root_name,
1573                                        is_local,
1574                                        full_path,
1575                                        detach,
1576                                    };
1577                                }
1578                                // Edit the buffer
1579                                30..=69 => {
1580                                    let edits = buffer.read_with(cx, |buffer, _| {
1581                                        buffer.get_random_edits(&mut self.rng, 3)
1582                                    });
1583                                    break ClientOperation::EditBuffer {
1584                                        project_root_name,
1585                                        is_local,
1586                                        full_path,
1587                                        edits,
1588                                    };
1589                                }
1590                                // Make an LSP request
1591                                _ => {
1592                                    let offset = buffer.read_with(cx, |buffer, _| {
1593                                        buffer.clip_offset(
1594                                            self.rng.gen_range(0..=buffer.len()),
1595                                            language::Bias::Left,
1596                                        )
1597                                    });
1598                                    let detach = self.rng.gen();
1599                                    break ClientOperation::RequestLspDataInBuffer {
1600                                        project_root_name,
1601                                        full_path,
1602                                        offset,
1603                                        is_local,
1604                                        kind: match self.rng.gen_range(0..5_u32) {
1605                                            0 => LspRequestKind::Rename,
1606                                            1 => LspRequestKind::Highlights,
1607                                            2 => LspRequestKind::Definition,
1608                                            3 => LspRequestKind::CodeAction,
1609                                            4.. => LspRequestKind::Completion,
1610                                        },
1611                                        detach,
1612                                    };
1613                                }
1614                            }
1615                        }
1616
1617                        71..=80 => {
1618                            let query = self.rng.gen_range('a'..='z').to_string();
1619                            let detach = self.rng.gen_bool(0.3);
1620                            break ClientOperation::SearchProject {
1621                                project_root_name,
1622                                is_local,
1623                                query,
1624                                detach,
1625                            };
1626                        }
1627
1628                        // Open a buffer
1629                        81.. => {
1630                            let worktree = project.read_with(cx, |project, cx| {
1631                                project
1632                                    .worktrees(cx)
1633                                    .filter(|worktree| {
1634                                        let worktree = worktree.read(cx);
1635                                        worktree.is_visible()
1636                                            && worktree.entries(false).any(|e| e.is_file())
1637                                    })
1638                                    .choose(&mut self.rng)
1639                            });
1640                            let Some(worktree) = worktree else { continue };
1641                            let full_path = worktree.read_with(cx, |worktree, _| {
1642                                let entry = worktree
1643                                    .entries(false)
1644                                    .filter(|e| e.is_file())
1645                                    .choose(&mut self.rng)
1646                                    .unwrap();
1647                                if entry.path.as_ref() == Path::new("") {
1648                                    Path::new(worktree.root_name()).into()
1649                                } else {
1650                                    Path::new(worktree.root_name()).join(&entry.path)
1651                                }
1652                            });
1653                            break ClientOperation::OpenBuffer {
1654                                project_root_name,
1655                                is_local,
1656                                full_path,
1657                            };
1658                        }
1659                    }
1660                }
1661
1662                // Update a git index
1663                91..=95 => {
1664                    let repo_path = client
1665                        .fs
1666                        .directories()
1667                        .choose(&mut self.rng)
1668                        .unwrap()
1669                        .clone();
1670
1671                    let mut file_paths = client
1672                        .fs
1673                        .files()
1674                        .into_iter()
1675                        .filter(|path| path.starts_with(&repo_path))
1676                        .collect::<Vec<_>>();
1677                    let count = self.rng.gen_range(0..=file_paths.len());
1678                    file_paths.shuffle(&mut self.rng);
1679                    file_paths.truncate(count);
1680
1681                    let mut contents = Vec::new();
1682                    for abs_child_file_path in &file_paths {
1683                        let child_file_path = abs_child_file_path
1684                            .strip_prefix(&repo_path)
1685                            .unwrap()
1686                            .to_path_buf();
1687                        let new_base = Alphanumeric.sample_string(&mut self.rng, 16);
1688                        contents.push((child_file_path, new_base));
1689                    }
1690
1691                    break ClientOperation::WriteGitIndex {
1692                        repo_path,
1693                        contents,
1694                    };
1695                }
1696
1697                // Create or update a file or directory
1698                96.. => {
1699                    let is_dir = self.rng.gen::<bool>();
1700                    let content;
1701                    let mut path;
1702                    let dir_paths = client.fs.directories();
1703
1704                    if is_dir {
1705                        content = String::new();
1706                        path = dir_paths.choose(&mut self.rng).unwrap().clone();
1707                        path.push(gen_file_name(&mut self.rng));
1708                    } else {
1709                        content = Alphanumeric.sample_string(&mut self.rng, 16);
1710
1711                        // Create a new file or overwrite an existing file
1712                        let file_paths = client.fs.files();
1713                        if file_paths.is_empty() || self.rng.gen_bool(0.5) {
1714                            path = dir_paths.choose(&mut self.rng).unwrap().clone();
1715                            path.push(gen_file_name(&mut self.rng));
1716                            path.set_extension("rs");
1717                        } else {
1718                            path = file_paths.choose(&mut self.rng).unwrap().clone()
1719                        };
1720                    }
1721                    break ClientOperation::WriteFsEntry {
1722                        path,
1723                        is_dir,
1724                        content,
1725                    };
1726                }
1727            }
1728        })
1729    }
1730
1731    fn next_root_dir_name(&mut self, user_id: UserId) -> String {
1732        let user_ix = self
1733            .users
1734            .iter()
1735            .position(|user| user.user_id == user_id)
1736            .unwrap();
1737        let root_id = util::post_inc(&mut self.users[user_ix].next_root_id);
1738        format!("dir-{user_id}-{root_id}")
1739    }
1740
1741    fn user(&mut self, user_id: UserId) -> &mut UserTestPlan {
1742        let ix = self
1743            .users
1744            .iter()
1745            .position(|user| user.user_id == user_id)
1746            .unwrap();
1747        &mut self.users[ix]
1748    }
1749}
1750
1751async fn simulate_client(
1752    client: Rc<TestClient>,
1753    mut operation_rx: futures::channel::mpsc::UnboundedReceiver<usize>,
1754    plan: Arc<Mutex<TestPlan>>,
1755    mut cx: TestAppContext,
1756) {
1757    // Setup language server
1758    let mut language = Language::new(
1759        LanguageConfig {
1760            name: "Rust".into(),
1761            path_suffixes: vec!["rs".to_string()],
1762            ..Default::default()
1763        },
1764        None,
1765    );
1766    let _fake_language_servers = language
1767        .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
1768            name: "the-fake-language-server",
1769            capabilities: lsp::LanguageServer::full_capabilities(),
1770            initializer: Some(Box::new({
1771                let fs = client.fs.clone();
1772                move |fake_server: &mut FakeLanguageServer| {
1773                    fake_server.handle_request::<lsp::request::Completion, _, _>(
1774                        |_, _| async move {
1775                            Ok(Some(lsp::CompletionResponse::Array(vec![
1776                                lsp::CompletionItem {
1777                                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1778                                        range: lsp::Range::new(
1779                                            lsp::Position::new(0, 0),
1780                                            lsp::Position::new(0, 0),
1781                                        ),
1782                                        new_text: "the-new-text".to_string(),
1783                                    })),
1784                                    ..Default::default()
1785                                },
1786                            ])))
1787                        },
1788                    );
1789
1790                    fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
1791                        |_, _| async move {
1792                            Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
1793                                lsp::CodeAction {
1794                                    title: "the-code-action".to_string(),
1795                                    ..Default::default()
1796                                },
1797                            )]))
1798                        },
1799                    );
1800
1801                    fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
1802                        |params, _| async move {
1803                            Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
1804                                params.position,
1805                                params.position,
1806                            ))))
1807                        },
1808                    );
1809
1810                    fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
1811                        let fs = fs.clone();
1812                        move |_, cx| {
1813                            let background = cx.background();
1814                            let mut rng = background.rng();
1815                            let count = rng.gen_range::<usize, _>(1..3);
1816                            let files = fs.files();
1817                            let files = (0..count)
1818                                .map(|_| files.choose(&mut *rng).unwrap().clone())
1819                                .collect::<Vec<_>>();
1820                            async move {
1821                                log::info!("LSP: Returning definitions in files {:?}", &files);
1822                                Ok(Some(lsp::GotoDefinitionResponse::Array(
1823                                    files
1824                                        .into_iter()
1825                                        .map(|file| lsp::Location {
1826                                            uri: lsp::Url::from_file_path(file).unwrap(),
1827                                            range: Default::default(),
1828                                        })
1829                                        .collect(),
1830                                )))
1831                            }
1832                        }
1833                    });
1834
1835                    fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
1836                        move |_, cx| {
1837                            let mut highlights = Vec::new();
1838                            let background = cx.background();
1839                            let mut rng = background.rng();
1840
1841                            let highlight_count = rng.gen_range(1..=5);
1842                            for _ in 0..highlight_count {
1843                                let start_row = rng.gen_range(0..100);
1844                                let start_column = rng.gen_range(0..100);
1845                                let end_row = rng.gen_range(0..100);
1846                                let end_column = rng.gen_range(0..100);
1847                                let start = PointUtf16::new(start_row, start_column);
1848                                let end = PointUtf16::new(end_row, end_column);
1849                                let range = if start > end { end..start } else { start..end };
1850                                highlights.push(lsp::DocumentHighlight {
1851                                    range: range_to_lsp(range.clone()),
1852                                    kind: Some(lsp::DocumentHighlightKind::READ),
1853                                });
1854                            }
1855                            highlights.sort_unstable_by_key(|highlight| {
1856                                (highlight.range.start, highlight.range.end)
1857                            });
1858                            async move { Ok(Some(highlights)) }
1859                        },
1860                    );
1861                }
1862            })),
1863            ..Default::default()
1864        }))
1865        .await;
1866    client.language_registry.add(Arc::new(language));
1867
1868    while let Some(batch_id) = operation_rx.next().await {
1869        let Some((operation, applied)) = plan.lock().next_client_operation(&client, batch_id, &cx) else { break };
1870        applied.store(true, SeqCst);
1871        match apply_client_operation(&client, operation, &mut cx).await {
1872            Ok(()) => {}
1873            Err(TestError::Inapplicable) => {
1874                applied.store(false, SeqCst);
1875                log::info!("skipped operation");
1876            }
1877            Err(TestError::Other(error)) => {
1878                log::error!("{} error: {}", client.username, error);
1879            }
1880        }
1881        cx.background().simulate_random_delay().await;
1882    }
1883    log::info!("{}: done", client.username);
1884}
1885
1886fn buffer_for_full_path(
1887    client: &TestClient,
1888    project: &ModelHandle<Project>,
1889    full_path: &PathBuf,
1890    cx: &TestAppContext,
1891) -> Option<ModelHandle<language::Buffer>> {
1892    client
1893        .buffers_for_project(project)
1894        .iter()
1895        .find(|buffer| {
1896            buffer.read_with(cx, |buffer, cx| {
1897                buffer.file().unwrap().full_path(cx) == *full_path
1898            })
1899        })
1900        .cloned()
1901}
1902
1903fn project_for_root_name(
1904    client: &TestClient,
1905    root_name: &str,
1906    cx: &TestAppContext,
1907) -> Option<ModelHandle<Project>> {
1908    if let Some(ix) = project_ix_for_root_name(&*client.local_projects(), root_name, cx) {
1909        return Some(client.local_projects()[ix].clone());
1910    }
1911    if let Some(ix) = project_ix_for_root_name(&*client.remote_projects(), root_name, cx) {
1912        return Some(client.remote_projects()[ix].clone());
1913    }
1914    None
1915}
1916
1917fn project_ix_for_root_name(
1918    projects: &[ModelHandle<Project>],
1919    root_name: &str,
1920    cx: &TestAppContext,
1921) -> Option<usize> {
1922    projects.iter().position(|project| {
1923        project.read_with(cx, |project, cx| {
1924            let worktree = project.visible_worktrees(cx).next().unwrap();
1925            worktree.read(cx).root_name() == root_name
1926        })
1927    })
1928}
1929
1930fn root_name_for_project(project: &ModelHandle<Project>, cx: &TestAppContext) -> String {
1931    project.read_with(cx, |project, cx| {
1932        project
1933            .visible_worktrees(cx)
1934            .next()
1935            .unwrap()
1936            .read(cx)
1937            .root_name()
1938            .to_string()
1939    })
1940}
1941
1942fn project_path_for_full_path(
1943    project: &ModelHandle<Project>,
1944    full_path: &Path,
1945    cx: &TestAppContext,
1946) -> Option<ProjectPath> {
1947    let mut components = full_path.components();
1948    let root_name = components.next().unwrap().as_os_str().to_str().unwrap();
1949    let path = components.as_path().into();
1950    let worktree_id = project.read_with(cx, |project, cx| {
1951        project.worktrees(cx).find_map(|worktree| {
1952            let worktree = worktree.read(cx);
1953            if worktree.root_name() == root_name {
1954                Some(worktree.id())
1955            } else {
1956                None
1957            }
1958        })
1959    })?;
1960    Some(ProjectPath { worktree_id, path })
1961}
1962
1963async fn ensure_project_shared(
1964    project: &ModelHandle<Project>,
1965    client: &TestClient,
1966    cx: &mut TestAppContext,
1967) {
1968    let first_root_name = root_name_for_project(project, cx);
1969    let active_call = cx.read(ActiveCall::global);
1970    if active_call.read_with(cx, |call, _| call.room().is_some())
1971        && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())
1972    {
1973        match active_call
1974            .update(cx, |call, cx| call.share_project(project.clone(), cx))
1975            .await
1976        {
1977            Ok(project_id) => {
1978                log::info!(
1979                    "{}: shared project {} with id {}",
1980                    client.username,
1981                    first_root_name,
1982                    project_id
1983                );
1984            }
1985            Err(error) => {
1986                log::error!(
1987                    "{}: error sharing project {}: {:?}",
1988                    client.username,
1989                    first_root_name,
1990                    error
1991                );
1992            }
1993        }
1994    }
1995}
1996
1997fn choose_random_project(client: &TestClient, rng: &mut StdRng) -> Option<ModelHandle<Project>> {
1998    client
1999        .local_projects()
2000        .iter()
2001        .chain(client.remote_projects().iter())
2002        .choose(rng)
2003        .cloned()
2004}
2005
2006fn gen_file_name(rng: &mut StdRng) -> String {
2007    let mut name = String::new();
2008    for _ in 0..10 {
2009        let letter = rng.gen_range('a'..='z');
2010        name.push(letter);
2011    }
2012    name
2013}
2014
2015fn path_env_var(name: &str) -> Option<PathBuf> {
2016    let value = env::var(name).ok()?;
2017    let mut path = PathBuf::from(value);
2018    if path.is_relative() {
2019        let mut abs_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2020        abs_path.pop();
2021        abs_path.pop();
2022        abs_path.push(path);
2023        path = abs_path
2024    }
2025    Some(path)
2026}