diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs index 672b3697fe1..a7c104a168c 100644 --- a/crates/acp_thread/src/connection.rs +++ b/crates/acp_thread/src/connection.rs @@ -510,6 +510,35 @@ impl dyn AgentSessionList { } } +/// Read protocol fields without replacing the concrete SDK error or its context chain. +#[derive(Clone, Copy)] +pub struct ProtocolErrorInfo<'a> { + pub code: i32, + pub message: &'a str, + pub data: Option<&'a serde_json::Value>, +} + +impl<'a> ProtocolErrorInfo<'a> { + pub fn from_error(error: &'a anyhow::Error) -> Option { + if let Some(error) = error.downcast_ref::() { + return Some(Self { + code: error.code.into(), + message: &error.message, + data: error.data.as_ref(), + }); + } + error.downcast_ref::().map(|error| Self { + code: error.code.into(), + message: &error.message, + data: error.data.as_ref(), + }) + } + + pub fn is_auth_required(&self) -> bool { + self.code == i32::from(acp_v2::ErrorCode::AuthRequired) + } +} + #[derive(Debug)] pub struct AuthRequired { pub description: Option, @@ -524,6 +553,19 @@ impl AuthRequired { self.description = Some(description); self } + + pub fn from_error(error: &anyhow::Error) -> Option { + if let Some(error) = error.downcast_ref::() { + return Some(Self { + description: error.description.clone(), + }); + } + let error = ProtocolErrorInfo::from_error(error)?; + error.is_auth_required().then(|| Self { + description: (error.message != acp_v2::ErrorCode::AuthRequired.to_string()) + .then(|| error.message.to_owned()), + }) + } } impl Error for AuthRequired {} diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 666d3807202..91aa9afd929 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -2014,10 +2014,6 @@ impl AgentConnection for AcpConnection { match result { Ok(response) => Ok(response), Err(err) => { - if err.code == acp::ErrorCode::AuthRequired { - return Err(anyhow!(acp::Error::auth_required())); - } - if err.code != ErrorCode::InternalError { anyhow::bail!(err) } @@ -2114,16 +2110,10 @@ impl AgentConnection for AcpConnection { } fn map_acp_error(err: acp::Error) -> anyhow::Error { - if err.code == acp::ErrorCode::AuthRequired { - let mut error = AuthRequired::new(); - - if err.message != acp::ErrorCode::AuthRequired.to_string() { - error = error.with_description(err.message); - } - - anyhow!(error) - } else { - anyhow!(err) + let error = anyhow!(err); + match AuthRequired::from_error(&error) { + Some(auth_required) => error.context(auth_required), + None => error, } } @@ -2757,6 +2747,136 @@ mod tests { use super::*; use settings::Settings as _; + #[test] + fn test_auth_error_mapping_retains_sdk_record_and_description() { + let original = acp::Error::new(-32000, "Sign in again") + .data(serde_json::json!({"detail": {"retain": [null, 7]}})); + let mapped = map_acp_error(original.clone()); + assert_eq!( + mapped.downcast_ref::(), + Some(&original), + ); + assert_eq!( + mapped + .downcast_ref::() + .expect("authentication marker") + .description + .as_deref(), + Some("Sign in again"), + ); + } + + #[gpui::test] + async fn prompt_auth_error_retains_sdk_record_and_classification( + cx: &mut gpui::TestAppContext, + ) { + init_settings_test(cx); + + let fs = fs::FakeFs::new(cx.executor()); + fs.insert_tree("/", serde_json::json!({ "a": {} })).await; + let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await; + let mut harness = test_support::connect_fake_acp_connection(project.clone(), cx).await; + let response_error = Arc::new(Mutex::new(acp::Error::auth_required())); + let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex(); + let _agent_io_task = cx.background_spawn( + Agent + .builder() + .name("prompt-auth-test-agent") + .on_receive_request( + async move |_request: acp::NewSessionRequest, responder, _cx| { + responder.respond(acp::NewSessionResponse::new("auth-session")) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + { + let response_error = response_error.clone(); + async move |request: acp::PromptRequest, responder, _cx| { + assert_eq!(request.session_id, acp::SessionId::new("auth-session")); + responder.respond_with_error( + response_error.lock().expect("response error").clone(), + ) + } + }, + agent_client_protocol::on_receive_request!(), + ) + .connect_to(agent_transport), + ); + let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); + let _client_io_task = cx.background_spawn(connect_client_future( + "prompt-auth-test-client", + client_transport, + harness.connection.dispatch_tx.clone(), + connection_tx, + )); + Rc::get_mut(&mut harness.connection) + .expect("test harness should own the only ACP connection handle") + .connection = connection_rx.await.expect("receive SDK connection"); + + let thread = cx + .update(|cx| { + harness.connection.clone().new_session( + project, + PathList::new(&[std::path::PathBuf::from("/a")]), + cx, + ) + }) + .await + .expect("registered session"); + let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone()); + for data in [ + serde_json::json!({"auth": {"provider": "test", "retry": [null, false, 7]}}), + serde_json::json!({"details": "The user aborted a request"}), + ] { + let original = acp::Error::new( + acp::ErrorCode::AuthRequired.into(), + "Sign in to continue this prompt", + ) + .data(data); + *response_error.lock().expect("response error") = original.clone(); + cx.update(|cx| harness.connection.cancel(&session_id, cx)); + assert!( + harness + .connection + .sessions + .borrow() + .get(&session_id) + .expect("registered session") + .suppress_abort_err + ); + let error = cx + .update(|cx| { + harness.connection.prompt( + acp_v2::PromptRequest::new(session_id.clone(), vec!["Hello".into()]), + cx, + ) + }) + .await + .expect_err("authentication errors must not be suppressed by cancellation") + .context("sending the initial prompt"); + assert_eq!( + error.downcast_ref::(), + Some(&original), + ); + assert_eq!( + AuthRequired::from_error(&error) + .expect("initial prompt should be classified as authentication required") + .description + .as_deref(), + Some("Sign in to continue this prompt"), + ); + assert!( + !harness + .connection + .sessions + .borrow() + .get(&session_id) + .expect("registered session") + .suppress_abort_err + ); + } + } + #[test] fn test_legacy_modes_use_config_choices_without_overriding_config_options() { let id = acp::SessionModeId::new("opaque/手動"); diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index e085489e3ee..71aa2703c89 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -2,13 +2,14 @@ use acp_thread::{ AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, AuthRequired, ClientUserMessageId, ElicitationEntryId, ElicitationStatus, ElicitationStore, ForegroundActivity, LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice, - PermissionOptions, PermissionPattern, PermissionRequest, PermissionRequestId, RetryStatus, - SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus, + PermissionOptions, PermissionPattern, PermissionRequest, PermissionRequestId, + ProtocolErrorInfo, RetryStatus, SelectedPermissionOutcome, ThreadStatus, ToolCall, + ToolCallContent, ToolCallStatus, }; use acp_thread::{AgentConnection, Plan}; use action_log::{ActionLog, ActionLogTelemetry, DiffStats}; use agent::{NativeAgentServer, NoModelConfiguredError, ThreadStore}; -use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2}; +use agent_client_protocol::schema::v2 as acp_v2; #[cfg(test)] use agent_servers::AgentServerDelegate; use agent_servers::{AgentServer, GEMINI_TERMINAL_AUTH_METHOD_ID}; @@ -170,18 +171,19 @@ impl From for ThreadError { impl From<&anyhow::Error> for ThreadError { fn from(error: &anyhow::Error) -> Self { + let protocol_error = ProtocolErrorInfo::from_error(error); if error.is::() { Self::MaxOutputTokens } else if error.is::() { Self::NoModelSelected - } else if let Some(acp_error) = error.downcast_ref::() - && acp_error.code == acp_v1::ErrorCode::AuthRequired - { - Self::AuthenticationRequired(acp_error.message.clone().into()) - } else if let Some(acp_error) = error.downcast_ref::() - && acp_error.code == acp_v2::ErrorCode::AuthRequired - { - Self::AuthenticationRequired(acp_error.message.clone().into()) + } else if let Some(auth_error) = AuthRequired::from_error(error) { + Self::AuthenticationRequired( + auth_error + .description + .clone() + .unwrap_or_else(|| auth_error.to_string()) + .into(), + ) } else if let Some(lm_error) = error.downcast_ref::() { use LanguageModelCompletionError::*; match lm_error { @@ -245,15 +247,8 @@ impl From<&anyhow::Error> for ThreadError { } else { let message: SharedString = format!("{:#}", error).into(); - // Extract ACP error code if available - let acp_error_code = error - .downcast_ref::() - .map(|acp_error| SharedString::from(acp_error.code.to_string())) - .or_else(|| { - error - .downcast_ref::() - .map(|acp_error| SharedString::from(i32::from(acp_error.code).to_string())) - }); + let acp_error_code = + protocol_error.map(|error| SharedString::from(error.code.to_string())); Self::Other { message, @@ -1362,16 +1357,16 @@ impl ConversationView { }; let result = match result.await { - Err(e) => match e.downcast::() { - Ok(err) => { + Err(error) => { + if let Some(auth_required) = AuthRequired::from_error(&error) { cx.update(|window, cx| { - Self::handle_auth_required(this, err, connection, window, cx) + Self::handle_auth_required(this, auth_required, connection, window, cx) }) .log_err(); return; } - Err(err) => Err(err), - }, + Err(error) + } Ok(thread) => Ok(thread), }; @@ -4033,6 +4028,7 @@ pub(crate) mod tests { use acp_thread::StubAgentConnection; use action_log::ActionLog; use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext}; + use agent_client_protocol::schema::v1 as acp_v1; use agent_servers::FakeAcpAgentServer; use editor::MultiBufferOffset; use editor::actions::Paste; @@ -4056,6 +4052,125 @@ pub(crate) mod tests { use super::*; + #[test] + fn test_thread_error_protocol_codes_preserve_context_and_data() { + let data = json!({"detail": {"retry": false, "values": [1, 2]}}); + for code in [-32603, -32099] { + for error in [ + anyhow!(acp_v2::Error::new(code, "Backend failed").data(data.clone())), + anyhow!( + agent_client_protocol::Error::new(code, "Backend failed").data(data.clone()) + ), + ] { + let error = error.context("Sending prompt"); + let protocol = ProtocolErrorInfo::from_error(&error).expect("protocol error"); + assert_eq!(protocol.message, "Backend failed"); + assert_eq!(protocol.data, Some(&data)); + let expected_message = format!("{error:#}"); + let ThreadError::Other { + message, + acp_error_code, + } = ThreadError::from(&error) + else { + panic!("expected a generic protocol error"); + }; + assert_eq!(message.as_ref(), expected_message); + assert!(message.contains("Sending prompt")); + assert!(message.contains("retry")); + assert_eq!( + acp_error_code.as_ref().map(|code| code.as_ref()), + Some(code.to_string().as_str()) + ); + } + } + } + + #[test] + fn test_thread_error_protocol_auth_uses_only_message() { + for message in ["Authentication required", "Sign in to continue"] { + for error in [ + anyhow!( + acp_v2::Error::new(-32000, message).data(json!({"private": "auth details"})) + ), + anyhow!( + agent_client_protocol::Error::new(-32000, message) + .data(json!({"private": "auth details"})) + ), + ] { + let error = error.context("Sending prompt"); + assert!(matches!( + ThreadError::from(&error), + ThreadError::AuthenticationRequired(description) if description == message + )); + } + } + } + + #[test] + fn test_thread_error_auth_marker_uses_description_or_default() { + for (marker, expected) in [ + (AuthRequired::new(), "Authentication required"), + ( + AuthRequired::new().with_description("Sign in again".to_string()), + "Sign in again", + ), + ] { + let error = anyhow!(marker).context("Sending prompt"); + assert!(matches!( + ThreadError::from(&error), + ThreadError::AuthenticationRequired(description) if description == expected + )); + } + + for error in [ + anyhow!(agent_client_protocol::Error::auth_required()), + anyhow!(acp_v2::Error::auth_required()), + ] { + let error = error.context( + AuthRequired::new().with_description("Use the application login".to_string()), + ); + assert_eq!( + AuthRequired::from_error(&error) + .expect("authentication required") + .description + .as_deref(), + Some("Use the application login") + ); + assert!(matches!( + ThreadError::from(&error), + ThreadError::AuthenticationRequired(description) + if description == "Use the application login" + )); + } + } + + #[test] + fn test_thread_error_preserves_native_error_precedence() { + let provider_error = LanguageModelCompletionError::from_provider_response( + language_model::OPEN_AI_PROVIDER_NAME, + None, + None, + "Try again later".to_string(), + None, + ProviderErrorCategory::RateLimit, + ); + let error = anyhow!(acp_v2::Error::internal_error()).context(provider_error); + assert!(matches!( + ThreadError::from(&error), + ThreadError::RateLimitExceeded { provider } + if provider.as_ref() == language_model::OPEN_AI_PROVIDER_NAME.to_string().as_str() + )); + assert!(matches!( + ThreadError::from(&error.context(MaxOutputTokensError)), + ThreadError::MaxOutputTokens + )); + let error = anyhow!(AuthRequired::new()).context(NoModelConfiguredError); + assert!(matches!( + ThreadError::from(&error), + ThreadError::NoModelSelected + )); + } + #[test] fn test_data_retention_error_maps_from_provider_error() { // The agent wraps the provider error in a fresh `anyhow::Error`, so @@ -6660,13 +6775,27 @@ pub(crate) mod tests { async fn test_auth_required_on_initial_connect(cx: &mut TestAppContext) { init_test(cx); - let connection = AuthGatedAgentConnection::new(); + for error_source in [ + AuthErrorSource::Marker, + AuthErrorSource::Sdk, + AuthErrorSource::V2, + ] { + assert_auth_required_on_initial_connect(error_source, cx).await; + } + } + + async fn assert_auth_required_on_initial_connect( + error_source: AuthErrorSource, + cx: &mut TestAppContext, + ) { + let mut connection = AuthGatedAgentConnection::new(); + connection.error_source = error_source; let (conversation_view, cx) = setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await; // When new_session returns AuthRequired, the server should transition // to Connected + Unauthenticated rather than getting stuck in Loading. - conversation_view.read_with(cx, |view, _cx| { + conversation_view.read_with(cx, |view, cx| { let connected = view .as_connected() .expect("Should be in Connected state even though auth is required"); @@ -6717,10 +6846,22 @@ pub(crate) mod tests { acp_v2::AuthMethodId::new(AuthGatedAgentConnection::TERMINAL_AUTH_METHOD_ID), ] ); - assert!( - !connected.auth_state.is_ok(), - "Auth state should be Unauthenticated" + let AuthState::Unauthenticated { + description, + pending_auth_method, + } = &connected.auth_state + else { + panic!("Auth state should be Unauthenticated"); + }; + assert_eq!( + description + .as_ref() + .expect("custom auth message should be preserved") + .read(cx) + .source(), + "Sign in to continue" ); + assert!(pending_auth_method.is_none()); assert!( !view.supports_logout(), "Logout should be hidden while unauthenticated" @@ -8755,12 +8896,20 @@ pub(crate) mod tests { } } + #[derive(Clone, Copy)] + enum AuthErrorSource { + Marker, + Sdk, + V2, + } + /// Simulates an agent that requires authentication before a session can be /// created. `new_session` returns `AuthRequired` until `authenticate` is /// called with the correct method, after which sessions are created normally. #[derive(Clone)] struct AuthGatedAgentConnection { authenticated: Arc>, + error_source: AuthErrorSource, auth_methods: Vec, authenticate_calls: Arc>>, terminal_auth_calls: Arc>>, @@ -8774,6 +8923,7 @@ pub(crate) mod tests { fn new() -> Self { Self { authenticated: Arc::new(Mutex::new(false)), + error_source: AuthErrorSource::Marker, auth_methods: vec![ acp_v2::AuthMethod::Other( acp_v2::OtherAuthMethod::new( @@ -8829,9 +8979,22 @@ pub(crate) mod tests { cx: &mut gpui::App, ) -> Task>> { if !*self.authenticated.lock() { - return Task::ready(Err(acp_thread::AuthRequired::new() - .with_description("Sign in to continue".to_string()) - .into())); + let error = match self.error_source { + AuthErrorSource::Marker => anyhow!( + AuthRequired::new().with_description("Sign in to continue".to_string()) + ), + AuthErrorSource::Sdk => anyhow!( + agent_client_protocol::Error::new(-32000, "Sign in to continue") + .data(json!({"private": "auth details"})) + ) + .context("Creating session"), + AuthErrorSource::V2 => anyhow!( + acp_v2::Error::new(-32000, "Sign in to continue") + .data(json!({"private": "auth details"})) + ) + .context("Creating session"), + }; + return Task::ready(Err(error)); } let session_id = acp_v2::SessionId::new("auth-gated-session");