fix (acp): fail session/prompt when a turn ends on an error (#13043)
This commit is contained in:
@@ -85,7 +85,9 @@ pub async fn run_interactive(stream: RoamingClientStream, agent_label: String) -
|
||||
session.send_prompt(line)?;
|
||||
// Drain updates until the turn completes; chunks are
|
||||
// rendered live via the notification handler above.
|
||||
let _ = session.read_to_string().await?;
|
||||
if let Err(error) = session.read_to_string().await {
|
||||
eprintln!("\nturn failed: {}", error.message);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -22,6 +22,7 @@ pub use provider::{
|
||||
/// Set by the ACP server, read by the provider to tell a spent account apart from a
|
||||
/// prompt the agent could not accept.
|
||||
pub(crate) const CREDITS_EXHAUSTED_REASON: &str = "credits_exhausted";
|
||||
pub(crate) const TURN_FAILED_REASON: &str = "turn_failed";
|
||||
|
||||
pub(crate) fn configured_model_for_provider(
|
||||
config: &crate::config::Config,
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::agents::extension::{Envs, PLATFORM_EXTENSIONS};
|
||||
use crate::agents::mcp_client::{GooseMcpHostInfo, McpClientTrait};
|
||||
use crate::agents::platform_extensions::developer::DeveloperClient;
|
||||
use crate::agents::state_machine::{
|
||||
has_unapplied_tool_confirmation_response, pending_tool_confirmations,
|
||||
has_unapplied_tool_confirmation_response, pending_tool_confirmations, turn_failure,
|
||||
};
|
||||
use crate::agents::{
|
||||
Agent, AgentConfig, ExtensionConfig, ExtensionLoadResult, GoosePlatform, SessionConfig,
|
||||
@@ -1645,7 +1645,7 @@ fn prompt_error_from_message_content(
|
||||
MessageContent::Error(error)
|
||||
if error.kind == crate::conversation::message::MessageErrorKind::Authentication =>
|
||||
{
|
||||
Some(agent_client_protocol::Error::auth_required())
|
||||
Some(agent_client_protocol::Error::auth_required().data(turn_failed_data()))
|
||||
}
|
||||
MessageContent::SystemNotification(notification)
|
||||
if notification.notification_type == SystemNotificationType::CreditsExhausted =>
|
||||
@@ -1665,10 +1665,18 @@ fn prompt_error_from_message_content(
|
||||
.data(serde_json::Value::Object(data)),
|
||||
)
|
||||
}
|
||||
MessageContent::Error(error) => Some(
|
||||
agent_client_protocol::Error::new(-32603, error.message.clone())
|
||||
.data(turn_failed_data()),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_failed_data() -> serde_json::Value {
|
||||
serde_json::json!({ "reason": crate::acp::TURN_FAILED_REASON })
|
||||
}
|
||||
|
||||
fn credits_exhausted_prompt_error(
|
||||
notification: &SystemNotificationContent,
|
||||
) -> agent_client_protocol::Error {
|
||||
@@ -2112,6 +2120,7 @@ impl GooseAcpAgent {
|
||||
let mut output_token_limit_reached = false;
|
||||
let mut tool_requests = HashMap::new();
|
||||
let mut chain_tracker = ToolChainTracker::default();
|
||||
let mut last_message_was_error = false;
|
||||
let mut context_limit = None;
|
||||
let target = SessionAgentTarget {
|
||||
agent: agent.clone(),
|
||||
@@ -2136,11 +2145,8 @@ impl GooseAcpAgent {
|
||||
drop(sessions);
|
||||
|
||||
populate_output_token_limit_content(&mut message);
|
||||
last_message_was_error = message.error_kind().is_some();
|
||||
for content_item in &message.content {
|
||||
if let Some(error) = prompt_error_from_message_content(content_item) {
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
if let MessageContent::ToolRequest(tool_request) = content_item {
|
||||
tool_requests.insert(tool_request.id.clone(), tool_request.clone());
|
||||
}
|
||||
@@ -2231,6 +2237,26 @@ impl GooseAcpAgent {
|
||||
|
||||
let was_cancelled = cancel_token.is_cancelled();
|
||||
if !was_cancelled {
|
||||
if last_message_was_error {
|
||||
let session = self
|
||||
.session_manager
|
||||
.get_session(session_id, true)
|
||||
.await
|
||||
.internal_err_ctx("Failed to load session")?;
|
||||
if let Some(error) = session
|
||||
.conversation
|
||||
.as_ref()
|
||||
.and_then(turn_failure)
|
||||
.and_then(|message| {
|
||||
message
|
||||
.content
|
||||
.iter()
|
||||
.find_map(prompt_error_from_message_content)
|
||||
})
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
if let Some(chain) = chain_tracker.close_current_chain() {
|
||||
self.spawn_ready_chain_summary(chain, agent, acp_session_id, cx);
|
||||
}
|
||||
@@ -2339,11 +2365,11 @@ impl GooseAcpAgent {
|
||||
let stream_result = forward.await;
|
||||
self.clear_active_run(&session_id, &run_id).await;
|
||||
Self::send_active_run_update(cx, &args.session_id, None)?;
|
||||
let outcome = stream_result?;
|
||||
|
||||
let session = self
|
||||
let usage_result = self
|
||||
.send_session_usage_updates(cx, &args.session_id, &session_id, &agent, &mut None)
|
||||
.await?;
|
||||
.await;
|
||||
let outcome = stream_result?;
|
||||
let session = usage_result?;
|
||||
|
||||
let stop_reason =
|
||||
prompt_stop_reason(outcome.was_cancelled, outcome.output_token_limit_reached);
|
||||
@@ -3486,6 +3512,27 @@ print(\"hello, world\")
|
||||
error.code,
|
||||
agent_client_protocol::schema::v1::ErrorCode::AuthRequired
|
||||
);
|
||||
assert_eq!(error.data.unwrap()["reason"], "turn_failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_error_messages_map_to_internal_error() {
|
||||
let message = "Network error: connection refused";
|
||||
let content = MessageContent::error(
|
||||
crate::conversation::message::MessageErrorKind::Other,
|
||||
message,
|
||||
);
|
||||
|
||||
let error = prompt_error_from_message_content(&content).expect("expected prompt error");
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(error).unwrap(),
|
||||
serde_json::json!({
|
||||
"code": -32603,
|
||||
"message": message,
|
||||
"data": { "reason": "turn_failed" }
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -319,23 +319,21 @@ impl GooseAcpAgent {
|
||||
stream,
|
||||
)
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
if let Err(error) = server
|
||||
.send_session_usage_updates(
|
||||
&task_cx,
|
||||
&task_acp_session_id,
|
||||
&task_session_id,
|
||||
&task_agent,
|
||||
&mut None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
session_id = task_session_id,
|
||||
?error,
|
||||
"Failed to update usage after resumed ACP turn"
|
||||
);
|
||||
}
|
||||
if let Err(error) = server
|
||||
.send_session_usage_updates(
|
||||
&task_cx,
|
||||
&task_acp_session_id,
|
||||
&task_session_id,
|
||||
&task_agent,
|
||||
&mut None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
session_id = task_session_id,
|
||||
?error,
|
||||
"Failed to update usage after resumed ACP turn"
|
||||
);
|
||||
}
|
||||
server
|
||||
.clear_active_run(&task_session_id, &task_run_id)
|
||||
|
||||
@@ -59,6 +59,7 @@ pub(super) use ops_bang_shell::BangShellOperation;
|
||||
pub(super) use ops_compaction::CompactionOperation;
|
||||
pub(super) use ops_doctor::DoctorOperation;
|
||||
pub(super) use ops_empty_response::EmptyResponseOperation;
|
||||
pub(crate) use ops_exit_on_error::turn_failure;
|
||||
pub(super) use ops_exit_on_error::ExitOnErrorOperation;
|
||||
pub(super) use ops_llm::{GooseInferenceProvider, InferenceRunner};
|
||||
pub(super) use ops_maxturns::{MaxTurnsOperation, MAX_TURNS_MESSAGE};
|
||||
|
||||
@@ -8,7 +8,7 @@ use tracing_futures::Instrument;
|
||||
|
||||
use crate::agents::state_machine::ops_llm::{chat_span, record_chat_usage};
|
||||
use crate::agents::state_machine::{
|
||||
applied, last_effective_role, messages_since_kickoff, not_applicable, trailing_error, yielded,
|
||||
applied, last_effective_role, messages_since_kickoff, not_applicable, trailing_error,
|
||||
yielded_with, ConversationEffect, Emitter, GooseEffect, Operation, OperationResult,
|
||||
SlashCommand,
|
||||
};
|
||||
@@ -17,6 +17,7 @@ use crate::conversation::message::{Message, MessageErrorKind, SystemNotification
|
||||
use crate::conversation::{Conversation, EffectiveRole};
|
||||
use crate::providers::base::Provider;
|
||||
use crate::session::Session;
|
||||
use goose_providers::errors::ProviderError;
|
||||
use goose_providers::model::ModelConfig;
|
||||
|
||||
const COMPACTION_THINKING_TEXT: &str = "goose is compacting the conversation...";
|
||||
@@ -284,12 +285,50 @@ impl Operation<Session, GooseEffect> for CompactionOperation {
|
||||
}
|
||||
Err(e) => {
|
||||
span.record("error.type", "compaction_error");
|
||||
emit.message(Message::assistant().with_text(format!(
|
||||
"Ran into this error trying to compact: {e}.\n\n\
|
||||
Please try again or create a new session"
|
||||
)));
|
||||
yielded()
|
||||
let message = emit.message(compaction_failure_message(&e));
|
||||
yielded_with([message.into()])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compaction_failure_message(e: &anyhow::Error) -> Message {
|
||||
let provider_error = e.downcast_ref::<ProviderError>();
|
||||
if let Some(err @ ProviderError::CreditsExhausted { .. }) = provider_error {
|
||||
return Message::from_provider_error(err);
|
||||
}
|
||||
Message::assistant().with_error(
|
||||
provider_error.map_or(MessageErrorKind::Other, MessageErrorKind::from),
|
||||
format!(
|
||||
"Ran into this error trying to compact: {e}.\n\n\
|
||||
Please try again or create a new session"
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credits_failure_keeps_the_top_up_url() {
|
||||
let error = anyhow::Error::from(ProviderError::CreditsExhausted {
|
||||
details: "no credits".to_string(),
|
||||
top_up_url: Some("https://example.com/billing".to_string()),
|
||||
});
|
||||
let message = compaction_failure_message(&error);
|
||||
let Some(crate::conversation::message::MessageContent::SystemNotification(notification)) =
|
||||
message.content.first()
|
||||
else {
|
||||
panic!("expected a credits notification, got {message:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
notification.notification_type,
|
||||
SystemNotificationType::CreditsExhausted
|
||||
);
|
||||
assert_eq!(
|
||||
notification.data.as_ref().unwrap()["top_up_url"],
|
||||
"https://example.com/billing"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,14 +4,19 @@ use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::agents::state_machine::effects::GooseEffect;
|
||||
use crate::agents::state_machine::{
|
||||
not_applicable, trailing_error, yielded, Emitter, Operation, OperationResult,
|
||||
};
|
||||
use crate::agents::state_machine::{not_applicable, yielded, Emitter, Operation, OperationResult};
|
||||
use crate::conversation::message::Message;
|
||||
use crate::conversation::Conversation;
|
||||
use crate::session::Session;
|
||||
|
||||
pub struct ExitOnErrorOperation;
|
||||
|
||||
pub(crate) fn turn_failure(conversation: &Conversation) -> Option<&Message> {
|
||||
conversation
|
||||
.last()
|
||||
.filter(|message| message.error_kind().is_some())
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Operation<Session, GooseEffect> for ExitOnErrorOperation {
|
||||
fn name(&self) -> &'static str {
|
||||
@@ -24,7 +29,7 @@ impl Operation<Session, GooseEffect> for ExitOnErrorOperation {
|
||||
conversation: &Conversation,
|
||||
_emit: &Emitter,
|
||||
) -> Result<OperationResult<GooseEffect>> {
|
||||
if trailing_error(conversation).is_none() {
|
||||
if turn_failure(conversation).is_none() {
|
||||
return not_applicable();
|
||||
}
|
||||
|
||||
|
||||
@@ -293,6 +293,47 @@ async fn context_errors_compact_and_retry() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_compaction_reports_the_provider_error_kind() -> Result<()> {
|
||||
let (pipeline, api) = test_pipeline().await?;
|
||||
api.on("overflow").context_limit_error("too long");
|
||||
api.on(SUMMARIZE_HISTORY).http_error(401);
|
||||
|
||||
let failed = pipeline.run(["overflow"]).await?;
|
||||
|
||||
assert_eq!(failed.history_replacements(), 0);
|
||||
assert_eq!(api.call_count(), 2);
|
||||
assert_eq!(
|
||||
failed.emitted_error_kinds(),
|
||||
[
|
||||
MessageErrorKind::ContextLengthExceeded,
|
||||
MessageErrorKind::Authentication
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_compaction_without_a_provider_error_reports_other() -> Result<()> {
|
||||
let (pipeline, api) = test_pipeline().await?;
|
||||
api.on("overflow").context_limit_error("too long");
|
||||
api.on(SUMMARIZE_HISTORY)
|
||||
.context_limit_error("still too long");
|
||||
|
||||
let failed = pipeline.run(["overflow"]).await?;
|
||||
|
||||
assert_eq!(failed.history_replacements(), 0);
|
||||
assert_eq!(api.call_count(), 2);
|
||||
assert_eq!(
|
||||
failed.emitted_error_kinds(),
|
||||
[
|
||||
MessageErrorKind::ContextLengthExceeded,
|
||||
MessageErrorKind::Other
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_context_errors_stop_compacting() -> Result<()> {
|
||||
let (pipeline, api) = test_pipeline().await?;
|
||||
|
||||
@@ -47,6 +47,7 @@ enum ApiResponse {
|
||||
OutputLimit,
|
||||
ContextLimitError(String),
|
||||
ServerError(String),
|
||||
HttpError(u16),
|
||||
EmptyServerError,
|
||||
ReplyThenServerError {
|
||||
reply: String,
|
||||
@@ -379,6 +380,10 @@ impl<'a> ApiRuleBuilder<'a> {
|
||||
self.configured(ApiResponse::ServerError(message.into()))
|
||||
}
|
||||
|
||||
pub(super) fn http_error(self, status: u16) -> ConfiguredResponse<'a> {
|
||||
self.configured(ApiResponse::HttpError(status))
|
||||
}
|
||||
|
||||
pub(super) fn no_choices(self) -> ConfiguredResponse<'a> {
|
||||
self.configured(ApiResponse::NoChoices)
|
||||
}
|
||||
@@ -591,6 +596,9 @@ impl DummyApiState {
|
||||
ApiResponse::ServerError(message) => {
|
||||
sse_response(format!("data: {}\n\n", api_error(message)))
|
||||
}
|
||||
ApiResponse::HttpError(status) => {
|
||||
ResponseTemplate::new(status).set_body_json(api_error("rejected"))
|
||||
}
|
||||
ApiResponse::EmptyServerError => ResponseTemplate::new(500),
|
||||
ApiResponse::ReplyThenServerError { reply, error } => sse_response(reply_events(
|
||||
&meta(reply.chars().count() as i32),
|
||||
|
||||
@@ -22,7 +22,7 @@ use crate::agents::subagent_handler::ForegroundSubagentRunner;
|
||||
use crate::agents::AgentEvent;
|
||||
use crate::config::permission::{PermissionLevel, PermissionManager};
|
||||
use crate::config::GooseMode;
|
||||
use crate::conversation::message::{ActionRequiredData, Message, MessageContent};
|
||||
use crate::conversation::message::{ActionRequiredData, Message, MessageContent, MessageErrorKind};
|
||||
use crate::conversation::Conversation;
|
||||
use crate::hooks::HookManager;
|
||||
use crate::permission::permission_inspector::PermissionInspector;
|
||||
@@ -1031,6 +1031,16 @@ impl TestRun {
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(super) fn emitted_error_kinds(&self) -> Vec<MessageErrorKind> {
|
||||
self.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
AgentEvent::Message(message) => message.error_kind(),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn assert_emitted(&self, contains: &str) {
|
||||
let emitted = self
|
||||
.events
|
||||
|
||||
@@ -393,7 +393,7 @@ pub async fn run_fs_write_text_file_true<C: Connection>() {
|
||||
include_str!("../acp_test_data/openai_fs_write_tool_call.txt"),
|
||||
),
|
||||
(
|
||||
r#"Created /tmp/test_acp_write.txt"#.into(),
|
||||
r#" /tmp/test_acp_write.txt (1 lines)"#.into(),
|
||||
include_str!("../acp_test_data/openai_fs_write_tool_result.txt"),
|
||||
),
|
||||
],
|
||||
@@ -478,8 +478,8 @@ pub async fn run_load_mode<C: Connection>() {
|
||||
include_str!("../acp_test_data/openai_tool_call.txt"),
|
||||
),
|
||||
(
|
||||
format!(r#""content":"{FAKE_CODE}""#),
|
||||
include_str!("../acp_test_data/openai_tool_result.txt"),
|
||||
"The user has declined to run this tool.".to_string(),
|
||||
include_str!("../acp_test_data/openai_tool_declined.txt"),
|
||||
),
|
||||
],
|
||||
expected_session_id.clone(),
|
||||
@@ -833,6 +833,14 @@ async fn run_mode_set_impl<C: Connection>(via: SetModeVia) {
|
||||
|
||||
let openai = OpenAiFixture::new(
|
||||
vec![
|
||||
(
|
||||
prompt.to_string(),
|
||||
include_str!("../acp_test_data/openai_tool_call.txt"),
|
||||
),
|
||||
(
|
||||
"The user has declined to run this tool.".to_string(),
|
||||
include_str!("../acp_test_data/openai_tool_declined.txt"),
|
||||
),
|
||||
(
|
||||
prompt.to_string(),
|
||||
include_str!("../acp_test_data/openai_tool_call.txt"),
|
||||
@@ -898,7 +906,6 @@ async fn run_mode_set_impl<C: Connection>(via: SetModeVia) {
|
||||
);
|
||||
|
||||
// Auto mode ignores Cancel -- tool succeeds without permission prompt
|
||||
conn.reset_openai();
|
||||
expected_session_id.set(&session_a.session_id().0);
|
||||
let output = session_a
|
||||
.prompt(prompt, PermissionDecision::Cancel)
|
||||
|
||||
@@ -195,6 +195,11 @@ impl SchedulerTrait for FixtureScheduler {
|
||||
}
|
||||
}
|
||||
|
||||
fn http_error_response(response: &str) -> Option<(u16, &str)> {
|
||||
let (status, body) = response.strip_prefix("status:")?.split_once(' ')?;
|
||||
Some((status.parse().ok()?, body))
|
||||
}
|
||||
|
||||
fn write_global_test_config(config_path: &Path, openai_base_url: &str) {
|
||||
let contents = fs::read_to_string(config_path).unwrap();
|
||||
let mut config: serde_yaml::Mapping = serde_yaml::from_str(&contents).unwrap();
|
||||
@@ -269,6 +274,11 @@ impl OpenAiFixture {
|
||||
let (expected_body, response) = q.front().cloned().unwrap_or_default();
|
||||
if !expected_body.is_empty() && body.contains(&expected_body) {
|
||||
q.pop_front();
|
||||
if let Some((status, error)) = http_error_response(response) {
|
||||
return ResponseTemplate::new(status)
|
||||
.insert_header("content-type", "application/json")
|
||||
.set_body_string(error);
|
||||
}
|
||||
return ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_string(response)
|
||||
|
||||
@@ -1344,3 +1344,100 @@ fn test_shell_terminal_false() {
|
||||
fn test_shell_terminal_true() {
|
||||
run_test(async { run_shell_terminal_true::<AcpServerConnection>().await });
|
||||
}
|
||||
|
||||
const CONTEXT_OVERFLOW: &str = r#"status:400 {"error":{"message":"too long","type":"invalid_request_error","code":"context_length_exceeded"}}"#;
|
||||
const SUMMARIZE_HISTORY: &str = "Please summarize the conversation history";
|
||||
const CONTEXT_ERROR_TEXT: &str =
|
||||
"Context length exceeded: too long\n\nThe conversation is too long for the model's context window.";
|
||||
|
||||
async fn prompt_after_context_overflow(
|
||||
exchanges: Vec<(&str, &'static str)>,
|
||||
) -> anyhow::Result<String> {
|
||||
let mut all = vec![("overflow", CONTEXT_OVERFLOW)];
|
||||
all.extend(exchanges);
|
||||
prompt_and_stream("overflow", all).await.0
|
||||
}
|
||||
|
||||
async fn prompt_and_stream(
|
||||
prompt: &str,
|
||||
exchanges: Vec<(&str, &'static str)>,
|
||||
) -> (anyhow::Result<String>, String) {
|
||||
let expected_session_id = <AcpServerConnection as Connection>::expected_session_id();
|
||||
let exchanges = exchanges
|
||||
.into_iter()
|
||||
.map(|(p, r)| (p.to_string(), r))
|
||||
.collect();
|
||||
let openai = OpenAiFixture::new(exchanges, expected_session_id.clone()).await;
|
||||
let mut conn =
|
||||
<AcpServerConnection as Connection>::new(TestConnectionConfig::default(), openai).await;
|
||||
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
|
||||
expected_session_id.set(&session.session_id().0);
|
||||
let result = session
|
||||
.prompt(prompt, PermissionDecision::Cancel)
|
||||
.await
|
||||
.map(|output| output.text);
|
||||
let streamed = session
|
||||
.session_updates()
|
||||
.into_iter()
|
||||
.filter_map(|update| match update {
|
||||
SessionUpdate::AgentMessageChunk(chunk) => match chunk.content {
|
||||
ContentBlock::Text(text) => Some(text.text),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(result, streamed)
|
||||
}
|
||||
|
||||
fn prompt_acp_error(error: anyhow::Error) -> agent_client_protocol::Error {
|
||||
error.downcast::<agent_client_protocol::Error>().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prompt_succeeds_when_compaction_recovers_from_context_overflow() {
|
||||
run_test(async {
|
||||
let basic = include_str!("acp_test_data/openai_basic.txt");
|
||||
let text = prompt_after_context_overflow(vec![
|
||||
(SUMMARIZE_HISTORY, basic),
|
||||
("Your context was compacted", basic),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(text, format!("{CONTEXT_ERROR_TEXT}2"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prompt_reports_context_error_when_compaction_limit_is_exhausted() {
|
||||
run_test(async {
|
||||
let basic = include_str!("acp_test_data/openai_basic.txt");
|
||||
let error = prompt_after_context_overflow(vec![
|
||||
(SUMMARIZE_HISTORY, basic),
|
||||
("Your context was compacted", CONTEXT_OVERFLOW),
|
||||
(SUMMARIZE_HISTORY, basic),
|
||||
("Your context was compacted", CONTEXT_OVERFLOW),
|
||||
])
|
||||
.await
|
||||
.unwrap_err();
|
||||
let error = prompt_acp_error(error);
|
||||
assert_eq!(error.code, ErrorCode::InternalError);
|
||||
assert_eq!(error.data.unwrap()["reason"], "turn_failed");
|
||||
});
|
||||
}
|
||||
|
||||
const PARTIAL_THEN_STREAM_ERROR: &str = "data: {\"id\":\"chatcmpl-test\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"partial answer\"},\"finish_reason\":null}]}\n\ndata: {\"error\":{\"message\":\"upstream exploded\"}}\n\n";
|
||||
|
||||
#[test]
|
||||
fn test_prompt_fails_and_streams_the_error() {
|
||||
run_test(async {
|
||||
let (result, streamed) =
|
||||
prompt_and_stream("partial", vec![("partial", PARTIAL_THEN_STREAM_ERROR)]).await;
|
||||
let error = prompt_acp_error(result.unwrap_err());
|
||||
assert_eq!(error.code, ErrorCode::InternalError);
|
||||
assert!(
|
||||
streamed.contains("partial answer") && streamed.contains("upstream exploded"),
|
||||
"streamed text: {streamed:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1766229303,"model":"gpt-5-nano","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
|
||||
|
||||
data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1766229303,"model":"gpt-5-nano","choices":[{"index":0,"delta":{"content":"The get_code tool was declined."},"finish_reason":null}]}
|
||||
|
||||
data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1766229303,"model":"gpt-5-nano","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
|
||||
|
||||
data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1766229303,"model":"gpt-5-nano","choices":[],"usage":{"prompt_tokens":100,"completion_tokens":10,"total_tokens":110}}
|
||||
|
||||
data: [DONE]
|
||||
@@ -267,6 +267,54 @@ describe('acpChatSessionController.submitMessage', () => {
|
||||
expect(acpPromptSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ code: -32603, message: 'Network error: connection refused' },
|
||||
{ code: -32000, message: 'Authentication required' },
|
||||
])('finishes a failed turn without a submit error ($code)', async ({ code, message }) => {
|
||||
vi.mocked(acpPromptSession).mockRejectedValueOnce({
|
||||
code,
|
||||
message,
|
||||
data: { reason: 'turn_failed' },
|
||||
});
|
||||
const onFinish = vi.fn();
|
||||
|
||||
await acpChatSessionController.submitMessage(SESSION_ID, userMessage(), {
|
||||
getCurrentSnapshot: () => snapshotWithActivePrompt(null),
|
||||
onFinish,
|
||||
});
|
||||
|
||||
expect(onFinish).toHaveBeenCalledWith({ status: 'failed' });
|
||||
});
|
||||
|
||||
it('finishes a credits failure without a submit error', async () => {
|
||||
vi.mocked(acpChatSessionActions.isCurrentPromptAttempt).mockReturnValue(true);
|
||||
vi.mocked(acpPromptSession).mockRejectedValueOnce({
|
||||
code: -32603,
|
||||
message: 'Out of credits',
|
||||
data: { reason: 'credits_exhausted' },
|
||||
});
|
||||
const onFinish = vi.fn();
|
||||
|
||||
await acpChatSessionController.submitMessage(SESSION_ID, userMessage(), {
|
||||
getCurrentSnapshot: () => snapshotWithActivePrompt(null),
|
||||
onFinish,
|
||||
});
|
||||
|
||||
expect(acpChatSessionActions.setMessages).toHaveBeenCalled();
|
||||
expect(onFinish).toHaveBeenCalledWith({ status: 'failed' });
|
||||
});
|
||||
|
||||
it('reports other prompt errors as a submit error', async () => {
|
||||
vi.mocked(acpPromptSession).mockRejectedValueOnce(new Error('Session not found'));
|
||||
const onFinish = vi.fn();
|
||||
|
||||
await acpChatSessionController.submitMessage(SESSION_ID, userMessage(), {
|
||||
getCurrentSnapshot: () => snapshotWithActivePrompt(null),
|
||||
onFinish,
|
||||
});
|
||||
|
||||
expect(onFinish).toHaveBeenCalledWith({ status: 'failed', message: 'Session not found' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('acpChatSessionController.updateMessage', () => {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { cancelAcpElicitationRequestsForSession } from './elicitationRequests';
|
||||
import {
|
||||
formatAcpError,
|
||||
isAcpTurnError,
|
||||
parseAcpCreditsExhaustedError,
|
||||
type AcpCreditsExhaustedError,
|
||||
} from './errors';
|
||||
@@ -41,8 +42,10 @@ export interface AcpSnapshotOptions {
|
||||
getCurrentSnapshot(): AcpChatSessionSnapshot | undefined;
|
||||
}
|
||||
|
||||
export type PromptOutcome = { status: 'completed' } | { status: 'failed'; message?: string };
|
||||
|
||||
export interface AcpSubmitMessageOptions extends AcpSnapshotOptions {
|
||||
onFinish(error?: string): void | Promise<void>;
|
||||
onFinish(outcome: PromptOutcome): void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface AcpChatSessionController {
|
||||
@@ -190,7 +193,7 @@ async function submitMessage(
|
||||
return;
|
||||
}
|
||||
if (acpChatSessionActions.finishPromptAttemptIfCurrent(sessionId, promptAttemptId)) {
|
||||
void options.onFinish();
|
||||
void options.onFinish({ status: 'completed' });
|
||||
}
|
||||
} catch (error) {
|
||||
if (acpChatSessionActions.clearPromptCancellation(sessionId, promptAttemptId)) {
|
||||
@@ -209,14 +212,14 @@ async function submitMessage(
|
||||
];
|
||||
acpChatSessionActions.setMessages(sessionId, messages);
|
||||
if (acpChatSessionActions.finishPromptAttemptIfCurrent(sessionId, promptAttemptId)) {
|
||||
void options.onFinish();
|
||||
void options.onFinish({ status: 'failed' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const submitError = formatAcpError(error);
|
||||
const message = isAcpTurnError(error) ? undefined : formatAcpError(error);
|
||||
if (acpChatSessionActions.finishPromptAttemptIfCurrent(sessionId, promptAttemptId)) {
|
||||
void options.onFinish(submitError);
|
||||
void options.onFinish({ status: 'failed', message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface AcpCreditsExhaustedError {
|
||||
}
|
||||
|
||||
const CREDITS_EXHAUSTED_REASON = 'credits_exhausted';
|
||||
const TURN_FAILED_REASON = 'turn_failed';
|
||||
const AUTH_REQUIRED_CODE = -32000;
|
||||
|
||||
// Kept in sync with RECIPE_PARAMS_CANCELLED_REASON in crates/goose/src/acp/server/recipe.rs.
|
||||
@@ -57,6 +58,10 @@ export function parseAcpCreditsExhaustedError(error: unknown): AcpCreditsExhaust
|
||||
};
|
||||
}
|
||||
|
||||
export function isAcpTurnError(error: unknown): boolean {
|
||||
return asAcpJsonRpcError(error)?.data?.reason === TURN_FAILED_REASON;
|
||||
}
|
||||
|
||||
export function formatAcpError(error: unknown): string {
|
||||
if (error instanceof RequestError && error.code === AUTH_REQUIRED_CODE) {
|
||||
return 'Sign in to your provider, then try again.';
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import { errorMessage } from '../utils/conversionUtils';
|
||||
import type { UseChatSessionParams, UseChatSessionResult } from './useChatSessionTypes';
|
||||
import { resolveAcpElicitationRequest } from '../acp/elicitationRequests';
|
||||
import { acpChatSessionController } from '../acp/chatSessionController';
|
||||
import { acpChatSessionController, type PromptOutcome } from '../acp/chatSessionController';
|
||||
import {
|
||||
acpChatSessionActions,
|
||||
acpChatSessionStore,
|
||||
@@ -109,9 +109,11 @@ export function useChatSession({
|
||||
}, [getCurrentSnapshot, sessionId]);
|
||||
|
||||
const onFinish = useCallback(
|
||||
async (error?: string): Promise<void> => {
|
||||
if (error) {
|
||||
toastError({ title: "Couldn't send message", msg: error });
|
||||
async (outcome: PromptOutcome): Promise<void> => {
|
||||
if (outcome.status === 'failed') {
|
||||
if (outcome.message) {
|
||||
toastError({ title: "Couldn't send message", msg: outcome.message });
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const [notificationsEnabled, anyWindowFocused] = await Promise.all([
|
||||
|
||||
Reference in New Issue
Block a user