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.

Stop rendering native slash commands as user messages (#58935)

Richard Feldman3ecb86952003
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 07f3f39460d..83b2f304d31 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -2607,6 +2607,27 @@ impl AcpThread {
&mut self,
message: Vec<acp::ContentBlock>,
cx: &mut Context<Self>,
+ ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ self.send_inner(message, true, cx)
+ }
+
+ /// Sends a prompt without displaying a user-message bubble for it.
+ /// This is used for native slash commands (e.g. `/compact`) that run a turn
+ /// which produces its own thread entry (like the compaction summary). The
+ /// typed command isn't sent to the model as an ordinary user turn.
+ pub fn send_command(
+ &mut self,
+ message: Vec<acp::ContentBlock>,
+ cx: &mut Context<Self>,
+ ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ self.send_inner(message, false, cx)
+ }
+
+ fn send_inner(
+ &mut self,
+ message: Vec<acp::ContentBlock>,
+ push_user_message: bool,
+ cx: &mut Context<Self>,
) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
let block = ContentBlock::new_combined(
message.clone(),
@@ -2620,32 +2641,38 @@ impl AcpThread {
let message_id = UserMessageId::new();
self.run_turn(cx, async move |this, cx| {
- this.update(cx, |this, cx| {
- this.push_entry(
- AgentThreadEntry::UserMessage(UserMessage {
- id: Some(message_id.clone()),
- content: block,
- chunks: message,
- checkpoint: None,
- indented: false,
- }),
- cx,
- );
- })
- .ok();
+ if push_user_message {
+ this.update(cx, |this, cx| {
+ this.push_entry(
+ AgentThreadEntry::UserMessage(UserMessage {
+ id: Some(message_id.clone()),
+ content: block,
+ chunks: message,
+ checkpoint: None,
+ indented: false,
+ }),
+ cx,
+ );
+ })
+ .ok();
+
+ let old_checkpoint = git_store
+ .update(cx, |git, cx| git.checkpoint(cx))
+ .await
+ .context("failed to get old checkpoint")
+ .log_err();
+ this.update(cx, |this, _cx| {
+ if let Some((_ix, message)) = this.last_user_message() {
+ message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
+ git_checkpoint,
+ show: false,
+ });
+ }
+ })
+ .ok();
+ }
- let old_checkpoint = git_store
- .update(cx, |git, cx| git.checkpoint(cx))
- .await
- .context("failed to get old checkpoint")
- .log_err();
this.update(cx, |this, cx| {
- if let Some((_ix, message)) = this.last_user_message() {
- message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
- git_checkpoint,
- show: false,
- });
- }
this.connection.prompt(message_id, request, cx)
})?
.await
@@ -4033,6 +4060,80 @@ mod tests {
);
}
+ /// `send_command` runs the turn (the connection receives the typed command)
+ /// but never echoes a user-message bubble, so commands like `/compact` don't
+ /// show a fake user message implying the text was sent to the model.
+ #[gpui::test]
+ async fn test_send_command_does_not_echo_user_message(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+
+ let received_prompt: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
+ let connection = Rc::new(FakeAgentConnection::new().on_user_message({
+ let received_prompt = received_prompt.clone();
+ move |request, thread, mut cx| {
+ let received_prompt = received_prompt.clone();
+ async move {
+ if let Some(acp::ContentBlock::Text(text)) = request.prompt.first() {
+ *received_prompt.borrow_mut() = Some(text.text.clone());
+ }
+ // Simulate a native command producing its own thread entry
+ // (here a compaction) rather than echoing a user message.
+ thread.update(&mut cx, |thread, cx| {
+ thread.push_context_compaction(
+ ContextCompaction {
+ id: ContextCompactionId("c1".into()),
+ status: ContextCompactionStatus::Completed,
+ summary: None,
+ },
+ cx,
+ );
+ })?;
+ Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ }
+ .boxed_local()
+ }
+ }));
+
+ let thread = cx
+ .update(|cx| {
+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
+ })
+ .await
+ .unwrap();
+
+ cx.update(|cx| {
+ thread.update(cx, |thread, cx| {
+ thread.send_command(vec!["/compact".into()], cx)
+ })
+ })
+ .await
+ .unwrap();
+
+ // The command turn ran: the connection received the typed command.
+ assert_eq!(received_prompt.borrow().as_deref(), Some("/compact"));
+
+ thread.update(cx, |thread, _cx| {
+ assert!(
+ !thread
+ .entries
+ .iter()
+ .any(|entry| matches!(entry, AgentThreadEntry::UserMessage(_))),
+ "send_command must not echo a user message"
+ );
+ // The command's own entry (here a compaction) is still shown.
+ assert!(
+ thread
+ .entries
+ .iter()
+ .any(|entry| matches!(entry, AgentThreadEntry::ContextCompaction(_))),
+ "the command's own thread entry should still be present"
+ );
+ });
+ }
+
#[gpui::test]
async fn test_ignore_echoed_user_message_chunks_during_active_turn(
cx: &mut gpui::TestAppContext,
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index b5722c86e75..825c70b780f 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -1454,8 +1454,9 @@ 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.
+ // A built-in command (e.g. `/compact`): run the bare command without
+ // echoing it as a user message, and queue any trailing text the user
+ // typed so it isn't silently dropped.
let native_command =
leading_native_command(text, self.session_capabilities.read().available_commands());
if let Some(command_name) = native_command {
@@ -1519,6 +1520,7 @@ impl ThreadView {
}
this.send_content(
Task::ready(Ok(Some((vec![command_block], Vec::new())))),
+ true,
window,
cx,
);
@@ -1564,12 +1566,13 @@ impl ThreadView {
Ok(Some((contents, tracked_buffers)))
});
- self.send_content(contents_task, window, cx);
+ self.send_content(contents_task, false, window, cx);
}
pub fn send_content(
&mut self,
contents_task: Task<anyhow::Result<Option<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>>,
+ is_native_command: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -1664,7 +1667,11 @@ impl ThreadView {
side = side
);
- thread.send(contents, cx)
+ if is_native_command {
+ thread.send_command(contents, cx)
+ } else {
+ thread.send(contents, cx)
+ }
})?;
let _ = this.update(cx, |this, cx| {
@@ -2055,6 +2062,21 @@ impl ThreadView {
let content = queued.content;
let tracked_buffers = queued.tracked_buffers;
+ // A queued message can itself be a built-in command (e.g. the user typed
+ // `/compact` while a turn was generating). Detect that so we run it as a
+ // command turn without echoing it as a user message, matching the
+ // non-queued path.
+ let is_native_command = content
+ .first()
+ .and_then(|block| match block {
+ acp::ContentBlock::Text(text) => Some(text.text.as_str()),
+ _ => None,
+ })
+ .and_then(|text| {
+ leading_native_command(text, self.session_capabilities.read().available_commands())
+ })
+ .is_some();
+
// Only increment skip count for "Send Now" operations (out-of-order sends)
// Normal auto-processing from the Stopped handler doesn't need to skip.
// We only skip the Stopped event from the cancelled generation, NOT the
@@ -2083,7 +2105,7 @@ impl ThreadView {
Ok(Some((content, tracked_buffers)))
});
- self.send_content(contents_task, window, cx);
+ self.send_content(contents_task, is_native_command, window, cx);
}
pub fn move_queued_message_to_main_editor(
@@ -10795,22 +10817,23 @@ 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.
+/// Returns the name of the leading built-in (native-category) slash command —
+/// e.g. `compact` for `/compact` or `/compact summarize the API work` — whether
+/// or not the user typed any trailing text after it. Built-in commands ignore
+/// trailing arguments, so the caller sends the bare command and queues any
+/// remainder rather than discarding it. Commands from MCP servers and ACP
+/// agents are excluded: their trailing text is a real argument the agent
+/// consumes.
+///
+/// Native commands run a turn that produces its own thread entry, so the typed
+/// command is never echoed as a user message (see `send_command_queueing_remainder`).
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_end = rest.find(char::is_whitespace).unwrap_or(rest.len());
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)
@@ -10851,10 +10874,10 @@ mod tests {
}
#[test]
- fn test_leading_native_command_only_splits_native_with_remainder() {
+ fn test_leading_native_command_matches_bare_and_with_remainder() {
let commands = [native_command("compact"), mcp_command("deploy")];
- // Native command with trailing text -> split.
+ // Native command with trailing text.
assert_eq!(
leading_native_command("/compact summarize the API work", &commands),
Some("compact".to_string())
@@ -10865,12 +10888,22 @@ mod tests {
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);
+ // Bare native command (no remainder) is still recognized, so it runs as
+ // a command turn (without echoing a user message) rather than being sent
+ // to the model as a normal prompt.
+ assert_eq!(
+ leading_native_command("/compact", &commands),
+ Some("compact".to_string())
+ );
+ assert_eq!(
+ leading_native_command("/compact ", &commands),
+ Some("compact".to_string())
+ );
- // MCP/ACP commands consume their trailing text as an argument.
+ // MCP/ACP commands are not native: their trailing text is a real
+ // argument the agent consumes, and they echo as normal user messages.
assert_eq!(leading_native_command("/deploy prod", &commands), None);
+ assert_eq!(leading_native_command("/deploy", &commands), None);
// Unknown command, or not a slash command at all.
assert_eq!(leading_native_command("/unknown foo", &commands), None);