Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
project_panel: Add remote support for undo/redo system (#59709)
Dinob562439e934a
diff --git a/Cargo.lock b/Cargo.lockindex 56b62212f48..2303a839d8f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6916,6 +6916,7 @@ dependencies = ["rope","serde","serde_json",+ "slotmap","smol","telemetry","tempfile",@@ -14151,7 +14152,6 @@ dependencies = ["anyhow","client","collections",- "command_palette_hooks","criterion","editor","feature_flags",diff --git a/crates/action_log/src/action_log.rs b/crates/action_log/src/action_log.rsindex f8b15f621e9..60bc58701a7 100644--- a/crates/action_log/src/action_log.rs+++ b/crates/action_log/src/action_log.rs@@ -758,11 +758,10 @@ impl ActionLog {.read(cx).entry_id(cx).and_then(|entry_id| {- self.project.update(cx, |project, cx| {- project.delete_entry(entry_id, false, cx)- })+ self.project+ .update(cx, |project, cx| project.delete_entry(entry_id, cx))})- .unwrap_or_else(|| Task::ready(Ok(None)));+ .unwrap_or_else(|| Task::ready(Ok(())));cx.background_spawn(async move {task.await?;@@ -1831,14 +1830,14 @@ mod tests {action_log.update(cx, |log, cx| log.will_delete_buffer(buffer2.clone(), cx));project.update(cx, |project, cx| {- project.delete_file(file1_path.clone(), false, cx)+ project.delete_file(file1_path.clone(), cx)}).unwrap().await.unwrap();project.update(cx, |project, cx| {- project.delete_file(file2_path.clone(), false, cx)+ project.delete_file(file2_path.clone(), cx)}).unwrap().await@@ -2143,9 +2142,7 @@ mod tests {action_log.update(cx, |log, cx| log.will_delete_buffer(buffer.clone(), cx));});project- .update(cx, |project, cx| {- project.delete_file(file_path.clone(), false, cx)- })+ .update(cx, |project, cx| project.delete_file(file_path.clone(), cx)).unwrap().await.unwrap();@@ -3156,7 +3153,7 @@ mod tests {child_log.update(cx, |log, cx| log.will_delete_buffer(buffer.clone(), cx));});project- .update(cx, |project, cx| project.delete_file(file_path, false, cx))+ .update(cx, |project, cx| project.delete_file(file_path, cx)).unwrap().await.unwrap();diff --git a/crates/agent/src/tools/delete_path_tool.rs b/crates/agent/src/tools/delete_path_tool.rsindex 7a23ac38d92..0f837e5144e 100644--- a/crates/agent/src/tools/delete_path_tool.rs+++ b/crates/agent/src/tools/delete_path_tool.rs@@ -247,9 +247,7 @@ impl AgentTool for DeletePathTool {}let deletion_task = project- .update(cx, |project, cx| {- project.delete_file(project_path, false, cx)- })+ .update(cx, |project, cx| project.delete_file(project_path, cx)).ok_or_else(|| {format!("Couldn't delete {path} because that path isn't in this project.")})?;diff --git a/crates/collab/src/rpc.rs b/crates/collab/src/rpc.rsindex 431350971ce..effe9fb2705 100644--- a/crates/collab/src/rpc.rs+++ b/crates/collab/src/rpc.rs@@ -406,6 +406,8 @@ impl Server {.add_request_handler(forward_mutating_project_request::<proto::RenameProjectEntry>).add_request_handler(forward_mutating_project_request::<proto::CopyProjectEntry>).add_request_handler(forward_mutating_project_request::<proto::DeleteProjectEntry>)+ .add_request_handler(forward_mutating_project_request::<proto::TrashProjectEntry>)+ .add_request_handler(forward_mutating_project_request::<proto::RestoreProjectEntry>).add_request_handler(forward_mutating_project_request::<proto::ExpandProjectEntry>).add_request_handler(forward_mutating_project_request::<proto::ExpandAllForProjectEntry>,diff --git a/crates/collab/tests/integration/integration_tests.rs b/crates/collab/tests/integration/integration_tests.rsindex 403e36487bf..4dcd4bb3e58 100644--- a/crates/collab/tests/integration/integration_tests.rs+++ b/crates/collab/tests/integration/integration_tests.rs@@ -3473,7 +3473,7 @@ async fn test_fs_operations(project_b.update(cx_b, |project, cx| {- project.delete_entry(dir_entry.id, false, cx).unwrap()+ project.delete_entry(dir_entry.id, cx).unwrap()}).await.unwrap();@@ -3501,7 +3501,7 @@ async fn test_fs_operations(project_b.update(cx_b, |project, cx| {- project.delete_entry(entry.id, false, cx).unwrap()+ project.delete_entry(entry.id, cx).unwrap()}).await.unwrap();diff --git a/crates/edit_prediction/src/udiff.rs b/crates/edit_prediction/src/udiff.rsindex 8411adde72e..5606b35e7fd 100644--- a/crates/edit_prediction/src/udiff.rs+++ b/crates/edit_prediction/src/udiff.rs@@ -209,7 +209,7 @@ pub async fn apply_diff(if status == FileStatus::Deleted {let delete_task = project.update(cx, |project, cx| {if let Some(path) = project.find_project_path(path.as_ref(), cx) {- project.delete_file(path, false, cx)+ project.delete_file(path, cx)} else {None}diff --git a/crates/fs/Cargo.toml b/crates/fs/Cargo.tomlindex 37588bb0eed..ef0cb4bd8c2 100644--- a/crates/fs/Cargo.toml+++ b/crates/fs/Cargo.toml@@ -36,6 +36,7 @@ proto.workspace = truethiserror.workspace = trueserde.workspace = trueserde_json.workspace = true+slotmap.workspace = truesmol.workspace = truetelemetry.workspace = truetempfile.workspace = truediff --git a/crates/fs/src/fs.rs b/crates/fs/src/fs.rsindex afbfaebaedf..01a76c04699 100644--- a/crates/fs/src/fs.rs+++ b/crates/fs/src/fs.rs@@ -3,6 +3,7 @@ pub mod fs_watcher;pub use fs_watcher::requires_poll_watcher;use parking_lot::Mutex;+use slotmap::{KeyData, SlotMap};use std::ffi::OsString;use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};use std::time::Instant;@@ -119,7 +120,7 @@ pub trait Fs: Send + Sync {/// Moves a file or directory to the system trash./// Returns a [`TrashedEntry`] that can be used to keep track of the/// location of the trashed item in the system's trash.- async fn trash(&self, path: &Path, options: RemoveOptions) -> Result<TrashedEntry>;+ async fn trash(&self, path: &Path, options: RemoveOptions) -> Result<TrashId>;/// Removes a file from the filesystem./// There is no expectation that the file will be preserved in the system@@ -169,10 +170,7 @@ pub trait Fs: Send + Sync {/// Restores a given `TrashedEntry`, moving it from the system's trash back/// to the original path.- async fn restore(- &self,- trashed_entry: TrashedEntry,- ) -> std::result::Result<PathBuf, TrashRestoreError>;+ async fn restore(&self, item: TrashId) -> std::result::Result<PathBuf, TrashRestoreError>;#[cfg(feature = "test-support")]fn as_fake(&self) -> Arc<FakeFs> {@@ -186,7 +184,7 @@ pub trait Fs: Send + Sync {/// Represents a file or directory that has been moved to the system trash,/// retaining enough information to restore it to its original location.#[derive(Clone, PartialEq, Debug)]-pub struct TrashedEntry {+struct TrashedEntry {/// Platform-specific identifier for the file/directory in the trash.////// * Freedesktop – Path to the `.trashinfo` file.@@ -228,6 +226,11 @@ pub enum TrashRestoreError {NotFound { path: PathBuf },#[error("File or directory ({}) already exists at the restore destination.", path.display())]Collision { path: PathBuf },+ // This should never occur, the only way to get a TrashId is to undo+ // consumes the Change::Trashed. We worry about remoting duplicate messages+ // we do not want to crash the app then which is why this error is there.+ #[error("The item was already restored")]+ AlreadyRestored,#[error("Unknown error ({description})")]Unknown { description: String },}@@ -396,11 +399,24 @@ impl From<MTime> for proto::Timestamp {}}+slotmap::new_key_type! { pub struct TrashId; }++impl TrashId {+ pub fn from_proto(value: u64) -> Self {+ KeyData::from_ffi(value).into()+ }++ pub fn to_proto(self) -> u64 {+ self.0.as_ffi()+ }+}+pub struct RealFs {bundled_git_binary_path: Option<PathBuf>,executor: BackgroundExecutor,next_job_id: Arc<AtomicUsize>,job_event_subscribers: Arc<Mutex<Vec<JobEventSender>>>,+ trash: Arc<Mutex<SlotMap<TrashId, TrashedEntry>>>,is_case_sensitive: AtomicU8,}@@ -509,6 +525,7 @@ impl RealFs {executor,next_job_id: Arc::new(AtomicUsize::new(0)),job_event_subscribers: Arc::new(Mutex::new(Vec::new())),+ trash: Arc::new(Mutex::new(SlotMap::with_key())),is_case_sensitive: Default::default(),}}@@ -799,7 +816,7 @@ impl Fs for RealFs {}}- async fn trash(&self, path: &Path, _options: RemoveOptions) -> Result<TrashedEntry> {+ async fn trash(&self, path: &Path, _options: RemoveOptions) -> Result<TrashId> {// We must make the path absolute or trash will make a weird abomination// of the zed working directory (not usually the worktree) and whatever// the path variable holds.@@ -808,10 +825,12 @@ impl Fs for RealFs {// its target and leave the link behind.let path = std::path::absolute(path).context("Could not make the path absolute")?;- Ok(smol::unblock(move || trash::delete_with_info(path))+ let entry = smol::unblock(move || trash::delete_with_info(path)).await.context("Could not trash file or dir")?- .into())+ .into();++ Ok(self.trash.lock().insert(entry))}async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {@@ -1281,10 +1300,13 @@ impl Fs for RealFs {res}- async fn restore(- &self,- trashed_entry: TrashedEntry,- ) -> std::result::Result<PathBuf, TrashRestoreError> {+ async fn restore(&self, item: TrashId) -> std::result::Result<PathBuf, TrashRestoreError> {+ let trashed_entry = self+ .trash+ .lock()+ .remove(item)+ .ok_or(TrashRestoreError::AlreadyRestored)?;+let restored_item_path = trashed_entry.original_parent.join(&trashed_entry.name);let (tx, rx) = futures::channel::oneshot::channel();@@ -1333,7 +1355,7 @@ struct FakeFsState {path_write_counts: std::collections::HashMap<PathBuf, usize>,moves: std::collections::HashMap<u64, PathBuf>,job_event_subscribers: Arc<Mutex<Vec<JobEventSender>>>,- trash: Vec<(TrashedEntry, FakeFsEntry)>,+ trash: Mutex<SlotMap<TrashId, (TrashedEntry, FakeFsEntry)>>,file_to_create_before_watch_add: Option<(PathBuf, PathBuf)>,remove_dir_errors: std::collections::HashMap<PathBuf, String>,}@@ -1653,7 +1675,7 @@ impl FakeFs {path_write_counts: Default::default(),moves: Default::default(),job_event_subscribers: Arc::new(Mutex::new(Vec::new())),- trash: Vec::new(),+ trash: Mutex::new(SlotMap::with_key()),file_to_create_before_watch_add: None,remove_dir_errors: Default::default(),})),@@ -2541,16 +2563,6 @@ impl FakeFs {self.executor.simulate_random_delay()}- /// Returns list of all tracked trash entries.- pub fn trash_entries(&self) -> Vec<TrashedEntry> {- self.state- .lock()- .trash- .iter()- .map(|(entry, _)| entry.clone())- .collect()- }-async fn remove_dir_inner(&self,path: &Path,@@ -2632,6 +2644,20 @@ impl FakeFs {state.emit_event([(path, Some(PathEventKind::Removed))]);Ok(removed)}++ pub fn trashed_paths(&self) -> Vec<PathBuf> {+ self.state+ .lock()+ .trash+ .lock()+ .values()+ .map(|(trashed_entry, _fake_entry)| {+ PathBuf::new()+ .join(trashed_entry.original_parent.clone())+ .join(trashed_entry.name.clone())+ })+ .collect::<Vec<PathBuf>>()+ }}#[cfg(feature = "test-support")]@@ -2948,7 +2974,7 @@ impl Fs for FakeFs {self.remove_dir_inner(path, options).await.map(|_| ())}- async fn trash(&self, path: &Path, options: RemoveOptions) -> Result<TrashedEntry> {+ async fn trash(&self, path: &Path, options: RemoveOptions) -> Result<TrashId> {let normalized_path = normalize_path(path);let parent_path = normalized_path.parent().context("cannot remove the root")?;let base_name = normalized_path.file_name().unwrap();@@ -2966,9 +2992,14 @@ impl Fs for FakeFs {original_parent: parent_path.to_path_buf(),};- let mut state = self.state.lock();- state.trash.push((trashed_entry.clone(), fake_entry));- Ok(trashed_entry)+ let trash_id = self+ .state+ .lock()+ .trash+ .lock()+ .insert((trashed_entry, fake_entry));++ Ok(trash_id)}None => anyhow::bail!("{normalized_path:?} does not exist"),}@@ -3231,18 +3262,11 @@ impl Fs for FakeFs {receiver}- async fn restore(&self, trashed_entry: TrashedEntry) -> Result<PathBuf, TrashRestoreError> {+ async fn restore(&self, trash_id: TrashId) -> Result<PathBuf, TrashRestoreError> {let mut state = self.state.lock();- let Some((trashed_entry, fake_entry)) = state- .trash- .iter()- .find(|(entry, _)| *entry == trashed_entry)- .cloned()- else {- return Err(TrashRestoreError::NotFound {- path: PathBuf::from(trashed_entry.id),- });+ let Some((trashed_entry, fake_entry)) = state.trash.lock().remove(trash_id) else {+ return Err(TrashRestoreError::AlreadyRestored);};let path = trashed_entry@@ -3261,7 +3285,6 @@ impl Fs for FakeFs {match result {Ok(_) => {- state.trash.retain(|(entry, _)| *entry != trashed_entry);state.emit_event([(path.clone(), Some(PathEventKind::Created))]);Ok(path)}diff --git a/crates/fs/tests/integration/fs_tests.rs b/crates/fs/tests/integration/fs_tests.rsindex 6f690be8967..c644229a0da 100644--- a/crates/fs/tests/integration/fs_tests.rs+++ b/crates/fs/tests/integration/fs_tests.rs@@ -2,7 +2,6 @@ mod fake_git_repo_tests;use std::{collections::BTreeSet,- ffi::OsString,io::Write,path::{Path, PathBuf},pin::Pin,@@ -648,15 +647,11 @@ async fn test_fake_fs_trash(executor: BackgroundExecutor) {.await;// Trashing a file.- let root_path = PathBuf::from(path!("/root"));let path = path!("/root/file_a.txt").as_ref();- let trashed_entry = fs- .trash(path, Default::default())+ fs.trash(path, Default::default()).await.expect("should be able to trash {path:?}");- assert_eq!(trashed_entry.name, "file_a.txt");- assert_eq!(trashed_entry.original_parent, root_path);assert_eq!(fs.files(),vec![@@ -666,32 +661,19 @@ async fn test_fake_fs_trash(executor: BackgroundExecutor) {]);- let trash_entries = fs.trash_entries();- assert_eq!(trash_entries.len(), 1);- assert_eq!(trash_entries[0].name, "file_a.txt");- assert_eq!(trash_entries[0].original_parent, root_path);-// Trashing a directory.let path = path!("/root/src").as_ref();- let trashed_entry = fs- .trash(- path,- RemoveOptions {- recursive: true,- ..Default::default()- },- )- .await- .expect("should be able to trash {path:?}");+ fs.trash(+ path,+ RemoveOptions {+ recursive: true,+ ..Default::default()+ },+ )+ .await+ .expect("should be able to trash {path:?}");- assert_eq!(trashed_entry.name, "src");- assert_eq!(trashed_entry.original_parent, root_path);assert_eq!(fs.files(), vec![PathBuf::from(path!("/root/file_b.txt"))]);-- let trash_entries = fs.trash_entries();- assert_eq!(trash_entries.len(), 2);- assert_eq!(trash_entries[1].name, "src");- assert_eq!(trash_entries[1].original_parent, root_path);}#[gpui::test]@@ -709,36 +691,14 @@ async fn test_fake_fs_restore(executor: BackgroundExecutor) {).await;- // Providing a non-existent `TrashedEntry` should result in an error.- let id = OsString::from("/trash/file_c.txt");- let name = OsString::from("file_c.txt");- let original_parent = PathBuf::from(path!("/root"));- let trashed_entry = TrashedEntry {- id,- name,- original_parent,- };- let result = fs.restore(trashed_entry).await;- assert!(matches!(result, Err(TrashRestoreError::NotFound { .. })));-// Attempt deleting a file, asserting that the filesystem no longer reports// it as part of its list of files, restore it and verify that the list of// files and trash has been updated accordingly.let path = path!("/root/src/file_a.txt").as_ref();let trashed_entry = fs.trash(path, Default::default()).await.unwrap();- assert_eq!(fs.trash_entries().len(), 1);- assert_eq!(- fs.files(),- vec![- PathBuf::from(path!("/root/file_c.txt")),- PathBuf::from(path!("/root/src/file_b.txt"))- ]- );-fs.restore(trashed_entry).await.unwrap();- assert_eq!(fs.trash_entries().len(), 0);assert_eq!(fs.files(),vec![@@ -758,7 +718,6 @@ async fn test_fake_fs_restore(executor: BackgroundExecutor) {let path = path!("/root/src/").as_ref();let trashed_entry = fs.trash(path, options).await.unwrap();- assert_eq!(fs.trash_entries().len(), 1);assert_eq!(fs.files(), vec![PathBuf::from(path!("/root/file_c.txt"))]);fs.restore(trashed_entry).await.unwrap();@@ -771,14 +730,12 @@ async fn test_fake_fs_restore(executor: BackgroundExecutor) {PathBuf::from(path!("/root/src/file_b.txt"))]);- assert_eq!(fs.trash_entries().len(), 0);// A collision error should be returned in case a file is being restored to// a path where a file already exists.let path = path!("/root/src/file_a.txt").as_ref();let trashed_entry = fs.trash(path, Default::default()).await.unwrap();- assert_eq!(fs.trash_entries().len(), 1);assert_eq!(fs.files(),vec![@@ -789,7 +746,6 @@ async fn test_fake_fs_restore(executor: BackgroundExecutor) {fs.write(path, "New File A".as_bytes()).await.unwrap();- assert_eq!(fs.trash_entries().len(), 1);assert_eq!(fs.files(),vec![@@ -815,19 +771,16 @@ async fn test_fake_fs_restore(executor: BackgroundExecutor) {let path = path!("/root/src/").as_ref();let trashed_entry = fs.trash(path, options).await.unwrap();- assert_eq!(fs.trash_entries().len(), 2);assert_eq!(fs.files(), vec![PathBuf::from(path!("/root/file_c.txt"))]);fs.create_dir(path).await.unwrap();assert_eq!(fs.files(), vec![PathBuf::from(path!("/root/file_c.txt"))]);- assert_eq!(fs.trash_entries().len(), 2);let result = fs.restore(trashed_entry).await;assert!(result.is_err());assert_eq!(fs.files(), vec![PathBuf::from(path!("/root/file_c.txt"))]);- assert_eq!(fs.trash_entries().len(), 2);}/// Create a directory symlink (`link` -> `target`) in a cross-platform way.diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rsindex e1c7d0e830e..fd97769d037 100644--- a/crates/git_ui/src/git_panel.rs+++ b/crates/git_ui/src/git_panel.rs@@ -2150,7 +2150,7 @@ impl GitPanel {let task = workspace.update(cx, |workspace, cx| {workspace.project()- .update(cx, |project, cx| project.delete_file(path, true, cx))+ .update(cx, |project, cx| project.trash_file(path, cx))})?;if let Some(task) = task {task.await?;@@ -2341,7 +2341,7 @@ impl GitPanel {let project_path = active_repo.read(cx).repo_path_to_project_path(&entry.repo_path, cx)?;- project.delete_file(project_path, true, cx)+ project.trash_file(project_path, cx)})}).collect::<Vec<_>>()diff --git a/crates/project/src/project.rs b/crates/project/src/project.rsindex 3ceed0412f0..f7d792a7f2a 100644--- a/crates/project/src/project.rs+++ b/crates/project/src/project.rs@@ -2663,36 +2663,53 @@ impl Project {})}+ #[inline]+ pub fn trash_file(+ &mut self,+ path: ProjectPath,+ cx: &mut Context<Self>,+ ) -> Option<Task<Result<TrashId>>> {+ let entry = self.entry_for_path(&path, cx)?;+ self.trash_entry(entry.id, cx)+ }+#[inline]pub fn delete_file(&mut self,path: ProjectPath,- trash: bool,cx: &mut Context<Self>,- ) -> Option<Task<Result<Option<TrashedEntry>>>> {+ ) -> Option<Task<Result<()>>> {let entry = self.entry_for_path(&path, cx)?;- self.delete_entry(entry.id, trash, cx)+ self.delete_entry(entry.id, cx)+ }++ #[inline]+ pub fn trash_entry(+ &mut self,+ entry_id: ProjectEntryId,+ cx: &mut Context<Self>,+ ) -> Option<Task<Result<TrashId>>> {+ let worktree = self.worktree_for_entry(entry_id, cx)?;+ cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));+ worktree.update(cx, |worktree, cx| worktree.trash_entry(entry_id, cx))}#[inline]pub fn delete_entry(&mut self,entry_id: ProjectEntryId,- trash: bool,cx: &mut Context<Self>,- ) -> Option<Task<Result<Option<TrashedEntry>>>> {+ ) -> Option<Task<Result<()>>> {let worktree = self.worktree_for_entry(entry_id, cx)?;cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));- worktree.update(cx, |worktree, cx| {- worktree.delete_entry(entry_id, trash, cx)- })+ worktree.update(cx, |worktree, cx| worktree.delete_entry(entry_id, cx))}#[inline]pub fn restore_entry(&self,worktree_id: WorktreeId,- trash_entry: TrashedEntry,+ trash_id: TrashId,cx: &mut Context<'_, Self>,) -> Task<Result<ProjectPath>> {let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {@@ -2700,12 +2717,14 @@ impl Project {};cx.spawn(async move |_, cx| {- Worktree::restore_entry(trash_entry, worktree, cx)- .await- .map(|rel_path_buf| ProjectPath {- worktree_id: worktree_id,- path: Arc::from(rel_path_buf.as_rel_path()),- })+ let entry = worktree+ .update(cx, |worktree, cx| worktree.restore_entry(trash_id, cx))+ .await?;++ Ok(ProjectPath {+ worktree_id: worktree_id,+ path: entry.path,+ })})}diff --git a/crates/project/src/worktree_store.rs b/crates/project/src/worktree_store.rsindex 17ca9a61dd4..3fcadabd4ba 100644--- a/crates/project/src/worktree_store.rs+++ b/crates/project/src/worktree_store.rs@@ -216,6 +216,8 @@ impl WorktreeStore {client.add_entity_request_handler(Self::handle_create_project_entry);client.add_entity_request_handler(Self::handle_copy_project_entry);client.add_entity_request_handler(Self::handle_delete_project_entry);+ client.add_entity_request_handler(Self::handle_trash_project_entry);+ client.add_entity_request_handler(Self::handle_restore_project_entry);client.add_entity_request_handler(Self::handle_expand_project_entry);client.add_entity_request_handler(Self::handle_expand_all_for_project_entry);}@@ -1260,6 +1262,28 @@ impl WorktreeStore {})}+ pub async fn handle_trash_project_entry(+ this: Entity<Self>,+ envelope: TypedEnvelope<proto::TrashProjectEntry>,+ mut cx: AsyncApp,+ ) -> Result<proto::TrashProjectEntryResponse> {+ let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);+ let worktree = this.update(&mut cx, |this, cx| {+ let Some((_, project_id)) = this.downstream_client else {+ bail!("no downstream client")+ };+ let Some(entry) = this.entry_for_id(entry_id, cx) else {+ bail!("no entry")+ };+ if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {+ bail!("entry is private")+ }+ this.worktree_for_entry(entry_id, cx)+ .context("worktree not found")+ })?;+ Worktree::handle_trash_entry(worktree, envelope.payload, cx).await+ }+pub async fn handle_delete_project_entry(this: Entity<Self>,envelope: TypedEnvelope<proto::DeleteProjectEntry>,@@ -1282,6 +1306,21 @@ impl WorktreeStore {Worktree::handle_delete_entry(worktree, envelope.payload, cx).await}+ pub async fn handle_restore_project_entry(+ this: Entity<Self>,+ envelope: TypedEnvelope<proto::RestoreProjectEntry>,+ mut cx: AsyncApp,+ ) -> Result<proto::RestoreProjectEntryResponse> {+ let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);++ let worktree = this.update(&mut cx, |this, cx| {+ this.worktree_for_id(worktree_id, cx)+ .context("worktree not found")+ })?;++ Worktree::handle_restore_entry(worktree, envelope.payload, cx).await+ }+pub async fn handle_rename_project_entry(this: Entity<Self>,request: proto::RenameProjectEntry,diff --git a/crates/project_panel/Cargo.toml b/crates/project_panel/Cargo.tomlindex 89e97ee9c78..00c66370533 100644--- a/crates/project_panel/Cargo.toml+++ b/crates/project_panel/Cargo.toml@@ -19,7 +19,6 @@ doctest = false[dependencies]anyhow.workspace = truecollections.workspace = true-command_palette_hooks.workspace = trueeditor.workspace = truefile_icons.workspace = truefutures.workspace = truediff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rsindex 0f9e1d98e2f..dc15dfbae8b 100644--- a/crates/project_panel/src/project_panel.rs+++ b/crates/project_panel/src/project_panel.rs@@ -5,7 +5,6 @@ mod utils;use anyhow::{Context as _, Result};use client::{ErrorCode, ErrorExt};use collections::{BTreeSet, HashMap, hash_map};-use command_palette_hooks::CommandPaletteFilter;use editor::{Editor, EditorEvent, MultiBufferOffset,items::{@@ -15,6 +14,7 @@ use editor::{};use feature_flags::{FeatureFlagAppExt, ProjectPanelUndoRedoFeatureFlag};use file_icons::FileIcons;+use fs::TrashId;use git;use git::status::GitSummary;use git_ui;@@ -651,6 +651,17 @@ enum DeleteEntryOutcome {Failed,}+/// Small wrapper around a pending task returned by either+/// [`Project::trash_entry`] or [`Project::delete_entry`].+///+/// Since the two operations return different types, this enum lets+/// [`ProjectPanel::remove`] collect and resolve both uniformly, while carrying+/// the intention (trash vs delete).+enum RemoveEntryTask {+ Trash(Task<Result<TrashId>>),+ Delete(Task<Result<()>>),+}+impl ProjectPanel {fn new(workspace: &mut Workspace,@@ -754,18 +765,6 @@ impl ProjectPanel {).detach();- let trash_action = [TypeId::of::<Trash>()];- let is_remote = project.read(cx).is_remote();-- // Make sure the trash option is never displayed anywhere on remote- // hosts since they may not support trashing. May want to dynamically- // detect this in the future.- if is_remote {- CommandPaletteFilter::update_global(cx, |filter, _cx| {- filter.hide_action_types(&trash_action);- });- }-let filename_editor = cx.new(|cx| Editor::single_line(window, cx));cx.subscribe_in(@@ -876,7 +875,12 @@ impl ProjectPanel {unfolded_dir_ids: Default::default(),},update_visible_entries_task: Default::default(),- undo_manager: UndoManager::new(workspace.weak_handle(), weak_project_panel, &cx),+ undo_manager: UndoManager::new(+ workspace.weak_handle(),+ weak_project_panel,+ project.read(cx).is_via_collab(),+ &cx,+ ),};this.update_visible_entries(None, false, false, window, cx);@@ -1159,18 +1163,16 @@ impl ProjectPanel {.action("Copy", Box::new(Copy)).action("Duplicate", Box::new(Duplicate)).action_disabled_when(!has_pasteable_content, "Paste", Box::new(Paste))- .when(cx.has_flag::<ProjectPanelUndoRedoFeatureFlag>(), |menu| {- menu.action_disabled_when(- !self.undo_manager.can_undo(),- "Undo",- Box::new(Undo),- )- .action_disabled_when(- !self.undo_manager.can_redo(),- "Redo",- Box::new(Redo),- )- })+ .when(+ !is_collab && cx.has_flag::<ProjectPanelUndoRedoFeatureFlag>(),+ |menu| {+ let can_undo = self.undo_manager.can_undo();+ let can_redo = self.undo_manager.can_redo();++ menu.action_disabled_when(!can_undo, "Undo", Box::new(Undo))+ .action_disabled_when(!can_redo, "Redo", Box::new(Redo))+ },+ ).when(is_remote, |menu| {menu.separator().action("Download...", Box::new(DownloadFromRemote))@@ -1201,7 +1203,7 @@ impl ProjectPanel {.when(!should_hide_rename, |menu| {menu.separator().action("Rename", Box::new(Rename))})- .when(!is_root && !is_remote, |menu| {+ .when(!is_root && !is_collab, |menu| {menu.action("Trash", Box::new(Trash { skip_prompt: false }))}).when(!is_root, |menu| {@@ -2074,9 +2076,8 @@ impl ProjectPanel {}async fn resolve_delete_entry(- task: Option<Task<Result<Option<fs::TrashedEntry>>>>,+ task: Option<RemoveEntryTask>,worktree_id: WorktreeId,- trash: bool,) -> DeleteEntryOutcome {let Some(task) = task else {// If there's no task to be awaited on, it means that the entry, or@@ -2084,18 +2085,21 @@ impl ProjectPanel {return DeleteEntryOutcome::Deleted;};- match task.await {- Ok(Some(trashed_entry)) if trash => {- DeleteEntryOutcome::Trashed(Change::Trashed(worktree_id, trashed_entry))- }- Err(err) => {- log::error!(- "Failed to {} an entry: {err:#}",- if trash { "trash" } else { "delete" }- );- DeleteEntryOutcome::Failed- }- Ok(_) => DeleteEntryOutcome::Deleted,+ match task {+ RemoveEntryTask::Trash(task) => match task.await {+ Ok(trash_id) => DeleteEntryOutcome::Trashed(Change::Trashed(worktree_id, trash_id)),+ Err(err) => {+ log::error!("Failed to trash an entry: {err:#}",);+ DeleteEntryOutcome::Failed+ }+ },+ RemoveEntryTask::Delete(task) => match task.await {+ Ok(()) => DeleteEntryOutcome::Deleted,+ Err(err) => {+ log::error!("Failed to delete an entry: {err:#}",);+ DeleteEntryOutcome::Failed+ }+ },}}@@ -2546,6 +2550,11 @@ impl ProjectPanel {});}+ // TODO(yara|dino): trashing and deleting are conceptually distinct, even+ // more so with the fact that trashing can now be undone, whereas deleting+ // cannot.+ // Worth splitting them, and exploring dropping the trash confirmation now+ // that trash is undoable.fn remove(&mut self,trash: bool,@@ -2665,14 +2674,24 @@ impl ProjectPanel {file_paths.into_iter().map(|(entry_id, worktree_id, _)| {- (worktree_id, project.delete_entry(entry_id, trash, cx))+ let task = if trash {+ project+ .trash_entry(entry_id, cx)+ .map(RemoveEntryTask::Trash)+ } else {+ project+ .delete_entry(entry_id, cx)+ .map(RemoveEntryTask::Delete)+ };++ (worktree_id, task)}).collect::<Vec<_>>()})})?;for (worktree_id, task) in tasks {- match Self::resolve_delete_entry(task, worktree_id, trash).await {+ match Self::resolve_delete_entry(task, worktree_id).await {DeleteEntryOutcome::Deleted => {}DeleteEntryOutcome::Trashed(change) => changes.push(change),DeleteEntryOutcome::Failed => failed_count += 1,@@ -6851,6 +6870,15 @@ impl Render for ProjectPanel {}};+ // Trashing, undo, and redo rely on the `TrashProjectEntry` and+ // `RestoreProjectEntry` messages, which older collab hosts can't+ // decode, with the operation silently never completing. As such, we+ // keep all three disabled for collab guests. Trashing is already+ // disabled in collab today, so existing users will not lose any+ // functionality and the plan is to eventually remove this check, once a+ // considerable portion of collab hosts had the chance to upgrade to a+ // version that understands these messages.+ let is_collab = project.is_via_collab();let is_local = project.is_local();if has_worktree {@@ -6983,10 +7011,13 @@ impl Render for ProjectPanel {.on_action(cx.listener(Self::fold_directory)).on_action(cx.listener(Self::remove_from_project)).on_action(cx.listener(Self::compare_marked_files))- .when(cx.has_flag::<ProjectPanelUndoRedoFeatureFlag>(), |el| {- el.on_action(cx.listener(Self::undo))- .on_action(cx.listener(Self::redo))- })+ .when(+ !is_collab && cx.has_flag::<ProjectPanelUndoRedoFeatureFlag>(),+ |el| {+ el.on_action(cx.listener(Self::undo))+ .on_action(cx.listener(Self::redo))+ },+ ).when(!project.is_read_only(cx), |el| {el.on_action(cx.listener(Self::new_file)).on_action(cx.listener(Self::new_directory))@@ -6999,9 +7030,7 @@ impl Render for ProjectPanel {.on_action(cx.listener(Self::restore_file)).on_action(cx.listener(Self::add_to_gitignore)).on_action(cx.listener(Self::add_to_git_info_exclude))- .when(!project.is_remote(), |el| {- el.on_action(cx.listener(Self::trash))- })+ .when(!is_collab, |el| el.on_action(cx.listener(Self::trash)))}).when(project.is_local() || project.is_via_wsl_with_host_interop(cx),diff --git a/crates/project_panel/src/tests/undo.rs b/crates/project_panel/src/tests/undo.rsindex 1e69c7443ae..774a71b6d03 100644--- a/crates/project_panel/src/tests/undo.rs+++ b/crates/project_panel/src/tests/undo.rs@@ -383,6 +383,37 @@ async fn trash_undo_redo(cx: &mut gpui::TestAppContext) {cx.assert_fs_state_is(&[]);}+#[gpui::test]+async fn trash_directory_undo_redo(cx: &mut gpui::TestAppContext) {+ let mut cx = TestContext::new_with_tree(+ cx,+ json!({+ "a.txt": "",+ "dir": {+ "b.txt": "File B's Content",+ },+ }),+ )+ .await;+ cx.assert_fs_state_is(&["a.txt", "dir/", "dir/b.txt"]);++ cx.trash(&["dir"]).await;+ cx.assert_fs_state_is(&["a.txt"]);++ cx.undo().await;+ cx.assert_fs_state_is(&["a.txt", "dir/", "dir/b.txt"]);+ assert_eq!(+ cx.fs+ .load(Path::new(&path("/workspace/dir/b.txt")))+ .await+ .unwrap(),+ "File B's Content",+ );++ cx.redo().await;+ cx.assert_fs_state_is(&["a.txt"]);+}+#[gpui::test]async fn trash_continues_when_one_entry_fails(cx: &mut gpui::TestAppContext) {let mut cx = TestContext::new_with_tree(@@ -404,3 +435,26 @@ async fn trash_continues_when_one_entry_fails(cx: &mut gpui::TestAppContext) {cx.undo().await;cx.assert_fs_state_is(&["0_dir/", "a.txt", "b.txt"]);}++#[gpui::test]+async fn record_via_collab(cx: &mut gpui::TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ // Manually update the `UndoManager::is_via_collab` field in order to+ // simulate a Project Panel's Undo Manager in a collab scenario, acting as a+ // client.+ cx.panel.update(&mut cx.cx, |panel, _cx| {+ panel.undo_manager.set_is_via_collab(true);+ });++ // Even though the rename operation should succeed, no operation should be+ // recorded so calling undo or redo should not update the filesystem state.+ cx.rename("a.txt", "renamed.txt").await;+ cx.assert_fs_state_is(&["b.txt", "renamed.txt"]);++ cx.undo().await;+ cx.assert_fs_state_is(&["b.txt", "renamed.txt"]);++ cx.redo().await;+ cx.assert_fs_state_is(&["b.txt", "renamed.txt"]);+}diff --git a/crates/project_panel/src/undo.rs b/crates/project_panel/src/undo.rsindex ca4fc9ed375..17b9b4b1bb8 100644--- a/crates/project_panel/src/undo.rs+++ b/crates/project_panel/src/undo.rs@@ -10,9 +10,9 @@//! Operations Results//! ───────────────────────────────── ──────────────────────────────────────//! Create(ProjectPath) → Created(ProjectPath)-//! Trash(ProjectPath) → Trashed(TrashedEntry)+//! Trash(ProjectPath) → Trashed(TrashId)//! Rename(ProjectPath, ProjectPath) → Renamed(ProjectPath, ProjectPath)-//! Restore(TrashedEntry) → Restored(ProjectPath)+//! Restore(TrashId) → Restored(ProjectPath)//! Batch(Vec<Operation>) → Batch(Vec<Result>)//!//!@@ -59,12 +59,12 @@//! │//! User Operation Undo v//! Execute Created(CONTRIBUTING.md) ────────> Trash(CONTRIBUTING.md)-//! Record Trashed(TrashedEntry(1))+//! Record Trashed(TrashId(1))//! History//! 0 Created(src/main.rs)//! 1 Renamed(README.md, readme.md) ─┐//! 2 +++cursor+++ │(before the cursor)-//! 2 Trashed(TrashedEntry(1)) │+//! 2 Trashed(TrashId(1)) │//! │//! User Operation Undo v//! Execute Renamed(README.md, readme.md) ───> Rename(readme.md, README.md)@@ -73,7 +73,7 @@//! 0 Created(src/main.rs)//! 1 +++cursor+++//! 1 Renamed(readme.md, README.md) ─┐ (at the cursor)-//! 2 Trashed(TrashedEntry(1)) │+//! 2 Trashed(TrashId(1)) │//! │//! ┌──────────────────────────────────┴─────────────────────────────────────────┐//! Redoing will take the result at the cursor position, convert that into the@@ -90,10 +90,10 @@//! 0 Created(src/main.rs)//! 1 Renamed(README.md, readme.md)//! 2 +++cursor+++-//! 2 Trashed(TrashedEntry(1))────┐ (at the cursor)-//! │-//! User Operation Redo v-//! Execute Trashed(TrashedEntry(1)) ────────> Restore(TrashedEntry(1))+//! 2 Trashed(TrashId(1))───────┐ (at the cursor)+//! │+//! User Operation Redo v+//! Execute Trashed(TrashId(1)) ────────> Restore(TrashId(1))//! Record Restored(ProjectPath)//! History//! 0 Created(src/main.rs)@@ -132,7 +132,7 @@use crate::ProjectPanel;use anyhow::{Context, Result, anyhow};-use fs::TrashedEntry;+use fs::TrashId;use futures::channel::mpsc;use gpui::{AppContext, AsyncApp, SharedString, Task, WeakEntity};use project::{ProjectPath, WorktreeId};@@ -148,7 +148,7 @@ use worktree::CreatedEntry;enum Operation {Trash(ProjectPath),Rename(ProjectPath, ProjectPath),- Restore(WorktreeId, TrashedEntry),+ Restore(WorktreeId, TrashId),Batch(Vec<Operation>),}@@ -156,15 +156,15 @@ impl Operation {async fn execute(self, undo_manager: &Inner, cx: &mut AsyncApp) -> Result<Change> {Ok(match self {Operation::Trash(project_path) => {- let trash_entry = undo_manager.trash(&project_path, cx).await?;- Change::Trashed(project_path.worktree_id, trash_entry)+ let trash_id = undo_manager.trash(&project_path, cx).await?;+ Change::Trashed(project_path.worktree_id, trash_id)}Operation::Rename(from, to) => {undo_manager.rename(&from, &to, cx).await?;Change::Renamed(from, to)}- Operation::Restore(worktree_id, trashed_entry) => {- let project_path = undo_manager.restore(worktree_id, trashed_entry, cx).await?;+ Operation::Restore(worktree_id, trash_id) => {+ let project_path = undo_manager.restore(worktree_id, trash_id, cx).await?;Change::Restored(project_path)}Operation::Batch(operations) => {@@ -181,7 +181,7 @@ impl Operation {#[derive(Clone, Debug)]pub(crate) enum Change {Created(ProjectPath),- Trashed(WorktreeId, TrashedEntry),+ Trashed(WorktreeId, TrashId),Renamed(ProjectPath, ProjectPath),Restored(ProjectPath),Batched(Vec<Change>),@@ -191,9 +191,7 @@ impl Change {fn to_inverse(self) -> Operation {match self {Change::Created(project_path) => Operation::Trash(project_path),- Change::Trashed(worktree_id, trashed_entry) => {- Operation::Restore(worktree_id, trashed_entry)- }+ Change::Trashed(worktree_id, trash_id) => Operation::Restore(worktree_id, trash_id),Change::Renamed(from, to) => Operation::Rename(to, from),Change::Restored(project_path) => Operation::Trash(project_path),// When inverting a batch of operations, we reverse the order of@@ -231,6 +229,7 @@ struct Inner {#[derive(Clone)]pub struct UndoManager {tx: mpsc::Sender<UndoMessage>,+ is_via_collab: bool,can_undo: Arc<AtomicBool>,can_redo: Arc<AtomicBool>,}@@ -239,6 +238,7 @@ impl UndoManager {pub fn new(workspace: WeakEntity<Workspace>,panel: WeakEntity<ProjectPanel>,+ is_via_collab: bool,cx: &App,) -> Self {let (tx, rx) = mpsc::channel(1024);@@ -246,6 +246,7 @@ impl UndoManager {let this = Self {tx,+ is_via_collab,can_undo: Arc::clone(&inner.can_undo),can_redo: Arc::clone(&inner.can_redo),};@@ -267,6 +268,17 @@ impl UndoManager {.context("Undo and redo task can not keep up")}pub fn record(&mut self, changes: impl IntoIterator<Item = Change>) -> Result<()> {+ // In a collab session, undoing or redoing can send `TrashProjectEntry`+ // or `RestoreProjectEntry`, for example, undoing a create or undoing a+ // trash.+ // Since older hosts can't decode those messages, which would+ // silently never complete, besides disabling the `Undo`/`Redo` actions+ // for collab, we also avoid recording history here so there's nothing+ // that could later trigger those messages.+ if self.is_via_collab {+ return Ok(());+ }+self.tx.try_send(UndoMessage::Changed(changes.into_iter().collect())).context("Undo and redo task can not keep up")@@ -281,6 +293,11 @@ impl UndoManager {pub fn can_redo(&self) -> bool {self.can_redo.load(Ordering::Relaxed)}++ #[cfg(test)]+ pub(crate) fn set_is_via_collab(&mut self, is_via_collab: bool) {+ self.is_via_collab = is_via_collab;+ }}#[derive(Debug)]@@ -384,7 +401,7 @@ impl Inner {// 0 Created(src/main.rs)// 1 Renamed(README.md, readme.md) ─┐// 2 +++cursor+++ │(before the cursor)- // 2 Trashed(TrashedEntry(1)) │+ // 2 Trashed(TrashId(1)) │// │// User Operation Undo v// Failed execute Renamed(README.md, readme.md) ───> Rename(readme.md, README.md)@@ -392,10 +409,10 @@ impl Inner {// History// 0 Created(src/main.rs)// 1 +++cursor+++- // 1 Trashed(TrashedEntry(1)) ------ // |(at the cursor)- // User Operation Redo v- // Execute Trashed(TrashedEntry(1)) ────────> Restore(TrashedEntry(1))+ // 1 Trashed(TrashId(1)) ---------+ // |(at the cursor)+ // User Operation Redo v+ // Execute Trashed(TrashId(1)) ────────> Restore(TrashId(1))// Record Restored(ProjectPath)// History// 0 Created(src/main.rs)@@ -494,7 +511,7 @@ impl Inner {res?.await}- async fn trash(&self, project_path: &ProjectPath, cx: &mut AsyncApp) -> Result<TrashedEntry> {+ async fn trash(&self, project_path: &ProjectPath, cx: &mut AsyncApp) -> Result<TrashId> {let Some(workspace) = self.workspace.upgrade() else {return Err(anyhow!("Failed to obtain workspace."));};@@ -508,20 +525,17 @@ impl Inner {.ok_or_else(|| anyhow!("No entry for path."))?;project- .delete_entry(entry_id, true, cx)+ .trash_entry(entry_id, cx).ok_or_else(|| anyhow!("Worktree entry should exist"))})})?.await- .and_then(|entry| {- entry.ok_or_else(|| anyhow!("When trashing we should always get a trashentry"))- })}async fn restore(&self,worktree_id: WorktreeId,- trashed_entry: TrashedEntry,+ trash_id: TrashId,cx: &mut AsyncApp,) -> Result<ProjectPath> {let Some(workspace) = self.workspace.upgrade() else {@@ -531,7 +545,7 @@ impl Inner {workspace.update(cx, |workspace, cx| {workspace.project().update(cx, |project, cx| {- project.restore_entry(worktree_id, trashed_entry, cx)+ project.restore_entry(worktree_id, trash_id, cx)})}).awaitdiff --git a/crates/proto/proto/worktree.proto b/crates/proto/proto/worktree.protoindex 285b4c9056d..42869a50811 100644--- a/crates/proto/proto/worktree.proto+++ b/crates/proto/proto/worktree.proto@@ -118,7 +118,22 @@ message CopyProjectEntry {message DeleteProjectEntry {uint64 project_id = 1;uint64 entry_id = 2;- bool use_trash = 3;+ // Deprecated in favor of `TrashProjectEntry`.+ //+ // TODO(yara|dino): once all supported peers use `TrashProjectEntry`, remove+ // this field and replace it with `reserved 3;` so the tag is never reused.+ bool use_trash = 3 [deprecated = true];+}++message TrashProjectEntry {+ uint64 project_id = 1;+ uint64 entry_id = 2;+}++message RestoreProjectEntry {+ uint64 project_id = 1;+ uint64 worktree_id = 2;+ uint64 trash_id = 3;}message ExpandProjectEntry {@@ -139,11 +154,29 @@ message ExpandAllForProjectEntryResponse {uint64 worktree_scan_id = 1;}+// TODO(yara|dino): split into per-operation response messages (e.g.+// `CreateProjectEntryResponse`, `CopyProjectEntryResponse`,+// `DeleteProjectEntryResponse`, `RenameProjectEntryResponse`) for consistency+// with the dedicated `TrashProjectEntryResponse` and+// `RestoreProjectEntryResponse` responses below.+// This generic message is shared by `CreateProjectEntry`, `CopyProjectEntry`,+// `DeleteProjectEntry`, and `RenameProjectEntry`, so `entry` doesn't fit all of+// them. For example, `DeleteProjectEntry` notably never populates it.message ProjectEntryResponse {optional Entry entry = 1;uint64 worktree_scan_id = 2;}+message TrashProjectEntryResponse {+ uint64 trash_id = 1;+ uint64 worktree_scan_id = 2;+}++message RestoreProjectEntryResponse {+ Entry entry = 1;+ uint64 worktree_scan_id = 2;+}+message UpdateWorktreeSettings {uint64 project_id = 1;uint64 worktree_id = 2;diff --git a/crates/proto/proto/zed.proto b/crates/proto/proto/zed.protoindex 07ec0046747..c4a378ee12d 100644--- a/crates/proto/proto/zed.proto+++ b/crates/proto/proto/zed.proto@@ -62,7 +62,7 @@ message Envelope {GetEditPredictionDefinition get_edit_prediction_definition = 462;GetEditPredictionDefinitionResponse get_edit_prediction_definition_response = 463;GetEditPredictionTypeDefinition get_edit_prediction_type_definition = 464;- GetEditPredictionTypeDefinitionResponse get_edit_prediction_type_definition_response = 465; // current max+ GetEditPredictionTypeDefinitionResponse get_edit_prediction_type_definition_response = 465;GetDeclaration get_declaration = 237;GetDeclarationResponse get_declaration_response = 238;GetTypeDefinition get_type_definition = 34;@@ -494,6 +494,10 @@ message Envelope {TelemetryEvent telemetry_event = 459;ResolveCodeAction resolve_code_action = 460;ResolveCodeActionResponse resolve_code_action_response = 461;+ TrashProjectEntry trash_project_entry = 466;+ TrashProjectEntryResponse trash_project_entry_response = 467;+ RestoreProjectEntry restore_project_entry = 468;+ RestoreProjectEntryResponse restore_project_entry_response = 469; // current max}reserved 87 to 88;diff --git a/crates/proto/src/proto.rs b/crates/proto/src/proto.rsindex f7dd604d82d..20ed7b9d7cd 100644--- a/crates/proto/src/proto.rs+++ b/crates/proto/src/proto.rs@@ -64,6 +64,10 @@ messages!((DeleteChannel, Foreground),(DeleteNotification, Foreground),(DeleteProjectEntry, Foreground),+ (TrashProjectEntry, Foreground),+ (TrashProjectEntryResponse, Foreground),+ (RestoreProjectEntry, Foreground),+ (RestoreProjectEntryResponse, Foreground),(DownloadFileByPath, Background),(DownloadFileResponse, Background),(EndStream, Foreground),@@ -406,6 +410,8 @@ request_messages!((DeclineCall, Ack),(DeleteChannel, Ack),(DeleteProjectEntry, ProjectEntryResponse),+ (TrashProjectEntry, TrashProjectEntryResponse),+ (RestoreProjectEntry, RestoreProjectEntryResponse),(DownloadFileByPath, DownloadFileResponse),(ExpandProjectEntry, ExpandProjectEntryResponse),(ExpandAllForProjectEntry, ExpandAllForProjectEntryResponse),@@ -663,6 +669,8 @@ entity_messages!(ResolveDocumentLink,GetFoldingRanges,DeleteProjectEntry,+ TrashProjectEntry,+ RestoreProjectEntry,ExpandProjectEntry,ExpandAllForProjectEntry,FindSearchCandidates,diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rsindex 53aec1f5673..31fb7d14211 100644--- a/crates/remote_server/src/remote_editing_tests.rs+++ b/crates/remote_server/src/remote_editing_tests.rs@@ -3492,6 +3492,113 @@ async fn test_remote_restore_unstaged_hunk_clears_diff(});}+#[gpui::test]+async fn test_remote_delete_project_entry_with_trash(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+) {+ let fs = FakeFs::new(server_cx.executor());++ fs.insert_tree(+ path!("/root"),+ json!({+ "zed": {+ "file_a.txt": "File A"+ }+ }),+ )+ .await;++ let (project, _headless_project) = init_test(&fs, cx, server_cx).await;+ let (worktree, _path) = project+ .update(cx, |project, cx| {+ project.find_or_create_worktree(path!("/root/zed"), true, cx)+ })+ .await+ .unwrap();+ cx.run_until_parked();++ let entry_id = worktree.update(cx, |worktree, _cx| {+ worktree.entry_for_path(rel_path("file_a.txt")).unwrap().id+ });++ let remote_client = project.read_with(cx, |project, _cx| {+ project+ .remote_client()+ .expect("project should have a remote client")+ });++ let proto_client =+ remote_client.read_with(cx, |remote_client, _cx| remote_client.proto_client());++ proto_client+ .request(proto::DeleteProjectEntry {+ project_id: proto::REMOTE_SERVER_PROJECT_ID,+ entry_id: entry_id.to_proto(),+ #[allow(deprecated)]+ use_trash: true,+ })+ .await+ .unwrap();++ assert_eq!(+ fs.trashed_paths(),+ vec![PathBuf::from(path!("/root/zed/file_a.txt"))]+ );+}++#[gpui::test]+async fn test_remote_trash_restore(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {+ let fs = FakeFs::new(server_cx.executor());++ fs.insert_tree(+ path!("/root"),+ json!({+ "zed": {+ "file_a.txt": "File A"+ }+ }),+ )+ .await;++ let (project, _headless_project) = init_test(&fs, cx, server_cx).await;+ let (worktree, _path) = project+ .update(cx, |project, cx| {+ project.find_or_create_worktree(path!("/root/zed"), true, cx)+ })+ .await+ .unwrap();+ cx.run_until_parked();++ let worktree_id = worktree.update(cx, |worktree, _cx| worktree.id());+ let entry_id = worktree.update(cx, |worktree, _cx| {+ worktree.entry_for_path(rel_path("file_a.txt")).unwrap().id+ });++ let trash_id = project+ .update(cx, |project, cx| project.trash_entry(entry_id, cx))+ .unwrap()+ .await+ .unwrap();+ cx.run_until_parked();++ worktree.update(cx, |worktree, _cx| {+ assert!(worktree.entry_for_path(rel_path("file_a.txt")).is_none());+ });++ project+ .update(cx, |project, cx| {+ project.restore_entry(worktree_id, trash_id, cx)+ })+ .await+ .unwrap();+ cx.run_until_parked();++ worktree.update(cx, |worktree, _cx| {+ assert!(worktree.entry_for_path(rel_path("file_a.txt")).is_some());+ });+}+pub async fn init_test(server_fs: &Arc<FakeFs>,cx: &mut TestAppContext,diff --git a/crates/rpc/src/peer.rs b/crates/rpc/src/peer.rsindex d9f34d0dc59..03bbf5028bd 100644--- a/crates/rpc/src/peer.rs+++ b/crates/rpc/src/peer.rs@@ -469,15 +469,18 @@ impl Peer {.lock().as_mut().context("connection was closed")?+ // requesting to forward the response on the oneshot tx+ // when it's envelope.id matches the one for the request we are about to send.insert(envelope.id, tx);connection.outgoing_tx+ // request that the message is send at some point in the future.unbounded_send(Message::Envelope(envelope)).context("connection was closed")?;Ok(())});async move {- send?;+ send?; // wait for receptionlet (response, received_at, _barrier) = rx.await.context("connection was closed")?;if let Some(proto::envelope::Payload::Error(error)) = &response.payload {return Err(RpcError::from_proto(error, type_name));diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rsindex 06442855fb1..ed06ceba7d1 100644--- a/crates/worktree/src/worktree.rs+++ b/crates/worktree/src/worktree.rs@@ -8,7 +8,7 @@ use clock::ReplicaId;use collections::{BTreeMap, HashMap, HashSet, VecDeque};use encoding_rs::Encoding;use fs::{- Fs, MTime, PathEvent, PathEventKind, RemoveOptions, TrashedEntry, Watcher, copy_recursive,+ Fs, MTime, PathEvent, PathEventKind, RemoveOptions, TrashId, Watcher, copy_recursive,read_dir_items,};use futures::{@@ -73,7 +73,7 @@ use text::{LineEnding, Rope};use util::{ResultExt, maybe,paths::{PathMatcher, PathStyle, SanitizedPath, home_dir},- rel_path::{RelPath, RelPathBuf},+ rel_path::RelPath,};pub use worktree_settings::WorktreeSettings;@@ -964,26 +964,51 @@ impl Worktree {}}- pub fn delete_entry(+ pub fn trash_entry(&mut self,entry_id: ProjectEntryId,- trash: bool,cx: &mut Context<Worktree>,- ) -> Option<Task<Result<Option<TrashedEntry>>>> {+ ) -> Option<Task<Result<TrashId>>> {+ let entry = match self {+ Worktree::Local(this) => this.entry_for_id(entry_id),+ Worktree::Remote(this) => this.entry_for_id(entry_id),+ }?+ .clone();+let task = match self {- Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),- Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),- }?;+ Worktree::Local(this) => this.trash_entry(entry.clone(), cx),+ Worktree::Remote(this) => this.trash_entry(entry_id, cx),+ };++ let mut ids = vec![entry_id];+ self.get_children_ids_recursive(&entry.path, &mut ids);++ for id in ids {+ cx.emit(Event::DeletedEntry(id));+ }+ Some(task)+ }- let entry = match &*self {+ pub fn delete_entry(+ &mut self,+ entry_id: ProjectEntryId,+ cx: &mut Context<Worktree>,+ ) -> Option<Task<Result<()>>> {+ let entry = match self {Worktree::Local(this) => this.entry_for_id(entry_id),Worktree::Remote(this) => this.entry_for_id(entry_id),- }?;+ }?+ .clone();++ let task = match self {+ Worktree::Local(this) => this.delete_entry(entry.clone(), cx),+ Worktree::Remote(this) => this.delete_entry(entry_id, cx),+ };let mut ids = vec![entry_id];- let path = &*entry.path;+ let path = entry.path;- self.get_children_ids_recursive(path, &mut ids);+ self.get_children_ids_recursive(&path, &mut ids);for id in ids {cx.emit(Event::DeletedEntry(id));@@ -991,17 +1016,14 @@ impl Worktree {Some(task)}- pub async fn restore_entry(- trash_entry: TrashedEntry,- worktree: Entity<Self>,- cx: &mut AsyncApp,- ) -> Result<RelPathBuf> {- let is_local = worktree.read_with(cx, |this, _| this.is_local());- if is_local {- LocalWorktree::restore_entry(trash_entry, worktree, cx).await- } else {- // TODO(dino): Add support for restoring entries in remote worktrees.- Err(anyhow!("Unsupported"))+ pub fn restore_entry(+ &mut self,+ trash_id: TrashId,+ cx: &mut Context<'_, Worktree>,+ ) -> Task<Result<Entry>> {+ match self {+ Worktree::Local(this) => this.restore_entry(trash_id, cx),+ Worktree::Remote(this) => this.restore_entry(trash_id, cx),}}@@ -1013,18 +1035,6 @@ impl Worktree {}}- // pub fn rename_entry(- // &mut self,- // entry_id: ProjectEntryId,- // new_path: Arc<RelPath>,- // cx: &Context<Self>,- // ) -> Task<Result<CreatedEntry>> {- // match self {- // Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),- // Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),- // }- // }-pub fn copy_external_entries(&mut self,target_directory: Arc<RelPath>,@@ -1119,21 +1129,49 @@ impl Worktree {})}- pub async fn handle_delete_entry(+ pub async fn handle_trash_entry(this: Entity<Self>,- request: proto::DeleteProjectEntry,+ request: proto::TrashProjectEntry,mut cx: AsyncApp,- ) -> Result<proto::ProjectEntryResponse> {+ ) -> Result<proto::TrashProjectEntryResponse> {let (scan_id, task) = this.update(&mut cx, |this, cx| {(this.scan_id(),- this.delete_entry(- ProjectEntryId::from_proto(request.entry_id),- request.use_trash,- cx,- ),+ this.trash_entry(ProjectEntryId::from_proto(request.entry_id), cx),)});+ let trash_id = task+ .ok_or_else(|| anyhow::anyhow!("invalid entry"))?+ .await?;++ Ok(proto::TrashProjectEntryResponse {+ trash_id: trash_id.to_proto(),+ worktree_scan_id: scan_id as u64,+ })+ }++ pub async fn handle_delete_entry(+ this: Entity<Self>,+ request: proto::DeleteProjectEntry,+ mut cx: AsyncApp,+ ) -> Result<proto::ProjectEntryResponse> {+ let (scan_id, task) = this.update(&mut cx, |this, cx| {+ // While the `use_trash` field is deprecated but not removed, we+ // still need to support either trashing or deleting the file.+ // Otherwise, if an older client sends the `DeleteProjectEntry {+ // use_trash: true }` rather than the newer `TrashProjectEntry`, and+ // the flag was ignored, we'd permanently delete a file that was+ // actually meant to be trashed.+ #[allow(deprecated)]+ let task = if request.use_trash {+ this.trash_entry(ProjectEntryId::from_proto(request.entry_id), cx)+ .map(|task| cx.background_spawn(async move { task.await.map(|_| ()) }))+ } else {+ this.delete_entry(ProjectEntryId::from_proto(request.entry_id), cx)+ };++ (this.scan_id(), task)+ });task.ok_or_else(|| anyhow::anyhow!("invalid entry"))?.await?;Ok(proto::ProjectEntryResponse {@@ -1142,6 +1180,26 @@ impl Worktree {})}+ pub async fn handle_restore_entry(+ this: Entity<Self>,+ request: proto::RestoreProjectEntry,+ mut cx: AsyncApp,+ ) -> Result<proto::RestoreProjectEntryResponse> {+ let (scan_id, task) = this.update(&mut cx, |this, cx| {+ (+ this.scan_id(),+ this.restore_entry(TrashId::from_proto(request.trash_id), cx),+ )+ });++ let entry = task.await?;++ Ok(proto::RestoreProjectEntryResponse {+ entry: Some(proto::Entry::from(&entry)),+ worktree_scan_id: scan_id as u64,+ })+ }+pub async fn handle_expand_entry(this: Entity<Self>,request: proto::ExpandProjectEntry,@@ -1841,89 +1899,91 @@ impl LocalWorktree {})}- pub fn delete_entry(- &self,- entry_id: ProjectEntryId,- trash: bool,- cx: &Context<Worktree>,- ) -> Option<Task<Result<Option<TrashedEntry>>>> {- let entry = self.entry_for_id(entry_id)?.clone();+ pub fn trash_entry(&self, entry: Entry, cx: &Context<Worktree>) -> Task<Result<TrashId>> {let abs_path = self.absolutize(&entry.path);let fs = self.fs.clone();- let delete = cx.background_spawn(async move {- let trashed_entry = match (entry.is_file(), trash) {- (true, true) => Some(fs.trash(&abs_path, Default::default()).await?),- (false, true) => Some(- fs.trash(- &abs_path,- RemoveOptions {- recursive: true,- ignore_if_not_exists: false,- },- )- .await?,- ),- (true, false) => {- fs.remove_file(&abs_path, Default::default()).await?;- None- }- (false, false) => {- fs.remove_dir(- &abs_path,- RemoveOptions {- recursive: true,- ignore_if_not_exists: false,- },- )- .await?;- None- }+ cx.spawn(async move |this, cx| {+ let trash_id = if entry.is_file() {+ fs.trash(&abs_path, Default::default()).await?+ } else {+ fs.trash(+ &abs_path,+ RemoveOptions {+ recursive: true,+ ignore_if_not_exists: false,+ },+ )+ .await?};- anyhow::Ok((trashed_entry, entry.path))- });-- Some(cx.spawn(async move |this, cx| {- let (trashed_entry, path) = delete.await?;this.update(cx, |this, _| {this.as_local_mut().unwrap()- .refresh_entries_for_paths(vec![path])+ .refresh_entries_for_paths(vec![entry.path])})?.recv().await;- Ok(trashed_entry)- }))+ Ok(trash_id)+ })}- pub async fn restore_entry(- trash_entry: TrashedEntry,- this: Entity<Worktree>,- cx: &mut AsyncApp,- ) -> Result<RelPathBuf> {- let Some((fs, worktree_abs_path, path_style)) = this.read_with(cx, |this, _cx| {- let local_worktree = match this {- Worktree::Local(local_worktree) => local_worktree,- Worktree::Remote(_) => return None,+ pub fn delete_entry(&self, entry: Entry, cx: &Context<Worktree>) -> Task<Result<()>> {+ let abs_path = self.absolutize(&entry.path);+ let fs = self.fs.clone();++ cx.spawn(async move |this, cx| {+ if entry.is_file() {+ fs.remove_file(&abs_path, Default::default()).await?+ } else {+ fs.remove_dir(+ &abs_path,+ RemoveOptions {+ recursive: true,+ ignore_if_not_exists: false,+ },+ )+ .await?};- let fs = local_worktree.fs.clone();- let path_style = local_worktree.path_style();- Some((fs, Arc::clone(local_worktree.abs_path()), path_style))- }) else {- return Err(anyhow!("Localworktree should not change into a remote one"));- };+ this.update(cx, |this, _| {+ this.as_local_mut()+ .unwrap()+ .refresh_entries_for_paths(vec![entry.path])+ })?+ .recv()+ .await;++ Ok(())+ })+ }++ pub fn restore_entry(+ &mut self,+ trash_id: TrashId,+ cx: &mut Context<'_, Worktree>,+ ) -> Task<Result<Entry>> {+ let fs = self.fs.clone();+ let worktree_abs_path = self.abs_path().clone();+ let path_style = self.path_style();++ cx.spawn(async move |this, cx| {+ let path_buf = fs.restore(trash_id).await?;+ let path = path_buf+ .strip_prefix(worktree_abs_path)+ .context("Could not strip prefix")?;+ let path = Arc::from(RelPath::new(&path, path_style)?.as_ref());- let path_buf = fs.restore(trash_entry).await?;- let path = path_buf- .strip_prefix(worktree_abs_path)- .context("Could not strip prefix")?;- let path = RelPath::new(&path, path_style)?;- let path = path.into_owned();+ let entry = this+ .update(cx, |this, cx| {+ this.as_local_mut().unwrap().refresh_entry(path, None, cx)+ })?+ .await?+ .context("Entry not found after restore")?;- Ok(path)+ Ok(entry)+ })}pub fn copy_external_entries(@@ -2294,20 +2354,20 @@ impl RemoteWorktree {})}- fn delete_entry(+ fn trash_entry(&self,entry_id: ProjectEntryId,- trash: bool,cx: &Context<Worktree>,- ) -> Option<Task<Result<Option<TrashedEntry>>>> {- let response = self.client.request(proto::DeleteProjectEntry {+ ) -> Task<Result<TrashId>> {+ let response = self.client.request(proto::TrashProjectEntry {project_id: self.project_id,entry_id: entry_id.to_proto(),- use_trash: trash,});- Some(cx.spawn(async move |this, cx| {++ cx.spawn(async move |this, cx| {let response = response.await?;let scan_id = response.worktree_scan_id as usize;+ let trash_id = response.trash_id;this.update(cx, move |this, _| {this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)@@ -2319,50 +2379,65 @@ impl RemoteWorktree {let snapshot = &mut this.background_snapshot.lock().0;snapshot.delete_entry(entry_id);this.snapshot = snapshot.clone();+ })?;- // TODO: How can we actually track the deleted entry when- // working in remote? We likely only need to keep this- // information on the remote side in order to support restoring- // the trashed file.- None+ Ok(TrashId::from_proto(trash_id))+ })+ }++ fn delete_entry(&self, entry_id: ProjectEntryId, cx: &Context<Worktree>) -> Task<Result<()>> {+ let response = self.client.request(proto::DeleteProjectEntry {+ project_id: self.project_id,+ entry_id: entry_id.to_proto(),+ // The `use_trash` field is being deprecated but it's still required+ // in the message, hence the `#[allow(deprecated)]` attribute.+ #[allow(deprecated)]+ use_trash: false,+ });++ cx.spawn(async move |this, cx| {+ let response = response.await?;+ let scan_id = response.worktree_scan_id as usize;++ this.update(cx, move |this, _| {+ this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)+ })?+ .await?;++ this.update(cx, |this, _| {+ let this = this.as_remote_mut().unwrap();+ let snapshot = &mut this.background_snapshot.lock().0;+ snapshot.delete_entry(entry_id);+ this.snapshot = snapshot.clone();})- }))+ })}- // fn rename_entry(- // &self,- // entry_id: ProjectEntryId,- // new_path: impl Into<Arc<RelPath>>,- // cx: &Context<Worktree>,- // ) -> Task<Result<CreatedEntry>> {- // let new_path: Arc<RelPath> = new_path.into();- // let response = self.client.request(proto::RenameProjectEntry {- // project_id: self.project_id,- // entry_id: entry_id.to_proto(),- // new_worktree_id: new_path.worktree_id,- // new_path: new_path.as_ref().to_proto(),- // });- // cx.spawn(async move |this, cx| {- // let response = response.await?;- // match response.entry {- // Some(entry) => this- // .update(cx, |this, cx| {- // this.as_remote_mut().unwrap().insert_entry(- // entry,- // response.worktree_scan_id as usize,- // cx,- // )- // })?- // .await- // .map(CreatedEntry::Included),- // None => {- // let abs_path =- // this.read_with(cx, |worktree, _| worktree.absolutize(&new_path))?;- // Ok(CreatedEntry::Excluded { abs_path })- // }- // }- // })- // }+ fn restore_entry(&mut self, trash_id: TrashId, cx: &Context<Worktree>) -> Task<Result<Entry>> {+ let project_id = self.project_id();+ let worktree_id = self.id().to_proto();+ let trash_id = trash_id.to_proto();++ let request = self.client.request(proto::RestoreProjectEntry {+ project_id,+ worktree_id,+ trash_id,+ });++ cx.spawn(async move |this, cx| {+ let response = request.await?;+ let scan_id = response.worktree_scan_id as usize;+ let proto_entry = response.entry.context("Missing entry in in response")?;++ this.update(cx, move |worktree, cx| {+ worktree+ .as_remote_mut()+ .unwrap()+ .insert_entry(proto_entry, scan_id, cx)+ })?+ .await+ })+ }fn copy_external_entries(&self,diff --git a/crates/worktree/tests/integration/worktree_tests.rs b/crates/worktree/tests/integration/worktree_tests.rsindex c036a6d16fa..a9a673d10e7 100644--- a/crates/worktree/tests/integration/worktree_tests.rs+++ b/crates/worktree/tests/integration/worktree_tests.rs@@ -3206,9 +3206,7 @@ fn randomly_mutate_worktree(match rng.random_range(0_u32..100) {0..=33 if entry.path.as_ref() != RelPath::empty() => {log::info!("deleting entry {:?} ({})", entry.path, entry.id.to_usize());- let task = worktree- .delete_entry(entry.id, false, cx)- .unwrap_or_else(|| Task::ready(Ok(None)));+ let task = worktree.delete_entry(entry.clone(), cx);cx.background_spawn(async move {task.await?;