1use crate::{AgentTool, ToolCallEventStream};
  2use action_log::ActionLog;
  3use agent_client_protocol::ToolKind;
  4use anyhow::{Context as _, Result, anyhow};
  5use futures::{SinkExt, StreamExt, channel::mpsc};
  6use gpui::{App, AppContext, Entity, SharedString, Task};
  7use project::{Project, ProjectPath};
  8use schemars::JsonSchema;
  9use serde::{Deserialize, Serialize};
 10use std::sync::Arc;
 11
 12/// Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.
 13#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 14pub struct DeletePathToolInput {
 15    /// The path of the file or directory to delete.
 16    ///
 17    /// <example>
 18    /// If the project has the following files:
 19    ///
 20    /// - directory1/a/something.txt
 21    /// - directory2/a/things.txt
 22    /// - directory3/a/other.txt
 23    ///
 24    /// You can delete the first file by providing a path of "directory1/a/something.txt"
 25    /// </example>
 26    pub path: String,
 27}
 28
 29pub struct DeletePathTool {
 30    project: Entity<Project>,
 31    action_log: Entity<ActionLog>,
 32}
 33
 34impl DeletePathTool {
 35    pub const fn new(project: Entity<Project>, action_log: Entity<ActionLog>) -> Self {
 36        Self {
 37            project,
 38            action_log,
 39        }
 40    }
 41}
 42
 43impl AgentTool for DeletePathTool {
 44    type Input = DeletePathToolInput;
 45    type Output = String;
 46
 47    fn name() -> &'static str {
 48        "delete_path"
 49    }
 50
 51    fn kind() -> ToolKind {
 52        ToolKind::Delete
 53    }
 54
 55    fn initial_title(
 56        &self,
 57        input: Result<Self::Input, serde_json::Value>,
 58        _cx: &mut App,
 59    ) -> SharedString {
 60        if let Ok(input) = input {
 61            format!("Delete “`{}`”", input.path).into()
 62        } else {
 63            "Delete path".into()
 64        }
 65    }
 66
 67    fn run(
 68        self: Arc<Self>,
 69        input: Self::Input,
 70        _event_stream: ToolCallEventStream,
 71        cx: &mut App,
 72    ) -> Task<Result<Self::Output>> {
 73        let path = input.path;
 74        let Some(project_path) = self.project.read(cx).find_project_path(&path, cx) else {
 75            return Task::ready(Err(anyhow!(
 76                "Couldn't delete {path} because that path isn't in this project."
 77            )));
 78        };
 79
 80        let Some(worktree) = self
 81            .project
 82            .read(cx)
 83            .worktree_for_id(project_path.worktree_id, cx)
 84        else {
 85            return Task::ready(Err(anyhow!(
 86                "Couldn't delete {path} because that path isn't in this project."
 87            )));
 88        };
 89
 90        let worktree_snapshot = worktree.read(cx).snapshot();
 91        let (mut paths_tx, mut paths_rx) = mpsc::channel(256);
 92        cx.background_spawn({
 93            let project_path = project_path.clone();
 94            async move {
 95                for entry in
 96                    worktree_snapshot.traverse_from_path(true, false, false, &project_path.path)
 97                {
 98                    if !entry.path.starts_with(&project_path.path) {
 99                        break;
100                    }
101                    paths_tx
102                        .send(ProjectPath {
103                            worktree_id: project_path.worktree_id,
104                            path: entry.path.clone(),
105                        })
106                        .await?;
107                }
108                anyhow::Ok(())
109            }
110        })
111        .detach();
112
113        let project = self.project.clone();
114        let action_log = self.action_log.clone();
115        cx.spawn(async move |cx| {
116            while let Some(path) = paths_rx.next().await {
117                if let Ok(buffer) = project
118                    .update(cx, |project, cx| project.open_buffer(path, cx))?
119                    .await
120                {
121                    action_log.update(cx, |action_log, cx| {
122                        action_log.will_delete_buffer(buffer.clone(), cx)
123                    })?;
124                }
125            }
126
127            let deletion_task = project
128                .update(cx, |project, cx| {
129                    project.delete_file(project_path, false, cx)
130                })?
131                .with_context(|| {
132                    format!("Couldn't delete {path} because that path isn't in this project.")
133                })?;
134            deletion_task
135                .await
136                .with_context(|| format!("Deleting {path}"))?;
137            Ok(format!("Deleted {path}"))
138        })
139    }
140}