Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T03:56:14.265Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

worktree_store.rs

1519 lines · 57.8 KB · rust
1use std::{
2    future::Future,
3    path::{Path, PathBuf},
4    sync::{
5        Arc,
6        atomic::{AtomicU64, AtomicUsize},
7    },
8};
9
10use anyhow::{Context as _, Result, anyhow, bail};
11use collections::HashMap;
12use fs::{Fs, copy_recursive};
13use futures::{FutureExt, future::Shared};
14use gpui::{
15    App, AppContext as _, AsyncApp, Context, Entity, EntityId, EventEmitter, Global, Task, TaskExt,
16    WeakEntity,
17};
18use itertools::Either;
19use postage::{prelude::Stream as _, watch};
20use rpc::{
21    AnyProtoClient, ErrorExt, TypedEnvelope,
22    proto::{self, REMOTE_SERVER_PROJECT_ID},
23};
24use text::ReplicaId;
25use util::{
26    ResultExt,
27    path_list::PathList,
28    paths::{PathStyle, RemotePathBuf, SanitizedPath},
29    rel_path::RelPath,
30};
31use worktree::{
32    CreatedEntry, Entry, ProjectEntryId, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree,
33    WorktreeId,
34};
35
36use crate::{ProjectPath, trusted_worktrees::TrustedWorktrees};
37
38/// The current paths for a project's worktrees. Each folder path has a corresponding
39/// main worktree path at the same position. The two lists are always the
40/// same length and are modified together via `add_path` / `remove_main_path`.
41///
42/// For non-linked worktrees, the main path and folder path are identical.
43/// For linked worktrees, the main path is the original repo and the folder
44/// path is the linked worktree location.
45#[derive(Default, Debug, Clone)]
46pub struct WorktreePaths {
47    paths: PathList,
48    main_paths: PathList,
49}
50
51impl PartialEq for WorktreePaths {
52    fn eq(&self, other: &Self) -> bool {
53        self.paths == other.paths && self.main_paths == other.main_paths
54    }
55}
56
57impl WorktreePaths {
58    /// Build from two parallel `PathList`s that already share the same
59    /// insertion order. Used for deserialization from DB.
60    ///
61    /// Returns an error if the two lists have different lengths, which
62    /// indicates corrupted data from a prior migration bug.
63    pub fn from_path_lists(
64        main_worktree_paths: PathList,
65        folder_paths: PathList,
66    ) -> anyhow::Result<Self> {
67        anyhow::ensure!(
68            main_worktree_paths.paths().len() == folder_paths.paths().len(),
69            "main_worktree_paths has {} entries but folder_paths has {}",
70            main_worktree_paths.paths().len(),
71            folder_paths.paths().len(),
72        );
73        Ok(Self {
74            paths: folder_paths,
75            main_paths: main_worktree_paths,
76        })
77    }
78
79    /// Build for non-linked worktrees where main == folder for every path.
80    pub fn from_folder_paths(folder_paths: &PathList) -> Self {
81        Self {
82            paths: folder_paths.clone(),
83            main_paths: folder_paths.clone(),
84        }
85    }
86
87    pub fn is_empty(&self) -> bool {
88        self.paths.is_empty()
89    }
90
91    /// The folder paths (for workspace matching / `threads_by_paths` index).
92    pub fn folder_path_list(&self) -> &PathList {
93        &self.paths
94    }
95
96    /// The main worktree paths (for group key / `threads_by_main_paths` index).
97    pub fn main_worktree_path_list(&self) -> &PathList {
98        &self.main_paths
99    }
100
101    /// Iterate the (main_worktree_path, folder_path) pairs in insertion order.
102    pub fn ordered_pairs(&self) -> impl Iterator<Item = (&PathBuf, &PathBuf)> {
103        self.main_paths
104            .ordered_paths()
105            .zip(self.paths.ordered_paths())
106    }
107
108    /// Add a new path pair. If the exact (main, folder) pair already exists,
109    /// this is a no-op. Rebuilds both internal `PathList`s to maintain
110    /// consistent ordering.
111    pub fn add_path(&mut self, main_path: &Path, folder_path: &Path) {
112        let already_exists = self
113            .ordered_pairs()
114            .any(|(m, f)| m.as_path() == main_path && f.as_path() == folder_path);
115        if already_exists {
116            return;
117        }
118        let (mut mains, mut folders): (Vec<PathBuf>, Vec<PathBuf>) = self
119            .ordered_pairs()
120            .map(|(m, f)| (m.clone(), f.clone()))
121            .unzip();
122        mains.push(main_path.to_path_buf());
123        folders.push(folder_path.to_path_buf());
124        self.main_paths = PathList::new(&mains);
125        self.paths = PathList::new(&folders);
126    }
127
128    /// Remove all pairs whose main worktree path matches the given path.
129    /// This removes the corresponding entries from both lists.
130    pub fn remove_main_path(&mut self, main_path: &Path) {
131        let (mains, folders): (Vec<PathBuf>, Vec<PathBuf>) = self
132            .ordered_pairs()
133            .filter(|(m, _)| m.as_path() != main_path)
134            .map(|(m, f)| (m.clone(), f.clone()))
135            .unzip();
136        self.main_paths = PathList::new(&mains);
137        self.paths = PathList::new(&folders);
138    }
139
140    /// Remove all pairs whose folder path matches the given path.
141    /// This removes the corresponding entries from both lists.
142    pub fn remove_folder_path(&mut self, folder_path: &Path) {
143        let (mains, folders): (Vec<PathBuf>, Vec<PathBuf>) = self
144            .ordered_pairs()
145            .filter(|(_, f)| f.as_path() != folder_path)
146            .map(|(m, f)| (m.clone(), f.clone()))
147            .unzip();
148        self.main_paths = PathList::new(&mains);
149        self.paths = PathList::new(&folders);
150    }
151}
152
153enum WorktreeStoreState {
154    Local {
155        fs: Arc<dyn Fs>,
156    },
157    Remote {
158        upstream_client: AnyProtoClient,
159        upstream_project_id: u64,
160        path_style: PathStyle,
161    },
162}
163
164#[derive(Clone)]
165pub struct WorktreeIdCounter(Arc<AtomicU64>);
166
167impl Default for WorktreeIdCounter {
168    fn default() -> Self {
169        Self(Arc::new(AtomicU64::new(1)))
170    }
171}
172
173impl WorktreeIdCounter {
174    pub fn get(cx: &mut App) -> Self {
175        cx.default_global::<Self>().clone()
176    }
177
178    fn next(&self) -> u64 {
179        self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
180    }
181}
182
183impl Global for WorktreeIdCounter {}
184
185/// Summarizes worktree ownership and current snapshot sizes.
186#[derive(Debug, Default)]
187pub struct WorktreeStoreDiagnostics {
188    pub worktree_slots: usize,
189    pub live_worktrees: usize,
190    pub visible_worktrees: usize,
191    pub strong_handles: usize,
192    pub dead_weak_handles: usize,
193    pub loading_worktrees: usize,
194    pub total_entries: usize,
195    pub visible_entries: usize,
196    pub largest_worktree: Option<LargestWorktreeDiagnostics>,
197}
198
199/// Identifies the worktree with the largest current snapshot.
200#[derive(Debug)]
201pub struct LargestWorktreeDiagnostics {
202    pub path: PathBuf,
203    pub entries: usize,
204    pub visible_entries: usize,
205}
206
207pub struct WorktreeStore {
208    next_entry_id: Arc<AtomicUsize>,
209    next_worktree_id: WorktreeIdCounter,
210    downstream_client: Option<(AnyProtoClient, u64)>,
211    retain_worktrees: bool,
212    worktrees: Vec<WorktreeHandle>,
213    scanning_enabled: bool,
214    #[allow(clippy::type_complexity)]
215    loading_worktrees:
216        HashMap<Arc<SanitizedPath>, Shared<Task<Result<Entity<Worktree>, Arc<anyhow::Error>>>>>,
217    initial_scan_complete: (watch::Sender<bool>, watch::Receiver<bool>),
218    state: WorktreeStoreState,
219}
220
221#[derive(Debug)]
222pub enum WorktreeStoreEvent {
223    WorktreeAdded(Entity<Worktree>),
224    WorktreeRemoved(EntityId, WorktreeId),
225    WorktreeReleased(EntityId, WorktreeId),
226    WorktreeOrderChanged,
227    WorktreeUpdateSent(Entity<Worktree>),
228    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
229    WorktreeUpdatedGitRepositories(WorktreeId, UpdatedGitRepositoriesSet),
230    WorktreeDeletedEntry(WorktreeId, ProjectEntryId),
231    WorktreeUpdatedRootRepoCommonDir(WorktreeId),
232}
233
234impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
235
236impl WorktreeStore {
237    pub fn init(client: &AnyProtoClient) {
238        client.add_entity_request_handler(Self::handle_create_project_entry);
239        client.add_entity_request_handler(Self::handle_copy_project_entry);
240        client.add_entity_request_handler(Self::handle_delete_project_entry);
241        client.add_entity_request_handler(Self::handle_trash_project_entry);
242        client.add_entity_request_handler(Self::handle_restore_project_entry);
243        client.add_entity_request_handler(Self::handle_expand_project_entry);
244        client.add_entity_request_handler(Self::handle_expand_all_for_project_entry);
245    }
246
247    pub fn init_remote(client: &AnyProtoClient) {
248        client.add_entity_request_handler(Self::handle_allocate_worktree_id);
249    }
250
251    pub fn local(
252        retain_worktrees: bool,
253        fs: Arc<dyn Fs>,
254        next_worktree_id: WorktreeIdCounter,
255    ) -> Self {
256        Self {
257            next_entry_id: Default::default(),
258            next_worktree_id,
259            loading_worktrees: Default::default(),
260            downstream_client: None,
261            worktrees: Vec::new(),
262            scanning_enabled: true,
263            retain_worktrees,
264            initial_scan_complete: watch::channel_with(true),
265            state: WorktreeStoreState::Local { fs },
266        }
267    }
268
269    pub fn remote(
270        retain_worktrees: bool,
271        upstream_client: AnyProtoClient,
272        upstream_project_id: u64,
273        path_style: PathStyle,
274        next_worktree_id: WorktreeIdCounter,
275    ) -> Self {
276        Self {
277            next_entry_id: Default::default(),
278            next_worktree_id,
279            loading_worktrees: Default::default(),
280            downstream_client: None,
281            worktrees: Vec::new(),
282            scanning_enabled: true,
283            retain_worktrees,
284            initial_scan_complete: watch::channel_with(true),
285            state: WorktreeStoreState::Remote {
286                upstream_client,
287                upstream_project_id,
288                path_style,
289            },
290        }
291    }
292
293    pub fn next_worktree_id(&self) -> impl Future<Output = Result<WorktreeId>> + use<> {
294        let strategy = match (&self.state, &self.downstream_client) {
295            // we are a remote server, the client is in charge of assigning worktree ids
296            (WorktreeStoreState::Local { .. }, Some((client, REMOTE_SERVER_PROJECT_ID))) => {
297                Either::Left(client.clone())
298            }
299            // we are just a local zed project, we can assign ids
300            (WorktreeStoreState::Local { .. }, _) => Either::Right(self.next_worktree_id.next()),
301            // we are connected to a remote server, we are in charge of assigning worktree ids
302            (WorktreeStoreState::Remote { .. }, _) => Either::Right(self.next_worktree_id.next()),
303        };
304        async move {
305            match strategy {
306                Either::Left(client) => Ok(client
307                    .request(proto::AllocateWorktreeId {
308                        project_id: REMOTE_SERVER_PROJECT_ID,
309                    })
310                    .await?
311                    .worktree_id),
312                Either::Right(id) => Ok(id),
313            }
314            .map(WorktreeId::from_proto)
315        }
316    }
317
318    pub fn disable_scanner(&mut self) {
319        self.scanning_enabled = false;
320        *self.initial_scan_complete.0.borrow_mut() = true;
321    }
322
323    /// Returns a future that resolves when all visible worktrees have completed
324    /// their initial scan (entries populated, git repos detected).
325    pub fn wait_for_initial_scan(&self) -> impl Future<Output = ()> + use<> {
326        let mut rx = self.initial_scan_complete.1.clone();
327        async move {
328            let mut done = *rx.borrow();
329            while !done {
330                if let Some(value) = rx.recv().await {
331                    done = value;
332                } else {
333                    break;
334                }
335            }
336        }
337    }
338
339    /// Returns whether all visible worktrees have completed their initial scan.
340    pub fn initial_scan_completed(&self) -> bool {
341        *self.initial_scan_complete.1.borrow()
342    }
343
344    /// Checks whether all visible worktrees have completed their initial scan
345    /// and no worktree creations are pending, and updates the watch channel accordingly.
346    fn update_initial_scan_state(&mut self, cx: &App) {
347        let complete = self.loading_worktrees.is_empty()
348            && self
349                .visible_worktrees(cx)
350                .all(|wt| wt.read(cx).completed_scan_id() >= 1);
351        *self.initial_scan_complete.0.borrow_mut() = complete;
352    }
353
354    /// Spawns a detached task that waits for a worktree's initial scan to complete,
355    /// then rechecks and updates the aggregate initial scan state.
356    fn observe_worktree_scan_completion(
357        &mut self,
358        worktree: &Entity<Worktree>,
359        cx: &mut Context<Self>,
360    ) {
361        let await_scan = worktree.update(cx, |worktree, _cx| worktree.wait_for_snapshot(1));
362        cx.spawn(async move |this, cx| {
363            await_scan.await.ok();
364            this.update(cx, |this, cx| {
365                this.update_initial_scan_state(cx);
366            })
367            .ok();
368            anyhow::Ok(())
369        })
370        .detach();
371    }
372
373    /// Returns worktree ownership and current snapshot size diagnostics.
374    pub fn diagnostics(&self, cx: &App) -> WorktreeStoreDiagnostics {
375        let mut diagnostics = WorktreeStoreDiagnostics {
376            worktree_slots: self.worktrees.len(),
377            loading_worktrees: self.loading_worktrees.len(),
378            ..WorktreeStoreDiagnostics::default()
379        };
380
381        for handle in &self.worktrees {
382            let worktree = match handle {
383                WorktreeHandle::Strong(worktree) => {
384                    diagnostics.strong_handles += 1;
385                    Some(worktree.clone())
386                }
387                WorktreeHandle::Weak(worktree) => {
388                    let worktree = worktree.upgrade();
389                    if worktree.is_none() {
390                        diagnostics.dead_weak_handles += 1;
391                    }
392                    worktree
393                }
394            };
395            let Some(worktree) = worktree else {
396                continue;
397            };
398
399            diagnostics.live_worktrees += 1;
400            let worktree = worktree.read(cx);
401            diagnostics.visible_worktrees += usize::from(worktree.is_visible());
402            let snapshot = worktree.snapshot();
403            let entries = snapshot.entry_count();
404            let visible_entries = snapshot.visible_entry_count();
405            diagnostics.total_entries += entries;
406            diagnostics.visible_entries += visible_entries;
407
408            let is_largest = diagnostics
409                .largest_worktree
410                .as_ref()
411                .is_none_or(|largest| entries > largest.entries);
412            if is_largest {
413                diagnostics.largest_worktree = Some(LargestWorktreeDiagnostics {
414                    path: worktree.abs_path().to_path_buf(),
415                    entries,
416                    visible_entries,
417                });
418            }
419        }
420
421        diagnostics
422    }
423
424    /// Iterates through all worktrees, including ones that don't appear in the project panel
425    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Entity<Worktree>> {
426        self.worktrees
427            .iter()
428            .filter_map(move |worktree| worktree.upgrade())
429    }
430
431    /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
432    pub fn visible_worktrees<'a>(
433        &'a self,
434        cx: &'a App,
435    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
436        self.worktrees()
437            .filter(|worktree| worktree.read(cx).is_visible())
438    }
439
440    /// 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.
441    pub fn visible_worktrees_and_single_files<'a>(
442        &'a self,
443        cx: &'a App,
444    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
445        self.worktrees()
446            .filter(|worktree| worktree.read(cx).is_visible() || worktree.read(cx).is_single_file())
447    }
448
449    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
450        self.worktrees()
451            .find(|worktree| worktree.read(cx).id() == id)
452    }
453
454    pub fn worktree_for_entry(
455        &self,
456        entry_id: ProjectEntryId,
457        cx: &App,
458    ) -> Option<Entity<Worktree>> {
459        self.worktrees()
460            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
461    }
462
463    pub fn find_worktree(
464        &self,
465        abs_path: impl AsRef<Path>,
466        cx: &App,
467    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
468        let abs_path = SanitizedPath::new(abs_path.as_ref());
469        for tree in self.worktrees() {
470            let path_style = tree.read(cx).path_style();
471            if let Some(relative_path) =
472                path_style.strip_prefix(abs_path.as_ref(), tree.read(cx).abs_path().as_ref())
473            {
474                return Some((tree.clone(), relative_path.into_arc()));
475            }
476        }
477        None
478    }
479
480    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
481        self.find_worktree(abs_path, cx)
482            .map(|(worktree, relative_path)| ProjectPath {
483                worktree_id: worktree.read(cx).id(),
484                path: relative_path,
485            })
486    }
487
488    pub fn absolutize(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
489        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
490        Some(worktree.read(cx).absolutize(&project_path.path))
491    }
492
493    pub fn path_style(&self) -> PathStyle {
494        match &self.state {
495            WorktreeStoreState::Local { .. } => PathStyle::local(),
496            WorktreeStoreState::Remote { path_style, .. } => *path_style,
497        }
498    }
499
500    pub fn find_or_create_worktree(
501        &mut self,
502        abs_path: impl AsRef<Path>,
503        visible: bool,
504        cx: &mut Context<Self>,
505    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
506        let abs_path = abs_path.as_ref();
507        if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
508            Task::ready(Ok((tree, relative_path)))
509        } else {
510            let worktree = self.create_worktree(abs_path, visible, cx);
511            cx.background_spawn(async move { Ok((worktree.await?, RelPath::empty_arc())) })
512        }
513    }
514
515    pub fn entry_for_id<'a>(&'a self, entry_id: ProjectEntryId, cx: &'a App) -> Option<&'a Entry> {
516        self.worktrees()
517            .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
518    }
519
520    pub fn worktree_and_entry_for_id<'a>(
521        &'a self,
522        entry_id: ProjectEntryId,
523        cx: &'a App,
524    ) -> Option<(Entity<Worktree>, &'a Entry)> {
525        self.worktrees().find_map(|worktree| {
526            worktree
527                .read(cx)
528                .entry_for_id(entry_id)
529                .map(|e| (worktree.clone(), e))
530        })
531    }
532
533    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
534        self.worktree_for_id(path.worktree_id, cx)?
535            .read(cx)
536            .entry_for_path(&path.path)
537    }
538
539    pub fn copy_entry(
540        &mut self,
541        entry_id: ProjectEntryId,
542        new_project_path: ProjectPath,
543        cx: &mut Context<Self>,
544    ) -> Task<Result<Option<Entry>>> {
545        let Some(old_worktree) = self.worktree_for_entry(entry_id, cx) else {
546            return Task::ready(Err(anyhow!("no such worktree")));
547        };
548        let Some(old_entry) = old_worktree.read(cx).entry_for_id(entry_id) else {
549            return Task::ready(Err(anyhow!("no such entry")));
550        };
551        let Some(new_worktree) = self.worktree_for_id(new_project_path.worktree_id, cx) else {
552            return Task::ready(Err(anyhow!("no such worktree")));
553        };
554
555        match &self.state {
556            WorktreeStoreState::Local { fs } => {
557                let old_abs_path = old_worktree.read(cx).absolutize(&old_entry.path);
558                let new_abs_path = new_worktree.read(cx).absolutize(&new_project_path.path);
559                let fs = fs.clone();
560                let copy = cx.background_spawn(async move {
561                    copy_recursive(
562                        fs.as_ref(),
563                        &old_abs_path,
564                        &new_abs_path,
565                        Default::default(),
566                    )
567                    .await
568                });
569
570                cx.spawn(async move |_, cx| {
571                    copy.await?;
572                    new_worktree
573                        .update(cx, |this, cx| {
574                            this.as_local_mut().unwrap().refresh_entry(
575                                new_project_path.path,
576                                None,
577                                cx,
578                            )
579                        })
580                        .await
581                })
582            }
583            WorktreeStoreState::Remote {
584                upstream_client,
585                upstream_project_id,
586                ..
587            } => {
588                let response = upstream_client.request(proto::CopyProjectEntry {
589                    project_id: *upstream_project_id,
590                    entry_id: entry_id.to_proto(),
591                    new_path: new_project_path.path.as_unix_str().to_owned(),
592                    new_worktree_id: new_project_path.worktree_id.to_proto(),
593                });
594                cx.spawn(async move |_, cx| {
595                    let response = response.await?;
596                    match response.entry {
597                        Some(entry) => new_worktree
598                            .update(cx, |worktree, cx| {
599                                worktree.as_remote_mut().unwrap().insert_entry(
600                                    entry,
601                                    response.worktree_scan_id as usize,
602                                    cx,
603                                )
604                            })
605                            .await
606                            .map(Some),
607                        None => Ok(None),
608                    }
609                })
610            }
611        }
612    }
613
614    pub fn rename_entry(
615        &mut self,
616        entry_id: ProjectEntryId,
617        new_project_path: ProjectPath,
618        cx: &mut Context<Self>,
619    ) -> Task<Result<CreatedEntry>> {
620        let Some(old_worktree) = self.worktree_for_entry(entry_id, cx) else {
621            return Task::ready(Err(anyhow!("no such worktree")));
622        };
623        let Some(old_entry) = old_worktree.read(cx).entry_for_id(entry_id).cloned() else {
624            return Task::ready(Err(anyhow!("no such entry")));
625        };
626        let Some(new_worktree) = self.worktree_for_id(new_project_path.worktree_id, cx) else {
627            return Task::ready(Err(anyhow!("no such worktree")));
628        };
629
630        match &self.state {
631            WorktreeStoreState::Local { fs } => {
632                let abs_old_path = old_worktree.read(cx).absolutize(&old_entry.path);
633                let new_worktree_ref = new_worktree.read(cx);
634                let is_root_entry = new_worktree_ref
635                    .root_entry()
636                    .is_some_and(|e| e.id == entry_id);
637                let abs_new_path = if is_root_entry {
638                    let abs_path = new_worktree_ref.abs_path();
639                    let Some(root_parent_path) = abs_path.parent() else {
640                        return Task::ready(Err(anyhow!("no parent for path {:?}", abs_path)));
641                    };
642                    root_parent_path.join(new_project_path.path.as_std_path())
643                } else {
644                    new_worktree_ref.absolutize(&new_project_path.path)
645                };
646
647                let fs = fs.clone();
648                let case_sensitive = new_worktree
649                    .read(cx)
650                    .as_local()
651                    .unwrap()
652                    .fs_is_case_sensitive();
653
654                let do_rename =
655                    async move |fs: &dyn Fs, old_path: &Path, new_path: &Path, overwrite| {
656                        fs.rename(
657                            &old_path,
658                            &new_path,
659                            fs::RenameOptions {
660                                overwrite,
661                                ..fs::RenameOptions::default()
662                            },
663                        )
664                        .await
665                        .with_context(|| format!("renaming {old_path:?} into {new_path:?}"))
666                    };
667
668                let rename = cx.background_spawn({
669                    let abs_new_path = abs_new_path.clone();
670                    async move {
671                        // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
672                        // we want to overwrite, because otherwise we run into a file-already-exists error.
673                        let overwrite = !case_sensitive
674                            && abs_old_path != abs_new_path
675                            && abs_old_path.to_str().map(|p| p.to_lowercase())
676                                == abs_new_path.to_str().map(|p| p.to_lowercase());
677
678                        // The directory we're renaming into might not exist yet
679                        if let Err(e) =
680                            do_rename(fs.as_ref(), &abs_old_path, &abs_new_path, overwrite).await
681                        {
682                            if let Some(err) = e.downcast_ref::<std::io::Error>()
683                                && err.kind() == std::io::ErrorKind::NotFound
684                            {
685                                if let Some(parent) = abs_new_path.parent() {
686                                    fs.create_dir(parent).await.with_context(|| {
687                                        format!("creating parent directory {parent:?}")
688                                    })?;
689                                    return do_rename(
690                                        fs.as_ref(),
691                                        &abs_old_path,
692                                        &abs_new_path,
693                                        overwrite,
694                                    )
695                                    .await;
696                                }
697                            }
698                            return Err(e);
699                        }
700                        Ok(())
701                    }
702                });
703
704                cx.spawn(async move |_, cx| {
705                    rename.await?;
706                    Ok(new_worktree
707                        .update(cx, |this, cx| {
708                            let local = this.as_local_mut().unwrap();
709                            if is_root_entry {
710                                // We eagerly update `abs_path` and refresh this worktree.
711                                // Otherwise, the FS watcher would do it on the `RootUpdated` event,
712                                // but with a noticeable delay, so we handle it proactively.
713                                local.update_abs_path_and_refresh(
714                                    SanitizedPath::new_arc(&abs_new_path),
715                                    cx,
716                                );
717                                Task::ready(Ok(this.root_entry().cloned()))
718                            } else {
719                                // First refresh the parent directory (in case it was newly created)
720                                if let Some(parent) = new_project_path.path.parent() {
721                                    let _ = local.refresh_entries_for_paths(vec![parent.into()]);
722                                }
723                                // Then refresh the new path
724                                local.refresh_entry(
725                                    new_project_path.path.clone(),
726                                    Some(old_entry.path),
727                                    cx,
728                                )
729                            }
730                        })
731                        .await?
732                        .map(CreatedEntry::Included)
733                        .unwrap_or_else(|| CreatedEntry::Excluded {
734                            abs_path: abs_new_path,
735                        }))
736                })
737            }
738            WorktreeStoreState::Remote {
739                upstream_client,
740                upstream_project_id,
741                ..
742            } => {
743                let response = upstream_client.request(proto::RenameProjectEntry {
744                    project_id: *upstream_project_id,
745                    entry_id: entry_id.to_proto(),
746                    new_path: new_project_path.path.as_unix_str().to_owned(),
747                    new_worktree_id: new_project_path.worktree_id.to_proto(),
748                });
749                cx.spawn(async move |_, cx| {
750                    let response = response.await?;
751                    match response.entry {
752                        Some(entry) => new_worktree
753                            .update(cx, |worktree, cx| {
754                                worktree.as_remote_mut().unwrap().insert_entry(
755                                    entry,
756                                    response.worktree_scan_id as usize,
757                                    cx,
758                                )
759                            })
760                            .await
761                            .map(CreatedEntry::Included),
762                        None => {
763                            let abs_path = new_worktree.read_with(cx, |worktree, _| {
764                                worktree.absolutize(&new_project_path.path)
765                            });
766                            Ok(CreatedEntry::Excluded { abs_path })
767                        }
768                    }
769                })
770            }
771        }
772    }
773    pub fn create_worktree(
774        &mut self,
775        abs_path: impl AsRef<Path>,
776        visible: bool,
777        cx: &mut Context<Self>,
778    ) -> Task<Result<Entity<Worktree>>> {
779        let abs_path: Arc<SanitizedPath> = SanitizedPath::new_arc(&abs_path);
780        let is_via_collab = matches!(&self.state, WorktreeStoreState::Remote { upstream_client, .. } if upstream_client.is_via_collab());
781        if !self.loading_worktrees.contains_key(&abs_path) {
782            let task = match &self.state {
783                WorktreeStoreState::Remote {
784                    upstream_client,
785                    path_style,
786                    ..
787                } => {
788                    if upstream_client.is_via_collab() {
789                        Task::ready(Err(Arc::new(anyhow!("cannot create worktrees via collab"))))
790                    } else {
791                        let abs_path = RemotePathBuf::new(abs_path.to_string(), *path_style);
792                        self.create_remote_worktree(upstream_client.clone(), abs_path, visible, cx)
793                    }
794                }
795                WorktreeStoreState::Local { fs } => {
796                    self.create_local_worktree(fs.clone(), abs_path.clone(), visible, cx)
797                }
798            };
799
800            self.loading_worktrees
801                .insert(abs_path.clone(), task.shared());
802
803            if visible && self.scanning_enabled {
804                *self.initial_scan_complete.0.borrow_mut() = false;
805            }
806        }
807        let task = self.loading_worktrees.get(&abs_path).unwrap().clone();
808        cx.spawn(async move |this, cx| {
809            let result = task.await;
810            this.update(cx, |this, cx| {
811                this.loading_worktrees.remove(&abs_path);
812                if !visible || !this.scanning_enabled || result.is_err() {
813                    this.update_initial_scan_state(cx);
814                }
815            })
816            .ok();
817
818            match result {
819                Ok(worktree) => {
820                    if !is_via_collab {
821                        if let Some((trusted_worktrees, worktree_store)) = this
822                            .update(cx, |_, cx| {
823                                TrustedWorktrees::try_get_global(cx).zip(Some(cx.entity()))
824                            })
825                            .ok()
826                            .flatten()
827                        {
828                            trusted_worktrees.update(cx, |trusted_worktrees, cx| {
829                                trusted_worktrees.can_trust(
830                                    &worktree_store,
831                                    worktree.read(cx).id(),
832                                    cx,
833                                );
834                            });
835                        }
836
837                        this.update(cx, |this, cx| {
838                            if this.scanning_enabled && visible {
839                                this.observe_worktree_scan_completion(&worktree, cx);
840                            }
841                        })
842                        .ok();
843                    }
844                    Ok(worktree)
845                }
846                Err(err) => Err((*err).cloned()),
847            }
848        })
849    }
850
851    fn create_remote_worktree(
852        &mut self,
853        client: AnyProtoClient,
854        abs_path: RemotePathBuf,
855        visible: bool,
856        cx: &mut Context<Self>,
857    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
858        let path_style = abs_path.path_style();
859        let mut abs_path = abs_path.to_string();
860        // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
861        // in which case want to strip the leading the `/`.
862        // On the host-side, the `~` will get expanded.
863        // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
864        if abs_path.starts_with("/~") {
865            abs_path = abs_path[1..].to_string();
866        }
867        if abs_path.is_empty() {
868            abs_path = "~/".to_string();
869        }
870
871        cx.spawn(async move |this, cx| {
872            let this = this.upgrade().context("Dropped worktree store")?;
873
874            let path = RemotePathBuf::new(abs_path, path_style);
875            let response = client
876                .request(proto::AddWorktree {
877                    project_id: REMOTE_SERVER_PROJECT_ID,
878                    path: path.to_proto(),
879                    visible,
880                })
881                .await?;
882
883            if let Some(existing_worktree) = this.read_with(cx, |this, cx| {
884                this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
885            }) {
886                return Ok(existing_worktree);
887            }
888
889            let root_path_buf = PathBuf::from(response.canonicalized_path.clone());
890            let root_name = root_path_buf
891                .file_name()
892                .map(|n| n.to_string_lossy().into_owned())
893                .unwrap_or(root_path_buf.to_string_lossy().into_owned());
894
895            let worktree = cx.update(|cx| {
896                Worktree::remote(
897                    REMOTE_SERVER_PROJECT_ID,
898                    ReplicaId::REMOTE_SERVER,
899                    proto::WorktreeMetadata {
900                        id: response.worktree_id,
901                        root_name,
902                        visible,
903                        abs_path: response.canonicalized_path,
904                        root_repo_common_dir: response.root_repo_common_dir,
905                        root_repo_is_linked_worktree: response.root_repo_is_linked_worktree,
906                    },
907                    client,
908                    path_style,
909                    cx,
910                )
911            });
912
913            this.update(cx, |this, cx| {
914                this.add(&worktree, cx);
915            });
916            Ok(worktree)
917        })
918    }
919
920    fn create_local_worktree(
921        &mut self,
922        fs: Arc<dyn Fs>,
923        abs_path: Arc<SanitizedPath>,
924        visible: bool,
925        cx: &mut Context<Self>,
926    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
927        let next_entry_id = self.next_entry_id.clone();
928        let scanning_enabled = self.scanning_enabled;
929
930        let next_worktree_id = self.next_worktree_id();
931
932        cx.spawn(async move |this, cx| {
933            let worktree_id = next_worktree_id.await?;
934            let worktree = Worktree::local(
935                SanitizedPath::cast_arc(abs_path.clone()),
936                visible,
937                fs,
938                next_entry_id,
939                scanning_enabled,
940                worktree_id,
941                cx,
942            )
943            .await?;
944
945            this.update(cx, |this, cx| this.add(&worktree, cx))?;
946
947            if visible {
948                cx.update(|cx| {
949                    cx.add_recent_document(abs_path.as_path());
950                });
951            }
952
953            Ok(worktree)
954        })
955    }
956
957    pub fn add(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
958        let worktree_id = worktree.read(cx).id();
959        debug_assert!(self.worktrees().all(|w| w.read(cx).id() != worktree_id));
960
961        let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
962        let handle = if push_strong_handle {
963            WorktreeHandle::Strong(worktree.clone())
964        } else {
965            WorktreeHandle::Weak(worktree.downgrade())
966        };
967        self.worktrees.push(handle);
968
969        cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
970        self.send_project_updates(cx);
971
972        let handle_id = worktree.entity_id();
973        cx.subscribe(worktree, |_, worktree, event, cx| {
974            let worktree_id = worktree.read(cx).id();
975            match event {
976                worktree::Event::UpdatedEntries(changes) => {
977                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedEntries(
978                        worktree_id,
979                        changes.clone(),
980                    ));
981                }
982                worktree::Event::UpdatedGitRepositories(set) => {
983                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedGitRepositories(
984                        worktree_id,
985                        set.clone(),
986                    ));
987                }
988                worktree::Event::DeletedEntry(id) => {
989                    cx.emit(WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, *id))
990                }
991                worktree::Event::Deleted => {
992                    // The worktree root itself has been deleted (for single-file worktrees)
993                    // The worktree will be removed via the observe_release callback
994                }
995                worktree::Event::UpdatedRootRepoCommonDir { .. } => {
996                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedRootRepoCommonDir(
997                        worktree_id,
998                    ));
999                }
1000            }
1001        })
1002        .detach();
1003        cx.observe_release(worktree, move |this, worktree, cx| {
1004            cx.emit(WorktreeStoreEvent::WorktreeReleased(
1005                handle_id,
1006                worktree.id(),
1007            ));
1008            cx.emit(WorktreeStoreEvent::WorktreeRemoved(
1009                handle_id,
1010                worktree.id(),
1011            ));
1012            this.send_project_updates(cx);
1013        })
1014        .detach();
1015    }
1016
1017    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
1018        self.worktrees.retain(|worktree| {
1019            if let Some(worktree) = worktree.upgrade() {
1020                if worktree.read(cx).id() == id_to_remove {
1021                    cx.emit(WorktreeStoreEvent::WorktreeRemoved(
1022                        worktree.entity_id(),
1023                        id_to_remove,
1024                    ));
1025                    false
1026                } else {
1027                    true
1028                }
1029            } else {
1030                false
1031            }
1032        });
1033        self.update_initial_scan_state(cx);
1034        self.send_project_updates(cx);
1035    }
1036
1037    pub fn worktree_for_main_worktree_path(
1038        &self,
1039        path: &Path,
1040        cx: &App,
1041    ) -> Option<Entity<Worktree>> {
1042        self.visible_worktrees(cx).find(|worktree| {
1043            let worktree = worktree.read(cx);
1044            if let Some(common_dir) = worktree.root_repo_common_dir() {
1045                common_dir.parent() == Some(path)
1046            } else {
1047                worktree.abs_path().as_ref() == path
1048            }
1049        })
1050    }
1051
1052    fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
1053        match &self.state {
1054            WorktreeStoreState::Remote {
1055                upstream_client,
1056                upstream_project_id,
1057                ..
1058            } => Some((upstream_client.clone(), *upstream_project_id)),
1059            WorktreeStoreState::Local { .. } => None,
1060        }
1061    }
1062
1063    pub fn set_worktrees_from_proto(
1064        &mut self,
1065        worktrees: Vec<proto::WorktreeMetadata>,
1066        replica_id: ReplicaId,
1067        cx: &mut Context<Self>,
1068    ) -> Result<()> {
1069        let mut old_worktrees_by_id = self
1070            .worktrees
1071            .drain(..)
1072            .filter_map(|worktree| {
1073                let worktree = worktree.upgrade()?;
1074                Some((worktree.read(cx).id(), worktree))
1075            })
1076            .collect::<HashMap<_, _>>();
1077
1078        let (client, project_id) = self.upstream_client().context("invalid project")?;
1079
1080        for worktree in worktrees {
1081            if let Some(old_worktree) =
1082                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
1083            {
1084                let push_strong_handle =
1085                    self.retain_worktrees || old_worktree.read(cx).is_visible();
1086                let handle = if push_strong_handle {
1087                    WorktreeHandle::Strong(old_worktree.clone())
1088                } else {
1089                    WorktreeHandle::Weak(old_worktree.downgrade())
1090                };
1091                self.worktrees.push(handle);
1092            } else {
1093                self.add(
1094                    &Worktree::remote(
1095                        project_id,
1096                        replica_id,
1097                        worktree,
1098                        client.clone(),
1099                        self.path_style(),
1100                        cx,
1101                    ),
1102                    cx,
1103                );
1104            }
1105        }
1106        self.send_project_updates(cx);
1107
1108        Ok(())
1109    }
1110
1111    pub fn move_worktree(
1112        &mut self,
1113        source: WorktreeId,
1114        destination: WorktreeId,
1115        cx: &mut Context<Self>,
1116    ) -> Result<()> {
1117        if source == destination {
1118            return Ok(());
1119        }
1120
1121        let mut source_index = None;
1122        let mut destination_index = None;
1123        for (i, worktree) in self.worktrees.iter().enumerate() {
1124            if let Some(worktree) = worktree.upgrade() {
1125                let worktree_id = worktree.read(cx).id();
1126                if worktree_id == source {
1127                    source_index = Some(i);
1128                    if destination_index.is_some() {
1129                        break;
1130                    }
1131                } else if worktree_id == destination {
1132                    destination_index = Some(i);
1133                    if source_index.is_some() {
1134                        break;
1135                    }
1136                }
1137            }
1138        }
1139
1140        let source_index =
1141            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
1142        let destination_index =
1143            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
1144
1145        if source_index == destination_index {
1146            return Ok(());
1147        }
1148
1149        let worktree_to_move = self.worktrees.remove(source_index);
1150        self.worktrees.insert(destination_index, worktree_to_move);
1151        cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
1152        cx.notify();
1153        Ok(())
1154    }
1155
1156    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1157        for worktree in &self.worktrees {
1158            if let Some(worktree) = worktree.upgrade() {
1159                worktree.update(cx, |worktree, _| {
1160                    if let Some(worktree) = worktree.as_remote_mut() {
1161                        worktree.disconnected_from_host();
1162                    }
1163                });
1164            }
1165        }
1166    }
1167
1168    pub fn send_project_updates(&mut self, cx: &mut Context<Self>) {
1169        let Some((downstream_client, project_id)) = self.downstream_client.clone() else {
1170            return;
1171        };
1172
1173        let update = proto::UpdateProject {
1174            project_id,
1175            worktrees: self.worktree_metadata_protos(cx),
1176        };
1177
1178        // collab has bad concurrency guarantees, so we send requests in serial.
1179        let update_project = if downstream_client.is_via_collab() {
1180            Some(downstream_client.request(update))
1181        } else {
1182            downstream_client.send(update).log_err();
1183            None
1184        };
1185        cx.spawn(async move |this, cx| {
1186            if let Some(update_project) = update_project {
1187                update_project.await?;
1188            }
1189
1190            this.update(cx, |this, cx| {
1191                let worktrees = this.worktrees().collect::<Vec<_>>();
1192
1193                for worktree in worktrees {
1194                    worktree.update(cx, |worktree, cx| {
1195                        let client = downstream_client.clone();
1196                        worktree.observe_updates(project_id, cx, {
1197                            move |update| {
1198                                let client = client.clone();
1199                                async move {
1200                                    if client.is_via_collab() {
1201                                        client
1202                                            .request(update)
1203                                            .map(|result| result.log_err().is_some())
1204                                            .await
1205                                    } else {
1206                                        client.send(update).log_err().is_some()
1207                                    }
1208                                }
1209                            }
1210                        });
1211                    });
1212
1213                    cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
1214                }
1215
1216                anyhow::Ok(())
1217            })
1218        })
1219        .detach_and_log_err(cx);
1220    }
1221
1222    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
1223        self.worktrees()
1224            .map(|worktree| {
1225                let worktree = worktree.read(cx);
1226                proto::WorktreeMetadata {
1227                    id: worktree.id().to_proto(),
1228                    root_name: worktree.root_name_str().to_owned(),
1229                    visible: worktree.is_visible(),
1230                    abs_path: worktree.abs_path().to_string_lossy().into_owned(),
1231                    root_repo_common_dir: worktree
1232                        .root_repo_common_dir()
1233                        .map(|p| p.to_string_lossy().into_owned()),
1234                    root_repo_is_linked_worktree: worktree.root_repo_is_linked_worktree(),
1235                }
1236            })
1237            .collect()
1238    }
1239
1240    pub fn shared(
1241        &mut self,
1242        remote_id: u64,
1243        downstream_client: AnyProtoClient,
1244        cx: &mut Context<Self>,
1245    ) {
1246        self.retain_worktrees = true;
1247        self.downstream_client = Some((downstream_client, remote_id));
1248
1249        // When shared, retain all worktrees
1250        for worktree_handle in self.worktrees.iter_mut() {
1251            match worktree_handle {
1252                WorktreeHandle::Strong(_) => {}
1253                WorktreeHandle::Weak(worktree) => {
1254                    if let Some(worktree) = worktree.upgrade() {
1255                        *worktree_handle = WorktreeHandle::Strong(worktree);
1256                    }
1257                }
1258            }
1259        }
1260        // Only send project updates if we share in a collaborative mode.
1261        // Otherwise we are the remote server which is currently constructing
1262        // worktree store before the client actually has set up its message
1263        // handlers.
1264        if remote_id != REMOTE_SERVER_PROJECT_ID {
1265            self.send_project_updates(cx);
1266        }
1267    }
1268
1269    pub fn unshared(&mut self, cx: &mut Context<Self>) {
1270        self.retain_worktrees = false;
1271        self.downstream_client.take();
1272
1273        // When not shared, only retain the visible worktrees
1274        for worktree_handle in self.worktrees.iter_mut() {
1275            if let WorktreeHandle::Strong(worktree) = worktree_handle {
1276                let is_visible = worktree.update(cx, |worktree, _| {
1277                    worktree.stop_observing_updates();
1278                    worktree.is_visible()
1279                });
1280                if !is_visible {
1281                    *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1282                }
1283            }
1284        }
1285    }
1286
1287    pub async fn handle_create_project_entry(
1288        this: Entity<Self>,
1289        envelope: TypedEnvelope<proto::CreateProjectEntry>,
1290        mut cx: AsyncApp,
1291    ) -> Result<proto::ProjectEntryResponse> {
1292        let worktree = this.update(&mut cx, |this, cx| {
1293            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1294            this.worktree_for_id(worktree_id, cx)
1295                .context("worktree not found")
1296        })?;
1297        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
1298    }
1299
1300    pub async fn handle_copy_project_entry(
1301        this: Entity<Self>,
1302        envelope: TypedEnvelope<proto::CopyProjectEntry>,
1303        mut cx: AsyncApp,
1304    ) -> Result<proto::ProjectEntryResponse> {
1305        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1306        let new_worktree_id = WorktreeId::from_proto(envelope.payload.new_worktree_id);
1307        let new_project_path = (
1308            new_worktree_id,
1309            RelPath::from_unix_str(&envelope.payload.new_path)?,
1310        );
1311        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
1312            let Some((_, project_id)) = this.downstream_client else {
1313                bail!("no downstream client")
1314            };
1315            let Some(entry) = this.entry_for_id(entry_id, cx) else {
1316                bail!("no such entry");
1317            };
1318            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1319                bail!("entry is private")
1320            }
1321
1322            let new_worktree = this
1323                .worktree_for_id(new_worktree_id, cx)
1324                .context("no such worktree")?;
1325            let scan_id = new_worktree.read(cx).scan_id();
1326            anyhow::Ok((
1327                scan_id,
1328                this.copy_entry(entry_id, new_project_path.into(), cx),
1329            ))
1330        })?;
1331        let entry = entry.await?;
1332        Ok(proto::ProjectEntryResponse {
1333            entry: entry.as_ref().map(|entry| entry.into()),
1334            worktree_scan_id: scan_id as u64,
1335        })
1336    }
1337
1338    pub async fn handle_trash_project_entry(
1339        this: Entity<Self>,
1340        envelope: TypedEnvelope<proto::TrashProjectEntry>,
1341        mut cx: AsyncApp,
1342    ) -> Result<proto::TrashProjectEntryResponse> {
1343        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1344        let worktree = this.update(&mut cx, |this, cx| {
1345            let Some((_, project_id)) = this.downstream_client else {
1346                bail!("no downstream client")
1347            };
1348            let Some(entry) = this.entry_for_id(entry_id, cx) else {
1349                bail!("no entry")
1350            };
1351            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1352                bail!("entry is private")
1353            }
1354            this.worktree_for_entry(entry_id, cx)
1355                .context("worktree not found")
1356        })?;
1357        Worktree::handle_trash_entry(worktree, envelope.payload, cx).await
1358    }
1359
1360    pub async fn handle_delete_project_entry(
1361        this: Entity<Self>,
1362        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
1363        mut cx: AsyncApp,
1364    ) -> Result<proto::ProjectEntryResponse> {
1365        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1366        let worktree = this.update(&mut cx, |this, cx| {
1367            let Some((_, project_id)) = this.downstream_client else {
1368                bail!("no downstream client")
1369            };
1370            let Some(entry) = this.entry_for_id(entry_id, cx) else {
1371                bail!("no entry")
1372            };
1373            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1374                bail!("entry is private")
1375            }
1376            this.worktree_for_entry(entry_id, cx)
1377                .context("worktree not found")
1378        })?;
1379        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
1380    }
1381
1382    pub async fn handle_restore_project_entry(
1383        this: Entity<Self>,
1384        envelope: TypedEnvelope<proto::RestoreProjectEntry>,
1385        mut cx: AsyncApp,
1386    ) -> Result<proto::RestoreProjectEntryResponse> {
1387        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1388
1389        let worktree = this.update(&mut cx, |this, cx| {
1390            this.worktree_for_id(worktree_id, cx)
1391                .context("worktree not found")
1392        })?;
1393
1394        Worktree::handle_restore_entry(worktree, envelope.payload, cx).await
1395    }
1396
1397    pub async fn handle_rename_project_entry(
1398        this: Entity<Self>,
1399        request: proto::RenameProjectEntry,
1400        mut cx: AsyncApp,
1401    ) -> Result<proto::ProjectEntryResponse> {
1402        let entry_id = ProjectEntryId::from_proto(request.entry_id);
1403        let new_worktree_id = WorktreeId::from_proto(request.new_worktree_id);
1404        let rel_path = RelPath::from_unix_str(&request.new_path)
1405            .with_context(|| format!("received invalid relative path {:?}", &request.new_path))?;
1406
1407        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1408            let worktree = this
1409                .worktree_for_entry(entry_id, cx)
1410                .context("no such worktree")?;
1411
1412            let Some((_, project_id)) = this.downstream_client else {
1413                bail!("no downstream client")
1414            };
1415            let entry = worktree
1416                .read(cx)
1417                .entry_for_id(entry_id)
1418                .ok_or_else(|| anyhow!("missing entry"))?;
1419            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1420                bail!("entry is private")
1421            }
1422
1423            let scan_id = worktree.read(cx).scan_id();
1424            anyhow::Ok((
1425                scan_id,
1426                this.rename_entry(entry_id, (new_worktree_id, rel_path).into(), cx),
1427            ))
1428        })?;
1429        Ok(proto::ProjectEntryResponse {
1430            entry: match &task.await? {
1431                CreatedEntry::Included(entry) => Some(entry.into()),
1432                CreatedEntry::Excluded { .. } => None,
1433            },
1434            worktree_scan_id: scan_id as u64,
1435        })
1436    }
1437
1438    pub async fn handle_expand_project_entry(
1439        this: Entity<Self>,
1440        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
1441        mut cx: AsyncApp,
1442    ) -> Result<proto::ExpandProjectEntryResponse> {
1443        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1444        let worktree = this
1445            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))
1446            .context("invalid request")?;
1447        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
1448    }
1449
1450    pub async fn handle_expand_all_for_project_entry(
1451        this: Entity<Self>,
1452        envelope: TypedEnvelope<proto::ExpandAllForProjectEntry>,
1453        mut cx: AsyncApp,
1454    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1455        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1456        let worktree = this
1457            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))
1458            .context("invalid request")?;
1459        Worktree::handle_expand_all_for_entry(worktree, envelope.payload, cx).await
1460    }
1461
1462    pub async fn handle_allocate_worktree_id(
1463        _this: Entity<Self>,
1464        _envelope: TypedEnvelope<proto::AllocateWorktreeId>,
1465        cx: AsyncApp,
1466    ) -> Result<proto::AllocateWorktreeIdResponse> {
1467        let worktree_id = cx.update(|cx| WorktreeIdCounter::get(cx).next());
1468        Ok(proto::AllocateWorktreeIdResponse { worktree_id })
1469    }
1470
1471    pub fn fs(&self) -> Option<Arc<dyn Fs>> {
1472        match &self.state {
1473            WorktreeStoreState::Local { fs } => Some(fs.clone()),
1474            WorktreeStoreState::Remote { .. } => None,
1475        }
1476    }
1477
1478    pub fn paths(&self, cx: &App) -> WorktreePaths {
1479        let (mains, folders): (Vec<PathBuf>, Vec<PathBuf>) = self
1480            .visible_worktrees(cx)
1481            .map(|worktree| {
1482                let snapshot = worktree.read(cx).snapshot();
1483                let folder_path = snapshot.abs_path().to_path_buf();
1484                let main_path = snapshot
1485                    .root_repo_common_dir()
1486                    .map(|dir| crate::git_store::repo_identity_path(dir))
1487                    .filter(|repo_path| {
1488                        snapshot.root_repo_is_linked_worktree()
1489                            || *repo_path == folder_path.as_path()
1490                            || !folder_path.starts_with(*repo_path)
1491                    })
1492                    .map(Path::to_path_buf)
1493                    .unwrap_or_else(|| folder_path.clone());
1494                (main_path, folder_path)
1495            })
1496            .unzip();
1497
1498        WorktreePaths {
1499            paths: PathList::new(&folders),
1500            main_paths: PathList::new(&mains),
1501        }
1502    }
1503}
1504
1505#[derive(Clone, Debug)]
1506enum WorktreeHandle {
1507    Strong(Entity<Worktree>),
1508    Weak(WeakEntity<Worktree>),
1509}
1510
1511impl WorktreeHandle {
1512    fn upgrade(&self) -> Option<Entity<Worktree>> {
1513        match self {
1514            WorktreeHandle::Strong(handle) => Some(handle.clone()),
1515            WorktreeHandle::Weak(handle) => handle.upgrade(),
1516        }
1517    }
1518}
1519
Served at tenant.openagents/omega Member data and write actions are omitted.