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.

Remove v1 coupling from ACP logs and application fixtures (#65560)

Ben Brandt72e6f413aa61
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 0d4c316fa89..e497fba2d1d 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -7961,6 +7961,91 @@ mod tests {
});
}
+ #[gpui::test]
+ async fn test_stub_prompt_action_preserves_current_values_and_propagates_errors(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let connection = Rc::new(StubAgentConnection::new());
+ let thread = cx
+ .update(|cx| {
+ connection.clone().new_session(
+ project,
+ PathList::new(&[Path::new(path!("/test"))]),
+ cx,
+ )
+ })
+ .await
+ .expect("stub session");
+ let source = json!({
+ "messageId": "current-response",
+ "content": [{"type": "_future", "payload": {"retain": [null, 7]},
+ "_meta": {"scope": "content"}}],
+ "_meta": {"scope": "message"}
+ });
+ let message: acp_v2::AgentMessage =
+ serde_json::from_value(source.clone()).expect("current message");
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("overridden legacy response".into()),
+ )]);
+ connection
+ .set_next_prompt_action(move |thread, cx| thread.upsert_assistant_message(message, cx));
+ thread
+ .update(cx, |thread, cx| thread.send_raw("question", cx))
+ .await
+ .expect("application action completes");
+ thread.read_with(cx, |thread, _| {
+ let Some(AgentThreadEntry::AssistantMessage(message)) = thread.entries().last() else {
+ panic!("current assistant message");
+ };
+ let [
+ AssistantMessageChunk::Message {
+ identity,
+ meta,
+ block,
+ },
+ ] = message.chunks.as_slice()
+ else {
+ panic!("one current message chunk");
+ };
+ assert_eq!(identity, &MessageIdentity::Keyed("current-response".into()));
+ assert_eq!(
+ serde_json::to_value(block.source_blocks()).expect("source"),
+ source["content"]
+ );
+ assert_eq!(
+ serde_json::to_value(meta).expect("message metadata"),
+ source["_meta"]
+ );
+ assert_eq!(thread.status(), ThreadStatus::Idle);
+ });
+
+ connection.set_next_prompt_action(|_, _| anyhow::bail!("fixture update failed"));
+ let error = thread
+ .update(cx, |thread, cx| thread.send_raw("failure", cx))
+ .await
+ .expect_err("application action errors propagate");
+ assert!(error.to_string().contains("fixture update failed"));
+
+ connection.set_next_prompt_action(|_, _| anyhow::bail!("overridden application action"));
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("legacy compatibility response".into()),
+ )]);
+ thread
+ .update(cx, |thread, cx| thread.send_raw("legacy", cx))
+ .await
+ .expect("legacy setter replaces application action");
+ thread.read_with(cx, |thread, cx| {
+ assert!(
+ thread
+ .to_markdown(cx)
+ .contains("legacy compatibility response")
+ );
+ });
+ }
+
#[test]
fn test_legacy_plan_entry_conversion_preserves_fields() {
for priority in [
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index a7c104a168c..5264ce454c5 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -912,7 +912,7 @@ mod test_support {
pub struct StubAgentConnection {
sessions: Arc<Mutex<HashMap<acp_v2::SessionId, Session>>>,
permission_requests: HashMap<acp_v2::ToolCallId, PermissionOptions>,
- next_prompt_updates: Arc<Mutex<Vec<acp_v1::SessionUpdate>>>,
+ next_prompt_updates: Arc<Mutex<Vec<StubPromptUpdate>>>,
next_prompt_response: Arc<Mutex<Option<oneshot::Receiver<Result<acp_v1::PromptResponse>>>>>,
next_receipt_response:
Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,
@@ -930,6 +930,13 @@ mod test_support {
prompt_capabilities_rx: watch::Receiver<acp_v2::PromptCapabilities>,
}
+ enum StubPromptUpdate {
+ Legacy(Box<acp_v1::SessionUpdate>),
+ Application(
+ Box<dyn FnOnce(&mut AcpThread, &mut gpui::Context<AcpThread>) -> Result<()> + Send>,
+ ),
+ }
+
struct Session {
thread: WeakEntity<AcpThread>,
response_tx: Option<oneshot::Sender<acp_v1::StopReason>>,
@@ -970,7 +977,20 @@ mod test_support {
}
pub fn set_next_prompt_updates(&self, updates: Vec<acp_v1::SessionUpdate>) {
- *self.next_prompt_updates.lock() = updates;
+ *self.next_prompt_updates.lock() = updates
+ .into_iter()
+ .map(|update| StubPromptUpdate::Legacy(Box::new(update)))
+ .collect();
+ }
+
+ pub fn set_next_prompt_action(
+ &self,
+ update: impl FnOnce(&mut AcpThread, &mut gpui::Context<AcpThread>) -> Result<()>
+ + Send
+ + 'static,
+ ) {
+ *self.next_prompt_updates.lock() =
+ vec![StubPromptUpdate::Application(Box::new(update))];
}
pub fn defer_next_prompt_response(
@@ -1227,9 +1247,8 @@ mod test_support {
} else {
for update in self.next_prompt_updates.lock().drain(..) {
let thread = thread.clone();
- let update = update.clone();
- let permission_request = if let acp_v1::SessionUpdate::ToolCall(tool_call) =
- &update
+ let permission_request = if let StubPromptUpdate::Legacy(update) = &update
+ && let acp_v1::SessionUpdate::ToolCall(tool_call) = update.as_ref()
&& let Some(options) = self
.permission_requests
.get(&acp_v2::ToolCallId::new(tool_call.tool_call_id.0.clone()))
@@ -1251,9 +1270,12 @@ mod test_support {
})??
.await;
}
- thread.update(cx, |thread, cx| {
- thread.handle_session_update(update.clone(), cx).unwrap();
- })?;
+ thread.update(cx, |thread, cx| match update {
+ StubPromptUpdate::Legacy(update) => thread
+ .handle_session_update(*update, cx)
+ .map_err(anyhow::Error::from),
+ StubPromptUpdate::Application(update) => update(thread, cx),
+ })??;
anyhow::Ok(())
});
tasks.push(task);
diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs
index 5675dfa2b55..1440cfbcc3e 100644
--- a/crates/acp_tools/src/acp_tools.rs
+++ b/crates/acp_tools/src/acp_tools.rs
@@ -1,6 +1,6 @@
use std::{collections::HashSet, fmt::Display, rc::Rc, sync::Arc};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::{Error, schema::v2::RequestId};
use agent_servers::{AcpDebugMessage, AcpDebugMessageContent, AcpDebugMessageDirection};
use agent_ui::agent_connection_store::AgentConnectionStatus;
use agent_ui::{Agent, AgentConnectionStore, AgentPanel};
@@ -65,8 +65,8 @@ struct WatchedConnection {
connection: Rc<agent_servers::AcpConnection>,
messages: Vec<WatchedConnectionMessage>,
list_state: ListState,
- incoming_request_methods: HashMap<acp::RequestId, Arc<str>>,
- outgoing_request_methods: HashMap<acp::RequestId, Arc<str>>,
+ incoming_request_methods: HashMap<RequestId, Arc<str>>,
+ outgoing_request_methods: HashMap<RequestId, Arc<str>>,
_task: Task<()>,
}
@@ -591,10 +591,10 @@ fn push_stream_message_for_connection(
struct WatchedConnectionMessage {
name: SharedString,
- request_id: Option<acp::RequestId>,
+ request_id: Option<RequestId>,
direction: AcpDebugMessageDirection,
message_type: MessageType,
- params: Result<Option<serde_json::Value>, acp::Error>,
+ params: Result<Option<serde_json::Value>, Error>,
collapsed_params_md: Option<Entity<Markdown>>,
expanded_params_md: Option<Entity<Markdown>>,
}
diff --git a/crates/agent_servers/src/acp/debug_log.rs b/crates/agent_servers/src/acp/debug_log.rs
index 71e690d2c2f..bdf16320be3 100644
--- a/crates/agent_servers/src/acp/debug_log.rs
+++ b/crates/agent_servers/src/acp/debug_log.rs
@@ -1,4 +1,4 @@
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::{Error, schema::v2::RequestId};
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
@@ -17,13 +17,13 @@ pub enum AcpDebugMessageDirection {
#[derive(Clone)]
pub enum AcpDebugMessageContent {
Request {
- id: acp::RequestId,
+ id: RequestId,
method: Arc<str>,
params: Option<serde_json::Value>,
},
Response {
- id: acp::RequestId,
- result: Result<Option<serde_json::Value>, acp::Error>,
+ id: RequestId,
+ result: Result<Option<serde_json::Value>, Error>,
},
Notification {
method: Arc<str>,
@@ -69,7 +69,7 @@ impl AcpDebugMessage {
let parsed_id = object
.get("id")
- .map(|raw| serde_json::from_value::<acp::RequestId>(raw.clone()));
+ .map(|raw| serde_json::from_value::<RequestId>(raw.clone()));
let message = if let Some(method) = object.get("method").and_then(|method| method.as_str())
{
@@ -99,9 +99,9 @@ impl AcpDebugMessage {
if let Some(error) = object.get("error") {
let acp_error =
- serde_json::from_value::<acp::Error>(error.clone()).unwrap_or_else(|err| {
+ serde_json::from_value::<Error>(error.clone()).unwrap_or_else(|err| {
log::warn!("Failed to deserialize ACP error: {err}");
- acp::Error::internal_error().data(error.to_string())
+ Error::internal_error().data(error.to_string())
});
AcpDebugMessageContent::Response {
@@ -206,6 +206,57 @@ impl AcpDebugLog {
mod tests {
use super::*;
+ #[test]
+ fn preserves_shared_request_ids_payloads_and_runtime_error_data() {
+ let id = RequestId::Str("opaque/request:雪".into());
+ let params = serde_json::json!({
+ "sessionId": "session",
+ "update": {"sessionUpdate": "_future", "payload": [null, 7]}
+ });
+ let request = serde_json::json!({
+ "jsonrpc": "2.0", "id": id, "method": "session/update", "params": params
+ });
+ let requests =
+ AcpDebugMessage::parse_line(AcpDebugMessageDirection::Outgoing, &request.to_string());
+ let [request] = requests.as_slice() else {
+ panic!("one request");
+ };
+ let AcpDebugMessageContent::Request {
+ id: request_id,
+ method,
+ params: actual_params,
+ } = &request.message
+ else {
+ panic!("request message");
+ };
+ assert_eq!(request_id, &id);
+ assert_eq!(method.as_ref(), "session/update");
+ assert_eq!(actual_params, &Some(params));
+
+ let error = serde_json::json!({
+ "code": -32999, "message": "Unknown runtime error",
+ "data": {"retain": [null, false, {"nested": "雪"}]}
+ });
+ let response = serde_json::json!({"jsonrpc": "2.0", "id": id, "error": error});
+ let responses =
+ AcpDebugMessage::parse_line(AcpDebugMessageDirection::Incoming, &response.to_string());
+ let [response] = responses.as_slice() else {
+ panic!("one response");
+ };
+ let AcpDebugMessageContent::Response {
+ id: response_id,
+ result: Err(actual_error),
+ } = &response.message
+ else {
+ panic!("error response");
+ };
+ assert_eq!(response_id, &id);
+ assert_eq!(
+ serde_json::to_value(actual_error).expect("runtime error"),
+ error
+ );
+ }
+
#[test]
fn trailing_stderr_only_uses_final_stderr_block() {
let debug_log = AcpDebugLog::default();
@@ -307,7 +358,7 @@ mod tests {
Some(AcpDebugMessage {
direction: AcpDebugMessageDirection::Incoming,
message: AcpDebugMessageContent::Request { id, method, .. },
- }) if id == &acp::RequestId::Number(1) && method.as_ref() == "session/one"
+ }) if id == &RequestId::Number(1) && method.as_ref() == "session/one"
));
assert!(matches!(
messages.next(),
@@ -317,7 +368,7 @@ mod tests {
id,
result: Ok(Some(_)),
},
- }) if id == &acp::RequestId::Number(1)
+ }) if id == &RequestId::Number(1)
));
assert!(matches!(
messages.next(),
@@ -327,7 +378,7 @@ mod tests {
id,
result: Err(_),
},
- }) if id == &acp::RequestId::Null
+ }) if id == &RequestId::Null
));
assert!(messages.next().is_none());
}
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index 28c3cc2f4bf..1ffc8b6d1a9 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -850,7 +850,7 @@ mod tests {
}
#[gpui::test]
- async fn test_diff_sync(cx: &mut TestAppContext) {
+ async fn test_legacy_diff_sync(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
@@ -993,14 +993,14 @@ mod tests {
)
.unwrap()
});
- cx.update(|_, cx| {
- connection.send_update(
- session_id,
- acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
- acp_v1::ContentBlock::Text(acp_v1::TextContent::new("hello")),
- )),
- cx,
- );
+ thread.update(cx, |thread, cx| {
+ thread
+ .append_message_chunk(
+ acp_thread::MessageKind::Assistant,
+ acp_v2::ContentChunk::new("hello".into(), "after-elicitation"),
+ cx,
+ )
+ .expect("append current message after elicitation");
});
let view_state = cx.new(|_cx| {
diff --git a/crates/agent_ui/src/test_support.rs b/crates/agent_ui/src/test_support.rs
index 6bc0de1e14d..c0238fca680 100644
--- a/crates/agent_ui/src/test_support.rs
+++ b/crates/agent_ui/src/test_support.rs
@@ -1,5 +1,5 @@
use acp_thread::{AgentConnection, StubAgentConnection};
-use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp};
+use agent_client_protocol::schema::v2 as acp;
use agent_servers::{AgentServer, AgentServerDelegate};
use gpui::{
App, AppContext as _, Context, Entity, EventEmitter, FocusHandle, Focusable, IntoElement,
@@ -67,9 +67,12 @@ where
impl StubAgentServer<StubAgentConnection> {
pub fn default_response() -> Self {
let conn = StubAgentConnection::new();
- conn.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
- acp_v1::ContentChunk::new("Default response".into()),
- )]);
+ conn.set_next_prompt_action(|thread, cx| {
+ thread.upsert_assistant_message(
+ acp::AgentMessage::new("default-response").content(vec!["Default response".into()]),
+ cx,
+ )
+ });
Self::new(conn)
}
}
diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs
index f97554ec7b0..78a373eb825 100644
--- a/crates/zed/src/visual_test_runner.rs
+++ b/crates/zed/src/visual_test_runner.rs
@@ -95,7 +95,7 @@ fn main() {
#[cfg(target_os = "macos")]
use {
acp_thread::{AgentConnection, StubAgentConnection},
- agent_client_protocol::schema::{v1 as acp, v2 as acp_v2},
+ agent_client_protocol::schema::v2 as acp_v2,
agent_servers::{AgentServer, AgentServerDelegate},
anyhow::{Context as _, Result},
assets::Assets,
@@ -2088,8 +2088,8 @@ fn run_agent_thread_view_test(
cx.run_until_parked();
// Collect the events from the tool execution
- let mut tool_content: Vec<acp::ToolCallContent> = Vec::new();
- let mut tool_locations: Vec<acp::ToolCallLocation> = Vec::new();
+ let mut tool_content: Vec<acp_v2::ToolCallContent> = Vec::new();
+ let mut tool_locations: Vec<acp_v2::ToolCallLocation> = Vec::new();
while let Ok(event) = event_receiver.try_recv() {
if let Ok(agent::ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update))) =
@@ -2102,18 +2102,11 @@ fn run_agent_thread_view_test(
"ReadFileTool produced non-content output in the image fixture"
);
};
- tool_content.push(acp::ToolCallContent::Content(
- acp::Content::new(acp_thread::content::to_v1(content.content)?)
- .meta(content.meta),
- ));
+ tool_content.push(acp_v2::ToolCallContent::Content(content));
}
}
if let Some(locations) = update.locations.take() {
- tool_locations.extend(locations.into_iter().map(|location| {
- acp::ToolCallLocation::new(location.path.into_inner())
- .line(location.line)
- .meta(location.meta)
- }));
+ tool_locations.extend(locations);
}
}
}
@@ -2124,16 +2117,14 @@ fn run_agent_thread_view_test(
// Create stub connection with the real tool output
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(
- "read_file",
- format!("Read file `{}/test-image.png`", worktree_name),
- )
- .kind(acp::ToolKind::Read)
- .status(acp::ToolCallStatus::Completed)
+ let tool_call = acp_v2::ToolCallUpdate::new("read_file")
+ .title(format!("Read file `{}/test-image.png`", worktree_name))
+ .kind(acp_v2::ToolKind::Read)
+ .status(acp_v2::ToolCallStatus::Completed)
.locations(tool_locations)
- .content(tool_content),
- )]);
+ .content(tool_content);
+ connection
+ .set_next_prompt_action(move |thread, cx| thread.upsert_local_tool_call(tool_call, cx));
let stub_agent: Rc<dyn AgentServer> = Rc::new(StubAgentServer::new(connection));