feat(agents): consolidate session stats into Session Info popover with Copilot context breakdown

Цей коміт міститься в:
Deng Liu committed 2026-11-27 10:52:17 -08:00
1 джерело e08de6771d
коміт a2ac3557fd
22 files changed
+1516 -420

No files matched your search

+9 -1
Переглянути файл
@@ -4298,7 +4298,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,
+7 -1
Переглянути файл
@@ -289,6 +289,9 @@ pub struct AgentContextUsage {
pub model: String,
pub is_auto_compact_enabled: Option<bool>,
pub auto_compact_threshold: Option<u32>,
/// Tokens reserved for model response / output buffer, when the agent reports it.
#[serde(default)]
pub reserved_tokens: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -296,13 +299,16 @@ pub struct AgentContextCategory {
pub name: String,
pub tokens: u32,
pub kind: Option<String>,
/// Visual section group (e.g. `"System"`, `"User Context"`).
#[serde(default)]
pub group: Option<String>,
}
#[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,
}
+185 -7
Переглянути файл
@@ -522,6 +522,7 @@ impl CopilotShim {
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
"_openidea/context_usage" => self.context_usage(&params).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close_session(&params).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<Self>, 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<Self>, 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<Value, ResponseError> {
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<Value, ResponseError> {
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<Value, ResponseError> {
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<Option<&str>> {
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<Value>, Vec<PathBuf>) {
let mut text_parts = Vec::new();
let mut attachments = Vec::new();
+259
Переглянути файл
@@ -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();
@@ -795,3 +832,225 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
}
}
#[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<_>>(),
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));
}
+340 -19
Переглянути файл
@@ -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<u32>,
pub tool_definitions_tokens: Option<u32>,
pub conversation_tokens: Option<u32>,
}
#[derive(Default)]
pub(super) struct EventTranslator {
@@ -18,6 +29,11 @@ pub(super) struct EventTranslator {
subagents: HashMap<String, String>,
/// Last reported prompt token count, used when updating context size.
pub last_used_tokens: Option<u32>,
/// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent.
pub last_usage_snapshot: Option<UsageSnapshot>,
/// 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<u32>) -> 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" {
@@ -573,9 +651,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<u32>,
) -> Option<AgentContextUsage> {
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<String, u32> = 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<u32>,
) -> Option<AgentContextUsage> {
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<String>, 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<AgentContextCategory>,
total_tokens: u32,
max_tokens: u32,
reserved_tokens: Option<u32>,
) {
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<u32> {
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<Value> {
+5 -1
Переглянути файл
@@ -2801,6 +2801,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 = {
@@ -2810,11 +2812,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,
};
+115 -87
Переглянути файл
@@ -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;
@@ -1223,26 +1200,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 +1964,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 +1983,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 +2065,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: 6px;
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: 4px;
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;
}
+28 -1
Переглянути файл
@@ -34,6 +34,8 @@ import {
usageLabel,
limitLabel,
costLabel,
groupContextCategories,
contextShareLabel,
workTime,
} from "./composerModel";
import {
@@ -442,11 +444,36 @@ 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("adds up the time spent on turns", () => {
+71 -1
Переглянути файл
@@ -2,6 +2,7 @@
import type {
AgentCommand,
AgentConfigOption,
AgentContextCategory,
AgentCost,
AgentEntry,
AgentImage,
@@ -598,8 +599,69 @@ const LIMIT_WINDOWS: Record<string, { short: string; name: string }> = {
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",
]);
/** 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") 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";
@@ -657,8 +719,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",
+266 -113
Переглянути файл
@@ -1,11 +1,27 @@
import { 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,29 @@ 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 hint = label ? `${tx("Context window")} · ${label.short}` : tx("Session Info");
const anchor = useRef<HTMLButtonElement>(null);
const [phase, setPhase] = useState<"closed" | "open" | "closing">("closed");
const open = phase === "open";
@@ -42,41 +61,13 @@ 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 = (
<>
<svg className={styles.usageRing} viewBox="0 0 14 14" aria-hidden>
<circle className={styles.usageRingTrack} cx="7" cy="7" r={RING_RADIUS} />
<circle
className={styles.usageRingArc}
cx="7"
cy="7"
r={RING_RADIUS}
strokeDasharray={RING_CIRCUMFERENCE}
strokeDashoffset={dashOffset}
strokeOpacity={label.percent > 0 ? 1 : 0}
transform="rotate(-90 7 7)"
data-percent={label.percent}
/>
</svg>
<span className={styles.meterValue}>{label.percent}%</span>
</>
);
if (!task.capabilities?.contextUsage)
return (
<span
tabIndex={0}
className={clsx(styles.meter, severityClass)}
data-tone={severity}
aria-label={hint}
{...tooltipAttrs(hint, undefined, true)}
>
{meter}
</span>
);
const worstLimitPercent = limits.reduce((max, l) => Math.max(max, Math.round(l.usedPercent ?? 0)), 0);
const triggerPercent = label ? label.percent : worstLimitPercent;
const severity = meterTone(triggerPercent);
const severityClass = severityClassName(triggerPercent);
const dashOffset = label ? RING_CIRCUMFERENCE * (1 - label.percent / 100) : RING_CIRCUMFERENCE;
return (
<>
<button
@@ -90,7 +81,27 @@ export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsa
{...tooltipAttrs(open ? undefined : hint, undefined, true)}
onClick={() => (open ? close() : setPhase("open"))}
>
{meter}
{label ? (
<>
<svg className={styles.usageRing} viewBox="0 0 14 14" aria-hidden>
<circle className={styles.usageRingTrack} cx="7" cy="7" r={RING_RADIUS} />
<circle
className={styles.usageRingArc}
cx="7"
cy="7"
r={RING_RADIUS}
strokeDasharray={RING_CIRCUMFERENCE}
strokeDashoffset={dashOffset}
strokeOpacity={label.percent > 0 ? 1 : 0}
transform="rotate(-90 7 7)"
data-percent={label.percent}
/>
</svg>
<span className={styles.meterValue}>{label.percent}%</span>
</>
) : (
<Icon name="info" size={13} />
)}
</button>
<Popup
open={phase !== "closed"}
@@ -99,21 +110,51 @@ export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsa
placement="top-end"
trapFocus={open}
role={open ? "dialog" : "presentation"}
aria-label={tx("Context window")}
aria-label={tx("Session Info")}
className={phase === "closing" ? styles.contextClosing : styles.contextPopover}
>
<ContextDetails task={task} onClose={close} closing={!open} />
<SessionInfoDetails
task={task}
usage={usage}
limits={limits}
cost={cost}
turnTokens={turnTokens}
now={now}
onClose={close}
closing={!open}
/>
</Popup>
</>
);
}
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<AgentContextUsage | null>(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 +167,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 +194,169 @@ function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose:
setSending(false);
}
};
return (
<div className={styles.contextDetails} inert={closing}>
<div className={styles.contextHeading}>
<div className={styles.sessionInfoHeader}>
<strong>
<T>Context window</T>
<T>Session Info</T>
</strong>
<span>{summary?.short}</span>
{(report?.model || task.model) && (
<span className={styles.sessionInfoModel}>{report?.model || task.model}</span>
)}
</div>
{error && (
<p role="alert">
{!report && tx("Context details unavailable") + " · "}
{error}
</p>
{cost && (
<div
className={styles.sessionInfoRow}
{...tooltipAttrs(tx("What the session has cost so far, as the agent reports it"), undefined, true)}
>
<span>
<T>Session Cost</T>
</span>
<strong className={styles.sessionInfoStrong}>{costLabel(cost)}</strong>
</div>
)}
{!error && !report && (
<span role="status">
<T>Loading context details…</T>
</span>
)}
{report && (
<>
<div className={styles.contextBar} aria-hidden>
{categories.map(
(c) =>
c.kind !== "deferred" &&
c.tokens > 0 && <span key={c.name} style={{ flexGrow: c.tokens, background: tone(c.name) }} />,
{usage && summary && (
<div className={styles.sessionInfoSection}>
<div className={styles.sessionInfoSectionTitle}>
<T>Context Window</T>
</div>
<div className={clsx(styles.sessionInfoRow, contextSeverityClass)} data-tone={contextSeverity}>
<span>{summary.detail}</span>
<span className={styles.sessionInfoPercent}>{summary.percent}%</span>
</div>
<div className={styles.contextProgressTrack} aria-hidden>
<span
className={clsx(styles.contextProgressFill, contextSeverityClass)}
style={{ width: `${usedBarPct}%` }}
/>
{reservedBarPct > 0 && (
<span className={styles.contextReservedFill} style={{ width: `${reservedBarPct}%` }} />
)}
</div>
<span>{report.model}</span>
{report.isAutoCompactEnabled && report.autoCompactThreshold != null && (
<span>
{reservedBarPct > 0 && reservedTokens != null && (
<span
className={styles.contextReservedLegend}
{...tooltipAttrs(
tx("{tokens} tokens").replace("{tokens}", reservedTokens.toLocaleString()),
undefined,
true,
)}
>
<i className={styles.contextReservedSwatch} aria-hidden />
<span>
<T>Reserved for response</T>
</span>
</span>
)}
{canQueryBreakdown && error && (
<p className={styles.sessionInfoError} role="alert">
{!report && tx("Context details unavailable") + " · "}
{error}
</p>
)}
{canQueryBreakdown && !error && !report && (
<span className={styles.sessionInfoMuted} role="status">
<T>Loading context details…</T>
</span>
)}
{grouped && grouped.system.length > 0 && (
<BreakdownGroup title="System" items={grouped.system} maxTokens={effectiveMax} />
)}
{grouped && grouped.userContext.length > 0 && (
<BreakdownGroup title="User Context" items={grouped.userContext} maxTokens={effectiveMax} />
)}
{report?.isAutoCompactEnabled && report.autoCompactThreshold != null && (
<span className={styles.sessionInfoMuted}>
{tx("Auto-compact at {count} tokens").replace("{count}", report.autoCompactThreshold.toLocaleString())}
</span>
)}
<details>
<summary>
<T>Detailed breakdown</T>
</summary>
<ul>
{categories.map((c) => (
<li key={c.name}>
<i aria-hidden style={{ background: tone(c.name) }} />
<span>{tx(c.name)}</span>
<span>{c.tokens.toLocaleString()}</span>
</li>
))}
</ul>
</details>
{report.isAutoCompactEnabled === false && (
<span>
{report?.isAutoCompactEnabled === false && (
<span className={styles.sessionInfoMuted}>
<T>Auto-compact is off</T>
</span>
)}
{task.commands.some((c) => c.name === "compact") && (
<Button
size="small"
className={styles.contextCompact}
disabled={sending || isBusy(task.status)}
onClick={() => void compact()}
>
<T>Compact session</T>
</Button>
)}
</>
</div>
)}
{turnTokens && (
<div className={styles.sessionInfoRow} {...tooltipAttrs(tx("Tokens of the last turn"), undefined, true)}>
<span>
<T>Last turn</T>
</span>
<span className={styles.sessionInfoValue}>{turnTokensLabel(turnTokens)}</span>
</div>
)}
{limitItems.length > 0 && (
<div className={clsx(styles.sessionInfoSection, (usage || cost || turnTokens) && styles.sessionInfoDivided)}>
<div className={styles.sessionInfoSectionTitle}>
<T>Usage limits</T>
</div>
<div className={styles.limitsList}>
{limitItems.map((item) => {
const severity = meterTone(item.percent);
const severityClass = severityClassName(item.percent);
return (
<div key={item.window} className={clsx(styles.limitsRow, severityClass)} data-tone={severity}>
<div className={styles.limitsRowHeader}>
<span className={styles.limitsRowName}>{item.name}</span>
<span className={styles.limitsRowPercent}>{item.percent}%</span>
</div>
<div className={styles.limitsTrack} aria-hidden>
<span className={styles.limitsFill} style={{ width: `${item.percent}%` }} />
</div>
{item.resetIn && <span className={styles.limitsReset}>{tx`Resets in ${item.resetIn}`}</span>}
</div>
);
})}
</div>
</div>
)}
{canCompact && (
<Button
size="small"
className={styles.contextCompact}
disabled={sending || isBusy(task.status)}
onClick={() => void compact()}
>
<T>Compact Conversation</T>
</Button>
)}
</div>
);
}
function BreakdownGroup({
title,
items,
maxTokens,
}: {
title: "System" | "User Context";
items: readonly AgentContextCategory[];
maxTokens: number;
}) {
const tx = useTx();
return (
<div className={styles.contextBreakdownGroup}>
<div className={styles.contextBreakdownTitle}>
<T>{title}</T>
</div>
<ul className={styles.contextBreakdownList}>
{items.map((c) => (
<li
key={c.name}
className={styles.contextBreakdownRow}
{...tooltipAttrs(tx("{tokens} tokens").replace("{tokens}", c.tokens.toLocaleString()), undefined, true)}
>
<span>{tx(c.name)}</span>
<span className={styles.contextBreakdownShare}>{contextShareLabel(c.tokens, maxTokens)}</span>
</li>
))}
</ul>
</div>
);
}
+16 -143
Переглянути файл
@@ -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: (
<span className={styles.meterGroup}>
{usage && <ContextMeter key={task.id} task={task} usage={usage} />}
{turnTokens && (
<span className={styles.meter} {...tooltipAttrs(tx("Tokens of the last turn"), undefined, true)}>
{turnTokensLabel(turnTokens)}
</span>
)}
</span>
),
});
}
if (limits.length > 0) {
groups.push({
key: "limits",
node: <LimitsMeter limits={limits} now={now} />,
});
}
if (cost) {
groups.push({
key: "cost",
node: (
<span
className={styles.meter}
{...tooltipAttrs(tx("What the session has cost so far, as the agent reports it"), undefined, true)}
>
{costLabel(cost)}
</span>
),
});
}
if (!groups.length) return null;
if (!usage && limits.length === 0 && !cost && !turnTokens) return null;
return (
<span className={styles.meters}>
{groups.map((group, i) => (
<span key={group.key} className={styles.meterSegment}>
{i > 0 && <span className={styles.meterDivider} aria-hidden />}
{group.node}
</span>
))}
<ContextMeter
key={task.id}
task={task}
usage={usage}
limits={limits}
cost={cost}
turnTokens={turnTokens}
now={now}
/>
</span>
);
}
/** 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<HTMLButtonElement>(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 (
<>
<button
type="button"
ref={anchor}
className={clsx(styles.meterButton, styles.limitsButton)}
aria-label={tx("Usage limits")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={() => (open ? close() : setPhase("open"))}
>
{items.map((item, i) => {
const severity = meterTone(item.percent);
const severityClass =
severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined;
return (
<Fragment key={item.window}>
{i > 0 && (
<span className={styles.meterDot} aria-hidden>
·
</span>
)}
<span
className={clsx(styles.limitItem, severityClass)}
data-tone={severity}
aria-label={item.detail}
{...tooltipAttrs(open ? undefined : item.detail, undefined, true)}
>
<span className={styles.limitWindow}>{item.windowShort}</span>{" "}
<span className={styles.limitPercent}>{item.percent}%</span>
</span>
</Fragment>
);
})}
</button>
<Popup
open={phase !== "closed"}
onClose={close}
anchor={anchor}
placement="top-end"
trapFocus={open}
role={open ? "dialog" : "presentation"}
aria-label={tx("Usage limits")}
className={phase === "closing" ? styles.contextClosing : styles.contextPopover}
>
<div className={styles.limitsDetails} inert={!open}>
<div className={styles.contextHeading}>
<strong>
<T>Usage limits</T>
</strong>
</div>
<div className={styles.limitsList}>
{items.map((item) => {
const severity = meterTone(item.percent);
const severityClass =
severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined;
return (
<div key={item.window} className={clsx(styles.limitsRow, severityClass)} data-tone={severity}>
<div className={styles.limitsRowHeader}>
<span className={styles.limitsRowName}>{item.name}</span>
<span className={styles.limitsRowPercent}>{item.percent}%</span>
</div>
<div className={styles.limitsTrack} aria-hidden>
<span className={styles.limitsFill} style={{ width: `${item.percent}%` }} />
</div>
{item.resetIn && <span className={styles.limitsReset}>{tx`Resets in ${item.resetIn}`}</span>}
</div>
);
})}
</div>
</div>
</Popup>
</>
);
}
+65 -26
Переглянути файл
@@ -2227,25 +2227,54 @@ 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(<SessionEditor input={input("A")} />);
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("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 +2282,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 +2294,23 @@ describe("meters in the task header", () => {
});
render(<SessionEditor input={input("A")} />);
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 +2322,15 @@ 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("colors the context meter and usage-limit rows at warning/danger thresholds inside Session Info", async () => {
const reported: AgentTask = {
...task("A"),
usage: { used: 164_000, size: 200_000, cost: null },
@@ -2304,20 +2346,17 @@ describe("meters in the task header", () => {
render(<SessionEditor input={input("A")} />);
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");
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 () => {
+15 -3
Переглянути файл
@@ -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",
@@ -4377,5 +4375,19 @@
"Cannot install django-types": "Cannot install django-types",
"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"
"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"
}
+15 -1
Переглянути файл
@@ -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"
}
+15 -1
Переглянути файл
@@ -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"
}
+15 -1
Переглянути файл
@@ -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": "프리미엄 요청"
}
+15 -1
Переглянути файл
@@ -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"
}
+15 -1
Переглянути файл
@@ -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"
}
+15 -3
Переглянути файл
@@ -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": "Свободное место",
@@ -10193,5 +10191,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": "Премиум-запросы"
}
+15 -3
Переглянути файл
@@ -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"
}
+15 -3
Переглянути файл
@@ -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": "剩餘空間",
@@ -9423,5 +9421,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": "進階請求"
}
+15 -3
Переглянути файл
@@ -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": "剩余空间",
@@ -10903,5 +10901,19 @@
"manage.py Tasks": "manage.py 任务",
"Install django-types to complete Django model fields and managers": "安装 django-types 以补全 Django 模型字段和管理器",
"Installing django-types": "正在安装 django-types",
"Cannot install 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": "高级请求"
}