Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Restore access to old threads that mention rules (#58560)
MartinYe1234b53b14d21406
diff --git a/crates/acp_thread/src/mention.rs b/crates/acp_thread/src/mention.rsindex d7b8e427ad9..0ebe1712ff1 100644--- a/crates/acp_thread/src/mention.rs+++ b/crates/acp_thread/src/mention.rs@@ -36,6 +36,14 @@ pub enum MentionUri {id: acp::SessionId,name: String,},+ /// Deprecated: kept so threads from before rules became skills still+ /// deserialize. `id` (an opaque `prompt_store::PromptId`) is preserved+ /// verbatim so re-saved threads stay loadable by older Zed versions.+ Rule {+ #[serde(default = "default_deprecated_rule_id")]+ id: serde_json::Value,+ name: String,+ },Diagnostics {#[serde(default = "default_include_errors")]include_errors: bool,@@ -200,6 +208,15 @@ impl MentionUri {id: acp::SessionId::new(thread_id),name,})+ } else if let Some(rule_id) = path.strip_prefix("/agent/rule/") {+ // Deprecated: parses legacy rule mentions.+ let name = single_query_param(&url, "name")?.context("Missing rule name")?;+ let id = if rule_id.is_empty() {+ default_deprecated_rule_id()+ } else {+ serde_json::json!({ "User": { "uuid": rule_id } })+ };+ Ok(Self::Rule { id, name })} else if path == "/agent/diagnostics" {let mut include_errors = default_include_errors();let mut include_warnings = false;@@ -330,6 +347,7 @@ impl MentionUri {MentionUri::PastedImage { name } => name.clone(),MentionUri::Symbol { name, .. } => name.clone(),MentionUri::Thread { name, .. } => name.clone(),+ MentionUri::Rule { name, .. } => name.clone(),MentionUri::Diagnostics { .. } => "Diagnostics".to_string(),MentionUri::TerminalSelection { line_count } => {if *line_count == 1 {@@ -430,6 +448,7 @@ impl MentionUri {.unwrap_or_else(|| IconName::Folder.path().into()),MentionUri::Symbol { .. } => IconName::Code.path().into(),MentionUri::Thread { .. } => IconName::Thread.path().into(),+ MentionUri::Rule { .. } => IconName::Reader.path().into(),MentionUri::Diagnostics { .. } => IconName::Warning.path().into(),MentionUri::TerminalSelection { .. } => IconName::Terminal.path().into(),MentionUri::Selection { .. } => IconName::Reader.path().into(),@@ -512,6 +531,17 @@ impl MentionUri {url.query_pairs_mut().append_pair("name", name);url}+ MentionUri::Rule { id, name } => {+ let mut url = Url::parse("zed:///").unwrap();+ let rule_id = id+ .get("User")+ .and_then(|user| user.get("uuid"))+ .and_then(|uuid| uuid.as_str())+ .unwrap_or_default();+ url.set_path(&format!("/agent/rule/{rule_id}"));+ url.query_pairs_mut().append_pair("name", name);+ url+ }MentionUri::Diagnostics {include_errors,include_warnings,@@ -573,6 +603,12 @@ fn default_include_errors() -> bool {true}+/// Placeholder rule `id` for legacy mentions missing one, shaped so older Zed+/// versions can still deserialize it as a `prompt_store::PromptId`.+fn default_deprecated_rule_id() -> serde_json::Value {+ serde_json::json!({ "User": { "uuid": "00000000-0000-0000-0000-000000000000" } })+}+fn query_param(url: &Url, name: &'static str) -> Option<String> {url.query_pairs().find_map(|(key, value)| (key == name).then(|| value.to_string()))@@ -803,6 +839,43 @@ mod tests {assert_eq!(parsed.to_uri().to_string(), thread_uri);}+ #[test]+ fn test_parse_legacy_rule_uri() {+ let rule_uri = "zed:///agent/rule/d8694ff2-90d5-4b6f-be33-33c1763acd52?name=Some+rule";+ let parsed = MentionUri::parse(rule_uri, PathStyle::local()).unwrap();+ match &parsed {+ MentionUri::Rule { name, .. } => assert_eq!(name, "Some rule"),+ _ => panic!("Expected Rule variant"),+ }+ // The id round-trips through the URI.+ assert_eq!(parsed.to_uri().to_string(), rule_uri);+ }++ #[test]+ fn test_legacy_rule_mention_preserves_id() {+ // The `id` older Zed versions require must survive a load + save.+ let json = r#"{"Rule":{"id":{"User":{"uuid":"d8694ff2-90d5-4b6f-be33-33c1763acd52"}},"name":"Some rule"}}"#;+ let parsed: MentionUri = serde_json::from_str(json).unwrap();+ match &parsed {+ MentionUri::Rule { name, .. } => assert_eq!(name, "Some rule"),+ _ => panic!("Expected Rule variant"),+ }+ let reserialized = serde_json::to_value(&parsed).unwrap();+ assert_eq!(+ reserialized["Rule"]["id"]["User"]["uuid"],+ "d8694ff2-90d5-4b6f-be33-33c1763acd52"+ );+ }++ #[test]+ fn test_legacy_rule_mention_without_id_gets_placeholder() {+ // A mention missing its id still serializes a valid id for older versions.+ let json = r#"{"Rule":{"name":"Some rule"}}"#;+ let parsed: MentionUri = serde_json::from_str(json).unwrap();+ let reserialized = serde_json::to_value(&parsed).unwrap();+ assert!(reserialized["Rule"]["id"]["User"]["uuid"].is_string());+ }+#[test]fn test_parse_skill_uri_round_trip() {let skill_uri = MentionUri::Skill {diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 716975bd177..54723a5f720 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -365,6 +365,18 @@ impl UserMessage {MentionUri::Thread { .. } => {write!(&mut thread_context, "\n{}\n", content).ok();}+ MentionUri::Rule { .. } => {+ // Deprecated: keeps legacy rule mentions as context.+ write!(+ &mut rules_context,+ "\n{}",+ MarkdownCodeBlock {+ tag: "",+ text: content+ }+ )+ .ok();+ }MentionUri::Fetch { url } => {write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();}diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex e44d25b7332..ed0f75da9ba 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -10353,6 +10353,9 @@ pub(crate) fn open_link(MentionUri::TerminalSelection { .. } => {}MentionUri::GitDiff { .. } => {}MentionUri::MergeConflict { .. } => {}+ MentionUri::Rule { name, .. } => {+ crate::ui::open_migrated_rule(workspace, &name, window, cx);+ }MentionUri::Skill {skill_file_path, ..} => {diff --git a/crates/agent_ui/src/mention_set.rs b/crates/agent_ui/src/mention_set.rsindex b19a0f2ff40..6fddacc3279 100644--- a/crates/agent_ui/src/mention_set.rs+++ b/crates/agent_ui/src/mention_set.rs@@ -166,7 +166,8 @@ impl MentionSet {))),MentionUri::PastedImage { .. }| MentionUri::TerminalSelection { .. }- | MentionUri::MergeConflict { .. } => {+ | MentionUri::MergeConflict { .. }+ | MentionUri::Rule { .. } => {Task::ready(Err(anyhow!("Unsupported mention URI type for paste")))}}@@ -347,6 +348,10 @@ impl MentionSet {debug_panic!("unexpected merge conflict URI");Task::ready(Err(anyhow!("unexpected merge conflict URI")))}+ MentionUri::Rule { .. } => {+ debug_panic!("unexpected rule URI");+ Task::ready(Err(anyhow!("unexpected rule URI")))+ }};let task = cx.spawn(async move |_, _| task.await.map_err(|e| e.to_string()))diff --git a/crates/agent_ui/src/ui/mention_crease.rs b/crates/agent_ui/src/ui/mention_crease.rsindex 77cfc5512ed..8b2fa0cbab6 100644--- a/crates/agent_ui/src/ui/mention_crease.rs+++ b/crates/agent_ui/src/ui/mention_crease.rs@@ -199,6 +199,9 @@ fn open_mention_uri(} => {open_skill_file(workspace, skill_file_path, window, cx);}+ MentionUri::Rule { name, .. } => {+ open_migrated_rule(workspace, &name, window, cx);+ }MentionUri::Fetch { url } => {cx.open_url(url.as_str());}@@ -211,49 +214,70 @@ fn open_mention_uri(});}+/// Notify the user that rules became skills and open the skill the rule was+/// migrated into. Migrated skills live in the local global skills dir, so the+/// file is always resolved against the local filesystem (local, SSH, or+/// collab). Does nothing else when no matching skill exists.+pub(crate) fn open_migrated_rule(+ workspace: &mut Workspace,+ name: &str,+ window: &mut Window,+ cx: &mut Context<Workspace>,+) {+ struct RulesMigratedToSkillsToast;+ workspace.show_toast(+ workspace::Toast::new(+ workspace::notifications::NotificationId::unique::<RulesMigratedToSkillsToast>(),+ "Rules have been migrated to Skills.",+ )+ .on_click("View docs", |_, cx| {+ cx.open_url("https://zed.dev/docs/ai/skills");+ })+ .autohide(),+ cx,+ );++ let Some(slug) = agent_skills::slugify_skill_name(name) else {+ return;+ };+ let skill_file_path = agent_skills::global_skills_dir()+ .join(slug)+ .join(agent_skills::SKILL_FILE_NAME);++ if workspace.project().read(cx).is_local() {+ // Local project: open the editable on-disk file if it exists.+ if skill_file_path.exists() {+ open_skill_file(workspace, skill_file_path, window, cx);+ }+ return;+ }++ // Remote/collab: `open_abs_path` targets the remote project, where this+ // local file doesn't exist, so read it locally and show it read-only.+ let fs = workspace.app_state().fs.clone();+ cx.spawn_in(window, async move |workspace, cx| {+ let Ok(content) = fs.load(&skill_file_path).await else {+ return Ok(()); // No readable migrated skill: do nothing.+ };+ let title = skill_content_buffer_title(&skill_file_path);+ workspace.update_in(cx, |workspace, window, cx| {+ open_skill_content_buffer(workspace, title, content, window, cx);+ })+ })+ .detach_and_log_err(cx);+}+fn open_skill_file(workspace: &mut Workspace,skill_file_path: PathBuf,window: &mut Window,cx: &mut Context<Workspace>,) {- // Built-in skills have synthetic paths that don't exist on disk.- // Open a read-only buffer with the embedded content instead.- //- // The buffer is intentionally not registered with the project's buffer- // store: it has no on-disk backing, isn't searchable, and `Project::- // create_local_buffer` panics for remote projects (SSH/collab), which- // would crash Zed if a user clicked a built-in skill mention while- // connected to a remote project.+ // Built-in skills have synthetic paths with no on-disk file, so show their+ // embedded content in a local buffer instead.if let Some(content) = agent_skills::builtin_skill_content(&skill_file_path) {- let languages = workspace.project().read(cx).languages().clone();- let buffer = cx.new(|cx| Buffer::local(content, cx));- // Set markdown highlighting asynchronously — the buffer- // opens instantly and the highlighting appears once loaded.- cx.spawn({- let buffer = buffer.clone();- async move |_, cx| {- if let Ok(markdown) = languages.language_for_name("Markdown").await {- buffer.update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));- }- }- })- .detach();- let editor = cx.new(|cx| {- let mut editor = Editor::for_buffer(buffer, None, window, cx);- editor.set_read_only(true);- let title = skill_file_path- .parent()- .and_then(|p| p.file_name())- .map(|n| n.to_string_lossy().into_owned())- .unwrap_or_else(|| "built-in skill".into());- editor- .buffer()- .update(cx, |buffer, cx| buffer.set_title(title, cx));- editor- });- let pane = workspace.active_pane().clone();- workspace.add_item(pane, Box::new(editor), None, true, true, window, cx);+ let title = skill_content_buffer_title(&skill_file_path);+ open_skill_content_buffer(workspace, title, content, window, cx);return;}@@ -270,6 +294,51 @@ fn open_skill_file(.detach_and_log_err(cx);}+fn skill_content_buffer_title(skill_file_path: &std::path::Path) -> String {+ skill_file_path+ .parent()+ .and_then(|p| p.file_name())+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| "skill".into())+}++/// Open `content` as a local, read-only Markdown buffer, for skills with no+/// openable file in the active project (built-in skills, and migrated rules on+/// remote/collab projects). It's deliberately not registered with the project's+/// buffer store: that keeps it out of search and avoids+/// `Project::create_local_buffer` panicking on remote projects.+fn open_skill_content_buffer(+ workspace: &mut Workspace,+ title: String,+ content: impl Into<String>,+ window: &mut Window,+ cx: &mut Context<Workspace>,+) {+ let languages = workspace.project().read(cx).languages().clone();+ let buffer = cx.new(|cx| Buffer::local(content, cx));+ // Set markdown highlighting asynchronously — the buffer+ // opens instantly and the highlighting appears once loaded.+ cx.spawn({+ let buffer = buffer.clone();+ async move |_, cx| {+ if let Ok(markdown) = languages.language_for_name("Markdown").await {+ buffer.update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx));+ }+ }+ })+ .detach();+ let editor = cx.new(|cx| {+ let mut editor = Editor::for_buffer(buffer, None, window, cx);+ editor.set_read_only(true);+ editor+ .buffer()+ .update(cx, |buffer, cx| buffer.set_title(title, cx));+ editor+ });+ let pane = workspace.active_pane().clone();+ workspace.add_item(pane, Box::new(editor), None, true, true, window, cx);+}+fn open_file(workspace: &mut Workspace,abs_path: PathBuf,