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: Warn about long skill descriptions (#58356)

Anant Goel6d68395c49d7
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index f78c0d2e675..9e17d3b21f1 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -31,9 +31,9 @@ use acp_thread::{
use agent_client_protocol::schema as acp;
use agent_skills::{
AGENTS_DIR_NAME, MAX_SKILL_DESCRIPTIONS_SIZE, MAX_SKILL_FILE_SIZE, ProjectSkillGroup,
- SKILL_FILE_NAME, Skill, SkillIndex, SkillLoadError, SkillScopeId, SkillSource, SkillSummary,
- builtin_skills, global_skills_dir, load_skills_from_directory, parse_skill_frontmatter,
- project_skills_relative_path, read_skill_body_from_content,
+ SKILL_FILE_NAME, Skill, SkillIndex, SkillLoadError, SkillLoadWarning, SkillScopeId,
+ SkillSource, SkillSummary, builtin_skills, global_skills_dir, load_skills_from_directory,
+ parse_skill_frontmatter, project_skills_relative_path, read_skill_body_from_content,
};
use anyhow::{Context as _, Result, anyhow};
use chrono::{DateTime, Utc};
@@ -76,21 +76,67 @@ pub struct RulesLoadingError {
pub message: SharedString,
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum SkillLoadingIssueKind {
+ LoadFailed,
+ DescriptionTooLong,
+ CatalogBudgetExceeded,
+}
+
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
-pub struct SkillLoadingError {
+pub struct SkillLoadingIssue {
pub project_id: EntityId,
pub path: PathBuf,
pub message: SharedString,
+ pub kind: SkillLoadingIssueKind,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct SkillLoadingIssueData {
+ path: PathBuf,
+ message: String,
+ kind: SkillLoadingIssueKind,
}
-/// Emitted whenever the set of skill loading errors for a project changes.
-/// The `errors` field is the full replacement list; subscribers should treat
-/// it as a snapshot rather than appending. An empty `errors` list means all
-/// previously-reported errors have been resolved.
+impl SkillLoadingIssueData {
+ fn from_load_error(error: SkillLoadError) -> Self {
+ Self {
+ path: error.path,
+ message: error.message,
+ kind: SkillLoadingIssueKind::LoadFailed,
+ }
+ }
+
+ fn from_load_warning(skill: &Skill, warning: &SkillLoadWarning) -> Self {
+ let kind = match warning {
+ SkillLoadWarning::DescriptionTooLong { .. } => {
+ SkillLoadingIssueKind::DescriptionTooLong
+ }
+ };
+ Self {
+ path: skill.skill_file_path.clone(),
+ message: warning.message(),
+ kind,
+ }
+ }
+
+ fn catalog_budget_exceeded(path: PathBuf, message: String) -> Self {
+ Self {
+ path,
+ message,
+ kind: SkillLoadingIssueKind::CatalogBudgetExceeded,
+ }
+ }
+}
+
+/// Emitted whenever the set of skill loading issues for a project changes.
+/// The `issues` field is the full replacement list; subscribers should treat
+/// it as a snapshot rather than appending. An empty `issues` list means all
+/// previously-reported issues have been resolved.
#[derive(Clone, Debug)]
-pub struct SkillLoadingErrorsUpdated {
+pub struct SkillLoadingIssuesUpdated {
pub project_id: EntityId,
- pub errors: Vec<SkillLoadingError>,
+ pub issues: Vec<SkillLoadingIssue>,
}
#[derive(Clone, Debug)]
@@ -99,6 +145,7 @@ pub struct NativeAvailableSkill {
pub description: String,
pub source: SharedString,
pub skill_file_path: PathBuf,
+ pub warning: Option<SharedString>,
}
impl From<&Skill> for NativeAvailableSkill {
@@ -108,6 +155,10 @@ impl From<&Skill> for NativeAvailableSkill {
description: skill.description.clone(),
source: skill.source.display_label().to_string().into(),
skill_file_path: skill.skill_file_path.clone(),
+ warning: skill
+ .load_warnings
+ .first()
+ .map(|warning| warning.message().into()),
}
}
}
@@ -116,7 +167,7 @@ struct ProjectState {
project: Entity<Project>,
project_context: Entity<ProjectContext>,
skills: Arc<Vec<Skill>>,
- skill_loading_errors: Vec<SkillLoadingError>,
+ skill_loading_issues: Vec<SkillLoadingIssue>,
project_context_needs_refresh: watch::Sender<()>,
_maintain_project_context: Task<Result<()>>,
context_server_registry: Entity<ContextServerRegistry>,
@@ -357,7 +408,7 @@ enum SkillsState {
Watching,
}
-impl gpui::EventEmitter<SkillLoadingErrorsUpdated> for NativeAgent {}
+impl gpui::EventEmitter<SkillLoadingIssuesUpdated> for NativeAgent {}
static RULES_FILE_REL_PATHS: LazyLock<Vec<Arc<RelPath>>> = LazyLock::new(|| {
RULES_FILE_NAMES
@@ -816,7 +867,7 @@ impl NativeAgent {
project,
project_context,
skills: Arc::new(Vec::new()),
- skill_loading_errors: Vec::new(),
+ skill_loading_issues: Vec::new(),
project_context_needs_refresh: project_context_needs_refresh_tx,
_maintain_project_context: cx.spawn(async move |this, cx| {
Self::maintain_project_context(
@@ -857,34 +908,35 @@ impl NativeAgent {
cx,
))
})??;
- let (project_context, skills, skill_errors) = task.await;
+ let (project_context, skills, skill_issue_data) = task.await;
let skills = Arc::new(skills);
- let skill_loading_errors: Vec<SkillLoadingError> = skill_errors
+ let skill_loading_issues: Vec<SkillLoadingIssue> = skill_issue_data
.into_iter()
- .map(|skill_error| SkillLoadingError {
+ .map(|issue| SkillLoadingIssue {
project_id,
- path: skill_error.path,
- message: skill_error.message.into(),
+ path: issue.path,
+ message: issue.message.into(),
+ kind: issue.kind,
})
.collect();
this.update(cx, |this, cx| {
- // Only emit SkillLoadingErrorsUpdated when the error list
+ // Only emit SkillLoadingIssuesUpdated when the issue list
// actually changed. Refreshes happen frequently (prompt-store
// updates, rules-file edits, worktree events, trust-state
// changes), and re-emitting an unchanged list causes the UI
- // to redisplay errors the user has already dismissed.
+ // to redisplay issues the user has already dismissed.
// Transitions from non-empty to empty still count as a change,
// so subscribers continue to receive an empty list to clear
- // previously-displayed errors when they get resolved.
- let errors_changed = this
+ // previously-displayed issues when they get resolved.
+ let issues_changed = this
.projects
.get(&project_id)
- .map(|state| state.skill_loading_errors != skill_loading_errors)
+ .map(|state| state.skill_loading_issues != skill_loading_issues)
.unwrap_or(true);
if let Some(state) = this.projects.get_mut(&project_id) {
state.skills = skills;
- state.skill_loading_errors = skill_loading_errors.clone();
+ state.skill_loading_issues = skill_loading_issues.clone();
// Only push the new `ProjectContext` through if it
// differs from the current one. The system prompt is
// re-rendered from this on every turn, so an unchanged
@@ -903,10 +955,10 @@ impl NativeAgent {
}
});
}
- if errors_changed {
- cx.emit(SkillLoadingErrorsUpdated {
+ if issues_changed {
+ cx.emit(SkillLoadingIssuesUpdated {
project_id,
- errors: skill_loading_errors,
+ issues: skill_loading_issues,
});
}
// Skills appear in the slash-command list, so a change in
@@ -926,7 +978,7 @@ impl NativeAgent {
project: &Entity<Project>,
fs: Arc<dyn Fs>,
cx: &mut App,
- ) -> Task<(ProjectContext, Vec<Skill>, Vec<SkillLoadError>)> {
+ ) -> Task<(ProjectContext, Vec<Skill>, Vec<SkillLoadingIssueData>)> {
let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
let worktree_tasks = worktrees
.iter()
@@ -1085,8 +1137,20 @@ impl NativeAgent {
// model-facing catalog.
let global_skills = global_skills_task.await;
let project_skills_results = project_skills_task.await;
- let (skills, mut skill_errors) =
+ let (skills, skill_errors) =
combine_skills(global_skills, project_skills_results.into_iter().flatten());
+ let mut skill_issues = skill_errors
+ .into_iter()
+ .map(SkillLoadingIssueData::from_load_error)
+ .collect::<Vec<_>>();
+ for skill in &skills {
+ skill_issues.extend(
+ skill
+ .load_warnings
+ .iter()
+ .map(|warning| SkillLoadingIssueData::from_load_warning(skill, warning)),
+ );
+ }
// Apply project-overrides-global before catalog selection
// so the model sees at most one entry per name. The full
@@ -1095,13 +1159,13 @@ impl NativeAgent {
let overridden = apply_skill_overrides(&skills);
// Enforce the catalog size budget here so that skills which
- // don't fit produce a load error in the UI rather than being
+ // don't fit produce an issue in the UI rather than being
// silently swallowed by ProjectContext.
- let (catalog_skills, budget_errors) = select_catalog_skills(&overridden);
- skill_errors.extend(budget_errors);
+ let (catalog_skills, budget_issues) = select_catalog_skills(&overridden);
+ skill_issues.extend(budget_issues);
let project_context = ProjectContext::new(worktrees).with_skills(catalog_skills);
- (project_context, skills, skill_errors)
+ (project_context, skills, skill_issues)
})
}
@@ -3193,9 +3257,9 @@ impl TerminalHandle for AcpTerminalHandle {
/// Returns `SkillSummary` values rather than full `Skill`s so that the
/// (potentially ~100KB) skill bodies aren't cloned just to be discarded by
/// `ProjectContext::new`, which only needs the summary fields.
-fn select_catalog_skills(skills: &[Skill]) -> (Vec<SkillSummary>, Vec<SkillLoadError>) {
+fn select_catalog_skills(skills: &[Skill]) -> (Vec<SkillSummary>, Vec<SkillLoadingIssueData>) {
let mut kept = Vec::new();
- let mut errors = Vec::new();
+ let mut issues = Vec::new();
let mut dropped: Vec<&Skill> = Vec::new();
let mut total_size = 0usize;
let mut budget_exceeded = false;
@@ -3248,13 +3312,13 @@ fn select_catalog_skills(skills: &[Skill]) -> (Vec<SkillSummary>, Vec<SkillLoadE
}
message
};
- errors.push(SkillLoadError {
- path: first.skill_file_path.clone(),
+ issues.push(SkillLoadingIssueData::catalog_budget_exceeded(
+ first.skill_file_path.clone(),
message,
- });
+ ));
}
- (kept, errors)
+ (kept, issues)
}
/// Build a closure that, when called, reads the latest `state.skills`
@@ -3441,6 +3505,7 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from(format!("/home/user/.agents/skills/{name}")),
skill_file_path: PathBuf::from(format!("/home/user/.agents/skills/{name}/SKILL.md")),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
}
@@ -3456,6 +3521,7 @@ mod internal_tests {
},
directory_path: PathBuf::from(format!("/{worktree}/.agents/skills/{name}")),
skill_file_path: PathBuf::from(format!("/{worktree}/.agents/skills/{name}/SKILL.md")),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
}
@@ -3468,6 +3534,7 @@ mod internal_tests {
source: SkillSource::BuiltIn,
directory_path: PathBuf::from(format!("/builtin/{name}")),
skill_file_path: PathBuf::from(format!("/builtin/{name}/SKILL.md")),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: Some("built-in body"),
}
@@ -3631,10 +3698,10 @@ mod internal_tests {
}
#[test]
- fn test_select_catalog_skills_emits_errors_for_dropped_skills() {
+ fn test_select_catalog_skills_emits_issue_for_dropped_skills() {
// Each skill's name + description occupies ~10KB. With a 50KB
// budget, only the first ~5 visible skills fit; the rest must
- // appear as load errors so the UI can surface them.
+ // appear as loading issues so the UI can surface them.
let description = "x".repeat(10 * 1024);
let mut skills = Vec::new();
let total = 10;
@@ -3646,12 +3713,13 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from(format!("/skills/{name}")),
skill_file_path: PathBuf::from(format!("/skills/{name}/SKILL.md")),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
});
}
- let (kept, errors) = select_catalog_skills(&skills);
+ let (kept, issues) = select_catalog_skills(&skills);
assert!(
kept.len() < skills.len(),
@@ -3660,9 +3728,9 @@ mod internal_tests {
skills.len(),
);
assert_eq!(
- errors.len(),
+ issues.len(),
1,
- "all dropped skills should be consolidated into a single error, got {errors:?}",
+ "all dropped skills should be consolidated into a single issue, got {issues:?}",
);
let kept_size: usize = kept
@@ -3674,33 +3742,34 @@ mod internal_tests {
"kept skills must fit in the budget (got {kept_size} bytes)",
);
- let error = &errors[0];
+ let issue = &issues[0];
+ assert_eq!(issue.kind, SkillLoadingIssueKind::CatalogBudgetExceeded);
assert!(
- error.message.contains("50KB") && error.message.contains("budget"),
- "error message {:?} should describe the budget",
- error.message,
+ issue.message.contains("50KB") && issue.message.contains("budget"),
+ "issue message {:?} should describe the budget",
+ issue.message,
);
assert_eq!(
- error.path,
+ issue.path,
skills[kept.len()].skill_file_path,
- "error path should match the first dropped skill",
+ "issue path should match the first dropped skill",
);
for dropped_skill in &skills[kept.len()..total] {
let name = &dropped_skill.name;
assert!(
- error.message.contains(name.as_str()),
- "error message {:?} should mention the dropped skill name {name:?}",
- error.message,
+ issue.message.contains(name.as_str()),
+ "issue message {:?} should mention the dropped skill name {name:?}",
+ issue.message,
);
let bullet_line = format!("- {name}");
assert!(
- error
+ issue
.message
.lines()
.any(|line| line.starts_with(&bullet_line)),
- "error message {:?} should contain a bullet line starting with {bullet_line:?}",
- error.message,
+ "issue message {:?} should contain a bullet line starting with {bullet_line:?}",
+ issue.message,
);
}
}
@@ -3721,6 +3790,7 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/skill-01-first"),
skill_file_path: PathBuf::from("/skills/skill-01-first/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
};
@@ -3730,6 +3800,7 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/skill-02-overflows"),
skill_file_path: PathBuf::from("/skills/skill-02-overflows/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
};
@@ -3739,6 +3810,7 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/skill-03-would-fit"),
skill_file_path: PathBuf::from("/skills/skill-03-would-fit/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
};
@@ -3754,29 +3826,30 @@ mod internal_tests {
);
let skills = vec![first.clone(), second.clone(), third.clone()];
- let (kept, errors) = select_catalog_skills(&skills);
+ let (kept, issues) = select_catalog_skills(&skills);
let kept_names: Vec<&str> = kept.iter().map(|s| s.name.as_str()).collect();
assert_eq!(kept_names, vec![first.name.as_str()]);
- assert_eq!(errors.len(), 1, "expected a single consolidated error");
- assert_eq!(errors[0].path, second.skill_file_path);
+ assert_eq!(issues.len(), 1, "expected a single consolidated issue");
+ assert_eq!(issues[0].kind, SkillLoadingIssueKind::CatalogBudgetExceeded);
+ assert_eq!(issues[0].path, second.skill_file_path);
assert!(
- errors[0].message.contains(second.name.as_str()),
- "error message {:?} should mention {:?}",
- errors[0].message,
+ issues[0].message.contains(second.name.as_str()),
+ "issue message {:?} should mention {:?}",
+ issues[0].message,
second.name,
);
assert!(
- errors[0].message.contains(third.name.as_str()),
- "error message {:?} should mention {:?}",
- errors[0].message,
+ issues[0].message.contains(third.name.as_str()),
+ "issue message {:?} should mention {:?}",
+ issues[0].message,
third.name,
);
assert!(
- errors[0].message.contains("- "),
- "error message {:?} should use bullet form when multiple skills are dropped",
- errors[0].message,
+ issues[0].message.contains("- "),
+ "issue message {:?} should use bullet form when multiple skills are dropped",
+ issues[0].message,
);
}
@@ -3786,7 +3859,7 @@ mod internal_tests {
// must not appear in the catalog returned by `select_catalog_skills`,
// even when they would otherwise fit in the budget. They also don't
// count against the budget, so a hidden skill larger than the entire
- // budget shouldn't generate a load error or prevent later visible
+ // budget shouldn't generate a loading issue or prevent later visible
// skills from fitting.
let huge_description = "y".repeat(MAX_SKILL_DESCRIPTIONS_SIZE * 2);
let hidden = Skill {
@@ -3795,6 +3868,7 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/hidden-huge"),
skill_file_path: PathBuf::from("/skills/hidden-huge/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: true,
embedded_body: None,
};
@@ -3804,13 +3878,14 @@ mod internal_tests {
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/visible"),
skill_file_path: PathBuf::from("/skills/visible/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
};
- let (kept, errors) = select_catalog_skills(&[hidden, visible]);
+ let (kept, issues) = select_catalog_skills(&[hidden, visible]);
- assert!(errors.is_empty(), "expected no errors, got: {errors:?}");
+ assert!(issues.is_empty(), "expected no issues, got: {issues:?}");
let kept_names: Vec<&str> = kept.iter().map(|s| s.name.as_str()).collect();
assert_eq!(kept_names, vec!["visible"]);
}
@@ -3968,6 +4043,101 @@ mod internal_tests {
});
}
+ #[gpui::test]
+ async fn test_global_skill_with_long_description_loads_with_warning(cx: &mut TestAppContext) {
+ init_test(cx);
+ let fs = FakeFs::new(cx.executor());
+ let skills_dir = global_skills_dir();
+ let skill_dir = skills_dir.join("long-description");
+ let skill_path = skill_dir.join("SKILL.md");
+ let long_description = "a".repeat(agent_skills::MAX_SKILL_DESCRIPTION_LEN + 1);
+ fs.create_dir(&skill_dir).await.unwrap();
+ fs.insert_file(
+ &skill_path,
+ format!("---\nname: long-description\ndescription: {long_description}\n---\n\nbody")
+ .into_bytes(),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [], cx).await;
+ let project_id = project.entity_id();
+ let thread_store = cx.new(|cx| ThreadStore::new(cx));
+ let agent =
+ cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
+
+ cx.update(|cx| {
+ agent.update(cx, |agent, cx| agent.ensure_skills_scan_started(cx));
+ });
+
+ let connection = NativeAgentConnection(agent.clone());
+ let acp_thread = cx
+ .update(|cx| {
+ Rc::new(connection.clone()).new_session(
+ project.clone(),
+ PathList::new(&[Path::new("/")]),
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let loaded_skill = agent.read_with(cx, |agent, cx| {
+ let state = agent.projects.get(&project_id).unwrap();
+ let user = user_skills(&state.skills);
+ assert_eq!(user.len(), 1);
+ assert_eq!(user[0].name, "long-description");
+ assert_eq!(user[0].description, long_description);
+
+ let catalog_names: Vec<&str> = state
+ .project_context
+ .read(cx)
+ .skills()
+ .iter()
+ .map(|skill| skill.name.as_str())
+ .collect();
+ assert!(
+ catalog_names.contains(&"long-description"),
+ "long-description skill should remain in the model catalog: {catalog_names:?}"
+ );
+
+ assert!(
+ state.skill_loading_issues.iter().any(|issue| {
+ issue.kind == SkillLoadingIssueKind::DescriptionTooLong
+ && issue.path == skill_path
+ && issue.message.to_string().contains("1024-byte limit")
+ }),
+ "expected a description-length warning issue, got {:?}",
+ state.skill_loading_issues
+ );
+
+ (*user[0]).clone()
+ });
+
+ let session_id = acp_thread.read_with(cx, |thread, _cx| thread.session_id().clone());
+ cx.update(|cx| {
+ let available_skills = connection.available_skills(&session_id, cx);
+ let available_skill = available_skills
+ .iter()
+ .find(|skill| skill.name == "long-description")
+ .expect("long-description should appear in available skills");
+ assert_eq!(available_skill.description, long_description);
+ assert!(
+ available_skill
+ .warning
+ .as_ref()
+ .is_some_and(|warning| warning.contains("1024-byte limit")),
+ "available skill should expose warning text, got {:?}",
+ available_skill.warning
+ );
+ });
+
+ let body = agent_skills::read_skill_body(fs.as_ref(), &loaded_skill.skill_file_path)
+ .await
+ .expect("body should load despite description-length warning");
+ assert_eq!(body, "body");
+ }
+
#[gpui::test]
async fn test_symlinked_global_skills_load_and_reload(cx: &mut TestAppContext) {
init_test(cx);
@@ -4765,11 +4935,12 @@ mod internal_tests {
);
assert!(
state
- .skill_loading_errors
+ .skill_loading_issues
.iter()
- .any(|error| error.message.to_string().contains("maximum size")),
+ .any(|issue| issue.kind == SkillLoadingIssueKind::LoadFailed
+ && issue.message.to_string().contains("maximum size")),
"expected a size-limit error, got {:?}",
- state.skill_loading_errors
+ state.skill_loading_issues
);
});
}
@@ -4811,11 +4982,12 @@ mod internal_tests {
assert_eq!(names, vec!["good"], "only the valid skill should load");
assert!(
state
- .skill_loading_errors
+ .skill_loading_issues
.iter()
- .any(|error| error.path.ends_with("bad/SKILL.md")),
+ .any(|issue| issue.kind == SkillLoadingIssueKind::LoadFailed
+ && issue.path.ends_with("bad/SKILL.md")),
"expected an error for the malformed skill, got {:?}",
- state.skill_loading_errors
+ state.skill_loading_issues
);
});
}
diff --git a/crates/agent_skills/agent_skills.rs b/crates/agent_skills/agent_skills.rs
index e545aaed6dd..a4d20ea5f78 100644
--- a/crates/agent_skills/agent_skills.rs
+++ b/crates/agent_skills/agent_skills.rs
@@ -51,6 +51,24 @@ pub const MAX_SKILL_DESCRIPTIONS_SIZE: usize = 50 * 1024;
/// The name of the skill definition file
pub const SKILL_FILE_NAME: &str = "SKILL.md";
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum SkillLoadWarning {
+ DescriptionTooLong { actual_len: usize, max_len: usize },
+}
+
+impl SkillLoadWarning {
+ pub fn message(&self) -> String {
+ match self {
+ Self::DescriptionTooLong {
+ actual_len,
+ max_len,
+ } => format!(
+ "Skill description is {actual_len} bytes, exceeding the {max_len}-byte limit. The skill was loaded, but long descriptions may consume more model-context tokens."
+ ),
+ }
+ }
+}
+
/// Represents a loaded skill with all its metadata and content.
#[derive(Debug, Clone)]
pub struct Skill {
@@ -61,6 +79,8 @@ pub struct Skill {
pub directory_path: PathBuf,
/// Absolute path to the SKILL.md file
pub skill_file_path: PathBuf,
+ /// Non-fatal issues found while loading this skill.
+ pub load_warnings: Vec<SkillLoadWarning>,
/// When `true`, this skill is hidden from the model's catalog and the
/// `skill` tool refuses to load it. The user can still invoke it as a
/// slash command.
@@ -242,7 +262,7 @@ pub fn parse_skill_frontmatter(
content: &str,
source: SkillSource,
) -> Result<Skill> {
- let (metadata, _body) = parse_skill_file_content(content)?;
+ let (metadata, _body, load_warnings) = parse_skill_file_content_for_loading(content)?;
let directory_path = skill_file_path
.parent()
@@ -255,6 +275,7 @@ pub fn parse_skill_frontmatter(
source,
directory_path,
skill_file_path: skill_file_path.to_path_buf(),
+ load_warnings,
disable_model_invocation: metadata.disable_model_invocation,
embedded_body: None,
})
@@ -283,6 +304,36 @@ pub fn parse_skill_file_content(content: &str) -> Result<(SkillMetadata, &str)>
Ok((metadata, body))
}
+fn parse_skill_file_content_for_loading(
+ content: &str,
+) -> Result<(SkillMetadata, &str, Vec<SkillLoadWarning>)> {
+ let (metadata, body) = extract_skill_frontmatter(content)?;
+
+ validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
+ let load_warnings =
+ validate_description_for_loading(&metadata.description).map_err(anyhow::Error::msg)?;
+
+ Ok((metadata, body, load_warnings))
+}
+
+fn validate_description_for_loading(
+ description: &str,
+) -> Result<Vec<SkillLoadWarning>, &'static str> {
+ if description.trim().is_empty() {
+ return Err("Skill description cannot be empty");
+ }
+
+ let mut warnings = Vec::new();
+ if description.len() > MAX_SKILL_DESCRIPTION_LEN {
+ warnings.push(SkillLoadWarning::DescriptionTooLong {
+ actual_len: description.len(),
+ max_len: MAX_SKILL_DESCRIPTION_LEN,
+ });
+ }
+
+ Ok(warnings)
+}
+
fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
let content = content.trim_start();
@@ -359,8 +410,9 @@ fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
/// by [`validate_name`].
pub const MAX_SKILL_NAME_LEN: usize = 64;
-/// Maximum length (in bytes) for a valid skill description. Mirrors the
-/// upper bound enforced by [`validate_description`].
+/// Maximum recommended length (in bytes) for a skill description. The
+/// create-skill UI enforces this as a hard limit, while the loader emits a
+/// warning and still loads longer descriptions.
///
/// Byte-based rather than char-based because that's what `.len()` returns
/// and what every caller currently measures; the UI also surfaces this
@@ -468,8 +520,8 @@ pub fn validate_name(name: &str) -> Result<(), &'static str> {
Ok(())
}
-/// Validate a skill description against the rules enforced by both the
-/// loader and the create-skill UI.
+/// Validate a skill description against the strict rules enforced by the
+/// create-skill UI and imported/shared skill parsing.
pub fn validate_description(description: &str) -> Result<(), &'static str> {
if description.trim().is_empty() {
return Err("Skill description cannot be empty");
@@ -627,10 +679,11 @@ pub fn read_skill_body_from_content(
skill_file_path: &Path,
content: &str,
) -> Result<String, SkillLoadError> {
- let (_metadata, body) = parse_skill_file_content(content).map_err(|e| SkillLoadError {
- path: skill_file_path.to_path_buf(),
- message: e.to_string(),
- })?;
+ let (_metadata, body, _load_warnings) =
+ parse_skill_file_content_for_loading(content).map_err(|e| SkillLoadError {
+ path: skill_file_path.to_path_buf(),
+ message: e.to_string(),
+ })?;
Ok(body.trim().to_string())
}
@@ -663,6 +716,7 @@ fn parse_builtin_skill(name: &str, content: &'static str) -> Result<Skill> {
source: SkillSource::BuiltIn,
directory_path: synthetic_dir,
skill_file_path: synthetic_path,
+ load_warnings: Vec::new(),
disable_model_invocation: metadata.disable_model_invocation,
embedded_body: Some(body.trim()),
})
@@ -1314,8 +1368,8 @@ Content.
}
#[test]
- fn test_parse_description_too_long() {
- let long_desc = "a".repeat(1025);
+ fn test_parse_description_too_long_loads_with_warning() {
+ let long_desc = "a".repeat(MAX_SKILL_DESCRIPTION_LEN + 1);
let content = format!(
r#"---
name: test
@@ -1326,11 +1380,38 @@ Content.
"#
);
- let result = parse_skill_frontmatter(
+ let skill = parse_skill_frontmatter(
Path::new("/skills/test/SKILL.md"),
&content,
SkillSource::Global,
+ )
+ .expect("long descriptions should load with a warning");
+
+ assert_eq!(skill.description, long_desc);
+ assert_eq!(skill.load_warnings.len(), 1);
+ assert_eq!(
+ skill.load_warnings[0],
+ SkillLoadWarning::DescriptionTooLong {
+ actual_len: MAX_SKILL_DESCRIPTION_LEN + 1,
+ max_len: MAX_SKILL_DESCRIPTION_LEN,
+ }
+ );
+ }
+
+ #[test]
+ fn test_parse_skill_file_content_rejects_description_too_long() {
+ let long_desc = "a".repeat(MAX_SKILL_DESCRIPTION_LEN + 1);
+ let content = format!(
+ r#"---
+name: test
+description: {long_desc}
+---
+
+Content.
+"#
);
+
+ let result = parse_skill_file_content(&content);
assert!(result.is_err());
let expected = format!("at most {MAX_SKILL_DESCRIPTION_LEN} bytes");
assert!(result.unwrap_err().to_string().contains(&expected));
@@ -1740,6 +1821,7 @@ description: A skill with no body content
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/test-skill"),
skill_file_path: PathBuf::from("/skills/test-skill/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
};
@@ -1879,6 +1961,27 @@ description: A skill with no body content
assert_eq!(body, "# Instructions\n\nDo the thing.");
}
+ #[gpui::test]
+ async fn test_read_skill_body_accepts_description_too_long(cx: &mut TestAppContext) {
+ let fs = FakeFs::new(cx.executor());
+ let long_desc = "a".repeat(MAX_SKILL_DESCRIPTION_LEN + 1);
+ fs.insert_tree(
+ "/skills",
+ serde_json::json!({
+ "long-description": {
+ "SKILL.md": format!("---\nname: long-description\ndescription: {long_desc}\n---\n\nBody")
+ }
+ }),
+ )
+ .await;
+
+ let body = read_skill_body(fs.as_ref(), Path::new("/skills/long-description/SKILL.md"))
+ .await
+ .expect("body should load despite description-length warning");
+
+ assert_eq!(body, "Body");
+ }
+
#[gpui::test]
async fn test_read_skill_body_for_skill_without_body(cx: &mut TestAppContext) {
let fs = FakeFs::new(cx.executor());
@@ -2028,8 +2131,8 @@ description: A skill with no body content
// "é" is 2 bytes in UTF-8. A string of MAX/2 + 1 "é" characters has
// only ~MAX/2 + 1 chars but exceeds MAX bytes, so it must be
// rejected by a byte-based validator (and accepted by a char-based
- // one). This regression-tests the byte semantics that the loader
- // and UI both rely on.
+ // one). This regression-tests the byte semantics that strict
+ // validation and load-time warnings both rely on.
let chars = MAX_SKILL_DESCRIPTION_LEN / 2 + 1;
let description = "é".repeat(chars);
assert!(description.chars().count() <= MAX_SKILL_DESCRIPTION_LEN);
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 2210e0c1465..0e2320a2d90 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -5704,6 +5704,7 @@ impl AgentPanel {
window.dispatch_action(
Box::new(zed_actions::OpenSettingsAt {
path: "agent.skills".to_string(),
+ target: None,
}),
cx,
);
diff --git a/crates/agent_ui/src/completion_provider.rs b/crates/agent_ui/src/completion_provider.rs
index acc08541100..87e0e09c81a 100644
--- a/crates/agent_ui/src/completion_provider.rs
+++ b/crates/agent_ui/src/completion_provider.rs
@@ -299,6 +299,26 @@ pub struct AvailableSkill {
/// worktree root name for project-local skills.
pub source: SharedString,
pub skill_file_path: PathBuf,
+ pub warning: Option<SharedString>,
+}
+
+fn skill_completion_icon_path(
+ _skill: &AvailableSkill,
+ uri: &MentionUri,
+ cx: &mut App,
+) -> SharedString {
+ uri.icon_path(cx)
+}
+
+fn skill_completion_documentation(skill: &AvailableSkill) -> CompletionDocumentation {
+ if let Some(warning) = &skill.warning {
+ CompletionDocumentation::WarningAndMultiLinePlainText {
+ warning: "".into(),
+ plain_text: Some(warning.clone()),
+ }
+ } else {
+ CompletionDocumentation::MultiLinePlainText(skill.description.to_string().into())
+ }
}
#[derive(Debug, Clone)]
@@ -467,7 +487,7 @@ impl<T: PromptCompletionProviderDelegate> PromptCompletionProvider<T> {
};
let new_text = format!("{} ", uri.as_link());
let new_text_len = new_text.len();
- let icon_path = uri.icon_path(cx);
+ let icon_path = skill_completion_icon_path(&skill, &uri, cx);
let crease_text: SharedString = uri.name().into();
let source_highlight_id = cx
.theme()
@@ -479,9 +499,7 @@ impl<T: PromptCompletionProviderDelegate> PromptCompletionProvider<T> {
replace_range: source_range.clone(),
new_text,
label,
- documentation: Some(CompletionDocumentation::MultiLinePlainText(
- skill.description.into(),
- )),
+ documentation: Some(skill_completion_documentation(&skill)),
insert_text_mode: None,
source: project::CompletionSource::Custom,
match_start: None,
@@ -1325,7 +1343,7 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletio
};
let new_text = format!("{} ", uri.as_link());
let new_text_len = new_text.len();
- let icon_path = uri.icon_path(cx);
+ let icon_path = skill_completion_icon_path(skill, &uri, cx);
let crease_text: SharedString = uri.name().into();
let confirm = confirm_completion_callback(
crease_text,
@@ -1368,11 +1386,7 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletio
replace_range: source_range.clone(),
new_text,
label,
- documentation: Some(
- CompletionDocumentation::MultiLinePlainText(
- skill.description.into(),
- ),
- ),
+ documentation: Some(skill_completion_documentation(&skill)),
source: project::CompletionSource::Custom,
icon_path: Some(icon_path),
match_start: None,
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 1134b6ded2f..7fc0a59f060 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -3074,6 +3074,7 @@ fn native_available_skills(
description: skill.description.into(),
source: skill.source,
skill_file_path: skill.skill_file_path,
+ warning: skill.warning,
})
.collect()
}
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index f69b7a7fa3d..539bb322031 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -8,8 +8,9 @@ use agent_client_protocol::schema as acp;
use std::cell::RefCell;
use acp_thread::{ContentBlock, PlanEntry, SandboxAuthorizationDetails};
-use agent::{SkillLoadingError, SkillLoadingErrorsUpdated};
+use agent::{SkillLoadingIssue, SkillLoadingIssueKind, SkillLoadingIssuesUpdated};
use agent_settings::UserAgentsMd;
+use agent_skills::global_skills_dir;
use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};
use editor::actions::OpenExcerpts;
@@ -617,13 +618,13 @@ pub struct ThreadView {
pub show_codex_windows_warning: bool,
pub multi_root_callout_dismissed: bool,
pub generating_indicator_in_list: bool,
- pub skill_loading_errors: Vec<SkillLoadingError>,
- /// Errors the user has explicitly dismissed. Each entry is matched against
- /// emitted errors by full equality; when an error no longer appears in the
- /// emitted list (i.e. the underlying file was fixed or removed), it's
+ pub skill_loading_issues: Vec<SkillLoadingIssue>,
+ /// Issues the user has explicitly dismissed. Each entry is matched against
+ /// emitted issues by full equality; when an issue no longer appears in the
+ /// latest replacement list (because the underlying file was fixed/removed), it's
/// dropped from this set so a future regression of the same kind would
/// re-show.
- dismissed_skill_loading_errors: HashSet<SkillLoadingError>,
+ dismissed_skill_loading_issues: HashSet<SkillLoadingIssue>,
}
impl Focusable for ThreadView {
fn focus_handle(&self, cx: &App) -> FocusHandle {
@@ -669,6 +670,84 @@ fn full_path_for_empty_project_path(file: &dyn language::File, cx: &App) -> Opti
(!full_path.is_empty()).then_some(full_path)
}
+fn skill_issue_file_label(path: &std::path::Path) -> String {
+ let file_name = path.file_name().and_then(|name| name.to_str());
+ let parent_name = path
+ .parent()
+ .and_then(|parent| parent.file_name())
+ .and_then(|name| name.to_str());
+
+ match (parent_name, file_name) {
+ (Some(parent_name), Some(file_name)) => format!("{parent_name}/{file_name}"),
+ (_, Some(file_name)) => file_name.to_string(),
+ _ => path.display().to_string(),
+ }
+}
+
+#[derive(Clone)]
+struct SkillSettingsTarget {
+ label: String,
+ target: Option<zed_actions::OpenSettingsAtTarget>,
+}
+
+fn skill_warning_settings_targets(
+ warnings: &[SkillLoadingIssue],
+ project: &WeakEntity<Project>,
+ cx: &App,
+) -> Vec<SkillSettingsTarget> {
+ let global_skills_dir = global_skills_dir();
+ let worktrees = project
+ .upgrade()
+ .map(|project| project.read(cx).visible_worktrees(cx).collect::<Vec<_>>())
+ .unwrap_or_default();
+
+ let mut has_global_warnings = false;
+ let mut project_targets: Vec<(usize, String)> = Vec::new();
+
+ for warning in warnings {
+ if warning.path.starts_with(&global_skills_dir) {
+ has_global_warnings = true;
+ continue;
+ }
+
+ for worktree in &worktrees {
+ let worktree = worktree.read(cx);
+ let worktree_id = worktree.id().to_usize();
+ if warning.path.starts_with(worktree.abs_path().as_ref())
+ && !project_targets
+ .iter()
+ .any(|(target_worktree_id, _)| *target_worktree_id == worktree_id)
+ {
+ project_targets.push((worktree_id, worktree.root_name_str().to_string()));
+ break;
+ }
+ }
+ }
+
+ let mut targets = Vec::new();
+ if has_global_warnings {
+ targets.push(SkillSettingsTarget {
+ label: "Manage Global Skills".to_string(),
+ target: Some(zed_actions::OpenSettingsAtTarget::User),
+ });
+ }
+
+ let multiple_project_targets = project_targets.len() > 1;
+ for (worktree_id, worktree_root_name) in project_targets {
+ let label = if multiple_project_targets {
+ format!("Manage {worktree_root_name} Skills")
+ } else {
+ "Manage Project Skills".to_string()
+ };
+ targets.push(SkillSettingsTarget {
+ label,
+ target: Some(zed_actions::OpenSettingsAtTarget::Project { worktree_id }),
+ });
+ }
+
+ targets
+}
+
pub fn open_markdown_in_workspace(
title: String,
markdown: String,
@@ -852,9 +931,9 @@ impl ThreadView {
));
// If this thread is backed by a NativeAgent, listen for skill loading
- // errors so we can surface them as banners. The agent emits a single
+ // issues so we can surface them as banners. The agent emits a single
// replacement-style event per project refresh, so we overwrite our
- // local list rather than appending — this also clears stale errors
+ // local list rather than appending — this also clears stale issues
// once a user resolves them.
if let Some(native_connection) = thread
.read(cx)
@@ -865,21 +944,21 @@ impl ThreadView {
let project_id = thread.read(cx).project().entity_id();
subscriptions.push(cx.subscribe(
&native_connection.0,
- move |this: &mut Self, _agent, event: &SkillLoadingErrorsUpdated, cx| {
+ move |this: &mut Self, _agent, event: &SkillLoadingIssuesUpdated, cx| {
if event.project_id != project_id {
return;
}
- // Drop dismissals for errors that no longer appear in the emitted
+ // Drop dismissals for issues that no longer appear in the emitted
// list — the underlying file must have been fixed or removed, so a
// future regression should re-show.
- this.dismissed_skill_loading_errors
- .retain(|dismissed| event.errors.contains(dismissed));
+ this.dismissed_skill_loading_issues
+ .retain(|dismissed| event.issues.contains(dismissed));
- // Show only errors that haven't been dismissed.
- this.skill_loading_errors = event
- .errors
+ // Show only issues that haven't been dismissed.
+ this.skill_loading_issues = event
+ .issues
.iter()
- .filter(|e| !this.dismissed_skill_loading_errors.contains(e))
+ .filter(|issue| !this.dismissed_skill_loading_issues.contains(issue))
.cloned()
.collect();
cx.notify();
@@ -981,8 +1060,8 @@ impl ThreadView {
show_codex_windows_warning,
multi_root_callout_dismissed: false,
generating_indicator_in_list: false,
- skill_loading_errors: Vec::new(),
- dismissed_skill_loading_errors: HashSet::default(),
+ skill_loading_issues: Vec::new(),
+ dismissed_skill_loading_issues: HashSet::default(),
};
this.sync_generating_indicator(cx);
@@ -9695,23 +9774,71 @@ impl ThreadView {
)
}
- fn render_skill_loading_errors(&self, cx: &mut Context<Self>) -> Vec<Callout> {
- self.skill_loading_errors
+ fn render_skill_loading_issues(&self, cx: &mut Context<Self>) -> Vec<Callout> {
+ let mut callouts = Vec::new();
+ let description_warnings = self
+ .skill_loading_issues
.iter()
- .enumerate()
- .map(|(index, error)| {
- let abs_path = error.path.clone();
- let workspace = self.workspace.clone();
- let path_label = error.path.display().to_string();
- let target = error.clone();
- Callout::new()
- .icon(IconName::Warning)
- .severity(Severity::Warning)
- .title("Skill failed to load")
- .description(format!("{}\n{path_label}", error.message))
- .actions_slot(
- Button::new(("open-skill-file", index), "Open File").on_click(cx.listener(
- move |_, _, window, cx| {
+ .filter(|issue| issue.kind == SkillLoadingIssueKind::DescriptionTooLong)
+ .cloned()
+ .collect::<Vec<_>>();
+
+ if !description_warnings.is_empty() {
+ let warning_count = description_warnings.len();
+ let title = if warning_count == 1 {
+ "1 skill loaded with warning".to_string()
+ } else {
+ format!("{warning_count} skills loaded with warnings")
+ };
+
+ let mut callout = Callout::new()
+ .icon(IconName::Warning)
+ .severity(Severity::Warning)
+ .title(title);
+
+ if warning_count == 1 {
+ let rows = description_warnings
+ .iter()
+ .enumerate()
+ .map(|(index, issue)| {
+ let abs_path = issue.path.clone();
+ let workspace = self.workspace.clone();
+ let full_path = issue.path.display().to_string();
+ let file_label = skill_issue_file_label(&issue.path);
+ let file_icon = FileIcons::get_icon(issue.path.as_path(), cx)
+ .map(Icon::from_path)
+ .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
+ .unwrap_or_else(|| {
+ Icon::new(IconName::File)
+ .color(Color::Muted)
+ .size(IconSize::Small)
+ });
+
+ v_flex()
+ .id(("skill-description-warning-file", index))
+ .w_full()
+ .min_w_0()
+ .gap_0p5()
+ .p_1()
+ .rounded_sm()
+ .cursor_pointer()
+ .hover(|style| style.bg(cx.theme().colors().element_hover))
+ .child(
+ h_flex().min_w_0().gap_1().child(file_icon).child(
+ Label::new(file_label)
+ .size(LabelSize::Small)
+ .buffer_font(cx),
+ ),
+ )
+ .child(
+ Label::new(issue.message.clone())
+ .size(LabelSize::XSmall)
+ .color(Color::Muted),
+ )
+ .tooltip(move |_, cx| {
+ Tooltip::with_meta("Open File", None, full_path.clone(), cx)
+ })
+ .on_click(cx.listener(move |_, _, window, cx| {
let abs_path = abs_path.clone();
workspace
.update(cx, |workspace, cx| {
@@ -9725,22 +9852,123 @@ impl ThreadView {
.detach_and_log_err(cx);
})
.ok();
- },
- )),
- )
- .dismiss_action(
- IconButton::new(("dismiss-skill-error", index), IconName::Close)
- .icon_size(IconSize::Small)
- .icon_color(Color::Muted)
- .tooltip(Tooltip::text("Dismiss"))
- .on_click(cx.listener(move |this, _, _, cx| {
- this.skill_loading_errors.retain(|e| *e != target);
- this.dismissed_skill_loading_errors.insert(target.clone());
- cx.notify();
- })),
- )
- })
- .collect()
+ }))
+ .into_any_element()
+ })
+ .collect::<Vec<_>>();
+ callout = callout.description_slot(v_flex().gap_1().children(rows));
+ } else {
+ let settings_targets =
+ skill_warning_settings_targets(&description_warnings, &self.project, cx);
+ if settings_targets.is_empty() {
+ callout = callout.description(
+ "Some skill descriptions exceed the recommended limit and may consume more model-context tokens.",
+ );
+ } else {
+ let manage_buttons =
+ h_flex()
+ .gap_0p5()
+ .children(settings_targets.into_iter().enumerate().map(
+ |(index, settings_target)| {
+ let target = settings_target.target.clone();
+ Button::new(
+ ("open-skills-settings", index),
+ settings_target.label,
+ )
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ window.dispatch_action(
+ Box::new(zed_actions::OpenSettingsAt {
+ path: "agent.skills".to_string(),
+ target: target.clone(),
+ }),
+ cx,
+ );
+ })
+ .into_any_element()
+ },
+ ));
+ callout = callout
+ .description("Open Skills settings to review these warnings and manage skill descriptions in one place.")
+ .actions_slot(manage_buttons);
+ }
+ }
+
+ let targets = description_warnings;
+ callouts.push(
+ callout.dismiss_action(
+ IconButton::new("dismiss-skill-description-warnings", IconName::Close)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Muted)
+ .tooltip(Tooltip::text("Dismiss"))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.skill_loading_issues
+ .retain(|issue| !targets.contains(issue));
+ for target in &targets {
+ this.dismissed_skill_loading_issues.insert(target.clone());
+ }
+ cx.notify();
+ })),
+ ),
+ );
+ }
+
+ callouts.extend(
+ self.skill_loading_issues
+ .iter()
+ .filter(|issue| issue.kind != SkillLoadingIssueKind::DescriptionTooLong)
+ .enumerate()
+ .map(|(index, issue)| {
+ let abs_path = issue.path.clone();
+ let workspace = self.workspace.clone();
+ let path_label = issue.path.display().to_string();
+ let target = issue.clone();
+ let title = match issue.kind {
+ SkillLoadingIssueKind::LoadFailed => "Skill failed to load",
+ SkillLoadingIssueKind::DescriptionTooLong => unreachable!(),
+ SkillLoadingIssueKind::CatalogBudgetExceeded => {
+ "Skill omitted from model catalog"
+ }
+ };
+ Callout::new()
+ .icon(IconName::Warning)
+ .severity(Severity::Warning)
+ .title(title)
+ .description(format!("{}\n{path_label}", issue.message))
+ .actions_slot(
+ Button::new(("open-skill-file", index), "Open File").on_click(
+ cx.listener(move |_, _, window, cx| {
+ let abs_path = abs_path.clone();
+ workspace
+ .update(cx, |workspace, cx| {
+ workspace
+ .open_abs_path(
+ abs_path,
+ workspace::OpenOptions::default(),
+ window,
+ cx,
+ )
+ .detach_and_log_err(cx);
+ })
+ .ok();
+ }),
+ ),
+ )
+ .dismiss_action(
+ IconButton::new(("dismiss-skill-issue", index), IconName::Close)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Muted)
+ .tooltip(Tooltip::text("Dismiss"))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.skill_loading_issues.retain(|issue| *issue != target);
+ this.dismissed_skill_loading_issues.insert(target.clone());
+ cx.notify();
+ })),
+ )
+ }),
+ );
+
+ callouts
}
fn render_external_source_prompt_warning(&self, cx: &mut Context<Self>) -> Callout {
@@ -10277,7 +10505,6 @@ impl Render for ThreadView {
.children(self.render_subagent_titlebar(cx))
.child(conversation)
.children(self.render_multi_root_callout(cx))
- .children(self.render_skill_loading_errors(cx))
.children(self.render_activity_bar(window, cx))
.when(self.show_external_source_prompt_warning, |this| {
this.child(self.render_external_source_prompt_warning(cx))
@@ -10285,6 +10512,7 @@ impl Render for ThreadView {
.when(self.show_codex_windows_warning, |this| {
this.child(self.render_codex_windows_warning(cx))
})
+ .children(self.render_skill_loading_issues(cx))
.children(self.render_thread_retry_status_callout())
.children(self.render_thread_error(window, cx))
.when_some(
diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs
index 3708914b489..951959a1b01 100644
--- a/crates/agent_ui/src/message_editor.rs
+++ b/crates/agent_ui/src/message_editor.rs
@@ -2282,6 +2282,7 @@ mod tests {
description: "Deploy the app".into(),
source: "".into(),
skill_file_path: skill_file_path.clone(),
+ warning: None,
};
let session_capabilities = SessionCapabilities::new(
acp::PromptCapabilities::default(),
@@ -2304,6 +2305,7 @@ mod tests {
description: "desc".into(),
source: source.into(),
skill_file_path: PathBuf::from(format!("/tmp/{source}-{name}/SKILL.md")),
+ warning: None,
};
// Global skills carry an empty scope (so the popup inserts
diff --git a/crates/edit_prediction_ui/src/edit_prediction_button.rs b/crates/edit_prediction_ui/src/edit_prediction_button.rs
index 1d1a423cc82..1593a70f5af 100644
--- a/crates/edit_prediction_ui/src/edit_prediction_button.rs
+++ b/crates/edit_prediction_ui/src/edit_prediction_button.rs
@@ -630,6 +630,7 @@ impl EditPredictionButton {
window.dispatch_action(
OpenSettingsAt {
path: "edit_predictions.providers".to_string(),
+ target: None,
}
.boxed_clone(),
cx,
diff --git a/crates/editor/src/code_context_menus.rs b/crates/editor/src/code_context_menus.rs
index 02634fcbd5c..d515692a08f 100644
--- a/crates/editor/src/code_context_menus.rs
+++ b/crates/editor/src/code_context_menus.rs
@@ -896,9 +896,29 @@ impl CompletionsMenu {
let documentation = &completion.documentation;
let mut len = completion.label.text.chars().count();
- if let Some(CompletionDocumentation::SingleLine(text)) = documentation {
- if show_completion_documentation {
- len += text.chars().count();
+ let show_completion_detail = show_completion_documentation
+ || matches!(
+ documentation,
+ Some(CompletionDocumentation::WarningAndMultiLinePlainText { .. })
+ );
+ if show_completion_detail {
+ match documentation {
+ Some(CompletionDocumentation::SingleLine(text)) => {
+ len += text.chars().count();
+ }
+ Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
+ single_line,
+ ..
+ }) => {
+ len += single_line.chars().count();
+ }
+ Some(CompletionDocumentation::WarningAndMultiLinePlainText {
+ warning,
+ ..
+ }) => {
+ len += warning.chars().count();
+ }
+ _ => {}
}
}
@@ -945,7 +965,12 @@ impl CompletionsMenu {
};
let completion = &completions_guard[mat.candidate_id];
- let documentation = if show_completion_documentation {
+ let show_completion_detail = show_completion_documentation
+ || matches!(
+ completion.documentation.as_ref(),
+ Some(CompletionDocumentation::WarningAndMultiLinePlainText { .. })
+ );
+ let documentation = if show_completion_detail {
&completion.documentation
} else {
&None
@@ -1060,10 +1085,32 @@ impl CompletionsMenu {
Label::new(text.trim().to_string())
.ml_4()
.size(LabelSize::Small)
- .color(Color::Muted),
+ .color(Color::Muted)
+ .into_any_element(),
)
}
}
+ Some(CompletionDocumentation::WarningAndMultiLinePlainText {
+ warning,
+ ..
+ }) => {
+ let warning = warning.trim();
+ let mut label = h_flex().ml_4().gap_0p5().child(
+ Icon::new(IconName::Warning)
+ .size(IconSize::XSmall)
+ .color(Color::Warning),
+ );
+
+ if !warning.is_empty() {
+ label = label.child(
+ Label::new(warning.to_string())
+ .size(LabelSize::Small)
+ .color(Color::Warning),
+ );
+ }
+
+ Some(label.into_any_element())
+ }
_ => None,
};
@@ -1145,7 +1192,7 @@ impl CompletionsMenu {
this.child(div().truncate().child(suffix))
}),
)
- .end_slot::<Label>(documentation_label),
+ .end_slot::<AnyElement>(documentation_label),
)
.into_any_element()
})
@@ -1197,6 +1244,10 @@ impl CompletionsMenu {
Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
plain_text: Some(text),
..
+ })
+ | Some(CompletionDocumentation::WarningAndMultiLinePlainText {
+ plain_text: Some(text),
+ ..
}) => div().child(text.clone()),
Some(CompletionDocumentation::MultiLineMarkdown(source)) if !source.is_empty() => {
let Some((false, markdown)) = self.get_or_create_markdown(
@@ -1230,6 +1281,10 @@ impl CompletionsMenu {
Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
plain_text: None,
..
+ })
+ | Some(CompletionDocumentation::WarningAndMultiLinePlainText {
+ plain_text: None,
+ ..
}) => {
return None;
}
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 4cbda008b92..0f13f6633ca 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -14603,6 +14603,11 @@ pub enum CompletionDocumentation {
single_line: SharedString,
plain_text: Option<SharedString>,
},
+ /// A warning label shown alongside multiple lines of plain text documentation.
+ WarningAndMultiLinePlainText {
+ warning: SharedString,
+ plain_text: Option<SharedString>,
+ },
}
impl CompletionDocumentation {
@@ -14616,6 +14621,9 @@ impl CompletionDocumentation {
CompletionDocumentation::SingleLineAndMultiLinePlainText { single_line, .. } => {
single_line.clone()
}
+ CompletionDocumentation::WarningAndMultiLinePlainText { warning, .. } => {
+ warning.clone()
+ }
}
}
}
diff --git a/crates/prompt_store/src/prompts.rs b/crates/prompt_store/src/prompts.rs
index 328ee93af02..eb72f38e6ca 100644
--- a/crates/prompt_store/src/prompts.rs
+++ b/crates/prompt_store/src/prompts.rs
@@ -148,6 +148,7 @@ mod tests {
source: SkillSource::Global,
directory_path: PathBuf::from("/skills/oversized"),
skill_file_path: PathBuf::from("/skills/oversized/SKILL.md"),
+ load_warnings: Vec::new(),
disable_model_invocation: false,
embedded_body: None,
};
diff --git a/crates/search/src/buffer_search.rs b/crates/search/src/buffer_search.rs
index 07c91d7659d..5e20f2e7ecf 100644
--- a/crates/search/src/buffer_search.rs
+++ b/crates/search/src/buffer_search.rs
@@ -197,6 +197,7 @@ impl Render for BufferSearchBar {
window.dispatch_action(
OpenSettingsAt {
path: "minimum_split_diff_width".to_string(),
+ target: None,
}
.boxed_clone(),
cx,
diff --git a/crates/settings_ui/src/pages/skills_setup.rs b/crates/settings_ui/src/pages/skills_setup.rs
index 2ab68f5b53e..378f100e5fc 100644
--- a/crates/settings_ui/src/pages/skills_setup.rs
+++ b/crates/settings_ui/src/pages/skills_setup.rs
@@ -1,10 +1,12 @@
-use agent_skills::{Skill, SkillIndex, encode_skill_share_link};
+use agent_skills::{MAX_SKILL_DESCRIPTION_LEN, Skill, SkillIndex, encode_skill_share_link};
use fs::RemoveOptions;
use gpui::{Action as _, ClipboardItem, ScrollHandle, SharedString, prelude::*};
use ui::{Divider, Tooltip, prelude::*};
use util::ResultExt as _;
+use std::borrow::Cow;
+
use crate::{SettingsUiFile, SettingsWindow};
pub(crate) fn render_skills_setup_page(
@@ -123,6 +125,7 @@ fn render_skill_row(
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());
let (share_icon, share_icon_color) = if share_copied {
(IconName::Check, Color::Success)
@@ -187,11 +190,35 @@ fn render_skill_row(
.px_8()
.gap_4()
.child(
- v_flex().gap_0p5().min_w_0().flex_1().child(title).child(
- Label::new(skill.description.clone())
- .size(LabelSize::Small)
- .color(Color::Muted),
- ),
+ v_flex()
+ .gap_0p5()
+ .min_w_0()
+ .flex_1()
+ .child(title)
+ .when_some(warning_message, |this, warning_message| {
+ this.child(
+ h_flex()
+ .id(SharedString::from(format!("warning-{}", skill.name)))
+ .min_w_0()
+ .gap_1()
+ .items_start()
+ .child(
+ Icon::new(IconName::Warning)
+ .size(IconSize::XSmall)
+ .color(Color::Warning),
+ )
+ .child(
+ Label::new(warning_message)
+ .size(LabelSize::XSmall)
+ .color(Color::Warning),
+ ),
+ )
+ })
+ .child(
+ Label::new(truncated_skill_description(&skill.description))
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ ),
)
.child(
h_flex()
@@ -282,3 +309,58 @@ fn render_skill_row(
)
.into_any_element()
}
+
+fn truncated_skill_description(description: &str) -> Cow<'_, str> {
+ if description.len() <= MAX_SKILL_DESCRIPTION_LEN {
+ return Cow::Borrowed(description);
+ }
+
+ let mut end = MAX_SKILL_DESCRIPTION_LEN;
+ while !description.is_char_boundary(end) {
+ end -= 1;
+ }
+ let hidden_bytes = description.len() - end;
+ let truncated = &description[..end];
+ if hidden_bytes > 100 {
+ Cow::Owned(format!("{truncated}... ({hidden_bytes} bytes not shown)"))
+ } else {
+ Cow::Owned(format!("{truncated}..."))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn truncated_skill_description_preserves_char_boundaries() {
+ let mut description = "a".repeat(MAX_SKILL_DESCRIPTION_LEN - 1);
+ description.push('é');
+
+ let truncated = truncated_skill_description(&description);
+
+ assert!(truncated.starts_with(&"a".repeat(MAX_SKILL_DESCRIPTION_LEN - 1)));
+ assert!(truncated.ends_with("..."));
+ }
+
+ #[test]
+ fn truncated_skill_description_leaves_short_descriptions_untouched() {
+ let description = "a".repeat(MAX_SKILL_DESCRIPTION_LEN);
+ assert_eq!(truncated_skill_description(&description), description);
+ }
+
+ #[test]
+ fn truncated_skill_description_reports_hidden_bytes_over_100() {
+ let description = "a".repeat(MAX_SKILL_DESCRIPTION_LEN + 101);
+ let truncated = truncated_skill_description(&description);
+ assert!(truncated.ends_with("... (101 bytes not shown)"));
+ }
+
+ #[test]
+ fn truncated_skill_description_omits_byte_count_at_or_under_100() {
+ let description = "a".repeat(MAX_SKILL_DESCRIPTION_LEN + 100);
+ let truncated = truncated_skill_description(&description);
+ assert!(truncated.ends_with("..."));
+ assert!(!truncated.contains("not shown"));
+ }
+}
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index 5ac57074d6f..c158110974d 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -48,7 +48,7 @@ use workspace::{
AppState, MultiWorkspace, OpenOptions, OpenVisible, Workspace, WorkspaceSettings,
client_side_decorations,
};
-use zed_actions::{OpenProjectSettings, OpenSettings, OpenSettingsAt};
+use zed_actions::{OpenProjectSettings, OpenSettings, OpenSettingsAt, OpenSettingsAtTarget};
use crate::components::{
EnumVariantDropdown, NumberField, NumberFieldMode, NumberFieldType, SettingsInputField,
@@ -423,9 +423,14 @@ pub fn init(cx: &mut App) {
cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
workspace
- .register_action(|_, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
+ .register_action(|_, action: &OpenSettingsAt, window, cx| {
let window_handle = window.window_handle().downcast::<MultiWorkspace>();
- open_settings_editor(Some(&path), None, window_handle, cx);
+ open_settings_editor_at_target(
+ Some(&action.path),
+ action.target.as_ref().map(SettingsFileTarget::from),
+ window_handle,
+ cx,
+ );
})
.register_action(|_, _: &OpenSettings, window, cx| {
let window_handle = window.window_handle().downcast::<MultiWorkspace>();
@@ -593,14 +598,63 @@ fn init_renderers(cx: &mut App) {
;
}
+#[derive(Clone, Copy)]
+enum SettingsFileTarget {
+ User,
+ Project(WorktreeId),
+}
+
+impl From<&OpenSettingsAtTarget> for SettingsFileTarget {
+ fn from(target: &OpenSettingsAtTarget) -> Self {
+ match target {
+ OpenSettingsAtTarget::User => Self::User,
+ OpenSettingsAtTarget::Project { worktree_id } => {
+ Self::Project(WorktreeId::from_usize(*worktree_id))
+ }
+ }
+ }
+}
+
pub fn open_settings_editor(
path: Option<&str>,
target_worktree_id: Option<WorktreeId>,
workspace_handle: Option<WindowHandle<MultiWorkspace>>,
cx: &mut App,
+) {
+ open_settings_editor_at_target(
+ path,
+ target_worktree_id.map(SettingsFileTarget::Project),
+ workspace_handle,
+ cx,
+ );
+}
+
+fn open_settings_editor_at_target(
+ path: Option<&str>,
+ target_file: Option<SettingsFileTarget>,
+ workspace_handle: Option<WindowHandle<MultiWorkspace>>,
+ cx: &mut App,
) {
telemetry::event!("Settings Viewed");
+ fn select_target_file(
+ target_file: SettingsFileTarget,
+ settings_window: &mut SettingsWindow,
+ window: &mut Window,
+ cx: &mut Context<SettingsWindow>,
+ ) {
+ let file_index = settings_window
+ .files
+ .iter()
+ .position(|(file, _)| match target_file {
+ SettingsFileTarget::User => matches!(file, SettingsUiFile::User),
+ SettingsFileTarget::Project(worktree_id) => file.worktree_id() == Some(worktree_id),
+ });
+ if let Some(file_index) = file_index {
+ settings_window.change_file(file_index, window, cx);
+ }
+ }
+
/// Assumes a settings GUI window is already open
fn open_path(
path: &str,
@@ -656,15 +710,12 @@ pub fn open_settings_editor(
settings_window.original_window = workspace_handle;
window.activate_window();
+ if let Some(target_file) = target_file {
+ select_target_file(target_file, settings_window, window, cx);
+ }
if let Some(path) = path {
open_path(path, settings_window, window, cx);
- } else if let Some(target_id) = target_worktree_id
- && let Some(file_index) = settings_window
- .files
- .iter()
- .position(|(file, _)| file.worktree_id() == Some(target_id))
- {
- settings_window.change_file(file_index, window, cx);
+ } else if target_file.is_some() {
cx.notify();
}
})
@@ -722,15 +773,11 @@ pub fn open_settings_editor(
let settings_window =
cx.new(|cx| SettingsWindow::new(workspace_handle, window, cx));
settings_window.update(cx, |settings_window, cx| {
+ if let Some(target_file) = target_file {
+ select_target_file(target_file, settings_window, window, cx);
+ }
if let Some(path) = path {
open_path(&path, settings_window, window, cx);
- } else if let Some(target_id) = target_worktree_id
- && let Some(file_index) = settings_window
- .files
- .iter()
- .position(|(file, _)| file.worktree_id() == Some(target_id))
- {
- settings_window.change_file(file_index, window, cx);
}
});
diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs
index e9fa128e490..100b01f1a9b 100644
--- a/crates/zed/src/main.rs
+++ b/crates/zed/src/main.rs
@@ -1240,7 +1240,10 @@ fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut
workspace.update(cx, |_, window, cx| match setting_path {
None => window.dispatch_action(Box::new(zed_actions::OpenSettings), cx),
Some(setting_path) => window.dispatch_action(
- Box::new(zed_actions::OpenSettingsAt { path: setting_path }),
+ Box::new(zed_actions::OpenSettingsAt {
+ path: setting_path,
+ target: None,
+ }),
cx,
),
})
diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs
index d8553c1bd14..609f5c180eb 100644
--- a/crates/zed/src/visual_test_runner.rs
+++ b/crates/zed/src/visual_test_runner.rs
@@ -1358,6 +1358,7 @@ fn run_settings_ui_subpage_visual_tests(
window.dispatch_action(
Box::new(OpenSettingsAt {
path: "agent".to_string(),
+ target: None,
}),
cx,
);
@@ -1403,6 +1404,7 @@ fn run_settings_ui_subpage_visual_tests(
window.dispatch_action(
Box::new(OpenSettingsAt {
path: "edit_predictions.providers".to_string(),
+ target: None,
}),
cx,
);
@@ -2387,6 +2389,7 @@ fn run_tool_permissions_visual_tests(
window.dispatch_action(
Box::new(OpenSettingsAt {
path: "agent.tool_permissions".to_string(),
+ target: None,
}),
cx,
);
diff --git a/crates/zed_actions/src/lib.rs b/crates/zed_actions/src/lib.rs
index b84c4c7b97a..9ac6f36b3af 100644
--- a/crates/zed_actions/src/lib.rs
+++ b/crates/zed_actions/src/lib.rs
@@ -143,6 +143,17 @@ pub struct IncreaseBufferFontSize {
pub struct OpenSettingsAt {
/// A path to a specific setting (e.g. `theme.mode`)
pub path: String,
+ /// The settings file to select before opening `path`. When omitted, the
+ /// existing settings file selection is preserved.
+ #[serde(default)]
+ pub target: Option<OpenSettingsAtTarget>,
+}
+
+#[derive(PartialEq, Clone, Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum OpenSettingsAtTarget {
+ User,
+ Project { worktree_id: usize },
}
/// Resets the buffer font size to the default value.