worktree_store.rs

   1use std::{
   2    path::{Path, PathBuf},
   3    sync::{Arc, atomic::AtomicUsize},
   4};
   5
   6use anyhow::{Context as _, Result, anyhow, bail};
   7use collections::HashMap;
   8use fs::{Fs, copy_recursive};
   9use futures::{FutureExt, future::Shared};
  10use gpui::{
  11    App, AppContext as _, AsyncApp, Context, Entity, EntityId, EventEmitter, Task, WeakEntity,
  12};
  13use rpc::{
  14    AnyProtoClient, ErrorExt, TypedEnvelope,
  15    proto::{self, REMOTE_SERVER_PROJECT_ID},
  16};
  17use text::ReplicaId;
  18use util::{
  19    ResultExt,
  20    paths::{PathStyle, RemotePathBuf, SanitizedPath},
  21    rel_path::RelPath,
  22};
  23use worktree::{
  24    CreatedEntry, Entry, ProjectEntryId, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree,
  25    WorktreeId,
  26};
  27
  28use crate::ProjectPath;
  29
  30enum WorktreeStoreState {
  31    Local {
  32        fs: Arc<dyn Fs>,
  33    },
  34    Remote {
  35        upstream_client: AnyProtoClient,
  36        upstream_project_id: u64,
  37        path_style: PathStyle,
  38    },
  39}
  40
  41pub struct WorktreeStore {
  42    next_entry_id: Arc<AtomicUsize>,
  43    downstream_client: Option<(AnyProtoClient, u64)>,
  44    retain_worktrees: bool,
  45    worktrees: Vec<WorktreeHandle>,
  46    worktrees_reordered: bool,
  47    scanning_enabled: bool,
  48    #[allow(clippy::type_complexity)]
  49    loading_worktrees:
  50        HashMap<Arc<SanitizedPath>, Shared<Task<Result<Entity<Worktree>, Arc<anyhow::Error>>>>>,
  51    state: WorktreeStoreState,
  52}
  53
  54#[derive(Debug)]
  55pub enum WorktreeStoreEvent {
  56    WorktreeAdded(Entity<Worktree>),
  57    WorktreeRemoved(EntityId, WorktreeId),
  58    WorktreeReleased(EntityId, WorktreeId),
  59    WorktreeOrderChanged,
  60    WorktreeUpdateSent(Entity<Worktree>),
  61    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
  62    WorktreeUpdatedGitRepositories(WorktreeId, UpdatedGitRepositoriesSet),
  63    WorktreeDeletedEntry(WorktreeId, ProjectEntryId),
  64}
  65
  66impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
  67
  68impl WorktreeStore {
  69    pub fn init(client: &AnyProtoClient) {
  70        client.add_entity_request_handler(Self::handle_create_project_entry);
  71        client.add_entity_request_handler(Self::handle_copy_project_entry);
  72        client.add_entity_request_handler(Self::handle_delete_project_entry);
  73        client.add_entity_request_handler(Self::handle_expand_project_entry);
  74        client.add_entity_request_handler(Self::handle_expand_all_for_project_entry);
  75    }
  76
  77    pub fn local(retain_worktrees: bool, fs: Arc<dyn Fs>) -> Self {
  78        Self {
  79            next_entry_id: Default::default(),
  80            loading_worktrees: Default::default(),
  81            downstream_client: None,
  82            worktrees: Vec::new(),
  83            worktrees_reordered: false,
  84            scanning_enabled: true,
  85            retain_worktrees,
  86            state: WorktreeStoreState::Local { fs },
  87        }
  88    }
  89
  90    pub fn remote(
  91        retain_worktrees: bool,
  92        upstream_client: AnyProtoClient,
  93        upstream_project_id: u64,
  94        path_style: PathStyle,
  95    ) -> Self {
  96        Self {
  97            next_entry_id: Default::default(),
  98            loading_worktrees: Default::default(),
  99            downstream_client: None,
 100            worktrees: Vec::new(),
 101            worktrees_reordered: false,
 102            scanning_enabled: true,
 103            retain_worktrees,
 104            state: WorktreeStoreState::Remote {
 105                upstream_client,
 106                upstream_project_id,
 107                path_style,
 108            },
 109        }
 110    }
 111
 112    pub fn disable_scanner(&mut self) {
 113        self.scanning_enabled = false;
 114    }
 115
 116    /// Iterates through all worktrees, including ones that don't appear in the project panel
 117    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Entity<Worktree>> {
 118        self.worktrees
 119            .iter()
 120            .filter_map(move |worktree| worktree.upgrade())
 121    }
 122
 123    /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
 124    pub fn visible_worktrees<'a>(
 125        &'a self,
 126        cx: &'a App,
 127    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
 128        self.worktrees()
 129            .filter(|worktree| worktree.read(cx).is_visible())
 130    }
 131
 132    /// Iterates through all user-visible worktrees (directories and files that appear in the project panel) and other, invisible single files that could appear e.g. due to drag and drop.
 133    pub fn visible_worktrees_and_single_files<'a>(
 134        &'a self,
 135        cx: &'a App,
 136    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
 137        self.worktrees()
 138            .filter(|worktree| worktree.read(cx).is_visible() || worktree.read(cx).is_single_file())
 139    }
 140
 141    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
 142        self.worktrees()
 143            .find(|worktree| worktree.read(cx).id() == id)
 144    }
 145
 146    pub fn worktree_for_entry(
 147        &self,
 148        entry_id: ProjectEntryId,
 149        cx: &App,
 150    ) -> Option<Entity<Worktree>> {
 151        self.worktrees()
 152            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 153    }
 154
 155    pub fn find_worktree(
 156        &self,
 157        abs_path: impl AsRef<Path>,
 158        cx: &App,
 159    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
 160        let abs_path = SanitizedPath::new(abs_path.as_ref());
 161        for tree in self.worktrees() {
 162            let path_style = tree.read(cx).path_style();
 163            if let Ok(relative_path) = abs_path.as_ref().strip_prefix(tree.read(cx).abs_path())
 164                && let Ok(relative_path) = RelPath::new(relative_path, path_style)
 165            {
 166                return Some((tree.clone(), relative_path.into_arc()));
 167            }
 168        }
 169        None
 170    }
 171
 172    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
 173        self.find_worktree(abs_path, cx)
 174            .map(|(worktree, relative_path)| ProjectPath {
 175                worktree_id: worktree.read(cx).id(),
 176                path: relative_path,
 177            })
 178    }
 179
 180    pub fn absolutize(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
 181        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 182        Some(worktree.read(cx).absolutize(&project_path.path))
 183    }
 184
 185    pub fn path_style(&self) -> PathStyle {
 186        match &self.state {
 187            WorktreeStoreState::Local { .. } => PathStyle::local(),
 188            WorktreeStoreState::Remote { path_style, .. } => *path_style,
 189        }
 190    }
 191
 192    pub fn find_or_create_worktree(
 193        &mut self,
 194        abs_path: impl AsRef<Path>,
 195        visible: bool,
 196        cx: &mut Context<Self>,
 197    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
 198        let abs_path = abs_path.as_ref();
 199        if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
 200            Task::ready(Ok((tree, relative_path)))
 201        } else {
 202            let worktree = self.create_worktree(abs_path, visible, cx);
 203            cx.background_spawn(async move { Ok((worktree.await?, RelPath::empty().into())) })
 204        }
 205    }
 206
 207    pub fn entry_for_id<'a>(&'a self, entry_id: ProjectEntryId, cx: &'a App) -> Option<&'a Entry> {
 208        self.worktrees()
 209            .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
 210    }
 211
 212    pub fn worktree_and_entry_for_id<'a>(
 213        &'a self,
 214        entry_id: ProjectEntryId,
 215        cx: &'a App,
 216    ) -> Option<(Entity<Worktree>, &'a Entry)> {
 217        self.worktrees().find_map(|worktree| {
 218            worktree
 219                .read(cx)
 220                .entry_for_id(entry_id)
 221                .map(|e| (worktree.clone(), e))
 222        })
 223    }
 224
 225    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
 226        self.worktree_for_id(path.worktree_id, cx)?
 227            .read(cx)
 228            .entry_for_path(&path.path)
 229    }
 230
 231    pub fn copy_entry(
 232        &mut self,
 233        entry_id: ProjectEntryId,
 234        new_project_path: ProjectPath,
 235        cx: &mut Context<Self>,
 236    ) -> Task<Result<Option<Entry>>> {
 237        let Some(old_worktree) = self.worktree_for_entry(entry_id, cx) else {
 238            return Task::ready(Err(anyhow!("no such worktree")));
 239        };
 240        let Some(old_entry) = old_worktree.read(cx).entry_for_id(entry_id) else {
 241            return Task::ready(Err(anyhow!("no such entry")));
 242        };
 243        let Some(new_worktree) = self.worktree_for_id(new_project_path.worktree_id, cx) else {
 244            return Task::ready(Err(anyhow!("no such worktree")));
 245        };
 246
 247        match &self.state {
 248            WorktreeStoreState::Local { fs } => {
 249                let old_abs_path = old_worktree.read(cx).absolutize(&old_entry.path);
 250                let new_abs_path = new_worktree.read(cx).absolutize(&new_project_path.path);
 251                let fs = fs.clone();
 252                let copy = cx.background_spawn(async move {
 253                    copy_recursive(
 254                        fs.as_ref(),
 255                        &old_abs_path,
 256                        &new_abs_path,
 257                        Default::default(),
 258                    )
 259                    .await
 260                });
 261
 262                cx.spawn(async move |_, cx| {
 263                    copy.await?;
 264                    new_worktree
 265                        .update(cx, |this, cx| {
 266                            this.as_local_mut().unwrap().refresh_entry(
 267                                new_project_path.path,
 268                                None,
 269                                cx,
 270                            )
 271                        })?
 272                        .await
 273                })
 274            }
 275            WorktreeStoreState::Remote {
 276                upstream_client,
 277                upstream_project_id,
 278                ..
 279            } => {
 280                let response = upstream_client.request(proto::CopyProjectEntry {
 281                    project_id: *upstream_project_id,
 282                    entry_id: entry_id.to_proto(),
 283                    new_path: new_project_path.path.to_proto(),
 284                    new_worktree_id: new_project_path.worktree_id.to_proto(),
 285                });
 286                cx.spawn(async move |_, cx| {
 287                    let response = response.await?;
 288                    match response.entry {
 289                        Some(entry) => new_worktree
 290                            .update(cx, |worktree, cx| {
 291                                worktree.as_remote_mut().unwrap().insert_entry(
 292                                    entry,
 293                                    response.worktree_scan_id as usize,
 294                                    cx,
 295                                )
 296                            })?
 297                            .await
 298                            .map(Some),
 299                        None => Ok(None),
 300                    }
 301                })
 302            }
 303        }
 304    }
 305
 306    pub fn rename_entry(
 307        &mut self,
 308        entry_id: ProjectEntryId,
 309        new_project_path: ProjectPath,
 310        cx: &mut Context<Self>,
 311    ) -> Task<Result<CreatedEntry>> {
 312        let Some(old_worktree) = self.worktree_for_entry(entry_id, cx) else {
 313            return Task::ready(Err(anyhow!("no such worktree")));
 314        };
 315        let Some(old_entry) = old_worktree.read(cx).entry_for_id(entry_id).cloned() else {
 316            return Task::ready(Err(anyhow!("no such entry")));
 317        };
 318        let Some(new_worktree) = self.worktree_for_id(new_project_path.worktree_id, cx) else {
 319            return Task::ready(Err(anyhow!("no such worktree")));
 320        };
 321
 322        match &self.state {
 323            WorktreeStoreState::Local { fs } => {
 324                let abs_old_path = old_worktree.read(cx).absolutize(&old_entry.path);
 325                let new_worktree_ref = new_worktree.read(cx);
 326                let is_root_entry = new_worktree_ref
 327                    .root_entry()
 328                    .is_some_and(|e| e.id == entry_id);
 329                let abs_new_path = if is_root_entry {
 330                    let abs_path = new_worktree_ref.abs_path();
 331                    let Some(root_parent_path) = abs_path.parent() else {
 332                        return Task::ready(Err(anyhow!("no parent for path {:?}", abs_path)));
 333                    };
 334                    root_parent_path.join(new_project_path.path.as_std_path())
 335                } else {
 336                    new_worktree_ref.absolutize(&new_project_path.path)
 337                };
 338
 339                let fs = fs.clone();
 340                let case_sensitive = new_worktree
 341                    .read(cx)
 342                    .as_local()
 343                    .unwrap()
 344                    .fs_is_case_sensitive();
 345
 346                let do_rename =
 347                    async move |fs: &dyn Fs, old_path: &Path, new_path: &Path, overwrite| {
 348                        fs.rename(
 349                            &old_path,
 350                            &new_path,
 351                            fs::RenameOptions {
 352                                overwrite,
 353                                ..fs::RenameOptions::default()
 354                            },
 355                        )
 356                        .await
 357                        .with_context(|| format!("renaming {old_path:?} into {new_path:?}"))
 358                    };
 359
 360                let rename = cx.background_spawn({
 361                    let abs_new_path = abs_new_path.clone();
 362                    async move {
 363                        // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
 364                        // we want to overwrite, because otherwise we run into a file-already-exists error.
 365                        let overwrite = !case_sensitive
 366                            && abs_old_path != abs_new_path
 367                            && abs_old_path.to_str().map(|p| p.to_lowercase())
 368                                == abs_new_path.to_str().map(|p| p.to_lowercase());
 369
 370                        // The directory we're renaming into might not exist yet
 371                        if let Err(e) =
 372                            do_rename(fs.as_ref(), &abs_old_path, &abs_new_path, overwrite).await
 373                        {
 374                            if let Some(err) = e.downcast_ref::<std::io::Error>()
 375                                && err.kind() == std::io::ErrorKind::NotFound
 376                            {
 377                                if let Some(parent) = abs_new_path.parent() {
 378                                    fs.create_dir(parent).await.with_context(|| {
 379                                        format!("creating parent directory {parent:?}")
 380                                    })?;
 381                                    return do_rename(
 382                                        fs.as_ref(),
 383                                        &abs_old_path,
 384                                        &abs_new_path,
 385                                        overwrite,
 386                                    )
 387                                    .await;
 388                                }
 389                            }
 390                            return Err(e);
 391                        }
 392                        Ok(())
 393                    }
 394                });
 395
 396                cx.spawn(async move |_, cx| {
 397                    rename.await?;
 398                    Ok(new_worktree
 399                        .update(cx, |this, cx| {
 400                            let local = this.as_local_mut().unwrap();
 401                            if is_root_entry {
 402                                // We eagerly update `abs_path` and refresh this worktree.
 403                                // Otherwise, the FS watcher would do it on the `RootUpdated` event,
 404                                // but with a noticeable delay, so we handle it proactively.
 405                                local.update_abs_path_and_refresh(
 406                                    SanitizedPath::new_arc(&abs_new_path),
 407                                    cx,
 408                                );
 409                                Task::ready(Ok(this.root_entry().cloned()))
 410                            } else {
 411                                // First refresh the parent directory (in case it was newly created)
 412                                if let Some(parent) = new_project_path.path.parent() {
 413                                    let _ = local.refresh_entries_for_paths(vec![parent.into()]);
 414                                }
 415                                // Then refresh the new path
 416                                local.refresh_entry(
 417                                    new_project_path.path.clone(),
 418                                    Some(old_entry.path),
 419                                    cx,
 420                                )
 421                            }
 422                        })?
 423                        .await?
 424                        .map(CreatedEntry::Included)
 425                        .unwrap_or_else(|| CreatedEntry::Excluded {
 426                            abs_path: abs_new_path,
 427                        }))
 428                })
 429            }
 430            WorktreeStoreState::Remote {
 431                upstream_client,
 432                upstream_project_id,
 433                ..
 434            } => {
 435                let response = upstream_client.request(proto::RenameProjectEntry {
 436                    project_id: *upstream_project_id,
 437                    entry_id: entry_id.to_proto(),
 438                    new_path: new_project_path.path.to_proto(),
 439                    new_worktree_id: new_project_path.worktree_id.to_proto(),
 440                });
 441                cx.spawn(async move |_, cx| {
 442                    let response = response.await?;
 443                    match response.entry {
 444                        Some(entry) => new_worktree
 445                            .update(cx, |worktree, cx| {
 446                                worktree.as_remote_mut().unwrap().insert_entry(
 447                                    entry,
 448                                    response.worktree_scan_id as usize,
 449                                    cx,
 450                                )
 451                            })?
 452                            .await
 453                            .map(CreatedEntry::Included),
 454                        None => {
 455                            let abs_path = new_worktree.read_with(cx, |worktree, _| {
 456                                worktree.absolutize(&new_project_path.path)
 457                            })?;
 458                            Ok(CreatedEntry::Excluded { abs_path })
 459                        }
 460                    }
 461                })
 462            }
 463        }
 464    }
 465    pub fn create_worktree(
 466        &mut self,
 467        abs_path: impl AsRef<Path>,
 468        visible: bool,
 469        cx: &mut Context<Self>,
 470    ) -> Task<Result<Entity<Worktree>>> {
 471        let abs_path: Arc<SanitizedPath> = SanitizedPath::new_arc(&abs_path);
 472        if !self.loading_worktrees.contains_key(&abs_path) {
 473            let task = match &self.state {
 474                WorktreeStoreState::Remote {
 475                    upstream_client,
 476                    path_style,
 477                    ..
 478                } => {
 479                    if upstream_client.is_via_collab() {
 480                        Task::ready(Err(Arc::new(anyhow!("cannot create worktrees via collab"))))
 481                    } else {
 482                        let abs_path = RemotePathBuf::new(abs_path.to_string(), *path_style);
 483                        self.create_remote_worktree(upstream_client.clone(), abs_path, visible, cx)
 484                    }
 485                }
 486                WorktreeStoreState::Local { fs } => {
 487                    self.create_local_worktree(fs.clone(), abs_path.clone(), visible, cx)
 488                }
 489            };
 490
 491            self.loading_worktrees
 492                .insert(abs_path.clone(), task.shared());
 493        }
 494        let task = self.loading_worktrees.get(&abs_path).unwrap().clone();
 495        cx.spawn(async move |this, cx| {
 496            let result = task.await;
 497            this.update(cx, |this, _| this.loading_worktrees.remove(&abs_path))
 498                .ok();
 499            match result {
 500                Ok(worktree) => Ok(worktree),
 501                Err(err) => Err((*err).cloned()),
 502            }
 503        })
 504    }
 505
 506    fn create_remote_worktree(
 507        &mut self,
 508        client: AnyProtoClient,
 509        abs_path: RemotePathBuf,
 510        visible: bool,
 511        cx: &mut Context<Self>,
 512    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
 513        let path_style = abs_path.path_style();
 514        let mut abs_path = abs_path.to_string();
 515        // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
 516        // in which case want to strip the leading the `/`.
 517        // On the host-side, the `~` will get expanded.
 518        // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
 519        if abs_path.starts_with("/~") {
 520            abs_path = abs_path[1..].to_string();
 521        }
 522        if abs_path.is_empty() {
 523            abs_path = "~/".to_string();
 524        }
 525
 526        cx.spawn(async move |this, cx| {
 527            let this = this.upgrade().context("Dropped worktree store")?;
 528
 529            let path = RemotePathBuf::new(abs_path, path_style);
 530            let response = client
 531                .request(proto::AddWorktree {
 532                    project_id: REMOTE_SERVER_PROJECT_ID,
 533                    path: path.to_proto(),
 534                    visible,
 535                })
 536                .await?;
 537
 538            if let Some(existing_worktree) = this.read_with(cx, |this, cx| {
 539                this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
 540            })? {
 541                return Ok(existing_worktree);
 542            }
 543
 544            let root_path_buf = PathBuf::from(response.canonicalized_path.clone());
 545            let root_name = root_path_buf
 546                .file_name()
 547                .map(|n| n.to_string_lossy().into_owned())
 548                .unwrap_or(root_path_buf.to_string_lossy().into_owned());
 549
 550            let worktree = cx.update(|cx| {
 551                Worktree::remote(
 552                    REMOTE_SERVER_PROJECT_ID,
 553                    ReplicaId::REMOTE_SERVER,
 554                    proto::WorktreeMetadata {
 555                        id: response.worktree_id,
 556                        root_name,
 557                        visible,
 558                        abs_path: response.canonicalized_path,
 559                    },
 560                    client,
 561                    path_style,
 562                    cx,
 563                )
 564            })?;
 565
 566            this.update(cx, |this, cx| {
 567                this.add(&worktree, cx);
 568            })?;
 569            Ok(worktree)
 570        })
 571    }
 572
 573    fn create_local_worktree(
 574        &mut self,
 575        fs: Arc<dyn Fs>,
 576        abs_path: Arc<SanitizedPath>,
 577        visible: bool,
 578        cx: &mut Context<Self>,
 579    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
 580        let next_entry_id = self.next_entry_id.clone();
 581        let scanning_enabled = self.scanning_enabled;
 582
 583        cx.spawn(async move |this, cx| {
 584            let worktree = Worktree::local(
 585                SanitizedPath::cast_arc(abs_path.clone()),
 586                visible,
 587                fs,
 588                next_entry_id,
 589                scanning_enabled,
 590                cx,
 591            )
 592            .await;
 593
 594            let worktree = worktree?;
 595
 596            this.update(cx, |this, cx| this.add(&worktree, cx))?;
 597
 598            if visible {
 599                cx.update(|cx| {
 600                    cx.add_recent_document(abs_path.as_path());
 601                })
 602                .log_err();
 603            }
 604
 605            Ok(worktree)
 606        })
 607    }
 608
 609    pub fn add(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
 610        let worktree_id = worktree.read(cx).id();
 611        debug_assert!(self.worktrees().all(|w| w.read(cx).id() != worktree_id));
 612
 613        let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
 614        let handle = if push_strong_handle {
 615            WorktreeHandle::Strong(worktree.clone())
 616        } else {
 617            WorktreeHandle::Weak(worktree.downgrade())
 618        };
 619        if self.worktrees_reordered {
 620            self.worktrees.push(handle);
 621        } else {
 622            let i = match self
 623                .worktrees
 624                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
 625                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
 626                }) {
 627                Ok(i) | Err(i) => i,
 628            };
 629            self.worktrees.insert(i, handle);
 630        }
 631
 632        cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
 633        self.send_project_updates(cx);
 634
 635        let handle_id = worktree.entity_id();
 636        cx.subscribe(worktree, |_, worktree, event, cx| {
 637            let worktree_id = worktree.read(cx).id();
 638            match event {
 639                worktree::Event::UpdatedEntries(changes) => {
 640                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedEntries(
 641                        worktree_id,
 642                        changes.clone(),
 643                    ));
 644                }
 645                worktree::Event::UpdatedGitRepositories(set) => {
 646                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedGitRepositories(
 647                        worktree_id,
 648                        set.clone(),
 649                    ));
 650                }
 651                worktree::Event::DeletedEntry(id) => {
 652                    cx.emit(WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, *id))
 653                }
 654            }
 655        })
 656        .detach();
 657        cx.observe_release(worktree, move |this, worktree, cx| {
 658            cx.emit(WorktreeStoreEvent::WorktreeReleased(
 659                handle_id,
 660                worktree.id(),
 661            ));
 662            cx.emit(WorktreeStoreEvent::WorktreeRemoved(
 663                handle_id,
 664                worktree.id(),
 665            ));
 666            this.send_project_updates(cx);
 667        })
 668        .detach();
 669    }
 670
 671    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
 672        self.worktrees.retain(|worktree| {
 673            if let Some(worktree) = worktree.upgrade() {
 674                if worktree.read(cx).id() == id_to_remove {
 675                    cx.emit(WorktreeStoreEvent::WorktreeRemoved(
 676                        worktree.entity_id(),
 677                        id_to_remove,
 678                    ));
 679                    false
 680                } else {
 681                    true
 682                }
 683            } else {
 684                false
 685            }
 686        });
 687        self.send_project_updates(cx);
 688    }
 689
 690    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
 691        self.worktrees_reordered = worktrees_reordered;
 692    }
 693
 694    fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
 695        match &self.state {
 696            WorktreeStoreState::Remote {
 697                upstream_client,
 698                upstream_project_id,
 699                ..
 700            } => Some((upstream_client.clone(), *upstream_project_id)),
 701            WorktreeStoreState::Local { .. } => None,
 702        }
 703    }
 704
 705    pub fn set_worktrees_from_proto(
 706        &mut self,
 707        worktrees: Vec<proto::WorktreeMetadata>,
 708        replica_id: ReplicaId,
 709        cx: &mut Context<Self>,
 710    ) -> Result<()> {
 711        let mut old_worktrees_by_id = self
 712            .worktrees
 713            .drain(..)
 714            .filter_map(|worktree| {
 715                let worktree = worktree.upgrade()?;
 716                Some((worktree.read(cx).id(), worktree))
 717            })
 718            .collect::<HashMap<_, _>>();
 719
 720        let (client, project_id) = self.upstream_client().context("invalid project")?;
 721
 722        for worktree in worktrees {
 723            if let Some(old_worktree) =
 724                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 725            {
 726                let push_strong_handle =
 727                    self.retain_worktrees || old_worktree.read(cx).is_visible();
 728                let handle = if push_strong_handle {
 729                    WorktreeHandle::Strong(old_worktree.clone())
 730                } else {
 731                    WorktreeHandle::Weak(old_worktree.downgrade())
 732                };
 733                self.worktrees.push(handle);
 734            } else {
 735                self.add(
 736                    &Worktree::remote(
 737                        project_id,
 738                        replica_id,
 739                        worktree,
 740                        client.clone(),
 741                        self.path_style(),
 742                        cx,
 743                    ),
 744                    cx,
 745                );
 746            }
 747        }
 748        self.send_project_updates(cx);
 749
 750        Ok(())
 751    }
 752
 753    pub fn move_worktree(
 754        &mut self,
 755        source: WorktreeId,
 756        destination: WorktreeId,
 757        cx: &mut Context<Self>,
 758    ) -> Result<()> {
 759        if source == destination {
 760            return Ok(());
 761        }
 762
 763        let mut source_index = None;
 764        let mut destination_index = None;
 765        for (i, worktree) in self.worktrees.iter().enumerate() {
 766            if let Some(worktree) = worktree.upgrade() {
 767                let worktree_id = worktree.read(cx).id();
 768                if worktree_id == source {
 769                    source_index = Some(i);
 770                    if destination_index.is_some() {
 771                        break;
 772                    }
 773                } else if worktree_id == destination {
 774                    destination_index = Some(i);
 775                    if source_index.is_some() {
 776                        break;
 777                    }
 778                }
 779            }
 780        }
 781
 782        let source_index =
 783            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
 784        let destination_index =
 785            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
 786
 787        if source_index == destination_index {
 788            return Ok(());
 789        }
 790
 791        let worktree_to_move = self.worktrees.remove(source_index);
 792        self.worktrees.insert(destination_index, worktree_to_move);
 793        self.worktrees_reordered = true;
 794        cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
 795        cx.notify();
 796        Ok(())
 797    }
 798
 799    pub fn disconnected_from_host(&mut self, cx: &mut App) {
 800        for worktree in &self.worktrees {
 801            if let Some(worktree) = worktree.upgrade() {
 802                worktree.update(cx, |worktree, _| {
 803                    if let Some(worktree) = worktree.as_remote_mut() {
 804                        worktree.disconnected_from_host();
 805                    }
 806                });
 807            }
 808        }
 809    }
 810
 811    pub fn send_project_updates(&mut self, cx: &mut Context<Self>) {
 812        let Some((downstream_client, project_id)) = self.downstream_client.clone() else {
 813            return;
 814        };
 815
 816        let update = proto::UpdateProject {
 817            project_id,
 818            worktrees: self.worktree_metadata_protos(cx),
 819        };
 820
 821        // collab has bad concurrency guarantees, so we send requests in serial.
 822        let update_project = if downstream_client.is_via_collab() {
 823            Some(downstream_client.request(update))
 824        } else {
 825            downstream_client.send(update).log_err();
 826            None
 827        };
 828        cx.spawn(async move |this, cx| {
 829            if let Some(update_project) = update_project {
 830                update_project.await?;
 831            }
 832
 833            this.update(cx, |this, cx| {
 834                let worktrees = this.worktrees().collect::<Vec<_>>();
 835
 836                for worktree in worktrees {
 837                    worktree.update(cx, |worktree, cx| {
 838                        let client = downstream_client.clone();
 839                        worktree.observe_updates(project_id, cx, {
 840                            move |update| {
 841                                let client = client.clone();
 842                                async move {
 843                                    if client.is_via_collab() {
 844                                        client
 845                                            .request(update)
 846                                            .map(|result| result.log_err().is_some())
 847                                            .await
 848                                    } else {
 849                                        client.send(update).log_err().is_some()
 850                                    }
 851                                }
 852                            }
 853                        });
 854                    });
 855
 856                    cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
 857                }
 858
 859                anyhow::Ok(())
 860            })
 861        })
 862        .detach_and_log_err(cx);
 863    }
 864
 865    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
 866        self.worktrees()
 867            .map(|worktree| {
 868                let worktree = worktree.read(cx);
 869                proto::WorktreeMetadata {
 870                    id: worktree.id().to_proto(),
 871                    root_name: worktree.root_name_str().to_owned(),
 872                    visible: worktree.is_visible(),
 873                    abs_path: worktree.abs_path().to_string_lossy().into_owned(),
 874                }
 875            })
 876            .collect()
 877    }
 878
 879    pub fn shared(
 880        &mut self,
 881        remote_id: u64,
 882        downstream_client: AnyProtoClient,
 883        cx: &mut Context<Self>,
 884    ) {
 885        self.retain_worktrees = true;
 886        self.downstream_client = Some((downstream_client, remote_id));
 887
 888        // When shared, retain all worktrees
 889        for worktree_handle in self.worktrees.iter_mut() {
 890            match worktree_handle {
 891                WorktreeHandle::Strong(_) => {}
 892                WorktreeHandle::Weak(worktree) => {
 893                    if let Some(worktree) = worktree.upgrade() {
 894                        *worktree_handle = WorktreeHandle::Strong(worktree);
 895                    }
 896                }
 897            }
 898        }
 899        self.send_project_updates(cx);
 900    }
 901
 902    pub fn unshared(&mut self, cx: &mut Context<Self>) {
 903        self.retain_worktrees = false;
 904        self.downstream_client.take();
 905
 906        // When not shared, only retain the visible worktrees
 907        for worktree_handle in self.worktrees.iter_mut() {
 908            if let WorktreeHandle::Strong(worktree) = worktree_handle {
 909                let is_visible = worktree.update(cx, |worktree, _| {
 910                    worktree.stop_observing_updates();
 911                    worktree.is_visible()
 912                });
 913                if !is_visible {
 914                    *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 915                }
 916            }
 917        }
 918    }
 919
 920    pub async fn handle_create_project_entry(
 921        this: Entity<Self>,
 922        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 923        mut cx: AsyncApp,
 924    ) -> Result<proto::ProjectEntryResponse> {
 925        let worktree = this.update(&mut cx, |this, cx| {
 926            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 927            this.worktree_for_id(worktree_id, cx)
 928                .context("worktree not found")
 929        })??;
 930        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
 931    }
 932
 933    pub async fn handle_copy_project_entry(
 934        this: Entity<Self>,
 935        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 936        mut cx: AsyncApp,
 937    ) -> Result<proto::ProjectEntryResponse> {
 938        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 939        let new_worktree_id = WorktreeId::from_proto(envelope.payload.new_worktree_id);
 940        let new_project_path = (
 941            new_worktree_id,
 942            RelPath::from_proto(&envelope.payload.new_path)?,
 943        );
 944        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
 945            let Some((_, project_id)) = this.downstream_client else {
 946                bail!("no downstream client")
 947            };
 948            let Some(entry) = this.entry_for_id(entry_id, cx) else {
 949                bail!("no such entry");
 950            };
 951            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
 952                bail!("entry is private")
 953            }
 954
 955            let new_worktree = this
 956                .worktree_for_id(new_worktree_id, cx)
 957                .context("no such worktree")?;
 958            let scan_id = new_worktree.read(cx).scan_id();
 959            anyhow::Ok((
 960                scan_id,
 961                this.copy_entry(entry_id, new_project_path.into(), cx),
 962            ))
 963        })??;
 964        let entry = entry.await?;
 965        Ok(proto::ProjectEntryResponse {
 966            entry: entry.as_ref().map(|entry| entry.into()),
 967            worktree_scan_id: scan_id as u64,
 968        })
 969    }
 970
 971    pub async fn handle_delete_project_entry(
 972        this: Entity<Self>,
 973        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 974        mut cx: AsyncApp,
 975    ) -> Result<proto::ProjectEntryResponse> {
 976        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 977        let worktree = this.update(&mut cx, |this, cx| {
 978            let Some((_, project_id)) = this.downstream_client else {
 979                bail!("no downstream client")
 980            };
 981            let Some(entry) = this.entry_for_id(entry_id, cx) else {
 982                bail!("no entry")
 983            };
 984            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
 985                bail!("entry is private")
 986            }
 987            this.worktree_for_entry(entry_id, cx)
 988                .context("worktree not found")
 989        })??;
 990        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
 991    }
 992
 993    pub async fn handle_rename_project_entry(
 994        this: Entity<Self>,
 995        request: proto::RenameProjectEntry,
 996        mut cx: AsyncApp,
 997    ) -> Result<proto::ProjectEntryResponse> {
 998        let entry_id = ProjectEntryId::from_proto(request.entry_id);
 999        let new_worktree_id = WorktreeId::from_proto(request.new_worktree_id);
1000        let rel_path = RelPath::from_proto(&request.new_path)
1001            .with_context(|| format!("received invalid relative path {:?}", &request.new_path))?;
1002
1003        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1004            let worktree = this
1005                .worktree_for_entry(entry_id, cx)
1006                .context("no such worktree")?;
1007
1008            let Some((_, project_id)) = this.downstream_client else {
1009                bail!("no downstream client")
1010            };
1011            let entry = worktree
1012                .read(cx)
1013                .entry_for_id(entry_id)
1014                .ok_or_else(|| anyhow!("missing entry"))?;
1015            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1016                bail!("entry is private")
1017            }
1018
1019            let scan_id = worktree.read(cx).scan_id();
1020            anyhow::Ok((
1021                scan_id,
1022                this.rename_entry(entry_id, (new_worktree_id, rel_path).into(), cx),
1023            ))
1024        })??;
1025        Ok(proto::ProjectEntryResponse {
1026            entry: match &task.await? {
1027                CreatedEntry::Included(entry) => Some(entry.into()),
1028                CreatedEntry::Excluded { .. } => None,
1029            },
1030            worktree_scan_id: scan_id as u64,
1031        })
1032    }
1033
1034    pub async fn handle_expand_project_entry(
1035        this: Entity<Self>,
1036        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
1037        mut cx: AsyncApp,
1038    ) -> Result<proto::ExpandProjectEntryResponse> {
1039        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1040        let worktree = this
1041            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1042            .context("invalid request")?;
1043        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
1044    }
1045
1046    pub async fn handle_expand_all_for_project_entry(
1047        this: Entity<Self>,
1048        envelope: TypedEnvelope<proto::ExpandAllForProjectEntry>,
1049        mut cx: AsyncApp,
1050    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1051        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1052        let worktree = this
1053            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1054            .context("invalid request")?;
1055        Worktree::handle_expand_all_for_entry(worktree, envelope.payload, cx).await
1056    }
1057
1058    pub fn fs(&self) -> Option<Arc<dyn Fs>> {
1059        match &self.state {
1060            WorktreeStoreState::Local { fs } => Some(fs.clone()),
1061            WorktreeStoreState::Remote { .. } => None,
1062        }
1063    }
1064}
1065
1066#[derive(Clone, Debug)]
1067enum WorktreeHandle {
1068    Strong(Entity<Worktree>),
1069    Weak(WeakEntity<Worktree>),
1070}
1071
1072impl WorktreeHandle {
1073    fn upgrade(&self) -> Option<Entity<Worktree>> {
1074        match self {
1075            WorktreeHandle::Strong(handle) => Some(handle.clone()),
1076            WorktreeHandle::Weak(handle) => handle.upgrade(),
1077        }
1078    }
1079}