randomized_integration_tests.rs

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