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.

fix(agent-cli): Stream tool output in real-time,improve TUI layout, fix budget exhaustion (#8789)

Akarshan Biswas8e0cdac1fa59
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 321833f3e..a3de0ba14 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "Jan"
@@ -23,6 +23,7 @@ dependencies = [
"form_urlencoded",
"futures",
"futures-util",
+ "genai",
"glob",
"gtk",
"hex",
@@ -48,6 +49,7 @@ dependencies = [
"ratatui",
"regex",
"reqwest 0.12.28",
+ "reqwest 0.13.4",
"rfd 0.15.4",
"rmcp",
"serde",
@@ -345,6 +347,18 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "async-compression"
+version = "0.4.43"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8"
+dependencies = [
+ "compression-codecs",
+ "compression-core",
+ "pin-project-lite",
+ "tokio",
+]
+
[[package]]
name = "async-executor"
version = "1.14.0"
@@ -516,6 +530,29 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "aws-lc-rs"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e"
+dependencies = [
+ "aws-lc-sys",
+ "zeroize",
+]
+
+[[package]]
+name = "aws-lc-sys"
+version = "0.44.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483"
+dependencies = [
+ "cc",
+ "cmake",
+ "dunce",
+ "fs_extra",
+ "pkg-config",
+]
+
[[package]]
name = "base64"
version = "0.21.7"
@@ -528,6 +565,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
[[package]]
name = "base64ct"
version = "1.8.3"
@@ -972,6 +1015,15 @@ dependencies = [
"error-code",
]
+[[package]]
+name = "cmake"
+version = "0.1.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "codepage"
version = "0.1.2"
@@ -1021,6 +1073,23 @@ dependencies = [
"static_assertions",
]
+[[package]]
+name = "compression-codecs"
+version = "0.4.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
+dependencies = [
+ "compression-core",
+ "flate2",
+ "memchr",
+]
+
+[[package]]
+name = "compression-core"
+version = "0.4.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
+
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -1655,6 +1724,7 @@ dependencies = [
"quote",
"rustc_version",
"syn 2.0.118",
+ "unicode-xid",
]
[[package]]
@@ -2071,6 +2141,17 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "eventsource-stream"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab"
+dependencies = [
+ "futures-core",
+ "nom 7.1.3",
+ "pin-project-lite",
+]
+
[[package]]
name = "fallible-iterator"
version = "0.3.0"
@@ -2310,6 +2391,12 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "fs_extra"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+
[[package]]
name = "futf"
version = "0.1.5"
@@ -2531,6 +2618,33 @@ dependencies = [
"x11",
]
+[[package]]
+name = "genai"
+version = "0.7.0-beta.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5384b6886a7538f657907d9d4d832a45f96dfd04a029713306c1cde5cea38991"
+dependencies = [
+ "base64 0.23.1",
+ "bytes",
+ "derive_more",
+ "eventsource-stream",
+ "futures",
+ "macro_rules_attribute",
+ "mime_guess",
+ "paste",
+ "regex",
+ "reqwest 0.13.4",
+ "serde",
+ "serde_json",
+ "serde_with",
+ "strum",
+ "tokio",
+ "tokio-stream",
+ "tracing",
+ "uuid",
+ "value-ext",
+]
+
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -3852,6 +3966,22 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "macro_rules_attribute"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c"
+dependencies = [
+ "macro_rules_attribute-proc_macro",
+ "pastey",
+]
+
+[[package]]
+name = "macro_rules_attribute-proc_macro"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c"
+
[[package]]
name = "malloc_buf"
version = "0.0.6"
@@ -3932,6 +4062,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+[[package]]
+name = "mime_guess"
+version = "2.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
+dependencies = [
+ "mime",
+ "unicase",
+]
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -4755,6 +4895,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+[[package]]
+name = "pastey"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
+
[[package]]
name = "pbkdf2"
version = "0.11.0"
@@ -5343,6 +5489,7 @@ version = "0.11.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"
dependencies = [
+ "aws-lc-rs",
"bytes",
"getrandom 0.4.3",
"lru-slab",
@@ -5734,18 +5881,24 @@ checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
dependencies = [
"base64 0.22.1",
"bytes",
+ "encoding_rs",
"futures-core",
"futures-util",
+ "h2",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
+ "hyper-tls",
"hyper-util",
"js-sys",
"log",
+ "mime",
+ "native-tls",
"percent-encoding",
"pin-project-lite",
+ "quinn",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
@@ -5753,6 +5906,7 @@ dependencies = [
"serde_json",
"sync_wrapper",
"tokio",
+ "tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
@@ -5944,6 +6098,7 @@ version = "0.23.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"
dependencies = [
+ "aws-lc-rs",
"once_cell",
"ring",
"rustls-pki-types",
@@ -6007,6 +6162,7 @@ version = "0.103.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
dependencies = [
+ "aws-lc-rs",
"ring",
"rustls-pki-types",
"untrusted",
@@ -6282,6 +6438,7 @@ version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
dependencies = [
+ "indexmap 2.14.0",
"itoa",
"memchr",
"serde",
@@ -8210,12 +8367,17 @@ version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
+ "async-compression",
"bitflags 2.13.0",
"bytes",
+ "futures-core",
"futures-util",
"http",
"http-body",
+ "http-body-util",
"pin-project-lite",
+ "tokio",
+ "tokio-util",
"tower",
"tower-layer",
"tower-service",
@@ -8452,6 +8614,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -8536,6 +8704,17 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "value-ext"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca945a9c7463ad3085da59b5dc4f8faf4dff6f3e7d835fa7ef08a3b36926512d"
+dependencies = [
+ "derive_more",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "vcpkg"
version = "0.2.15"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 60e2bb367..4e7d5d06e 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -6,9 +6,9 @@ authors = ["Jan <[email protected]>"]
license = "MIT"
repository = "https://github.com/janhq/jan"
edition = "2021"
-# 1.82 is the floor actually used: `Option::is_none_or` (1.82) in agent/loop.rs
-# and `LazyLock` (1.80) in cli/tui.rs.
-rust-version = "1.82"
+# 1.85 is the floor: `genai` (the OpenAI upstream client) is edition 2024.
+# Below that the previous floor was 1.82, for `Option::is_none_or` in agent/loop.rs.
+rust-version = "1.85"
resolver = "2"
default-run = "jan-desktop"
@@ -257,12 +257,21 @@ tauri-plugin-mlx = { path = "./plugins/tauri-plugin-mlx", optional = true }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
reqwest = { version = "0.12", features = ["json", "blocking", "stream", "native-tls"] }
+# TLS backend must track `reqwest` above: reqwest features are additive across the
+# graph, so letting genai default to rustls would link both backends here.
+genai = { version = "=0.7.0-beta.19", default-features = false, features = ["native-tls"] }
+# genai is on reqwest 0.13 while the rest of the app is on 0.12, so its client
+# type is a distinct crate. Aliased here solely to build the pool-tuned client
+# `agent_http_client` hands to genai (see core/agent/upstream.rs).
+reqwest13 = { package = "reqwest", version = "0.13", default-features = false, features = ["json", "stream", "charset", "http2", "system-proxy", "native-tls"] }
tauri-plugin-updater = { version = "2", optional = true }
once_cell = "1.18"
tauri-plugin-single-instance = { version = "2", features = ["deep-link"], optional = true }
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
reqwest = { version = "0.12", features = ["json", "blocking", "stream", "rustls-tls"], default-features = false }
+genai = { version = "=0.7.0-beta.19", default-features = false, features = ["rustls-tls"] }
+reqwest13 = { package = "reqwest", version = "0.13", default-features = false, features = ["json", "stream", "charset", "http2", "rustls"] }
tauri-plugin-dialog = { version = "2.2.1", default-features = false, optional = true }
tauri-plugin-http = { version = "2", default-features = false, optional = true }
tauri-plugin-log = { version = "2.0.0-rc", default-features = false, optional = true }
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index 9d934190b..628988ef6 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -773,13 +773,16 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
// reap its whole process tree if it is still running.
let (tx, mut rx) = oneshot::channel();
let spill_scratch = ctx.scratch_root.map(Path::to_path_buf);
+ // Cloned into the detached task, which is what keeps a backgrounded command
+ // reporting after this call has already returned its `job_id`.
+ let sink = ctx.on_output.clone();
let sandboxed = ctx.sandbox;
// The model writes POSIX commands by default, which `cmd` rejects. Surface
// the resolved shell so it can adapt when the only shell on a Windows box
// is cmd, instead of the tool silently presenting cmd as bash.
let shell_description = shell.description;
tokio::spawn(async move {
- let mut out = collect_and_format(child, spill_scratch).await;
+ let mut out = collect_and_format(child, spill_scratch, sink).await;
// Appended inside the task so a backgrounded job carries the hint too.
// `Permission denied` on its own tells the model nothing about *why*;
// without this it retries the same command until it gives up. Only when
@@ -834,7 +837,11 @@ async fn await_bash_job(job_id: &str) -> String {
/// combined chronologically and spilled to a temp file once it outgrows the
/// in-memory window, so the full text stays readable even though only a bounded
/// tail is kept in RAM.
-async fn collect_and_format(mut child: tokio::process::Child, scratch: Option<PathBuf>) -> String {
+async fn collect_and_format(
+ mut child: tokio::process::Child,
+ scratch: Option<PathBuf>,
+ sink: Option<crate::tools::OutputSink>,
+) -> String {
use tokio::io::AsyncReadExt;
let mut stdout = child.stdout.take();
let mut stderr = child.stderr.take();
@@ -843,18 +850,42 @@ async fn collect_and_format(mut child: tokio::process::Child, scratch: Option<Pa
let mut be = vec![0u8; 8192];
let mut out_open = stdout.is_some();
let mut err_open = stderr.is_some();
+ // A read boundary can land mid-character, so decoding each chunk on its own
+ // would emit a replacement character for any multi-byte sequence unlucky
+ // enough to straddle one. Hold the incomplete tail back for the next chunk.
+ let mut carry: Vec<u8> = Vec::new();
+ let tee = |bytes: &[u8], carry: &mut Vec<u8>| {
+ let Some(sink) = sink.as_ref() else { return };
+ carry.extend_from_slice(bytes);
+ let text = match std::str::from_utf8(carry) {
+ Ok(_) => std::mem::take(carry),
+ // Everything before the first bad byte is complete; the rest is
+ // either a split character or genuinely invalid, and waiting one
+ // more chunk tells us which.
+ Err(e) => carry.drain(..e.valid_up_to()).collect(),
+ };
+ if !text.is_empty() {
+ sink(String::from_utf8_lossy(&text).into_owned());
+ }
+ };
while out_open || err_open {
tokio::select! {
r = stdout.as_mut().unwrap().read(&mut bo), if out_open => match r {
Ok(0) | Err(_) => out_open = false,
- Ok(n) => cap.push(&bo[..n]),
+ Ok(n) => { cap.push(&bo[..n]); tee(&bo[..n], &mut carry); }
},
r = stderr.as_mut().unwrap().read(&mut be), if err_open => match r {
Ok(0) | Err(_) => err_open = false,
- Ok(n) => cap.push(&be[..n]),
+ Ok(n) => { cap.push(&be[..n]); tee(&be[..n], &mut carry); }
},
}
}
+ // Whatever is left was never completed: emit it lossily rather than losing it.
+ if !carry.is_empty() {
+ if let Some(sink) = sink.as_ref() {
+ sink(String::from_utf8_lossy(&carry).into_owned());
+ }
+ }
match child.wait().await {
Ok(status) => cap.finish(status.code()),
Err(e) => format!("ERROR: failed to run command: {e}"),
@@ -2475,6 +2506,77 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// A command's output reaches the sink as it is produced, not just in the
+ /// returned string -- this is what makes a long command visible while it runs.
+ #[tokio::test]
+ async fn bash_streams_output_to_the_sink() {
+ let root = unique_root();
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
+ let sink = {
+ let seen = seen.clone();
+ std::sync::Arc::new(move |chunk: String| {
+ seen.lock().unwrap().push_str(&chunk);
+ }) as crate::tools::OutputSink
+ };
+ let store = crate::workspace::project_store(&root);
+ let ctx = ToolContext::new(&root, &store, &[])
+ .with_sandbox(false)
+ .with_output_sink(sink);
+ let out = super::execute_builtin(
+ lookup("bash").unwrap(),
+ &json!({"command": "printf 'one\ntwo\n'"}),
+ &ctx,
+ )
+ .await
+ .0;
+ let streamed = seen.lock().unwrap().clone();
+ assert!(streamed.contains("one"), "sink saw nothing: {streamed:?}");
+ assert!(streamed.contains("two"), "sink missed a chunk: {streamed:?}");
+ // The return value still carries it, so the model's view is unchanged.
+ assert!(out.contains("one") && out.contains("two"), "{out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A backgrounded command keeps streaming after the call has returned its
+ /// `job_id`: the sink lives in the detached task, which is the whole reason
+ /// waiting on a long job can show progress.
+ #[tokio::test]
+ async fn a_backgrounded_command_keeps_streaming() {
+ let root = unique_root();
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
+ let sink = {
+ let seen = seen.clone();
+ std::sync::Arc::new(move |chunk: String| {
+ seen.lock().unwrap().push_str(&chunk);
+ }) as crate::tools::OutputSink
+ };
+ let store = crate::workspace::project_store(&root);
+ let ctx = ToolContext::new(&root, &store, &[])
+ .with_sandbox(false)
+ .with_output_sink(sink);
+ // timeout 0 => backgrounds immediately, before the command prints.
+ let out = super::execute_builtin(
+ lookup("bash").unwrap(),
+ &json!({"command": "sleep 0.2; printf 'late\n'", "timeout": 0}),
+ &ctx,
+ )
+ .await
+ .0;
+ assert!(out.contains("job_id=bash-"), "should background: {out}");
+ assert!(
+ seen.lock().unwrap().is_empty(),
+ "nothing printed yet at hand-off"
+ );
+ // The detached task is still running and still holds the sink.
+ tokio::time::sleep(std::time::Duration::from_millis(900)).await;
+ let streamed = seen.lock().unwrap().clone();
+ assert!(
+ streamed.contains("late"),
+ "a backgrounded job must keep reporting: {streamed:?}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[tokio::test]
async fn bash_exceeding_timeout_backgrounds_instead_of_erroring() {
let root = unique_root();
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index 50f3842c5..851e65453 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
@@ -49,7 +49,10 @@ pub struct ImageContentPart {
/// `allow_network` opens the sandboxed shell's network namespace. It defaults to
/// off and is a field rather than a `new` parameter so existing callers keep the
/// safe default without being rewritten.
-#[derive(Debug, Clone, Copy)]
+/// Not `Copy`: the output sink is an `Arc`. Cloning is cheap either way (every
+/// other field is a borrow or a bool), so callers that relied on implicit copies
+/// clone explicitly.
+#[derive(Clone)]
pub struct ToolContext<'a> {
pub project_root: &'a Path,
pub store_root: &'a Path,
@@ -83,8 +86,40 @@ pub struct ToolContext<'a> {
/// gate is then the only thing between the model and the machine, which is
/// why nothing else about the gate changes when this is off.
pub sandbox: bool,
+ /// Where a tool sends output as it is produced, when the caller wants to
+ /// show it live. `None` means "collect and return only", which is what every
+ /// non-interactive caller wants.
+ ///
+ /// `Arc` and not a borrow because `bash` hands its child to a detached task:
+ /// the sink has to outlive the call that created it, which is also what makes
+ /// a backgrounded command keep reporting after the tool has returned its
+ /// `job_id`.
+ pub on_output: Option<OutputSink>,
+}
+
+impl std::fmt::Debug for ToolContext<'_> {
+ /// Hand-written because a sink is a closure: reported as present or absent,
+ /// which is the only thing about it worth printing.
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ToolContext")
+ .field("project_root", &self.project_root)
+ .field("store_root", &self.store_root)
+ .field("enabled_skills", &self.enabled_skills)
+ .field("allow_network", &self.allow_network)
+ .field("confine_writes", &self.confine_writes)
+ .field("mask_root", &self.mask_root)
+ .field("home_readonly", &self.home_readonly)
+ .field("scratch_root", &self.scratch_root)
+ .field("sandbox", &self.sandbox)
+ .field("on_output", &self.on_output.is_some())
+ .finish()
+ }
}
+/// A tool's live-output channel: called with each chunk as it arrives, in order.
+/// Chunks are raw fragments, not lines -- a caller that wants lines buffers them.
+pub type OutputSink = std::sync::Arc<dyn Fn(String) + Send + Sync>;
+
impl<'a> ToolContext<'a> {
pub fn new(project_root: &'a Path, store_root: &'a Path, enabled_skills: &'a [String]) -> Self {
Self {
@@ -97,9 +132,17 @@ impl<'a> ToolContext<'a> {
home_readonly: false,
scratch_root: None,
sandbox: true,
+ on_output: None,
}
}
+ /// Stream this call's output to `sink` as it is produced, as well as
+ /// returning it. See [`Self::on_output`].
+ pub fn with_output_sink(mut self, sink: OutputSink) -> Self {
+ self.on_output = Some(sink);
+ self
+ }
+
pub fn with_network(mut self, allow: bool) -> Self {
self.allow_network = allow;
self
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 b36b4d85a..b96ca3302 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -948,32 +948,6 @@ 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 eb6be2a95..494ee500a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
@@ -702,18 +702,6 @@
"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/bin/jan.rs b/src-tauri/src/bin/jan.rs
index 4a828244f..5e67b6ebe 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -950,7 +950,7 @@ async fn handle_models(cmd: ModelsCommands) {
"provider": c.provider,
"base_url": c.base_url,
"api_type": c.api_type,
- "has_api_key": !c.bearer_key_chain().is_empty(),
+ "has_api_key": app_lib::core::cli::providers::has_credential(c),
})
})
})
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 6914eeef8..ad81f44c2 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -42,6 +42,18 @@ pub enum StreamEvent {
name: String,
args: serde_json::Value,
},
+ /// A chunk of a tool's output, as it is produced. Emitted between
+ /// [`ToolCall`] and [`ToolResult`] so a consumer can show a command's output
+ /// while it runs instead of only once it exits.
+ ///
+ /// Deltas, not the accumulated buffer, for the same reason as
+ /// [`ToolCallArgsDelta`]: resending the prefix on every chunk is quadratic in
+ /// the output size. Chunks are raw fragments and may split a line.
+ ///
+ /// Keeps arriving after a `bash` call has backgrounded itself and returned a
+ /// `job_id`, so a long-running job reports progress under the id of the call
+ /// that started it.
+ ToolOutputDelta { id: String, delta: String },
/// A tool finished. `is_error` reflects the upstream "ERROR" encoding.
/// `diff` is display-only focused-change text (line-prefixed `-`/`+`) for
/// `write`/`edit`; `None` for other tools.
diff --git a/src-tauri/src/core/agent/genai_bridge.rs b/src-tauri/src/core/agent/genai_bridge.rs
new file mode 100644
index 000000000..b0af16b13
--- /dev/null
+++ b/src-tauri/src/core/agent/genai_bridge.rs
@@ -0,0 +1,1366 @@
+//! The agent's upstream chat client, built on `genai`.
+//!
+//! Every provider the agent talks to routes through here: cloud providers, a Jan
+//! desktop API server, a local llama.cpp router, an MLX session. The wire format
+//! stays OpenAI `/chat/completions` -- `genai` is used for its provider handling
+//! (field-name variance, SSE correctness, tool-call merging), not to change the
+//! protocol.
+//!
+//! The boundary is deliberately JSON in / JSON out, matching what
+//! [`super::upstream`] and `core::agent::loop` already pass around: a request
+//! body as `serde_json::Value` and a reconstructed non-streaming completion back.
+//! Threads persist messages in that shape, so converting the agent loop to
+//! `genai`'s types would change an on-disk format for no gain.
+//!
+//! The API server proxy (`core::server::proxy`) does NOT come through here: it
+//! forwards upstream bytes verbatim to external SDK clients, and re-serializing
+//! through typed structs would corrupt that passthrough.
+
+use std::time::Duration;
+
+use genai::adapter::AdapterKind;
+use genai::chat::{
+ ChatMessage, ChatOptions, ChatRequest, ChatRole, ChatStreamEvent, ContentPart, MessageContent,
+ ReasoningEffort, Tool, ToolCall, ToolResponse,
+};
+use genai::resolver::{AuthData, Endpoint, ServiceTargetResolver};
+use genai::{Client, ClientBuilder, ModelIden, ServiceTarget};
+use tokio::sync::mpsc;
+use tokio_stream::StreamExt;
+
+use crate::core::agent::events::StreamEvent;
+
+/// How long a pooled connection may sit idle. Deliberately shorter than any
+/// plausible upstream idle timeout: a turn spends minutes running tools with no
+/// bytes flowing, and reusing a connection the peer already reclaimed is the
+/// `Connection reset by peer` a long session otherwise hits.
+const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(15);
+const TCP_KEEPALIVE: Duration = Duration::from_secs(30);
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// The pool-tuned client every agent turn goes through. `genai` is on reqwest
+/// 0.13 while the rest of the app is on 0.12, so this is the aliased crate --
+/// the two `Client` types are not interchangeable.
+///
+/// No overall request timeout: a streamed answer legitimately runs for minutes.
+pub(crate) fn shared_http_client() -> reqwest13::Client {
+ // One pool for the process. `reqwest::Client` is an `Arc` internally, so the
+ // clone is cheap and every caller shares the same connections -- building one
+ // per turn (or per API-server request) would discard the pool each time,
+ // which is the opposite of what the idle-timeout tuning above is for.
+ static SHARED: std::sync::LazyLock<reqwest13::Client> =
+ std::sync::LazyLock::new(build_http_client);
+ SHARED.clone()
+}
+
+fn build_http_client() -> reqwest13::Client {
+ reqwest13::Client::builder()
+ .pool_idle_timeout(POOL_IDLE_TIMEOUT)
+ .tcp_keepalive(TCP_KEEPALIVE)
+ .connect_timeout(CONNECT_TIMEOUT)
+ .build()
+ .unwrap_or_default()
+}
+
+/// Turn the full chat-completions URL the resolver produces into the endpoint
+/// base `genai` expects.
+///
+/// `genai` appends the service suffix with `Url::join("chat/completions")`, and
+/// `join` *replaces* the last path segment unless the base ends in `/`. Without
+/// the trailing slash `https://host/v1` would resolve to `https://host/chat/completions`,
+/// silently dropping `/v1` -- so the slash is not cosmetic.
+pub(crate) fn endpoint_base_from_chat_url(upstream_url: &str) -> String {
+ let trimmed = upstream_url.trim_end_matches('/');
+ let base = trimmed
+ .strip_suffix("/chat/completions")
+ .unwrap_or(trimmed);
+ format!("{base}/")
+}
+
+/// Map a provider's configured `api_type` to a `genai` adapter. Everything
+/// unrecognized stays on the OpenAI-compatible path, which is what the agent has
+/// always spoken and what every provider in `~/.jan/config.toml` serves today.
+pub(crate) fn adapter_kind_for(api_type: Option<&str>) -> AdapterKind {
+ match api_type {
+ Some("anthropic") => AdapterKind::Anthropic,
+ Some("google") => AdapterKind::Gemini,
+ Some("openai-responses") => AdapterKind::OpenAIResp,
+ _ => AdapterKind::OpenAI,
+ }
+}
+
+/// Build a client pinned to one endpoint, key, and adapter. The resolver is
+/// fixed rather than model-derived: the agent has already resolved which
+/// upstream this model lives on, and letting `genai` re-derive it from the model
+/// name would route a local llama.cpp model to api.openai.com.
+fn client_for(
+ http: &reqwest13::Client,
+ endpoint_base: &str,
+ request_url: &str,
+ api_key: Option<&str>,
+ adapter: AdapterKind,
+) -> Client {
+ let endpoint = Endpoint::from_owned(endpoint_base.to_string());
+
+ // `RequestOverride` rather than `AuthData::Key`, for three reasons:
+ //
+ // * Keyless local endpoints (llama.cpp, LM Studio) have no key to send.
+ // `AuthData::None` is rejected for `AdapterKind::OpenAI` -- only the MLX
+ // adapter sets `allow_no_api_key` -- and an empty `Bearer` is worse than
+ // no header at all, since some servers reject it outright.
+ // * The override supplies the request URL verbatim, so the resolved
+ // upstream URL is used exactly as the agent computed it instead of being
+ // rebuilt by `Url::join`.
+ // * `Accept-Encoding: identity` has to reach the upstream: a compressed SSE
+ // body defeats incremental delivery, which is the whole point of a stream.
+ let mut headers: Vec<(String, String)> = vec![
+ ("Content-Type".to_string(), "application/json".to_string()),
+ ("Accept".to_string(), "text/event-stream".to_string()),
+ ("Accept-Encoding".to_string(), "identity".to_string()),
+ ];
+ if let Some(key) = api_key.filter(|k| !k.is_empty()) {
+ headers.push(("Authorization".to_string(), format!("Bearer {key}")));
+ }
+ let auth = AuthData::RequestOverride {
+ url: request_url.to_string(),
+ headers: genai::Headers::from(headers),
+ };
+ let resolver = ServiceTargetResolver::from_resolver_fn(
+ move |target: ServiceTarget| -> Result<ServiceTarget, genai::resolver::Error> {
+ let ServiceTarget { model, .. } = target;
+ Ok(ServiceTarget {
+ endpoint: endpoint.clone(),
+ auth: auth.clone(),
+ model: ModelIden::new(adapter, model.model_name),
+ })
+ },
+ );
+
+ ClientBuilder::default()
+ .with_reqwest(http.clone())
+ .with_service_target_resolver(resolver)
+ .build()
+}
+
+/// Everything the agent sends that `genai`'s typed options do not model. `top_k`
+/// and `stop_sequences` are not OpenAI-standard but reach llama.cpp and vLLM,
+/// so they ride through `extra_body` verbatim rather than being dropped.
+const EXTRA_BODY_KEYS: &[&str] = &["top_k", "frequency_penalty", "presence_penalty"];
+
+/// Split an OpenAI request body into the pieces `genai` takes. Unknown keys are
+/// preserved via `extra_body`, so a provider-specific parameter the agent grows
+/// later does not silently vanish.
+fn options_from_body(body: &serde_json::Value) -> ChatOptions {
+ // `stop` (OpenAI) and `stop_sequences` (Anthropic-ish) both appear in bodies
+ // the agent builds; either spelling can be a bare string or an array.
+ let stop_sequences = match body.get("stop").or_else(|| body.get("stop_sequences")) {
+ Some(serde_json::Value::String(s)) => vec![s.clone()],
+ Some(serde_json::Value::Array(items)) => items
+ .iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect(),
+ _ => Vec::new(),
+ };
+
+ let extra: serde_json::Map<String, serde_json::Value> = EXTRA_BODY_KEYS
+ .iter()
+ .filter_map(|k| body.get(*k).map(|v| ((*k).to_string(), v.clone())))
+ .collect();
+
+ ChatOptions {
+ temperature: body.get("temperature").and_then(|v| v.as_f64()),
+ top_p: body.get("top_p").and_then(|v| v.as_f64()),
+ max_tokens: body
+ .get("max_tokens")
+ .and_then(|v| v.as_u64())
+ .and_then(|v| u32::try_from(v).ok()),
+ seed: body.get("seed").and_then(|v| v.as_u64()),
+ stop_sequences,
+ reasoning_effort: body
+ .get("reasoning_effort")
+ .and_then(|v| v.as_str())
+ .and_then(|s| match s.to_ascii_lowercase().as_str() {
+ "none" | "zero" => Some(ReasoningEffort::Zero),
+ "low" => Some(ReasoningEffort::Low),
+ "medium" => Some(ReasoningEffort::Medium),
+ "high" => Some(ReasoningEffort::High),
+ "xhigh" => Some(ReasoningEffort::XHigh),
+ _ => None,
+ }),
+ extra_body: (!extra.is_empty()).then(|| serde_json::Value::Object(extra)),
+ // The reconstructed completion needs usage, the final content, and the
+ // merged tool calls; reasoning is carried back on the assistant message
+ // so a follow-up turn can resend it.
+ capture_usage: Some(true),
+ 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),
+ ..Default::default()
+ }
+}
+
+/// Convert the agent's OpenAI `messages` array into `genai` messages.
+///
+/// `system` is lifted out of the array: `genai` carries it on the request rather
+/// than as a message, and adapters place it where each provider wants it.
+fn messages_from_body(
+ body: &serde_json::Value,
+) -> Result<(Option<String>, Vec<ChatMessage>), String> {
+ let raw = body
+ .get("messages")
+ .and_then(|v| v.as_array())
+ .ok_or("Request body must include 'messages' as an array")?;
+
+ let mut system: Option<String> = None;
+ let mut out: Vec<ChatMessage> = Vec::with_capacity(raw.len());
+
+ for msg in raw {
+ let role = msg
+ .get("role")
+ .and_then(|v| v.as_str())
+ .ok_or("Each message must include a string 'role'")?;
+ let content = msg.get("content");
+
+ match role {
+ "system" | "developer" => {
+ let text = content_text(content);
+ // Several system turns concatenate rather than the last winning,
+ // which would silently drop an earlier instruction.
+ system = Some(match system.take() {
+ Some(prev) if !prev.is_empty() => format!("{prev}\n\n{text}"),
+ _ => text,
+ });
+ }
+ "tool" => {
+ let call_id = msg
+ .get("tool_call_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string();
+ out.push(ChatMessage::new(
+ ChatRole::Tool,
+ ToolResponse::new(call_id, content_text(content)),
+ ));
+ }
+ "assistant" => {
+ let mut parts: Vec<ContentPart> = Vec::new();
+ // Reasoning first: adapters hoist it back into the provider's
+ // sibling field, and its position relative to text is not
+ // meaningful.
+ if let Some(r) = msg
+ .get("reasoning_content")
+ .or_else(|| msg.get("reasoning"))
+ .and_then(|v| v.as_str())
+ .filter(|r| !r.is_empty())
+ {
+ parts.push(ContentPart::ReasoningContent(r.to_string()));
+ }
+ let text = content_text(content);
+ if !text.is_empty() {
+ parts.push(ContentPart::Text(text));
+ }
+ for tc in msg
+ .get("tool_calls")
+ .and_then(|v| v.as_array())
+ .map(|a| a.as_slice())
+ .unwrap_or_default()
+ {
+ parts.push(ContentPart::ToolCall(tool_call_from_json(tc)));
+ }
+ // A turn with no text, no reasoning and no calls would serialize
+ // to an empty assistant message, which some providers reject.
+ if parts.is_empty() {
+ continue;
+ }
+ out.push(ChatMessage::new(
+ ChatRole::Assistant,
+ parts.into_iter().collect::<MessageContent>(),
+ ));
+ }
+ // Everything else is a user turn. Multimodal content-part arrays are
+ // flattened to their text; images are not yet forwarded (see below).
+ _ => {
+ out.push(ChatMessage::new(
+ ChatRole::User,
+ content_text(content),
+ ));
+ }
+ }
+ }
+
+ Ok((system, out))
+}
+
+/// Text of an OpenAI `content` field: a bare string, or the concatenated `text`
+/// parts of a multimodal array. Non-text parts (`image_url`) are skipped.
+fn content_text(content: Option<&serde_json::Value>) -> String {
+ match content {
+ Some(serde_json::Value::String(s)) => s.clone(),
+ Some(serde_json::Value::Array(parts)) => parts
+ .iter()
+ .filter_map(|p| p.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join(""),
+ _ => String::new(),
+ }
+}
+
+/// Rebuild a `genai` tool call from the OpenAI JSON shape the agent persists.
+///
+/// `arguments` is a JSON *string* on the wire. It is parsed so `genai` can
+/// re-serialize it, and left as a string value when it does not parse -- a
+/// truncated argument is preserved verbatim rather than being turned into
+/// something the model never emitted.
+fn tool_call_from_json(tc: &serde_json::Value) -> ToolCall {
+ let func = tc.get("function");
+ let raw_args = func
+ .and_then(|f| f.get("arguments"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let fn_arguments = if raw_args.trim().is_empty() {
+ serde_json::json!({})
+ } else {
+ serde_json::from_str(raw_args)
+ .unwrap_or_else(|_| serde_json::Value::String(raw_args.to_string()))
+ };
+ ToolCall {
+ call_id: tc
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ fn_name: func
+ .and_then(|f| f.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ fn_arguments,
+ thought_signatures: None,
+ }
+}
+
+/// Convert the agent's OpenAI `tools` array into `genai` tools.
+fn tools_from_body(body: &serde_json::Value) -> Option<Vec<Tool>> {
+ let raw = body.get("tools").and_then(|v| v.as_array())?;
+ let tools: Vec<Tool> = raw
+ .iter()
+ .filter_map(|t| {
+ let func = t.get("function")?;
+ let name = func.get("name").and_then(|v| v.as_str())?;
+ let mut tool = Tool::new(name.to_string());
+ if let Some(desc) = func.get("description").and_then(|v| v.as_str()) {
+ tool = tool.with_description(desc.to_string());
+ }
+ if let Some(params) = func.get("parameters") {
+ tool = tool.with_schema(params.clone());
+ }
+ Some(tool)
+ })
+ .collect();
+ (!tools.is_empty()).then_some(tools)
+}
+
+/// Build the full `genai` request from an OpenAI body.
+fn chat_request_from_body(body: &serde_json::Value) -> Result<(String, ChatRequest), String> {
+ let model = body
+ .get("model")
+ .and_then(|v| v.as_str())
+ .ok_or("Request body must include 'model'")?
+ .to_string();
+
+ let (system, messages) = messages_from_body(body)?;
+ let mut req = ChatRequest::new(messages);
+ req.system = system;
+ req.tools = tools_from_body(body);
+ Ok((model, req))
+}
+
+/// Attempts per API key, per the "10 retries with increasing backoff" policy.
+const MAX_ATTEMPTS: u32 = 10;
+/// First backoff; doubles per attempt up to [`MAX_RETRY_DELAY`].
+const BASE_RETRY_DELAY: Duration = Duration::from_millis(250);
+/// Backoff ceiling. Unbounded doubling over 10 attempts would idle for ~4
+/// minutes, which a user reads as a hang rather than a retry.
+const MAX_RETRY_DELAY: Duration = Duration::from_secs(8);
+/// Total time that may be spent *waiting* between attempts. Bounds the worst
+/// case regardless of attempt count or a hostile `Retry-After`.
+const RETRY_BUDGET: Duration = Duration::from_secs(45);
+
+/// What to do about a failed attempt.
+enum Disposition {
+ /// Retry the same key after a backoff.
+ Retry,
+ /// The key was rejected; move to the next key in the chain.
+ NextKey,
+ /// Nothing will help.
+ Fatal,
+}
+
+/// HTTP statuses worth another attempt: rate limiting and the transient 5xx
+/// family a load balancer emits while a backend recycles. A 4xx other than 429
+/// is a request the upstream will reject identically forever.
+fn disposition_for_status(status: u16) -> Disposition {
+ match status {
+ 401 | 403 => Disposition::NextKey,
+ // 429 can be either: with more keys it's worth rotating, and retrying the
+ // same key after a delay is the documented remedy. Rotation is preferred
+ // (see the caller) and this is the fallback when the chain is exhausted.
+ 429 => Disposition::Retry,
+ 408 | 409 | 425 => Disposition::Retry,
+ s if (500..600).contains(&s) => Disposition::Retry,
+ _ => Disposition::Fatal,
+ }
+}
+
+/// A provider-requested delay, honored when it is present and sane.
+/// `retry-after-ms` wins over `retry-after` (it is more precise); a date-form
+/// `Retry-After` is ignored rather than parsed.
+fn provider_retry_after(headers: &reqwest13::header::HeaderMap) -> Option<Duration> {
+ let ms = headers
+ .get("retry-after-ms")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .map(Duration::from_millis);
+ ms.or_else(|| {
+ headers
+ .get("retry-after")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .map(Duration::from_secs)
+ })
+}
+
+/// Pull the HTTP status, response body, and headers out of whichever error shape
+/// `genai` used. Kept in one place because the same failure arrives as
+/// `HttpError`, `WebModelCall`, or `WebAdapterCall` depending on the call stage.
+fn http_parts(err: &genai::Error) -> (Option<u16>, Option<&str>, Option<&reqwest13::header::HeaderMap>) {
+ use genai::webc::Error as WebcError;
+ match err {
+ genai::Error::HttpError {
+ status,
+ body,
+ headers,
+ ..
+ } => (Some(status.as_u16()), Some(body.as_str()), Some(headers)),
+ // The streaming path never returns `HttpError` directly: a non-2xx is
+ // boxed inside `WebStream`, so without this unwrap every status looks
+ // like a transport failure and a plain 400 would be retried to death.
+ genai::Error::WebStream { error, .. } => match error.downcast_ref::<genai::Error>() {
+ Some(inner) => http_parts(inner),
+ None => (None, None, None),
+ },
+ genai::Error::WebModelCall { webc_error, .. }
+ | genai::Error::WebAdapterCall { webc_error, .. } => match webc_error {
+ WebcError::ResponseFailedStatus {
+ status,
+ body,
+ headers,
+ } => (Some(status.as_u16()), Some(body.as_str()), Some(headers)),
+ other => (other.status().map(|s| s.as_u16()), None, None),
+ },
+ _ => (err.status().map(|s| s.as_u16()), None, None),
+ }
+}
+
+/// Every message in an error's `source()` chain, outermost cause first, with
+/// consecutive duplicates collapsed. A transport failure's real reason (DNS,
+/// refused connection, TLS mismatch) is several opaque layers below the message
+/// `genai` prints, and is otherwise lost to the user.
+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
+}
+
+/// A failed upstream call described well enough to act on: the `genai` message,
+/// its whole cause chain, and the HTTP status when there was a response.
+fn describe_error(err: &genai::Error) -> String {
+ let mut msg = err.to_string();
+ let chain = error_source_chain(err);
+ if !chain.is_empty() {
+ msg.push_str(&format!(" (caused by: {})", chain.join(" <- ")));
+ }
+ msg
+}
+
+/// Reconstruct the OpenAI non-streaming completion the agent loop expects.
+/// `genai`'s typed result is collapsed back to JSON here rather than at every
+/// call site, so `core::agent::loop` keeps reading the shape it persists.
+fn completion_json(
+ content: String,
+ reasoning: String,
+ tool_calls: Vec<serde_json::Value>,
+ finish_reason: Option<&str>,
+ usage: Option<&genai::chat::Usage>,
+) -> serde_json::Value {
+ let mut message = serde_json::Map::new();
+ message.insert("role".into(), serde_json::json!("assistant"));
+ message.insert(
+ "content".into(),
+ if content.is_empty() {
+ serde_json::Value::Null
+ } else {
+ serde_json::json!(content)
+ },
+ );
+ // Reasoning stays out of `content` but rides on the message so a caller that
+ // resends assistant turns can forward it. Empty is omitted, so a
+ // non-reasoning provider produces an unchanged shape.
+ if !reasoning.is_empty() {
+ message.insert("reasoning_content".into(), serde_json::json!(reasoning));
+ }
+ if !tool_calls.is_empty() {
+ message.insert("tool_calls".into(), serde_json::Value::Array(tool_calls));
+ }
+
+ let mut choice = serde_json::Map::new();
+ choice.insert("index".into(), serde_json::json!(0));
+ choice.insert("message".into(), serde_json::Value::Object(message));
+ choice.insert(
+ "finish_reason".into(),
+ finish_reason
+ .map(|s| serde_json::json!(s))
+ .unwrap_or(serde_json::Value::Null),
+ );
+
+ let mut completion = serde_json::Map::new();
+ completion.insert(
+ "choices".into(),
+ serde_json::Value::Array(vec![serde_json::Value::Object(choice)]),
+ );
+ if let Some(u) = usage {
+ let mut usage_obj = serde_json::Map::new();
+ if let Some(v) = u.prompt_tokens {
+ usage_obj.insert("prompt_tokens".into(), serde_json::json!(v));
+ }
+ if let Some(v) = u.completion_tokens {
+ usage_obj.insert("completion_tokens".into(), serde_json::json!(v));
+ }
+ if let Some(v) = u.total_tokens {
+ usage_obj.insert("total_tokens".into(), serde_json::json!(v));
+ }
+ if !usage_obj.is_empty() {
+ completion.insert("usage".into(), serde_json::Value::Object(usage_obj));
+ }
+ }
+ serde_json::Value::Object(completion)
+}
+
+/// Map `genai`'s normalized stop reason back onto the OpenAI `finish_reason`
+/// vocabulary the agent loop branches on (notably `length`, which fails
+/// truncated tool calls, and `tool_calls`).
+fn finish_reason_str(reason: Option<&genai::chat::StopReason>) -> Option<&'static str> {
+ use genai::chat::StopReason;
+ reason.map(|r| match r {
+ StopReason::Completed(_) => "stop",
+ StopReason::MaxTokens(_) => "length",
+ StopReason::ToolCall(_) => "tool_calls",
+ StopReason::ContentFilter(_) => "content_filter",
+ StopReason::StopSequence(_) => "stop",
+ StopReason::Other(_) => "stop",
+ })
+}
+
+/// Tracks a streaming tool call so `ToolCallStarted` fires once and
+/// `ToolCallArgsDelta` carries only new bytes.
+#[derive(Default)]
+struct ToolCallProgress {
+ started: bool,
+ forwarded: usize,
+}
+
+/// Stream one chat completion, emitting [`StreamEvent`]s as tokens arrive and
+/// returning the reconstructed completion JSON.
+///
+/// Retries live here rather than at the HTTP layer: only at this level are both
+/// the provider's status/`Retry-After` and "has anything been streamed yet"
+/// visible. A retry is attempted **only before the first event reaches the
+/// consumer** -- afterwards a second attempt would duplicate visible output.
+pub(crate) async fn stream_chat_completions(
+ http: &reqwest13::Client,
+ upstream_url: &str,
+ api_keys: &[String],
+ api_type: Option<&str>,
+ body: &serde_json::Value,
+ events: &mpsc::UnboundedSender<StreamEvent>,
+) -> Result<serde_json::Value, String> {
+ let (model, chat_req) = chat_request_from_body(body)?;
+ let options = options_from_body(body);
+ let endpoint_base = endpoint_base_from_chat_url(upstream_url);
+ let adapter = adapter_kind_for(api_type);
+
+ let keys: Vec<Option<&str>> = if api_keys.is_empty() {
+ vec![None]
+ } else {
+ api_keys.iter().map(|k| Some(k.as_str())).collect()
+ };
+
+ let mut spent = Duration::ZERO;
+ let mut last_err = String::from("Upstream request failed");
+
+ for (key_index, key) in keys.iter().enumerate() {
+ let client = client_for(http, &endpoint_base, upstream_url, *key, adapter);
+
+ for attempt in 0..MAX_ATTEMPTS {
+ let mut progressed = false;
+ match run_once(
+ &client,
+ &model,
+ chat_req.clone(),
+ &options,
+ events,
+ &mut progressed,
+ )
+ .await
+ {
+ Ok(completion) => return Ok(completion),
+ Err(err) => {
+ let (status, err_body, headers) = http_parts(&err);
+ let described = describe_error(&err);
+ last_err = match status {
+ Some(s) => format!("Upstream returned HTTP {s}: {described}"),
+ None => format!("Upstream request failed: {described}"),
+ };
+ // A context overflow is not a transport problem: the caller
+ // compacts and retries the turn itself, so mark it and stop.
+ let overflow_text = err_body.unwrap_or(described.as_str());
+ if super::upstream::is_context_overflow_body(overflow_text) {
+ return Err(format!(
+ "[{}] {last_err}",
+ super::upstream::CONTEXT_OVERFLOW_MARKER
+ ));
+ }
+
+ // Anything already streamed to the consumer makes a retry
+ // unsafe -- it would replay tokens the user has seen.
+ if progressed {
+ return Err(last_err);
+ }
+
+ let disposition = match status {
+ Some(s) => disposition_for_status(s),
+ // No HTTP response at all: connect failure, timeout, or a
+ // stream that died before its first event. Nothing was
+ // received, so another attempt is safe.
+ None => Disposition::Retry,
+ };
+
+ match disposition {
+ Disposition::Fatal => return Err(last_err),
+ Disposition::NextKey => {
+ if key_index + 1 < keys.len() {
+ log::warn!(
+ "genai: HTTP {} with API key index {key_index}, trying next key",
+ status.unwrap_or(0)
+ );
+ }
+ break;
+ }
+ Disposition::Retry if attempt + 1 == MAX_ATTEMPTS => {
+ return Err(format!("{last_err} (after {MAX_ATTEMPTS} attempts)"));
+ }
+ Disposition::Retry => {
+ // A 429 with more keys available rotates rather than
+ // waiting: another key usually has its own quota.
+ if status == Some(429) && key_index + 1 < keys.len() {
+ break;
+ }
+ let delay = next_delay(attempt, headers.and_then(provider_retry_after));
+ let Some(delay) = budgeted(delay, spent) else {
+ return Err(format!("{last_err} (retry budget exhausted)"));
+ };
+ spent += delay;
+ log::warn!(
+ "genai: {last_err} -- retrying in {}ms (attempt {}/{MAX_ATTEMPTS})",
+ delay.as_millis(),
+ attempt + 2
+ );
+ tokio::time::sleep(delay).await;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Err(last_err)
+}
+
+/// Exponential backoff for `attempt` (0-based), capped, with a provider-supplied
+/// delay taking precedence when it is longer than what we'd have waited anyway.
+fn next_delay(attempt: u32, provider: Option<Duration>) -> Duration {
+ let backoff = BASE_RETRY_DELAY
+ .saturating_mul(1u32 << attempt.min(15))
+ .min(MAX_RETRY_DELAY);
+ match provider {
+ Some(p) if p > backoff => p,
+ _ => backoff,
+ }
+}
+
+/// Clamp a delay to what remains of [`RETRY_BUDGET`]; `None` when nothing does.
+fn budgeted(delay: Duration, spent: Duration) -> Option<Duration> {
+ let remaining = RETRY_BUDGET.checked_sub(spent)?;
+ if remaining.is_zero() {
+ return None;
+ }
+ Some(delay.min(remaining))
+}
+
+/// One attempt: drive the stream to completion, emitting events as they arrive.
+/// Sets `progressed` as soon as anything has been handed to the consumer, which
+/// makes the attempt non-retryable.
+async fn run_once(
+ client: &Client,
+ model: &str,
+ chat_req: ChatRequest,
+ options: &ChatOptions,
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ progressed: &mut bool,
+) -> Result<serde_json::Value, genai::Error> {
+ let response = client
+ .exec_chat_stream(model, chat_req, Some(options))
+ .await?;
+ let mut stream = response.stream;
+
+ let mut content = String::new();
+ let mut reasoning = String::new();
+ let mut calls: std::collections::HashMap<String, ToolCallProgress> = Default::default();
+ let mut final_calls: Vec<serde_json::Value> = Vec::new();
+ let mut finish: Option<&'static str> = None;
+ let mut usage: Option<genai::chat::Usage> = None;
+
+ while let Some(event) = stream.next().await {
+ match event? {
+ ChatStreamEvent::Start | ChatStreamEvent::Heartbeat => {}
+ ChatStreamEvent::Chunk(chunk) => {
+ if !chunk.content.is_empty() {
+ content.push_str(&chunk.content);
+ *progressed = true;
+ let _ = events.send(StreamEvent::Token {
+ text: chunk.content,
+ });
+ }
+ }
+ ChatStreamEvent::ReasoningChunk(chunk) => {
+ if !chunk.content.is_empty() {
+ reasoning.push_str(&chunk.content);
+ *progressed = true;
+ let _ = events.send(StreamEvent::Reasoning {
+ text: chunk.content,
+ });
+ }
+ }
+ // Signals for the in-progress UI only; the authoritative, merged
+ // calls come from `StreamEnd` below.
+ ChatStreamEvent::ToolCallChunk(chunk) => {
+ let tc = chunk.tool_call;
+ if tc.call_id.is_empty() {
+ continue;
+ }
+ let progress = calls.entry(tc.call_id.clone()).or_default();
+ if !progress.started && !tc.fn_name.is_empty() {
+ progress.started = true;
+ *progressed = true;
+ let _ = events.send(StreamEvent::ToolCallStarted {
+ id: tc.call_id.clone(),
+ name: tc.fn_name.clone(),
+ });
+ }
+ // genai emits the *accumulated* arguments each chunk, so forward
+ // only the part the consumer has not seen. Deltas, not prefixes:
+ // resending the whole buffer is quadratic in a file-sized write.
+ if progress.started {
+ if let Some(acc) = tc.fn_arguments.as_str() {
+ if acc.len() > progress.forwarded {
+ let delta = acc[progress.forwarded..].to_string();
+ progress.forwarded = acc.len();
+ let _ = events.send(StreamEvent::ToolCallArgsDelta {
+ id: tc.call_id,
+ delta,
+ });
+ }
+ }
+ }
+ }
+ ChatStreamEvent::ThoughtSignatureChunk(_) => {}
+ ChatStreamEvent::End(end) => {
+ finish = finish_reason_str(end.captured_stop_reason.as_ref());
+ usage = end.captured_usage.clone();
+ if let Some(tool_calls) = end.captured_tool_calls() {
+ final_calls = tool_calls
+ .into_iter()
+ .map(|tc| {
+ // Arguments go back on the wire as a JSON string,
+ // which is what the loop parses and re-sends.
+ let args = match &tc.fn_arguments {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ };
+ serde_json::json!({
+ "id": tc.call_id,
+ "type": "function",
+ "function": { "name": tc.fn_name, "arguments": args }
+ })
+ })
+ .collect();
+ }
+ // A provider that streamed content but reported nothing at the
+ // end still needs the text captured above.
+ if content.is_empty() {
+ if let Some(text) = end.captured_first_text() {
+ content = text.to_string();
+ }
+ }
+ if reasoning.is_empty() {
+ if let Some(r) = end.captured_reasoning_content.as_deref() {
+ reasoning = r.to_string();
+ }
+ }
+ }
+ }
+ }
+
+ Ok(completion_json(
+ content,
+ reasoning,
+ final_calls,
+ finish,
+ usage.as_ref(),
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ /// The trailing slash is load-bearing: `Url::join` would otherwise replace
+ /// the last segment and drop the API version from the path.
+ #[test]
+ fn endpoint_base_keeps_the_version_segment_and_trailing_slash() {
+ for (input, want) in [
+ (
+ "https://api.tokamak.sh/v1/chat/completions",
+ "https://api.tokamak.sh/v1/",
+ ),
+ (
+ "http://127.0.0.1:1337/v1/chat/completions",
+ "http://127.0.0.1:1337/v1/",
+ ),
+ // Already a base (no suffix to strip).
+ ("https://api.example.com/v1", "https://api.example.com/v1/"),
+ // Redundant trailing slash must not produce a doubled one.
+ (
+ "https://api.example.com/v1/chat/completions/",
+ "https://api.example.com/v1/",
+ ),
+ ] {
+ assert_eq!(endpoint_base_from_chat_url(input), want, "for {input}");
+ }
+ }
+
+ #[test]
+ fn api_type_selects_the_adapter_and_defaults_to_openai() {
+ assert_eq!(adapter_kind_for(None), AdapterKind::OpenAI);
+ assert_eq!(adapter_kind_for(Some("openai")), AdapterKind::OpenAI);
+ assert_eq!(adapter_kind_for(Some("anthropic")), AdapterKind::Anthropic);
+ assert_eq!(adapter_kind_for(Some("google")), AdapterKind::Gemini);
+ // An unknown value must not fail the turn -- OpenAI-compatible is the
+ // shape every configured provider actually serves.
+ assert_eq!(adapter_kind_for(Some("who-knows")), AdapterKind::OpenAI);
+ }
+
+ #[test]
+ fn system_messages_are_lifted_out_and_concatenated() {
+ let body = json!({
+ "model": "m",
+ "messages": [
+ { "role": "system", "content": "be terse" },
+ { "role": "user", "content": "hi" },
+ { "role": "system", "content": "and precise" },
+ ]
+ });
+ let (_, req) = chat_request_from_body(&body).unwrap();
+ assert_eq!(req.system.as_deref(), Some("be terse\n\nand precise"));
+ assert_eq!(req.messages.len(), 1, "only the user turn remains");
+ }
+
+ #[test]
+ fn assistant_reasoning_and_tool_calls_survive_the_round_trip() {
+ let body = json!({
+ "model": "m",
+ "messages": [{
+ "role": "assistant",
+ "content": "calling",
+ "reasoning_content": "i should look it up",
+ "tool_calls": [{
+ "id": "call_abc",
+ "type": "function",
+ "function": { "name": "grep", "arguments": "{\"q\":\"x\"}" }
+ }]
+ }]
+ });
+ let (_, req) = chat_request_from_body(&body).unwrap();
+ let parts: Vec<&ContentPart> = req.messages[0].content.iter().collect();
+
+ assert!(
+ parts
+ .iter()
+ .any(|p| matches!(p, ContentPart::ReasoningContent(r) if r == "i should look it up")),
+ "reasoning is carried so the adapter can resend it: {parts:?}"
+ );
+ let call = parts
+ .iter()
+ .find_map(|p| match p {
+ ContentPart::ToolCall(tc) => Some(tc),
+ _ => None,
+ })
+ .expect("tool call preserved");
+ assert_eq!(call.call_id, "call_abc");
+ assert_eq!(call.fn_name, "grep");
+ // Parsed, not left as a string, so genai re-serializes real JSON.
+ assert_eq!(call.fn_arguments, json!({ "q": "x" }));
+ }
+
+ /// A truncated argument cannot be parsed. Keeping the raw text beats
+ /// inventing an object the model never emitted.
+ #[test]
+ fn unparsable_tool_arguments_are_kept_verbatim() {
+ let tc = json!({
+ "id": "c1",
+ "function": { "name": "write", "arguments": "{\"path\": \"a.txt" }
+ });
+ assert_eq!(
+ tool_call_from_json(&tc).fn_arguments,
+ json!("{\"path\": \"a.txt")
+ );
+ }
+
+ #[test]
+ fn absent_tool_arguments_become_an_empty_object() {
+ let tc = json!({ "id": "c1", "function": { "name": "ls", "arguments": "" } });
+ assert_eq!(tool_call_from_json(&tc).fn_arguments, json!({}));
+ }
+
+ #[test]
+ fn tool_result_messages_become_tool_responses() {
+ let body = json!({
+ "model": "m",
+ "messages": [
+ { "role": "tool", "tool_call_id": "call_abc", "content": "42" }
+ ]
+ });
+ let (_, req) = chat_request_from_body(&body).unwrap();
+ assert!(matches!(req.messages[0].role, ChatRole::Tool));
+ let parts: Vec<&ContentPart> = req.messages[0].content.iter().collect();
+ assert!(
+ parts.iter().any(|p| matches!(
+ p,
+ ContentPart::ToolResponse(tr) if tr.call_id == "call_abc" && tr.content == "42"
+ )),
+ "tool result keyed by call id: {parts:?}"
+ );
+ }
+
+ #[test]
+ fn multimodal_content_parts_are_flattened_to_their_text() {
+ let body = json!({
+ "model": "m",
+ "messages": [{
+ "role": "user",
+ "content": [
+ { "type": "text", "text": "look: " },
+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AAA" } },
+ { "type": "text", "text": "what is it?" }
+ ]
+ }]
+ });
+ let (_, req) = chat_request_from_body(&body).unwrap();
+ let parts: Vec<&ContentPart> = req.messages[0].content.iter().collect();
+ assert!(
+ parts
+ .iter()
+ .any(|p| matches!(p, ContentPart::Text(t) if t == "look: what is it?")),
+ "text parts joined: {parts:?}"
+ );
+ }
+
+ #[test]
+ fn non_standard_params_ride_through_extra_body() {
+ let body = json!({
+ "model": "m",
+ "messages": [],
+ "temperature": 0.4,
+ "top_p": 0.9,
+ "max_tokens": 256,
+ "top_k": 40,
+ "stop": ["<end>"],
+ "reasoning_effort": "high"
+ });
+ let options = options_from_body(&body);
+ assert_eq!(options.temperature, Some(0.4));
+ assert_eq!(options.top_p, Some(0.9));
+ assert_eq!(options.max_tokens, Some(256));
+ assert_eq!(options.stop_sequences, vec!["<end>".to_string()]);
+ assert!(matches!(
+ options.reasoning_effort,
+ Some(ReasoningEffort::High)
+ ));
+ // `top_k` has no typed home; it must still reach llama.cpp / vLLM.
+ assert_eq!(
+ options.extra_body.as_ref().and_then(|b| b.get("top_k")),
+ Some(&json!(40))
+ );
+ }
+
+ #[test]
+ fn a_bare_string_stop_is_accepted_as_well_as_an_array() {
+ let body = json!({ "model": "m", "messages": [], "stop": "STOP" });
+ assert_eq!(
+ options_from_body(&body).stop_sequences,
+ vec!["STOP".to_string()]
+ );
+ }
+
+ #[test]
+ fn tools_carry_their_schema_across() {
+ let body = json!({
+ "model": "m",
+ "messages": [],
+ "tools": [{
+ "type": "function",
+ "function": {
+ "name": "grep",
+ "description": "search",
+ "parameters": { "type": "object", "properties": { "q": { "type": "string" } } }
+ }
+ }]
+ });
+ let (_, req) = chat_request_from_body(&body).unwrap();
+ let tools = req.tools.expect("tools converted");
+ assert_eq!(tools.len(), 1);
+ assert_eq!(tools[0].name.as_str(), "grep");
+ assert_eq!(tools[0].description.as_deref(), Some("search"));
+ assert_eq!(
+ tools[0].schema.as_ref().and_then(|s| s.get("type")),
+ Some(&json!("object"))
+ );
+ }
+
+ #[test]
+ fn a_body_without_a_model_or_messages_is_rejected() {
+ assert!(chat_request_from_body(&json!({ "messages": [] })).is_err());
+ assert!(chat_request_from_body(&json!({ "model": "m" })).is_err());
+ }
+
+ // -- End-to-end: a real socket, real SSE bytes, the real genai stack.
+ // The conversion tests above prove the mapping; these prove the wire.
+
+ fn sink() -> (
+ mpsc::UnboundedSender<StreamEvent>,
+ mpsc::UnboundedReceiver<StreamEvent>,
+ ) {
+ mpsc::unbounded_channel()
+ }
+
+ fn sse_response(events: &[&str]) -> String {
+ let body: String = events.iter().map(|e| format!("data: {e}\n\n")).collect();
+ let body = format!("{body}data: [DONE]\n\n");
+ format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{body}",
+ body.len()
+ )
+ }
+
+ fn status_response(status: u16, reason: &str, body: &str) -> String {
+ format!(
+ "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
+ body.len()
+ )
+ }
+
+ /// Serve one canned reply per connection, in order. `None` accepts the
+ /// request then hangs up without a byte -- what a reclaimed pooled
+ /// connection looks like from the client side.
+ async fn serve(replies: Vec<Option<String>>) -> (String, tokio::task::JoinHandle<()>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ let handle = tokio::spawn(async move {
+ let mut open = Vec::new();
+ for reply in replies {
+ let Ok((mut sock, _)) = listener.accept().await else {
+ return;
+ };
+ let mut scratch = [0u8; 8192];
+ let _ = sock.read(&mut scratch).await;
+ match reply {
+ Some(bytes) => {
+ let _ = sock.write_all(bytes.as_bytes()).await;
+ let _ = sock.flush().await;
+ // Graceful FIN, not an abrupt drop: closing the socket
+ // outright can RST away bytes the client has not read.
+ let _ = sock.shutdown().await;
+ open.push(sock);
+ }
+ None => drop(sock),
+ }
+ }
+ });
+ (format!("http://{addr}/v1/chat/completions"), handle)
+ }
+
+ fn body() -> serde_json::Value {
+ json!({ "model": "m", "messages": [{ "role": "user", "content": "hi" }] })
+ }
+
+ async fn run(url: &str, keys: &[String], events: &mpsc::UnboundedSender<StreamEvent>)
+ -> Result<serde_json::Value, String> {
+ stream_chat_completions(&build_http_client(), url, keys, None, &body(), events).await
+ }
+
+ #[tokio::test]
+ async fn streams_tokens_and_reconstructs_the_completion() {
+ let (url, server) = serve(vec![Some(sse_response(&[
+ r#"{"choices":[{"delta":{"content":"He"}}]}"#,
+ r#"{"choices":[{"delta":{"content":"llo"}}]}"#,
+ r#"{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}"#,
+ ]))])
+ .await;
+
+ let (tx, mut rx) = sink();
+ let completion = run(&url, &[], &tx).await.expect("stream succeeds");
+
+ assert_eq!(completion["choices"][0]["message"]["content"], "Hello");
+ assert_eq!(completion["choices"][0]["finish_reason"], "stop");
+ assert_eq!(completion["usage"]["total_tokens"], 5);
+
+ drop(tx);
+ let mut tokens = Vec::new();
+ while let Ok(ev) = rx.try_recv() {
+ if let StreamEvent::Token { text } = ev {
+ tokens.push(text);
+ }
+ }
+ assert_eq!(tokens, vec!["He", "llo"]);
+ server.await.expect("server");
+ }
+
+ /// The whole reason for this migration: vLLM (and so `tokamak-1-preview`)
+ /// spells the field `reasoning`, not `reasoning_content`. genai accepts both
+ /// and normalizes, so the reasoning pane is no longer empty for Tokamak.
+ #[tokio::test]
+ async fn bare_reasoning_deltas_surface_as_reasoning_events() {
+ let (url, server) = serve(vec![Some(sse_response(&[
+ r#"{"choices":[{"delta":{"reasoning":"We"}}]}"#,
+ r#"{"choices":[{"delta":{"reasoning":" need 391"}}]}"#,
+ r#"{"choices":[{"delta":{"content":"391"}}]}"#,
+ r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
+ ]))])
+ .await;
+
+ let (tx, mut rx) = sink();
+ let completion = run(&url, &[], &tx).await.expect("stream succeeds");
+
+ assert_eq!(completion["choices"][0]["message"]["content"], "391");
+ assert_eq!(
+ completion["choices"][0]["message"]["reasoning_content"],
+ "We need 391",
+ "normalized onto the canonical spelling: {completion}"
+ );
+
+ drop(tx);
+ let (mut reasoning, mut tokens) = (Vec::new(), Vec::new());
+ 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!["We", " need 391"]);
+ assert_eq!(tokens, vec!["391"], "reasoning never leaks into content");
+ server.await.expect("server");
+ }
+
+ #[tokio::test]
+ async fn tool_call_arguments_stream_as_deltas_and_land_in_the_completion() {
+ let (url, server) = serve(vec![Some(sse_response(&[
+ r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"grep","arguments":""}}]}}]}"#,
+ r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"q\":"}}]}}]}"#,
+ r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"x\"}"}}]}}]}"#,
+ r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#,
+ ]))])
+ .await;
+
+ let (tx, mut rx) = sink();
+ let completion = run(&url, &[], &tx).await.expect("stream succeeds");
+
+ assert_eq!(completion["choices"][0]["finish_reason"], "tool_calls");
+ let call = &completion["choices"][0]["message"]["tool_calls"][0];
+ assert_eq!(call["id"], "call_1");
+ assert_eq!(call["function"]["name"], "grep");
+ // Arguments go back as a JSON *string*, which is what the loop parses.
+ assert_eq!(call["function"]["arguments"], r#"{"q":"x"}"#);
+
+ drop(tx);
+ let (mut started, mut args) = (Vec::new(), String::new());
+ while let Ok(ev) = rx.try_recv() {
+ match ev {
+ StreamEvent::ToolCallStarted { id, name } => started.push((id, name)),
+ StreamEvent::ToolCallArgsDelta { delta, .. } => args.push_str(&delta),
+ _ => {}
+ }
+ }
+ assert_eq!(started, vec![("call_1".to_string(), "grep".to_string())],
+ "announced exactly once");
+ // Deltas, not prefixes: concatenating them must rebuild the arguments
+ // rather than repeating them.
+ assert_eq!(args, r#"{"q":"x"}"#);
+ server.await.expect("server");
+ }
+
+ /// A connection reclaimed while the agent ran tools is the classic long-turn
+ /// failure. Nothing was streamed, so the retry is safe -- and must not
+ /// duplicate the answer.
+ #[tokio::test]
+ async fn a_dropped_first_connection_is_retried_and_streams_once() {
+ let (url, server) = serve(vec![
+ None,
+ Some(sse_response(&[
+ r#"{"choices":[{"delta":{"content":"hi"}}]}"#,
+ r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
+ ])),
+ ])
+ .await;
+
+ let (tx, mut rx) = sink();
+ let completion = run(&url, &[], &tx).await.expect("the retry carries the turn");
+ assert_eq!(completion["choices"][0]["message"]["content"], "hi");
+
+ drop(tx);
+ let tokens: Vec<String> = std::iter::from_fn(|| rx.try_recv().ok())
+ .filter_map(|ev| match ev {
+ StreamEvent::Token { text } => Some(text),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(tokens, vec!["hi".to_string()], "streamed once, not twice");
+ server.await.expect("server");
+ }
+
+ /// 401 rotates to the next key rather than burning retries on a key the
+ /// upstream has already rejected.
+ #[tokio::test]
+ async fn an_unauthorized_key_falls_through_to_the_next_key() {
+ let (url, server) = serve(vec![
+ Some(status_response(401, "Unauthorized", r#"{"error":"bad key"}"#)),
+ Some(sse_response(&[
+ r#"{"choices":[{"delta":{"content":"ok"}}]}"#,
+ r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
+ ])),
+ ])
+ .await;
+
+ let (tx, _rx) = sink();
+ let completion = run(&url, &["dead".into(), "live".into()], &tx)
+ .await
+ .expect("second key works");
+ assert_eq!(completion["choices"][0]["message"]["content"], "ok");
+ server.await.expect("server");
+ }
+
+ /// Guard against the whole status-detection path silently regressing: with a
+ /// single key and a single 401 reply queued, a spurious retry would hit a
+ /// closed listener and report a transport error instead. Asserting the 401
+ /// itself surfaces proves the status was read, not that a later attempt
+ /// happened to succeed.
+ #[tokio::test]
+ async fn an_unauthorized_status_is_reported_not_retried_away() {
+ let (url, server) = serve(vec![Some(status_response(
+ 401,
+ "Unauthorized",
+ r#"{"error":"bad key"}"#,
+ ))])
+ .await;
+
+ let (tx, _rx) = sink();
+ let err = run(&url, &["only".into()], &tx)
+ .await
+ .expect_err("a rejected key fails the turn");
+ assert!(
+ err.contains("401"),
+ "the status reached the caller rather than being masked by a retry: {err}"
+ );
+ server.await.expect("server");
+ }
+
+ /// A 4xx that is not an auth or rate-limit problem is the same on every
+ /// attempt, so it must fail immediately rather than spending the budget.
+ #[tokio::test]
+ async fn a_bad_request_is_not_retried() {
+ let (url, server) = serve(vec![Some(status_response(
+ 400,
+ "Bad Request",
+ r#"{"error":{"message":"nope"}}"#,
+ ))])
+ .await;
+
+ let (tx, _rx) = sink();
+ let err = run(&url, &[], &tx).await.expect_err("400 is fatal");
+ assert!(err.contains("400"), "status surfaces to the caller: {err}");
+ server.await.expect("server");
+ }
+
+ #[test]
+ fn backoff_grows_then_holds_at_the_ceiling() {
+ assert_eq!(next_delay(0, None), BASE_RETRY_DELAY);
+ assert_eq!(next_delay(1, None), BASE_RETRY_DELAY * 2);
+ assert_eq!(next_delay(20, None), MAX_RETRY_DELAY, "capped, not overflowing");
+ }
+
+ #[test]
+ fn a_provider_retry_after_wins_only_when_it_is_longer() {
+ let long = Duration::from_secs(30);
+ assert_eq!(next_delay(0, Some(long)), long);
+ // A provider asking for less than our backoff does not get to make us
+ // hammer it faster than we would have.
+ assert_eq!(next_delay(5, Some(Duration::from_millis(1))), MAX_RETRY_DELAY);
+ }
+
+ #[test]
+ fn the_retry_budget_clamps_and_then_gives_up() {
+ assert_eq!(
+ budgeted(Duration::from_secs(10), RETRY_BUDGET - Duration::from_secs(2)),
+ Some(Duration::from_secs(2)),
+ "clamped to what is left"
+ );
+ assert_eq!(budgeted(Duration::from_secs(1), RETRY_BUDGET), None);
+ }
+
+ #[test]
+ fn only_transient_statuses_are_retried() {
+ assert!(matches!(disposition_for_status(500), Disposition::Retry));
+ assert!(matches!(disposition_for_status(503), Disposition::Retry));
+ assert!(matches!(disposition_for_status(429), Disposition::Retry));
+ assert!(matches!(disposition_for_status(401), Disposition::NextKey));
+ assert!(matches!(disposition_for_status(403), Disposition::NextKey));
+ assert!(matches!(disposition_for_status(400), Disposition::Fatal));
+ assert!(matches!(disposition_for_status(404), Disposition::Fatal));
+ assert!(matches!(disposition_for_status(422), Disposition::Fatal));
+ }
+}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 7ec4e66ee..0845da597 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -9,7 +9,9 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use async_trait::async_trait;
-use reqwest::Client;
+// Agent upstream traffic runs on `genai`, which is built against reqwest 0.13;
+// the rest of the app is still on 0.12, so the two `Client` types differ.
+use reqwest13::Client;
#[cfg(not(feature = "cli"))]
use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, Mutex};
@@ -162,6 +164,9 @@ impl ModelInvoker for HttpModelInvoker {
&self.client,
&self.upstream_url,
&self.api_keys,
+ // The agent speaks OpenAI chat/completions to every provider; see
+ // the note on `stream_openai_chat_completions`.
+ None,
request,
events,
)
@@ -367,6 +372,32 @@ fn resolve_run_settings(
}
}
+/// Build a tool output sink that streams deltas to the run's event channel.
+///
+/// The sender is downgraded: `bash` hands its child to a detached task that
+/// keeps the sink alive after the call returns (that is what makes a
+/// backgrounded job keep reporting), and a strong clone in there would hold the
+/// run's channel open forever -- every consumer waits on channel closure, so the
+/// desktop's `invoke`, the headless printer and a subagent's forwarder would all
+/// hang once the turn was logically done. A weak sender still resolves for as
+/// long as the run holds its own sender, so live output is unaffected; once the
+/// run ends, a straggler's output is dropped, which is what it is worth.
+fn output_sink(
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ id: &str,
+) -> tauri_plugin_agent_tools::tools::OutputSink {
+ let events = events.downgrade();
+ let id = id.to_string();
+ std::sync::Arc::new(move |delta: String| {
+ if let Some(events) = events.upgrade() {
+ let _ = events.send(StreamEvent::ToolOutputDelta {
+ id: id.clone(),
+ delta,
+ });
+ }
+ })
+}
+
impl CompositeToolInvoker {
fn tool_context(&self) -> tauri_plugin_agent_tools::tools::ToolContext<'_> {
tauri_plugin_agent_tools::tools::ToolContext::new(
@@ -380,6 +411,18 @@ impl CompositeToolInvoker {
.with_scratch_root(&self.scratch_root)
}
+ /// A tool context whose output streams to the run's event channel as
+ /// [`StreamEvent::ToolOutputDelta`], tagged with the call's `id`.
+ ///
+ /// Only exec-capable tools produce anything here: `bash` tees its child's
+ /// combined stdout/stderr through the sink as it reads. A send failure is
+ /// ignored -- the receiver is gone only when the run is over, and a dead
+ /// display must not stop the command.
+ fn streaming_tool_context(&self, id: &str) -> tauri_plugin_agent_tools::tools::ToolContext<'_> {
+ self.tool_context()
+ .with_output_sink(output_sink(&self.events, id))
+ }
+
/// Prompt the user to approve an MCP tool call, mirroring the built-in gate.
/// A dropped responder (client gone / run cancelled) resolves to Deny.
async fn prompt_mcp_permission(&self, tool_name: &str) -> PermissionDecision {
@@ -904,7 +947,7 @@ impl ToolInvoker for CompositeToolInvoker {
}
let (text, diff, images) = match decision {
Decision::Allow => {
- execute_builtin_with_diff(tool, &args, &self.tool_context()).await
+ execute_builtin_with_diff(tool, &args, &self.streaming_tool_context(&id)).await
}
Decision::HardDeny(reason) => {
(hard_deny_msg(name, reason, &self.project_root), None, None)
@@ -958,7 +1001,12 @@ impl ToolInvoker for CompositeToolInvoker {
self.permission_requests.lock().await.remove(&request_id);
match decision {
PermissionDecision::AllowOnce => {
- execute_builtin_with_diff(tool, &args, &self.tool_context()).await
+ execute_builtin_with_diff(
+ tool,
+ &args,
+ &self.streaming_tool_context(&id),
+ )
+ .await
}
PermissionDecision::AllowAlways => {
// Thread-scoped only; never persisted to agent.toml.
@@ -972,7 +1020,12 @@ impl ToolInvoker for CompositeToolInvoker {
} else {
self.grants.lock().unwrap().grant(kind);
}
- execute_builtin_with_diff(tool, &args, &self.tool_context()).await
+ execute_builtin_with_diff(
+ tool,
+ &args,
+ &self.streaming_tool_context(&id),
+ )
+ .await
}
PermissionDecision::Deny => {
(format!("ERROR: tool '{name}' denied by user"), None, None)
@@ -1419,7 +1472,12 @@ async fn orchestrate_inner(
#[cfg(not(feature = "cli"))]
{
if model_id.is_none() {
- if let Some(first) = router_first_model(llama_state, client).await {
+ // The llama.cpp router is a desktop-only listing call on the app's
+ // reqwest 0.12 stack, not agent upstream traffic, so it does not use
+ // the genai client threaded through `OrchestrationArgs`.
+ static ROUTER_CLIENT: std::sync::LazyLock<reqwest::Client> =
+ std::sync::LazyLock::new(reqwest::Client::new);
+ if let Some(first) = router_first_model(llama_state, &ROUTER_CLIENT).await {
model_id = Some(first);
}
}
@@ -1872,6 +1930,10 @@ async fn run_turn_cycle(
// fixed turn cap.
let unlimited = max_turns == 0;
let mut turn: usize = 0;
+ // The budget notice is announced once, on the turn that crosses the
+ // ceiling. Without the latch every later turn would push another copy and
+ // the notice would crowd out the conversation it is annotating.
+ let mut budget_notice_recorded = false;
// Mid-run todo upkeep: after a long uninterrupted run of mutating tool
// calls with no todo touch, nudge the model once to keep the list honest
// rather than only ever reminding it at a full stop -- a task that never
@@ -2010,42 +2072,63 @@ async fn run_turn_cycle(
continue;
}
}
+ // Every turn is finished and the run passed its token ceiling, so
+ // the conversation is both complete and oversized. Compact it here,
+ // while nothing is waiting on the result: the ceiling no longer
+ // stops a run, so without this the thread only grows, and the next
+ // run resumes it by sending the whole oversized history upstream.
+ // The reactive path above cannot help with that -- it only fires
+ // once an upstream has already rejected a request.
+ //
+ // Only when it actually shrinks: `compact_conversation` returns the
+ // input untouched when there is too little to drop, and publishing
+ // an unchanged history would spend a summarizer call for nothing.
+ if budget.exhausted() {
+ let compacted = crate::core::agent::compaction::compact_conversation(
+ &conversation_messages,
+ model_id,
+ model,
+ crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
+ )
+ .await;
+ if compacted.len() < conversation_messages.len() {
+ log::info!(
+ "agent: budget exhausted at end of run, compacted {} -> {} messages",
+ conversation_messages.len(),
+ compacted.len()
+ );
+ conversation_messages = compacted;
+ }
+ }
let _ = events.send(StreamEvent::MessagesUpdated {
messages: conversation_messages.clone(),
});
return Ok(completion);
}
- // The session budget is exhausted. This is a soft stop, not an error:
- // a subagent that inherits the parent's remaining budget must hand back
- // its partial progress (as an assistant message) so the parent can act
- // on it, instead of the run hard-failing and losing the work. Tool
- // calls are not executed; nothing further is spent against the ceiling.
- if budget.exhausted() {
- let partial = extract_choice_message(&completion)
- .and_then(|m| m.get("content").and_then(|c| c.as_str()))
- .unwrap_or("")
- .to_string();
- let stop_note = format!(
- "[session token budget exhausted ({} tokens)] Partial progress so far:\n\
- {}",
- budget.spent(),
- if partial.is_empty() {
- "(none yet reported)".to_string()
- } else {
- partial
- }
- );
+ // Crossing the session budget is advisory: it is recorded and the run
+ // carries on, tool calls included. Note what this costs -- `max_turns
+ // == 0` is the normal case (see above), so with the budget no longer
+ // stopping anything, user cancellation is the only remaining bound on a
+ // run's spend.
+ //
+ // Recorded as a system note rather than an assistant turn: the model
+ // never wrote it, and putting a bracketed status marker in the
+ // assistant's voice hands it an example of itself emitting one, which
+ // is the shape a model will imitate unprompted on later turns.
+ if budget.exhausted() && !budget_notice_recorded {
+ budget_notice_recorded = true;
conversation_messages.push(serde_json::json!({
- "role": "assistant",
- "content": stop_note,
+ "role": "system",
+ "content": format!(
+ "[session token budget exhausted ({} tokens)] The configured \
+ ceiling has been passed; this run is continuing past it.",
+ budget.spent()
+ ),
}));
let _ = events.send(StreamEvent::MessagesUpdated {
messages: conversation_messages.clone(),
});
- return Ok(serde_json::json!({
- "choices": [{ "message": { "content": stop_note }, "finish_reason": "stop" }]
- }));
}
for tc in &tool_calls {
@@ -3163,12 +3246,21 @@ mod tests {
assert!(!bash_result_is_error_flag("ok\n[exit 0]").await);
}
+ /// Crossing the session token budget is advisory: it is announced once, as
+ /// a system note, and the run carries on -- tool calls included.
#[tokio::test]
- async fn turn_cycle_soft_stops_when_budget_exhausted() {
+ async fn an_exhausted_budget_is_announced_once_and_the_run_continues() {
let (tx, mut rx) = mpsc::unbounded_channel();
let mut over_budget = tool_call_completion();
over_budget["usage"] = json!({ "total_tokens": 100 });
- let model = MockModel::new(vec![over_budget]);
+ let done = json!({
+ "choices": [{ "message": { "content": "all done" }, "finish_reason": "stop" }]
+ });
+ // A second tool-calling turn after the ceiling is crossed, so the
+ // once-only latch is actually exercised rather than assumed.
+ let mut still_over = tool_call_completion();
+ still_over["usage"] = json!({ "total_tokens": 200 });
+ let model = MockModel::new(vec![over_budget, still_over, done]);
let tool = MockTool::default();
let mut budget = SessionBudget::new(Some(50));
let convo = vec![json!({ "role": "user", "content": "hi" })];
@@ -3188,31 +3280,189 @@ mod tests {
None,
)
.await
- .expect("budget exhaustion is a soft stop, not an error");
+ .expect("passing the ceiling is not an error");
- let final_text = extract_choice_message(&result)
- .and_then(|m| m.get("content").and_then(|c| c.as_str()))
- .unwrap_or_default();
- let spent = budget.spent();
assert!(
- final_text.contains("budget")
- && final_text.contains(&spent.to_string()),
- "soft stop should describe the exhausted budget ({spent} tokens): {final_text}",
+ budget.exhausted(),
+ "precondition: the run really did cross the ceiling"
);
assert!(
- tool.calls.lock().unwrap().is_empty(),
- "tool must not run once budget is exhausted"
+ !tool.calls.lock().unwrap().is_empty(),
+ "tool calls still run once the ceiling is passed"
);
- // A MessagesUpdated is published so live surfaces (and the replay
- // session) see the partial conversation before the soft stop.
+ assert_eq!(
+ extract_choice_message(&result)
+ .and_then(|m| m.get("content").and_then(|c| c.as_str()))
+ .unwrap_or_default(),
+ "all done",
+ "the run finishes on the model's own answer, not a stop notice"
+ );
+
+ // Announced exactly once, in the system voice -- never as an assistant
+ // turn the model could later imitate.
+ let requests = model.requests.lock().unwrap();
+ assert_eq!(requests.len(), 3, "the run kept taking turns");
+ // The last request is two turns past the ceiling: if the latch were
+ // missing, the note would appear once per turn here.
+ let messages = requests[2]["messages"].as_array().unwrap();
+ let notes: Vec<&serde_json::Value> = messages
+ .iter()
+ .filter(|m| {
+ m.get("content")
+ .and_then(|c| c.as_str())
+ .is_some_and(|c| c.contains("budget exhausted"))
+ })
+ .collect();
+ assert_eq!(notes.len(), 1, "announced once, not per turn: {messages:#?}");
+ assert_eq!(notes[0]["role"], "system", "system voice, not assistant");
assert!(
- std::iter::from_fn(|| rx.try_recv().ok()).any(
- |ev| matches!(ev, StreamEvent::MessagesUpdated { .. })
- ),
- "expected a MessagesUpdated event on soft stop"
+ messages
+ .iter()
+ .all(|m| m.get("role").and_then(|v| v.as_str()) != Some("assistant")
+ || !m["content"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("budget exhausted")),
+ "no assistant turn carries the marker"
+ );
+
+ assert!(
+ std::iter::from_fn(|| rx.try_recv().ok())
+ .any(|ev| matches!(ev, StreamEvent::MessagesUpdated { .. })),
+ "live surfaces see the annotated conversation"
);
}
+ /// Passing the ceiling no longer stops a run, so a long thread only grows.
+ /// Once every turn is finished, the oversized conversation is compacted
+ /// before it is published -- otherwise the next run resumes this thread by
+ /// sending the whole thing upstream.
+ #[tokio::test]
+ async fn an_exhausted_budget_compacts_the_conversation_once_turns_are_done() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+
+ // Comfortably longer than DEFAULT_KEEP_RECENT so there is a middle to drop.
+ let convo: Vec<serde_json::Value> = (0..24)
+ .map(|i| {
+ json!({
+ "role": if i % 2 == 0 { "user" } else { "assistant" },
+ "content": format!("message {i}"),
+ })
+ })
+ .collect();
+ let original_len = convo.len();
+
+ let mut over_budget = json!({
+ "choices": [{ "message": { "content": "all done" }, "finish_reason": "stop" }]
+ });
+ over_budget["usage"] = json!({ "total_tokens": 100 });
+ let summary = json!({
+ "choices": [{ "message": { "content": "SUMMARY OF THE EARLIER WORK" } }]
+ });
+ // Second response is consumed by the summarizer inside compaction.
+ let model = MockModel::new(vec![over_budget, summary]);
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(Some(50));
+
+ run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ convo,
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await
+ .expect("run completes");
+
+ assert!(budget.exhausted(), "precondition: the ceiling was passed");
+ assert_eq!(
+ model.requests.lock().unwrap().len(),
+ 2,
+ "one turn, plus the summarizer call compaction makes"
+ );
+
+ // The published history is the compacted one: shorter, and carrying the
+ // summary in place of the dropped middle.
+ let published = std::iter::from_fn(|| rx.try_recv().ok())
+ .filter_map(|ev| match ev {
+ StreamEvent::MessagesUpdated { messages } => Some(messages),
+ _ => None,
+ })
+ .last()
+ .expect("a MessagesUpdated is published");
+ assert!(
+ published.len() < original_len,
+ "history was compacted: {} -> {}",
+ original_len,
+ published.len()
+ );
+ assert!(
+ published.iter().any(|m| m["content"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("SUMMARY OF THE EARLIER WORK")),
+ "the summary replaced the dropped middle: {published:#?}"
+ );
+ }
+
+ /// A run that stayed inside its ceiling is left alone -- no summarizer call,
+ /// no compaction, history published as-is.
+ #[tokio::test]
+ async fn a_run_within_budget_is_not_compacted() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let convo: Vec<serde_json::Value> = (0..24)
+ .map(|i| json!({ "role": "user", "content": format!("message {i}") }))
+ .collect();
+ let original_len = convo.len();
+
+ let mut under_budget = json!({
+ "choices": [{ "message": { "content": "all done" }, "finish_reason": "stop" }]
+ });
+ under_budget["usage"] = json!({ "total_tokens": 10 });
+ let model = MockModel::new(vec![under_budget]);
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(Some(50_000));
+
+ run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ convo,
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await
+ .expect("run completes");
+
+ assert!(!budget.exhausted());
+ assert_eq!(
+ model.requests.lock().unwrap().len(),
+ 1,
+ "no summarizer call: compaction never ran"
+ );
+ let published = std::iter::from_fn(|| rx.try_recv().ok())
+ .filter_map(|ev| match ev {
+ StreamEvent::MessagesUpdated { messages } => Some(messages),
+ _ => None,
+ })
+ .last()
+ .expect("a MessagesUpdated is published");
+ assert_eq!(published.len(), original_len, "history untouched");
+ }
+
struct ResultQueueModel {
results: StdMutex<VecDeque<Result<serde_json::Value, String>>>,
}
@@ -4647,4 +4897,42 @@ mod tests {
assert!(tools.is_empty(), "default=deny must lock down MCP advertisement");
assert!(map.is_empty());
}
+
+ /// `bash` hands its child to a detached task that keeps the output sink
+ /// alive after the call has returned its `job_id`. The sink must not keep
+ /// the run's event channel open with it: every consumer of that channel --
+ /// the desktop forwarder, the headless printer, a subagent's forwarder --
+ /// finishes only when the channel closes.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_backgrounded_job_does_not_hold_the_event_channel_open() {
+ use tauri_plugin_agent_tools::tools::{handlers::execute_builtin, lookup, ToolContext};
+ let dir = tempfile::tempdir().unwrap();
+ let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
+ let skills: Vec<String> = Vec::new();
+ let ctx = ToolContext::new(dir.path(), dir.path(), &skills)
+ .with_sandbox(false)
+ .with_output_sink(output_sink(&tx, "call-1"));
+ let out = execute_builtin(
+ lookup("bash").unwrap(),
+ &json!({"command": "sleep 3; printf 'late\\n'", "timeout": 0}),
+ &ctx,
+ )
+ .await
+ .0;
+ assert!(out.contains("job_id=bash-"), "expected a backgrounded job, got: {out}");
+
+ // The run is over: the orchestration future has returned and dropped its
+ // sender, so the receiver must observe closure without waiting for the
+ // straggling command (which outlives this assertion by seconds).
+ drop(tx);
+ let closed = tokio::time::timeout(std::time::Duration::from_millis(1500), async {
+ while rx.recv().await.is_some() {}
+ })
+ .await;
+ assert!(
+ closed.is_ok(),
+ "the event channel never closed while a backgrounded bash job was still running"
+ );
+ }
}
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 888bf25e3..500fcaa1e 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -12,6 +12,7 @@ pub mod commands;
pub mod compaction;
pub mod context;
pub mod events;
+pub mod genai_bridge;
pub mod git;
#[cfg(feature = "cli")]
pub mod global_config;
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 41489e374..74a6564d3 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -1782,7 +1782,7 @@ mod tests {
use std::sync::Arc;
use tauri_plugin_agent_tools::permissions::ToolPermissions;
OrchestrationArgs {
- client: reqwest::Client::new(),
+ client: crate::core::agent::upstream::agent_http_client(),
provider_configs: Arc::new(tokio::sync::Mutex::new(
HashMap::<String, ProviderConfig>::new(),
)),
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index c03f96f81..bc6e499a1 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -9,7 +9,7 @@ use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
-use futures_util::StreamExt;
+#[cfg(not(feature = "cli"))]
use reqwest::Client;
use rmcp::model::{CallToolRequestParam, CallToolResult};
#[cfg(not(feature = "cli"))]
@@ -17,9 +17,9 @@ use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, Mutex};
use crate::core::agent::events::StreamEvent;
-use crate::core::openai_schema::{
- http_status_indicates_api_key_retry, normalize_openai_tool_parameters_schema,
-};
+use crate::core::openai_schema::normalize_openai_tool_parameters_schema;
+#[cfg(not(feature = "cli"))]
+use crate::core::openai_schema::http_status_indicates_api_key_retry;
#[cfg(not(feature = "cli"))]
use crate::core::server::proxy::router_upstream;
#[cfg(not(feature = "cli"))]
@@ -389,6 +389,15 @@ pub(crate) async fn resolve_upstream_for_model(
// the MLX session / llama-server router resolution below.
if let Some(api_url) = provider_cfg.base_url.clone().filter(|u| !u.is_empty()) {
let url = format!("{}{}", api_url, destination_path);
+ // Desktop-inherited providers arrive keyless in this build; the
+ // OS secret store is read here, for the one provider the run
+ // resolved to, rather than for every provider at load time.
+ #[cfg(feature = "cli")]
+ let provider_cfg = {
+ let mut cfg = provider_cfg;
+ crate::core::cli::providers::hydrate_provider_keys(&mut cfg);
+ cfg
+ };
return Ok((url, provider_cfg.bearer_key_chain()));
}
}
@@ -701,6 +710,7 @@ pub(crate) fn is_reasoning_field_error(err: &str) -> bool {
.any(|phrase| e.contains(phrase))
}
+#[cfg(not(feature = "cli"))]
/// 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
@@ -720,6 +730,7 @@ fn error_source_chain(err: &dyn std::error::Error) -> Vec<String> {
chain
}
+#[cfg(not(feature = "cli"))]
/// True when a failed send can be retried safely: the connection died before any
/// response arrived, so nothing has been streamed to the caller and no side
/// effect on the upstream is implied. Covers a refused/failed connect and the
@@ -734,6 +745,7 @@ fn is_retryable_send_error(err: &reqwest::Error) -> bool {
err.is_connect() || chain_indicates_dropped_connection(&error_source_chain(err))
}
+#[cfg(not(feature = "cli"))]
/// Whether an error's cause chain names a connection the peer dropped. Matched
/// on text because the io error is several opaque layers down (hyper's
/// `SendRequest` -> `connection error` -> `std::io::Error`) and its `ErrorKind`
@@ -754,11 +766,13 @@ fn chain_indicates_dropped_connection(chain: &[String]) -> bool {
})
}
+#[cfg(not(feature = "cli"))]
/// How long to wait before the one retry of a dropped connection. Long enough
/// for a load balancer that just recycled a backend to finish, short enough that
/// the user does not read it as a hang.
const SEND_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(250);
+#[cfg(not(feature = "cli"))]
/// Send a request, retrying it once when the connection dropped before any
/// response arrived. This is the failure a long turn invites: while tools run
/// locally no bytes flow, an idle keep-alive connection is reclaimed by the peer
@@ -793,22 +807,15 @@ async fn send_with_one_retry(req: reqwest::RequestBuilder) -> Result<reqwest::Re
})
}
-/// The HTTP client every agent turn goes through. `Client::new()`'s defaults are
-/// wrong for this traffic in one specific way: connections idle for up to 90s
-/// stay in the pool, but a turn spends far longer than that running tools, and
-/// the peer (or its load balancer) closes an idle connection well before then.
-/// Reusing one is the `Connection reset by peer` a long session eventually hits,
-/// so the pool is kept shorter-lived than any plausible upstream idle timeout.
-/// No overall request timeout: a streamed answer legitimately runs for minutes.
-pub(crate) fn agent_http_client() -> Client {
- Client::builder()
- .pool_idle_timeout(std::time::Duration::from_secs(15))
- .tcp_keepalive(std::time::Duration::from_secs(30))
- .connect_timeout(std::time::Duration::from_secs(30))
- .build()
- .unwrap_or_else(|_| Client::new())
+/// The HTTP client every agent turn goes through. Agent traffic now runs on
+/// `genai`, which is built against reqwest 0.13, so this is the aliased crate
+/// rather than the 0.12 `Client` the rest of the app (and the API server below)
+/// uses. Pool tuning lives with the builder in [`super::genai_bridge`].
+pub(crate) fn agent_http_client() -> reqwest13::Client {
+ super::genai_bridge::shared_http_client()
}
+#[cfg(not(feature = "cli"))]
/// 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
@@ -834,6 +841,7 @@ fn proxy_env_hint() -> Option<String> {
(!set.is_empty()).then(|| format!("proxy env set: {}", set.join(", ")))
}
+#[cfg(not(feature = "cli"))]
/// 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
@@ -868,365 +876,36 @@ pub(crate) fn describe_request_error(err: &reqwest::Error) -> String {
msg
}
+/// Stream a chat completion for the agent loop.
+///
+/// A thin delegate to [`super::genai_bridge`], which owns the wire format, SSE
+/// handling, provider field-name variance, and the retry policy. Every provider
+/// the agent talks to comes through here -- cloud, a Jan desktop API server, a
+/// local llama.cpp router, an MLX session -- so there is exactly one upstream
+/// implementation to reason about.
+///
+/// `api_type` selects the `genai` adapter. It is `None` for every caller today:
+/// the agent has always spoken OpenAI `/chat/completions` regardless of a
+/// provider's configured `api_type`, and honoring it here would silently change
+/// the wire format for an existing config. The API server's own converters
+/// (`core::server::converters`) remain the only consumer of that field.
pub(crate) async fn stream_openai_chat_completions(
- client: &Client,
+ client: &reqwest13::Client,
upstream_url: &str,
api_keys: &[String],
+ api_type: Option<&str>,
body: &serde_json::Value,
events: &mpsc::UnboundedSender<StreamEvent>,
) -> Result<serde_json::Value, String> {
- let mut req_body = body.clone();
- if let Some(obj) = req_body.as_object_mut() {
- obj.insert("stream".to_string(), serde_json::json!(true));
- obj.insert(
- "stream_options".to_string(),
- serde_json::json!({ "include_usage": true }),
- );
- }
-
- let attempts: Vec<Option<&str>> = if api_keys.is_empty() {
- vec![None]
- } else {
- api_keys.iter().map(|s| Some(s.as_str())).collect()
- };
-
- let mut last_err = String::new();
- for (i, key_ref) in attempts.iter().enumerate() {
- let mut req = client
- .post(upstream_url)
- .header("Content-Type", "application/json")
- .header("Accept", "text/event-stream")
- .header("Accept-Encoding", "identity");
-
- if let Some(key) = key_ref {
- req = req.header("Authorization", format!("Bearer {key}"));
- }
-
- let resp = send_with_one_retry(req.body(req_body.to_string())).await?;
-
- let status = resp.status();
- if status.is_success() {
- return consume_openai_sse(resp, events).await;
- }
-
- let text = resp.text().await.unwrap_or_default();
- last_err = format!("Upstream returned HTTP {status}: {text}");
- if is_context_overflow_body(&text) {
- last_err = format!("[{CONTEXT_OVERFLOW_MARKER}] {last_err}");
- }
- if http_status_indicates_api_key_retry(status) && i + 1 < attempts.len() {
- log::warn!("OpenAI stream: HTTP {status} with API key index {i}, trying next key");
- continue;
- }
-
- return Err(last_err);
- }
-
- Err(last_err)
-}
-
-#[derive(Default)]
-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,
- /// Bytes of `arguments` already forwarded as `ToolCallArgsDelta`. Zero
- /// until the first forward, which replays whatever arrived before the call
- /// could be announced.
- args_forwarded: usize,
-}
-
-/// Accumulates OpenAI SSE deltas into a single reconstructed completion. Kept
-/// separate from the byte-stream reader so it is unit-testable without a live
-/// HTTP response.
-#[derive(Default)]
-struct SseAccumulator {
- content: String,
- /// Natively streamed reasoning (`reasoning_content` deltas), accumulated so
- /// the reconstructed completion carries it back on the assistant message.
- /// Kept apart from `content`: reasoning is never part of the answer prose,
- /// but a caller resending assistant turns may forward it to the model.
- reasoning: String,
- tool_calls: Vec<ToolCallAccum>,
- finish_reason: Option<String>,
- usage: Option<serde_json::Value>,
- /// 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 {
- /// 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:") {
- let data = rest.trim();
- if !data.is_empty() {
- self.ingest(data, events);
- }
- }
- }
-
- fn ingest(&mut self, data: &str, events: &mpsc::UnboundedSender<StreamEvent>) {
- if data == "[DONE]" {
- return;
- }
- let json: serde_json::Value = match serde_json::from_str(data) {
- Ok(v) => v,
- 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());
- }
- }
-
- let Some(choice) = json
- .get("choices")
- .and_then(|c| c.as_array())
- .and_then(|a| a.first())
- else {
- return;
- };
-
- if let Some(fr) = choice.get("finish_reason").and_then(|v| v.as_str()) {
- self.finish_reason = Some(fr.to_string());
- }
-
- 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() {
- self.reasoning.push_str(text);
- let _ = events.send(StreamEvent::Reasoning {
- text: text.to_string(),
- });
- }
- }
-
- if let Some(text) = delta.get("content").and_then(|v| v.as_str()) {
- if !text.is_empty() {
- self.content.push_str(text);
- let _ = events.send(StreamEvent::Token {
- text: text.to_string(),
- });
- }
- }
-
- if let Some(tcs) = delta.get("tool_calls").and_then(|v| v.as_array()) {
- for tc in tcs {
- let idx = tc.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
- while self.tool_calls.len() <= idx {
- self.tool_calls.push(ToolCallAccum::default());
- }
- let slot = &mut self.tool_calls[idx];
- if let Some(id) = tc.get("id").and_then(|v| v.as_str()) {
- if !id.is_empty() {
- slot.id = id.to_string();
- }
- }
- let func = tc.get("function");
- if let Some(name) = func
- .and_then(|f| f.get("name"))
- .and_then(|v| v.as_str())
- .filter(|n| !n.is_empty())
- {
- slot.name = name.to_string();
- }
- let arg_delta = func
- .and_then(|f| f.get("arguments"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty());
- if let Some(arg) = arg_delta {
- 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(),
- });
- }
-
- // Forward the argument text itself, but only once the call has
- // been announced -- a delta with no preceding `ToolCallStarted`
- // has no call for the consumer to attach it to. Providers that
- // send arguments before the id/name are covered by the replay
- // below, which flushes what was buffered before the announce.
- if slot.started_emitted {
- if let Some(arg) = arg_delta {
- let delta = if slot.args_forwarded == 0 {
- // First forward after the announce: ship everything
- // accumulated so far, including any chunks that
- // arrived before id/name were known.
- slot.arguments.clone()
- } else {
- arg.to_string()
- };
- slot.args_forwarded = slot.arguments.len();
- let _ = events.send(StreamEvent::ToolCallArgsDelta {
- id: slot.id.clone(),
- delta,
- });
- }
- }
- }
- }
- }
-
- fn into_completion(self) -> serde_json::Value {
- let tool_calls: Vec<serde_json::Value> = self
- .tool_calls
- .into_iter()
- .filter(|t| !t.id.is_empty() || !t.name.is_empty() || !t.arguments.is_empty())
- .map(|t| {
- serde_json::json!({
- "id": t.id,
- "type": "function",
- "function": { "name": t.name, "arguments": t.arguments }
- })
- })
- .collect();
-
- let mut message = serde_json::Map::new();
- message.insert("role".to_string(), serde_json::json!("assistant"));
- message.insert(
- "content".to_string(),
- if self.content.is_empty() {
- serde_json::Value::Null
- } else {
- serde_json::json!(self.content)
- },
- );
- // Reasoning stays out of `content` but is carried on the message so a
- // caller that resends assistant turns to the model can forward it (and
- // so a turn that only reasoned still surfaces its reasoning). Empty is
- // omitted so non-reasoning providers produce an unchanged shape.
- if !self.reasoning.is_empty() {
- message.insert("reasoning_content".to_string(), serde_json::json!(self.reasoning));
- }
- if !tool_calls.is_empty() {
- message.insert(
- "tool_calls".to_string(),
- serde_json::Value::Array(tool_calls),
- );
- }
-
- let mut choice = serde_json::Map::new();
- choice.insert("index".to_string(), serde_json::json!(0));
- choice.insert("message".to_string(), serde_json::Value::Object(message));
- choice.insert(
- "finish_reason".to_string(),
- self.finish_reason
- .map(|s| serde_json::json!(s))
- .unwrap_or(serde_json::Value::Null),
- );
-
- let mut completion = serde_json::Map::new();
- completion.insert(
- "choices".to_string(),
- serde_json::Value::Array(vec![serde_json::Value::Object(choice)]),
- );
- if let Some(u) = self.usage {
- completion.insert("usage".to_string(), u);
- }
-
- serde_json::Value::Object(completion)
- }
-}
-
-/// Drain every complete (newline-terminated) line from `buf` into `acc`,
-/// leaving any trailing partial line buffered for the next chunk.
-fn drain_complete_lines(
- buf: &mut String,
- acc: &mut SseAccumulator,
- events: &mpsc::UnboundedSender<StreamEvent>,
-) {
- while let Some(nl) = buf.find('\n') {
- let line = buf[..nl].to_string();
- buf.drain(..=nl);
- acc.ingest_line(&line, events);
- }
-}
-
-/// Ingest a final, non-newline-terminated line left after the stream closes.
-/// Providers may end with `data: {...}` and no trailing blank line / `[DONE]`;
-/// without this the last chunk's finish_reason and tool-call args are dropped.
-fn flush_trailing_line(
- buf: &str,
- acc: &mut SseAccumulator,
- events: &mpsc::UnboundedSender<StreamEvent>,
-) {
- if !buf.trim().is_empty() {
- acc.ingest_line(buf, events);
- }
-}
-
-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 {
- // 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);
- }
- 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())
+ super::genai_bridge::stream_chat_completions(
+ client,
+ upstream_url,
+ api_keys,
+ api_type,
+ body,
+ events,
+ )
+ .await
}
#[cfg(test)]
@@ -1234,13 +913,7 @@ mod tests {
use super::*;
use serde_json::json;
- fn sink() -> (
- mpsc::UnboundedSender<StreamEvent>,
- mpsc::UnboundedReceiver<StreamEvent>,
- ) {
- mpsc::unbounded_channel()
- }
-
+ #[cfg(not(feature = "cli"))]
/// `reqwest` prints only its own layer, so the cause chain is where the
/// actual failure lives -- the whole point of `describe_request_error`.
#[test]
@@ -1278,6 +951,7 @@ mod tests {
);
}
+ #[cfg(not(feature = "cli"))]
/// 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]
@@ -1297,6 +971,7 @@ mod tests {
);
}
+ #[cfg(not(feature = "cli"))]
#[test]
fn dropped_connection_is_recognised_from_the_cause_chain() {
assert!(chain_indicates_dropped_connection(&[
@@ -1317,6 +992,7 @@ mod tests {
assert!(!chain_indicates_dropped_connection(&[]));
}
+ #[cfg(not(feature = "cli"))]
/// A refused connect never reached the peer, so retrying it is safe; a
/// timeout is excluded on purpose (retrying one doubles the wait).
#[tokio::test]
@@ -1345,65 +1021,7 @@ mod tests {
}
}
- /// The failure a long turn invites: the peer reclaims a keep-alive
- /// connection while tools run, and the next request is written into a socket
- /// that is already gone. One retry must carry the turn through, transparently
- /// -- the caller sees a normal completion, not an error.
- #[tokio::test]
- async fn a_dropped_first_connection_is_retried_and_the_turn_succeeds() {
- use tokio::io::{AsyncReadExt, AsyncWriteExt};
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind");
- let addr = listener.local_addr().expect("addr");
- let server = tokio::spawn(async move {
- // First connection: read the request, then hang up without a byte of
- // response -- exactly what a reclaimed pooled connection looks like.
- let (mut first, _) = listener.accept().await.expect("first accept");
- let mut scratch = [0u8; 1024];
- let _ = first.read(&mut scratch).await;
- drop(first);
-
- // Second connection: a normal one-token SSE answer.
- let (mut second, _) = listener.accept().await.expect("second accept");
- let _ = second.read(&mut scratch).await;
- let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n\
- data: [DONE]\n\n";
- let resp = format!(
- "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{sse}",
- sse.len()
- );
- let _ = second.write_all(resp.as_bytes()).await;
- let _ = second.flush().await;
- });
-
- let (tx, mut rx) = sink();
- let url = format!("http://{addr}/v1/chat/completions");
- let completion = stream_openai_chat_completions(
- &Client::new(),
- &url,
- &[],
- &json!({ "model": "m", "messages": [] }),
- &tx,
- )
- .await
- .expect("the retry carries the turn");
-
- assert_eq!(
- completion["choices"][0]["message"]["content"], "hi",
- "answer from the second connection: {completion}"
- );
- let mut tokens = Vec::new();
- while let Ok(ev) = rx.try_recv() {
- if let StreamEvent::Token { text } = ev {
- tokens.push(text);
- }
- }
- assert_eq!(tokens, vec!["hi".to_string()], "streamed once, not twice");
- server.await.expect("server task");
- }
-
+ #[cfg(not(feature = "cli"))]
/// A proxy in the environment breaks Jan and nothing else, and never shows up
/// in the error. Names only: the values carry credentials.
#[test]
@@ -1776,163 +1394,6 @@ mod tests {
));
}
- #[test]
- fn accumulates_content_and_emits_token_per_delta() {
- let (tx, mut rx) = sink();
- let mut acc = SseAccumulator::default();
- acc.ingest(
- &json!({ "choices": [{ "delta": { "content": "Hel" } }] }).to_string(),
- &tx,
- );
- acc.ingest(
- &json!({ "choices": [{ "delta": { "content": "lo" } }] }).to_string(),
- &tx,
- );
- acc.ingest(
- &json!({ "choices": [{ "delta": {}, "finish_reason": "stop" }] }).to_string(),
- &tx,
- );
-
- let completion = acc.into_completion();
- assert_eq!(completion["choices"][0]["message"]["content"], "Hello");
- assert_eq!(completion["choices"][0]["finish_reason"], "stop");
- assert!(completion["choices"][0]["message"]
- .get("tool_calls")
- .is_none());
-
- drop(tx);
- let mut tokens = Vec::new();
- while let Ok(ev) = rx.try_recv() {
- if let StreamEvent::Token { text } = ev {
- tokens.push(text);
- }
- }
- assert_eq!(tokens, vec!["Hel", "lo"]);
- }
-
- #[test]
- 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(
- &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 stays out of the answer prose, but is preserved on the
- // reconstructed message so a caller can resend it as history.
- let completion = acc.into_completion();
- assert_eq!(completion["choices"][0]["message"]["content"], "answer");
- assert_eq!(
- completion["choices"][0]["message"]["reasoning_content"],
- "let me think"
- );
-
- drop(tx);
- let mut reasoning = Vec::new();
- let mut tokens = Vec::new();
- while let Ok(ev) = rx.try_recv() {
- match ev {
- StreamEvent::Reasoning { text } => reasoning.push(text),
- StreamEvent::Token { text } => tokens.push(text),
- _ => {}
- }
- }
- // 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_emits_reasoning_and_no_tokens() {
- 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 reasoning = Vec::new();
- let mut tokens = Vec::new();
- 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:?}");
- }
-
- /// A completion with no `reasoning_content` deltas must keep exactly the
- /// shape it always had: the field is omitted, not emitted empty, so a
- /// provider that rejects unknown assistant keys is unaffected.
- #[test]
- fn a_turn_without_reasoning_omits_the_field_entirely() {
- let (tx, _rx) = sink();
- let mut acc = SseAccumulator::default();
- acc.ingest(
- &json!({ "choices": [{ "delta": { "content": "answer" } }] }).to_string(),
- &tx,
- );
- let completion = acc.into_completion();
- let message = &completion["choices"][0]["message"];
- assert_eq!(message["content"], "answer");
- assert!(
- message.get("reasoning_content").is_none(),
- "no reasoning streamed, so the key must be absent: {message}"
- );
- }
-
- /// A tool-call turn's reasoning is preserved too: the model reasons about
- /// which tool to call, and that reasoning has to survive onto the assistant
- /// turn the loop resends with its `tool_calls`.
- #[test]
- fn reasoning_is_preserved_on_a_tool_call_turn() {
- let (tx, _rx) = sink();
- let mut acc = SseAccumulator::default();
- acc.ingest(
- &json!({ "choices": [{ "delta": { "reasoning_content": "need to grep" } }] })
- .to_string(),
- &tx,
- );
- acc.ingest(
- &json!({ "choices": [{ "delta": { "tool_calls": [{
- "index": 0,
- "id": "c1",
- "function": { "name": "bash", "arguments": "{}" }
- }] } }] })
- .to_string(),
- &tx,
- );
- let completion = acc.into_completion();
- let message = &completion["choices"][0]["message"];
- assert_eq!(message["reasoning_content"], "need to grep");
- assert_eq!(message["tool_calls"][0]["id"], "c1");
- }
-
/// A resent assistant turn keeps its `reasoning_content` through the message
/// normalizer. Local llama.cpp templates with `preserve_thinking` re-emit
/// prior reasoning from this field; dropping it would shrink earlier turns
@@ -1964,208 +1425,4 @@ mod tests {
"an assistant turn with no reasoning stays unchanged"
);
}
-
- /// 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>answer"]);
- }
-
- #[test]
- fn reassembles_tool_call_arguments_split_across_deltas() {
- let (tx, _rx) = sink();
- let mut acc = SseAccumulator::default();
- acc.ingest(
- &json!({ "choices": [{ "delta": { "tool_calls": [
- { "index": 0, "id": "call_1", "function": { "name": "search", "arguments": "{\"q\":" } }
- ] } }] })
- .to_string(),
- &tx,
- );
- acc.ingest(
- &json!({ "choices": [{ "delta": { "tool_calls": [
- { "index": 0, "function": { "arguments": "\"rust\"}" } }
- ] } }] })
- .to_string(),
- &tx,
- );
- acc.ingest(
- &json!({ "choices": [{ "delta": {}, "finish_reason": "tool_calls" }],
- "usage": { "total_tokens": 12 } })
- .to_string(),
- &tx,
- );
-
- let completion = acc.into_completion();
- let tc = &completion["choices"][0]["message"]["tool_calls"][0];
- assert_eq!(tc["id"], "call_1");
- assert_eq!(tc["function"]["name"], "search");
- assert_eq!(tc["function"]["arguments"], "{\"q\":\"rust\"}");
- assert_eq!(completion["choices"][0]["finish_reason"], "tool_calls");
- 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();
- let mut acc = SseAccumulator::default();
- acc.ingest("[DONE]", &tx);
- acc.ingest("not json", &tx);
- let completion = acc.into_completion();
- assert!(completion["choices"][0]["message"]["content"].is_null());
- }
-
- /// Feed arbitrary byte chunks through the real buffering path, then close.
- fn feed_and_close(
- chunks: &[&str],
- events: &mpsc::UnboundedSender<StreamEvent>,
- ) -> serde_json::Value {
- let mut buf = String::new();
- let mut acc = SseAccumulator::default();
- for c in chunks {
- buf.push_str(c);
- drain_complete_lines(&mut buf, &mut acc, events);
- }
- flush_trailing_line(&buf, &mut acc, events);
- acc.into_completion()
- }
-
- #[test]
- fn flushes_final_line_without_trailing_newline() {
- let (tx, _rx) = sink();
- // Provider closes right after the final data line: no `\n`, no `[DONE]`.
- let final_chunk = json!({ "choices": [{ "delta": {}, "finish_reason": "tool_calls" }] });
- let completion = feed_and_close(
- &[
- "data: ",
- &json!({ "choices": [{ "delta": { "content": "hi" } }] }).to_string(),
- "\n\ndata: ",
- &final_chunk.to_string(),
- ],
- &tx,
- );
-
- assert_eq!(completion["choices"][0]["message"]["content"], "hi");
- assert_eq!(completion["choices"][0]["finish_reason"], "tool_calls");
- }
-
- #[test]
- fn newline_terminated_stream_still_parses() {
- let (tx, _rx) = sink();
- let completion = feed_and_close(
- &[
- &format!(
- "data: {}\n\n",
- json!({ "choices": [{ "delta": { "content": "ok" }, "finish_reason": "stop" }] })
- ),
- "data: [DONE]\n\n",
- ],
- &tx,
- );
- assert_eq!(completion["choices"][0]["message"]["content"], "ok");
- assert_eq!(completion["choices"][0]["finish_reason"], "stop");
- }
}
diff --git a/src-tauri/src/core/cli/brand.rs b/src-tauri/src/core/cli/brand.rs
index 0d0f6cb55..b53ecf6df 100644
--- a/src-tauri/src/core/cli/brand.rs
+++ b/src-tauri/src/core/cli/brand.rs
@@ -14,61 +14,12 @@ pub const LOGO: [&str; 6] = [
pub const LOGO_WIDTH: u16 = 25;
-/// The Jan hand-wave mark: the brand logo rendered above the wordmark in the
-/// TUI splash, and repeatedly whenever a slash command starts a fresh view
-/// (`/clear`, `/new`, `/resume`). Each glyph cell is one terminal column, so
-/// `HAND_WIDTH` is the rendered width.
-pub const HAND: [&str; 15] = [
- r" ██ ███ ",
- r" ███████████ ████ ",
- r" ███ ██ ██ ███ ██ ",
- r" ██ ███ ███ ███ ██ █ ",
- r" ██ ███ ██ ██ ███ ",
- r" ██ ███ ███ ███ ██ ██",
- r" █████ ███ ██ ████ ██",
- r" ██ ██ ██ ██ ██",
- r" ███ ███ █ ██",
- r" █ █ ██ ██ ██",
- r" ██ ██ ███ █ ",
- r" ██ ██ ██ ██ ",
- r" ████ ███ ███ ",
- r" ████ █████ ",
- r" ████████ ",
-];
-
-pub const HAND_WIDTH: u16 = 32;
-
/// The hand-wave mark as a single glyph, for the header's leading column where
/// the block art has no room. No VS16: the emoji is already presentation-default
/// and the extra selector makes some terminals advance a column ratatui has not
/// reserved, which shifts the rest of the row.
pub const WAVE: &str = "\u{1F44B}";
-/// Columns between the hand mark and the wordmark in the lockup.
-const LOCKUP_GAP: u16 = 2;
-
-/// Rendered width of `lockup()`.
-pub const LOCKUP_WIDTH: u16 = HAND_WIDTH + LOCKUP_GAP + LOGO_WIDTH;
-
-/// The full brand lockup: the hand mark with the wordmark set beside it,
-/// vertically centred against the hand. Lines are padded to `LOCKUP_WIDTH`.
-pub fn lockup() -> Vec<String> {
- let gap = " ".repeat(LOCKUP_GAP as usize);
- let top = (HAND.len() - LOGO.len()) / 2;
- HAND.iter()
- .enumerate()
- .map(|(i, hand)| {
- let word = i
- .checked_sub(top)
- .and_then(|row| LOGO.get(row))
- .copied()
- .unwrap_or("");
- let pad = LOGO_WIDTH as usize - word.chars().count();
- format!("{hand}{gap}{word}{}", " ".repeat(pad))
- })
- .collect()
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -83,52 +34,4 @@ mod tests {
);
}
}
-
- #[test]
- fn every_hand_line_is_the_advertised_width() {
- for line in HAND {
- assert_eq!(
- line.chars().count(),
- HAND_WIDTH as usize,
- "ragged hand line: {line}"
- );
- }
- }
-
- #[test]
- fn every_lockup_line_is_the_advertised_width() {
- let lockup = lockup();
- assert_eq!(lockup.len(), HAND.len(), "the lockup is as tall as the hand");
- for line in &lockup {
- assert_eq!(
- line.chars().count(),
- LOCKUP_WIDTH as usize,
- "ragged lockup line: {line}"
- );
- }
- }
-
- /// Side by side, not stacked: the wordmark shares its rows with the hand,
- /// centred against it.
- #[test]
- fn the_wordmark_sits_beside_the_hand() {
- let lockup = lockup();
- let rows: Vec<usize> = lockup
- .iter()
- .enumerate()
- .filter(|(_, l)| l[..].contains(LOGO[0].trim()) || l.contains(LOGO[3].trim()))
- .map(|(i, _)| i)
- .collect();
- assert!(!rows.is_empty(), "wordmark missing from the lockup");
- for row in rows {
- let line = &lockup[row];
- let hand = HAND[row].trim();
- assert!(
- !hand.is_empty() && line.contains(hand),
- "row {row} must carry the hand too: {line}"
- );
- }
- let blank_above = lockup[0].chars().skip(HAND_WIDTH as usize).all(|c| c == ' ');
- assert!(blank_above, "the wordmark should be centred, not flush top");
- }
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 41890cdcd..1950895a3 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -517,7 +517,7 @@ pub fn cli_agent_status(
serde_json::json!({
"provider": c.provider,
"base_url": c.base_url,
- "has_api_key": c.api_key.is_some() || !c.api_keys.is_empty(),
+ "has_api_key": crate::core::cli::providers::has_credential(c),
"models": c.models.len(),
})
})
@@ -829,6 +829,17 @@ pub struct SessionFlags {
pub sandbox: Option<bool>,
}
+/// The desktop app's currently-selected model, adopted only when signed in to
+/// Tokamak. Split out from the resolution chain so the rule is testable without
+/// a `settings.json` on disk; see the note at the call site for why the sign-in
+/// gates it.
+fn inherit_desktop_model(
+ signed_in: bool,
+ selection: crate::core::cli::providers::DesktopSelection,
+) -> Option<String> {
+ signed_in.then_some(selection.model).flatten()
+}
+
/// Resolve project config + credentials into a ready-to-run engine handle.
/// Shared by `run_agent_loop` (plain CLI) and `cli_agent_ui` (TUI).
fn prepare_agent_session(
@@ -850,11 +861,24 @@ fn prepare_agent_session(
// model), then the desktop app's currently-selected model (settings.json
// inherit). Global config outranks desktop so a standalone agent is
// self-sufficient without a desktop install.
+ //
+ // The desktop inherit is the last resort and applies only when signed in to
+ // Tokamak. Without a sign-in, silently adopting whatever model the desktop
+ // app last had selected starts the session on a provider the user never
+ // chose here -- and hides the sign-in notice that would otherwise fire,
+ // because a non-empty model reads as "configured". Leaving it unset surfaces
+ // the notice instead. An explicit --model, agent.toml, or ~/.jan default is
+ // unaffected: all three outrank this.
let explicit = model_override.is_some() || overrides.api_key.is_some();
let model = model_override
.or_else(|| cfg.agent.model.clone())
.or_else(|| crate::core::agent::global_config::default_model().ok().flatten())
- .or_else(|| crate::core::cli::providers::desktop_selection().model);
+ .or_else(|| {
+ inherit_desktop_model(
+ crate::core::cli::tokamak::auth_status().signed_in,
+ crate::core::cli::providers::desktop_selection(),
+ )
+ });
// A project or global default can name a model with nobody around to serve
// it (e.g. this repo's own agent.toml pins one, but a fresh `~/.jan` has no
// credentials for anything). Trust it only when the user was explicit
@@ -1292,6 +1316,14 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
print!("{text}");
let _ = std::io::stdout().flush();
}
+ // A command's live output is progress, not answer: it goes to stderr so a
+ // piped stdout still holds only the model's completion. The full output
+ // arrives again with the tool result, which is what the model sees; this
+ // is purely so a long command is not silent in a headless run.
+ StreamEvent::ToolOutputDelta { delta, .. } => {
+ eprint!("\x1b[2m{delta}\x1b[0m");
+ let _ = std::io::stderr().flush();
+ }
// Reasoning is progress, not answer: dimmed on stderr so piping stdout
// yields only the real completion.
StreamEvent::Reasoning { text } => {
@@ -1415,6 +1447,36 @@ async fn prompt_permission(
mod tests {
use super::*;
+ /// Signing in to Tokamak is what unlocks the desktop inherit. Without it the
+ /// model stays unset so the TUI's sign-in notice fires, instead of the
+ /// session silently starting on whatever the desktop app last had selected.
+ #[test]
+ fn desktop_model_is_inherited_only_when_signed_in() {
+ let selection = crate::core::cli::providers::DesktopSelection {
+ provider: Some("llamacpp".into()),
+ model: Some("gemma-4-E2B-it-IQ4_XS".into()),
+ };
+ assert_eq!(
+ inherit_desktop_model(true, selection.clone()).as_deref(),
+ Some("gemma-4-E2B-it-IQ4_XS"),
+ );
+ assert_eq!(
+ inherit_desktop_model(false, selection),
+ None,
+ "a signed-out session does not adopt the desktop's selection"
+ );
+ }
+
+ /// Signed in but the desktop has no selection (or no desktop at all) is not
+ /// an error -- it just contributes nothing to the chain.
+ #[test]
+ fn an_empty_desktop_selection_contributes_nothing() {
+ assert_eq!(
+ inherit_desktop_model(true, crate::core::cli::providers::DesktopSelection::default()),
+ None
+ );
+ }
+
// ── resume ─────────────────────────────────────────────────────────────
#[test]
@@ -1793,6 +1855,59 @@ mod tests {
});
}
+ /// End-to-end for the sign-in gate, arranged so the pre-existing
+ /// "nothing usable is configured" guard cannot mask it: a usable non-Tokamak
+ /// provider is present (so the guard passes) but names no models (so
+ /// `default_model` contributes nothing), leaving the desktop inherit as the
+ /// only thing that could supply a model. Signed out, it must not.
+ #[test]
+ fn a_signed_out_session_does_not_adopt_the_desktop_model() {
+ crate::core::agent::global_config::with_temp_home(|home| {
+ crate::core::agent::global_config::set_provider(
+ "openai",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("sk-test".into()),
+ base_url: Some("https://api.openai.com/v1".into()),
+ models: Some(vec![]),
+ ..Default::default()
+ },
+ )
+ .expect("seed provider");
+
+ let data = home.join("jan-data");
+ std::fs::create_dir_all(&data).unwrap();
+ std::fs::write(
+ data.join("settings.json"),
+ r#"{"model-provider":"{\"state\":{\"selectedProvider\":\"llamacpp\",\"selectedModel\":{\"id\":\"gemma-4-E2B-it-IQ4_XS\"}}}"}"#,
+ )
+ .unwrap();
+ std::env::set_var("JAN_DATA_FOLDER", &data);
+
+ // Sanity: the desktop selection really is readable, so a passing
+ // assertion below means the gate fired, not that the fixture is dead.
+ assert_eq!(
+ crate::core::cli::providers::desktop_selection().model.as_deref(),
+ Some("gemma-4-E2B-it-IQ4_XS")
+ );
+ assert!(!crate::core::cli::tokamak::auth_status().signed_in);
+
+ let dir = tempfile::tempdir().unwrap();
+ let session = prepare_agent_session(
+ dir.path().to_str().unwrap(),
+ None,
+ ProviderOverrides::default(),
+ SessionFlags::default(),
+ )
+ .expect("session prep");
+ std::env::remove_var("JAN_DATA_FOLDER");
+
+ assert_eq!(
+ session.model, "",
+ "signed out, the desktop's last selection must not become the session model"
+ );
+ });
+ }
+
/// The same project config, once a provider is actually usable, must be
/// trusted again.
#[test]
diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rs
index b1b420f17..4c688dee8 100644
--- a/src-tauri/src/core/cli/providers.rs
+++ b/src-tauri/src/core/cli/providers.rs
@@ -145,9 +145,7 @@ fn is_usable(config: &ProviderConfig) -> bool {
if !is_cli_reachable(config) {
return false;
}
- config.api_key.is_some()
- || !config.api_keys.is_empty()
- || config.base_url.as_deref().is_some_and(is_loopback_url)
+ has_credential(config) || config.base_url.as_deref().is_some_and(is_loopback_url)
}
/// Whether a base URL points at this machine, where an API key is usually not
@@ -168,15 +166,31 @@ pub(crate) fn is_loopback_url(url: &str) -> bool {
matches!(host, "localhost" | "127.0.0.1" | "0.0.0.0" | "::1")
}
-/// `(provider, model_id)` pairs the CLI can actually run, sorted by provider
-/// then model.
+/// `(provider, model_id)` pairs the CLI can actually run: Tokamak first, then
+/// every other provider by name, models sorted within each.
+///
+/// Tokamak leads because it is the provider the product signs users in to; a
+/// plain alphabetical sort buried it below whatever else happened to be
+/// configured. Ordering only -- nothing is filtered by provider, so a user who
+/// prefers another provider still sees it.
pub fn reachable_models(configs: &HashMap<String, ProviderConfig>) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = configs
.values()
.filter(|c| is_cli_reachable(c))
.flat_map(|c| c.models.iter().map(|m| (c.provider.clone(), m.clone())))
.collect();
- out.sort();
+ // `false < true`, so the Tokamak rows sort ahead of everything else while
+ // the rest stay alphabetical.
+ out.sort_by(|a, b| {
+ let key = |(provider, model): &(String, String)| {
+ (
+ provider != super::tokamak::PROVIDER,
+ provider.clone(),
+ model.clone(),
+ )
+ };
+ key(a).cmp(&key(b))
+ });
out
}
@@ -247,25 +261,28 @@ pub async fn fetch_missing_models(
.filter(|c| {
global.contains_key(&c.provider) && is_cli_reachable(c) && c.models.is_empty()
})
- .map(|c| {
- (
- c.provider.clone(),
- c.base_url.clone().unwrap_or_default(),
- c.bearer_key_chain(),
- )
- })
// Probe each provider at most once per session. A provider that still
// has an empty list after a probe was unreachable or offered nothing;
// re-probing it on every bare `/model` would freeze the render loop
- // for the full request timeout each time.
- .filter(|(name, base_url, _)| {
- let tag = format!("{name}|{base_url}");
+ // for the full request timeout each time. Filtered before the key is
+ // fetched so a re-open cannot re-prompt for a provider already probed.
+ .filter(|c| {
+ let tag = format!("{}|{}", c.provider, c.base_url.clone().unwrap_or_default());
if already_probed.contains(&tag) {
return false;
}
already_probed.insert(tag);
true
})
+ .cloned()
+ .map(|mut c| {
+ hydrate_provider_keys(&mut c);
+ (
+ c.provider.clone(),
+ c.base_url.clone().unwrap_or_default(),
+ c.bearer_key_chain(),
+ )
+ })
.collect();
if to_fetch.is_empty() {
return Ok(false);
@@ -391,17 +408,20 @@ pub fn load_provider_configs(
/// Layer in providers from Desktop's `settings.json` that Global doesn't
/// already define. Read-only inherit: never overwrites a Global entry, never
-/// writes back to `settings.json`. Secrets are seeded from the OS keyring /
-/// encrypted fallback file (#8388) since they no longer live in the JSON blob.
+/// writes back to `settings.json`.
+///
+/// Their secrets live in the OS keyring (#8388) and are deliberately *not*
+/// read here: this runs on startup, on every `/model` open and on every status
+/// call, and reading N keychain items costs N macOS authorization prompts for
+/// providers a run will never select. Keys are fetched by
+/// [`hydrate_provider_keys`] for the one provider that is actually used;
+/// [`has_stored_key`] answers presence without touching the secret.
fn inherit_desktop_providers(configs: &mut HashMap<String, ProviderConfig>) {
let path = resolve_jan_data_folder().join("settings.json");
- let mut desktop_configs = match std::fs::read_to_string(&path) {
+ let desktop_configs = match std::fs::read_to_string(&path) {
Ok(raw) => parse_provider_store(&raw),
Err(_) => return,
};
- seed_keys_from_store(&mut desktop_configs, |p| {
- crate::core::server::provider_secrets::load_provider_keys(p)
- });
for (name, cfg) in desktop_configs {
configs.entry(name).or_insert(cfg);
}
@@ -439,24 +459,40 @@ fn provider_config_from_section(section: ProviderSection) -> ProviderConfig {
/// Seed each config's key chain from the secret store when the settings blob
/// carried no key. `load` is injected for testability. Explicit `--api-key`/env
/// overrides run afterward and still win.
-fn seed_keys_from_store(
- configs: &mut HashMap<String, ProviderConfig>,
- load: impl Fn(&str) -> Vec<String>,
-) {
- for (name, cfg) in configs.iter_mut() {
- if cfg.api_key.is_some() {
- continue;
- }
- let keys = load(name);
- if !keys.is_empty() {
- cfg.api_key = keys.first().cloned();
- cfg.api_keys = keys;
- }
+/// Fill in a provider's key chain from the OS secret store, on demand.
+///
+/// No-op when the config already carries one: `~/.jan/config.toml` providers
+/// (Tokamak included) hold their key inline, as do `--api-key`/env overrides,
+/// so the prioritized path never reaches the keyring at all. Call this only for
+/// a provider that is about to be used -- each call can cost a macOS keychain
+/// prompt.
+pub fn hydrate_provider_keys(config: &mut ProviderConfig) {
+ hydrate_with(config, |p| {
+ crate::core::server::provider_secrets::load_provider_keys(p)
+ })
+}
+
+fn hydrate_with(config: &mut ProviderConfig, mut load: impl FnMut(&str) -> Vec<String>) {
+ if !config.bearer_key_chain().is_empty() {
+ return;
+ }
+ let keys = load(&config.provider);
+ if !keys.is_empty() {
+ config.api_key = keys.first().cloned();
+ config.api_keys = keys;
}
}
+/// Whether `config` can present a key, without reading one. Inline keys answer
+/// themselves; anything else defers to the secret store's presence index.
+pub fn has_credential(config: &ProviderConfig) -> bool {
+ !config.bearer_key_chain().is_empty()
+ || crate::core::server::provider_secrets::has_stored_key(&config.provider)
+}
+
/// Parse the `settings.json` body into provider configs. Tolerant of shape
-/// drift: anything it cannot read is skipped rather than erroring.
+/// drift: anything it cannot read is skipped rather than erroring. Providers
+/// Desktop has marked inactive are skipped too (see `provider_from_json`).
fn parse_provider_store(raw: &str) -> HashMap<String, ProviderConfig> {
let root: serde_json::Value = match serde_json::from_str(raw) {
Ok(v) => v,
@@ -493,6 +529,16 @@ fn parse_provider_store(raw: &str) -> HashMap<String, ProviderConfig> {
fn provider_from_json(p: &serde_json::Value) -> Option<ProviderConfig> {
let provider = p.get("provider").and_then(|v| v.as_str())?.to_string();
+ // A provider the user switched off in Desktop is not an option here either.
+ // Desktop stops registering an inactive provider (`syncRemoteProviders`
+ // gates on `active`), so inheriting one meant offering an entry whose key
+ // Desktop no longer maintains. Absent field = inherit: `active` is written
+ // for every provider Desktop creates, so only an explicit `false` is a
+ // deliberate opt-out.
+ if p.get("active").and_then(|v| v.as_bool()) == Some(false) {
+ return None;
+ }
+
let base_url = p
.get("base_url")
.and_then(|v| v.as_str())
@@ -605,6 +651,34 @@ mod tests {
assert!(openai.api_keys.is_empty());
}
+ /// Desktop stops maintaining an inactive provider's key, so inheriting one
+ /// offers an entry that cannot run and reports as keyless.
+ #[test]
+ fn an_inactive_desktop_provider_is_not_inherited() {
+ let store = STORE.replace(
+ r#"{\"provider\":\"openai\""#,
+ r#"{\"provider\":\"openai\",\"active\":false"#,
+ );
+ let configs = parse_provider_store(&store);
+ assert!(!configs.contains_key("openai"), "inactive provider skipped");
+ assert!(configs.contains_key("anthropic"), "active one still there");
+ }
+
+ #[test]
+ fn an_active_desktop_provider_is_inherited() {
+ let store = STORE.replace(
+ r#"{\"provider\":\"openai\""#,
+ r#"{\"provider\":\"openai\",\"active\":true"#,
+ );
+ assert!(parse_provider_store(&store).contains_key("openai"));
+ }
+
+ /// Stores predating the flag, and any shape drift, must keep working.
+ #[test]
+ fn a_provider_without_the_active_flag_is_inherited() {
+ assert!(parse_provider_store(STORE).contains_key("openai"));
+ }
+
#[test]
fn malformed_store_yields_empty_map() {
assert!(parse_provider_store("not json").is_empty());
@@ -653,14 +727,14 @@ mod tests {
}
#[test]
- fn seed_fills_missing_key_from_store() {
+ fn hydrate_fills_missing_key_from_store() {
let mut configs = parse_provider_store(STORE);
- // openai has an empty key in the blob -> should be seeded.
- seed_keys_from_store(&mut configs, |p| match p {
+ // openai has an empty key in the blob -> should be filled in.
+ let openai = configs.get_mut("openai").unwrap();
+ hydrate_with(openai, |p| match p {
"openai" => vec!["sk-stored-1".to_string(), "sk-stored-2".to_string()],
_ => Vec::new(),
});
- let openai = configs.get("openai").unwrap();
assert_eq!(openai.api_key.as_deref(), Some("sk-stored-1"));
assert_eq!(
openai.api_keys,
@@ -669,19 +743,43 @@ mod tests {
}
#[test]
- fn seed_does_not_clobber_existing_key() {
+ fn hydrate_does_not_clobber_existing_key() {
let mut configs = parse_provider_store(STORE);
// anthropic already has sk-ant-123 from the blob -> store must not win.
- seed_keys_from_store(&mut configs, |_| vec!["sk-should-not-apply".to_string()]);
- let anthropic = configs.get("anthropic").unwrap();
+ let anthropic = configs.get_mut("anthropic").unwrap();
+ hydrate_with(anthropic, |_| vec!["sk-should-not-apply".to_string()]);
assert_eq!(anthropic.api_key.as_deref(), Some("sk-ant-123"));
}
+ /// The whole point of deferring: a desktop-inherited provider is keyless
+ /// as loaded, and reaches the secret store exactly once, only when it is
+ /// the provider actually being used -- each read can cost a macOS keychain
+ /// prompt.
#[test]
- fn seed_empty_store_leaves_key_none() {
+ fn a_desktop_provider_stays_keyless_until_hydrated() {
let mut configs = parse_provider_store(STORE);
- seed_keys_from_store(&mut configs, |_| Vec::new());
- assert_eq!(configs.get("openai").unwrap().api_key, None);
+ let openai = configs.get_mut("openai").unwrap();
+ assert_eq!(openai.api_key, None, "keyless until hydrated");
+
+ let mut reads = 0;
+ hydrate_with(openai, |_| {
+ reads += 1;
+ Vec::new()
+ });
+ assert_eq!(reads, 1, "and exactly one read when it is");
+ assert_eq!(openai.api_key, None);
+ }
+
+ #[test]
+ fn hydrate_skips_the_store_when_a_key_is_already_present() {
+ let mut configs = parse_provider_store(STORE);
+ let anthropic = configs.get_mut("anthropic").unwrap();
+ let mut reads = 0;
+ hydrate_with(anthropic, |_| {
+ reads += 1;
+ Vec::new()
+ });
+ assert_eq!(reads, 0, "an inline key must not trigger a store read");
}
#[test]
@@ -787,6 +885,51 @@ mod tests {
assert!(!is_loopback_url(""));
}
+ /// Tokamak leads the `/model` picker; everything else keeps its alphabetical
+ /// order behind it, and models stay sorted within each provider.
+ #[test]
+ fn reachable_models_lists_tokamak_first() {
+ let mut configs = HashMap::new();
+ configs.insert(
+ "anthropic".to_string(),
+ cfg("anthropic", Some("https://api.anthropic.com/v1"), &["claude-sonnet-5"]),
+ );
+ configs.insert(
+ "tokamak".to_string(),
+ cfg("tokamak", Some("https://api.tokamak.sh/v1"), &["tokamak-1-preview"]),
+ );
+ configs.insert(
+ "openai".to_string(),
+ cfg("openai", Some("https://api.openai.com/v1"), &["gpt-5", "gpt-4o"]),
+ );
+
+ assert_eq!(
+ reachable_models(&configs),
+ vec![
+ ("tokamak".to_string(), "tokamak-1-preview".to_string()),
+ ("anthropic".to_string(), "claude-sonnet-5".to_string()),
+ ("openai".to_string(), "gpt-4o".to_string()),
+ ("openai".to_string(), "gpt-5".to_string()),
+ ]
+ );
+ }
+
+ /// Ordering is the only change: with no Tokamak entry the list is exactly
+ /// the alphabetical order it always was.
+ #[test]
+ fn without_tokamak_the_order_is_unchanged() {
+ let mut configs = HashMap::new();
+ configs.insert("zeta".to_string(), cfg("zeta", Some("https://z.example/v1"), &["z1"]));
+ configs.insert("alpha".to_string(), cfg("alpha", Some("https://a.example/v1"), &["a1"]));
+ assert_eq!(
+ reachable_models(&configs),
+ vec![
+ ("alpha".to_string(), "a1".to_string()),
+ ("zeta".to_string(), "z1".to_string()),
+ ]
+ );
+ }
+
#[test]
fn reachable_models_skips_local_engine_providers() {
let mut configs = HashMap::new();
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 256a8836b..2a3cac134 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -817,11 +817,10 @@ fn banner_lines(banner: &Banner, width: u16) -> Vec<Line<'static>> {
let indent = " ".repeat(BANNER_INDENT as usize);
let mut out: Vec<Line<'static>> = Vec::new();
- // A clipped logo reads as breakage, so a narrow terminal gets the name
- // as text instead. The lockup (hand beside the wordmark) is the widest
- // splash element, so it sets the threshold that gates the whole block.
- if width >= brand::LOCKUP_WIDTH + BANNER_INDENT * 2 {
- for art in brand::lockup() {
+ // A clipped wordmark reads as breakage, so a narrow terminal gets the name
+ // as text instead.
+ if width >= brand::LOGO_WIDTH + BANNER_INDENT * 2 {
+ for art in brand::LOGO {
out.push(Line::styled(format!("{indent}{art}"), accent));
}
out.push(Line::raw(""));
@@ -1438,6 +1437,21 @@ struct App {
/// until the command finishes, so without this its row -- live for as long
/// as the command runs -- has nothing to name.
bash_jobs: HashMap<String, String>,
+ /// Output streamed by each `bash` call so far, keyed by call id, bounded to
+ /// [`LIVE_OUTPUT_MAX_BYTES`] from the end. This is what turns a running
+ /// command from a spinner into a terminal.
+ live_output: HashMap<String, String>,
+ /// When each call's first output arrived, gating the panel by
+ /// [`LIVE_OUTPUT_GRACE`] so a command that finishes quickly never flashes a
+ /// box on its way to the group summary.
+ live_since: HashMap<String, Instant>,
+ /// Maps the call that *collects* a backgrounded job to the call that
+ /// *started* it. The job keeps streaming under the original id, so without
+ /// this the collecting call -- the one the user is actually waiting on --
+ /// would show an empty box while the output piled up out of sight.
+ live_alias: HashMap<String, String>,
+ /// Call id that started each backgrounded job, keyed by `job_id`.
+ job_origin: HashMap<String, String>,
/// Base snapshot (working-tree state before the first turn) for the active
/// thread. `Some` once snapshotting is armed; `None` = no workspace restore.
base_snapshot: Option<String>,
@@ -2005,6 +2019,10 @@ impl App {
diff_paths: HashMap::new(),
bash_commands: HashMap::new(),
bash_jobs: HashMap::new(),
+ live_output: HashMap::new(),
+ live_since: HashMap::new(),
+ live_alias: HashMap::new(),
+ job_origin: HashMap::new(),
base_snapshot: None,
checkpoints: Vec::new(),
snap_queue: std::collections::VecDeque::new(),
@@ -2479,6 +2497,44 @@ impl App {
self.awaiting.clear();
}
+ /// The live shell panel for `group`'s newest unresolved *command*, or no rows
+ /// when nothing in the group is streaming yet.
+ ///
+ /// Picks the newest call that has output rather than the newest call
+ /// outright: a group runs its calls in parallel, so a `read` issued after a
+ /// `bash` must not blank the panel until it lands and then let it pop back.
+ ///
+ /// Follows the job alias, so a call *waiting on* a backgrounded job shows the
+ /// output the detached job is still producing under the id of the call that
+ /// started it.
+ fn live_shell_panel(&self, group: &ToolGroup, width: u16) -> Vec<Line<'static>> {
+ let Some((command, output)) = group
+ .calls
+ .iter()
+ .rev()
+ .filter(|c| c.content.is_none())
+ .find_map(|c| self.live_view(&c.id))
+ else {
+ return Vec::new();
+ };
+ shell_panel_lines(command, output, width, SHELL_PANEL_GUTTER)
+ }
+
+ /// A call's command and the output it has streamed, once both exist and the
+ /// command has been running long enough to be worth a box.
+ fn live_view(&self, id: &str) -> Option<(&str, &str)> {
+ let command = self.bash_commands.get(id)?;
+ let key = self.live_alias.get(id).map_or(id, String::as_str);
+ let output = self.live_output.get(key)?;
+ // A command that prints and exits inside the grace period renders no box
+ // at all, so its output never appears only to be yanked away a frame
+ // later by the group summary.
+ if self.live_since.get(key)?.elapsed() < LIVE_OUTPUT_GRACE {
+ return None;
+ }
+ Some((command, output))
+ }
+
/// Pair a `bash` call with the backgrounded command it is about.
///
/// Both directions run off the same maps: a call carrying a `command` is
@@ -2507,10 +2563,17 @@ impl App {
self.bash_commands.insert(id.to_string(), cmd);
return args;
}
+ // Collecting a backgrounded job: the detached command still streams under
+ // the id of the call that started it, so point this call at that buffer.
+ // Without the alias the row the user is waiting on shows an empty box.
+ if let Some(origin) = bash_job_id(&args).and_then(|job| self.job_origin.get(job)) {
+ self.live_alias.insert(id.to_string(), origin.clone());
+ }
let remembered = bash_job_id(&args)
.and_then(|job| self.bash_jobs.get(job))
.cloned();
if let (Some(cmd), Some(obj)) = (remembered, args.as_object_mut()) {
+ self.bash_commands.insert(id.to_string(), cmd.clone());
obj.insert("command".to_string(), serde_json::Value::String(cmd));
}
args
@@ -3865,6 +3928,25 @@ impl App {
call.args.push_str(&delta);
}
}
+ StreamEvent::ToolOutputDelta { id, delta } => {
+ // Bounded from the end: a runaway command must not be able to
+ // grow the TUI's memory. The tool keeps the authoritative full
+ // output (spilling to disk past its own cap) and hands it over
+ // with the result; this buffer only has to feed the live view.
+ self.live_since
+ .entry(id.clone())
+ .or_insert_with(Instant::now);
+ let buf = self.live_output.entry(id).or_default();
+ buf.push_str(&delta);
+ if buf.len() > LIVE_OUTPUT_MAX_BYTES {
+ // Trim on a char boundary so the buffer stays valid UTF-8.
+ let cut = buf.len() - LIVE_OUTPUT_MAX_BYTES;
+ let at = (cut..buf.len())
+ .find(|i| buf.is_char_boundary(*i))
+ .unwrap_or(buf.len());
+ buf.drain(..at);
+ }
+ }
StreamEvent::ToolCall { id, name, args } => {
// The full call (with parsed args) supersedes its in-progress
// throbber.
@@ -3952,8 +4034,18 @@ impl App {
if let Some(cmd) = self.bash_commands.remove(&id) {
if let Some(job) = backgrounded_job_id(&content) {
self.bash_jobs.insert(job.to_string(), cmd);
+ self.job_origin.insert(job.to_string(), id.clone());
}
}
+ // The command is over, so its live buffer is dead weight: the
+ // authoritative output is in this result. A call that backgrounded
+ // itself keeps its buffer -- the detached job is still writing to
+ // it, under this same id.
+ if backgrounded_job_id(&content).is_none() {
+ let key = self.live_alias.remove(&id).unwrap_or_else(|| id.clone());
+ self.live_output.remove(&key);
+ self.live_since.remove(&key);
+ }
let resolved = self.resolve_pending_row(&id, is_error);
// Any tool result means the model took some action since the last
// reminder fired; let a later stop remind again if work is still
@@ -4194,8 +4286,12 @@ impl App {
panel.prompt_tokens = usage.prompt_tokens.unwrap_or(panel.prompt_tokens);
}
}
- // Token/ToolResult and any nested bracket are internal to the child
- // run and not surfaced in the parent transcript.
+ // Token/ToolResult, a child's live tool output (`ToolOutputDelta`)
+ // and any nested bracket are internal to the child run and not
+ // surfaced in the parent transcript: a subagent panel is a one-line
+ // activity summary, so a child's shell output would have nowhere to
+ // go and would push the parent's own live panel off screen. Deliberate
+ // -- the child's output still reaches its `ToolResult`.
_ => {}
}
}
@@ -5633,6 +5729,70 @@ fn running_group_rows(group: &ToolGroup, spinner_frame: usize, width: u16) -> Ve
)
}
+/// Live output kept per running command. Past this the front is dropped: the
+/// view shows a tail, and the tool hands over the authoritative full output when
+/// the call finishes.
+const LIVE_OUTPUT_MAX_BYTES: usize = 64 * 1024;
+
+/// Rendered rows of live command output, so a long-running command fills at most
+/// this much of the viewport.
+const LIVE_OUTPUT_TAIL_LINES: usize = 12;
+
+/// How long a command must have been printing before its output gets a box. The
+/// panel is transient -- it gives way to the group summary when the call
+/// resolves -- so anything short-lived is better shown as no box than as a flash.
+const LIVE_OUTPUT_GRACE: Duration = Duration::from_millis(400);
+
+/// Indent of the live shell panel, matching a single-call group's detail box so
+/// the running command and its expanded result sit on the same column.
+const SHELL_PANEL_GUTTER: &str = "│ ";
+
+/// A running command and its output so far, framed like a terminal. No rows
+/// until the first chunk arrives, so a command that has printed nothing shows
+/// only its activity row rather than an empty box.
+fn shell_panel_lines(
+ command: &str,
+ output: &str,
+ width: u16,
+ gutter: &'static str,
+) -> Vec<Line<'static>> {
+ if output.is_empty() {
+ return Vec::new();
+ }
+ let max = panel_inner(width as usize, gutter);
+ // The command is the session's first line, as a prompt, so the box reads as
+ // a terminal rather than as a detached wall of output.
+ let mut rows: Vec<Line<'static>> =
+ wrap_text(command, Style::new().bold(), max.saturating_sub(2))
+ .into_iter()
+ .enumerate()
+ .map(|(i, chunk)| {
+ let mut spans = vec![Span::styled(
+ if i == 0 { "$ " } else { " " },
+ Style::new().cyan().bold(),
+ )];
+ spans.extend(chunk);
+ Line::from(spans)
+ })
+ .collect();
+ let all: Vec<&str> = output.lines().collect();
+ let skipped = all.len().saturating_sub(LIVE_OUTPUT_TAIL_LINES);
+ if skipped > 0 {
+ rows.push(Line::styled(
+ format!("… ({})", pluralize("earlier line", skipped)),
+ Style::new().dark_gray(),
+ ));
+ }
+ for line in &all[skipped..] {
+ rows.extend(
+ wrap_text(line, Style::new().dim(), max)
+ .into_iter()
+ .map(Line::from),
+ );
+ }
+ boxed_panel(rows, width as usize, gutter)
+}
+
/// Bucket `nouns` into read-style and run-style clauses (first-seen order,
/// counted and pluralized) and join them with the given verbs, so the verb
/// always agrees with its noun (never "Ran 1 directory").
@@ -12017,7 +12177,8 @@ fn trailing_blank(tail: &[Line<'static>], transcript: &[Row], width: u16) -> boo
/// `MIN_TRANSCRIPT_ROWS`, capped at `PANEL_MAX_ROWS`, and disappears entirely
/// on a frame with nothing to spare.
fn panel_budget(frame_h: u16, input_h: u16) -> usize {
- let fixed = 1 + 1 + input_h + 1; // header, rule, input, dock
+ // header, transcript air, rule, input, dock
+ let fixed = 1 + TRANSCRIPT_BOTTOM_PAD + 1 + input_h + 1;
frame_h
.saturating_sub(fixed + MIN_TRANSCRIPT_ROWS)
.min(PANEL_MAX_ROWS as u16) as usize
@@ -12062,20 +12223,21 @@ fn draw(f: &mut Frame, app: &mut App) {
// between the rule and the prompt. A zero-length slot collapses away, so a
// session with neither todos nor subagents renders exactly as before.
let raw = Layout::vertical([
- Constraint::Length(1), // 0: header
- Constraint::Min(1), // 1: body
- Constraint::Length(panel_h), // 2: status panel
- Constraint::Length(1), // 3: separator rule
- Constraint::Length(input_h), // 4: input
- Constraint::Length(1), // 5: path + key hints
+ Constraint::Length(1), // 0: header
+ Constraint::Min(1), // 1: body
+ Constraint::Length(TRANSCRIPT_BOTTOM_PAD), // 2: air
+ Constraint::Length(panel_h), // 3: status panel
+ Constraint::Length(1), // 4: separator rule
+ Constraint::Length(input_h), // 5: input
+ Constraint::Length(1), // 6: path + key hints
])
.split(f.area());
- let panel_area = raw[2];
- let chunks = [raw[0], raw[1], raw[4], raw[5]];
+ let panel_area = raw[3];
+ let chunks = [raw[0], raw[1], raw[5], raw[6]];
f.render_widget(header(app), chunks[0]);
// Drawn for every path (picker included) so the dock always reads the same.
- f.render_widget(Block::default().borders(Borders::TOP), raw[3]);
+ f.render_widget(Block::default().borders(Borders::TOP), raw[4]);
// Top border only, so wrapping uses the full width; the border row reduces
// the vertical viewport.
@@ -12113,11 +12275,13 @@ fn draw(f: &mut Frame, app: &mut App) {
.as_ref()
.filter(|g| g.idx == i && g.is_running())
{
- Some(g) => Segment::eager(
- Some(i),
- running_group_rows(g, app.spinner_frame, width),
- width,
- ),
+ Some(g) => {
+ // The running row plus, when the call is a command that has
+ // started printing, its output live under it.
+ let mut rows = running_group_rows(g, app.spinner_frame, width);
+ rows.extend(app.live_shell_panel(g, width));
+ Segment::eager(Some(i), rows, width)
+ }
None => Segment {
idx: Some(i),
height: row.height(width),
@@ -13267,6 +13431,13 @@ const PANEL_MAX_ROWS: usize = 8;
/// up its own rows first: the transcript is the point of the screen.
const MIN_TRANSCRIPT_ROWS: u16 = 4;
+/// Blank rows between the last transcript row and the dock below it. The body is
+/// bottom-pinned, so without this the model's closing line sits flush against the
+/// panel -- or, with no panel, against the separator rule over the input -- and
+/// the conversation and the dock read as one block. Unconditional: air that
+/// appears only on some frames is a layout that jumps.
+const TRANSCRIPT_BOTTOM_PAD: u16 = 1;
+
/// Narrowest terminal that still gets two side-by-side columns. Under it they
/// stack, plan first, because a 30-column half fits neither a task nor an agent.
const PANEL_SPLIT_MIN_WIDTH: u16 = 76;
@@ -16079,6 +16250,184 @@ mod tests {
);
}
+ /// Backdate a call's first-output stamp past [`LIVE_OUTPUT_GRACE`], so a test
+ /// renders the panel a long-running command would have without sleeping.
+ fn age_live_output(app: &mut App, id: &str) {
+ let since = app.live_since.get_mut(id).expect("call has streamed");
+ *since -= super::LIVE_OUTPUT_GRACE;
+ }
+
+ /// A running command is a terminal, not a spinner: its output appears under
+ /// the activity row as it is produced, framed and prefixed by the command.
+ #[test]
+ fn a_running_command_shows_its_output_live() {
+ let mut app = test_app();
+ app.apply(StreamEvent::ToolCall {
+ id: "t1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "make" }),
+ });
+ // Nothing printed yet: the activity row stands alone rather than opening
+ // an empty box.
+ let quiet = render_rows(&mut app, 70, 16).join("\n");
+ assert!(!quiet.contains("$ make"), "no box before output: {quiet}");
+
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "compiling foo\n".into(),
+ });
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "compiling bar\n".into(),
+ });
+ // Still inside the grace window: a command this brief would only flash.
+ let brief = render_rows(&mut app, 70, 16).join("\n");
+ assert!(!brief.contains("$ make"), "no box while brief: {brief}");
+
+ age_live_output(&mut app, "t1");
+ let live = render_rows(&mut app, 70, 16).join("\n");
+ assert!(
+ live.contains("$ make"),
+ "command on the prompt line: {live}"
+ );
+ assert!(live.contains("compiling foo"), "first chunk: {live}");
+ assert!(live.contains("compiling bar"), "and the next: {live}");
+ assert!(live.contains('\u{250c}'), "framed: {live}");
+ }
+
+ /// The result is the authoritative output, so the live buffer is released
+ /// with it -- a long session must not accumulate every command it ran.
+ #[test]
+ fn a_finished_command_releases_its_live_buffer() {
+ let mut app = test_app();
+ app.apply(StreamEvent::ToolCall {
+ id: "t1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "make" }),
+ });
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "compiling foo\n".into(),
+ });
+ app.apply(StreamEvent::ToolResult {
+ id: "t1".into(),
+ content: "compiling foo\n[exit 0]".into(),
+ is_error: false,
+ diff: None,
+ });
+ assert!(
+ !app.live_output.contains_key("t1"),
+ "the finished call still holds its buffer"
+ );
+ }
+
+ /// A group runs its calls in parallel, so the panel follows the call that is
+ /// actually printing. Keying it to the newest unresolved call instead made a
+ /// `read` issued after a long `bash` blank the box until the read landed.
+ #[test]
+ fn a_later_call_does_not_blank_the_live_panel() {
+ let mut app = test_app();
+ app.apply(StreamEvent::ToolCall {
+ id: "t1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "make" }),
+ });
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "compiling foo\n".into(),
+ });
+ age_live_output(&mut app, "t1");
+ app.apply(StreamEvent::ToolCall {
+ id: "t2".into(),
+ name: "read".into(),
+ args: json!({ "path": "src/main.rs" }),
+ });
+ let live = render_rows(&mut app, 70, 18).join("\n");
+ assert!(
+ live.contains("compiling foo"),
+ "the streaming call keeps the panel: {live}"
+ );
+ }
+
+ /// The wait on a backgrounded job is the case the live view matters most for.
+ /// The job streams under the id of the call that *started* it while the user
+ /// watches the later call that *collects* it, so the two are aliased.
+ #[test]
+ fn waiting_on_a_backgrounded_job_shows_its_live_output() {
+ let mut app = test_app();
+ app.apply(StreamEvent::ToolCall {
+ id: "t1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "cargo test" }),
+ });
+ app.apply(StreamEvent::ToolResult {
+ id: "t1".into(),
+ content: "Command exceeded 30s and is continuing in the background \
+ (job_id=bash-7)."
+ .into(),
+ is_error: false,
+ diff: None,
+ });
+ // Backgrounded, so the buffer survives its own result.
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "test tui::rolls ... ok\n".into(),
+ });
+ app.apply(StreamEvent::ToolCall {
+ id: "t2".into(),
+ name: "bash".into(),
+ args: json!({ "job_id": "bash-7" }),
+ });
+ assert_eq!(
+ app.live_alias.get("t2").map(String::as_str),
+ Some("t1"),
+ "the collecting call is aliased to the job's origin"
+ );
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "test tui::folds ... ok\n".into(),
+ });
+ age_live_output(&mut app, "t1");
+ let live = render_rows(&mut app, 74, 20).join("\n");
+ assert!(
+ live.contains("test tui::folds ... ok"),
+ "the waiting row reports the job's progress: {live}"
+ );
+ }
+
+ /// A runaway command must not grow the TUI's memory without bound.
+ #[test]
+ fn live_output_is_bounded() {
+ let mut app = test_app();
+ app.apply(StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "x".repeat(super::LIVE_OUTPUT_MAX_BYTES * 2),
+ });
+ let held = app.live_output.get("t1").expect("buffered").len();
+ assert!(held <= super::LIVE_OUTPUT_MAX_BYTES, "kept {held} bytes");
+ }
+
+ /// Only a bounded tail is rendered, so a chatty command cannot push the
+ /// conversation off the screen.
+ #[test]
+ fn the_live_panel_renders_only_a_bounded_tail() {
+ let many: String = (0..60).map(|i| format!("line {i}\n")).collect();
+ let rows = super::shell_panel_lines("make", &many, 70, "\u{2502} ");
+ assert!(
+ rows.len() <= super::LIVE_OUTPUT_TAIL_LINES + 4,
+ "unbounded panel: {} rows",
+ rows.len()
+ );
+ let text = rows
+ .iter()
+ .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>())
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(text.contains("line 59"), "the newest line shows: {text}");
+ assert!(!text.contains("line 0\n"), "the oldest is elided: {text}");
+ assert!(text.contains("earlier lines"), "elision is reported: {text}");
+ }
+
#[test]
fn tool_activity_is_concise_present_tense() {
assert_eq!(
@@ -24204,6 +24553,84 @@ mod tests {
assert!(todos < agents, "plan first when stacked: {rows:?}");
}
+ /// The dock is one unit and the conversation is another:
+ /// `TRANSCRIPT_BOTTOM_PAD` keeps the model's closing line off the rule that
+ /// separates the transcript from the input.
+ #[test]
+ fn the_transcript_keeps_its_air_above_the_dock() {
+ let mut app = test_app();
+ app.apply(StreamEvent::Token {
+ text: "an answer".into(),
+ });
+ app.flush_assistant();
+ let rows = render_rows(&mut app, 60, 20);
+
+ let rule = rows
+ .iter()
+ .rposition(|r| r.trim_end().chars().filter(|c| *c == '─').count() > 20)
+ .expect("the separator rule is on screen");
+ let last_prose = rows[..rule]
+ .iter()
+ .rposition(|r| r.trim() == "an answer")
+ .expect("the answer is on screen");
+ // Literal, not derived from the constant: the point is the geometry on
+ // screen, and reading the expectation back off `TRANSCRIPT_BOTTOM_PAD`
+ // would make the test pass at any value including zero.
+ assert_eq!(
+ rule - last_prose,
+ 2,
+ "exactly one blank row between the transcript and the dock: {rows:#?}"
+ );
+ assert!(
+ rows[rule - 1].trim().is_empty(),
+ "the row above the rule is the air, not content: {rows:#?}"
+ );
+ }
+
+ /// Reasoning and answer are different bands, and the committed path gaps
+ /// between them. The live tail packed them together, so a native-reasoning
+ /// model's answer streamed flush against the reasoning above it and then
+ /// dropped a row when the commit put the real separator in.
+ #[test]
+ fn the_live_tail_gaps_between_reasoning_and_the_answer() {
+ let mut app = test_app();
+ app.apply(StreamEvent::Reasoning {
+ text: "musing".into(),
+ });
+ app.apply(StreamEvent::Token {
+ text: "Here is the ".into(),
+ });
+
+ // The `┊` gutter marks the reasoning band in both forms: folded to a
+ // summary row while it streams, and as dimmed detail once committed.
+ let gap = |rows: &[String]| -> usize {
+ let reasoning = rows
+ .iter()
+ .rposition(|r| r.contains('┊'))
+ .unwrap_or_else(|| panic!("the reasoning band is on screen: {rows:#?}"));
+ let prose = rows
+ .iter()
+ .position(|r| r.contains("Here is the"))
+ .unwrap_or_else(|| panic!("the answer is on screen: {rows:#?}"));
+ prose - reasoning
+ };
+ let live = render_rows(&mut app, 60, 16);
+ assert_eq!(
+ gap(&live),
+ 2,
+ "one blank row between the reasoning and the answer: {live:#?}"
+ );
+
+ // Committing it moves nothing: the live gap is the one the commit puts in.
+ app.flush_assistant();
+ let flushed = render_rows(&mut app, 60, 16);
+ assert_eq!(
+ gap(&flushed),
+ 2,
+ "the commit must not change the gap: {flushed:#?}"
+ );
+ }
+
/// A short terminal spends its rows on the conversation: the panel shrinks
/// first, eliding its own tail, and disappears before the transcript does.
#[test]
@@ -24216,8 +24643,9 @@ mod tests {
// Roomy: capped at the panel ceiling, never more.
assert_eq!(super::panel_budget(40, 2), super::PANEL_MAX_ROWS);
// Squeezed: only what is left after the fixed rows and the transcript
- // floor, and nothing at all once even that is gone.
- assert_eq!(super::panel_budget(12, 2), 3);
+ // floor, less the row `TRANSCRIPT_BOTTOM_PAD` holds open above the dock,
+ // and nothing at all once even that is gone.
+ assert_eq!(super::panel_budget(12, 2), 2);
assert_eq!(super::panel_budget(9, 2), 0);
let rows = render_rows(&mut app, 80, 12);
@@ -24225,9 +24653,9 @@ mod tests {
.iter()
.filter(|r| r.contains("Todos") || r.contains("a task") || r.contains("more"))
.collect();
- assert!(panel.len() <= 3, "panel clamped to its budget: {rows:?}");
+ assert!(panel.len() <= 2, "panel clamped to its budget: {rows:?}");
assert!(
- rows.iter().any(|r| r.contains("+11 more")),
+ rows.iter().any(|r| r.contains("+12 more")),
"the tail is elided, not dropped silently: {rows:?}"
);
@@ -24473,8 +24901,8 @@ mod tests {
"transcript not reset: {text}"
);
assert!(
- text.contains(brand::HAND[0].trim()),
- "hand logo missing after /clear: {text}"
+ text.contains(brand::LOGO[0].trim()),
+ "wordmark missing after /clear: {text}"
);
assert!(
text.contains("--safe: approval needed"),
@@ -25803,32 +26231,30 @@ mod tests {
);
}
- /// The mark and the name are one lockup, so they share rows instead of
- /// stacking: the wordmark's first row also carries part of the hand.
+ /// The splash opens on the wordmark alone. The hand-wave block art that used
+ /// to sit beside it spent 15 rows of a fresh screen on decoration and forced
+ /// a 61-column floor before the splash would render at all.
#[test]
- fn banner_opens_with_the_hand_logo_beside_the_wordmark() {
+ fn banner_opens_with_the_wordmark() {
let mut app = test_app();
app.push_banner("--safe", true);
let text = banner_text(&app, 90);
let joined = text.join("\n");
- let row = text
- .iter()
- .find(|l| l.contains(brand::LOGO[0].trim()))
- .unwrap_or_else(|| panic!("wordmark missing:\n{joined}"));
- let hand_row = brand::HAND
- .iter()
- .find(|h| row.contains(h.trim()))
- .unwrap_or_else(|| panic!("the wordmark's row carries no hand: {row}"));
assert!(
- row.find(hand_row.trim()).unwrap() < row.find(brand::LOGO[0].trim()).unwrap(),
- "the hand should sit left of the wordmark: {row}"
+ text.iter().any(|l| l.contains(brand::LOGO[0].trim())),
+ "wordmark missing:\n{joined}"
);
assert!(joined.contains('█'), "{joined}");
+ // The wordmark is six rows; the hand was fifteen more.
+ assert!(
+ text.iter().filter(|l| l.contains('█')).count() <= brand::LOGO.len(),
+ "the splash carries block art beyond the wordmark:\n{joined}"
+ );
}
#[test]
- fn a_24_column_terminal_drops_the_hand_logo_too() {
+ fn a_24_column_terminal_drops_the_wordmark() {
let mut app = test_app();
app.push_banner("--safe", true);
let narrow = banner_text(&app, 24);
diff --git a/src-tauri/src/core/cli/tui/markdown.rs b/src-tauri/src/core/cli/tui/markdown.rs
index 483b8aaea..b945407a6 100644
--- a/src-tauri/src/core/cli/tui/markdown.rs
+++ b/src-tauri/src/core/cli/tui/markdown.rs
@@ -15,15 +15,34 @@ pub(super) fn format_assistant_lines(
) -> Vec<Line<'static>> {
let mut lines = Vec::new();
for (reasoning, seg) in super::assistant_runs(prose, segs) {
- if reasoning {
- lines.extend(reasoning_detail_lines(&seg));
+ let next = if reasoning {
+ reasoning_detail_lines(&seg)
} else {
- lines.extend(format_markdown_lines(&seg, width));
- }
+ format_markdown_lines(&seg, width)
+ };
+ append_band(&mut lines, next);
}
lines
}
+/// Append `next` under `lines`, separated by the blank row the committed path
+/// puts between bands (`gap(Kind::Reasoning)` / `gap(Kind::Prose)` in
+/// `push_assistant_blocks`). Reasoning and answer are different bands, so
+/// without this the streaming answer sits flush against the summary above it and
+/// then drops a row the moment the turn commits and the real gap goes in.
+///
+/// A run that rendered nothing appends nothing, so a hidden block leaves no
+/// stray separator behind.
+fn append_band(lines: &mut Vec<Line<'static>>, next: Vec<Line<'static>>) {
+ if next.is_empty() {
+ return;
+ }
+ if !lines.is_empty() {
+ lines.push(Line::raw(""));
+ }
+ lines.extend(next);
+}
+
/// 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.
@@ -52,7 +71,7 @@ pub(super) fn live_assistant_lines(
let last = runs.len().saturating_sub(1);
let mut lines = Vec::new();
for (i, (reasoning, seg)) in runs.into_iter().enumerate() {
- if reasoning {
+ let next = if reasoning {
// 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();
@@ -60,15 +79,18 @@ pub(super) fn live_assistant_lines(
continue;
}
if i < last {
- lines.push(reasoning_summary_row(body.len()));
+ vec![reasoning_summary_row(body.len())]
} else if stream_reasoning {
- lines.extend(live_reasoning_tail(&body, width));
+ live_reasoning_tail(&body, width)
+ } else {
+ continue;
}
+ } else if seg.trim().is_empty() {
continue;
- }
- if !seg.trim().is_empty() {
- lines.extend(format_markdown_lines(&seg, width));
- }
+ } else {
+ format_markdown_lines(&seg, width)
+ };
+ append_band(&mut lines, next);
}
lines
}
diff --git a/src-tauri/src/core/openai_schema.rs b/src-tauri/src/core/openai_schema.rs
index 62997f2ba..abd140f9b 100644
--- a/src-tauri/src/core/openai_schema.rs
+++ b/src-tauri/src/core/openai_schema.rs
@@ -2,6 +2,7 @@
//! upstream layer: tool-schema normalization and key-rotation status checks.
//! Tauri-free so the headless CLI build can use it without the proxy.
+#[cfg(not(feature = "cli"))]
use reqwest::StatusCode;
const SCHEMA_PRIMITIVE_TYPES: &[&str] = &[
@@ -167,6 +168,9 @@ pub(crate) fn normalize_openai_tools_in_chat_body(body: &mut serde_json::Value)
}
}
+/// Only the desktop API-server path branches on this; the agent's key
+/// rotation lives in `agent::genai_bridge`.
+#[cfg(not(feature = "cli"))]
pub(crate) fn http_status_indicates_api_key_retry(status: StatusCode) -> bool {
matches!(
status,
diff --git a/src-tauri/src/core/server/provider_secrets.rs b/src-tauri/src/core/server/provider_secrets.rs
index 5d2f1b9bd..5d44bdb64 100644
--- a/src-tauri/src/core/server/provider_secrets.rs
+++ b/src-tauri/src/core/server/provider_secrets.rs
@@ -15,7 +15,7 @@
//! local-key scheme can be). Keyring failure is never fatal; callers additionally
//! have `--api-key`/env as a last resort.
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -30,11 +30,16 @@ use crate::core::app::commands::resolve_jan_data_folder;
const KEYRING_SERVICE: &str = "jan-providers";
const SECRETS_FILE_NAME: &str = "provider_secrets.enc";
+const SECRETS_INDEX_FILE_NAME: &str = "provider_secrets.index.json";
const NONCE_LEN: usize = 12;
/// Serializes read-modify-write on the fallback file.
static FILE_LOCK: Mutex<()> = Mutex::new(());
+/// Serializes read-modify-write on the presence index. Separate from
+/// `FILE_LOCK` because the index is updated around calls that take it.
+static INDEX_LOCK: Mutex<()> = Mutex::new(());
+
/// Latched on the first infrastructure-level keyring failure (D-Bus timeout,
/// platform/storage-access failure). Once set, every secret op skips the
/// keyring and goes straight to the encrypted file fallback for the rest of the
@@ -136,6 +141,62 @@ fn restrict_permissions(path: &PathBuf) {
#[cfg(not(unix))]
fn restrict_permissions(_path: &PathBuf) {}
+fn secrets_index_path() -> PathBuf {
+ resolve_jan_data_folder().join(SECRETS_INDEX_FILE_NAME)
+}
+
+fn read_index() -> BTreeSet<String> {
+ fs::read(secrets_index_path())
+ .ok()
+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())
+ .unwrap_or_default()
+}
+
+fn write_index(names: &BTreeSet<String>) -> Result<(), String> {
+ let path = secrets_index_path();
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ }
+ let body = serde_json::to_vec(names).map_err(|e| e.to_string())?;
+ let tmp = path.with_extension("json.tmp");
+ fs::write(&tmp, &body).map_err(|e| e.to_string())?;
+ fs::rename(&tmp, &path).map_err(|e| e.to_string())
+}
+
+/// Index updates are bookkeeping: a failure must never fail the store/delete
+/// that carries the actual secret, so it is logged and swallowed.
+fn index_set(provider: &str, present: bool) {
+ let Ok(_guard) = INDEX_LOCK.lock() else {
+ return;
+ };
+ let mut names = read_index();
+ let changed = match present {
+ true => names.insert(provider.to_string()),
+ false => names.remove(provider),
+ };
+ if changed {
+ if let Err(err) = write_index(&names) {
+ log::warn!("Failed to update the provider secret index: {err}");
+ }
+ }
+}
+
+/// Whether a key is stored for `provider`, without reading the key.
+///
+/// Presence has to be answerable cheaply: on macOS a keychain item's ACL is
+/// per-entry and every authorization dialog is labelled with the shared service
+/// name, so probing the real store to answer "does this provider have a key"
+/// produced one indistinguishable prompt per provider. The index holds provider
+/// names only -- never secret material.
+///
+/// The index is authoritative once written; the encrypted fallback file is
+/// consulted as a backstop because reading it is free (no prompt) and it covers
+/// installs whose index predates this file. A keyring entry written before the
+/// index existed reads as absent until the owning app next stores that key.
+pub fn has_stored_key(provider: &str) -> bool {
+ read_index().contains(provider) || !file_load(provider).is_empty()
+}
+
fn file_store(provider: &str, keys: &[String]) -> Result<(), String> {
let _guard = FILE_LOCK.lock().map_err(|e| e.to_string())?;
let path = secrets_file_path();
@@ -173,12 +234,17 @@ pub fn store_provider_keys(provider: &str, keys: &[String]) -> Result<(), String
Ok(()) => {
// Keyring is authoritative; drop any stale fallback copy.
let _ = file_remove(provider);
+ index_set(provider, true);
return Ok(());
}
Err(err) => note_keyring_failure(&err),
}
}
- file_store(provider, keys)
+ let stored = file_store(provider, keys);
+ if stored.is_ok() {
+ index_set(provider, true);
+ }
+ stored
}
/// Remove a provider's stored keys from both the keyring and the fallback file.
@@ -193,7 +259,9 @@ pub fn delete_provider_keys(provider: &str) -> Result<(), String> {
}
}
}
- file_remove(provider)
+ let removed = file_remove(provider);
+ index_set(provider, false);
+ removed
}
/// Read a provider's key chain: keyring first, then the fallback file. Returns
@@ -313,6 +381,39 @@ mod tests {
))));
}
+ /// Presence must be answerable from the index alone: `has_stored_key` is
+ /// what replaced probing the real store, and probing is exactly the thing
+ /// that costs a keychain prompt per provider on macOS.
+ #[test]
+ fn the_index_answers_presence_without_the_secret() {
+ let _tmp = TempDataFolder::new();
+ assert!(!has_stored_key("openai"));
+
+ index_set("openai", true);
+ assert!(has_stored_key("openai"));
+ assert!(!has_stored_key("anthropic"), "presence is per provider");
+
+ // The index carries names, never key material.
+ let raw = fs::read_to_string(secrets_index_path()).unwrap();
+ assert!(raw.contains("openai"));
+
+ index_set("openai", false);
+ assert!(!has_stored_key("openai"));
+ }
+
+ /// An install whose keys predate the index still has the encrypted fallback
+ /// file, which is free to read, so presence is not silently lost there.
+ #[test]
+ fn the_fallback_file_backstops_a_missing_index() {
+ let _tmp = TempDataFolder::new();
+ file_store("openai", &["sk-x".to_string()]).unwrap();
+ assert!(
+ !secrets_index_path().exists(),
+ "no index written by file_store"
+ );
+ assert!(has_stored_key("openai"));
+ }
+
#[test]
fn file_remove_missing_is_ok() {
let _tmp = TempDataFolder::new();
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index e4ddfca14..f53d6d05b 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -981,7 +981,9 @@ async fn proxy_request(
match run_server_side_openai_orchestration(
&openai_body,
- &client,
+ // The agent loop runs on genai (reqwest 0.13); the
+ // proxy's own passthrough stays on 0.12.
+ &crate::core::agent::upstream::agent_http_client(),
provider_configs.clone(),
llama_state.clone(),
mlx_sessions.clone(),
@@ -1498,7 +1500,7 @@ async fn proxy_request(
{
match run_server_side_openai_orchestration(
&json_body,
- &client,
+ &crate::core::agent::upstream::agent_http_client(),
provider_configs.clone(),
llama_state.clone(),
mlx_sessions.clone(),