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): recover from context overflow, add JSON output, and run on headless hosts (#8646)

Akarshan Biswasc5c3be736a6f
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 2f3294518..5c09e10d9 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -83,12 +83,65 @@ jan cli agent run --safe "run the migration" # approve each step
| `--resume[=ID]` | Resume the most recent session, or one by id |
| `-c`, `--continue` | Resume the most recent session |
| `--provider`, `--api-key` | Credential overrides for this run |
+| `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object |
<Callout type="info">
`run` takes a positional task, so a space-separated `--resume ID` would swallow it. Write the value
form with an equals sign: `--resume=3f7a91c2`.
</Callout>
+#### JSON output
+
+`--output-format json` suppresses the streamed answer and prints a single object on stdout when the
+run finishes. Progress and diagnostics still go to stderr, so stdout is safe to pipe into `jq`.
+
+```bash
+jan cli agent run --output-format json "review auth.rs" | jq -r .result
+```
+
+```json
+{
+ "type": "result",
+ "is_error": false,
+ "result": "APPROVED: the retry loop is correct...",
+ "stop_reason": "end_turn",
+ "session_id": "3f7a91c2",
+ "model": "tokamak-1-preview",
+ "num_turns": 3,
+ "duration_ms": 48213,
+ "usage": { "prompt_tokens": 9011, "completion_tokens": 655, "total_tokens": 9666 }
+}
+```
+
+A failed run adds an `error` object, sets `stop_reason` to `error`, and reports whatever the model
+had said before it broke as `result`:
+
+```json
+{
+ "type": "result",
+ "is_error": true,
+ "result": "I started reviewing auth.rs and...",
+ "stop_reason": "error",
+ "error": { "code": "upstream_error", "message": "[400] tool_choice does not match any of the specified tools" },
+ "session_id": null,
+ "model": "tokamak-1-preview",
+ "num_turns": 1,
+ "duration_ms": 1204,
+ "usage": { "prompt_tokens": 8123, "completion_tokens": 0, "total_tokens": 8123 }
+}
+```
+
+| Field | Notes |
+| --- | --- |
+| `result` | The final answer, or the partial answer of the turn that failed. Reasoning is stripped |
+| `stop_reason` | The upstream finish reason, or `error` |
+| `error.code` | `context_overflow`, `upstream_error`, `setup_error`, or the raw code |
+| `session_id` | Short session id for `--resume`. `null` when the run failed before producing one |
+| `num_turns` | Agent turns taken. Subagent turns are not counted |
+| `usage` | Summed over every request the run made, subagents included |
+
+The process exit code is unchanged: `0` on success, `1` on failure.
+
### `step`
Run a single turn. Useful when debugging a prompt or a tool.
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 77bdc0b01..595497a61 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -355,6 +355,17 @@ dependencies = [
"slab",
]
+[[package]]
+name = "async-fs"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"
+dependencies = [
+ "async-lock",
+ "blocking",
+ "futures-lite",
+]
+
[[package]]
name = "async-io"
version = "2.6.0"
@@ -3607,6 +3618,7 @@ dependencies = [
"security-framework 2.11.1",
"security-framework 3.7.0",
"windows-sys 0.60.2",
+ "zbus 4.4.0",
"zeroize",
]
@@ -9808,9 +9820,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"
dependencies = [
"async-broadcast",
+ "async-executor",
+ "async-fs",
+ "async-io",
+ "async-lock",
"async-process",
"async-recursion",
+ "async-task",
"async-trait",
+ "blocking",
"enumflags2",
"event-listener",
"futures-core",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index c01af57f3..da2073ce4 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -184,10 +184,19 @@ clap = { version = "4", features = ["derive"] }
env_logger = { version = "0.11", optional = true }
indicatif = { version = "0.17", optional = true }
console = { version = "0.15", optional = true }
+# The Secret Service backend must be `async-secret-service` (zbus, pure Rust),
+# not `sync-secret-service`: the latter pulls `libdbus-sys`, whose `DT_NEEDED`
+# on libdbus-1.so.3 is resolved before `main`, so a headless host without the
+# D-Bus runtime cannot even exec `jan` -- the encrypted-file fallback in
+# `core::server::provider_secrets` never gets a chance to run. `async-io`
+# rather than `tokio`: zbus's `tokio` `block_on` drives a runtime of its own,
+# which panics when called from inside one, and the keyring is read from async
+# CLI paths.
keyring = { version = "3", features = [
"apple-native",
"windows-native",
- "sync-secret-service",
+ "async-secret-service",
+ "async-io",
"crypto-rust",
] }
aes-gcm = "0.10"
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index a3f868306..7a7efa89f 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -10,6 +10,7 @@ use console::Style;
// Import the library crate so we can access core modules.
// The lib target is named "app_lib" (see [lib] section in Cargo.toml).
use app_lib::core::cli::providers::{load_provider_configs, ProviderOverrides};
+use app_lib::core::cli::run_report::OutputFormat;
use app_lib::core::cli::{
cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,
cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,
@@ -208,6 +209,10 @@ enum AgentCommands {
providers: ProviderArgs,
#[command(flatten)]
resume: ResumeRunArgs,
+ /// `text` streams the answer as it arrives; `json` prints one result
+ /// object on stdout when the run finishes
+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
+ output_format: OutputFormat,
},
/// Run a single turn (debugging)
Step {
@@ -449,6 +454,7 @@ async fn handle_agent(cmd: AgentCommands) {
safe,
providers,
resume,
+ output_format,
} => {
cli_agent_run(
&project,
@@ -457,6 +463,7 @@ async fn handle_agent(cmd: AgentCommands) {
providers.into_overrides(),
!safe,
resume.into_target(),
+ output_format,
)
.await
}
@@ -623,6 +630,44 @@ mod tests {
assert!(Cli::parse_from(["jan", "--safe"]).safe);
}
+ /// Parse `jan cli agent run <task> <extra...>` and pull out its output format.
+ fn parsed_output_format(extra: &[&str]) -> OutputFormat {
+ let mut argv = vec!["jan", "cli", "agent", "run", "task"];
+ argv.extend_from_slice(extra);
+ match Cli::parse_from(argv).command {
+ Some(Commands::Cli {
+ cmd:
+ CliCommands::Agent {
+ cmd: AgentCommands::Run { output_format, .. },
+ },
+ }) => output_format,
+ _ => panic!("expected `cli agent run`"),
+ }
+ }
+
+ #[test]
+ fn output_format_parses_and_defaults_to_text() {
+ assert_eq!(parsed_output_format(&[]), OutputFormat::Text);
+ assert_eq!(
+ parsed_output_format(&["--output-format", "json"]),
+ OutputFormat::Json
+ );
+ assert_eq!(
+ parsed_output_format(&["--output-format=text"]),
+ OutputFormat::Text
+ );
+ assert!(Cli::try_parse_from([
+ "jan",
+ "cli",
+ "agent",
+ "run",
+ "task",
+ "--output-format",
+ "yaml"
+ ])
+ .is_err());
+ }
+
#[test]
fn update_command_parses() {
let cli = Cli::parse_from(["jan", "update"]);
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index 1b1a23847..71bd2b89d 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -21,13 +21,21 @@ pub(crate) const DEFAULT_KEEP_RECENT: usize = 8;
#[cfg(feature = "cli")]
pub(crate) const MANUAL_KEEP_RECENT: usize = 2;
-const SUMMARY_SYSTEM_PROMPT: &str = "Summarize the preceding AI agent conversation into a dense, \
-factual brief that preserves everything needed to continue the task: the user's goals and constraints, \
-decisions made, files and commands touched with their outcomes, and any unresolved questions. Omit \
-pleasantries and redundant tool output. Write only the summary.";
+const SUMMARY_SYSTEM_PROMPT: &str = "Summarize the AI agent conversation transcript below into a \
+dense, factual brief that preserves everything needed to continue the task: the user's goals and \
+constraints, decisions made, files and commands touched with their outcomes, and any unresolved \
+questions. Omit pleasantries and redundant tool output. Write only the summary.";
const FALLBACK_NOTE: &str = "[Earlier conversation was omitted to fit the model's context window.]";
+/// Character budget for the transcript handed to the summarizer (~12K tokens).
+/// Compaction runs *because* the conversation overflowed, so replaying it whole
+/// would guarantee the summarizer overflows too: the dropped span is rendered to
+/// text and clamped head-and-tail to something a small window can still accept.
+const SUMMARY_INPUT_CHARS: usize = 48_000;
+
+const SUMMARY_ELISION: &str = "\n\n[... middle of the dropped transcript omitted ...]\n\n";
+
fn role(msg: &Value) -> &str {
msg.get("role").and_then(|r| r.as_str()).unwrap_or("")
}
@@ -60,7 +68,7 @@ pub(crate) async fn compact_conversation(
}
let kept = &rest[cut..];
- let summary = summarize(messages, model_id, model).await;
+ let summary = summarize(&rest[..cut], model_id, model).await;
let mut out = Vec::with_capacity(system_msgs.len() + 1 + kept.len());
out.extend_from_slice(system_msgs);
@@ -72,15 +80,79 @@ pub(crate) async fn compact_conversation(
out
}
-async fn summarize(messages: &[Value], model_id: &str, model: &dyn ModelInvoker) -> String {
- let mut request_messages = messages.to_vec();
- request_messages.push(json!({
- "role": "user",
- "content": SUMMARY_SYSTEM_PROMPT,
- }));
+/// Flatten a span of wire messages into a plain-text transcript. Rendering
+/// rather than replaying keeps the request small and sidesteps tool pairing:
+/// the dropped span is a slice, so its trailing assistant `tool_calls` may have
+/// their results in the kept tail, and an upstream rejects that conversation.
+fn render_transcript(messages: &[Value]) -> String {
+ let mut out = String::new();
+ for msg in messages {
+ out.push_str(role(msg));
+ out.push_str(": ");
+ match msg.get("content") {
+ Some(Value::String(text)) => out.push_str(text),
+ Some(Value::Array(parts)) => {
+ for part in parts {
+ match part.get("text").and_then(|t| t.as_str()) {
+ Some(text) => out.push_str(text),
+ None => out.push_str("[non-text content]"),
+ }
+ }
+ }
+ _ => {}
+ }
+ for call in msg
+ .get("tool_calls")
+ .and_then(|c| c.as_array())
+ .into_iter()
+ .flatten()
+ {
+ let f = call.get("function");
+ let name = f
+ .and_then(|f| f.get("name"))
+ .and_then(|n| n.as_str())
+ .unwrap_or("");
+ let args = f
+ .and_then(|f| f.get("arguments"))
+ .and_then(|a| a.as_str())
+ .unwrap_or("");
+ out.push_str(&format!("\n[tool call] {name}({args})"));
+ }
+ out.push('\n');
+ }
+ out
+}
+
+/// Clamp to `max` characters by dropping the middle: the start of a task and
+/// its most recent state both matter more than what sits between them.
+fn clamp_middle(text: &str, max: usize) -> String {
+ if text.chars().count() <= max {
+ return text.to_string();
+ }
+ let keep = max.saturating_sub(SUMMARY_ELISION.chars().count());
+ let head_len = keep / 2;
+ let tail_len = keep - head_len;
+ let chars: Vec<char> = text.chars().collect();
+ let head: String = chars[..head_len].iter().collect();
+ let tail: String = chars[chars.len() - tail_len..].iter().collect();
+ format!("{head}{SUMMARY_ELISION}{tail}")
+}
+
+/// Summarize the span being dropped. Takes only that span, never the whole
+/// conversation: this runs after an overflow, so a request carrying the full
+/// history plus a prompt is strictly larger than the one that just failed and
+/// could only fail too, silently degrading every compaction to [`FALLBACK_NOTE`].
+async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker) -> String {
+ let transcript = clamp_middle(&render_transcript(dropped), SUMMARY_INPUT_CHARS);
+ if transcript.trim().is_empty() {
+ return FALLBACK_NOTE.to_string();
+ }
let request = json!({
"model": model_id,
- "messages": request_messages,
+ "messages": [
+ { "role": "system", "content": SUMMARY_SYSTEM_PROMPT },
+ { "role": "user", "content": transcript },
+ ],
});
// Discard the summarizer's streamed tokens: a dropped receiver means these
// never reach the user-facing event stream.
@@ -176,8 +248,11 @@ mod tests {
assert_eq!(out[out.len() - 4]["content"], "msg16");
}
+ /// Compaction runs after an overflow, so the summarizer request must be
+ /// *smaller* than the conversation that just failed: only the dropped span
+ /// is sent, rendered to text, and never the kept tail.
#[tokio::test]
- async fn summary_request_appends_the_compaction_prompt() {
+ async fn summary_request_carries_only_the_dropped_span() {
let model = StubModel {
summary: "CONDENSED".into(),
calls: StdMutex::new(0),
@@ -189,14 +264,27 @@ mod tests {
let requests = model.requests.lock().await;
let messages = requests[0]["messages"].as_array().unwrap();
- assert_eq!(messages.len(), input.len() + 1);
- assert_eq!(&messages[..input.len()], input.as_slice());
- assert_eq!(messages.last().unwrap()["role"], "user");
- assert_eq!(messages.last().unwrap()["content"], SUMMARY_SYSTEM_PROMPT);
+ assert_eq!(messages.len(), 2, "a system prompt plus one transcript");
+ assert_eq!(messages[0]["role"], "system");
+ assert_eq!(messages[0]["content"], SUMMARY_SYSTEM_PROMPT);
+ assert_eq!(messages[1]["role"], "user");
+ let transcript = messages[1]["content"].as_str().unwrap();
+ assert!(transcript.contains("msg0"), "dropped span is summarized");
+ assert!(transcript.contains("msg15"), "dropped span runs to the cut");
+ for kept in ["msg16", "msg17", "msg18", "msg19"] {
+ assert!(
+ !transcript.contains(kept),
+ "the kept tail must not be re-sent: {kept}"
+ );
+ }
}
+ /// Tool calls carry the work the summary has to preserve, so they are
+ /// rendered by name and arguments -- but as text, never as wire messages:
+ /// the dropped span can end on a call whose result sits in the kept tail,
+ /// and an upstream rejects that conversation outright.
#[tokio::test]
- async fn summary_request_preserves_tool_calls_and_file_results() {
+ async fn summary_request_renders_tool_calls_as_text() {
let model = StubModel {
summary: "CONDENSED".into(),
calls: StdMutex::new(0),
@@ -223,14 +311,77 @@ mod tests {
"content": "Wrote config.toml"
}),
json!({ "role": "assistant", "content": "Configuration updated." }),
+ json!({ "role": "user", "content": "thanks" }),
+ json!({ "role": "assistant", "content": "welcome" }),
];
compact_conversation(&input, "m", &model, 2).await;
let requests = model.requests.lock().await;
let messages = requests[0]["messages"].as_array().unwrap();
- assert_eq!(&messages[..input.len()], input.as_slice());
- assert_eq!(messages.last().unwrap()["content"], SUMMARY_SYSTEM_PROMPT);
+ assert_eq!(messages.len(), 2);
+ let transcript = messages[1]["content"].as_str().unwrap();
+ assert!(transcript.contains("[tool call] write("));
+ assert!(transcript.contains("config.toml"));
+ assert!(transcript.contains("Wrote config.toml"), "tool result kept");
+ assert!(
+ messages
+ .iter()
+ .all(|m| m.get("tool_calls").is_none() && m.get("tool_call_id").is_none()),
+ "no wire tool-call structure may reach the summarizer"
+ );
+ }
+
+ #[tokio::test]
+ async fn summary_input_is_clamped_to_a_budget() {
+ let model = StubModel {
+ summary: "CONDENSED".into(),
+ calls: StdMutex::new(0),
+ requests: tokio::sync::Mutex::new(Vec::new()),
+ };
+ let mut input = vec![json!({ "role": "system", "content": "sys" })];
+ for i in 0..40 {
+ let r = if i % 2 == 0 { "user" } else { "assistant" };
+ input.push(json!({ "role": r, "content": "x".repeat(8_000) }));
+ }
+
+ compact_conversation(&input, "m", &model, 4).await;
+
+ let requests = model.requests.lock().await;
+ let transcript = requests[0]["messages"][1]["content"].as_str().unwrap();
+ assert!(
+ transcript.chars().count() <= SUMMARY_INPUT_CHARS,
+ "transcript must fit the budget: {}",
+ transcript.chars().count()
+ );
+ assert!(transcript.contains(SUMMARY_ELISION.trim()));
+ }
+
+ #[test]
+ fn clamp_middle_is_char_safe_and_keeps_both_ends() {
+ let text = "\u{e9}".repeat(500);
+ let out = clamp_middle(&text, 100);
+ assert!(out.chars().count() <= 100);
+ assert!(out.starts_with('\u{e9}') && out.ends_with('\u{e9}'));
+ assert_eq!(clamp_middle("short", 100), "short");
+ }
+
+ #[test]
+ fn render_transcript_keeps_multimodal_text_parts() {
+ let msgs = vec![json!({
+ "role": "user",
+ "content": [
+ { "type": "text", "text": "look at this" },
+ { "type": "image_url", "image_url": { "url": "data:..." } }
+ ]
+ })];
+ let out = render_transcript(&msgs);
+ assert!(out.contains("look at this"));
+ assert!(out.contains("[non-text content]"));
+ assert!(
+ !out.contains("data:"),
+ "image payloads must not be replayed"
+ );
}
#[tokio::test]
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 1934919ab..7b40e8ef9 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1680,6 +1680,13 @@ async fn run_turn_cycle(
attempts + 1
);
conversation_messages = compacted;
+ // Publish now, not at the end of the run: a retry that
+ // never recovers returns Err, and an unpublished
+ // compaction leaves the client holding the oversized
+ // history that every later turn would re-overflow on.
+ let _ = events.send(StreamEvent::MessagesUpdated {
+ messages: conversation_messages.clone(),
+ });
keep_recent = (keep_recent / 2).max(2);
attempts += 1;
}
@@ -2644,6 +2651,76 @@ mod tests {
assert!(tool.calls.lock().unwrap().is_empty());
}
+ /// A run that never recovers from overflow still has to hand its compacted
+ /// conversation to the client: without it the session keeps the oversized
+ /// history and every later turn re-overflows by construction.
+ #[tokio::test]
+ async fn turn_cycle_publishes_compacted_history_before_giving_up() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let overflow = || {
+ Err(format!(
+ "[{}] Upstream returned HTTP 400: context_length_exceeded",
+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER
+ ))
+ };
+ let summary = || Ok(json!({ "choices": [{ "message": { "content": "SUMMARY" } }] }));
+ let model = ResultQueueModel {
+ results: StdMutex::new(
+ vec![
+ overflow(),
+ summary(),
+ overflow(),
+ summary(),
+ overflow(),
+ summary(),
+ overflow(),
+ summary(),
+ overflow(),
+ ]
+ .into_iter()
+ .collect(),
+ ),
+ };
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(None);
+ let mut convo = vec![json!({ "role": "system", "content": "sys" })];
+ for i in 0..60 {
+ let r = if i % 2 == 0 { "user" } else { "assistant" };
+ convo.push(json!({ "role": r, "content": format!("m{i}") }));
+ }
+ let original_len = convo.len();
+
+ let result = run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ convo,
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await;
+
+ assert!(result.is_err(), "a persistent overflow must still fail");
+ drop(tx);
+ let mut published: Option<usize> = None;
+ while let Ok(ev) = rx.try_recv() {
+ if let StreamEvent::MessagesUpdated { messages } = ev {
+ published = Some(messages.len());
+ }
+ }
+ let len = published.expect("compaction must publish MessagesUpdated");
+ assert!(
+ len < original_len,
+ "published history must be shorter than the overflowing one ({len} vs {original_len})"
+ );
+ }
+
#[tokio::test]
async fn turn_cycle_skips_execution_on_truncated_tool_calls() {
let (tx, _rx) = mpsc::unbounded_channel();
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 2eb8e81ec..7f52171a4 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -8,6 +8,7 @@ pub mod login;
pub mod mcp;
pub mod providers;
mod path_refs;
+pub mod run_report;
mod secret_input;
pub mod tokamak;
mod tui;
@@ -457,6 +458,7 @@ use crate::core::agent::r#loop::{
};
use tauri_plugin_agent_tools::tools::gate::PermissionDecision;
use crate::core::cli::providers::{load_provider_configs, ProviderOverrides};
+use crate::core::cli::run_report::{OutputFormat, RunReport};
use crate::core::mcp::models::McpSettings;
use std::collections::HashMap;
use std::io::Write as _;
@@ -581,6 +583,7 @@ pub fn cli_agent_config_list() -> Result<serde_json::Value, String> {
/// Autonomous run: as many turns as the task needs, bounded only by the
/// session token budget.
+#[allow(clippy::too_many_arguments)]
pub async fn cli_agent_run(
project: &str,
task: &str,
@@ -588,8 +591,19 @@ pub async fn cli_agent_run(
overrides: ProviderOverrides,
auto_approve: bool,
resume: Option<ResumeTarget>,
+ format: OutputFormat,
) -> Result<(), String> {
- run_agent_loop(project, task, model, false, overrides, auto_approve, resume).await
+ run_agent_loop(
+ project,
+ task,
+ model,
+ false,
+ overrides,
+ auto_approve,
+ resume,
+ format,
+ )
+ .await
}
/// Single-turn run for debugging: the one place a turn cap is still applied,
@@ -601,7 +615,17 @@ pub async fn cli_agent_step(
overrides: ProviderOverrides,
auto_approve: bool,
) -> Result<(), String> {
- run_agent_loop(project, task, model, true, overrides, auto_approve, None).await
+ run_agent_loop(
+ project,
+ task,
+ model,
+ true,
+ overrides,
+ auto_approve,
+ None,
+ OutputFormat::Text,
+ )
+ .await
}
#[allow(clippy::too_many_arguments)]
@@ -942,6 +966,7 @@ fn short_id(id: &str) -> String {
id.chars().take(8).collect()
}
+#[allow(clippy::too_many_arguments)]
async fn run_agent_loop(
project: &str,
task: &str,
@@ -950,14 +975,10 @@ async fn run_agent_loop(
overrides: ProviderOverrides,
auto_approve: bool,
resume: Option<ResumeTarget>,
+ format: OutputFormat,
) -> Result<(), String> {
- let PreparedRun {
- args,
- body,
- permission_requests,
- mcp_task,
- persist,
- } = prepare_agent_run(
+ let started = std::time::Instant::now();
+ let prepared = prepare_agent_run(
project,
task,
model_override,
@@ -965,7 +986,29 @@ async fn run_agent_loop(
overrides,
auto_approve,
resume,
- )?;
+ );
+ // A setup failure never reaches the event stream, so a JSON consumer would
+ // otherwise get an empty stdout and have to parse the human error off stderr.
+ let PreparedRun {
+ args,
+ body,
+ permission_requests,
+ mcp_task,
+ persist,
+ } = match prepared {
+ Ok(prepared) => prepared,
+ Err(e) => {
+ if format.is_json() {
+ print_report(RunReport::setup_failure(&e).finish(
+ None,
+ "",
+ started.elapsed().as_millis(),
+ None,
+ ));
+ }
+ return Err(e);
+ }
+ };
// Block until active MCP servers connect, so tools (collected once per run)
// are present on the first turn.
@@ -985,30 +1028,98 @@ async fn run_agent_loop(
}
let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
+ // The report is folded in both formats from the same stream the printer
+ // reads, so the JSON envelope can never disagree with the text output.
let printer = tokio::spawn(async move {
+ let mut report = RunReport::default();
while let Some(ev) = rx.recv().await {
- print_event(ev, &permission_requests).await;
+ report.observe(&ev);
+ if format.is_json() {
+ resolve_permission_silently(ev, &permission_requests).await;
+ } else {
+ print_event(ev, &permission_requests).await;
+ }
}
+ report
});
let result = run_orchestration_streamed(&tx, &body, &args).await;
drop(tx);
- let _ = printer.await;
+ let report = printer.await.unwrap_or_default();
// Write the turn back so the session stays continuable with --resume.
+ let PersistTarget {
+ agent_dir,
+ thread_id,
+ model,
+ mut history,
+ } = persist;
+ let mut session_id = thread_id.clone();
+ let mut final_text = None;
if let Ok(completion) = result.as_ref() {
- let PersistTarget { agent_dir, thread_id, model, mut history } = persist;
- if let Some(text) = completion_text(completion) {
- history.push(serde_json::json!({ "role": "assistant", "content": text }));
+ final_text = completion_text(completion);
+ if let Some(text) = final_text.as_ref() {
+ history.push(serde_json::json!({ "role": "assistant", "content": text.clone() }));
}
match cli_save_thread(&agent_dir, thread_id.as_deref(), &model, &history, None) {
- Ok(id) => eprintln!("\x1b[2m[session {} - resume with `jan --resume={}`]\x1b[0m", short_id(&id), short_id(&id)),
+ Ok(id) => {
+ if !format.is_json() {
+ eprintln!(
+ "\x1b[2m[session {} - resume with `jan --resume={}`]\x1b[0m",
+ short_id(&id),
+ short_id(&id)
+ );
+ }
+ session_id = Some(id);
+ }
Err(e) => eprintln!("(could not save session: {e})"),
}
}
+ if format.is_json() {
+ print_report(report.finish(
+ session_id.as_deref().map(short_id).as_deref(),
+ &model,
+ started.elapsed().as_millis(),
+ final_text.as_deref(),
+ ));
+ }
result.map(|_| ())
}
+/// Write the result envelope to stdout, the only thing `--output-format json`
+/// puts there. Pretty-printed: these are read by people at least as often as by
+/// programs, and `jq` does not care either way.
+fn print_report(report: run_report::RunResult) {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&report).unwrap_or_default()
+ );
+}
+
+/// Answer a permission request without printing progress, for the JSON format.
+/// Leaving it unanswered would wedge the run: the loop waits on the reply.
+/// Every other event is silent -- stdout belongs to the envelope.
+async fn resolve_permission_silently(ev: StreamEvent, registry: &PermissionRegistry) {
+ if let StreamEvent::PermissionRequest {
+ request_id,
+ tool_name,
+ capability,
+ path,
+ command,
+ ..
+ } = ev
+ {
+ let detail = command
+ .map(|c| format!(" ({c})"))
+ .or_else(|| path.map(|p| format!(" on {p}")))
+ .unwrap_or_default();
+ let decision = prompt_permission(tool_name, capability, detail).await;
+ if let Some(sender) = registry.lock().await.remove(&request_id) {
+ let _ = sender.send(decision);
+ }
+ }
+}
+
/// Assistant text of a chat-completion response, if any.
fn completion_text(completion: &serde_json::Value) -> Option<String> {
let text = completion
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
new file mode 100644
index 000000000..876cfb11f
--- /dev/null
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -0,0 +1,351 @@
+//! Machine-readable result envelope for a non-interactive `jan cli agent run`.
+//!
+//! The human output of a run is a stream: prose on stdout, progress on stderr.
+//! `--output-format json` replaces it with a single object printed once the run
+//! is over, so a caller can branch on `is_error` and read `result` without
+//! parsing terminal chatter. The object is assembled from the same
+//! [`StreamEvent`]s the printer consumes -- there is no second source of truth.
+
+use crate::core::agent::events::StreamEvent;
+
+/// How a non-interactive run reports itself.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
+pub enum OutputFormat {
+ /// Streamed prose on stdout, progress on stderr (the default).
+ #[default]
+ Text,
+ /// A single result object on stdout when the run finishes.
+ Json,
+}
+
+impl OutputFormat {
+ pub(crate) fn is_json(self) -> bool {
+ matches!(self, OutputFormat::Json)
+ }
+}
+
+/// Terminal outcome of a run, accumulated from its event stream.
+#[derive(Default)]
+pub(crate) struct RunReport {
+ /// Assistant prose of the turn in flight, reset at each `Step` so a failed
+ /// run still reports what the model had said before it broke.
+ partial: String,
+ stop_reason: Option<String>,
+ error: Option<(String, String)>,
+ num_turns: u32,
+ prompt_tokens: u64,
+ completion_tokens: u64,
+}
+
+impl RunReport {
+ /// A run that failed before the event stream existed (bad config, no
+ /// reachable provider): no turns, no usage, just the failure.
+ pub(crate) fn setup_failure(message: &str) -> Self {
+ let mut report = Self::default();
+ report.observe(&StreamEvent::Error {
+ code: "setup_error".to_string(),
+ message: message.to_string(),
+ });
+ report
+ }
+
+ /// Fold one event into the report. Cheap enough to call on every event, so
+ /// the collector runs in both output formats and only printing differs.
+ pub(crate) fn observe(&mut self, ev: &StreamEvent) {
+ match ev {
+ StreamEvent::Step { index, .. } => {
+ self.num_turns = self.num_turns.max(*index);
+ self.partial.clear();
+ }
+ StreamEvent::Token { text } => self.partial.push_str(text),
+ StreamEvent::TurnUsage { usage } => {
+ self.prompt_tokens += usage.prompt_tokens.unwrap_or(0);
+ self.completion_tokens += usage.completion_tokens.unwrap_or(0);
+ }
+ // Subagent work is real spend on the same budget, so its usage
+ // counts. Its `Step`/`Token` must not: those describe the child's
+ // own turns and prose, not this run's.
+ StreamEvent::Subagent { event, .. } => {
+ if let StreamEvent::TurnUsage { .. } = **event {
+ self.observe(event);
+ }
+ }
+ StreamEvent::Done { stop_reason, .. } => {
+ self.stop_reason = Some(stop_reason.clone());
+ }
+ StreamEvent::Error { code, message } => {
+ self.error = Some((code.clone(), message.clone()));
+ }
+ _ => {}
+ }
+ }
+
+ /// Render the envelope. `final_text` is the completion the run returned;
+ /// on failure there is none and the partial prose stands in for it.
+ pub(crate) fn finish(
+ self,
+ session_id: Option<&str>,
+ model: &str,
+ duration_ms: u128,
+ final_text: Option<&str>,
+ ) -> RunResult {
+ let is_error = self.error.is_some();
+ RunResult {
+ kind: "result",
+ is_error,
+ result: super::tui::answer_without_reasoning(final_text.unwrap_or(&self.partial)),
+ stop_reason: if is_error {
+ "error".to_string()
+ } else {
+ self.stop_reason.unwrap_or_else(|| "stop".to_string())
+ },
+ error: self.error.map(|(code, message)| RunError {
+ code: error_code(&code, &message),
+ message,
+ }),
+ session_id: session_id.map(str::to_string),
+ model: model.to_string(),
+ num_turns: self.num_turns,
+ duration_ms: duration_ms as u64,
+ usage: ReportUsage {
+ prompt_tokens: self.prompt_tokens,
+ completion_tokens: self.completion_tokens,
+ total_tokens: self.prompt_tokens + self.completion_tokens,
+ },
+ }
+ }
+}
+
+/// The envelope itself. A struct rather than a `json!` literal so the fields
+/// serialize in declaration order: `serde_json`'s map is sorted, which would
+/// print this contract alphabetically and bury `result` in the middle.
+#[derive(serde::Serialize)]
+pub(crate) struct RunResult {
+ #[serde(rename = "type")]
+ kind: &'static str,
+ is_error: bool,
+ result: String,
+ stop_reason: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ error: Option<RunError>,
+ /// `null` when nothing was persisted, which is any run that failed before
+ /// producing a completion: there is no session to resume.
+ session_id: Option<String>,
+ model: String,
+ num_turns: u32,
+ duration_ms: u64,
+ usage: ReportUsage,
+}
+
+#[derive(serde::Serialize)]
+struct RunError {
+ code: String,
+ message: String,
+}
+
+#[derive(serde::Serialize)]
+struct ReportUsage {
+ prompt_tokens: u64,
+ completion_tokens: u64,
+ total_tokens: u64,
+}
+
+/// A stable, machine-readable code for a failure. The loop stamps every
+/// terminal error `"error"`, which tells a caller nothing; the message it
+/// carries is what distinguishes a blown context window from a refused
+/// request, and only those two are classified -- an invented taxonomy would be
+/// worse than falling back to the raw code.
+fn error_code(code: &str, message: &str) -> String {
+ if crate::core::agent::upstream::is_context_overflow_error(message) {
+ return "context_overflow".to_string();
+ }
+ if message.starts_with("Upstream ") {
+ return "upstream_error".to_string();
+ }
+ code.to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::events::Usage;
+
+ fn usage(prompt: u64, completion: u64) -> Usage {
+ Usage {
+ prompt_tokens: Some(prompt),
+ completion_tokens: Some(completion),
+ total_tokens: Some(prompt + completion),
+ }
+ }
+
+ fn value(result: RunResult) -> serde_json::Value {
+ serde_json::to_value(result).unwrap()
+ }
+
+ fn token(text: &str) -> StreamEvent {
+ StreamEvent::Token {
+ text: text.to_string(),
+ }
+ }
+
+ #[test]
+ fn success_envelope_matches_the_documented_shape() {
+ let mut report = RunReport::default();
+ for ev in [
+ StreamEvent::Step { index: 1, max: 0 },
+ StreamEvent::TurnUsage {
+ usage: usage(9011, 655),
+ },
+ token("done"),
+ StreamEvent::Done {
+ stop_reason: "end_turn".to_string(),
+ usage: None,
+ },
+ ] {
+ report.observe(&ev);
+ }
+ let out = value(report.finish(Some("3f7a91c2"), "tokamak-1-preview", 48213, Some("done")));
+
+ assert_eq!(out["type"], "result");
+ assert_eq!(out["is_error"], false);
+ assert_eq!(out["result"], "done");
+ assert_eq!(out["stop_reason"], "end_turn");
+ assert_eq!(out["session_id"], "3f7a91c2");
+ assert_eq!(out["model"], "tokamak-1-preview");
+ assert_eq!(out["num_turns"], 1);
+ assert_eq!(out["duration_ms"], 48213u64);
+ assert_eq!(out["usage"]["prompt_tokens"], 9011);
+ assert_eq!(out["usage"]["completion_tokens"], 655);
+ assert_eq!(out["usage"]["total_tokens"], 9666);
+ assert!(out.get("error").is_none(), "success carries no error key");
+ }
+
+ #[test]
+ fn failure_reports_the_partial_answer_and_a_classified_code() {
+ let mut report = RunReport::default();
+ for ev in [
+ StreamEvent::Step { index: 1, max: 0 },
+ StreamEvent::TurnUsage {
+ usage: usage(8123, 0),
+ },
+ token("I started reviewing auth.rs and"),
+ StreamEvent::Error {
+ code: "error".to_string(),
+ message: "Upstream returned HTTP 400: tool_choice does not match".to_string(),
+ },
+ ] {
+ report.observe(&ev);
+ }
+ let out = value(report.finish(Some("3f7a91c2"), "tokamak-1-preview", 1204, None));
+
+ assert_eq!(out["is_error"], true);
+ assert_eq!(out["result"], "I started reviewing auth.rs and");
+ assert_eq!(out["stop_reason"], "error");
+ assert_eq!(out["error"]["code"], "upstream_error");
+ assert_eq!(
+ out["error"]["message"],
+ "Upstream returned HTTP 400: tool_choice does not match"
+ );
+ assert_eq!(out["usage"]["total_tokens"], 8123);
+ }
+
+ #[test]
+ fn partial_answer_is_the_last_turn_only_and_drops_reasoning() {
+ let mut report = RunReport::default();
+ for ev in [
+ StreamEvent::Step { index: 1, max: 0 },
+ token("first turn prose"),
+ StreamEvent::Step { index: 2, max: 0 },
+ token("<think>deliberating</think>second turn prose"),
+ StreamEvent::Error {
+ code: "error".to_string(),
+ message: "boom".to_string(),
+ },
+ ] {
+ report.observe(&ev);
+ }
+ let out = value(report.finish(None, "m", 1, None));
+ assert_eq!(out["result"], "second turn prose");
+ assert_eq!(out["num_turns"], 2);
+ // Unclassifiable messages keep the code the loop stamped.
+ assert_eq!(out["error"]["code"], "error");
+ assert_eq!(out["session_id"], serde_json::Value::Null);
+ }
+
+ #[test]
+ fn usage_accumulates_across_turns_and_subagents() {
+ let mut report = RunReport::default();
+ let child = |ev: StreamEvent| StreamEvent::Subagent {
+ run_id: "r".to_string(),
+ name: "child".to_string(),
+ event: Box::new(ev),
+ };
+ for ev in [
+ StreamEvent::Step { index: 1, max: 0 },
+ StreamEvent::TurnUsage {
+ usage: usage(100, 10),
+ },
+ child(StreamEvent::TurnUsage {
+ usage: usage(50, 5),
+ }),
+ // A child's own turns and prose belong to the child, not this run.
+ child(StreamEvent::Step { index: 9, max: 0 }),
+ child(token("child prose")),
+ StreamEvent::Step { index: 2, max: 0 },
+ StreamEvent::TurnUsage {
+ usage: usage(200, 20),
+ },
+ ] {
+ report.observe(&ev);
+ }
+ let out = value(report.finish(None, "m", 1, Some("answer")));
+ assert_eq!(out["num_turns"], 2);
+ assert_eq!(out["result"], "answer");
+ assert_eq!(out["usage"]["prompt_tokens"], 350);
+ assert_eq!(out["usage"]["completion_tokens"], 35);
+ assert_eq!(out["usage"]["total_tokens"], 385);
+ }
+
+ /// The printed order is part of the contract: a human reading the envelope
+ /// should hit `result` near the top, not alphabetically between `num_turns`
+ /// and `session_id`.
+ #[test]
+ fn keys_serialize_in_the_documented_order() {
+ let mut report = RunReport::default();
+ report.observe(&StreamEvent::Error {
+ code: "error".to_string(),
+ message: "boom".to_string(),
+ });
+ let printed = serde_json::to_string(&report.finish(None, "m", 1, None)).unwrap();
+ let order = [
+ "\"type\"",
+ "\"is_error\"",
+ "\"result\"",
+ "\"stop_reason\"",
+ "\"error\"",
+ "\"session_id\"",
+ "\"model\"",
+ "\"num_turns\"",
+ "\"duration_ms\"",
+ "\"usage\"",
+ ];
+ let mut at = 0;
+ for key in order {
+ let found = printed[at..]
+ .find(key)
+ .unwrap_or_else(|| panic!("{key} missing or out of order in {printed}"));
+ at += found + key.len();
+ }
+ }
+
+ #[test]
+ fn context_overflow_is_classified_from_the_marker() {
+ let mut report = RunReport::default();
+ report.observe(&StreamEvent::Error {
+ code: "error".to_string(),
+ message: "[context-overflow] Upstream returned HTTP 400: too long".to_string(),
+ });
+ let out = value(report.finish(None, "m", 1, None));
+ assert_eq!(out["error"]["code"], "context_overflow");
+ }
+}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index d3ff4c348..c8517c978 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -1129,6 +1129,17 @@ struct App {
compacting: Option<CompactKind>,
/// When the in-flight compaction started, for the elapsed counter.
compact_started: Option<Instant>,
+ /// The in-flight compaction was triggered by a context-overflow error, so
+ /// the errored turn is resumed once it lands.
+ retry_after_compact: bool,
+ /// Overflow retries spent in the current user turn, capped so a model that
+ /// overflows no matter how small the context cannot spin forever.
+ overflow_retries: u8,
+ /// False once a prompt the provider *accepted* exceeded `context_window`,
+ /// which proves the configured value wrong. Nothing then divides by it: the
+ /// gauge drops its denominator, the subagent share is hidden, and proactive
+ /// compaction stands down in favour of the loop's reactive path.
+ context_window_trusted: bool,
/// An install is in flight: `/update` is refused (two processes must not
/// rewrite the same binary) and the footer shows progress.
update_installing: bool,
@@ -1411,6 +1422,9 @@ impl App {
compact_request: None,
compacting: None,
compact_started: None,
+ retry_after_compact: false,
+ overflow_retries: 0,
+ context_window_trusted: true,
scrollback: 0,
want_start: false,
turns_since_todos_closed: 0,
@@ -2254,6 +2268,9 @@ impl App {
self.last_todo_reminder = None;
self.reminder_count = 0;
self.reminder_awaiting_progress = false;
+ // A fresh turn gets a fresh overflow-recovery budget: the previous
+ // turn's failures say nothing about this one's size.
+ self.overflow_retries = 0;
self.want_start = true;
self.persist();
}
@@ -2851,6 +2868,7 @@ impl App {
// Keep the header's context gauge live during the turn
// instead of jumping only when the run ends.
self.tokens = prompt + usage.completion_tokens.unwrap_or(0);
+ self.observe_prompt_tokens(prompt);
}
}
StreamEvent::Done { .. } | StreamEvent::Error { .. } => {}
@@ -3063,10 +3081,55 @@ impl App {
self.persist();
}
- /// Whether auto-compaction should trigger after a turn completes.
+ /// Whether auto-compaction should trigger after a turn completes. Requires
+ /// a window worth measuring against: with the configured one disproven,
+ /// this would fire on every remaining turn of the session.
fn should_auto_compact(&self) -> bool {
let limit = self.context_window.saturating_sub(self.reserve_tokens);
- self.tokens > limit && self.tokens > 0 && self.history.len() > 4
+ self.context_window_trusted
+ && self.tokens > limit
+ && self.tokens > 0
+ && self.history.len() > 4
+ }
+
+ /// Fold an accepted request's prompt size into the session's view of the
+ /// context window. `context_window` is a guess (`[agent].context_window`,
+ /// default 128K) with nothing tying it to the model actually in use, so a
+ /// prompt the provider served proves it wrong when it exceeds it -- the
+ /// real window is at least this big. How much bigger is unknowable from
+ /// here, so nothing is invented: the value is simply no longer used as a
+ /// denominator, and the user is told once how to set it.
+ fn observe_prompt_tokens(&mut self, prompt_tokens: u64) {
+ if !self.context_window_trusted || prompt_tokens <= self.context_window {
+ return;
+ }
+ self.context_window_trusted = false;
+ self.note(&format!(
+ "a {}K prompt exceeded the configured {}K context window: set [agent].context_window in agent.toml",
+ (prompt_tokens + 500) / 1000,
+ self.context_window / 1000,
+ ));
+ }
+
+ /// Queue a compaction and a retry for a context-overflow error, reporting
+ /// whether recovery was taken up. Declines when the error is something
+ /// else, the turn's retry budget is spent, a compaction is already in
+ /// flight, or there is too little history for compaction to shrink -- in
+ /// those cases a retry would re-send the request that just failed.
+ fn request_overflow_recovery(&mut self, message: &str) -> bool {
+ if !crate::core::agent::upstream::is_context_overflow_error(message)
+ || self.overflow_retries >= MAX_OVERFLOW_RETRIES
+ || self.compacting.is_some()
+ || self.history.len() <= 4
+ {
+ return false;
+ }
+ self.overflow_retries += 1;
+ self.retry_after_compact = true;
+ self.compact_request = Some(CompactKind::Auto);
+ self.detail = "context overflow: compacting".to_string();
+ self.note("context overflow: compacting and retrying the turn");
+ true
}
fn on_error(&mut self, code: String, message: String) {
@@ -3081,6 +3144,20 @@ impl App {
format!("{code}: {message}")
};
self.system(Level::Error, &format!("error: {message}"));
+ // A context overflow is the one error the session can recover from by
+ // itself: compact, then resume the turn that failed. The goal loop and
+ // the message queue are left alone until the retry resolves, so neither
+ // acts on a turn that is about to run again.
+ if self.request_overflow_recovery(&message) {
+ return;
+ }
+ self.halt_turn();
+ }
+
+ /// Hand control back after a turn ended abnormally. Also reached from
+ /// `finish_compaction` when an overflow recovery is abandoned, so the two
+ /// paths cannot drift.
+ fn halt_turn(&mut self) {
// An errored turn halts the goal loop; the user decides how to recover.
self.goal_eval_pending = false;
if let Some(goal) = self.goal.as_ref() {
@@ -3200,29 +3277,59 @@ fn truncate(s: &str, max: usize) -> String {
format!("{head}…")
}
-/// Summarize tool output to one transcript line: first non-empty line with its
-/// internal whitespace collapsed, truncated to `max`, plus a `(+N lines)`
-/// suffix when more follow.
-/// Rough token count from message content characters (~4 chars ≈ 1 token).
+/// Per-message envelope (role, delimiters) in the estimate below, the usual
+/// OpenAI-accounting constant.
+const TOKENS_PER_MESSAGE: u64 = 4;
+
+/// Rough token count (~4 chars per token) for a history the provider has not
+/// reported usage for: the window between a compaction and the next response.
+/// Counts what actually goes on the wire -- text content including multimodal
+/// text parts, tool-call names and arguments, tool-result ids -- so a
+/// tool-heavy history is not scored as empty. Image parts are left out: their
+/// cost is a provider-specific function of resolution, and inventing a number
+/// there is worse than omitting one.
fn estimate_token_count(messages: &[serde_json::Value]) -> u64 {
let mut total_chars: usize = 0;
for msg in messages {
- if let Some(content) = msg.get("content").and_then(|c| c.as_str()) {
- total_chars += content.len();
- }
- if let Some(calls) = msg.get("tool_calls") {
- if let Some(arr) = calls.as_array() {
- for call in arr {
- if let Some(args) = call.get("arguments") {
- total_chars += args.to_string().len();
- }
+ match msg.get("content") {
+ Some(serde_json::Value::String(text)) => total_chars += text.len(),
+ Some(serde_json::Value::Array(parts)) => {
+ for part in parts {
+ total_chars += part
+ .get("text")
+ .and_then(|t| t.as_str())
+ .map_or(0, str::len);
}
}
+ _ => {}
+ }
+ for call in msg
+ .get("tool_calls")
+ .and_then(|c| c.as_array())
+ .into_iter()
+ .flatten()
+ {
+ // Arguments live under `function`, not on the call itself.
+ if let Some(f) = call.get("function") {
+ total_chars += f.get("name").and_then(|n| n.as_str()).map_or(0, str::len);
+ total_chars += f
+ .get("arguments")
+ .and_then(|a| a.as_str())
+ .map_or(0, str::len);
+ }
}
+ total_chars += msg
+ .get("tool_call_id")
+ .and_then(|v| v.as_str())
+ .map_or(0, str::len);
}
- (total_chars / 4).max(1) as u64
+ let envelope = TOKENS_PER_MESSAGE * messages.len() as u64;
+ ((total_chars / 4) as u64 + envelope).max(1)
}
+/// Summarize tool output to one transcript line: first non-empty line with its
+/// internal whitespace collapsed, truncated to `max`, plus a `(+N lines)`
+/// suffix when more follow.
fn summarize_result(s: &str, max: usize) -> String {
let mut lines = s.lines().filter(|l| !l.trim().is_empty());
let first = lines.next().unwrap_or("");
@@ -4004,7 +4111,7 @@ fn has_answer_text(buf: &str) -> bool {
/// `text` with its reasoning removed, for the copy that goes into `history`.
/// Reasoning is display-only and must never be resent to the model (see
/// `SseAccumulator`); the display journal is what keeps it for a resume.
-fn answer_without_reasoning(text: &str) -> String {
+pub(crate) fn answer_without_reasoning(text: &str) -> String {
split_reasoning(text)
.into_iter()
.filter_map(|(reasoning, seg)| (!reasoning).then_some(seg))
@@ -5758,6 +5865,11 @@ fn compact_command(app: &mut App) {
app.compact_request = Some(CompactKind::Manual);
}
+/// Compact-and-retry attempts allowed per user turn. The loop already retries
+/// within a single request (`MAX_COMPACTION_ATTEMPTS`); this bounds the outer
+/// recovery so a model that overflows at any size still hands control back.
+const MAX_OVERFLOW_RETRIES: u8 = 2;
+
/// Which path asked for a compaction: `/compact` keeps a shorter tail than the
/// automatic one and reports itself differently.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -5815,6 +5927,7 @@ fn finish_compaction(
) {
let kind = app.compacting.take().unwrap_or(CompactKind::Manual);
app.compact_started = None;
+ let retrying = std::mem::take(&mut app.retry_after_compact);
match result {
Ok(mut compacted) if compacted.len() < base_len => {
compacted.extend(app.history.split_off(base_len.min(app.history.len())));
@@ -5829,13 +5942,30 @@ fn finish_compaction(
app.tokens / 1000,
app.context_window / 1000,
));
+ // The turn this compaction was queued for died on an overflow
+ // error: resume it now that the history it failed on is smaller.
+ if retrying {
+ app.begin_turn();
+ app.want_start = true;
+ }
}
Ok(_) => {
if kind == CompactKind::Manual {
app.note("nothing to compact yet");
}
+ // Nothing shrank, so the retry would re-send the request that
+ // already overflowed. Hand control back instead.
+ if retrying {
+ app.note("nothing left to compact: the turn cannot be retried");
+ app.halt_turn();
+ }
+ }
+ Err(e) => {
+ app.note(&format!("{} failed: {e}", kind.label()));
+ if retrying {
+ app.halt_turn();
+ }
}
- Err(e) => app.note(&format!("{} failed: {e}", kind.label())),
}
}
@@ -8231,8 +8361,11 @@ fn agents_column(
let mut stats = format!(" {}t · {}r", panel.calls.len(), panel.requests);
// Only once the child has reported usage; "0%" before its first
// response would read as a stalled agent rather than a starting one.
+ // `context_window` arrives as 0 when the session has disproven it,
+ // and the share is clamped: a child on a model with a larger window
+ // than the parent's config would otherwise report past 100%.
if panel.prompt_tokens > 0 && context_window > 0 {
- let pct = panel.prompt_tokens as f64 / context_window as f64 * 100.0;
+ let pct = (panel.prompt_tokens as f64 / context_window as f64 * 100.0).min(100.0);
stats.push_str(&format!(" · {pct:.1}%"));
}
spans.push(Span::styled(stats, dim));
@@ -8358,6 +8491,10 @@ fn shimmer_spans(text: &str, palette: [Style; 3], frame: usize) -> Vec<Span<'sta
}
fn header(app: &App) -> Paragraph<'static> {
+ Paragraph::new(Line::from(header_spans(app)))
+}
+
+fn header_spans(app: &App) -> Vec<Span<'static>> {
let (status, style): (String, Style) = if let Some(kind) = app.compacting {
(kind.label().to_string(), Style::new().magenta().bold())
} else if app.status == Status::Idle {
@@ -8403,15 +8540,17 @@ fn header(app: &App) -> Paragraph<'static> {
));
}
spans.push(Span::raw(format!(" {turn}")));
- if app.tokens > 0 {
- spans.push(Span::raw(format!(
+ // The denominator is dropped once an accepted prompt has disproven the
+ // configured window: `ctx 143K/128K` is not a gauge, it is a contradiction.
+ match (app.tokens, app.context_window_trusted) {
+ // Round to nearest K for display clarity.
+ (0, true) => spans.push(Span::raw(format!("ctx 0/{}K ", app.context_window / 1000))),
+ (n, true) => spans.push(Span::raw(format!(
"ctx {}K/{}K ",
- // Round to nearest K for display clarity.
- (app.tokens + 500) / 1000,
+ (n + 500) / 1000,
app.context_window / 1000
- )));
- } else {
- spans.push(Span::raw(format!("ctx 0/{}K ", app.context_window / 1000)));
+ ))),
+ (n, false) => spans.push(Span::raw(format!("ctx {}K ", (n + 500) / 1000))),
}
spans.push(Span::styled(elapsed, Style::new().dim()));
// Output rate segment: last completed turn's tokens/sec, cached so it holds
@@ -8456,7 +8595,7 @@ fn header(app: &App) -> Paragraph<'static> {
} else {
spans.push(Span::styled(format!("[{status}]"), style));
}
- Paragraph::new(Line::from(spans))
+ spans
}
/// One task row: ` <glyph> <text>`, styled by status. Pending is dim,
@@ -8631,7 +8770,13 @@ fn status_panel(app: &mut App, width: u16, rows: usize) -> Vec<Line<'static>> {
return Vec::new();
}
let frame = app.spinner();
- let context_window = app.context_window;
+ // 0 is the columns' "unknown window" encoding: they suppress the share
+ // rather than divide by a value the session has already disproven.
+ let context_window = if app.context_window_trusted {
+ app.context_window
+ } else {
+ 0
+ };
let has_todos = !app.todos.is_empty() && !app.todos_expired();
let has_agents = !app.subagents.is_empty();
match (has_todos, has_agents) {
@@ -8968,7 +9113,8 @@ mod tests {
route_paste_event,
compact_tokens, finish_compaction, finish_login, finish_update_install,
image_mime_of, load_first_file_image, load_image_file, MAX_IMAGE_BYTES,
- message_text, CompactKind,
+ message_text, CompactKind, MAX_OVERFLOW_RETRIES,
+ estimate_token_count, header_spans, status_panel, SubagentPanel,
note_update, open_config_screen,
parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,
autoscroll_selection, selection_text, Selection, SelectionMode, COPY_NOTICE,
@@ -15672,6 +15818,213 @@ mod tests {
assert!(!app.should_auto_compact());
}
+ fn overflow_error() -> String {
+ format!(
+ "[{}] Upstream returned HTTP 400: context_length_exceeded",
+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER
+ )
+ }
+
+ fn app_with_history(n: usize) -> App {
+ let mut app = test_app();
+ for i in 0..n {
+ app.history.push(serde_json::json!({
+ "role": if i % 2 == 0 { "user" } else { "assistant" },
+ "content": format!("msg{i}")
+ }));
+ }
+ app
+ }
+
+ #[test]
+ fn context_overflow_error_queues_a_compaction_and_retry() {
+ let mut app = app_with_history(6);
+ app.on_error("upstream_error".into(), overflow_error());
+ assert_eq!(
+ app.compact_request,
+ Some(CompactKind::Auto),
+ "an overflow must queue a compaction instead of going idle"
+ );
+ assert!(app.retry_after_compact, "the turn must be retried");
+ assert!(!app.want_start, "the retry waits for the compaction to land");
+ }
+
+ #[test]
+ fn ordinary_error_does_not_queue_a_compaction() {
+ let mut app = app_with_history(6);
+ app.on_error("upstream_error".into(), "invalid api key".into());
+ assert_eq!(app.compact_request, None);
+ assert!(!app.retry_after_compact);
+ }
+
+ #[test]
+ fn overflow_on_a_short_history_does_not_retry() {
+ // Nothing to compact: retrying would just re-send the same request.
+ let mut app = app_with_history(2);
+ app.on_error("upstream_error".into(), overflow_error());
+ assert_eq!(app.compact_request, None);
+ assert!(!app.retry_after_compact);
+ }
+
+ #[test]
+ fn compaction_after_an_overflow_restarts_the_turn() {
+ let mut app = app_with_history(6);
+ app.on_error("upstream_error".into(), overflow_error());
+ app.compacting = app.compact_request.take();
+ let compacted = vec![serde_json::json!({ "role": "system", "content": "summary" })];
+ finish_compaction(&mut app, Ok(compacted), 7);
+ assert!(app.want_start, "a landed compaction resumes the errored turn");
+ assert!(!app.retry_after_compact);
+ assert_eq!(app.status, Status::Running);
+ }
+
+ #[test]
+ fn a_no_op_compaction_after_an_overflow_does_not_retry() {
+ // Compaction could not shrink the history, so a retry would overflow
+ // again on exactly the same request.
+ let mut app = app_with_history(6);
+ app.on_error("upstream_error".into(), overflow_error());
+ app.compacting = app.compact_request.take();
+ let unchanged = app.history.clone();
+ let base = unchanged.len();
+ finish_compaction(&mut app, Ok(unchanged), base);
+ assert!(!app.want_start);
+ assert!(!app.retry_after_compact);
+ }
+
+ #[test]
+ fn repeated_overflows_stop_retrying_within_one_turn() {
+ let mut app = app_with_history(6);
+ for _ in 0..MAX_OVERFLOW_RETRIES {
+ app.on_error("upstream_error".into(), overflow_error());
+ assert!(app.retry_after_compact);
+ app.compacting = app.compact_request.take();
+ let shorter = app.history[..app.history.len() - 1].to_vec();
+ let base = app.history.len();
+ finish_compaction(&mut app, Ok(shorter), base);
+ }
+ app.on_error("upstream_error".into(), overflow_error());
+ assert_eq!(
+ app.compact_request, None,
+ "the retry budget is spent for this turn"
+ );
+ assert!(!app.retry_after_compact);
+ }
+
+ #[test]
+ fn a_new_user_turn_rearms_the_overflow_retry_budget() {
+ let mut app = app_with_history(6);
+ app.overflow_retries = MAX_OVERFLOW_RETRIES;
+ app.submit_user("next".into());
+ assert_eq!(app.overflow_retries, 0);
+ }
+
+ fn usage_of(prompt: u64, completion: u64) -> Usage {
+ Usage {
+ prompt_tokens: Some(prompt),
+ completion_tokens: Some(completion),
+ total_tokens: Some(prompt + completion),
+ }
+ }
+
+ #[test]
+ fn estimate_counts_tool_call_arguments() {
+ // Arguments live at `function.arguments`; reading `arguments` off the
+ // call itself scored every tool-heavy history as empty.
+ let args = "x".repeat(4_000);
+ let with_calls = vec![serde_json::json!({
+ "role": "assistant",
+ "content": serde_json::Value::Null,
+ "tool_calls": [{
+ "id": "c1",
+ "function": { "name": "bash", "arguments": args }
+ }]
+ })];
+ assert!(
+ estimate_token_count(&with_calls) >= 1_000,
+ "tool-call arguments must be counted: {}",
+ estimate_token_count(&with_calls)
+ );
+ }
+
+ #[test]
+ fn estimate_counts_multimodal_text_parts() {
+ let msgs = vec![serde_json::json!({
+ "role": "user",
+ "content": [{ "type": "text", "text": "y".repeat(4_000) }]
+ })];
+ assert!(estimate_token_count(&msgs) >= 1_000);
+ }
+
+ #[test]
+ fn an_accepted_prompt_above_the_window_stops_trusting_it() {
+ let mut app = test_app();
+ assert!(app.context_window_trusted);
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage_of(200_000, 100),
+ });
+ assert!(
+ !app.context_window_trusted,
+ "a prompt the provider accepted proves the configured window wrong"
+ );
+ // The gauge has no denominator it can trust, so it must not divide.
+ assert!(!app.should_auto_compact(), "and it must not compact on it");
+ }
+
+ #[test]
+ fn a_prompt_within_the_window_keeps_it_trusted() {
+ let mut app = test_app();
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage_of(50_000, 100),
+ });
+ assert!(app.context_window_trusted);
+ }
+
+ #[test]
+ fn header_drops_the_denominator_once_the_window_is_untrusted() {
+ let mut app = test_app();
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage_of(200_000, 100),
+ });
+ let text: String = header_spans(&app)
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>();
+ assert!(text.contains("ctx 200K"), "usage still shown: {text}");
+ assert!(
+ !text.contains("/128K"),
+ "a disproven window must not be a denominator: {text}"
+ );
+ }
+
+ #[test]
+ fn subagent_share_is_suppressed_when_the_window_is_untrusted() {
+ let mut app = test_app();
+ app.subagents.push(SubagentPanel {
+ run_id: "r".into(),
+ name: "alpha".into(),
+ task: "t".into(),
+ calls: Vec::new(),
+ requests: 1,
+ prompt_tokens: 200_000,
+ active: None,
+ queued: false,
+ waiting: 0,
+ });
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage_of(200_000, 100),
+ });
+ let rows = status_panel(&mut app, 120, 8);
+ let text: String = rows
+ .iter()
+ .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
+ .collect::<String>();
+ assert!(
+ !text.contains('%'),
+ "no share against a wrong window: {text}"
+ );
+ }
+
#[test]
fn body_omits_max_tokens_when_unset() {
let app = test_app();
diff --git a/src-tauri/src/core/server/provider_secrets.rs b/src-tauri/src/core/server/provider_secrets.rs
index 3439f5275..5d2f1b9bd 100644
--- a/src-tauri/src/core/server/provider_secrets.rs
+++ b/src-tauri/src/core/server/provider_secrets.rs
@@ -319,6 +319,19 @@ mod tests {
assert!(file_remove("never-stored").is_ok());
}
+ /// The Secret Service backend is async underneath, and `load_provider_keys`
+ /// is sync and reached from async CLI paths (`cli::providers`). zbus's
+ /// `tokio` `block_on` drives a runtime of its own, which panics when it is
+ /// already inside one; the `async-io` feature must be what is selected.
+ #[tokio::test]
+ async fn keyring_read_survives_being_called_inside_a_runtime() {
+ let _tmp = TempDataFolder::new();
+ // A prior test may have latched the keyring off, which would skip the
+ // very path under test.
+ KEYRING_DOWN.store(false, Ordering::Relaxed);
+ assert!(load_provider_keys("never-stored-provider").is_empty());
+ }
+
/// A stored key must persist across reloads (restarts) and only disappear on
/// an explicit remove — never as a side effect of provider-config churn.
/// Regression guard for keys being wiped during boot reconciliation.