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.

feat(agent-tui): stream open reasoning into the live tail behind a config gate

Akarshan Biswas0ee95f15ac0b
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
index b96ca3302..b36b4d85a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -948,6 +948,32 @@ Denies the prioritize_backends command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-probe-backend-load`
+
+</td>
+<td>
+
+Enables the probe_backend_load command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-probe-backend-load`
+
+</td>
+<td>
+
+Denies the probe_backend_load command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-read-gguf-metadata`
</td>
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
index 494ee500a..eb6be2a95 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
@@ -702,6 +702,18 @@
"const": "deny-prioritize-backends",
"markdownDescription": "Denies the prioritize_backends command without any pre-configured scope."
},
+ {
+ "description": "Enables the probe_backend_load command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-probe-backend-load",
+ "markdownDescription": "Enables the probe_backend_load command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the probe_backend_load command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-probe-backend-load",
+ "markdownDescription": "Denies the probe_backend_load command without any pre-configured scope."
+ },
{
"description": "Enables the read_gguf_metadata command without any pre-configured scope.",
"type": "string",
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 664000ff5..b145caf20 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -26,6 +26,9 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# # content as reasoning; they render and
# # are resent as ordinary prose. On by
# # default
+# stream_reasoning = false # stop streaming reasoning into the TUI
+# # live tail while it folds; only the
+# # [thinking] badge shows it. On by default
#
# [providers.my-provider]
# api_key = "sk-..."
@@ -57,6 +60,11 @@ struct GlobalConfigToml {
/// mechanism and is unaffected.
#[serde(default, skip_serializing_if = "Option::is_none")]
think_tags: Option<bool>,
+ /// Stream reasoning into the TUI live tail while it is still folded. `None`
+ /// = the default, on. Unrelated to `[agent].show_reasoning`, which unfolds
+ /// reasoning for good.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ stream_reasoning: Option<bool>,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
@@ -192,6 +200,19 @@ pub(crate) fn think_tags_enabled() -> bool {
.unwrap_or(true)
}
+/// Whether the TUI streams reasoning into its live tail while folding is on
+/// (`stream_reasoning` in `~/.jan/config.toml`), defaulting to on. `false` keeps
+/// a folded block off screen entirely, leaving the header badge to stand for it.
+///
+/// A display preference must never block startup, so an unreadable or malformed
+/// config yields the default rather than an error.
+pub(crate) fn stream_reasoning_enabled() -> bool {
+ load_raw()
+ .ok()
+ .and_then(|config| config.stream_reasoning)
+ .unwrap_or(true)
+}
+
/// Read `~/.jan/config.toml` into the raw TOML struct for editing. Missing file
/// -> default (empty); malformed file -> error, so a set never silently drops an
/// unparseable file's contents.
@@ -369,6 +390,26 @@ mod tests {
});
}
+ #[test]
+ fn stream_reasoning_default_on_and_read_from_the_toml_key() {
+ with_temp_home(|_| {
+ assert!(stream_reasoning_enabled(), "missing file -> streaming on");
+ let path = ensure_global_config().expect("ensure");
+ assert!(stream_reasoning_enabled(), "scaffolded file -> streaming on");
+
+ std::fs::write(&path, "stream_reasoning = false\n").unwrap();
+ assert!(!stream_reasoning_enabled());
+ std::fs::write(&path, "stream_reasoning = true\n").unwrap();
+ assert!(stream_reasoning_enabled());
+
+ std::fs::write(&path, "not valid toml [[[").unwrap();
+ assert!(
+ stream_reasoning_enabled(),
+ "an unreadable config keeps the default"
+ );
+ });
+ }
+
#[test]
fn ensure_scaffolds_and_is_idempotent() {
with_temp_home(|home| {
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 2dda97b18..2be88cfac 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -514,10 +514,15 @@ pub(crate) async fn call_openai_chat_completions(
.body(body.to_string())
.send()
.await
- .map_err(|e| format!("Upstream request failed: {e}"))?;
+ .map_err(|e| format!("Upstream request failed: {}", describe_request_error(&e)))?;
let status = resp.status();
- let text = resp.text().await.map_err(|e| e.to_string())?;
+ let text = resp.text().await.map_err(|e| {
+ format!(
+ "Reading the upstream response failed ({upstream_url}): {}",
+ describe_request_error(&e)
+ )
+ })?;
if status.is_success() {
return serde_json::from_str::<serde_json::Value>(&text)
@@ -569,6 +574,84 @@ pub(crate) fn is_context_overflow_error(err: &str) -> bool {
err.contains(CONTEXT_OVERFLOW_MARKER)
}
+/// 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
+/// connection, TLS mismatch, dropped socket) is one or more sources down and is
+/// otherwise lost to the user. Consecutive duplicates are collapsed: hyper and
+/// its io error often stringify identically.
+fn error_source_chain(err: &dyn std::error::Error) -> Vec<String> {
+ let mut chain = Vec::new();
+ let mut cur = err.source();
+ while let Some(e) = cur {
+ let msg = e.to_string();
+ if !msg.trim().is_empty() && chain.last() != Some(&msg) {
+ chain.push(msg);
+ }
+ cur = e.source();
+ }
+ chain
+}
+
+/// Names the proxy environment variables in force, without their values (they
+/// routinely carry credentials). A proxy set in the environment is a common
+/// reason a request fails for Jan and for nothing else, and it is invisible in
+/// the error itself.
+fn proxy_env_hint() -> Option<String> {
+ const VARS: &[&str] = &[
+ "HTTPS_PROXY",
+ "https_proxy",
+ "HTTP_PROXY",
+ "http_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ ];
+ let set: Vec<&str> = VARS
+ .iter()
+ .copied()
+ .filter(|name| {
+ std::env::var_os(name).is_some_and(|v| !v.to_string_lossy().trim().is_empty())
+ })
+ .collect();
+ (!set.is_empty()).then(|| format!("proxy env set: {}", set.join(", ")))
+}
+
+/// A failed HTTP request described well enough to act on: what stage failed, the
+/// `reqwest` message, its whole cause chain, and -- for a connect or timeout
+/// failure, where the environment is usually the culprit -- which proxy
+/// variables are set.
+pub(crate) fn describe_request_error(err: &reqwest::Error) -> String {
+ let stage = if err.is_timeout() {
+ "timed out"
+ } else if err.is_connect() {
+ "could not connect"
+ } else if err.is_redirect() {
+ "too many redirects"
+ } else if err.is_body() || err.is_decode() {
+ "response body failed"
+ } else if err.is_builder() {
+ "request could not be built"
+ } else {
+ "send failed"
+ };
+ let mut msg = format!("{stage}: {err}");
+ let chain = error_source_chain(err);
+ if !chain.is_empty() {
+ msg.push_str(&format!(" (caused by: {})", chain.join(" <- ")));
+ }
+ if let Some(status) = err.status() {
+ msg.push_str(&format!(" [HTTP {status}]"));
+ }
+ if err.is_connect() || err.is_timeout() {
+ if let Some(hint) = proxy_env_hint() {
+ msg.push_str(&format!(" [{hint}]"));
+ }
+ }
+ msg
+}
+
pub(crate) async fn stream_openai_chat_completions(
client: &Client,
upstream_url: &str,
@@ -607,7 +690,7 @@ pub(crate) async fn stream_openai_chat_completions(
.body(req_body.to_string())
.send()
.await
- .map_err(|e| format!("Upstream request failed: {e}"))?;
+ .map_err(|e| format!("Upstream request failed: {}", describe_request_error(&e)))?;
let status = resp.status();
if status.is_success() {
@@ -901,12 +984,22 @@ async fn consume_openai_sse(
resp: reqwest::Response,
events: &mpsc::UnboundedSender<StreamEvent>,
) -> Result<serde_json::Value, String> {
+ let url = resp.url().to_string();
let mut stream = resp.bytes_stream();
let mut buf = String::new();
let mut acc = SseAccumulator::default();
+ let mut bytes = 0usize;
while let Some(chunk) = stream.next().await {
- let chunk = chunk.map_err(|e| format!("Upstream stream error: {e}"))?;
+ // A stream that dies mid-response is the hardest case to tell apart from
+ // an empty answer, so the byte count so far goes in the message.
+ let chunk = chunk.map_err(|e| {
+ format!(
+ "Upstream stream error ({url}) after {bytes} bytes: {}",
+ describe_request_error(&e)
+ )
+ })?;
+ bytes += chunk.len();
buf.push_str(&String::from_utf8_lossy(&chunk));
drain_complete_lines(&mut buf, &mut acc, events);
}
@@ -936,6 +1029,86 @@ mod tests {
mpsc::unbounded_channel()
}
+ /// `reqwest` prints only its own layer, so the cause chain is where the
+ /// actual failure lives -- the whole point of `describe_request_error`.
+ #[test]
+ fn error_source_chain_lists_every_cause_and_collapses_repeats() {
+ #[derive(Debug)]
+ struct Err2(&'static str, Option<Box<Err2>>);
+ impl std::fmt::Display for Err2 {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.0)
+ }
+ }
+ impl std::error::Error for Err2 {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ self.1.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
+ }
+ }
+
+ // The outermost message is printed by the caller, so the chain starts at
+ // its first source; the repeated innermost layer collapses.
+ let inner = Err2("connection refused", None);
+ let middle = Err2("connection refused", Some(Box::new(inner)));
+ let connect = Err2("tcp connect error", Some(Box::new(middle)));
+ let outer = Err2("error sending request", Some(Box::new(connect)));
+ assert_eq!(
+ error_source_chain(&outer),
+ vec![
+ "tcp connect error".to_string(),
+ "connection refused".to_string()
+ ],
+ "sources only, consecutive duplicates collapsed"
+ );
+ assert!(
+ error_source_chain(&Err2("alone", None)).is_empty(),
+ "no sources -> nothing to add"
+ );
+ }
+
+ /// The reported error must name the stage and carry the OS-level reason, not
+ /// just the URL. Port 1 on loopback refuses without touching the network.
+ #[tokio::test]
+ async fn describe_request_error_names_the_stage_and_the_os_cause() {
+ let err = Client::new()
+ .post("http://127.0.0.1:1/v1/chat/completions")
+ .body("{}")
+ .send()
+ .await
+ .expect_err("loopback port 1 refuses");
+ let msg = describe_request_error(&err);
+ assert!(msg.starts_with("could not connect: "), "stage named: {msg}");
+ assert!(msg.contains("caused by: "), "cause chain present: {msg}");
+ assert!(
+ msg.to_lowercase().contains("refused") || msg.to_lowercase().contains("connect"),
+ "the OS reason survives: {msg}"
+ );
+ }
+
+ /// A proxy in the environment breaks Jan and nothing else, and never shows up
+ /// in the error. Names only: the values carry credentials.
+ #[test]
+ fn proxy_env_hint_names_set_variables_without_their_values() {
+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let prev = std::env::var_os("HTTPS_PROXY");
+ std::env::remove_var("HTTPS_PROXY");
+ let before = proxy_env_hint();
+
+ std::env::set_var("HTTPS_PROXY", "http://user:[email protected]:8080");
+ let hint = proxy_env_hint().expect("a set proxy is reported");
+ assert!(hint.contains("HTTPS_PROXY"), "names the variable: {hint}");
+ assert!(!hint.contains("secret"), "never prints the value: {hint}");
+
+ std::env::set_var("HTTPS_PROXY", " ");
+ assert_eq!(proxy_env_hint(), before, "a blank value is not a proxy");
+
+ match prev {
+ Some(v) => std::env::set_var("HTTPS_PROXY", v),
+ None => std::env::remove_var("HTTPS_PROXY"),
+ }
+ }
+
/// A model served both by a Jan desktop API server (reachable over HTTP) and
/// by local engine descriptors (no base_url) must always resolve to the
/// server. `HashMap` order is randomized, so the local entries outnumber the
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index a8286fd5d..11517cb3b 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -763,6 +763,10 @@ pub(crate) struct AgentSession {
pub limits: SessionLimits,
/// Whether the TUI expands `<think>` reasoning blocks (default false).
pub show_reasoning: bool,
+ /// Whether the TUI streams reasoning into the live tail while it folds
+ /// (`stream_reasoning` in `~/.jan/config.toml`, default true). Independent
+ /// of `show_reasoning`, which unfolds it for good.
+ pub stream_reasoning: bool,
/// Whether to resend a prior assistant turn's reasoning to the model
/// (default true). False drops `reasoning_content` from outgoing assistant
/// messages; the display journal still keeps reasoning for a resume.
@@ -939,6 +943,7 @@ fn prepare_agent_session(
max_session_tokens: cfg.budget.max_tokens.unwrap_or(DEFAULT_MAX_SESSION_TOKENS),
},
show_reasoning: cfg.agent.show_reasoning.unwrap_or(false),
+ stream_reasoning: crate::core::agent::global_config::stream_reasoning_enabled(),
send_reasoning: cfg.agent.send_reasoning.unwrap_or(true),
mcp_servers,
mcp_task,
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 80b7a9dfb..7aaf2d3be 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -1268,6 +1268,12 @@ struct App {
/// from `[agent].show_reasoning` in agent.toml (false). Ctrl-O toggles every
/// existing block between its summary row and full detail for the session.
show_reasoning: bool,
+ /// Whether reasoning streams into the live tail while folding is on.
+ /// Defaults from `stream_reasoning` in `~/.jan/config.toml` (true). The open
+ /// block shows its last `LIVE_REASONING_TAIL_LINES` lines and still folds to
+ /// a summary row when the turn commits; false shows nothing but the header
+ /// badge, as before. Orthogonal to `show_reasoning`, which unfolds for good.
+ stream_reasoning: bool,
/// Whether a prior assistant turn's reasoning is resent to the model.
/// Defaults from `[agent].send_reasoning` in agent.toml (true). False keeps
/// long chains of thought out of the request (and satisfies upstreams that
@@ -1673,6 +1679,7 @@ impl App {
reasoning_blocks: Vec::new(),
show_reasoning,
// Overwritten from the session config right after construction.
+ stream_reasoning: true,
send_reasoning: true,
expanded: std::collections::HashSet::new(),
reveal: None,
@@ -2189,11 +2196,15 @@ impl App {
.is_some_and(|closed| closed.elapsed() >= TODO_HIDE_AFTER)
}
- /// True while a reasoning block is streaming with folding on: the one
- /// stretch of a run that puts nothing on screen, so the header badge is the
- /// only place progress can show.
+ /// True while a reasoning block is streaming and nothing of it is on screen:
+ /// the one stretch of a run with no visible motion, which is what the
+ /// header's shimmering `[thinking]` badge stands in for. With
+ /// `stream_reasoning` on the tail itself is moving, so the badge stays flat.
fn is_thinking(&self) -> bool {
- self.status != Status::Idle && !self.show_reasoning && self.reasoning_open()
+ self.status != Status::Idle
+ && !self.show_reasoning
+ && !self.stream_reasoning
+ && self.reasoning_open()
}
/// True while the model is mid-reasoning: either a `<think>` block is live
@@ -5466,6 +5477,7 @@ pub async fn run(
smol_model,
limits,
show_reasoning,
+ stream_reasoning,
send_reasoning,
mcp_servers,
mcp_task,
@@ -5516,6 +5528,7 @@ pub async fn run(
repo_root,
);
app.smol_model = smol_model;
+ app.stream_reasoning = stream_reasoning;
app.send_reasoning = send_reasoning;
app.args = Some(args.clone());
// Adopt the session's startup run mode (e.g. `--plan`) so the header badge
@@ -9885,6 +9898,7 @@ fn draw(f: &mut Frame, app: &mut App) {
&app.reasoning_segs,
width,
!app.show_reasoning,
+ app.stream_reasoning,
);
if !live.is_empty() {
// Mirror flush_assistant's `gap(Kind::Prose)` so the separator above
@@ -13021,39 +13035,82 @@ mod tests {
}
#[test]
- fn live_tail_hides_open_think_block_and_shows_it_when_revealed() {
- use ratatui::{backend::TestBackend, Terminal};
+ fn live_tail_streams_open_reasoning_and_the_gate_hides_it() {
let mut app = test_app();
app.assistant_buf = "<think>pondering the answer".to_string();
- let render = |app: &mut App| {
- 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::<Vec<_>>()
- .join("\n")
- };
+ // Streaming is the default: a folded, still-open block shows its tail so
+ // the user can watch the thought form.
+ let streamed = render_rows(&mut app, 60, 30).join("\n");
+ assert!(
+ streamed.contains("pondering"),
+ "open reasoning streams by default: {streamed}"
+ );
- // Reasoning folding is the default: an open block is hidden from
- // the live tail (the header shows [thinking] instead).
- let hidden = render(&mut app);
+ // With the gate off only the header's [thinking] badge stands for it.
+ app.stream_reasoning = false;
+ let hidden = render_rows(&mut app, 60, 30).join("\n");
assert!(
!hidden.contains("pondering"),
- "open reasoning must be hidden by default"
+ "stream_reasoning = false hides the open block"
);
- // With show_reasoning on, the streaming reasoning renders dimmed as before.
+ // With show_reasoning on, folding is off entirely and it renders whole.
app.show_reasoning = true;
- let shown = render(&mut app);
+ let shown = render_rows(&mut app, 60, 30).join("\n");
assert!(shown.contains("pondering"), "revealed live tail must contain it");
}
+ /// A long chain of thought must not push the answer, or the conversation
+ /// above it, off the screen: the live tail keeps only the last few lines.
+ #[test]
+ fn live_tail_bounds_streaming_reasoning_to_its_last_lines() {
+ let body: String = (1..=20).map(|n| format!("step {n}\n")).collect();
+ let lines = super::live_assistant_lines(
+ &format!("<think>{body}"),
+ &[],
+ 60,
+ true,
+ true,
+ );
+ let text: Vec<String> = lines
+ .iter()
+ .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
+ .collect();
+ assert_eq!(text.len(), 6, "capped at the tail: {text:?}");
+ assert!(text[0].contains("step 15"), "starts at the tail: {text:?}");
+ assert!(text[5].contains("step 20"), "ends at the newest: {text:?}");
+ }
+
+ /// A block that already closed mid-turn folds to the very summary row the
+ /// commit will emit, so finalizing the turn does not move the transcript.
+ #[test]
+ fn live_tail_folds_a_closed_reasoning_run_to_its_summary_row() {
+ let lines = super::live_assistant_lines(
+ "<think>weighed it\ntwice</think>Here is the answer.",
+ &[],
+ 60,
+ true,
+ true,
+ );
+ let text: Vec<String> = lines
+ .iter()
+ .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
+ .collect();
+ assert!(
+ text.iter().any(|l| l.contains("reasoning (2 lines)")),
+ "closed run folds to a summary: {text:?}"
+ );
+ assert!(
+ !text.iter().any(|l| l.contains("weighed it")),
+ "closed run is not shown in full: {text:?}"
+ );
+ assert!(
+ text.iter().any(|l| l.contains("Here is the answer.")),
+ "prose still renders: {text:?}"
+ );
+ }
+
#[test]
fn header_shows_thinking_and_thought_for_status_when_folded() {
use ratatui::{backend::TestBackend, Terminal};
@@ -18595,9 +18652,9 @@ mod tests {
app.reasoning_status().map(|(w, _)| w),
Some("thinking".to_string())
);
- assert!(app.is_thinking(), "reasoning is live");
+ assert!(app.reasoning_open(), "reasoning is live");
app.apply(StreamEvent::Token { text: "Answer".into() });
- assert!(!app.is_thinking(), "prose has started");
+ assert!(!app.reasoning_open(), "prose has started");
assert_eq!(
app.reasoning_status().map(|(w, _)| w),
Some("thought for 0s".to_string()),
@@ -19787,8 +19844,11 @@ mod tests {
/// The animation is scoped to the state that needs it: a folded, streaming
/// reasoning block. Everything else keeps its flat badge.
#[test]
- fn only_folded_live_reasoning_animates_the_badge() {
+ fn only_invisible_live_reasoning_animates_the_badge() {
let mut app = test_app();
+ // Streaming reasoning puts the thought on screen, so the badge has
+ // nothing to stand in for; the shimmer is for the hidden case.
+ app.stream_reasoning = false;
assert!(!app.is_thinking(), "idle");
app.submit_user("hi".into());
assert!(!app.is_thinking(), "running, but nothing thinking yet");
@@ -19805,12 +19865,15 @@ mod tests {
});
assert!(!app.is_thinking(), "the block closed");
- // With reasoning shown inline the transcript itself is moving, so the
- // badge stays flat.
- app.show_reasoning = true;
+ // With reasoning on screen -- streamed into the live tail, or unfolded
+ // outright -- the transcript itself is moving, so the badge stays flat.
+ app.stream_reasoning = true;
app.apply(StreamEvent::Token {
text: "<think>more".into(),
});
+ assert!(!app.is_thinking(), "streamed reasoning needs no badge motion");
+ app.stream_reasoning = false;
+ app.show_reasoning = true;
assert!(!app.is_thinking(), "unfolded reasoning needs no badge motion");
}
diff --git a/src-tauri/src/core/cli/tui/markdown.rs b/src-tauri/src/core/cli/tui/markdown.rs
index c739d98af..38cee0be1 100644
--- a/src-tauri/src/core/cli/tui/markdown.rs
+++ b/src-tauri/src/core/cli/tui/markdown.rs
@@ -24,26 +24,47 @@ pub(super) fn format_assistant_lines(
lines
}
+/// Lines of an open reasoning block kept in the live tail: enough to see the
+/// thought moving without letting a long chain of thought push the answer, and
+/// the conversation above it, off the screen.
+const LIVE_REASONING_TAIL_LINES: usize = 6;
+
/// Live tail rendering for the in-progress assistant buffer. With reasoning
-/// folding on (`fold_reasoning`), an open (unterminated) think block is hidden
-/// entirely so the user sees only the answer prose stream, matching the
-/// `[thinking]` header state; once the tag closes (or prose begins) the rest
-/// renders as usual. When folding is off this is identical to
-/// `format_assistant_lines`, so the existing live-tail tests hold.
+/// folding on (`fold_reasoning`) the block is bounded rather than shown whole:
+/// the open (unterminated) one keeps its last [`LIVE_REASONING_TAIL_LINES`]
+/// lines when `stream_reasoning` is on, and a block that already closed shows
+/// the same summary row `push_assistant_blocks` will commit for it, so nothing
+/// jumps as the turn finalizes. With `stream_reasoning` off the open block is
+/// hidden entirely and only the `[thinking]` header stands for it. When folding
+/// is off this is identical to `format_assistant_lines`, so the existing
+/// live-tail tests hold.
pub(super) fn live_assistant_lines(
prose: &str,
segs: &[super::ReasoningSeg],
width: u16,
fold_reasoning: bool,
+ stream_reasoning: bool,
) -> Vec<Line<'static>> {
if !fold_reasoning {
return format_assistant_lines(prose, segs, width);
}
+ let runs = super::assistant_runs(prose, segs);
+ let last = runs.len().saturating_sub(1);
let mut lines = Vec::new();
- for (reasoning, seg) in super::assistant_runs(prose, segs) {
+ for (i, (reasoning, seg)) in runs.into_iter().enumerate() {
if reasoning {
- // Folded: the streaming content is hidden; nothing to show. (Once it
- // commits, `push_assistant_blocks` emits the summary row instead.)
+ // Only the trailing run can still be open; anything a later run
+ // follows has ended and folds to its summary row.
+ let body: Vec<&str> = seg.lines().filter(|l| !l.trim().is_empty()).collect();
+ if body.is_empty() {
+ continue;
+ }
+ if i < last {
+ lines.push(reasoning_summary_row(body.len()));
+ } else if stream_reasoning {
+ let tail = &body[body.len().saturating_sub(LIVE_REASONING_TAIL_LINES)..];
+ lines.extend(reasoning_detail_lines(&tail.join("\n")));
+ }
continue;
}
if !seg.trim().is_empty() {
@@ -1398,6 +1419,4 @@ mod tests {
.collect();
assert_eq!(joined, long);
}
-
}
-