Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Click the context ring to see what the context is full of (#442)

Yaowei Zhengdf3cf3be416a
diff --git a/changelog/unreleased/2026-08-24-context-composition-panel.md b/changelog/unreleased/2026-08-24-context-composition-panel.md
new file mode 100644
index 00000000..131e4904
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-context-composition-panel.md
@@ -0,0 +1,66 @@
+# Click the context ring to see what the context is full of
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `web`, `server`
+- **PR:** [#442](https://github.com/Prism-Shadow/penguin-harness/pull/442)
+
+[中文版](2026-08-24-context-composition-panel.zh.md)
+
+The context ring in the chat composer became a button. Clicking it opens a panel that splits the
+current model context into six parts — system prompt, tool definitions, user messages, model
+messages, tool requests, tool results — as a bar running the full context window and a legend of
+tokens and percentages, followed by the five tools whose traffic occupies the most of it. A dashed
+mark on the bar says where compaction will fire. The `used/window` figures that
+used to sit beside the ring moved into that panel's header; the composer now shows the ring alone,
+and hovering it names the figures.
+
+## Details
+
+- `GET /api/sessions/:sessionId/context` returns the six parts, their sum, and the tool ranking. It
+ reads the Session's **newest Trace shard**, which is one complete model context: the Trace writer
+ rotates on compaction and opens the new file with `session_meta` and `tool_list_ready`, and
+ Session resumption keeps appending to the shard it left off in.
+- Sizes come from the character heuristic core already applies to request inputs
+ (`approximateMessagesTokens`), so images carry their flat allowance instead of their base64
+ length, and no tokenizer is introduced.
+- The panel spends those figures on **shares only**. Each part is drawn as its share of the
+ occupancy the ring itself reports — the last `token_usage`'s `request.total` — so the parts add up
+ to the figure in the panel header, and every derived value is marked `~`. Both columns are
+ apportioned by largest remainder, so the percentages total exactly 100 and the token column
+ exactly the measured occupancy.
+- Events are skipped (none of them is sent to the model), and so are the messages between a
+ `compaction_begin` and its `compaction_end`: the compaction prompt and the summary it produces
+ are recorded in the shard but were never part of the context being described.
+- The tool ranking counts each tool's calls **and** their results. A tool's *definition* is counted
+ in the tool-definitions part instead, and a result whose call is not in the same shard still
+ counts toward tool results but has no tool to be attributed to — so the ranking can sum to less
+ than the two tool parts.
+- The bar's scale is the whole context window: the filled run is the occupancy the ring reports, the
+ rest is headroom, and the parts subdivide the filled run. It carries no gaps between fills —
+ once a bar has an absolute position scale, a surface gap pushes every fill after it off the
+ coordinate the compaction mark is drawn on — so what keeps neighbouring hues apart is the
+ palette's own adjacent-pair separation.
+- The response gained `compactionThreshold`: the Agent's configured `compaction.max_context_length`
+ (its seeded default when unset) capped at `context_window − 2048`, the same derivation the Agent
+ applies when it builds a Session's compaction settings. Null when compaction is off, when the
+ Agent's config cannot be read, or when the threshold is not inside the window — nothing to mark.
+- Hovering a bar segment or its legend row links the two: the row lights up and the other segments
+ fade. The bar carries no labels of its own, so this is how a sliver gets identified.
+- A shard ending in a completed `compaction_end` reports `contextClosed`, the same test Trace replay
+ uses to decide it must replay nothing. The panel then shows `—` and says the next request will
+ report the usage, matching what the ring already shows in that state, rather than describing the
+ context that was just compacted away.
+- The panel is portaled and positioned by `usePortalPanel`, closing on outside click, Esc, scroll or
+ resize. It is offered where a Session-level endpoint can serve it: not in the draft composer,
+ which has no Session, and not in the subagent composer, whose child Session is not registered in
+ the sessions table.
+
+## Colours
+
+- The six parts took a categorical palette of their own in `lib/category-colors.ts`, separate from
+ `SERIES_COLORS` whose length is also the cost center's fold cap.
+- Legend rows are drawn in the same order as the bar segments, so only neighbours have to be told
+ apart; the order clears the adjacent-pair gates in both light and dark (worst adjacent ΔE 21.1
+ simulated for protanopia and deuteranopia, 22.1 unsimulated, OKLab ×100). Six hues cannot also
+ clear those gates for arbitrary pairs, so every legend row carries its own value beside its name.
diff --git a/changelog/unreleased/2026-08-24-context-composition-panel.zh.md b/changelog/unreleased/2026-08-24-context-composition-panel.zh.md
new file mode 100644
index 00000000..ba27372d
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-context-composition-panel.zh.md
@@ -0,0 +1,50 @@
+# 点击上下文圆环,看清上下文被什么占满
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `web`, `server`
+- **PR:** [#442](https://github.com/Prism-Shadow/penguin-harness/pull/442)
+
+[English](2026-08-24-context-composition-panel.md)
+
+对话输入区的上下文圆环变成了按钮。点击后弹出面板,把当前模型上下文拆成六项——系统提示词、工具定义、
+用户消息、模型消息、工具请求、工具结果——条形以整个上下文窗口为标尺,配合图例给出各自的 token 用量
+与占比,其下是流量占用最多的五个工具。条形上另有一条虚线,标出压缩会在哪里触发。原先跟在圆环旁的 `已用 / 上限` 数字移入面板表头,输入区只留圆环,悬停圆环即可读到
+这两个数字。
+
+## 细节
+
+- `GET /api/sessions/:sessionId/context` 返回六个分项、它们的合计与工具排行。它读取该 Session
+ **最新的一个 Trace 分片**,一个分片即一个完整的模型上下文:Trace 写入器在压缩时轮转,新文件以
+ `session_meta` 与 `tool_list_ready` 开头,而 Session 恢复会继续追加到中断时的那个分片。
+- 各项大小取自 core 已经用于估算请求输入的字符启发式(`approximateMessagesTokens`),因此图片按固
+ 定额度计入而不是按 base64 长度,也不引入本地 tokenizer。
+- 面板只使用这些数字的**占比**。每一项按其占估算总量的比例,折算到圆环自身报告的占用量——最近一次
+ `token_usage` 的 `request.total`——因此各项之和恰好等于面板表头的数字,且每个折算值都带 `~` 标记。
+ 两列均按最大余额法分配,占比合计恰为 100,token 列合计恰为实测占用。
+- 事件消息一律跳过(它们都不会发给模型);`compaction_begin` 与 `compaction_end` 之间的消息同样跳
+ 过:压缩请求的提示与它产出的摘要虽记录在该分片里,却从不属于这里所描述的上下文。
+- 工具排行统计每个工具的调用**与**结果两部分 token。工具的**定义**计入「工具定义」一项;调用不在同
+ 一分片里的结果仍计入「工具结果」,但没有可归属的工具——因此排行之和可能小于两个工具分项之和。
+- 条形以整个上下文窗口为标尺:已填充的部分即圆环报告的占用量,其余为余量,六个分项在已填充部分内细分。
+ 分段之间不留缝隙——条形一旦带有绝对位置标尺,一道底色缝隙就会把它之后的每一段推离压缩虚线所依据的坐
+ 标——相邻色相之间的区分因此完全交给配色自身的相邻项间距。
+- 响应新增 `compactionThreshold`:Agent 配置的 `compaction.max_context_length`(未配置时取其缺省
+ 值),并以 `context_window − 2048` 封顶,与 Agent 组装 Session 压缩设置时的推导完全一致。压缩关闭、
+ Agent 配置读不出来,或阈值不落在窗口之内时为 null——没有可标注的位置。
+- 悬停条形分段或对应的图例行会把两者关联起来:该行高亮,其余分段淡出。条形本身没有标注,细到几乎看不
+ 见的分段正是靠这个才能认出来。
+- 以状态为 completed 的 `compaction_end` 结尾的分片报告 `contextClosed`,判据与 Trace 重放判定
+ 「无需重放」的一致。此时面板显示 `—` 并说明占用待下次请求回报,与圆环在该状态下的表现一致,而不是去
+ 描述刚刚被压缩掉的那个上下文。
+- 面板经 `usePortalPanel` 传送并定位,点击外部、Esc、滚动或改变窗口大小即关闭。它只出现在
+ Session 级端点能够服务的地方:草稿输入区没有 Session,子智能体输入区的子 Session 未登记在 sessions
+ 表中,两处都不提供。
+
+## 配色
+
+- 六个分项在 `lib/category-colors.ts` 中拥有独立的分类色序列,与 `SERIES_COLORS` 分开——后者的长度
+ 同时是成本中心的折叠上限。
+- 图例行与条形分段同序绘制,读者只需分辨相邻项;该顺序在浅色与深色下都通过相邻项校验(最差相邻
+ ΔE:模拟红色盲/绿色盲 21.1,未模拟 22.1,OKLab ×100)。六种色相无法同时对**任意**两项通过这些
+ 校验,因此每一行图例都在名称旁给出自己的数值。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index fd1106b2..2b8bbd20 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1659,6 +1659,54 @@ export interface SessionTracesResponse {
files: TraceFileInfo[];
}
+/** One tool's share of the context: its calls plus their results. Its *definition* is counted in `toolDefs`, not here. */
+export interface ContextToolShare {
+ name: string;
+ tokens: number;
+}
+
+/**
+ * What the Session's current model context is made of — the part derived from its messages.
+ *
+ * Every token figure is an **estimate** from a character heuristic, not a tokenizer: the
+ * authoritative occupancy is the last `token_usage`'s `request.total`, which says how large the
+ * context is but not what fills it. Consumers should present these as shares of that measured
+ * occupancy rather than as counts of their own.
+ *
+ * The six parts partition the context and sum to `total`; `topTools` is a ranking inside
+ * `toolRequests + toolResults` and can sum to less than those two (a result whose call was not
+ * recorded in the same Trace shard has no tool to be attributed to).
+ */
+export interface SessionContextParts {
+ systemPrompt: number;
+ toolDefs: number;
+ userMessages: number;
+ assistantMessages: number;
+ toolRequests: number;
+ toolResults: number;
+ /** Sum of the six parts. */
+ total: number;
+ /** Tools ranked by the context their traffic occupies, descending; at most five. */
+ topTools: ContextToolShare[];
+ /**
+ * A completed compaction closed the context these figures describe, and the next one has not
+ * been written yet: the composition is of what was compacted away, not of what the model now
+ * carries. The same state in which the chat page's context ring shows `—`.
+ */
+ contextClosed: boolean;
+}
+
+/** `GET /api/sessions/:id/context`: the message-derived composition plus where compaction will fire. */
+export interface SessionContextResponse extends SessionContextParts {
+ /**
+ * Occupancy (tokens) at which this Session's next Request triggers context compaction: the
+ * Agent's configured `compaction.max_context_length`, capped by what the model's context window
+ * leaves room for. Null when compaction is disabled, when the Agent's config could not be read,
+ * or when the derived threshold is not below the window — nothing to mark inside the gauge.
+ */
+ compactionThreshold: number | null;
+}
+
export interface TraceEventsResponse {
events: OmniMessage[];
offset: number;
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 3717d6b0..55bd9e3f 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -22,6 +22,7 @@ import type {
RecalledMessageResponse,
ServerEvent,
SessionCategory,
+ SessionContextResponse,
SessionCreateResponse,
SessionForkResponse,
SessionProcessesResponse,
@@ -31,6 +32,7 @@ import type {
RetryNowResponse,
TaskCreateResponse,
} from "../../api/types.js";
+import { compactionThresholdFor } from "../../services/context-breakdown.js";
import { decodeCursor } from "../../services/message-window.js";
import type { MessagesPageRequest } from "../../services/trace-service.js";
import { PREVIEW_TOKEN_TTL_MS, resolvePreviewTarget } from "../../services/preview-token.js";
@@ -158,6 +160,29 @@ function messagesPageQuery(c: Context): MessagesPageRequest | null {
};
}
+/**
+ * Where compaction will fire for one Session, in tokens of occupancy: the Agent's configured
+ * threshold capped by what its model's context window leaves room for. Both halves are read from
+ * config rather than from a running engine, so an idle Session answers as well as a busy one.
+ *
+ * Fail-soft: this is one mark on a gauge, and an Agent deleted out from under a still-indexed
+ * Session (or a config that will not parse) must not take the whole composition down with it.
+ */
+async function sessionCompactionThreshold(deps: AppDeps, row: SessionRow): Promise<number | null> {
+ try {
+ const [agent, project] = await Promise.all([
+ deps.agentConfigService.getConfig(row.projectId, row.agentId),
+ deps.projectConfigService.loadConfig(row.projectId),
+ ]);
+ const entry = (project.models ?? []).find(
+ (m) => m.provider === row.provider && m.model_id === row.modelId,
+ );
+ return compactionThresholdFor(agent.config.compaction?.maxContextLength, entry?.context_window);
+ } catch {
+ return null;
+ }
+}
+
/** Accepted `category` query values of the list endpoint (SessionCategory, spelled out for validation). */
const SESSION_CATEGORIES: readonly SessionCategory[] = [
"active",
@@ -1281,6 +1306,25 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
return c.body(null, 204);
});
+ /**
+ * What the Session's current model context is made of, and where compaction will fire. Read on
+ * demand (the chat page's context ring opens its detail panel with it), not streamed: it
+ * re-reads the newest Trace shard on every call, and the figures are a snapshot rather than a
+ * live counter.
+ */
+ app.get("/:sessionId/context", async (c) => {
+ const row = resolveSession(c);
+ const parts = await deps.traceService.contextBreakdown(
+ row.projectId,
+ row.agentId,
+ row.sessionId,
+ );
+ return c.json({
+ ...parts,
+ compactionThreshold: await sessionCompactionThreshold(deps, row),
+ } satisfies SessionContextResponse);
+ });
+
app.get("/:sessionId/traces", async (c) => {
const row = resolveSession(c);
const files = await deps.traceService.listTraceFiles(row.projectId, row.agentId, row.sessionId);
diff --git a/packages/server/src/services/context-breakdown.ts b/packages/server/src/services/context-breakdown.ts
new file mode 100644
index 00000000..3259d6d0
--- /dev/null
+++ b/packages/server/src/services/context-breakdown.ts
@@ -0,0 +1,177 @@
+/**
+ * Context composition: what the Session's current model context is made of, split into the six
+ * parts a reader can act on — system prompt, tool definitions, user messages, model messages,
+ * tool requests, tool results — plus the tools whose call traffic occupies the most of it.
+ *
+ * The basis is **one Trace shard**. A shard is one complete model context by construction: the
+ * writer rotates on compaction and opens the new file with `session_meta` followed by
+ * `tool_list_ready`, and Session resumption keeps appending to the shard it left off in. So a
+ * Session's newest shard holds exactly the messages the model still sees. The one exception is
+ * a shard whose last record is a completed `compaction_end`: that context is closed and the
+ * next one has not been written yet (rotation is deferred until the first write after the
+ * compaction), so the composition describes what was compacted away rather than what the model
+ * now carries. `contextClosed` reports it; the rule is the same one Trace replay applies to
+ * decide it must replay nothing.
+ *
+ * Sizes come from the character heuristic core already applies to request inputs
+ * (`approximateMessagesTokens`: ASCII at ~4 characters per token, wide characters at 1, a flat
+ * allowance per image), not from a tokenizer — this project ships none, and occupancy itself is
+ * read off the provider's `token_usage`. Every figure here is therefore an estimate; what it is
+ * good for is **shares**, which is what its consumers spend it on.
+ */
+import {
+ DEFAULT_MAX_CONTEXT_LENGTH,
+ approximateMessagesTokens,
+ approximateTokens,
+ effectiveMaxContextLength,
+} from "@prismshadow/penguin-core";
+import type {
+ OmniMessage,
+ SessionMetaPayload,
+ ToolCallOutputPayload,
+ ToolCallPayload,
+ ToolListReadyPayload,
+} from "@prismshadow/penguin-core";
+import type { SessionContextParts } from "../api/types.js";
+
+/** How many tools the ranking names before the tail is dropped. */
+const TOP_TOOLS = 5;
+
+/** The answer for a Session with no Trace yet: measured as empty, not unknown. */
+export function emptyContextBreakdown(): SessionContextParts {
+ return {
+ systemPrompt: 0,
+ toolDefs: 0,
+ userMessages: 0,
+ assistantMessages: 0,
+ toolRequests: 0,
+ toolResults: 0,
+ total: 0,
+ topTools: [],
+ contextClosed: false,
+ };
+}
+
+function bump(per: Map<string, number>, name: string, tokens: number): void {
+ per.set(name, (per.get(name) ?? 0) + tokens);
+}
+
+/**
+ * True when this shard's context was closed by a completed compaction — the same test Trace
+ * replay uses: the file's last record is a `compaction_end` reporting `completed`. Anything
+ * written after a compaction lands in the next shard, so no later record can follow it here.
+ */
+function endsWithCompletedCompaction(messages: OmniMessage[]): boolean {
+ const last = messages[messages.length - 1];
+ if (last === undefined || last.type !== "event_msg") return false;
+ const p = last.payload as { type?: string; status?: string };
+ return p.type === "compaction_end" && p.status === "completed";
+}
+
+/** Composition of the context held by one Trace shard's messages (in write order). */
+export function buildContextBreakdown(messages: OmniMessage[]): SessionContextParts {
+ const out = emptyContextBreakdown();
+ /** name -> its calls plus their results; the definition is the `toolDefs` part, not a tool's own share. */
+ const perTool = new Map<string, number>();
+ /** tool_call_id -> tool name, so a result can be attributed to the tool that produced it. */
+ const callName = new Map<string, string>();
+ let compacting = false;
+
+ for (const msg of messages) {
+ if (msg.type === "session_meta") {
+ // A per-shard invariant, not an accumulation: a resumed process writes its own copy into
+ // the shard it continues, and a rotation writes one at the head of the new file. The
+ // newest wins; adding them would count one system prompt several times.
+ out.systemPrompt = approximateTokens((msg.payload as SessionMetaPayload).system_prompt ?? "");
+ continue;
+ }
+ const p = msg.payload as { type?: string; role?: string };
+ if (msg.type === "event_msg") {
+ // Events are observability records — none of them is sent to the model — so the only ones
+ // that matter here are the toolset record and the compaction span's boundaries.
+ if (p.type === "tool_list_ready") {
+ // Same "newest wins" reasoning as session_meta: this record rides the first run of each
+ // process and each rotation, and it always carries the whole toolset.
+ const tools = (p as unknown as ToolListReadyPayload).tools ?? [];
+ out.toolDefs = tools.reduce((n, t) => n + approximateTokens(JSON.stringify(t)), 0);
+ } else if (p.type === "compaction_begin") {
+ compacting = true;
+ } else if (p.type === "compaction_end") {
+ compacting = false;
+ }
+ continue;
+ }
+ // A compaction is an LLM Request of its own, recorded inside this shard: its prompt and the
+ // summary it produces were never part of the context being described.
+ if (compacting) continue;
+
+ const size = approximateMessagesTokens([msg]);
+ switch (p.type) {
+ case "text":
+ case "image_url":
+ case "inline_data":
+ if (p.role === "assistant") out.assistantMessages += size;
+ else out.userMessages += size;
+ break;
+ case "thinking":
+ case "inline_thinking":
+ out.assistantMessages += size;
+ break;
+ case "tool_call": {
+ const tc = p as unknown as ToolCallPayload;
+ out.toolRequests += size;
+ callName.set(tc.tool_call_id, tc.name);
+ bump(perTool, tc.name, size);
+ break;
+ }
+ case "tool_call_output": {
+ const result = p as unknown as ToolCallOutputPayload;
+ out.toolResults += size;
+ // An output whose call is not in this shard still counts toward the tool-results part;
+ // it just has no tool to be attributed to, so the ranking can sum to less than
+ // `toolRequests + toolResults`.
+ const name = callName.get(result.tool_call_id);
+ if (name !== undefined) bump(perTool, name, size);
+ break;
+ }
+ }
+ }
+
+ out.total =
+ out.systemPrompt +
+ out.toolDefs +
+ out.userMessages +
+ out.assistantMessages +
+ out.toolRequests +
+ out.toolResults;
+ out.topTools = [...perTool]
+ // Name breaks ties so equal-sized tools keep a stable order across calls.
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .slice(0, TOP_TOOLS)
+ .map(([name, tokens]) => ({ name, tokens }));
+ out.contextClosed = endsWithCompletedCompaction(messages);
+ return out;
+}
+
+/**
+ * Where compaction will fire for a Session, in tokens of occupancy — the Agent's configured
+ * `compaction.max_context_length` (its seeded default when unset) capped by what the model's
+ * context window leaves room for, which is the same derivation the Agent applies when it builds a
+ * Session's compaction settings.
+ *
+ * Null means "nothing to mark on a gauge that runs to the window": compaction switched off
+ * (`<= 0`), or a threshold at or past the window itself — which is what an implausibly small
+ * `context_window` produces, since the derivation then reasons from the assumed default window
+ * instead of the configured one.
+ */
+export function compactionThresholdFor(
+ configured: number | undefined,
+ contextWindow: number | undefined,
+): number | null {
+ const threshold = effectiveMaxContextLength(
+ configured ?? DEFAULT_MAX_CONTEXT_LENGTH,
+ contextWindow,
+ );
+ if (threshold <= 0) return null;
+ return contextWindow !== undefined && threshold >= contextWindow ? null : threshold;
+}
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 7a1117b8..d621138b 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -36,6 +36,7 @@ import type {
RequestSpan,
SessionCategory,
SessionCategoryCounts,
+ SessionContextParts,
HistoryMessage,
TracePosition,
ToolCallSpan,
@@ -69,6 +70,7 @@ import type {
ScanState,
WindowPriorStats,
} from "./message-window.js";
+import { buildContextBreakdown, emptyContextBreakdown } from "./context-breakdown.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;
@@ -758,6 +760,26 @@ export class TraceService {
}
}
+ /**
+ * Composition of the Session's current model context, read from its **newest** Trace shard —
+ * one shard is one complete context (see context-breakdown.ts). A Session with no Trace yet
+ * answers with zeros rather than a 404: "nothing in the context" is a true statement about it,
+ * and the caller is a display that would have to invent the same answer.
+ */
+ async contextBreakdown(
+ projectId: string,
+ agentId: string,
+ sessionId: string,
+ ): Promise<SessionContextParts> {
+ const files = await this.locateAll(projectId, agentId, sessionId);
+ const newest = files.reduce<LocatedFile | null>(
+ (best, f) => (best === null || f.index > best.index ? f : best),
+ null,
+ );
+ if (newest === null) return emptyContextBreakdown();
+ return buildContextBreakdown(await this.readShard(newest.path));
+ }
+
/** List of Trace files (index / date / size / mtime). */
async listTraceFiles(
projectId: string,
diff --git a/packages/server/test/context-breakdown.test.ts b/packages/server/test/context-breakdown.test.ts
new file mode 100644
index 00000000..a2cebd4f
--- /dev/null
+++ b/packages/server/test/context-breakdown.test.ts
@@ -0,0 +1,246 @@
+/**
+ * Unit tests for the context composition: how a Trace shard's messages are split across the six
+ * parts, how tool traffic is attributed to tool names, and which shard the service reads.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import fs from "node:fs/promises";
+import {
+ approximateTokens,
+ assistantText,
+ compactionBegin,
+ compactionEnd,
+ imageUrlMessage,
+ requestBegin,
+ requestEnd,
+ sessionMeta,
+ thinkingMessage,
+ tokenUsage,
+ toolCall,
+ toolCallOutput,
+ toolListReady,
+ userText,
+} from "@prismshadow/penguin-core";
+import type { OmniMessage, SessionMetaPayload, ToolDefinition } from "@prismshadow/penguin-core";
+import {
+ buildContextBreakdown,
+ compactionThresholdFor,
+} from "../src/services/context-breakdown.js";
+import { makeTempRoot, makeTraceHarness, writeTraceFile } from "./helpers.js";
+
+const P = "project-c";
+const A = "agent-c";
+const S = "session-2026-08-24-09-00-00-aabbccdd";
+
+function metaPayload(systemPrompt: string): SessionMetaPayload {
+ return {
+ session_id: S,
+ model_id: "m1",
+ provider: "custom",
+ model_context_window: 128000,
+ system_prompt: systemPrompt,
+ agent_state: `/data/${P}/agents/${A}`,
+ workspace: "/data/ws",
+ };
+}
+
+const TOOLS: ToolDefinition[] = [
+ { name: "read_file", description: "Read a file", parameters: { type: "object" } },
+ { name: "exec_command", description: "Run a command", parameters: { type: "object" } },
+];
+
+describe("buildContextBreakdown", () => {
+ it("splits a shard across the six parts and sums them into total", () => {
+ const b = buildContextBreakdown([
+ sessionMeta(metaPayload("You are a helpful agent.")),
+ toolListReady(TOOLS),
+ userText("please read the config"),
+ thinkingMessage("the config lives in the workspace root"),
+ assistantText("reading it now"),
+ toolCall({ name: "read_file", arguments: '{"path":"config.toml"}', toolCallId: "c1" }),
+ toolCallOutput({ output: "port = 8080", toolCallId: "c1" }),
+ ]);
+
+ expect(b.systemPrompt).toBe(approximateTokens("You are a helpful agent."));
+ expect(b.toolDefs).toBe(TOOLS.reduce((n, t) => n + approximateTokens(JSON.stringify(t)), 0));
+ for (const part of [
+ b.userMessages,
+ b.assistantMessages,
+ b.toolRequests,
+ b.toolResults,
+ ] as const) {
+ expect(part).toBeGreaterThan(0);
+ }
+ expect(b.total).toBe(
+ b.systemPrompt +
+ b.toolDefs +
+ b.userMessages +
+ b.assistantMessages +
+ b.toolRequests +
+ b.toolResults,
+ );
+ expect(b.contextClosed).toBe(false);
+ });
+
+ it("counts thinking as a model message and a user image as a user message", () => {
+ const thinkingOnly = buildContextBreakdown([thinkingMessage("a long deliberation")]);
+ expect(thinkingOnly.assistantMessages).toBeGreaterThan(0);
+ expect(thinkingOnly.userMessages).toBe(0);
+
+ // A data URL's base64 body must not be counted character by character: an image carries a
+ // flat allowance, so a 1x1 pixel and a photograph cost the same estimate here.
+ const tiny = buildContextBreakdown([imageUrlMessage("data:image/png;base64,iVBORw0KGgo=")]);
+ const big = buildContextBreakdown([
+ imageUrlMessage(`data:image/png;base64,${"A".repeat(200_000)}`),
+ ]);
+ expect(tiny.userMessages).toBe(big.userMessages);
+ expect(tiny.assistantMessages).toBe(0);
+ });
+
+ it("ranks tools by their calls plus their results, capped at five", () => {
+ const messages: OmniMessage[] = [];
+ // Sizes are engineered so the ranking is unambiguous: exec_command's single result dwarfs
+ // everything else, and read_file's three small calls still beat the one-off tools.
+ messages.push(
+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: "e1" }),
+ toolCallOutput({ output: "x".repeat(4000), toolCallId: "e1" }),
+ );
+ for (let i = 0; i < 3; i++) {
+ messages.push(
+ toolCall({ name: "read_file", arguments: "{}", toolCallId: `r${i}` }),
+ toolCallOutput({ output: "y".repeat(400), toolCallId: `r${i}` }),
+ );
+ }
+ for (const name of ["grep", "write_file", "list_dir", "web_fetch"]) {
+ messages.push(
+ toolCall({ name, arguments: "{}", toolCallId: `${name}-1` }),
+ toolCallOutput({ output: "z".repeat(40), toolCallId: `${name}-1` }),
+ );
+ }
+
+ const b = buildContextBreakdown(messages);
+ expect(b.topTools).toHaveLength(5);
+ expect(b.topTools.map((t) => t.name).slice(0, 2)).toEqual(["exec_command", "read_file"]);
+ expect(b.topTools[0]!.tokens).toBeGreaterThan(b.topTools[1]!.tokens);
+ // The ranking lives inside the two tool parts and never exceeds them.
+ expect(b.topTools.reduce((n, t) => n + t.tokens, 0)).toBeLessThanOrEqual(
+ b.toolRequests + b.toolResults,
+ );
+ });
+
+ it("keeps the newest session_meta and tool_list_ready instead of adding a second copy", () => {
+ // A resumed process writes its own bootstrap pair into the shard it continues.
+ const once = buildContextBreakdown([sessionMeta(metaPayload("prompt")), toolListReady(TOOLS)]);
+ const twice = buildContextBreakdown([
+ sessionMeta(metaPayload("prompt")),
+ toolListReady(TOOLS),
+ userText("hello"),
+ sessionMeta(metaPayload("prompt")),
+ toolListReady(TOOLS),
+ ]);
+ expect(twice.systemPrompt).toBe(once.systemPrompt);
+ expect(twice.toolDefs).toBe(once.toolDefs);
+ });
+
+ it("excludes the compaction request's own messages from the composition", () => {
+ const base: OmniMessage[] = [userText("hi"), assistantText("hello")];
+ const withCompaction: OmniMessage[] = [
+ ...base,
+ compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 4 }),
+ requestBegin(),
+ assistantText("[context_summary] a long summary of everything so far"),
+ tokenUsage(
+ { cache_read: 0, cache_write: 0, output: 0, total: 0 },
+ { cache_read: 0, cache_write: 0, output: 0, total: 0 },
+ ),
+ requestEnd("completed"),
+ compactionEnd({ reason: "context", mode: "summarize", status: "failed" }),
+ ];
+ const plain = buildContextBreakdown(base);
+ const compacted = buildContextBreakdown(withCompaction);
+ expect(compacted.assistantMessages).toBe(plain.assistantMessages);
+ // A failed compaction leaves the context open — only a completed one closes it.
+ expect(compacted.contextClosed).toBe(false);
+ });
+
+ it("reports contextClosed when the shard ends on a completed compaction", () => {
+ const b = buildContextBreakdown([
+ userText("hi"),
+ compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 4 }),
+ compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }),
+ ]);
+ expect(b.contextClosed).toBe(true);
+ });
+});
+
+describe("TraceService.contextBreakdown", () => {
+ let root = "";
+ let harness: ReturnType<typeof makeTraceHarness> | null = null;
+
+ beforeEach(async () => {
+ root = await makeTempRoot();
+ harness = makeTraceHarness(root);
+ });
+
+ afterEach(async () => {
+ harness?.close();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it("reads the newest shard only — an earlier context is not part of the current one", async () => {
+ await writeTraceFile(root, P, A, "2026-08-24", S, 1, [
+ sessionMeta(metaPayload("old prompt")),
+ userText("x".repeat(4000)),
+ ]);
+ await writeTraceFile(root, P, A, "2026-08-24", S, 2, [
+ sessionMeta(metaPayload("new prompt")),
+ toolListReady(TOOLS),
+ userText("short"),
+ ]);
+
+ const b = await harness!.service.contextBreakdown(P, A, S);
+ expect(b.systemPrompt).toBe(approximateTokens("new prompt"));
+ expect(b.userMessages).toBe(buildContextBreakdown([userText("short")]).userMessages);
+ expect(harness!.shardReads).toHaveLength(1);
+ expect(harness!.shardReads[0]).toContain("_002.jsonl");
+ });
+
+ it("answers with zeros for a Session that has no Trace", async () => {
+ const b = await harness!.service.contextBreakdown(P, A, "session-nonexistent");
+ expect(b).toEqual({
+ systemPrompt: 0,
+ toolDefs: 0,
+ userMessages: 0,
+ assistantMessages: 0,
+ toolRequests: 0,
+ toolResults: 0,
+ total: 0,
+ topTools: [],
+ contextClosed: false,
+ });
+ });
+});
+
+describe("compactionThresholdFor", () => {
+ it("caps the configured threshold at what the window leaves room for", () => {
+ // 2048 tokens of headroom: the compaction request's own prompt and summary have to fit.
+ expect(compactionThresholdFor(256_000, 200_000)).toBe(197_952);
+ // Configured below the cap: taken as configured.
+ expect(compactionThresholdFor(100_000, 1_000_000)).toBe(100_000);
+ });
+
+ it("falls back to the seeded threshold when the Agent configures none", () => {
+ expect(compactionThresholdFor(undefined, 1_000_000)).toBe(256_000);
+ });
+
+ it("derives from the assumed window when the model configures none", () => {
+ expect(compactionThresholdFor(256_000, undefined)).toBe(125_952);
+ });
+
+ it("has nothing to mark when compaction is off or the threshold is not inside the window", () => {
+ expect(compactionThresholdFor(-1, 200_000)).toBeNull();
+ expect(compactionThresholdFor(0, 200_000)).toBeNull();
+ // An implausibly small window is treated as unconfigured, so the derivation reasons from the
+ // assumed default instead — a threshold far outside the gauge it would be drawn on.
+ expect(compactionThresholdFor(256_000, 2000)).toBeNull();
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 188975fb..a3c80f81 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -73,6 +73,7 @@ import type {
ServerSettingsResponse,
ServerSettingsUpdateRequest,
SessionCategory,
+ SessionContextResponse,
SessionCreateRequest,
SessionCreateResponse,
SessionForkRequest,
@@ -615,6 +616,14 @@ export const postCompact = (sessionId: string) =>
body: {},
});
+/**
+ * Composition of the Session's current model context (the chat page's context-ring detail panel).
+ * A snapshot read from the newest Trace shard on each call, not a live counter: the figures are
+ * estimates whose value is the *shares* they give the measured occupancy.
+ */
+export const getSessionContext = (sessionId: string) =>
+ apiFetch<SessionContextResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/context`);
+
// Trace browsing & performance analysis -----------------------------------------------------------
export const getSessionTraces = (sessionId: string) =>
diff --git a/packages/web/src/components/ui/token-donut.tsx b/packages/web/src/components/ui/token-donut.tsx
index 3c433d56..5ad2ed24 100644
--- a/packages/web/src/components/ui/token-donut.tsx
+++ b/packages/web/src/components/ui/token-donut.tsx
@@ -12,8 +12,8 @@
* Segments use the site-wide TOKEN_COLORS (works in both light/dark); the base
* ring uses a currentColor gray.
* The context usage under the chat page's input box is a **single-color,
- * single-value** ring (total only), custom-drawn in chat-input — it doesn't use
- * this component.
+ * single-value** ring (total only), custom-drawn in context-gauge — it doesn't
+ * use this component.
*/
import { TOKEN_COLORS } from "../../lib/token-colors";
import { humanizeTokens } from "../../lib/format";
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index dd5b2196..cb7b7b72 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -89,7 +89,6 @@ import type {
} from "@prismshadow/penguin-server/api";
import { S } from "../../lib/strings";
import { formatBytes, humanizeTokens } from "../../lib/format";
-import { resolveContextWindow } from "../../lib/context";
import { useLocale } from "../../state/locale";
import { useAuth } from "../../state/auth";
import { agentDisplayName } from "../../state/project";
@@ -124,9 +123,9 @@ import type { HistoryStep } from "./input-history";
import { isStopAction, midRunAction } from "./composer-send";
import { PAPERCLIP_ICON } from "./attached-files-banner";
import { FileDropZone } from "./drop-zone";
+import { ContextGauge } from "./context-gauge";
import { splitDroppedFiles } from "../../lib/file-drop";
import { splitBySize } from "../../lib/upload-limits";
-import { toneInk } from "../../lib/tone";
const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];
@@ -630,74 +629,6 @@ interface SlashCommand {
run: () => void;
}
-/**
- * Context usage: a **single-color** ring indicator (only conveys total usage, no bucketing) +
- * `used/window` (amber above 80%, red above 95%). When the model has no `context_window`
- * configured, resolveContextWindow falls back to 128000 and the ring is drawn as usual — the
- * usage ratio always has a reference point, instead of degrading into a lone number when config
- * is missing.
- *
- * `unknown` (after a successful compaction, before the next regular Request reports usage): draws
- * an empty ring, value shown as `—`. **Must not be drawn as 0** — that would claim the context
- * has been cleared, while the summary itself still occupies tokens; at this point we simply
- * haven't measured yet, not measured to be zero.
- */
-function ContextGauge({
- now,
- window: win,
- unknown = false,
-}: {
- now: number;
- window?: number;
- unknown?: boolean;
-}) {
- const max = resolveContextWindow(win);
- const pct = unknown ? 0 : Math.min(1, now / max);
- const color =
- unknown || pct <= 0.8
- ? "text-gray-400 dark:text-gray-500"
- : pct > 0.95
- ? toneInk.danger
- : toneInk.attention;
- const R = 5;
- const C = 2 * Math.PI * R;
- return (
- <span
- title={unknown ? S.chat.contextUnknown : `${S.chat.contextUsage} ${Math.round(pct * 100)}%`}
- className={`flex shrink-0 items-center gap-1 font-mono ${color}`}
- >
- <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden className="block shrink-0">
- <circle
- cx="7"
- cy="7"
- r={R}
- fill="none"
- stroke="currentColor"
- strokeOpacity="0.25"
- strokeWidth="2"
- />
- <circle
- cx="7"
- cy="7"
- r={R}
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeDasharray={`${C * pct} ${C}`}
- transform="rotate(-90 7 7)"
- />
- </svg>
- {/* The ring alone carries the meaning on phones: the numbers hide below @md (the title
- still shows the exact usage), keeping the right-hand control group inside a 320px
- viewport in the running state. */}
- <span className="hidden @md:inline">
- {unknown ? "—" : humanizeTokens(now)}/{humanizeTokens(max)}
- </span>
- </span>
- );
-}
-
/**
* One file attachment staged in the composer. `dataUrl` is the base64 `data:` URL sent as the
* task input's `file` part; `name` / `size` only feed the chip (the server decides the name the
@@ -848,6 +779,7 @@ export function ChatInput({
contextWindow,
contextNow,
contextStale = false,
+ sessionId,
vision,
approvalMode,
onChangeApprovalMode,
@@ -990,6 +922,13 @@ export function ChatInput({
contextNow: number;
/** After a successful compaction, before the next regular Request reports usage: usage is **unknown** (not 0); the ring is drawn empty and the value shown as `—`. */
contextStale?: boolean;
+ /**
+ * Enables the context ring's composition panel, which is served by a Session-level endpoint.
+ * Omitted in the draft composer (no Session yet) and in the subagent composer (a child Session
+ * is not registered in the sessions table, so the endpoint cannot resolve it) — the ring stays
+ * the plain readout it has always been there.
+ */
+ sessionId?: string;
/** Whether the current model supports image input (models config's vision; assumed supported by default). */
vision: boolean;
approvalMode: ApprovalMode;
@@ -2693,6 +2632,7 @@ export function ChatInput({
now={contextNow}
unknown={contextStale}
{...(contextWindow !== undefined ? { window: contextWindow } : {})}
+ {...(sessionId !== undefined ? { sessionId } : {})}
/>
)}
{/* Draft state: conversation-time thinking level (backed by Agent settings), docked left of the model selector. */}
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index c1427d91..ceb967b4 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -1611,6 +1611,7 @@ export function ChatPage() {
{...(contextWindow !== undefined ? { contextWindow } : {})}
contextNow={stream.model.stats.contextNow}
contextStale={stream.model.stats.contextStale}
+ sessionId={selected.sessionId}
vision={vision}
approvalMode={selected.approvalMode}
onChangeApprovalMode={onChangeApprovalMode}
diff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsx
new file mode 100644
index 00000000..6038e014
--- /dev/null
+++ b/packages/web/src/features/chat/context-gauge.tsx
@@ -0,0 +1,399 @@
+/**
+ * Context usage gauge in the composer toolbar, and the composition panel behind it.
+ *
+ * The resting state is the ring alone: a **single-colour** indicator of total occupancy (no
+ * bucketing), turning amber past 80% and red past 95%. The exact `used/window` figures are not
+ * printed beside it — the panel a click away leads with them, and hovering the ring names them
+ * too. When the model has no `context_window` configured, resolveContextWindow falls back to
+ * 128000 and the ring is drawn as usual, so the ratio always has a reference point.
+ *
+ * `unknown` (a compaction succeeded and the next regular Request has not reported usage yet)
+ * draws an empty ring. **Never a full-looking 0**: that would claim the context had been cleared
+ * while the summary itself occupies tokens. Nothing has been measured yet, which is not the same
+ * as having measured zero — and the panel says exactly that rather than describing the context
+ * that was just compacted away.
+ *
+ * Given a `sessionId` the ring becomes a button that discloses the panel, which answers what the
+ * ring cannot: what the context is full of. The server splits the Session's newest Trace shard —
+ * one shard is one complete model context — into six parts and ranks the tools whose traffic
+ * occupies the most of it. Those figures come from a character heuristic, not a tokenizer (this
+ * project bundles none), so only their **shares** are used: each part is drawn as its share of
+ * `now`, the measured occupancy the ring itself shows. The parts therefore always add up to the
+ * figure in the panel header, and the estimate's absolute error never reaches the display; the
+ * `~` on every derived value marks what is still an approximation.
+ *
+ * The bar runs the full **context window**, so its filled run is the occupancy the ring shows and
+ * a dashed mark says where compaction will fire — how much room is left before the context is
+ * summarized away is the thing that decides what to do next. The parts subdivide that filled run;
+ * their exact shares are the legend's job, since at low occupancy the run is only a few pixels
+ * wide. Hovering a segment or its legend row links the two: the row lights up and the other
+ * segments fade.
+ *
+ * The panel is portaled to document.body and positioned against viewport coordinates by
+ * usePortalPanel, so the composer's own overflow cannot clip it, and it closes on outside click /
+ * Esc / scroll / resize. It opens upward on its own: the composer sits at the bottom of the page,
+ * so there is never room below.
+ */
+import { useEffect, useId, useState } from "react";
+import { createPortal } from "react-dom";
+import type { SessionContextResponse } from "@prismshadow/penguin-server/api";
+import { getSessionContext } from "../../api/endpoints";
+import { usePortalPanel } from "../../components/ui/use-portal-panel";
+import { resolveContextWindow } from "../../lib/context";
+import { formatPercent, humanizeTokens } from "../../lib/format";
+import { S } from "../../lib/strings";
+import { toneInk } from "../../lib/tone";
+import { contextComposition } from "./context-parts";
+import type { ContextPartKey } from "./context-parts";
+
+/**
+ * Panel geometry. The width is applied inline rather than as a `w-*` class because the same
+ * number has to reach usePortalPanel, which clamps the left edge with it — a rem-based class
+ * would resolve against the app's root font size and drift from the pixel the clamp assumed,
+ * letting the panel hang off the right edge on a narrow viewport. The max-width matches the
+ * hook's own 16px viewport margin on both sides. The height only decides up or down.
+ */
+const PANEL_WIDTH = 300;
+const PANEL_MAX_WIDTH = "calc(100vw - 32px)";
+const PANEL_HEIGHT = 264;
+
+/** Smallest painted width (px) of the filled run, so a context with a few hundred tokens in it still shows a mark rather than nothing. */
+const MIN_FILL_PX = 2;
+
+/** How far (px) the compaction mark runs past the bar top and bottom: a 9px dash inside the bar reads as a dot, an 18px one reads as dashed. */
+const MARK_OVERHANG_PX = 4;
+
+type PanelState =
+ { status: "loading" } | { status: "failed" } | { status: "ready"; data: SessionContextResponse };
+
+export function ContextGauge({
+ now,
+ window: win,
+ unknown = false,
+ sessionId,
+}: {
+ now: number;
+ window?: number;
+ unknown?: boolean;
+ /** Enables the composition panel. Omitted where no Session-level endpoint can serve it (the subagent composer), leaving the ring a plain readout. */
+ sessionId?: string;
+}) {
+ const max = resolveContextWindow(win);
+ const pct = unknown ? 0 : Math.min(1, now / max);
+ const [open, setOpen] = useState(false);
+ const panelId = useId();
+ const { triggerRef, panelRef, position } = usePortalPanel({
+ open,
+ onClose: () => setOpen(false),
+ estimatedHeight: PANEL_HEIGHT,
+ panelWidth: PANEL_WIDTH,
+ });
+
+ const color =
+ unknown || pct <= 0.8
+ ? "text-gray-400 dark:text-gray-500"
+ : pct > 0.95
+ ? toneInk.danger
+ : toneInk.attention;
+ // The ring draws no numbers, so its accessible name carries them: the ratio AND the figures it
+ // was computed from, which is all the subagent composer's panel-less ring can offer.
+ const usageText = unknown
+ ? S.chat.contextUnknown
+ : `${S.chat.contextUsage} ${Math.round(pct * 100)}% · ${humanizeTokens(now)}/${humanizeTokens(max)}`;
+ const R = 5;
+ const C = 2 * Math.PI * R;
+ const gauge = (
+ <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden className="block shrink-0">
+ <circle
+ cx="7"
+ cy="7"
+ r={R}
+ fill="none"
+ stroke="currentColor"
+ strokeOpacity="0.25"
+ strokeWidth="2"
+ />
+ <circle
+ cx="7"
+ cy="7"
+ r={R}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeDasharray={`${C * pct} ${C}`}
+ transform="rotate(-90 7 7)"
+ />
+ </svg>
+ );
+ // Same box as every other icon control on this toolbar (h-8 w-8, matching the model selector
+ // and the send button): a 14px ring in a 23px hit area sat visibly short of its neighbours.
+ const shell = `flex h-8 w-8 shrink-0 items-center justify-center ${color}`;
+
+ if (sessionId === undefined) {
+ return (
+ <span title={usageText} aria-label={usageText} role="img" className={shell}>
+ {gauge}
+ </span>
+ );
+ }
+ return (
+ <>
+ {/* Hover paints only a background, not the ink its neighbours also change: the ring's colour
+ is the warning ladder, and a hover tone would overwrite the very thing it reports. */}
+ <button
+ ref={triggerRef}
+ type="button"
+ title={usageText}
+ aria-label={usageText}
+ aria-expanded={open}
+ aria-controls={panelId}
+ onClick={() => setOpen((v) => !v)}
+ className={`${shell} rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}
+ >
+ {gauge}
+ </button>
+ {open &&
+ position &&
+ createPortal(
+ <div
+ ref={panelRef}
+ id={panelId}
+ role="group"
+ aria-label={S.chat.contextComposition}
+ style={{
+ position: "fixed",
+ top: position.topPx,
+ bottom: position.bottomPx,
+ left: position.left,
+ width: PANEL_WIDTH,
+ maxWidth: PANEL_MAX_WIDTH,
+ }}
+ className="anim-pop z-[60] rounded-md border border-gray-200 bg-white p-2.5 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900"
+ >
+ <ContextPanel sessionId={sessionId} now={now} max={max} pct={pct} unknown={unknown} />
+ </div>,
+ document.body,
+ )}
+ </>
+ );
+}
+
+function ContextPanel({
+ sessionId,
+ now,
+ max,
+ pct,
+ unknown,
+}: {
+ sessionId: string;
+ now: number;
+ max: number;
+ pct: number;
+ unknown: boolean;
+}) {
+ // A snapshot taken when the panel opens (it only mounts while open), not a live counter: the
+ // endpoint re-reads a whole Trace shard, and the panel closes on any scroll anyway.
+ const [state, setState] = useState<PanelState>({ status: "loading" });
+ // Row id under the pointer — a part key, or `tool:<name>` for the ranking below. One piece of
+ // state for both lists, so a hovered tool row cannot also dim the bar it has no segment in.
+ const [hovered, setHovered] = useState<string | null>(null);
+ useEffect(() => {
+ let cancelled = false;
+ setState({ status: "loading" });
+ getSessionContext(sessionId).then(
+ (data) => {
+ if (!cancelled) setState({ status: "ready", data });
+ },
+ () => {
+ if (!cancelled) setState({ status: "failed" });
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [sessionId]);
+
+ const data = state.status === "ready" ? state.data : null;
+ // `contextClosed` is the server seeing what `unknown` reports from the stream: a completed
+ // compaction, and no measurement of the new context yet. Both say the occupancy is unknown
+ // rather than zero, so both render `—` instead of describing a context that no longer exists.
+ const unmeasured = unknown || data?.contextClosed === true;
+ const composition = data === null ? null : contextComposition(data, now);
+ const hoveredPart = composition?.parts.some((p) => p.key === hovered) ? hovered : null;
+ // Only drawn when it falls inside the bar's scale; the server already returns null for a
+ // Session whose compaction is off or whose threshold sits past the window.
+ const compactAt =
+ data !== null && data.compactionThreshold !== null && data.compactionThreshold < max
+ ? data.compactionThreshold
+ : null;
+
+ return (
+ <>
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="flex items-baseline gap-1.5">
+ <span className="text-gray-500 dark:text-gray-400">{S.chat.contextUsage}</span>
+ <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
+ {unmeasured ? "—" : formatPercent(pct)}
+ </span>
+ </span>
+ <span className="font-mono text-gray-500 dark:text-gray-400">
+ {unmeasured ? "—" : humanizeTokens(now)} / {humanizeTokens(max)}
+ </span>
+ </div>
+
+ {unmeasured ? (
+ <p className="mt-2 leading-relaxed text-gray-400 dark:text-gray-500">
+ {S.chat.contextUnknownHint}
+ </p>
+ ) : state.status === "loading" ? (
+ <p className="mt-2 text-gray-400 dark:text-gray-500">{S.common.loading}</p>
+ ) : state.status === "failed" ? (
+ <p className="mt-2 text-gray-400 dark:text-gray-500">{S.chat.contextBreakdownFailed}</p>
+ ) : composition === null ? (
+ <p className="mt-2 text-gray-400 dark:text-gray-500">{S.chat.contextBreakdownEmpty}</p>
+ ) : (
+ <>
+ {/* The bar's scale is the whole window: the filled run is the occupancy, the rest is
+ headroom, and the dashed mark is where compaction fires. Squared off, and with no
+ gaps between the fills — once the bar carries an absolute position scale, a surface
+ gap would push every fill after it off the coordinate the mark is drawn on. What
+ keeps neighbouring hues apart is the palette's own adjacent-pair separation.
+ Decorative: the legend below carries every figure, which is why the bar is hidden
+ from assistive tech and offers hover rather than focus. */}
+ <div
+ aria-hidden
+ className="relative mt-2 h-2 bg-gray-200 dark:bg-gray-800"
+ style={{ marginBottom: MARK_OVERHANG_PX }}
+ >
+ <div
+ className="absolute inset-y-0 left-0 flex overflow-hidden"
+ style={{ width: `${(now / max) * 100}%`, minWidth: now > 0 ? MIN_FILL_PX : 0 }}
+ >
+ {composition.parts.map((p) =>
+ p.tokens > 0 ? (
+ <span
+ key={p.key}
+ title={`${PART_LABELS[p.key]()} ~${humanizeTokens(p.tokens)} · ${p.percent}%`}
+ onMouseEnter={() => setHovered(p.key)}
+ onMouseLeave={() => setHovered(null)}
+ style={{ flexGrow: p.tokens, flexBasis: 0 }}
+ className={`h-full transition-opacity duration-150 ${p.color} ${
+ hoveredPart !== null && hoveredPart !== p.key ? "opacity-25" : ""
+ }`}
+ />
+ ) : null,
+ )}
+ </div>
+ {compactAt !== null && (
+ <span
+ title={S.chat.contextCompactAt(humanizeTokens(compactAt))}
+ style={{
+ left: `${(compactAt / max) * 100}%`,
+ top: -MARK_OVERHANG_PX,
+ bottom: -MARK_OVERHANG_PX,
+ }}
+ className="absolute border-l border-dashed border-gray-500 dark:border-gray-400"
+ />
+ )}
+ </div>
+
+ <ul className="mt-2 space-y-0.5">
+ {composition.parts.map((p) => (
+ <ShareRow
+ key={p.key}
+ label={PART_LABELS[p.key]()}
+ swatch={p.color}
+ tokens={p.tokens}
+ percent={p.percent}
+ highlighted={hovered === p.key}
+ onHover={(on) => setHovered(on ? p.key : null)}
+ />
+ ))}
+ </ul>
+
+ {composition.tools.length > 0 && (
+ <>
+ <p
+ title={S.chat.contextTopToolsHint}
+ className="mt-2 border-t border-gray-100 pt-1.5 text-gray-400 dark:border-gray-800 dark:text-gray-500"
+ >
+ {S.chat.contextTopTools}
+ </p>
+ <ul className="mt-1 space-y-0.5">
+ {composition.tools.map((t) => (
+ <ShareRow
+ key={t.name}
+ label={t.name}
+ mono
+ tokens={t.tokens}
+ percent={t.percent}
+ highlighted={hovered === `tool:${t.name}`}
+ onHover={(on) => setHovered(on ? `tool:${t.name}` : null)}
+ />
+ ))}
+ </ul>
+ </>
+ )}
+ </>
+ )}
+ </>
+ );
+}
+
+/** Part label lookups, read at render time: `S` is a live binding swapped on locale change. */
+const PART_LABELS: Record<ContextPartKey, () => string> = {
+ systemPrompt: () => S.chat.contextPartSystemPrompt,
+ toolDefs: () => S.chat.contextPartToolDefs,
+ userMessages: () => S.chat.contextPartUserMessages,
+ assistantMessages: () => S.chat.contextPartAssistantMessages,
+ toolRequests: () => S.chat.contextPartToolRequests,
+ toolResults: () => S.chat.contextPartToolResults,
+};
+
+/** One `swatch · label · ~tokens · percent` line, shared by the six parts and the tool ranking. */
+function ShareRow({
+ label,
+ swatch,
+ tokens,
+ percent,
+ mono = false,
+ highlighted = false,
+ onHover,
+}: {
+ label: string;
+ /** Legend colour of the matching bar segment; absent for the tool ranking, which has no segment. */
+ swatch?: string;
+ tokens: number;
+ /** Already a whole percent (apportioned for the parts, rounded for the tools) — not re-rounded here. */
+ percent: number;
+ mono?: boolean;
+ highlighted?: boolean;
+ onHover?: (on: boolean) => void;
+}) {
+ return (
+ <li
+ onMouseEnter={() => onHover?.(true)}
+ onMouseLeave={() => onHover?.(false)}
+ className={`-mx-1 flex items-center gap-1.5 rounded px-1 py-px transition-colors duration-150 ${
+ highlighted ? "bg-gray-100 dark:bg-gray-800" : ""
+ }`}
+ >
+ {swatch !== undefined && (
+ <span aria-hidden className={`h-2 w-2 shrink-0 rounded-[2px] ${swatch}`} />
+ )}
+ <span
+ title={label}
+ className={`min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300 ${mono ? "font-mono" : ""}`}
+ >
+ {label}
+ </span>
+ <span className="shrink-0 font-mono font-medium text-gray-900 dark:text-gray-100">
+ ~{humanizeTokens(tokens)}
+ </span>
+ <span className="w-8 shrink-0 text-right font-mono text-gray-400 dark:text-gray-500">
+ {percent}%
+ </span>
+ </li>
+ );
+}
diff --git a/packages/web/src/features/chat/context-parts.ts b/packages/web/src/features/chat/context-parts.ts
new file mode 100644
index 00000000..6dd06780
--- /dev/null
+++ b/packages/web/src/features/chat/context-parts.ts
@@ -0,0 +1,120 @@
+/**
+ * Context composition rows: the server's estimated parts, re-expressed on the scale the context
+ * ring actually shows.
+ *
+ * The server splits a Session's current model context into six parts and ranks the tools whose
+ * traffic occupies the most of it, sizing everything with a character heuristic rather than a
+ * tokenizer (this project bundles none). Taken as counts those figures would contradict the
+ * ring, which reports the provider's own measurement; taken as **shares** they are exactly what
+ * the ring cannot say. So each part is expressed as its share of the estimate, applied to `now`
+ * — the parts add up to the occupancy in the panel header, and the estimate's absolute error
+ * never reaches the display.
+ *
+ * Pure, no React: unit-tested in test/context-parts.test.ts, rendered by context-gauge.tsx.
+ */
+import type { SessionContextResponse } from "@prismshadow/penguin-server/api";
+import { CONTEXT_PART_COLORS } from "../../lib/category-colors";
+
+/** The six parts, by the DTO field each reads. Callers resolve a key to its label at render time — `S` is a live binding and must not be captured in a module constant. */
+export type ContextPartKey =
+ | "systemPrompt"
+ | "toolDefs"
+ | "userMessages"
+ | "assistantMessages"
+ | "toolRequests"
+ | "toolResults";
+
+/**
+ * Display order of the parts, from the fixed prefix every request carries to the traffic that
+ * accumulates during a conversation. It is also the order CONTEXT_PART_COLORS was validated in —
+ * the two are zipped below, so reordering either without the other silently repaints the legend.
+ */
+export const CONTEXT_PART_KEYS: readonly ContextPartKey[] = [
+ "systemPrompt",
+ "toolDefs",
+ "userMessages",
+ "assistantMessages",
+ "toolRequests",
+ "toolResults",
+];
+
+export interface ContextShare {
+ /** Estimated tokens re-expressed on the measured scale. */
+ tokens: number;
+ /** Whole-percent share of the whole context. */
+ percent: number;
+}
+
+export interface ContextPartShare extends ContextShare {
+ key: ContextPartKey;
+ /** Background class of this part's bar segment and legend swatch. */
+ color: string;
+}
+
+export interface ContextToolShare extends ContextShare {
+ name: string;
+}
+
+export interface ContextComposition {
+ parts: ContextPartShare[];
+ /** Tools ranked by the context their calls and results occupy; their shares are of the whole context, so they do not sum to 100. */
+ tools: ContextToolShare[];
+}
+
+/**
+ * Composition rows for a measured occupancy of `now` tokens, or **null** when there is nothing
+ * to break down — an estimate of zero (a Session whose context holds no recorded message yet),
+ * or a context a completed compaction has closed, whose composition describes what was
+ * compacted away rather than what the model now carries.
+ */
+export function contextComposition(
+ data: SessionContextResponse,
+ now: number,
+): ContextComposition | null {
+ if (data.contextClosed || data.total <= 0) return null;
+ const estimates = CONTEXT_PART_KEYS.map((key) => data[key]);
+ // Apportioned rather than rounded independently: a panel whose parts read 50/40/9/1/1/1 does
+ // not describe one context, and its own header would contradict it. Both columns are laid out
+ // so they land on exactly the measured occupancy and exactly 100%.
+ const tokens = apportion(estimates, now);
+ const percents = apportion(estimates, 100);
+ return {
+ parts: CONTEXT_PART_KEYS.map((key, i) => ({
+ key,
+ color: CONTEXT_PART_COLORS[i] ?? "",
+ tokens: tokens[i] ?? 0,
+ percent: percents[i] ?? 0,
+ })),
+ // A ranking, not a partition: these are shares of the whole context and sum to less than it,
+ // so there is nothing to apportion against — each is simply rounded.
+ tools: data.topTools.map((t) => ({
+ name: t.name,
+ tokens: Math.round((t.tokens / data.total) * now),
+ percent: Math.round((t.tokens / data.total) * 100),
+ })),
+ };
+}
+
+/**
+ * Splits `total` across `values` in proportion, as whole numbers that sum to exactly `total`
+ * (largest remainder: everyone takes their floor, and the leftover units go to the largest
+ * fractional parts first). Independent rounding would leave the column short or over by a few
+ * units — visible as a percentage column adding up to 102.
+ */
+function apportion(values: readonly number[], total: number): number[] {
+ const sum = values.reduce((n, v) => n + v, 0);
+ if (sum <= 0) return values.map(() => 0);
+ const exact = values.map((v) => (v / sum) * total);
+ const out = exact.map((v) => Math.floor(v));
+ let left = Math.round(total) - out.reduce((n, v) => n + v, 0);
+ const order = exact
+ .map((v, i) => ({ i, frac: v - Math.floor(v) }))
+ // Index breaks ties so the leftover always lands on the same part for the same input.
+ .sort((a, b) => b.frac - a.frac || a.i - b.i);
+ for (const { i } of order) {
+ if (left <= 0) break;
+ out[i] = (out[i] ?? 0) + 1;
+ left -= 1;
+ }
+ return out;
+}
diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsx
index 1a7c8b77..182a2e84 100644
--- a/packages/web/src/features/chat/task-stats-line.tsx
+++ b/packages/web/src/features/chat/task-stats-line.tsx
@@ -21,7 +21,7 @@
* composition** — how much of the input hit cache is a debugging-level detail that belongs to the
* Trace page's turn card (which shows cache hits and hit rate); the current **context usage** is
* likewise not repeated here — it's expressed by the ring below the input box (see ContextGauge
- * in chat-input).
+ * in context-gauge), which also discloses what that context is made of.
* This line sits right below this turn's AI reply and simultaneously **serves as that reply's
* footer**: it provides the reply timestamp and copy button at the end, so the assistant message
* itself doesn't render a separate one (otherwise two copy buttons would pop up in the same spot).
diff --git a/packages/web/src/lib/category-colors.ts b/packages/web/src/lib/category-colors.ts
index 48ccc5f4..ff3cdfd3 100644
--- a/packages/web/src/lib/category-colors.ts
+++ b/packages/web/src/lib/category-colors.ts
@@ -39,6 +39,31 @@ export function seriesColor(i: number): SeriesColor {
return SERIES_COLORS[i % SERIES_COLORS.length]!;
}
+/**
+ * The six parts of a model context, in the order the chat page's context panel lists them:
+ * system prompt, tool definitions, user messages, model messages, tool requests, tool results.
+ * Identity again, not severity — no part of a context is worse than another — so these belong
+ * here and not in tone.ts, and they are a sequence of their own rather than a longer
+ * SERIES_COLORS: that array's length is also the cost center's fold cap.
+ *
+ * **The order is part of the palette.** The legend rows are drawn in the same order as the bar
+ * segments, so a reader only ever has to separate neighbours; this sequence is what clears the
+ * adjacent-pair gates in both modes (worst adjacent ΔE 21.1 simulated for protanopia and
+ * deuteranopia, 22.1 unsimulated; OKLab ×100). Reordering the parts means re-checking the
+ * palette, not just moving rows. Six hues cannot also clear those gates for *arbitrary* pairs —
+ * no six can — so the weakest non-neighbour pair here sits at ΔE 13 unsimulated, and the legend
+ * carries every part's own value beside its name so colour never has to be read alone. Three
+ * steps sit under 3:1 against white for the same reason.
+ */
+export const CONTEXT_PART_COLORS: readonly string[] = [
+ "bg-sky-500 dark:bg-sky-600",
+ "bg-amber-500 dark:bg-amber-600",
+ "bg-fuchsia-500 dark:bg-fuchsia-600",
+ "bg-rose-500",
+ "bg-violet-500",
+ "bg-emerald-500 dark:bg-emerald-600",
+];
+
/**
* The neutral a series wears when it stands for "the rest" rather than one
* identity — the cost center's folded tail, the eval center's untagged runs.
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 124438c1..c0ff6726 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1538,6 +1538,21 @@ Scenarios:
moreGroups: (n: number) => `More groups (${n})`,
contextUsage: "Context usage",
contextUnknown: "Context usage: unknown until the next request reports it",
+ contextComposition: "Context composition",
+ contextPartSystemPrompt: "System prompt",
+ contextPartToolDefs: "Tool definitions",
+ contextPartUserMessages: "User messages",
+ contextPartAssistantMessages: "Model messages",
+ contextPartToolRequests: "Tool requests",
+ contextPartToolResults: "Tool results",
+ contextTopTools: "Top 5 tools",
+ contextCompactAt: (n: string): string => `Compaction threshold ${n}`,
+ contextTopToolsHint:
+ "Ranked by the context each tool's calls and results occupy (definitions count under “Tool definitions”)",
+ contextUnknownHint:
+ "Just compacted — the next request reports the usage, and the composition with it",
+ contextBreakdownEmpty: "Nothing in the current context to break down yet",
+ contextBreakdownFailed: "Could not read the context composition",
slashHint: "Type / for commands",
switchAgent: "Hand off to another agent — opens a new session on send",
switchAgentTitle: "Choose agent",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 0a39c62a..1d6e69f3 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1496,6 +1496,21 @@ Benchmark:
moreGroups: (n: number) => `更多分组(${n})`,
contextUsage: "上下文占用",
contextUnknown: "上下文占用:压缩后待下次请求回报",
+ /** Context ring -> composition panel: the trigger's accessible name, the six part labels, the tool ranking, and the panel's empty / failed states. */
+ contextComposition: "上下文构成",
+ contextPartSystemPrompt: "系统提示词",
+ contextPartToolDefs: "工具定义",
+ contextPartUserMessages: "用户消息",
+ contextPartAssistantMessages: "模型消息",
+ contextPartToolRequests: "工具请求",
+ contextPartToolResults: "工具结果",
+ contextTopTools: "工具用量 Top 5",
+ /** Tooltip of the dashed mark on the context bar; n = the humanized threshold. */
+ contextCompactAt: (n: string): string => `压缩阈值 ${n}`,
+ contextTopToolsHint: "按每个工具的调用与结果所占上下文排序(工具定义计入「工具定义」一项)",
+ contextUnknownHint: "刚压缩过,占用待下次请求回报,届时才能给出构成",
+ contextBreakdownEmpty: "当前上下文还没有可统计的内容",
+ contextBreakdownFailed: "读取上下文构成失败",
slashHint: "输入 / 使用命令",
/** `/agent` handoff: command description, picker title, search box, no-match hint, and the staged target's description and remove button. */
switchAgent: "交给其他 Agent,发送时开启新会话",
diff --git a/packages/web/test/context-parts.test.ts b/packages/web/test/context-parts.test.ts
new file mode 100644
index 00000000..dfdea229
--- /dev/null
+++ b/packages/web/test/context-parts.test.ts
@@ -0,0 +1,102 @@
+/**
+ * Context composition rows: the estimate-to-measured rescaling behind the context ring's panel,
+ * and the palette it is zipped with.
+ */
+import { describe, expect, it } from "vitest";
+import type { SessionContextResponse } from "@prismshadow/penguin-server/api";
+import { CONTEXT_PART_KEYS, contextComposition } from "../src/features/chat/context-parts";
+import { CONTEXT_PART_COLORS } from "../src/lib/category-colors";
+
+function response(over: Partial<SessionContextResponse> = {}): SessionContextResponse {
+ const base = {
+ systemPrompt: 1000,
+ toolDefs: 4000,
+ userMessages: 1000,
+ assistantMessages: 2000,
+ toolRequests: 2000,
+ toolResults: 10000,
+ topTools: [
+ { name: "read_file", tokens: 6000 },
+ { name: "exec_command", tokens: 4000 },
+ ],
+ contextClosed: false,
+ compactionThreshold: null,
+ ...over,
+ };
+ return {
+ ...base,
+ total:
+ over.total ??
+ base.systemPrompt +
+ base.toolDefs +
+ base.userMessages +
+ base.assistantMessages +
+ base.toolRequests +
+ base.toolResults,
+ };
+}
+
+describe("contextComposition", () => {
+ it("rescales the estimate so the parts add up to the measured occupancy", () => {
+ // Estimate totals 20000; the provider measured 50000. Each part keeps its share.
+ const c = contextComposition(response(), 50_000)!;
+ expect(c.parts.map((p) => p.tokens)).toEqual([2500, 10_000, 2500, 5000, 5000, 25_000]);
+ expect(c.parts.map((p) => p.percent)).toEqual([5, 20, 5, 10, 10, 50]);
+ expect(c.parts.reduce((n, p) => n + p.tokens, 0)).toBe(50_000);
+ expect(c.parts.reduce((n, p) => n + p.percent, 0)).toBe(100);
+ });
+
+ it("apportions both columns so neither drifts off the total it describes", () => {
+ // Independently rounded, these six shares read 50/40/1/9/1/1 — 102% of a context whose
+ // parts would also miss the header figure.
+ const c = contextComposition(
+ response({
+ systemPrompt: 3279,
+ toolDefs: 2616,
+ userMessages: 65,
+ assistantMessages: 562,
+ toolRequests: 38,
+ toolResults: 51,
+ topTools: [],
+ }),
+ 350,
+ )!;
+ expect(c.parts.reduce((n, p) => n + p.percent, 0)).toBe(100);
+ expect(c.parts.reduce((n, p) => n + p.tokens, 0)).toBe(350);
+ });
+
+ it("gives the parts the palette in its documented order", () => {
+ const c = contextComposition(response(), 1000)!;
+ expect(c.parts.map((p) => p.key)).toEqual([...CONTEXT_PART_KEYS]);
+ expect(c.parts.map((p) => p.color)).toEqual([...CONTEXT_PART_COLORS]);
+ // Zipped by index: a part added on one side and not the other would silently lose its colour.
+ expect(CONTEXT_PART_COLORS).toHaveLength(CONTEXT_PART_KEYS.length);
+ expect(new Set(CONTEXT_PART_COLORS).size).toBe(CONTEXT_PART_COLORS.length);
+ });
+
+ it("scales the tool ranking on the same basis, as shares of the whole context", () => {
+ const c = contextComposition(response(), 50_000)!;
+ expect(c.tools).toEqual([
+ { name: "read_file", tokens: 15_000, percent: 30 },
+ { name: "exec_command", tokens: 10_000, percent: 20 },
+ ]);
+ // A ranking inside two of the six parts: it never claims the whole context.
+ expect(c.tools.reduce((n, t) => n + t.percent, 0)).toBeLessThan(100);
+ });
+
+ it("has nothing to break down for an empty estimate or a closed context", () => {
+ const empty = response({
+ systemPrompt: 0,
+ toolDefs: 0,
+ userMessages: 0,
+ assistantMessages: 0,
+ toolRequests: 0,
+ toolResults: 0,
+ topTools: [],
+ });
+ expect(empty.total).toBe(0);
+ expect(contextComposition(empty, 0)).toBeNull();
+ // A completed compaction closed the context these figures describe; the next one is unmeasured.
+ expect(contextComposition(response({ contextClosed: true }), 50_000)).toBeNull();
+ });
+});