From 6b82d642fc119288d0cb77c038214f5dede090d3 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:13:17 +0800 Subject: [PATCH] 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 --- nanobot/agent/loop.py | 2 +- nanobot/agent/runner.py | 33 +- nanobot/agent/turn_delivery.py | 4 +- nanobot/bus/outbound_events.py | 1 + nanobot/bus/runtime_events.py | 25 +- nanobot/channels/websocket/runtime.py | 3 + .../websocket/tests/test_websocket_channel.py | 16 + nanobot/session/webui_turns.py | 3 + nanobot/webui/outbound_projection.py | 2 + nanobot/webui/transcript.py | 35 +- tests/agent/test_runner_core.py | 21 + tests/agent/test_runner_governance.py | 6 + tests/bus/test_runtime_events.py | 8 +- tests/utils/test_webui_transcript.py | 25 ++ webui/src/components/MessageBubble.tsx | 76 +--- .../thread/ComposerUsagePopover.tsx | 410 ++++++++++++++++++ .../src/components/thread/ThreadComposer.tsx | 116 +---- webui/src/components/thread/ThreadShell.tsx | 70 ++- webui/src/globals.css | 31 ++ webui/src/hooks/useNanobotStream.ts | 1 + webui/src/i18n/locales/en/common.json | 12 +- webui/src/i18n/locales/es/common.json | 12 +- webui/src/i18n/locales/fr/common.json | 12 +- webui/src/i18n/locales/id/common.json | 12 +- webui/src/i18n/locales/ja/common.json | 12 +- webui/src/i18n/locales/ko/common.json | 12 +- webui/src/i18n/locales/pt-BR/common.json | 12 +- webui/src/i18n/locales/vi/common.json | 12 +- webui/src/i18n/locales/zh-CN/common.json | 12 +- webui/src/i18n/locales/zh-TW/common.json | 12 +- webui/src/lib/thread-event-projection.ts | 5 +- webui/src/lib/types.ts | 12 +- webui/src/tests/message-bubble.test.tsx | 45 -- webui/src/tests/thread-composer.test.tsx | 126 +++++- webui/src/tests/thread-shell.test.tsx | 72 +++ 35 files changed, 994 insertions(+), 274 deletions(-) create mode 100644 webui/src/components/thread/ComposerUsagePopover.tsx 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 = ( - - {parts.join(" · ")} - - ); - - if (details.length === 0) return usageMeta; - - return ( - - {usageMeta} - - {details.join(" · ")} - - - ); -} - 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({ {forkLabel} ) : null} - {showUsage ? ( - - ) : null} {showAssistantTimestamp ? ( 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(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 ( + + + + + + + + + + {contextDescription} + + + + { + 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" + > +
+ {contextPercentage !== null ? ( + <> +
+
+ + {t("thread.composer.context.contextTitle", { + defaultValue: "Context", + })} + + + {formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount( + context!.contextWindowTokens!, + )} + +
+ + {contextPercentage}% + +
+
+
+
+ + ) : null} + + {normalizedRounds.length > 0 ? ( + <> +
+ + {t("thread.composer.context.recentRounds", { + defaultValue: "Recent rounds", + })} + + + {t("thread.composer.context.inputTrend", { + defaultValue: "Input tokens", + })} + +
+
+ {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 => !!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 ( + 1 + && index === normalizedRounds.length - 1 + && "justify-end", + index === normalizedRounds.length - 1 && "opacity-100", + )} + > + + + + {cachedKnown ? ( + <> + {notReusedTokens > 0 ? ( + + ) : null} + {cachedTokens > 0 ? ( + + ) : null} + + ) : ( + + )} + + + + + {timestampLabel} + + + {detailRows.map((row) => ( + + + {row.label} + + + {row.value} + + + ))} + + {detailNote ? ( + + {detailNote} + + ) : null} + + + + ); + })} +
+ + ) : null} + +
+ + + + ); +} 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 ( - - - - - - - {contextDescription} - - - - ); -} - 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 ? : null} + {!voiceRecorder.isRecording ? ( + + ) : null} {showVoiceButton ? ( 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(); + 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, + 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(); - - 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(); - - 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( + , + ); + + 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( + , + ); + + 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( + {}} + 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( { ); }); + 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, + {}} + 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");