Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): stream reasoning_content as dimmed <think> in TUI
Akarshan Biswasf52d8630a968
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex 218c6c555..8182d2566 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -473,9 +473,22 @@ struct SseAccumulator {tool_calls: Vec<ToolCallAccum>,finish_reason: Option<String>,usage: Option<serde_json::Value>,+ /// A `<think>` boundary was streamed for `reasoning_content` and not yet+ /// 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,}impl SseAccumulator {+ fn close_reasoning(&mut self, events: &mpsc::UnboundedSender<StreamEvent>) {+ if self.reasoning_open {+ self.reasoning_open = false;+ let _ = events.send(StreamEvent::Token {+ text: "</think>".to_string(),+ });+ }+ }+/// Parse one raw SSE line (`data: {...}`); non-`data:`/blank lines are ignored.fn ingest_line(&mut self, line: &str, events: &mpsc::UnboundedSender<StreamEvent>) {if let Some(rest) = line.trim_end_matches('\r').strip_prefix("data:") {@@ -511,14 +524,30 @@ impl SseAccumulator {if let Some(fr) = choice.get("finish_reason").and_then(|v| v.as_str()) {self.finish_reason = Some(fr.to_string());+ self.close_reasoning(events);}let Some(delta) = choice.get("delta") else {return;};+ if let Some(text) = delta.get("reasoning_content").and_then(|v| v.as_str()) {+ if !text.is_empty() {+ if !self.reasoning_open {+ self.reasoning_open = true;+ let _ = events.send(StreamEvent::Token {+ text: "<think>".to_string(),+ });+ }+ let _ = events.send(StreamEvent::Token {+ text: text.to_string(),+ });+ }+ }+if let Some(text) = delta.get("content").and_then(|v| v.as_str()) {if !text.is_empty() {+ self.close_reasoning(events);self.content.push_str(text);let _ = events.send(StreamEvent::Token {text: text.to_string(),@@ -697,6 +726,64 @@ mod tests {assert_eq!(tokens, vec!["Hel", "lo"]);}+ #[test]+ fn reasoning_content_streams_as_think_wrapped_tokens_but_stays_out_of_content() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "reasoning_content": "let me " } }] }).to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": { "reasoning_content": "think" } }] }).to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": { "content": "answer" } }] }).to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": {}, "finish_reason": "stop" }] }).to_string(),+ &tx,+ );++ // Reasoning must not leak into the reconstructed message sent back to the+ // model as history; only the answer prose is persisted.+ let completion = acc.into_completion();+ assert_eq!(completion["choices"][0]["message"]["content"], "answer");++ drop(tx);+ let mut tokens = Vec::new();+ while let Ok(StreamEvent::Token { text }) = rx.try_recv() {+ tokens.push(text);+ }+ assert_eq!(tokens, vec!["<think>", "let me ", "think", "</think>", "answer"]);+ }++ #[test]+ fn reasoning_only_completion_closes_the_open_think_block() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "reasoning_content": "hmm" } }] }).to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": {}, "finish_reason": "stop" }] }).to_string(),+ &tx,+ );++ let completion = acc.into_completion();+ assert!(completion["choices"][0]["message"]["content"].is_null());++ drop(tx);+ let mut tokens = Vec::new();+ while let Ok(StreamEvent::Token { text }) = rx.try_recv() {+ tokens.push(text);+ }+ assert_eq!(tokens, vec!["<think>", "hmm", "</think>"]);+ }+#[test]fn reassembles_tool_call_arguments_split_across_deltas() {let (tx, _rx) = sink();diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex f554734b1..daf2a5fda 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -2328,7 +2328,8 @@ fn draw(f: &mut Frame, app: &mut App) {if !last_blank {lines.push(Line::raw(""));}- // Live tail: strip reasoning tags so partial streaming stays clean.+ // Live tail: same renderer as finalized messages, so an open+ // (unterminated) <think> block dims and grows during streaming.lines.extend(tail);}}@@ -2660,7 +2661,7 @@ mod tests {parse_command, render_table, run_command, split_reasoning, summarize_result,tool_activity, tool_finished, transcript_top_padding, App, Pending, DIFF_MAX_ROWS,};- use ratatui::text::Line;+ use ratatui::{style::Modifier, text::Line};use crate::core::agent::events::StreamEvent;use crate::core::agent::tools::gate::PermissionDecision;use serde_json::json;@@ -2786,6 +2787,30 @@ mod tests {assert_eq!(segs, vec![(true, "reasoning tail".to_string())]);}+ #[test]+ fn live_tail_dims_open_think_block_instead_of_stripping() {+ use ratatui::{backend::TestBackend, Terminal};+ let mut app = test_app();+ app.assistant_buf = "<think>pondering the answer".to_string();+ let mut terminal = Terminal::new(TestBackend::new(60, 30)).unwrap();+ terminal.draw(|f| super::draw(f, &mut app)).unwrap();+ let buf = terminal.backend().buffer().clone();++ let mut found_dim = false;+ for y in 0..buf.area.height {+ let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();+ if row.contains("pondering") {+ let x = row.find("pondering").unwrap() as u16;+ assert!(+ buf[(x, y)].style().add_modifier.contains(Modifier::DIM),+ "open <think> content must render dimmed while streaming"+ );+ found_dim = true;+ }+ }+ assert!(found_dim, "open <think> content must still appear in the live tail");+ }+#[test]fn long_user_prompt_wraps_in_transcript() {use ratatui::{backend::TestBackend, Terminal};