Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): stop early compaction on 1M models and report every compaction (#9088)
Akarshan Biswas8c816cafbb09
diff --git a/adk/python/jan_adk/_generated.py b/adk/python/jan_adk/_generated.pyindex 11dbb4dc1..91fc8adca 100644--- a/adk/python/jan_adk/_generated.py+++ b/adk/python/jan_adk/_generated.py@@ -43,6 +43,7 @@ EVENT_TAGS: tuple[str, ...] = ("subagent_plan","subagent","notice",+ "compaction","monitors","parked","messages_updated",@@ -92,6 +93,7 @@ EventTag = Literal["subagent_plan","subagent","notice",+ "compaction","monitors","parked","messages_updated",@@ -119,6 +121,12 @@ class ClientInfo(TypedDict):name: strversion: str+# `Deserialize` as well as `Serialize`: a consumer validates what it received against these shapes, and `JsonSchema` is what `jan cli agent schema` publishes them as -- a consumer generates its own types from `protocol/schema.json` rather than copying this declaration. The wire has to survive a round trip, not just a write, so `#[serde(tag = "type")]` keeps the tag on both sides. Where a [`StreamEvent::Compaction`] is in its round trip.+CompactionPhase = Union[Literal["started", "finished"], Literal["failed"]]++# Which path asked for a [`StreamEvent::Compaction`].+CompactionReason = Union[Literal["preflight"], Literal["context_overflow"], Literal["session_budget"]]+# What a host says a tool does, which decides how the loop treats it. Absent means opaque: prompted unless `auto_approve`, sequential, withheld in Plan mode -- the plugin/MCP default.HostCapability = Union[Literal["read"], Literal["actuator"]]@@ -374,6 +382,14 @@ class NoticeEvent(TypedDict):text: strtype: Literal["notice"]+class CompactionEvent(TypedDict):+ """`item/compaction`"""++ phase: CompactionPhase+ reason: CompactionReason+ messages: NotRequired[Union[int, None]]+ type: Literal["compaction"]+class MonitorsEvent(TypedDict):"""`item/monitors`"""@@ -512,6 +528,7 @@ StreamEvent = Union[SubagentPlanEvent,SubagentEvent,NoticeEvent,+ CompactionEvent,MonitorsEvent,ParkedEvent,MessagesUpdatedEvent,diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdxindex ca773a82b..f08121a10 100644--- a/docs/src/pages/docs/agent/context.mdx+++ b/docs/src/pages/docs/agent/context.mdx@@ -171,13 +171,22 @@ compaction_ratio = 0.6The check runs on the request itself, before it is dispatched, so the break lands at a point thesession chose rather than after a provider rejects an oversized prompt and the run retries. When itruns, the session history is replaced with the compacted version, the transcript is told, and the-console says so:+console says so. While the summary is being written, the header and input row show `compacting`,+and the note that follows says why it happened:```auto-compacted 84 -> 31 messages (ctx 96K/128K)-compacted 84 messages into a summary before sending (104K tokens against a 102K token budget)+compacted 84 messages into a summary: the prompt neared the context window```+A run also compacts when it uses up its [session token budget](#budgets), and after a provider+rejects a prompt as too long (see [Context overflow](#context-overflow)). Both report the same+way, and so does a subagent's compaction, prefixed with its name.++Headless and RPC clients get a `compaction` event: `phase` is `started`, then `finished` (with+`messages`, the number summarized) or `failed`, and `reason` is `preflight`, `context_overflow` or+`session_budget`.+## Compacting on purpose```@@ -215,7 +224,7 @@ Separately from the context window, a project can bound how far one run goes:```toml[budget]-# max_tokens = 128000 # token-spend ceiling per run; 0 disables the cap+# max_tokens = 128000 # token-spend ceiling per run; defaults to the model's context window; 0 disables the cap```That's a stop point for the run as a whole, not a per-request limit. There is no turn cap - thediff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdxindex 370ae72d6..b428372cd 100644--- a/docs/src/pages/docs/agent/project-config.mdx+++ b/docs/src/pages/docs/agent/project-config.mdx@@ -95,8 +95,8 @@ by hand or with `/init`.# compaction_ratio = 0.6 # override the [agent] ratio for this provider's routes# The run's only cap: new token spend across all turns (replayed context is not-# recharged each turn). There is no turn limit. Defaults to 128000 when unset;-# 0 disables the cap.+# recharged each turn). There is no turn limit. Defaults to the model's context+# window when unset (128000 if the window is unknown); 0 disables the cap.[budget]# max_tokens = 128000# max_usd = 5.00@@ -147,7 +147,7 @@ Desktop. Most projects don't need it. See [Providers](/docs/agent/providers#per-| Key | Default | Description || --- | --- | --- |-| `max_tokens` | `128000` | Advisory token ceiling for one run (new spend across all turns). Set `0` to disable it. Overridden per invocation by `--max-session-tokens`. Defaults to `128000` when unset |+| `max_tokens` | model's context window | Advisory token ceiling for one run (new spend across all turns). Set `0` to disable it. Overridden per invocation by `--max-session-tokens`. Defaults to the model's context window when unset, or `128000` when the window is unknown || `max_usd` | unset | USD one run may spend before it stops -- a hard bound, unlike `max_tokens`. Priced from the provider's published rates, so a model with no published price is refused rather than run uncapped. Subagents inherit it. Overridden per invocation by `--max-budget-usd` |A marker for how far one run has gone, distinct from the per-request context window. It tracks thediff --git a/packages/adk/src/generated/rpc-types.d.ts b/packages/adk/src/generated/rpc-types.d.tsindex 1b3887291..6959295f9 100644--- a/packages/adk/src/generated/rpc-types.d.ts+++ b/packages/adk/src/generated/rpc-types.d.ts@@ -38,6 +38,7 @@ export type EventTag =| "subagent_plan"| "subagent"| "notice"+ | "compaction"| "monitors"| "parked"| "messages_updated"@@ -68,6 +69,12 @@ export interface ClientInfo {"version": string}+/** `Deserialize` as well as `Serialize`: a consumer validates what it received against these shapes, and `JsonSchema` is what `jan cli agent schema` publishes them as -- a consumer generates its own types from `protocol/schema.json` rather than copying this declaration. The wire has to survive a round trip, not just a write, so `#[serde(tag = "type")]` keeps the tag on both sides. Where a [`StreamEvent::Compaction`] is in its round trip. */+export type CompactionPhase = "started" | "finished" | "failed"++/** Which path asked for a [`StreamEvent::Compaction`]. */+export type CompactionReason = "preflight" | "context_overflow" | "session_budget"+/** What a host says a tool does, which decides how the loop treats it. Absent means opaque: prompted unless `auto_approve`, sequential, withheld in Plan mode -- the plugin/MCP default. */export type HostCapability = "read" | "actuator"@@ -345,6 +352,14 @@ export interface NoticeEvent {"type": "notice"}+/** The loop is summarizing part of the conversation to make room. Sent as `Started` before the summarizer call and `Finished` or `Failed` after it, so a consumer can show progress for what is otherwise a silent round trip. `reason` says which path asked. `messages` is how many were folded into the summary, `None` except on `Finished`. Display-only and never journaled; the compacted history itself arrives as `MessagesUpdated`. */+export interface CompactionEvent {+ "phase": CompactionPhase+ "reason": CompactionReason+ "messages"?: number | null+ "type": "compaction"+}+/** The run's active file monitors, as a whole replacing the previous set. Emitted whenever the set changes (a `monitor` start or stop, a condition matching, a monitor finishing), so a consumer keeps a live view without bookkeeping of its own. Display-only and never journaled. Not forwarded from a child: a child's monitors are its own. */export interface MonitorsEvent {"monitors": MonitorSnapshot[]@@ -483,6 +498,7 @@ export type StreamEvent =| SubagentPlanEvent| SubagentEvent| NoticeEvent+ | CompactionEvent| MonitorsEvent| ParkedEvent| MessagesUpdatedEvent@@ -514,6 +530,7 @@ export interface EventByTag {"subagent_plan": SubagentPlanEvent"subagent": SubagentEvent"notice": NoticeEvent+ "compaction": CompactionEvent"monitors": MonitorsEvent"parked": ParkedEvent"messages_updated": MessagesUpdatedEventdiff --git a/packages/adk/src/generated/rpc-types.js b/packages/adk/src/generated/rpc-types.jsindex 4f1ea1740..4a2944a25 100644--- a/packages/adk/src/generated/rpc-types.js+++ b/packages/adk/src/generated/rpc-types.js@@ -20,6 +20,7 @@ export const EVENT_TAGS = Object.freeze(["subagent_plan","subagent","notice",+ "compaction","monitors","parked","messages_updated",diff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.jsonindex 5e850cef6..78f6f2c79 100644--- a/protocol/rpc-schema.json+++ b/protocol/rpc-schema.json@@ -481,7 +481,6 @@"events": {"$schema": "https://json-schema.org/draft/2020-12/schema","title": "StreamEvent",- "description": "`Deserialize` as well as `Serialize`: a consumer validates what it received\nagainst these shapes, and `JsonSchema` is what `jan cli agent schema`\npublishes them as -- a consumer generates its own types from\n`protocol/schema.json` rather than copying this declaration. The wire has to\nsurvive a round trip, not just a write, so `#[serde(tag = \"type\")]` keeps the\ntag on both sides.","oneOf": [{"description": "A streamed content delta from the model.",@@ -810,6 +809,35 @@"text"]},+ {+ "description": "The loop is summarizing part of the conversation to make room. Sent as\n`Started` before the summarizer call and `Finished` or `Failed` after\nit, so a consumer can show progress for what is otherwise a silent\nround trip. `reason` says which path asked. `messages` is how many were\nfolded into the summary, `None` except on `Finished`. Display-only and\nnever journaled; the compacted history itself arrives as\n`MessagesUpdated`.",+ "type": "object",+ "properties": {+ "phase": {+ "$ref": "#/$defs/CompactionPhase"+ },+ "reason": {+ "$ref": "#/$defs/CompactionReason"+ },+ "messages": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint",+ "minimum": 0+ },+ "type": {+ "type": "string",+ "const": "compaction"+ }+ },+ "required": [+ "type",+ "phase",+ "reason"+ ]+ },{"description": "The run's active file monitors, as a whole replacing the previous set.\nEmitted whenever the set changes (a `monitor` start or stop, a condition\nmatching, a monitor finishing), so a consumer keeps a live view without\nbookkeeping of its own. Display-only and never journaled. Not forwarded\nfrom a child: a child's monitors are its own.","type": "object",@@ -1213,6 +1241,43 @@"phase"]},+ "CompactionPhase": {+ "description": "`Deserialize` as well as `Serialize`: a consumer validates what it received\nagainst these shapes, and `JsonSchema` is what `jan cli agent schema`\npublishes them as -- a consumer generates its own types from\n`protocol/schema.json` rather than copying this declaration. The wire has to\nsurvive a round trip, not just a write, so `#[serde(tag = \"type\")]` keeps the\ntag on both sides.\nWhere a [`StreamEvent::Compaction`] is in its round trip.",+ "oneOf": [+ {+ "type": "string",+ "enum": [+ "started",+ "finished"+ ]+ },+ {+ "description": "The summarizer call failed or had nothing to fold; the history is\nunchanged.",+ "type": "string",+ "const": "failed"+ }+ ]+ },+ "CompactionReason": {+ "description": "Which path asked for a [`StreamEvent::Compaction`].",+ "oneOf": [+ {+ "description": "The request about to be sent was over the window's trigger.",+ "type": "string",+ "const": "preflight"+ },+ {+ "description": "The provider rejected a request as too long for its window.",+ "type": "string",+ "const": "context_overflow"+ },+ {+ "description": "The run used up its session token budget.",+ "type": "string",+ "const": "session_budget"+ }+ ]+ },"MonitorSnapshot": {"description": "Display-only view of one active monitor, for a status panel.","type": "object",diff --git a/protocol/schema.json b/protocol/schema.jsonindex 4469b9b28..f4df3f009 100644--- a/protocol/schema.json+++ b/protocol/schema.json@@ -39,7 +39,6 @@]},"StreamEvent": {- "description": "`Deserialize` as well as `Serialize`: a consumer validates what it received\nagainst these shapes, and `JsonSchema` is what `jan cli agent schema`\npublishes them as -- a consumer generates its own types from\n`protocol/schema.json` rather than copying this declaration. The wire has to\nsurvive a round trip, not just a write, so `#[serde(tag = \"type\")]` keeps the\ntag on both sides.","oneOf": [{"description": "A streamed content delta from the model.",@@ -368,6 +367,35 @@"text"]},+ {+ "description": "The loop is summarizing part of the conversation to make room. Sent as\n`Started` before the summarizer call and `Finished` or `Failed` after\nit, so a consumer can show progress for what is otherwise a silent\nround trip. `reason` says which path asked. `messages` is how many were\nfolded into the summary, `None` except on `Finished`. Display-only and\nnever journaled; the compacted history itself arrives as\n`MessagesUpdated`.",+ "type": "object",+ "properties": {+ "phase": {+ "$ref": "#/$defs/CompactionPhase"+ },+ "reason": {+ "$ref": "#/$defs/CompactionReason"+ },+ "messages": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint",+ "minimum": 0+ },+ "type": {+ "type": "string",+ "const": "compaction"+ }+ },+ "required": [+ "type",+ "phase",+ "reason"+ ]+ },{"description": "The run's active file monitors, as a whole replacing the previous set.\nEmitted whenever the set changes (a `monitor` start or stop, a condition\nmatching, a monitor finishing), so a consumer keeps a live view without\nbookkeeping of its own. Display-only and never journaled. Not forwarded\nfrom a child: a child's monitors are its own.","type": "object",@@ -771,6 +799,43 @@"phase"]},+ "CompactionPhase": {+ "description": "`Deserialize` as well as `Serialize`: a consumer validates what it received\nagainst these shapes, and `JsonSchema` is what `jan cli agent schema`\npublishes them as -- a consumer generates its own types from\n`protocol/schema.json` rather than copying this declaration. The wire has to\nsurvive a round trip, not just a write, so `#[serde(tag = \"type\")]` keeps the\ntag on both sides.\nWhere a [`StreamEvent::Compaction`] is in its round trip.",+ "oneOf": [+ {+ "type": "string",+ "enum": [+ "started",+ "finished"+ ]+ },+ {+ "description": "The summarizer call failed or had nothing to fold; the history is\nunchanged.",+ "type": "string",+ "const": "failed"+ }+ ]+ },+ "CompactionReason": {+ "description": "Which path asked for a [`StreamEvent::Compaction`].",+ "oneOf": [+ {+ "description": "The request about to be sent was over the window's trigger.",+ "type": "string",+ "const": "preflight"+ },+ {+ "description": "The provider rejected a request as too long for its window.",+ "type": "string",+ "const": "context_overflow"+ },+ {+ "description": "The run used up its session token budget.",+ "type": "string",+ "const": "session_budget"+ }+ ]+ },"MonitorSnapshot": {"description": "Display-only view of one active monitor, for a status panel.","type": "object",diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 3c51661bb..90b2dae5f 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -179,8 +179,9 @@ struct BudgetArgs {/// its subagents (0 = unbounded, the default)#[arg(long, value_name = "N")]max_turns: Option<u64>,- /// Advisory token ceiling overriding [budget].max_tokens: triggers- /// compaction and a note, but does not stop the run (0 = no ceiling)+ /// Advisory token ceiling overriding [budget].max_tokens (default: the+ /// model's context window): triggers compaction and a note, but does not+ /// stop the run (0 = no ceiling)#[arg(long, value_name = "N")]max_session_tokens: Option<u64>,/// Stop the run once it has spent this much in USD, overridingdiff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rsindex 3223d5003..0e8996f8b 100644--- a/src-tauri/src/core/agent/compaction.rs+++ b/src-tauri/src/core/agent/compaction.rs@@ -81,6 +81,10 @@ pub(crate) struct CompactionBudget {pub(crate) ratio: f64,/// An explicit `[agent].compaction_reserve_tokens`, which wins over `ratio`.pub(crate) reserve_tokens: Option<u64>,+ /// `context_window` is an explicit `[agent].context_window`, which holds+ /// for every model. Otherwise it was resolved for this run's model, and a+ /// subagent on a different model must re-resolve its own.+ pub(crate) window_pinned: bool,}impl CompactionBudget {@@ -88,6 +92,29 @@ impl CompactionBudget {pub(crate) fn trigger_tokens(&self) -> u64 {trigger_tokens(self.context_window, self.ratio, self.reserve_tokens)}++ /// This budget for a run on `model` under a dispatcher running+ /// `parent_model`, with `resolve` sizing a window for a model. Kept when+ /// the model is the same, the window was configured (which holds for+ /// every model), or `resolve` cannot size one; otherwise the window is+ /// the resolved one. Ratio and reserve are the project's and carry over.+ pub(crate) fn for_model(+ self,+ model: &str,+ parent_model: &str,+ resolve: impl FnOnce(&str) -> Option<u64>,+ ) -> Self {+ if model == parent_model || self.window_pinned {+ return self;+ }+ match resolve(model) {+ Some(context_window) => Self {+ context_window,+ ..self+ },+ None => self,+ }+ }}/// Rough token count for a whole request body (~4 chars per token), tool@@ -481,6 +508,30 @@ mod tests {use async_trait::async_trait;use std::sync::Mutex as StdMutex;+ /// A budget re-sized for another model takes that model's window and+ /// keeps the project's ratio; the same model, or a configured window,+ /// keeps the budget as it was.+ #[test]+ fn a_budget_for_another_model_takes_that_models_window() {+ let parent = CompactionBudget {+ context_window: 1_000_000,+ ratio: 0.7,+ reserve_tokens: None,+ window_pinned: false,+ };+ let child = parent.for_model("small", "big", |_| Some(200_000));+ assert_eq!(child.context_window, 200_000);+ assert_eq!(child.ratio, 0.7);+ assert_eq!(parent.for_model("big", "big", |_| Some(1)).context_window, 1_000_000);+ let pinned = CompactionBudget {+ window_pinned: true,+ ..parent+ };+ assert_eq!(pinned.for_model("small", "big", |_| Some(1)).context_window, 1_000_000);+ // A build that cannot size a window keeps the one it has.+ assert_eq!(parent.for_model("small", "big", |_| None).context_window, 1_000_000);+ }+/// The `PreCompact` call site: the hook runs, and it is told how much/// conversation is about to be summarized away -- the one fact a hook that/// archives a transcript needs.diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex d478980fb..b494c7717 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -22,6 +22,29 @@ pub const PROTOCOL_VERSION: u32 = 1;/// `protocol/schema.json` rather than copying this declaration. The wire has to/// survive a round trip, not just a write, so `#[serde(tag = "type")]` keeps the/// tag on both sides.+/// Where a [`StreamEvent::Compaction`] is in its round trip.+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum CompactionPhase {+ Started,+ Finished,+ /// The summarizer call failed or had nothing to fold; the history is+ /// unchanged.+ Failed,+}++/// Which path asked for a [`StreamEvent::Compaction`].+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum CompactionReason {+ /// The request about to be sent was over the window's trigger.+ Preflight,+ /// The provider rejected a request as too long for its window.+ ContextOverflow,+ /// The run used up its session token budget.+ SessionBudget,+}+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]#[serde(tag = "type", rename_all = "snake_case")]pub enum StreamEvent {@@ -149,6 +172,19 @@ pub enum StreamEvent {/// transcript reads in the order the model saw things. Display-only and/// transient, like notes: it is never journaled.Notice { text: String },+ /// The loop is summarizing part of the conversation to make room. Sent as+ /// `Started` before the summarizer call and `Finished` or `Failed` after+ /// it, so a consumer can show progress for what is otherwise a silent+ /// round trip. `reason` says which path asked. `messages` is how many were+ /// folded into the summary, `None` except on `Finished`. Display-only and+ /// never journaled; the compacted history itself arrives as+ /// `MessagesUpdated`.+ Compaction {+ phase: CompactionPhase,+ reason: CompactionReason,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ messages: Option<usize>,+ },/// The run's active file monitors, as a whole replacing the previous set./// Emitted whenever the set changes (a `monitor` start or stop, a condition/// matching, a monitor finishing), so a consumer keeps a live view without@@ -571,6 +607,14 @@ pub(crate) mod tests {text: "monitor matched".into(),},),+ (+ "Compaction",+ StreamEvent::Compaction {+ phase: CompactionPhase::Finished,+ reason: CompactionReason::SessionBudget,+ messages: Some(12),+ },+ ),("Monitors",StreamEvent::Monitors {@@ -733,6 +777,7 @@ pub(crate) mod tests {| StreamEvent::SubagentPlan { .. }| StreamEvent::Subagent { .. }| StreamEvent::Notice { .. }+ | StreamEvent::Compaction { .. }| StreamEvent::Monitors { .. }| StreamEvent::Parked| StreamEvent::MessagesUpdated { .. }diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 9edc1f001..502c90b09 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -16,7 +16,7 @@ use tauri_plugin_llamacpp::state::LlamacppState;use tokio::sync::{mpsc, Mutex};use crate::core::agent::context::ComposedPrompt;-use crate::core::agent::events::{StreamEvent, Usage};+use crate::core::agent::events::{CompactionPhase, CompactionReason, StreamEvent, Usage};use crate::core::agent::prompt::{Composer, Placement, PromptPolicy};use crate::core::agent::session::SessionBudget;use crate::core::agent::transcript::{Projection, Transcript};@@ -3954,21 +3954,45 @@ fn record_assistant_turn(transcript: &mut Transcript, message: &serde_json::Valu/// into `budget` here. A turn can compact several times (the preflight plus the/// overflow retries), and spend the budget never saw would make `/usage` and/// the money ceiling agree with each other while both undercounted.+///+/// Every in-run compaction goes through here, so this is where it is reported:+/// `Compaction { Started }` before the summarizer call and `Finished` or+/// `Failed` after it. A plan with nothing to drop sends nothing, since no+/// summarizer call was made.async fn compact(transcript: &mut Transcript,keep_recent: usize,model_id: &str,model: &dyn ModelInvoker,budget: &mut SessionBudget,+ events: &mpsc::UnboundedSender<StreamEvent>,+ reason: CompactionReason,) -> Result<Option<usize>, String> {let Some(plan) = transcript.compaction_plan(keep_recent) else {return Ok(None);};let summarized = plan.summarize.len();+ let report = |phase, messages| {+ let _ = events.send(StreamEvent::Compaction {+ phase,+ reason,+ messages,+ });+ };+ report(CompactionPhase::Started, None);let (summary, usage) =- crate::core::agent::compaction::summarize_span(&plan.summarize, model_id, model).await?;+ match crate::core::agent::compaction::summarize_span(&plan.summarize, model_id, model)+ .await+ {+ Ok(done) => done,+ Err(error) => {+ report(CompactionPhase::Failed, None);+ return Err(error);+ }+ };budget.record_side_request(&usage);transcript.record_compaction(summary, plan.covers);+ report(CompactionPhase::Finished, Some(summarized));Ok(Some(summarized))}@@ -4140,6 +4164,8 @@ async fn run_turn_cycle(model_id,model,budget,+ events,+ CompactionReason::Preflight,).await?{@@ -4156,16 +4182,9 @@ async fn run_turn_cycle(let _ = events.send(StreamEvent::MessagesUpdated {messages: client_history(&transcript, send_reasoning),});- // The one legitimate cache break in a session,- // and the only way the user can tell it apart- // from a stall: say it happened, and why.- let _ = events.send(StreamEvent::Notice {- text: format!(- "compacted {dropped} messages into a summary before sending \- ({estimate} tokens against a {} token budget)",- window.trigger_tokens()- ),- });+ // Announced by `compact` itself, which is+ // how the user tells this cache break apart+ // from a stall.continue;}}@@ -4187,9 +4206,17 @@ async fn run_turn_cycle(// Nothing safe left to drop: the request is smaller than the// window only in the provider's own maths.let dropped =- compact(&mut transcript, keep_recent, model_id, model, budget)- .await?- .ok_or(e)?;+ compact(+ &mut transcript,+ keep_recent,+ model_id,+ model,+ budget,+ events,+ CompactionReason::ContextOverflow,+ )+ .await?+ .ok_or(e)?;log::info!("agent: context overflow, compacted {dropped} messages into a \summary (attempt {})",@@ -4367,6 +4394,8 @@ async fn run_turn_cycle(model_id,model,budget,+ events,+ CompactionReason::SessionBudget,).await{@@ -5616,6 +5645,7 @@ mod tests {context_window: 1_000,ratio: 0.5,reserve_tokens: None,+ window_pinned: false,}),).await@@ -5650,15 +5680,21 @@ mod tests {}drop(tx);- let mut notices = Vec::new();+ let mut phases = Vec::new();while let Some(ev) = rx.recv().await {- if let StreamEvent::Notice { text } = ev {- notices.push(text);+ if let StreamEvent::Compaction {+ phase,+ reason: CompactionReason::Preflight,+ ..+ } = ev+ {+ phases.push(phase);}}- assert!(- notices.iter().any(|n| n.contains("before sending")),- "a prefix break the user did not ask for has to be announced: {notices:?}"+ assert_eq!(+ phases,+ [CompactionPhase::Started, CompactionPhase::Finished],+ "a prefix break the user did not ask for has to be announced");}@@ -5693,6 +5729,7 @@ mod tests {context_window: 128_000,ratio: crate::core::agent::compaction::DEFAULT_COMPACTION_RATIO,reserve_tokens: None,+ window_pinned: false,}),).await@@ -6985,7 +7022,16 @@ mod tests {));assert!(!budget.over_cost_ceiling(), "nothing spent yet");- let dropped = compact(&mut transcript, 4, "m", &model, &mut budget)+ let (tx, _rx) = mpsc::unbounded_channel();+ let dropped = compact(+ &mut transcript,+ 4,+ "m",+ &model,+ &mut budget,+ &tx,+ CompactionReason::Preflight,+ ).await.expect("the summarizer answered").expect("a long history has a span to compact");@@ -7058,7 +7104,9 @@ mod tests {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 });+ // The replayed prompt is the baseline; the 100-token reply is the spend.+ over_budget["usage"] =+ json!({ "prompt_tokens": 900, "completion_tokens": 100, "total_tokens": 1_000 });let done = json!({"choices": [{ "message": { "content": "all done" }, "finish_reason": "stop" }]});@@ -7169,7 +7217,9 @@ mod tests {let mut over_budget = json!({"choices": [{ "message": { "content": "all done" }, "finish_reason": "stop" }]});- over_budget["usage"] = json!({ "total_tokens": 100 });+ // The replayed prompt is the baseline; the 100-token reply is the spend.+ over_budget["usage"] =+ json!({ "prompt_tokens": 900, "completion_tokens": 100, "total_tokens": 1_000 });let summary = json!({"choices": [{ "message": { "content": "SUMMARY OF THE EARLIER WORK" } }]});@@ -7206,14 +7256,34 @@ mod tests {"one turn, plus the summarizer call compaction makes");+ let events: Vec<StreamEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();+ // The user is told: the TUI runs with logging off, so without an event+ // this compaction is invisible.+ let phases: Vec<CompactionPhase> = events+ .iter()+ .filter_map(|ev| match ev {+ StreamEvent::Compaction {+ phase,+ reason: CompactionReason::SessionBudget,+ ..+ } => Some(*phase),+ _ => None,+ })+ .collect();+ assert_eq!(+ phases,+ [CompactionPhase::Started, CompactionPhase::Finished],+ "the budget compaction is announced, start and end"+ );// 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 {+ let published = events+ .into_iter()+ .rev()+ .find_map(|ev| match ev {StreamEvent::MessagesUpdated { messages } => Some(messages),_ => None,})- .last().expect("a MessagesUpdated is published");assert!(published.len() < original_len,@@ -7305,7 +7375,7 @@ mod tests {#[tokio::test]async fn turn_cycle_compacts_and_retries_on_context_overflow() {- let (tx, _rx) = mpsc::unbounded_channel();+ let (tx, mut 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",@@ -7353,6 +7423,17 @@ mod tests {assert_eq!(result["choices"][0]["message"]["content"], "final");assert!(tool.calls.lock().unwrap().is_empty());+ assert!(+ std::iter::from_fn(|| rx.try_recv().ok()).any(|ev| matches!(+ ev,+ StreamEvent::Compaction {+ phase: CompactionPhase::Finished,+ reason: CompactionReason::ContextOverflow,+ messages: Some(_),+ }+ )),+ "the overflow compaction is announced"+ );}/// A strict endpoint rejects the DeepSeek `reasoning_content` extension@@ -7596,15 +7677,23 @@ mod tests {);drop(tx);let mut published = false;+ let mut failed = false;while let Ok(ev) = rx.try_recv() {- if let StreamEvent::MessagesUpdated { .. } = ev {- published = true;+ match ev {+ StreamEvent::MessagesUpdated { .. } => published = true,+ // The throbber a `Started` put up has to come down again.+ StreamEvent::Compaction {+ phase: CompactionPhase::Failed,+ ..+ } => failed = true,+ _ => {}}}assert!(!published,"no fabricated compacted history may be published");+ assert!(failed, "a summarizer failure ends the compaction as Failed");}#[tokio::test]diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex cb84cb2ea..ce0589be1 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -119,7 +119,8 @@ pub(crate) struct SkillsSection {/// `[budget]` — the only cap on how long a run may go. The agent takes as many/// turns as the task needs; `max_tokens` bounds the run's *marginal* token/// spend (see `SessionBudget`: replayed context is not recharged each turn).-/// Unset applies `DEFAULT_MAX_SESSION_TOKENS`; an explicit `0` disables the+/// Unset applies the model's context window, or `DEFAULT_MAX_SESSION_TOKENS`+/// when that is unknown; an explicit `0` disables the/// ceiling, leaving cancellation as the only guard.#[cfg(feature = "cli")]#[derive(Debug, Clone, Default, Deserialize)]@@ -263,7 +264,8 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]# New token spend across all turns (replayed context is not recharged each# turn). Advisory: crossing it compacts and files a note, it does not stop the-# run. Defaults to 128000 when unset; 0 disables the cap.+# run. Defaults to the model's context window when unset (128000 if the window+# is unknown); 0 disables the cap.[budget]# max_tokens = 128000# USD this run may spend before it stops -- unlike max_tokens, a hard bound.diff --git a/src-tauri/src/core/agent/session.rs b/src-tauri/src/core/agent/session.rsindex 0bf26c202..85cc2a3dd 100644--- a/src-tauri/src/core/agent/session.rs+++ b/src-tauri/src/core/agent/session.rs@@ -77,6 +77,8 @@ pub(crate) struct SessionBudget {spent_tokens: u64,last_total: u64,last_prompt: Option<u64>,+ /// The previous request's completion, which the next prompt replays.+ last_completion: u64,/// `None` leaves money unmetered, which is the default: without published/// prices there is no honest number to meter against.ceiling: Option<CostCeiling>,@@ -90,6 +92,7 @@ impl SessionBudget {spent_tokens: 0,last_total: 0,last_prompt: None,+ last_completion: 0,ceiling: None,spent_usd: 0.0,}@@ -103,37 +106,45 @@ impl SessionBudget {/// Fold a completion's usage into the running total, returning the new total.///- /// Counts new completion tokens and positive prompt-token growth rather than- /// replayed prompt history. The first request uses its reported total as the- /// baseline. When providers omit prompt or completion fields, the total-token- /// delta remains the fallback.+ /// Counts the new tokens a request added to the conversation, never the+ /// history it replays:+ ///+ /// - **Completion tokens**, always.+ /// - **Prompt growth beyond what is already counted.** The previous+ /// request's completion is resent inside this one's prompt, and was+ /// charged when it was generated, so growth is measured against+ /// `last_prompt + last_completion`. What remains is new input: tool+ /// results, a user message, a steering note.+ /// - **Nothing for a run's first prompt.** A run starts by replaying the+ /// thread it resumes; charging that would exhaust the budget on turn 1 of+ /// every run on a long thread. The first request sets the baseline.+ ///+ /// When a provider omits the prompt/completion split, the growth of+ /// `total_tokens` stands in (it already includes the new completion), and a+ /// first total-only request likewise only sets the baseline.pub(crate) fn record(&mut self, usage: &Option<Usage>) -> u64 {let Some(usage) = usage.as_ref() else {return self.spent_tokens;};- let delta = match usage.total_tokens {- Some(total) => {- let delta = match (- usage.prompt_tokens,- self.last_prompt,- usage.completion_tokens,- ) {- (Some(prompt), Some(last_prompt), Some(completion)) => {- completion.saturating_add(prompt.saturating_sub(last_prompt))- }- (Some(_), None, _) => total,- (_, Some(_), Some(completion)) => {- completion.max(total.saturating_sub(self.last_total))- }- _ => total.saturating_sub(self.last_total),- };- self.last_total = total;- delta+ let first = self.last_prompt.is_none() && self.last_total == 0;+ let delta = match (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) {+ (Some(prompt), Some(completion), _) => {+ let already = self.last_prompt.map(|p| p.saturating_add(self.last_completion));+ let growth = already.map_or(0, |already| prompt.saturating_sub(already));+ completion.saturating_add(growth)+ }+ (_, completion, Some(total)) => {+ let growth = if first { 0 } else { total.saturating_sub(self.last_total) };+ completion.map_or(growth, |c| c.max(growth))}- None => usage.completion_tokens.unwrap_or(0),+ (_, Some(completion), None) => completion,+ _ => 0,};-+ if let Some(total) = usage.total_tokens {+ self.last_total = total;+ }+ self.last_completion = usage.completion_tokens.unwrap_or(0);self.last_prompt = usage.prompt_tokens.or(self.last_prompt);self.spent_tokens = self.spent_tokens.saturating_add(delta);// Money is charged on the request as billed -- the whole prompt, every@@ -234,55 +245,78 @@ mod tests {})}+ /// A run starts by replaying the thread it resumes. That history was+ /// charged by the runs that wrote it, so a resumed 500K thread must not+ /// exhaust a budget on its first request -- the bug that compacted long+ /// threads at the start of every run.+ #[test]+ fn a_runs_first_prompt_is_the_baseline_not_spend() {+ let mut b = SessionBudget::new(Some(10_000));+ b.record(&usage_with_parts(500_000, 1_000, 501_000));+ assert_eq!(b.spent(), 1_000, "only the new completion counts");+ assert!(!b.exhausted());+ }++ /// A reply is charged once, when generated. The next prompt resends it,+ /// so prompt growth is measured past it: only the new input (a tool+ /// result here) counts, not the reply a second time.+ #[test]+ fn a_replayed_completion_is_not_charged_twice() {+ let mut b = SessionBudget::new(None);+ b.record(&usage_with_parts(10_000, 2_000, 12_000));+ // Prompt = 10K history + 2K reply + 300 tool result.+ b.record(&usage_with_parts(12_300, 500, 12_800));+ assert_eq!(b.spent(), 2_000 + 300 + 500);+ }+#[test]fn compaction_still_charges_completion_tokens() {- let mut b = SessionBudget::new(Some(1_100));+ let mut b = SessionBudget::new(Some(200));b.record(&usage_with_parts(900, 100, 1_000));assert!(!b.exhausted());// The compacted prompt is smaller, but this request still consumed// another 100 completion tokens and must exhaust the session budget.b.record(&usage_with_parts(400, 100, 500));- assert_eq!(b.spent(), 1_100);+ assert_eq!(b.spent(), 200);assert!(b.exhausted());}#[test]fn no_ceiling_is_never_exhausted() {let mut b = SessionBudget::new(None);- assert_eq!(b.record(&usage(Some(1_000_000))), 1_000_000);+ b.record(&usage_with_parts(0, 1_000_000, 1_000_000));+ assert_eq!(b.spent(), 1_000_000);assert!(!b.exhausted());}+ /// A provider that reports only `total_tokens`: its growth stands in for+ /// spend, and the first total is the baseline like a first prompt is.#[test]- fn accumulates_marginal_spend_and_exhausts_at_or_over_ceiling() {+ fn total_only_usage_accumulates_growth_and_exhausts_at_the_ceiling() {let mut b = SessionBudget::new(Some(100));- // First request counts its full total, since there is no baseline yet.b.record(&usage(Some(60)));- assert!(!b.exhausted());- // Context grew by only a little between requests, so only the marginal- // increase counts — the replayed prior history must not be double-charged.+ assert_eq!(b.spent(), 0, "the first total is the replayed baseline");b.record(&usage(Some(64)));- assert_eq!(b.spent(), 64);+ assert_eq!(b.spent(), 4);assert!(!b.exhausted());- // A big single-request increase (e.g. a large new completion) trips it.b.record(&usage(Some(200)));- assert_eq!(b.spent(), 200);+ assert_eq!(b.spent(), 140);assert!(b.exhausted());}#[test]fn compaction_does_not_refund_or_double_charge_spend() {- let mut b = SessionBudget::new(Some(100));+ let mut b = SessionBudget::new(Some(40));b.record(&usage(Some(60)));b.record(&usage(Some(90)));- assert_eq!(b.spent(), 90);+ assert_eq!(b.spent(), 30);// Compaction shrinks the replay below the last total; must not refund, and// later small growth is counted from the compacted baseline.b.record(&usage(Some(70)));- assert_eq!(b.spent(), 90);+ assert_eq!(b.spent(), 30);b.record(&usage(Some(80)));- assert_eq!(b.spent(), 100);+ assert_eq!(b.spent(), 40);assert!(b.exhausted());}@@ -320,11 +354,11 @@ mod tests {(spent - (30_300.0 * 1e-6 + 300.0 * 10e-6)).abs() < 1e-9,"every request pays for its whole prompt: {spent}");- // Marginal token spend over the same three turns is a third of the 30K- // tokens actually billed: the baseline plus 100 new completion and 100- // prompt-growth tokens a turn. The two ceilings measure different+ // Marginal token spend over the same three turns is only the 300 new+ // completion tokens (each next prompt grew by exactly the reply it+ // replays) against 30K billed. The two ceilings measure different// things, which is why money could not simply be priced off `spent()`.- assert_eq!(b.spent(), 10_500);+ assert_eq!(b.spent(), 300);}/// An unmetered run reports `None`, not `0.0`. "This run tracks no money"@@ -373,10 +407,11 @@ mod tests {// the conversation's own last prompt (100K), not the summarizer's 20K:// a side request replays a different prompt entirely, so letting it set// that baseline would make the next turn's growth arbitrary.- b.record(&usage_with_parts(100_100, 200, 100_300));+ // 100K history + the 10K reply + 100 new input tokens.+ b.record(&usage_with_parts(110_100, 200, 110_300));assert_eq!(b.spent(),- 110_000 + 500 + 300,+ 10_000 + 500 + 100 + 200,"the turn after a side request grows by 100 prompt + 200 completion");}diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 343cd749a..ed6f5dfa2 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1295,6 +1295,34 @@ fn child_model(resolved: &ResolvedDispatch, parent: &ParentRun) -> String {.unwrap_or_else(|| parent.model.clone())}+/// The context window `model` resolves to, the way the CLI resolves a run's+/// (provider listing first, then the catalog). `None` for a model neither+/// knows: the 128K fallback is a guess, and the parent's window is a better+/// one than that for a child the catalog cannot place.+#[cfg(feature = "cli")]+fn model_window(+ model: &str,+ provider_configs: &std::collections::HashMap<String, crate::core::state::ProviderConfig>,+) -> Option<u64> {+ use crate::core::cli::model_capabilities::{+ reported_window, resolve_context_window, ContextWindowSource,+ };+ let provider = crate::core::agent::upstream::pick_provider_for_model(model, provider_configs);+ let resolved =+ resolve_context_window(model, None, reported_window(provider.as_deref(), model));+ (resolved.source != ContextWindowSource::Fallback).then_some(resolved.tokens)+}++/// No model catalog outside the `cli` build, so no window can be sized here;+/// a child keeps the budget it inherited.+#[cfg(not(feature = "cli"))]+fn model_window(+ _model: &str,+ _provider_configs: &std::collections::HashMap<String, crate::core::state::ProviderConfig>,+) -> Option<u64> {+ None+}+/// The per-token rates a model is published at, or `None` when it cannot be/// priced at all.///@@ -1462,6 +1490,15 @@ async fn run_subagent(child_args.run_id = Some(run_id.clone());let body = child_body(&resolved, &description, &parent);+ // The parent's compaction budget describes the parent's model. A child on+ // another model compacts against its own window, or a 200K child of a 1M+ // parent would only compact after the provider rejected it.+ if let Some(budget) = child_args.compaction {+ let pc = child_args.provider_configs.lock().await;+ let model = child_model(&resolved, &parent);+ child_args.compaction =+ Some(budget.for_model(&model, &parent.model, |m| model_window(m, &pc)));+ }let _ = events.send(StreamEvent::SubagentStart {run_id: run_id.clone(),@@ -2453,6 +2490,43 @@ mod tests {static COUNTER: AtomicU32 = AtomicU32::new(0);+ /// A child on another model compacts against its own window, not the+ /// parent's: a 200K child of a 1M parent would otherwise sail past its+ /// window. Same model, or a configured window, keeps the parent's budget.+ #[cfg(feature = "cli")]+ #[test]+ fn a_child_on_another_model_compacts_against_its_own_window() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let parent = crate::core::agent::compaction::CompactionBudget {+ context_window: 1_000_000,+ ratio: 0.7,+ reserve_tokens: None,+ window_pinned: false,+ };+ let pc = std::collections::HashMap::new();+ let window = |m: &str| model_window(m, &pc);+ let child = parent.for_model("claude-sonnet-4-5", "claude-sonnet-4-6", window);+ assert_eq!(child.context_window, 200_000);+ assert_eq!(child.ratio, 0.7, "the project's ratio carries over");++ let same = parent.for_model("claude-sonnet-4-6", "claude-sonnet-4-6", window);+ assert_eq!(same.context_window, 1_000_000);++ let pinned = crate::core::agent::compaction::CompactionBudget {+ window_pinned: true,+ ..parent+ };+ let kept = pinned.for_model("claude-sonnet-4-5", "claude-sonnet-4-6", window);+ assert_eq!(kept.context_window, 1_000_000, "a configured window holds");++ let unknown = parent.for_model("some-unlisted-model", "claude-sonnet-4-6", window);+ assert_eq!(+ unknown.context_window, 1_000_000,+ "an unknown child model keeps the parent's window, not the 128K guess"+ );+ });+ }+fn unique_root(tag: &str) -> PathBuf {let n = COUNTER.fetch_add(1, Ordering::SeqCst);let root = std::env::temp_dir().join(format!(diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 96af108bb..8759fb441 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -14,7 +14,7 @@ pub mod login;pub mod mcp;/// `jan mcp serve`: the other direction, Jan's toolset served over MCP.pub mod mcp_serve;-mod model_capabilities;+pub(crate) mod model_capabilities;pub mod model_catalog;mod path_refs;/// `jan cli agent schema`: the protocol's JSON Schema, generated from the types.@@ -764,10 +764,9 @@ use std::io::Write as _;use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use tokio::sync::{mpsc, Mutex};-/// Token-spend ceiling for one agent run when `agent.toml [budget].max_tokens`-/// is unset. `0` disables the ceiling entirely. Counted marginally by-/// `SessionBudget`, so it tracks real new spend, not the context replayed on-/// every turn.+/// Token-spend ceiling for one agent run when neither `--max-session-tokens` nor+/// `agent.toml [budget].max_tokens` is set and the model's context window is+/// unknown. `0` disables the ceiling entirely.////// Advisory, not a bound: crossing it compacts the history and records a note,/// then the run carries on (see `body_session_budget`). `--max-turns` and@@ -775,28 +774,68 @@ use tokio::sync::{mpsc, Mutex};const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;/// Where the session token ceiling in effect came from, so `agent status` can-/// say which source won.-///-/// `agent status` takes no budget flag and so always passes `None`, making-/// `"flag"` unreachable from the binary today. It is kept because the argument-/// mirrors `resolve_session_budget` below: a status surface that does accept-/// the flag (or any caller reporting an in-flight run's ceiling) would-/// otherwise report `agent.toml` for a value the flag had overridden.-fn session_budget_source(flag: Option<u64>, configured: Option<u64>) -> &'static str {- match (flag, configured) {- (Some(_), _) => "flag",- (None, Some(_)) => "agent.toml",- (None, None) => "default",+/// say which source won and the TUI knows whether a model switch moves it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum SessionBudgetSource {+ /// `--max-session-tokens`, per invocation; outranks the file.+ Flag,+ /// `agent.toml [budget].max_tokens`.+ Config,+ /// The resolved context window of the model serving the run.+ ContextWindow,+ /// `DEFAULT_MAX_SESSION_TOKENS`: no window was known.+ Default,+}++impl SessionBudgetSource {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ SessionBudgetSource::Flag => "flag",+ SessionBudgetSource::Config => "agent.toml",+ SessionBudgetSource::ContextWindow => "context_window",+ SessionBudgetSource::Default => "default",+ }+ }++ /// Whether the ceiling follows the model: only an unpinned, unconfigured+ /// ceiling is re-derived when the model or its window changes.+ pub(crate) fn follows_window(self) -> bool {+ matches!(+ self,+ SessionBudgetSource::ContextWindow | SessionBudgetSource::Default+ )}}/// Session token ceiling for one run. Precedence is the per-invocation/// `--max-session-tokens` flag, then `agent.toml [budget].max_tokens`, then-/// `DEFAULT_MAX_SESSION_TOKENS` - the same flag/config/default shape the-/// sandbox setting resolves with. `0` from either source means unbounded and is-/// carried through as-is (see `body_session_budget`).-pub(crate) fn resolve_session_budget(flag: Option<u64>, configured: Option<u64>) -> u64 {- flag.or(configured).unwrap_or(DEFAULT_MAX_SESSION_TOKENS)+/// the model's context window, then `DEFAULT_MAX_SESSION_TOKENS`. `0` from+/// either explicit source means unbounded and is carried through as-is (see+/// `body_session_budget`).+///+/// The window is the default because the ceiling compacts when crossed: a+/// fixed 128K would compact a 1M-window model at an eighth of its capacity,+/// long before the window-based trigger would.+pub(crate) fn resolve_session_budget(+ flag: Option<u64>,+ configured: Option<u64>,+ context_window: Option<u64>,+) -> (u64, SessionBudgetSource) {+ match (flag, configured, context_window.filter(|w| *w > 0)) {+ (Some(v), _, _) => (v, SessionBudgetSource::Flag),+ (None, Some(v), _) => (v, SessionBudgetSource::Config),+ (None, None, Some(w)) => (w, SessionBudgetSource::ContextWindow),+ (None, None, None) => (DEFAULT_MAX_SESSION_TOKENS, SessionBudgetSource::Default),+ }+}++/// The context window to size a default session budget by: `None` for the+/// conservative fallback, which is a guess and not the model's window.+pub(crate) fn known_window(+ resolved: crate::core::cli::model_capabilities::ResolvedContextWindow,+) -> Option<u64> {+ (resolved.source != crate::core::cli::model_capabilities::ContextWindowSource::Fallback)+ .then_some(resolved.tokens)}/// The compaction ratio for `model`. A provider that names its own ratio wins@@ -969,6 +1008,18 @@ pub fn cli_agent_status(}).collect();+ // The default ceiling follows the configured model's window, so status+ // resolves that window the way a run would.+ let status_window = cfg.agent.model.as_deref().and_then(|model| {+ let provider = crate::core::cli::providers::provider_for_model(model, &provider_configs);+ known_window(crate::core::cli::model_capabilities::resolve_context_window(+ model,+ cfg.agent.context_window,+ crate::core::cli::model_capabilities::reported_window(provider.as_deref(), model),+ ))+ });+ let session_budget = resolve_session_budget(None, cfg.budget.max_tokens, status_window);+Ok(serde_json::json!({"project": project_root.to_string_lossy(),"data_folder": resolve_jan_data_folder().to_string_lossy(),@@ -976,8 +1027,8 @@ pub fn cli_agent_status(// The effective ceiling with the config files resolved. A// `--max-session-tokens` flag is per-invocation and so, like// `--sandbox` below, cannot be reflected in a config dump.- "max_session_tokens": resolve_session_budget(None, cfg.budget.max_tokens),- "max_session_tokens_source": session_budget_source(None, cfg.budget.max_tokens),+ "max_session_tokens": session_budget.0,+ "max_session_tokens_source": session_budget.1.as_str(),// The configured money ceiling, or null when the project sets none.// Reported unpriced: whether it can actually be enforced depends on the// model a run resolves, which a config dump has not resolved.@@ -1281,15 +1332,17 @@ pub(crate) struct SessionLimits {/// Per-request output cap forwarded to the model as OpenAI `max_tokens`./// `None` omits the field (model default).pub max_tokens: Option<u64>,- /// `--max-session-tokens`, else `[budget].max_tokens`, else the default:- /// marginal token-spend ceiling for one run. `0` is no ceiling.+ /// `--max-session-tokens`, else `[budget].max_tokens`, else the model's+ /// context window, else the default: marginal token-spend ceiling for one+ /// run. `0` is no ceiling.////// Advisory: crossing it triggers compaction and a recorded note, it does/// not end the run. `max_turns` is the hard bound.pub max_session_tokens: u64,- /// Whether `--max-session-tokens` set `max_session_tokens`. A flag outranks- /// `[budget].max_tokens`, so `/reload config` must leave a pinned value alone.- pub max_session_tokens_pinned: bool,+ /// Which source set `max_session_tokens`. A flag outranks+ /// `[budget].max_tokens`, so `/reload config` must leave a pinned value+ /// alone; a window-derived one follows a model switch.+ pub max_session_tokens_source: SessionBudgetSource,/// `--max-turns`: hard cap on agentic turns for this run, and the only/// setting that terminates one. `None` omits the field from the request/// body, which the engine reads as unbounded; `0` means unbounded too (see@@ -1420,8 +1473,8 @@ pub struct SessionFlags {/// is unbounded as well.pub max_turns: Option<u64>,/// `--max-session-tokens`: advisory session token ceiling, outranking- /// `[budget].max_tokens`. `None` (not passed) defers to that, then to- /// `DEFAULT_MAX_SESSION_TOKENS`.+ /// `[budget].max_tokens`. `None` (not passed) defers to that, then to the+ /// model's context window, then to `DEFAULT_MAX_SESSION_TOKENS`.pub max_session_tokens: Option<u64>,/// `--max-budget-usd`: hard USD ceiling for the run, outranking/// `[budget].max_usd`. `None` (not passed) defers to that, then leaves the@@ -1723,8 +1776,15 @@ fn prepare_agent_session(context_window: resolved_window.tokens,ratio: compaction_ratio,reserve_tokens: cfg.agent.compaction_reserve_tokens,+ window_pinned: cfg.agent.context_window.is_some(),});+ let session_budget = resolve_session_budget(+ flags.max_session_tokens,+ cfg.budget.max_tokens,+ known_window(resolved_window),+ );+// Resolved before the session is built: a run that asked for a ceiling it// cannot be priced against is refused here, before any paid request.// Priced against `serving_provider`, the provider that will actually be@@ -1749,11 +1809,8 @@ fn prepare_agent_session(compaction_ratio,compaction_reserve_tokens: cfg.agent.compaction_reserve_tokens,max_tokens: cfg.agent.max_tokens,- max_session_tokens: resolve_session_budget(- flags.max_session_tokens,- cfg.budget.max_tokens,- ),- max_session_tokens_pinned: flags.max_session_tokens.is_some(),+ max_session_tokens: session_budget.0,+ max_session_tokens_source: session_budget.1,max_turns: flags.max_turns,cost_ceiling,},@@ -2779,6 +2836,21 @@ pub fn agent_dir_for(project_root: &std::path::Path) -> PathBuf {/// Render one `StreamEvent` for the terminal. Content tokens go to stdout so a/// run can be piped; progress/diagnostics go to stderr. `PermissionRequest` is/// resolved via the terminal (deny when non-interactive).+/// One headless line for a compaction event: `started (session_budget)`.+fn describe_compaction(+ phase: crate::core::agent::events::CompactionPhase,+ reason: crate::core::agent::events::CompactionReason,+ messages: Option<usize>,+) -> String {+ let wire = |v: serde_json::Value| v.as_str().unwrap_or_default().to_string();+ let phase = wire(serde_json::json!(phase));+ let reason = wire(serde_json::json!(reason));+ match messages {+ Some(n) => format!("{phase} ({reason}): {n} messages summarized"),+ None => format!("{phase} ({reason})"),+ }+}+async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: bool) {if crate::core::cli::auth::account::take_claude_alias_engaged() {eprintln!(@@ -2855,20 +2927,35 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: booStreamEvent::Notice { text } => {eprintln!("\x1b[2m[notice] {text}\x1b[0m")}+ StreamEvent::Compaction {+ phase,+ reason,+ messages,+ } => eprintln!("\x1b[2m[compaction] {}\x1b[0m", describe_compaction(phase, reason, messages)),// The snapshot backs a live panel the headless printer has no room// for; `Notice` already reports each match as it lands.StreamEvent::Monitors { .. } => {}StreamEvent::Parked => {eprintln!("\x1b[2m[parked] waiting on background work\x1b[0m")}- StreamEvent::Subagent { name, event, .. } => {- if let StreamEvent::ToolCall { name: tool, args, .. } = *event {- eprintln!(- "\x1b[2m[subagent:{name}] {}\x1b[0m",- crate::core::agent::events::describe_tool_call(&tool, &args)- );+ StreamEvent::Subagent { name, event, .. } => match *event {+ StreamEvent::ToolCall { name: tool, args, .. } => eprintln!(+ "\x1b[2m[subagent:{name}] {}\x1b[0m",+ crate::core::agent::events::describe_tool_call(&tool, &args)+ ),+ StreamEvent::Notice { text } => {+ eprintln!("\x1b[2m[subagent:{name}] [notice] {text}\x1b[0m")}- }+ StreamEvent::Compaction {+ phase,+ reason,+ messages,+ } => eprintln!(+ "\x1b[2m[subagent:{name}] [compaction] {}\x1b[0m",+ describe_compaction(phase, reason, messages)+ ),+ _ => {}+ },StreamEvent::Done { stop_reason, usage } => {let tokens = usage.and_then(|u| u.total_tokens).unwrap_or(0);eprintln!("\n\x1b[2m[done] stop_reason={stop_reason} tokens={tokens}\x1b[0m");@@ -4375,23 +4462,55 @@ mod tests {}/// `--max-session-tokens` outranks `[budget].max_tokens`, which outranks- /// the built-in default; `0` from either source survives as the unbounded- /// marker `body_session_budget` expects rather than falling through.+ /// the model's window, which outranks the built-in default; `0` from+ /// either explicit source survives as the unbounded marker+ /// `body_session_budget` expects rather than falling through.#[test]- fn session_budget_precedence_is_flag_then_config_then_default() {+ fn session_budget_precedence_is_flag_then_config_then_window_then_default() {+ use SessionBudgetSource::*;assert_eq!(- resolve_session_budget(None, None),- DEFAULT_MAX_SESSION_TOKENS+ resolve_session_budget(None, None, None),+ (DEFAULT_MAX_SESSION_TOKENS, Default)+ );+ assert_eq!(+ resolve_session_budget(None, None, Some(1_000_000)),+ (1_000_000, ContextWindow)+ );+ assert_eq!(+ resolve_session_budget(None, None, Some(0)),+ (DEFAULT_MAX_SESSION_TOKENS, Default)+ );+ let w = Some(1_000_000);+ assert_eq!(resolve_session_budget(None, Some(50_000), w), (50_000, Config));+ assert_eq!(resolve_session_budget(Some(20_000), Some(50_000), None), (20_000, Flag));+ assert_eq!(resolve_session_budget(Some(20_000), None, w), (20_000, Flag));+ assert_eq!(resolve_session_budget(Some(0), Some(50_000), None), (0, Flag));+ assert_eq!(resolve_session_budget(None, Some(0), w), (0, Config));++ assert_eq!(Default.as_str(), "default");+ assert_eq!(Config.as_str(), "agent.toml");+ assert_eq!(Flag.as_str(), "flag");+ assert_eq!(ContextWindow.as_str(), "context_window");+ }++ /// A 1M-window model must not be compacted at 128K by the session budget:+ /// the budget defaults to the window. The fallback window is a guess, not+ /// the model's, so it leaves the budget on the built-in default.+ #[test]+ fn default_session_budget_follows_a_known_window_only() {+ use crate::core::cli::model_capabilities::resolve_context_window;+ let big = resolve_context_window("claude-sonnet-4-6", None, None);+ assert_eq!(known_window(big), Some(1_000_000));+ assert_eq!(+ resolve_session_budget(None, None, known_window(big)).0,+ 1_000_000+ );+ let unknown = resolve_context_window("private-gateway-model", None, None);+ assert_eq!(known_window(unknown), None);+ assert_eq!(+ resolve_session_budget(None, None, known_window(unknown)),+ (DEFAULT_MAX_SESSION_TOKENS, SessionBudgetSource::Default));- assert_eq!(resolve_session_budget(None, Some(50_000)), 50_000);- assert_eq!(resolve_session_budget(Some(20_000), Some(50_000)), 20_000);- assert_eq!(resolve_session_budget(Some(20_000), None), 20_000);- assert_eq!(resolve_session_budget(Some(0), Some(50_000)), 0);- assert_eq!(resolve_session_budget(None, Some(0)), 0);-- assert_eq!(session_budget_source(None, None), "default");- assert_eq!(session_budget_source(None, Some(50_000)), "agent.toml");- assert_eq!(session_budget_source(Some(0), Some(50_000)), "flag");}/// The money ceiling resolves flag > config > none, and a run that asks@@ -4454,7 +4573,7 @@ mod tests {compaction_reserve_tokens: None,max_tokens: None,max_session_tokens,- max_session_tokens_pinned: false,+ max_session_tokens_source: SessionBudgetSource::Default,max_turns,cost_ceiling: None,}diff --git a/src-tauri/src/core/cli/model_capabilities.rs b/src-tauri/src/core/cli/model_capabilities.rsindex f992447f8..8514fbb4c 100644--- a/src-tauri/src/core/cli/model_capabilities.rs+++ b/src-tauri/src/core/cli/model_capabilities.rs@@ -58,19 +58,32 @@ fn strip_provider_qualifier(mut model_id: &str) -> &str {model_id}+/// The `(major, minor)` generation at the front of a Claude version suffix:+/// `4-6` -> (4, 6), `5` -> (5, 0), `4-5-20250929` -> (4, 5). A trailing date+/// snapshot is not a minor version, so an 8-digit segment ends the parse.+fn claude_generation(version: &str) -> (u32, u32) {+ let mut parts = version.split('-').map(|p| {+ if p.len() >= 8 { None } else { p.parse::<u32>().ok() }+ });+ let major = parts.next().flatten().unwrap_or(0);+ let minor = parts.next().flatten().unwrap_or(0);+ (major, minor)+}+/// Look up the catalog window for a bare model id (provider qualifier already/// stripped). `None` means the id matches no known family -> fallback.fn catalog_window(model_id: &str) -> Option<u64> {- // Claude family: the two newest releases get 1M, everything else claude 200K.- if model_id.starts_with("claude-") {- let is_new = ["haiku", "sonnet", "opus"]- .iter()- .any(|family| {- let prefix = format!("claude-{family}-4-6");- let prefix7 = format!("claude-{family}-4-7");- model_id.starts_with(&prefix) || model_id.starts_with(&prefix7)+ // Claude family, per Anthropic's models overview: Sonnet 4.6, Opus 4.6+ // and every later Opus/Sonnet generation, and the Fable and Mythos lines,+ // are 1M by default (no beta header). Everything else, Haiku included, is+ // 200K. Matched by generation so a new point release is not 200K by default.+ if let Some(rest) = model_id.strip_prefix("claude-") {+ let one_million = ["fable-", "mythos-"].iter().any(|f| rest.starts_with(f))+ || ["opus-", "sonnet-"].iter().any(|family| {+ rest.strip_prefix(family)+ .is_some_and(|version| claude_generation(version) >= (4, 6))});- return Some(if is_new { 1_000_000 } else { 200_000 });+ return Some(if one_million { 1_000_000 } else { 200_000 });}// Codex variants are matched before the base gpt-5.x rows they contain.@@ -86,6 +99,10 @@ fn catalog_window(model_id: &str) -> Option<u64> {if model_id == "gpt-5.4" || model_id == "gpt-5.5" {return Some(1_050_000);}+ // gpt-4.1 and its mini/nano variants (and their dated snapshots).+ if model_id.starts_with("gpt-4.1") {+ return Some(1_047_576);+ }if model_id == "gpt-4" || model_id == "gpt-4o" || model_id == "gpt-4o-mini" {return Some(128_000);}@@ -176,6 +193,14 @@ mod tests {resolve_context_window("gpt-5.2", None, None).tokens,400_000);+ assert_eq!(+ resolve_context_window("gpt-4.1", None, None).tokens,+ 1_047_576+ );+ assert_eq!(+ resolve_context_window("gpt-4.1-mini-2025-04-14", None, None).tokens,+ 1_047_576+ );assert_eq!(resolve_context_window("gpt-5.2-codex", None, None).tokens,272_000@@ -186,6 +211,37 @@ mod tests {);}+ /// Anthropic's current lineup: Sonnet/Opus 4.6 and later, Fable and Mythos+ /// are 1M by default; older generations and every Haiku are 200K. A dated+ /// snapshot suffix must not read as a minor version.+ #[test]+ fn claude_windows_follow_the_generation() {+ let window = |m: &str| resolve_context_window(m, None, None).tokens;+ for m in [+ "claude-sonnet-4-6",+ "claude-opus-4-7",+ "claude-opus-4-8",+ "claude-opus-5",+ "claude-sonnet-5",+ "claude-fable-5-1",+ "claude-mythos-5",+ ] {+ assert_eq!(window(m), 1_000_000, "{m}");+ }+ for m in [+ "claude-sonnet-4-5",+ "claude-sonnet-4-5-20250929",+ "claude-sonnet-4-20250514",+ "claude-opus-4-1",+ "claude-opus-4-5",+ "claude-haiku-4-5",+ "claude-haiku-4-6",+ "claude-3-7-sonnet-latest",+ ] {+ assert_eq!(window(m), 200_000, "{m}");+ }+ }+#[test]fn provider_qualifier_does_not_change_resolution() {let bare = resolve_context_window("claude-sonnet-4-6", None, None);@@ -241,6 +297,26 @@ mod tests {);}+ /// Tokamak reports each model's window in its `/models` listing, and that+ /// figure is authoritative: the Claude catalog rows only fill in when the+ /// listing said nothing, so a catalog change can never override it.+ #[test]+ fn tokamak_reported_window_beats_the_claude_catalog() {+ for (model, reported) in [+ ("tokamak/anthropic/claude-opus-5", 400_000),+ ("tokamak/anthropic/claude-sonnet-4-5", 1_000_000),+ ] {+ assert_eq!(+ resolve_context_window(model, None, Some(reported)),+ ResolvedContextWindow {+ tokens: reported,+ source: ContextWindowSource::Provider,+ },+ "{model}"+ );+ }+ }+#[test]fn non_catalog_provider_qualifier_is_not_stripped() {// A provider Jan doesn't ship keeps its qualifier: the id must stilldiff --git a/src-tauri/src/core/cli/model_catalog.rs b/src-tauri/src/core/cli/model_catalog.rsindex 7008889cc..8072c0129 100644--- a/src-tauri/src/core/cli/model_catalog.rs+++ b/src-tauri/src/core/cli/model_catalog.rs@@ -258,6 +258,8 @@ pub fn parse_listing(value: &serde_json::Value) -> BTreeMap<String, ModelInfo> {let entries = value.get("data").and_then(|d| d.as_array())+ // Gemini's native Models API: `{"models": [{"name": "models/<id>"}]}`.+ .or_else(|| value.get("models").and_then(|m| m.as_array())).or_else(|| value.as_array());let Some(entries) = entries else {return BTreeMap::new();@@ -268,6 +270,14 @@ pub fn parse_listing(value: &serde_json::Value) -> BTreeMap<String, ModelInfo> {let id = entry.get("id").and_then(|id| id.as_str())+ .or_else(|| {+ // Requests name the bare id, so the `models/` resource+ // prefix is dropped to key the entry the way it is looked up.+ entry+ .get("name")+ .and_then(|n| n.as_str())+ .map(|n| n.strip_prefix("models/").unwrap_or(n))+ }).map(str::trim).filter(|id| !id.is_empty())?;let info = model_info(entry);@@ -290,6 +300,10 @@ fn model_info(entry: &serde_json::Value) -> ModelInfo {context_length: entry.get("context_length").or_else(|| entry.get("context_window"))+ // Anthropic's own Models API.+ .or_else(|| entry.get("max_input_tokens"))+ // Gemini's.+ .or_else(|| entry.get("inputTokenLimit")).and_then(number).map(|v| v as u64),max_output_tokens: entry@@ -364,6 +378,31 @@ mod tests {assert!(parse_listing(&json!({"unexpected": 1})).is_empty());}+ /// Anthropic's Models API names the window `max_input_tokens`; without it+ /// a direct Anthropic route never learns a window from its listing.+ #[test]+ fn anthropic_max_input_tokens_is_read_as_the_window() {+ let parsed = parse_listing(&json!({"data": [+ {"id": "claude-opus-5", "type": "model", "max_input_tokens": 1000000, "max_tokens": 128000},+ ]}));+ assert_eq!(parsed["claude-opus-5"].context_length, Some(1_000_000));+ }++ /// Gemini's Models API lists `models/<id>` names with `inputTokenLimit`;+ /// the entry is keyed by the bare id a request names.+ #[test]+ fn gemini_input_token_limit_is_read_as_the_window() {+ let parsed = parse_listing(&json!({"models": [+ {"name": "models/gemini-2.5-pro", "inputTokenLimit": 1048576, "outputTokenLimit": 65536},+ ]}));+ assert_eq!(parsed["gemini-2.5-pro"].context_length, Some(1_048_576));++ let compat = parse_listing(&json!({"data": [+ {"id": "gemini-2.5-flash", "inputTokenLimit": 1048576},+ ]}));+ assert_eq!(compat["gemini-2.5-flash"].context_length, Some(1_048_576));+ }+/// Numbers and numeric strings are both accepted, and a nonsense price is/// dropped rather than poisoning a cost estimate.#[test]diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex a7945a7fe..447705b2c 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -13,10 +13,11 @@//! consumer matches on are the snake_case variant names: `token`, `reasoning`,//! `step`, `tool_call_started`, `tool_call_args_delta`, `tool_call`,//! `tool_output_delta`, `tool_result`, `subagent_start`, `subagent_queued`,-//! `subagent_end`, `subagent_plan`, `subagent`, `notice`, `monitors`,-//! `parked`, `messages_updated`, `ask_request`, `ask_resolved`, `todo_update`,-//! `turn_usage`, `done`, `error`, `permission_request`, `tool_request`,-//! `tool_request_cancelled`, `tool_details`, `request_provenance`. Four tags are+//! `subagent_end`, `subagent_plan`, `subagent`, `notice`, `compaction`,+//! `monitors`, `parked`, `messages_updated`, `ask_request`, `ask_resolved`,+//! `todo_update`, `turn_usage`, `done`, `error`, `permission_request`,+//! `tool_request`, `tool_request_cancelled`, `tool_details`,+//! `request_provenance`. Four tags are//! minted by//! the CLI rather than by the loop: `init`, `permission_decision`, `result` and//! `input_error`. `init` is the handshake a client reads before any other recorddiff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 68b76e26b..0b9e9faaf 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -50,7 +50,8 @@ use super::mcp::McpServerEntry;use super::user_message::{build_user_message, image_mime, image_mime_of, PendingImage, MAX_IMAGE_BYTES};use super::worktree::Worktree;use super::{- is_user_turn, sort_threads_recent, AgentSession, ResumeRequest, ResumeTarget, SessionLimits,+ is_user_turn, sort_threads_recent, AgentSession, ResumeRequest, ResumeTarget,+ SessionBudgetSource, SessionLimits,};use crate::core::agent::compaction::{estimate_token_count, trigger_tokens};use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};@@ -1854,9 +1855,9 @@ struct App {/// Token-spend ceiling for one message's run; `0` is unbounded. Advisory:/// crossing it compacts and files a note rather than stopping the run.max_session_tokens: u64,- /// `--max-session-tokens` pinned `max_session_tokens`, so `/reload config`- /// does not replace it with `[budget].max_tokens`.- max_session_tokens_pinned: bool,+ /// Which source set `max_session_tokens`. `--max-session-tokens` pins it+ /// against `/reload config`; a window-derived one follows the model.+ max_session_tokens_source: SessionBudgetSource,/// `[budget].max_usd`: what one message's run may spend before it stops,/// with the rates to meter it against. `None` -- the default -- leaves the/// session unmetered. Per run, not per session: each message gets the same@@ -2147,6 +2148,13 @@ struct App {compacting: Option<CompactKind>,/// When the in-flight compaction started, for the elapsed counter.compact_started: Option<Instant>,+ /// The running turn is itself compacting (the loop's preflight, overflow+ /// or budget path), and since when. Display-only: unlike `compacting` it+ /// gates nothing, because the run that compacts is the one already going.+ run_compacting: Option<Instant>,+ /// A mid-run compaction finished, so the next `MessagesUpdated` carries a+ /// shorter history the gauge must be re-estimated against.+ pending_compaction_refresh: bool,/// The in-flight compaction was triggered by a context-overflow error, so/// the errored turn is resumed once it lands.retry_after_compact: bool,@@ -2623,7 +2631,7 @@ impl App {compaction_reserve_tokens: limits.compaction_reserve_tokens,max_tokens: limits.max_tokens,max_session_tokens: limits.max_session_tokens,- max_session_tokens_pinned: limits.max_session_tokens_pinned,+ max_session_tokens_source: limits.max_session_tokens_source,cost_ceiling: limits.cost_ceiling,repo_root,git_branch: git::current_branch(&project_root),@@ -2719,6 +2727,8 @@ impl App {compact_request: None,compacting: None,compact_started: None,+ run_compacting: None,+ pending_compaction_refresh: false,retry_after_compact: false,overflow_retries: 0,scrollback: 0,@@ -4998,6 +5008,12 @@ impl App {let changed = resolved.tokens != self.context_window;self.context_window = resolved.tokens;self.context_window_source = resolved.source;+ // An unconfigured session budget is sized by the window, so it moves+ // with it; a flag or `[budget].max_tokens` stays put.+ if self.max_session_tokens_source.follows_window() {+ (self.max_session_tokens, self.max_session_tokens_source) =+ super::resolve_session_budget(None, None, super::known_window(resolved));+ }self.sync_compaction_budget();changed}@@ -5016,11 +5032,13 @@ impl App {context_window: self.context_window,ratio: self.compaction_ratio,reserve_tokens: self.compaction_reserve_tokens,+ window_pinned: self.configured_context_window.is_some(),};let unchanged = args.compaction.is_some_and(|b| {b.context_window == budget.context_window&& b.ratio == budget.ratio&& b.reserve_tokens == budget.reserve_tokens+ && b.window_pinned == budget.window_pinned});if unchanged {return;@@ -5804,11 +5822,26 @@ impl App {self.tokens_estimated = false;}}- StreamEvent::Done { .. } | StreamEvent::Error { .. } => {}+ StreamEvent::Done { .. } | StreamEvent::Error { .. } => {+ self.run_compacting = None;+ }StreamEvent::MessagesUpdated { messages } => {self.history = messages;self.persist();+ // A compaction mid-run replaced the history the last `usage`+ // measured, so the gauge re-estimates instead of showing the+ // pre-compaction fill until the next response lands.+ if self.pending_compaction_refresh {+ self.pending_compaction_refresh = false;+ self.tokens = estimate_token_count(&self.history);+ self.invalidate_token_provenance();+ }}+ StreamEvent::Compaction {+ phase,+ reason,+ messages,+ } => self.apply_compaction(phase, reason, messages, None),StreamEvent::TodoUpdate { list } => {self.todos = list;// A snapshot only arrives on a successful mutation; its absence@@ -5912,6 +5945,19 @@ impl App {let key = self.usage_key();self.session_usage.entry(key).or_default().add(&usage);}+ // A child's headline (a compaction, a monitor match) is as much the+ // user's business as the parent's: dropping it made a child's+ // compaction invisible.+ StreamEvent::Notice { text } => {+ self.note(&format!("{name}: {text}"));+ }+ // A child's compaction is announced, but the spinner and gauge are+ // the parent's: the child's history is not the one on screen.+ StreamEvent::Compaction {+ phase,+ reason,+ messages,+ } => self.apply_compaction(phase, reason, messages, Some(name)),// 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@@ -5922,6 +5968,50 @@ impl App {}}+ /// Show a loop-side compaction: a throbber while the summarizer runs and a+ /// note when it lands or fails. `child` names the subagent it came from,+ /// whose compaction gets a note only.+ fn apply_compaction(+ &mut self,+ phase: crate::core::agent::events::CompactionPhase,+ reason: crate::core::agent::events::CompactionReason,+ messages: Option<usize>,+ child: Option<&str>,+ ) {+ use crate::core::agent::events::{CompactionPhase, CompactionReason};+ let why = match reason {+ CompactionReason::Preflight => "the prompt neared the context window",+ CompactionReason::ContextOverflow => "the provider rejected the prompt as too long",+ CompactionReason::SessionBudget => "the session token budget was used up",+ };+ let who = child.map(|c| format!("{c}: ")).unwrap_or_default();+ match phase {+ CompactionPhase::Started => {+ if child.is_none() {+ self.run_compacting = Some(Instant::now());+ }+ }+ CompactionPhase::Finished => {+ if child.is_none() {+ self.run_compacting = None;+ self.pending_compaction_refresh = true;+ }+ self.finalize_tool_group();+ self.flush_assistant();+ self.note(&format!(+ "{who}compacted {} messages into a summary: {why}",+ messages.unwrap_or(0)+ ));+ }+ CompactionPhase::Failed => {+ if child.is_none() {+ self.run_compacting = None;+ }+ self.note(&format!("{who}compaction failed ({why}); history unchanged"));+ }+ }+ }+/// Recompute and publish the Orca-visible agent status from primary state/// (turn status plus pending prompts). The reporter dedupes, so calling/// this after every transition is cheap. The prompt preview carries the@@ -14729,8 +14819,12 @@ fn reload_config(app: &mut App) {}app.compaction_reserve_tokens = cfg.agent.compaction_reserve_tokens;app.max_tokens = cfg.agent.max_tokens;- if !app.max_session_tokens_pinned {- app.max_session_tokens = super::resolve_session_budget(None, cfg.budget.max_tokens);+ let pinned = app.max_session_tokens_source == SessionBudgetSource::Flag;+ if !pinned {+ // Seeded from the file alone; `refresh_context_window` below fills in+ // the window-derived default when the file sets none.+ (app.max_session_tokens, app.max_session_tokens_source) =+ super::resolve_session_budget(None, cfg.budget.max_tokens, None);}app.send_reasoning = cfg.agent.send_reasoning.unwrap_or(true);// Re-resolves the window and pushes the compaction budget to the engine.@@ -14742,9 +14836,7 @@ fn reload_config(app: &mut App) {crate::core::agent::project::agent_toml_path(&app.project_root).display()));report_reload_diff(app, diff_reload_entries(&before, &after));- if app.max_session_tokens_pinned- && super::resolve_session_budget(None, cfg.budget.max_tokens) != budget_before- {+ if pinned && cfg.budget.max_tokens.is_some_and(|v| v != budget_before) {app.system_detail_text(" budget.max_tokens ignored: --max-session-tokens was passed");}if !ratio_busy@@ -19389,6 +19481,8 @@ fn header(app: &App) -> Paragraph<'static> {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.run_compacting.is_some() {+ ("compacting".to_string(), Style::new().magenta().bold())} else if app.mcp_auth.is_some() {// A sign-in runs while the model is otherwise idle; the badge stands in// for `[ready]` so the pending auth is visible even off the `/mcp` screen.@@ -19947,6 +20041,18 @@ fn input_box(app: &App) -> Paragraph<'static> {),])).block(block)+ } else if let Some(started) = app.run_compacting.filter(|_| app.input.is_empty()) {+ Paragraph::new(Line::from(vec![+ Span::styled(format!("{} ", app.spinner()), Style::new().magenta()),+ Span::styled(+ format!(+ "compacting conversation… {}",+ format_elapsed(started.elapsed().as_secs())+ ),+ Style::new().dim().italic(),+ ),+ ]))+ .block(block)} else if app.picker.is_some() {Paragraph::new(Line::styled("selecting…", Style::new().dim().italic())).block(block)} else if app.status == Status::Running && app.input.is_empty() {@@ -20314,7 +20420,7 @@ mod tests {compaction_reserve_tokens: Some(16_384),max_tokens: None,max_session_tokens: 128_000,- max_session_tokens_pinned: false,+ max_session_tokens_source: crate::core::cli::SessionBudgetSource::Default,max_turns: None,cost_ceiling: None,};@@ -20821,7 +20927,7 @@ mod tests {compaction_reserve_tokens: Some(16_384),max_tokens: None,max_session_tokens: 128_000,- max_session_tokens_pinned: false,+ max_session_tokens_source: crate::core::cli::SessionBudgetSource::Default,max_turns: None,cost_ceiling: None,},@@ -31705,6 +31811,107 @@ mod tests {});}+ /// A compaction the running turn makes shows a throbber while the+ /// summarizer runs, a note saying why when it lands, and re-estimates the+ /// gauge from the compacted history instead of keeping the old fill.+ #[test]+ fn a_mid_run_compaction_shows_progress_and_refreshes_the_gauge() {+ use crate::core::agent::events::{CompactionPhase, CompactionReason};+ let mut app = test_app();+ app.tokens = 900_000;+ app.apply(StreamEvent::Compaction {+ phase: CompactionPhase::Started,+ reason: CompactionReason::SessionBudget,+ messages: None,+ });+ assert!(app.run_compacting.is_some());+ let header: String = header_spans(&app).iter().map(|s| s.content.to_string()).collect();+ assert!(header.contains("compacting"), "{header}");++ app.apply(StreamEvent::Compaction {+ phase: CompactionPhase::Finished,+ reason: CompactionReason::SessionBudget,+ messages: Some(12),+ });+ assert!(app.run_compacting.is_none());+ let out = transcript_text(&app);+ assert!(+ out.contains("compacted 12 messages into a summary: the session token budget"),+ "{out}"+ );++ app.apply(StreamEvent::MessagesUpdated {+ messages: vec![serde_json::json!({ "role": "user", "content": "short" })],+ });+ assert!(app.tokens < 1_000, "gauge re-estimated: {}", app.tokens);+ assert!(app.tokens_estimated);+ }++ /// A failed compaction takes its throbber down and says so.+ #[test]+ fn a_failed_mid_run_compaction_clears_the_throbber() {+ use crate::core::agent::events::{CompactionPhase, CompactionReason};+ let mut app = test_app();+ for phase in [CompactionPhase::Started, CompactionPhase::Failed] {+ app.apply(StreamEvent::Compaction {+ phase,+ reason: CompactionReason::ContextOverflow,+ messages: None,+ });+ }+ assert!(app.run_compacting.is_none());+ assert!(transcript_text(&app).contains("compaction failed"));+ }++ /// A child's compaction gets a note but not the parent's throbber: the+ /// child's history is not the one on screen.+ #[test]+ fn a_subagent_compaction_is_noted_without_the_parent_throbber() {+ use crate::core::agent::events::{CompactionPhase, CompactionReason};+ let mut app = test_app();+ start_subagent(&mut app, "r0", "alpha");+ for (phase, messages) in [(CompactionPhase::Started, None), (CompactionPhase::Finished, Some(5))] {+ subagent_event(+ &mut app,+ "r0",+ "alpha",+ StreamEvent::Compaction {+ phase,+ reason: CompactionReason::Preflight,+ messages,+ },+ );+ assert!(app.run_compacting.is_none());+ }+ assert!(+ transcript_text(&app).contains("alpha: compacted 5 messages"),+ "{}",+ transcript_text(&app)+ );+ }++ /// A child's `Notice` (e.g. "compacted N messages") reaches the parent+ /// transcript, attributed to the child. It used to fall into the catch-all+ /// arm, so a subagent's compaction was invisible.+ #[test]+ fn subagent_notice_is_shown_in_the_transcript() {+ let mut app = test_app();+ start_subagent(&mut app, "r0", "alpha");+ subagent_event(+ &mut app,+ "r0",+ "alpha",+ StreamEvent::Notice {+ text: "compacted 12 messages into a summary".into(),+ },+ );+ let out = transcript_text(&app);+ assert!(+ out.contains("alpha: compacted 12 messages into a summary"),+ "{out}"+ );+ }+/// Parallel agents collapse into one fixed-height block, each carrying the/// numbers that say whether it is progressing or about to blow its context.#[test]@@ -37496,7 +37703,7 @@ mod tests {async fn reload_config_respects_a_pinned_session_budget() {let (mut app, root) = skill_test_app("deploy", "How to deploy.");app.max_session_tokens = 42;- app.max_session_tokens_pinned = true;+ app.max_session_tokens_source = crate::core::cli::SessionBudgetSource::Flag;write_agent_toml(&root, "[budget]\nmax_tokens = 999\n");run_command(&mut app, "reload config", &no_mcp()).await;assert_eq!(app.max_session_tokens, 42, "--max-session-tokens outranks the file");@@ -38232,6 +38439,29 @@ mod tests {);}+ /// An unconfigured session budget is sized by the model's window and+ /// follows a model switch; the old fixed 128K compacted 1M-window models at+ /// an eighth of their capacity. A `[budget].max_tokens` value stays put.+ #[test]+ fn default_session_budget_follows_the_model_window() {+ let mut app = test_app();+ app.set_model("claude-sonnet-4-6".to_string());+ assert_eq!(app.context_window, 1_000_000);+ assert_eq!(app.max_session_tokens, 1_000_000);+ assert_eq!(+ app.max_session_tokens_source,+ crate::core::cli::SessionBudgetSource::ContextWindow+ );++ app.set_model("claude-sonnet-4-5".to_string());+ assert_eq!(app.max_session_tokens, 200_000);++ app.max_session_tokens = 50_000;+ app.max_session_tokens_source = crate::core::cli::SessionBudgetSource::Config;+ app.set_model("claude-sonnet-4-6".to_string());+ assert_eq!(app.max_session_tokens, 50_000, "a configured budget is not resized");+ }+#[test]fn configured_window_stays_authoritative_across_switch() {let mut app = test_app();