feat(webui): visualize context usage by logical round (#5649)

* feat(webui): visualize per-request context reuse

* refactor(webui): report usage by logical round

* fix(webui): align context chart with logical rounds

* refactor(webui): derive turn usage from logical rounds

* fix(webui): polish context usage details
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-04 15:13:17 +08:00
1 parent 8fb7bc34ec
commit 6b82d642fc
35 files changed
+994 -274

No files matched your search

-45
View File
@@ -1013,49 +1013,4 @@ describe("MessageBubble", () => {
expect(screen.queryByLabelText("File attachment")).not.toBeInTheDocument();
});
it("keeps turn usage focused on the completed reply", () => {
const message: UIMessage = {
id: "a-usage",
role: "assistant",
content: "done",
createdAt: Date.now(),
latencyMs: 18_200,
contextWindowTokens: 128_000,
usage: {
prompt_tokens: 12_400,
completion_tokens: 823,
cached_tokens: 9_672,
context_tokens: 8_100,
request_count: 3,
},
};
render(<MessageBubble message={message} />);
const usage = screen.getByText("12.4K in · 823 out · 78% cached · 18s");
expect(usage).toHaveAttribute("data-turn-usage");
expect(usage).not.toHaveAttribute("tabindex");
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
});
it("marks estimated usage and omits cache when the provider did not report it", () => {
const message: UIMessage = {
id: "a-estimated-usage",
role: "assistant",
content: "done",
createdAt: Date.now(),
usage: {
prompt_tokens: 1_250,
completion_tokens: 90,
estimated_tokens: 1_340,
},
};
render(<MessageBubble message={message} />);
const usage = screen.getByText("~1.3K in · ~90 out");
expect(usage).not.toHaveTextContent("cached");
fireEvent.focus(usage);
expect(screen.getByRole("tooltip")).toHaveTextContent("Includes estimated usage");
});
});
+124 -2
View File
@@ -551,16 +551,138 @@ describe("ThreadComposer", () => {
expect(context).not.toHaveTextContent("Context 74.9K / 1M");
expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument();
expect(context).toHaveAccessibleName(
"Context · 74.9K / 1M. 7% used.",
"Context 7%. Open context usage",
);
fireEvent.focus(context);
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).toHaveTextContent("Context · 74.9K / 1M");
expect(tooltip).toHaveTextContent("Context 7%");
expect(tooltip.parentElement).toHaveClass("rounded-full", "px-2.5", "py-1");
expect(tooltip.parentElement).not.toHaveTextContent("Available");
});
it("opens an input-token chart with one bar for each logical round", () => {
render(
<ThreadComposer
onSend={vi.fn()}
modelLabel="gpt-5.6-sol"
modelPreset="gpt-5-6-sol"
modelProvider="openai_codex"
contextUsage={{
contextTokens: 14_700,
contextWindowTokens: 200_000,
}}
recentRoundUsage={[
{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 3, 7, 20),
inputTokens: 18_000,
outputTokens: 280,
cachedTokens: 12_000,
generationMs: 12_000,
},
{
id: "turn-2",
timestamp: Date.UTC(2026, 8, 3, 8, 22),
inputTokens: 29_400,
outputTokens: 416,
cachedTokens: 26_180,
generationMs: 40_000,
},
]}
placeholder="Ask anything..."
/>,
);
fireEvent.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByText("Context")).toBeInTheDocument();
expect(screen.getByText("14.7K / 200K")).toBeInTheDocument();
expect(screen.getByText("Recent rounds")).toBeInTheDocument();
expect(screen.getByText("Input tokens")).toBeInTheDocument();
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(2);
const [smallerBar, largerBar] = screen.getAllByTestId("round-usage-bar");
expect(
Number.parseFloat(smallerBar.style.height) / Number.parseFloat(largerBar.style.height),
).toBeCloseTo(18_000 / 29_400, 5);
expect(largerBar.querySelector(".kv-cache-reused")).toBeInTheDocument();
expect(largerBar.querySelector(".kv-cache-not-reused")).toBeInTheDocument();
expect(screen.queryByText("Reused")).not.toBeInTheDocument();
expect(screen.queryByText("Not reused")).not.toBeInTheDocument();
expect(screen.getByRole("img", {
name: /input tokens 29,400.*KV cache hit rate 89%.*output tokens 416.*generation time 40/i,
})).toBeInTheDocument();
});
it("uses each visible bar as its round detail trigger", async () => {
const user = userEvent.setup();
render(
<ThreadComposer
onSend={vi.fn()}
contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}
recentRoundUsage={[
{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 3, 7, 20),
inputTokens: 18_000,
outputTokens: 280,
cachedTokens: 12_000,
},
{
id: "turn-2",
timestamp: Date.UTC(2026, 8, 3, 8, 22),
inputTokens: 29_400,
outputTokens: 416,
cachedTokens: 26_180,
},
]}
placeholder="Ask anything..."
/>,
);
await user.click(screen.getByTestId("composer-context-usage"));
const firstBar = screen.getByRole("img", { name: /input tokens 18,000/i });
const secondBar = screen.getByRole("img", { name: /input tokens 29,400/i });
expect(firstBar).toHaveAttribute("data-testid", "round-usage-bar");
expect(secondBar).toHaveAttribute("data-testid", "round-usage-bar");
await user.hover(firstBar);
const firstTooltip = await screen.findByRole("tooltip");
expect(within(firstTooltip).getByText("Input tokens")).toBeInTheDocument();
expect(within(firstTooltip).getByText("18,000")).toBeInTheDocument();
await user.click(firstBar);
await user.unhover(firstBar);
await user.hover(secondBar);
const secondTooltip = await screen.findByRole("tooltip");
expect(within(secondTooltip).getByText("Input tokens")).toBeInTheDocument();
expect(within(secondTooltip).getByText("29,400")).toBeInTheDocument();
});
it("keeps context usage visible when the provider omits cache metrics", () => {
render(
<ThreadComposer
onSend={() => {}}
contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}
recentRoundUsage={[{
id: "turn-without-cache-metrics",
timestamp: new Date(2026, 8, 3, 16, 22).getTime(),
inputTokens: 29_400,
outputTokens: 416,
}]}
placeholder="Ask anything..."
/>,
);
fireEvent.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("progressbar", { name: "Context 7%" })).toHaveAttribute(
"aria-valuenow",
"7",
);
const [bar] = screen.getAllByTestId("round-usage-bar");
expect(bar.firstElementChild).toHaveClass("bg-muted-foreground/25");
expect(screen.queryByText("Reused")).not.toBeInTheDocument();
});
it("keeps the thread composer compact while matching the hero style", () => {
render(
<ThreadComposer
+72
View File
@@ -426,6 +426,78 @@ describe("ThreadShell", () => {
);
});
it("renders each logical round in a completed turn as its own usage bar", async () => {
const client = makeClient();
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
if (String(input).includes("websocket%3Ausage-chart/webui-thread")) {
return Promise.resolve(httpJson({
schemaVersion: 3,
messages: [
{
id: "assistant-1",
role: "assistant",
content: "First response",
turnId: "turn-1",
createdAt: 1_000,
usage: {
prompt_tokens: 18_000,
completion_tokens: 280,
cached_tokens: 12_000,
request_count: 2,
},
roundUsages: [
{ prompt_tokens: 8_000, completion_tokens: 120, cached_tokens: 2_000 },
{ prompt_tokens: 10_000, completion_tokens: 160, cached_tokens: 10_000 },
],
},
{
id: "assistant-2",
role: "assistant",
content: "Second response",
turnId: "turn-2",
createdAt: 2_000,
contextWindowTokens: 65_536,
usage: {
prompt_tokens: 29_400,
completion_tokens: 416,
cached_tokens: 26_180,
context_tokens: 14_700,
request_count: 2,
},
roundUsages: [
{ prompt_tokens: 13_000, completion_tokens: 180, cached_tokens: 10_000 },
{ prompt_tokens: 16_400, completion_tokens: 236, cached_tokens: 16_180 },
],
},
] satisfies UIMessage[],
}));
}
return Promise.resolve({
ok: false,
status: 404,
json: async () => ({}),
});
}));
render(wrap(
client,
<ThreadShell
session={session("usage-chart")}
title="Usage chart"
onToggleSidebar={() => {}}
settingsSnapshot={modelSettings("openai-codex/gpt-5.5", "openai_codex")}
/>,
"openai-codex/gpt-5.5",
));
const trigger = await screen.findByTestId("composer-context-usage");
fireEvent.click(trigger);
expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(4);
expect(screen.getByRole("img", {
name: /input tokens 16,400.*KV cache hit rate 99%.*output tokens 236/i,
})).toBeInTheDocument();
});
it("moves the session handle into the pane only when the workbench is split", () => {
const client = makeClient();
const portal = document.createElement("div");