Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): close pi parity gaps in prompt, harness, and context mgmt

Akarshan Biswasfb7aaa2f3927
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
new file mode 100644
index 000000000..29e21cb7f
--- /dev/null
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -0,0 +1,228 @@
+//! Reactive context compaction. The agent loop has no reliable view of a
+//! model's context window at request time (local windows live inside the
+//! llamacpp plugin/preset; remote windows are unknown), so compaction is
+//! triggered by an upstream context-overflow error rather than a proactive
+//! token estimate. Given the conversation, we preserve the leading system
+//! message(s) and a recent tail, summarize the dropped middle via one model
+//! call, and splice the summary back in. If summarization fails the middle is
+//! replaced with a short note, so the run always makes forward progress.
+
+use serde_json::{json, Value};
+use tokio::sync::mpsc;
+
+use crate::core::agent::r#loop::ModelInvoker;
+use crate::core::agent::upstream::extract_choice_message;
+
+/// Default number of most-recent non-system messages kept verbatim.
+pub(crate) const DEFAULT_KEEP_RECENT: usize = 8;
+
+const SUMMARY_SYSTEM_PROMPT: &str = "You are compacting an AI agent conversation that grew too long for \
+the model's context window. Summarize the messages 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.]";
+
+fn role(msg: &Value) -> &str {
+ msg.get("role").and_then(|r| r.as_str()).unwrap_or("")
+}
+
+/// Compact `messages` so the result is meaningfully smaller than the input.
+/// Returns the input unchanged when there is nothing safe to compact (so the
+/// caller can detect a no-op and stop retrying).
+pub(crate) async fn compact_conversation(
+ messages: &[Value],
+ model_id: &str,
+ model: &dyn ModelInvoker,
+ keep_recent: usize,
+) -> Vec<Value> {
+ let sys_end = messages.iter().take_while(|m| role(m) == "system").count();
+ let (system_msgs, rest) = messages.split_at(sys_end);
+
+ if rest.len() <= keep_recent {
+ return messages.to_vec();
+ }
+
+ let mut cut = rest.len() - keep_recent;
+ // The kept tail must not begin with an orphaned tool result whose assistant
+ // tool-call message sits in the dropped prefix; push the boundary forward
+ // until the tail starts on a user/assistant message.
+ while cut < rest.len() && role(&rest[cut]) == "tool" {
+ cut += 1;
+ }
+ if cut == 0 || cut >= rest.len() {
+ return messages.to_vec();
+ }
+
+ let dropped = &rest[..cut];
+ let kept = &rest[cut..];
+ let summary = summarize(dropped, model_id, model).await;
+
+ let mut out = Vec::with_capacity(system_msgs.len() + 1 + kept.len());
+ out.extend_from_slice(system_msgs);
+ out.push(json!({
+ "role": "system",
+ "content": format!("[Summary of earlier conversation, condensed to save context]\n\n{summary}")
+ }));
+ out.extend_from_slice(kept);
+ out
+}
+
+async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker) -> String {
+ let request = json!({
+ "model": model_id,
+ "messages": [
+ { "role": "system", "content": SUMMARY_SYSTEM_PROMPT },
+ { "role": "user", "content": serialize_messages(dropped) }
+ ]
+ });
+ // Discard the summarizer's streamed tokens: a dropped receiver means these
+ // never reach the user-facing event stream.
+ let (sink, _rx) = mpsc::unbounded_channel();
+ match model.invoke(&request, &sink).await {
+ Ok(completion) => extract_choice_message(&completion)
+ .and_then(|m| m.get("content"))
+ .and_then(|c| c.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+ .unwrap_or_else(|| FALLBACK_NOTE.to_string()),
+ Err(_) => FALLBACK_NOTE.to_string(),
+ }
+}
+
+/// Render dropped messages as plain text for the summarizer, capped so a very
+/// large prefix cannot itself overflow the summarization request; the most
+/// recent (most relevant) content is kept when truncating.
+fn serialize_messages(messages: &[Value]) -> String {
+ const MAX_CHARS: usize = 120_000;
+ let mut lines: Vec<String> = Vec::with_capacity(messages.len());
+ for msg in messages {
+ let r = role(msg);
+ let content = match msg.get("content") {
+ Some(Value::String(s)) => s.clone(),
+ Some(Value::Null) | None => String::new(),
+ Some(other) => other.to_string(),
+ };
+ let mut line = format!("{r}: {content}");
+ if let Some(calls) = msg.get("tool_calls").and_then(|v| v.as_array()) {
+ let names: Vec<&str> = calls
+ .iter()
+ .filter_map(|c| c.get("function").and_then(|f| f.get("name")).and_then(|n| n.as_str()))
+ .collect();
+ if !names.is_empty() {
+ line.push_str(&format!(" [tool_calls: {}]", names.join(", ")));
+ }
+ }
+ lines.push(line);
+ }
+ let joined = lines.join("\n");
+ if joined.len() > MAX_CHARS {
+ let start = joined.len() - MAX_CHARS;
+ // Snap to a char boundary so the slice is valid UTF-8.
+ let start = (start..joined.len())
+ .find(|i| joined.is_char_boundary(*i))
+ .unwrap_or(joined.len());
+ format!("[...older content truncated...]\n{}", &joined[start..])
+ } else {
+ joined
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use async_trait::async_trait;
+ use std::sync::Mutex as StdMutex;
+
+ struct StubModel {
+ summary: String,
+ calls: StdMutex<usize>,
+ }
+ #[async_trait]
+ impl ModelInvoker for StubModel {
+ async fn invoke(
+ &self,
+ _request: &Value,
+ _events: &mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
+ ) -> Result<Value, String> {
+ *self.calls.lock().unwrap() += 1;
+ Ok(json!({ "choices": [{ "message": { "content": self.summary.clone() } }] }))
+ }
+ }
+
+ struct FailingModel;
+ #[async_trait]
+ impl ModelInvoker for FailingModel {
+ async fn invoke(
+ &self,
+ _request: &Value,
+ _events: &mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
+ ) -> Result<Value, String> {
+ Err("boom".to_string())
+ }
+ }
+
+ fn convo(n: usize) -> Vec<Value> {
+ let mut v = vec![json!({ "role": "system", "content": "sys" })];
+ for i in 0..n {
+ let r = if i % 2 == 0 { "user" } else { "assistant" };
+ v.push(json!({ "role": r, "content": format!("msg{i}") }));
+ }
+ v
+ }
+
+ #[tokio::test]
+ async fn noop_when_nothing_to_compact() {
+ let model = StubModel { summary: "S".into(), calls: StdMutex::new(0) };
+ let input = convo(4);
+ let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT).await;
+ assert_eq!(out, input);
+ assert_eq!(*model.calls.lock().unwrap(), 0, "no summarization on no-op");
+ }
+
+ #[tokio::test]
+ async fn compacts_and_preserves_system_and_tail() {
+ let model = StubModel { summary: "CONDENSED".into(), calls: StdMutex::new(0) };
+ let input = convo(20);
+ let out = compact_conversation(&input, "m", &model, 4).await;
+
+ assert!(out.len() < input.len());
+ assert_eq!(role(&out[0]), "system");
+ assert_eq!(out[0]["content"], "sys");
+ // Second message is the injected summary.
+ assert_eq!(role(&out[1]), "system");
+ assert!(out[1]["content"].as_str().unwrap().contains("CONDENSED"));
+ // Last four originals are kept verbatim.
+ assert_eq!(out[out.len() - 1]["content"], "msg19");
+ assert_eq!(out[out.len() - 4]["content"], "msg16");
+ }
+
+ #[tokio::test]
+ async fn falls_back_to_note_when_summarizer_fails() {
+ let input = convo(20);
+ let out = compact_conversation(&input, "m", &FailingModel, 4).await;
+ assert!(out[1]["content"].as_str().unwrap().contains(FALLBACK_NOTE));
+ assert!(out.len() < input.len());
+ }
+
+ #[tokio::test]
+ async fn tail_never_starts_with_orphan_tool_result() {
+ let model = StubModel { summary: "S".into(), calls: StdMutex::new(0) };
+ let mut input = vec![json!({ "role": "system", "content": "sys" })];
+ for i in 0..6 {
+ input.push(json!({ "role": "user", "content": format!("u{i}") }));
+ input.push(json!({
+ "role": "assistant", "content": Value::Null,
+ "tool_calls": [{ "id": "t", "function": { "name": "read" } }]
+ }));
+ input.push(json!({ "role": "tool", "tool_call_id": "t", "content": "res" }));
+ }
+ // keep_recent=4 would place the boundary mid tool-group; the guard must
+ // advance it so the kept tail does not begin with a tool message.
+ let out = compact_conversation(&input, "m", &model, 4).await;
+ let first_kept = &out[2];
+ assert_ne!(role(first_kept), "tool", "kept tail must not start with a tool result");
+ }
+}
diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rs
index 22739cac4..3a21636f4 100644
--- a/src-tauri/src/core/agent/context.rs
+++ b/src-tauri/src/core/agent/context.rs
@@ -6,6 +6,59 @@ use std::path::Path;
use crate::core::agent::skills;
+/// Default persona used only when no assistant instructions are supplied, so a
+/// bare project run still opens with a role statement instead of "# Working
+/// Directory". An assistant's own instructions replace this entirely.
+const DEFAULT_IDENTITY: &str = "You are Jan, an AI coding agent. You help users by reading files, \
+running commands, editing code, and writing new files.";
+
+/// Always-on behavioral guidelines. Kept short and model-facing.
+const GUIDELINES: &str =
+ "# Guidelines\n\n- Be concise in your responses.\n- Show file paths clearly when working with files.";
+
+/// Context-file names discovered by walking from the project root up to the
+/// filesystem root, most general (top ancestor) first so the nearest file wins.
+const CONTEXT_FILE_NAMES: &[&str] = &["AGENTS.md", "CLAUDE.md"];
+
+/// Ingest project instruction files (`AGENTS.md` / `CLAUDE.md`) from the project
+/// root and its ancestors, wrapped in a `<project_context>` block so the model
+/// treats them as authoritative project instructions. Returns None when none
+/// exist. At most one file per directory (first match by `CONTEXT_FILE_NAMES`).
+pub(crate) fn load_context_files(project_root: &Path) -> Option<String> {
+ let mut files: Vec<(std::path::PathBuf, String)> = Vec::new();
+ let mut dir = Some(project_root);
+ while let Some(current) = dir {
+ for name in CONTEXT_FILE_NAMES {
+ let path = current.join(name);
+ if let Ok(content) = std::fs::read_to_string(&path) {
+ if !content.trim().is_empty() {
+ files.push((path, content));
+ }
+ break;
+ }
+ }
+ dir = current.parent();
+ }
+ if files.is_empty() {
+ return None;
+ }
+ // Ancestors are collected nearest-first; reverse so the nearest (most
+ // specific) instructions appear last and take precedence.
+ files.reverse();
+ let mut block = String::from(
+ "<project_context>\n\nProject-specific instructions and guidelines:\n\n",
+ );
+ for (path, content) in files {
+ block.push_str(&format!(
+ "<project_instructions path=\"{}\">\n{}\n</project_instructions>\n\n",
+ path.display(),
+ content.trim()
+ ));
+ }
+ block.push_str("</project_context>");
+ Some(block)
+}
+
/// Built-in guide teaching the model the skills/memory file conventions. Always
/// injected for project runs so the model can read and maintain both without
/// prior knowledge. Embedded in the binary at compile time.
@@ -64,9 +117,11 @@ pub(crate) fn build_system_prompt(
subagents_enabled: bool,
) -> Option<String> {
let mut blocks: Vec<String> = Vec::new();
- if let Some(b) = base {
- blocks.push(b.to_string());
+ match base {
+ Some(b) => blocks.push(b.to_string()),
+ None => blocks.push(DEFAULT_IDENTITY.to_string()),
}
+ blocks.push(GUIDELINES.to_string());
blocks.push(format!(
"# Working Directory\n\nCurrent project directory: `{}`\n\nAll relative paths in tool calls resolve against this directory unless stated otherwise.",
project_root.display()
@@ -75,6 +130,9 @@ pub(crate) fn build_system_prompt(
blocks.push(SUBAGENT_GUIDE.to_string());
}
blocks.push(DEFAULT_SKILL_GUIDE.trim().to_string());
+ if let Some(context) = load_context_files(project_root) {
+ blocks.push(context);
+ }
if let Some(skills) = load_skills(project_root) {
blocks.push(skills);
}
@@ -173,6 +231,46 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ #[test]
+ fn default_identity_and_guidelines_present_without_base() {
+ let root = scratch_project("identity");
+ let out = build_system_prompt(None, &root, false).expect("prompt");
+ assert!(out.starts_with("You are Jan, an AI coding agent."));
+ assert!(out.contains("# Guidelines"));
+ assert!(out.contains("Be concise"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn context_files_ingested_nearest_last() {
+ let root = scratch_project("ctxfiles");
+ let nested = root.join("sub");
+ std::fs::create_dir_all(&nested).unwrap();
+ std::fs::write(root.join("AGENTS.md"), "ROOT_RULES").unwrap();
+ std::fs::write(nested.join("CLAUDE.md"), "NESTED_RULES").unwrap();
+
+ let block = load_context_files(&nested).expect("context block");
+ assert!(block.starts_with("<project_context>"));
+ assert!(block.contains("ROOT_RULES"));
+ assert!(block.contains("NESTED_RULES"));
+ assert!(block.contains("<project_instructions path="));
+ // Nearest (nested) file wins by appearing last.
+ assert!(block.find("ROOT_RULES").unwrap() < block.find("NESTED_RULES").unwrap());
+
+ let prompt = build_system_prompt(None, &nested, false).expect("prompt");
+ // Context files precede the skills catalog position and follow the guide.
+ assert!(prompt.contains("NESTED_RULES"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn no_context_files_yields_none() {
+ let root = scratch_project("noctx");
+ std::fs::create_dir_all(&root).unwrap();
+ assert!(load_context_files(&root).is_none());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn build_system_prompt_advertises_subagents_only_when_enabled() {
let root = scratch_project("subagents");
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 2de9b2710..d6449debf 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -324,6 +324,11 @@ impl ToolInvoker for CompositeToolInvoker {
};
let mut out: Vec<ToolOutcome> = Vec::with_capacity(tool_calls.len());
let mut mcp_calls: Vec<serde_json::Value> = Vec::new();
+ // Auto-allowed read-only built-ins (no prompt, no filesystem mutation)
+ // are deferred and executed concurrently after the gating pass. Anything
+ // that prompts, writes, execs, or dispatches stays sequential so
+ // permission prompts don't interleave and writes can't race.
+ let mut read_futures = Vec::new();
for tc in tool_calls {
let name = tc
.get("function")
@@ -391,6 +396,18 @@ impl ToolInvoker for CompositeToolInvoker {
&self.permissions,
&snapshot,
);
+ if matches!(decision, Decision::Allow) && tool.capability == Capability::Read {
+ let root = self.project_root.clone();
+ read_futures.push(async move {
+ let (text, diff) = execute_builtin_with_diff(tool, &args, &root).await;
+ ToolOutcome {
+ id,
+ content: text,
+ diff,
+ }
+ });
+ continue;
+ }
let (text, diff) = match decision {
Decision::Allow => execute_builtin_with_diff(tool, &args, &self.project_root).await,
Decision::HardDeny => {
@@ -469,6 +486,9 @@ impl ToolInvoker for CompositeToolInvoker {
diff,
});
}
+ if !read_futures.is_empty() {
+ out.extend(futures::future::join_all(read_futures).await);
+ }
if !mcp_calls.is_empty() {
out.extend(self.mcp.invoke(&mcp_calls).await?);
}
@@ -854,6 +874,34 @@ async fn orchestrate_inner(
}
}
+/// Upper bound on compaction retries per model call, so a persistently
+/// overflowing request fails loudly instead of looping forever.
+const MAX_COMPACTION_ATTEMPTS: usize = 4;
+
+/// Build one OpenAI chat-completion request from the current conversation.
+fn build_completion_request(
+ model_id: &str,
+ conversation_messages: &[serde_json::Value],
+ openai_tools: &[serde_json::Value],
+ json_body: &serde_json::Value,
+) -> serde_json::Value {
+ let mut completion_map = serde_json::Map::new();
+ completion_map.insert("model".to_string(), serde_json::json!(model_id));
+ completion_map.insert(
+ "messages".to_string(),
+ serde_json::Value::Array(conversation_messages.to_vec()),
+ );
+ completion_map.insert("tool_choice".to_string(), serde_json::json!("auto"));
+ if !openai_tools.is_empty() {
+ completion_map.insert(
+ "tools".to_string(),
+ serde_json::Value::Array(openai_tools.to_vec()),
+ );
+ }
+ copy_optional_chat_params(json_body, &mut completion_map);
+ serde_json::Value::Object(completion_map)
+}
+
#[allow(clippy::too_many_arguments)]
async fn run_turn_cycle(
events: &mpsc::UnboundedSender<StreamEvent>,
@@ -877,25 +925,45 @@ async fn run_turn_cycle(
max: max_turns as u32,
});
- let mut completion_map = serde_json::Map::new();
- completion_map.insert("model".to_string(), serde_json::json!(model_id));
- completion_map.insert(
- "messages".to_string(),
- serde_json::Value::Array(conversation_messages.clone()),
- );
- completion_map.insert("tool_choice".to_string(), serde_json::json!("auto"));
-
- if !openai_tools.is_empty() {
- completion_map.insert(
- "tools".to_string(),
- serde_json::Value::Array(openai_tools.to_vec()),
- );
- }
-
- copy_optional_chat_params(json_body, &mut completion_map);
- let request_value = serde_json::Value::Object(completion_map);
-
- let completion = model.invoke(&request_value, events).await?;
+ // On a context-overflow error, compact the conversation and retry.
+ // Compaction runs progressively (a smaller kept tail each attempt) and
+ // the loop gives up if a pass fails to shrink the message list.
+ let completion = {
+ let mut keep_recent = crate::core::agent::compaction::DEFAULT_KEEP_RECENT;
+ let mut attempts = 0usize;
+ loop {
+ let request_value =
+ build_completion_request(model_id, &conversation_messages, openai_tools, json_body);
+ match model.invoke(&request_value, events).await {
+ Ok(c) => break c,
+ Err(e)
+ if crate::core::agent::upstream::is_context_overflow_error(&e)
+ && attempts < MAX_COMPACTION_ATTEMPTS =>
+ {
+ let compacted = crate::core::agent::compaction::compact_conversation(
+ &conversation_messages,
+ model_id,
+ model,
+ keep_recent,
+ )
+ .await;
+ if compacted.len() >= conversation_messages.len() {
+ return Err(e);
+ }
+ log::info!(
+ "agent: context overflow, compacted {} -> {} messages (attempt {})",
+ conversation_messages.len(),
+ compacted.len(),
+ attempts + 1
+ );
+ conversation_messages = compacted;
+ keep_recent = (keep_recent / 2).max(2);
+ attempts += 1;
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ };
budget.record(&Usage::from_completion(&completion));
@@ -952,6 +1020,33 @@ async fn run_turn_cycle(
}));
}
+ // A `length` finish means the model was cut off mid-emission, so the
+ // streamed tool-call arguments may be silently truncated. Executing them
+ // would run with partial/empty args; instead fail every call so the model
+ // sees the error and retries with a shorter response next turn.
+ if stop_reason_of(&completion) == "length" {
+ for tc in &tool_calls {
+ let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let content =
+ "ERROR: response truncated (finish_reason=length); tool-call arguments are \
+ incomplete and were not executed. Retry with a shorter response."
+ .to_string();
+ let _ = events.send(StreamEvent::ToolResult {
+ id: id.clone(),
+ content: content.clone(),
+ is_error: true,
+ diff: None,
+ });
+ conversation_messages.push(serde_json::json!({
+ "role": "tool",
+ "tool_call_id": id,
+ "content": content
+ }));
+ }
+ turn += 1;
+ continue;
+ }
+
let tool_results = tools.invoke(&tool_calls).await?;
for outcome in tool_results {
@@ -1130,6 +1225,83 @@ mod tests {
);
}
+ struct ResultQueueModel {
+ results: StdMutex<VecDeque<Result<serde_json::Value, String>>>,
+ }
+ #[async_trait]
+ impl ModelInvoker for ResultQueueModel {
+ async fn invoke(
+ &self,
+ _request: &serde_json::Value,
+ _events: &mpsc::UnboundedSender<StreamEvent>,
+ ) -> Result<serde_json::Value, String> {
+ self.results
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| Err("mock exhausted".to_string()))
+ }
+ }
+
+ #[tokio::test]
+ async fn turn_cycle_compacts_and_retries_on_context_overflow() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ // 1) main request overflows, 2) summarizer succeeds, 3) retry succeeds.
+ let overflow = Err(format!(
+ "[{}] Upstream returned HTTP 400: context_length_exceeded",
+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER
+ ));
+ let model = ResultQueueModel {
+ results: StdMutex::new(
+ vec![
+ overflow,
+ Ok(json!({ "choices": [{ "message": { "content": "SUMMARY" } }] })),
+ Ok(json!({ "choices": [{ "message": { "content": "final" }, "finish_reason": "stop" }] })),
+ ]
+ .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..20 {
+ let r = if i % 2 == 0 { "user" } else { "assistant" };
+ convo.push(json!({ "role": r, "content": format!("m{i}") }));
+ }
+
+ let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool)
+ .await
+ .unwrap();
+
+ assert_eq!(result["choices"][0]["message"]["content"], "final");
+ assert!(tool.calls.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn turn_cycle_skips_execution_on_truncated_tool_calls() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let mut truncated = tool_call_completion();
+ truncated["choices"][0]["finish_reason"] = json!("length");
+ let model = MockModel::new(vec![
+ truncated,
+ json!({ "choices": [{ "message": { "content": "recovered" }, "finish_reason": "stop" }] }),
+ ]);
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(None);
+ let convo = vec![json!({ "role": "user", "content": "hi" })];
+
+ let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool)
+ .await
+ .unwrap();
+
+ assert_eq!(result["choices"][0]["message"]["content"], "recovered");
+ assert!(
+ tool.calls.lock().unwrap().is_empty(),
+ "truncated tool calls must not execute"
+ );
+ }
+
#[tokio::test]
async fn turn_cycle_unbounded_runs_until_final_answer() {
let (tx, _rx) = mpsc::unbounded_channel();
@@ -1246,6 +1418,38 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn parallel_reads_all_execute_and_preserve_order() {
+ let root = unique_project_root();
+ std::fs::write(root.join("a.txt"), "AAA").unwrap();
+ std::fs::write(root.join("b.txt"), "BBB").unwrap();
+ std::fs::write(root.join("c.txt"), "CCC").unwrap();
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ // Read-only default => reads auto-allow (no prompt) and run concurrently.
+ let invoker = build_prompting_invoker(root.clone(), tx, registry);
+
+ let read = |id: &str, path: &str| {
+ json!({
+ "id": id,
+ "type": "function",
+ "function": { "name": "read", "arguments": format!("{{\"path\":\"{path}\"}}") }
+ })
+ };
+ let calls = vec![read("r1", "a.txt"), read("r2", "b.txt"), read("r3", "c.txt")];
+ let out = invoker.invoke(&calls).await.unwrap();
+
+ assert_eq!(out.len(), 3);
+ // Output order must match input order regardless of completion order.
+ assert_eq!(out[0].id, "r1");
+ assert_eq!(out[1].id, "r2");
+ assert_eq!(out[2].id, "r3");
+ assert!(out[0].content.contains("AAA"), "got: {}", out[0].content);
+ assert!(out[1].content.contains("BBB"), "got: {}", out[1].content);
+ assert!(out[2].content.contains("CCC"), "got: {}", out[2].content);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[tokio::test]
async fn prompt_allow_once_executes_and_writes() {
let root = unique_project_root();
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 462bda42b..bd5fc81f0 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -2,6 +2,7 @@
//! plumbing, consumed by both the API-server proxy and `tauri-plugin-agent`.
pub mod commands;
+pub mod compaction;
pub mod context;
pub mod events;
#[cfg(feature = "cli")]
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 8182d2566..03d1a72ea 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -399,6 +399,33 @@ pub(crate) async fn call_openai_chat_completions(
/// (with usage), emits `StreamEvent::Token` per content delta, and reconstructs
/// an OpenAI non-streaming completion JSON so the rest of the loop (tool-call
/// extraction, history append) is identical to the non-streaming path.
+/// Stable marker prefixed onto an upstream error when the failure looks like a
+/// context/prompt-length overflow, so the agent loop can react (compact + retry)
+/// instead of surfacing the raw provider error. Works uniformly for local
+/// (llama-server) and remote (OpenAI/Anthropic/Google) since all report overflow
+/// via an HTTP error body rather than the streamed deltas.
+pub(crate) const CONTEXT_OVERFLOW_MARKER: &str = "context-overflow";
+
+/// True when a provider error body reads like a context/prompt-length overflow.
+/// Matches the OpenAI `context_length_exceeded` code, Anthropic's "prompt is too
+/// long", Google's token-limit phrasing, and llama-server's context messages.
+pub(crate) fn is_context_overflow_body(body: &str) -> bool {
+ let b = body.to_lowercase();
+ b.contains("context_length_exceeded")
+ || b.contains("maximum context length")
+ || b.contains("prompt is too long")
+ || b.contains("exceeds the maximum number of tokens")
+ || b.contains("the request exceeds the available context")
+ || b.contains("exceed context")
+ || b.contains("context window")
+ || (b.contains("context") && b.contains("too long"))
+}
+
+/// True when an error string carries the [`CONTEXT_OVERFLOW_MARKER`].
+pub(crate) fn is_context_overflow_error(err: &str) -> bool {
+ err.contains(CONTEXT_OVERFLOW_MARKER)
+}
+
pub(crate) async fn stream_openai_chat_completions(
client: &Client,
upstream_url: &str,
@@ -446,6 +473,9 @@ pub(crate) async fn stream_openai_chat_completions(
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;
@@ -692,6 +722,27 @@ mod tests {
mpsc::unbounded_channel()
}
+ #[test]
+ fn detects_provider_context_overflow_bodies() {
+ assert!(is_context_overflow_body(
+ "{\"error\":{\"code\":\"context_length_exceeded\"}}"
+ ));
+ assert!(is_context_overflow_body("This model's maximum context length is 8192 tokens"));
+ assert!(is_context_overflow_body("prompt is too long: 210000 tokens > 200000"));
+ assert!(is_context_overflow_body(
+ "the request exceeds the available context size"
+ ));
+ assert!(!is_context_overflow_body("invalid api key"));
+ assert!(!is_context_overflow_body("rate limit exceeded"));
+ }
+
+ #[test]
+ fn overflow_marker_round_trips() {
+ let err = format!("[{CONTEXT_OVERFLOW_MARKER}] Upstream returned HTTP 400: ...");
+ assert!(is_context_overflow_error(&err));
+ assert!(!is_context_overflow_error("Upstream returned HTTP 500: boom"));
+ }
+
#[test]
fn accumulates_content_and_emits_token_per_delta() {
let (tx, mut rx) = sink();