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::{LanguageModelRequestMessage, 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 _messages: &[LanguageModelRequestMessage],
53 project: Entity<Project>,
54 _action_log: Entity<ActionLog>,
55 _window: Option<AnyWindowHandle>,
56 cx: &mut App,
57 ) -> ToolResult {
58 let input: OpenToolInput = match serde_json::from_value(input) {
59 Ok(input) => input,
60 Err(err) => return Task::ready(Err(anyhow!(err))).into(),
61 };
62
63 // If path_or_url turns out to be a path in the project, make it absolute.
64 let abs_path = to_absolute_path(&input.path_or_url, project, cx);
65
66 cx.background_spawn(async move {
67 match abs_path {
68 Some(path) => open::that(path),
69 None => open::that(&input.path_or_url),
70 }
71 .context("Failed to open URL or file path")?;
72
73 Ok(format!("Successfully opened {}", input.path_or_url))
74 })
75 .into()
76 }
77}
78
79fn to_absolute_path(
80 potential_path: &str,
81 project: Entity<Project>,
82 cx: &mut App,
83) -> Option<PathBuf> {
84 let project = project.read(cx);
85 project
86 .find_project_path(PathBuf::from(potential_path), cx)
87 .and_then(|project_path| project.absolute_path(&project_path, cx))
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 use gpui::TestAppContext;
94 use project::{FakeFs, Project};
95 use settings::SettingsStore;
96 use std::path::Path;
97 use tempfile::TempDir;
98
99 #[gpui::test]
100 async fn test_to_absolute_path(cx: &mut TestAppContext) {
101 init_test(cx);
102 let temp_dir = TempDir::new().expect("Failed to create temp directory");
103 let temp_path = temp_dir.path().to_string_lossy().to_string();
104
105 let fs = FakeFs::new(cx.executor());
106 fs.insert_tree(
107 &temp_path,
108 serde_json::json!({
109 "src": {
110 "main.rs": "fn main() {}",
111 "lib.rs": "pub fn lib_fn() {}"
112 },
113 "docs": {
114 "readme.md": "# Project Documentation"
115 }
116 }),
117 )
118 .await;
119
120 // Use the temp_path as the root directory, not just its filename
121 let project = Project::test(fs.clone(), [temp_dir.path()], cx).await;
122
123 // Test cases where the function should return Some
124 cx.update(|cx| {
125 // Project-relative paths should return Some
126 // Create paths using the last segment of the temp path to simulate a project-relative path
127 let root_dir_name = Path::new(&temp_path)
128 .file_name()
129 .unwrap_or_else(|| std::ffi::OsStr::new("temp"))
130 .to_string_lossy();
131
132 assert!(
133 to_absolute_path(&format!("{root_dir_name}/src/main.rs"), project.clone(), cx)
134 .is_some(),
135 "Failed to resolve main.rs path"
136 );
137
138 assert!(
139 to_absolute_path(
140 &format!("{root_dir_name}/docs/readme.md",),
141 project.clone(),
142 cx,
143 )
144 .is_some(),
145 "Failed to resolve readme.md path"
146 );
147
148 // External URL should return None
149 let result = to_absolute_path("https://example.com", project.clone(), cx);
150 assert_eq!(result, None, "External URLs should return None");
151
152 // Path outside project
153 let result = to_absolute_path("../invalid/path", project.clone(), cx);
154 assert_eq!(result, None, "Paths outside the project should return None");
155 });
156 }
157
158 fn init_test(cx: &mut TestAppContext) {
159 cx.update(|cx| {
160 let settings_store = SettingsStore::test(cx);
161 cx.set_global(settings_store);
162 language::init(cx);
163 Project::init_settings(cx);
164 });
165 }
166}