diff --git a/Cargo.lock b/Cargo.lock index 58f2fea2710..610dbc61920 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -136,6 +136,7 @@ dependencies = [ name = "acp_tools" version = "0.1.0" dependencies = [ + "acp_thread", "agent-client-protocol", "agent_servers", "agent_ui", @@ -382,6 +383,7 @@ dependencies = [ "client", "collections", "env_logger 0.11.8", + "feature_flags", "fs", "futures 0.3.34", "gpui", diff --git a/crates/acp_tools/Cargo.toml b/crates/acp_tools/Cargo.toml index 4ee524b3687..c199d58b403 100644 --- a/crates/acp_tools/Cargo.toml +++ b/crates/acp_tools/Cargo.toml @@ -18,6 +18,7 @@ test = false test-support = ["workspace/test-support"] [dependencies] +acp_thread.workspace = true agent-client-protocol.workspace = true agent_servers.workspace = true agent_ui.workspace = true diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index 1440cfbcc3e..c6b747951ec 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -62,7 +62,7 @@ struct AcpTools { struct WatchedConnection { agent_id: AgentId, - connection: Rc, + connection: Rc, messages: Vec, list_state: ListState, incoming_request_methods: HashMap>, @@ -158,7 +158,9 @@ impl AcpTools { continue; } - let (backlog, messages_rx) = active_connection.connection.subscribe_debug_messages(); + let Some((backlog, messages_rx)) = active_connection.subscribe_debug_messages() else { + continue; + }; let agent_id = active_connection.agent_id.clone(); let task = cx.spawn({ let agent_id = agent_id.clone(); diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index 50b6e1c09d9..6213fdb7767 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -37,6 +37,7 @@ chrono.workspace = true client.workspace = true collections.workspace = true env_logger = { workspace = true, optional = true } +feature_flags.workspace = true fs.workspace = true futures.workspace = true gpui.workspace = true diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 907f9f35ec1..fc8c7ad5a3c 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -12,7 +12,7 @@ use session_updates::{InboundSessionNotification, InboundSessionUpdate, PendingS pub use terminal_updates::{DecodedTerminalNotification, DecodedTerminalUpdate}; #[cfg(any(test, feature = "test-support"))] pub use v1::test_support; -pub use v1::{AcpConnection, AcpSessionList, GEMINI_TERMINAL_AUTH_METHOD_ID, connect}; +pub use v1::{AcpConnection, AcpSessionList, GEMINI_TERMINAL_AUTH_METHOD_ID}; pub use v2::AcpV2Connection; use acp_thread::{AcpThread, AuthRequired, ElicitationStore, LoadError}; @@ -26,6 +26,7 @@ use agent_client_protocol::{ }; use anyhow::{Context as _, Result, anyhow}; use collections::{HashMap, HashSet}; +use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; use futures::{Future, channel::mpsc}; use gpui::{App, AsyncApp, Entity, SharedString, Subscription, Task, WeakEntity}; use project::agent_server_store::{AgentServerCommand, AgentServerStore}; @@ -102,6 +103,110 @@ async fn exited_load_error_after_drain( #[error("Unsupported version")] pub struct UnsupportedVersion; +#[derive(Debug, Error)] +#[error("ACP v1 fallback failed: {failure}; v2 negotiation: {negotiation:#}")] +struct V1FallbackFailure { + failure: String, + negotiation: anyhow::Error, +} + +fn fallback_failure(failure: anyhow::Error, negotiation: anyhow::Error) -> anyhow::Error { + let context = V1FallbackFailure { + failure: format!("{failure:#}"), + negotiation, + }; + // The final attempt's typed error must remain authoritative for UI error classification. + failure.context(context) +} + +pub async fn connect( + agent_id: AgentId, + project: Entity, + command: AgentServerCommand, + agent_server_store: WeakEntity, + default_mode: Option, + default_config_options: HashMap, + cx: &mut AsyncApp, +) -> Result> { + let negotiation_error = if cx.update(|cx| cx.has_flag::()) { + match AcpV2Connection::stdio( + agent_id.clone(), + project.clone(), + command.clone(), + agent_server_store.clone(), + cx, + ) + .await + { + Ok(connection) => return Ok(Rc::new(connection)), + Err(error) if error.is::() => Some(error), + Err(error) => return Err(error), + } + } else { + None + }; + v1::connect( + agent_id, + project, + command, + agent_server_store, + default_mode, + default_config_options, + cx, + ) + .await + .map_err(|error| match negotiation_error { + Some(negotiation) => fallback_failure(error, negotiation), + None => error, + }) +} + +fn v1_only_mismatch(error: &agent_client_protocol::Error) -> bool { + if error.code != agent_client_protocol::Error::new(-32022, "").code { + return false; + } + let Some(data) = error.data.as_ref() else { + return false; + }; + let Some(supported) = data.get("supported").and_then(serde_json::Value::as_array) else { + return false; + }; + data.get("requested").and_then(serde_json::Value::as_u64) == Some(2) + && supported + .iter() + .all(|value| value.as_u64().is_some_and(|version| version > 0)) + && supported.iter().any(|value| value.as_u64() == Some(1)) + && !supported.iter().any(|value| value.as_u64() == Some(2)) +} + +fn initialization_error(error: anyhow::Error, debug_log: &AcpDebugLog) -> anyhow::Error { + match debug_log.initialization_response() { + Some(Ok(Some(value))) => { + if serde_json::from_value::(value).is_ok_and(|response| { + response.protocol_version == agent_client_protocol::schema::ProtocolVersion::V1 + }) { + error.context(UnsupportedVersion) + } else { + error + } + } + Some(Err(protocol_error)) => { + let retry_v1 = v1_only_mismatch(&protocol_error); + let error = if error.is::() { + error + } else { + anyhow!(protocol_error).context(format!("ACP initialization failed: {error}")) + }; + if retry_v1 { + error.context(UnsupportedVersion) + } else { + error + } + } + _ => error, + } +} + /// Helper for flattening the nested `Result` shapes that come out of /// `entity.update(cx, |_, cx| fallible_op(cx))` into a single `Result`. @@ -887,3 +992,338 @@ fn handle_v2_complete_elicitation( store.complete_url_elicitation(&elicitation_id, cx); }) } + +#[cfg(all(test, unix))] +mod selection_tests { + use super::*; + use gpui::{TestAppContext, UpdateGlobal as _}; + use serde_json::json; + + fn set_beta(enabled: bool, cx: &mut App) { + cx.update_flags( + false, + if enabled { + vec!["acp-beta".into()] + } else { + vec![] + }, + ); + settings::SettingsStore::update_global(cx, |store, cx| { + store.update_user_settings(cx, |settings| { + settings + .feature_flags + .get_or_insert_default() + .insert("acp-beta".into(), if enabled { "on" } else { "off" }.into()); + }); + }); + assert_eq!(cx.has_flag::(), enabled); + } + + #[gpui::test] + async fn beta_selection_uses_fresh_v1_fallback_only_for_version_mismatch( + cx: &mut TestAppContext, + ) { + cx.update(|cx| { + let mut store = settings::SettingsStore::test(cx); + store.register_setting::(); + cx.set_global(store); + release_channel::init("0.0.0".parse().expect("version"), cx); + }); + cx.executor().allow_parking(); + let directory = tempfile::tempdir().expect("working directory"); + let project = Project::example([directory.path()], &mut cx.to_async()).await; + let v1 = r#""result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"selected-v1","version":"1"}}"#; + let v2 = r#""result":{"protocolVersion":2,"info":{"name":"selected-v2","version":"1"},"capabilities":{"session":{}}}"#; + for (beta, response, exit_after_response, expected, requests) in [ + (false, v2, false, Some(false), "1"), + (true, v2, false, Some(true), "2"), + (true, v1, false, Some(false), "2 1"), + ( + true, + r#""error":{"code":-32022,"message":"Unsupported protocol version","data":{"requested":2,"supported":[1]}}"#, + false, + Some(false), + "2 1", + ), + ( + true, + r#""error":{"code":-32022,"message":"Unsupported protocol version","data":{"requested":2,"supported":[1]}}"#, + true, + Some(false), + "2 1", + ), + ( + true, + r#""error":{"code":-32022,"message":"Unsupported protocol version","data":{"requested":2,"supported":[3]}}"#, + true, + None, + "2", + ), + ( + true, + r#""error":{"code":-32022,"message":"Unsupported protocol version","data":{"requested":2,"supported":[1,2]}}"#, + false, + None, + "2", + ), + ( + true, + r#""error":{"code":-32602,"message":"Bad initialize parameters"}"#, + false, + None, + "2", + ), + ( + true, + r#""result":{"protocolVersion":1},"error":{"code":-32022,"message":"Invalid envelope","data":{"requested":2,"supported":[1]}}"#, + true, + None, + "2", + ), + ( + true, + r#""result":{"info":{"name":"malformed","version":"1"}}"#, + false, + None, + "2", + ), + ( + true, + r#""result":{"protocolVersion":"malformed","agentCapabilities":{}}"#, + false, + None, + "2", + ), + (true, "", true, None, "2"), + ] { + cx.update(|cx| { + set_beta(beta, cx); + }); + let trace = directory.path().join("connections"); + std::fs::write(&trace, "").expect("clear trace"); + let command = AgentServerCommand { + path: "/bin/sh".into(), + args: vec!["-c".into(), r#" +printf 'start %s\n' "$$" >> "$ACP_SELECTION_TRACE" +while IFS= read -r request; do + case "$request" in + *'"method":"initialize"'*) + id=${request#*\"id\":}; id=${id%%,*} + case "$request" in + *'"protocolVersion":2'*) + printf 'initialize 2\n' >> "$ACP_SELECTION_TRACE" + if [ -n "$ACP_SELECTION_RESPONSE" ]; then + printf '{"jsonrpc":"2.0","id":%s,%s}\n' "$id" "$ACP_SELECTION_RESPONSE" + fi + if [ "$ACP_SELECTION_EXIT" = 1 ]; then exit 7; fi + ;; + *) + printf 'initialize 1\n' >> "$ACP_SELECTION_TRACE" + printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"selected-v1","version":"1"}}}\n' "$id" + ;; + esac + ;; + esac +done +"#.into()], + env: Some(HashMap::from_iter([ + ("ACP_SELECTION_TRACE".into(), trace.to_string_lossy().into_owned()), + ("ACP_SELECTION_RESPONSE".into(), response.into()), + ("ACP_SELECTION_EXIT".into(), if exit_after_response { "1" } else { "0" }.into()), + ])), + }; + let connecting = cx.spawn({ + let project = project.clone(); + async move |mut cx| { + connect( + AgentId::new("selection"), + project, + command, + WeakEntity::new_invalid(), + None, + HashMap::default(), + &mut cx, + ) + .await + } + }); + let timeout = cx + .background_executor + .timer(std::time::Duration::from_secs(10)); + futures::pin_mut!(connecting, timeout); + let result = match futures::future::select(connecting, timeout).await { + futures::future::Either::Left((result, _)) => result, + _ => panic!("selection timed out: {response}"), + }; + if let Some(v2) = expected { + let connection = result.expect("selected connection"); + assert_eq!( + connection.clone().downcast::().is_some(), + v2 + ); + cx.update(|cx| set_beta(false, cx)); + assert_eq!( + connection.clone().downcast::().is_some(), + v2 + ); + connection.shutdown(); + drop(connection); + } else { + let error = result + .err() + .unwrap_or_else(|| panic!("unexpected successful selection for {response}")); + if response.starts_with(r#""error":{"code":-32022"#) { + let protocol_error = error + .downcast_ref::() + .expect("structured mismatch retained"); + assert_eq!( + protocol_error.code, + agent_client_protocol::Error::new(-32022, "").code + ); + assert!(protocol_error.data.is_some()); + } + } + let trace = std::fs::read_to_string(&trace).expect("connection trace"); + let actual = trace + .lines() + .filter_map(|line| line.strip_prefix("initialize ")) + .collect::>() + .join(" "); + assert_eq!(actual, requests, "{response}"); + let processes = trace + .lines() + .filter_map(|line| line.strip_prefix("start ")) + .collect::>(); + assert_eq!(processes.len(), requests.split_whitespace().count()); + if let [first, second] = processes.as_slice() { + assert_ne!(first, second, "fallback must launch a fresh process"); + } + } + } + + #[test] + fn version_mismatch_requires_valid_v1_only_support() { + for data in [ + json!({"requested": 1, "supported": [1]}), + json!({"requested": 2, "supported": [1, 2]}), + json!({"requested": 2, "supported": [0, 1]}), + json!({"requested": 2, "supported": [1, "2"]}), + json!({"requested": 2}), + ] { + assert!(!v1_only_mismatch( + &agent_client_protocol::Error::new(-32022, "").data(data) + )); + } + assert!(!v1_only_mismatch( + &agent_client_protocol::Error::invalid_params() + .data(json!({"requested": 2, "supported": [1]})) + )); + } + + #[test] + fn fallback_failure_keeps_the_final_error_authoritative() { + let negotiation_data = json!({"requested": 2, "supported": [1]}); + let final_data = json!({"attempt": "v1"}); + let error = fallback_failure( + anyhow!(agent_client_protocol::Error::invalid_params().data(final_data.clone())), + anyhow!( + agent_client_protocol::Error::new(-32022, "Unsupported") + .data(negotiation_data.clone()) + ) + .context(UnsupportedVersion), + ); + let info = acp_thread::ProtocolErrorInfo::from_error(&error).expect("final protocol error"); + assert_eq!(info.code, -32602); + assert_eq!(info.data, Some(&final_data)); + assert!(!error.is::()); + let context = error + .downcast_ref::() + .expect("negotiation context"); + assert_eq!( + context + .negotiation + .downcast_ref::() + .expect("original negotiation") + .data, + Some(negotiation_data) + ); + } + + #[gpui::test] + #[cfg_attr(not(feature = "e2e"), ignore)] + async fn claude_adapter_initialize_smoke(cx: &mut TestAppContext) { + cx.update(|cx| { + let mut store = settings::SettingsStore::test(cx); + store.register_setting::(); + cx.set_global(store); + release_channel::init("0.0.0".parse().expect("version"), cx); + }); + cx.executor().allow_parking(); + let directory = tempfile::tempdir().expect("isolated working directory"); + let config = directory.path().join("claude-config"); + std::fs::create_dir(&config).expect("isolated Claude configuration"); + let project = Project::example([directory.path()], &mut cx.to_async()).await; + for (beta, adapter_v2, expected_v2) in [ + (false, true, false), + (true, true, true), + (true, false, false), + ] { + cx.update(|cx| set_beta(beta, cx)); + let command = AgentServerCommand { + path: "npx".into(), + args: vec![ + "--yes".into(), + "@agentclientprotocol/claude-agent-acp@0.94.0".into(), + ], + env: Some(HashMap::from_iter([ + ( + "CLAUDE_CONFIG_DIR".into(), + config.to_string_lossy().into_owned(), + ), + ( + "CLAUDE_AGENT_ACP_EXPERIMENTAL_V2".into(), + if adapter_v2 { "1" } else { "0" }.into(), + ), + ("ANTHROPIC_API_KEY".into(), "".into()), + ("CLAUDE_CODE_OAUTH_TOKEN".into(), "".into()), + ])), + }; + let connecting = cx.spawn({ + let project = project.clone(); + async move |mut cx| { + connect( + AgentId::new("claude-acp"), + project, + command, + WeakEntity::new_invalid(), + None, + HashMap::default(), + &mut cx, + ) + .await + } + }); + let timeout = cx + .background_executor + .timer(std::time::Duration::from_secs(30)); + futures::pin_mut!(connecting, timeout); + let connection = match futures::future::select(connecting, timeout).await { + futures::future::Either::Left((result, _)) => { + result.expect("Claude adapter handshake") + } + _ => panic!("Claude adapter handshake timed out"), + }; + let actual_v2 = connection.clone().downcast::().is_some(); + assert_eq!( + actual_v2, expected_v2, + "beta={beta} adapter_v2={adapter_v2}" + ); + println!( + "Claude ACP 0.94.0: beta={beta}, adapter_v2={adapter_v2}, selected_v2={actual_v2}" + ); + connection.shutdown(); + drop(connection); + cx.run_until_parked(); + } + } +} diff --git a/crates/agent_servers/src/acp/debug_log.rs b/crates/agent_servers/src/acp/debug_log.rs index bdf16320be3..b384beec4ec 100644 --- a/crates/agent_servers/src/acp/debug_log.rs +++ b/crates/agent_servers/src/acp/debug_log.rs @@ -40,14 +40,23 @@ pub struct AcpDebugMessage { pub message: AcpDebugMessageContent, } +#[derive(Clone)] +struct ParsedDebugMessage { + message: AcpDebugMessage, + valid_envelope: bool, +} + impl AcpDebugMessage { - fn parse_line(direction: AcpDebugMessageDirection, line: &str) -> Vec { + fn parse_line(direction: AcpDebugMessageDirection, line: &str) -> Vec { if direction == AcpDebugMessageDirection::Stderr { - return vec![Self { - direction, - message: AcpDebugMessageContent::Stderr { - line: Arc::from(line), + return vec![ParsedDebugMessage { + message: Self { + direction, + message: AcpDebugMessageContent::Stderr { + line: Arc::from(line), + }, }, + valid_envelope: false, }]; } @@ -64,8 +73,23 @@ impl AcpDebugMessage { } } - fn parse_value(direction: AcpDebugMessageDirection, value: serde_json::Value) -> Option { + fn parse_value( + direction: AcpDebugMessageDirection, + value: serde_json::Value, + ) -> Option { let object = value.as_object()?; + // Malformed frames are useful diagnostics, but cannot authorize protocol fallback. + let valid_envelope = object.get("jsonrpc").and_then(serde_json::Value::as_str) + == Some("2.0") + && if object.contains_key("method") { + object + .get("method") + .is_some_and(serde_json::Value::is_string) + && !object.contains_key("result") + && !object.contains_key("error") + } else { + object.contains_key("result") != object.contains_key("error") + }; let parsed_id = object .get("id") @@ -118,7 +142,10 @@ impl AcpDebugMessage { return None; }; - Some(Self { direction, message }) + Some(ParsedDebugMessage { + message: Self { direction, message }, + valid_envelope, + }) } } @@ -126,6 +153,13 @@ impl AcpDebugMessage { struct AcpDebugLogState { messages: VecDeque, subscribers: Vec>, + // Startup fallback must not depend on eviction from the diagnostic backlog. + initialization: Option, +} + +struct InitializationExchange { + request_id: RequestId, + response: Option, } #[derive(Clone, Default)] @@ -134,6 +168,23 @@ pub(super) struct AcpDebugLog { } impl AcpDebugLog { + pub(super) fn initialization_response( + &self, + ) -> Option, Error>> { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let response = state.initialization.as_ref()?.response.as_ref()?; + if !response.valid_envelope { + return None; + } + match &response.message.message { + AcpDebugMessageContent::Response { result, .. } => Some(result.clone()), + _ => None, + } + } + pub(super) fn subscribe( &self, ) -> ( @@ -158,14 +209,41 @@ impl AcpDebugLog { self.record_messages(messages); } - fn record_messages(&self, messages: Vec) { + fn record_messages(&self, messages: Vec) { let mut state = self .state .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); state.subscribers.retain(|sender| !sender.is_closed()); - for message in messages { + for parsed in messages { + let message = &parsed.message; + match (message.direction, &message.message) { + ( + AcpDebugMessageDirection::Outgoing, + AcpDebugMessageContent::Request { id, method, .. }, + ) if parsed.valid_envelope + && method.as_ref() == "initialize" + && state.initialization.is_none() => + { + state.initialization = Some(InitializationExchange { + request_id: id.clone(), + response: None, + }); + } + ( + AcpDebugMessageDirection::Incoming, + AcpDebugMessageContent::Response { id, .. }, + ) => { + if let Some(initialization) = &mut state.initialization + && initialization.request_id == *id + && initialization.response.is_none() + { + initialization.response = Some(parsed.clone()); + } + } + _ => {} + } if state.messages.len() == MAX_DEBUG_BACKLOG_MESSAGES { state.messages.pop_front(); } @@ -206,6 +284,76 @@ impl AcpDebugLog { mod tests { use super::*; + #[test] + fn malformed_initialization_envelopes_never_become_fallback_evidence() { + for response in [ + r#"{"id":"initialize","result":{"protocolVersion":1}}"#, + r#"{"jsonrpc":"1.0","id":"initialize","result":{"protocolVersion":1}}"#, + r#"{"jsonrpc":"2.0","id":"initialize","result":{"protocolVersion":1},"error":{"code":-32022,"message":"Unsupported","data":{"requested":2,"supported":[1]}}}"#, + r#"{"jsonrpc":"2.0","id":"initialize","method":null,"result":{"protocolVersion":1}}"#, + ] { + let log = AcpDebugLog::default(); + log.record_line( + AcpDebugMessageDirection::Outgoing, + r#"{"jsonrpc":"2.0","id":"initialize","method":"initialize","params":{"protocolVersion":2}}"#, + ); + log.record_line(AcpDebugMessageDirection::Incoming, response); + assert!(log.initialization_response().is_none(), "{response}"); + log.record_line( + AcpDebugMessageDirection::Incoming, + r#"{"jsonrpc":"2.0","id":"initialize","result":{"protocolVersion":1}}"#, + ); + assert!( + log.initialization_response().is_none(), + "invalid first response must not be replaced" + ); + assert_eq!(log.subscribe().0.len(), 3, "diagnostics remain visible"); + } + } + + #[test] + fn initialization_evidence_is_correlated_and_survives_backlog_eviction() { + let log = AcpDebugLog::default(); + log.record_line( + AcpDebugMessageDirection::Outgoing, + r#"{"jsonrpc":"2.0","id":"initialize","method":"initialize","params":{"protocolVersion":2}}"#, + ); + log.record_line( + AcpDebugMessageDirection::Incoming, + r#"{"jsonrpc":"2.0","id":"unrelated","result":{"protocolVersion":1}}"#, + ); + assert!(log.initialization_response().is_none()); + log.record_line( + AcpDebugMessageDirection::Incoming, + r#"{"jsonrpc":"2.0","id":"initialize","error":{"code":-32022,"message":"Unsupported","data":{"requested":2,"supported":[1]}}}"#, + ); + log.record_line( + AcpDebugMessageDirection::Incoming, + r#"{"jsonrpc":"2.0","id":"initialize","result":{"protocolVersion":2}}"#, + ); + for _ in 0..MAX_DEBUG_BACKLOG_MESSAGES { + log.record_line( + AcpDebugMessageDirection::Incoming, + r#"{"jsonrpc":"2.0","method":"_noise"}"#, + ); + } + let error = log + .initialization_response() + .expect("retained initialization") + .expect_err("first response wins"); + assert_eq!(error.code, Error::new(-32022, "").code); + assert_eq!( + error.data, + Some(serde_json::json!({"requested": 2, "supported": [1]})) + ); + assert!( + log.subscribe().0.iter().all(|message| matches!( + message.message, + AcpDebugMessageContent::Notification { .. } + )) + ); + } + #[test] fn preserves_shared_request_ids_payloads_and_runtime_error_data() { let id = RequestId::Str("opaque/request:雪".into()); @@ -225,7 +373,7 @@ mod tests { id: request_id, method, params: actual_params, - } = &request.message + } = &request.message.message else { panic!("request message"); }; @@ -246,7 +394,7 @@ mod tests { let AcpDebugMessageContent::Response { id: response_id, result: Err(actual_error), - } = &response.message + } = &response.message.message else { panic!("error response"); }; diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs index 1338bce8d0a..7c22cbcab4d 100644 --- a/crates/agent_servers/src/acp/v2.rs +++ b/crates/agent_servers/src/acp/v2.rs @@ -183,7 +183,7 @@ fn shared_session_error(error: Arc) -> anyhow::Error { } } -/// An unselected v2 backend with auth, initial sessions/config and receipt-driven prompts. +/// An ACP v2 backend with auth, initial sessions/config and receipt-driven prompts. pub struct AcpV2Connection { id: AgentId, connection: V2ConnectionTo, @@ -211,6 +211,7 @@ struct StdioStartup { child: transport::OwnedChild, stderr_task: Shared>, runtime: Rc>>, + drain: Option>>, } impl AcpV2Connection { @@ -251,6 +252,7 @@ impl AcpV2Connection { // Keep cleanup from killing the child before startup error arbitration can // distinguish a protocol rejection from a natural process exit. let startup_runtime = Rc::new(RefCell::new(None)); + let (drain_sender, drain_received) = futures::channel::oneshot::channel(); let initialized = { let mut cx = cx.clone(); let debug_log = debug_log.clone(); @@ -267,6 +269,7 @@ impl AcpV2Connection { child, stderr_task, runtime, + drain: Some(drain_sender), }), &mut cx, ) @@ -274,17 +277,17 @@ impl AcpV2Connection { } } .boxed_local(); - let result = runtime::race_startup(initialized, status, stderr_task, &debug_log, cx).await; + let drained = async move { + match drain_received.await { + Ok(drained) => drained.await, + Err(_) => stderr_task.await, + } + } + .boxed_local(); + let result = runtime::race_startup(initialized, status, drained, &debug_log, cx).await; drop(startup_runtime); - let (connection, status, stderr_task) = result?; - let drained = { - let sdk_connection = connection.connection.clone(); - runtime::drain_transport( - async move { sdk_connection.incoming_closed().await }, - connection.dispatch_tx.clone(), - stderr_task, - ) - }; + let (connection, status, drained) = + result.map_err(|error| super::initialization_error(error, &debug_log))?; let mut runtime = connection.runtime.borrow_mut(); let owned = runtime .as_mut() @@ -311,9 +314,19 @@ impl AcpV2Connection { startup: Option, cx: &mut AsyncApp, ) -> Result { - let (runtime, child, stderr_task) = match startup { - Some(startup) => (startup.runtime, Some(startup.child), startup.stderr_task), - None => (Rc::new(RefCell::new(None)), None, Task::ready(()).shared()), + let (runtime, child, stderr_task, drain_sender) = match startup { + Some(startup) => ( + startup.runtime, + Some(startup.child), + startup.stderr_task, + startup.drain, + ), + None => ( + Rc::new(RefCell::new(None)), + None, + Task::ready(()).shared(), + None, + ), }; let request_elicitations = cx.new(|_| ElicitationStore::default()); let sessions = Rc::new(RefCell::new(HashMap::default())); @@ -344,6 +357,7 @@ impl AcpV2Connection { .await }); client_runtime.start_io(runtime::finish_connection(connection_future, cleanup), cx); + let stderr_for_drain = stderr_task.clone(); *runtime.borrow_mut() = Some(ConnectionRuntime { _client: client_runtime, _stderr_task: stderr_task, @@ -369,6 +383,18 @@ impl AcpV2Connection { let connection = received .await .context("Failed to receive ACP v2 connection handle")?; + if let Some(sender) = drain_sender { + let sdk_connection = connection.clone(); + let drained = runtime::drain_transport( + async move { sdk_connection.incoming_closed().await }, + dispatch_tx.clone(), + stderr_for_drain, + ) + .boxed_local(); + if sender.send(drained).is_err() { + log::debug!("ACP startup drain observer was released"); + } + } let supports_terminal_auth = agent_server_store.upgrade().is_some_and(|store| { store.update(cx, |store, _| store.get_external_agent(&id).is_some()) }); @@ -6866,6 +6892,7 @@ exec sleep 60 child, stderr_task: Task::ready(()).shared(), runtime: Rc::new(RefCell::new(None)), + drain: None, }), &mut cx, ) diff --git a/crates/agent_ui/src/agent_connection_store.rs b/crates/agent_ui/src/agent_connection_store.rs index 76e292280c6..320f6f8c563 100644 --- a/crates/agent_ui/src/agent_connection_store.rs +++ b/crates/agent_ui/src/agent_connection_store.rs @@ -1,7 +1,7 @@ use std::rc::{Rc, Weak}; use acp_thread::{AgentConnection, LoadError}; -use agent_servers::AcpConnection; +use agent_servers::{AcpConnection, AcpDebugMessage, AcpV2Connection}; use agent_servers::{AgentServer, AgentServerDelegate}; use anyhow::Result; use collections::HashMap; @@ -63,7 +63,25 @@ impl EventEmitter for AgentConnectionEntry {} #[derive(Clone)] pub struct ActiveAcpConnection { pub agent_id: project::AgentId, - pub connection: Rc, + pub connection: Rc, +} + +impl ActiveAcpConnection { + pub fn subscribe_debug_messages( + &self, + ) -> Option<( + Vec, + async_channel::Receiver, + )> { + if let Some(connection) = self.connection.clone().downcast::() { + Some(connection.subscribe_debug_messages()) + } else { + self.connection + .clone() + .downcast::() + .map(|connection| connection.subscribe_debug_messages()) + } + } } pub struct AgentConnectionStore { @@ -132,14 +150,16 @@ impl AgentConnectionStore { self.entries .values() .filter_map(|entry| match entry.read(cx) { - AgentConnectionEntry::Connected(state) => state - .connection - .clone() - .downcast::() - .map(|connection| ActiveAcpConnection { - agent_id: state.connection.agent_id(), - connection, - }), + AgentConnectionEntry::Connected(state) => { + let connection = state.connection.clone(); + let concrete = connection.clone().into_any(); + (concrete.is::() || concrete.is::()).then( + || ActiveAcpConnection { + agent_id: connection.agent_id(), + connection, + }, + ) + } AgentConnectionEntry::Connecting { .. } | AgentConnectionEntry::Error { .. } => { None }