Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

agent: Fix project skill mentions, share links, and deletion in remote workspaces (#66207)

Smit Barmasee8e579d6eacd
diff --git a/crates/agent_ui/src/mention_set.rs b/crates/agent_ui/src/mention_set.rs
index d6f0cd6ef2e..25588a3baf2 100644
--- a/crates/agent_ui/src/mention_set.rs
+++ b/crates/agent_ui/src/mention_set.rs
@@ -10,6 +10,7 @@ use editor::{
display_map::{Crease, CreaseId, CreaseMetadata, FoldId},
scroll::Autoscroll,
};
+use fs::Fs;
use futures::{AsyncReadExt as _, FutureExt as _, future::Shared};
use gpui::{
AppContext, ClipboardEntry, Context, Empty, Entity, EntityId, Image, ImageFormat, Img,
@@ -147,8 +148,10 @@ impl MentionSet {
..
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
MentionUri::Skill {
- skill_file_path, ..
- } => self.confirm_mention_for_skill(skill_file_path, cx),
+ source,
+ skill_file_path,
+ ..
+ } => self.confirm_mention_for_skill(source, skill_file_path, cx),
MentionUri::Diagnostics {
include_errors,
include_warnings,
@@ -321,8 +324,10 @@ impl MentionSet {
..
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
MentionUri::Skill {
- skill_file_path, ..
- } => self.confirm_mention_for_skill(skill_file_path, cx),
+ source,
+ skill_file_path,
+ ..
+ } => self.confirm_mention_for_skill(source, skill_file_path, cx),
MentionUri::Diagnostics {
include_errors,
include_warnings,
@@ -494,6 +499,7 @@ impl MentionSet {
fn confirm_mention_for_skill(
&self,
+ source: String,
skill_file_path: PathBuf,
cx: &mut Context<Self>,
) -> Task<Result<Mention>> {
@@ -505,8 +511,26 @@ impl MentionSet {
tracked_buffers: Vec::new(),
}));
}
+ // Project skills may be on a remote machine, so read them through the project.
+ // Global skills stay local, even if a worktree contains their path.
+ if let Some(project) = self.project.upgrade()
+ && let Some(buffer) = project.update(cx, |project, cx| {
+ let project_path = project_path_for_skill(project, &source, &skill_file_path, cx)?;
+ Some(project.open_buffer(project_path, cx))
+ })
+ {
+ return cx.spawn(async move |_, cx| {
+ let buffer = buffer.await?;
+ let content = buffer.update(cx, |buffer, _cx| buffer.text());
+ Ok(Mention::Text {
+ content,
+ tracked_buffers: Vec::new(),
+ })
+ });
+ }
+ let fs = <dyn Fs>::global(cx);
cx.background_spawn(async move {
- let content = std::fs::read_to_string(&skill_file_path).map_err(|e| {
+ let content = fs.load(&skill_file_path).await.map_err(|e| {
anyhow!(
"Failed to read skill file {}: {}",
skill_file_path.display(),
@@ -709,6 +733,30 @@ impl MentionSet {
}
}
+/// A project skill's source is its worktree's root name.
+fn project_path_for_skill(
+ project: &Project,
+ source: &str,
+ skill_file_path: &Path,
+ cx: &App,
+) -> Option<ProjectPath> {
+ project.worktrees(cx).find_map(|worktree| {
+ let worktree = worktree.read(cx);
+ if worktree.root_name_str() != source {
+ return None;
+ }
+ let path_style = worktree.path_style();
+ let relative_path = path_style
+ .strip_prefix(skill_file_path, worktree.abs_path())
+ .ok()?;
+ let relative_path = RelPath::new(relative_path, path_style).ok()?;
+ Some(ProjectPath {
+ worktree_id: worktree.id(),
+ path: relative_path.into_arc(),
+ })
+ })
+}
+
/// Computes disambiguated labels for a set of mentions, so that mentions sharing
/// a base name get extra context (parent path components, skill source) to tell
/// them apart. Same approach as buffer tab titles and the sidebar.
@@ -836,6 +884,71 @@ mod tests {
}
}
+ #[gpui::test]
+ async fn test_global_skill_mention_inside_worktree_reads_from_host_fs(cx: &mut TestAppContext) {
+ let content = read_skill_mention_with_project_and_host_copies(
+ "global",
+ path!("/home/user"),
+ path!("/home/user/.agents/skills/my-skill/SKILL.md"),
+ cx,
+ )
+ .await;
+ assert_eq!(content, "host copy");
+ }
+
+ async fn read_skill_mention_with_project_and_host_copies(
+ source: &str,
+ worktree_root: &str,
+ skill_file_path: &str,
+ cx: &mut TestAppContext,
+ ) -> String {
+ init_test(cx);
+ let skill_directory = Path::new(skill_file_path).parent().unwrap();
+
+ let host_fs = FakeFs::new(cx.executor());
+ host_fs
+ .insert_tree(skill_directory, json!({ "SKILL.md": "host copy" }))
+ .await;
+ cx.update(|cx| <dyn Fs>::set_global(host_fs, cx));
+
+ let project_fs = FakeFs::new(cx.executor());
+ project_fs
+ .insert_tree(skill_directory, json!({ "SKILL.md": "project copy" }))
+ .await;
+ let project = Project::test(project_fs, [Path::new(worktree_root)], cx).await;
+ let mention_set = cx.new(|_cx| MentionSet::new(project.downgrade(), None));
+
+ let mention_task = mention_set.update(cx, |mention_set, cx| {
+ let http_client = project.read(cx).client().http_client();
+ mention_set.confirm_mention_for_uri(
+ MentionUri::Skill {
+ name: "my-skill".to_string(),
+ source: source.to_string(),
+ skill_file_path: skill_file_path.into(),
+ },
+ false,
+ http_client,
+ cx,
+ )
+ });
+ match mention_task.await.unwrap() {
+ Mention::Text { content, .. } => content,
+ other => panic!("Expected skill mention to resolve as text, got {other:?}"),
+ }
+ }
+
+ #[gpui::test]
+ async fn test_project_skill_mention_reads_through_project_fs(cx: &mut TestAppContext) {
+ let content = read_skill_mention_with_project_and_host_copies(
+ "project",
+ path!("/project"),
+ path!("/project/.agents/skills/my-skill/SKILL.md"),
+ cx,
+ )
+ .await;
+ assert_eq!(content, "project copy");
+ }
+
#[test]
fn test_is_raster_image_path_is_case_insensitive() {
// Regression test for #54308: drag-and-dropping a file whose extension
diff --git a/crates/settings_ui/src/pages.rs b/crates/settings_ui/src/pages.rs
index 6038a5eaa16..4fe316a1b09 100644
--- a/crates/settings_ui/src/pages.rs
+++ b/crates/settings_ui/src/pages.rs
@@ -33,6 +33,8 @@ pub(crate) use skill_creator::{
#[cfg(test)]
pub(crate) use skills_setup::displayed_skills;
pub(crate) use skills_setup::render_skills_setup_page;
+#[cfg(test)]
+pub(crate) use skills_setup::{copy_skill_share_link, trash_skill};
pub(crate) use tool_permissions_setup::render_tool_permissions_setup_page;
pub use tool_permissions_setup::{
diff --git a/crates/settings_ui/src/pages/skills_setup.rs b/crates/settings_ui/src/pages/skills_setup.rs
index 72d61885154..b6d13e35ad9 100644
--- a/crates/settings_ui/src/pages/skills_setup.rs
+++ b/crates/settings_ui/src/pages/skills_setup.rs
@@ -1,6 +1,8 @@
use agent_skills::{Skill, SkillIndex, SkillSource, encode_skill_share_link};
+use anyhow::Context as _;
use fs::RemoveOptions;
-use gpui::{App, ClipboardItem, PromptLevel, ScrollHandle, SharedString, prelude::*};
+use gpui::{App, ClipboardItem, Entity, PromptLevel, ScrollHandle, SharedString, Task, prelude::*};
+use project::{Project, WorktreeId};
use ui::{Divider, Tooltip, prelude::*};
use util::ResultExt as _;
@@ -9,6 +11,142 @@ use util::paths::PathExt as _;
use crate::pages::SkillCreatorOpenMode;
use crate::{SettingsUiFile, SettingsWindow};
+fn project_for_skill(
+ skill: &Skill,
+ settings_window: &SettingsWindow,
+ cx: &App,
+) -> Option<Entity<Project>> {
+ let SkillSource::ProjectLocal { worktree_id, .. } = &skill.source else {
+ return None;
+ };
+ let worktree_id = WorktreeId::from_usize(worktree_id.0);
+ // Collab projects use the host's worktree ids, which can repeat, so also check the path.
+ // The file path, unlike `directory_path`, is in the worktree's path style.
+ crate::all_projects(settings_window.original_window.as_ref(), cx).find(|project| {
+ project
+ .read(cx)
+ .worktree_for_id(worktree_id, cx)
+ .is_some_and(|worktree| {
+ let worktree = worktree.read(cx);
+ worktree
+ .path_style()
+ .starts_with(&skill.skill_file_path, worktree.abs_path())
+ })
+ })
+}
+
+pub(crate) fn copy_skill_share_link(
+ skill: &Skill,
+ settings_window: &SettingsWindow,
+ cx: &mut Context<SettingsWindow>,
+) -> Task<()> {
+ let skill_file_path = skill.skill_file_path.clone();
+ let directory_path = skill.directory_path.clone();
+ let project = project_for_skill(skill, settings_window, cx);
+ let fs = workspace::AppState::global(cx).fs.clone();
+ cx.spawn(async move |settings_window, cx| {
+ let content = match &project {
+ Some(project) => {
+ let Some(project_path) = project.update(cx, |project, cx| {
+ project.project_path_for_absolute_path(&skill_file_path, cx)
+ }) else {
+ log::error!(
+ "failed to read skill file {} for sharing: outside the project's worktrees",
+ skill_file_path.display()
+ );
+ return;
+ };
+ let buffer = project
+ .update(cx, |project, cx| project.open_buffer(project_path, cx))
+ .await;
+ buffer.map(|buffer| buffer.update(cx, |buffer, _cx| buffer.text()))
+ }
+ None => fs.load(&skill_file_path).await,
+ };
+ match content {
+ Ok(content) => {
+ let link = encode_skill_share_link(&content);
+ settings_window
+ .update(cx, |settings_window, cx| {
+ cx.write_to_clipboard(ClipboardItem::new_string(link));
+ settings_window.last_copied_skill_directory_path = Some(directory_path);
+ cx.notify();
+ })
+ .ok();
+ }
+ Err(error) => {
+ log::error!(
+ "failed to read skill file {} for sharing: {error:#}",
+ skill_file_path.display()
+ );
+ }
+ }
+ })
+}
+
+pub(crate) fn trash_skill(
+ skill: &Skill,
+ settings_window: &mut SettingsWindow,
+ cx: &mut Context<SettingsWindow>,
+) -> Task<()> {
+ let directory_path = skill.directory_path.clone();
+ if !settings_window
+ .hidden_deleted_skill_directory_paths
+ .insert(directory_path.clone())
+ {
+ return Task::ready(());
+ }
+ cx.notify();
+
+ let project = project_for_skill(skill, settings_window, cx);
+ let fs = workspace::AppState::global(cx).fs.clone();
+ cx.spawn(async move |settings_window, cx| {
+ let trash_result = match &project {
+ Some(project) => {
+ let trash_task = project.update(cx, |project, cx| {
+ let project_path = project
+ .project_path_for_absolute_path(&directory_path, cx)
+ .context("skill directory is outside the project's worktrees")?;
+ let entry_id = project
+ .entry_for_path(&project_path, cx)
+ .map(|entry| entry.id);
+ // Already deleted outside Zed.
+ anyhow::Ok(entry_id.and_then(|entry_id| project.trash_entry(entry_id, cx)))
+ });
+ match trash_task {
+ Ok(Some(trash_task)) => trash_task.await.map(|_| ()),
+ Ok(None) => Ok(()),
+ Err(error) => Err(error),
+ }
+ }
+ None => fs
+ .trash(
+ &directory_path,
+ RemoveOptions {
+ recursive: true,
+ ignore_if_not_exists: true,
+ },
+ )
+ .await
+ .map(|_| ()),
+ };
+ if let Err(error) = trash_result {
+ log::error!(
+ "failed to move skill directory {} to trash: {error:#}",
+ directory_path.display()
+ );
+ settings_window
+ .update(cx, |settings_window, cx| {
+ settings_window
+ .hidden_deleted_skill_directory_paths
+ .remove(&directory_path);
+ cx.notify();
+ })
+ .ok();
+ }
+ })
+}
+
/// Skills shown on the Skills page for the currently selected settings file:
/// - User file → global skills only
/// - Project file → project-local skills for that worktree only
@@ -123,6 +261,8 @@ fn render_skill_row(
_ => ("global", "on this machine"),
};
+ let delete_skill = skill.clone();
+
let share_copied = settings_window.last_copied_skill_directory_path.as_deref()
== Some(skill.directory_path.as_path());
let warning_message = skill.load_warnings.first().map(|warning| warning.message());
@@ -139,8 +279,7 @@ fn render_skill_row(
.ml(rems_from_px(-22.0_f32))
.gap_1()
.child({
- let share_skill_file_path = skill.skill_file_path.clone();
- let share_directory_path = skill.directory_path.clone();
+ let share_skill = skill.clone();
IconButton::new(
SharedString::from(format!("share-{}", skill.name)),
share_icon,
@@ -151,33 +290,8 @@ fn render_skill_row(
.icon_color(share_icon_color)
.tooltip(Tooltip::text("Copy Share Link"))
.visible_on_hover(&group)
- .on_click(cx.listener(move |_settings_window, _event, _window, cx| {
- let skill_file_path = share_skill_file_path.clone();
- let directory_path = share_directory_path.clone();
- let app_state = workspace::AppState::global(cx);
- let fs = app_state.fs.clone();
- cx.spawn(
- async move |settings_window, cx| match fs.load(&skill_file_path).await {
- Ok(content) => {
- let link = encode_skill_share_link(&content);
- settings_window
- .update(cx, |settings_window, cx| {
- cx.write_to_clipboard(ClipboardItem::new_string(link));
- settings_window.last_copied_skill_directory_path =
- Some(directory_path.clone());
- cx.notify();
- })
- .ok();
- }
- Err(error) => {
- log::error!(
- "failed to read skill file {} for sharing: {error:#}",
- skill_file_path.display()
- );
- }
- },
- )
- .detach();
+ .on_click(cx.listener(move |settings_window, _event, _window, cx| {
+ copy_skill_share_link(&share_skill, settings_window, cx).detach();
}))
})
.child(Label::new(skill.name.clone()))
@@ -246,51 +360,19 @@ fn render_skill_row(
cx,
);
- let app_state = workspace::AppState::global(cx);
- let fs = app_state.fs.clone();
+ let delete_skill = delete_skill.clone();
cx.spawn(async move |settings_window, cx| {
if answer.await != Ok(0) {
return;
}
-
- let confirmed = settings_window
- .update(cx, |settings_window, cx| {
- let inserted = settings_window
- .hidden_deleted_skill_directory_paths
- .insert(directory_path.clone());
- if inserted {
- cx.notify();
- }
- inserted
+ let Ok(trash_task) =
+ settings_window.update(cx, |settings_window, cx| {
+ trash_skill(&delete_skill, settings_window, cx)
})
- .unwrap_or(false);
- if !confirmed {
+ else {
return;
- }
-
- let trash_result = fs
- .trash(
- &directory_path,
- RemoveOptions {
- recursive: true,
- ignore_if_not_exists: true,
- },
- )
- .await;
- if let Err(error) = trash_result {
- log::error!(
- "failed to move skill directory {} to trash: {error:#}",
- directory_path.display()
- );
- settings_window
- .update(cx, |settings_window, cx| {
- settings_window
- .hidden_deleted_skill_directory_paths
- .remove(&directory_path);
- cx.notify();
- })
- .ok();
- }
+ };
+ trash_task.await;
})
.detach();
},
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index 96371f98a15..7e637cf8229 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -7124,6 +7124,210 @@ pub mod test {
});
}
+ /// The project's fs is separate from the host's, so tests can tell which one was used.
+ async fn init_project_skill_test(
+ cx: &mut gpui::TestAppContext,
+ ) -> (
+ Entity<SettingsWindow>,
+ &mut gpui::VisualTestContext,
+ Arc<fs::FakeFs>,
+ Arc<fs::FakeFs>,
+ project::WorktreeId,
+ ) {
+ use project::Project;
+ use serde_json::json;
+
+ cx.update(|cx| {
+ register_settings(cx);
+ });
+ let app_state = cx.update(|cx| {
+ let app_state = AppState::test(cx);
+ AppState::set_global(app_state.clone(), cx);
+ app_state
+ });
+
+ let host_fs = app_state.fs.as_fake();
+ host_fs
+ .insert_tree(
+ "/project",
+ json!({ ".agents": { "skills": { "my-skill": { "SKILL.md": "host copy" } } } }),
+ )
+ .await;
+ let project_fs = fs::FakeFs::new(cx.executor());
+ project_fs
+ .insert_tree(
+ "/project",
+ json!({ ".agents": { "skills": { "my-skill": { "SKILL.md": "project copy" } } } }),
+ )
+ .await;
+
+ let project = Project::test(project_fs.clone(), ["/project".as_ref()], cx).await;
+ let worktree_id = project.read_with(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+
+ let (_multi_workspace, cx) = cx.add_window_view(|window, cx| {
+ let workspace = cx.new(|cx| {
+ Workspace::new(
+ Default::default(),
+ project.clone(),
+ app_state.clone(),
+ window,
+ cx,
+ )
+ });
+ MultiWorkspace::new(workspace, window, cx)
+ });
+ let workspace_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
+ cx.run_until_parked();
+
+ let (settings_window, cx) = cx
+ .add_window_view(|window, cx| SettingsWindow::new(Some(workspace_handle), window, cx));
+ cx.run_until_parked();
+
+ (settings_window, cx, project_fs, host_fs, worktree_id)
+ }
+
+ fn project_skill(worktree_id: project::WorktreeId, name: &str) -> agent_skills::Skill {
+ let directory_path = PathBuf::from(format!("/project/.agents/skills/{name}"));
+ agent_skills::Skill {
+ name: name.to_string(),
+ description: String::new(),
+ source: agent_skills::SkillSource::ProjectLocal {
+ worktree_id: agent_skills::SkillScopeId(worktree_id.to_usize()),
+ worktree_root_name: "project".into(),
+ },
+ skill_file_path: directory_path.join("SKILL.md"),
+ directory_path,
+ load_warnings: Vec::new(),
+ disable_model_invocation: false,
+ embedded_body: None,
+ }
+ }
+
+ #[gpui::test]
+ async fn test_project_skill_share_link_reads_through_project(cx: &mut gpui::TestAppContext) {
+ let (settings_window, cx, _project_fs, _host_fs, worktree_id) =
+ init_project_skill_test(cx).await;
+ let skill = project_skill(worktree_id, "my-skill");
+
+ settings_window
+ .update(cx, |settings_window, cx| {
+ crate::pages::copy_skill_share_link(&skill, settings_window, cx)
+ })
+ .await;
+
+ assert_eq!(
+ cx.read_from_clipboard().and_then(|item| item.text()),
+ Some(agent_skills::encode_skill_share_link("project copy"))
+ );
+ settings_window.read_with(cx, |settings_window, _| {
+ assert_eq!(
+ settings_window.last_copied_skill_directory_path,
+ Some(skill.directory_path.clone())
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_project_skill_delete_trashes_through_project(cx: &mut gpui::TestAppContext) {
+ use fs::Fs as _;
+
+ let (settings_window, cx, project_fs, host_fs, worktree_id) =
+ init_project_skill_test(cx).await;
+ let skill = project_skill(worktree_id, "my-skill");
+
+ settings_window
+ .update(cx, |settings_window, cx| {
+ crate::pages::trash_skill(&skill, settings_window, cx)
+ })
+ .await;
+
+ assert!(!project_fs.is_dir(&skill.directory_path).await);
+ assert!(host_fs.is_dir(&skill.directory_path).await);
+ settings_window.read_with(cx, |settings_window, _| {
+ assert!(
+ settings_window
+ .hidden_deleted_skill_directory_paths
+ .contains(&skill.directory_path)
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_project_skill_share_link_skips_project_with_same_worktree_id(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ // Shares the project's worktree id but not its path, as a collab project can.
+ let (settings_window, cx, _project_fs, host_fs, worktree_id) =
+ init_project_skill_test(cx).await;
+ host_fs
+ .insert_tree(
+ "/elsewhere",
+ serde_json::json!({ ".agents": { "skills": { "my-skill": { "SKILL.md": "elsewhere copy" } } } }),
+ )
+ .await;
+ let mut skill = project_skill(worktree_id, "my-skill");
+ skill.directory_path = PathBuf::from("/elsewhere/.agents/skills/my-skill");
+ skill.skill_file_path = skill.directory_path.join("SKILL.md");
+
+ settings_window
+ .update(cx, |settings_window, cx| {
+ crate::pages::copy_skill_share_link(&skill, settings_window, cx)
+ })
+ .await;
+
+ assert_eq!(
+ cx.read_from_clipboard().and_then(|item| item.text()),
+ Some(agent_skills::encode_skill_share_link("elsewhere copy"))
+ );
+ }
+
+ #[gpui::test]
+ async fn test_project_skill_delete_failure_shows_skill_again(cx: &mut gpui::TestAppContext) {
+ let (settings_window, cx, project_fs, _host_fs, worktree_id) =
+ init_project_skill_test(cx).await;
+ let skill = project_skill(worktree_id, "my-skill");
+ project_fs.set_remove_dir_error(&skill.directory_path, "permission denied".into());
+
+ settings_window
+ .update(cx, |settings_window, cx| {
+ crate::pages::trash_skill(&skill, settings_window, cx)
+ })
+ .await;
+
+ settings_window.read_with(cx, |settings_window, _| {
+ assert!(
+ !settings_window
+ .hidden_deleted_skill_directory_paths
+ .contains(&skill.directory_path)
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_project_skill_delete_keeps_already_deleted_skill_hidden(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ let (settings_window, cx, _project_fs, _host_fs, worktree_id) =
+ init_project_skill_test(cx).await;
+ let skill = project_skill(worktree_id, "deleted-outside-zed");
+
+ settings_window
+ .update(cx, |settings_window, cx| {
+ crate::pages::trash_skill(&skill, settings_window, cx)
+ })
+ .await;
+
+ settings_window.read_with(cx, |settings_window, _| {
+ assert!(
+ settings_window
+ .hidden_deleted_skill_directory_paths
+ .contains(&skill.directory_path)
+ );
+ });
+ }
+
#[gpui::test]
async fn test_open_skill_creator_navigates_to_sub_page(cx: &mut gpui::TestAppContext) {
use project::Project;