Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): resume a compacted turn from where it died, and retire orphan tool rows (#8679)
Akarshan Biswascec2d2da6ee3
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rsindex 71bd2b89d..b22c7dbd5 100644--- a/src-tauri/src/core/agent/compaction.rs+++ b/src-tauri/src/core/agent/compaction.rs@@ -40,6 +40,31 @@ fn role(msg: &Value) -> &str {msg.get("role").and_then(|r| r.as_str()).unwrap_or("")}+/// Where the kept tail may begin, given the ideal boundary `target`. The tail+/// must not open on an orphaned tool result whose `tool_calls` message sits in+/// the dropped prefix, so the boundary moves to the nearest message that is not+/// one. Forward first, since that drops the most; but a long agentic run under+/// a single prompt can end on a fan-out whose results reach the end of the+/// conversation, and walking forward there runs off the end and abandons+/// compaction on exactly the history that needed it. So fall back to walking+/// back onto the call that owns the batch, keeping the group whole.+///+/// `None` when the tail would leave nothing worth dropping: the summary is+/// itself a message, so a prefix of one shrinks nothing.+fn tail_start(rest: &[Value], target: usize) -> Option<usize> {+ let mut cut = target;+ while cut < rest.len() && role(&rest[cut]) == "tool" {+ cut += 1;+ }+ if cut >= rest.len() {+ cut = target;+ while cut > 0 && role(&rest[cut]) == "tool" {+ cut -= 1;+ }+ }+ (cut >= 2).then_some(cut)+}+/// Compact `messages` so the result is meaningfully smaller than the input./// Returns the input unchanged when there is nothing safe to compact (so the/// caller can detect a no-op and stop retrying).@@ -56,16 +81,9 @@ pub(crate) async fn compact_conversation(return messages.to_vec();}- let mut cut = rest.len() - keep_recent;- // The kept tail must not begin with an orphaned tool result whose assistant- // tool-call message sits in the dropped prefix; push the boundary forward- // until the tail starts on a user/assistant message.- while cut < rest.len() && role(&rest[cut]) == "tool" {- cut += 1;- }- if cut == 0 || cut >= rest.len() {+ let Some(cut) = tail_start(rest, rest.len() - keep_recent) else {return messages.to_vec();- }+ };let kept = &rest[cut..];let summary = summarize(&rest[..cut], model_id, model).await;@@ -392,6 +410,95 @@ mod tests {assert!(out.len() < input.len());}+ /// One prompt driving a long agentic run is the normal shape here: a single+ /// user message followed by hundreds of assistant/tool rounds. Compaction+ /// has to bite into that from the top, or the run it was called to rescue+ /// cannot continue.+ #[tokio::test]+ async fn compacts_a_run_with_a_single_user_message() {+ let model = StubModel {+ summary: "CONDENSED".into(),+ calls: StdMutex::new(0),+ requests: tokio::sync::Mutex::new(Vec::new()),+ };+ let mut input = vec![+ json!({ "role": "system", "content": "sys" }),+ json!({ "role": "user", "content": "do the whole task" }),+ ];+ for i in 0..40 {+ input.push(json!({+ "role": "assistant", "content": Value::Null,+ "tool_calls": [{ "id": format!("t{i}"), "function": { "name": "bash" } }]+ }));+ input.push(json!({+ "role": "tool", "tool_call_id": format!("t{i}"), "content": format!("out{i}")+ }));+ }+ let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT).await;++ assert!(out.len() < input.len(), "the run must shrink");+ assert_ne!(+ role(&out[2]),+ "tool",+ "kept tail must not start on a result"+ );+ assert_eq!(+ out[out.len() - 1],+ input[input.len() - 1],+ "the newest round is what the run resumes from"+ );+ }++ /// The cut can land inside a batch of parallel tool results with nothing+ /// but results between it and the end. Walking the boundary forward runs it+ /// off the end and compaction gives up -- on exactly the conversation that+ /// needed it. The boundary has to fall back to the call that owns the batch.+ #[tokio::test]+ async fn compacts_when_the_tail_is_one_batch_of_parallel_results() {+ let model = StubModel {+ summary: "CONDENSED".into(),+ calls: StdMutex::new(0),+ requests: tokio::sync::Mutex::new(Vec::new()),+ };+ let mut input = vec![+ json!({ "role": "system", "content": "sys" }),+ json!({ "role": "user", "content": "do the whole task" }),+ ];+ for i in 0..10 {+ input.push(json!({+ "role": "assistant", "content": Value::Null,+ "tool_calls": [{ "id": format!("t{i}"), "function": { "name": "bash" } }]+ }));+ input.push(json!({+ "role": "tool", "tool_call_id": format!("t{i}"), "content": format!("out{i}")+ }));+ }+ // A final fan-out: one call message, then results all the way to the end.+ let calls: Vec<Value> = (0..20)+ .map(|i| json!({ "id": format!("p{i}"), "function": { "name": "read" } }))+ .collect();+ input.push(json!({+ "role": "assistant", "content": Value::Null, "tool_calls": calls+ }));+ let batch_start = input.len() - 1;+ for i in 0..20 {+ input.push(json!({+ "role": "tool", "tool_call_id": format!("p{i}"), "content": format!("r{i}")+ }));+ }++ let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT).await;++ assert!(+ out.len() < input.len(),+ "a tail of parallel results must not defeat compaction"+ );+ assert_eq!(+ out[2], input[batch_start],+ "the tail must start on the call that owns the results it keeps"+ );+ }+#[tokio::test]async fn tail_never_starts_with_orphan_tool_result() {let model = StubModel {diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 1bb150478..5cf1f1e14 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -1659,6 +1659,24 @@ fn body_session_budget(json_body: &serde_json::Value) -> Option<u64> {.filter(|v| *v > 0)}+/// Hand the client the conversation a failed cycle got to, so the turn it+/// retries resumes from the work already done instead of the prompt that+/// started it. Only from a round boundary, where every tool call is paired with+/// its result: an upstream rejects a conversation ending on an unanswered+/// `tool_calls`. No-op until a round has actually closed -- before that the+/// client's own copy is already current.+fn publish_progress(+ events: &mpsc::UnboundedSender<StreamEvent>,+ conversation_messages: &[serde_json::Value],+ progressed: bool,+) {+ if progressed {+ let _ = events.send(StreamEvent::MessagesUpdated {+ messages: conversation_messages.to_vec(),+ });+ }+}+#[allow(clippy::too_many_arguments)]async fn run_turn_cycle(events: &mpsc::UnboundedSender<StreamEvent>,@@ -1694,6 +1712,9 @@ async fn run_turn_cycle(let mut mid_run_nudge_count: u32 = 0;// One-shot: asked the model to close out its todos before handing back.let mut closeout_nudged = false;+ // Whether a tool round has closed, i.e. whether the client's copy of the+ // conversation is behind this one. See `publish_progress`.+ let mut progressed = false;while unlimited || turn < max_turns {let _ = events.send(StreamEvent::Step {@@ -1729,6 +1750,7 @@ async fn run_turn_cycle().await;if compacted.len() >= conversation_messages.len() {+ publish_progress(events, &conversation_messages, progressed);return Err(e);}log::info!(@@ -1748,7 +1770,10 @@ async fn run_turn_cycle(keep_recent = (keep_recent / 2).max(2);attempts += 1;}- Err(e) => return Err(e),+ Err(e) => {+ publish_progress(events, &conversation_messages, progressed);+ return Err(e);+ }}}};@@ -1870,6 +1895,11 @@ async fn run_turn_cycle(// for the specific model that needs it (scoped, content preserved), so// the agent can speak standard OpenAI tool protocol on the wire again.// See janhq/jan-internal#238.+ //+ // Everything appended from here until this round's results are in is an+ // unanswered `tool_calls`, which no upstream accepts as the tail of a+ // conversation: a failure in between resumes from `round_start`.+ let round_start = conversation_messages.len();if let Some(choice_message) = extract_choice_message(&completion) {let assistant_content = choice_message.get("content")@@ -1911,11 +1941,18 @@ async fn run_turn_cycle("content": content}));}+ progressed = true;turn += 1;continue;}- let tool_results = tools.invoke(&tool_calls).await?;+ let tool_results = match tools.invoke(&tool_calls).await {+ Ok(results) => results,+ Err(e) => {+ publish_progress(events, &conversation_messages[..round_start], progressed);+ return Err(e);+ }+ };// Standard OpenAI tool protocol: each result is a `role: "tool"` message// carrying its `tool_call_id` (see note above the assistant push -- the@@ -2000,9 +2037,14 @@ async fn run_turn_cycle(}));}}+ // This round is closed and its calls are all answered, so the+ // conversation is a valid resume point for whatever kills the cycle+ // next.+ progressed = true;turn += 1;}+ publish_progress(events, &conversation_messages, progressed);Err(format!("reached the {max_turns}-turn limit while the model was still calling tools"))@@ -2827,6 +2869,108 @@ mod tests {);}+ /// A run that dies partway through has already done work: the client owns+ /// the conversation it will retry with, so a failing cycle has to hand over+ /// the rounds it completed. Publishing only on success means the retry+ /// resends the turn's opening prompt and the model redoes everything.+ #[tokio::test]+ async fn turn_cycle_publishes_progress_when_the_cycle_fails() {+ let (tx, mut rx) = mpsc::unbounded_channel();+ let model = ResultQueueModel {+ results: StdMutex::new(+ vec![Ok(tool_call_completion()), Err("upstream 500".to_string())]+ .into_iter()+ .collect(),+ ),+ };+ let tool = MockTool::default();+ let mut budget = SessionBudget::new(None);+ let convo = vec![json!({ "role": "user", "content": "hi" })];++ 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());+ drop(tx);+ let mut published: Option<Vec<serde_json::Value>> = None;+ while let Ok(ev) = rx.try_recv() {+ if let StreamEvent::MessagesUpdated { messages } = ev {+ published = Some(messages);+ }+ }+ let messages = published.expect("the completed tool round must be published");+ assert_eq!(messages[0]["role"], "user");+ assert_eq!(messages[1]["role"], "assistant");+ assert!(messages[1]["tool_calls"].is_array());+ assert_eq!(+ messages[2]["role"], "tool",+ "the published history must pair every call with its result"+ );+ }++ /// The round that failed is not a resume point: its `tool_calls` never got+ /// results, and an upstream rejects a conversation ending on one. The+ /// published history stops at the last round that closed.+ #[tokio::test]+ async fn turn_cycle_progress_never_ends_on_an_unanswered_tool_call() {+ struct FailingTool;+ #[async_trait]+ impl ToolInvoker for FailingTool {+ async fn invoke(+ &self,+ _tool_calls: &[serde_json::Value],+ ) -> Result<Vec<ToolOutcome>, String> {+ Err("tool dispatch failed".to_string())+ }+ }+ let (tx, mut rx) = mpsc::unbounded_channel();+ let model = MockModel::new(vec![tool_call_completion(), tool_call_completion()]);+ let mut budget = SessionBudget::new(None);+ let convo = vec![json!({ "role": "user", "content": "hi" })];++ let result = run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ convo,+ 8,+ &mut budget,+ &model,+ &FailingTool,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ )+ .await;++ assert!(result.is_err());+ drop(tx);+ let mut published: Option<Vec<serde_json::Value>> = None;+ while let Ok(ev) = rx.try_recv() {+ if let StreamEvent::MessagesUpdated { messages } = ev {+ published = Some(messages);+ }+ }+ assert!(+ published.is_none(),+ "no round closed, so there is nothing to resume from"+ );+ }+#[tokio::test]async fn turn_cycle_skips_execution_on_truncated_tool_calls() {let (tx, _rx) = mpsc::unbounded_channel();diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 86c42c827..729bafb3b 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -1896,10 +1896,22 @@ impl App {/// work that is still running or that succeeded.fn abort_tool_rows(&mut self) {self.close_tool_group(true);+ self.resolve_orphan_tool_rows();+ }++ /// Retire every in-flight tool row the stream will never speak for again.+ /// Shared by the abort paths and by `on_done`: a run that ends normally can+ /// still leave both behind (an upstream that stops mid tool call, or a soft+ /// stop that returns before the calls are dispatched), and neither a+ /// "Preparing X" throbber nor a `▸` row has anything left to resolve it.+ fn resolve_orphan_tool_rows(&mut self) {// A call whose args were still streaming never gets its "Preparing X"// throbber cleared by the `ToolCall` that would have superseded it, so// it animates on past the end of the run, naming a tool that never ran.self.starting.clear();+ // Same for a wait whose `ToolResult` never landed: its child cannot+ // outlive the run, so the row has nothing left to wait for.+ self.awaiting.clear();for row in std::mem::take(&mut self.pending_rows) {if row.idx < self.transcript.len() {self.transcript[row.idx] = RowKind::Tool {@@ -3056,6 +3068,9 @@ impl App {fn on_done(&mut self, stop_reason: String, usage: Option<Usage>) {self.finalize_tool_group();+ // Done is terminal: nothing more arrives on this stream, so a call that+ // never completed cannot be left animating for the rest of the session.+ self.resolve_orphan_tool_rows();// Children cannot outlive the run that dispatched them: their events// arrive on its stream. Any panel still open here never got its own// `SubagentEnd`.@@ -14669,6 +14684,59 @@ mod tests {);}+ /// A run can end normally while a tool call was still streaming its+ /// arguments: the upstream stops mid-call and the assembled completion+ /// carries no `tool_calls`, so no `ToolCall` ever supersedes the throbber+ /// and no `ToolResult` ever resolves the pending row.+ #[test]+ fn normal_done_clears_an_unfinished_tool_call() {+ let mut app = test_app();+ app.submit_user("do a thing".into());+ app.apply(StreamEvent::ToolCallStarted {+ id: "c1".into(),+ name: "write".into(),+ });+ app.apply(StreamEvent::ToolCall {+ id: "c2".into(),+ name: "write".into(),+ args: serde_json::json!({ "path": "a.txt", "content": "x" }),+ });+ assert_eq!(app.starting.len(), 1);+ assert_eq!(app.pending_rows.len(), 1);++ app.on_done("stop".into(), None);++ assert!(+ app.starting.is_empty(),+ "a finished run leaves a throbber naming a tool that never ran"+ );+ assert!(+ app.pending_rows.is_empty(),+ "a finished run leaves a call row spinning for a result that never comes"+ );+ }++ /// An `await_subagent` whose result never lands is the same orphan: the+ /// child cannot outlive the run whose stream carried its events.+ #[test]+ fn terminal_events_clear_an_unresolved_await() {+ for terminal in [0, 1] {+ let mut app = test_app();+ app.submit_user("do a thing".into());+ app.awaiting+ .push(("c1".into(), "run-1".into(), "explorer".into()));+ if terminal == 0 {+ app.on_done("stop".into(), None);+ } else {+ app.on_error("stream".into(), "connection reset".into());+ }+ assert!(+ app.awaiting.is_empty(),+ "an awaiting throbber outlived the run that could resolve it"+ );+ }+ }+/// The deltas have to actually reach the call they belong to.#[test]fn args_deltas_accumulate_onto_the_starting_call() {