diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index ca5155cfa6..494e3785b0 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -5032,13 +5032,21 @@ impl Task { self.persist_for_epoch(epoch); return; } - if let Ok(stop) = &result - && stop == "refusal" - { + let stopped_early = match &result { + Ok(stop) if stop == "refusal" => Some("The agent declined to continue."), + Ok(stop) if stop == "max_tokens" => { + Some("The reply was cut off: the agent reached its output token limit.") + } + Ok(stop) if stop == "max_turn_requests" => { + Some("The turn stopped: the agent reached its limit of model requests per turn.") + } + _ => None, + }; + if let Some(message) = stopped_early { if self.shared.shut_down_since(epoch) { return; } - self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() }); + self.push_entry(AgentEntry::Error { message: message.into() }); } match (next, result) { (Some(queued), _) => { diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 6c658ad6f4..15f887b53a 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -494,6 +494,10 @@ impl Handler for FakeAgent { self.asks_then_withdraws(&session); return Ok(json!({"stopReason": "end_turn"})); } + if let Some(reason) = text.strip_prefix("stop with ") { + self.say(&session, "Here is the fix:\n```rust\nfn parse(input: &str) -> Result<"); + return Ok(json!({"stopReason": reason})); + } if text == "late option" { // An option the session offers only once it runs. self.update( @@ -3201,6 +3205,31 @@ async fn an_agent_can_withdraw_its_requests() { assert_eq!(answers, [("first".to_owned(), cancelled())]); } +/// A turn that ends at one of the agent's limits says so, as a refusal does. +#[tokio::test(flavor = "multi_thread")] +async fn a_turn_stopped_by_a_limit_says_so() { + for (reason, message) in [ + ("max_tokens", "The reply was cut off: the agent reached its output token limit."), + ("max_turn_requests", "The turn stopped: the agent reached its limit of model requests per turn."), + ("refusal", "The agent declined to continue."), + ] { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let task = mgr + .create(NewAgentTask { + prompt: text(&format!("stop with {reason}")), + provider: "claude".into(), + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + let entries = mgr.entries(&task.id, None).unwrap(); + assert_eq!(entries.last(), Some(&AgentEntry::Error { message: message.into() }), "{reason}: {entries:?}"); + mgr.shutdown(); + } +} + #[test] fn image_blocks_declare_the_type_of_their_bytes() { let image = |mime: &str, data: &str| AgentImage { diff --git a/crates/ide-agent/src/timeline.rs b/crates/ide-agent/src/timeline.rs index 34c8103a7d..16402604d3 100644 --- a/crates/ide-agent/src/timeline.rs +++ b/crates/ide-agent/src/timeline.rs @@ -366,7 +366,8 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option }) } -/// Folds a tool update's content into its output, diffs and images. +/// Replaces a tool's output, diffs and images with `content`: an update's `content` replaces the +/// whole array, so what it leaves out is gone. fn merge_content( content: &[Value], output: &mut Option, @@ -398,20 +399,14 @@ fn merge_content( _ => {} } } - if !text.is_empty() { - // The command a call announced (`$ cmd`) stays above the result that replaces it. - let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ ")); - if let Some(command) = command.filter(|c| !text.starts_with(c)) { - text = format!("{command}\n{text}"); - } - *output = Some(tail(text)); - } - if !new_diffs.is_empty() { - *diffs = new_diffs; - } - if !new_images.is_empty() { - *images = new_images; + // The command a call announced (`$ cmd`) stays above the result that replaces it. + let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ ")); + if let Some(command) = command.filter(|c| !text.starts_with(c)) { + text = if text.is_empty() { command.to_owned() } else { format!("{command}\n{text}") }; } + *output = (!text.is_empty()).then(|| tail(text)); + *diffs = new_diffs; + *images = new_images; } /// The text of a list of content blocks, one per line. @@ -621,6 +616,42 @@ mod tests { assert!(t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "zz"})).changed.is_empty()); } + #[test] + fn an_update_with_content_replaces_all_of_the_calls_content() { + let text = |t: &str| json!({"type": "content", "content": {"type": "text", "text": t}}); + let update = |id: &str, content: Value| json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "content": content}); + let mut t = Timeline::default(); + // An edit announced with its diff that fails: the error replaces the diff. + t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "e1", "title": "Edit a.txt", "kind": "edit", + "status": "pending", + "content": [{"type": "diff", "path": "/p/a.txt", "oldText": "one\n", "newText": "two\nthree\n"}]})); + t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "e1", "status": "failed", + "content": [text("old_string not found in a.txt")]})); + let AgentEntry::Tool { diffs, output, .. } = &t.entries[0] else { panic!() }; + assert!(diffs.is_empty(), "{diffs:?}"); + assert_eq!(output.as_deref(), Some("old_string not found in a.txt")); + // Text replaces images, and no content clears the output. + let image = + json!({"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "iVBORw0KGgo="}}); + t.apply(&update("e1", json!([image]))); + t.apply(&update("e1", json!([text("done")]))); + let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() }; + assert!(images.is_empty()); + assert_eq!(output.as_deref(), Some("done")); + t.apply(&update("e1", json!([]))); + let AgentEntry::Tool { output, .. } = &t.entries[0] else { panic!() }; + assert_eq!(*output, None); + // The command a call announced (`$ cmd`) stays above what replaces its output. + t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r1", "title": "Run make", "kind": "execute", + "content": [text("$ make")]})); + t.apply(&update("r1", json!([text("building")]))); + let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() }; + assert_eq!(output.as_deref(), Some("$ make\nbuilding")); + t.apply(&update("r1", json!([]))); + let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() }; + assert_eq!(output.as_deref(), Some("$ make")); + } + #[test] fn plan_is_one_entry_and_end_turn_settles_open_items() { let mut t = Timeline::default();