1use crate::AgentTool;
2use agent_client_protocol::ToolKind;
3use anyhow::{Context as _, Result};
4use gpui::{App, AppContext, Entity, SharedString, Task};
5use project::Project;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use std::{path::PathBuf, sync::Arc};
9use util::markdown::MarkdownEscaped;
10
11/// This tool opens a file or URL with the default application associated with it on the user's operating system:
12///
13/// - On macOS, it's equivalent to the `open` command
14/// - On Windows, it's equivalent to `start`
15/// - On Linux, it uses something like `xdg-open`, `gio open`, `gnome-open`, `kde-open`, `wslview` as appropriate
16///
17/// For example, it can open a web browser with a URL, open a PDF file with the default PDF viewer, etc.
18///
19/// You MUST ONLY use this tool when the user has explicitly requested opening something. You MUST NEVER assume that the user would like for you to use this tool.
20#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
21pub struct OpenToolInput {
22 /// The path or URL to open with the default application.
23 path_or_url: String,
24}
25
26pub struct OpenTool {
27 project: Entity<Project>,
28}
29
30impl OpenTool {
31 pub fn new(project: Entity<Project>) -> Self {
32 Self { project }
33 }
34}
35
36impl AgentTool for OpenTool {
37 type Input = OpenToolInput;
38 type Output = String;
39
40 fn name() -> &'static str {
41 "open"
42 }
43
44 fn kind() -> ToolKind {
45 ToolKind::Execute
46 }
47
48 fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
49 if let Ok(input) = input {
50 format!("Open `{}`", MarkdownEscaped(&input.path_or_url)).into()
51 } else {
52 "Open file or URL".into()
53 }
54 }
55
56 fn run(
57 self: Arc<Self>,
58 input: Self::Input,
59 event_stream: crate::ToolCallEventStream,
60 cx: &mut App,
61 ) -> Task<Result<Self::Output>> {
62 // If path_or_url turns out to be a path in the project, make it absolute.
63 let abs_path = to_absolute_path(&input.path_or_url, self.project.clone(), cx);
64 let authorize = event_stream.authorize(self.initial_title(Ok(input.clone())), cx);
65 cx.background_spawn(async move {
66 authorize.await?;
67
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))
75 })
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}