feat(agents): show the Claude Code context window breakdown (#4710)

Clicking the agent status bar's context meter in a Claude Code session opens a breakdown of the context window read on demand from the CLI's get_context_usage control request (system prompt, tools, MCP, memory files, skills, messages, autocompact buffer, free space), with the auto-compact threshold and a Compact session button when the session offers /compact. Other providers keep the plain meter with its tooltip.

Co-authored-by: 0xC3B6 <93749947+0xC3B6@users.noreply.github.com>
This commit is contained in:
C3B6
2026-11-20 14:46:35 +08:00
committed by GitHub
parent e6905f288e
commit 7b2ba44a8d
12 changed files with 419 additions and 21 deletions
+13
View File
@@ -1557,6 +1557,18 @@ impl AgentManager {
Ok(())
}
pub async fn context_usage(&self, id: &str) -> IdeResult<AgentContextUsage> {
let task = self.task(id)?;
let live = task.live.lock().clone().ok_or_else(|| IdeError::unavailable("the agent session is offline"))?;
if !live.capabilities.context_usage {
return Err(IdeError::unavailable("this agent does not report context details"));
}
live.peer
.request("_openidea/context_usage", json!({ "sessionId": live.session }), None)
.await
.map_err(|error| IdeError::internal(task.describe(error)))
}
/// Stops background task `background` of task `id`.
pub async fn stop_background(&self, id: &str, background: &str) -> IdeResult<()> {
let task = self.task(id)?;
@@ -3867,6 +3879,7 @@ fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
rollback: meta("/openidea/rollback"),
steer: steer_method(init).is_some(),
background_tasks: meta("/openidea/backgroundTasks"),
context_usage: meta("/openidea/contextUsage"),
};
(capabilities, init.prompt("embeddedContext"))
}
+20
View File
@@ -45,6 +45,8 @@ pub struct AgentCapabilities {
pub steer: bool,
/// It reports its background tasks and stops them one by one.
pub background_tasks: bool,
/// The connected agent can report a breakdown of its context window.
pub context_usage: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -275,6 +277,24 @@ pub struct AgentUsage {
pub cost: Option<Box<AgentCost>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentContextUsage {
pub categories: Vec<AgentContextCategory>,
pub total_tokens: u32,
pub max_tokens: u32,
pub model: String,
pub is_auto_compact_enabled: Option<bool>,
pub auto_compact_threshold: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
pub struct AgentContextCategory {
pub name: String,
pub tokens: u32,
pub kind: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCost {
+6 -1
View File
@@ -407,7 +407,7 @@ impl Shim {
"promptCapabilities": { "image": true, "embeddedContext": true },
"sessionCapabilities": { "fork": {} },
"mcpCapabilities": { "stdio": true, "http": true, "sse": true },
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
"authMethods": [],
@@ -492,6 +492,11 @@ impl Shim {
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
Ok(json!({}))
}
"_openidea/context_usage" => {
let session = self.session(&params)?;
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
}
"_openidea/stop_task" => {
let session = self.session(&params)?;
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
+12 -4
View File
@@ -5,10 +5,10 @@ use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
McpTransport, NewAgentTask,
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentContextUsage,
AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -351,6 +351,13 @@ pub async fn agent_probe(host: &Host, window: &str, provider: String, refresh: b
host.project(window)?.agents.probe(&provider, refresh).await
}
/// Reads the running session's context categories without sending a prompt.
#[command(trust = trusted)]
pub async fn agent_context_usage(host: &Host, window: &str, task: String) -> IdeResult<AgentContextUsage> {
host.require_trust(window)?;
host.project(window)?.agents.context_usage(&task).await
}
/// Stops the task's current turn, or with `subagent` only that subagent's work.
#[command(trust = always)]
pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
@@ -1077,6 +1084,7 @@ ide_command::domain!(
agent_archive,
agent_base_text,
agent_cancel,
agent_context_usage,
agent_changes,
agent_commands,
agent_create,
+1
View File
@@ -7,6 +7,7 @@ agent_base_text trusted project_host bin
agent_cancel always project_host bindings sync
agent_changes trusted project_host bindings async
agent_commands always project_host bindings async
agent_context_usage trusted project_host bindings async
agent_create trusted project_host bindings async
agent_custom_import trusted desktop bindings sync
agent_custom_remove trusted desktop bindings sync
+19
View File
@@ -38,6 +38,8 @@ export const commands = {
* before a task exists (skills and custom commands on disk included).
*/
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
/** Reads the running session's context categories without sending a prompt. */
agentContextUsage: (task: string) => typedError<AgentContextUsage, IdeError>(__TAURI_INVOKE("agent_context_usage", { task })),
agentCreate: (request: NewAgentTask) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create", { request })),
/** Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents. */
agentCustomImport: (text: string) => typedError<AcpImportOutcome[], IdeError>(__TAURI_INVOKE("agent_custom_import", { text })),
@@ -2153,6 +2155,8 @@ export type AgentCapabilities = {
steer?: boolean,
/** It reports its background tasks and stops them one by one. */
backgroundTasks?: boolean,
/** The connected agent can report a breakdown of its context window. */
contextUsage?: boolean,
};
/**
@@ -2257,6 +2261,21 @@ export type AgentConfigVia =
/** `session/set_model` (agents that report `models` instead of a model config option). */
"model";
export type AgentContextCategory = {
name: string,
tokens: number,
kind: string | null,
};
export type AgentContextUsage = {
categories: AgentContextCategory[],
totalTokens: number,
maxTokens: number,
model: string,
isAutoCompactEnabled: boolean | null,
autoCompactThreshold: number | null,
};
export type AgentCost = {
amount: number | null,
/** ISO 4217 code, e.g. `USD`. */
+94
View File
@@ -2015,3 +2015,97 @@
animation: none;
}
}
.meterButton {
composes: meter;
cursor: pointer;
color: inherit;
font: inherit;
border: 0;
background: transparent;
padding: 0 var(--space-1);
}
.contextPopover {
max-width: calc(100vw - 24px);
}
.contextPopover[data-positioned],
.contextClosing[data-positioned] {
animation: none;
transition: opacity 100ms ease;
}
.contextClosing {
composes: contextPopover;
pointer-events: none;
}
.contextClosing.contextPopover[data-positioned] {
opacity: 0;
}
@starting-style {
.contextPopover[data-positioned] {
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
.contextPopover[data-positioned] {
transition: none;
}
}
.contextDetails {
display: grid;
gap: var(--space-2);
width: min(330px, 80vw);
padding: var(--space-3);
color: var(--fg-secondary);
font-size: var(--fs-ui);
font-variant-numeric: tabular-nums;
}
.contextHeading,
.contextDetails li {
display: flex;
align-items: center;
gap: var(--space-2);
}
.contextHeading {
justify-content: space-between;
color: var(--fg);
}
.contextBar {
display: flex;
height: 6px;
border-radius: 3px;
overflow: hidden;
background: var(--border);
}
.contextBar span {
flex-basis: 0;
}
.contextDetails summary {
cursor: pointer;
color: var(--fg);
}
.contextDetails ul {
margin: var(--space-2) 0 0;
padding: 0;
max-height: 220px;
overflow: auto;
}
.contextDetails li {
padding: var(--space-1) 0;
}
.contextDetails li i {
width: 8px;
height: 8px;
border-radius: 2px;
}
.contextDetails li span:last-child {
margin-left: auto;
}
.contextCompact {
justify-self: end;
cursor: pointer;
color: var(--fg);
background: var(--bg-button);
border: 1px solid var(--border);
border-radius: 4px;
padding: var(--space-1) var(--space-2);
}
@@ -0,0 +1,182 @@
import { useEffect, useRef, useState } from "react";
import type { AgentContextUsage, AgentTask, AgentUsage } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Popup, T, tooltipAttrs } from "@/ui";
import { usageLabel } from "../composerModel";
import { isBusy } from "../model";
import { resendMessage } from "../store";
import styles from "../Session.module.css";
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)";
export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsage }) {
const tx = useTx();
const label = usageLabel(usage);
const hint = tx("Context window") + " · " + label.short;
const anchor = useRef<HTMLButtonElement>(null);
const [phase, setPhase] = useState<"closed" | "open" | "closing">("closed");
const open = phase === "open";
const close = () => setPhase(window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "closed" : "closing");
useEffect(() => {
if (phase !== "closing") return;
const timer = window.setTimeout(() => setPhase("closed"), 100);
return () => window.clearTimeout(timer);
}, [phase]);
const meter = (
<>
<span className={styles.usageBar} aria-hidden>
<span style={{ width: label.percent + "%" }} />
</span>
{label.percent}%
</>
);
if (!task.capabilities?.contextUsage)
return (
<span tabIndex={0} className={styles.meter} aria-label={hint} {...tooltipAttrs(hint, undefined, true)}>
{meter}
</span>
);
return (
<>
<button
type="button"
ref={anchor}
className={styles.meterButton}
aria-label={hint}
aria-haspopup="dialog"
aria-expanded={open}
{...tooltipAttrs(open ? undefined : hint, undefined, true)}
onClick={() => (open ? close() : setPhase("open"))}
>
{meter}
</button>
<Popup
open={phase !== "closed"}
onClose={close}
anchor={anchor}
placement="top-end"
trapFocus={open}
role={open ? "dialog" : "presentation"}
aria-label={tx("Context window")}
className={phase === "closing" ? styles.contextClosing : styles.contextPopover}
>
<ContextDetails task={task} onClose={close} closing={!open} />
</Popup>
</>
);
}
function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose: () => void; closing: boolean }) {
const [report, setReport] = useState<AgentContextUsage | null>(null);
const [error, setError] = useState("");
const [sending, setSending] = useState(false);
const tx = useTx();
useEffect(() => {
let current = true;
call(commands.agentContextUsage(task.id)).then(
(value) => {
if (current) setReport(value);
},
(e) => {
if (current) setError(String(e));
},
);
return () => {
current = false;
};
}, [task.id]);
const summary = report && usageLabel({ used: report.totalTokens, size: report.maxTokens, cost: null });
const categories = report?.categories ?? [];
const compact = async () => {
setSending(true);
try {
await resendMessage(task.id, "/compact");
onClose();
} catch (e) {
setError(String(e));
setSending(false);
}
};
return (
<div className={styles.contextDetails} inert={closing}>
<div className={styles.contextHeading}>
<strong>
<T>Context window</T>
</strong>
<span>{summary?.short}</span>
</div>
{error && (
<p role="alert">
{!report && tx("Context details unavailable") + " · "}
{error}
</p>
)}
{!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) }} />,
)}
</div>
<span>{report.model}</span>
{report.isAutoCompactEnabled && report.autoCompactThreshold != null && (
<span>
{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>
<T>Auto-compact is off</T>
</span>
)}
{task.commands.some((c) => c.name === "compact") && (
<button
type="button"
className={styles.contextCompact}
disabled={sending || isBusy(task.status)}
onClick={() => void compact()}
>
<T>Compact session</T>
</button>
)}
</>
)}
</div>
);
}
+4 -16
View File
@@ -1,10 +1,11 @@
import type { AgentChange, AgentCommit, AgentEntry, AgentLimit, AgentTask, AgentUsage } from "@/bindings";
import type { AgentChange, AgentCommit, AgentEntry, AgentLimit, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import { Icon, IconButton, showContextMenu, T } from "@/ui";
import styles from "../Session.module.css";
import { costLabel, limitLabel, turnTokensLabel, usageLabel, workTime } from "../composerModel";
import { costLabel, limitLabel, turnTokensLabel, workTime } from "../composerModel";
import { ContextMeter } from "./ContextMeter";
import { formatDuration, formatSentAt } from "../conversation";
import { branchLabel, hasTaskTerminal, isBusy, providerIcon, statusLabel } from "../model";
import { useAgents } from "../store";
@@ -157,7 +158,7 @@ function Meters({ task, entries }: { task: AgentTask; entries: AgentEntry[] | nu
const work = show?.showWorkTime !== false && entries ? workTime(entries, busy ? now : null) : 0;
return (
<span className={styles.meters}>
{usage && <Usage usage={usage} />}
{usage && <ContextMeter key={task.id} task={task} usage={usage} />}
{turnTokens && <span title={tx("Tokens of the last turn")}>{turnTokensLabel(turnTokens)}</span>}
{limits.map((l) => (
<Limit key={l.window} limit={l} now={now} />
@@ -180,16 +181,3 @@ function Limit({ limit, now }: { limit: AgentLimit; now: number }) {
</span>
);
}
/** Context window use: "167k/1M (17%)", the exact counts in the tooltip. */
function Usage({ usage }: { usage: AgentUsage }) {
const label = usageLabel(usage);
return (
<span className={styles.meter} title={label.detail} aria-label={`Context ${label.short}, ${label.detail}`}>
<span className={styles.usageBar} aria-hidden>
<span style={{ width: `${label.percent}%` }} />
</span>
{`${label.percent}%`}
</span>
);
}
+32
View File
@@ -73,6 +73,20 @@ vi.mock("@/platform/ipc", async (original) => ({
status: "ok",
data: { size: 1, binary: false, tooLarge: false },
}),
agentContextUsage: vi.fn(async () => ({
status: "ok",
data: {
model: "Claude",
totalTokens: 3200,
maxTokens: 200000,
isAutoCompactEnabled: true,
autoCompactThreshold: 180000,
categories: [
{ name: "System tools", tokens: 3200, kind: "used" },
{ name: "Free space", tokens: 196800, kind: "free" },
],
},
})),
agentEntries: async (id: string, sub: string | null) => {
const key = sub ? `${id}/${sub}` : id;
backend.fetched.push(key);
@@ -2099,6 +2113,24 @@ describe("meters in the task header", () => {
useAgents.setState({ limits: new Map() });
});
it("queries the active task only when context details are opened", async () => {
const { commands } = await import("@/platform/ipc");
const reported: AgentTask = {
...task("A"),
capabilities: { contextUsage: true },
usage: { used: 3000, size: 200000, 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();
expect(commands.agentContextUsage).toHaveBeenCalledWith("A");
expect(screen.getByText("196,800")).toBeInTheDocument();
fireEvent.keyDown(document, { key: "Escape" });
expect(screen.queryByRole("dialog", { name: "Context window" })).toBeNull();
});
it("shows the provider's usage limits by default and each meter as Settings › Tools › Agents › Chat allows", async () => {
const reported: AgentTask = {
...task("A"),
+18
View File
@@ -1,4 +1,22 @@
{
"MCP server instructions": "MCP server instructions",
"MCP tools (deferred)": "MCP tools (deferred)",
"System tools (deferred)": "System tools (deferred)",
"Custom agents": "Custom agents",
"Context window": "Context window",
"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",
"Messages": "Messages",
"Memory files": "Memory files",
"MCP tools": "MCP tools",
"Autocompact buffer": "Autocompact buffer",
"Inspection details": "Inspection details",
"Resize inspection panes": "Resize inspection panes",
"Resize branch comparison panes": "Resize branch comparison panes",
+18
View File
@@ -1,4 +1,22 @@
{
"MCP server instructions": "MCP 服务器说明",
"MCP tools (deferred)": "MCP 工具(延迟加载)",
"System tools (deferred)": "系统工具(延迟加载)",
"Custom agents": "自定义 Agent",
"Context window": "上下文窗口",
"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": "剩余空间",
"Messages": "消息",
"Memory files": "记忆文件",
"MCP tools": "MCP 工具",
"Autocompact buffer": "自动压缩预留空间",
"Inspection details": "检查详情",
"Resize inspection panes": "调整检查窗格大小",
"Resize branch comparison panes": "调整分支比较窗格大小",