random_project_collaboration_tests.rs

   1use super::{RandomizedTest, TestClient, TestError, TestServer, UserTestPlan};
   2use crate::{db::UserId, tests::run_randomized_test};
   3use anyhow::{Result, anyhow};
   4use async_trait::async_trait;
   5use call::ActiveCall;
   6use collections::{BTreeMap, HashMap};
   7use editor::Bias;
   8use fs::{FakeFs, Fs as _};
   9use git::status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode};
  10use gpui::{BackgroundExecutor, Entity, TestAppContext};
  11use language::{
  12    FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, PointUtf16, range_to_lsp,
  13};
  14use lsp::FakeLanguageServer;
  15use pretty_assertions::assert_eq;
  16use project::{
  17    DEFAULT_COMPLETION_CONTEXT, Project, ProjectPath, search::SearchQuery, search::SearchResult,
  18};
  19use rand::{
  20    distributions::{Alphanumeric, DistString},
  21    prelude::*,
  22};
  23use serde::{Deserialize, Serialize};
  24use std::{
  25    ops::{Deref, Range},
  26    path::{Path, PathBuf},
  27    rc::Rc,
  28    sync::Arc,
  29};
  30use util::{ResultExt, path};
  31
  32#[gpui::test(
  33    iterations = 100,
  34    on_failure = "crate::tests::save_randomized_test_plan"
  35)]
  36async fn test_random_project_collaboration(
  37    cx: &mut TestAppContext,
  38    executor: BackgroundExecutor,
  39    rng: StdRng,
  40) {
  41    run_randomized_test::<ProjectCollaborationTest>(cx, executor, rng).await;
  42}
  43
  44#[derive(Clone, Debug, Serialize, Deserialize)]
  45enum ClientOperation {
  46    AcceptIncomingCall,
  47    RejectIncomingCall,
  48    LeaveCall,
  49    InviteContactToCall {
  50        user_id: UserId,
  51    },
  52    OpenLocalProject {
  53        first_root_name: String,
  54    },
  55    OpenRemoteProject {
  56        host_id: UserId,
  57        first_root_name: String,
  58    },
  59    AddWorktreeToProject {
  60        project_root_name: String,
  61        new_root_path: PathBuf,
  62    },
  63    CloseRemoteProject {
  64        project_root_name: String,
  65    },
  66    OpenBuffer {
  67        project_root_name: String,
  68        is_local: bool,
  69        full_path: PathBuf,
  70    },
  71    SearchProject {
  72        project_root_name: String,
  73        is_local: bool,
  74        query: String,
  75        detach: bool,
  76    },
  77    EditBuffer {
  78        project_root_name: String,
  79        is_local: bool,
  80        full_path: PathBuf,
  81        edits: Vec<(Range<usize>, Arc<str>)>,
  82    },
  83    CloseBuffer {
  84        project_root_name: String,
  85        is_local: bool,
  86        full_path: PathBuf,
  87    },
  88    SaveBuffer {
  89        project_root_name: String,
  90        is_local: bool,
  91        full_path: PathBuf,
  92        detach: bool,
  93    },
  94    RequestLspDataInBuffer {
  95        project_root_name: String,
  96        is_local: bool,
  97        full_path: PathBuf,
  98        offset: usize,
  99        kind: LspRequestKind,
 100        detach: bool,
 101    },
 102    CreateWorktreeEntry {
 103        project_root_name: String,
 104        is_local: bool,
 105        full_path: PathBuf,
 106        is_dir: bool,
 107    },
 108    WriteFsEntry {
 109        path: PathBuf,
 110        is_dir: bool,
 111        content: String,
 112    },
 113    GitOperation {
 114        operation: GitOperation,
 115    },
 116}
 117
 118#[derive(Clone, Debug, Serialize, Deserialize)]
 119enum GitOperation {
 120    WriteGitIndex {
 121        repo_path: PathBuf,
 122        contents: Vec<(PathBuf, String)>,
 123    },
 124    WriteGitBranch {
 125        repo_path: PathBuf,
 126        new_branch: Option<String>,
 127    },
 128    WriteGitStatuses {
 129        repo_path: PathBuf,
 130        statuses: Vec<(PathBuf, FileStatus)>,
 131    },
 132}
 133
 134#[derive(Clone, Debug, Serialize, Deserialize)]
 135enum LspRequestKind {
 136    Rename,
 137    Completion,
 138    CodeAction,
 139    Definition,
 140    Highlights,
 141}
 142
 143struct ProjectCollaborationTest;
 144
 145#[async_trait(?Send)]
 146impl RandomizedTest for ProjectCollaborationTest {
 147    type Operation = ClientOperation;
 148
 149    async fn initialize(server: &mut TestServer, users: &[UserTestPlan]) {
 150        let db = &server.app_state.db;
 151        for (ix, user_a) in users.iter().enumerate() {
 152            for user_b in &users[ix + 1..] {
 153                db.send_contact_request(user_a.user_id, user_b.user_id)
 154                    .await
 155                    .unwrap();
 156                db.respond_to_contact_request(user_b.user_id, user_a.user_id, true)
 157                    .await
 158                    .unwrap();
 159            }
 160        }
 161    }
 162
 163    fn generate_operation(
 164        client: &TestClient,
 165        rng: &mut StdRng,
 166        plan: &mut UserTestPlan,
 167        cx: &TestAppContext,
 168    ) -> ClientOperation {
 169        let call = cx.read(ActiveCall::global);
 170        loop {
 171            match rng.gen_range(0..100_u32) {
 172                // Mutate the call
 173                0..=29 => {
 174                    // Respond to an incoming call
 175                    if call.read_with(cx, |call, _| call.incoming().borrow().is_some()) {
 176                        break if rng.gen_bool(0.7) {
 177                            ClientOperation::AcceptIncomingCall
 178                        } else {
 179                            ClientOperation::RejectIncomingCall
 180                        };
 181                    }
 182
 183                    match rng.gen_range(0..100_u32) {
 184                        // Invite a contact to the current call
 185                        0..=70 => {
 186                            let available_contacts =
 187                                client.user_store().read_with(cx, |user_store, _| {
 188                                    user_store
 189                                        .contacts()
 190                                        .iter()
 191                                        .filter(|contact| contact.online && !contact.busy)
 192                                        .cloned()
 193                                        .collect::<Vec<_>>()
 194                                });
 195                            if !available_contacts.is_empty() {
 196                                let contact = available_contacts.choose(rng).unwrap();
 197                                break ClientOperation::InviteContactToCall {
 198                                    user_id: UserId(contact.user.id as i32),
 199                                };
 200                            }
 201                        }
 202
 203                        // Leave the current call
 204                        71.. => {
 205                            if plan.allow_client_disconnection
 206                                && call.read_with(cx, |call, _| call.room().is_some())
 207                            {
 208                                break ClientOperation::LeaveCall;
 209                            }
 210                        }
 211                    }
 212                }
 213
 214                // Mutate projects
 215                30..=59 => match rng.gen_range(0..100_u32) {
 216                    // Open a new project
 217                    0..=70 => {
 218                        // Open a remote project
 219                        if let Some(room) = call.read_with(cx, |call, _| call.room().cloned()) {
 220                            let existing_dev_server_project_ids = cx.read(|cx| {
 221                                client
 222                                    .dev_server_projects()
 223                                    .iter()
 224                                    .map(|p| p.read(cx).remote_id().unwrap())
 225                                    .collect::<Vec<_>>()
 226                            });
 227                            let new_dev_server_projects = room.read_with(cx, |room, _| {
 228                                room.remote_participants()
 229                                    .values()
 230                                    .flat_map(|participant| {
 231                                        participant.projects.iter().filter_map(|project| {
 232                                            if existing_dev_server_project_ids.contains(&project.id)
 233                                            {
 234                                                None
 235                                            } else {
 236                                                Some((
 237                                                    UserId::from_proto(participant.user.id),
 238                                                    project.worktree_root_names[0].clone(),
 239                                                ))
 240                                            }
 241                                        })
 242                                    })
 243                                    .collect::<Vec<_>>()
 244                            });
 245                            if !new_dev_server_projects.is_empty() {
 246                                let (host_id, first_root_name) =
 247                                    new_dev_server_projects.choose(rng).unwrap().clone();
 248                                break ClientOperation::OpenRemoteProject {
 249                                    host_id,
 250                                    first_root_name,
 251                                };
 252                            }
 253                        }
 254                        // Open a local project
 255                        else {
 256                            let first_root_name = plan.next_root_dir_name();
 257                            break ClientOperation::OpenLocalProject { first_root_name };
 258                        }
 259                    }
 260
 261                    // Close a remote project
 262                    71..=80 => {
 263                        if !client.dev_server_projects().is_empty() {
 264                            let project = client.dev_server_projects().choose(rng).unwrap().clone();
 265                            let first_root_name = root_name_for_project(&project, cx);
 266                            break ClientOperation::CloseRemoteProject {
 267                                project_root_name: first_root_name,
 268                            };
 269                        }
 270                    }
 271
 272                    // Mutate project worktrees
 273                    81.. => match rng.gen_range(0..100_u32) {
 274                        // Add a worktree to a local project
 275                        0..=50 => {
 276                            let Some(project) = client.local_projects().choose(rng).cloned() else {
 277                                continue;
 278                            };
 279                            let project_root_name = root_name_for_project(&project, cx);
 280                            let mut paths = client.fs().paths(false);
 281                            paths.remove(0);
 282                            let new_root_path = if paths.is_empty() || rng.r#gen() {
 283                                Path::new(path!("/")).join(plan.next_root_dir_name())
 284                            } else {
 285                                paths.choose(rng).unwrap().clone()
 286                            };
 287                            break ClientOperation::AddWorktreeToProject {
 288                                project_root_name,
 289                                new_root_path,
 290                            };
 291                        }
 292
 293                        // Add an entry to a worktree
 294                        _ => {
 295                            let Some(project) = choose_random_project(client, rng) else {
 296                                continue;
 297                            };
 298                            let project_root_name = root_name_for_project(&project, cx);
 299                            let is_local = project.read_with(cx, |project, _| project.is_local());
 300                            let worktree = project.read_with(cx, |project, cx| {
 301                                project
 302                                    .worktrees(cx)
 303                                    .filter(|worktree| {
 304                                        let worktree = worktree.read(cx);
 305                                        worktree.is_visible()
 306                                            && worktree.entries(false, 0).any(|e| e.is_file())
 307                                            && worktree.root_entry().map_or(false, |e| e.is_dir())
 308                                    })
 309                                    .choose(rng)
 310                            });
 311                            let Some(worktree) = worktree else { continue };
 312                            let is_dir = rng.r#gen::<bool>();
 313                            let mut full_path =
 314                                worktree.read_with(cx, |w, _| PathBuf::from(w.root_name()));
 315                            full_path.push(gen_file_name(rng));
 316                            if !is_dir {
 317                                full_path.set_extension("rs");
 318                            }
 319                            break ClientOperation::CreateWorktreeEntry {
 320                                project_root_name,
 321                                is_local,
 322                                full_path,
 323                                is_dir,
 324                            };
 325                        }
 326                    },
 327                },
 328
 329                // Query and mutate buffers
 330                60..=90 => {
 331                    let Some(project) = choose_random_project(client, rng) else {
 332                        continue;
 333                    };
 334                    let project_root_name = root_name_for_project(&project, cx);
 335                    let is_local = project.read_with(cx, |project, _| project.is_local());
 336
 337                    match rng.gen_range(0..100_u32) {
 338                        // Manipulate an existing buffer
 339                        0..=70 => {
 340                            let Some(buffer) = client
 341                                .buffers_for_project(&project)
 342                                .iter()
 343                                .choose(rng)
 344                                .cloned()
 345                            else {
 346                                continue;
 347                            };
 348
 349                            let full_path = buffer
 350                                .read_with(cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
 351
 352                            match rng.gen_range(0..100_u32) {
 353                                // Close the buffer
 354                                0..=15 => {
 355                                    break ClientOperation::CloseBuffer {
 356                                        project_root_name,
 357                                        is_local,
 358                                        full_path,
 359                                    };
 360                                }
 361                                // Save the buffer
 362                                16..=29 if buffer.read_with(cx, |b, _| b.is_dirty()) => {
 363                                    let detach = rng.gen_bool(0.3);
 364                                    break ClientOperation::SaveBuffer {
 365                                        project_root_name,
 366                                        is_local,
 367                                        full_path,
 368                                        detach,
 369                                    };
 370                                }
 371                                // Edit the buffer
 372                                30..=69 => {
 373                                    let edits = buffer
 374                                        .read_with(cx, |buffer, _| buffer.get_random_edits(rng, 3));
 375                                    break ClientOperation::EditBuffer {
 376                                        project_root_name,
 377                                        is_local,
 378                                        full_path,
 379                                        edits,
 380                                    };
 381                                }
 382                                // Make an LSP request
 383                                _ => {
 384                                    let offset = buffer.read_with(cx, |buffer, _| {
 385                                        buffer.clip_offset(
 386                                            rng.gen_range(0..=buffer.len()),
 387                                            language::Bias::Left,
 388                                        )
 389                                    });
 390                                    let detach = rng.r#gen();
 391                                    break ClientOperation::RequestLspDataInBuffer {
 392                                        project_root_name,
 393                                        full_path,
 394                                        offset,
 395                                        is_local,
 396                                        kind: match rng.gen_range(0..5_u32) {
 397                                            0 => LspRequestKind::Rename,
 398                                            1 => LspRequestKind::Highlights,
 399                                            2 => LspRequestKind::Definition,
 400                                            3 => LspRequestKind::CodeAction,
 401                                            4.. => LspRequestKind::Completion,
 402                                        },
 403                                        detach,
 404                                    };
 405                                }
 406                            }
 407                        }
 408
 409                        71..=80 => {
 410                            let query = rng.gen_range('a'..='z').to_string();
 411                            let detach = rng.gen_bool(0.3);
 412                            break ClientOperation::SearchProject {
 413                                project_root_name,
 414                                is_local,
 415                                query,
 416                                detach,
 417                            };
 418                        }
 419
 420                        // Open a buffer
 421                        81.. => {
 422                            let worktree = project.read_with(cx, |project, cx| {
 423                                project
 424                                    .worktrees(cx)
 425                                    .filter(|worktree| {
 426                                        let worktree = worktree.read(cx);
 427                                        worktree.is_visible()
 428                                            && worktree.entries(false, 0).any(|e| e.is_file())
 429                                    })
 430                                    .choose(rng)
 431                            });
 432                            let Some(worktree) = worktree else { continue };
 433                            let full_path = worktree.read_with(cx, |worktree, _| {
 434                                let entry = worktree
 435                                    .entries(false, 0)
 436                                    .filter(|e| e.is_file())
 437                                    .choose(rng)
 438                                    .unwrap();
 439                                if entry.path.as_ref() == Path::new("") {
 440                                    Path::new(worktree.root_name()).into()
 441                                } else {
 442                                    Path::new(worktree.root_name()).join(&entry.path)
 443                                }
 444                            });
 445                            break ClientOperation::OpenBuffer {
 446                                project_root_name,
 447                                is_local,
 448                                full_path,
 449                            };
 450                        }
 451                    }
 452                }
 453
 454                // Update a git related action
 455                91..=95 => {
 456                    break ClientOperation::GitOperation {
 457                        operation: generate_git_operation(rng, client),
 458                    };
 459                }
 460
 461                // Create or update a file or directory
 462                96.. => {
 463                    let is_dir = rng.r#gen::<bool>();
 464                    let content;
 465                    let mut path;
 466                    let dir_paths = client.fs().directories(false);
 467
 468                    if is_dir {
 469                        content = String::new();
 470                        path = dir_paths.choose(rng).unwrap().clone();
 471                        path.push(gen_file_name(rng));
 472                    } else {
 473                        content = Alphanumeric.sample_string(rng, 16);
 474
 475                        // Create a new file or overwrite an existing file
 476                        let file_paths = client.fs().files();
 477                        if file_paths.is_empty() || rng.gen_bool(0.5) {
 478                            path = dir_paths.choose(rng).unwrap().clone();
 479                            path.push(gen_file_name(rng));
 480                            path.set_extension("rs");
 481                        } else {
 482                            path = file_paths.choose(rng).unwrap().clone()
 483                        };
 484                    }
 485                    break ClientOperation::WriteFsEntry {
 486                        path,
 487                        is_dir,
 488                        content,
 489                    };
 490                }
 491            }
 492        }
 493    }
 494
 495    async fn apply_operation(
 496        client: &TestClient,
 497        operation: ClientOperation,
 498        cx: &mut TestAppContext,
 499    ) -> Result<(), TestError> {
 500        match operation {
 501            ClientOperation::AcceptIncomingCall => {
 502                let active_call = cx.read(ActiveCall::global);
 503                if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {
 504                    Err(TestError::Inapplicable)?;
 505                }
 506
 507                log::info!("{}: accepting incoming call", client.username);
 508                active_call
 509                    .update(cx, |call, cx| call.accept_incoming(cx))
 510                    .await?;
 511            }
 512
 513            ClientOperation::RejectIncomingCall => {
 514                let active_call = cx.read(ActiveCall::global);
 515                if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {
 516                    Err(TestError::Inapplicable)?;
 517                }
 518
 519                log::info!("{}: declining incoming call", client.username);
 520                active_call.update(cx, |call, cx| call.decline_incoming(cx))?;
 521            }
 522
 523            ClientOperation::LeaveCall => {
 524                let active_call = cx.read(ActiveCall::global);
 525                if active_call.read_with(cx, |call, _| call.room().is_none()) {
 526                    Err(TestError::Inapplicable)?;
 527                }
 528
 529                log::info!("{}: hanging up", client.username);
 530                active_call.update(cx, |call, cx| call.hang_up(cx)).await?;
 531            }
 532
 533            ClientOperation::InviteContactToCall { user_id } => {
 534                let active_call = cx.read(ActiveCall::global);
 535
 536                log::info!("{}: inviting {}", client.username, user_id,);
 537                active_call
 538                    .update(cx, |call, cx| call.invite(user_id.to_proto(), None, cx))
 539                    .await
 540                    .log_err();
 541            }
 542
 543            ClientOperation::OpenLocalProject { first_root_name } => {
 544                log::info!(
 545                    "{}: opening local project at {:?}",
 546                    client.username,
 547                    first_root_name
 548                );
 549
 550                let root_path = Path::new(path!("/")).join(&first_root_name);
 551                client.fs().create_dir(&root_path).await.unwrap();
 552                client
 553                    .fs()
 554                    .create_file(&root_path.join("main.rs"), Default::default())
 555                    .await
 556                    .unwrap();
 557                let project = client.build_local_project(root_path, cx).await.0;
 558                ensure_project_shared(&project, client, cx).await;
 559                client.local_projects_mut().push(project.clone());
 560            }
 561
 562            ClientOperation::AddWorktreeToProject {
 563                project_root_name,
 564                new_root_path,
 565            } => {
 566                let project = project_for_root_name(client, &project_root_name, cx)
 567                    .ok_or(TestError::Inapplicable)?;
 568
 569                log::info!(
 570                    "{}: finding/creating local worktree at {:?} to project with root path {}",
 571                    client.username,
 572                    new_root_path,
 573                    project_root_name
 574                );
 575
 576                ensure_project_shared(&project, client, cx).await;
 577                if !client.fs().paths(false).contains(&new_root_path) {
 578                    client.fs().create_dir(&new_root_path).await.unwrap();
 579                }
 580                project
 581                    .update(cx, |project, cx| {
 582                        project.find_or_create_worktree(&new_root_path, true, cx)
 583                    })
 584                    .await
 585                    .unwrap();
 586            }
 587
 588            ClientOperation::CloseRemoteProject { project_root_name } => {
 589                let project = project_for_root_name(client, &project_root_name, cx)
 590                    .ok_or(TestError::Inapplicable)?;
 591
 592                log::info!(
 593                    "{}: closing remote project with root path {}",
 594                    client.username,
 595                    project_root_name,
 596                );
 597
 598                let ix = client
 599                    .dev_server_projects()
 600                    .iter()
 601                    .position(|p| p == &project)
 602                    .unwrap();
 603                cx.update(|_| {
 604                    client.dev_server_projects_mut().remove(ix);
 605                    client.buffers().retain(|p, _| *p != project);
 606                    drop(project);
 607                });
 608            }
 609
 610            ClientOperation::OpenRemoteProject {
 611                host_id,
 612                first_root_name,
 613            } => {
 614                let active_call = cx.read(ActiveCall::global);
 615                let project = active_call
 616                    .update(cx, |call, cx| {
 617                        let room = call.room().cloned()?;
 618                        let participant = room
 619                            .read(cx)
 620                            .remote_participants()
 621                            .get(&host_id.to_proto())?;
 622                        let project_id = participant
 623                            .projects
 624                            .iter()
 625                            .find(|project| project.worktree_root_names[0] == first_root_name)?
 626                            .id;
 627                        Some(room.update(cx, |room, cx| {
 628                            room.join_project(
 629                                project_id,
 630                                client.language_registry().clone(),
 631                                FakeFs::new(cx.background_executor().clone()),
 632                                cx,
 633                            )
 634                        }))
 635                    })
 636                    .ok_or(TestError::Inapplicable)?;
 637
 638                log::info!(
 639                    "{}: joining remote project of user {}, root name {}",
 640                    client.username,
 641                    host_id,
 642                    first_root_name,
 643                );
 644
 645                let project = project.await?;
 646                client.dev_server_projects_mut().push(project.clone());
 647            }
 648
 649            ClientOperation::CreateWorktreeEntry {
 650                project_root_name,
 651                is_local,
 652                full_path,
 653                is_dir,
 654            } => {
 655                let project = project_for_root_name(client, &project_root_name, cx)
 656                    .ok_or(TestError::Inapplicable)?;
 657                let project_path = project_path_for_full_path(&project, &full_path, cx)
 658                    .ok_or(TestError::Inapplicable)?;
 659
 660                log::info!(
 661                    "{}: creating {} at path {:?} in {} project {}",
 662                    client.username,
 663                    if is_dir { "dir" } else { "file" },
 664                    full_path,
 665                    if is_local { "local" } else { "remote" },
 666                    project_root_name,
 667                );
 668
 669                ensure_project_shared(&project, client, cx).await;
 670                project
 671                    .update(cx, |p, cx| p.create_entry(project_path, is_dir, cx))
 672                    .await?;
 673            }
 674
 675            ClientOperation::OpenBuffer {
 676                project_root_name,
 677                is_local,
 678                full_path,
 679            } => {
 680                let project = project_for_root_name(client, &project_root_name, cx)
 681                    .ok_or(TestError::Inapplicable)?;
 682                let project_path = project_path_for_full_path(&project, &full_path, cx)
 683                    .ok_or(TestError::Inapplicable)?;
 684
 685                log::info!(
 686                    "{}: opening buffer {:?} in {} project {}",
 687                    client.username,
 688                    full_path,
 689                    if is_local { "local" } else { "remote" },
 690                    project_root_name,
 691                );
 692
 693                ensure_project_shared(&project, client, cx).await;
 694                let buffer = project
 695                    .update(cx, |project, cx| project.open_buffer(project_path, cx))
 696                    .await?;
 697                client.buffers_for_project(&project).insert(buffer);
 698            }
 699
 700            ClientOperation::EditBuffer {
 701                project_root_name,
 702                is_local,
 703                full_path,
 704                edits,
 705            } => {
 706                let project = project_for_root_name(client, &project_root_name, cx)
 707                    .ok_or(TestError::Inapplicable)?;
 708                let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 709                    .ok_or(TestError::Inapplicable)?;
 710
 711                log::info!(
 712                    "{}: editing buffer {:?} in {} project {} with {:?}",
 713                    client.username,
 714                    full_path,
 715                    if is_local { "local" } else { "remote" },
 716                    project_root_name,
 717                    edits
 718                );
 719
 720                ensure_project_shared(&project, client, cx).await;
 721                buffer.update(cx, |buffer, cx| {
 722                    let snapshot = buffer.snapshot();
 723                    buffer.edit(
 724                        edits.into_iter().map(|(range, text)| {
 725                            let start = snapshot.clip_offset(range.start, Bias::Left);
 726                            let end = snapshot.clip_offset(range.end, Bias::Right);
 727                            (start..end, text)
 728                        }),
 729                        None,
 730                        cx,
 731                    );
 732                });
 733            }
 734
 735            ClientOperation::CloseBuffer {
 736                project_root_name,
 737                is_local,
 738                full_path,
 739            } => {
 740                let project = project_for_root_name(client, &project_root_name, cx)
 741                    .ok_or(TestError::Inapplicable)?;
 742                let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 743                    .ok_or(TestError::Inapplicable)?;
 744
 745                log::info!(
 746                    "{}: closing buffer {:?} in {} project {}",
 747                    client.username,
 748                    full_path,
 749                    if is_local { "local" } else { "remote" },
 750                    project_root_name
 751                );
 752
 753                ensure_project_shared(&project, client, cx).await;
 754                cx.update(|_| {
 755                    client.buffers_for_project(&project).remove(&buffer);
 756                    drop(buffer);
 757                });
 758            }
 759
 760            ClientOperation::SaveBuffer {
 761                project_root_name,
 762                is_local,
 763                full_path,
 764                detach,
 765            } => {
 766                let project = project_for_root_name(client, &project_root_name, cx)
 767                    .ok_or(TestError::Inapplicable)?;
 768                let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 769                    .ok_or(TestError::Inapplicable)?;
 770
 771                log::info!(
 772                    "{}: saving buffer {:?} in {} project {}, {}",
 773                    client.username,
 774                    full_path,
 775                    if is_local { "local" } else { "remote" },
 776                    project_root_name,
 777                    if detach { "detaching" } else { "awaiting" }
 778                );
 779
 780                ensure_project_shared(&project, client, cx).await;
 781                let requested_version = buffer.read_with(cx, |buffer, _| buffer.version());
 782                let save =
 783                    project.update(cx, |project, cx| project.save_buffer(buffer.clone(), cx));
 784                let save = cx.spawn(|cx| async move {
 785                    save.await
 786                        .map_err(|err| anyhow!("save request failed: {:?}", err))?;
 787                    assert!(
 788                        buffer
 789                            .read_with(&cx, |buffer, _| { buffer.saved_version().to_owned() })
 790                            .expect("App should not be dropped")
 791                            .observed_all(&requested_version)
 792                    );
 793                    anyhow::Ok(())
 794                });
 795                if detach {
 796                    cx.update(|cx| save.detach_and_log_err(cx));
 797                } else {
 798                    save.await?;
 799                }
 800            }
 801
 802            ClientOperation::RequestLspDataInBuffer {
 803                project_root_name,
 804                is_local,
 805                full_path,
 806                offset,
 807                kind,
 808                detach,
 809            } => {
 810                let project = project_for_root_name(client, &project_root_name, cx)
 811                    .ok_or(TestError::Inapplicable)?;
 812                let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 813                    .ok_or(TestError::Inapplicable)?;
 814
 815                log::info!(
 816                    "{}: request LSP {:?} for buffer {:?} in {} project {}, {}",
 817                    client.username,
 818                    kind,
 819                    full_path,
 820                    if is_local { "local" } else { "remote" },
 821                    project_root_name,
 822                    if detach { "detaching" } else { "awaiting" }
 823                );
 824
 825                use futures::{FutureExt as _, TryFutureExt as _};
 826                let offset = buffer.read_with(cx, |b, _| b.clip_offset(offset, Bias::Left));
 827
 828                let process_lsp_request = project.update(cx, |project, cx| match kind {
 829                    LspRequestKind::Rename => project
 830                        .prepare_rename(buffer, offset, cx)
 831                        .map_ok(|_| ())
 832                        .boxed(),
 833                    LspRequestKind::Completion => project
 834                        .completions(&buffer, offset, DEFAULT_COMPLETION_CONTEXT, cx)
 835                        .map_ok(|_| ())
 836                        .boxed(),
 837                    LspRequestKind::CodeAction => project
 838                        .code_actions(&buffer, offset..offset, None, cx)
 839                        .map(|_| Ok(()))
 840                        .boxed(),
 841                    LspRequestKind::Definition => project
 842                        .definition(&buffer, offset, cx)
 843                        .map_ok(|_| ())
 844                        .boxed(),
 845                    LspRequestKind::Highlights => project
 846                        .document_highlights(&buffer, offset, cx)
 847                        .map_ok(|_| ())
 848                        .boxed(),
 849                });
 850                let request = cx.foreground_executor().spawn(process_lsp_request);
 851                if detach {
 852                    request.detach();
 853                } else {
 854                    request.await?;
 855                }
 856            }
 857
 858            ClientOperation::SearchProject {
 859                project_root_name,
 860                is_local,
 861                query,
 862                detach,
 863            } => {
 864                let project = project_for_root_name(client, &project_root_name, cx)
 865                    .ok_or(TestError::Inapplicable)?;
 866
 867                log::info!(
 868                    "{}: search {} project {} for {:?}, {}",
 869                    client.username,
 870                    if is_local { "local" } else { "remote" },
 871                    project_root_name,
 872                    query,
 873                    if detach { "detaching" } else { "awaiting" }
 874                );
 875
 876                let search = project.update(cx, |project, cx| {
 877                    project.search(
 878                        SearchQuery::text(
 879                            query,
 880                            false,
 881                            false,
 882                            false,
 883                            Default::default(),
 884                            Default::default(),
 885                            false,
 886                            None,
 887                        )
 888                        .unwrap(),
 889                        cx,
 890                    )
 891                });
 892                drop(project);
 893                let search = cx.executor().spawn(async move {
 894                    let mut results = HashMap::default();
 895                    while let Ok(result) = search.recv().await {
 896                        if let SearchResult::Buffer { buffer, ranges } = result {
 897                            results.entry(buffer).or_insert(ranges);
 898                        }
 899                    }
 900                    results
 901                });
 902                search.await;
 903            }
 904
 905            ClientOperation::WriteFsEntry {
 906                path,
 907                is_dir,
 908                content,
 909            } => {
 910                if !client
 911                    .fs()
 912                    .directories(false)
 913                    .contains(&path.parent().unwrap().to_owned())
 914                {
 915                    return Err(TestError::Inapplicable);
 916                }
 917
 918                if is_dir {
 919                    log::info!("{}: creating dir at {:?}", client.username, path);
 920                    client.fs().create_dir(&path).await.unwrap();
 921                } else {
 922                    let exists = client.fs().metadata(&path).await?.is_some();
 923                    let verb = if exists { "updating" } else { "creating" };
 924                    log::info!("{}: {} file at {:?}", verb, client.username, path);
 925
 926                    client
 927                        .fs()
 928                        .save(&path, &content.as_str().into(), text::LineEnding::Unix)
 929                        .await
 930                        .unwrap();
 931                }
 932            }
 933
 934            ClientOperation::GitOperation { operation } => match operation {
 935                GitOperation::WriteGitIndex {
 936                    repo_path,
 937                    contents,
 938                } => {
 939                    if !client.fs().directories(false).contains(&repo_path) {
 940                        return Err(TestError::Inapplicable);
 941                    }
 942
 943                    for (path, _) in contents.iter() {
 944                        if !client.fs().files().contains(&repo_path.join(path)) {
 945                            return Err(TestError::Inapplicable);
 946                        }
 947                    }
 948
 949                    log::info!(
 950                        "{}: writing git index for repo {:?}: {:?}",
 951                        client.username,
 952                        repo_path,
 953                        contents
 954                    );
 955
 956                    let dot_git_dir = repo_path.join(".git");
 957                    let contents = contents
 958                        .into_iter()
 959                        .map(|(path, contents)| (path.into(), contents))
 960                        .collect::<Vec<_>>();
 961                    if client.fs().metadata(&dot_git_dir).await?.is_none() {
 962                        client.fs().create_dir(&dot_git_dir).await?;
 963                    }
 964                    client.fs().set_index_for_repo(&dot_git_dir, &contents);
 965                }
 966                GitOperation::WriteGitBranch {
 967                    repo_path,
 968                    new_branch,
 969                } => {
 970                    if !client.fs().directories(false).contains(&repo_path) {
 971                        return Err(TestError::Inapplicable);
 972                    }
 973
 974                    log::info!(
 975                        "{}: writing git branch for repo {:?}: {:?}",
 976                        client.username,
 977                        repo_path,
 978                        new_branch
 979                    );
 980
 981                    let dot_git_dir = repo_path.join(".git");
 982                    if client.fs().metadata(&dot_git_dir).await?.is_none() {
 983                        client.fs().create_dir(&dot_git_dir).await?;
 984                    }
 985                    client
 986                        .fs()
 987                        .set_branch_name(&dot_git_dir, new_branch.clone());
 988                }
 989                GitOperation::WriteGitStatuses {
 990                    repo_path,
 991                    statuses,
 992                } => {
 993                    if !client.fs().directories(false).contains(&repo_path) {
 994                        return Err(TestError::Inapplicable);
 995                    }
 996                    for (path, _) in statuses.iter() {
 997                        if !client.fs().files().contains(&repo_path.join(path)) {
 998                            return Err(TestError::Inapplicable);
 999                        }
1000                    }
1001
1002                    log::info!(
1003                        "{}: writing git statuses for repo {:?}: {:?}",
1004                        client.username,
1005                        repo_path,
1006                        statuses
1007                    );
1008
1009                    let dot_git_dir = repo_path.join(".git");
1010
1011                    let statuses = statuses
1012                        .iter()
1013                        .map(|(path, val)| (path.as_path(), *val))
1014                        .collect::<Vec<_>>();
1015
1016                    if client.fs().metadata(&dot_git_dir).await?.is_none() {
1017                        client.fs().create_dir(&dot_git_dir).await?;
1018                    }
1019
1020                    client
1021                        .fs()
1022                        .set_status_for_repo(&dot_git_dir, statuses.as_slice());
1023                }
1024            },
1025        }
1026        Ok(())
1027    }
1028
1029    async fn on_client_added(client: &Rc<TestClient>, _: &mut TestAppContext) {
1030        client.language_registry().add(Arc::new(Language::new(
1031            LanguageConfig {
1032                name: "Rust".into(),
1033                matcher: LanguageMatcher {
1034                    path_suffixes: vec!["rs".to_string()],
1035                    ..Default::default()
1036                },
1037                ..Default::default()
1038            },
1039            None,
1040        )));
1041        client.language_registry().register_fake_lsp(
1042            "Rust",
1043            FakeLspAdapter {
1044                name: "the-fake-language-server",
1045                capabilities: lsp::LanguageServer::full_capabilities(),
1046                initializer: Some(Box::new({
1047                    let fs = client.app_state.fs.clone();
1048                    move |fake_server: &mut FakeLanguageServer| {
1049                        fake_server.set_request_handler::<lsp::request::Completion, _, _>(
1050                            |_, _| async move {
1051                                Ok(Some(lsp::CompletionResponse::Array(vec![
1052                                    lsp::CompletionItem {
1053                                        text_edit: Some(lsp::CompletionTextEdit::Edit(
1054                                            lsp::TextEdit {
1055                                                range: lsp::Range::new(
1056                                                    lsp::Position::new(0, 0),
1057                                                    lsp::Position::new(0, 0),
1058                                                ),
1059                                                new_text: "the-new-text".to_string(),
1060                                            },
1061                                        )),
1062                                        ..Default::default()
1063                                    },
1064                                ])))
1065                            },
1066                        );
1067
1068                        fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
1069                            |_, _| async move {
1070                                Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
1071                                    lsp::CodeAction {
1072                                        title: "the-code-action".to_string(),
1073                                        ..Default::default()
1074                                    },
1075                                )]))
1076                            },
1077                        );
1078
1079                        fake_server
1080                            .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(
1081                                |params, _| async move {
1082                                    Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
1083                                        params.position,
1084                                        params.position,
1085                                    ))))
1086                                },
1087                            );
1088
1089                        fake_server.set_request_handler::<lsp::request::GotoDefinition, _, _>({
1090                            let fs = fs.clone();
1091                            move |_, cx| {
1092                                let background = cx.background_executor();
1093                                let mut rng = background.rng();
1094                                let count = rng.gen_range::<usize, _>(1..3);
1095                                let files = fs.as_fake().files();
1096                                let files = (0..count)
1097                                    .map(|_| files.choose(&mut rng).unwrap().clone())
1098                                    .collect::<Vec<_>>();
1099                                async move {
1100                                    log::info!("LSP: Returning definitions in files {:?}", &files);
1101                                    Ok(Some(lsp::GotoDefinitionResponse::Array(
1102                                        files
1103                                            .into_iter()
1104                                            .map(|file| lsp::Location {
1105                                                uri: lsp::Url::from_file_path(file).unwrap(),
1106                                                range: Default::default(),
1107                                            })
1108                                            .collect(),
1109                                    )))
1110                                }
1111                            }
1112                        });
1113
1114                        fake_server
1115                            .set_request_handler::<lsp::request::DocumentHighlightRequest, _, _>(
1116                                move |_, cx| {
1117                                    let mut highlights = Vec::new();
1118                                    let background = cx.background_executor();
1119                                    let mut rng = background.rng();
1120
1121                                    let highlight_count = rng.gen_range(1..=5);
1122                                    for _ in 0..highlight_count {
1123                                        let start_row = rng.gen_range(0..100);
1124                                        let start_column = rng.gen_range(0..100);
1125                                        let end_row = rng.gen_range(0..100);
1126                                        let end_column = rng.gen_range(0..100);
1127                                        let start = PointUtf16::new(start_row, start_column);
1128                                        let end = PointUtf16::new(end_row, end_column);
1129                                        let range =
1130                                            if start > end { end..start } else { start..end };
1131                                        highlights.push(lsp::DocumentHighlight {
1132                                            range: range_to_lsp(range.clone()).unwrap(),
1133                                            kind: Some(lsp::DocumentHighlightKind::READ),
1134                                        });
1135                                    }
1136                                    highlights.sort_unstable_by_key(|highlight| {
1137                                        (highlight.range.start, highlight.range.end)
1138                                    });
1139                                    async move { Ok(Some(highlights)) }
1140                                },
1141                            );
1142                    }
1143                })),
1144                ..Default::default()
1145            },
1146        );
1147    }
1148
1149    async fn on_quiesce(_: &mut TestServer, clients: &mut [(Rc<TestClient>, TestAppContext)]) {
1150        for (client, client_cx) in clients.iter() {
1151            for guest_project in client.dev_server_projects().iter() {
1152                guest_project.read_with(client_cx, |guest_project, cx| {
1153                        let host_project = clients.iter().find_map(|(client, cx)| {
1154                            let project = client
1155                                .local_projects()
1156                                .iter()
1157                                .find(|host_project| {
1158                                    host_project.read_with(cx, |host_project, _| {
1159                                        host_project.remote_id() == guest_project.remote_id()
1160                                    })
1161                                })?
1162                                .clone();
1163                            Some((project, cx))
1164                        });
1165
1166                        if !guest_project.is_disconnected(cx) {
1167                            if let Some((host_project, host_cx)) = host_project {
1168                                let host_worktree_snapshots =
1169                                    host_project.read_with(host_cx, |host_project, cx| {
1170                                        host_project
1171                                            .worktrees(cx)
1172                                            .map(|worktree| {
1173                                                let worktree = worktree.read(cx);
1174                                                (worktree.id(), worktree.snapshot())
1175                                            })
1176                                            .collect::<BTreeMap<_, _>>()
1177                                    });
1178                                let guest_worktree_snapshots = guest_project
1179                                    .worktrees(cx)
1180                                    .map(|worktree| {
1181                                        let worktree = worktree.read(cx);
1182                                        (worktree.id(), worktree.snapshot())
1183                                    })
1184                                    .collect::<BTreeMap<_, _>>();
1185                                let host_repository_snapshots = host_project.read_with(host_cx, |host_project, cx| {
1186                                    host_project.git_store().read(cx).repo_snapshots(cx)
1187                                });
1188                                let guest_repository_snapshots = guest_project.git_store().read(cx).repo_snapshots(cx);
1189
1190                                assert_eq!(
1191                                    guest_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
1192                                    host_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
1193                                    "{} has different worktrees than the host for project {:?}",
1194                                    client.username, guest_project.remote_id(),
1195                                );
1196
1197                                assert_eq!(
1198                                    guest_repository_snapshots.values().collect::<Vec<_>>(),
1199                                    host_repository_snapshots.values().collect::<Vec<_>>(),
1200                                    "{} has different repositories than the host for project {:?}",
1201                                    client.username, guest_project.remote_id(),
1202                                );
1203
1204                                for (id, host_snapshot) in &host_worktree_snapshots {
1205                                    let guest_snapshot = &guest_worktree_snapshots[id];
1206                                    assert_eq!(
1207                                        guest_snapshot.root_name(),
1208                                        host_snapshot.root_name(),
1209                                        "{} has different root name than the host for worktree {}, project {:?}",
1210                                        client.username,
1211                                        id,
1212                                        guest_project.remote_id(),
1213                                    );
1214                                    assert_eq!(
1215                                        guest_snapshot.abs_path(),
1216                                        host_snapshot.abs_path(),
1217                                        "{} has different abs path than the host for worktree {}, project: {:?}",
1218                                        client.username,
1219                                        id,
1220                                        guest_project.remote_id(),
1221                                    );
1222                                    assert_eq!(
1223                                        guest_snapshot.entries(false, 0).collect::<Vec<_>>(),
1224                                        host_snapshot.entries(false, 0).collect::<Vec<_>>(),
1225                                        "{} has different snapshot than the host for worktree {:?} ({:?}) and project {:?}",
1226                                        client.username,
1227                                        host_snapshot.abs_path(),
1228                                        id,
1229                                        guest_project.remote_id(),
1230                                    );
1231                                    assert_eq!(guest_snapshot.scan_id(), host_snapshot.scan_id(),
1232                                        "{} has different scan id than the host for worktree {:?} and project {:?}",
1233                                        client.username,
1234                                        host_snapshot.abs_path(),
1235                                        guest_project.remote_id(),
1236                                    );
1237                                }
1238                            }
1239                        }
1240
1241                        for buffer in guest_project.opened_buffers(cx) {
1242                            let buffer = buffer.read(cx);
1243                            assert_eq!(
1244                                buffer.deferred_ops_len(),
1245                                0,
1246                                "{} has deferred operations for buffer {:?} in project {:?}",
1247                                client.username,
1248                                buffer.file().unwrap().full_path(cx),
1249                                guest_project.remote_id(),
1250                            );
1251                        }
1252                    });
1253            }
1254
1255            let buffers = client.buffers().clone();
1256            for (guest_project, guest_buffers) in &buffers {
1257                let project_id = if guest_project.read_with(client_cx, |project, cx| {
1258                    project.is_local() || project.is_disconnected(cx)
1259                }) {
1260                    continue;
1261                } else {
1262                    guest_project
1263                        .read_with(client_cx, |project, _| project.remote_id())
1264                        .unwrap()
1265                };
1266                let guest_user_id = client.user_id().unwrap();
1267
1268                let host_project = clients.iter().find_map(|(client, cx)| {
1269                    let project = client
1270                        .local_projects()
1271                        .iter()
1272                        .find(|host_project| {
1273                            host_project.read_with(cx, |host_project, _| {
1274                                host_project.remote_id() == Some(project_id)
1275                            })
1276                        })?
1277                        .clone();
1278                    Some((client.user_id().unwrap(), project, cx))
1279                });
1280
1281                let (host_user_id, host_project, host_cx) =
1282                    if let Some((host_user_id, host_project, host_cx)) = host_project {
1283                        (host_user_id, host_project, host_cx)
1284                    } else {
1285                        continue;
1286                    };
1287
1288                for guest_buffer in guest_buffers {
1289                    let buffer_id =
1290                        guest_buffer.read_with(client_cx, |buffer, _| buffer.remote_id());
1291                    let host_buffer = host_project.read_with(host_cx, |project, cx| {
1292                        project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| {
1293                            panic!(
1294                                "host does not have buffer for guest:{}, peer:{:?}, id:{}",
1295                                client.username,
1296                                client.peer_id(),
1297                                buffer_id
1298                            )
1299                        })
1300                    });
1301                    let path = host_buffer
1302                        .read_with(host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
1303
1304                    assert_eq!(
1305                        guest_buffer.read_with(client_cx, |buffer, _| buffer.deferred_ops_len()),
1306                        0,
1307                        "{}, buffer {}, path {:?} has deferred operations",
1308                        client.username,
1309                        buffer_id,
1310                        path,
1311                    );
1312                    assert_eq!(
1313                        guest_buffer.read_with(client_cx, |buffer, _| buffer.text()),
1314                        host_buffer.read_with(host_cx, |buffer, _| buffer.text()),
1315                        "{}, buffer {}, path {:?}, differs from the host's buffer",
1316                        client.username,
1317                        buffer_id,
1318                        path
1319                    );
1320
1321                    let host_file = host_buffer.read_with(host_cx, |b, _| b.file().cloned());
1322                    let guest_file = guest_buffer.read_with(client_cx, |b, _| b.file().cloned());
1323                    match (host_file, guest_file) {
1324                        (Some(host_file), Some(guest_file)) => {
1325                            assert_eq!(guest_file.path(), host_file.path());
1326                            assert_eq!(
1327                                guest_file.disk_state(),
1328                                host_file.disk_state(),
1329                                "guest {} disk_state does not match host {} for path {:?} in project {}",
1330                                guest_user_id,
1331                                host_user_id,
1332                                guest_file.path(),
1333                                project_id,
1334                            );
1335                        }
1336                        (None, None) => {}
1337                        (None, _) => panic!("host's file is None, guest's isn't"),
1338                        (_, None) => panic!("guest's file is None, hosts's isn't"),
1339                    }
1340
1341                    let host_diff_base = host_project.read_with(host_cx, |project, cx| {
1342                        project
1343                            .git_store()
1344                            .read(cx)
1345                            .get_unstaged_diff(host_buffer.read(cx).remote_id(), cx)
1346                            .unwrap()
1347                            .read(cx)
1348                            .base_text_string()
1349                    });
1350                    let guest_diff_base = guest_project.read_with(client_cx, |project, cx| {
1351                        project
1352                            .git_store()
1353                            .read(cx)
1354                            .get_unstaged_diff(guest_buffer.read(cx).remote_id(), cx)
1355                            .unwrap()
1356                            .read(cx)
1357                            .base_text_string()
1358                    });
1359                    assert_eq!(
1360                        guest_diff_base, host_diff_base,
1361                        "guest {} diff base does not match host's for path {path:?} in project {project_id}",
1362                        client.username
1363                    );
1364
1365                    let host_saved_version =
1366                        host_buffer.read_with(host_cx, |b, _| b.saved_version().clone());
1367                    let guest_saved_version =
1368                        guest_buffer.read_with(client_cx, |b, _| b.saved_version().clone());
1369                    assert_eq!(
1370                        guest_saved_version, host_saved_version,
1371                        "guest {} saved version does not match host's for path {path:?} in project {project_id}",
1372                        client.username
1373                    );
1374
1375                    let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
1376                    let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
1377                    assert_eq!(
1378                        guest_is_dirty, host_is_dirty,
1379                        "guest {} dirty state does not match host's for path {path:?} in project {project_id}",
1380                        client.username
1381                    );
1382
1383                    let host_saved_mtime = host_buffer.read_with(host_cx, |b, _| b.saved_mtime());
1384                    let guest_saved_mtime =
1385                        guest_buffer.read_with(client_cx, |b, _| b.saved_mtime());
1386                    assert_eq!(
1387                        guest_saved_mtime, host_saved_mtime,
1388                        "guest {} saved mtime does not match host's for path {path:?} in project {project_id}",
1389                        client.username
1390                    );
1391
1392                    let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
1393                    let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
1394                    assert_eq!(
1395                        guest_is_dirty, host_is_dirty,
1396                        "guest {} dirty status does not match host's for path {path:?} in project {project_id}",
1397                        client.username
1398                    );
1399
1400                    let host_has_conflict = host_buffer.read_with(host_cx, |b, _| b.has_conflict());
1401                    let guest_has_conflict =
1402                        guest_buffer.read_with(client_cx, |b, _| b.has_conflict());
1403                    assert_eq!(
1404                        guest_has_conflict, host_has_conflict,
1405                        "guest {} conflict status does not match host's for path {path:?} in project {project_id}",
1406                        client.username
1407                    );
1408                }
1409            }
1410        }
1411    }
1412}
1413
1414fn generate_git_operation(rng: &mut StdRng, client: &TestClient) -> GitOperation {
1415    fn generate_file_paths(
1416        repo_path: &Path,
1417        rng: &mut StdRng,
1418        client: &TestClient,
1419    ) -> Vec<PathBuf> {
1420        let mut paths = client
1421            .fs()
1422            .files()
1423            .into_iter()
1424            .filter(|path| path.starts_with(repo_path))
1425            .collect::<Vec<_>>();
1426
1427        let count = rng.gen_range(0..=paths.len());
1428        paths.shuffle(rng);
1429        paths.truncate(count);
1430
1431        paths
1432            .iter()
1433            .map(|path| path.strip_prefix(repo_path).unwrap().to_path_buf())
1434            .collect::<Vec<_>>()
1435    }
1436
1437    let repo_path = client.fs().directories(false).choose(rng).unwrap().clone();
1438
1439    match rng.gen_range(0..100_u32) {
1440        0..=25 => {
1441            let file_paths = generate_file_paths(&repo_path, rng, client);
1442
1443            let contents = file_paths
1444                .into_iter()
1445                .map(|path| (path, Alphanumeric.sample_string(rng, 16)))
1446                .collect();
1447
1448            GitOperation::WriteGitIndex {
1449                repo_path,
1450                contents,
1451            }
1452        }
1453        26..=63 => {
1454            let new_branch = (rng.gen_range(0..10) > 3).then(|| Alphanumeric.sample_string(rng, 8));
1455
1456            GitOperation::WriteGitBranch {
1457                repo_path,
1458                new_branch,
1459            }
1460        }
1461        64..=100 => {
1462            let file_paths = generate_file_paths(&repo_path, rng, client);
1463            let statuses = file_paths
1464                .into_iter()
1465                .map(|path| (path, gen_status(rng)))
1466                .collect::<Vec<_>>();
1467            GitOperation::WriteGitStatuses {
1468                repo_path,
1469                statuses,
1470            }
1471        }
1472        _ => unreachable!(),
1473    }
1474}
1475
1476fn buffer_for_full_path(
1477    client: &TestClient,
1478    project: &Entity<Project>,
1479    full_path: &PathBuf,
1480    cx: &TestAppContext,
1481) -> Option<Entity<language::Buffer>> {
1482    client
1483        .buffers_for_project(project)
1484        .iter()
1485        .find(|buffer| {
1486            buffer.read_with(cx, |buffer, cx| {
1487                buffer.file().unwrap().full_path(cx) == *full_path
1488            })
1489        })
1490        .cloned()
1491}
1492
1493fn project_for_root_name(
1494    client: &TestClient,
1495    root_name: &str,
1496    cx: &TestAppContext,
1497) -> Option<Entity<Project>> {
1498    if let Some(ix) = project_ix_for_root_name(client.local_projects().deref(), root_name, cx) {
1499        return Some(client.local_projects()[ix].clone());
1500    }
1501    if let Some(ix) = project_ix_for_root_name(client.dev_server_projects().deref(), root_name, cx)
1502    {
1503        return Some(client.dev_server_projects()[ix].clone());
1504    }
1505    None
1506}
1507
1508fn project_ix_for_root_name(
1509    projects: &[Entity<Project>],
1510    root_name: &str,
1511    cx: &TestAppContext,
1512) -> Option<usize> {
1513    projects.iter().position(|project| {
1514        project.read_with(cx, |project, cx| {
1515            let worktree = project.visible_worktrees(cx).next().unwrap();
1516            worktree.read(cx).root_name() == root_name
1517        })
1518    })
1519}
1520
1521fn root_name_for_project(project: &Entity<Project>, cx: &TestAppContext) -> String {
1522    project.read_with(cx, |project, cx| {
1523        project
1524            .visible_worktrees(cx)
1525            .next()
1526            .unwrap()
1527            .read(cx)
1528            .root_name()
1529            .to_string()
1530    })
1531}
1532
1533fn project_path_for_full_path(
1534    project: &Entity<Project>,
1535    full_path: &Path,
1536    cx: &TestAppContext,
1537) -> Option<ProjectPath> {
1538    let mut components = full_path.components();
1539    let root_name = components.next().unwrap().as_os_str().to_str().unwrap();
1540    let path = components.as_path().into();
1541    let worktree_id = project.read_with(cx, |project, cx| {
1542        project.worktrees(cx).find_map(|worktree| {
1543            let worktree = worktree.read(cx);
1544            if worktree.root_name() == root_name {
1545                Some(worktree.id())
1546            } else {
1547                None
1548            }
1549        })
1550    })?;
1551    Some(ProjectPath { worktree_id, path })
1552}
1553
1554async fn ensure_project_shared(
1555    project: &Entity<Project>,
1556    client: &TestClient,
1557    cx: &mut TestAppContext,
1558) {
1559    let first_root_name = root_name_for_project(project, cx);
1560    let active_call = cx.read(ActiveCall::global);
1561    if active_call.read_with(cx, |call, _| call.room().is_some())
1562        && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())
1563    {
1564        match active_call
1565            .update(cx, |call, cx| call.share_project(project.clone(), cx))
1566            .await
1567        {
1568            Ok(project_id) => {
1569                log::info!(
1570                    "{}: shared project {} with id {}",
1571                    client.username,
1572                    first_root_name,
1573                    project_id
1574                );
1575            }
1576            Err(error) => {
1577                log::error!(
1578                    "{}: error sharing project {}: {:?}",
1579                    client.username,
1580                    first_root_name,
1581                    error
1582                );
1583            }
1584        }
1585    }
1586}
1587
1588fn choose_random_project(client: &TestClient, rng: &mut StdRng) -> Option<Entity<Project>> {
1589    client
1590        .local_projects()
1591        .deref()
1592        .iter()
1593        .chain(client.dev_server_projects().iter())
1594        .choose(rng)
1595        .cloned()
1596}
1597
1598fn gen_file_name(rng: &mut StdRng) -> String {
1599    let mut name = String::new();
1600    for _ in 0..10 {
1601        let letter = rng.gen_range('a'..='z');
1602        name.push(letter);
1603    }
1604    name
1605}
1606
1607fn gen_status(rng: &mut StdRng) -> FileStatus {
1608    fn gen_tracked_status(rng: &mut StdRng) -> TrackedStatus {
1609        match rng.gen_range(0..3) {
1610            0 => TrackedStatus {
1611                index_status: StatusCode::Unmodified,
1612                worktree_status: StatusCode::Unmodified,
1613            },
1614            1 => TrackedStatus {
1615                index_status: StatusCode::Modified,
1616                worktree_status: StatusCode::Modified,
1617            },
1618            2 => TrackedStatus {
1619                index_status: StatusCode::Added,
1620                worktree_status: StatusCode::Modified,
1621            },
1622            3 => TrackedStatus {
1623                index_status: StatusCode::Added,
1624                worktree_status: StatusCode::Unmodified,
1625            },
1626            _ => unreachable!(),
1627        }
1628    }
1629
1630    fn gen_unmerged_status_code(rng: &mut StdRng) -> UnmergedStatusCode {
1631        match rng.gen_range(0..3) {
1632            0 => UnmergedStatusCode::Updated,
1633            1 => UnmergedStatusCode::Added,
1634            2 => UnmergedStatusCode::Deleted,
1635            _ => unreachable!(),
1636        }
1637    }
1638
1639    match rng.gen_range(0..2) {
1640        0 => FileStatus::Unmerged(UnmergedStatus {
1641            first_head: gen_unmerged_status_code(rng),
1642            second_head: gen_unmerged_status_code(rng),
1643        }),
1644        1 => FileStatus::Tracked(gen_tracked_status(rng)),
1645        _ => unreachable!(),
1646    }
1647}