Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): stream native reasoning_content as Reasoning events, keep out of answer/history
Akarshan Biswascd5c40c5a075
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 1857a5b52..1e96fadd9 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -9,6 +9,13 @@pub enum StreamEvent {/// A streamed content delta from the model.Token { text: String },+ /// A streamed reasoning delta, carried natively when the upstream exposes+ /// it as a dedicated field (`reasoning_content`). Display-only: reasoning+ /// never joins the assistant `content` that is resent as history, and it+ /// must never leak into piped stdout. Providers that instead inline+ /// `<think>` tags in `content` stream those through [`Token`]; consumers+ /// fall back to stripping the tags manually.+ Reasoning { text: String },/// A new orchestration turn began (`index` is 1-based; `max` is the turn/// cap, `0` when the run is unbounded, which is the normal case).Step { index: u32, max: u32 },@@ -236,6 +243,12 @@ mod tests {assert_eq!(v, json!({ "type": "token", "text": "hi" }));}+ #[test]+ fn reasoning_serializes_with_snake_case_tag() {+ let v = serde_json::to_value(StreamEvent::Reasoning { text: "hmm".into() }).unwrap();+ assert_eq!(v, json!({ "type": "reasoning", "text": "hmm" }));+ }+#[test]fn step_serializes_with_snake_case_tag() {let v = serde_json::to_value(StreamEvent::Step { index: 1, max: 8 }).unwrap();diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex 273984bf3..69ecfa2d1 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -640,10 +640,6 @@ 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,/// 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@@ -652,15 +648,6 @@ struct SseAccumulator {}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:") {@@ -710,22 +697,20 @@ 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;};+ // Native reasoning: providers exposing a dedicated `reasoning_content`+ // field stream it as `Reasoning` events, never as content tokens, so+ // consumers get the boundary for free instead of re-parsing synthetic+ // `<think>` tags. Providers that inline tags in `content` still flow+ // through `Token`; consumers keep the tag-stripping fallback for them.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 {+ let _ = events.send(StreamEvent::Reasoning {text: text.to_string(),});}@@ -733,7 +718,6 @@ impl SseAccumulator {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(),@@ -1170,7 +1154,7 @@ mod tests {}#[test]- fn reasoning_content_streams_as_think_wrapped_tokens_but_stays_out_of_content() {+ fn reasoning_content_streams_as_native_reasoning_events_and_stays_out_of_content() {let (tx, mut rx) = sink();let mut acc = SseAccumulator::default();acc.ingest(@@ -1196,15 +1180,23 @@ mod tests {assert_eq!(completion["choices"][0]["message"]["content"], "answer");drop(tx);+ let mut reasoning = Vec::new();let mut tokens = Vec::new();- while let Ok(StreamEvent::Token { text }) = rx.try_recv() {- tokens.push(text);+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::Reasoning { text } => reasoning.push(text),+ StreamEvent::Token { text } => tokens.push(text),+ _ => {}+ }}- assert_eq!(tokens, vec!["<think>", "let me ", "think", "</think>", "answer"]);+ // Native events: no synthetic <think> wrapper tokens on the content+ // stream, so a consumer never has to re-parse tags it did not receive.+ assert_eq!(reasoning, vec!["let me ", "think"]);+ assert_eq!(tokens, vec!["answer"]);}#[test]- fn reasoning_only_completion_closes_the_open_think_block() {+ fn reasoning_only_completion_emits_reasoning_and_no_tokens() {let (tx, mut rx) = sink();let mut acc = SseAccumulator::default();acc.ingest(@@ -1220,11 +1212,41 @@ mod tests {assert!(completion["choices"][0]["message"]["content"].is_null());drop(tx);+ let mut reasoning = Vec::new();let mut tokens = Vec::new();- while let Ok(StreamEvent::Token { text }) = rx.try_recv() {- tokens.push(text);+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::Reasoning { text } => reasoning.push(text),+ StreamEvent::Token { text } => tokens.push(text),+ _ => {}+ }+ }+ assert_eq!(reasoning, vec!["hmm"]);+ assert!(tokens.is_empty(), "no content tokens for a reasoning-only turn: {tokens:?}");+ }++ /// Providers that inline `<think>` tags in `content` (no reasoning_content+ /// field) keep streaming through Token untouched: the tag-stripping+ /// fallback lives in the consumers.+ #[test]+ fn inline_think_tags_in_content_pass_through_as_tokens() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "content": "<think>hmm</think>answer" } }] })+ .to_string(),+ &tx,+ );+ drop(tx);+ let mut tokens = Vec::new();+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::Token { text } => tokens.push(text),+ StreamEvent::Reasoning { .. } => panic!("no native reasoning here"),+ _ => {}+ }}- assert_eq!(tokens, vec!["<think>", "hmm", "</think>"]);+ assert_eq!(tokens, vec!["<think>hmm</think>answer"]);}#[test]diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 4aa62a72f..f8db7d836 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1258,6 +1258,12 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {print!("{text}");let _ = std::io::stdout().flush();}+ // Reasoning is progress, not answer: dimmed on stderr so piping stdout+ // yields only the real completion.+ StreamEvent::Reasoning { text } => {+ eprint!("\x1b[2m{text}\x1b[0m");+ let _ = std::io::stderr().flush();+ }StreamEvent::Step { index, max } => match max {0 => eprintln!("\n\x1b[2m[turn {index}]\x1b[0m"),m => eprintln!("\n\x1b[2m[turn {index}/{m}]\x1b[0m"),diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex 876cfb11f..3200b200c 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -58,6 +58,9 @@ impl RunReport {self.partial.clear();}StreamEvent::Token { text } => self.partial.push_str(text),+ // Reasoning is display-only: it must not enter the piped/plain-text+ // report answer, which is reserved for the final completion.+ StreamEvent::Reasoning { .. } => {}StreamEvent::TurnUsage { usage } => {self.prompt_tokens += usage.prompt_tokens.unwrap_or(0);self.completion_tokens += usage.completion_tokens.unwrap_or(0);diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 094af7f02..8b2da04b5 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -1132,6 +1132,14 @@ struct App {/// In-progress assistant text for the current turn, flushed on the next/// step/tool/terminal event.assistant_buf: String,+ /// Reasoning streamed natively via `StreamEvent::Reasoning` since the last+ /// flush, each segment anchored to the `assistant_buf` offset it arrived at.+ /// Kept apart from `assistant_buf` so it is never wrapped into the wire+ /// history: it is display-only, folded like `<think>` blocks. Anchoring+ /// (rather than one flat buffer) is what keeps a turn that interleaves+ /// reasoning with prose in emission order, and what lets `reasoning_open`+ /// tell "still reasoning" from "prose has started".+ reasoning_segs: Vec<ReasoningSeg>,/// The current run of consecutive collapsible tool calls, rendered as one/// transcript row that updates in real time and finalizes to a short summary./// edit/write are excluded (they render their own diff panel).@@ -1513,6 +1521,7 @@ impl App {display_log: Vec::new(),journal_writer: None,assistant_buf: String::new(),+ reasoning_segs: Vec::new(),tool_group: None,grouped_ids: std::collections::HashSet::new(),groups: Vec::new(),@@ -1653,6 +1662,7 @@ impl App {self.expanded.clear();self.reveal = None;self.assistant_buf.clear();+ self.reasoning_segs.clear();self.message_queue.clear();self.pending_queue.clear();self.ask_queue.clear();@@ -1752,7 +1762,10 @@ impl App {}fn flush_assistant(&mut self) {- let text = self.assistant_buf.trim_end().to_string();+ let segs = std::mem::take(&mut self.reasoning_segs);+ let text = fold_native_reasoning(&self.assistant_buf, &segs)+ .trim_end()+ .to_string();self.assistant_buf.clear();// The buffered stream is committed: any open reasoning window closes// (its elapsed time was stashed when the block itself closed, so this@@ -1765,9 +1778,9 @@ impl App {}// Model prose ends the current run of tool calls.self.finalize_tool_group();- // Journaled with its `<think>` markers intact: this is the only place the- // reasoning exists (it is kept out of `history` on purpose), and the- // replay folds it exactly as the live turn did.+ // Native reasoning is already folded into `text` as wrapped blocks at the+ // offsets it streamed at. Display-logged here (out of `history` on+ // purpose) so the replay folds it like the live turn did.self.display_log.push(DisplayEntry::Assistant {text: text.clone(),});@@ -2028,7 +2041,27 @@ impl App {/// stretch of a run that puts nothing on screen, so the header badge is the/// only place progress can show.fn is_thinking(&self) -> bool {- self.status != Status::Idle && !self.show_reasoning && thinking_open(&self.assistant_buf)+ self.status != Status::Idle && !self.show_reasoning && self.reasoning_open()+ }++ /// True while the model is mid-reasoning: either a `<think>` block is live+ /// in the answer buffer (inline-tag providers) or the newest native segment+ /// is still at the tail, i.e. no content token has arrived since+ /// (`reasoning_content` providers). The tail check is what closes the window+ /// when prose starts, since native segments live on until the next flush.+ fn reasoning_open(&self) -> bool {+ thinking_open(&self.assistant_buf)+ || self+ .reasoning_segs+ .last()+ .is_some_and(|seg| seg.at == self.assistant_buf.len())+ }++ /// The live assistant text with native reasoning folded in as wrapped blocks,+ /// exactly as `flush_assistant` will commit it. Lets the shared renderer+ /// treat native and inline-tag reasoning identically while streaming.+ fn live_assistant_text(&self) -> String {+ fold_native_reasoning(&self.assistant_buf, &self.reasoning_segs)}/// Header status while a turn is running with reasoning folding on:@@ -2037,7 +2070,7 @@ impl App {/// plain `[working]`) once the model is working again. `None` when no/// reasoning has happened recently this turn.fn reasoning_status(&self) -> Option<(String, Style)> {- if thinking_open(&self.assistant_buf) {+ if self.reasoning_open() {Some(("thinking".to_string(), Style::new().yellow().bold()))} else {// The summary is transient: it lasts only `THOUGHT_FOR_TTL` after the@@ -3068,10 +3101,13 @@ impl App {StreamEvent::Token { text } => {self.assistant_buf.push_str(&text);// Track the live thinking state so the header can fold reasoning- // to `[thinking]` / `[thought for Ns]`. Start the timer when a- // block opens; close it (stashing the duration) once the block- // closes or the tool group proceeds.- let open = thinking_open(&self.assistant_buf);+ // to `[thinking]` / `[thought for Ns]`. Start the timer when+ // reasoning is open; close it (stashing the duration) once the+ // block ends. `reasoning_open` covers both inline ` think>` tags+ // and native reasoning_buf, so a content token after reasoning+ // closes the window (and prose arriving with no reasoning leaves+ // it closed).+ let open = self.reasoning_open();if open && self.thinking_since.is_none() {self.thinking_since = Some(Instant::now());} else if !open {@@ -3088,6 +3124,23 @@ impl App {self.finalize_tool_group();}}+ StreamEvent::Reasoning { text } => {+ // Native reasoning stays out of the answer buffer entirely; it is+ // folded into the display log on the next flush. Deltas that+ // arrive with no prose in between extend the open segment;+ // reasoning after prose starts a new one, so the timeline keeps+ // emission order instead of hoisting every thought to the top.+ if !text.is_empty() {+ let at = self.assistant_buf.len();+ match self.reasoning_segs.last_mut() {+ Some(seg) if seg.at == at => seg.text.push_str(&text),+ _ => self.reasoning_segs.push(ReasoningSeg { at, text }),+ }+ if self.thinking_since.is_none() {+ self.thinking_since = Some(Instant::now());+ }+ }+ }StreamEvent::Step { index, max } => {// Only flush (and thereby close the tool group) once the model// has produced answer prose; a turn that only reasoned or only@@ -4745,6 +4798,49 @@ fn split_reasoning(text: &str) -> Vec<(bool, String)> {out}+/// One stretch of natively streamed reasoning, anchored to the byte offset in+/// `App::assistant_buf` it arrived at, so it can be folded back into the answer+/// text in emission order.+#[derive(Debug, Clone, PartialEq)]+struct ReasoningSeg {+ at: usize,+ text: String,+}++/// Splice native reasoning segments into `prose` as `<think>` blocks at the+/// offsets they streamed at, yielding the one string form both the live renderer+/// and the display journal use. Offsets come from `prose.len()` at emission time,+/// so they are always char boundaries and always ascending.+fn fold_native_reasoning(prose: &str, segs: &[ReasoningSeg]) -> String {+ if segs.is_empty() {+ return prose.to_string();+ }+ let extra: usize = segs.iter().map(|s| s.text.len() + 16).sum();+ let mut out = String::with_capacity(prose.len() + extra);+ let mut last = 0;+ for seg in segs {+ let at = seg.at.min(prose.len());+ out.push_str(&prose[last..at]);+ if !seg.text.trim().is_empty() {+ out.push_str("<think>");+ out.push_str(escape_think_tags(seg.text.trim_end()).trim_end());+ out.push_str("</think>");+ }+ last = at;+ }+ out.push_str(&prose[last..]);+ out+}++/// Neutralize `<think>`-family tags inside reasoning text before it is wrapped in+/// one. A model reasoning *about* thinking tags would otherwise close the block+/// early and have the rest of its thought rendered and journaled as answer prose.+fn escape_think_tags(text: &str) -> std::borrow::Cow<'_, str> {+ think_re().replace_all(text, |m: ®ex::Captures| {+ format!("<{}", &m[0][1..])+ })+}+/// True if `text` ends inside an unclosed ` think>` block (an opening tag whose/// matching close has not yet streamed). Used to show `[thinking]` while/// reasoning streams. Re-uses the same tag matcher as `split_reasoning`.@@ -8856,6 +8952,7 @@ fn rebuild_transcript(app: &mut App) {app.expanded.clear();app.reveal = None;app.assistant_buf.clear();+ app.reasoning_segs.clear();app.last_kind = Kind::None;if !app.display_log.is_empty() {let logged = std::mem::take(&mut app.display_log);@@ -8920,6 +9017,7 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value) {app.expanded.clear();app.reveal = None;app.assistant_buf.clear();+ app.reasoning_segs.clear();app.turn = (0, 0);app.tokens = 0;app.scrollback = 0;@@ -9375,16 +9473,19 @@ fn draw(f: &mut Frame, app: &mut App) {// Streaming prose and the awaiting throbbers have no transcript index; they// are rebuilt every frame and ride along as one trailing segment.let mut tail: Vec<Line<'static>> = Vec::new();- if !app.assistant_buf.is_empty() {- let live = live_assistant_lines(&app.assistant_buf, width, !app.show_reasoning);+ if !app.assistant_buf.is_empty() || !app.reasoning_segs.is_empty() {+ // Native reasoning is folded into a wrapped block beside the live text+ // so the shared renderer dims/folds it exactly like inline-tag providers.+ let live_text = app.live_assistant_text();+ let live = live_assistant_lines(&live_text, width, !app.show_reasoning);if !live.is_empty() {// Mirror flush_assistant's `gap(Kind::Prose)` so the separator above- // streaming prose is present live, not only once it's finalized.+ // streaming prose is present live, not only once it is finalized.if !trailing_blank(&tail, &app.transcript, width) {tail.push(Line::raw(""));}// Live tail: same renderer as finalized messages, so an open- // (unterminated) <think> block dims and grows during streaming.+ // (unterminated) wrapped reasoning block dims and grows during streaming.tail.extend(live);}}@@ -10932,7 +11033,7 @@ fn input_box(app: &App) -> Paragraph<'static> {// synonyms in orange while a reasoning block streams -- so the row// reads alive without shifting under the eye.let step = app.spinner_frame / WORD_ROTATE_FRAMES;- let (word, style) = if thinking_open(&app.assistant_buf) {+ let (word, style) = if app.reasoning_open() {(THINKING_WORDS[step % THINKING_WORDS.len()],Style::new().fg(THINKING_ORANGE).italic(),@@ -17339,6 +17440,139 @@ mod tests {assert!(row.contains(SPINNER[5]), "expected frame 5 glyph: {row:?}");}+ /// Native reasoning events (a dedicated `reasoning_content` field) drive the+ /// same orange thinking placeholder as inline `<`> tags, are folded into the+ /// transcript like a wrapped block on flush, and never enter the wire answer.+ #[test]+ fn native_reasoning_drives_thinking_placeholder_and_folds_on_flush() {+ let mut app = test_app();+ app.submit_user("go".into());+ app.apply(StreamEvent::Reasoning {+ text: "ponder the plan".into(),+ });+ // Orange thinking synonyms while reasoning streams.+ let row = render_rows(&mut app, 80, 12)+ .into_iter()+ .find(|r| r.contains("(Esc to cancel, type to queue next message)"))+ .expect("running placeholder present");+ assert!(+ THINKING_WORDS.iter().any(|w| row.contains(w)),+ "expected a thinking synonym while reasoning: {row:?}"+ );+ // The answer arrives: reasoning stays folded into a summary row.+ app.apply(StreamEvent::Token {+ text: "Here is the answer".into(),+ });+ app.on_done("stop".into(), None);+ assert_eq!(app.reasoning_blocks.len(), 1, "reasoning folded into one block");+ // The wire history carries the answer without the reasoning.+ let wire = app+ .history+ .iter()+ .map(serde_json::Value::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(wire.contains("Here is the answer"), "answer missing: {wire}");+ assert!(!wire.contains("ponder the plan"), "reasoning leaked into history: {wire}");+ }++ /// The `[thinking]` badge and the orange placeholder must close when the+ /// answer starts streaming: native segments live until the next flush, so+ /// only the "newest segment is still at the tail" check can tell the two+ /// apart. Without it the badge shimmered through the whole answer and+ /// `[thought for Ns]` never appeared for a `reasoning_content` provider.+ #[test]+ fn native_reasoning_badge_closes_once_prose_starts() {+ let mut app = test_app();+ app.submit_user("go".into());+ app.apply(StreamEvent::Reasoning { text: "ponder".into() });+ assert_eq!(+ app.reasoning_status().map(|(w, _)| w),+ Some("thinking".to_string())+ );+ assert!(app.is_thinking(), "reasoning is live");+ app.apply(StreamEvent::Token { text: "Answer".into() });+ assert!(!app.is_thinking(), "prose has started");+ assert_eq!(+ app.reasoning_status().map(|(w, _)| w),+ Some("thought for 0s".to_string()),+ "the closed block reports its duration"+ );+ }++ fn detail_text(block: &super::ReasoningBlock) -> String {+ block+ .detail+ .iter()+ .map(|l| {+ l.spans+ .iter()+ .map(|sp| sp.content.as_ref())+ .collect::<String>()+ })+ .collect::<Vec<_>>()+ .join(" ")+ }++ /// Reasoning that mentions a `</think>` tag must not close the block it is+ /// wrapped in and spill the rest of the thought into the answer.+ #[test]+ fn native_reasoning_mentioning_a_close_tag_stays_reasoning() {+ let mut app = test_app();+ app.submit_user("go".into());+ app.apply(StreamEvent::Reasoning {+ text: "the </think> tag is tricky".into(),+ });+ app.on_done("stop".into(), None);+ let rows = render_rows(&mut app, 80, 30).join("\n");+ assert!(+ !rows.contains("tag is tricky"),+ "reasoning rendered as answer prose: {rows}"+ );+ assert_eq!(app.reasoning_blocks.len(), 1, "one folded reasoning block");+ assert!(+ detail_text(&app.reasoning_blocks[0]).contains("</think>"),+ "the tag is neutralized, not dropped: {}",+ detail_text(&app.reasoning_blocks[0])+ );+ }++ /// Interleaved reasoning keeps emission order: each stretch folds where it+ /// streamed instead of every thought being hoisted above all the prose.+ #[test]+ fn interleaved_native_reasoning_keeps_emission_order() {+ let mut app = test_app();+ app.submit_user("go".into());+ app.apply(StreamEvent::Reasoning { text: "first thought".into() });+ app.apply(StreamEvent::Token { text: "Part one.".into() });+ app.apply(StreamEvent::Reasoning { text: "second thought".into() });+ app.apply(StreamEvent::Token { text: " Part two.".into() });+ app.on_done("stop".into(), None);+ assert_eq!(app.reasoning_blocks.len(), 2, "two separate stretches");+ let DisplayEntry::Assistant { text } = app+ .display_log+ .iter()+ .rev()+ .find(|e| matches!(e, DisplayEntry::Assistant { .. }))+ .expect("assistant entry journaled")+ else {+ unreachable!()+ };+ assert_eq!(+ text,+ "<think>first thought</think>Part one.<think>second thought</think> Part two."+ );+ // The wire answer carries neither thought.+ let wire = app+ .history+ .iter()+ .map(serde_json::Value::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(wire.contains("Part one. Part two."), "answer missing: {wire}");+ assert!(!wire.contains("thought"), "reasoning leaked into history: {wire}");+ }+#[test]fn compact_tokens_keeps_a_stable_width() {assert_eq!(compact_tokens(0), "0");