Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): realtime tool-call streaming, mid-stream error surfacing, and bash exit-status in TUI
Akarshan Biswasb01b6515699b
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex b0aeaff74..a39523714 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -11,6 +11,12 @@ pub enum StreamEvent {Token { text: String },/// A new orchestration turn began (`index` is 1-based, `max` = max_turns).Step { index: u32, max: u32 },+ /// A tool call started streaming: emitted mid-stream the instant the model's+ /// tool-call `id` and `name` are known, before its arguments finish+ /// streaming. Lets a consumer show an in-progress indicator during the+ /// (potentially long) argument-streaming window; the full [`ToolCall`] with+ /// parsed `args` follows once the completion is assembled.+ ToolCallStarted { id: String, name: String },/// The model requested a tool call. `args` is the parsed argument object/// (null if the model emitted non-JSON arguments).ToolCall {@@ -228,6 +234,19 @@ mod tests {);}+ #[test]+ fn tool_call_started_serializes_to_wire_shape() {+ let v = serde_json::to_value(StreamEvent::ToolCallStarted {+ id: "c1".into(),+ name: "write".into(),+ })+ .unwrap();+ assert_eq!(+ v,+ json!({ "type": "tool_call_started", "id": "c1", "name": "write" })+ );+ }+#[test]fn tool_call_and_result_serialize_to_wire_shape() {let call = serde_json::to_value(StreamEvent::ToolCall {diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex a10700724..f1a7f97e3 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -1153,12 +1153,31 @@ async fn run_turn_cycle(// Standard OpenAI tool protocol: each result is a `role: "tool"` message// carrying its `tool_call_id` (see note above the assistant push -- the// tokamak-1-preview facade handles models that can't attend to it).+ let tool_names: HashMap<&str, &str> = tool_calls+ .iter()+ .filter_map(|tc| {+ let id = tc.get("id").and_then(|v| v.as_str())?;+ let name = tc+ .get("function")+ .and_then(|f| f.get("name"))+ .and_then(|v| v.as_str())?;+ Some((id, name))+ })+ .collect();+for outcome in tool_results {let ToolOutcome { id, content, diff } = outcome;+ // A `bash` call that exits non-zero isn't prefixed "ERROR" (that+ // convention is reserved for hard tool failures the model must+ // treat as errors), but its failed exit marker still flags the+ // call as failed for display.+ let is_error = content.starts_with("ERROR")+ || (tool_names.get(id.as_str()) == Some(&"bash")+ && crate::core::agent::tools::handlers::bash_result_failed(&content));let _ = events.send(StreamEvent::ToolResult {id: id.clone(),content: content.clone(),- is_error: content.starts_with("ERROR"),+ is_error,diff,});conversation_messages.push(serde_json::json!({@@ -1298,6 +1317,82 @@ mod tests {assert!(saw_tool_call && saw_tool_result);}+ struct FixedTool {+ content: String,+ }+ #[async_trait]+ impl ToolInvoker for FixedTool {+ async fn invoke(+ &self,+ tool_calls: &[serde_json::Value],+ ) -> Result<Vec<ToolOutcome>, String> {+ Ok(tool_calls+ .iter()+ .map(|tc| {+ let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();+ ToolOutcome::plain(id, self.content.clone())+ })+ .collect())+ }+ }++ fn bash_call_completion() -> serde_json::Value {+ json!({+ "choices": [{+ "message": {+ "content": serde_json::Value::Null,+ "tool_calls": [{+ "id": "call_1",+ "type": "function",+ "function": { "name": "bash", "arguments": "{\"command\":\"false\"}" }+ }]+ },+ "finish_reason": "tool_calls"+ }]+ })+ }++ async fn bash_result_is_error_flag(content: &str) -> bool {+ let (tx, mut rx) = mpsc::unbounded_channel();+ let model = MockModel::new(vec![+ bash_call_completion(),+ json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),+ ]);+ let tool = FixedTool { content: content.to_string() };+ let mut budget = SessionBudget::new(None);+ run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ vec![json!({ "role": "user", "content": "hi" })],+ 8,+ &mut budget,+ &model,+ &tool,+ )+ .await+ .unwrap();+ drop(tx);+ while let Some(ev) = rx.recv().await {+ if let StreamEvent::ToolResult { is_error, .. } = ev {+ return is_error;+ }+ }+ panic!("no ToolResult emitted");+ }++ #[tokio::test]+ async fn bash_nonzero_exit_flags_tool_result_as_error() {+ assert!(bash_result_is_error_flag("boom\n[exit 1]").await);+ assert!(bash_result_is_error_flag("[terminated by signal]").await);+ }++ #[tokio::test]+ async fn bash_zero_exit_does_not_flag_tool_result_as_error() {+ assert!(!bash_result_is_error_flag("ok\n[exit 0]").await);+ }+#[tokio::test]async fn turn_cycle_stops_when_budget_exhausted() {let (tx, _rx) = mpsc::unbounded_channel();diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/src/core/agent/tools/handlers.rsindex d62e8f858..0807d8297 100644--- a/src-tauri/src/core/agent/tools/handlers.rs+++ b/src-tauri/src/core/agent/tools/handlers.rs@@ -735,6 +735,26 @@ impl BashCapture {}}+/// True when a `bash` tool result reports failure via its exit marker: a+/// non-zero `[exit N]` or a signal termination. The marker is emitted by+/// [`BashCapture::finish`] on its own line and a truncation note may follow it,+/// so scan every line rather than only the tail. Model-facing content is+/// deliberately left unprefixed (a non-zero exit is not an "ERROR" string, since+/// commands like `grep`/`diff`/`test` exit non-zero without failing); this feeds+/// the display-only `is_error` flag so the TUI marks the call failed.+pub(crate) fn bash_result_failed(content: &str) -> bool {+ content.lines().any(|line| {+ let l = line.trim();+ if l == "[terminated by signal]" {+ return true;+ }+ l.strip_prefix("[exit ")+ .and_then(|r| r.strip_suffix(']'))+ .and_then(|n| n.parse::<i32>().ok())+ .is_some_and(|code| code != 0)+ })+}+impl Drop for BashCapture {/// Reclaim the spill file on any path that drops the capture without/// consuming it via `finish` (e.g. `child.wait()` erroring). `finish`@@ -1448,6 +1468,19 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[test]+ fn bash_result_failed_detects_nonzero_and_signal_markers() {+ assert!(bash_result_failed("output\n[exit 1]"));+ assert!(bash_result_failed("output\n[exit 127]"));+ assert!(bash_result_failed("[terminated by signal]"));+ // Truncation note follows the marker on its own line: still detected.+ assert!(bash_result_failed(+ "output\n[exit 2]\n[output truncated at 10 of 99 bytes]"+ ));+ assert!(!bash_result_failed("output\n[exit 0]"));+ assert!(!bash_result_failed("plain output, no marker"));+ }+#[tokio::test]async fn bash_nonzero_exit_is_not_error() {let root = unique_root();diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex 89458287f..b99ea58f6 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -529,6 +529,9 @@ struct ToolCallAccum {id: String,name: String,arguments: String,+ /// A `ToolCallStarted` was already emitted for this call; guards the+ /// once-per-call in-progress signal against later argument deltas.+ started_emitted: bool,}/// Accumulates OpenAI SSE deltas into a single reconstructed completion. Kept@@ -544,6 +547,11 @@ struct SseAccumulator {/// closed. Reasoning is display-only (dimmed in the TUI) and deliberately/// kept out of `content` so it is never resent to the model as history.reasoning_open: bool,+ /// An error object delivered inside the stream (`data: {"error": {...}}`).+ /// OpenAI-compatible upstreams can fail mid-stream after a `200 OK`; without+ /// capturing it the run would end as a silent "no answer" instead of+ /// surfacing the failure. Propagated as an `Err` by `consume_openai_sse`.+ error: Option<String>,}impl SseAccumulator {@@ -575,6 +583,20 @@ impl SseAccumulator {Err(_) => return,};+ if let Some(err) = json.get("error").filter(|e| !e.is_null()) {+ let message = err+ .get("message")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string())+ .unwrap_or_else(|| err.to_string());+ let kind = err.get("type").and_then(|v| v.as_str());+ self.error = Some(match kind {+ Some(t) if !t.is_empty() => format!("{t}: {message}"),+ _ => message,+ });+ return;+ }+if let Some(u) = json.get("usage") {if !u.is_null() {self.usage = Some(u.clone());@@ -644,6 +666,17 @@ impl SseAccumulator {slot.arguments.push_str(arg);}}++ // Signal the in-progress tool call the instant both id and name+ // are known, so consumers can show activity while arguments are+ // still streaming (a long window for large write/edit calls).+ if !slot.started_emitted && !slot.id.is_empty() && !slot.name.is_empty() {+ slot.started_emitted = true;+ let _ = events.send(StreamEvent::ToolCallStarted {+ id: slot.id.clone(),+ name: slot.name.clone(),+ });+ }}}}@@ -744,6 +777,15 @@ async fn consume_openai_sse(}flush_trailing_line(&buf, &mut acc, events);+ if let Some(err) = acc.error.take() {+ let msg = format!("Upstream stream error: {err}");+ return Err(if is_context_overflow_body(&err) {+ format!("[{CONTEXT_OVERFLOW_MARKER}] {msg}")+ } else {+ msg+ });+ }+Ok(acc.into_completion())}@@ -966,6 +1008,91 @@ mod tests {assert_eq!(completion["usage"]["total_tokens"], 12);}+ #[test]+ fn emits_tool_call_started_once_when_id_and_name_first_known() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ // First delta carries id + name; arguments arrive later, split across+ // deltas -- the in-progress signal must fire on this first delta only.+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "id": "call_1", "function": { "name": "write", "arguments": "{\"path\":" } }+ ] } }] })+ .to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "function": { "arguments": "\"a.txt\"}" } }+ ] } }] })+ .to_string(),+ &tx,+ );++ drop(tx);+ let started: Vec<(String, String)> = std::iter::from_fn(|| rx.try_recv().ok())+ .filter_map(|ev| match ev {+ StreamEvent::ToolCallStarted { id, name } => Some((id, name)),+ _ => None,+ })+ .collect();+ assert_eq!(started, vec![("call_1".to_string(), "write".to_string())]);+ }++ #[test]+ fn emits_tool_call_started_per_parallel_call() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "id": "call_a", "function": { "name": "read", "arguments": "" } },+ { "index": 1, "id": "call_b", "function": { "name": "grep", "arguments": "" } }+ ] } }] })+ .to_string(),+ &tx,+ );++ drop(tx);+ let mut names: Vec<String> = std::iter::from_fn(|| rx.try_recv().ok())+ .filter_map(|ev| match ev {+ StreamEvent::ToolCallStarted { name, .. } => Some(name),+ _ => None,+ })+ .collect();+ names.sort();+ assert_eq!(names, vec!["grep".to_string(), "read".to_string()]);+ }++ #[test]+ fn captures_mid_stream_error_object_with_type_prefix() {+ let (tx, _rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "content": "partial" } }] }).to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "error": { "message": "upstream exploded", "type": "server_error" } })+ .to_string(),+ &tx,+ );+ assert_eq!(+ acc.error.as_deref(),+ Some("server_error: upstream exploded")+ );+ }++ #[test]+ fn mid_stream_error_falls_back_to_message_without_type() {+ let (tx, _rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "error": { "message": "boom" } }).to_string(),+ &tx,+ );+ assert_eq!(acc.error.as_deref(), Some("boom"));+ }+#[test]fn ignores_done_sentinel_and_malformed_lines() {let (tx, _rx) = sink();diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 4e120e276..55cdd521b 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1275,6 +1275,9 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {let _ = std::io::stdout().flush();}StreamEvent::Step { index, max } => eprintln!("\n\x1b[2m[turn {index}/{max}]\x1b[0m"),+ // In-progress signal is for the live TUI; the piped log stays quiet+ // until the full call (with args) arrives just below.+ StreamEvent::ToolCallStarted { .. } => {}StreamEvent::ToolCall { name, args, .. } => eprintln!("\x1b[2m[tool] {}\x1b[0m",crate::core::agent::events::describe_tool_call(&name, &args)diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex ab12cc4ec..9734486d9 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -395,6 +395,10 @@ struct App {/// Cleared on the matching `ToolResult` or `SubagentEnd`, whichever comes/// first (the two can race).awaiting: Vec<(String, String, String)>,+ /// Tool calls whose arguments are still streaming, `(tool_call_id, name)`.+ /// Rendered as a live throbber and cleared on the matching `ToolCall` (full+ /// args) or on the next `Step`, whichever comes first.+ starting: Vec<(String, String)>,/// Monotonic frame counter advanced each render tick; drives the throbber.spinner_frame: usize,/// Transcript viewport rect from the last draw, for mapping mouse clicks@@ -532,6 +536,7 @@ impl App {subagents: Vec::new(),subagent_blocks: Vec::new(),awaiting: Vec::new(),+ starting: Vec::new(),spinner_frame: 0,transcript_rect: Rect::default(),last_scroll: 0,@@ -593,6 +598,7 @@ impl App {self.transcript.clear();self.tool_group = None;self.grouped_ids.clear();+ self.starting.clear();self.groups.clear();self.reasoning_blocks.clear();self.subagent_blocks.clear();@@ -1185,9 +1191,21 @@ impl App {if has_answer_text(&self.assistant_buf) {self.flush_assistant();}+ self.starting.clear();self.turn = (index, max);}+ StreamEvent::ToolCallStarted { id, name } => {+ // Commit buffered prose/reasoning so it renders above the+ // in-progress throbber, matching the grouped-call ordering.+ self.flush_assistant();+ if !self.starting.iter().any(|(sid, _)| sid == &id) {+ self.starting.push((id, name));+ }+ }StreamEvent::ToolCall { id, name, args } => {+ // The full call (with parsed args) supersedes its in-progress+ // throbber.+ self.starting.retain(|(sid, _)| sid != &id);// Awaiting a subagent is a long block: show a live throbber row// (advanced each render tick) instead of a static grouped row,// cleared when its result arrives.@@ -3607,6 +3625,7 @@ fn rebuild_transcript(app: &mut App) {app.transcript.clear();app.tool_group = None;app.grouped_ids.clear();+ app.starting.clear();app.groups.clear();app.reasoning_blocks.clear();app.subagent_blocks.clear();@@ -4021,6 +4040,19 @@ fn draw(f: &mut Frame, app: &mut App) {),]));}+ // In-progress tool calls whose arguments are still streaming: a throbber+ // trails the prose until the full call (with args) arrives and renders its+ // own row.+ for (_, name) in &app.starting {+ let frame = SPINNER[app.spinner_frame % SPINNER.len()];+ lines.push(Line::from(vec![+ Span::styled(format!("{frame} "), Style::new().cyan()),+ Span::styled(+ format!("Preparing {name}"),+ Style::new().cyan().dim(),+ ),+ ]));+ }// Live subagent panels, streaming prose, and awaiting throbbers above have// no transcript index; they're all appended after the transcript loop.row_index.resize(lines.len(), None);@@ -5269,6 +5301,50 @@ mod tests {);}+ #[test]+ fn tool_call_started_throbber_shows_then_clears_on_full_call() {+ use ratatui::{backend::TestBackend, Terminal};+ let render = |app: &mut App| -> Vec<String> {+ let mut terminal = Terminal::new(TestBackend::new(60, 30)).unwrap();+ terminal.draw(|f| super::draw(f, app)).unwrap();+ let buf = terminal.backend().buffer().clone();+ (0..buf.area.height)+ .map(|y| {+ (0..buf.area.width)+ .map(|x| buf[(x, y)].symbol())+ .collect::<String>()+ })+ .collect()+ };++ let mut app = test_app();+ // Arguments still streaming: only the in-progress signal has arrived.+ app.apply(StreamEvent::ToolCallStarted {+ id: "c1".into(),+ name: "write".into(),+ });+ let rows = render(&mut app);+ assert!(+ rows.iter().any(|r| r.contains("Preparing write")),+ "throbber must show while args stream:\n{}",+ rows.join("\n")+ );++ // Full call (parsed args) supersedes the throbber and renders its row.+ app.apply(StreamEvent::ToolCall {+ id: "c1".into(),+ name: "write".into(),+ args: json!({ "path": "a.txt", "content": "hi" }),+ });+ let rows = render(&mut app);+ assert!(+ !rows.iter().any(|r| r.contains("Preparing write")),+ "throbber must clear once the full call arrives:\n{}",+ rows.join("\n")+ );+ assert!(app.starting.is_empty());+ }+#[test]fn reasoning_folds_before_await_subagent() {// A reasoning model that thinks and then awaits a subagent must fold