Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): parse inline think tags per provider, off for providers that send reasoning separately
Akarshan Biswas80f282932e41
diff --git a/docs/src/pages/docs/agent/console.mdx b/docs/src/pages/docs/agent/console.mdxindex ef30c6dd9..4ad1ac1ea 100644--- a/docs/src/pages/docs/agent/console.mdx+++ b/docs/src/pages/docs/agent/console.mdx@@ -201,7 +201,8 @@ Two knobs in `agent.toml` and two in `~/.jan/config.toml` tune this:| --- | --- | --- | --- || `[agent].show_reasoning` | `agent.toml` | `false` | Unfold every reasoning block in the transcript by default. Still folds when off; <kbd>Ctrl</kbd>+<kbd>O</kbd> or a click expands a block either way || `[agent].send_reasoning` | `agent.toml` | `true` | Resend a prior turn's reasoning to the model with the conversation. Turn off for an upstream that rejects the field (Groq), or to keep chains of thought out of the context budget |-| `think_tags` | `~/.jan/config.toml` | `false` | Treat `<think>` tags in model content as reasoning (folded and resendable). Only for a provider that inlines its reasoning; a `reasoning_content` field needs no tags. Off renders tags as ordinary prose |+| `think_tags` | `~/.jan/config.toml` | per provider | Treat `<think>` tags in model content as reasoning (folded and resendable), for every provider. Unset, it is on for a custom OpenAI-compatible provider and off for `openai`, `anthropic` and `tokamak`, which send reasoning in its own field, and for the Anthropic, Google and Responses wire APIs. Off renders tags as ordinary prose |+| `parse_think_tags` | `[providers.<name>]` in `~/.jan/config.toml` | inherits `think_tags` | The same switch for one provider; it beats `think_tags` || `stream_reasoning` | `~/.jan/config.toml` | `true` | Stream an open reasoning block's last lines into the live tail. Off shows only the `[thinking]` badge |See [Project config](/docs/agent/project-config) for the `agent.toml` keys.diff --git a/src-tauri/src/core/agent/genai_bridge.rs b/src-tauri/src/core/agent/genai_bridge.rsindex 708899890..ec9be14e2 100644--- a/src-tauri/src/core/agent/genai_bridge.rs+++ b/src-tauri/src/core/agent/genai_bridge.rs@@ -203,10 +203,9 @@ fn options_from_body(body: &serde_json::Value) -> ChatOptions {capture_content: Some(true),capture_tool_calls: Some(true),capture_reasoning_content: Some(true),- // Providers that inline `<think>` tags in `content` instead of exposing a- // reasoning field get normalized into reasoning events too, so consumers- // see one shape regardless of provider.- normalize_reasoning_content: Some(true),+ // `normalize_reasoning_content` is deliberately unset: genai only honours+ // it on non-streaming OpenAI calls, and this bridge streams. Inline+ // `<think>` tags are split by the TUI, per provider (`think_tags`)...Default::default()}}diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex 7fbdca347..7831a00e9 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -27,10 +27,13 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # (same as passing --worktree); off by# # default, so the agent edits your checkout# think_tags = true # treat <think> tags in model content as-# # reasoning (folded, resent); only for a-# # provider that inlines them, since a-# # reasoning_content field needs no tags.-# # Off by default: tags render as prose+# # reasoning (folded, resent), for every+# # provider. Unset: on only for a custom+# # OpenAI-compatible provider; off for+# # openai, anthropic and tokamak, which+# # send reasoning in its own field. A+# # provider overrides it with+# # parse_think_tags in its own table# stream_reasoning = false # stop streaming reasoning into the TUI# # live tail while it folds; only the# # [thinking] badge shows it. On by default@@ -118,9 +121,10 @@ struct GlobalConfigToml {/// default, off. The "permanently on" answer to `--worktree`.#[serde(default, skip_serializing_if = "Option::is_none")]worktree: Option<bool>,- /// Parse `<think>` tags in model *content* as reasoning. `None` = the- /// default, off. Native `reasoning_content` streaming is a separate- /// mechanism and is unaffected.+ /// Parse `<think>` tags in model *content* as reasoning, for every+ /// provider. `None` = each provider's default (see+ /// `think_tags_enabled_for`). Native `reasoning_content` streaming is a+ /// separate 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`@@ -285,6 +289,13 @@ struct GlobalProviderEntry {/// session's `JAN_CUSTOM_HEADERS` beats a header of the same name here.#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]headers: BTreeMap<String, String>,+ /// Parse `<think>` tags in this provider's content as reasoning. `None`+ /// inherits the root `think_tags`, then the provider default. Named apart+ /// from the root key on purpose: a root `think_tags` appended to the end of+ /// the file lands in the last provider table, and must not silently become+ /// that provider's setting.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ parse_think_tags: Option<bool>,}/// Fields to update on a provider entry via [`set_provider`]. `None` leaves the@@ -527,20 +538,38 @@ pub(crate) fn hook_entries() -> Vec<tauri_plugin_agent_tools::tools::hooks::Hookload_raw().map(|config| config.hooks).unwrap_or_default()}-/// Whether inline `<think>` tags in model content are parsed as reasoning-/// (`think_tags` in `~/.jan/config.toml`), defaulting to off: reasoning arrives-/// in its own `reasoning_content` field, so a tag in content is the model-/// writing about tags. Off renders them verbatim, keeps them in the answer sent-/// back as history, and never folds them into a reasoning block; on is for a-/// provider that inlines its reasoning.+/// Providers known to send reasoning in its own `reasoning_content` field, so+/// tag parsing is off for them unless the user opts in. Anything else on the+/// OpenAI wire (a custom endpoint, a local server) may inline its reasoning.+const SEPARATE_REASONING_PROVIDERS: &[&str] = &["openai", "anthropic", "tokamak"];++/// Whether inline `<think>` tags in the content `provider` serves are parsed as+/// reasoning. `provider` is the one serving the active model and `api_type` its+/// wire API; `None` when nothing serves it.+///+/// Answered in this order: the provider's own `parse_think_tags`, the root+/// `think_tags` (every provider), then the default. The default is on only for+/// a custom OpenAI-compatible provider: the known providers send reasoning+/// separately, and a non-chat-completions wire API (`anthropic`, `google`,+/// `openai-responses`) carries it in typed blocks, so a tag in their content is+/// the model writing about tags.////// A display preference must never block startup, so an unreadable or malformed/// config yields the default rather than an error.-pub(crate) fn think_tags_enabled() -> bool {- load_raw()- .ok()- .and_then(|config| config.think_tags)- .unwrap_or(false)+pub(crate) fn think_tags_enabled_for(provider: Option<&str>, api_type: Option<&str>) -> bool {+ let Some(provider) = provider else {+ return false;+ };+ let config = load_raw().ok();+ config+ .as_ref()+ .and_then(|c| c.providers.get(provider))+ .and_then(|entry| entry.parse_think_tags)+ .or_else(|| config.as_ref().and_then(|c| c.think_tags))+ .unwrap_or_else(|| {+ !SEPARATE_REASONING_PROVIDERS.contains(&provider)+ && matches!(api_type, None | Some("openai"))+ })}/// Whether other projects' memory is listed and readable@@ -1052,20 +1081,52 @@ mod tests {}#[test]- fn think_tags_default_off_and_read_from_the_toml_key() {+ fn think_tags_default_follows_who_serves_the_model() {+ with_temp_home(|_| {+ // Providers known to send reasoning in its own field, and any+ // non-chat-completions wire API, never need tag parsing.+ for known in ["openai", "anthropic", "tokamak"] {+ assert!(!think_tags_enabled_for(Some(known), None), "{known}");+ }+ assert!(!think_tags_enabled_for(Some("mine"), Some("anthropic")));+ assert!(!think_tags_enabled_for(Some("mine"), Some("google")));+ assert!(!think_tags_enabled_for(Some("mine"), Some("openai-responses")));+ // A custom OpenAI-compatible endpoint may inline its reasoning.+ assert!(think_tags_enabled_for(Some("mine"), None));+ assert!(think_tags_enabled_for(Some("mine"), Some("openai")));+ // Nothing serves the model: nothing to parse for.+ assert!(!think_tags_enabled_for(None, None));+ });+ }++ #[test]+ fn think_tags_overrides_beat_the_default_provider_first() {with_temp_home(|_| {- assert!(!think_tags_enabled(), "missing file -> parsing off");let path = ensure_global_config().expect("ensure");- assert!(!think_tags_enabled(), "scaffolded file -> parsing off");+ assert!(think_tags_enabled_for(Some("mine"), None), "scaffold is neutral");- std::fs::write(&path, "think_tags = true\n").unwrap();- assert!(think_tags_enabled());+ // The root key is the user-wide answer for every provider.std::fs::write(&path, "think_tags = false\n").unwrap();- assert!(!think_tags_enabled());+ assert!(!think_tags_enabled_for(Some("mine"), None));+ std::fs::write(&path, "think_tags = true\n").unwrap();+ assert!(think_tags_enabled_for(Some("openai"), None));++ // A provider's own key beats the root key, both ways.+ std::fs::write(+ &path,+ "think_tags = true\n[providers.openai]\nparse_think_tags = false\n\+ [providers.mine]\nparse_think_tags = false\n",+ )+ .unwrap();+ assert!(!think_tags_enabled_for(Some("openai"), None));+ assert!(!think_tags_enabled_for(Some("mine"), None));+ std::fs::write(&path, "[providers.openai]\nparse_think_tags = true\n").unwrap();+ assert!(think_tags_enabled_for(Some("openai"), None));+ assert!(!think_tags_enabled_for(Some("anthropic"), None));std::fs::write(&path, "not valid toml [[[").unwrap();assert!(- !think_tags_enabled(),+ think_tags_enabled_for(Some("mine"), None),"an unreadable config keeps the default");});diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex ed03920dc..da94a68c7 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1836,10 +1836,6 @@ fn prepare_agent_session(None};- // `think_tags` is user-wide and read from free rendering functions, so it is- // applied to the process here, the one path every agent surface takes.- tui::set_think_tags_parsed(crate::core::agent::global_config::think_tags_enabled());-let permission_requests: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));let max_parallel_subagents = cfg.agentdiff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 4b332f07d..50f218451 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -6819,6 +6819,7 @@ impl App {fn set_model(&mut self, model: String) {self.model = model;self.refresh_context_window();+ self.sync_think_tags();// A model the session-scoped provider serves is this session's choice// only: its id names the session's endpoint, and saving it would start// the next native `jan` in this project on a model nothing it has@@ -6946,6 +6947,29 @@ impl App {resolved}+ /// Point the `<think>` tag gate at whoever serves the current model. The+ /// default differs per provider, so it follows the model across `/model`+ /// switches and provider reloads; rows already built keep the split they+ /// were built with.+ fn sync_think_tags(&mut self) {+ let gate = self.think_tags_gate();+ set_think_tags_parsed(gate);+ }++ /// Whether the current model's provider has its inline tags parsed.+ fn think_tags_gate(&mut self) -> bool {+ let provider = self.serving_provider();+ let api_type = provider.as_deref().and_then(|name| {+ let args = self.args.as_ref()?;+ let pc = args.provider_configs.try_lock().ok()?;+ pc.get(name)?.api_type.clone()+ });+ crate::core::agent::global_config::think_tags_enabled_for(+ provider.as_deref(),+ api_type.as_deref(),+ )+ }+/// The `/usage` bucket one request bills against.fn usage_key(&mut self) -> UsageKey {UsageKey {@@ -11033,8 +11057,8 @@ fn think_re() -> &'static regex::Regex {/// Whether inline `<think>` tags in model content are parsed as reasoning./// Process-wide rather than a session field because the split runs on every/// rendered row, from free functions a `Row` reaches with no session in hand.-/// Seeded once from `~/.jan/config.toml` by `set_think_tags_parsed`; `false`-/// until then, which is also the default.+/// Set from the serving provider's setting by `set_think_tags_parsed`; `false`+/// until then.static PARSE_THINK_TAGS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);#[cfg(test)]@@ -11048,9 +11072,9 @@ thread_local! {const { std::cell::Cell::new(Some(true)) };}-/// Apply the `think_tags` setting for the process. Called once per session from-/// `prepare_agent_session`, the chokepoint every agent surface goes through.-pub(crate) fn set_think_tags_parsed(enabled: bool) {+/// Apply the tag gate for the process. `App::sync_think_tags` calls it at+/// startup and whenever the serving provider can change.+fn set_think_tags_parsed(enabled: bool) {PARSE_THINK_TAGS.store(enabled, std::sync::atomic::Ordering::Relaxed);}@@ -11978,6 +12002,7 @@ pub async fn run(app.shell_set = shell_set;app.subagent_set = subagent_set;app.args = Some(args.clone());+ app.sync_think_tags();// Adopt the session's startup run mode (e.g. `--plan`) so the header badge// shows immediately; a resumed thread overrides this via restore_run_mode.app.run_mode = args.run_mode;@@ -19395,6 +19420,7 @@ async fn reload_provider_configs(app: &mut App) {// The memoized model -> provider answer was resolved against the// snapshot just replaced.app.invalidate_serving_provider();+ app.sync_think_tags();}Err(e) => {app.note(&format!(@@ -30080,6 +30106,42 @@ mod tests {});}+ /// The tag gate follows whoever serves the model: a custom OpenAI-compatible+ /// provider parses inline tags, tokamak (reasoning in its own field) does not,+ /// and switching models moves the gate with it.+ #[test]+ fn think_tag_gate_follows_the_serving_provider_across_a_model_switch() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let provider = |name: &str, model: &str| {+ (+ name.to_string(),+ crate::core::state::ProviderConfig {+ provider: name.into(),+ base_url: Some("http://127.0.0.1:1/v1".into()),+ models: vec![model.into()],+ ..Default::default()+ },+ )+ };+ let mut app = test_app();+ let args = test_args(+ &app,+ [provider("mine", "local-reasoner"), provider("tokamak", "tk-1")]+ .into_iter()+ .collect(),+ );+ app.args = Some(args);++ app.model = "local-reasoner".into();+ assert!(app.think_tags_gate(), "custom provider parses tags");+ app.set_model("tk-1".into());+ assert!(!app.think_tags_gate(), "tokamak sends reasoning separately");+ assert!(!super::PARSE_THINK_TAGS.load(std::sync::atomic::Ordering::Relaxed));+ app.set_model("local-reasoner".into());+ assert!(super::PARSE_THINK_TAGS.load(std::sync::atomic::Ordering::Relaxed));+ });+ }+/// A contended provider-config lock must not re-key the session's usage/// rows: without the last-known fallback the same model bills into a/// `(model, Some(provider))` row and a `(model, None)` one, and the