Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent-tui): make the cancelled-turn tool fold idempotent (#8707)

Akarshan Biswas46e17b349161
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 68bd1f263..75b69c601 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -197,6 +197,10 @@ struct SubagentContext {
parent_args: OrchestrationArgs,
model_id: String,
max_session_tokens: Option<u64>,
+ /// The parent's `send_reasoning`, forwarded to every child body: a child
+ /// resends the reasoning of its own tool-call turns, so an opt-out that
+ /// stopped at the parent would still break a strict provider.
+ send_reasoning: bool,
/// Background children of this run, aborted when the run ends.
bg: std::sync::Arc<crate::core::agent::subagent::BackgroundSubagents>,
}
@@ -431,8 +435,11 @@ impl CompositeToolInvoker {
&ctx.bg,
&ctx.parent_args,
req,
- &ctx.model_id,
- ctx.max_session_tokens,
+ &crate::core::agent::subagent::ParentRun {
+ model: ctx.model_id.clone(),
+ budget_remaining: ctx.max_session_tokens,
+ send_reasoning: ctx.send_reasoning,
+ },
&self.events,
) {
Ok(run_id) => format!(
@@ -1504,6 +1511,7 @@ async fn orchestrate_inner(
parent_args: args.clone(),
model_id: model_id.clone(),
max_session_tokens,
+ send_reasoning: body_send_reasoning(json_body),
bg: bg.clone(),
});
// Resolved once above, where the system prompt also needed it.
@@ -1630,10 +1638,7 @@ fn build_completion_request(
) -> serde_json::Value {
// `[agent].send_reasoning` is forwarded per-request; default true (resend
// reasoning). False opts out of resending prior reason on every turn.
- let send_reasoning = json_body
- .get("send_reasoning")
- .and_then(|v| v.as_bool())
- .unwrap_or(true);
+ let send_reasoning = body_send_reasoning(json_body);
let messages = if send_reasoning {
conversation_messages.to_vec()
} else {
@@ -1748,6 +1753,26 @@ fn body_turn_cap(json_body: &serde_json::Value) -> usize {
.unwrap_or(0) as usize
}
+/// Whether any assistant turn in `messages` carries `reasoning_content`, i.e.
+/// whether [`strip_assistant_reasoning`] would change anything. Guards the
+/// rejection retry below, which would otherwise resend an identical request.
+fn carries_assistant_reasoning(messages: &[serde_json::Value]) -> bool {
+ messages.iter().any(|m| {
+ m.get("role").and_then(|r| r.as_str()) == Some("assistant")
+ && m.get("reasoning_content").is_some()
+ })
+}
+
+/// `[agent].send_reasoning` for a request body; default true (resend prior
+/// reasoning). Read in one place so the request builder and the subagent body
+/// (which forwards the parent's answer to its children) cannot disagree.
+pub(crate) fn body_send_reasoning(json_body: &serde_json::Value) -> bool {
+ json_body
+ .get("send_reasoning")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true)
+}
+
/// Token-spend ceiling for a request body, the real bound on run length.
/// `0` is the explicit "no ceiling" encoding, matching `max_turns`.
fn body_session_budget(json_body: &serde_json::Value) -> Option<u64> {
@@ -1846,6 +1871,27 @@ async fn run_turn_cycle(
keep_recent = (keep_recent / 2).max(2);
attempts += 1;
}
+ // This provider rejects `reasoning_content` outright rather
+ // than ignoring it, so the opt-out `[agent].send_reasoning`
+ // exists for is discovered here instead of having to be
+ // configured by hand. Dropping it from the conversation is
+ // enough on its own: a provider that rejects the field never
+ // streams one either, so no later turn re-adds it. Published
+ // so the client's persisted history loses it too, the way the
+ // compacted history above is published.
+ Err(e)
+ if crate::core::agent::upstream::is_reasoning_field_error(&e)
+ && body_send_reasoning(json_body)
+ && carries_assistant_reasoning(&conversation_messages) =>
+ {
+ log::info!(
+ "agent: upstream rejected reasoning_content, retrying without it"
+ );
+ conversation_messages = strip_assistant_reasoning(&conversation_messages);
+ let _ = events.send(StreamEvent::MessagesUpdated {
+ messages: conversation_messages.clone(),
+ });
+ }
Err(e) => return Err(e),
}
}
@@ -2937,6 +2983,82 @@ mod tests {
assert!(tool.calls.lock().unwrap().is_empty());
}
+ /// A strict endpoint rejects the DeepSeek `reasoning_content` extension
+ /// instead of ignoring it. The turn must recover by dropping the field and
+ /// retrying, and hand the stripped conversation to the client so its
+ /// persisted history stops carrying it.
+ #[tokio::test]
+ async fn turn_cycle_strips_reasoning_and_retries_when_the_upstream_rejects_it() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let model = ResultQueueModel {
+ results: StdMutex::new(
+ vec![
+ Err("Upstream returned HTTP 400: property 'reasoning_content' is unsupported"
+ .to_string()),
+ Ok(json!({ "choices": [{ "message": { "content": "final" }, "finish_reason": "stop" }] })),
+ ]
+ .into_iter()
+ .collect(),
+ ),
+ };
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(None);
+ let convo = vec![
+ json!({ "role": "user", "content": "hi" }),
+ json!({ "role": "assistant", "content": "hey", "reasoning_content": "thinking" }),
+ json!({ "role": "user", "content": "again" }),
+ ];
+
+ let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)
+ .await
+ .unwrap();
+
+ assert_eq!(result["choices"][0]["message"]["content"], "final");
+ let published: Vec<serde_json::Value> = std::iter::from_fn(|| rx.try_recv().ok())
+ .filter_map(|ev| match ev {
+ StreamEvent::MessagesUpdated { messages } => Some(messages),
+ _ => None,
+ })
+ .flatten()
+ .collect();
+ assert!(
+ !published.is_empty()
+ && published
+ .iter()
+ .all(|m| m.get("reasoning_content").is_none()),
+ "published history must have lost reasoning_content: {published:?}"
+ );
+ }
+
+ /// The retry is one-shot by construction: once stripped, nothing carries the
+ /// field, so a provider that keeps rejecting fails the turn instead of
+ /// resending the same request forever.
+ #[tokio::test]
+ async fn a_persistent_reasoning_rejection_fails_the_turn() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let reject =
+ || Err("Upstream returned HTTP 400: 'reasoning_content' is unsupported".to_string());
+ let model = ResultQueueModel {
+ results: StdMutex::new(vec![reject(), reject(), reject()].into_iter().collect()),
+ };
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(None);
+ let convo = vec![
+ json!({ "role": "user", "content": "hi" }),
+ json!({ "role": "assistant", "content": "hey", "reasoning_content": "thinking" }),
+ ];
+
+ let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)
+ .await;
+
+ assert!(result.is_err(), "a persistent rejection must fail the turn");
+ assert_eq!(
+ model.results.lock().unwrap().len(),
+ 1,
+ "exactly one retry after the strip"
+ );
+ }
+
/// A run that never recovers from overflow still has to hand its compacted
/// conversation to the client: without it the session keeps the oversized
/// history and every later turn re-overflows by construction.
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index e8c6488c0..6ee86b226 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -161,6 +161,7 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]
# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO
# show_reasoning = false # expand reasoning in the transcript (Ctrl-O still toggles)
# send_reasoning = true # resend prior reasoning to the model; false drops it from the request
+# # (a provider that rejects the field is detected and stripped automatically)
# Project-local provider override. Wins over ~/.jan/config.toml and any
# provider inherited from Jan Desktop's settings.json. Most projects don't
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index c0ff65710..41489e374 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -662,18 +662,27 @@ impl Drop for AbortOnDrop {
}
}
+/// What a child inherits from the run that dispatched it: the model to fall back
+/// on when the definition names none, the parent's remaining token budget, and
+/// its `send_reasoning` answer.
+#[derive(Clone)]
+pub(crate) struct ParentRun {
+ pub(crate) model: String,
+ pub(crate) budget_remaining: Option<u64>,
+ pub(crate) send_reasoning: bool,
+}
+
/// Build the child request body shared by every subagent run.
fn child_body(
resolved: &ResolvedDispatch,
description: &str,
- parent_model: &str,
- budget_remaining: Option<u64>,
+ parent: &ParentRun,
) -> serde_json::Value {
let model = resolved
.definition
.model
.clone()
- .unwrap_or_else(|| parent_model.to_string());
+ .unwrap_or_else(|| parent.model.clone());
let mut body = serde_json::Map::new();
body.insert("model".to_string(), serde_json::json!(model));
body.insert(
@@ -686,9 +695,15 @@ fn child_body(
if let Some(tools) = &resolved.allowed_tools {
body.insert("allowed_tools".to_string(), serde_json::json!(tools));
}
- if let Some(remaining) = budget_remaining {
+ if let Some(remaining) = parent.budget_remaining {
body.insert("max_session_tokens".to_string(), serde_json::json!(remaining));
}
+ // A child's own tool-call turns carry `reasoning_content`, so the parent's
+ // opt-out has to travel with the dispatch or a strict provider still sees
+ // the field on the second child turn.
+ if !parent.send_reasoning {
+ body.insert("send_reasoning".to_string(), serde_json::json!(false));
+ }
serde_json::Value::Object(body)
}
@@ -699,8 +714,7 @@ async fn run_subagent(
parent_args: crate::core::agent::r#loop::OrchestrationArgs,
resolved: ResolvedDispatch,
description: String,
- parent_model: String,
- budget_remaining: Option<u64>,
+ parent: ParentRun,
events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
run_id: String,
) -> Result<String, SubagentError> {
@@ -719,7 +733,7 @@ async fn run_subagent(
// context, matching ask_requests above).
child_args.todo_registry = None;
- let body = child_body(&resolved, &description, &parent_model, budget_remaining);
+ let body = child_body(&resolved, &description, &parent);
let _ = events.send(StreamEvent::SubagentStart {
run_id: run_id.clone(),
@@ -770,8 +784,7 @@ pub(crate) fn spawn_subagent(
bg: &Arc<BackgroundSubagents>,
parent_args: &crate::core::agent::r#loop::OrchestrationArgs,
req: SubagentRequest,
- parent_model: &str,
- budget_remaining: Option<u64>,
+ parent: &ParentRun,
events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
) -> Result<String, SubagentError> {
use crate::core::agent::events::StreamEvent;
@@ -817,7 +830,7 @@ pub(crate) fn spawn_subagent(
let parent_args = parent_args.clone();
let task_events = events.clone();
let entry_events = events.clone();
- let model = parent_model.to_string();
+ let inherited = parent.clone();
let description = req.description.clone();
let run_id_task = run_id.clone();
let queued_counter = bg.clone();
@@ -838,8 +851,7 @@ pub(crate) fn spawn_subagent(
parent_args,
resolved,
description,
- model,
- budget_remaining,
+ inherited,
task_events,
run_id_task,
)
@@ -1397,6 +1409,41 @@ mod tests {
}
}
+ /// The dispatching run's inheritance, with the defaults every test that only
+ /// cares about scheduling wants.
+ fn parent_run() -> ParentRun {
+ ParentRun {
+ model: "m".to_string(),
+ budget_remaining: None,
+ send_reasoning: true,
+ }
+ }
+
+ /// `[agent].send_reasoning = false` has to reach the child body: a child
+ /// resends the `reasoning_content` of its own tool-call turns, so an opt-out
+ /// that stopped at the parent would still break a strict provider on the
+ /// child's second turn.
+ #[test]
+ fn child_body_forwards_the_parents_send_reasoning_opt_out() {
+ let reg = registry_with("reviewer", None);
+ let p = ToolPermissions::allow_all();
+ let resolved = resolve_dispatch(&reg, &req("reviewer", None), &p).expect("resolves");
+ let on = child_body(&resolved, "task", &parent_run());
+ assert!(
+ on.get("send_reasoning").is_none(),
+ "the default is inherited implicitly: {on}"
+ );
+ let off = child_body(
+ &resolved,
+ "task",
+ &ParentRun {
+ send_reasoning: false,
+ ..parent_run()
+ },
+ );
+ assert_eq!(off["send_reasoning"], serde_json::json!(false));
+ }
+
#[test]
fn resolve_unknown_name_without_inline_prompt_errors() {
let reg = registry_with("reviewer", None);
@@ -1822,9 +1869,9 @@ mod tests {
let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();
let mut starts = Vec::new();
- let r1 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
- let r2 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
- let r3 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r1 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r2 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r3 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
assert_ne!(r1, r2);
assert_ne!(r2, r3);
@@ -1877,8 +1924,8 @@ mod tests {
// Occupy the only slot BEFORE dispatching, so every dispatch queues and
// the await below is deterministic: nothing can start while held.
let _running = bg.semaphore.clone().try_acquire_owned().unwrap();
- let r1 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
- let r2 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let r1 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r2 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
// r2 is queued (not started), and awaiting it must NOT start it: the
// slot is still held, so the await parks. Assert via the events: no
@@ -1919,9 +1966,9 @@ mod tests {
// Hold the slot before dispatching so r1, r2, r3 all queue (parked on
// the semaphore) -- the interesting teardown case.
let _running = bg.semaphore.clone().try_acquire_owned().unwrap();
- let _r1 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
- let r2 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
- let r3 = spawn_subagent(&bg, &args, req("reviewer", None), "m", None, &events_tx).unwrap();
+ let _r1 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r2 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r3 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
AbortOnDrop(bg.clone()); // teardown with queued children parked
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 2efe5f975..99c00c209 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -571,6 +571,34 @@ pub(crate) fn is_context_overflow_error(err: &str) -> bool {
err.contains(CONTEXT_OVERFLOW_MARKER)
}
+/// True when the upstream rejected the request *because* an assistant turn
+/// carries `reasoning_content`. The field is a DeepSeek extension that some
+/// providers require to be resent (llama.cpp `preserve_thinking`) while strict
+/// OpenAI-compatible endpoints (Groq, vLLM's pydantic validation) reject the
+/// whole request rather than ignoring the unknown key. Recognizing it lets the
+/// caller drop the field and retry instead of failing the turn, so
+/// `send_reasoning` does not have to be configured per provider by hand.
+/// Requires both the field name and a rejection phrase: a body that merely
+/// echoes the request must not be read as a rejection of it.
+pub(crate) fn is_reasoning_field_error(err: &str) -> bool {
+ let e = err.to_lowercase();
+ e.contains("reasoning_content")
+ && [
+ "unsupported",
+ "unrecognized",
+ "unknown",
+ "not permitted",
+ "not allowed",
+ "unexpected",
+ "additional",
+ "extra input",
+ "extra field",
+ "invalid",
+ ]
+ .iter()
+ .any(|phrase| e.contains(phrase))
+}
+
/// Every message in an error's `source()` chain, outermost cause first.
/// `reqwest::Error` prints only its own layer -- `error sending request for url
/// (...)` -- so the reason the request never left (DNS failure, refused
@@ -1507,6 +1535,27 @@ mod tests {
assert!(!is_context_overflow_error("Upstream returned HTTP 500: boom"));
}
+ /// The shapes strict endpoints actually return, plus the two ways a false
+ /// positive would arise: an error that names the field without rejecting it,
+ /// and a rejection of some other field.
+ #[test]
+ fn detects_a_rejected_reasoning_content_field() {
+ for body in [
+ "Upstream returned HTTP 400: {\"error\":{\"message\":\"'messages.1' : for 'role':'assistant' the following must be satisfied[('messages.1.reasoning_content' : property 'reasoning_content' is unsupported)]\"}}",
+ "Upstream returned HTTP 400: Unrecognized request argument supplied: reasoning_content",
+ "Upstream returned HTTP 400: body.messages.1.reasoning_content: Extra inputs are not permitted",
+ "Upstream returned HTTP 400: Invalid value for 'reasoning_content'",
+ ] {
+ assert!(is_reasoning_field_error(body), "missed: {body}");
+ }
+ assert!(!is_reasoning_field_error(
+ "Upstream returned HTTP 500: reasoning_content was truncated"
+ ));
+ assert!(!is_reasoning_field_error(
+ "Upstream returned HTTP 400: property 'audio' is unsupported"
+ ));
+ }
+
#[test]
fn accumulates_content_and_emits_token_per_delta() {
let (tx, mut rx) = sink();
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index c0e7597f8..2fa5d336d 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -4023,11 +4023,25 @@ impl App {
.rposition(|e| matches!(e, DisplayEntry::User { .. }))
.map(|i| i + 1)
.unwrap_or(0);
+ // `display_log` is not cleared by a cancel and the fold is reached from
+ // several terminal paths, so a call can already be in `history`: the
+ // backend publishes a mid-turn `MessagesUpdated` on a compaction retry
+ // and on the budget soft-stop, and a cancel is routinely followed by a
+ // late `Error` or stream close from the aborted task. Folding it twice
+ // puts the exchange on the wire twice, which invites a double execution
+ // and wastes context, so ids already folded are skipped.
+ let folded: std::collections::HashSet<&str> = self
+ .history
+ .iter()
+ .filter_map(|m| m.get("tool_calls").and_then(|v| v.as_array()))
+ .flatten()
+ .filter_map(|tc| tc.get("id").and_then(|v| v.as_str()))
+ .collect();
let mut calls: Vec<(String, String, serde_json::Value)> = Vec::new();
let mut results: Vec<(String, String)> = Vec::new();
for entry in self.display_log.iter().skip(start) {
match entry {
- DisplayEntry::ToolCall { id, name, args } => {
+ DisplayEntry::ToolCall { id, name, args } if !folded.contains(id.as_str()) => {
calls.push((id.clone(), name.clone(), args.clone()));
}
DisplayEntry::ToolResult { id, content, .. } => {
@@ -4057,6 +4071,10 @@ impl App {
"content": serde_json::Value::Null,
"tool_calls": tool_calls,
}));
+ // Results are paired to the ids of the `tool_calls` array and emitted in
+ // its order, not in the order they finished: the loop dispatches calls
+ // concurrently, so an out-of-order or partial completion would otherwise
+ // hand a strict endpoint results it cannot match to the calls above.
for (id, _, _) in &calls {
let content = results
.iter()
@@ -16550,6 +16568,145 @@ mod tests {
);
}
+ /// Helper: the wire messages carrying `tool_calls`, and the `role: "tool"`
+ /// messages, for the assertions below.
+ fn tool_turns(app: &App) -> (Vec<&serde_json::Value>, Vec<&serde_json::Value>) {
+ (
+ app.history
+ .iter()
+ .filter(|m| m.get("tool_calls").is_some())
+ .collect(),
+ app.history
+ .iter()
+ .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("tool"))
+ .collect(),
+ )
+ }
+
+ /// The backend publishes a mid-turn `MessagesUpdated` on a compaction retry
+ /// and on the budget soft-stop, so the turn's exchange can already be in
+ /// `history` when the cancel folds it. Folding it again would put the same
+ /// call and result on the wire twice.
+ #[test]
+ fn cancel_after_a_mid_turn_messages_updated_folds_each_call_once() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCall {
+ id: "c1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "ls" }),
+ });
+ app.apply(StreamEvent::ToolResult {
+ id: "c1".into(),
+ content: "ok".into(),
+ is_error: false,
+ diff: None,
+ });
+ app.apply(StreamEvent::MessagesUpdated {
+ messages: vec![
+ json!({ "role": "user", "content": "do a thing" }),
+ json!({
+ "role": "assistant",
+ "content": serde_json::Value::Null,
+ "tool_calls": [{
+ "id": "c1",
+ "type": "function",
+ "function": { "name": "bash", "arguments": "{\"command\":\"ls\"}" }
+ }],
+ }),
+ json!({ "role": "tool", "tool_call_id": "c1", "content": "ok" }),
+ ],
+ });
+ app.cancel_run();
+ let (calls, results) = tool_turns(&app);
+ assert_eq!(calls.len(), 1, "call folded twice: {:?}", app.history);
+ assert_eq!(results.len(), 1, "result folded twice: {:?}", app.history);
+ }
+
+ /// A cancel is routinely followed by a late `Error` or stream close from the
+ /// task it aborted, and `display_log` is not cleared by the cancel, so the
+ /// fold must be idempotent across both.
+ #[test]
+ fn cancel_then_a_late_error_folds_each_call_once() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCall {
+ id: "c1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "ls" }),
+ });
+ app.apply(StreamEvent::ToolResult {
+ id: "c1".into(),
+ content: "ok".into(),
+ is_error: false,
+ diff: None,
+ });
+ app.cancel_run();
+ app.on_error("upstream".into(), "connection reset".into());
+ let (calls, results) = tool_turns(&app);
+ assert_eq!(calls.len(), 1, "call folded twice: {:?}", app.history);
+ assert_eq!(results.len(), 1, "result folded twice: {:?}", app.history);
+ }
+
+ /// The loop emits every `ToolCall` in the model's order and then dispatches
+ /// them concurrently, so results arrive in completion order. The folded
+ /// exchange must pair each result to its call by id and keep the
+ /// `tool_calls` order, the invariant strict endpoints enforce.
+ #[test]
+ fn cancelled_turn_pairs_out_of_order_results_to_their_calls() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ for (id, command) in [("c1", "sleep 5"), ("c2", "ls"), ("c3", "pwd")] {
+ app.apply(StreamEvent::ToolCall {
+ id: id.into(),
+ name: "bash".into(),
+ args: json!({ "command": command }),
+ });
+ }
+ // c3 and c2 finish first; c1 is still in flight at the cancel.
+ for id in ["c3", "c2"] {
+ app.apply(StreamEvent::ToolResult {
+ id: id.into(),
+ content: format!("out of {id}"),
+ is_error: false,
+ diff: None,
+ });
+ }
+ app.cancel_run();
+ let (calls, results) = tool_turns(&app);
+ assert_eq!(
+ calls.len(),
+ 1,
+ "one assistant tool-call turn: {:?}",
+ app.history
+ );
+ let ids: Vec<&str> = calls[0]["tool_calls"]
+ .as_array()
+ .expect("tool_calls array")
+ .iter()
+ .map(|tc| tc["id"].as_str().expect("id"))
+ .collect();
+ assert_eq!(ids, ["c1", "c2", "c3"], "tool_calls kept in model order");
+ let paired: Vec<(&str, &str)> = results
+ .iter()
+ .map(|m| {
+ (
+ m["tool_call_id"].as_str().expect("tool_call_id"),
+ m["content"].as_str().expect("content"),
+ )
+ })
+ .collect();
+ assert_eq!(
+ paired,
+ [
+ ("c1", super::super::MISSING_TOOL_RESULT),
+ ("c2", "out of c2"),
+ ("c3", "out of c3"),
+ ],
+ "results follow the tool_calls order, paired by id"
+ );
+ }
+
#[test]
fn single_collapsible_tool_folds_to_one_row() {
let mut app = test_app();