delete_path_tool.rs

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