random_project_collaboration_tests.rs

   1use super::{RandomizedTest, TestClient, TestError, TestServer, UserTestPlan};
   2use crate::{db::UserId, tests::run_randomized_test};
   3use anyhow::{anyhow, Result};
   4use async_trait::async_trait;
   5use call::ActiveCall;
   6use collections::{BTreeMap, HashMap};
   7use editor::Bias;
   8use fs::{FakeFs, Fs as _};
   9use futures::StreamExt;
  10use git::repository::GitFileStatus;
  11use gpui::{BackgroundExecutor, Model, TestAppContext};
  12use language::{
  13    range_to_lsp, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, PointUtf16,
  14};
  15use lsp::FakeLanguageServer;
  16use pretty_assertions::assert_eq;
  17use project::{search::SearchQuery, Project, ProjectPath, SearchResult};
  18use rand::{
  19    distributions::{Alphanumeric, DistString},
  20    prelude::*,
  21};
  22use serde::{Deserialize, Serialize};
  23use std::{
  24    ops::{Deref, Range},
  25    path::{Path, PathBuf},
  26    rc::Rc,
  27    sync::Arc,
  28};
  29use util::ResultExt;
  30
  31#[gpui::test(
  32    iterations = 100,
  33    on_failure = "crate::tests::save_randomized_test_plan"
  34)]
  35async fn test_random_project_collaboration(
  36    cx: &mut TestAppContext,
  37    executor: BackgroundExecutor,
  38    rng: StdRng,
  39) {
  40    run_randomized_test::<ProjectCollaborationTest>(cx, executor, rng).await;
  41}
  42
  43#[derive(Clone, Debug, Serialize, Deserialize)]
  44enum ClientOperation {
  45    AcceptIncomingCall,
  46    RejectIncomingCall,
  47    LeaveCall,
  48    InviteContactToCall {
  49        user_id: UserId,
  50    },
  51    OpenLocalProject {
  52        first_root_name: String,
  53    },
  54    OpenRemoteProject {
  55        host_id: UserId,
  56        first_root_name: String,
  57    },
  58    AddWorktreeToProject {
  59        project_root_name: String,
  60        new_root_path: PathBuf,
  61    },
  62    CloseRemoteProject {
  63        project_root_name: String,
  64    },
  65    OpenBuffer {
  66        project_root_name: String,
  67        is_local: bool,
  68        full_path: PathBuf,
  69    },
  70    SearchProject {
  71        project_root_name: String,
  72        is_local: bool,
  73        query: String,
  74        detach: bool,
  75    },
  76    EditBuffer {
  77        project_root_name: String,
  78        is_local: bool,
  79        full_path: PathBuf,
  80        edits: Vec<(Range<usize>, Arc<str>)>,
  81    },
  82    CloseBuffer {
  83        project_root_name: String,
  84        is_local: bool,
  85        full_path: PathBuf,
  86    },
  87    SaveBuffer {
  88        project_root_name: String,
  89        is_local: bool,
  90        full_path: PathBuf,
  91        detach: bool,
  92    },
  93    RequestLspDataInBuffer {
  94        project_root_name: String,
  95        is_local: bool,
  96        full_path: PathBuf,
  97        offset: usize,
  98        kind: LspRequestKind,
  99        detach: bool,
 100    },
 101    CreateWorktreeEntry {
 102        project_root_name: String,
 103        is_local: bool,
 104        full_path: PathBuf,
 105        is_dir: bool,
 106    },
 107    WriteFsEntry {
 108        path: PathBuf,
 109        is_dir: bool,
 110        content: String,
 111    },
 112    GitOperation {
 113        operation: GitOperation,
 114    },
 115}
 116
 117#[derive(Clone, Debug, Serialize, Deserialize)]
 118enum GitOperation {
 119    WriteGitIndex {
 120        repo_path: PathBuf,
 121        contents: Vec<(PathBuf, String)>,
 122    },
 123    WriteGitBranch {
 124        repo_path: PathBuf,
 125        new_branch: Option<String>,
 126    },
 127    WriteGitStatuses {
 128        repo_path: PathBuf,
 129        statuses: Vec<(PathBuf, GitFileStatus)>,
 130        git_operation: bool,
 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.gen() {
 283                                Path::new("/").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()
 303                                    .filter(|worktree| {
 304                                        let worktree = worktree.read(cx);
 305                                        worktree.is_visible()
 306                                            && worktree.entries(false).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.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.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()
 425                                    .filter(|worktree| {
 426                                        let worktree = worktree.read(cx);
 427                                        worktree.is_visible()
 428                                            && worktree.entries(false).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)
 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.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("/").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_local_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!(buffer
 788                        .read_with(&cx, |buffer, _| { buffer.saved_version().to_owned() })
 789                        .expect("App should not be dropped")
 790                        .observed_all(&requested_version));
 791                    anyhow::Ok(())
 792                });
 793                if detach {
 794                    cx.update(|cx| save.detach_and_log_err(cx));
 795                } else {
 796                    save.await?;
 797                }
 798            }
 799
 800            ClientOperation::RequestLspDataInBuffer {
 801                project_root_name,
 802                is_local,
 803                full_path,
 804                offset,
 805                kind,
 806                detach,
 807            } => {
 808                let project = project_for_root_name(client, &project_root_name, cx)
 809                    .ok_or(TestError::Inapplicable)?;
 810                let buffer = buffer_for_full_path(client, &project, &full_path, cx)
 811                    .ok_or(TestError::Inapplicable)?;
 812
 813                log::info!(
 814                    "{}: request LSP {:?} for buffer {:?} in {} project {}, {}",
 815                    client.username,
 816                    kind,
 817                    full_path,
 818                    if is_local { "local" } else { "remote" },
 819                    project_root_name,
 820                    if detach { "detaching" } else { "awaiting" }
 821                );
 822
 823                use futures::{FutureExt as _, TryFutureExt as _};
 824                let offset = buffer.read_with(cx, |b, _| b.clip_offset(offset, Bias::Left));
 825
 826                let process_lsp_request = project.update(cx, |project, cx| match kind {
 827                    LspRequestKind::Rename => project
 828                        .prepare_rename(buffer, offset, cx)
 829                        .map_ok(|_| ())
 830                        .boxed(),
 831                    LspRequestKind::Completion => project
 832                        .completions(&buffer, offset, cx)
 833                        .map_ok(|_| ())
 834                        .boxed(),
 835                    LspRequestKind::CodeAction => project
 836                        .code_actions(&buffer, offset..offset, cx)
 837                        .map(|_| Ok(()))
 838                        .boxed(),
 839                    LspRequestKind::Definition => project
 840                        .definition(&buffer, offset, cx)
 841                        .map_ok(|_| ())
 842                        .boxed(),
 843                    LspRequestKind::Highlights => project
 844                        .document_highlights(&buffer, offset, cx)
 845                        .map_ok(|_| ())
 846                        .boxed(),
 847                });
 848                let request = cx.foreground_executor().spawn(process_lsp_request);
 849                if detach {
 850                    request.detach();
 851                } else {
 852                    request.await?;
 853                }
 854            }
 855
 856            ClientOperation::SearchProject {
 857                project_root_name,
 858                is_local,
 859                query,
 860                detach,
 861            } => {
 862                let project = project_for_root_name(client, &project_root_name, cx)
 863                    .ok_or(TestError::Inapplicable)?;
 864
 865                log::info!(
 866                    "{}: search {} project {} for {:?}, {}",
 867                    client.username,
 868                    if is_local { "local" } else { "remote" },
 869                    project_root_name,
 870                    query,
 871                    if detach { "detaching" } else { "awaiting" }
 872                );
 873
 874                let mut search = project.update(cx, |project, cx| {
 875                    project.search(
 876                        SearchQuery::text(query, false, false, false, Vec::new(), Vec::new())
 877                            .unwrap(),
 878                        cx,
 879                    )
 880                });
 881                drop(project);
 882                let search = cx.executor().spawn(async move {
 883                    let mut results = HashMap::default();
 884                    while let Some(result) = search.next().await {
 885                        if let SearchResult::Buffer { buffer, ranges } = result {
 886                            results.entry(buffer).or_insert(ranges);
 887                        }
 888                    }
 889                    results
 890                });
 891                search.await;
 892            }
 893
 894            ClientOperation::WriteFsEntry {
 895                path,
 896                is_dir,
 897                content,
 898            } => {
 899                if !client
 900                    .fs()
 901                    .directories(false)
 902                    .contains(&path.parent().unwrap().to_owned())
 903                {
 904                    return Err(TestError::Inapplicable);
 905                }
 906
 907                if is_dir {
 908                    log::info!("{}: creating dir at {:?}", client.username, path);
 909                    client.fs().create_dir(&path).await.unwrap();
 910                } else {
 911                    let exists = client.fs().metadata(&path).await?.is_some();
 912                    let verb = if exists { "updating" } else { "creating" };
 913                    log::info!("{}: {} file at {:?}", verb, client.username, path);
 914
 915                    client
 916                        .fs()
 917                        .save(&path, &content.as_str().into(), text::LineEnding::Unix)
 918                        .await
 919                        .unwrap();
 920                }
 921            }
 922
 923            ClientOperation::GitOperation { operation } => match operation {
 924                GitOperation::WriteGitIndex {
 925                    repo_path,
 926                    contents,
 927                } => {
 928                    if !client.fs().directories(false).contains(&repo_path) {
 929                        return Err(TestError::Inapplicable);
 930                    }
 931
 932                    for (path, _) in contents.iter() {
 933                        if !client.fs().files().contains(&repo_path.join(path)) {
 934                            return Err(TestError::Inapplicable);
 935                        }
 936                    }
 937
 938                    log::info!(
 939                        "{}: writing git index for repo {:?}: {:?}",
 940                        client.username,
 941                        repo_path,
 942                        contents
 943                    );
 944
 945                    let dot_git_dir = repo_path.join(".git");
 946                    let contents = contents
 947                        .iter()
 948                        .map(|(path, contents)| (path.as_path(), contents.clone()))
 949                        .collect::<Vec<_>>();
 950                    if client.fs().metadata(&dot_git_dir).await?.is_none() {
 951                        client.fs().create_dir(&dot_git_dir).await?;
 952                    }
 953                    client.fs().set_index_for_repo(&dot_git_dir, &contents);
 954                }
 955                GitOperation::WriteGitBranch {
 956                    repo_path,
 957                    new_branch,
 958                } => {
 959                    if !client.fs().directories(false).contains(&repo_path) {
 960                        return Err(TestError::Inapplicable);
 961                    }
 962
 963                    log::info!(
 964                        "{}: writing git branch for repo {:?}: {:?}",
 965                        client.username,
 966                        repo_path,
 967                        new_branch
 968                    );
 969
 970                    let dot_git_dir = repo_path.join(".git");
 971                    if client.fs().metadata(&dot_git_dir).await?.is_none() {
 972                        client.fs().create_dir(&dot_git_dir).await?;
 973                    }
 974                    client
 975                        .fs()
 976                        .set_branch_name(&dot_git_dir, new_branch.clone());
 977                }
 978                GitOperation::WriteGitStatuses {
 979                    repo_path,
 980                    statuses,
 981                    git_operation,
 982                } => {
 983                    if !client.fs().directories(false).contains(&repo_path) {
 984                        return Err(TestError::Inapplicable);
 985                    }
 986                    for (path, _) in statuses.iter() {
 987                        if !client.fs().files().contains(&repo_path.join(path)) {
 988                            return Err(TestError::Inapplicable);
 989                        }
 990                    }
 991
 992                    log::info!(
 993                        "{}: writing git statuses for repo {:?}: {:?}",
 994                        client.username,
 995                        repo_path,
 996                        statuses
 997                    );
 998
 999                    let dot_git_dir = repo_path.join(".git");
1000
1001                    let statuses = statuses
1002                        .iter()
1003                        .map(|(path, val)| (path.as_path(), *val))
1004                        .collect::<Vec<_>>();
1005
1006                    if client.fs().metadata(&dot_git_dir).await?.is_none() {
1007                        client.fs().create_dir(&dot_git_dir).await?;
1008                    }
1009
1010                    if git_operation {
1011                        client.fs().set_status_for_repo_via_git_operation(
1012                            &dot_git_dir,
1013                            statuses.as_slice(),
1014                        );
1015                    } else {
1016                        client.fs().set_status_for_repo_via_working_copy_change(
1017                            &dot_git_dir,
1018                            statuses.as_slice(),
1019                        );
1020                    }
1021                }
1022            },
1023        }
1024        Ok(())
1025    }
1026
1027    async fn on_client_added(client: &Rc<TestClient>, _: &mut TestAppContext) {
1028        client.language_registry().add(Arc::new(Language::new(
1029            LanguageConfig {
1030                name: "Rust".into(),
1031                matcher: LanguageMatcher {
1032                    path_suffixes: vec!["rs".to_string()],
1033                    ..Default::default()
1034                },
1035                ..Default::default()
1036            },
1037            None,
1038        )));
1039        client.language_registry().register_fake_lsp_adapter(
1040            "Rust",
1041            FakeLspAdapter {
1042                name: "the-fake-language-server",
1043                capabilities: lsp::LanguageServer::full_capabilities(),
1044                initializer: Some(Box::new({
1045                    let fs = client.app_state.fs.clone();
1046                    move |fake_server: &mut FakeLanguageServer| {
1047                        fake_server.handle_request::<lsp::request::Completion, _, _>(
1048                            |_, _| async move {
1049                                Ok(Some(lsp::CompletionResponse::Array(vec![
1050                                    lsp::CompletionItem {
1051                                        text_edit: Some(lsp::CompletionTextEdit::Edit(
1052                                            lsp::TextEdit {
1053                                                range: lsp::Range::new(
1054                                                    lsp::Position::new(0, 0),
1055                                                    lsp::Position::new(0, 0),
1056                                                ),
1057                                                new_text: "the-new-text".to_string(),
1058                                            },
1059                                        )),
1060                                        ..Default::default()
1061                                    },
1062                                ])))
1063                            },
1064                        );
1065
1066                        fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
1067                            |_, _| async move {
1068                                Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
1069                                    lsp::CodeAction {
1070                                        title: "the-code-action".to_string(),
1071                                        ..Default::default()
1072                                    },
1073                                )]))
1074                            },
1075                        );
1076
1077                        fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
1078                            |params, _| async move {
1079                                Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
1080                                    params.position,
1081                                    params.position,
1082                                ))))
1083                            },
1084                        );
1085
1086                        fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
1087                            let fs = fs.clone();
1088                            move |_, cx| {
1089                                let background = cx.background_executor();
1090                                let mut rng = background.rng();
1091                                let count = rng.gen_range::<usize, _>(1..3);
1092                                let files = fs.as_fake().files();
1093                                let files = (0..count)
1094                                    .map(|_| files.choose(&mut rng).unwrap().clone())
1095                                    .collect::<Vec<_>>();
1096                                async move {
1097                                    log::info!("LSP: Returning definitions in files {:?}", &files);
1098                                    Ok(Some(lsp::GotoDefinitionResponse::Array(
1099                                        files
1100                                            .into_iter()
1101                                            .map(|file| lsp::Location {
1102                                                uri: lsp::Url::from_file_path(file).unwrap(),
1103                                                range: Default::default(),
1104                                            })
1105                                            .collect(),
1106                                    )))
1107                                }
1108                            }
1109                        });
1110
1111                        fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
1112                            move |_, cx| {
1113                                let mut highlights = Vec::new();
1114                                let background = cx.background_executor();
1115                                let mut rng = background.rng();
1116
1117                                let highlight_count = rng.gen_range(1..=5);
1118                                for _ in 0..highlight_count {
1119                                    let start_row = rng.gen_range(0..100);
1120                                    let start_column = rng.gen_range(0..100);
1121                                    let end_row = rng.gen_range(0..100);
1122                                    let end_column = rng.gen_range(0..100);
1123                                    let start = PointUtf16::new(start_row, start_column);
1124                                    let end = PointUtf16::new(end_row, end_column);
1125                                    let range = if start > end { end..start } else { start..end };
1126                                    highlights.push(lsp::DocumentHighlight {
1127                                        range: range_to_lsp(range.clone()),
1128                                        kind: Some(lsp::DocumentHighlightKind::READ),
1129                                    });
1130                                }
1131                                highlights.sort_unstable_by_key(|highlight| {
1132                                    (highlight.range.start, highlight.range.end)
1133                                });
1134                                async move { Ok(Some(highlights)) }
1135                            },
1136                        );
1137                    }
1138                })),
1139                ..Default::default()
1140            },
1141        );
1142    }
1143
1144    async fn on_quiesce(_: &mut TestServer, clients: &mut [(Rc<TestClient>, TestAppContext)]) {
1145        for (client, client_cx) in clients.iter() {
1146            for guest_project in client.dev_server_projects().iter() {
1147                guest_project.read_with(client_cx, |guest_project, cx| {
1148                        let host_project = clients.iter().find_map(|(client, cx)| {
1149                            let project = client
1150                                .local_projects()
1151                                .iter()
1152                                .find(|host_project| {
1153                                    host_project.read_with(cx, |host_project, _| {
1154                                        host_project.remote_id() == guest_project.remote_id()
1155                                    })
1156                                })?
1157                                .clone();
1158                            Some((project, cx))
1159                        });
1160
1161                        if !guest_project.is_disconnected() {
1162                            if let Some((host_project, host_cx)) = host_project {
1163                                let host_worktree_snapshots =
1164                                    host_project.read_with(host_cx, |host_project, cx| {
1165                                        host_project
1166                                            .worktrees()
1167                                            .map(|worktree| {
1168                                                let worktree = worktree.read(cx);
1169                                                (worktree.id(), worktree.snapshot())
1170                                            })
1171                                            .collect::<BTreeMap<_, _>>()
1172                                    });
1173                                let guest_worktree_snapshots = guest_project
1174                                    .worktrees()
1175                                    .map(|worktree| {
1176                                        let worktree = worktree.read(cx);
1177                                        (worktree.id(), worktree.snapshot())
1178                                    })
1179                                    .collect::<BTreeMap<_, _>>();
1180
1181                                assert_eq!(
1182                                    guest_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
1183                                    host_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
1184                                    "{} has different worktrees than the host for project {:?}",
1185                                    client.username, guest_project.remote_id(),
1186                                );
1187
1188                                for (id, host_snapshot) in &host_worktree_snapshots {
1189                                    let guest_snapshot = &guest_worktree_snapshots[id];
1190                                    assert_eq!(
1191                                        guest_snapshot.root_name(),
1192                                        host_snapshot.root_name(),
1193                                        "{} has different root name than the host for worktree {}, project {:?}",
1194                                        client.username,
1195                                        id,
1196                                        guest_project.remote_id(),
1197                                    );
1198                                    assert_eq!(
1199                                        guest_snapshot.abs_path(),
1200                                        host_snapshot.abs_path(),
1201                                        "{} has different abs path than the host for worktree {}, project: {:?}",
1202                                        client.username,
1203                                        id,
1204                                        guest_project.remote_id(),
1205                                    );
1206                                    assert_eq!(
1207                                        guest_snapshot.entries(false).collect::<Vec<_>>(),
1208                                        host_snapshot.entries(false).collect::<Vec<_>>(),
1209                                        "{} has different snapshot than the host for worktree {:?} ({:?}) and project {:?}",
1210                                        client.username,
1211                                        host_snapshot.abs_path(),
1212                                        id,
1213                                        guest_project.remote_id(),
1214                                    );
1215                                    assert_eq!(guest_snapshot.repositories().collect::<Vec<_>>(), host_snapshot.repositories().collect::<Vec<_>>(),
1216                                        "{} has different repositories than the host for worktree {:?} and project {:?}",
1217                                        client.username,
1218                                        host_snapshot.abs_path(),
1219                                        guest_project.remote_id(),
1220                                    );
1221                                    assert_eq!(guest_snapshot.scan_id(), host_snapshot.scan_id(),
1222                                        "{} has different scan id than the host for worktree {:?} and project {:?}",
1223                                        client.username,
1224                                        host_snapshot.abs_path(),
1225                                        guest_project.remote_id(),
1226                                    );
1227                                }
1228                            }
1229                        }
1230
1231                        for buffer in guest_project.opened_buffers() {
1232                            let buffer = buffer.read(cx);
1233                            assert_eq!(
1234                                buffer.deferred_ops_len(),
1235                                0,
1236                                "{} has deferred operations for buffer {:?} in project {:?}",
1237                                client.username,
1238                                buffer.file().unwrap().full_path(cx),
1239                                guest_project.remote_id(),
1240                            );
1241                        }
1242                    });
1243            }
1244
1245            let buffers = client.buffers().clone();
1246            for (guest_project, guest_buffers) in &buffers {
1247                let project_id = if guest_project.read_with(client_cx, |project, _| {
1248                    project.is_local() || project.is_disconnected()
1249                }) {
1250                    continue;
1251                } else {
1252                    guest_project
1253                        .read_with(client_cx, |project, _| project.remote_id())
1254                        .unwrap()
1255                };
1256                let guest_user_id = client.user_id().unwrap();
1257
1258                let host_project = clients.iter().find_map(|(client, cx)| {
1259                    let project = client
1260                        .local_projects()
1261                        .iter()
1262                        .find(|host_project| {
1263                            host_project.read_with(cx, |host_project, _| {
1264                                host_project.remote_id() == Some(project_id)
1265                            })
1266                        })?
1267                        .clone();
1268                    Some((client.user_id().unwrap(), project, cx))
1269                });
1270
1271                let (host_user_id, host_project, host_cx) =
1272                    if let Some((host_user_id, host_project, host_cx)) = host_project {
1273                        (host_user_id, host_project, host_cx)
1274                    } else {
1275                        continue;
1276                    };
1277
1278                for guest_buffer in guest_buffers {
1279                    let buffer_id =
1280                        guest_buffer.read_with(client_cx, |buffer, _| buffer.remote_id());
1281                    let host_buffer = host_project.read_with(host_cx, |project, _| {
1282                        project.buffer_for_id(buffer_id).unwrap_or_else(|| {
1283                            panic!(
1284                                "host does not have buffer for guest:{}, peer:{:?}, id:{}",
1285                                client.username,
1286                                client.peer_id(),
1287                                buffer_id
1288                            )
1289                        })
1290                    });
1291                    let path = host_buffer
1292                        .read_with(host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
1293
1294                    assert_eq!(
1295                        guest_buffer.read_with(client_cx, |buffer, _| buffer.deferred_ops_len()),
1296                        0,
1297                        "{}, buffer {}, path {:?} has deferred operations",
1298                        client.username,
1299                        buffer_id,
1300                        path,
1301                    );
1302                    assert_eq!(
1303                        guest_buffer.read_with(client_cx, |buffer, _| buffer.text()),
1304                        host_buffer.read_with(host_cx, |buffer, _| buffer.text()),
1305                        "{}, buffer {}, path {:?}, differs from the host's buffer",
1306                        client.username,
1307                        buffer_id,
1308                        path
1309                    );
1310
1311                    let host_file = host_buffer.read_with(host_cx, |b, _| b.file().cloned());
1312                    let guest_file = guest_buffer.read_with(client_cx, |b, _| b.file().cloned());
1313                    match (host_file, guest_file) {
1314                        (Some(host_file), Some(guest_file)) => {
1315                            assert_eq!(guest_file.path(), host_file.path());
1316                            assert_eq!(guest_file.is_deleted(), host_file.is_deleted());
1317                            assert_eq!(
1318                                guest_file.mtime(),
1319                                host_file.mtime(),
1320                                "guest {} mtime does not match host {} for path {:?} in project {}",
1321                                guest_user_id,
1322                                host_user_id,
1323                                guest_file.path(),
1324                                project_id,
1325                            );
1326                        }
1327                        (None, None) => {}
1328                        (None, _) => panic!("host's file is None, guest's isn't"),
1329                        (_, None) => panic!("guest's file is None, hosts's isn't"),
1330                    }
1331
1332                    let host_diff_base = host_buffer
1333                        .read_with(host_cx, |b, _| b.diff_base().map(ToString::to_string));
1334                    let guest_diff_base = guest_buffer
1335                        .read_with(client_cx, |b, _| b.diff_base().map(ToString::to_string));
1336                    assert_eq!(
1337                            guest_diff_base, host_diff_base,
1338                            "guest {} diff base does not match host's for path {path:?} in project {project_id}",
1339                            client.username
1340                        );
1341
1342                    let host_saved_version =
1343                        host_buffer.read_with(host_cx, |b, _| b.saved_version().clone());
1344                    let guest_saved_version =
1345                        guest_buffer.read_with(client_cx, |b, _| b.saved_version().clone());
1346                    assert_eq!(
1347                            guest_saved_version, host_saved_version,
1348                            "guest {} saved version does not match host's for path {path:?} in project {project_id}",
1349                            client.username
1350                        );
1351
1352                    let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
1353                    let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
1354                    assert_eq!(
1355                            guest_is_dirty, host_is_dirty,
1356                            "guest {} dirty state does not match host's for path {path:?} in project {project_id}",
1357                            client.username
1358                        );
1359
1360                    let host_saved_mtime = host_buffer.read_with(host_cx, |b, _| b.saved_mtime());
1361                    let guest_saved_mtime =
1362                        guest_buffer.read_with(client_cx, |b, _| b.saved_mtime());
1363                    assert_eq!(
1364                            guest_saved_mtime, host_saved_mtime,
1365                            "guest {} saved mtime does not match host's for path {path:?} in project {project_id}",
1366                            client.username
1367                        );
1368
1369                    let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
1370                    let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
1371                    assert_eq!(guest_is_dirty, host_is_dirty,
1372                            "guest {} dirty status does not match host's for path {path:?} in project {project_id}",
1373                            client.username
1374                        );
1375
1376                    let host_has_conflict = host_buffer.read_with(host_cx, |b, _| b.has_conflict());
1377                    let guest_has_conflict =
1378                        guest_buffer.read_with(client_cx, |b, _| b.has_conflict());
1379                    assert_eq!(guest_has_conflict, host_has_conflict,
1380                            "guest {} conflict status does not match host's for path {path:?} in project {project_id}",
1381                            client.username
1382                        );
1383                }
1384            }
1385        }
1386    }
1387}
1388
1389fn generate_git_operation(rng: &mut StdRng, client: &TestClient) -> GitOperation {
1390    fn generate_file_paths(
1391        repo_path: &Path,
1392        rng: &mut StdRng,
1393        client: &TestClient,
1394    ) -> Vec<PathBuf> {
1395        let mut paths = client
1396            .fs()
1397            .files()
1398            .into_iter()
1399            .filter(|path| path.starts_with(repo_path))
1400            .collect::<Vec<_>>();
1401
1402        let count = rng.gen_range(0..=paths.len());
1403        paths.shuffle(rng);
1404        paths.truncate(count);
1405
1406        paths
1407            .iter()
1408            .map(|path| path.strip_prefix(repo_path).unwrap().to_path_buf())
1409            .collect::<Vec<_>>()
1410    }
1411
1412    let repo_path = client.fs().directories(false).choose(rng).unwrap().clone();
1413
1414    match rng.gen_range(0..100_u32) {
1415        0..=25 => {
1416            let file_paths = generate_file_paths(&repo_path, rng, client);
1417
1418            let contents = file_paths
1419                .into_iter()
1420                .map(|path| (path, Alphanumeric.sample_string(rng, 16)))
1421                .collect();
1422
1423            GitOperation::WriteGitIndex {
1424                repo_path,
1425                contents,
1426            }
1427        }
1428        26..=63 => {
1429            let new_branch = (rng.gen_range(0..10) > 3).then(|| Alphanumeric.sample_string(rng, 8));
1430
1431            GitOperation::WriteGitBranch {
1432                repo_path,
1433                new_branch,
1434            }
1435        }
1436        64..=100 => {
1437            let file_paths = generate_file_paths(&repo_path, rng, client);
1438
1439            let statuses = file_paths
1440                .into_iter()
1441                .map(|paths| {
1442                    (
1443                        paths,
1444                        match rng.gen_range(0..3_u32) {
1445                            0 => GitFileStatus::Added,
1446                            1 => GitFileStatus::Modified,
1447                            2 => GitFileStatus::Conflict,
1448                            _ => unreachable!(),
1449                        },
1450                    )
1451                })
1452                .collect::<Vec<_>>();
1453
1454            let git_operation = rng.gen::<bool>();
1455
1456            GitOperation::WriteGitStatuses {
1457                repo_path,
1458                statuses,
1459                git_operation,
1460            }
1461        }
1462        _ => unreachable!(),
1463    }
1464}
1465
1466fn buffer_for_full_path(
1467    client: &TestClient,
1468    project: &Model<Project>,
1469    full_path: &PathBuf,
1470    cx: &TestAppContext,
1471) -> Option<Model<language::Buffer>> {
1472    client
1473        .buffers_for_project(project)
1474        .iter()
1475        .find(|buffer| {
1476            buffer.read_with(cx, |buffer, cx| {
1477                buffer.file().unwrap().full_path(cx) == *full_path
1478            })
1479        })
1480        .cloned()
1481}
1482
1483fn project_for_root_name(
1484    client: &TestClient,
1485    root_name: &str,
1486    cx: &TestAppContext,
1487) -> Option<Model<Project>> {
1488    if let Some(ix) = project_ix_for_root_name(client.local_projects().deref(), root_name, cx) {
1489        return Some(client.local_projects()[ix].clone());
1490    }
1491    if let Some(ix) = project_ix_for_root_name(client.dev_server_projects().deref(), root_name, cx)
1492    {
1493        return Some(client.dev_server_projects()[ix].clone());
1494    }
1495    None
1496}
1497
1498fn project_ix_for_root_name(
1499    projects: &[Model<Project>],
1500    root_name: &str,
1501    cx: &TestAppContext,
1502) -> Option<usize> {
1503    projects.iter().position(|project| {
1504        project.read_with(cx, |project, cx| {
1505            let worktree = project.visible_worktrees(cx).next().unwrap();
1506            worktree.read(cx).root_name() == root_name
1507        })
1508    })
1509}
1510
1511fn root_name_for_project(project: &Model<Project>, cx: &TestAppContext) -> String {
1512    project.read_with(cx, |project, cx| {
1513        project
1514            .visible_worktrees(cx)
1515            .next()
1516            .unwrap()
1517            .read(cx)
1518            .root_name()
1519            .to_string()
1520    })
1521}
1522
1523fn project_path_for_full_path(
1524    project: &Model<Project>,
1525    full_path: &Path,
1526    cx: &TestAppContext,
1527) -> Option<ProjectPath> {
1528    let mut components = full_path.components();
1529    let root_name = components.next().unwrap().as_os_str().to_str().unwrap();
1530    let path = components.as_path().into();
1531    let worktree_id = project.read_with(cx, |project, cx| {
1532        project.worktrees().find_map(|worktree| {
1533            let worktree = worktree.read(cx);
1534            if worktree.root_name() == root_name {
1535                Some(worktree.id())
1536            } else {
1537                None
1538            }
1539        })
1540    })?;
1541    Some(ProjectPath { worktree_id, path })
1542}
1543
1544async fn ensure_project_shared(
1545    project: &Model<Project>,
1546    client: &TestClient,
1547    cx: &mut TestAppContext,
1548) {
1549    let first_root_name = root_name_for_project(project, cx);
1550    let active_call = cx.read(ActiveCall::global);
1551    if active_call.read_with(cx, |call, _| call.room().is_some())
1552        && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())
1553    {
1554        match active_call
1555            .update(cx, |call, cx| call.share_project(project.clone(), cx))
1556            .await
1557        {
1558            Ok(project_id) => {
1559                log::info!(
1560                    "{}: shared project {} with id {}",
1561                    client.username,
1562                    first_root_name,
1563                    project_id
1564                );
1565            }
1566            Err(error) => {
1567                log::error!(
1568                    "{}: error sharing project {}: {:?}",
1569                    client.username,
1570                    first_root_name,
1571                    error
1572                );
1573            }
1574        }
1575    }
1576}
1577
1578fn choose_random_project(client: &TestClient, rng: &mut StdRng) -> Option<Model<Project>> {
1579    client
1580        .local_projects()
1581        .deref()
1582        .iter()
1583        .chain(client.dev_server_projects().iter())
1584        .choose(rng)
1585        .cloned()
1586}
1587
1588fn gen_file_name(rng: &mut StdRng) -> String {
1589    let mut name = String::new();
1590    for _ in 0..10 {
1591        let letter = rng.gen_range('a'..='z');
1592        name.push(letter);
1593    }
1594    name
1595}