From 7b2ba44a8de183d002a08a431d441551684411bd Mon Sep 17 00:00:00 2001 From: C3B6 <93749947+0xC3B6@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:46:35 +0800 Subject: [PATCH] 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> --- crates/ide-agent/src/lib.rs | 13 ++ crates/ide-agent/src/model.rs | 20 ++ crates/ide-agent/src/native/claude/mod.rs | 7 +- crates/ide-host/src/ops/agent.rs | 16 +- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 19 ++ src/features/agents/Session.module.css | 94 +++++++++ src/features/agents/session/ContextMeter.tsx | 182 ++++++++++++++++++ src/features/agents/session/SessionStatus.tsx | 20 +- src/features/agents/sessionState.test.tsx | 32 +++ src/platform/locales/text/en.json | 18 ++ src/platform/locales/text/zh.json | 18 ++ 12 files changed, 419 insertions(+), 21 deletions(-) create mode 100644 src/features/agents/session/ContextMeter.tsx diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 79d081f69..20c7f66df 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -1557,6 +1557,18 @@ impl AgentManager { Ok(()) } + pub async fn context_usage(&self, id: &str) -> IdeResult { + 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")) } diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index 203b01d01..7ef60a1e5 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -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>, } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct AgentContextUsage { + pub categories: Vec, + pub total_tokens: u32, + pub max_tokens: u32, + pub model: String, + pub is_auto_compact_enabled: Option, + pub auto_compact_threshold: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +pub struct AgentContextCategory { + pub name: String, + pub tokens: u32, + pub kind: Option, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct AgentCost { diff --git a/crates/ide-agent/src/native/claude/mod.rs b/crates/ide-agent/src/native/claude/mod.rs index 8657947fa..9d34dbddf 100644 --- a/crates/ide-agent/src/native/claude/mod.rs +++ b/crates/ide-agent/src/native/claude/mod.rs @@ -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(¶ms)?; + 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(¶ms)?; let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?; diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index 69f1a81c3..1a6ea8b40 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -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 { + 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) -> IdeResult<()> { @@ -1077,6 +1084,7 @@ ide_command::domain!( agent_archive, agent_base_text, agent_cancel, + agent_context_usage, agent_changes, agent_commands, agent_create, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 628526ff3..c9d582c40 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -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 diff --git a/src/bindings.ts b/src/bindings.ts index 4bc0355a6..badc60631 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -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(__TAURI_INVOKE("agent_commands", { provider, task })), + /** Reads the running session's context categories without sending a prompt. */ + agentContextUsage: (task: string) => typedError(__TAURI_INVOKE("agent_context_usage", { task })), agentCreate: (request: NewAgentTask) => typedError(__TAURI_INVOKE("agent_create", { request })), /** Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents. */ agentCustomImport: (text: string) => typedError(__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`. */ diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index 81c714b46..c39ff996e 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -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); +} diff --git a/src/features/agents/session/ContextMeter.tsx b/src/features/agents/session/ContextMeter.tsx new file mode 100644 index 000000000..1beb3b4e4 --- /dev/null +++ b/src/features/agents/session/ContextMeter.tsx @@ -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(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 = ( + <> + + + + {label.percent}% + + ); + if (!task.capabilities?.contextUsage) + return ( + + {meter} + + ); + return ( + <> + + + + + + ); +} + +function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose: () => void; closing: boolean }) { + const [report, setReport] = useState(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 ( +
+
+ + Context window + + {summary?.short} +
+ {error && ( +

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

+ )} + {!error && !report && ( + + Loading context details… + + )} + {report && ( + <> +
+ {categories.map( + (c) => + c.kind !== "deferred" && + c.tokens > 0 && , + )} +
+ {report.model} + {report.isAutoCompactEnabled && report.autoCompactThreshold != null && ( + + {tx("Auto-compact at {count} tokens").replace("{count}", report.autoCompactThreshold.toLocaleString())} + + )} +
+ + Detailed breakdown + +
    + {categories.map((c) => ( +
  • + + {tx(c.name)} + {c.tokens.toLocaleString()} +
  • + ))} +
+
+ {report.isAutoCompactEnabled === false && ( + + Auto-compact is off + + )} + {task.commands.some((c) => c.name === "compact") && ( + + )} + + )} +
+ ); +} diff --git a/src/features/agents/session/SessionStatus.tsx b/src/features/agents/session/SessionStatus.tsx index 7c48050da..94434920e 100644 --- a/src/features/agents/session/SessionStatus.tsx +++ b/src/features/agents/session/SessionStatus.tsx @@ -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 ( - {usage && } + {usage && } {turnTokens && {turnTokensLabel(turnTokens)}} {limits.map((l) => ( @@ -180,16 +181,3 @@ function Limit({ limit, now }: { limit: AgentLimit; now: number }) { ); } - -/** Context window use: "167k/1M (17%)", the exact counts in the tooltip. */ -function Usage({ usage }: { usage: AgentUsage }) { - const label = usageLabel(usage); - return ( - - - - - {`${label.percent}%`} - - ); -} diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index 18809bb70..5ff461be9 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -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(); + 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"), diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index c647f053c..557aadd86 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -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", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index f5cb3e305..a7302acd4 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -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": "调整分支比较窗格大小",