1use crate::schema::json_schema_for;
2use anyhow::{Context as _, Result, anyhow};
3use assistant_tool::{ActionLog, Tool, ToolResult};
4use gpui::{AnyWindowHandle, App, AppContext, Entity, Task};
5use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
6use project::Project;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use std::{path::PathBuf, sync::Arc};
10use ui::IconName;
11use util::markdown::MarkdownEscaped;
12
13#[derive(Debug, Serialize, Deserialize, JsonSchema)]
14pub struct OpenToolInput {
15 /// The path or URL to open with the default application.
16 path_or_url: String,
17}
18
19pub struct OpenTool;
20
21impl Tool for OpenTool {
22 fn name(&self) -> String {
23 "open".to_string()
24 }
25
26 fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
27 true
28 }
29
30 fn description(&self) -> String {
31 include_str!("./open_tool/description.md").to_string()
32 }
33
34 fn icon(&self) -> IconName {
35 IconName::ArrowUpRight
36 }
37
38 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
39 json_schema_for::<OpenToolInput>(format)
40 }
41
42 fn ui_text(&self, input: &serde_json::Value) -> String {
43 match serde_json::from_value::<OpenToolInput>(input.clone()) {
44 Ok(input) => format!("Open `{}`", MarkdownEscaped(&input.path_or_url)),
45 Err(_) => "Open file or URL".to_string(),
46 }
47 }
48
49 fn run(
50 self: Arc<Self>,
51 input: serde_json::Value,
52 _request: Arc<LanguageModelRequest>,
53 project: Entity<Project>,
54 _action_log: Entity<ActionLog>,
55 _model: Arc<dyn LanguageModel>,
56 _window: Option<AnyWindowHandle>,
57 cx: &mut App,
58 ) -> ToolResult {
59 let input: OpenToolInput = match serde_json::from_value(input) {
60 Ok(input) => input,
61 Err(err) => return Task::ready(Err(anyhow!(err))).into(),
62 };
63
64 // If path_or_url turns out to be a path in the project, make it absolute.
65 let abs_path = to_absolute_path(&input.path_or_url, project, cx);
66
67 cx.background_spawn(async move {
68 match abs_path {
69 Some(path) => open::that(path),
70 None => open::that(&input.path_or_url),
71 }
72 .context("Failed to open URL or file path")?;
73
74 Ok(format!("Successfully opened {}", input.path_or_url).into())
75 })
76 .into()
77 }
78}
79
80fn to_absolute_path(
81 potential_path: &str,
82 project: Entity<Project>,
83 cx: &mut App,
84) -> Option<PathBuf> {
85 let project = project.read(cx);
86 project
87 .find_project_path(PathBuf::from(potential_path), cx)
88 .and_then(|project_path| project.absolute_path(&project_path, cx))
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94 use gpui::TestAppContext;
95 use project::{FakeFs, Project};
96 use settings::SettingsStore;
97 use std::path::Path;
98 use tempfile::TempDir;
99
100 #[gpui::test]
101 async fn test_to_absolute_path(cx: &mut TestAppContext) {
102 init_test(cx);
103 let temp_dir = TempDir::new().expect("Failed to create temp directory");
104 let temp_path = temp_dir.path().to_string_lossy().to_string();
105
106 let fs = FakeFs::new(cx.executor());
107 fs.insert_tree(
108 &temp_path,
109 serde_json::json!({
110 "src": {
111 "main.rs": "fn main() {}",
112 "lib.rs": "pub fn lib_fn() {}"
113 },
114 "docs": {
115 "readme.md": "# Project Documentation"
116 }
117 }),
118 )
119 .await;
120
121 // Use the temp_path as the root directory, not just its filename
122 let project = Project::test(fs.clone(), [temp_dir.path()], cx).await;
123
124 // Test cases where the function should return Some
125 cx.update(|cx| {
126 // Project-relative paths should return Some
127 // Create paths using the last segment of the temp path to simulate a project-relative path
128 let root_dir_name = Path::new(&temp_path)
129 .file_name()
130 .unwrap_or_else(|| std::ffi::OsStr::new("temp"))
131 .to_string_lossy();
132
133 assert!(
134 to_absolute_path(&format!("{root_dir_name}/src/main.rs"), project.clone(), cx)
135 .is_some(),
136 "Failed to resolve main.rs path"
137 );
138
139 assert!(
140 to_absolute_path(
141 &format!("{root_dir_name}/docs/readme.md",),
142 project.clone(),
143 cx,
144 )
145 .is_some(),
146 "Failed to resolve readme.md path"
147 );
148
149 // External URL should return None
150 let result = to_absolute_path("https://example.com", project.clone(), cx);
151 assert_eq!(result, None, "External URLs should return None");
152
153 // Path outside project
154 let result = to_absolute_path("../invalid/path", project.clone(), cx);
155 assert_eq!(result, None, "Paths outside the project should return None");
156 });
157 }
158
159 fn init_test(cx: &mut TestAppContext) {
160 cx.update(|cx| {
161 let settings_store = SettingsStore::test(cx);
162 cx.set_global(settings_store);
163 language::init(cx);
164 Project::init_settings(cx);
165 });
166 }
167}