Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Add built-in /compact slash command to the native agent (#58663)
Richard Feldmane5052961af01
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex e3fcf7ac4fa..421a3afb7f0 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -77,6 +77,49 @@ pub fn meta_with_tool_name(tool_name: &str) -> acp::Meta {acp::Meta::from_iter([(TOOL_NAME_META_KEY.into(), tool_name.into())])}+/// Key used in ACP `AvailableCommand` meta to record which source produced a+/// slash command, so the completion popup can group commands by category.+pub const COMMAND_CATEGORY_META_KEY: &str = "command_category";++/// The source category of a slash command, used to group commands in the+/// completion popup. Only the native Zed agent annotates its commands; commands+/// from external ACP agents carry no category and are grouped on their own.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CommandCategory {+ /// Built-in Zed agent commands (e.g. `/compact`).+ Native,+ /// Commands sourced from MCP server prompts.+ Mcp,+}++impl CommandCategory {+ fn as_str(self) -> &'static str {+ match self {+ Self::Native => "native",+ Self::Mcp => "mcp",+ }+ }++ fn from_str(value: &str) -> Option<Self> {+ match value {+ "native" => Some(Self::Native),+ "mcp" => Some(Self::Mcp),+ _ => None,+ }+ }+}++pub fn meta_with_command_category(category: CommandCategory) -> acp::Meta {+ acp::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), category.as_str().into())])+}++pub fn command_category_from_meta(meta: &Option<acp::Meta>) -> Option<CommandCategory> {+ meta.as_ref()+ .and_then(|m| m.get(COMMAND_CATEGORY_META_KEY))+ .and_then(|v| v.as_str())+ .and_then(CommandCategory::from_str)+}+/// Key used in ACP ToolCall meta to store the session id and message indexespub const SUBAGENT_SESSION_INFO_META_KEY: &str = "subagent_session_info";@@ -3440,6 +3483,27 @@ mod tests {};use util::{path, path_list::PathList};+ #[test]+ fn command_category_meta_round_trips() {+ // Exhaustive list of variants. The match below has no wildcard arm, so+ // adding a `CommandCategory` variant fails to compile here until it's+ // covered, keeping the `as_str`/`from_str` wire contract in sync.+ let all = [CommandCategory::Native, CommandCategory::Mcp];+ for category in all {+ match category {+ CommandCategory::Native | CommandCategory::Mcp => {}+ }+ let meta = meta_with_command_category(category);+ assert_eq!(command_category_from_meta(&Some(meta)), Some(category));+ }++ // Absent meta and unknown categories both decode to `None`.+ assert_eq!(command_category_from_meta(&None), None);+ let unknown =+ acp::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), "future-category".into())]);+ assert_eq!(command_category_from_meta(&Some(unknown)), None);+ }+fn init_test(cx: &mut TestAppContext) {env_logger::try_init().ok();cx.update(|cx| {diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 6b4b81e7426..48a1e5b2bf2 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -14,6 +14,7 @@ mod tools;use context_server::ContextServerId;pub use db::*;+use feature_flags::{FeatureFlagAppExt as _, HandoffFeatureFlag};use itertools::Itertools;pub use native_agent_server::NativeAgentServer;pub use pattern_extraction::*;@@ -163,6 +164,27 @@ impl From<&Skill> for NativeAvailableSkill {}}+const COMPACT_COMMAND_NAME: &str = "compact";++/// Returns the set of MCP prompt names that must be server-qualified+/// (`/<server>.<name>`) to stay unambiguous in the slash-command popup: names+/// shared by more than one MCP prompt, or names colliding with a reserved+/// built-in command (e.g. `/compact`). A built-in always wins an unqualified+/// invocation, so colliding MCP prompts are only reachable when prefixed.+fn ambiguous_mcp_prompt_names<'a>(+ reserved: impl IntoIterator<Item = &'a str>,+ prompt_names: impl IntoIterator<Item = &'a str>,+) -> HashSet<&'a str> {+ let mut counts: HashMap<&str, usize> = HashMap::default();+ for name in reserved.into_iter().chain(prompt_names) {+ *counts.entry(name).or_insert(0) += 1;+ }+ counts+ .into_iter()+ .filter_map(|(name, count)| (count > 1).then_some(name))+ .collect()+}+struct ProjectState {project: Entity<Project>,project_context: Entity<ProjectContext>,@@ -1466,25 +1488,33 @@ impl NativeAgent {cx: &App,) -> Vec<acp::AvailableCommand> {let Some(state) = project_state else {- return vec![];+ return Vec::new();};+ let compact_command = cx.has_flag::<HandoffFeatureFlag>().then(|| {+ acp::AvailableCommand::new(+ COMPACT_COMMAND_NAME,+ "Summarize the conversation so far to free up context",+ )+ .meta(acp_thread::meta_with_command_category(+ acp_thread::CommandCategory::Native,+ ))+ });+let registry = state.context_server_registry.read(cx);- let mut prompt_name_counts: HashMap<&str, usize> = HashMap::default();- for context_server_prompt in registry.prompts() {- *prompt_name_counts- .entry(context_server_prompt.prompt.name.as_str())- .or_insert(0) += 1;- }+ // Reserve the built-in command name (when active) so a same-named MCP+ // prompt is force-prefixed (`/<server>.compact`) and stays reachable:+ // an unqualified `/compact` always routes to the native command.+ let reserved = compact_command.as_ref().map(|_| COMPACT_COMMAND_NAME);+ let ambiguous_prompt_names = ambiguous_mcp_prompt_names(+ reserved,+ registry.prompts().map(|p| p.prompt.name.as_str()),+ );let mcp_commands = registry.prompts().flat_map(|context_server_prompt| {let prompt = &context_server_prompt.prompt;- let should_prefix = prompt_name_counts- .get(prompt.name.as_str())- .copied()- .unwrap_or(0)- > 1;+ let should_prefix = ambiguous_prompt_names.contains(prompt.name.as_str());let name = if should_prefix {format!("{}.{}", context_server_prompt.server_id, prompt.name)@@ -1493,7 +1523,10 @@ impl NativeAgent {};let mut command =- acp::AvailableCommand::new(name, prompt.description.clone().unwrap_or_default());+ acp::AvailableCommand::new(name, prompt.description.clone().unwrap_or_default())+ .meta(acp_thread::meta_with_command_category(+ acp_thread::CommandCategory::Mcp,+ ));match prompt.arguments.as_deref() {Some([arg]) => {@@ -1513,7 +1546,7 @@ impl NativeAgent {Some(command)});- mcp_commands.collect()+ compact_command.into_iter().chain(mcp_commands).collect()}pub fn load_thread(@@ -1832,6 +1865,36 @@ impl NativeAgent {})}+ /// Run a summary-based context compaction in response to the built-in+ /// `/compact` slash command.+ fn send_compact_command(+ &self,+ message_id: UserMessageId,+ session_id: acp::SessionId,+ cx: &mut Context<Self>,+ ) -> Task<Result<acp::PromptResponse>> {+ cx.spawn(async move |this, cx| {+ let (acp_thread, thread) = this.update(cx, |this, _cx| {+ let session = this+ .sessions+ .get(&session_id)+ .context("Failed to get session")?;+ anyhow::Ok((session.acp_thread.clone(), session.thread.clone()))+ })??;++ let response_stream = thread.update(cx, |thread, cx| thread.compact(message_id, cx))?;++ cx.update(|cx| {+ NativeAgentConnection::handle_thread_events(+ response_stream,+ acp_thread.downgrade(),+ cx,+ )+ })+ .await+ })+ }+/// Activate a skill in response to a `/skill-name` slash command. The/// skill body is wrapped in the same `<skill_content>` envelope the/// model-driven `skill` tool uses, so the conversation looks the same@@ -2147,6 +2210,12 @@ struct Command<'a> {}impl<'a> Command<'a> {+ fn is_unqualified(&self, prompt_name: &str) -> bool {+ self.prompt_name == prompt_name+ && self.explicit_server_id.is_none()+ && self.skill_scope.is_none()+ }+fn parse(prompt: &'a [acp::ContentBlock]) -> Option<Self> {let acp::ContentBlock::Text(text_content) = prompt.first()? else {return None;@@ -2483,6 +2552,14 @@ impl acp_thread::AgentConnection for NativeAgentConnection {};if let Some(parsed_command) = Command::parse(¶ms.prompt) {+ if cx.has_flag::<HandoffFeatureFlag>()+ && parsed_command.is_unqualified(COMPACT_COMMAND_NAME)+ {+ return self.0.update(cx, |agent, cx| {+ agent.send_compact_command(id, session_id, cx)+ });+ }+// Skill scope qualifiers (`/:<name>` and// `/<worktree>:<name>`) use a colon separator that can't// collide with MCP's `/<server>.<name>` grammar. The popup@@ -3484,12 +3561,14 @@ mod internal_tests {use super::*;use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelInfo, MentionUri};+ use agent_settings::COMPACTION_PROMPT;use fs::FakeFs;use gpui::TestAppContext;use indoc::formatdoc;use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};use language_model::{- LanguageModelCompletionEvent, LanguageModelProviderId, LanguageModelProviderName,+ CompletionIntent, LanguageModelCompletionEvent, LanguageModelProviderId,+ LanguageModelProviderName,};use serde_json::json;use settings::SettingsStore;@@ -3508,6 +3587,231 @@ mod internal_tests {}}+ async fn setup_native_agent_session(+ cx: &mut TestAppContext,+ ) -> (+ Rc<NativeAgentConnection>,+ Entity<NativeAgent>,+ Entity<Project>,+ Entity<AcpThread>,+ ) {+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/", json!({ "a": {} })).await;+ let project = Project::test(fs.clone(), [Path::new("/a")], cx).await;+ let thread_store = cx.new(|cx| ThreadStore::new(cx));+ let agent = cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs, cx));+ let connection = Rc::new(NativeAgentConnection(agent.clone()));+ let acp_thread = cx+ .update(|cx| {+ connection.clone().new_session(+ project.clone(),+ PathList::new(&[Path::new("/a")]),+ cx,+ )+ })+ .await+ .unwrap();++ (connection, agent, project, acp_thread)+ }++ fn native_thread_for_session(+ agent: &Entity<NativeAgent>,+ session_id: &acp::SessionId,+ cx: &App,+ ) -> Entity<Thread> {+ agent.read_with(cx, |agent, _cx| {+ agent.sessions.get(session_id).unwrap().thread.clone()+ })+ }++ fn request_texts_after_system(+ messages: &[language_model::LanguageModelRequestMessage],+ ) -> Vec<String> {+ messages+ .iter()+ .skip(1)+ .map(language_model::LanguageModelRequestMessage::string_contents)+ .collect()+ }++ #[gpui::test]+ async fn test_compact_command_requires_handoff_feature_flag(cx: &mut TestAppContext) {+ init_test(cx);+ let fs = FakeFs::new(cx.executor());+ let project = Project::test(fs.clone(), [], cx).await;+ let thread_store = cx.new(|cx| ThreadStore::new(cx));+ let agent =+ cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), 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();++ cx.update(|cx| {+ let commands = acp_thread.read(cx).available_commands();+ assert!(commands.is_empty());+ });++ cx.update(|cx| cx.update_flags(true, vec!["handoff".to_string()]));++ 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();++ cx.update(|cx| {+ let commands = acp_thread.read(cx).available_commands();++ let compact = commands.iter().find(|command| command.name == "compact");+ let compact = compact.expect("compact command should be available behind the flag");+ assert_eq!(+ acp_thread::command_category_from_meta(&compact.meta),+ Some(acp_thread::CommandCategory::Native),+ );+ });+ }++ #[gpui::test]+ async fn test_compact_prompt_is_regular_prompt_without_handoff(cx: &mut TestAppContext) {+ init_test(cx);+ let (connection, agent, _project, acp_thread) = setup_native_agent_session(cx).await;+ let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());+ let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));+ let model = Arc::new(FakeLanguageModel::default());+ cx.update(|cx| thread.update(cx, |thread, cx| thread.set_model(model.clone(), cx)));++ let message_id = UserMessageId::new();+ let prompt_task = cx.update(|cx| {+ connection.prompt(+ message_id.clone(),+ acp::PromptRequest::new(session_id.clone(), vec!["/compact".into()]),+ cx,+ )+ });+ cx.run_until_parked();++ let request = model.pending_completions().pop().unwrap();+ assert_eq!(request.intent, Some(CompletionIntent::UserPrompt));+ assert_eq!(+ request_texts_after_system(&request.messages),+ vec!["/compact".to_string()]+ );++ model.send_completion_stream_text_chunk(&request, "regular response");+ model.end_completion_stream(&request);+ cx.run_until_parked();+ prompt_task.await.unwrap();+ }++ #[gpui::test]+ async fn test_compact_prompt_routes_to_manual_compaction_with_handoff(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| cx.update_flags(true, vec!["handoff".to_string()]));+ let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await;+ let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());+ let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));+ let model = Arc::new(FakeLanguageModel::default());+ let old_message_id = UserMessageId::new();++ cx.update(|cx| {+ let path_style = project.read(cx).path_style(cx);+ thread.update(cx, |thread, cx| {+ thread.set_model(model.clone(), cx);+ thread.push_acp_user_block(+ old_message_id,+ [acp::ContentBlock::from("old user")],+ path_style,+ cx,+ );+ thread.push_acp_agent_block("old assistant".into(), cx);+ });+ });++ let compact_message_id = UserMessageId::new();+ let prompt_task = cx.update(|cx| {+ connection.prompt(+ compact_message_id,+ acp::PromptRequest::new(session_id.clone(), vec!["/compact".into()]),+ cx,+ )+ });+ cx.run_until_parked();++ let request = model.pending_completions().pop().unwrap();+ assert_eq!(+ request.intent,+ Some(CompletionIntent::ThreadContextSummarization)+ );+ assert_eq!(+ request_texts_after_system(&request.messages),+ vec![+ "old user".to_string(),+ "old assistant".to_string(),+ COMPACTION_PROMPT.to_string(),+ ]+ );++ model.send_completion_stream_text_chunk(&request, "summary");+ model.end_completion_stream(&request);+ cx.run_until_parked();+ prompt_task.await.unwrap();+ }++ #[test]+ fn test_ambiguous_mcp_prompt_names() {+ // Reserving the built-in `/compact` forces a same-named MCP prompt to be+ // server-qualified so it stays reachable; unique names stay bare.+ let ambiguous = ambiguous_mcp_prompt_names([COMPACT_COMMAND_NAME], ["compact", "deploy"]);+ assert!(ambiguous.contains("compact"));+ assert!(!ambiguous.contains("deploy"));++ // Without the reservation (handoff off), a unique MCP prompt is left bare.+ let ambiguous = ambiguous_mcp_prompt_names([], ["compact", "deploy"]);+ assert!(ambiguous.is_empty());++ // Two MCP prompts sharing a name are both qualified regardless of+ // reservation.+ let ambiguous = ambiguous_mcp_prompt_names([], ["dup", "dup", "unique"]);+ assert!(ambiguous.contains("dup"));+ assert!(!ambiguous.contains("unique"));+ }++ #[test]+ fn test_qualified_compact_commands_are_not_native_compact() {+ let unqualified_blocks = [acp::ContentBlock::from("/compact")];+ let unqualified = Command::parse(&unqualified_blocks).unwrap();+ assert!(unqualified.is_unqualified("compact"));++ let mcp_blocks = [acp::ContentBlock::from("/server.compact")];+ let mcp_qualified = Command::parse(&mcp_blocks).unwrap();+ assert_eq!(mcp_qualified.prompt_name, "compact");+ assert_eq!(mcp_qualified.explicit_server_id, Some("server"));+ assert!(!mcp_qualified.is_unqualified("compact"));++ let skill_blocks = [acp::ContentBlock::from("/:compact")];+ let skill_qualified = Command::parse(&skill_blocks).unwrap();+ assert_eq!(skill_qualified.prompt_name, "compact");+ assert_eq!(skill_qualified.skill_scope, Some(""));+ assert!(!skill_qualified.is_unqualified("compact"));+ }+fn make_project_skill(name: &str, description: &str, worktree: &str) -> Skill {Skill {name: name.to_string(),diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex b8406547982..3fd029e8d74 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -2200,6 +2200,82 @@ impl Thread {self.run_turn(cx)}+ /// Force a manual context compaction using the summary strategy,+ /// regardless of the current token usage or context window size.+ pub fn compact(+ &mut self,+ id: UserMessageId,+ cx: &mut Context<Self>,+ ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {+ let model = self+ .model+ .clone()+ .ok_or_else(|| anyhow!(NoModelConfiguredError))?;++ // Flush any pending message and cancel an in-flight turn before we+ // start, mirroring `run_turn` so a stray completion can't race with the+ // compaction we're about to perform.+ self.flush_pending_message(cx);+ self.cancel(cx).detach();++ let compaction = self.forced_compaction_target_ix().map(|request_end_ix| {+ self.advance_prompt_id();+ let request = self.build_compaction_request(request_end_ix, &model, cx);+ self.current_request_token_usage = TokenUsage::default();+ (model, request)+ });++ self.clear_summary();+ cx.notify();++ let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();+ let event_stream = ThreadEventStream(events_tx);+ let (cancellation_tx, mut cancellation_rx) = watch::channel(false);+ let task = cx.spawn({+ let event_stream = event_stream.clone();+ async move |this, cx| {+ let result = if let Some((model, request)) = compaction {+ Self::stream_compaction(+ &this,+ &event_stream,+ cancellation_rx.clone(),+ model,+ request,+ CompactionInsertion::Manual { marker_id: id },+ cx,+ )+ .await+ } else {+ Ok(ControlFlow::Continue(()))+ };++ // If we were cancelled, `cancel()` already took `running_turn`+ // (possibly for a new turn), so leave it alone.+ if *cancellation_rx.borrow() {+ return;+ }++ match result {+ Ok(_) => event_stream.send_stop(acp::StopReason::EndTurn),+ Err(error) => {+ log::error!("Manual compaction failed: {:?}", error);+ event_stream.send_error(error);+ }+ }++ _ = this.update(cx, |this, _| this.running_turn.take());+ }+ });+ self.running_turn = Some(RunningTurn::new(+ event_stream,+ BTreeMap::default(),+ cancellation_tx,+ task,+ ));++ Ok(events_rx)+ }+pub fn push_acp_user_block(&mut self,id: UserMessageId,@@ -2251,13 +2327,11 @@ impl Thread {let event_stream = ThreadEventStream(events_tx);let message_ix = self.messages.len().saturating_sub(1);self.clear_summary();+ let tools = self.enabled_tools(cx);let (cancellation_tx, mut cancellation_rx) = watch::channel(false);- self.running_turn = Some(RunningTurn {- event_stream: event_stream.clone(),- tools: self.enabled_tools(cx),- cancellation_tx,- streaming_tool_inputs: HashMap::default(),- _task: cx.spawn(async move |this, cx| {+ let task = cx.spawn({+ let event_stream = event_stream.clone();+ async move |this, cx| {log::debug!("Starting agent turn execution");let turn_result =@@ -2297,8 +2371,9 @@ impl Thread {}_ = this.update(cx, |this, _| this.running_turn.take());- }),+ }});+ self.running_turn = Some(RunningTurn::new(event_stream, tools, cancellation_tx, task));Ok(events_rx)}@@ -2579,13 +2654,11 @@ impl Thread {async fn perform_compaction_if_needed(this: &WeakEntity<Self>,event_stream: &ThreadEventStream,- mut cancellation_rx: watch::Receiver<bool>,+ cancellation_rx: watch::Receiver<bool>,cx: &mut AsyncApp,) -> Result<ControlFlow<()>> {let Some((model, request, insertion_ix)) = this.update(cx, |this, cx| {- let Some(insertion_ix) = this.compaction_message_target_ix() else {- return None;- };+ let insertion_ix = this.compaction_message_target_ix()?;let model = this.model.clone()?;let request = this.build_compaction_request(insertion_ix, &model, cx);this.current_request_token_usage = TokenUsage::default();@@ -2595,6 +2668,27 @@ impl Thread {return Ok(ControlFlow::Continue(()));};+ Self::stream_compaction(+ this,+ event_stream,+ cancellation_rx,+ model,+ request,+ CompactionInsertion::Auto { insertion_ix },+ cx,+ )+ .await+ }++ async fn stream_compaction(+ this: &WeakEntity<Self>,+ event_stream: &ThreadEventStream,+ mut cancellation_rx: watch::Receiver<bool>,+ model: Arc<dyn LanguageModel>,+ request: LanguageModelRequest,+ insertion: CompactionInsertion,+ cx: &mut AsyncApp,+ ) -> Result<ControlFlow<()>> {log::debug!("Running compaction");let compaction_id = acp_thread::ContextCompactionId(Uuid::new_v4().to_string().into());event_stream.send_context_compaction(compaction_id.clone());@@ -2664,10 +2758,21 @@ impl Thread {this.update(cx, |this, cx| {let compaction = Arc::new(Message::Compaction(CompactionInfo::Summary(summary.into())));- if insertion_ix <= this.messages.len() {- this.messages.insert(insertion_ix, compaction);- } else {- this.messages.push(compaction);+ match insertion {+ CompactionInsertion::Auto { insertion_ix } => {+ if insertion_ix <= this.messages.len() {+ this.messages.insert(insertion_ix, compaction);+ } else {+ this.messages.push(compaction);+ }+ }+ CompactionInsertion::Manual { marker_id } => {+ this.messages.push(Arc::new(Message::User(UserMessage {+ id: marker_id,+ content: Arc::from([]),+ })));+ this.messages.push(compaction);+ }}cx.notify();})?;@@ -3720,6 +3825,18 @@ impl Thread {Some(insertion_ix)}+ /// Insertion point for a manually-triggered compaction.+ /// Returns `None` only when there is nothing to summarize (no messages, or the thread already ends in a compaction).+ fn forced_compaction_target_ix(&self) -> Option<usize> {+ if matches!(+ self.messages.last().map(|message| &**message),+ None | Some(Message::Compaction(_))+ ) {+ return None;+ }+ Some(self.messages.len())+ }+fn build_compaction_request(&self,insertion_ix: usize,@@ -3984,6 +4101,16 @@ fn take_text_within_byte_budget(text: String, remaining_bytes: &mut usize) -> Opif text.is_empty() { None } else { Some(text) }}+/// Describes where a streamed compaction summary should land in the thread+/// once it completes successfully.+enum CompactionInsertion {+ /// Automatic compaction inserts the summary at an index computed up front+ /// (which may be before a trailing not-yet-answered user message).+ Auto { insertion_ix: usize },+ /// Manual `/compact` appends a zero-content user message followed by the summary.+ Manual { marker_id: UserMessageId },+}+struct RunningTurn {/// Holds the task that handles agent interaction until the end of the turn./// Survives across multiple requests as the model performs tool calls and@@ -4004,6 +4131,21 @@ struct RunningTurn {}impl RunningTurn {+ fn new(+ event_stream: ThreadEventStream,+ tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,+ cancellation_tx: watch::Sender<bool>,+ task: Task<()>,+ ) -> Self {+ Self {+ _task: task,+ event_stream,+ tools,+ cancellation_tx,+ streaming_tool_inputs: HashMap::default(),+ }+ }+fn cancel(mut self) -> Task<()> {log::debug!("Cancelling in progress turn");self.cancellation_tx.send(true).ok();@@ -5670,6 +5812,229 @@ mod tests {});}+ #[gpui::test]+ async fn test_manual_compact_forces_summary(cx: &mut TestAppContext) {+ let (thread, _event_stream) = setup_thread_for_test(cx).await;+ let model = Arc::new(FakeLanguageModel::default());+ // A context window below the minimum and no recorded token usage would+ // both disable *automatic* compaction. Manual compaction forces it anyway.+ model.set_max_token_count(MIN_COMPACTION_CONTEXT_WINDOW - 1);+ let user_message_id = UserMessageId::new();+ let compact_message_id = UserMessageId::new();++ cx.update(|cx| {+ thread.update(cx, |thread, cx| {+ thread.set_model(model.clone(), cx);+ thread+ .messages+ .push(user_text_message(user_message_id.clone(), "old user"));+ thread.messages.push(agent_text_message("old assistant"));+ // Auto-compaction would be a no-op here.+ assert_eq!(thread.compaction_message_target_ix(), None);+ });+ });++ let _events = cx+ .update(|cx| {+ thread.update(cx, |thread, cx| {+ thread.compact(compact_message_id.clone(), cx)+ })+ })+ .unwrap();+ cx.run_until_parked();++ let compaction_request = model.pending_completions().pop().unwrap();+ assert_eq!(+ compaction_request.intent,+ Some(CompletionIntent::ThreadContextSummarization)+ );+ let compaction_texts = request_texts_after_system(&compaction_request.messages);+ assert_eq!(compaction_texts.len(), 3);+ assert_eq!(compaction_texts[0], "old user");+ assert_eq!(compaction_texts[1], "old assistant");+ assert_eq!(compaction_texts[2], COMPACTION_PROMPT);++ model.send_completion_stream_text_chunk(&compaction_request, "summary of old context");+ model.end_completion_stream(&compaction_request);+ cx.run_until_parked();++ // The compaction summary is appended after a zero-content user message+ // marker, and no follow-up model turn is requested — `/compact` only+ // compacts.+ assert!(model.pending_completions().is_empty());+ cx.update(|cx| {+ thread.read_with(cx, |thread, _cx| {+ assert!(matches!(&*thread.messages[0], Message::User(_)));+ assert!(matches!(&*thread.messages[1], Message::Agent(_)));+ assert!(matches!(+ &*thread.messages[2],+ Message::User(UserMessage { id, content }) if id == &compact_message_id && content.is_empty()+ ));+ assert!(matches!(+ &*thread.messages[3],+ Message::Compaction(CompactionInfo::Summary(summary)) if summary.as_ref() == "summary of old context"+ ));+ // Re-running `/compact` with nothing new to summarize is a+ // no-op: the thread already ends in a compaction.+ assert_eq!(thread.forced_compaction_target_ix(), None);+ });++ thread+ .update(cx, |thread, cx| thread.truncate(compact_message_id.clone(), cx))+ .unwrap();++ thread.read_with(cx, |thread, _cx| {+ assert_eq!(thread.messages.len(), 2);+ assert!(matches!(&*thread.messages[0], Message::User(_)));+ assert!(matches!(&*thread.messages[1], Message::Agent(_)));+ });+ });+ }++ /// Cancelling an in-flight manual compaction must not leave the zero-content+ /// rewind marker (or a partial summary) dangling at the end of the thread.+ #[gpui::test]+ async fn test_manual_compact_cancelled_leaves_no_marker(cx: &mut TestAppContext) {+ let (thread, _event_stream) = setup_thread_for_test(cx).await;+ let model = Arc::new(FakeLanguageModel::default());++ cx.update(|cx| {+ thread.update(cx, |thread, cx| {+ thread.set_model(model.clone(), cx);+ thread+ .messages+ .push(user_text_message(UserMessageId::new(), "old user"));+ thread.messages.push(agent_text_message("old assistant"));+ });+ });++ let _events = cx+ .update(|cx| thread.update(cx, |thread, cx| thread.compact(UserMessageId::new(), cx)))+ .unwrap();+ cx.run_until_parked();+ // The compaction request is in flight but hasn't streamed a summary.+ assert_eq!(model.pending_completions().len(), 1);++ cx.update(|cx| thread.update(cx, |thread, cx| thread.cancel(cx)))+ .await;+ cx.run_until_parked();++ thread.read_with(cx, |thread, _cx| {+ assert_eq!(thread.messages.len(), 2);+ assert!(matches!(&*thread.messages[0], Message::User(_)));+ assert!(matches!(&*thread.messages[1], Message::Agent(_)));+ });+ }++ /// A failed compaction (here, an empty summary) reports an error and leaves+ /// the thread untouched — no marker, no compaction.+ #[gpui::test]+ async fn test_manual_compact_empty_summary_leaves_no_marker(cx: &mut TestAppContext) {+ let (thread, _event_stream) = setup_thread_for_test(cx).await;+ let model = Arc::new(FakeLanguageModel::default());++ cx.update(|cx| {+ thread.update(cx, |thread, cx| {+ thread.set_model(model.clone(), cx);+ thread+ .messages+ .push(user_text_message(UserMessageId::new(), "old user"));+ thread.messages.push(agent_text_message("old assistant"));+ });+ });++ let mut events = cx+ .update(|cx| thread.update(cx, |thread, cx| thread.compact(UserMessageId::new(), cx)))+ .unwrap();+ cx.run_until_parked();++ let request = model.pending_completions().pop().unwrap();+ // End the stream without emitting any summary text.+ model.end_completion_stream(&request);+ cx.run_until_parked();++ // An error is surfaced, and the thread is left exactly as it was. The+ // compaction task drops the event stream after failing, so the channel+ // closes and this drain terminates.+ let mut saw_error = false;+ while let Some(event) = events.next().await {+ if event.is_err() {+ saw_error = true;+ }+ }+ assert!(saw_error, "expected an error event for the empty summary");+ thread.read_with(cx, |thread, _cx| {+ assert_eq!(thread.messages.len(), 2);+ assert!(matches!(&*thread.messages[0], Message::User(_)));+ assert!(matches!(&*thread.messages[1], Message::Agent(_)));+ });+ }++ /// `/compact` on an empty thread (nothing to summarize) is a no-op: it+ /// issues no model request and adds no marker.+ #[gpui::test]+ async fn test_manual_compact_noop_on_empty_thread(cx: &mut TestAppContext) {+ let (thread, _event_stream) = setup_thread_for_test(cx).await;+ let model = Arc::new(FakeLanguageModel::default());+ cx.update(|cx| thread.update(cx, |thread, cx| thread.set_model(model.clone(), cx)));++ let _events = cx+ .update(|cx| thread.update(cx, |thread, cx| thread.compact(UserMessageId::new(), cx)))+ .unwrap();+ cx.run_until_parked();++ assert!(model.pending_completions().is_empty());+ thread.read_with(cx, |thread, _cx| {+ assert!(thread.messages.is_empty());+ });+ }++ /// The zero-content marker replays as an empty user message, which the UI+ /// drops (it renders content blocks, of which there are none), so reloading+ /// a compacted thread doesn't surface an empty `/compact` bubble.+ #[gpui::test]+ async fn test_manual_compact_marker_replays_as_empty_user_message(cx: &mut TestAppContext) {+ let (thread, _event_stream) = setup_thread_for_test(cx).await;+ let marker_id = UserMessageId::new();++ let mut replay_events = cx.update(|cx| {+ thread.update(cx, |thread, cx| {+ thread+ .messages+ .push(user_text_message(UserMessageId::new(), "before"));+ thread.messages.push(agent_text_message("answer"));+ thread.messages.push(Arc::new(Message::User(UserMessage {+ id: marker_id.clone(),+ content: Arc::from([]),+ })));+ thread.messages.push(summary_compaction("summary"));+ thread.replay(cx)+ })+ });++ // Skip the leading "before"/"answer" replay events.+ let _ = replay_events.next().await;+ let _ = replay_events.next().await;++ let event = replay_events.next().await;+ match event {+ Some(Ok(ThreadEvent::UserMessage(message))) => {+ assert_eq!(message.id, marker_id);+ assert!(+ message.content.is_empty(),+ "marker should replay with no content so the UI renders nothing"+ );+ }+ _ => panic!("expected the marker to replay as a user message, got {event:?}"),+ }++ let event = replay_events.next().await;+ assert!(+ matches!(&event, Some(Ok(ThreadEvent::ContextCompaction(_)))),+ "expected the compaction to replay after the marker, got {event:?}"+ );+ }+#[gpui::test]async fn test_compaction_usage_counts_toward_cumulative_usage(cx: &mut TestAppContext) {let (thread, _event_stream) = setup_thread_for_test(cx).await;diff --git a/crates/agent_ui/src/completion_provider.rs b/crates/agent_ui/src/completion_provider.rsindex f38568624db..01c58ab38a2 100644--- a/crates/agent_ui/src/completion_provider.rs+++ b/crates/agent_ui/src/completion_provider.rs@@ -334,6 +334,32 @@ pub struct AvailableCommand {pub description: Arc<str>,pub requires_argument: bool,pub source: Option<SharedString>,+ /// Source category used to group the command in the slash popup. `None`+ /// means the command came from an external ACP agent.+ pub category: Option<acp_thread::CommandCategory>,+}++impl AvailableCommand {+ fn category_order(&self) -> u8 {+ match self.category {+ Some(acp_thread::CommandCategory::Native) => 0,+ Some(acp_thread::CommandCategory::Mcp) => 1,+ None => 2,+ }+ }++ /// Completion group key and header label for this command's category.+ fn group(&self) -> CompletionGroup {+ let (key, label) = match self.category {+ Some(acp_thread::CommandCategory::Native) => ("commands", "Commands"),+ Some(acp_thread::CommandCategory::Mcp) => ("mcp-commands", "MCP Server Commands"),+ None => ("acp-commands", "Commands"),+ };+ CompletionGroup {+ key: key.into(),+ label: Some(label.into()),+ }+ }}#[derive(Debug, Clone)]@@ -351,6 +377,29 @@ impl SlashCompletionCandidate {}}+/// Stable group identity for a slash completion: skills are one group, commands+/// are grouped by category. This identifies which section header an entry sits+/// under; the order the groups appear in is decided by relevance (see+/// [`group_by_relevance`]).+fn slash_completion_group_key(candidate: &SlashCompletionCandidate) -> u32 {+ match candidate {+ SlashCompletionCandidate::Skill(_) => 0,+ SlashCompletionCandidate::Command(command) => 1 + command.category_order() as u32,+ }+}++/// Reorders `items` (which must already be in relevance/score order, best+/// first) so that each group's entries stay contiguous while the groups+/// themselves are ordered by their best-ranked member. The sort is stable, so+/// within a group the original order is preserved.+fn group_by_relevance<T>(items: &mut [T], group_key: impl Fn(&T) -> u32) {+ let mut group_best_rank: collections::HashMap<u32, usize> = collections::HashMap::default();+ for (rank, item) in items.iter().enumerate() {+ group_best_rank.entry(group_key(item)).or_insert(rank);+ }+ items.sort_by_key(|item| group_best_rank[&group_key(item)]);+}+pub trait PromptCompletionProviderDelegate: Send + Sync + 'static {fn supports_context(&self, mode: PromptContextType, cx: &App) -> bool {self.supported_modes(cx).contains(&mode)@@ -1327,11 +1376,13 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletioPromptCompletion::SlashCommand(SlashCommandCompletion {command, argument, ..}) => {- let show_section_headers = command.is_none() && argument.is_none();let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);- // Resolve the muted-text highlight up front: the- // completion build happens on a background thread where- // `cx.theme()` isn't available.+ // Keep the category section headers visible while the user is+ // still narrowing the command name (`/c`); only drop them once+ // they've moved on to typing the command's argument, where+ // grouping no longer applies.+ let show_section_headers = argument.is_none();+let source_highlight_id = cx.theme().syntax()@@ -1387,9 +1438,16 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletiocx.background_spawn(async move {let mut slash_candidates = slash_candidates.await;- slash_candidates.sort_by_key(|(candidate, _)| match candidate {- SlashCompletionCandidate::Skill(_) => 0,- SlashCompletionCandidate::Command(_) => 1,+ // `slash_candidates` arrives in fuzzy-match order (best+ // first). Keep each group's items contiguous so section+ // headers render once, but order the groups by their+ // best-scoring member. That way an exact/prefix match (e.g.+ // `/compa` -> `compact`) floats its whole section to the top+ // and becomes the default selection, instead of being+ // buried under a less relevant skill. Within a group, the+ // fuzzy-match order is preserved (the sort is stable).+ group_by_relevance(&mut slash_candidates, |(candidate, _)| {+ slash_completion_group_key(candidate)});let completions = slash_candidates.into_iter()@@ -1440,6 +1498,7 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletiolet is_missing_argument =command.requires_argument && argument.is_none();+ let group = show_section_headers.then(|| command.group());Completion {replace_range: source_range.clone(),@@ -1475,10 +1534,7 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletiofalse}})),- group: show_section_headers.then(|| CompletionGroup {- key: "agent-commands".into(),- label: Some("Agent Commands".into()),- }),+ group,}}})@@ -2800,6 +2856,51 @@ mod tests {assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);}+ #[test]+ fn test_section_headers_visible_until_argument() {+ // Section headers stay visible while the user narrows the command name+ // (`/`, `/comp`, `/compact `) and only disappear once they start typing+ // the command's argument, where category grouping no longer applies.+ let show_section_headers = |input: &str| {+ SlashCommandCompletion::try_parse(input, 0)+ .unwrap()+ .argument+ .is_none()+ };++ assert!(show_section_headers("/"));+ assert!(show_section_headers("/comp"));+ assert!(show_section_headers("/compact"));+ assert!(show_section_headers("/compact "));+ assert!(!show_section_headers("/compact now"));+ }++ #[test]+ fn test_group_by_relevance_floats_best_group_and_keeps_groups_contiguous() {+ // Items arrive in fuzzy-score order (best first). The group containing+ // the best match floats to the top, groups stay contiguous, and the+ // within-group order is preserved.+ let mut items = [+ ("compact", 1u32), // best match, group 1+ ("skill-a", 0u32), // group 0+ ("deploy", 2u32), // group 2+ ("skill-b", 0u32), // group 0 (after skill-a in score order)+ ("native-b", 1u32), // group 1 (after compact)+ ];+ group_by_relevance(&mut items, |(_, key)| *key);+ let order: Vec<&str> = items.iter().map(|(name, _)| *name).collect();+ assert_eq!(+ order,+ vec!["compact", "native-b", "skill-a", "skill-b", "deploy"]+ );++ // When the best match is a skill, the skill group leads instead.+ let mut items = [("skill-a", 0u32), ("compact", 1u32)];+ group_by_relevance(&mut items, |(_, key)| *key);+ let order: Vec<&str> = items.iter().map(|(name, _)| *name).collect();+ assert_eq!(order, vec!["skill-a", "compact"]);+ }+#[test]fn test_mention_completion_parse() {let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 0e5570e06ec..58f2e804c95 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -1452,10 +1452,80 @@ impl ThreadView {}}+ // A built-in command (e.g. `/compact`) with trailing text: send the bare+ // command and queue the rest, so the extra text isn't silently dropped.+ let native_command =+ leading_native_command(text, self.session_capabilities.read().available_commands());+ if let Some(command_name) = native_command {+ cx.emit(AcpThreadViewEvent::Interacted);+ self.send_command_queueing_remainder(message_editor, command_name, window, cx);+ return;+ }+cx.emit(AcpThreadViewEvent::Interacted);self.send_impl(message_editor, window, cx)}+ /// Sends a bare `/command` turn and queues everything the user typed after+ /// it as a follow-up message. The queued remainder auto-processes when the+ /// command turn stops, so e.g. `/compact do X` compacts and then runs `do X`+ /// rather than discarding it.+ fn send_command_queueing_remainder(+ &mut self,+ message_editor: Entity<MessageEditor>,+ command_name: String,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ // Resolve the editor contents before clearing it: the resolve task+ // reads the editor lazily, so clearing first would wipe the contents.+ let contents = self.resolve_message_contents(&message_editor, cx);+ self.thread_error.take();+ self.thread_feedback.clear();+ self.editing_message.take();++ cx.spawn_in(window, async move |this, cx| {+ let (mut content, tracked_buffers) = contents.await?;++ cx.update(|window, cx| {+ message_editor.update(cx, |message_editor, cx| {+ message_editor.clear(window, cx);+ });+ })?;++ // Strip the leading `/command` from the first text block; whatever+ // remains (including any later mention blocks) becomes the queued+ // follow-up message.+ if let Some(acp::ContentBlock::Text(text_content)) = content.first_mut() {+ text_content.text = strip_leading_command(&text_content.text, &command_name);+ }+ if matches!(+ content.first(),+ Some(acp::ContentBlock::Text(text)) if text.text.trim().is_empty()+ ) {+ content.remove(0);+ }++ let command_block =+ acp::ContentBlock::Text(acp::TextContent::new(format!("/{command_name}")));++ this.update_in(cx, |this, window, cx| {+ // Queue the remainder first, then start the command turn; the+ // queue auto-processes when the command turn stops.+ if !content.is_empty() {+ this.add_to_queue(content, tracked_buffers, cx);+ }+ this.send_content(+ Task::ready(Ok(Some((vec![command_block], Vec::new())))),+ window,+ cx,+ );+ })?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }+pub fn send_impl(&mut self,message_editor: Entity<MessageEditor>,@@ -10557,6 +10627,41 @@ pub(crate) fn open_link(}}+/// If `text` is a built-in (native-category) slash command followed by extra+/// text — e.g. `/compact summarize the API work` — returns the command name.+/// Built-in commands ignore trailing arguments, so the caller sends the bare+/// command and queues the remainder rather than discarding it. Commands from+/// MCP servers and ACP agents are excluded: their trailing text is a real+/// argument the agent consumes.+fn leading_native_command(+ text: &str,+ available_commands: &[acp::AvailableCommand],+) -> Option<String> {+ let rest = text.trim_start().strip_prefix('/')?;+ let name_end = rest.find(char::is_whitespace)?;+ let name = &rest[..name_end];+ if rest[name_end..].trim().is_empty() {+ return None;+ }+ let is_native = available_commands.iter().any(|command| {+ command.name == name+ && acp_thread::command_category_from_meta(&command.meta)+ == Some(acp_thread::CommandCategory::Native)+ });+ is_native.then(|| name.to_string())+}++/// Removes a leading `/command_name` token from `text`, returning the trimmed+/// remainder. Falls back to the trimmed input if the prefix isn't present.+fn strip_leading_command(text: &str, command_name: &str) -> String {+ let trimmed = text.trim_start();+ trimmed+ .strip_prefix('/')+ .and_then(|rest| rest.strip_prefix(command_name))+ .map(|rest| rest.trim_start().to_string())+ .unwrap_or_else(|| trimmed.to_string())+}+#[cfg(test)]mod tests {use super::*;@@ -10565,6 +10670,56 @@ mod tests {use util::path;use workspace::MultiWorkspace;+ fn native_command(name: &str) -> acp::AvailableCommand {+ acp::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(+ acp_thread::CommandCategory::Native,+ ))+ }++ fn mcp_command(name: &str) -> acp::AvailableCommand {+ acp::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(+ acp_thread::CommandCategory::Mcp,+ ))+ }++ #[test]+ fn test_leading_native_command_only_splits_native_with_remainder() {+ let commands = [native_command("compact"), mcp_command("deploy")];++ // Native command with trailing text -> split.+ assert_eq!(+ leading_native_command("/compact summarize the API work", &commands),+ Some("compact".to_string())+ );+ // Leading/trailing whitespace is tolerated.+ assert_eq!(+ leading_native_command(" /compact do x ", &commands),+ Some("compact".to_string())+ );++ // Bare native command (no remainder) -> no split; it sends normally.+ assert_eq!(leading_native_command("/compact", &commands), None);+ assert_eq!(leading_native_command("/compact ", &commands), None);++ // MCP/ACP commands consume their trailing text as an argument.+ assert_eq!(leading_native_command("/deploy prod", &commands), None);++ // Unknown command, or not a slash command at all.+ assert_eq!(leading_native_command("/unknown foo", &commands), None);+ assert_eq!(leading_native_command("just a message", &commands), None);+ }++ #[test]+ fn test_strip_leading_command() {+ assert_eq!(strip_leading_command("/compact do x", "compact"), "do x");+ assert_eq!(+ strip_leading_command(" /compact do x ", "compact"),+ "do x "+ );+ // No matching prefix: returns the trimmed input unchanged.+ assert_eq!(strip_leading_command("hello", "compact"), "hello");+ }+#[gpui::test]async fn test_open_link_bare_path(cx: &mut gpui::TestAppContext) {crate::test_support::init_test(cx);diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rsindex 951959a1b01..d25f86c516c 100644--- a/crates/agent_ui/src/message_editor.rs+++ b/crates/agent_ui/src/message_editor.rs@@ -116,6 +116,7 @@ impl SessionCapabilities {description: command.description.clone().into(),requires_argument: command.input.is_some(),source: None,+ category: acp_thread::command_category_from_meta(&command.meta),}).collect()}@@ -2297,6 +2298,40 @@ mod tests {assert_eq!(skills[0].skill_file_path, skill_file_path);}+ #[test]+ fn test_completion_commands_derive_category_from_meta() {+ let session_capabilities = SessionCapabilities::new(+ acp::PromptCapabilities::default(),+ vec![+ acp::AvailableCommand::new("compact", "Built-in").meta(+ acp_thread::meta_with_command_category(acp_thread::CommandCategory::Native),+ ),+ acp::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::AvailableCommand::new("help", "External"),+ ],+ Vec::new(),+ );++ let commands = session_capabilities.completion_commands();+ let category = |name: &str| {+ commands+ .iter()+ .find(|command| command.name.as_ref() == name)+ .unwrap()+ .category+ };+ assert_eq!(+ category("compact"),+ Some(acp_thread::CommandCategory::Native)+ );+ assert_eq!(category("deploy"), Some(acp_thread::CommandCategory::Mcp));+ assert_eq!(category("help"), None);+ }+#[test]fn test_validate_slash_commands_accepts_scope_qualified_skill() {let agent_id = AgentId::from("Zed");