Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_servers: Include stderr in ACP startup exit errors (#55757)
Ben Brandt360f955c2837
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 42c6af38362..a18f9f21e79 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -1177,6 +1177,7 @@ pub enum LoadError {FailedToInstall(SharedString),Exited {status: ExitStatus,+ stderr: Option<SharedString>,},Other(SharedString),}@@ -1195,7 +1196,7 @@ impl Display for LoadError {)}LoadError::FailedToInstall(msg) => write!(f, "Failed to install: {msg}"),- LoadError::Exited { status } => write!(f, "Server exited with status {status}"),+ LoadError::Exited { status, .. } => write!(f, "Server exited with status {status}"),LoadError::Other(msg) => write!(f, "{msg}"),}}diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex 832b6afe048..93efddb03d8 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -20,7 +20,7 @@ use project::{AgentId, Project};use remote::remote_client::Interactive;use serde::Deserialize;use std::path::PathBuf;-use std::process::Stdio;+use std::process::{ExitStatus, Stdio};use std::rc::Rc;use std::sync::{Arc, Mutex};use std::{any::Any, cell::RefCell, collections::VecDeque};@@ -195,6 +195,34 @@ impl AcpDebugLog {sender.try_send(message.clone()).log_err();}}++ fn trailing_stderr(&self) -> Option<String> {+ let state = self.state.lock().ok()?;+ let mut lines = state+ .messages+ .iter()+ .rev()+ .take_while(|message| matches!(&message.message, AcpDebugMessageContent::Stderr { .. }))+ .filter_map(|message| match &message.message {+ AcpDebugMessageContent::Stderr { line } if !line.is_empty() => Some(line.as_ref()),+ _ => None,+ })+ .collect::<Vec<_>>();++ if lines.is_empty() {+ return None;+ }++ lines.reverse();+ Some(lines.join("\n"))+ }+}++fn exited_load_error_with_stderr(status: ExitStatus, debug_log: &AcpDebugLog) -> LoadError {+ LoadError::Exited {+ status,+ stderr: debug_log.trailing_stderr().map(SharedString::from),+ }}/// Awaits the response to an ACP request from a GPUI foreground task.@@ -714,6 +742,7 @@ impl AcpConnection {log::trace!("Spawned (pid: {})", child.id());let sessions = Rc::new(RefCell::new(HashMap::default()));+ let debug_log = AcpDebugLog::default();let (release_channel, version): (Option<&str>, String) = cx.update(|cx| {(@@ -729,7 +758,6 @@ impl AcpConnection {// Set up the foreground dispatch channel for bridging Send handler// closures to the !Send foreground thread.let (dispatch_tx, dispatch_rx) = mpsc::unbounded::<ForegroundWork>();- let debug_log = AcpDebugLog::default();let incoming_lines = futures::io::BufReader::new(stdout).lines();let tapped_incoming = incoming_lines.inspect({@@ -756,6 +784,23 @@ impl AcpConnection {let transport = Lines::new(tapped_outgoing, tapped_incoming);+ let stderr_task = cx.background_spawn({+ let debug_log = debug_log.clone();+ async move {+ let mut stderr = BufReader::new(stderr);+ let mut line = String::new();+ while let Ok(n) = stderr.read_line(&mut line).await+ && n > 0+ {+ let trimmed = line.trim_end_matches(['\n', '\r']);+ log::warn!("agent stderr: {trimmed}");+ debug_log.record_line(AcpDebugMessageDirection::Stderr, trimmed);+ line.clear();+ }+ Ok(())+ }+ });+// `connect_client_future` installs the production handler set and// hands us back both the connection-future (to run on a background// executor) and a oneshot receiver that produces the@@ -769,9 +814,24 @@ impl AcpConnection {}});- let connection: ConnectionTo<Agent> = connection_rx+ let connection_rx = async move {+ connection_rx+ .await+ .context("Failed to receive ACP connection handle")+ }+ .boxed_local();+ let status_fut = child.status().boxed_local();+ let (connection, status_fut) = match futures::future::select(connection_rx, status_fut).await- .context("Failed to receive ACP connection handle")?;+ {+ futures::future::Either::Left((connection, status_fut)) => (connection?, status_fut),+ futures::future::Either::Right((status, _connection_rx)) => match status {+ Ok(status) => return Err(exited_load_error_with_stderr(status, &debug_log).into()),+ Err(err) => {+ return Err(anyhow!("agent server exited before initialization: {err}"));+ }+ },+ };// Set up the foreground dispatch loop to process work items from handlers.let dispatch_context = ClientContext {@@ -787,34 +847,7 @@ impl AcpConnection {}});- let stderr_task = cx.background_spawn({- let debug_log = debug_log.clone();- async move {- let mut stderr = BufReader::new(stderr);- let mut line = String::new();- while let Ok(n) = stderr.read_line(&mut line).await- && n > 0- {- let trimmed = line.trim_end_matches(['\n', '\r']);- log::warn!("agent stderr: {trimmed}");- debug_log.record_line(AcpDebugMessageDirection::Stderr, trimmed);- line.clear();- }- Ok(())- }- });-- let wait_task = cx.spawn({- let sessions = sessions.clone();- let status_fut = child.status();- async move |cx| {- let status = status_fut.await?;- emit_load_error_to_all_sessions(&sessions, LoadError::Exited { status }, cx);- anyhow::Ok(())- }- });-- let response = into_foreground_future(+ let initialize_response = into_foreground_future(connection.send_request(acp::InitializeRequest::new(acp::ProtocolVersion::V1).client_capabilities(@@ -835,12 +868,38 @@ impl AcpConnection {),),)- .await?;+ .map(|response| response.map_err(anyhow::Error::from))+ .boxed_local();+ let (response, status_fut) = match futures::future::select(initialize_response, status_fut)+ .await+ {+ futures::future::Either::Left((response, status_fut)) => (response?, status_fut),+ futures::future::Either::Right((status, _initialize_response)) => match status {+ Ok(status) => return Err(exited_load_error_with_stderr(status, &debug_log).into()),+ Err(err) => {+ return Err(anyhow!("agent server exited before initialization: {err}"));+ }+ },+ };if response.protocol_version < MINIMUM_SUPPORTED_VERSION {return Err(UnsupportedVersion.into());}+ let wait_task = cx.spawn({+ let sessions = sessions.clone();+ let debug_log = debug_log.clone();+ async move |cx| {+ let status = status_fut.await?;+ emit_load_error_to_all_sessions(+ &sessions,+ exited_load_error_with_stderr(status, &debug_log),+ cx,+ );+ anyhow::Ok(())+ }+ });+let telemetry_id = response.agent_info// Use the one the agent provides if we have one@@ -1881,7 +1940,10 @@ pub mod test_support {while let Ok(status) = exit_rx.recv().await {emit_load_error_to_all_sessions(&connection.sessions,- LoadError::Exited { status },+ LoadError::Exited {+ status,+ stderr: None,+ },cx,);}@@ -2373,6 +2435,85 @@ mod tests {assert_eq!(task.label, "Login");}+ #[test]+ fn trailing_stderr_only_uses_final_stderr_block() {+ let debug_log = AcpDebugLog::default();+ debug_log.record_line(AcpDebugMessageDirection::Stderr, "stale stderr");+ debug_log.record_line(+ AcpDebugMessageDirection::Incoming,+ r#"{"method":"initialized"}"#,+ );++ assert_eq!(debug_log.trailing_stderr(), None);++ debug_log.record_line(AcpDebugMessageDirection::Stderr, "recent stderr");+ assert_eq!(+ debug_log.trailing_stderr().as_deref(),+ Some("recent stderr")+ );+ }++ #[cfg(not(windows))]+ #[gpui::test]+ async fn startup_returns_error_when_agent_exits_before_initialization(+ cx: &mut gpui::TestAppContext,+ ) {+ cx.update(|cx| {+ let store = settings::SettingsStore::test(cx);+ cx.set_global(store);+ });+ cx.executor().allow_parking();++ let temp_dir = tempfile::tempdir().unwrap();+ let project = project::Project::example([temp_dir.path()], &mut cx.to_async()).await;+ let agent_server_store =+ project.read_with(cx, |project, _| project.agent_server_store().downgrade());+ let command = AgentServerCommand {+ path: "/bin/sh".into(),+ args: vec![+ "-c".into(),+ r#"printf '%s\n' 'npm error code ETARGET' 'npm error notarget No matching version found for @agentclientprotocol/[email protected] with a date before 4/28/2026, 12:11:38 PM.' >&2; exit 1"#.into(),+ ],+ env: None,+ };++ let mut async_cx = cx.to_async();+ let startup = AcpConnection::stdio(+ AgentId::new("test-agent"),+ project,+ command,+ agent_server_store,+ None,+ None,+ HashMap::default(),+ &mut async_cx,+ )+ .fuse();+ let timeout = cx+ .background_executor+ .timer(std::time::Duration::from_secs(5))+ .fuse();+ futures::pin_mut!(startup, timeout);++ let result = futures::select! {+ result = startup => result,+ _ = timeout => panic!("timed out waiting for failed ACP startup"),+ };++ let Err(error) = result else {+ panic!("expected ACP startup to fail");+ };+ let load_error = error+ .downcast::<LoadError>()+ .expect("startup failure should preserve the typed load error");+ match load_error {+ LoadError::Exited { status, .. } => {+ assert!(!status.success(), "expected non-zero exit status");+ }+ error => panic!("expected exited load error, got: {error:?}"),+ };+ }+async fn connect_fake_agent(cx: &mut gpui::TestAppContext,) -> (diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex c1a975939f6..6ddac5f3f9f 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -2159,11 +2159,17 @@ impl ConversationView {msg.into(),Some(self.create_copy_button(msg.to_string()).into_any_element()),),- LoadError::Exited { status } => (- "Failed to Launch",- format!("Server exited with status {status}").into(),- None,- ),+ LoadError::Exited { status, stderr } => {+ let mut message = format!("Server exited with status {status}");+ if let Some(stderr) = stderr {+ message.push_str("\n");+ message.push_str(stderr);+ };+ let action_slot = stderr+ .is_some()+ .then(|| self.create_copy_button(message.clone()).into_any_element());+ ("Failed to Launch", message.into(), action_slot)+ }LoadError::Other(msg) => ("Failed to Launch",msg.into(),