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.

agent_servers: Decode v2 terminal notifications (#64985)

Ben Brandte8c6c67fad69
diff --git a/Cargo.lock b/Cargo.lock
index 20384a30fbd..fd3702c6870 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -384,6 +384,7 @@ dependencies = [
"agent-client-protocol",
"anyhow",
"async-channel 2.5.0",
+ "base64 0.22.1",
"chrono",
"client",
"collections",
diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml
index 58bf698b0f2..9ce7a7e5702 100644
--- a/crates/agent_servers/Cargo.toml
+++ b/crates/agent_servers/Cargo.toml
@@ -30,6 +30,7 @@ action_log.workspace = true
async-channel.workspace = true
agent-client-protocol.workspace = true
anyhow.workspace = true
+base64.workspace = true
chrono.workspace = true
client.workspace = true
collections.workspace = true
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index 859cf7bbd32..9968cff0e42 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -1,8 +1,10 @@
mod debug_log;
+mod terminal_updates;
mod transport;
use debug_log::AcpDebugLog;
pub use debug_log::{AcpDebugMessage, AcpDebugMessageContent, AcpDebugMessageDirection};
+pub use terminal_updates::{DecodedTerminalNotification, DecodedTerminalUpdate};
use acp_thread::{
AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,
@@ -12,9 +14,11 @@ use action_log::ActionLog;
use agent_client_protocol::schema::{
ProtocolVersion,
v1::{self as acp, ErrorCode},
+ v2 as acp_v2,
};
use agent_client_protocol::{
- Agent, Builder, Client, ConnectionTo, HandleDispatchFrom, JsonRpcResponse, Lines, Responder,
+ Agent, Builder, Client, ConnectionTo, HandleDispatchFrom, Handled, JsonRpcMessage,
+ JsonRpcResponse, Lines, Responder, UntypedMessage, V2Builder, V2ConnectionTo,
};
use anyhow::anyhow;
use async_channel;
@@ -629,6 +633,44 @@ fn client_builder(
)
}
+/// Builds a v2 terminal-notification handler without selecting it for application connections.
+/// Other session updates remain unclaimed so later inbound handlers can process them.
+pub fn v2_terminal_client_builder(
+ mut dispatch: impl FnMut(DecodedTerminalNotification) -> Result<(), agent_client_protocol::Error>
+ + Send
+ + 'static,
+) -> V2Builder<Client, impl HandleDispatchFrom<Agent>> {
+ Client.v2().on_receive_notification(
+ async move |message: UntypedMessage, connection: V2ConnectionTo<Agent>| {
+ let kind = message
+ .params()
+ .get("update")
+ .and_then(|update| update.get("sessionUpdate"))
+ .and_then(serde_json::Value::as_str);
+ if !acp_v2::UpdateSessionNotification::matches_method(message.method())
+ || !matches!(kind, Some("terminal_update" | "terminal_output_chunk"))
+ {
+ return Ok(Handled::No {
+ message: (message, connection),
+ retry: false,
+ });
+ }
+ let notification = terminal_updates::parse_terminal_notification(&message)?;
+ let decoded = terminal_updates::decode_terminal_notification(notification)
+ .map_err(|error| {
+ agent_client_protocol::Error::invalid_params().data(format!("{error:#}"))
+ })?
+ .ok_or_else(|| {
+ agent_client_protocol::Error::internal_error()
+ .data("Terminal notification was not decoded")
+ })?;
+ dispatch(decoded)?;
+ Ok(Handled::Yes)
+ },
+ agent_client_protocol::on_receive_notification!(),
+ )
+}
+
fn client_capabilities_for_agent(
agent_id: &AgentId,
beta_features_enabled: bool,
@@ -2582,6 +2624,570 @@ mod tests {
use feature_flags::{AcpBetaFeatureFlag, FeatureFlag as _};
use settings::Settings as _;
+ #[derive(Debug, PartialEq)]
+ struct V2TerminalReceive {
+ envelope_meta: Option<acp_v2::Meta>,
+ chunk_meta: Option<acp_v2::Meta>,
+ bytes: Option<Vec<u8>>,
+ }
+
+ struct V2TerminalHarness {
+ connection: Rc<AcpConnection>,
+ thread: Entity<AcpThread>,
+ agent: V2ConnectionTo<Client>,
+ received: Arc<Mutex<Vec<V2TerminalReceive>>>,
+ fallback: Arc<Mutex<Vec<agent_client_protocol::UntypedMessage>>>,
+ acknowledgment: Arc<Mutex<Option<futures::channel::oneshot::Sender<()>>>>,
+ _client_task: Task<Result<(), agent_client_protocol::Error>>,
+ _agent_task: Task<Result<(), agent_client_protocol::Error>>,
+ _legacy_agent_task: Task<Result<()>>,
+ }
+
+ fn apply_v2_terminal_for_test(
+ notification: DecodedTerminalNotification,
+ cx: &mut AsyncApp,
+ context: &ClientContext,
+ ) {
+ let session_id = acp::SessionId::new(notification.session_id.to_string());
+ session_thread(context, &session_id)
+ .expect("registered terminal session")
+ .update(cx, |thread, cx| notification.apply(thread, cx))
+ .expect("live terminal session")
+ .expect("apply decoded terminal update");
+ }
+
+ fn v2_terminal_meta(scope: &str) -> acp_v2::Meta {
+ acp_v2::Meta::from_iter([("scope".to_owned(), serde_json::json!(scope))])
+ }
+
+ impl V2TerminalHarness {
+ async fn new(cx: &mut gpui::TestAppContext) -> Self {
+ let (connection, project, _, _, _, _, legacy_agent_task) =
+ connect_fake_agent(None, cx).await;
+ let thread = cx
+ .update(|cx| {
+ connection.clone().load_session(
+ acp::SessionId::new("v2-terminal-session"),
+ project,
+ PathList::new(&[std::path::Path::new("/a")]),
+ None,
+ cx,
+ )
+ })
+ .await
+ .expect("load the existing model session");
+
+ let received = Arc::new(Mutex::new(Vec::new()));
+ let fallback = Arc::new(Mutex::new(Vec::new()));
+ let acknowledgment =
+ Arc::new(Mutex::new(None::<futures::channel::oneshot::Sender<()>>));
+ let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();
+ let (client_sender, client_receiver) = futures::channel::oneshot::channel();
+ let client_builder = v2_terminal_client_builder({
+ let dispatch_sender = connection.dispatch_tx.clone();
+ let received = received.clone();
+ let acknowledgment = acknowledgment.clone();
+ move |notification| {
+ let is_barrier = notification
+ .meta
+ .as_ref()
+ .and_then(|meta| meta.get("terminalTestBarrier"))
+ == Some(&serde_json::json!(true));
+ if !is_barrier {
+ let (chunk_meta, bytes) = match &notification.update {
+ DecodedTerminalUpdate::Patch { .. } => (None, None),
+ DecodedTerminalUpdate::Output { data, meta, .. } => {
+ (meta.clone(), Some(data.clone()))
+ }
+ };
+ received
+ .lock()
+ .expect("receive mutex")
+ .push(V2TerminalReceive {
+ envelope_meta: notification.meta.clone(),
+ chunk_meta,
+ bytes,
+ });
+ }
+ enqueue_notification(
+ &dispatch_sender,
+ notification,
+ apply_v2_terminal_for_test,
+ );
+ if is_barrier {
+ acknowledgment
+ .lock()
+ .expect("acknowledgment mutex")
+ .take()
+ .expect("installed receive barrier")
+ .send(())
+ .expect("waiting receive barrier");
+ }
+ Ok(())
+ }
+ })
+ .on_receive_notification(
+ {
+ let fallback = fallback.clone();
+ async move |message: agent_client_protocol::UntypedMessage,
+ _connection: V2ConnectionTo<Agent>| {
+ fallback.lock().expect("fallback mutex").push(message);
+ Ok(())
+ }
+ },
+ agent_client_protocol::on_receive_notification!(),
+ );
+ let client_task = cx.background_spawn(client_builder.connect_with(
+ client_transport,
+ async move |client| {
+ assert!(client_sender.send(client).is_ok(), "receive v2 client");
+ futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
+ },
+ ));
+ let (agent_sender, agent_receiver) = futures::channel::oneshot::channel();
+ let agent_task = cx.background_spawn(
+ Agent
+ .v2()
+ .on_receive_request(
+ async move |request: acp_v2::InitializeRequest, responder, _connection| {
+ assert_eq!(request.protocol_version, ProtocolVersion::V2);
+ responder.respond(acp_v2::InitializeResponse::new(
+ ProtocolVersion::V2,
+ acp_v2::Implementation::new("terminal-test-agent", "1.0.0"),
+ ))
+ },
+ agent_client_protocol::on_receive_request!(),
+ )
+ .connect_with(agent_transport, async move |agent| {
+ assert!(agent_sender.send(agent).is_ok(), "receive v2 agent");
+ futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
+ }),
+ );
+ let client = client_receiver.await.expect("v2 client handle");
+ let agent = agent_receiver.await.expect("v2 agent handle");
+ let response = client
+ .send_request(acp_v2::InitializeRequest::new(
+ ProtocolVersion::V2,
+ acp_v2::Implementation::new("terminal-test-client", "1.0.0"),
+ ))
+ .block_task()
+ .await
+ .expect("initialize the real SDK v2 channel");
+ assert_eq!(response.protocol_version, ProtocolVersion::V2);
+
+ Self {
+ connection,
+ thread,
+ agent,
+ received,
+ fallback,
+ acknowledgment,
+ _client_task: client_task,
+ _agent_task: agent_task,
+ _legacy_agent_task: legacy_agent_task,
+ }
+ }
+
+ fn send(&self, update: serde_json::Value, envelope_meta: Option<acp_v2::Meta>) {
+ let update: acp_v2::SessionUpdate =
+ serde_json::from_value(update).expect("valid SDK session update fixture");
+ self.agent
+ .send_notification(
+ acp_v2::UpdateSessionNotification::new("v2-terminal-session", update)
+ .meta(envelope_meta),
+ )
+ .expect("send SDK v2 terminal notification");
+ }
+
+ async fn drain(&self, cx: &mut gpui::TestAppContext) {
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ assert!(
+ self.acknowledgment
+ .lock()
+ .expect("acknowledgment mutex")
+ .replace(sender)
+ .is_none()
+ );
+ self.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "terminal-1",
+ "data": ""
+ }),
+ Some(acp_v2::Meta::from_iter([(
+ "terminalTestBarrier".to_owned(),
+ serde_json::json!(true),
+ )])),
+ );
+ // Notification errors have no reply. This valid chunk acknowledges SDK
+ // dispatch before the foreground barrier acknowledges model application.
+ let delivered = async {
+ receiver.await.expect("SDK receive barrier");
+ drain_foreground_queue(&self.connection.dispatch_tx)
+ .await
+ .expect("foreground application barrier");
+ };
+ let timeout = cx
+ .background_executor
+ .timer(std::time::Duration::from_secs(5));
+ futures::pin_mut!(delivered, timeout);
+ if let futures::future::Either::Right(_) =
+ futures::future::select(delivered, timeout).await
+ {
+ panic!("timed out receiving and applying v2 terminal notifications");
+ }
+ }
+
+ fn terminal(&self, id: &str, cx: &gpui::TestAppContext) -> Entity<acp_thread::Terminal> {
+ self.thread.read_with(cx, |thread, _| {
+ thread
+ .terminal(acp::TerminalId::new(id))
+ .expect("display terminal")
+ })
+ }
+ }
+
+ #[gpui::test]
+ async fn v2_terminal_sdk_snapshots_chunks_and_metadata(cx: &mut gpui::TestAppContext) {
+ let harness = V2TerminalHarness::new(cx).await;
+ harness
+ .thread
+ .update(cx, |thread, cx| {
+ thread.upsert_tool_call_patch(
+ acp_v2::ToolCallUpdate::new("terminal-tool").content(vec![
+ acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new("terminal-1")),
+ ]),
+ cx,
+ )
+ })
+ .expect("tool reference creates terminal before wire update");
+ let terminal = harness.terminal("terminal-1", cx);
+ let renderer = terminal.read_with(cx, |terminal, _| terminal.inner().clone());
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_update", "terminalId": "terminal-1",
+ "command": "wire command", "cwd": "/tmp",
+ "output": {"data": "b2xk", "_meta": {"scope": "snapshot"}},
+ "exitStatus": {"exitCode": 7, "signal": "SIGTERM", "_meta": {"scope": "exit"}},
+ "_meta": {"scope": "terminal"}
+ }),
+ Some(v2_terminal_meta("snapshot-envelope")),
+ );
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_output_chunk", "terminalId": "terminal-1",
+ "data": "IQ==", "_meta": {"scope": "chunk"}
+ }),
+ Some(v2_terminal_meta("chunk-envelope")),
+ );
+ harness.drain(cx).await;
+ let ended_at = terminal.read_with(cx, |terminal, cx| {
+ assert_eq!(terminal.inner(), &renderer);
+ assert_eq!(
+ terminal.command().read(cx).source(),
+ "```\nwire command\n```"
+ );
+ assert_eq!(
+ terminal.working_dir().as_deref(),
+ Some(std::path::Path::new("/tmp"))
+ );
+ let display = terminal.display_state().expect("display state");
+ assert_eq!(display.meta, Some(v2_terminal_meta("terminal")));
+ assert_eq!(display.output_meta, Some(v2_terminal_meta("snapshot")));
+ let output = terminal.output().expect("exited snapshot");
+ assert_eq!(output.exit_status.exit_code, Some(7));
+ assert_eq!(output.exit_status.signal.as_deref(), Some("SIGTERM"));
+ assert_eq!(output.exit_status.meta, Some(v2_terminal_meta("exit")));
+ assert_eq!(output.content.trim_end(), "old!");
+ assert_eq!(renderer.read(cx).get_content().trim_end(), "old!");
+ output.ended_at
+ });
+ assert_eq!(
+ *harness.received.lock().expect("receive mutex"),
+ vec![
+ V2TerminalReceive {
+ envelope_meta: Some(v2_terminal_meta("snapshot-envelope")),
+ chunk_meta: None,
+ bytes: None,
+ },
+ V2TerminalReceive {
+ envelope_meta: Some(v2_terminal_meta("chunk-envelope")),
+ chunk_meta: Some(v2_terminal_meta("chunk")),
+ bytes: Some(b"!".to_vec()),
+ },
+ ]
+ );
+
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_update", "terminalId": "terminal-1",
+ "output": {"data": "bmV3DQo=", "_meta": {"scope": "replacement"}}
+ }),
+ None,
+ );
+ for data in ["G1s=", "MzFtwg==", "og==", "Clo="] {
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_output_chunk", "terminalId": "terminal-1",
+ "data": data, "_meta": {}
+ }),
+ Some(acp_v2::Meta::new()),
+ );
+ }
+ harness.drain(cx).await;
+ assert_eq!(harness.terminal("terminal-1", cx), terminal);
+ terminal.read_with(cx, |terminal, cx| {
+ assert_eq!(terminal.inner(), &renderer);
+ assert_eq!(renderer.read(cx).get_content().trim_end(), "new\n¢\n Z");
+ let display = terminal.display_state().expect("display state");
+ assert_eq!(display.command(), Some("wire command"));
+ assert_eq!(display.meta, Some(v2_terminal_meta("terminal")));
+ assert_eq!(display.output_meta, Some(v2_terminal_meta("replacement")));
+ let output = terminal
+ .output()
+ .expect("omitted exit preserves completion");
+ assert_eq!(output.ended_at, ended_at);
+ assert_eq!(output.exit_status.meta, Some(v2_terminal_meta("exit")));
+ assert_eq!(output.content.trim_end(), "new\n¢\n Z");
+ });
+ {
+ let received = harness.received.lock().expect("receive mutex");
+ assert_eq!(
+ received
+ .iter()
+ .skip(3)
+ .map(|event| event.bytes.clone())
+ .collect::<Vec<_>>(),
+ vec![
+ Some(b"\x1b[".to_vec()),
+ Some(b"31m\xc2".to_vec()),
+ Some(vec![0xa2]),
+ Some(b"\nZ".to_vec()),
+ ]
+ );
+ assert!(received.iter().skip(3).all(|event| {
+ event.envelope_meta == Some(acp_v2::Meta::new())
+ && event.chunk_meta == Some(acp_v2::Meta::new())
+ }));
+ }
+
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_update", "terminalId": "terminal-1",
+ "exitStatus": {}
+ }),
+ None,
+ );
+ harness.drain(cx).await;
+ terminal.read_with(cx, |terminal, _| {
+ let output = terminal
+ .output()
+ .expect("empty exit object still means exited");
+ assert_eq!(output.exit_status, acp_v2::TerminalExitStatus::new());
+ assert_eq!(output.ended_at, ended_at);
+ });
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_update", "terminalId": "terminal-1",
+ "command": null, "cwd": null, "output": {"data": "", "_meta": {}},
+ "exitStatus": null, "_meta": null
+ }),
+ None,
+ );
+ harness.drain(cx).await;
+ terminal.read_with(cx, |terminal, cx| {
+ let display = terminal.display_state().expect("display state");
+ assert_eq!(display.command(), None);
+ assert_eq!(display.meta, None);
+ assert_eq!(display.output_meta, Some(acp_v2::Meta::new()));
+ assert_eq!(terminal.working_dir(), &None);
+ assert!(terminal.output().is_none());
+ assert!(renderer.read(cx).get_content().trim().is_empty());
+ assert_eq!(terminal.inner(), &renderer);
+ });
+ assert_eq!(harness.terminal("terminal-1", cx), terminal);
+ harness.thread.read_with(cx, |thread, _| {
+ let (_, tool) = thread
+ .tool_call(&acp::ToolCallId::new("terminal-tool"))
+ .expect("tool");
+ assert_eq!(tool.terminals().next(), Some(&terminal));
+ });
+ assert!(harness.fallback.lock().expect("fallback mutex").is_empty());
+ }
+
+ #[gpui::test]
+ async fn v2_terminal_sdk_invalid_base64_is_atomic(cx: &mut gpui::TestAppContext) {
+ let harness = V2TerminalHarness::new(cx).await;
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_update", "terminalId": "terminal-1",
+ "command": "original", "cwd": "/tmp",
+ "output": {"data": "b2xk", "_meta": {"scope": "snapshot"}},
+ "exitStatus": {"exitCode": 7, "_meta": {"scope": "exit"}},
+ "_meta": {"scope": "terminal"}
+ }),
+ None,
+ );
+ harness.drain(cx).await;
+ let terminal = harness.terminal("terminal-1", cx);
+ let observe = |cx: &gpui::TestAppContext| {
+ terminal.read_with(cx, |terminal, cx| {
+ let display = terminal.display_state().expect("display state");
+ let output = terminal.output().expect("completed terminal");
+ (
+ display.command().map(str::to_owned),
+ terminal.working_dir().clone(),
+ display.meta.clone(),
+ display.output_meta.clone(),
+ output.exit_status.clone(),
+ output.ended_at,
+ output.content.clone(),
+ terminal.inner().read(cx).get_content(),
+ )
+ })
+ };
+ let before = observe(cx);
+ let received_before = harness.received.lock().expect("receive mutex").len();
+ for terminal_id in ["terminal-1", "unseen"] {
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_update", "terminalId": terminal_id,
+ "command": "must not apply", "cwd": "/changed",
+ "output": {"data": "not base64!", "_meta": {"scope": "bad snapshot"}},
+ "exitStatus": {"exitCode": 99, "_meta": {"scope": "bad exit"}},
+ "_meta": {"scope": "bad terminal"}
+ }),
+ Some(v2_terminal_meta("bad envelope")),
+ );
+ harness
+ .agent
+ .send_notification(
+ agent_client_protocol::UntypedMessage::new(
+ "session/update",
+ serde_json::json!({
+ "sessionId": "v2-terminal-session",
+ "_meta": {"scope": "malformed envelope"},
+ "update": {
+ "sessionUpdate": "terminal_update", "terminalId": terminal_id,
+ "command": "must not apply", "cwd": "/changed",
+ "output": {"data": 42},
+ "exitStatus": {"exitCode": 99, "_meta": {"scope": "bad exit"}},
+ "_meta": {"scope": "bad terminal"}
+ }
+ }),
+ )
+ .expect("malformed snapshot SDK fixture"),
+ )
+ .expect("send malformed snapshot through SDK");
+ // Together these strings form valid base64, but neither is a valid
+ // independently encoded chunk.
+ for data in ["b2", "s=", "not base64!"] {
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_output_chunk", "terminalId": terminal_id,
+ "data": data, "_meta": {"scope": "bad chunk"}
+ }),
+ Some(v2_terminal_meta("bad chunk envelope")),
+ );
+ }
+ }
+ harness.drain(cx).await;
+ assert_eq!(observe(cx), before);
+ assert_eq!(harness.terminal("terminal-1", cx), terminal);
+ harness.thread.read_with(cx, |thread, _| {
+ assert!(thread.terminal(acp::TerminalId::new("unseen")).is_err());
+ });
+ assert_eq!(
+ harness.received.lock().expect("receive mutex").len(),
+ received_before
+ );
+ assert!(harness.fallback.lock().expect("fallback mutex").is_empty());
+ harness.send(
+ serde_json::json!({
+ "sessionUpdate": "terminal_output_chunk", "terminalId": "terminal-1",
+ "data": "IQ=="
+ }),
+ None,
+ );
+ harness.drain(cx).await;
+ terminal.read_with(cx, |terminal, cx| {
+ assert_eq!(terminal.inner().read(cx).get_content().trim_end(), "old!");
+ assert_eq!(
+ terminal
+ .output()
+ .expect("still completed")
+ .content
+ .trim_end(),
+ "old!"
+ );
+ assert_eq!(
+ terminal.display_state().expect("display").meta,
+ Some(v2_terminal_meta("terminal"))
+ );
+ });
+ assert_eq!(
+ harness.received.lock().expect("receive mutex").len(),
+ received_before + 1
+ );
+ }
+
+ #[gpui::test]
+ async fn v2_terminal_sdk_falls_through_without_losing_unknown_fields(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ let harness = V2TerminalHarness::new(cx).await;
+ let params = [
+ serde_json::json!({
+ "sessionId": "v2-terminal-session", "_meta": {"scope": "known envelope"},
+ "futureOuter": {"preserve": [1, null, true]},
+ "update": {
+ "sessionUpdate": "agent_message_chunk", "messageId": "message-1",
+ "content": {"type": "text", "text": "not a terminal", "futureContent": 42},
+ "_meta": {"scope": "known update"}, "futureKnownField": {"nested": "keep"}
+ }
+ }),
+ serde_json::json!({
+ "sessionId": "v2-terminal-session", "_meta": {"scope": "other envelope"},
+ "futureOuter": "keep",
+ "update": {
+ "sessionUpdate": "_future_terminal_neighbor",
+ "payload": {"bytes": ["not", "base64!"], "nested": {"unknown": null}},
+ "_meta": {"scope": "other update"}
+ }
+ }),
+ ];
+ let mut expected = params
+ .iter()
+ .map(|params| {
+ agent_client_protocol::UntypedMessage::new("session/update", params)
+ .expect("raw SDK notification")
+ })
+ .collect::<Vec<_>>();
+ for message in &expected {
+ harness
+ .agent
+ .send_notification(message.clone())
+ .expect("send unrelated SDK update");
+ }
+ let unrelated_method = agent_client_protocol::UntypedMessage::new(
+ "_other/notification",
+ serde_json::json!({
+ "update": {"sessionUpdate": "terminal_update", "output": {"data": "invalid!"}},
+ "_meta": {"scope": "unrelated method"}
+ }),
+ )
+ .expect("unrelated SDK notification");
+ harness
+ .agent
+ .send_notification(unrelated_method.clone())
+ .expect("send unrelated method");
+ expected.push(unrelated_method);
+ harness.drain(cx).await;
+ let fallback = harness.fallback.lock().expect("fallback mutex");
+ assert_eq!(*fallback, expected);
+ assert!(harness.received.lock().expect("receive mutex").is_empty());
+ }
+
fn init_feature_flags_test(cx: &mut gpui::TestAppContext) {
cx.update(|cx| {
let mut settings_store = SettingsStore::test(cx);
diff --git a/crates/agent_servers/src/acp/terminal_updates.rs b/crates/agent_servers/src/acp/terminal_updates.rs
new file mode 100644
index 00000000000..126f5ba8a29
--- /dev/null
+++ b/crates/agent_servers/src/acp/terminal_updates.rs
@@ -0,0 +1,446 @@
+use acp_thread::{AcpThread, DisplayTerminalOutput, DisplayTerminalPatch};
+use agent_client_protocol::schema::{MaybeUndefined, v2 as acp_v2};
+use agent_client_protocol::{JsonRpcMessage, UntypedMessage};
+use anyhow::{Context as _, Result};
+use base64::{Engine as _, engine::general_purpose::STANDARD};
+use gpui::Context;
+
+#[derive(Debug)]
+pub struct DecodedTerminalNotification {
+ pub session_id: acp_v2::SessionId,
+ pub meta: Option<acp_v2::Meta>,
+ pub update: DecodedTerminalUpdate,
+}
+
+#[derive(Debug)]
+pub enum DecodedTerminalUpdate {
+ Patch {
+ terminal_id: acp_v2::TerminalId,
+ patch: DisplayTerminalPatch,
+ },
+ Output {
+ terminal_id: acp_v2::TerminalId,
+ data: Vec<u8>,
+ meta: Option<acp_v2::Meta>,
+ },
+}
+
+impl DecodedTerminalNotification {
+ /// Applies a fully decoded update to its session. Envelope and chunk metadata
+ /// remain event-scoped and are not promoted to terminal or snapshot metadata.
+ pub fn apply(self, thread: &mut AcpThread, cx: &mut Context<AcpThread>) -> Result<()> {
+ anyhow::ensure!(
+ self.session_id.0.as_ref() == thread.session_id().0.as_ref(),
+ "Terminal notification belongs to a different ACP session"
+ );
+ match self.update {
+ DecodedTerminalUpdate::Patch { terminal_id, patch } => {
+ thread.upsert_display_terminal(terminal_id, patch, cx)
+ }
+ DecodedTerminalUpdate::Output {
+ terminal_id, data, ..
+ } => thread.append_display_terminal_output(terminal_id, &data, cx),
+ }
+ }
+}
+
+pub(super) fn parse_terminal_notification(
+ message: &UntypedMessage,
+) -> Result<acp_v2::UpdateSessionNotification, agent_client_protocol::Error> {
+ // SDK deserialization errors include the complete params, which its warning logger would print.
+ let notification =
+ acp_v2::UpdateSessionNotification::parse_message(message.method(), message.params())
+ .map_err(|_| {
+ agent_client_protocol::Error::invalid_params()
+ .data("Malformed ACP v2 terminal notification")
+ })?;
+ // The SDK defaults malformed output to Undefined; don't apply sibling fields in that case.
+ if let acp_v2::SessionUpdate::TerminalUpdate(update) = &notification.update
+ && message
+ .params()
+ .get("update")
+ .and_then(|update| update.get("output"))
+ .is_some_and(|output| !output.is_null())
+ && update.output.is_undefined()
+ {
+ return Err(agent_client_protocol::Error::invalid_params()
+ .data("Malformed ACP v2 terminal output snapshot"));
+ }
+ Ok(notification)
+}
+
+pub fn decode_terminal_notification(
+ notification: acp_v2::UpdateSessionNotification,
+) -> Result<Option<DecodedTerminalNotification>> {
+ let update = match notification.update {
+ acp_v2::SessionUpdate::TerminalUpdate(update) => {
+ let output = match update.output {
+ MaybeUndefined::Undefined => MaybeUndefined::Undefined,
+ MaybeUndefined::Null => MaybeUndefined::Null,
+ MaybeUndefined::Value(output) => MaybeUndefined::Value(DisplayTerminalOutput {
+ data: STANDARD
+ .decode(output.data)
+ .context("invalid base64 in ACP v2 terminal output snapshot")?,
+ meta: output.meta,
+ }),
+ };
+ DecodedTerminalUpdate::Patch {
+ terminal_id: update.terminal_id,
+ patch: DisplayTerminalPatch {
+ command: update.command,
+ cwd: update.cwd,
+ output,
+ exit_status: update.exit_status,
+ meta: update.meta,
+ },
+ }
+ }
+ acp_v2::SessionUpdate::TerminalOutputChunk(chunk) => DecodedTerminalUpdate::Output {
+ terminal_id: chunk.terminal_id,
+ data: STANDARD
+ .decode(chunk.data)
+ .context("invalid base64 in ACP v2 terminal output chunk")?,
+ meta: chunk.meta,
+ },
+ _ => return Ok(None),
+ };
+
+ Ok(Some(DecodedTerminalNotification {
+ session_id: notification.session_id,
+ meta: notification.meta,
+ update,
+ }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use anyhow::bail;
+ use serde_json::json;
+
+ fn decode_fixture(fixture: &str) -> Result<DecodedTerminalNotification> {
+ decode_terminal_notification(serde_json::from_str(fixture)?)?
+ .context("expected a terminal notification")
+ }
+
+ fn scoped_meta(scope: &str) -> acp_v2::Meta {
+ acp_v2::Meta::from_iter([("scope".to_owned(), json!(scope))])
+ }
+
+ #[test]
+ fn sdk_parse_errors_do_not_echo_private_notification_params() -> Result<()> {
+ let message = UntypedMessage::new(
+ "session/update",
+ json!({
+ "sessionId": "private-session-marker",
+ "_meta": {"private": "private-envelope-marker"},
+ "update": {
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "private-terminal-marker",
+ "data": 7,
+ "_meta": {"private": "private-chunk-marker"}
+ }
+ }),
+ )?;
+ let error =
+ parse_terminal_notification(&message).expect_err("malformed chunk must be rejected");
+ assert_eq!(error.code, agent_client_protocol::ErrorCode::InvalidParams);
+ let serialized = serde_json::to_string(&error)?;
+ assert!(!serialized.contains("private-"));
+ assert!(serialized.len() < 200);
+ Ok(())
+ }
+
+ #[test]
+ fn patch_preserves_omission_and_null() -> Result<()> {
+ let omitted = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "update": {"sessionUpdate": "terminal_update", "terminalId": "terminal-1"}
+ }"#,
+ )?;
+ assert_eq!(omitted.session_id, acp_v2::SessionId::new("session-1"));
+ assert_eq!(omitted.meta, None);
+ let DecodedTerminalUpdate::Patch { terminal_id, patch } = omitted.update else {
+ bail!("expected a terminal patch");
+ };
+ assert_eq!(terminal_id, acp_v2::TerminalId::new("terminal-1"));
+ assert_eq!(patch.command, MaybeUndefined::Undefined);
+ assert_eq!(patch.cwd, MaybeUndefined::Undefined);
+ assert!(matches!(patch.output, MaybeUndefined::Undefined));
+ assert_eq!(patch.exit_status, MaybeUndefined::Undefined);
+ assert_eq!(patch.meta, MaybeUndefined::Undefined);
+
+ let cleared = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "_meta": null,
+ "update": {
+ "sessionUpdate": "terminal_update",
+ "terminalId": "terminal-1",
+ "command": null,
+ "cwd": null,
+ "output": null,
+ "exitStatus": null,
+ "_meta": null
+ }
+ }"#,
+ )?;
+ assert_eq!(cleared.meta, None);
+ let DecodedTerminalUpdate::Patch { patch, .. } = cleared.update else {
+ bail!("expected a terminal patch");
+ };
+ assert_eq!(patch.command, MaybeUndefined::Null);
+ assert_eq!(patch.cwd, MaybeUndefined::Null);
+ assert!(matches!(patch.output, MaybeUndefined::Null));
+ assert_eq!(patch.exit_status, MaybeUndefined::Null);
+ assert_eq!(patch.meta, MaybeUndefined::Null);
+ Ok(())
+ }
+
+ #[test]
+ fn patch_preserves_values_and_separate_metadata_scopes() -> Result<()> {
+ let decoded = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "_meta": {"scope": "envelope"},
+ "update": {
+ "sessionUpdate": "terminal_update",
+ "terminalId": "terminal-1",
+ "command": "printf '\\377\\000'",
+ "cwd": "/tmp",
+ "output": {"data": "/wCA", "_meta": {"scope": "snapshot"}},
+ "exitStatus": {
+ "exitCode": 7,
+ "signal": "SIGTERM",
+ "_meta": {"scope": "exit"}
+ },
+ "_meta": {"scope": "terminal"}
+ }
+ }"#,
+ )?;
+ assert_eq!(decoded.meta, Some(scoped_meta("envelope")));
+ let DecodedTerminalUpdate::Patch { patch, .. } = decoded.update else {
+ bail!("expected a terminal patch");
+ };
+ assert_eq!(
+ patch.command,
+ MaybeUndefined::Value("printf '\\377\\000'".to_owned())
+ );
+ assert_eq!(
+ patch.cwd,
+ MaybeUndefined::Value(acp_v2::AbsolutePath::new("/tmp"))
+ );
+ assert_eq!(patch.meta, MaybeUndefined::Value(scoped_meta("terminal")));
+ assert_eq!(
+ patch.exit_status,
+ MaybeUndefined::Value(
+ acp_v2::TerminalExitStatus::new()
+ .exit_code(7u32)
+ .signal("SIGTERM")
+ .meta(scoped_meta("exit"))
+ )
+ );
+ let MaybeUndefined::Value(output) = patch.output else {
+ bail!("expected an output snapshot");
+ };
+ assert_eq!(output.data, [0xff, 0x00, 0x80]);
+ assert_eq!(output.meta, Some(scoped_meta("snapshot")));
+ Ok(())
+ }
+
+ #[test]
+ fn empty_snapshot_preserves_empty_metadata_distinct_from_absence() -> Result<()> {
+ let decoded = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "_meta": {},
+ "update": {
+ "sessionUpdate": "terminal_update",
+ "terminalId": "terminal-1",
+ "output": {"data": "", "_meta": {}},
+ "exitStatus": {"_meta": {}},
+ "_meta": {}
+ }
+ }"#,
+ )?;
+ assert_eq!(decoded.meta, Some(acp_v2::Meta::new()));
+ let DecodedTerminalUpdate::Patch { patch, .. } = decoded.update else {
+ bail!("expected a terminal patch");
+ };
+ assert_eq!(patch.meta, MaybeUndefined::Value(acp_v2::Meta::new()));
+ assert_eq!(
+ patch.exit_status,
+ MaybeUndefined::Value(acp_v2::TerminalExitStatus::new().meta(acp_v2::Meta::new()))
+ );
+ let MaybeUndefined::Value(output) = patch.output else {
+ bail!("expected an output snapshot");
+ };
+ assert!(output.data.is_empty());
+ assert_eq!(output.meta, Some(acp_v2::Meta::new()));
+
+ let decoded = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "update": {
+ "sessionUpdate": "terminal_update",
+ "terminalId": "terminal-1",
+ "output": {"data": ""}
+ }
+ }"#,
+ )?;
+ assert_eq!(decoded.meta, None);
+ let DecodedTerminalUpdate::Patch { patch, .. } = decoded.update else {
+ bail!("expected a terminal patch");
+ };
+ assert_eq!(patch.meta, MaybeUndefined::Undefined);
+ let MaybeUndefined::Value(output) = patch.output else {
+ bail!("expected an output snapshot");
+ };
+ assert!(output.data.is_empty());
+ assert_eq!(output.meta, None);
+ Ok(())
+ }
+
+ #[test]
+ fn chunks_decode_independently_across_ansi_and_utf8_boundaries() -> Result<()> {
+ let first = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "_meta": {"scope": "envelope"},
+ "update": {
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "terminal-1",
+ "data": "G1s=",
+ "_meta": {"scope": "chunk"}
+ }
+ }"#,
+ )?;
+ assert_eq!(first.session_id, acp_v2::SessionId::new("session-1"));
+ assert_eq!(first.meta, Some(scoped_meta("envelope")));
+ let DecodedTerminalUpdate::Output {
+ terminal_id,
+ data,
+ meta,
+ } = first.update
+ else {
+ bail!("expected an output chunk");
+ };
+ assert_eq!(terminal_id, acp_v2::TerminalId::new("terminal-1"));
+ assert_eq!(data, b"\x1b[");
+ assert_eq!(meta, Some(scoped_meta("chunk")));
+
+ let second = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "update": {
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "terminal-1",
+ "data": "MzFtwg=="
+ }
+ }"#,
+ )?;
+ assert_eq!(second.meta, None);
+ let DecodedTerminalUpdate::Output { data, meta, .. } = second.update else {
+ bail!("expected an output chunk");
+ };
+ assert_eq!(data, b"31m\xc2");
+ assert_eq!(meta, None);
+
+ let third = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "update": {
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "terminal-1",
+ "data": "og==",
+ "_meta": null
+ }
+ }"#,
+ )?;
+ let DecodedTerminalUpdate::Output { data, meta, .. } = third.update else {
+ bail!("expected an output chunk");
+ };
+ assert_eq!(data, [0xa2]);
+ assert_eq!(meta, None);
+ Ok(())
+ }
+
+ #[test]
+ fn empty_chunk_preserves_empty_metadata() -> Result<()> {
+ let decoded = decode_fixture(
+ r#"{
+ "sessionId": "session-1",
+ "_meta": {},
+ "update": {
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "terminal-1",
+ "data": "",
+ "_meta": {}
+ }
+ }"#,
+ )?;
+ assert_eq!(decoded.meta, Some(acp_v2::Meta::new()));
+ let DecodedTerminalUpdate::Output { data, meta, .. } = decoded.update else {
+ bail!("expected an output chunk");
+ };
+ assert!(data.is_empty());
+ assert_eq!(meta, Some(acp_v2::Meta::new()));
+ Ok(())
+ }
+
+ #[test]
+ fn invalid_snapshot_and_chunk_are_rejected_without_echoing_payloads() -> Result<()> {
+ for (fixture, context) in [
+ (
+ r#"{
+ "sessionId": "session-1",
+ "update": {
+ "sessionUpdate": "terminal_update",
+ "terminalId": "terminal-1",
+ "command": "echo ready",
+ "cwd": "/tmp",
+ "output": {"data": "private-output!"}
+ }
+ }"#,
+ "terminal output snapshot",
+ ),
+ (
+ r#"{
+ "sessionId": "session-1",
+ "update": {
+ "sessionUpdate": "terminal_output_chunk",
+ "terminalId": "terminal-1",
+ "data": "private-output!"
+ }
+ }"#,
+ "terminal output chunk",
+ ),
+ ] {
+ let error = match decode_terminal_notification(serde_json::from_str(fixture)?) {
+ Err(error) => error,
+ Ok(_) => bail!("expected invalid base64 to reject the entire notification"),
+ };
+ let message = format!("{error:#}");
+ assert!(message.contains(context));
+ assert!(!message.contains("private-output!"));
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn unrelated_update_is_unclaimed() -> Result<()> {
+ let notification = serde_json::from_str(
+ r#"{
+ "sessionId": "session-1",
+ "update": {
+ "sessionUpdate": "agent_message_chunk",
+ "messageId": "message-1",
+ "content": {"type": "text", "text": "hello"}
+ }
+ }"#,
+ )?;
+ assert!(decode_terminal_notification(notification)?.is_none());
+ Ok(())
+ }
+}
diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs
index 5983ee88d41..1b36ff8b537 100644
--- a/crates/agent_servers/src/agent_servers.rs
+++ b/crates/agent_servers/src/agent_servers.rs
@@ -24,7 +24,8 @@ pub use acp::test_support::{
};
pub use acp::{
AcpConnection, AcpDebugMessage, AcpDebugMessageContent, AcpDebugMessageDirection,
- GEMINI_TERMINAL_AUTH_METHOD_ID,
+ DecodedTerminalNotification, DecodedTerminalUpdate, GEMINI_TERMINAL_AUTH_METHOD_ID,
+ v2_terminal_client_builder,
};
pub struct AgentServerDelegate {