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.

acp: Use first-class ACP tool-call names (#64080)

Ben Brandt3e442f25b701
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index c3ec880cb58..f7b8140f969 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -63,19 +63,18 @@ impl std::fmt::Display for MaxOutputTokensError {
impl std::error::Error for MaxOutputTokensError {}
-/// Key used in ACP ToolCall meta to store the tool's programmatic name.
-/// This is a workaround since ACP's ToolCall doesn't have a dedicated name field.
+/// Legacy ACP metadata key used before tool calls had a dedicated name field.
pub const TOOL_NAME_META_KEY: &str = "tool_name";
-/// Helper to extract tool name from ACP meta
+/// Extracts a tool name from the legacy ACP metadata field.
pub fn tool_name_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
meta.as_ref()
- .and_then(|m| m.get(TOOL_NAME_META_KEY))
- .and_then(|v| v.as_str())
- .map(|s| SharedString::from(s.to_owned()))
+ .and_then(|meta| meta.get(TOOL_NAME_META_KEY))
+ .and_then(|value| value.as_str())
+ .map(|name| SharedString::from(name.to_owned()))
}
-/// Helper to create meta with tool name
+/// Creates ACP metadata containing the legacy tool-name field.
pub fn meta_with_tool_name(tool_name: &str) -> acp::Meta {
acp::Meta::from_iter([(TOOL_NAME_META_KEY.into(), tool_name.into())])
}
@@ -916,7 +915,10 @@ impl ToolCall {
.as_ref()
.and_then(|input| markdown_for_raw_output(input, &language_registry, cx));
- let tool_name = tool_name_from_meta(&tool_call.meta);
+ let tool_name = tool_call
+ .name
+ .map(SharedString::from)
+ .or_else(|| tool_name_from_meta(&tool_call.meta));
let subagent_session_info = subagent_session_info_from_meta(&tool_call.meta);
let sandbox_authorization_details =
@@ -964,6 +966,7 @@ impl ToolCall {
kind,
status,
title,
+ name,
content,
locations,
raw_input,
@@ -979,6 +982,14 @@ impl ToolCall {
self.update_acp_status(status);
}
+ if let Some(tool_name) = name.map(SharedString::from) {
+ self.tool_name = Some(tool_name);
+ } else if self.tool_name.is_none() {
+ // Legacy metadata only fills a missing name so it cannot replace a
+ // first-class name received earlier.
+ self.tool_name = tool_name_from_meta(&meta);
+ }
+
if let Some(subagent_session_info) = subagent_session_info_from_meta(&meta) {
self.subagent_session_info = Some(subagent_session_info);
}
@@ -6446,6 +6457,148 @@ mod tests {
});
}
+ #[gpui::test]
+ async fn test_tool_call_name_precedence_and_updates(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let connection = Rc::new(FakeAgentConnection::new());
+ let thread = cx
+ .update(|cx| {
+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
+ })
+ .await
+ .expect("failed to create ACP thread");
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.handle_session_update(
+ acp::SessionUpdate::ToolCall(
+ acp::ToolCall::new("tool-call", "Tool call")
+ .name("first_class")
+ .meta(meta_with_tool_name("legacy")),
+ ),
+ cx,
+ )
+ })
+ .expect("failed to create first-class named tool call");
+
+ thread.read_with(cx, |thread, _| {
+ let Some(AgentThreadEntry::ToolCall(tool_call)) = thread.entries.last() else {
+ unreachable!("tool call update must create a tool call entry");
+ };
+ assert_eq!(tool_call.tool_name.as_deref(), Some("first_class"));
+ });
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.handle_session_update(
+ acp::SessionUpdate::ToolCall(
+ acp::ToolCall::new("legacy-tool-call", "Legacy tool call")
+ .meta(meta_with_tool_name("legacy")),
+ ),
+ cx,
+ )
+ })
+ .expect("failed to create legacy named tool call");
+
+ thread.read_with(cx, |thread, _| {
+ let Some(AgentThreadEntry::ToolCall(tool_call)) = thread.entries.last() else {
+ unreachable!("tool call update must create a tool call entry");
+ };
+ assert_eq!(tool_call.tool_name.as_deref(), Some("legacy"));
+ });
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.handle_session_update(
+ acp::SessionUpdate::ToolCallUpdate(
+ acp::ToolCallUpdate::new("tool-call", acp::ToolCallUpdateFields::new())
+ .meta(meta_with_tool_name("legacy_update")),
+ ),
+ cx,
+ )
+ })
+ .expect("failed to apply stale legacy tool-call name update");
+
+ thread.read_with(cx, |thread, _| {
+ let Some(tool_call) = thread.entries.iter().find_map(|entry| match entry {
+ AgentThreadEntry::ToolCall(tool_call)
+ if tool_call.id == acp::ToolCallId::new("tool-call") =>
+ {
+ Some(tool_call)
+ }
+ _ => None,
+ }) else {
+ unreachable!("tool call update must create a tool call entry");
+ };
+ assert_eq!(tool_call.tool_name.as_deref(), Some("first_class"));
+ });
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.handle_session_update(
+ acp::SessionUpdate::ToolCallUpdate(
+ acp::ToolCallUpdate::new(
+ "legacy-tool-call",
+ acp::ToolCallUpdateFields::new().name("first_class_update"),
+ )
+ .meta(meta_with_tool_name("ignored_legacy_update")),
+ ),
+ cx,
+ )
+ })
+ .expect("failed to apply first-class tool-call name update");
+
+ thread.read_with(cx, |thread, _| {
+ let Some(tool_call) = thread.entries.iter().find_map(|entry| match entry {
+ AgentThreadEntry::ToolCall(tool_call)
+ if tool_call.id == acp::ToolCallId::new("legacy-tool-call") =>
+ {
+ Some(tool_call)
+ }
+ _ => None,
+ }) else {
+ unreachable!("tool call update must create a tool call entry");
+ };
+ assert_eq!(tool_call.tool_name.as_deref(), Some("first_class_update"));
+ });
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.handle_session_update(
+ acp::SessionUpdate::ToolCall(acp::ToolCall::new(
+ "late-legacy-tool-call",
+ "Late legacy tool call",
+ )),
+ cx,
+ )
+ })
+ .expect("failed to create unnamed tool call");
+ thread
+ .update(cx, |thread, cx| {
+ thread.handle_session_update(
+ acp::SessionUpdate::ToolCallUpdate(
+ acp::ToolCallUpdate::new(
+ "late-legacy-tool-call",
+ acp::ToolCallUpdateFields::new(),
+ )
+ .meta(meta_with_tool_name("late_legacy")),
+ ),
+ cx,
+ )
+ })
+ .expect("failed to apply late legacy tool-call name");
+
+ thread.read_with(cx, |thread, _| {
+ let Some(AgentThreadEntry::ToolCall(tool_call)) = thread.entries.last() else {
+ unreachable!("tool call update must preserve the tool call entry");
+ };
+ assert_eq!(tool_call.tool_name.as_deref(), Some("late_legacy"));
+ });
+ }
+
#[gpui::test]
async fn test_tool_call_location_resolves_external_file(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index 998c0e16f19..14b8c9882e6 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -4136,6 +4136,126 @@ mod internal_tests {
prompt_task.await.unwrap();
}
+ #[gpui::test]
+ async fn test_native_tool_names_survive_reused_ids_and_reload(cx: &mut TestAppContext) {
+ use language_model::{LanguageModelToolUse, LanguageModelToolUseInput};
+
+ init_test(cx);
+ let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await;
+ let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));
+ let model = Arc::new(FakeLanguageModel::default());
+ let fs = project.read_with(cx, |project, _| project.fs().clone());
+ fs.write(Path::new("/a/file.txt"), b"retained file contents")
+ .await
+ .expect("test file should be written");
+ cx.update(|cx| {
+ let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
+ settings.tool_permissions.default = settings::ToolPermissionMode::Allow;
+ settings.tool_permissions.tools.clear();
+ agent_settings::AgentSettings::override_global(settings, cx);
+ thread.update(cx, |thread, cx| thread.set_model(model.clone(), cx));
+ });
+
+ for tool_name in ["read_file", "unavailable_tool"] {
+ let prompt_task = cx.update(|cx| {
+ acp_thread::AgentSessionClientUserMessageIds::prompt(
+ connection.as_ref(),
+ ClientUserMessageId::new(),
+ acp::PromptRequest::new(session_id.clone(), vec!["use a tool".into()]),
+ cx,
+ )
+ });
+ cx.run_until_parked();
+ let request = model
+ .pending_completions()
+ .pop()
+ .expect("user prompt should reach the model");
+ let input = json!({"path": "a/file.txt"});
+ model.send_completion_stream_event(
+ &request,
+ LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
+ id: "reused_id".into(),
+ name: tool_name.into(),
+ raw_input: input.to_string(),
+ input: LanguageModelToolUseInput::Json(input),
+ is_input_complete: true,
+ thought_signature: None,
+ }),
+ );
+ model.end_completion_stream(&request);
+ cx.run_until_parked();
+ let request = model
+ .pending_completions()
+ .pop()
+ .expect("tool result should reach the model");
+ assert_eq!(request.intent, Some(CompletionIntent::ToolResults));
+ model.send_completion_stream_text_chunk(&request, "done");
+ model.end_completion_stream(&request);
+ cx.run_until_parked();
+ prompt_task.await.expect("native tool turn should complete");
+ }
+
+ let tool_names = |thread: &AcpThread| {
+ thread
+ .entries()
+ .iter()
+ .filter_map(|entry| match entry {
+ acp_thread::AgentThreadEntry::ToolCall(tool_call) => Some((
+ tool_call.id.clone(),
+ tool_call.tool_name.clone(),
+ std::mem::discriminant(&tool_call.status),
+ )),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ };
+ let live_tool_names = acp_thread.read_with(cx, |thread, _| tool_names(thread));
+ let [
+ (read_file_id, read_file_name, read_file_status),
+ (unavailable_id, unavailable_name, unavailable_status),
+ ] = live_tool_names.as_slice()
+ else {
+ panic!("native turns should produce two distinct ACP tool calls");
+ };
+ assert_ne!(read_file_id, unavailable_id);
+ assert_eq!(read_file_name.as_deref(), Some("read_file"));
+ assert_eq!(
+ *read_file_status,
+ std::mem::discriminant(&acp_thread::ToolCallStatus::Completed)
+ );
+ assert_eq!(unavailable_name.as_deref(), Some("unavailable_tool"));
+ assert_eq!(
+ *unavailable_status,
+ std::mem::discriminant(&acp_thread::ToolCallStatus::Failed)
+ );
+
+ drop(thread);
+ drop(acp_thread);
+ release_dropped_entities(cx);
+ agent.read_with(cx, |agent, _| {
+ assert!(!agent.sessions.contains_key(&session_id));
+ });
+
+ let restored = cx
+ .update(|cx| {
+ connection.clone().load_session(
+ session_id,
+ project,
+ PathList::new(&[Path::new("/a")]),
+ None,
+ cx,
+ )
+ })
+ .await
+ .expect("native tool session should reload");
+ cx.run_until_parked();
+ assert_eq!(
+ restored.read_with(cx, |thread, _| tool_names(thread)),
+ live_tool_names
+ );
+ }
+
#[gpui::test]
async fn test_threads_flushed_to_database_on_app_quit(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index ceb35fa6496..b5590f9297d 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -4341,8 +4341,8 @@ async fn test_tool_updates_to_completion(cx: &mut TestAppContext) {
assert_eq!(
tool_call,
acp::ToolCall::new(tool_call_id.clone(), "Echo")
+ .name("echo")
.raw_input(json!({}))
- .meta(acp::Meta::from_iter([("tool_name".into(), "echo".into())]))
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs
index 2d4742f8ab6..630c9c85df1 100644
--- a/crates/agent/src/thread.rs
+++ b/crates/agent/src/thread.rs
@@ -1640,6 +1640,7 @@ impl Thread {
.0
.unbounded_send(Ok(ThreadEvent::ToolCall(
acp::ToolCall::new(tool_call_id.clone(), tool_use.name.to_string())
+ .name(tool_use.name.to_string())
.status(status)
.raw_input(tool_use.input.to_display_json()),
)))
@@ -5323,9 +5324,9 @@ impl ThreadEventStream {
input: serde_json::Value,
) -> acp::ToolCall {
acp::ToolCall::new(id.clone(), title)
+ .name(tool_name)
.kind(kind)
.raw_input(input)
- .meta(acp_thread::meta_with_tool_name(tool_name))
}
fn update_tool_call_fields(
@@ -8596,35 +8597,50 @@ mod tests {
})
});
+ let registered_tool_call_id = scoped_tool_call_id(0, &registered_tool_use_id).to_string();
+ let missing_tool_call_id = scoped_tool_call_id(0, &missing_tool_use_id).to_string();
+ let mut tool_names_by_id = HashMap::default();
let mut tool_use_ids_with_image_content = HashSet::default();
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
- if let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) =
- event
- && let Some(content) = &update.fields.content
- && content.iter().any(|content| {
- matches!(
- content,
- acp::ToolCallContent::Content(acp::Content {
- content: acp::ContentBlock::Image(_),
- ..
+ match event {
+ ThreadEvent::ToolCall(tool_call) => {
+ tool_names_by_id.insert(tool_call.tool_call_id.to_string(), tool_call.name);
+ }
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
+ if update.fields.content.as_ref().is_some_and(|content| {
+ content.iter().any(|content| {
+ matches!(
+ content,
+ acp::ToolCallContent::Content(acp::Content {
+ content: acp::ContentBlock::Image(_),
+ ..
+ })
+ )
})
- )
- })
- {
- tool_use_ids_with_image_content.insert(update.tool_call_id.to_string());
+ }) =>
+ {
+ tool_use_ids_with_image_content.insert(update.tool_call_id.to_string());
+ }
+ _ => {}
}
}
// Both tool uses live in the message pushed above, at index 0 (see
// `scoped_tool_call_id`).
- assert!(
- tool_use_ids_with_image_content
- .contains(&scoped_tool_call_id(0, &registered_tool_use_id).to_string())
+ assert!(tool_use_ids_with_image_content.contains(&registered_tool_call_id));
+ assert!(tool_use_ids_with_image_content.contains(&missing_tool_call_id));
+ assert_eq!(
+ tool_names_by_id
+ .get(&registered_tool_call_id)
+ .and_then(Option::as_deref),
+ Some(ReplayImageTool::NAME)
);
- assert!(
- tool_use_ids_with_image_content
- .contains(&scoped_tool_call_id(0, &missing_tool_use_id).to_string())
+ assert_eq!(
+ tool_names_by_id
+ .get(&missing_tool_call_id)
+ .and_then(Option::as_deref),
+ Some("missing_image_tool")
);
}
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index c72b01c3874..7d83869d851 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -6965,9 +6965,9 @@ pub(crate) mod tests {
// parent's action log through the linked-log mechanism.
connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
acp::ToolCall::new("spawn1", "Subagent task")
+ .name("spawn_agent")
.kind(acp::ToolKind::Other)
- .status(acp::ToolCallStatus::Completed)
- .meta(acp_thread::meta_with_tool_name("spawn_agent")),
+ .status(acp::ToolCallStatus::Completed),
)]);
thread