remote_editing_tests.rs

   1/// todo(windows)
   2/// The tests in this file assume that server_cx is running on Windows too.
   3/// We neead to find a way to test Windows-Non-Windows interactions.
   4use crate::headless_project::HeadlessProject;
   5use assistant_tool::{Tool as _, ToolResultContent};
   6use assistant_tools::{ReadFileTool, ReadFileToolInput};
   7use client::{Client, UserStore};
   8use clock::FakeSystemClock;
   9use language_model::{LanguageModelRequest, fake_provider::FakeLanguageModel};
  10
  11use extension::ExtensionHostProxy;
  12use fs::{FakeFs, Fs};
  13use gpui::{AppContext as _, Entity, SemanticVersion, TestAppContext};
  14use http_client::{BlockedHttpClient, FakeHttpClient};
  15use language::{
  16    Buffer, FakeLspAdapter, LanguageConfig, LanguageMatcher, LanguageRegistry, LineEnding,
  17    language_settings::{AllLanguageSettings, language_settings},
  18};
  19use lsp::{CompletionContext, CompletionResponse, CompletionTriggerKind, LanguageServerName};
  20use node_runtime::NodeRuntime;
  21use project::{
  22    Project, ProjectPath,
  23    search::{SearchQuery, SearchResult},
  24};
  25use remote::RemoteClient;
  26use serde_json::json;
  27use settings::{Settings, SettingsLocation, SettingsStore, initial_server_settings_content};
  28use smol::stream::StreamExt;
  29use std::{
  30    collections::HashSet,
  31    path::{Path, PathBuf},
  32    sync::Arc,
  33};
  34#[cfg(not(windows))]
  35use unindent::Unindent as _;
  36use util::path;
  37
  38#[gpui::test]
  39async fn test_basic_remote_editing(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
  40    let fs = FakeFs::new(server_cx.executor());
  41    fs.insert_tree(
  42        path!("/code"),
  43        json!({
  44            "project1": {
  45                ".git": {},
  46                "README.md": "# project 1",
  47                "src": {
  48                    "lib.rs": "fn one() -> usize { 1 }"
  49                }
  50            },
  51            "project2": {
  52                "README.md": "# project 2",
  53            },
  54        }),
  55    )
  56    .await;
  57    fs.set_index_for_repo(
  58        Path::new(path!("/code/project1/.git")),
  59        &[("src/lib.rs".into(), "fn one() -> usize { 0 }".into())],
  60    );
  61
  62    let (project, _headless) = init_test(&fs, cx, server_cx).await;
  63    let (worktree, _) = project
  64        .update(cx, |project, cx| {
  65            project.find_or_create_worktree(path!("/code/project1"), true, cx)
  66        })
  67        .await
  68        .unwrap();
  69
  70    // The client sees the worktree's contents.
  71    cx.executor().run_until_parked();
  72    let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
  73    worktree.update(cx, |worktree, _cx| {
  74        assert_eq!(
  75            worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),
  76            vec![
  77                Path::new("README.md"),
  78                Path::new("src"),
  79                Path::new("src/lib.rs"),
  80            ]
  81        );
  82    });
  83
  84    // The user opens a buffer in the remote worktree. The buffer's
  85    // contents are loaded from the remote filesystem.
  86    let buffer = project
  87        .update(cx, |project, cx| {
  88            project.open_buffer((worktree_id, Path::new("src/lib.rs")), cx)
  89        })
  90        .await
  91        .unwrap();
  92    let diff = project
  93        .update(cx, |project, cx| {
  94            project.open_unstaged_diff(buffer.clone(), cx)
  95        })
  96        .await
  97        .unwrap();
  98
  99    diff.update(cx, |diff, _| {
 100        assert_eq!(diff.base_text_string().unwrap(), "fn one() -> usize { 0 }");
 101    });
 102
 103    buffer.update(cx, |buffer, cx| {
 104        assert_eq!(buffer.text(), "fn one() -> usize { 1 }");
 105        let ix = buffer.text().find('1').unwrap();
 106        buffer.edit([(ix..ix + 1, "100")], None, cx);
 107    });
 108
 109    // The user saves the buffer. The new contents are written to the
 110    // remote filesystem.
 111    project
 112        .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 113        .await
 114        .unwrap();
 115    assert_eq!(
 116        fs.load("/code/project1/src/lib.rs".as_ref()).await.unwrap(),
 117        "fn one() -> usize { 100 }"
 118    );
 119
 120    // A new file is created in the remote filesystem. The user
 121    // sees the new file.
 122    fs.save(
 123        path!("/code/project1/src/main.rs").as_ref(),
 124        &"fn main() {}".into(),
 125        Default::default(),
 126    )
 127    .await
 128    .unwrap();
 129    cx.executor().run_until_parked();
 130    worktree.update(cx, |worktree, _cx| {
 131        assert_eq!(
 132            worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),
 133            vec![
 134                Path::new("README.md"),
 135                Path::new("src"),
 136                Path::new("src/lib.rs"),
 137                Path::new("src/main.rs"),
 138            ]
 139        );
 140    });
 141
 142    // A file that is currently open in a buffer is renamed.
 143    fs.rename(
 144        path!("/code/project1/src/lib.rs").as_ref(),
 145        path!("/code/project1/src/lib2.rs").as_ref(),
 146        Default::default(),
 147    )
 148    .await
 149    .unwrap();
 150    cx.executor().run_until_parked();
 151    buffer.update(cx, |buffer, _| {
 152        assert_eq!(&**buffer.file().unwrap().path(), Path::new("src/lib2.rs"));
 153    });
 154
 155    fs.set_index_for_repo(
 156        Path::new(path!("/code/project1/.git")),
 157        &[("src/lib2.rs".into(), "fn one() -> usize { 100 }".into())],
 158    );
 159    cx.executor().run_until_parked();
 160    diff.update(cx, |diff, _| {
 161        assert_eq!(
 162            diff.base_text_string().unwrap(),
 163            "fn one() -> usize { 100 }"
 164        );
 165    });
 166}
 167
 168#[gpui::test]
 169async fn test_remote_project_search(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
 170    let fs = FakeFs::new(server_cx.executor());
 171    fs.insert_tree(
 172        path!("/code"),
 173        json!({
 174            "project1": {
 175                ".git": {},
 176                "README.md": "# project 1",
 177                "src": {
 178                    "lib.rs": "fn one() -> usize { 1 }"
 179                }
 180            },
 181        }),
 182    )
 183    .await;
 184
 185    let (project, headless) = init_test(&fs, cx, server_cx).await;
 186
 187    project
 188        .update(cx, |project, cx| {
 189            project.find_or_create_worktree(path!("/code/project1"), true, cx)
 190        })
 191        .await
 192        .unwrap();
 193
 194    cx.run_until_parked();
 195
 196    async fn do_search(project: &Entity<Project>, mut cx: TestAppContext) -> Entity<Buffer> {
 197        let receiver = project.update(&mut cx, |project, cx| {
 198            project.search(
 199                SearchQuery::text(
 200                    "project",
 201                    false,
 202                    true,
 203                    false,
 204                    Default::default(),
 205                    Default::default(),
 206                    false,
 207                    None,
 208                )
 209                .unwrap(),
 210                cx,
 211            )
 212        });
 213
 214        let first_response = receiver.recv().await.unwrap();
 215        let SearchResult::Buffer { buffer, .. } = first_response else {
 216            panic!("incorrect result");
 217        };
 218        buffer.update(&mut cx, |buffer, cx| {
 219            assert_eq!(
 220                buffer.file().unwrap().full_path(cx).to_string_lossy(),
 221                path!("project1/README.md")
 222            )
 223        });
 224
 225        assert!(receiver.recv().await.is_err());
 226        buffer
 227    }
 228
 229    let buffer = do_search(&project, cx.clone()).await;
 230
 231    // test that the headless server is tracking which buffers we have open correctly.
 232    cx.run_until_parked();
 233    headless.update(server_cx, |headless, cx| {
 234        assert!(headless.buffer_store.read(cx).has_shared_buffers())
 235    });
 236    do_search(&project, cx.clone()).await;
 237
 238    cx.update(|_| {
 239        drop(buffer);
 240    });
 241    cx.run_until_parked();
 242    headless.update(server_cx, |headless, cx| {
 243        assert!(!headless.buffer_store.read(cx).has_shared_buffers())
 244    });
 245
 246    do_search(&project, cx.clone()).await;
 247}
 248
 249#[gpui::test]
 250async fn test_remote_settings(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
 251    let fs = FakeFs::new(server_cx.executor());
 252    fs.insert_tree(
 253        "/code",
 254        json!({
 255            "project1": {
 256                ".git": {},
 257                "README.md": "# project 1",
 258                "src": {
 259                    "lib.rs": "fn one() -> usize { 1 }"
 260                }
 261            },
 262        }),
 263    )
 264    .await;
 265
 266    let (project, headless) = init_test(&fs, cx, server_cx).await;
 267
 268    cx.update_global(|settings_store: &mut SettingsStore, cx| {
 269        settings_store.set_user_settings(
 270            r#"{"languages":{"Rust":{"language_servers":["from-local-settings"]}}}"#,
 271            cx,
 272        )
 273    })
 274    .unwrap();
 275
 276    cx.run_until_parked();
 277
 278    server_cx.read(|cx| {
 279        assert_eq!(
 280            AllLanguageSettings::get_global(cx)
 281                .language(None, Some(&"Rust".into()), cx)
 282                .language_servers,
 283            ["from-local-settings"],
 284            "User language settings should be synchronized with the server settings"
 285        )
 286    });
 287
 288    server_cx
 289        .update_global(|settings_store: &mut SettingsStore, cx| {
 290            settings_store.set_server_settings(
 291                r#"{"languages":{"Rust":{"language_servers":["from-server-settings"]}}}"#,
 292                cx,
 293            )
 294        })
 295        .unwrap();
 296
 297    cx.run_until_parked();
 298
 299    server_cx.read(|cx| {
 300        assert_eq!(
 301            AllLanguageSettings::get_global(cx)
 302                .language(None, Some(&"Rust".into()), cx)
 303                .language_servers,
 304            ["from-server-settings".to_string()],
 305            "Server language settings should take precedence over the user settings"
 306        )
 307    });
 308
 309    fs.insert_tree(
 310        "/code/project1/.zed",
 311        json!({
 312            "settings.json": r#"
 313                  {
 314                    "languages": {"Rust":{"language_servers":["override-rust-analyzer"]}},
 315                    "lsp": {
 316                      "override-rust-analyzer": {
 317                        "binary": {
 318                          "path": "~/.cargo/bin/rust-analyzer"
 319                        }
 320                      }
 321                    }
 322                  }"#
 323        }),
 324    )
 325    .await;
 326
 327    let worktree_id = project
 328        .update(cx, |project, cx| {
 329            project.find_or_create_worktree("/code/project1", true, cx)
 330        })
 331        .await
 332        .unwrap()
 333        .0
 334        .read_with(cx, |worktree, _| worktree.id());
 335
 336    let buffer = project
 337        .update(cx, |project, cx| {
 338            project.open_buffer((worktree_id, Path::new("src/lib.rs")), cx)
 339        })
 340        .await
 341        .unwrap();
 342    cx.run_until_parked();
 343
 344    server_cx.read(|cx| {
 345        let worktree_id = headless
 346            .read(cx)
 347            .worktree_store
 348            .read(cx)
 349            .worktrees()
 350            .next()
 351            .unwrap()
 352            .read(cx)
 353            .id();
 354        assert_eq!(
 355            AllLanguageSettings::get(
 356                Some(SettingsLocation {
 357                    worktree_id,
 358                    path: Path::new("src/lib.rs")
 359                }),
 360                cx
 361            )
 362            .language(None, Some(&"Rust".into()), cx)
 363            .language_servers,
 364            ["override-rust-analyzer".to_string()]
 365        )
 366    });
 367
 368    cx.read(|cx| {
 369        let file = buffer.read(cx).file();
 370        assert_eq!(
 371            language_settings(Some("Rust".into()), file, cx).language_servers,
 372            ["override-rust-analyzer".to_string()]
 373        )
 374    });
 375}
 376
 377#[gpui::test]
 378async fn test_remote_lsp(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
 379    let fs = FakeFs::new(server_cx.executor());
 380    fs.insert_tree(
 381        path!("/code"),
 382        json!({
 383            "project1": {
 384                ".git": {},
 385                "README.md": "# project 1",
 386                "src": {
 387                    "lib.rs": "fn one() -> usize { 1 }"
 388                }
 389            },
 390        }),
 391    )
 392    .await;
 393
 394    let (project, headless) = init_test(&fs, cx, server_cx).await;
 395
 396    fs.insert_tree(
 397        path!("/code/project1/.zed"),
 398        json!({
 399            "settings.json": r#"
 400          {
 401            "languages": {"Rust":{"language_servers":["rust-analyzer"]}},
 402            "lsp": {
 403              "rust-analyzer": {
 404                "binary": {
 405                  "path": "~/.cargo/bin/rust-analyzer"
 406                }
 407              }
 408            }
 409          }"#
 410        }),
 411    )
 412    .await;
 413
 414    cx.update_entity(&project, |project, _| {
 415        project.languages().register_test_language(LanguageConfig {
 416            name: "Rust".into(),
 417            matcher: LanguageMatcher {
 418                path_suffixes: vec!["rs".into()],
 419                ..Default::default()
 420            },
 421            ..Default::default()
 422        });
 423        project.languages().register_fake_lsp_adapter(
 424            "Rust",
 425            FakeLspAdapter {
 426                name: "rust-analyzer",
 427                capabilities: lsp::ServerCapabilities {
 428                    completion_provider: Some(lsp::CompletionOptions::default()),
 429                    rename_provider: Some(lsp::OneOf::Left(true)),
 430                    ..lsp::ServerCapabilities::default()
 431                },
 432                ..FakeLspAdapter::default()
 433            },
 434        )
 435    });
 436
 437    let mut fake_lsp = server_cx.update(|cx| {
 438        headless.read(cx).languages.register_fake_language_server(
 439            LanguageServerName("rust-analyzer".into()),
 440            lsp::ServerCapabilities {
 441                completion_provider: Some(lsp::CompletionOptions::default()),
 442                rename_provider: Some(lsp::OneOf::Left(true)),
 443                ..lsp::ServerCapabilities::default()
 444            },
 445            None,
 446        )
 447    });
 448
 449    cx.run_until_parked();
 450
 451    let worktree_id = project
 452        .update(cx, |project, cx| {
 453            project.find_or_create_worktree(path!("/code/project1"), true, cx)
 454        })
 455        .await
 456        .unwrap()
 457        .0
 458        .read_with(cx, |worktree, _| worktree.id());
 459
 460    // Wait for the settings to synchronize
 461    cx.run_until_parked();
 462
 463    let (buffer, _handle) = project
 464        .update(cx, |project, cx| {
 465            project.open_buffer_with_lsp((worktree_id, Path::new("src/lib.rs")), cx)
 466        })
 467        .await
 468        .unwrap();
 469    cx.run_until_parked();
 470
 471    let fake_lsp = fake_lsp.next().await.unwrap();
 472
 473    cx.read(|cx| {
 474        let file = buffer.read(cx).file();
 475        assert_eq!(
 476            language_settings(Some("Rust".into()), file, cx).language_servers,
 477            ["rust-analyzer".to_string()]
 478        )
 479    });
 480
 481    let buffer_id = cx.read(|cx| {
 482        let buffer = buffer.read(cx);
 483        assert_eq!(buffer.language().unwrap().name(), "Rust".into());
 484        buffer.remote_id()
 485    });
 486
 487    server_cx.read(|cx| {
 488        let buffer = headless
 489            .read(cx)
 490            .buffer_store
 491            .read(cx)
 492            .get(buffer_id)
 493            .unwrap();
 494
 495        assert_eq!(buffer.read(cx).language().unwrap().name(), "Rust".into());
 496    });
 497
 498    server_cx.read(|cx| {
 499        let lsp_store = headless.read(cx).lsp_store.read(cx);
 500        assert_eq!(lsp_store.as_local().unwrap().language_servers.len(), 1);
 501    });
 502
 503    fake_lsp.set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
 504        Ok(Some(CompletionResponse::Array(vec![lsp::CompletionItem {
 505            label: "boop".to_string(),
 506            ..Default::default()
 507        }])))
 508    });
 509
 510    let result = project
 511        .update(cx, |project, cx| {
 512            project.completions(
 513                &buffer,
 514                0,
 515                CompletionContext {
 516                    trigger_kind: CompletionTriggerKind::INVOKED,
 517                    trigger_character: None,
 518                },
 519                cx,
 520            )
 521        })
 522        .await
 523        .unwrap();
 524
 525    assert_eq!(
 526        result
 527            .into_iter()
 528            .flat_map(|response| response.completions)
 529            .map(|c| c.label.text)
 530            .collect::<Vec<_>>(),
 531        vec!["boop".to_string()]
 532    );
 533
 534    fake_lsp.set_request_handler::<lsp::request::Rename, _, _>(|_, _| async move {
 535        Ok(Some(lsp::WorkspaceEdit {
 536            changes: Some(
 537                [(
 538                    lsp::Uri::from_file_path(path!("/code/project1/src/lib.rs")).unwrap(),
 539                    vec![lsp::TextEdit::new(
 540                        lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 6)),
 541                        "two".to_string(),
 542                    )],
 543                )]
 544                .into_iter()
 545                .collect(),
 546            ),
 547            ..Default::default()
 548        }))
 549    });
 550
 551    project
 552        .update(cx, |project, cx| {
 553            project.perform_rename(buffer.clone(), 3, "two".to_string(), cx)
 554        })
 555        .await
 556        .unwrap();
 557
 558    cx.run_until_parked();
 559    buffer.update(cx, |buffer, _| {
 560        assert_eq!(buffer.text(), "fn two() -> usize { 1 }")
 561    })
 562}
 563
 564#[gpui::test]
 565async fn test_remote_cancel_language_server_work(
 566    cx: &mut TestAppContext,
 567    server_cx: &mut TestAppContext,
 568) {
 569    let fs = FakeFs::new(server_cx.executor());
 570    fs.insert_tree(
 571        path!("/code"),
 572        json!({
 573            "project1": {
 574                ".git": {},
 575                "README.md": "# project 1",
 576                "src": {
 577                    "lib.rs": "fn one() -> usize { 1 }"
 578                }
 579            },
 580        }),
 581    )
 582    .await;
 583
 584    let (project, headless) = init_test(&fs, cx, server_cx).await;
 585
 586    fs.insert_tree(
 587        path!("/code/project1/.zed"),
 588        json!({
 589            "settings.json": r#"
 590          {
 591            "languages": {"Rust":{"language_servers":["rust-analyzer"]}},
 592            "lsp": {
 593              "rust-analyzer": {
 594                "binary": {
 595                  "path": "~/.cargo/bin/rust-analyzer"
 596                }
 597              }
 598            }
 599          }"#
 600        }),
 601    )
 602    .await;
 603
 604    cx.update_entity(&project, |project, _| {
 605        project.languages().register_test_language(LanguageConfig {
 606            name: "Rust".into(),
 607            matcher: LanguageMatcher {
 608                path_suffixes: vec!["rs".into()],
 609                ..Default::default()
 610            },
 611            ..Default::default()
 612        });
 613        project.languages().register_fake_lsp_adapter(
 614            "Rust",
 615            FakeLspAdapter {
 616                name: "rust-analyzer",
 617                ..Default::default()
 618            },
 619        )
 620    });
 621
 622    let mut fake_lsp = server_cx.update(|cx| {
 623        headless.read(cx).languages.register_fake_language_server(
 624            LanguageServerName("rust-analyzer".into()),
 625            Default::default(),
 626            None,
 627        )
 628    });
 629
 630    cx.run_until_parked();
 631
 632    let worktree_id = project
 633        .update(cx, |project, cx| {
 634            project.find_or_create_worktree(path!("/code/project1"), true, cx)
 635        })
 636        .await
 637        .unwrap()
 638        .0
 639        .read_with(cx, |worktree, _| worktree.id());
 640
 641    cx.run_until_parked();
 642
 643    let (buffer, _handle) = project
 644        .update(cx, |project, cx| {
 645            project.open_buffer_with_lsp((worktree_id, Path::new("src/lib.rs")), cx)
 646        })
 647        .await
 648        .unwrap();
 649
 650    cx.run_until_parked();
 651
 652    let mut fake_lsp = fake_lsp.next().await.unwrap();
 653
 654    // Cancelling all language server work for a given buffer
 655    {
 656        // Two operations, one cancellable and one not.
 657        fake_lsp
 658            .start_progress_with(
 659                "another-token",
 660                lsp::WorkDoneProgressBegin {
 661                    cancellable: Some(false),
 662                    ..Default::default()
 663                },
 664            )
 665            .await;
 666
 667        let progress_token = "the-progress-token";
 668        fake_lsp
 669            .start_progress_with(
 670                progress_token,
 671                lsp::WorkDoneProgressBegin {
 672                    cancellable: Some(true),
 673                    ..Default::default()
 674                },
 675            )
 676            .await;
 677
 678        cx.executor().run_until_parked();
 679
 680        project.update(cx, |project, cx| {
 681            project.cancel_language_server_work_for_buffers([buffer.clone()], cx)
 682        });
 683
 684        cx.executor().run_until_parked();
 685
 686        // Verify the cancellation was received on the server side
 687        let cancel_notification = fake_lsp
 688            .receive_notification::<lsp::notification::WorkDoneProgressCancel>()
 689            .await;
 690        assert_eq!(
 691            cancel_notification.token,
 692            lsp::NumberOrString::String(progress_token.into())
 693        );
 694    }
 695
 696    // Cancelling work by server_id and token
 697    {
 698        let server_id = fake_lsp.server.server_id();
 699        let progress_token = "the-progress-token";
 700
 701        fake_lsp
 702            .start_progress_with(
 703                progress_token,
 704                lsp::WorkDoneProgressBegin {
 705                    cancellable: Some(true),
 706                    ..Default::default()
 707                },
 708            )
 709            .await;
 710
 711        cx.executor().run_until_parked();
 712
 713        project.update(cx, |project, cx| {
 714            project.cancel_language_server_work(server_id, Some(progress_token.into()), cx)
 715        });
 716
 717        cx.executor().run_until_parked();
 718
 719        // Verify the cancellation was received on the server side
 720        let cancel_notification = fake_lsp
 721            .receive_notification::<lsp::notification::WorkDoneProgressCancel>()
 722            .await;
 723        assert_eq!(
 724            cancel_notification.token,
 725            lsp::NumberOrString::String(progress_token.into())
 726        );
 727    }
 728}
 729
 730#[gpui::test]
 731async fn test_remote_reload(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
 732    let fs = FakeFs::new(server_cx.executor());
 733    fs.insert_tree(
 734        path!("/code"),
 735        json!({
 736            "project1": {
 737                ".git": {},
 738                "README.md": "# project 1",
 739                "src": {
 740                    "lib.rs": "fn one() -> usize { 1 }"
 741                }
 742            },
 743        }),
 744    )
 745    .await;
 746
 747    let (project, _headless) = init_test(&fs, cx, server_cx).await;
 748    let (worktree, _) = project
 749        .update(cx, |project, cx| {
 750            project.find_or_create_worktree(path!("/code/project1"), true, cx)
 751        })
 752        .await
 753        .unwrap();
 754
 755    let worktree_id = cx.update(|cx| worktree.read(cx).id());
 756
 757    let buffer = project
 758        .update(cx, |project, cx| {
 759            project.open_buffer((worktree_id, Path::new("src/lib.rs")), cx)
 760        })
 761        .await
 762        .unwrap();
 763
 764    fs.save(
 765        &PathBuf::from(path!("/code/project1/src/lib.rs")),
 766        &("bangles".to_string().into()),
 767        LineEnding::Unix,
 768    )
 769    .await
 770    .unwrap();
 771
 772    cx.run_until_parked();
 773
 774    buffer.update(cx, |buffer, cx| {
 775        assert_eq!(buffer.text(), "bangles");
 776        buffer.edit([(0..0, "a")], None, cx);
 777    });
 778
 779    fs.save(
 780        &PathBuf::from(path!("/code/project1/src/lib.rs")),
 781        &("bloop".to_string().into()),
 782        LineEnding::Unix,
 783    )
 784    .await
 785    .unwrap();
 786
 787    cx.run_until_parked();
 788    cx.update(|cx| {
 789        assert!(buffer.read(cx).has_conflict());
 790    });
 791
 792    project
 793        .update(cx, |project, cx| {
 794            project.reload_buffers([buffer.clone()].into_iter().collect(), false, cx)
 795        })
 796        .await
 797        .unwrap();
 798    cx.run_until_parked();
 799
 800    cx.update(|cx| {
 801        assert!(!buffer.read(cx).has_conflict());
 802    });
 803}
 804
 805#[gpui::test]
 806async fn test_remote_resolve_path_in_buffer(
 807    cx: &mut TestAppContext,
 808    server_cx: &mut TestAppContext,
 809) {
 810    let fs = FakeFs::new(server_cx.executor());
 811    // Even though we are not testing anything from project1, it is necessary to test if project2 is picking up correct worktree
 812    fs.insert_tree(
 813        path!("/code"),
 814        json!({
 815            "project1": {
 816                ".git": {},
 817                "README.md": "# project 1",
 818                "src": {
 819                    "lib.rs": "fn one() -> usize { 1 }"
 820                }
 821            },
 822            "project2": {
 823                ".git": {},
 824                "README.md": "# project 2",
 825                "src": {
 826                    "lib.rs": "fn two() -> usize { 2 }"
 827                }
 828            }
 829        }),
 830    )
 831    .await;
 832
 833    let (project, _headless) = init_test(&fs, cx, server_cx).await;
 834
 835    let _ = project
 836        .update(cx, |project, cx| {
 837            project.find_or_create_worktree(path!("/code/project1"), true, cx)
 838        })
 839        .await
 840        .unwrap();
 841
 842    let (worktree2, _) = project
 843        .update(cx, |project, cx| {
 844            project.find_or_create_worktree(path!("/code/project2"), true, cx)
 845        })
 846        .await
 847        .unwrap();
 848
 849    let worktree2_id = cx.update(|cx| worktree2.read(cx).id());
 850
 851    let buffer2 = project
 852        .update(cx, |project, cx| {
 853            project.open_buffer((worktree2_id, Path::new("src/lib.rs")), cx)
 854        })
 855        .await
 856        .unwrap();
 857
 858    let path = project
 859        .update(cx, |project, cx| {
 860            project.resolve_path_in_buffer(path!("/code/project2/README.md"), &buffer2, cx)
 861        })
 862        .await
 863        .unwrap();
 864    assert!(path.is_file());
 865    assert_eq!(
 866        path.abs_path().unwrap().to_string_lossy(),
 867        path!("/code/project2/README.md")
 868    );
 869
 870    let path = project
 871        .update(cx, |project, cx| {
 872            project.resolve_path_in_buffer("../README.md", &buffer2, cx)
 873        })
 874        .await
 875        .unwrap();
 876    assert!(path.is_file());
 877    assert_eq!(
 878        path.project_path().unwrap().clone(),
 879        ProjectPath::from((worktree2_id, "README.md"))
 880    );
 881
 882    let path = project
 883        .update(cx, |project, cx| {
 884            project.resolve_path_in_buffer("../src", &buffer2, cx)
 885        })
 886        .await
 887        .unwrap();
 888    assert_eq!(
 889        path.project_path().unwrap().clone(),
 890        ProjectPath::from((worktree2_id, "src"))
 891    );
 892    assert!(path.is_dir());
 893}
 894
 895#[gpui::test]
 896async fn test_remote_resolve_abs_path(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
 897    let fs = FakeFs::new(server_cx.executor());
 898    fs.insert_tree(
 899        path!("/code"),
 900        json!({
 901            "project1": {
 902                ".git": {},
 903                "README.md": "# project 1",
 904                "src": {
 905                    "lib.rs": "fn one() -> usize { 1 }"
 906                }
 907            },
 908        }),
 909    )
 910    .await;
 911
 912    let (project, _headless) = init_test(&fs, cx, server_cx).await;
 913
 914    let path = project
 915        .update(cx, |project, cx| {
 916            project.resolve_abs_path(path!("/code/project1/README.md"), cx)
 917        })
 918        .await
 919        .unwrap();
 920
 921    assert!(path.is_file());
 922    assert_eq!(
 923        path.abs_path().unwrap().to_string_lossy(),
 924        path!("/code/project1/README.md")
 925    );
 926
 927    let path = project
 928        .update(cx, |project, cx| {
 929            project.resolve_abs_path(path!("/code/project1/src"), cx)
 930        })
 931        .await
 932        .unwrap();
 933
 934    assert!(path.is_dir());
 935    assert_eq!(
 936        path.abs_path().unwrap().to_string_lossy(),
 937        path!("/code/project1/src")
 938    );
 939
 940    let path = project
 941        .update(cx, |project, cx| {
 942            project.resolve_abs_path(path!("/code/project1/DOESNOTEXIST"), cx)
 943        })
 944        .await;
 945    assert!(path.is_none());
 946}
 947
 948#[gpui::test(iterations = 10)]
 949async fn test_canceling_buffer_opening(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
 950    let fs = FakeFs::new(server_cx.executor());
 951    fs.insert_tree(
 952        "/code",
 953        json!({
 954            "project1": {
 955                ".git": {},
 956                "README.md": "# project 1",
 957                "src": {
 958                    "lib.rs": "fn one() -> usize { 1 }"
 959                }
 960            },
 961        }),
 962    )
 963    .await;
 964
 965    let (project, _headless) = init_test(&fs, cx, server_cx).await;
 966    let (worktree, _) = project
 967        .update(cx, |project, cx| {
 968            project.find_or_create_worktree("/code/project1", true, cx)
 969        })
 970        .await
 971        .unwrap();
 972    let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
 973
 974    // Open a buffer on the client but cancel after a random amount of time.
 975    let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, "src/lib.rs"), cx));
 976    cx.executor().simulate_random_delay().await;
 977    drop(buffer);
 978
 979    // Try opening the same buffer again as the client, and ensure we can
 980    // still do it despite the cancellation above.
 981    let buffer = project
 982        .update(cx, |p, cx| p.open_buffer((worktree_id, "src/lib.rs"), cx))
 983        .await
 984        .unwrap();
 985
 986    buffer.read_with(cx, |buf, _| {
 987        assert_eq!(buf.text(), "fn one() -> usize { 1 }")
 988    });
 989}
 990
 991#[gpui::test]
 992async fn test_adding_then_removing_then_adding_worktrees(
 993    cx: &mut TestAppContext,
 994    server_cx: &mut TestAppContext,
 995) {
 996    let fs = FakeFs::new(server_cx.executor());
 997    fs.insert_tree(
 998        path!("/code"),
 999        json!({
1000            "project1": {
1001                ".git": {},
1002                "README.md": "# project 1",
1003                "src": {
1004                    "lib.rs": "fn one() -> usize { 1 }"
1005                }
1006            },
1007            "project2": {
1008                "README.md": "# project 2",
1009            },
1010        }),
1011    )
1012    .await;
1013
1014    let (project, _headless) = init_test(&fs, cx, server_cx).await;
1015    let (_worktree, _) = project
1016        .update(cx, |project, cx| {
1017            project.find_or_create_worktree(path!("/code/project1"), true, cx)
1018        })
1019        .await
1020        .unwrap();
1021
1022    let (worktree_2, _) = project
1023        .update(cx, |project, cx| {
1024            project.find_or_create_worktree(path!("/code/project2"), true, cx)
1025        })
1026        .await
1027        .unwrap();
1028    let worktree_id_2 = worktree_2.read_with(cx, |tree, _| tree.id());
1029
1030    project.update(cx, |project, cx| project.remove_worktree(worktree_id_2, cx));
1031
1032    let (worktree_2, _) = project
1033        .update(cx, |project, cx| {
1034            project.find_or_create_worktree(path!("/code/project2"), true, cx)
1035        })
1036        .await
1037        .unwrap();
1038
1039    cx.run_until_parked();
1040    worktree_2.update(cx, |worktree, _cx| {
1041        assert!(worktree.is_visible());
1042        let entries = worktree.entries(true, 0).collect::<Vec<_>>();
1043        assert_eq!(entries.len(), 2);
1044        assert_eq!(
1045            entries[1].path.to_string_lossy().to_string(),
1046            "README.md".to_string()
1047        )
1048    })
1049}
1050
1051#[gpui::test]
1052async fn test_open_server_settings(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1053    let fs = FakeFs::new(server_cx.executor());
1054    fs.insert_tree(
1055        path!("/code"),
1056        json!({
1057            "project1": {
1058                ".git": {},
1059                "README.md": "# project 1",
1060                "src": {
1061                    "lib.rs": "fn one() -> usize { 1 }"
1062                }
1063            },
1064        }),
1065    )
1066    .await;
1067
1068    let (project, _headless) = init_test(&fs, cx, server_cx).await;
1069    let buffer = project.update(cx, |project, cx| project.open_server_settings(cx));
1070    cx.executor().run_until_parked();
1071
1072    let buffer = buffer.await.unwrap();
1073
1074    cx.update(|cx| {
1075        assert_eq!(
1076            buffer.read(cx).text(),
1077            initial_server_settings_content()
1078                .to_string()
1079                .replace("\r\n", "\n")
1080        )
1081    })
1082}
1083
1084#[gpui::test(iterations = 20)]
1085async fn test_reconnect(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1086    let fs = FakeFs::new(server_cx.executor());
1087    fs.insert_tree(
1088        path!("/code"),
1089        json!({
1090            "project1": {
1091                ".git": {},
1092                "README.md": "# project 1",
1093                "src": {
1094                    "lib.rs": "fn one() -> usize { 1 }"
1095                }
1096            },
1097        }),
1098    )
1099    .await;
1100
1101    let (project, _headless) = init_test(&fs, cx, server_cx).await;
1102
1103    let (worktree, _) = project
1104        .update(cx, |project, cx| {
1105            project.find_or_create_worktree(path!("/code/project1"), true, cx)
1106        })
1107        .await
1108        .unwrap();
1109
1110    let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
1111    let buffer = project
1112        .update(cx, |project, cx| {
1113            project.open_buffer((worktree_id, Path::new("src/lib.rs")), cx)
1114        })
1115        .await
1116        .unwrap();
1117
1118    buffer.update(cx, |buffer, cx| {
1119        assert_eq!(buffer.text(), "fn one() -> usize { 1 }");
1120        let ix = buffer.text().find('1').unwrap();
1121        buffer.edit([(ix..ix + 1, "100")], None, cx);
1122    });
1123
1124    let client = cx.read(|cx| project.read(cx).remote_client().unwrap());
1125    client
1126        .update(cx, |client, cx| client.simulate_disconnect(cx))
1127        .detach();
1128
1129    project
1130        .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
1131        .await
1132        .unwrap();
1133
1134    assert_eq!(
1135        fs.load(path!("/code/project1/src/lib.rs").as_ref())
1136            .await
1137            .unwrap(),
1138        "fn one() -> usize { 100 }"
1139    );
1140}
1141
1142#[gpui::test]
1143async fn test_remote_root_rename(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1144    let fs = FakeFs::new(server_cx.executor());
1145    fs.insert_tree(
1146        "/code",
1147        json!({
1148            "project1": {
1149                ".git": {},
1150                "README.md": "# project 1",
1151            },
1152        }),
1153    )
1154    .await;
1155
1156    let (project, _) = init_test(&fs, cx, server_cx).await;
1157
1158    let (worktree, _) = project
1159        .update(cx, |project, cx| {
1160            project.find_or_create_worktree("/code/project1", true, cx)
1161        })
1162        .await
1163        .unwrap();
1164
1165    cx.run_until_parked();
1166
1167    fs.rename(
1168        &PathBuf::from("/code/project1"),
1169        &PathBuf::from("/code/project2"),
1170        Default::default(),
1171    )
1172    .await
1173    .unwrap();
1174
1175    cx.run_until_parked();
1176    worktree.update(cx, |worktree, _| {
1177        assert_eq!(worktree.root_name(), "project2")
1178    })
1179}
1180
1181#[gpui::test]
1182async fn test_remote_rename_entry(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1183    let fs = FakeFs::new(server_cx.executor());
1184    fs.insert_tree(
1185        "/code",
1186        json!({
1187            "project1": {
1188                ".git": {},
1189                "README.md": "# project 1",
1190            },
1191        }),
1192    )
1193    .await;
1194
1195    let (project, _) = init_test(&fs, cx, server_cx).await;
1196    let (worktree, _) = project
1197        .update(cx, |project, cx| {
1198            project.find_or_create_worktree("/code/project1", true, cx)
1199        })
1200        .await
1201        .unwrap();
1202
1203    cx.run_until_parked();
1204
1205    let entry = worktree
1206        .update(cx, |worktree, cx| {
1207            let entry = worktree.entry_for_path("README.md").unwrap();
1208            worktree.rename_entry(entry.id, Path::new("README.rst"), cx)
1209        })
1210        .await
1211        .unwrap()
1212        .into_included()
1213        .unwrap();
1214
1215    cx.run_until_parked();
1216
1217    worktree.update(cx, |worktree, _| {
1218        assert_eq!(worktree.entry_for_path("README.rst").unwrap().id, entry.id)
1219    });
1220}
1221
1222#[gpui::test]
1223async fn test_copy_file_into_remote_project(
1224    cx: &mut TestAppContext,
1225    server_cx: &mut TestAppContext,
1226) {
1227    let remote_fs = FakeFs::new(server_cx.executor());
1228    remote_fs
1229        .insert_tree(
1230            path!("/code"),
1231            json!({
1232                "project1": {
1233                    ".git": {},
1234                    "README.md": "# project 1",
1235                    "src": {
1236                        "main.rs": ""
1237                    }
1238                },
1239            }),
1240        )
1241        .await;
1242
1243    let (project, _) = init_test(&remote_fs, cx, server_cx).await;
1244    let (worktree, _) = project
1245        .update(cx, |project, cx| {
1246            project.find_or_create_worktree(path!("/code/project1"), true, cx)
1247        })
1248        .await
1249        .unwrap();
1250
1251    cx.run_until_parked();
1252
1253    let local_fs = project
1254        .read_with(cx, |project, _| project.fs().clone())
1255        .as_fake();
1256    local_fs
1257        .insert_tree(
1258            path!("/local-code"),
1259            json!({
1260                "dir1": {
1261                    "file1": "file 1 content",
1262                    "dir2": {
1263                        "file2": "file 2 content",
1264                        "dir3": {
1265                            "file3": ""
1266                        },
1267                        "dir4": {}
1268                    },
1269                    "dir5": {}
1270                },
1271                "file4": "file 4 content"
1272            }),
1273        )
1274        .await;
1275
1276    worktree
1277        .update(cx, |worktree, cx| {
1278            worktree.copy_external_entries(
1279                Path::new("src").into(),
1280                vec![
1281                    Path::new(path!("/local-code/dir1/file1")).into(),
1282                    Path::new(path!("/local-code/dir1/dir2")).into(),
1283                ],
1284                local_fs.clone(),
1285                cx,
1286            )
1287        })
1288        .await
1289        .unwrap();
1290
1291    assert_eq!(
1292        remote_fs.paths(true),
1293        vec![
1294            PathBuf::from(path!("/")),
1295            PathBuf::from(path!("/code")),
1296            PathBuf::from(path!("/code/project1")),
1297            PathBuf::from(path!("/code/project1/.git")),
1298            PathBuf::from(path!("/code/project1/README.md")),
1299            PathBuf::from(path!("/code/project1/src")),
1300            PathBuf::from(path!("/code/project1/src/dir2")),
1301            PathBuf::from(path!("/code/project1/src/file1")),
1302            PathBuf::from(path!("/code/project1/src/main.rs")),
1303            PathBuf::from(path!("/code/project1/src/dir2/dir3")),
1304            PathBuf::from(path!("/code/project1/src/dir2/dir4")),
1305            PathBuf::from(path!("/code/project1/src/dir2/file2")),
1306            PathBuf::from(path!("/code/project1/src/dir2/dir3/file3")),
1307        ]
1308    );
1309    assert_eq!(
1310        remote_fs
1311            .load(path!("/code/project1/src/file1").as_ref())
1312            .await
1313            .unwrap(),
1314        "file 1 content"
1315    );
1316    assert_eq!(
1317        remote_fs
1318            .load(path!("/code/project1/src/dir2/file2").as_ref())
1319            .await
1320            .unwrap(),
1321        "file 2 content"
1322    );
1323    assert_eq!(
1324        remote_fs
1325            .load(path!("/code/project1/src/dir2/dir3/file3").as_ref())
1326            .await
1327            .unwrap(),
1328        ""
1329    );
1330}
1331
1332// TODO: this test fails on Windows.
1333#[cfg(not(windows))]
1334#[gpui::test]
1335async fn test_remote_git_diffs(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1336    let text_2 = "
1337        fn one() -> usize {
1338            1
1339        }
1340    "
1341    .unindent();
1342    let text_1 = "
1343        fn one() -> usize {
1344            0
1345        }
1346    "
1347    .unindent();
1348
1349    let fs = FakeFs::new(server_cx.executor());
1350    fs.insert_tree(
1351        "/code",
1352        json!({
1353            "project1": {
1354                ".git": {},
1355                "src": {
1356                    "lib.rs": text_2
1357                },
1358                "README.md": "# project 1",
1359            },
1360        }),
1361    )
1362    .await;
1363    fs.set_index_for_repo(
1364        Path::new("/code/project1/.git"),
1365        &[("src/lib.rs".into(), text_1.clone())],
1366    );
1367    fs.set_head_for_repo(
1368        Path::new("/code/project1/.git"),
1369        &[("src/lib.rs".into(), text_1.clone())],
1370        "deadbeef",
1371    );
1372
1373    let (project, _headless) = init_test(&fs, cx, server_cx).await;
1374    let (worktree, _) = project
1375        .update(cx, |project, cx| {
1376            project.find_or_create_worktree("/code/project1", true, cx)
1377        })
1378        .await
1379        .unwrap();
1380    let worktree_id = cx.update(|cx| worktree.read(cx).id());
1381    cx.executor().run_until_parked();
1382
1383    let buffer = project
1384        .update(cx, |project, cx| {
1385            project.open_buffer((worktree_id, Path::new("src/lib.rs")), cx)
1386        })
1387        .await
1388        .unwrap();
1389    let diff = project
1390        .update(cx, |project, cx| {
1391            project.open_uncommitted_diff(buffer.clone(), cx)
1392        })
1393        .await
1394        .unwrap();
1395
1396    diff.read_with(cx, |diff, cx| {
1397        assert_eq!(diff.base_text_string().unwrap(), text_1);
1398        assert_eq!(
1399            diff.secondary_diff()
1400                .unwrap()
1401                .read(cx)
1402                .base_text_string()
1403                .unwrap(),
1404            text_1
1405        );
1406    });
1407
1408    // stage the current buffer's contents
1409    fs.set_index_for_repo(
1410        Path::new("/code/project1/.git"),
1411        &[("src/lib.rs".into(), text_2.clone())],
1412    );
1413
1414    cx.executor().run_until_parked();
1415    diff.read_with(cx, |diff, cx| {
1416        assert_eq!(diff.base_text_string().unwrap(), text_1);
1417        assert_eq!(
1418            diff.secondary_diff()
1419                .unwrap()
1420                .read(cx)
1421                .base_text_string()
1422                .unwrap(),
1423            text_2
1424        );
1425    });
1426
1427    // commit the current buffer's contents
1428    fs.set_head_for_repo(
1429        Path::new("/code/project1/.git"),
1430        &[("src/lib.rs".into(), text_2.clone())],
1431        "deadbeef",
1432    );
1433
1434    cx.executor().run_until_parked();
1435    diff.read_with(cx, |diff, cx| {
1436        assert_eq!(diff.base_text_string().unwrap(), text_2);
1437        assert_eq!(
1438            diff.secondary_diff()
1439                .unwrap()
1440                .read(cx)
1441                .base_text_string()
1442                .unwrap(),
1443            text_2
1444        );
1445    });
1446}
1447
1448// TODO: this test fails on Windows.
1449#[cfg(not(windows))]
1450#[gpui::test]
1451async fn test_remote_git_diffs_when_recv_update_repository_delay(
1452    cx: &mut TestAppContext,
1453    server_cx: &mut TestAppContext,
1454) {
1455    use editor::Editor;
1456    use gpui::VisualContext;
1457    let text_2 = "
1458        fn one() -> usize {
1459            1
1460        }
1461    "
1462    .unindent();
1463    let text_1 = "
1464        fn one() -> usize {
1465            0
1466        }
1467    "
1468    .unindent();
1469
1470    let fs = FakeFs::new(server_cx.executor());
1471    fs.insert_tree(
1472        "/code",
1473        json!({
1474            "project1": {
1475                "src": {
1476                    "lib.rs": text_2
1477                },
1478                "README.md": "# project 1",
1479            },
1480        }),
1481    )
1482    .await;
1483
1484    let (project, _headless) = init_test(&fs, cx, server_cx).await;
1485    let (worktree, _) = project
1486        .update(cx, |project, cx| {
1487            project.find_or_create_worktree("/code/project1", true, cx)
1488        })
1489        .await
1490        .unwrap();
1491    let worktree_id = cx.update(|cx| worktree.read(cx).id());
1492    let buffer = project
1493        .update(cx, |project, cx| {
1494            project.open_buffer((worktree_id, Path::new("src/lib.rs")), cx)
1495        })
1496        .await
1497        .unwrap();
1498    let buffer_id = cx.update(|cx| buffer.read(cx).remote_id());
1499    cx.update(|cx| {
1500        workspace::init_settings(cx);
1501        editor::init_settings(cx);
1502    });
1503    let cx = cx.add_empty_window();
1504    let editor = cx.new_window_entity(|window, cx| {
1505        Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1506    });
1507
1508    // Remote server will send proto::UpdateRepository after the instance of Editor create.
1509    fs.insert_tree(
1510        "/code",
1511        json!({
1512            "project1": {
1513                ".git": {},
1514            },
1515        }),
1516    )
1517    .await;
1518
1519    fs.set_index_for_repo(
1520        Path::new("/code/project1/.git"),
1521        &[("src/lib.rs".into(), text_1.clone())],
1522    );
1523    fs.set_head_for_repo(
1524        Path::new("/code/project1/.git"),
1525        &[("src/lib.rs".into(), text_1.clone())],
1526        "sha",
1527    );
1528
1529    cx.executor().run_until_parked();
1530    let diff = editor
1531        .read_with(cx, |editor, cx| {
1532            editor
1533                .buffer()
1534                .read_with(cx, |buffer, _| buffer.diff_for(buffer_id))
1535        })
1536        .unwrap();
1537
1538    diff.read_with(cx, |diff, cx| {
1539        assert_eq!(diff.base_text_string().unwrap(), text_1);
1540        assert_eq!(
1541            diff.secondary_diff()
1542                .unwrap()
1543                .read(cx)
1544                .base_text_string()
1545                .unwrap(),
1546            text_1
1547        );
1548    });
1549
1550    // stage the current buffer's contents
1551    fs.set_index_for_repo(
1552        Path::new("/code/project1/.git"),
1553        &[("src/lib.rs".into(), text_2.clone())],
1554    );
1555
1556    cx.executor().run_until_parked();
1557    diff.read_with(cx, |diff, cx| {
1558        assert_eq!(diff.base_text_string().unwrap(), text_1);
1559        assert_eq!(
1560            diff.secondary_diff()
1561                .unwrap()
1562                .read(cx)
1563                .base_text_string()
1564                .unwrap(),
1565            text_2
1566        );
1567    });
1568
1569    // commit the current buffer's contents
1570    fs.set_head_for_repo(
1571        Path::new("/code/project1/.git"),
1572        &[("src/lib.rs".into(), text_2.clone())],
1573        "sha",
1574    );
1575
1576    cx.executor().run_until_parked();
1577    diff.read_with(cx, |diff, cx| {
1578        assert_eq!(diff.base_text_string().unwrap(), text_2);
1579        assert_eq!(
1580            diff.secondary_diff()
1581                .unwrap()
1582                .read(cx)
1583                .base_text_string()
1584                .unwrap(),
1585            text_2
1586        );
1587    });
1588}
1589
1590#[gpui::test]
1591async fn test_remote_git_branches(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1592    let fs = FakeFs::new(server_cx.executor());
1593    fs.insert_tree(
1594        path!("/code"),
1595        json!({
1596            "project1": {
1597                ".git": {},
1598                "README.md": "# project 1",
1599            },
1600        }),
1601    )
1602    .await;
1603
1604    let (project, headless_project) = init_test(&fs, cx, server_cx).await;
1605    let branches = ["main", "dev", "feature-1"];
1606    let branches_set = branches
1607        .iter()
1608        .map(ToString::to_string)
1609        .collect::<HashSet<_>>();
1610    fs.insert_branches(Path::new(path!("/code/project1/.git")), &branches);
1611
1612    let (_worktree, _) = project
1613        .update(cx, |project, cx| {
1614            project.find_or_create_worktree(path!("/code/project1"), true, cx)
1615        })
1616        .await
1617        .unwrap();
1618    // Give the worktree a bit of time to index the file system
1619    cx.run_until_parked();
1620
1621    let repository = project.update(cx, |project, cx| project.active_repository(cx).unwrap());
1622
1623    let remote_branches = repository
1624        .update(cx, |repository, _| repository.branches())
1625        .await
1626        .unwrap()
1627        .unwrap();
1628
1629    let new_branch = branches[2];
1630
1631    let remote_branches = remote_branches
1632        .into_iter()
1633        .map(|branch| branch.name().to_string())
1634        .collect::<HashSet<_>>();
1635
1636    assert_eq!(&remote_branches, &branches_set);
1637
1638    cx.update(|cx| {
1639        repository.update(cx, |repository, _cx| {
1640            repository.change_branch(new_branch.to_string())
1641        })
1642    })
1643    .await
1644    .unwrap()
1645    .unwrap();
1646
1647    cx.run_until_parked();
1648
1649    let server_branch = server_cx.update(|cx| {
1650        headless_project.update(cx, |headless_project, cx| {
1651            headless_project.git_store.update(cx, |git_store, cx| {
1652                git_store
1653                    .repositories()
1654                    .values()
1655                    .next()
1656                    .unwrap()
1657                    .read(cx)
1658                    .branch
1659                    .as_ref()
1660                    .unwrap()
1661                    .clone()
1662            })
1663        })
1664    });
1665
1666    assert_eq!(server_branch.name(), branches[2]);
1667
1668    // Also try creating a new branch
1669    cx.update(|cx| {
1670        repository.update(cx, |repo, _cx| {
1671            repo.create_branch("totally-new-branch".to_string())
1672        })
1673    })
1674    .await
1675    .unwrap()
1676    .unwrap();
1677
1678    cx.update(|cx| {
1679        repository.update(cx, |repo, _cx| {
1680            repo.change_branch("totally-new-branch".to_string())
1681        })
1682    })
1683    .await
1684    .unwrap()
1685    .unwrap();
1686
1687    cx.run_until_parked();
1688
1689    let server_branch = server_cx.update(|cx| {
1690        headless_project.update(cx, |headless_project, cx| {
1691            headless_project.git_store.update(cx, |git_store, cx| {
1692                git_store
1693                    .repositories()
1694                    .values()
1695                    .next()
1696                    .unwrap()
1697                    .read(cx)
1698                    .branch
1699                    .as_ref()
1700                    .unwrap()
1701                    .clone()
1702            })
1703        })
1704    });
1705
1706    assert_eq!(server_branch.name(), "totally-new-branch");
1707}
1708
1709#[gpui::test]
1710async fn test_remote_agent_fs_tool_calls(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
1711    let fs = FakeFs::new(server_cx.executor());
1712    fs.insert_tree(
1713        path!("/project"),
1714        json!({
1715            "a.txt": "A",
1716            "b.txt": "B",
1717        }),
1718    )
1719    .await;
1720
1721    let (project, _headless_project) = init_test(&fs, cx, server_cx).await;
1722    project
1723        .update(cx, |project, cx| {
1724            project.find_or_create_worktree(path!("/project"), true, cx)
1725        })
1726        .await
1727        .unwrap();
1728
1729    let action_log = cx.new(|_| action_log::ActionLog::new(project.clone()));
1730    let model = Arc::new(FakeLanguageModel::default());
1731    let request = Arc::new(LanguageModelRequest::default());
1732
1733    let input = ReadFileToolInput {
1734        path: "project/b.txt".into(),
1735        start_line: None,
1736        end_line: None,
1737    };
1738    let exists_result = cx.update(|cx| {
1739        ReadFileTool::run(
1740            Arc::new(ReadFileTool),
1741            serde_json::to_value(input).unwrap(),
1742            request.clone(),
1743            project.clone(),
1744            action_log.clone(),
1745            model.clone(),
1746            None,
1747            cx,
1748        )
1749    });
1750    let output = exists_result.output.await.unwrap().content;
1751    assert_eq!(output, ToolResultContent::Text("B".to_string()));
1752
1753    let input = ReadFileToolInput {
1754        path: "project/c.txt".into(),
1755        start_line: None,
1756        end_line: None,
1757    };
1758    let does_not_exist_result = cx.update(|cx| {
1759        ReadFileTool::run(
1760            Arc::new(ReadFileTool),
1761            serde_json::to_value(input).unwrap(),
1762            request.clone(),
1763            project.clone(),
1764            action_log.clone(),
1765            model.clone(),
1766            None,
1767            cx,
1768        )
1769    });
1770    does_not_exist_result.output.await.unwrap_err();
1771}
1772
1773pub async fn init_test(
1774    server_fs: &Arc<FakeFs>,
1775    cx: &mut TestAppContext,
1776    server_cx: &mut TestAppContext,
1777) -> (Entity<Project>, Entity<HeadlessProject>) {
1778    let server_fs = server_fs.clone();
1779    cx.update(|cx| {
1780        release_channel::init(SemanticVersion::default(), cx);
1781    });
1782    server_cx.update(|cx| {
1783        release_channel::init(SemanticVersion::default(), cx);
1784    });
1785    init_logger();
1786
1787    let (opts, ssh_server_client) = RemoteClient::fake_server(cx, server_cx);
1788    let http_client = Arc::new(BlockedHttpClient);
1789    let node_runtime = NodeRuntime::unavailable();
1790    let languages = Arc::new(LanguageRegistry::new(cx.executor()));
1791    let proxy = Arc::new(ExtensionHostProxy::new());
1792    server_cx.update(HeadlessProject::init);
1793    let headless = server_cx.new(|cx| {
1794        client::init_settings(cx);
1795
1796        HeadlessProject::new(
1797            crate::HeadlessAppState {
1798                session: ssh_server_client,
1799                fs: server_fs.clone(),
1800                http_client,
1801                node_runtime,
1802                languages,
1803                extension_host_proxy: proxy,
1804            },
1805            cx,
1806        )
1807    });
1808
1809    let ssh = RemoteClient::fake_client(opts, cx).await;
1810    let project = build_project(ssh, cx);
1811    project
1812        .update(cx, {
1813            let headless = headless.clone();
1814            |_, cx| cx.on_release(|_, _| drop(headless))
1815        })
1816        .detach();
1817    (project, headless)
1818}
1819
1820fn init_logger() {
1821    zlog::init_test();
1822}
1823
1824fn build_project(ssh: Entity<RemoteClient>, cx: &mut TestAppContext) -> Entity<Project> {
1825    cx.update(|cx| {
1826        if !cx.has_global::<SettingsStore>() {
1827            let settings_store = SettingsStore::test(cx);
1828            cx.set_global(settings_store);
1829        }
1830    });
1831
1832    let client = cx.update(|cx| {
1833        Client::new(
1834            Arc::new(FakeSystemClock::new()),
1835            FakeHttpClient::with_404_response(),
1836            cx,
1837        )
1838    });
1839
1840    let node = NodeRuntime::unavailable();
1841    let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1842    let languages = Arc::new(LanguageRegistry::test(cx.executor()));
1843    let fs = FakeFs::new(cx.executor());
1844
1845    cx.update(|cx| {
1846        Project::init(&client, cx);
1847        language::init(cx);
1848    });
1849
1850    cx.update(|cx| Project::remote(ssh, client, node, user_store, languages, fs, cx))
1851}