worktree_store.rs

  1use std::{
  2    cell::RefCell,
  3    path::{Path, PathBuf},
  4    sync::{atomic::AtomicUsize, Arc},
  5};
  6
  7use anyhow::{anyhow, Context as _, Result};
  8use client::DevServerProjectId;
  9use collections::{HashMap, HashSet};
 10use fs::Fs;
 11use futures::{
 12    future::{BoxFuture, Shared},
 13    FutureExt, SinkExt,
 14};
 15use gpui::{
 16    AppContext, AsyncAppContext, EntityId, EventEmitter, Model, ModelContext, Task, WeakModel,
 17};
 18use postage::oneshot;
 19use rpc::{
 20    proto::{self, SSH_PROJECT_ID},
 21    AnyProtoClient, TypedEnvelope,
 22};
 23use smol::{
 24    channel::{Receiver, Sender},
 25    stream::StreamExt,
 26};
 27use text::ReplicaId;
 28use util::{paths::compare_paths, ResultExt};
 29use worktree::{Entry, ProjectEntryId, Worktree, WorktreeId, WorktreeSettings};
 30
 31use crate::{search::SearchQuery, ProjectPath};
 32
 33struct MatchingEntry {
 34    worktree_path: Arc<Path>,
 35    path: ProjectPath,
 36    respond: oneshot::Sender<ProjectPath>,
 37}
 38
 39pub struct WorktreeStore {
 40    next_entry_id: Arc<AtomicUsize>,
 41    upstream_client: Option<AnyProtoClient>,
 42    dev_server_project_id: Option<DevServerProjectId>,
 43    is_shared: bool,
 44    worktrees: Vec<WorktreeHandle>,
 45    worktrees_reordered: bool,
 46    #[allow(clippy::type_complexity)]
 47    loading_worktrees:
 48        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
 49    fs: Arc<dyn Fs>,
 50}
 51
 52pub enum WorktreeStoreEvent {
 53    WorktreeAdded(Model<Worktree>),
 54    WorktreeRemoved(EntityId, WorktreeId),
 55    WorktreeOrderChanged,
 56}
 57
 58impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
 59
 60impl WorktreeStore {
 61    pub fn init(client: &AnyProtoClient) {
 62        client.add_model_request_handler(Self::handle_create_project_entry);
 63        client.add_model_request_handler(Self::handle_rename_project_entry);
 64        client.add_model_request_handler(Self::handle_copy_project_entry);
 65        client.add_model_request_handler(Self::handle_delete_project_entry);
 66        client.add_model_request_handler(Self::handle_expand_project_entry);
 67    }
 68
 69    pub fn new(retain_worktrees: bool, fs: Arc<dyn Fs>) -> Self {
 70        Self {
 71            next_entry_id: Default::default(),
 72            loading_worktrees: Default::default(),
 73            upstream_client: None,
 74            dev_server_project_id: None,
 75            is_shared: retain_worktrees,
 76            worktrees: Vec::new(),
 77            worktrees_reordered: false,
 78            fs,
 79        }
 80    }
 81
 82    pub fn set_upstream_client(&mut self, client: AnyProtoClient) {
 83        self.upstream_client = Some(client);
 84    }
 85
 86    pub fn set_dev_server_project_id(&mut self, id: DevServerProjectId) {
 87        self.dev_server_project_id = Some(id);
 88    }
 89
 90    /// Iterates through all worktrees, including ones that don't appear in the project panel
 91    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
 92        self.worktrees
 93            .iter()
 94            .filter_map(move |worktree| worktree.upgrade())
 95    }
 96
 97    /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
 98    pub fn visible_worktrees<'a>(
 99        &'a self,
