Skip to content

Your lightweight open-source personal agent.

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

chengyongru6b82d642fc11
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index 0131adbd6..27aaa88d3 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -2035,7 +2035,7 @@ class AgentLoop:
):
ctx.suppress_response = True
ctx.usage = result.usage
- ctx.delivery.record_usage(ctx.usage)
+ ctx.delivery.record_usage(result.round_usages)
if ctx.kind is TurnKind.USER:
await turn_continuation.maybe_continue_turn(ctx)
diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py
index c658d448b..41a048c54 100644
--- a/nanobot/agent/runner.py
+++ b/nanobot/agent/runner.py
@@ -126,6 +126,9 @@ class AgentRunResult:
messages: list[dict[str, Any]]
tools_used: list[str] = field(default_factory=list)
usage: LLMUsage | None = None
+ # One entry per runner-visible model round. Recovery dispatches needed to
+ # produce that round's response are folded into the same usage value.
+ round_usages: list[LLMUsage] = field(default_factory=list)
stop_reason: str = "completed"
error: str | None = None
tool_events: list[dict[str, str]] = field(default_factory=list)
@@ -392,6 +395,7 @@ class AgentRunner:
final_content: str | None = None
tools_used: list[str] = []
usage: LLMUsage | None = None
+ round_usages: list[LLMUsage] = []
error: str | None = None
stop_reason = "completed"
tool_events: list[dict[str, str]] = []
@@ -442,7 +446,7 @@ class AgentRunner:
if request_state.compaction is not None
else messages
)
- response = await self._request_model(
+ response, raw_usage = await self._request_model(
spec,
request_messages,
hook,
@@ -468,7 +472,7 @@ class AgentRunner:
response.content,
)
response.content = cleaned_content
- raw_usage = self._record_request_usage(spec, request_state, response)
+ round_usages.append(raw_usage)
context.usage = raw_usage
usage = self._merge_usage(usage, raw_usage)
if reasoning_text and not context.streamed_reasoning:
@@ -614,6 +618,7 @@ class AgentRunner:
transcript=messages,
)
retry_usage = self._record_request_usage(spec, request_state, response)
+ round_usages.append(retry_usage)
usage = self._merge_usage(usage, retry_usage)
raw_usage = self._merge_usage(raw_usage, retry_usage)
context.response = response
@@ -801,6 +806,7 @@ class AgentRunner:
messages,
usage,
request_state=request_state,
+ round_usages=round_usages,
)
if terminal_content is None:
terminal_content = self._max_iterations_fallback(spec)
@@ -819,6 +825,7 @@ class AgentRunner:
messages=messages,
tools_used=tools_used,
usage=usage,
+ round_usages=round_usages,
stop_reason=stop_reason,
error=error,
tool_events=tool_events,
@@ -863,7 +870,7 @@ class AgentRunner:
request_state: ModelRequestState,
malformed_retry: bool = False,
transcript: list[dict[str, Any]] | None,
- ) -> LLMResponse:
+ ) -> tuple[LLMResponse, LLMUsage]:
timeout_s = self._resolve_llm_timeout_s(spec)
tool_definitions = spec.tools.get_definitions()
messages, provider_context = await self.context_governor.prepare_request(
@@ -1032,6 +1039,7 @@ class AgentRunner:
current_request_boundary=(len(transcript) if transcript is not None else None),
)
request_state.provider_compaction_applied |= response.provider_compaction_applied
+ round_usage = self._record_request_usage(spec, request_state, response)
# chat_stream_with_retry may recover internally, so only fail unfinished
# hosted calls after the provider returns its final error response.
if response.finish_reason == "error":
@@ -1058,12 +1066,13 @@ class AgentRunner:
retry_messages = self._malformed_tool_call_retry_messages(
messages, response.content,
)
- return await self._request_model(
+ retry_response, retry_usage = await self._request_model(
spec, retry_messages, hook, context,
request_state=request_state,
malformed_retry=True,
transcript=None,
)
+ return retry_response, round_usage + retry_usage
if (
all_dropped
and original_finish_reason in ("tool_calls", "function_call")
@@ -1075,12 +1084,18 @@ class AgentRunner:
fallback_messages = self._malformed_tool_call_retry_messages(
messages, response.content,
)
- return await self._request_no_tools(
+ fallback_response = await self._request_no_tools(
spec,
fallback_messages,
request_state=request_state,
)
- return response
+ fallback_usage = self._record_request_usage(
+ spec,
+ request_state,
+ fallback_response,
+ )
+ return fallback_response, round_usage + fallback_usage
+ return response, round_usage
@staticmethod
def _drop_malformed_tool_calls(
@@ -1177,6 +1192,7 @@ class AgentRunner:
usage: LLMUsage | None,
*,
request_state: ModelRequestState,
+ round_usages: list[LLMUsage],
) -> tuple[str | None, LLMUsage | None]:
compaction = request_state.compaction
request_messages = (
@@ -1200,6 +1216,7 @@ class AgentRunner:
return None, usage
raw_usage = self._record_request_usage(spec, request_state, response)
+ round_usages.append(raw_usage)
usage = self._merge_usage(usage, raw_usage)
if response.finish_reason == "error" or response.has_tool_calls:
logger.warning(
@@ -1309,7 +1326,7 @@ class AgentRunner:
response: LLMResponse,
*,
tool_definitions: list[dict[str, Any]] | None,
- ) -> LLMUsage | None:
+ ) -> LLMUsage:
usage = response.usage
if response.finish_reason == "error":
if usage is None or usage.total_tokens == 0:
@@ -1331,7 +1348,7 @@ class AgentRunner:
spec: AgentRunSpec,
state: ModelRequestState,
response: LLMResponse,
- ) -> LLMUsage | None:
+ ) -> LLMUsage:
assert state.messages is not None
state.usage = self._usage_or_estimate(
spec,
diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.py
index c1de57f01..92a22af71 100644
--- a/nanobot/agent/turn_delivery.py
+++ b/nanobot/agent/turn_delivery.py
@@ -204,8 +204,8 @@ class TurnDelivery:
def record_latency(self, latency_ms: int | None) -> None:
self.runtime_event_publisher.record_turn_latency(self.session_key, latency_ms)
- def record_usage(self, usage: LLMUsage | None) -> None:
- self.runtime_event_publisher.record_turn_usage(self.session_key, usage)
+ def record_usage(self, round_usages: list[LLMUsage]) -> None:
+ self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages)
def background_response(
self,
diff --git a/nanobot/bus/outbound_events.py b/nanobot/bus/outbound_events.py
index 68e7e1026..fcc000e4e 100644
--- a/nanobot/bus/outbound_events.py
+++ b/nanobot/bus/outbound_events.py
@@ -60,6 +60,7 @@ class TurnEndEvent(OutboundEvent):
latency_ms: int | None = None
goal_state: dict[str, Any] | None = None
usage: LLMUsage | None = None
+ round_usages: tuple[LLMUsage, ...] = ()
context_window_tokens: int | None = None
diff --git a/nanobot/bus/runtime_events.py b/nanobot/bus/runtime_events.py
index c92890878..3cacbf858 100644
--- a/nanobot/bus/runtime_events.py
+++ b/nanobot/bus/runtime_events.py
@@ -74,6 +74,8 @@ class TurnCompleted:
latency_ms: int | None = None
runtime: LLMRuntime | None = None
usage: LLMUsage | None = None
+ # Logical model rounds in display order; recovery dispatches are aggregated.
+ round_usages: tuple[LLMUsage, ...] = ()
@dataclass(frozen=True)
@@ -182,6 +184,7 @@ class RuntimeEventPublisher:
self._turn_latency_ms: dict[str, int] = {}
self._turn_runtime: dict[str, LLMRuntime] = {}
self._turn_usage: dict[str, LLMUsage] = {}
+ self._turn_round_usages: dict[str, tuple[LLMUsage, ...]] = {}
@staticmethod
def _context(
@@ -207,14 +210,29 @@ class RuntimeEventPublisher:
if latency_ms is not None:
self._turn_latency_ms[session_key] = int(latency_ms)
- def record_turn_usage(self, session_key: str, usage: LLMUsage | None) -> None:
- if usage is not None:
- self._turn_usage[session_key] = usage
+ def record_turn_usage(
+ self,
+ session_key: str,
+ round_usages: list[LLMUsage],
+ ) -> None:
+ if not round_usages:
+ return
+
+ usage = round_usages[0]
+ for round_usage in round_usages[1:]:
+ usage += round_usage
+ previous = self._turn_usage.get(session_key)
+ self._turn_usage[session_key] = usage if previous is None else previous + usage
+ self._turn_round_usages[session_key] = (
+ *self._turn_round_usages.get(session_key, ()),
+ *round_usages,
+ )
def clear_turn(self, session_key: str) -> None:
self._turn_latency_ms.pop(session_key, None)
self._turn_runtime.pop(session_key, None)
self._turn_usage.pop(session_key, None)
+ self._turn_round_usages.pop(session_key, None)
async def user_input_accepted(
self,
@@ -331,6 +349,7 @@ class RuntimeEventPublisher:
latency_ms=self._turn_latency_ms.pop(session_key, None),
runtime=self._turn_runtime.pop(session_key, None),
usage=self._turn_usage.pop(session_key, None),
+ round_usages=self._turn_round_usages.pop(session_key, ()),
)
)
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index 70bd79a47..6cca22162 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -1156,6 +1156,7 @@ class WebSocketChannel(BaseChannel):
*,
goal_state: dict[str, Any] | None = None,
usage: LLMUsage | None = None,
+ round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
metadata: dict[str, Any] | None = None,
turn_owner: str | None = None,
@@ -1172,6 +1173,8 @@ class WebSocketChannel(BaseChannel):
body["goal_state"] = goal_state
if usage is not None:
body["usage"] = usage.to_turn_dict()
+ if round_usages:
+ body["round_usages"] = [item.to_turn_dict() for item in round_usages]
if context_window_tokens is not None:
body["context_window_tokens"] = int(context_window_tokens)
canonical_webui_turn = (metadata or {}).get("webui") is True
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py
index 39c76003d..b325f0a04 100644
--- a/nanobot/channels/websocket/tests/test_websocket_channel.py
+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py
@@ -3311,6 +3311,7 @@ async def test_send_turn_end_includes_latency_ms_when_present() -> None:
event=TurnEndEvent(
latency_ms=1500,
usage=usage,
+ round_usages=(usage,),
context_window_tokens=128_000,
),
))
@@ -3333,6 +3334,21 @@ async def test_send_turn_end_includes_latency_ms_when_present() -> None:
"ttft_ms": 125,
"timed_requests": 1,
},
+ "round_usages": [
+ {
+ "prompt_tokens": 80,
+ "completion_tokens": 20,
+ "total_tokens": 100,
+ "context_tokens": 80,
+ "cached_tokens": 40,
+ "request_count": 1,
+ "estimated_tokens": 0,
+ "generation_ms": 500,
+ "measured_completion_tokens": 20,
+ "ttft_ms": 125,
+ "timed_requests": 1,
+ }
+ ],
"context_window_tokens": 128_000,
},
{"event": "session_updated", "chat_id": "chat-1", "scope": "thread"},
diff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.py
index ff7182995..10cf8abea 100644
--- a/nanobot/session/webui_turns.py
+++ b/nanobot/session/webui_turns.py
@@ -706,6 +706,7 @@ class WebuiTurnCoordinator:
session_key=event.context.session_key,
latency_ms=event.latency_ms,
usage=event.usage,
+ round_usages=event.round_usages,
context_window_tokens=(
event.runtime.context_window_tokens if event.runtime is not None else None
),
@@ -750,6 +751,7 @@ class WebuiTurnCoordinator:
session_key: str,
latency_ms: int | None,
usage: LLMUsage | None = None,
+ round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
) -> None:
if msg.channel != "websocket":
@@ -764,6 +766,7 @@ class WebuiTurnCoordinator:
latency_ms=latency_ms,
goal_state=goal_state_ws_blob(session.metadata),
usage=usage,
+ round_usages=round_usages,
context_window_tokens=context_window_tokens,
),
metadata=msg.metadata,
diff --git a/nanobot/webui/outbound_projection.py b/nanobot/webui/outbound_projection.py
index 89ba293c3..d84e7b77e 100644
--- a/nanobot/webui/outbound_projection.py
+++ b/nanobot/webui/outbound_projection.py
@@ -85,6 +85,7 @@ class WebUIOutboundTransport(Protocol):
*,
goal_state: dict[str, Any] | None = None,
usage: LLMUsage | None = None,
+ round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
metadata: dict[str, Any] | None = None,
turn_owner: str | None = None,
@@ -225,6 +226,7 @@ class WebUIOutboundProjector:
latency_ms=event.latency_ms,
goal_state=event.goal_state,
usage=event.usage,
+ round_usages=event.round_usages,
context_window_tokens=event.context_window_tokens,
metadata=msg.metadata,
turn_owner=turn_owner if isinstance(turn_owner, str) else None,
diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py
index 22f6c7684..405ce6410 100644
--- a/nanobot/webui/transcript.py
+++ b/nanobot/webui/transcript.py
@@ -74,6 +74,20 @@ _SESSION_MENTION_NAME_RE = re.compile(r"^[\w-]+$")
_SESSION_HANDLE_ID_RE = re.compile(r"^handle_[0-9a-f]{32}$")
+def _sanitize_turn_usage(value: object) -> dict[str, int] | None:
+ if not isinstance(value, dict):
+ return None
+ data = cast(dict[object, object], value)
+ return {
+ key: item
+ for key, item in data.items()
+ if isinstance(key, str)
+ and isinstance(item, int)
+ and not isinstance(item, bool)
+ and item >= 0
+ }
+
+
def rewrite_local_markdown_images(
text: str,
*,
@@ -1916,6 +1930,7 @@ def replay_transcript_to_ui_messages(
*,
latency_ms: int | None = None,
usage: dict[str, int] | None = None,
+ round_usages: list[dict[str, int]] | None = None,
context_window_tokens: int | None = None,
) -> None:
for i in range(len(messages) - 1, -1, -1):
@@ -1925,6 +1940,8 @@ def replay_transcript_to_ui_messages(
completion["latencyMs"] = latency_ms
if usage:
completion["usage"] = usage
+ if round_usages:
+ completion["roundUsages"] = round_usages
if context_window_tokens is not None:
completion["contextWindowTokens"] = context_window_tokens
messages[i] = {
@@ -2428,19 +2445,23 @@ def replay_transcript_to_ui_messages(
messages[i] = {**m, "isStreaming": False}
lat = rec.get("latency_ms")
usage = rec.get("usage")
- sanitized_usage = (
- {
- key: value
- for key, value in cast(dict[object, object], usage).items()
- if isinstance(key, str) and type(value) is int and value >= 0
- }
- if isinstance(usage, dict)
+ sanitized_usage = _sanitize_turn_usage(usage)
+ raw_round_usages = rec.get("round_usages")
+ sanitized_round_usages = (
+ [
+ sanitized
+ for item in cast(list[object], raw_round_usages)
+ if (sanitized := _sanitize_turn_usage(item))
+ is not None
+ ]
+ if isinstance(raw_round_usages, list)
else None
)
context_window = rec.get("context_window_tokens")
stamp_completion(
latency_ms=int(lat) if isinstance(lat, (int, float)) and lat >= 0 else None,
usage=sanitized_usage,
+ round_usages=sanitized_round_usages,
context_window_tokens=(
int(context_window)
if isinstance(context_window, (int, float)) and context_window >= 0
diff --git a/tests/agent/test_runner_core.py b/tests/agent/test_runner_core.py
index 67ef542c4..1c4be1fa1 100644
--- a/tests/agent/test_runner_core.py
+++ b/tests/agent/test_runner_core.py
@@ -629,6 +629,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
arguments={"path": "."},
)
],
+ usage=LLMUsage.reported(input_tokens=1, output_tokens=1),
)
return LLMResponse(
content="Read the directory twice. More investigation remains.",
@@ -660,6 +661,14 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
assert calls[-1]["tools"] is None
assert "tool-call budget" in calls[-1]["messages"][-1]["content"]
assert tools.execute.await_count == 2
+ assert result.usage is not None
+ assert result.usage.input_tokens == 12
+ assert result.usage.output_tokens == 9
+ assert [(item.input_tokens, item.output_tokens) for item in result.round_usages] == [
+ (1, 1),
+ (1, 1),
+ (10, 7),
+ ]
@pytest.mark.asyncio
@@ -914,6 +923,11 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
assert result.usage is not None
assert result.usage.input_tokens == 13
assert result.usage.output_tokens == 9
+ assert [(item.input_tokens, item.output_tokens) for item in result.round_usages] == [
+ (5, 1),
+ (5, 1),
+ (3, 7),
+ ]
@pytest.mark.asyncio
@@ -1258,6 +1272,13 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
assert result.usage.cache_read_tokens == 230 # 80 + 150
assert result.usage.context_tokens == 200
assert result.usage.request_count == 2
+ assert [
+ (item.input_tokens, item.cache_read_tokens)
+ for item in result.round_usages
+ ] == [
+ (100, 80),
+ (200, 150),
+ ]
@pytest.mark.asyncio
diff --git a/tests/agent/test_runner_governance.py b/tests/agent/test_runner_governance.py
index a3ddb4c93..ff2e6701e 100644
--- a/tests/agent/test_runner_governance.py
+++ b/tests/agent/test_runner_governance.py
@@ -742,6 +742,12 @@ async def test_runner_fits_each_malformed_retry_with_its_actual_tools(monkeypatc
assert None in estimated_tools
assert [len(call["messages"]) for call in calls] == [1, 1, 1]
assert result.final_content == "recovered"
+ assert result.usage is not None
+ assert result.usage.input_tokens == 300
+ assert result.usage.output_tokens == 30
+ assert result.usage.request_count == 3
+ # Recovery dispatches contribute to the total without becoming extra chart bars.
+ assert result.round_usages == [result.usage]
assert result.messages == [
{"role": "user", "content": "use a tool"},
{"role": "assistant", "content": "recovered"},
diff --git a/tests/bus/test_runtime_events.py b/tests/bus/test_runtime_events.py
index 44dd2440a..610c799d8 100644
--- a/tests/bus/test_runtime_events.py
+++ b/tests/bus/test_runtime_events.py
@@ -100,7 +100,10 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
bus.subscribe(seen.append)
publisher.record_turn_runtime("cli:direct", "runtime")
publisher.record_turn_latency("cli:direct", 123)
- publisher.record_turn_usage("cli:direct", LLMUsage.reported(input_tokens=40, output_tokens=2))
+ first_round = LLMUsage.reported(input_tokens=40, output_tokens=2)
+ second_round = LLMUsage.reported(input_tokens=60, output_tokens=3)
+ publisher.record_turn_usage("cli:direct", [first_round])
+ publisher.record_turn_usage("cli:direct", [second_round])
await publisher.turn_completed(
channel="cli",
@@ -121,7 +124,8 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
assert first.context.metadata == {"source": "test"}
assert first.latency_ms == 123
assert first.runtime == "runtime"
- assert first.usage == LLMUsage.reported(input_tokens=40, output_tokens=2)
+ assert first.usage == first_round + second_round
+ assert first.round_usages == (first_round, second_round)
assert isinstance(second, TurnCompleted)
assert second.latency_ms is None
assert second.runtime is None
diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py
index 2cac8a685..a331b3a7e 100644
--- a/tests/utils/test_webui_transcript.py
+++ b/tests/utils/test_webui_transcript.py
@@ -548,6 +548,26 @@ def test_replay_turn_end_preserves_usage_semantics(tmp_path, monkeypatch) -> Non
"context_tokens": 8_200,
"request_count": 3,
},
+ "round_usages": [
+ {
+ "prompt_tokens": 4_000,
+ "completion_tokens": 200,
+ "cached_tokens": 2_000,
+ "request_count": 1,
+ },
+ {
+ "prompt_tokens": 4_200,
+ "completion_tokens": 300,
+ "cached_tokens": 3_672,
+ "request_count": 1,
+ },
+ {
+ "prompt_tokens": 4_200,
+ "completion_tokens": 323,
+ "cached_tokens": 4_000,
+ "request_count": 1,
+ },
+ ],
"context_window_tokens": 128_000,
},
):
@@ -562,6 +582,11 @@ def test_replay_turn_end_preserves_usage_semantics(tmp_path, monkeypatch) -> Non
"context_tokens": 8_200,
"request_count": 3,
}
+ assert [item["prompt_tokens"] for item in messages[-1]["roundUsages"]] == [
+ 4_000,
+ 4_200,
+ 4_200,
+ ]
assert messages[-1]["contextWindowTokens"] == 128_000
assert messages[-1]["latencyMs"] == 18_200
diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx
index 26720ef40..18e0a74cd 100644
--- a/webui/src/components/MessageBubble.tsx
+++ b/webui/src/components/MessageBubble.tsx
@@ -36,7 +36,6 @@ import { cn } from "@/lib/utils";
import { copyTextToClipboard } from "@/lib/clipboard";
import {
fmtDateTime,
- formatCompactTokenCount,
formatMessageEndTime,
} from "@/lib/format";
import { toMediaAttachment } from "@/lib/media";
@@ -54,7 +53,6 @@ import type {
UIMessage,
MessageDeliveryErrorKind,
MessageDeliveryStatus,
- TurnUsage,
} from "@/lib/types";
interface MessageBubbleProps {
@@ -181,71 +179,6 @@ function MessageCopyButton({ content }: { content: string }) {
);
}
-function compactDuration(milliseconds: number): string {
- const seconds = milliseconds / 1_000;
- if (seconds < 10) return `${seconds.toFixed(1)}s`;
- if (seconds < 60) return `${Math.round(seconds)}s`;
- const minutes = Math.floor(seconds / 60);
- return `${minutes}m ${Math.round(seconds % 60)}s`;
-}
-
-function TurnUsageMeta({
- usage,
- latencyMs,
-}: {
- usage: TurnUsage;
- latencyMs?: number;
-}) {
- const { t } = useTranslation();
- const prompt = usage.prompt_tokens;
- const completion = usage.completion_tokens;
- const approximate = (usage.estimated_tokens ?? 0) > 0 ? "~" : "";
- const parts: string[] = [];
- if (typeof prompt === "number") parts.push(`${approximate}${formatCompactTokenCount(prompt)} in`);
- if (typeof completion === "number") parts.push(`${approximate}${formatCompactTokenCount(completion)} out`);
- if (
- typeof usage.cached_tokens === "number"
- && typeof prompt === "number"
- && prompt > 0
- ) {
- parts.push(`${Math.round(Math.min(1, usage.cached_tokens / prompt) * 100)}% cached`);
- }
- if (typeof latencyMs === "number" && latencyMs >= 0) parts.push(compactDuration(latencyMs));
- if (parts.length === 0) return null;
-
- const details: string[] = [];
- if (approximate) {
- details.push(t("message.usage.estimated", { defaultValue: "Includes estimated usage" }));
- }
- const usageMeta = (
- <span
- data-turn-usage
- tabIndex={details.length ? 0 : undefined}
- className={cn(
- "text-[11px] leading-none text-muted-foreground/70 tabular-nums",
- details.length && "cursor-help",
- )}
- >
- {parts.join(" · ")}
- </span>
- );
-
- if (details.length === 0) return usageMeta;
-
- return (
- <Tooltip>
- <TooltipTrigger asChild>{usageMeta}</TooltipTrigger>
- <TooltipContent
- side="top"
- align="start"
- className="max-w-96 whitespace-nowrap"
- >
- {details.join(" · ")}
- </TooltipContent>
- </Tooltip>
- );
-}
-
function deliveryErrorCopy(
kind: MessageDeliveryErrorKind | undefined,
t: (key: string) => string,
@@ -549,9 +482,8 @@ export function MessageBubble({
&& (!empty || hasReasoning || media.length > 0);
const assistantTimestampTitle = showAssistantTimestamp ? fmtDateTime(assistantTimestamp) : "";
const showAutomationTrigger = showAssistantTimestamp && automationSourceLabel.length > 0;
- const showUsage = message.role === "assistant" && !!message.usage && !message.isStreaming;
const showAssistantFooterRow =
- showCopyButton || showForkButton || showAssistantTimestamp || showUsage;
+ showCopyButton || showForkButton || showAssistantTimestamp;
const showAssistantFooterSlot =
message.role === "assistant"
&& (!empty || hasReasoning || media.length > 0);
@@ -617,12 +549,6 @@ export function MessageBubble({
<TooltipContent side="top" align="center">{forkLabel}</TooltipContent>
</Tooltip>
) : null}
- {showUsage ? (
- <TurnUsageMeta
- usage={message.usage!}
- latencyMs={message.latencyMs}
- />
- ) : null}
{showAssistantTimestamp ? (
<MessageTimestamp
{...(showCompletedAt ? { "data-assistant-completed-at": true } : {})}
diff --git a/webui/src/components/thread/ComposerUsagePopover.tsx b/webui/src/components/thread/ComposerUsagePopover.tsx
new file mode 100644
index 000000000..8cd54f5f4
--- /dev/null
+++ b/webui/src/components/thread/ComposerUsagePopover.tsx
@@ -0,0 +1,410 @@
+import { Fragment, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { formatCompactTokenCount, formatTurnLatency } from "@/lib/format";
+import { cn } from "@/lib/utils";
+
+export interface ComposerContextUsage {
+ contextTokens: number;
+ contextWindowTokens?: number;
+}
+
+export interface ComposerRoundUsage {
+ id: string;
+ timestamp: number;
+ inputTokens: number;
+ outputTokens?: number;
+ cachedTokens?: number;
+ estimatedTokens?: number;
+ generationMs?: number;
+}
+
+interface NormalizedRoundUsage extends ComposerRoundUsage {
+ cachedTokens?: number;
+ outputTokens: number;
+}
+
+function normalizeRounds(
+ rounds: readonly ComposerRoundUsage[],
+): NormalizedRoundUsage[] {
+ return rounds
+ .filter((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0)
+ .map((round) => ({
+ ...round,
+ inputTokens: Math.max(0, round.inputTokens),
+ outputTokens: Number.isFinite(round.outputTokens)
+ ? Math.max(0, round.outputTokens ?? 0)
+ : 0,
+ ...(Number.isFinite(round.cachedTokens)
+ ? { cachedTokens: Math.min(round.inputTokens, Math.max(0, round.cachedTokens ?? 0)) }
+ : {}),
+ }));
+}
+
+export function ComposerUsagePopover({
+ context,
+ rounds,
+}: {
+ context: ComposerContextUsage | null;
+ rounds: readonly ComposerRoundUsage[];
+}) {
+ const { t, i18n } = useTranslation();
+ const panelRef = useRef<HTMLDivElement>(null);
+ const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]);
+ const hasContext = !!context
+ && Number.isFinite(context.contextTokens)
+ && context.contextTokens >= 0
+ && Number.isFinite(context.contextWindowTokens)
+ && (context.contextWindowTokens ?? 0) > 0;
+ if (!hasContext && normalizedRounds.length === 0) {
+ return null;
+ }
+
+ const contextPercentage = hasContext
+ ? Math.min(
+ 100,
+ Math.round(context!.contextTokens / context!.contextWindowTokens! * 100),
+ )
+ : null;
+ const meterPercentage = contextPercentage ?? 0;
+ const status = meterPercentage >= 90
+ ? "critical"
+ : meterPercentage >= 75
+ ? "caution"
+ : "normal";
+ const detailsLabel = t("thread.composer.context.detailsLabel", {
+ defaultValue: "Open context usage",
+ });
+ const contextDescription = contextPercentage === null
+ ? detailsLabel
+ : t("thread.composer.context.tooltip", {
+ defaultValue: "Context {{percent}}%",
+ percent: contextPercentage,
+ });
+ const triggerLabel = contextPercentage === null
+ ? detailsLabel
+ : `${contextDescription}. ${detailsLabel}`;
+ const ringCircumference = 2 * Math.PI * 6;
+ const ringLength = ringCircumference * meterPercentage / 100;
+ const maxInputTokens = Math.max(0, ...normalizedRounds.map((round) => round.inputTokens));
+ const numberFormatter = new Intl.NumberFormat(i18n.language);
+ const percentageFormatter = new Intl.NumberFormat(i18n.language, {
+ style: "percent",
+ maximumFractionDigits: 0,
+ });
+ const roundDateFormatter = new Intl.DateTimeFormat(i18n.language, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+
+ return (
+ <Popover>
+ <TooltipProvider delayDuration={300} skipDelayDuration={80}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ data-testid="composer-context-usage"
+ aria-label={triggerLabel}
+ className={cn(
+ "touch-target inline-flex size-5 shrink-0 items-center justify-center rounded-full",
+ "text-muted-foreground/75 transition-colors hover:text-foreground/85",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}
+ >
+ {contextPercentage === null ? (
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="size-[15px]">
+ <path
+ d="M3 12V9m5 3V5m5 7V2"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ </svg>
+ ) : (
+ <svg
+ viewBox="0 0 16 16"
+ aria-hidden="true"
+ className={cn(
+ "size-[15px] shrink-0 -rotate-90",
+ status === "critical" && "text-destructive",
+ status === "caution" && "text-amber-600 dark:text-amber-400",
+ status === "normal" && "text-muted-foreground/75",
+ )}
+ >
+ <circle
+ cx="8"
+ cy="8"
+ r="6"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ className="opacity-20"
+ />
+ <circle
+ cx="8"
+ cy="8"
+ r="6"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeDasharray={`${ringLength} ${ringCircumference}`}
+ data-testid="composer-context-meter"
+ />
+ </svg>
+ )}
+ </button>
+ </PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="center"
+ sideOffset={8}
+ className="w-fit max-w-[calc(100vw-2rem)] rounded-full border-border/70 px-2.5 py-1 text-xs font-medium shadow-[0_8px_24px_rgba(15,23,42,0.13)]"
+ >
+ <span className="whitespace-nowrap tabular-nums">{contextDescription}</span>
+ </TooltipContent>
+ </Tooltip>
+
+ <PopoverContent
+ ref={panelRef}
+ side="top"
+ align="end"
+ sideOffset={10}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ panelRef.current?.focus();
+ }}
+ aria-label={t("thread.composer.context.panelTitle", {
+ defaultValue: "Context usage",
+ })}
+ className="w-[min(22rem,calc(100vw-1.5rem))] p-0"
+ >
+ <div className="px-4 pb-4 pt-3.5">
+ {contextPercentage !== null ? (
+ <>
+ <div className="flex items-baseline justify-between gap-3">
+ <div className="flex min-w-0 items-baseline gap-2">
+ <span className="shrink-0 text-[12px] font-medium text-foreground">
+ {t("thread.composer.context.contextTitle", {
+ defaultValue: "Context",
+ })}
+ </span>
+ <span className="truncate text-[11px] tabular-nums text-muted-foreground">
+ {formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount(
+ context!.contextWindowTokens!,
+ )}
+ </span>
+ </div>
+ <span className="shrink-0 text-[11px] tabular-nums text-muted-foreground">
+ {contextPercentage}%
+ </span>
+ </div>
+ <div
+ role="progressbar"
+ aria-label={contextDescription}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={contextPercentage}
+ className="mt-2 h-1 overflow-hidden rounded-full bg-muted"
+ >
+ <div
+ className={cn(
+ "h-full rounded-full",
+ status === "critical" && "bg-destructive",
+ status === "caution" && "bg-amber-500",
+ status === "normal" && "bg-foreground/45",
+ )}
+ style={{ width: `${contextPercentage}%` }}
+ />
+ </div>
+ </>
+ ) : null}
+
+ {normalizedRounds.length > 0 ? (
+ <>
+ <div className={cn(
+ "flex items-baseline justify-between gap-3",
+ contextPercentage === null ? "mt-0" : "mt-5",
+ )}>
+ <span className="text-[12px] font-medium text-foreground">
+ {t("thread.composer.context.recentRounds", {
+ defaultValue: "Recent rounds",
+ })}
+ </span>
+ <span className="text-[11px] text-muted-foreground">
+ {t("thread.composer.context.inputTrend", {
+ defaultValue: "Input tokens",
+ })}
+ </span>
+ </div>
+ <div
+ role="group"
+ aria-label={t("thread.composer.context.inputTrend", {
+ defaultValue: "Input tokens",
+ })}
+ className="mt-2 flex h-28 items-end gap-1.5 border-b border-border/60"
+ >
+ {normalizedRounds.map((round, index) => {
+ const cachedKnown = typeof round.cachedTokens === "number";
+ const cachedTokens = round.cachedTokens ?? 0;
+ const notReusedTokens = Math.max(0, round.inputTokens - cachedTokens);
+ const cacheHitRate = cachedKnown
+ ? percentageFormatter.format(cachedTokens / round.inputTokens)
+ : null;
+ const cachedHeight = cachedKnown
+ ? cachedTokens / round.inputTokens * 100
+ : 0;
+ const barHeight = round.inputTokens / maxInputTokens * 108;
+ const timestampLabel = roundDateFormatter.format(round.timestamp);
+ const detailRows = [
+ {
+ key: "input",
+ label: t("thread.composer.context.input", {
+ defaultValue: "Input tokens",
+ }),
+ value: numberFormatter.format(round.inputTokens),
+ },
+ cachedKnown
+ ? {
+ key: "cache-hit-rate",
+ label: t("thread.composer.context.cacheHitRate", {
+ defaultValue: "KV cache hit rate",
+ }),
+ value: cacheHitRate!,
+ }
+ : null,
+ {
+ key: "output",
+ label: t("thread.composer.context.output", {
+ defaultValue: "Output tokens",
+ }),
+ value: numberFormatter.format(round.outputTokens),
+ },
+ typeof round.generationMs === "number"
+ ? {
+ key: "duration",
+ label: t("thread.composer.context.duration", {
+ defaultValue: "Generation time",
+ }),
+ value: formatTurnLatency(round.generationMs, i18n.language),
+ }
+ : null,
+ ].filter((row): row is NonNullable<typeof row> => !!row);
+ const detailNote = (round.estimatedTokens ?? 0) > 0
+ ? t("message.usage.estimated", {
+ defaultValue: "Includes estimated usage",
+ })
+ : null;
+ const detailLabel = [
+ timestampLabel,
+ ...detailRows.map((row) => `${row.label} ${row.value}`),
+ detailNote,
+ ].filter((part): part is string => !!part).join(". ");
+
+ return (
+ <span
+ key={round.id}
+ className={cn(
+ "flex h-full min-w-0 flex-1 items-end justify-center rounded-sm",
+ "opacity-70 transition-opacity hover:opacity-100",
+ index === 0 && "justify-start",
+ normalizedRounds.length > 1
+ && index === normalizedRounds.length - 1
+ && "justify-end",
+ index === normalizedRounds.length - 1 && "opacity-100",
+ )}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ role="img"
+ tabIndex={0}
+ aria-label={detailLabel}
+ data-testid="round-usage-bar"
+ className={cn(
+ "flex w-full max-w-7 flex-col overflow-hidden rounded-t-[3px] bg-muted",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}
+ style={{ height: `${barHeight}px` }}
+ >
+ {cachedKnown ? (
+ <>
+ {notReusedTokens > 0 ? (
+ <span
+ className="kv-cache-not-reused block w-full"
+ style={{ height: `${100 - cachedHeight}%` }}
+ />
+ ) : null}
+ {cachedTokens > 0 ? (
+ <span
+ className="kv-cache-reused block w-full"
+ style={{ height: `${cachedHeight}%` }}
+ />
+ ) : null}
+ </>
+ ) : (
+ <span className="block h-full w-full bg-muted-foreground/25" />
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="center"
+ className="max-w-72 px-3 py-2 text-[11px]"
+ >
+ <span
+ className="block font-medium text-foreground"
+ >
+ {timestampLabel}
+ </span>
+ <span className="mt-1 grid grid-cols-[max-content_max-content] gap-x-3 gap-y-0.5">
+ {detailRows.map((row) => (
+ <Fragment key={row.key}>
+ <span className="text-muted-foreground">
+ {row.label}
+ </span>
+ <span className="text-end tabular-nums text-foreground">
+ {row.value}
+ </span>
+ </Fragment>
+ ))}
+ </span>
+ {detailNote ? (
+ <span
+ className="mt-1 block text-muted-foreground"
+ >
+ {detailNote}
+ </span>
+ ) : null}
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ );
+ })}
+ </div>
+ </>
+ ) : null}
+
+ </div>
+ </PopoverContent>
+ </TooltipProvider>
+ </Popover>
+ );
+}
diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx
index 71d1576d9..6541390fd 100644
--- a/webui/src/components/thread/ThreadComposer.tsx
+++ b/webui/src/components/thread/ThreadComposer.tsx
@@ -70,6 +70,11 @@ import {
ModelPresetBadge,
type ModelPresetOption,
} from "@/components/thread/ModelPresetBadge";
+import {
+ ComposerUsagePopover,
+ type ComposerContextUsage,
+ type ComposerRoundUsage,
+} from "@/components/thread/ComposerUsagePopover";
import {
ACCEPT_ATTR,
MAX_ATTACHMENTS_PER_MESSAGE,
@@ -112,7 +117,6 @@ import {
readDraggedSession,
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
-import { formatCompactTokenCount } from "@/lib/format";
import { cn } from "@/lib/utils";
const VOICE_SHORTCUT_CODE = "KeyD";
@@ -179,107 +183,6 @@ function getVoiceShortcutLabel(): string {
}
}
-export interface ComposerContextUsage {
- contextTokens: number;
- contextWindowTokens?: number;
-}
-
-function ComposerContextBadge({ usage }: { usage: ComposerContextUsage | null }) {
- const { t } = useTranslation();
- if (!usage || !Number.isFinite(usage.contextTokens) || usage.contextTokens < 0) return null;
-
- const context = formatCompactTokenCount(usage.contextTokens);
- const contextWindow = typeof usage.contextWindowTokens === "number"
- && Number.isFinite(usage.contextWindowTokens)
- && usage.contextWindowTokens > 0
- ? usage.contextWindowTokens
- : null;
- const capacity = contextWindow !== null
- ? ` / ${formatCompactTokenCount(contextWindow)}`
- : "";
- // The meter is meaningful only with a known capacity. Do not turn an
- // otherwise unknown total into a second, text-heavy control beside the
- // model picker.
- if (contextWindow === null) return null;
- const percentage = Math.min(100, Math.round(usage.contextTokens / contextWindow * 100));
- const status = percentage >= 90
- ? "critical"
- : percentage >= 75
- ? "caution"
- : "normal";
- const contextDescription = t("thread.composer.context.tooltip", {
- defaultValue: "Context · {{tokens}}{{capacity}}",
- tokens: context,
- capacity,
- });
- const meterDescription = t("thread.composer.context.meterDescription", {
- defaultValue: "{{context}}. {{percent}}% used.",
- context: contextDescription,
- percent: percentage,
- });
- const ringCircumference = 2 * Math.PI * 6;
- const ringLength = ringCircumference * percentage / 100;
-
- return (
- <TooltipProvider delayDuration={300} skipDelayDuration={80}>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- data-testid="composer-context-usage"
- aria-label={meterDescription}
- className={cn(
- "inline-flex size-5 shrink-0 items-center justify-center rounded-full",
- "text-muted-foreground/75 transition-colors hover:text-foreground/85",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- )}
- >
- <svg
- viewBox="0 0 16 16"
- aria-hidden="true"
- className={cn(
- "size-[15px] shrink-0 -rotate-90",
- status === "critical" && "text-destructive",
- status === "caution" && "text-amber-600 dark:text-amber-400",
- status === "normal" && "text-muted-foreground/75",
- )}
- >
- <circle
- cx="8"
- cy="8"
- r="6"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- className="opacity-20"
- />
- <circle
- cx="8"
- cy="8"
- r="6"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeDasharray={`${ringLength} ${ringCircumference}`}
- data-testid="composer-context-meter"
- />
- </svg>
- </button>
- </TooltipTrigger>
- <TooltipContent
- side="top"
- align="center"
- sideOffset={8}
- className="w-fit max-w-[calc(100vw-2rem)] rounded-full border-border/70 px-2.5 py-1 text-xs font-medium shadow-[0_8px_24px_rgba(15,23,42,0.13)]"
- >
- <span className="whitespace-nowrap tabular-nums">{contextDescription}</span>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
-}
-
interface ThreadComposerProps {
onSend: (
content: string,
@@ -302,6 +205,7 @@ interface ThreadComposerProps {
onModelBadgeClick?: () => void;
onManageModels?: () => void;
contextUsage?: ComposerContextUsage | null;
+ recentRoundUsage?: readonly ComposerRoundUsage[];
variant?: "thread" | "hero";
slashCommands?: SlashCommand[];
cliApps?: CliAppInfo[];
@@ -1001,6 +905,7 @@ export function ThreadComposer({
onModelBadgeClick,
onManageModels,
contextUsage = null,
+ recentRoundUsage = [],
variant = "thread",
slashCommands = [],
cliApps = [],
@@ -2555,7 +2460,12 @@ export function ThreadComposer({
onClick={modelNeedsSetup ? onModelBadgeClick : undefined}
/>
) : null}
- {!voiceRecorder.isRecording ? <ComposerContextBadge usage={contextUsage} /> : null}
+ {!voiceRecorder.isRecording ? (
+ <ComposerUsagePopover
+ context={contextUsage}
+ rounds={recentRoundUsage}
+ />
+ ) : null}
{showVoiceButton ? (
<TooltipProvider delayDuration={220} skipDelayDuration={80}>
<Tooltip>
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 61c35f7e9..03ee6652c 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -9,10 +9,11 @@ import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
-import {
- ThreadComposer,
- type ComposerContextUsage,
-} from "@/components/thread/ThreadComposer";
+import { ThreadComposer } from "@/components/thread/ThreadComposer";
+import type {
+ ComposerContextUsage,
+ ComposerRoundUsage,
+} from "@/components/thread/ComposerUsagePopover";
import type { ModelPresetOption } from "@/components/thread/ModelPresetBadge";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
@@ -41,6 +42,7 @@ import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import { inferProviderFromModelName, providerDisplayLabel } from "@/lib/provider-brand";
import type {
ChatSummary,
+ RoundUsage,
SettingsPayload,
SlashCommand,
SkillSummary,
@@ -111,6 +113,60 @@ function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage
return null;
}
+function recentComposerRoundUsage(messages: UIMessage[]): ComposerRoundUsage[] {
+ const recent: ComposerRoundUsage[] = [];
+ const seenTurns = new Set<string>();
+ for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {
+ const message = messages[index];
+ const turnKey = message.turnId || message.id;
+ if (
+ message.role !== "assistant"
+ || message.kind === "trace"
+ || message.isStreaming
+ || seenTurns.has(turnKey)
+ ) {
+ continue;
+ }
+
+ seenTurns.add(turnKey);
+ const rounds: RoundUsage[] = message.roundUsages ?? [];
+ for (let roundIndex = rounds.length - 1; roundIndex >= 0; roundIndex -= 1) {
+ const round = rounds[roundIndex];
+ const inputTokens = round.prompt_tokens;
+ if (
+ recent.length >= 8
+ || typeof inputTokens !== "number"
+ || !Number.isFinite(inputTokens)
+ || inputTokens <= 0
+ ) {
+ continue;
+ }
+ const outputTokens = round.completion_tokens;
+ const cachedTokens = round.cached_tokens;
+ const estimatedTokens = round.estimated_tokens;
+ const generationMs = round.generation_ms;
+ recent.push({
+ id: `${turnKey}:${roundIndex}`,
+ timestamp: message.completedAt ?? message.createdAt,
+ inputTokens,
+ ...(typeof outputTokens === "number" && Number.isFinite(outputTokens)
+ ? { outputTokens }
+ : {}),
+ ...(typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
+ ? { cachedTokens }
+ : {}),
+ ...(typeof estimatedTokens === "number" && Number.isFinite(estimatedTokens)
+ ? { estimatedTokens }
+ : {}),
+ ...(typeof generationMs === "number" && Number.isFinite(generationMs)
+ ? { generationMs }
+ : {}),
+ });
+ }
+ }
+ return recent.reverse();
+}
+
function snapshotPreservesMessage(
current: MessageShape,
candidate: MessageShape,
@@ -839,6 +895,10 @@ export function ThreadShell({
() => latestComposerContextUsage(displayMessages),
[displayMessages],
);
+ const composerRoundUsage = useMemo(
+ () => recentComposerRoundUsage(displayMessages),
+ [displayMessages],
+ );
const currentGoalState = messagesReady ? goalState : undefined;
// Decision states freeze the interrupted turn and hand the next action to
// the recovery notice. ``resuming`` remains active; ``recovered`` is only
@@ -1520,6 +1580,7 @@ export function ThreadShell({
onModelBadgeClick={modelBadge.needsSetup ? onOpenModelSettings : undefined}
onManageModels={onOpenModelSettings}
contextUsage={composerContextUsage}
+ recentRoundUsage={composerRoundUsage}
variant={composerVariant}
slashCommands={availableSlashCommands}
cliApps={cliApps}
@@ -1569,6 +1630,7 @@ export function ThreadShell({
onModelBadgeClick={modelBadge.needsSetup ? onOpenModelSettings : undefined}
onManageModels={onOpenModelSettings}
contextUsage={composerContextUsage}
+ recentRoundUsage={composerRoundUsage}
variant="hero"
slashCommands={availableSlashCommands}
cliApps={cliApps}
diff --git a/webui/src/globals.css b/webui/src/globals.css
index 9c0eae90b..553764cb3 100644
--- a/webui/src/globals.css
+++ b/webui/src/globals.css
@@ -33,6 +33,7 @@
--input: 40 8% 90.5%;
--ring: 0 0% 3.9%;
--inline-token-highlight: #ef8e30;
+ --usage-token: 29 86% 56%;
--session-handle-lightness: 0.5;
--session-handle-chroma: 0.12;
--temporary-control-active: #ef8e30;
@@ -157,6 +158,36 @@
overflow: hidden;
}
+ .kv-cache-not-reused {
+ background: hsl(var(--usage-token) / 0.84);
+ }
+
+ .kv-cache-reused {
+ background-color: hsl(var(--usage-token) / 0.1);
+ background-image: repeating-linear-gradient(
+ 135deg,
+ hsl(var(--usage-token) / 0.46) 0,
+ hsl(var(--usage-token) / 0.46) 1px,
+ transparent 1px,
+ transparent 4px
+ );
+ }
+
+ .dark .kv-cache-not-reused {
+ background: hsl(var(--usage-token) / 0.92);
+ }
+
+ .dark .kv-cache-reused {
+ background-color: hsl(var(--usage-token) / 0.15);
+ background-image: repeating-linear-gradient(
+ 135deg,
+ hsl(var(--usage-token) / 0.58) 0,
+ hsl(var(--usage-token) / 0.58) 1px,
+ transparent 1px,
+ transparent 4px
+ );
+ }
+
.composer-model-badge::before {
content: "";
position: absolute;
diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts
index dc6f0cc01..83bc6856d 100644
--- a/webui/src/hooks/useNanobotStream.ts
+++ b/webui/src/hooks/useNanobotStream.ts
@@ -873,6 +873,7 @@ export function useNanobotStream(
{
...(latencyMs !== undefined ? { latencyMs } : {}),
...(ev.usage ? { usage: ev.usage } : {}),
+ ...(ev.round_usages?.length ? { roundUsages: ev.round_usages } : {}),
...(typeof ev.context_window_tokens === "number"
? { contextWindowTokens: ev.context_window_tokens }
: {}),
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 441e0035e..4bb51e35c 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -1199,8 +1199,16 @@
"switchModel": "Switch model for this chat",
"manageModels": "Manage models",
"context": {
- "tooltip": "Context · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. {{percent}}% used."
+ "tooltip": "Context {{percent}}%",
+ "detailsLabel": "Open context usage",
+ "panelTitle": "Context usage",
+ "contextTitle": "Context",
+ "recentRounds": "Recent rounds",
+ "inputTrend": "Input tokens",
+ "input": "Input tokens",
+ "cacheHitRate": "KV cache hit rate",
+ "output": "Output tokens",
+ "duration": "Generation time"
},
"queued": {
"label": "Queued guidance",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 8846f19cb..d9fce3880 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1186,8 +1186,16 @@
"switchModel": "Cambiar el modelo de este chat",
"manageModels": "Gestionar modelos",
"context": {
- "tooltip": "Contexto · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. {{percent}} % usado."
+ "tooltip": "Contexto {{percent}}%",
+ "detailsLabel": "Abrir uso del contexto",
+ "panelTitle": "Uso del contexto",
+ "contextTitle": "Contexto",
+ "recentRounds": "Rondas recientes",
+ "inputTrend": "Tokens de entrada",
+ "input": "Tokens de entrada",
+ "cacheHitRate": "Tasa de aciertos de KV Cache",
+ "output": "Tokens de salida",
+ "duration": "Tiempo de generación"
},
"queued": {
"label": "Guía en cola",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index be16a2c24..73d63aa8d 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1185,8 +1185,16 @@
"switchModel": "Changer le modèle de cette conversation",
"manageModels": "Gérer les modèles",
"context": {
- "tooltip": "Contexte · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. {{percent}} % utilisé."
+ "tooltip": "Contexte {{percent}} %",
+ "detailsLabel": "Ouvrir l’utilisation du contexte",
+ "panelTitle": "Utilisation du contexte",
+ "contextTitle": "Contexte",
+ "recentRounds": "Tours récents",
+ "inputTrend": "Jetons d’entrée",
+ "input": "Jetons d’entrée",
+ "cacheHitRate": "Taux de succès du cache KV",
+ "output": "Jetons de sortie",
+ "duration": "Temps de génération"
},
"queued": {
"label": "Guidage en attente",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index 2e6d1b002..ab13fb0d6 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1185,8 +1185,16 @@
"switchModel": "Ganti model untuk percakapan ini",
"manageModels": "Kelola model",
"context": {
- "tooltip": "Konteks · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. {{percent}}% digunakan."
+ "tooltip": "Konteks {{percent}}%",
+ "detailsLabel": "Buka penggunaan konteks",
+ "panelTitle": "Penggunaan konteks",
+ "contextTitle": "Konteks",
+ "recentRounds": "Putaran terbaru",
+ "inputTrend": "Token masukan",
+ "input": "Token masukan",
+ "cacheHitRate": "Rasio hit KV cache",
+ "output": "Token keluaran",
+ "duration": "Waktu pembuatan"
},
"queued": {
"label": "Panduan antrean",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 565dbffd7..09291c941 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1185,8 +1185,16 @@
"switchModel": "この会話で使うモデルを切り替える",
"manageModels": "モデルを管理",
"context": {
- "tooltip": "コンテキスト · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}。{{percent}}% 使用中"
+ "tooltip": "コンテキスト {{percent}}%",
+ "detailsLabel": "コンテキスト使用量を開く",
+ "panelTitle": "コンテキスト使用量",
+ "contextTitle": "コンテキスト",
+ "recentRounds": "最近のラウンド",
+ "inputTrend": "入力トークン",
+ "input": "入力トークン",
+ "cacheHitRate": "KV キャッシュヒット率",
+ "output": "出力トークン",
+ "duration": "生成時間"
},
"queued": {
"label": "保留中のガイド",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index 68607b66b..d5f1681ed 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1185,8 +1185,16 @@
"switchModel": "이 대화에서 사용할 모델 전환",
"manageModels": "모델 관리",
"context": {
- "tooltip": "컨텍스트 · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. {{percent}}% 사용 중."
+ "tooltip": "컨텍스트 {{percent}}%",
+ "detailsLabel": "컨텍스트 사용량 열기",
+ "panelTitle": "컨텍스트 사용량",
+ "contextTitle": "컨텍스트",
+ "recentRounds": "최근 라운드",
+ "inputTrend": "입력 토큰",
+ "input": "입력 토큰",
+ "cacheHitRate": "KV 캐시 적중률",
+ "output": "출력 토큰",
+ "duration": "생성 시간"
},
"queued": {
"label": "대기 중인 안내",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 338847b3d..8e5b970ae 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1199,8 +1199,16 @@
"switchModel": "Alternar o modelo desta conversa",
"manageModels": "Gerenciar modelos",
"context": {
- "tooltip": "Contexto · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. {{percent}}% usado."
+ "tooltip": "Contexto {{percent}}%",
+ "detailsLabel": "Abrir uso do contexto",
+ "panelTitle": "Uso do contexto",
+ "contextTitle": "Contexto",
+ "recentRounds": "Rodadas recentes",
+ "inputTrend": "Tokens de entrada",
+ "input": "Tokens de entrada",
+ "cacheHitRate": "Taxa de acertos do cache KV",
+ "output": "Tokens de saída",
+ "duration": "Tempo de geração"
},
"queued": {
"label": "Guia em fila",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 0e7c4c7aa..d305dcb57 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1185,8 +1185,16 @@
"switchModel": "Chuyển mô hình cho cuộc trò chuyện này",
"manageModels": "Quản lý mô hình",
"context": {
- "tooltip": "Ngữ cảnh · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}. Đã dùng {{percent}}%."
+ "tooltip": "Ngữ cảnh {{percent}}%",
+ "detailsLabel": "Mở mức sử dụng ngữ cảnh",
+ "panelTitle": "Mức sử dụng ngữ cảnh",
+ "contextTitle": "Ngữ cảnh",
+ "recentRounds": "Các lượt gần đây",
+ "inputTrend": "Token đầu vào",
+ "input": "Token đầu vào",
+ "cacheHitRate": "Tỷ lệ hit KV cache",
+ "output": "Token đầu ra",
+ "duration": "Thời gian tạo"
},
"queued": {
"label": "Hướng dẫn đang chờ",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 5238f3a9e..cf443e047 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -1198,8 +1198,16 @@
"switchModel": "切换本次对话所用模型",
"manageModels": "管理模型预设",
"context": {
- "tooltip": "上下文 · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}。已使用 {{percent}}%。"
+ "tooltip": "上下文 {{percent}}%",
+ "detailsLabel": "打开上下文用量",
+ "panelTitle": "上下文用量",
+ "contextTitle": "上下文",
+ "recentRounds": "最近轮次",
+ "inputTrend": "输入 Token",
+ "input": "输入 Token",
+ "cacheHitRate": "KV Cache 命中率",
+ "output": "输出 Token",
+ "duration": "生成耗时"
},
"queued": {
"label": "排队中的引导消息",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 45291302b..20b8ffb2a 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1185,8 +1185,16 @@
"switchModel": "切換此對話使用的模型",
"manageModels": "管理模型預設",
"context": {
- "tooltip": "上下文 · {{tokens}}{{capacity}}",
- "meterDescription": "{{context}}。已使用 {{percent}}%。"
+ "tooltip": "上下文 {{percent}}%",
+ "detailsLabel": "開啟上下文用量",
+ "panelTitle": "上下文用量",
+ "contextTitle": "上下文",
+ "recentRounds": "最近輪次",
+ "inputTrend": "輸入 Token",
+ "input": "輸入 Token",
+ "cacheHitRate": "KV Cache 命中率",
+ "output": "輸出 Token",
+ "duration": "生成耗時"
},
"queued": {
"label": "佇列中的引導訊息",
diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts
index 471b51b1f..1715129e1 100644
--- a/webui/src/lib/thread-event-projection.ts
+++ b/webui/src/lib/thread-event-projection.ts
@@ -121,7 +121,10 @@ export function isReasoningOnlyPlaceholder(message: UIMessage): boolean {
export function stampLastAssistantCompletion(
prev: UIMessage[],
- completion: Pick<UIMessage, "latencyMs" | "completedAt" | "usage" | "contextWindowTokens">,
+ completion: Pick<
+ UIMessage,
+ "latencyMs" | "completedAt" | "usage" | "roundUsages" | "contextWindowTokens"
+ >,
turnId?: string,
): UIMessage[] {
for (let i = prev.length - 1; i >= 0; i -= 1) {
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 22c05d7d2..481f696a2 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -42,13 +42,20 @@ interface UIMessageSource { kind: "cron" | "local_trigger" | "trigger" | string;
export interface TurnUsage {
prompt_tokens?: number;
completion_tokens?: number;
+ total_tokens?: number;
cached_tokens?: number;
+ cache_write_tokens?: number;
context_tokens?: number;
request_count?: number;
estimated_tokens?: number;
- [key: string]: number | undefined;
+ generation_ms?: number;
+ measured_completion_tokens?: number;
+ ttft_ms?: number;
+ timed_requests?: number;
}
+export type RoundUsage = TurnUsage;
+
export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed";
export interface RecoveryState {
@@ -102,6 +109,8 @@ export interface UIMessage {
completedAt?: number;
/** Additive model usage for this turn; context_tokens is the final request only. */
usage?: TurnUsage;
+ /** Logical model rounds in display order; runner-level recovery calls are aggregated. */
+ roundUsages?: RoundUsage[];
/** Configured context-window capacity for the model used by this turn. */
contextWindowTokens?: number;
/** Lightweight provenance for proactive assistant messages. */
@@ -1419,6 +1428,7 @@ export type InboundEvent =
chat_id: string;
latency_ms?: number;
usage?: TurnUsage;
+ round_usages?: RoundUsage[];
context_window_tokens?: number;
/** Authoritative sustained-goal snapshot for this chat (same shape as ``goal_state`` events). */
goal_state?: GoalStateWsPayload;
diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx
index 369abde2f..44589a22c 100644
--- a/webui/src/tests/message-bubble.test.tsx
+++ b/webui/src/tests/message-bubble.test.tsx
@@ -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");
- });
});
diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx
index f0a40d20b..6ee3a48fe 100644
--- a/webui/src/tests/thread-composer.test.tsx
+++ b/webui/src/tests/thread-composer.test.tsx
@@ -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
diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx
index 3136f83ab..58c8cd4b6 100644
--- a/webui/src/tests/thread-shell.test.tsx
+++ b/webui/src/tests/thread-shell.test.tsx
@@ -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");