Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Share v2 command definitions (#65190)
Ben Brandt8fda6e46539b
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 88b5012af8d..593caf6f45c 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -1,3 +1,4 @@+pub mod commands;pub mod config_options;mod connection;pub mod content;@@ -118,11 +119,11 @@ impl CommandCategory {}}-pub fn meta_with_command_category(category: CommandCategory) -> acp_v1::Meta {- acp_v1::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), category.as_str().into())])+pub fn meta_with_command_category(category: CommandCategory) -> acp_v2::Meta {+ acp_v2::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), category.as_str().into())])}-pub fn command_category_from_meta(meta: &Option<acp_v1::Meta>) -> Option<CommandCategory> {+pub fn command_category_from_meta(meta: &Option<acp_v2::Meta>) -> Option<CommandCategory> {meta.as_ref().and_then(|m| m.get(COMMAND_CATEGORY_META_KEY)).and_then(|v| v.as_str())@@ -3386,7 +3387,7 @@ pub struct AcpThread {token_usage: Option<TokenUsage>,cost: Option<SessionCost>,prompt_capabilities: acp_v1::PromptCapabilities,- available_commands: Vec<acp_v1::AvailableCommand>,+ available_commands: Vec<acp_v2::AvailableCommand>,_observe_prompt_capabilities: Task<anyhow::Result<()>>,_idle_sleep_subscriptions: Vec<Subscription>,terminals: HashMap<acp_v1::TerminalId, Entity<Terminal>>,@@ -3526,7 +3527,7 @@ pub enum AcpThreadEvent {LoadError(LoadError),PromptCapabilitiesUpdated,Refusal,- AvailableCommandsUpdated(Vec<acp_v1::AvailableCommand>),+ AvailableCommandsUpdated(Vec<acp_v2::AvailableCommand>),ModeUpdated(acp_v1::SessionModeId),ConfigOptionsUpdated(Vec<acp_v2::SessionConfigOption>),WorkingDirectoriesUpdated,@@ -3739,10 +3740,19 @@ impl AcpThread {self.prompt_capabilities.clone()}- pub fn available_commands(&self) -> &[acp_v1::AvailableCommand] {+ pub fn available_commands(&self) -> &[acp_v2::AvailableCommand] {&self.available_commands}+ pub fn update_available_commands(+ &mut self,+ commands: Vec<acp_v2::AvailableCommand>,+ cx: &mut Context<Self>,+ ) {+ self.available_commands = commands.clone();+ cx.emit(AcpThreadEvent::AvailableCommandsUpdated(commands));+ }+pub fn is_draft_thread(&self) -> bool {self.entries().is_empty()}@@ -4289,8 +4299,10 @@ impl AcpThread {available_commands,..}) => {- self.available_commands = available_commands.clone();- cx.emit(AcpThreadEvent::AvailableCommandsUpdated(available_commands));+ self.update_available_commands(+ commands::from_v1(available_commands).map_err(acp_v1::Error::from)?,+ cx,+ );}acp_v1::SessionUpdate::CurrentModeUpdate(acp_v1::CurrentModeUpdate {current_mode_id,diff --git a/crates/acp_thread/src/commands.rs b/crates/acp_thread/src/commands.rsnew file mode 100644index 00000000000..afb7fb1c8cd--- /dev/null+++ b/crates/acp_thread/src/commands.rs@@ -0,0 +1,66 @@+use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};+use anyhow::{Result, bail};++pub fn from_v1(commands: Vec<acp_v1::AvailableCommand>) -> Result<Vec<acp_v2::AvailableCommand>> {+ commands+ .into_iter()+ .map(|command| {+ let input = command+ .input+ .map(|input| {+ Ok(match input {+ acp_v1::AvailableCommandInput::Unstructured(input) => {+ acp_v2::AvailableCommandInput::Text(+ acp_v2::TextCommandInput::new(input.hint).meta(input.meta),+ )+ }+ _ => bail!("Unsupported legacy command input"),+ })+ })+ .transpose()?;+ Ok(+ acp_v2::AvailableCommand::new(command.name, command.description)+ .input(input)+ .meta(command.meta),+ )+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn legacy_definitions_preserve_input_and_metadata() -> Result<()> {+ let commands = vec![+ acp_v1::AvailableCommand::new("/opaque.name", ""),+ acp_v1::AvailableCommand::new("empty", "").meta(acp_v1::Meta::new()),+ acp_v1::AvailableCommand::new("deploy", "Deploy code")+ .input(acp_v1::AvailableCommandInput::Unstructured(+ acp_v1::UnstructuredCommandInput::new("").meta(acp_v1::Meta::from_iter([(+ "input".into(),+ json!([null, true]),+ )])),+ ))+ .meta(acp_v1::Meta::from_iter([+ ("command_category".into(), json!("mcp")),+ ("command".into(), json!({"nested": [1, "value"]})),+ ])),+ ];+ assert_eq!(+ serde_json::to_value(from_v1(commands)?)?,+ json!([+ {"name": "/opaque.name", "description": ""},+ {"name": "empty", "description": "", "_meta": {}},+ {+ "name": "deploy", "description": "Deploy code",+ "input": {"type": "text", "hint": "", "_meta": {"input": [null, true]}},+ "_meta": {"command_category": "mcp", "command": {"nested": [1, "value"]}}+ }+ ])+ );+ Ok(())+ }+}diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 7bb989892cc..33efb1db20d 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -5836,6 +5836,78 @@ pub(crate) mod tests {.await;assert!(contents_result.is_ok());++ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _cx| view.thread.clone());+ let command_payload = json!({+ "name": "deploy",+ "description": "Updated command",+ "input": {+ "type": "_choice",+ "hint": "<not a text hint>",+ "options": ["staging", "production"],+ "_meta": { "extension": { "enabled": true } }+ },+ "_meta": { "custom": "preserved" }+ });+ let command: acp_v2::AvailableCommand =+ serde_json::from_value(command_payload.clone()).expect("valid future command input");+ thread.update(cx, |thread, cx| {+ thread.update_available_commands(vec![command], cx);+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, _cx| {+ let capabilities = view.session_capabilities.read();+ assert_eq!(+ serde_json::to_value(capabilities.available_commands())+ .expect("serialize command definitions"),+ json!([command_payload])+ );+ let completions = capabilities.completion_commands();+ assert_eq!(completions.len(), 1);+ let completion = completions.first().expect("replacement command completion");+ assert_eq!(completion.name.as_ref(), "deploy");+ assert_eq!(completion.description.as_ref(), "Updated command");+ assert!(!completion.requires_argument);+ });++ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("/deploy", window, cx)+ });+ cx.run_until_parked();+ editor.update(cx, |editor, cx| {+ assert_eq!(editor.display_text(cx), "/deploy")+ });+ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("/deploy free text", window, cx);+ });+ let (content, _) = message_editor+ .update(cx, |editor, cx| editor.contents(false, cx))+ .await+ .expect("unknown command input still permits text dispatch");+ assert_eq!(+ content,+ vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(+ "/deploy free text"+ ))]+ );++ thread.update(cx, |thread, cx| {+ thread.update_available_commands(Vec::new(), cx);+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, _cx| {+ let capabilities = view.session_capabilities.read();+ assert!(capabilities.available_commands().is_empty());+ assert!(capabilities.completion_commands().is_empty());+ assert!(!capabilities.has_slash_completions());+ });+ assert!(+ message_editor+ .update(cx, |editor, cx| editor.contents(false, cx))+ .await+ .is_err()+ );}#[gpui::test]diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 9729d8c23ed..63033df5bef 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -13495,7 +13495,7 @@ pub(crate) fn open_link(/// command is never echoed as a user message (see `send_command_queueing_remainder`).fn leading_native_command(text: &str,- available_commands: &[acp_v1::AvailableCommand],+ available_commands: &[acp_v2::AvailableCommand],) -> Option<String> {let rest = text.trim_start().strip_prefix('/')?;let name_end = rest.find(char::is_whitespace).unwrap_or(rest.len());@@ -13574,14 +13574,14 @@ mod tests {}}- fn native_command(name: &str) -> acp_v1::AvailableCommand {- acp_v1::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(+ fn native_command(name: &str) -> acp_v2::AvailableCommand {+ acp_v2::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(acp_thread::CommandCategory::Native,))}- fn mcp_command(name: &str) -> acp_v1::AvailableCommand {- acp_v1::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(+ fn mcp_command(name: &str) -> acp_v2::AvailableCommand {+ acp_v2::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(acp_thread::CommandCategory::Mcp,))}diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rsindex 6a524adeb67..9746b4fac22 100644--- a/crates/agent_ui/src/message_editor.rs+++ b/crates/agent_ui/src/message_editor.rs@@ -48,14 +48,14 @@ use zed_actions::agent::{Chat, PasteRaw};#[derive(Default)]pub struct SessionCapabilities {prompt_capabilities: acp_v1::PromptCapabilities,- available_commands: Vec<acp_v1::AvailableCommand>,+ available_commands: Vec<acp_v2::AvailableCommand>,available_skills: Vec<AvailableSkill>,}impl SessionCapabilities {pub fn new(prompt_capabilities: acp_v1::PromptCapabilities,- available_commands: Vec<acp_v1::AvailableCommand>,+ available_commands: Vec<acp_v2::AvailableCommand>,available_skills: Vec<AvailableSkill>,) -> Self {Self {@@ -67,7 +67,7 @@ impl SessionCapabilities {pub fn from_acp_commands(prompt_capabilities: acp_v1::PromptCapabilities,- available_commands: Vec<acp_v1::AvailableCommand>,+ available_commands: Vec<acp_v2::AvailableCommand>,) -> Self {Self::new(prompt_capabilities, available_commands, Vec::new())}@@ -80,7 +80,7 @@ impl SessionCapabilities {self.prompt_capabilities.embedded_context}- pub fn available_commands(&self) -> &[acp_v1::AvailableCommand] {+ pub fn available_commands(&self) -> &[acp_v2::AvailableCommand] {&self.available_commands}@@ -114,7 +114,10 @@ impl SessionCapabilities {.map(|command| AvailableCommand {name: command.name.clone().into(),description: command.description.clone().into(),- requires_argument: command.input.is_some(),+ requires_argument: matches!(+ command.input,+ Some(acp_v2::AvailableCommandInput::Text(_))+ ),source: None,category: acp_thread::command_category_from_meta(&command.meta),})@@ -129,7 +132,7 @@ impl SessionCapabilities {self.prompt_capabilities = prompt_capabilities;}- pub fn set_available_commands(&mut self, available_commands: Vec<acp_v1::AvailableCommand>) {+ pub fn set_available_commands(&mut self, available_commands: Vec<acp_v2::AvailableCommand>) {self.available_commands = available_commands;}@@ -644,13 +647,10 @@ impl MessageEditor {.iter().find(|available_command| available_command.name == command_name)?;- let acp_v1::AvailableCommandInput::Unstructured(acp_v1::UnstructuredCommandInput {- mut hint,- ..- }) = available_command.input.clone()?- else {+ let acp_v2::AvailableCommandInput::Text(input) = available_command.input.as_ref()? else {return None;};+ let mut hint = input.hint.clone();let mut hint_pos = MultiBufferOffset(parsed_command.source_range.end) + 1usize;if hint_pos > snapshot.len() {@@ -751,7 +751,7 @@ impl MessageEditor {fn validate_slash_commands(text: &str,- available_commands: &[acp_v1::AvailableCommand],+ available_commands: &[acp_v2::AvailableCommand],available_skills: &[AvailableSkill],agent_id: &AgentId,) -> Result<()> {@@ -825,7 +825,7 @@ impl MessageEditor {/// when both a global and a project-local skill share a name./// Globals carry an empty scope and so render as `/:<name>`.fn format_available_commands(- commands: &[acp_v1::AvailableCommand],+ commands: &[acp_v2::AvailableCommand],skills: &[AvailableSkill],) -> String {if commands.is_empty() && skills.is_empty() {@@ -2339,7 +2339,7 @@ mod tests {};let session_capabilities = SessionCapabilities::new(acp_v1::PromptCapabilities::default(),- vec![acp_v1::AvailableCommand::new("help", "Get help")],+ vec![acp_v2::AvailableCommand::new("help", "Get help")],vec![skill],);@@ -2355,15 +2355,15 @@ mod tests {let session_capabilities = SessionCapabilities::new(acp_v1::PromptCapabilities::default(),vec![- acp_v1::AvailableCommand::new("compact", "Built-in").meta(+ acp_v2::AvailableCommand::new("compact", "Built-in").meta(acp_thread::meta_with_command_category(acp_thread::CommandCategory::Native),),- acp_v1::AvailableCommand::new("deploy", "MCP").meta(+ acp_v2::AvailableCommand::new("deploy", "MCP").meta(acp_thread::meta_with_command_category(acp_thread::CommandCategory::Mcp),),// No category meta: this is how external ACP agents' commands// arrive, and they should group on their own.- acp_v1::AvailableCommand::new("help", "External"),+ acp_v2::AvailableCommand::new("help", "External"),],Vec::new(),);@@ -2399,7 +2399,7 @@ mod tests {// `/:<name>`); project-local skills carry their worktree root// name. The empty-scope encoding means a worktree literally// named `global` no longer collides with the global source.- let commands = vec![acp_v1::AvailableCommand::new("help", "Get help")];+ let commands = vec![acp_v2::AvailableCommand::new("help", "Get help")];let skills = vec![make_skill("deploy", ""), make_skill("deploy", "zed")];let no_skills = Vec::new();@@ -2727,7 +2727,7 @@ mod tests {// Now simulate Claude providing its list of available commands (which doesn't include file)session_capabilities.write()- .set_available_commands(vec![acp_v1::AvailableCommand::new("help", "Get help")]);+ .set_available_commands(vec![acp_v2::AvailableCommand::new("help", "Get help")]);// Test that unsupported slash commands trigger an error when we have a list of available commandseditor.update_in(cx, |editor, window, cx| {@@ -2844,11 +2844,9 @@ mod tests {let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(acp_v1::PromptCapabilities::default(),vec![- acp_v1::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),- acp_v1::AvailableCommand::new("say-hello", "Say hello to whoever you want").input(- acp_v1::AvailableCommandInput::Unstructured(- acp_v1::UnstructuredCommandInput::new("<name>"),- ),+ acp_v2::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),+ acp_v2::AvailableCommand::new("say-hello", "Say hello to whoever you want").input(+ acp_v2::AvailableCommandInput::Text(acp_v2::TextCommandInput::new("<name>")),),],)));@@ -3128,7 +3126,7 @@ mod tests {let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(acp_v1::PromptCapabilities::default(),- vec![acp_v1::AvailableCommand::new("hello", "Say hello")],+ vec![acp_v2::AvailableCommand::new("hello", "Say hello")],)));// Track every event emitted by the message editor across the