100        cx: &'a AppContext,
101    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
102        self.worktrees()
103            .filter(|worktree| worktree.read(cx).is_visible())
104    }
105
106    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
107        self.worktrees()
108            .find(|worktree| worktree.read(cx).id() == id)
109    }
110
111    pub fn worktree_for_entry(
112        &self,
113        entry_id: ProjectEntryId,
114        cx: &AppContext,
115    ) -> Option<Model<Worktree>> {
116        self.worktrees()
117            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
118    }
119
120    pub fn find_worktree(
121        &self,
122        abs_path: &Path,
123        cx: &AppContext,
124    ) -> Option<(Model<Worktree>, PathBuf)> {
125        for tree in self.worktrees() {
126            if let Ok(relative_path) = abs_path.strip_prefix(tree.read(cx).abs_path()) {
127                return Some((tree.clone(), relative_path.into()));
128            }
129        }
130        None
131    }
132
133    pub fn entry_for_id<'a>(
134        &'a self,
135        entry_id: ProjectEntryId,
136        cx: &'a AppContext,
137    ) -> Option<&'a Entry> {
138        self.worktrees()
139            .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
140    }
141
142    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
143        self.worktree_for_id(path.worktree_id, cx)?
144            .read(cx)
145            .entry_for_path(&path.path)
146            .cloned()
147    }
148
149    pub fn create_worktree(
150        &mut self,
151        abs_path: impl AsRef<Path>,
152        visible: bool,
153        cx: &mut ModelContext<Self>,
154    ) -> Task<Result<Model<Worktree>>> {
155        let path: Arc<Path> = abs_path.as_ref().into();
156        if !self.loading_worktrees.contains_key(&path) {
157            let task = if let Some(client) = self.upstream_client.clone() {
158                if let Some(dev_server_project_id) = self.dev_server_project_id {
159                    self.create_dev_server_worktree(client, dev_server_project_id, abs_path, cx)
160                } else {
161                    self.create_ssh_worktree(client, abs_path, visible, cx)
162                }
163            } else {
164                self.create_local_worktree(abs_path, visible, cx)
165            };
166
167            self.loading_worktrees.insert(path.clone(), task.shared());
168        }
169        let task = self.loading_worktrees.get(&path).unwrap().clone();
170        cx.background_executor().spawn(async move {
171            match task.await {
172                Ok(worktree) => Ok(worktree),
173                Err(err) => Err(anyhow!("{}", err)),
174            }
175        })
176    }
177
178    fn create_ssh_worktree(
179        &mut self,
180        client: AnyProtoClient,
181        abs_path: impl AsRef<Path>,
182        visible: bool,
183        cx: &mut ModelContext<Self>,
184    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
185        let mut abs_path = abs_path.as_ref().to_string_lossy().to_string();
186        // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
187        // in which case want to strip the leading the `/` and expand the tilde.
188        // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
189        if abs_path.starts_with("/~") {
190            abs_path = shellexpand::tilde(&abs_path[1..]).to_string();
191        }
192        let root_name = PathBuf::from(abs_path.clone())
193            .file_name()
194            .unwrap()
195            .to_string_lossy()
196            .to_string();
197        cx.spawn(|this, mut cx| async move {
198            let response = client
199                .request(proto::AddWorktree {
200                    project_id: SSH_PROJECT_ID,
201                    path: abs_path.clone(),
202                })
203                .await?;
204            let worktree = cx.update(|cx| {
205                Worktree::remote(
206                    0,
207                    0,
208                    proto::WorktreeMetadata {
209                        id: response.worktree_id,
210                        root_name,
211                        visible,
212                        abs_path,
213                    },
214                    client,
215                    cx,
216                )
217            })?;
218
219            this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
220
221            Ok(worktree)
222        })
223    }
224
225    fn create_local_worktree(
226        &mut self,
227        abs_path: impl AsRef<Path>,
228        visible: bool,
229        cx: &mut ModelContext<Self>,
230    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
231        let fs = self.fs.clone();
232        let next_entry_id = self.next_entry_id.clone();
233        let path: Arc<Path> = abs_path.as_ref().into();
234
235        cx.spawn(move |this, mut cx| async move {
236            let worktree = Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx).await;
237
238            this.update(&mut cx, |project, _| {
239                project.loading_worktrees.remove(&path);
240            })?;
241
242            let worktree = worktree?;
243            this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
244
245            if visible {
246                cx.update(|cx| {
247                    cx.add_recent_document(&path);
248                })
249                .log_err();
250            }
251
252            Ok(worktree)
253        })
254    }
255
256    fn create_dev_server_worktree(
257        &mut self,
258        client: AnyProtoClient,
259        dev_server_project_id: DevServerProjectId,
260        abs_path: impl AsRef<Path>,
261        cx: &mut ModelContext<Self>,
262    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
263        let path: Arc<Path> = abs_path.as_ref().into();
264        let mut paths: Vec<String> = self
265            .visible_worktrees(cx)
266            .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
267            .collect();
268        paths.push(path.to_string_lossy().to_string());
269        let request = client.request(proto::UpdateDevServerProject {
270            dev_server_project_id: dev_server_project_id.0,
271            paths,
272        });
273
274        let abs_path = abs_path.as_ref().to_path_buf();
275        cx.spawn(move |project, mut cx| async move {
276            let (tx, rx) = futures::channel::oneshot::channel();
277            let tx = RefCell::new(Some(tx));
278            let Some(project) = project.upgrade() else {
279                return Err(anyhow!("project dropped"))?;
280            };
281            let observer = cx.update(|cx| {
282                cx.observe(&project, move |project, cx| {
283                    let abs_path = abs_path.clone();
284                    project.update(cx, |project, cx| {
285                        if let Some((worktree, _)) = project.find_worktree(&abs_path, cx) {
286                            if let Some(tx) = tx.borrow_mut().take() {
287                                tx.send(worktree).ok();
288                            }
289                        }
290                    })
291                })
292            })?;
293
294            request.await?;
295            let worktree = rx.await.map_err(|e| anyhow!(e))?;
296            drop(observer);
297            project.update(&mut cx, |project, _| {
298                project.loading_worktrees.remove(&path);
299            })?;
300            Ok(worktree)
301        })
302    }
303
304    pub fn add(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
305        let push_strong_handle = self.is_shared || worktree.read(cx).is_visible();
306        let handle = if push_strong_handle {
307            WorktreeHandle::Strong(worktree.clone())
308        } else {
309            WorktreeHandle::Weak(worktree.downgrade())
310        };
311        if self.worktrees_reordered {
312            self.worktrees.push(handle);
313        } else {
314            let i = match self
315                .worktrees
316                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
317                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
318                }) {
319                Ok(i) | Err(i) => i,
320            };
321            self.worktrees.insert(i, handle);
322        }
323
324        cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
325
326        let handle_id = worktree.entity_id();
327        cx.observe_release(worktree, move |_, worktree, cx| {
328            cx.emit(WorktreeStoreEvent::WorktreeRemoved(
329                handle_id,
330                worktree.id(),
331            ));
332        })
333        .detach();
334    }
335
336    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
337        self.worktrees.retain(|worktree| {
338            if let Some(worktree) = worktree.upgrade() {
339                if worktree.read(cx).id() == id_to_remove {
340                    cx.emit(WorktreeStoreEvent::WorktreeRemoved(
341                        worktree.entity_id(),
342                        id_to_remove,
343                    ));
344                    false
345                } else {
346                    true
347                }
348            } else {
349                false
350            }
351        });
352    }
353
354    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
355        self.worktrees_reordered = worktrees_reordered;
356    }
357
358    pub fn set_worktrees_from_proto(
359        &mut self,
360        worktrees: Vec<proto::WorktreeMetadata>,
361        replica_id: ReplicaId,
362        remote_id: u64,
363        client: AnyProtoClient,
364        cx: &mut ModelContext<Self>,
365    ) -> Result<()> {
366        let mut old_worktrees_by_id = self
367            .worktrees
368            .drain(..)
369            .filter_map(|worktree| {
370                let worktree = worktree.upgrade()?;
371                Some((worktree.read(cx).id(), worktree))
372            })
373            .collect::<HashMap<_, _>>();
374
375        for worktree in worktrees {
376            if let Some(old_worktree) =
377                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
378            {
379                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
380            } else {
381                self.add(
382                    &Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx),
383                    cx,
384                );
385            }
386        }
387
388        Ok(())
389    }
390
391    pub fn move_worktree(
392        &mut self,
393        source: WorktreeId,
394        destination: WorktreeId,
395        cx: &mut ModelContext<Self>,
396    ) -> Result<()> {
397        if source == destination {
398            return Ok(());
399        }
400
401        let mut source_index = None;
402        let mut destination_index = None;
403        for (i, worktree) in self.worktrees.iter().enumerate() {
404            if let Some(worktree) = worktree.upgrade() {
405                let worktree_id = worktree.read(cx).id();
406                if worktree_id == source {
407                    source_index = Some(i);
408                    if destination_index.is_some() {
409                        break;
410                    }
411                } else if worktree_id == destination {
412                    destination_index = Some(i);
413                    if source_index.is_some() {
414                        break;
415                    }
416                }
417            }
418        }
419
420        let source_index =
421            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
422        let destination_index =
423            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
424
425        if source_index == destination_index {
426            return Ok(());
427        }
428
429        let worktree_to_move = self.worktrees.remove(source_index);
430        self.worktrees.insert(destination_index, worktree_to_move);
431        self.worktrees_reordered = true;
432        cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
433        cx.notify();
434        Ok(())
435    }
436
437    pub fn disconnected_from_host(&mut self, cx: &mut AppContext) {
438        for worktree in &self.worktrees {
439            if let Some(worktree) = worktree.upgrade() {
440                worktree.update(cx, |worktree, _| {
441                    if let Some(worktree) = worktree.as_remote_mut() {
442                        worktree.disconnected_from_host();
443                    }
444                });
445            }
446        }
447    }
448
449    pub fn set_shared(&mut self, is_shared: bool, cx: &mut ModelContext<Self>) {
450        self.is_shared = is_shared;
451
452        // When shared, retain all worktrees
453        if is_shared {
454            for worktree_handle in self.worktrees.iter_mut() {
455                match worktree_handle {
456                    WorktreeHandle::Strong(_) => {}
457                    WorktreeHandle::Weak(worktree) => {
458                        if let Some(worktree) = worktree.upgrade() {
459                            *worktree_handle = WorktreeHandle::Strong(worktree);
460                        }
461                    }
462                }
463            }
464        }
465        // When not shared, only retain the visible worktrees
466        else {
467            for worktree_handle in self.worktrees.iter_mut() {
468                if let WorktreeHandle::Strong(worktree) = worktree_handle {
469                    let is_visible = worktree.update(cx, |worktree, _| {
470                        worktree.stop_observing_updates();
471                        worktree.is_visible()
472                    });
473                    if !is_visible {
474                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
475                    }
476                }
477            }
478        }
479    }
480
481    /// search over all worktrees and return buffers that *might* match the search.
482    pub fn find_search_candidates(
483        &self,
484        query: SearchQuery,
485        limit: usize,
486        open_entries: HashSet<ProjectEntryId>,
487        fs: Arc<dyn Fs>,
488        cx: &ModelContext<Self>,
489    ) -> Receiver<ProjectPath> {
490        let snapshots = self
491            .visible_worktrees(cx)
492            .filter_map(|tree| {
493                let tree = tree.read(cx);
494                Some((tree.snapshot(), tree.as_local()?.settings()))
495            })
496            .collect::<Vec<_>>();
497
498        let executor = cx.background_executor().clone();
499
500        // We want to return entries in the order they are in the worktrees, so we have one
501        // thread that iterates over the worktrees (and ignored directories) as necessary,
502        // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
503        // channel.
504        // We spawn a number of workers that take items from the filter channel and check the query
505        // against the version of the file on disk.
506        let (filter_tx, filter_rx) = smol::channel::bounded(64);
507        let (output_tx, mut output_rx) = smol::channel::bounded(64);
508        let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
509
510        let input = cx.background_executor().spawn({
511            let fs = fs.clone();
512            let query = query.clone();
513            async move {
514                Self::find_candidate_paths(
515                    fs,
516                    snapshots,
517                    open_entries,
518                    query,
519                    filter_tx,
520                    output_tx,
521                )
522                .await
523                .log_err();
524            }
525        });
526        const MAX_CONCURRENT_FILE_SCANS: usize = 64;
527        let filters = cx.background_executor().spawn(async move {
528            let fs = &fs;
529            let query = &query;
530            executor
531                .scoped(move |scope| {
532                    for _ in 0..MAX_CONCURRENT_FILE_SCANS {
533                        let filter_rx = filter_rx.clone();
534                        scope.spawn(async move {
535                            Self::filter_paths(fs, filter_rx, query).await.log_err();
536                        })
537                    }
538                })
539                .await;
540        });
541        cx.background_executor()
542            .spawn(async move {
543                let mut matched = 0;
544                while let Some(mut receiver) = output_rx.next().await {
545                    let Some(path) = receiver.next().await else {
546                        continue;
547                    };
548                    let Ok(_) = matching_paths_tx.send(path).await else {
549                        break;
550                    };
551                    matched += 1;
552                    if matched == limit {
553                        break;
554                    }
555                }
556                drop(input);
557                drop(filters);
558            })
559            .detach();
560        matching_paths_rx
561    }
562
563    fn scan_ignored_dir<'a>(
564        fs: &'a Arc<dyn Fs>,
565        snapshot: &'a worktree::Snapshot,
566        path: &'a Path,
567        query: &'a SearchQuery,
568        include_root: bool,
569        filter_tx: &'a Sender<MatchingEntry>,
570        output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
571    ) -> BoxFuture<'a, Result<()>> {
572        async move {
573            let abs_path = snapshot.abs_path().join(path);
574            let Some(mut files) = fs
575                .read_dir(&abs_path)
576                .await
577                .with_context(|| format!("listing ignored path {abs_path:?}"))
578                .log_err()
579            else {
580                return Ok(());
581            };
582
583            let mut results = Vec::new();
584
585            while let Some(Ok(file)) = files.next().await {
586                let Some(metadata) = fs
587                    .metadata(&file)
588                    .await
589                    .with_context(|| format!("fetching fs metadata for {abs_path:?}"))
590                    .log_err()
591                    .flatten()
592                else {
593                    continue;
594                };
595                if metadata.is_symlink || metadata.is_fifo {
596                    continue;
597                }
598                results.push((
599                    file.strip_prefix(snapshot.abs_path())?.to_path_buf(),
600                    !metadata.is_dir,
601                ))
602            }
603            results.sort_by(|(a_path, a_is_file), (b_path, b_is_file)| {
604                compare_paths((a_path, *a_is_file), (b_path, *b_is_file))
605            });
606            for (path, is_file) in results {
607                if is_file {
608                    if query.filters_path() {
609                        let matched_path = if include_root {
610                            let mut full_path = PathBuf::from(snapshot.root_name());
611                            full_path.push(&path);
612                            query.file_matches(&full_path)
613                        } else {
614                            query.file_matches(&path)
615                        };
616                        if !matched_path {
617                            continue;
618                        }
619                    }
620                    let (tx, rx) = oneshot::channel();
621                    output_tx.send(rx).await?;
622                    filter_tx
623                        .send(MatchingEntry {
624                            respond: tx,
625                            worktree_path: snapshot.abs_path().clone(),
626                            path: ProjectPath {
627                                worktree_id: snapshot.id(),
628                                path: Arc::from(path),
629                            },
630                        })
631                        .await?;
632                } else {
633                    Self::scan_ignored_dir(
634                        fs,
635                        snapshot,
636                        &path,
637                        query,
638                        include_root,
639                        filter_tx,
640                        output_tx,
641                    )
642                    .await?;
643                }
644            }
645            Ok(())
646        }
647        .boxed()
648    }
649
650    async fn find_candidate_paths(
651        fs: Arc<dyn Fs>,
652        snapshots: Vec<(worktree::Snapshot, WorktreeSettings)>,
653        open_entries: HashSet<ProjectEntryId>,
654        query: SearchQuery,
655        filter_tx: Sender<MatchingEntry>,
656        output_tx: Sender<oneshot::Receiver<ProjectPath>>,
657    ) -> Result<()> {
658        let include_root = snapshots.len() > 1;
659        for (snapshot, settings) in snapshots {
660            let mut entries: Vec<_> = snapshot.entries(query.include_ignored(), 0).collect();
661            entries.sort_by(|a, b| compare_paths((&a.path, a.is_file()), (&b.path, b.is_file())));
662            for entry in entries {
663                if entry.is_dir() && entry.is_ignored {
664                    if !settings.is_path_excluded(&entry.path) {
665                        Self::scan_ignored_dir(
666                            &fs,
667                            &snapshot,
668                            &entry.path,
669                            &query,
670                            include_root,
671                            &filter_tx,
672                            &output_tx,
673                        )
674                        .await?;
675                    }
676                    continue;
677                }
678
679                if entry.is_fifo || !entry.is_file() {
680                    continue;
681                }
682
683                if query.filters_path() {
684                    let matched_path = if include_root {
685                        let mut full_path = PathBuf::from(snapshot.root_name());
686                        full_path.push(&entry.path);
687                        query.file_matches(&full_path)
688                    } else {
689                        query.file_matches(&entry.path)
690                    };
691                    if !matched_path {
692                        continue;
693                    }
694                }
695
696                let (mut tx, rx) = oneshot::channel();
697
698                if open_entries.contains(&entry.id) {
699                    tx.send(ProjectPath {
700                        worktree_id: snapshot.id(),
701                        path: entry.path.clone(),
702                    })
703                    .await?;
704                } else {
705                    filter_tx
706                        .send(MatchingEntry {
707                            respond: tx,
708                            worktree_path: snapshot.abs_path().clone(),
709                            path: ProjectPath {
710                                worktree_id: snapshot.id(),
711                                path: entry.path.clone(),
712                            },
713                        })
714                        .await?;
715                }
716
717                output_tx.send(rx).await?;
718            }
719        }
720        Ok(())
721    }
722
723    async fn filter_paths(
724        fs: &Arc<dyn Fs>,
725        mut input: Receiver<MatchingEntry>,
726        query: &SearchQuery,
727    ) -> Result<()> {
728        while let Some(mut entry) = input.next().await {
729            let abs_path = entry.worktree_path.join(&entry.path.path);
730            let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
731                continue;
732            };
733            if query.detect(file).unwrap_or(false) {
734                entry.respond.send(entry.path).await?
735            }
736        }
737
738        Ok(())
739    }
740
741    pub async fn handle_create_project_entry(
742        this: Model<Self>,
743        envelope: TypedEnvelope<proto::CreateProjectEntry>,
744        mut cx: AsyncAppContext,
745    ) -> Result<proto::ProjectEntryResponse> {
746        let worktree = this.update(&mut cx, |this, cx| {
747            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
748            this.worktree_for_id(worktree_id, cx)
749                .ok_or_else(|| anyhow!("worktree not found"))
750        })??;
751        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
752    }
753
754    pub async fn handle_rename_project_entry(
755        this: Model<Self>,
756        envelope: TypedEnvelope<proto::RenameProjectEntry>,
757        mut cx: AsyncAppContext,
758    ) -> Result<proto::ProjectEntryResponse> {
759        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
760        let worktree = this.update(&mut cx, |this, cx| {
761            this.worktree_for_entry(entry_id, cx)
762                .ok_or_else(|| anyhow!("worktree not found"))
763        })??;
764        Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
765    }
766
767    pub async fn handle_copy_project_entry(
768        this: Model<Self>,
769        envelope: TypedEnvelope<proto::CopyProjectEntry>,
770        mut cx: AsyncAppContext,
771    ) -> Result<proto::ProjectEntryResponse> {
772        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
773        let worktree = this.update(&mut cx, |this, cx| {
774            this.worktree_for_entry(entry_id, cx)
775                .ok_or_else(|| anyhow!("worktree not found"))
776        })??;
777        Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
778    }
779
780    pub async fn handle_delete_project_entry(
781        this: Model<Self>,
782        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
783        mut cx: AsyncAppContext,
784    ) -> Result<proto::ProjectEntryResponse> {
785        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
786        let worktree = this.update(&mut cx, |this, cx| {
787            this.worktree_for_entry(entry_id, cx)
788                .ok_or_else(|| anyhow!("worktree not found"))
789        })??;
790        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
791    }
792
793    pub async fn handle_expand_project_entry(
794        this: Model<Self>,
795        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
796        mut cx: AsyncAppContext,
797    ) -> Result<proto::ExpandProjectEntryResponse> {
798        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
799        let worktree = this
800            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
801            .ok_or_else(|| anyhow!("invalid request"))?;
802        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
803    }
804}
805
806#[derive(Clone)]
807enum WorktreeHandle {
808    Strong(Model<Worktree>),
809    Weak(WeakModel<Worktree>),
810}
811
812impl WorktreeHandle {
813    fn upgrade(&self) -> Option<Model<Worktree>> {
814        match self {
815            WorktreeHandle::Strong(handle) => Some(handle.clone()),
816            WorktreeHandle::Weak(handle) => handle.upgrade(),
817        }
818    }
819}