From b5e45ca98b534020bc71aecb4423432fe4559d13 Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Fri, 27 Nov 2026 15:19:50 -0800 Subject: [PATCH] feat(agents): consolidate session stats into a Session Info popover (#6563) The agent status strip showed context usage, last-turn tokens, every usage-limit window and session cost inline. It now shows the context ring and percentage, plus any usage limit at 80% or more in its warning tone; everything else moves into one Session Info popover with a Context Window bar (reserved-for-response segment, System and User Context breakdown with token counts on hover), the last turn's tokens, usage limits and cost. Free space and deferred categories are skipped by name for Claude Code. GitHub Copilot sessions now report a context breakdown through _openidea/context_usage (session.metadata.getContextAttribution, with contextInfo and usage_info fallbacks), accumulate AI-credit spend across turns and subagents, keep session cost across usage updates without cost, map /compact to session.history.compact, and label quota windows Chat, Completions and Premium requests. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/lib.rs | 10 +- crates/ide-agent/src/model.rs | 8 +- crates/ide-agent/src/native/copilot/mod.rs | 192 +++++++- crates/ide-agent/src/native/copilot/tests.rs | 263 ++++++++++- .../ide-agent/src/native/copilot/translate.rs | 359 ++++++++++++++- src/bindings.ts | 6 +- src/features/agents/Session.module.css | 231 ++++++---- src/features/agents/agents.test.ts | 48 +- src/features/agents/composerModel.ts | 82 +++- src/features/agents/session/ContextMeter.tsx | 414 +++++++++++++----- src/features/agents/session/SessionStatus.tsx | 159 +------ src/features/agents/sessionState.test.tsx | 161 +++++-- src/platform/locales/text/en.json | 16 +- src/platform/locales/text/es.json | 16 +- src/platform/locales/text/fr.json | 16 +- src/platform/locales/text/ko.json | 16 +- src/platform/locales/text/pl.json | 16 +- src/platform/locales/text/pt.json | 16 +- src/platform/locales/text/ru.json | 18 +- src/platform/locales/text/tr.json | 18 +- src/platform/locales/text/zh-TW.json | 18 +- src/platform/locales/text/zh.json | 16 +- 22 files changed, 1677 insertions(+), 422 deletions(-) diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index b8c66631bc..c197811816 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -4297,7 +4297,15 @@ impl Task { true } "usage_update" => { - s.task.usage = config::usage_of(update).or(s.task.usage.take()); + let prev_cost = s.task.usage.as_ref().and_then(|u| u.cost.clone()); + s.task.usage = config::usage_of(update) + .map(|mut u| { + if u.cost.is_none() { + u.cost = prev_cost; + } + u + }) + .or(s.task.usage.take()); true } _ => false, diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index cf9bf2be7e..b96b7018bc 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -300,6 +300,9 @@ pub struct AgentContextUsage { pub model: String, pub is_auto_compact_enabled: Option, pub auto_compact_threshold: Option, + /// Tokens reserved for model response / output buffer, when the agent reports it. + #[serde(default)] + pub reserved_tokens: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] @@ -307,13 +310,16 @@ pub struct AgentContextCategory { pub name: String, pub tokens: u32, pub kind: Option, + /// Visual section group (e.g. `"System"`, `"User Context"`). + #[serde(default)] + pub group: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct AgentCost { pub amount: f64, - /// ISO 4217 code, e.g. `USD`. + /// ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing. pub currency: String, } diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index 6d46e7b60b..80a3e56750 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -522,6 +522,7 @@ impl CopilotShim { "session/set_config_option" => self.set_config(¶ms).await, "session/prompt" => self.prompt(¶ms, false).await, "_openidea/steer" => self.prompt(¶ms, true).await, + "_openidea/context_usage" => self.context_usage(¶ms).await, "_openidea/stop_task" => self.stop_task(¶ms).await, "session/close" => self.close_session(¶ms).await, _ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))), @@ -537,7 +538,7 @@ impl CopilotShim { "promptCapabilities": { "image": true, "audio": false, "embeddedContext": true }, "mcpCapabilities": { "http": true, "sse": true, "stdio": true }, "sessionCapabilities": { "close": {}, "list": {} }, - "_meta": { "openidea": { "steer": true, "backgroundTasks": true } }, + "_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } }, }, "agentInfo": { "name": "copilot", @@ -655,12 +656,47 @@ impl CopilotShim { let options = models::config_options(&catalog, &settings); self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings)); self.publish_commands(&actual_id, cwd); + self.sync_usage_metrics(&actual_id); Ok(json!({ "sessionId": actual_id, "configOptions": options, })) } + fn sync_usage_metrics(self: &Arc, session_id: &str) { + let shim = self.clone(); + let sid = session_id.to_owned(); + self.runtime.spawn(async move { + let Ok(metrics) = shim.call("session.usage.getMetrics", json!({ "sessionId": sid })).await else { + return; + }; + let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) else { + return; + }; + let catalog = shim.catalog.try_lock().ok().and_then(|g| g.clone()); + let update = { + let mut st = shim.state.lock(); + st.sessions.get_mut(&sid).and_then(|entry| { + entry.translator.set_total_nano_aiu(nano_aiu); + let used = entry.translator.last_used_tokens?; + let size = entry + .translator + .last_usage_snapshot + .as_ref() + .map(|s| s.token_limit) + .filter(|&s| s > 0) + .or_else(|| { + catalog.as_deref().and_then(|m| entry.settings.active_context_tokens(m)).filter(|&s| s > 0) + })?; + Some(entry.translator.usage_update(used, size)) + }) + }; + if let Some(update) = update { + shim.send_update(&sid, update); + } + }); + } + fn publish_commands(self: &Arc, session_id: &str, cwd: &str) { let shim = self.clone(); let sid = session_id.to_owned(); @@ -735,25 +771,152 @@ impl CopilotShim { let new_limit = next_settings.active_context_tokens(&catalog); let options = models::config_options(&catalog, &next_settings); - { + let usage_update = { let mut st = self.state.lock(); if let Some(entry) = st.sessions.get_mut(session_id) { entry.settings = next_settings; + if matches!(option, MODEL | CONTEXT_TIER) + && let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0)) + { + Some(entry.translator.usage_update(used, size)) + } else { + None + } + } else { + None } - } - if matches!(option, MODEL | CONTEXT_TIER) - && let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0)) - { - self.send_update(session_id, json!({ "sessionUpdate": "usage_update", "used": used, "size": size })); + }; + if let Some(update) = usage_update { + self.send_update(session_id, update); } Ok(json!({ "configOptions": options })) } + async fn context_usage(&self, params: &Value) -> Result { + let session_id = str_param(params, "sessionId")?; + let catalog = self.models().await.ok(); + let (model_id, fallback_limit, snapshot) = { + let st = self.state.lock(); + let entry = st.sessions.get(session_id).ok_or_else(|| invalid(format!("unknown session {session_id}")))?; + let limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models)); + (entry.settings.model.clone(), limit, entry.translator.last_usage_snapshot.clone()) + }; + + let (attr_res, metrics_res) = tokio::join!( + self.call("session.metadata.getContextAttribution", json!({ "sessionId": session_id })), + self.call("session.usage.getMetrics", json!({ "sessionId": session_id })), + ); + + if let Ok(metrics) = metrics_res + && let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) + && let Some(entry) = self.state.lock().sessions.get_mut(session_id) + { + entry.translator.set_total_nano_aiu(nano_aiu); + } + + let mut usage = + attr_res.ok().and_then(|v| translate::context_usage_from_attribution(&v, &model_id, fallback_limit)); + + if usage.is_none() + && !model_id.is_empty() + && let Ok(info) = self + .call("session.metadata.contextInfo", json!({ "sessionId": session_id, "modelName": model_id })) + .await + { + usage = translate::context_usage_from_context_info(&info, &model_id, fallback_limit); + } + + let usage = usage + .or_else(|| snapshot.as_ref().map(|snap| translate::context_usage_from_snapshot(snap, &model_id))) + .ok_or_else(|| error(codes::INTERNAL_ERROR, "Context details are not available yet"))?; + + let meter_update = { + let mut st = self.state.lock(); + st.sessions.get_mut(session_id).map(|entry| { + entry.translator.last_used_tokens = Some(usage.total_tokens); + entry.translator.usage_update(usage.total_tokens, usage.max_tokens) + }) + }; + if let Some(update) = meter_update { + self.send_update(session_id, update); + } + + serde_json::to_value(usage).map_err(|e| error(codes::INTERNAL_ERROR, e.to_string())) + } + + async fn compact_session(&self, session_id: &str, instructions: Option<&str>) -> Result { + let mut req = json!({ + "sessionId": session_id, + "trigger": "manual", + }); + if let Some(text) = instructions.map(str::trim).filter(|s| !s.is_empty()) { + req["customInstructions"] = json!(text); + } + let res = self.call("session.history.compact", req).await?; + let success = res.get("success").and_then(Value::as_bool).unwrap_or(true); + if !success { + let msg = res.get("error").and_then(Value::as_str).unwrap_or("Conversation compaction failed"); + return Err(error(codes::INTERNAL_ERROR, msg)); + } + + let catalog = self.models().await.ok(); + let meter_update = { + let mut st = self.state.lock(); + st.sessions.get_mut(session_id).and_then(|entry| { + let cw = res.get("contextWindow")?; + let used = cw.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())?; + let fallback_limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models)); + let size = cw + .get("tokenLimit") + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .filter(|&n| n > 0) + .or(fallback_limit.filter(|&n| n > 0))?; + let u32_field = |k: &str| cw.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()); + entry.translator.record_snapshot(translate::UsageSnapshot { + current_tokens: used, + token_limit: size, + system_tokens: u32_field("systemTokens"), + tool_definitions_tokens: u32_field("toolDefinitionsTokens"), + conversation_tokens: u32_field("conversationTokens"), + }); + Some(entry.translator.usage_update(used, size)) + }) + }; + if let Some(update) = meter_update { + self.send_update(session_id, update); + } + + let tokens_removed = res.get("tokensRemoved").and_then(Value::as_u64).unwrap_or(0); + let messages_removed = res.get("messagesRemoved").and_then(Value::as_u64).unwrap_or(0); + let summary = if tokens_removed > 0 || messages_removed > 0 { + format!("Compacted conversation ({tokens_removed} tokens, {messages_removed} messages removed).") + } else { + "Conversation compacted.".to_owned() + }; + self.send_update( + session_id, + json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": summary } }), + ); + if let Some(entry) = self.state.lock().sessions.get_mut(session_id) { + entry.early_cancel = None; + } + Ok(json!({ "stopReason": "end_turn" })) + } + async fn prompt(&self, params: &Value, steer: bool) -> Result { let session_id = str_param(params, "sessionId")?.to_owned(); let blocks = params.get("prompt").and_then(Value::as_array).ok_or_else(|| invalid("missing prompt"))?; let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks); + if !steer + && attachments.is_empty() + && let Some(instructions) = parse_compact_command(&text) + { + cleanup_files(&temp_files); + return self.compact_session(&session_id, instructions).await; + } + if steer { let (is_running, main_busy) = { let st = self.state.lock(); @@ -1070,6 +1233,21 @@ impl CopilotShim { } } +fn parse_compact_command(text: &str) -> Option> { + let trimmed = text.trim(); + if trimmed == "/compact" { + return Some(None); + } + let rest = trimmed.strip_prefix("/compact")?; + let first = rest.chars().next()?; + if first.is_whitespace() { + let focus = rest.trim(); + Some((!focus.is_empty()).then_some(focus)) + } else { + None + } +} + fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec, Vec) { let mut text_parts = Vec::new(); let mut attachments = Vec::new(); diff --git a/crates/ide-agent/src/native/copilot/tests.rs b/crates/ide-agent/src/native/copilot/tests.rs index 1138d84313..ddf492e87b 100644 --- a/crates/ide-agent/src/native/copilot/tests.rs +++ b/crates/ide-agent/src/native/copilot/tests.rs @@ -1,6 +1,11 @@ use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults}; +use super::translate::{ + self, EventTranslator, UsageSnapshot, context_usage_from_attribution, context_usage_from_context_info, + context_usage_from_snapshot, +}; use super::{acp_args, acp_fallback_spec, attach, headless_args}; use crate::config; +use crate::model::{AgentContextCategory, AgentContextUsage}; use crate::provider::Driver; use ide_jsonrpc::{Framing, Handler, Peer, codes}; use parking_lot::Mutex; @@ -443,6 +448,38 @@ impl Handler for FakeCopilotServer { ] })), "session.tasks.cancel" => Ok(json!({ "cancelled": true })), "session.abort" => Ok(json!({})), + "session.usage.getMetrics" => Ok(json!({ + "totalNanoAiu": 4_211_400_000_000.0, + "totalPremiumRequestCost": 12.0, + })), + "session.metadata.getContextAttribution" => Ok(json!({ + "contextAttribution": { + "totalTokens": 405_200, + "limit": 1_000_000, + "promptTokenLimit": 936_000, + "bufferTokens": 64_000, + "compactionThreshold": 800_000, + "modelId": "gemini-4-carbon", + "entries": [ + { "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 }, + { "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" }, + { "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 203_000, "parentId": "system:root" }, + { "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 } + ] + } + })), + "session.history.compact" => Ok(json!({ + "success": true, + "tokensRemoved": 250_000, + "messagesRemoved": 12, + "contextWindow": { + "currentTokens": 155_200, + "tokenLimit": 1_000_000, + "systemTokens": 20_000, + "toolDefinitionsTokens": 100_000, + "conversationTokens": 35_200 + } + })), "session.send" if self.background_shell => { if let Some(peer) = self.peer.get().cloned() { let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned(); @@ -796,6 +833,228 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil } } +#[test] +fn translates_context_attribution_without_double_counting_parent_rollups() { + let payload = json!({ + "contextAttribution": { + "totalTokens": 405_200, + "limit": 1_000_000, + "bufferTokens": 64_000, + "compactionThreshold": 800_000, + "modelId": "gemini-4-carbon", + "entries": [ + { "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 }, + { "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" }, + { "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 120_000, "parentId": "system:root" }, + { "kind": "toolDefinition", "id": "toolDefinition:view", "label": "view", "tokens": 83_000, "parentId": "system:root" }, + { "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 }, + { "kind": "plugin", "id": "plugin:git", "label": "git", "tokens": 5_000 }, + { "kind": "skill", "id": "skill:pr", "label": "pr", "tokens": 5_000, "parentId": "plugin:git" } + ] + } + }); + let usage = context_usage_from_attribution(&payload, "fallback", None).unwrap(); + assert_eq!(usage.total_tokens, 405_200); + assert_eq!(usage.max_tokens, 1_000_000); + assert_eq!(usage.reserved_tokens, Some(64_000)); + assert_eq!(usage.auto_compact_threshold, Some(800_000)); + assert_eq!(usage.is_auto_compact_enabled, Some(true)); + assert_eq!( + usage.categories, + vec![ + AgentContextCategory { + name: "System prompt".into(), + tokens: 20_000, + kind: Some("used".into()), + group: Some("System".into()), + }, + AgentContextCategory { + name: "Tool Definitions".into(), + tokens: 203_000, + kind: Some("used".into()), + group: Some("System".into()), + }, + AgentContextCategory { + name: "Tool Results".into(), + tokens: 69_000, + kind: Some("used".into()), + group: Some("User Context".into()), + }, + AgentContextCategory { + name: "Messages".into(), + tokens: 108_200, + kind: Some("used".into()), + group: Some("User Context".into()), + }, + AgentContextCategory { + name: "Skills".into(), + tokens: 5_000, + kind: Some("used".into()), + group: Some("User Context".into()), + }, + AgentContextCategory { name: "Free space".into(), tokens: 530_800, kind: Some("free".into()), group: None }, + ] + ); +} + +#[test] +fn translates_context_info_and_usage_snapshot_fallbacks() { + let info = json!({ + "contextInfo": { + "modelName": "claude-sonnet-4.5", + "systemTokens": 12_000, + "toolDefinitionsTokens": 48_000, + "conversationTokens": 40_000, + "totalTokens": 100_000, + "limit": 200_000, + "bufferTokens": 20_000, + "compactionThreshold": 160_000 + } + }); + let from_info = context_usage_from_context_info(&info, "fallback", None).unwrap(); + assert_eq!(from_info.reserved_tokens, Some(20_000)); + assert_eq!( + from_info.categories.iter().map(|c| (c.name.as_str(), c.tokens, c.group.as_deref())).collect::>(), + vec![ + ("System prompt", 12_000, Some("System")), + ("Tool Definitions", 48_000, Some("System")), + ("Messages", 40_000, Some("User Context")), + ("Free space", 80_000, None), + ] + ); + + let from_snap = context_usage_from_snapshot( + &UsageSnapshot { + current_tokens: 50_000, + token_limit: 200_000, + system_tokens: Some(10_000), + tool_definitions_tokens: Some(25_000), + conversation_tokens: Some(15_000), + }, + "gpt-5.6-sol", + ); + assert_eq!(from_snap.total_tokens, 50_000); + assert_eq!(from_snap.max_tokens, 200_000); + assert_eq!(from_snap.categories.len(), 4); +} + +#[test] +fn accumulates_copilot_credits_across_turns_subagents_and_compaction() { + let mut tr = EventTranslator::default(); + let first = tr.translate( + "s1", + &json!({ + "type": "session.usage_info", + "data": { "currentTokens": 40_000, "tokenLimit": 200_000, "systemTokens": 10_000, "toolDefinitionsTokens": 20_000, "conversationTokens": 10_000 } + }), + Some(200_000), + ); + assert_eq!(first.updates[0].1["used"], 40_000); + assert!(first.updates[0].1.get("cost").is_none()); + + // Main-agent usage reports 1.5 credits; subagent usage adds 0.5 credits -> 2.0 credits total. + let main_usage = tr.translate( + "s1", + &json!({ + "type": "assistant.usage", + "data": { "inputTokens": 45_000, "copilotUsage": { "totalNanoAiu": 1_500_000_000.0 } } + }), + Some(200_000), + ); + assert_eq!(main_usage.updates[0].1["cost"]["currency"], "credits"); + assert!((main_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 1.5).abs() < 1e-6); + + let sub_usage = tr.translate( + "s1", + &json!({ + "type": "assistant.usage", + "agentId": "sub-1", + "data": { "inputTokens": 12_000, "copilotUsage": { "totalNanoAiu": 500_000_000.0 } } + }), + Some(200_000), + ); + assert_eq!(sub_usage.updates[0].1["used"], 45_000); + assert!((sub_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6); + + // Compaction updates token count while keeping accumulated credits. + let compacted = tr.translate( + "s1", + &json!({ + "type": "session.compaction_complete", + "data": { "success": true, "postCompactionTokens": 22_000, "tokenLimit": 200_000 } + }), + Some(200_000), + ); + assert_eq!(compacted.updates[0].1["used"], 22_000); + assert!((compacted.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6); +} + +#[test] +fn available_commands_includes_compact_when_omitted_by_server() { + let cmds = translate::available_commands(Some(&json!({ "commands": [{ "name": "review" }] })), None); + assert!(cmds.iter().any(|c| c["name"] == "compact")); + assert!(cmds.iter().any(|c| c["name"] == "review")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn context_usage_rpc_and_compact_command_work_end_to_end() { + let server = + Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false }); + let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new()))); + let server_clone = server.clone(); + let client = attach(updates.clone(), move |events| { + let (a, b) = tokio::io::duplex(1 << 16); + let (ar, aw) = tokio::io::split(a); + let (br, bw) = tokio::io::split(b); + let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength); + let _ = server_clone.peer.set(srv_peer); + Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength)) + }) + .unwrap(); + + let init: Value = client.request("initialize", json!({}), None).await.unwrap(); + assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["contextUsage"], true); + let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap(); + + let ctx: AgentContextUsage = + client.request("_openidea/context_usage", json!({ "sessionId": "cop-sess-1" }), None).await.unwrap(); + assert_eq!(ctx.total_tokens, 405_200); + assert_eq!(ctx.max_tokens, 1_000_000); + assert_eq!(ctx.reserved_tokens, Some(64_000)); + assert!(ctx.categories.iter().any(|c| c.name == "System prompt" && c.group.as_deref() == Some("System"))); + assert!(ctx.categories.iter().any(|c| c.name == "Tool Definitions" && c.group.as_deref() == Some("System"))); + assert!(ctx.categories.iter().any(|c| c.name == "Tool Results" && c.group.as_deref() == Some("User Context"))); + assert!(ctx.categories.iter().any(|c| c.name == "Messages" && c.group.as_deref() == Some("User Context"))); + + // Syncing metrics updated usage_update with credits cost. + tokio::time::sleep(Duration::from_millis(20)).await; + assert!(updates.0.lock().iter().any(|u| { + u["sessionUpdate"] == "usage_update" + && u["used"] == 405_200 + && u["cost"]["currency"] == "credits" + && (u["cost"]["amount"].as_f64().unwrap_or(0.0) - 4211.4).abs() < 0.01 + })); + + // `/compact` invokes `session.history.compact` instead of `session.send`. + let res: Value = client + .request( + "session/prompt", + json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "/compact keep PR notes" }] }), + None, + ) + .await + .unwrap(); + assert_eq!(res["stopReason"], "end_turn"); + assert!(server.calls.lock().iter().any(|(m, p)| { + m == "session.history.compact" + && p["sessionId"] == "cop-sess-1" + && p["trigger"] == "manual" + && p["customInstructions"] == "keep PR notes" + })); + tokio::time::sleep(Duration::from_millis(20)).await; + assert!(updates.0.lock().iter().any(|u| u["sessionUpdate"] == "usage_update" && u["used"] == 155_200)); +} + #[test] fn available_commands_preserves_input_choices() { let cmds = json!({ @@ -825,7 +1084,9 @@ fn available_commands_preserves_input_choices() { }); let list = super::translate::available_commands(Some(&cmds), None); let parsed = crate::config::commands_of(&json!({ "availableCommands": list }), "copilot"); - assert_eq!(parsed.len(), 2); + // Then the built-in /compact. + assert_eq!(parsed.len(), 3); + assert_eq!(parsed[2].name, "compact"); assert_eq!(parsed[0].name, "skills"); assert_eq!(parsed[0].hint.as_deref(), Some("[list|info|reload]")); assert_eq!( diff --git a/crates/ide-agent/src/native/copilot/translate.rs b/crates/ide-agent/src/native/copilot/translate.rs index 3cd1029fe4..37d672e235 100644 --- a/crates/ide-agent/src/native/copilot/translate.rs +++ b/crates/ide-agent/src/native/copilot/translate.rs @@ -2,11 +2,22 @@ //! permissions, slash commands, MCP servers) and ACP v1. use crate::LIMITS_UPDATE; +use crate::model::{AgentContextCategory, AgentContextUsage}; use serde_json::{Map, Value, json}; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::Path; const MAX_OUTPUT: usize = 64 * 1024; +const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct UsageSnapshot { + pub current_tokens: u32, + pub token_limit: u32, + pub system_tokens: Option, + pub tool_definitions_tokens: Option, + pub conversation_tokens: Option, +} #[derive(Default)] pub(super) struct EventTranslator { @@ -18,6 +29,11 @@ pub(super) struct EventTranslator { subagents: HashMap, /// Last reported prompt token count, used when updating context size. pub last_used_tokens: Option, + /// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent. + pub last_usage_snapshot: Option, + /// Accumulated session AI-credit spend in nano-AIU (across main agent and subagents). + total_nano_aiu: f64, + has_nano_aiu: bool, } #[derive(Clone, Debug)] @@ -46,6 +62,29 @@ impl EventTranslator { self.streamed_messages.clear(); } + pub fn set_total_nano_aiu(&mut self, nano_aiu: f64) { + if nano_aiu.is_finite() && nano_aiu > 0.0 { + self.total_nano_aiu = nano_aiu; + self.has_nano_aiu = true; + } + } + + pub fn record_snapshot(&mut self, snapshot: UsageSnapshot) { + self.last_used_tokens = Some(snapshot.current_tokens); + self.last_usage_snapshot = Some(snapshot); + } + + pub fn usage_update(&self, used: u32, size: u32) -> Value { + let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size }); + if self.has_nano_aiu && self.total_nano_aiu > 0.0 { + update["cost"] = json!({ + "amount": self.total_nano_aiu / NANO_AIU_PER_CREDIT, + "currency": "credits", + }); + } + update + } + pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option) -> Translated { let mut out = Translated { updates: Vec::new(), terminal: None }; let event_type = str_of(event, "type").unwrap_or_default(); @@ -239,36 +278,75 @@ impl EventTranslator { } } "session.usage_info" => { - let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()); - let limit = data - .get("tokenLimit") - .and_then(Value::as_u64) - .and_then(|n| u32::try_from(n).ok()) - .filter(|&n| n > 0) - .or(fallback_limit); + let used = u32_of(data, "currentTokens"); + let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit); if let (Some(used), Some(size)) = (used, limit) { - self.last_used_tokens = Some(used); - out.updates.push(( - main_session.to_owned(), - json!({ "sessionUpdate": "usage_update", "used": used, "size": size }), - )); + self.record_snapshot(UsageSnapshot { + current_tokens: used, + token_limit: size, + system_tokens: u32_of(data, "systemTokens"), + tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"), + conversation_tokens: u32_of(data, "conversationTokens"), + }); + out.updates.push((main_session.to_owned(), self.usage_update(used, size))); } } "assistant.usage" => { + let added_credits = data + .pointer("/copilotUsage/totalNanoAiu") + .and_then(Value::as_f64) + .filter(|n| n.is_finite() && *n > 0.0); + if let Some(nano_aiu) = added_credits { + self.total_nano_aiu += nano_aiu; + self.has_nano_aiu = true; + } if agent_id.is_none() { - let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()); - if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) { + let used = u32_of(data, "inputTokens").or(self.last_used_tokens); + let size = self + .last_usage_snapshot + .as_ref() + .map(|s| s.token_limit) + .filter(|&s| s > 0) + .or(fallback_limit.filter(|&s| s > 0)); + if let (Some(used), Some(size)) = (used, size) { self.last_used_tokens = Some(used); - out.updates.push(( - main_session.to_owned(), - json!({ "sessionUpdate": "usage_update", "used": used, "size": size }), - )); + out.updates.push((main_session.to_owned(), self.usage_update(used, size))); } + } else if added_credits.is_some() + && let (Some(used), Some(size)) = ( + self.last_used_tokens, + self.last_usage_snapshot + .as_ref() + .map(|s| s.token_limit) + .filter(|&s| s > 0) + .or(fallback_limit.filter(|&s| s > 0)), + ) + { + out.updates.push((main_session.to_owned(), self.usage_update(used, size))); } if let Some(limits) = quota_limits(data.get("quotaSnapshots")) { out.updates.push((main_session.to_owned(), limits)); } } + "session.compaction_complete" if agent_id.is_none() => { + if data.get("success").and_then(Value::as_bool) == Some(true) { + let used = u32_of(data, "postCompactionTokens"); + let size = u32_of(data, "tokenLimit") + .filter(|&n| n > 0) + .or_else(|| self.last_usage_snapshot.as_ref().map(|s| s.token_limit).filter(|&n| n > 0)) + .or(fallback_limit.filter(|&n| n > 0)); + if let (Some(used), Some(size)) = (used, size) { + self.record_snapshot(UsageSnapshot { + current_tokens: used, + token_limit: size, + system_tokens: u32_of(data, "systemTokens"), + tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"), + conversation_tokens: u32_of(data, "conversationTokens"), + }); + out.updates.push((main_session.to_owned(), self.usage_update(used, size))); + } + } + } "session.idle" if agent_id.is_none() => { let mode = str_of(data, "mode").unwrap_or_default(); if mode != "autopilot" { @@ -596,9 +674,252 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio "input": hint.map(|h| json!({ "hint": h })), })); } + if seen.insert("compact".to_owned()) { + out.push(json!({ + "name": "compact", + "description": "Compact conversation history to free context window space", + "source": "command", + "input": { "hint": "optional focus instructions" }, + })); + } out } +/// Converts Copilot's `session.metadata.getContextAttribution` payload into [`AgentContextUsage`], +/// grouping items into `System` (`System prompt`, `Tool Definitions`, …) and `User Context` +/// (`Tool Results`, `Messages`, `Skills`, …) without double-counting parent rollup entries. +pub(super) fn context_usage_from_attribution( + res: &Value, + fallback_model: &str, + fallback_limit: Option, +) -> Option { + let attr = res.get("contextAttribution").unwrap_or(res); + if !attr.is_object() { + return None; + } + let total_tokens = u32_of(attr, "totalTokens")?; + let max_tokens = u32_of(attr, "limit") + .filter(|&n| n > 0) + .or_else(|| u32_of(attr, "promptTokenLimit").filter(|&n| n > 0)) + .or_else(|| fallback_limit.filter(|&n| n > 0))?; + let reserved_tokens = u32_of(attr, "bufferTokens").filter(|&n| n > 0); + let model = str_of(attr, "modelId").filter(|s| !s.is_empty()).unwrap_or(fallback_model).to_owned(); + let auto_compact_threshold = u32_of(attr, "compactionThreshold").filter(|&n| n > 0); + let is_auto_compact_enabled = auto_compact_threshold.map(|_| true); + + let mut categories = Vec::new(); + let entries = attr.get("entries").and_then(Value::as_array).filter(|e| !e.is_empty()); + + if let Some(entries) = entries { + // Any entry referenced via `parentId` is a rollup parent whose children are accounted for individually. + let parent_ids: HashSet<&str> = entries.iter().filter_map(|e| str_of(e, "parentId")).collect(); + let mut system_rows: Vec<(String, u32)> = Vec::new(); + let mut tool_definitions: u32 = 0; + let mut tool_results: u32 = 0; + let mut skills: u32 = 0; + let mut subagents: u32 = 0; + let mut mcp_tools: u32 = 0; + let mut plugins: u32 = 0; + let mut other_user: BTreeMap = BTreeMap::new(); + let mut accounted: u32 = 0; + + for entry in entries { + if let Some(id) = str_of(entry, "id") + && parent_ids.contains(id) + { + continue; + } + let tokens = u32_of(entry, "tokens").unwrap_or(0); + if tokens == 0 { + continue; + } + accounted = accounted.saturating_add(tokens); + match str_of(entry, "kind").unwrap_or_default() { + "system" => { + let label = normalize_system_label(str_of(entry, "label").unwrap_or("System prompt")); + if let Some((_, existing)) = system_rows.iter_mut().find(|(k, _)| k == &label) { + *existing = existing.saturating_add(tokens); + } else { + system_rows.push((label, tokens)); + } + } + "toolDefinition" => tool_definitions = tool_definitions.saturating_add(tokens), + "tool" => tool_results = tool_results.saturating_add(tokens), + "skill" => skills = skills.saturating_add(tokens), + "subagent" => subagents = subagents.saturating_add(tokens), + "mcpServer" => mcp_tools = mcp_tools.saturating_add(tokens), + "plugin" => plugins = plugins.saturating_add(tokens), + kind => { + let label = str_of(entry, "label").filter(|s| !s.is_empty()).unwrap_or(kind).to_owned(); + let slot = other_user.entry(label).or_insert(0); + *slot = slot.saturating_add(tokens); + } + } + } + + for (name, tokens) in system_rows { + categories.push(used_category(name, tokens, "System")); + } + if tool_definitions > 0 { + categories.push(used_category("Tool Definitions", tool_definitions, "System")); + } + if tool_results > 0 { + categories.push(used_category("Tool Results", tool_results, "User Context")); + } + let messages = total_tokens.saturating_sub(accounted); + if messages > 0 { + categories.push(used_category("Messages", messages, "User Context")); + } + if skills > 0 { + categories.push(used_category("Skills", skills, "User Context")); + } + if subagents > 0 { + categories.push(used_category("Sub-agents", subagents, "User Context")); + } + if mcp_tools > 0 { + categories.push(used_category("MCP tools", mcp_tools, "User Context")); + } + if plugins > 0 { + categories.push(used_category("Plugins", plugins, "User Context")); + } + for (name, tokens) in other_user { + categories.push(used_category(name, tokens, "User Context")); + } + } else if let Some(cats) = attr.get("categories").and_then(Value::as_object) { + let get = |k: &str| cats.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0); + let sys_prompt = get("systemPrompt"); + let custom_inst = get("customInstructions"); + let tool_defs = get("systemTools").saturating_add(get("mcpTools")); + let messages = get("messages"); + if sys_prompt > 0 { + categories.push(used_category("System prompt", sys_prompt, "System")); + } + if custom_inst > 0 { + categories.push(used_category("Custom instructions", custom_inst, "System")); + } + if tool_defs > 0 { + categories.push(used_category("Tool Definitions", tool_defs, "System")); + } + if messages > 0 { + categories.push(used_category("Messages", messages, "User Context")); + } + } + + push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens); + Some(AgentContextUsage { + categories, + total_tokens, + max_tokens, + model, + is_auto_compact_enabled, + auto_compact_threshold, + reserved_tokens, + }) +} + +/// Converts Copilot's `session.metadata.contextInfo` payload into [`AgentContextUsage`]. +pub(super) fn context_usage_from_context_info( + res: &Value, + fallback_model: &str, + fallback_limit: Option, +) -> Option { + let info = res.get("contextInfo").unwrap_or(res); + if !info.is_object() { + return None; + } + let total_tokens = u32_of(info, "totalTokens")?; + let max_tokens = u32_of(info, "limit") + .filter(|&n| n > 0) + .or_else(|| u32_of(info, "promptTokenLimit").filter(|&n| n > 0)) + .or_else(|| fallback_limit.filter(|&n| n > 0))?; + let reserved_tokens = u32_of(info, "bufferTokens").filter(|&n| n > 0); + let model = str_of(info, "displayModelName") + .or_else(|| str_of(info, "modelName")) + .filter(|s| !s.is_empty()) + .unwrap_or(fallback_model) + .to_owned(); + let auto_compact_threshold = u32_of(info, "compactionThreshold").filter(|&n| n > 0); + let is_auto_compact_enabled = auto_compact_threshold.map(|_| true); + + let mut categories = Vec::new(); + if let Some(sys) = u32_of(info, "systemTokens").filter(|&n| n > 0) { + categories.push(used_category("System prompt", sys, "System")); + } + if let Some(tools) = u32_of(info, "toolDefinitionsTokens").filter(|&n| n > 0) { + categories.push(used_category("Tool Definitions", tools, "System")); + } + if let Some(conv) = u32_of(info, "conversationTokens").filter(|&n| n > 0) { + categories.push(used_category("Messages", conv, "User Context")); + } + push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens); + Some(AgentContextUsage { + categories, + total_tokens, + max_tokens, + model, + is_auto_compact_enabled, + auto_compact_threshold, + reserved_tokens, + }) +} + +/// Fallback breakdown from the latest `session.usage_info` / compaction snapshot. +pub(super) fn context_usage_from_snapshot(snap: &UsageSnapshot, model: &str) -> AgentContextUsage { + let mut categories = Vec::new(); + if let Some(sys) = snap.system_tokens.filter(|&n| n > 0) { + categories.push(used_category("System prompt", sys, "System")); + } + if let Some(tools) = snap.tool_definitions_tokens.filter(|&n| n > 0) { + categories.push(used_category("Tool Definitions", tools, "System")); + } + if let Some(conv) = snap.conversation_tokens.filter(|&n| n > 0) { + categories.push(used_category("Messages", conv, "User Context")); + } + push_free_space(&mut categories, snap.current_tokens, snap.token_limit, None); + AgentContextUsage { + categories, + total_tokens: snap.current_tokens, + max_tokens: snap.token_limit, + model: model.to_owned(), + is_auto_compact_enabled: None, + auto_compact_threshold: None, + reserved_tokens: None, + } +} + +fn used_category(name: impl Into, tokens: u32, group: &str) -> AgentContextCategory { + AgentContextCategory { name: name.into(), tokens, kind: Some("used".to_owned()), group: Some(group.to_owned()) } +} + +fn push_free_space( + categories: &mut Vec, + total_tokens: u32, + max_tokens: u32, + reserved_tokens: Option, +) { + let free = max_tokens.saturating_sub(total_tokens.saturating_add(reserved_tokens.unwrap_or(0))); + if free > 0 { + categories.push(AgentContextCategory { + name: "Free space".to_owned(), + tokens: free, + kind: Some("free".to_owned()), + group: None, + }); + } +} + +fn normalize_system_label(raw: &str) -> String { + match raw.trim().to_ascii_lowercase().as_str() { + "system prompt" | "system" | "system instructions" => "System prompt".to_owned(), + "custom instructions" => "Custom instructions".to_owned(), + _ => raw.trim().to_owned(), + } +} + +fn u32_of(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()) +} + /// The running entries of a `session.tasks.list` result, in the background-task shape the /// app shows (`task_id`, `task_type`, `description`). pub(super) fn background_tasks(list: &Value) -> Vec { diff --git a/src/bindings.ts b/src/bindings.ts index c27789173c..d4204b4216 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2809,6 +2809,8 @@ export type AgentContextCategory = { name: string, tokens: number, kind: string | null, + /** Visual section group (e.g. `"System"`, `"User Context"`). */ + group?: string | null, }; export type AgentContextUsage = { @@ -2818,11 +2820,13 @@ export type AgentContextUsage = { model: string, isAutoCompactEnabled: boolean | null, autoCompactThreshold: number | null, + /** Tokens reserved for model response / output buffer, when the agent reports it. */ + reservedTokens?: number | null, }; export type AgentCost = { amount: number | null, - /** ISO 4217 code, e.g. `USD`. */ + /** ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing. */ currency: string, }; diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index f918951e53..80de18097b 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -1168,29 +1168,6 @@ font-variant-numeric: tabular-nums; white-space: nowrap; } -.meterSegment { - display: inline-flex; - flex: 0 1 auto; - align-items: center; - min-width: 0; - height: 22px; - gap: var(--space-1-5); -} -.meterGroup { - display: inline-flex; - flex: 0 1 auto; - align-items: center; - min-width: 0; - height: 22px; - gap: var(--space-1-5); -} -.meterDivider { - flex: none; - width: 1px; - height: 11px; - background: var(--border-strong); - opacity: 0.5; -} .meter { display: inline-flex; flex: 0 1 auto; @@ -1200,6 +1177,35 @@ gap: 5px; overflow: hidden; } +.meterContext { + display: inline-flex; + align-items: center; + gap: 5px; +} +.meterInlineDivider { + flex: none; + width: 1px; + height: 11px; + margin: 0 2px; + background: var(--border-strong); + opacity: 0.5; +} +.meterLimitAlerts { + display: inline-flex; + align-items: baseline; +} +.meterLimitAlert { + display: inline-flex; + align-items: baseline; + font-weight: 500; + line-height: 1; +} +.meterAlertDot { + flex: none; + margin: 0 4px; + color: var(--fg-faint); + opacity: 0.65; +} .meterValue { line-height: 1; } @@ -1223,26 +1229,6 @@ stroke-dashoffset 200ms var(--ease), stroke var(--dur-fast) var(--ease); } -.limitsButton { - gap: 0; -} -.limitItem { - display: inline-flex; - align-items: baseline; - gap: 3px; -} -.limitWindow { - color: var(--fg-faint); -} -.limitPercent { - color: inherit; -} -.meterDot { - flex: none; - margin: 0 5px; - color: var(--fg-faint); - opacity: 0.65; -} .images { display: flex; @@ -2007,10 +1993,6 @@ .meterButton[aria-expanded="true"] .usageRingArc { stroke: currentColor; } -.limitsButton:hover .limitWindow, -.limitsButton[aria-expanded="true"] .limitWindow { - color: var(--fg-subtle); -} .meterButton:focus-visible { outline: 1px solid var(--focus-ring); outline-offset: -1px; @@ -2030,23 +2012,12 @@ stroke: currentColor; } .meterWarning .meterValue, -.meterDanger .meterValue, -.meterWarning .limitPercent, -.meterDanger .limitPercent { +.meterDanger .meterValue { font-weight: 500; } -.limitsDetails { - display: grid; - gap: var(--space-2); - width: min(272px, 80vw); - padding: var(--space-3); - color: var(--fg-secondary); - font-size: var(--fs-ui); - font-variant-numeric: tabular-nums; -} .limitsList { display: grid; - gap: var(--space-3); + gap: var(--space-2-5, 10px); } .limitsRow { display: grid; @@ -2123,54 +2094,140 @@ } .contextDetails { display: grid; - gap: var(--space-2); - width: min(330px, 80vw); + gap: var(--space-2-5, 10px); + width: min(296px, 82vw); padding: var(--space-3); color: var(--fg-secondary); font-size: var(--fs-ui); font-variant-numeric: tabular-nums; } -.contextHeading, -.contextDetails li { +.sessionInfoHeader { display: flex; - align-items: center; - gap: var(--space-2); -} -.contextHeading { + align-items: baseline; justify-content: space-between; + gap: var(--space-2); color: var(--fg); } -.contextBar { +.sessionInfoModel { + color: var(--fg-subtle); + font-size: var(--fs-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.sessionInfoRow { display: flex; - height: 6px; + align-items: baseline; + justify-content: space-between; + gap: var(--space-2); +} +.sessionInfoStrong { + color: var(--fg); + font-weight: 600; +} +.sessionInfoValue { + color: var(--fg); + font-size: var(--fs-small); +} +.sessionInfoPercent { + color: var(--fg); + font-weight: 500; +} +.meterWarning .sessionInfoPercent { + color: var(--warning); +} +.meterDanger .sessionInfoPercent { + color: var(--danger); +} +.sessionInfoSection { + display: grid; + gap: var(--space-2); +} +.sessionInfoDivided { + padding-top: var(--space-2-5, 10px); + border-top: 1px solid var(--border); +} +.sessionInfoSectionTitle { + color: var(--fg); + font-weight: 600; + font-size: var(--fs-small); +} +.contextProgressTrack { + display: flex; + height: 5px; border-radius: 3px; overflow: hidden; background: var(--border); } -.contextBar span { - flex-basis: 0; +.contextProgressFill { + display: block; + height: 100%; + background: var(--accent); } -.contextDetails summary { - cursor: default; - color: var(--fg); +.contextProgressFill.meterWarning { + background: var(--warning); } -.contextDetails ul { - margin: var(--space-2) 0 0; - padding: 0; - max-height: 220px; - overflow: auto; +.contextProgressFill.meterDanger { + background: var(--danger); } -.contextDetails li { - padding: var(--space-1) 0; +.contextReservedFill { + display: block; + height: 100%; + background: repeating-linear-gradient(-45deg, var(--accent), var(--accent) 2px, transparent 2px, transparent 4px); + opacity: 0.75; } -.contextDetails li i { - width: 8px; +.contextReservedLegend { + display: inline-flex; + align-items: center; + gap: var(--space-1-5); + color: var(--fg-subtle); + font-size: var(--fs-small); + justify-self: start; +} +.contextReservedSwatch { + width: 10px; height: 8px; border-radius: 2px; + background: repeating-linear-gradient(-45deg, var(--accent), var(--accent) 2px, transparent 2px, transparent 4px); } -.contextDetails li span:last-child { - margin-left: auto; +.contextBreakdownGroup { + display: grid; + gap: var(--space-1); + margin-top: 2px; +} +.contextBreakdownTitle { + color: var(--fg); + font-weight: 600; + font-size: var(--fs-small); +} +.contextBreakdownList { + display: grid; + gap: 3px; + margin: 0; + padding: 0; + list-style: none; +} +.contextBreakdownRow { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-2); + color: var(--fg-secondary); + font-size: var(--fs-small); +} +.contextBreakdownShare { + color: var(--fg); +} +.sessionInfoMuted { + color: var(--fg-subtle); + font-size: var(--fs-small); +} +.sessionInfoError { + margin: 0; + color: var(--danger); + font-size: var(--fs-small); } .contextCompact { - justify-self: end; + width: 100%; + justify-content: center; } diff --git a/src/features/agents/agents.test.ts b/src/features/agents/agents.test.ts index 4ddbf1bfd9..58b334726b 100644 --- a/src/features/agents/agents.test.ts +++ b/src/features/agents/agents.test.ts @@ -38,6 +38,8 @@ import { usageLabel, limitLabel, costLabel, + groupContextCategories, + contextShareLabel, workTime, } from "./composerModel"; import { @@ -566,11 +568,55 @@ describe("usage meters", () => { percent: 7, detail: "spend_limit: 7% used", }); + expect(limitLabel({ window: "premium_interactions", usedPercent: 4, resetsMs: null }, 0)).toEqual({ + short: "Premium 4%", + percent: 4, + detail: "Premium requests: 4% used", + }); }); it("formats the session cost", () => { expect(costLabel({ amount: 0.4231, currency: "USD" })).toBe("$0.42"); - expect(costLabel({ amount: 1.5, currency: "credits" })).toBe("1.50 credits"); + expect(costLabel({ amount: 1.5, currency: "credits" })).toBe("1.5 credits"); + expect(costLabel({ amount: 4211.4, currency: "credits" })).toBe("4,211.4 credits"); + expect(costLabel({ amount: 1.5, currency: "tokens" })).toBe("1.50 tokens"); + }); + + it("groups context categories into System and User Context and formats window share", () => { + const grouped = groupContextCategories([ + { name: "System prompt", tokens: 20_000, kind: "used", group: "System" }, + { name: "Tool Definitions", tokens: 203_000, kind: "used", group: "System" }, + { name: "System tools (deferred)", tokens: 50_000, kind: "deferred", group: null }, + { name: "Tool Results", tokens: 69_000, kind: "used", group: "User Context" }, + { name: "Messages", tokens: 113_200, kind: "used", group: "User Context" }, + { name: "Autocompact buffer", tokens: 32_000, kind: "buffer", group: null }, + { name: "Free space", tokens: 562_800, kind: "free", group: null }, + ]); + expect(grouped.system.map((c) => c.name)).toEqual(["System prompt", "Tool Definitions"]); + expect(grouped.userContext.map((c) => c.name)).toEqual(["Tool Results", "Messages"]); + expect(grouped.bufferTokens).toBe(32_000); + expect(contextShareLabel(20_000, 1_000_000)).toBe("2.0%"); + expect(contextShareLabel(203_000, 1_000_000)).toBe("20.3%"); + expect(contextShareLabel(100, 1_000_000)).toBe("<0.1%"); + }); + + it("skips Claude Code's plain Free space and deferred categories without kind tags", () => { + const grouped = groupContextCategories([ + { name: "System prompt", tokens: 3_100, kind: null }, + { name: "System tools", tokens: 18_400, kind: null }, + { name: "System tools (deferred)", tokens: 4_000, kind: null }, + { name: "MCP tools", tokens: 6_200, kind: null }, + { name: "MCP tools (deferred)", tokens: 1_500, kind: null }, + { name: "Custom agents", tokens: 1_200, kind: null }, + { name: "Memory files", tokens: 900, kind: null }, + { name: "Skills", tokens: 1_600, kind: null }, + { name: "Messages", tokens: 52_600, kind: null }, + { name: "Autocompact buffer", tokens: 33_000, kind: null }, + { name: "Free space", tokens: 83_000, kind: null }, + ]); + expect(grouped.system.map((c) => c.name)).toEqual(["System prompt", "System tools", "MCP tools", "Custom agents"]); + expect(grouped.userContext.map((c) => c.name)).toEqual(["Memory files", "Skills", "Messages"]); + expect(grouped.bufferTokens).toBe(33_000); }); it("adds up the time spent on turns", () => { diff --git a/src/features/agents/composerModel.ts b/src/features/agents/composerModel.ts index 55ac06c902..325c1f4708 100644 --- a/src/features/agents/composerModel.ts +++ b/src/features/agents/composerModel.ts @@ -3,6 +3,7 @@ import type { AgentCommand, AgentCommandChoice, AgentConfigOption, + AgentContextCategory, AgentCost, AgentEntry, AgentImage, @@ -727,8 +728,79 @@ const LIMIT_WINDOWS: Record = { seven_day: { short: "7d", name: "Weekly limit" }, seven_day_opus: { short: "7d Opus", name: "Weekly Opus limit" }, seven_day_sonnet: { short: "7d Sonnet", name: "Weekly Sonnet limit" }, + chat: { short: "Chat", name: "Chat" }, + completions: { short: "Completions", name: "Completions" }, + premium_interactions: { short: "Premium", name: "Premium requests" }, }; +const SYSTEM_CATEGORY_NAMES = new Set([ + "System prompt", + "Custom instructions", + "Tool Definitions", + "System tools", + "System tools (deferred)", + "MCP tools", + "MCP tools (deferred)", + "MCP server instructions", + "Custom agents", +]); + +/** Known user-context categories from Claude Code and Copilot (kept explicit so translations stay active). */ +const USER_CONTEXT_CATEGORY_NAMES = new Set([ + "Tool Results", + "Messages", + "Memory files", + "Skills", + "Sub-agents", + "Plugins", +]); + +const FREE_CATEGORY_NAMES = new Set(["Free space"]); + +/** Splits context categories into `System` and `User Context` sections plus any buffer tokens. */ +export function groupContextCategories(categories: readonly AgentContextCategory[]): { + system: AgentContextCategory[]; + userContext: AgentContextCategory[]; + bufferTokens: number; +} { + const system: AgentContextCategory[] = []; + const userContext: AgentContextCategory[] = []; + let bufferTokens = 0; + for (const c of categories) { + if ( + c.tokens <= 0 || + c.kind === "free" || + c.kind === "deferred" || + FREE_CATEGORY_NAMES.has(c.name) || + c.name.endsWith(" (deferred)") + ) { + continue; + } + if (c.name === "Autocompact buffer") { + bufferTokens += c.tokens; + continue; + } + const group = + c.group ?? + (SYSTEM_CATEGORY_NAMES.has(c.name) + ? "System" + : USER_CONTEXT_CATEGORY_NAMES.has(c.name) + ? "User Context" + : "User Context"); + if (group === "System") system.push(c); + else userContext.push(c); + } + return { system, userContext, bufferTokens }; +} + +/** Share of the context window as a compact percentage ("2.0%", "20.3%", "<0.1%"). */ +export function contextShareLabel(used: number, max: number): string { + if (max <= 0 || used <= 0) return "0.0%"; + const pct = (used / max) * 100; + if (pct < 0.05) return "<0.1%"; + return `${pct.toFixed(1)}%`; +} + /** Visual severity for a usage percentage meter: quiet until nearing the cap. */ export type MeterTone = "warning" | "danger"; @@ -786,8 +858,16 @@ function untilReset(ms: number): string { return `${Math.floor(h / 24)}d ${h % 24}h`; } -/** "$0.42": what the session has cost so far. */ +/** "$0.42" or "4,211.4 credits": what the session has cost so far. */ export function costLabel(c: AgentCost): string { + if (c.currency === "credits") { + const amount = c.amount ?? 0; + const formatted = new Intl.NumberFormat("en-US", { + minimumFractionDigits: amount > 0 && amount < 10 ? 1 : 0, + maximumFractionDigits: 1, + }).format(amount); + return tx`${formatted} credits`; + } try { return new Intl.NumberFormat("en-US", { style: "currency", diff --git a/src/features/agents/session/ContextMeter.tsx b/src/features/agents/session/ContextMeter.tsx index 8263099ef9..6b4c08391c 100644 --- a/src/features/agents/session/ContextMeter.tsx +++ b/src/features/agents/session/ContextMeter.tsx @@ -1,11 +1,27 @@ -import { useEffect, useRef, useState } from "react"; +import { Fragment, useEffect, useRef, useState } from "react"; import clsx from "clsx"; -import type { AgentContextUsage, AgentTask, AgentUsage } from "@/bindings"; +import type { + AgentContextCategory, + AgentContextUsage, + AgentCost, + AgentLimit, + AgentTask, + AgentTokens, + AgentUsage, +} from "@/bindings"; import { call, commands } from "@/platform/ipc"; import { useTx } from "@/platform/i18n"; import { reducedMotion } from "@/platform/motion"; -import { Button, Popup, T, tooltipAttrs } from "@/ui"; -import { meterTone, usageLabel } from "../composerModel"; +import { Button, Icon, Popup, T, tooltipAttrs } from "@/ui"; +import { + contextShareLabel, + costLabel, + groupContextCategories, + limitParts, + meterTone, + turnTokensLabel, + usageLabel, +} from "../composerModel"; import { isBusy } from "../model"; import { resendMessage } from "../store"; import styles from "../Session.module.css"; @@ -13,26 +29,34 @@ import styles from "../Session.module.css"; const RING_RADIUS = 5; const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS; -const categoryTones = new Map([ - ["System prompt", "var(--accent)"], - ["System tools", "var(--warning)"], - ["System tools (deferred)", "var(--fg-muted)"], - ["Custom agents", "var(--info)"], - ["Skills", "var(--success)"], - ["MCP tools", "var(--warning)"], - ["MCP tools (deferred)", "var(--fg-muted)"], - ["MCP server instructions", "var(--warning)"], - ["Messages", "var(--info)"], - ["Memory files", "var(--success)"], - ["Autocompact buffer", "var(--fg-muted)"], - ["Free space", "var(--fg-subtle)"], -]); -const tone = (name: string) => categoryTones.get(name) ?? "var(--fg-muted)"; +function severityClassName(percent: number): string | undefined { + const severity = meterTone(percent); + return severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined; +} -export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsage }) { +export function ContextMeter({ + task, + usage, + limits, + cost, + turnTokens, + now, +}: { + task: AgentTask; + usage: AgentUsage | null; + limits: readonly AgentLimit[]; + cost: AgentCost | null; + turnTokens: AgentTokens | null; + now: number; +}) { const tx = useTx(); - const label = usageLabel(usage); - const hint = tx("Context window") + " · " + label.short; + const label = usage ? usageLabel(usage) : null; + const alertLimits = limits + .map((limit) => ({ window: limit.window, ...limitParts(limit, now) })) + .filter((item) => meterTone(item.percent) !== undefined); + const alertDetails = alertLimits.map((item) => item.detail).join(" · "); + const baseHint = label ? `${tx("Context window")} · ${label.short}` : tx("Session Info"); + const hint = alertDetails ? `${baseHint} · ${alertDetails}` : baseHint; const anchor = useRef(null); const [phase, setPhase] = useState<"closed" | "open" | "closing">("closed"); const open = phase === "open"; @@ -42,55 +66,71 @@ export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsa const timer = window.setTimeout(() => setPhase("closed"), 100); return () => window.clearTimeout(timer); }, [phase]); - const severity = meterTone(label.percent); - const severityClass = - severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined; - const dashOffset = RING_CIRCUMFERENCE * (1 - label.percent / 100); - const meter = ( - <> - - - 0 ? 1 : 0} - transform="rotate(-90 7 7)" - data-percent={label.percent} - /> - - {label.percent}% - - ); - if (!task.capabilities?.contextUsage) - return ( - - {meter} - - ); + + const contextSeverity = label ? meterTone(label.percent) : undefined; + const contextSeverityClass = label ? severityClassName(label.percent) : undefined; + const dashOffset = label ? RING_CIRCUMFERENCE * (1 - label.percent / 100) : RING_CIRCUMFERENCE; + return ( <> - + ); } -function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose: () => void; closing: boolean }) { +function SessionInfoDetails({ + task, + usage, + limits, + cost, + turnTokens, + now, + onClose, + closing, +}: { + task: AgentTask; + usage: AgentUsage | null; + limits: readonly AgentLimit[]; + cost: AgentCost | null; + turnTokens: AgentTokens | null; + now: number; + onClose: () => void; + closing: boolean; +}) { + const canQueryBreakdown = Boolean(usage && task.capabilities?.contextUsage && task.status !== "archived"); const [report, setReport] = useState(null); const [error, setError] = useState(""); const [sending, setSending] = useState(false); const tx = useTx(); + useEffect(() => { + if (!canQueryBreakdown) return; let current = true; call(commands.agentContextUsage(task.id)).then( (value) => { @@ -126,9 +196,23 @@ function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose: return () => { current = false; }; - }, [task.id]); - const summary = report && usageLabel({ used: report.totalTokens, size: report.maxTokens, cost: null }); - const categories = report?.categories ?? []; + }, [canQueryBreakdown, task.id]); + + const effectiveUsed = report?.totalTokens ?? usage?.used ?? 0; + const effectiveMax = report?.maxTokens ?? usage?.size ?? 0; + const summary = effectiveMax > 0 ? usageLabel({ used: effectiveUsed, size: effectiveMax, cost: null }) : null; + const grouped = report ? groupContextCategories(report.categories) : null; + const reservedTokens = report?.reservedTokens ?? (grouped?.bufferTokens || null); + const usedBarPct = effectiveMax > 0 ? Math.max(0, Math.min(100, (effectiveUsed / effectiveMax) * 100)) : 0; + const reservedBarPct = + effectiveMax > 0 && reservedTokens != null && reservedTokens > 0 + ? Math.max(0, Math.min(100 - usedBarPct, (reservedTokens / effectiveMax) * 100)) + : 0; + const limitItems = limits.map((limit) => ({ window: limit.window, ...limitParts(limit, now) })); + const canCompact = Boolean(usage && task.commands.some((c) => c.name === "compact")); + const contextSeverity = summary ? meterTone(summary.percent) : undefined; + const contextSeverityClass = summary ? severityClassName(summary.percent) : undefined; + const compact = async () => { setSending(true); try { @@ -139,71 +223,169 @@ function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose: setSending(false); } }; + return (
-
+
- Context window + Session Info - {summary?.short} + {(report?.model || task.model) && ( + {report?.model || task.model} + )}
- {error && ( -

- {!report && tx("Context details unavailable") + " · "} - {error} -

+ + {cost && ( +
+ + Session Cost + + {costLabel(cost)} +
)} - {!error && !report && ( - - Loading context details… - - )} - {report && ( - <> -
- {categories.map( - (c) => - c.kind !== "deferred" && - c.tokens > 0 && , + + {usage && summary && ( +
+
+ Context Window +
+
+ {summary.detail} + {summary.percent}% +
+
+ + {reservedBarPct > 0 && ( + )}
- {report.model} - {report.isAutoCompactEnabled && report.autoCompactThreshold != null && ( - + {reservedBarPct > 0 && reservedTokens != null && ( + + + + Reserved for response + + + )} + {canQueryBreakdown && error && ( +

+ {!report && tx("Context details unavailable") + " · "} + {error} +

+ )} + {canQueryBreakdown && !error && !report && ( + + Loading context details… + + )} + {grouped && grouped.system.length > 0 && ( + + )} + {grouped && grouped.userContext.length > 0 && ( + + )} + {report?.isAutoCompactEnabled && report.autoCompactThreshold != null && ( + {tx("Auto-compact at {count} tokens").replace("{count}", report.autoCompactThreshold.toLocaleString())} )} -
- - Detailed breakdown - -
    - {categories.map((c) => ( -
  • - - {tx(c.name)} - {c.tokens.toLocaleString()} -
  • - ))} -
-
- {report.isAutoCompactEnabled === false && ( - + {report?.isAutoCompactEnabled === false && ( + Auto-compact is off )} - {task.commands.some((c) => c.name === "compact") && ( - - )} - +
+ )} + + {turnTokens && ( +
+ + Last turn + + {turnTokensLabel(turnTokens)} +
+ )} + + {limitItems.length > 0 && ( +
+
+ Usage limits +
+
+ {limitItems.map((item) => { + const severity = meterTone(item.percent); + const severityClass = severityClassName(item.percent); + return ( +
+
+ {item.name} + {item.percent}% +
+
+ +
+ {item.resetIn && {tx`Resets in ${item.resetIn}`}} +
+ ); + })} +
+
+ )} + + {canCompact && ( + )}
); } + +function BreakdownGroup({ + title, + items, + maxTokens, +}: { + title: "System" | "User Context"; + items: readonly AgentContextCategory[]; + maxTokens: number; +}) { + const tx = useTx(); + return ( +
+
+ {title} +
+
    + {items.map((c) => ( +
  • + {tx(c.name)} + {contextShareLabel(c.tokens, maxTokens)} +
  • + ))} +
+
+ ); +} diff --git a/src/features/agents/session/SessionStatus.tsx b/src/features/agents/session/SessionStatus.tsx index 3145d01c37..cf9f0330f0 100644 --- a/src/features/agents/session/SessionStatus.tsx +++ b/src/features/agents/session/SessionStatus.tsx @@ -1,13 +1,10 @@ -import { Fragment, useEffect, useRef, useState, type ReactNode } from "react"; -import type { AgentChange, AgentCommit, AgentLimit, AgentTask } from "@/bindings"; +import type { AgentChange, AgentCommit, AgentTask } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { useTx } from "@/platform/i18n"; -import { reducedMotion } from "@/platform/motion"; import { basename, useProject } from "@/platform/project"; import clsx from "clsx"; -import { Icon, IconButton, Popup, showContextMenu, T, tooltipAttrs } from "@/ui"; +import { Icon, IconButton, showContextMenu, T } from "@/ui"; import styles from "../Session.module.css"; -import { costLabel, limitParts, meterTone, turnTokensLabel } from "../composerModel"; import { ContextMeter } from "./ContextMeter"; import { formatSentAt } from "../conversation"; import { branchLabel, hasTaskTerminal, isBusy, providerIcon, statusLabel } from "../model"; @@ -154,156 +151,32 @@ export function SessionStatus({ } /** - * Context use, usage limits and cost (when the agent reports them), grouped with subtle - * dividers and controlled by Settings › Tools › Agents › Chat. + * Compact context-window meter in the status bar; clicking it opens the unified + * Session Info popover with cost, context breakdown, last-turn tokens and usage limits. */ function Meters({ task }: { task: AgentTask }) { - const tx = useTx(); const show = useProject((s) => s.settings?.agents); const busy = isBusy(task.status); const now = useNow(60_000); const usage = show?.showContextUsage !== false ? task.usage : null; const reported = useAgents((s) => s.limits.get(task.provider)); const limits = show?.showUsageLimits !== false ? (reported ?? []) : []; - const cost = show?.showCost === true ? task.usage?.cost : null; - const turnTokens = show?.showContextUsage !== false && !busy ? task.stats?.tokens : null; + const cost = show?.showCost === true ? (task.usage?.cost ?? null) : null; + const turnTokens = show?.showContextUsage !== false && !busy ? (task.stats?.tokens ?? null) : null; - const groups: { key: string; node: ReactNode }[] = []; - if (usage || turnTokens) { - groups.push({ - key: "context", - node: ( - - {usage && } - {turnTokens && ( - - {turnTokensLabel(turnTokens)} - - )} - - ), - }); - } - if (limits.length > 0) { - groups.push({ - key: "limits", - node: , - }); - } - if (cost) { - groups.push({ - key: "cost", - node: ( - - {costLabel(cost)} - - ), - }); - } - if (!groups.length) return null; + if (!usage && limits.length === 0 && !cost && !turnTokens) return null; return ( - {groups.map((group, i) => ( - - {i > 0 && } - {group.node} - - ))} + ); } - -/** Compact account usage limits ("5h 77% · 7d 95%") with a click popover for bars and reset times. */ -function LimitsMeter({ limits, now }: { limits: readonly AgentLimit[]; now: number }) { - const tx = useTx(); - const anchor = useRef(null); - const [phase, setPhase] = useState<"closed" | "open" | "closing">("closed"); - const open = phase === "open"; - const close = () => setPhase(reducedMotion() ? "closed" : "closing"); - useEffect(() => { - if (phase !== "closing") return; - const timer = window.setTimeout(() => setPhase("closed"), 100); - return () => window.clearTimeout(timer); - }, [phase]); - - const items = limits.map((limit) => ({ window: limit.window, ...limitParts(limit, now) })); - - return ( - <> - - -
-
- - Usage limits - -
-
- {items.map((item) => { - const severity = meterTone(item.percent); - const severityClass = - severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined; - return ( -
-
- {item.name} - {item.percent}% -
-
- -
- {item.resetIn && {tx`Resets in ${item.resetIn}`}} -
- ); - })} -
-
-
- - ); -} diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index ba3aaf4cc3..94856caa3d 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -2227,25 +2227,89 @@ describe("meters in the task header", () => { useAgents.setState({ limits: new Map() }); }); - it("queries the active task only when context details are opened", async () => { + it("queries the active task only when Session Info is opened and renders System and User Context breakdown", async () => { const { commands } = await import("@/platform/ipc"); + vi.mocked(commands.agentContextUsage).mockResolvedValueOnce({ + status: "ok", + data: { + model: "gemini-4-carbon", + totalTokens: 405_200, + maxTokens: 1_000_000, + reservedTokens: 64_000, + isAutoCompactEnabled: true, + autoCompactThreshold: 800_000, + categories: [ + { name: "System prompt", tokens: 20_000, kind: "used", group: "System" }, + { name: "Tool Definitions", tokens: 203_000, kind: "used", group: "System" }, + { name: "Tool Results", tokens: 69_000, kind: "used", group: "User Context" }, + { name: "Messages", tokens: 113_200, kind: "used", group: "User Context" }, + { name: "Free space", tokens: 530_800, kind: "free", group: null }, + ], + }, + }); const reported: AgentTask = { ...task("A"), capabilities: { contextUsage: true }, - usage: { used: 3000, size: 200000, cost: null }, + commands: [{ name: "compact", description: "Compact", source: "command", hint: null }], + usage: { used: 405_200, size: 1_000_000, cost: null }, }; useAgents.setState({ tasks: new Map([["A", reported]]) }); render(); const meter = await screen.findByRole("button", { name: /^Context window/ }); expect(commands.agentContextUsage).not.toHaveBeenCalled(); fireEvent.click(meter); - expect(await screen.findByText("System tools")).toBeInTheDocument(); + const dialog = await screen.findByRole("dialog", { name: "Session Info" }); expect(commands.agentContextUsage).toHaveBeenCalledWith("A"); - expect(screen.getByText("196,800")).toBeInTheDocument(); + expect(await within(dialog).findByText("System prompt")).toBeInTheDocument(); + expect(within(dialog).getByText("2.0%")).toBeInTheDocument(); + expect(within(dialog).getByText("Tool Definitions")).toBeInTheDocument(); + expect(within(dialog).getByText("20.3%")).toBeInTheDocument(); + expect(within(dialog).getByText("Tool Results")).toBeInTheDocument(); + expect(within(dialog).getByText("6.9%")).toBeInTheDocument(); + expect(within(dialog).getByText("Messages")).toBeInTheDocument(); + expect(within(dialog).getByText("11.3%")).toBeInTheDocument(); + expect(within(dialog).getByText("Reserved for response")).toBeInTheDocument(); + expect(within(dialog).getByRole("button", { name: "Compact Conversation" })).toBeInTheDocument(); fireEvent.keyDown(document, { key: "Escape" }); - expect(screen.queryByRole("dialog", { name: "Context window" })).toBeNull(); + expect(screen.queryByRole("dialog", { name: "Session Info" })).toBeNull(); }); - it("shows the provider's usage limits by default and each meter as Settings › Tools › Agents › Chat allows", async () => { + + it("omits Claude Code's plain Free space category from User Context and maps Autocompact buffer to Reserved for response", async () => { + const { commands } = await import("@/platform/ipc"); + vi.mocked(commands.agentContextUsage).mockResolvedValueOnce({ + status: "ok", + data: { + model: "claude-opus-4-6", + totalTokens: 84_000, + maxTokens: 200_000, + isAutoCompactEnabled: true, + autoCompactThreshold: 167_000, + categories: [ + { name: "System prompt", tokens: 3_100, kind: null }, + { name: "System tools", tokens: 18_400, kind: null }, + { name: "Messages", tokens: 62_500, kind: null }, + { name: "Autocompact buffer", tokens: 33_000, kind: null }, + { name: "Free space", tokens: 83_000, kind: null }, + ], + }, + }); + const reported: AgentTask = { + ...task("A"), + provider: "claude", + capabilities: { contextUsage: true }, + usage: { used: 84_000, size: 200_000, cost: null }, + }; + useAgents.setState({ tasks: new Map([["A", reported]]) }); + render(); + fireEvent.click(await screen.findByRole("button", { name: /^Context window/ })); + const dialog = await screen.findByRole("dialog", { name: "Session Info" }); + expect(await within(dialog).findByText("System tools")).toBeInTheDocument(); + expect(within(dialog).getByText("Messages")).toBeInTheDocument(); + expect(within(dialog).getByText("Reserved for response")).toBeInTheDocument(); + expect(within(dialog).queryByText("Free space")).toBeNull(); + }); + + it("shows only the context ring inline and moves limits, turn tokens, and cost into the Session Info popover", async () => { const reported: AgentTask = { ...task("A"), usage: { @@ -2253,6 +2317,7 @@ describe("meters in the task header", () => { size: 200_000, cost: { amount: 0.42, currency: "USD" }, }, + stats: { tokens: { input: 12_000, cached: 4_000, output: 500 }, compressions: 0 }, }; const limits = [ { window: "five_hour", usedPercent: 19, resetsMs: null }, @@ -2264,14 +2329,23 @@ describe("meters in the task header", () => { }); render(); await screen.findByText("Answer A"); - const usage = screen.getByLabelText(/^Context /); - // The ring and percent show; the counts are in its label and tooltip. + const usage = screen.getByRole("button", { name: /^Context window/ }); + // Only the context ring and percent appear inline; limits, turn tokens, and cost live in the popover. expect(usage).toHaveTextContent("12%"); expect(usage).toHaveAccessibleName(/24k\/200k \(12%\)/); expect(usage.querySelector(`.${styles.usageRingArc}`)).toHaveAttribute("data-percent", "12"); - expect(screen.getByLabelText("5-hour limit: 19% used")).toHaveTextContent("5h 19%"); - expect(screen.getByLabelText("Weekly limit: 9% used")).toHaveTextContent("7d 9%"); + expect(screen.queryByText("5h 19%")).toBeNull(); + expect(screen.queryByText("7d 9%")).toBeNull(); expect(screen.queryByText("$0.42")).toBeNull(); + + fireEvent.click(usage); + const dialog = await screen.findByRole("dialog", { name: "Session Info" }); + expect(within(dialog).getByText("5-hour limit")).toBeInTheDocument(); + expect(within(dialog).getByText("Weekly limit")).toBeInTheDocument(); + expect(within(dialog).getByText("in 12k · cached 4k · out 500")).toBeInTheDocument(); + expect(within(dialog).queryByText("$0.42")).toBeNull(); + fireEvent.keyDown(document, { key: "Escape" }); + act(() => useProject.setState({ settings: { @@ -2283,12 +2357,48 @@ describe("meters in the task header", () => { }, }), ); - expect(screen.queryByText("24k/200k (12%)")).toBeNull(); - expect(screen.queryByLabelText("5-hour limit: 19% used")).toBeNull(); - expect(screen.getByText("$0.42")).toBeInTheDocument(); + const infoButton = screen.getByRole("button", { name: "Session Info" }); + fireEvent.click(infoButton); + const costOnly = await screen.findByRole("dialog", { name: "Session Info" }); + expect(within(costOnly).getByText("$0.42")).toBeInTheDocument(); + expect(within(costOnly).queryByText("5-hour limit")).toBeNull(); + expect(within(costOnly).queryByText("Context Window")).toBeNull(); }); - it("colors meters at warning/danger thresholds and opens usage-limit details on click", async () => { + it("keeps warning/danger usage limits visible inline next to a neutral context meter while hiding safe limits in Session Info", async () => { + const reported: AgentTask = { + ...task("A"), + usage: { used: 84_000, size: 200_000, cost: null }, + }; + const limits = [ + { window: "five_hour", usedPercent: 92, resetsMs: Date.now() + 2 * 3_600_000 }, + { window: "seven_day", usedPercent: 40, resetsMs: null }, + ]; + useAgents.setState({ + tasks: new Map([["A", reported]]), + limits: new Map([["codex", limits]]), + }); + render(); + await screen.findByText("Answer A"); + + const trigger = screen.getByRole("button", { name: /^Context window/ }); + expect(trigger).not.toHaveAttribute("data-tone"); + expect(trigger).toHaveTextContent("42%"); + const fiveHourInline = within(trigger).getByLabelText(/^5-hour limit: 92% used/); + expect(fiveHourInline).toHaveTextContent("5h 92%"); + expect(fiveHourInline).toHaveAttribute("data-tone", "warning"); + expect(within(trigger).queryByText(/7d/)).toBeNull(); + + fireEvent.click(trigger); + const dialog = await screen.findByRole("dialog", { name: "Session Info" }); + const fiveHourRow = within(dialog).getByText("5-hour limit").closest("[data-tone]"); + expect(fiveHourRow).toHaveAttribute("data-tone", "warning"); + expect(within(dialog).getByText("Weekly limit")).toBeInTheDocument(); + fireEvent.keyDown(document, { key: "Escape" }); + expect(screen.queryByRole("dialog", { name: "Session Info" })).toBeNull(); + }); + + it("colors the context meter and danger usage-limit rows at their own thresholds", async () => { const reported: AgentTask = { ...task("A"), usage: { used: 164_000, size: 200_000, cost: null }, @@ -2304,20 +2414,19 @@ describe("meters in the task header", () => { render(); await screen.findByText("Answer A"); - expect(screen.getByLabelText(/^Context /)).toHaveAttribute("data-tone", "warning"); - const fiveHour = screen.getByLabelText(/^5-hour limit: 82% used/); - const sevenDay = screen.getByLabelText("Weekly limit: 95% used"); - expect(fiveHour).toHaveTextContent("5h 82%"); - expect(fiveHour).toHaveAttribute("data-tone", "warning"); - expect(sevenDay).toHaveTextContent("7d 95%"); - expect(sevenDay).toHaveAttribute("data-tone", "danger"); + const trigger = screen.getByRole("button", { name: /^Context window/ }); + expect(trigger).toHaveAttribute("data-tone", "warning"); + expect(within(trigger).getByLabelText(/^5-hour limit: 82% used/)).toHaveAttribute("data-tone", "warning"); + expect(within(trigger).getByLabelText("Weekly limit: 95% used")).toHaveAttribute("data-tone", "danger"); - fireEvent.click(screen.getByRole("button", { name: "Usage limits" })); - expect(await screen.findByRole("dialog", { name: "Usage limits" })).toBeInTheDocument(); - expect(screen.getByText("5-hour limit")).toBeInTheDocument(); - expect(screen.getByText("Weekly limit")).toBeInTheDocument(); + fireEvent.click(trigger); + const dialog = await screen.findByRole("dialog", { name: "Session Info" }); + const fiveHourRow = within(dialog).getByText("5-hour limit").closest("[data-tone]"); + const sevenDayRow = within(dialog).getByText("Weekly limit").closest("[data-tone]"); + expect(fiveHourRow).toHaveAttribute("data-tone", "warning"); + expect(sevenDayRow).toHaveAttribute("data-tone", "danger"); fireEvent.keyDown(document, { key: "Escape" }); - expect(screen.queryByRole("dialog", { name: "Usage limits" })).toBeNull(); + expect(screen.queryByRole("dialog", { name: "Session Info" })).toBeNull(); }); it("toggles fitWidth on the session root and remeasures off-screen rows from settings.agents.fitWindowWidth", async () => { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 9695b3f5d5..d1e13f228b 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -323,9 +323,7 @@ "Context details unavailable": "Context details unavailable", "Loading context details…": "Loading context details…", "Auto-compact at {count} tokens": "Auto-compact at {count} tokens", - "Detailed breakdown": "Detailed breakdown", "Auto-compact is off": "Auto-compact is off", - "Compact session": "Compact session", "System prompt": "System prompt", "System tools": "System tools", "Free space": "Free space", @@ -4388,6 +4386,20 @@ "Gutter": "Gutter", "Highlight modified lines in the gutter": "Highlight modified lines in the gutter", "Highlight modified lines in error stripe on the scrollbar": "Highlight modified lines in error stripe on the scrollbar", + "{formatted} credits": "{formatted} credits", + "Session Info": "Session Info", + "Session Cost": "Session Cost", + "Context Window": "Context Window", + "Reserved for response": "Reserved for response", + "System": "System", + "User Context": "User Context", + "Tool Definitions": "Tool Definitions", + "Tool Results": "Tool Results", + "Custom instructions": "Custom instructions", + "Sub-agents": "Sub-agents", + "Last turn": "Last turn", + "Compact Conversation": "Compact Conversation", + "Premium requests": "Premium requests", "Unique": "Unique", "Key columns": "Key columns", "Add Unique Key": "Add Unique Key", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 203a75ffb2..955e6aa5a2 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -6192,5 +6192,19 @@ "Context": "Contexto", "Allow all optional permissions": "Permitir todos los permisos opcionales", "Get from Version Control": "Obtener del control de versiones", - "Cannot connect to the remote host": "No se puede conectar al host remoto" + "Cannot connect to the remote host": "No se puede conectar al host remoto", + "{formatted} credits": "{formatted} créditos", + "Session Info": "Información de la sesión", + "Session Cost": "Costo de la sesión", + "Context Window": "Ventana de contexto", + "Reserved for response": "Reservado para la respuesta", + "System": "Sistema", + "User Context": "Contexto del usuario", + "Tool Definitions": "Definiciones de herramientas", + "Tool Results": "Resultados de herramientas", + "Custom instructions": "Instrucciones personalizadas", + "Sub-agents": "Subagentes", + "Last turn": "Último turno", + "Compact Conversation": "Compactar conversación", + "Premium requests": "Solicitudes premium" } diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index b30c915686..78cdb5c807 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5836,5 +5836,19 @@ "Context": "Contexte", "Allow all optional permissions": "Autoriser toutes les autorisations facultatives", "Get from Version Control": "Récupérer depuis le contrôle de version", - "Cannot connect to the remote host": "Impossible de se connecter à l’hôte distant" + "Cannot connect to the remote host": "Impossible de se connecter à l’hôte distant", + "{formatted} credits": "{formatted} crédits", + "Session Info": "Informations de session", + "Session Cost": "Coût de la session", + "Context Window": "Fenêtre de contexte", + "Reserved for response": "Réservé pour la réponse", + "System": "Système", + "User Context": "Contexte utilisateur", + "Tool Definitions": "Définitions d’outils", + "Tool Results": "Résultats d’outils", + "Custom instructions": "Instructions personnalisées", + "Sub-agents": "Sous-agents", + "Last turn": "Dernier tour", + "Compact Conversation": "Compacter la conversation", + "Premium requests": "Requêtes premium" } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 96cdf7f0cd..aa2e00978f 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -6301,5 +6301,19 @@ "Context": "컨텍스트", "Allow all optional permissions": "모든 선택 권한 허용", "Get from Version Control": "버전 관리에서 가져오기", - "Cannot connect to the remote host": "원격 호스트에 연결할 수 없음" + "Cannot connect to the remote host": "원격 호스트에 연결할 수 없음", + "{formatted} credits": "{formatted} 크레딧", + "Session Info": "세션 정보", + "Session Cost": "세션 비용", + "Context Window": "컨텍스트 창", + "Reserved for response": "응답용 예약", + "System": "시스템", + "User Context": "사용자 컨텍스트", + "Tool Definitions": "도구 정의", + "Tool Results": "도구 결과", + "Custom instructions": "사용자 지정 지침", + "Sub-agents": "하위 에이전트", + "Last turn": "마지막 턴", + "Compact Conversation": "대화 압축", + "Premium requests": "프리미엄 요청" } diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index a0f44f54b5..039edb7bcd 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -6000,5 +6000,19 @@ "Context": "Kontekst", "Allow all optional permissions": "Zezwól na wszystkie opcjonalne uprawnienia", "Get from Version Control": "Pobierz z systemu kontroli wersji", - "Cannot connect to the remote host": "Nie można połączyć się z hostem zdalnym" + "Cannot connect to the remote host": "Nie można połączyć się z hostem zdalnym", + "{formatted} credits": "{formatted} kredytów", + "Session Info": "Informacje o sesji", + "Session Cost": "Koszt sesji", + "Context Window": "Okno kontekstu", + "Reserved for response": "Zarezerwowane na odpowiedź", + "System": "System", + "User Context": "Kontekst użytkownika", + "Tool Definitions": "Definicje narzędzi", + "Tool Results": "Wyniki narzędzi", + "Custom instructions": "Instrukcje niestandardowe", + "Sub-agents": "Podagenci", + "Last turn": "Ostatnia tura", + "Compact Conversation": "Skompresuj rozmowę", + "Premium requests": "Żądania premium" } diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index a38c0f7e47..8a830af9eb 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -6015,5 +6015,19 @@ "Context": "Contexto", "Allow all optional permissions": "Permitir todas as permissões opcionais", "Get from Version Control": "Obter do controle de versão", - "Cannot connect to the remote host": "Não é possível conectar ao host remoto" + "Cannot connect to the remote host": "Não é possível conectar ao host remoto", + "{formatted} credits": "{formatted} créditos", + "Session Info": "Informações da sessão", + "Session Cost": "Custo da sessão", + "Context Window": "Janela de contexto", + "Reserved for response": "Reservado para resposta", + "System": "Sistema", + "User Context": "Contexto do usuário", + "Tool Definitions": "Definições de ferramentas", + "Tool Results": "Resultados de ferramentas", + "Custom instructions": "Instruções personalizadas", + "Sub-agents": "Subagentes", + "Last turn": "Último turno", + "Compact Conversation": "Compactar conversa", + "Premium requests": "Solicitações premium" } diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 6a9e85f313..09930717c6 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -214,9 +214,7 @@ "Context details unavailable": "Сведения о контексте недоступны", "Loading context details…": "Загрузка сведений о контексте…", "Auto-compact at {count} tokens": "Автосжатие при {count} токенах", - "Detailed breakdown": "Подробная разбивка", "Auto-compact is off": "Автосжатие отключено", - "Compact session": "Сжать сессию", "System prompt": "Системный промпт", "System tools": "Системные инструменты", "Free space": "Свободное место", @@ -10195,5 +10193,19 @@ "Pull request link {text}": "Ссылка на pull request {text}", "Issue link {text}": "Ссылка на issue {text}", "Commit link {text}": "Ссылка на коммит {text}", - "Link {text}": "Ссылка {text}" + "Link {text}": "Ссылка {text}", + "{formatted} credits": "{formatted} кредитов", + "Session Info": "Сведения о сессии", + "Session Cost": "Стоимость сессии", + "Context Window": "Контекстное окно", + "Reserved for response": "Зарезервировано для ответа", + "System": "Система", + "User Context": "Контекст пользователя", + "Tool Definitions": "Определения инструментов", + "Tool Results": "Результаты инструментов", + "Custom instructions": "Пользовательские инструкции", + "Sub-agents": "Субагенты", + "Last turn": "Последний ход", + "Compact Conversation": "Сжать диалог", + "Premium requests": "Премиум-запросы" } diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index b4ae9e7ea5..b06d118f4f 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -18,9 +18,7 @@ "Context details unavailable": "Bağlam ayrıntıları kullanılamıyor", "Loading context details…": "Bağlam ayrıntıları yükleniyor…", "Auto-compact at {count} tokens": "{count} token düzeyinde otomatik sıkıştır", - "Detailed breakdown": "Ayrıntılı döküm", "Auto-compact is off": "Otomatik sıkıştırma kapalı", - "Compact session": "Oturumu sıkıştır", "System prompt": "Sistem istemi", "System tools": "Sistem araçları", "Free space": "Boş alan", @@ -8853,5 +8851,19 @@ "Pull request link {text}": "{text} pull request bağlantısı", "Issue link {text}": "{text} issue bağlantısı", "Commit link {text}": "{text} commit bağlantısı", - "Link {text}": "{text} bağlantısı" + "Link {text}": "{text} bağlantısı", + "{formatted} credits": "{formatted} kredi", + "Session Info": "Oturum Bilgisi", + "Session Cost": "Oturum Maliyeti", + "Context Window": "Bağlam Penceresi", + "Reserved for response": "Yanıt için ayrıldı", + "System": "Sistem", + "User Context": "Kullanıcı Bağlamı", + "Tool Definitions": "Araç Tanımları", + "Tool Results": "Araç Sonuçları", + "Custom instructions": "Özel talimatlar", + "Sub-agents": "Alt aracılar", + "Last turn": "Son tur", + "Compact Conversation": "Konuşmayı Sıkıştır", + "Premium requests": "Premium istekler" } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index f8440109d5..822179cbed 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -13,9 +13,7 @@ "Context details unavailable": "無法取得上下文明細", "Loading context details…": "正在讀取上下文明細…", "Auto-compact at {count} tokens": "達到 {count} tokens 時自動壓縮", - "Detailed breakdown": "檢視詳細構成", "Auto-compact is off": "已關閉自動壓縮", - "Compact session": "壓縮工作階段", "System prompt": "系統提示", "System tools": "系統工具", "Free space": "剩餘空間", @@ -9427,5 +9425,19 @@ "Issue link {text}": "Issue 連結 {text}", "Commit link {text}": "提交連結 {text}", "Link {text}": "連結 {text}", - "No safe lint fixes to apply": "沒有可套用的安全 lint 修正" + "No safe lint fixes to apply": "沒有可套用的安全 lint 修正", + "{formatted} credits": "{formatted} 點數", + "Session Info": "工作階段資訊", + "Session Cost": "工作階段費用", + "Context Window": "上下文視窗", + "Reserved for response": "為回應保留", + "System": "系統", + "User Context": "使用者上下文", + "Tool Definitions": "工具定義", + "Tool Results": "工具結果", + "Custom instructions": "自訂指令", + "Sub-agents": "子代理", + "Last turn": "上一輪", + "Compact Conversation": "壓縮對話", + "Premium requests": "進階請求" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 6835856762..a5d9d21104 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -238,9 +238,7 @@ "Context details unavailable": "无法获取上下文明细", "Loading context details…": "正在读取上下文明细…", "Auto-compact at {count} tokens": "达到 {count} tokens 时自动压缩", - "Detailed breakdown": "查看详细构成", "Auto-compact is off": "已关闭自动压缩", - "Compact session": "压缩会话", "System prompt": "系统提示", "System tools": "系统工具", "Free space": "剩余空间", @@ -10915,6 +10913,20 @@ "Install django-types to complete Django model fields and managers": "安装 django-types 以补全 Django 模型字段和管理器", "Installing django-types": "正在安装 django-types", "Cannot install django-types": "无法安装 django-types", + "{formatted} credits": "{formatted} 积分", + "Session Info": "会话信息", + "Session Cost": "会话费用", + "Context Window": "上下文窗口", + "Reserved for response": "为响应保留", + "System": "系统", + "User Context": "用户上下文", + "Tool Definitions": "工具定义", + "Tool Results": "工具结果", + "Custom instructions": "自定义指令", + "Sub-agents": "子代理", + "Last turn": "上一轮", + "Compact Conversation": "压缩对话", + "Premium requests": "高级请求", "Unique": "唯一", "Key columns": "键列", "Add Unique Key": "添加唯一键",