Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(chat): show per-turn token usage capsule
v_wyxgwang6c90bf42739d
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex c6d9bfe45..87c6091c0 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -425,6 +425,7 @@ export const AssistantTurn = memo(function AssistantTurn({usage={usage}responseDurationMs={responseDurationMs}responseOutputTokens={responseOutputTokens}+ responseOutputEstimated={summary.responseOutputEstimated}/>) : null}{complete && actionMessage ? (diff --git a/apps/desktop/src/features/chat/transcript/TurnUsageCapsule.tsx b/apps/desktop/src/features/chat/transcript/TurnUsageCapsule.tsxnew file mode 100644index 000000000..3e9041833--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/TurnUsageCapsule.tsx@@ -0,0 +1,337 @@+import {+ useCallback,+ useEffect,+ useId,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { formatCompactTokenCount, type MessageUsage } from "@pi-desktop/shared";+import {+ placeContextInspector,+ type ContextInspectorPlacement,+} from "../../../lib/context-inspector-position";+import {+ turnUsageBreakdown,+ type TurnUsageBreakdown,+} from "../../../lib/context-usage";+import { portalToBody } from "../../../lib/portal-visibility";++const CLOSE_DELAY_MS = 120;++type CompositionSegment = {+ key: "cache" | "input" | "output" | "write";+ tokens: number;+};++function compositionSegments(+ breakdown: TurnUsageBreakdown,+): CompositionSegment[] {+ const segments: CompositionSegment[] = [+ { key: "cache", tokens: breakdown.cacheReadTokens },+ { key: "input", tokens: breakdown.inputTokens },+ { key: "output", tokens: breakdown.outputTokens },+ { key: "write", tokens: breakdown.cacheWriteTokens },+ ];+ return segments.filter((segment) => segment.tokens > 0);+}++/**+ * One proportional bar for the turn composition. Segments with no tokens are+ * omitted rather than painted at zero width; `flex-basis: 0` makes the inline+ * grow factor their only width input.+ */+function CompositionBar({ breakdown }: { breakdown: TurnUsageBreakdown }) {+ return (+ <span className="turn-usage-bar" aria-hidden="true">+ {compositionSegments(breakdown).map((segment) => (+ <span+ key={segment.key}+ className={`turn-usage-seg ${segment.key}`}+ style={{ flexGrow: segment.tokens }}+ />+ ))}+ </span>+ );+}++/**+ * Completed-turn usage capsule: speed and total stay visible, while the+ * composition and exact counts live in a hover/focus popover.+ *+ * The popover is pointer-open rather than click-toggled, so it leaves a short+ * grace window while the pointer crosses the gap between the capsule and the+ * panel. It portals to the body and clamps to `.main-pane` for the same reason+ * as the composer context inspector: the work panel's native surfaces compose+ * above every renderer layer.+ */+export function TurnUsageCapsule({+ usage,+ throughput,+ estimated = false,+}: {+ usage: MessageUsage;+ throughput?: number;+ /** Output tokens came from the interrupted-response estimate, not provider usage. */+ estimated?: boolean;+}) {+ const { t, i18n } = useTranslation();+ const panelId = useId();+ const triggerRef = useRef<HTMLButtonElement>(null);+ const popoverRef = useRef<HTMLDivElement>(null);+ const closeTimerRef = useRef<number | null>(null);+ const overTriggerRef = useRef(false);+ const overPanelRef = useRef(false);+ const [open, setOpen] = useState(false);+ const [position, setPosition] = useState<ContextInspectorPlacement | null>(+ null,+ );++ const breakdown = turnUsageBreakdown(usage);+ const compactTotal = formatCompactTokenCount(breakdown.totalTokens);+ const speed =+ throughput === undefined+ ? t("chat.usageThroughputUnavailable")+ : t(+ estimated+ ? "chat.usageThroughputEstimated"+ : "chat.usageThroughput",+ {+ count: formatCompactTokenCount(throughput),+ },+ );+ const numberFormat = useMemo(+ () => new Intl.NumberFormat(i18n.language),+ [i18n.language],+ );++ const cancelClose = useCallback(() => {+ if (closeTimerRef.current === null) return;+ window.clearTimeout(closeTimerRef.current);+ closeTimerRef.current = null;+ }, []);++ const scheduleClose = useCallback(() => {+ cancelClose();+ // Hovering the capsule and its panel keeps the popover open, and keyboard+ // focus owns it until focus moves away.+ if (+ overTriggerRef.current ||+ overPanelRef.current ||+ document.activeElement === triggerRef.current+ ) {+ return;+ }+ closeTimerRef.current = window.setTimeout(() => {+ closeTimerRef.current = null;+ setOpen(false);+ setPosition(null);+ }, CLOSE_DELAY_MS);+ }, [cancelClose]);++ const openPopover = useCallback(() => {+ cancelClose();+ setOpen(true);+ }, [cancelClose]);++ const updatePosition = useCallback(() => {+ const trigger = triggerRef.current;+ const popover = popoverRef.current;+ if (!trigger || !popover) return;++ const triggerRect = trigger.getBoundingClientRect();+ if (triggerRect.bottom <= 0 || triggerRect.top >= window.innerHeight) {+ setOpen(false);+ setPosition(null);+ return;+ }++ const popoverRect = popover.getBoundingClientRect();+ const paneRect = trigger.closest(".main-pane")?.getBoundingClientRect();+ const next = placeContextInspector({+ trigger: {+ left: triggerRect.left,+ top: triggerRect.top,+ bottom: triggerRect.bottom,+ },+ popover: { width: popoverRect.width, height: popoverRect.height },+ pane: paneRect ? { left: paneRect.left, right: paneRect.right } : null,+ viewport: { width: window.innerWidth, height: window.innerHeight },+ // The approved capsule design opens into the space under the answer;+ // the bottom dock flips it above only when that space is too short.+ prefer: "below",+ });+ if (!next) {+ setOpen(false);+ setPosition(null);+ return;+ }++ setPosition((previous) =>+ previous?.top === next.top &&+ previous.left === next.left &&+ previous.maxWidth === next.maxWidth+ ? previous+ : next,+ );+ }, []);++ useEffect(() => cancelClose, [cancelClose]);++ useLayoutEffect(() => {+ if (!open) return;+ const frame = window.requestAnimationFrame(updatePosition);+ return () => window.cancelAnimationFrame(frame);+ }, [open, updatePosition]);++ useEffect(() => {+ if (!open) return;+ const handleViewportChange = () => updatePosition();+ window.addEventListener("resize", handleViewportChange);+ window.addEventListener("scroll", handleViewportChange, true);+ return () => {+ window.removeEventListener("resize", handleViewportChange);+ window.removeEventListener("scroll", handleViewportChange, true);+ };+ }, [open, updatePosition]);++ // Sidebar and work-panel changes move the pane's right edge without a window+ // resize or scroll event, so the open popover watches the pane geometry.+ useEffect(() => {+ if (!open || typeof ResizeObserver === "undefined") return;+ const pane = triggerRef.current?.closest(".main-pane");+ if (!pane) return;+ const observer = new ResizeObserver(updatePosition);+ observer.observe(pane);+ return () => observer.disconnect();+ }, [open, updatePosition]);++ useEffect(() => {+ if (!open) return;+ const handlePointerDown = (event: PointerEvent) => {+ const target = event.target as Node | null;+ if (!target) return;+ if (+ triggerRef.current?.contains(target) ||+ popoverRef.current?.contains(target)+ ) {+ return;+ }+ cancelClose();+ setOpen(false);+ setPosition(null);+ };+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ cancelClose();+ setOpen(false);+ setPosition(null);+ };+ window.addEventListener("pointerdown", handlePointerDown, true);+ window.addEventListener("keydown", handleKeyDown);+ return () => {+ window.removeEventListener("pointerdown", handlePointerDown, true);+ window.removeEventListener("keydown", handleKeyDown);+ };+ }, [cancelClose, open]);++ const popover = open ? (+ <div+ ref={popoverRef}+ id={panelId}+ className={`turn-usage-popover${position ? " is-open" : ""}`}+ role="dialog"+ aria-label={t("chat.usageTurnTotal")}+ style={+ position+ ? {+ top: `${position.top}px`,+ left: `${position.left}px`,+ maxWidth: `${position.maxWidth}px`,+ }+ : undefined+ }+ onPointerEnter={() => {+ overPanelRef.current = true;+ cancelClose();+ }}+ onPointerLeave={() => {+ overPanelRef.current = false;+ scheduleClose();+ }}+ >+ <div className="turn-usage-popover-head">+ <span className="turn-usage-popover-title">+ {t("chat.usageTurnTotal")}+ </span>+ <span className="turn-usage-popover-total">{compactTotal}</span>+ </div>+ <CompositionBar breakdown={breakdown} />+ <dl className="turn-usage-rows">+ <div className="turn-usage-row">+ <dt>{t("chat.usageCacheRead")}</dt>+ <dd>{numberFormat.format(breakdown.cacheReadTokens)}</dd>+ </div>+ <div className="turn-usage-row">+ <dt>{t("chat.usageInput")}</dt>+ <dd>{numberFormat.format(breakdown.inputTokens)}</dd>+ </div>+ <div className="turn-usage-row">+ <dt>{t("chat.usageOutput")}</dt>+ <dd>{numberFormat.format(breakdown.outputTokens)}</dd>+ </div>+ {breakdown.cacheWriteTokens > 0 ? (+ <div className="turn-usage-row">+ <dt>{t("chat.usageCacheWrite")}</dt>+ <dd>{numberFormat.format(breakdown.cacheWriteTokens)}</dd>+ </div>+ ) : null}+ </dl>+ <div className="turn-usage-popover-footer">+ <span>{t("chat.usageTotal")}</span>+ <strong>{numberFormat.format(breakdown.totalTokens)}</strong>+ </div>+ </div>+ ) : null;++ return (+ <>+ <button+ ref={triggerRef}+ type="button"+ className="turn-usage-capsule"+ data-open={open ? "true" : "false"}+ aria-haspopup="dialog"+ aria-expanded={open}+ aria-controls={open ? panelId : undefined}+ aria-label={t("chat.usageTurnAria", {+ speed,+ count: compactTotal,+ })}+ onPointerEnter={() => {+ overTriggerRef.current = true;+ openPopover();+ }}+ onPointerLeave={() => {+ overTriggerRef.current = false;+ scheduleClose();+ }}+ onFocus={openPopover}+ onBlur={scheduleClose}+ onClick={openPopover}+ >+ <CompositionBar breakdown={breakdown} />+ <span className="turn-usage-speed">{speed}</span>+ <span className="turn-usage-separator" aria-hidden="true">+ ·+ </span>+ <span className="turn-usage-total">{compactTotal}</span>+ </button>+ {popover && typeof document !== "undefined"+ ? portalToBody(popover)+ : null}+ </>+ );+}diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsxindex 3a075dd8b..5942fc729 100644--- a/apps/desktop/src/features/chat/transcript/shared.tsx+++ b/apps/desktop/src/features/chat/transcript/shared.tsx@@ -32,7 +32,10 @@ import { useVerifiedChatText } from "../../../hooks/use-verified-chat-text";import { isHtmlFilePath } from "../../../lib/chat-links";import type { SourcePositionProps } from "../../../lib/markdown-source";import type { ToolAction } from "../../../lib/tool-display";-import { calculateTokenRate } from "../../../lib/context-usage";+import {+ calculateTokenRate,+ turnUsageBreakdown,+} from "../../../lib/context-usage";import { useAppStore } from "../../../stores/app-store";import { Markdown, useCopy } from "../../../components/Markdown";import {@@ -62,6 +65,7 @@ import {} from "../../../components/icons";import { TooltipButton } from "../../../components/ui";import { TextShimmer } from "./TextShimmer";+import { TurnUsageCapsule } from "./TurnUsageCapsule";/*** Legacy message navigation reveals the row it names, at message precision.@@ -159,19 +163,25 @@ export function MessageMeta({usage,responseDurationMs,responseOutputTokens,+ responseOutputEstimated,}: {modelId?: string;usage?: MessageUsage;responseDurationMs?: number;responseOutputTokens?: number;+ responseOutputEstimated?: boolean;}) {const { t } = useTranslation();const throughput = calculateTokenRate(responseOutputTokens ?? usage?.outputTokens ?? 0,responseDurationMs,);+ // Completed turns with usage replace the legacy estimated-throughput chip+ // with the full turn capsule; only usage-less turns keep the estimate.+ const showTurnUsage =+ usage !== undefined && turnUsageBreakdown(usage).totalTokens > 0;const showThroughput = !usage && throughput !== undefined;- if (!modelId && !showThroughput) {+ if (!modelId && !showThroughput && !showTurnUsage) {return null;}return (@@ -181,6 +191,13 @@ export function MessageMeta({{modelId}</span>) : null}+ {usage && showTurnUsage ? (+ <TurnUsageCapsule+ usage={usage}+ throughput={throughput}+ estimated={responseOutputEstimated}+ />+ ) : null}{showThroughput ? (<span className="message-meta-chip throughput">{t("chat.usageThroughputEstimated", {diff --git a/apps/desktop/src/lib/context-inspector-position.ts b/apps/desktop/src/lib/context-inspector-position.tsindex a18e5e81c..58647419b 100644--- a/apps/desktop/src/lib/context-inspector-position.ts+++ b/apps/desktop/src/lib/context-inspector-position.ts@@ -49,6 +49,7 @@ export function placeContextInspector({viewport,margin = CONTEXT_INSPECTOR_MARGIN,gap = CONTEXT_INSPECTOR_GAP,+ prefer = "above",}: {trigger: ContextInspectorTrigger;popover: { width: number; height: number };@@ -57,6 +58,11 @@ export function placeContextInspector({viewport: { width: number; height: number };margin?: number;gap?: number;+ /**+ * Which side wins when both fit. The composer inspector opens above its+ * bottom-docked trigger; a turn footer prefers the space below the answer.+ */+ prefer?: "above" | "below";}): ContextInspectorPlacement | null {const left = (pane ? pane.left : 0) + margin;const right = (pane ? pane.right : viewport.width) - margin;@@ -75,12 +81,20 @@ export function placeContextInspector({margin,viewport.height - popover.height - margin,);+ const fitsAbove = above >= margin && above <= maximumTop;+ const fitsBelow = below >= margin && below <= maximumTop;const top =- above >= margin && above <= maximumTop- ? above- : below >= margin && below <= maximumTop+ prefer === "below"+ ? fitsBelow? below- : Math.min(Math.max(margin, below), maximumTop);+ : fitsAbove+ ? above+ : Math.min(Math.max(margin, below), maximumTop)+ : fitsAbove+ ? above+ : fitsBelow+ ? below+ : Math.min(Math.max(margin, below), maximumTop);return { top, left: clampedLeft, maxWidth };}diff --git a/apps/desktop/src/lib/context-usage.ts b/apps/desktop/src/lib/context-usage.tsindex 169581781..d87eaedd1 100644--- a/apps/desktop/src/lib/context-usage.ts+++ b/apps/desktop/src/lib/context-usage.ts@@ -42,6 +42,43 @@ export function contextOccupancyTokens(usage: MessageUsage): number {return occupancy > 0 ? occupancy : usageTokenTotal(usage);}+export type TurnUsageBreakdown = {+ inputTokens: number;+ outputTokens: number;+ cacheReadTokens: number;+ cacheWriteTokens: number;+ totalTokens: number;+};++/**+ * Token composition of one visual turn, built from the `usage` that+ * `getAssistantTurnSummary` already aggregated across the turn's assistant+ * messages.+ *+ * `totalTokens` is deliberately the sum of the four buckets and never the+ * provider-reported `usage.totalTokens`, which can be rounded or omit cache+ * buckets. Reasoning tokens are already part of `outputTokens`, so they are+ * never added again. Subagent spend stays out: only the parent messages'+ * usage is aggregated here, consistent with ADR 0171.+ *+ * This is a turn aggregate, unlike the composer context inspector, which+ * describes only the newest model request (D355 / ADR 0193).+ */+export function turnUsageBreakdown(usage?: MessageUsage): TurnUsageBreakdown {+ const inputTokens = positiveTokenCount(usage?.inputTokens);+ const outputTokens = positiveTokenCount(usage?.outputTokens);+ const cacheReadTokens = positiveTokenCount(usage?.cacheReadTokens);+ const cacheWriteTokens = positiveTokenCount(usage?.cacheWriteTokens);+ return {+ inputTokens,+ outputTokens,+ cacheReadTokens,+ cacheWriteTokens,+ totalTokens:+ inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens,+ };+}+export function latestMessageUsage(messages: UiMessage[]): MessageUsage | undefined {for (let index = messages.length - 1; index >= 0; index -= 1) {if (messages[index].usage) return messages[index].usage;diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.cssindex 9dc23f946..8d2d47eb8 100644--- a/apps/desktop/src/styles/messages.css+++ b/apps/desktop/src/styles/messages.css@@ -1366,6 +1366,210 @@text-overflow: ellipsis;}+/* Turn usage capsule: the completed turn's speed and total stay visible; the+ composition and exact counts live in the hover/focus popover. */+.turn-usage-capsule {+ display: inline-flex;+ min-height: 20px;+ max-width: 100%;+ align-items: center;+ gap: 6px;+ border: 0;+ border-radius: var(--radius-full);+ background: var(--ds-tile);+ padding: 0 8px;+ color: var(--ds-text-secondary);+ cursor: pointer;+ font: inherit;+ font-size: var(--text-xs);+ line-height: var(--leading-compact);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+ transition:+ background var(--motion-duration-fast) var(--motion-ease-out),+ color var(--motion-duration-fast) var(--motion-ease-out),+ box-shadow var(--motion-duration-fast) var(--motion-ease-out);+}++.turn-usage-capsule:hover,+.turn-usage-capsule[data-open="true"] {+ background: var(--ds-tile-hover);+ color: var(--ds-text-primary);+ box-shadow: inset 0 0 0 1px var(--ds-border-subtle);+}++.turn-usage-capsule:focus-visible {+ outline: 2px solid color-mix(in oklab, var(--ds-text-primary) 44%, transparent);+ outline-offset: 2px;+}++/* The bar is a flex row of proportional segments. Segment order matches the+ popover rows: cache read, input, output, then cache write when present. */+.turn-usage-bar {+ display: flex;+ width: 36px;+ height: 4px;+ flex: 0 0 36px;+ gap: 1px;+ overflow: hidden;+ border-radius: var(--radius-full);+ background: color-mix(in oklab, var(--ds-text-primary) 7%, transparent);+}++.turn-usage-seg {+ min-width: 1px;+ flex-basis: 0;+ border-radius: var(--radius-full);+}++.turn-usage-seg.cache {+ background: color-mix(in oklab, var(--ds-text-primary) 24%, transparent);+}++.turn-usage-seg.input {+ background: color-mix(in oklab, var(--ds-text-primary) 51%, transparent);+}++.turn-usage-seg.output {+ background: color-mix(in oklab, var(--ds-text-primary) 86%, transparent);+}++.turn-usage-seg.write {+ background: color-mix(in oklab, var(--ds-text-primary) 36%, transparent);+}++.turn-usage-separator {+ color: var(--ds-text-faint);+}++.turn-usage-total {+ color: var(--ds-text-muted);+ font-variant-numeric: tabular-nums;+}++.turn-usage-capsule:hover .turn-usage-total,+.turn-usage-capsule[data-open="true"] .turn-usage-total {+ color: var(--ds-text-secondary);+}++.turn-usage-popover {+ position: fixed;+ z-index: 60;+ display: flex;+ width: min(268px, calc(100vw - 32px));+ flex-direction: column;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-md-plus);+ background: var(--ds-bg-elevated-opaque);+ padding: 12px;+ color: var(--ds-text-primary);+ box-shadow: var(--ds-shadow-dialog);+ font-size: var(--text-xs);+ line-height: var(--leading-body);+ text-align: left;+ white-space: normal;+ opacity: 0;+ pointer-events: none;+ transform: translateY(4px);+ visibility: hidden;+ transition:+ opacity var(--motion-duration-fast) var(--motion-ease-out),+ transform var(--motion-duration-fast) var(--motion-ease-out),+ visibility 0s linear var(--motion-duration-fast);+}++.turn-usage-popover.is-open {+ opacity: 1;+ pointer-events: auto;+ transform: translateY(0);+ visibility: visible;+ transition-delay: 0s;+}++.turn-usage-popover-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+}++.turn-usage-popover-title {+ color: var(--ds-text-muted);+ font-size: var(--text-2xs);+ line-height: var(--leading-compact);+}++.turn-usage-popover-total {+ color: var(--ds-text-primary);+ font-size: var(--text-md);+ font-weight: var(--font-weight-strong);+ line-height: var(--leading-compact);+ font-variant-numeric: tabular-nums;+}++.turn-usage-popover .turn-usage-bar {+ width: 100%;+ flex: 0 0 auto;+ height: 4px;+ gap: 2px;+ margin: 11px 0 8px;+}++.turn-usage-rows {+ display: flex;+ flex-direction: column;+ gap: 1px;+ margin: 0;+}++.turn-usage-row {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 14px;+ padding: 2px 0;+ font-size: var(--text-xs);+ line-height: var(--leading-body);+}++.turn-usage-row dt {+ margin: 0;+ color: var(--ds-text-muted);+ font-weight: var(--font-weight-normal);+}++.turn-usage-row dd {+ margin: 0;+ color: var(--ds-text-secondary);+ font-weight: var(--font-weight-medium);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.turn-usage-popover-footer {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ margin-top: 8px;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+ line-height: var(--leading-compact);+}++.turn-usage-popover-footer strong {+ color: var(--ds-text-primary);+ font-weight: var(--font-weight-medium);+ font-variant-numeric: tabular-nums;+}++@media (prefers-reduced-motion: reduce) {+ .turn-usage-capsule,+ .turn-usage-popover {+ transition: none;+ }+}+.context-inspector {position: relative;display: inline-flex;diff --git a/apps/desktop/test/context-inspector-position.test.mjs b/apps/desktop/test/context-inspector-position.test.mjsindex dda30cb22..c9c785ffd 100644--- a/apps/desktop/test/context-inspector-position.test.mjs+++ b/apps/desktop/test/context-inspector-position.test.mjs@@ -77,6 +77,21 @@ test("the popover opens above the trigger and falls back below it", () => {assert.equal(below.top, 128 + 8);});+test("a turn footer can prefer the space below while the dock keeps above", () => {+ const trigger = { left: 600, top: 400, bottom: 428 };+ const above = place(trigger);+ const below = placeContextInspector({+ trigger,+ popover: POPOVER,+ pane: PANE,+ viewport: VIEWPORT,+ prefer: "below",+ });+ assert.ok(above && below);+ assert.equal(above.top, 400 - POPOVER.height - 8);+ assert.equal(below.top, 428 + 8);+});+test("a pane with no usable width leaves the popover unplaced", () => {assert.equal(place({ left: 10, top: 700, bottom: 728 }, { left: 0, right: 20 }),diff --git a/apps/desktop/test/context-usage.test.mjs b/apps/desktop/test/context-usage.test.mjsindex b5f6c9f9f..e29514fd0 100644--- a/apps/desktop/test/context-usage.test.mjs+++ b/apps/desktop/test/context-usage.test.mjs@@ -12,6 +12,7 @@ import {resolveContextUsageDisplay,resolveContextWindow,toolTokenUsage,+ turnUsageBreakdown,usageTokenTotal,settleStoppedAssistantMetrics,} from "../src/lib/context-usage.ts";@@ -218,6 +219,68 @@ test("occupancy sums last-request input, output, and cache, not reasoning twice"assert.equal(usageTokenTotal(usage), 15);});+test("turn usage breakdown returns zeros for an absent usage", () => {+ assert.deepEqual(turnUsageBreakdown(undefined), {+ inputTokens: 0,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ totalTokens: 0,+ });+});++test("turn usage breakdown sums the visual turn instead of the reported total", () => {+ const breakdown = turnUsageBreakdown({+ inputTokens: 3_214,+ outputTokens: 1_824,+ cacheReadTokens: 12_096,+ totalTokens: 17_000,+ });+ assert.deepEqual(breakdown, {+ inputTokens: 3_214,+ outputTokens: 1_824,+ cacheReadTokens: 12_096,+ cacheWriteTokens: 0,+ totalTokens: 17_134,+ });+});++test("turn usage breakdown includes cache writes but never adds reasoning again", () => {+ const breakdown = turnUsageBreakdown({+ inputTokens: 100,+ outputTokens: 50,+ cacheReadTokens: 200,+ cacheWriteTokens: 25,+ reasoningTokens: 12,+ totalTokens: 150,+ });+ // Reasoning is already inside output, and the provider total is ignored.+ assert.deepEqual(breakdown, {+ inputTokens: 100,+ outputTokens: 50,+ cacheReadTokens: 200,+ cacheWriteTokens: 25,+ totalTokens: 375,+ });+});++test("turn usage breakdown normalizes negative and fractional values", () => {+ const breakdown = turnUsageBreakdown({+ inputTokens: -5,+ outputTokens: 10.6,+ cacheReadTokens: 2.4,+ cacheWriteTokens: Number.NaN,+ totalTokens: 999,+ });+ assert.deepEqual(breakdown, {+ inputTokens: 0,+ outputTokens: 11,+ cacheReadTokens: 2,+ cacheWriteTokens: 0,+ totalTokens: 13,+ });+});+test("generation throughput uses provider output and stream duration", () => {assert.equal(calculateTokenRate(1_200, 4_000), 300);assert.equal(calculateTokenRate(0, 4_000), undefined);diff --git a/apps/desktop/test/turn-usage-capsule.test.mjs b/apps/desktop/test/turn-usage-capsule.test.mjsnew file mode 100644index 000000000..25603db98--- /dev/null+++ b/apps/desktop/test/turn-usage-capsule.test.mjs@@ -0,0 +1,183 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++const read = (path) => readFile(new URL(path, import.meta.url), "utf8");++const LOCALES = ["en", "zh-CN", "zh-TW", "tr", "de", "es", "fr", "ko", "pt-BR"];++const [capsule, shared, css, componentSpec, ...catalogs] = await Promise.all([+ read("../src/features/chat/transcript/TurnUsageCapsule.tsx"),+ read("../src/features/chat/transcript/shared.tsx"),+ read("../src/styles/messages.css"),+ read("../../../docs/spec/04-ux/08-component-spec.md"),+ ...LOCALES.map((locale) =>+ read(`../../../packages/i18n/src/locales/${locale}/index.ts`),+ ),+]);++test("MessageMeta places the capsule immediately after the model chip", () => {+ const modelChip = shared.indexOf("message-meta-chip model");+ const capsuleUsage = shared.indexOf("<TurnUsageCapsule");+ assert.ok(modelChip > -1, "the model chip is still rendered");+ assert.ok(capsuleUsage > modelChip, "the capsule follows the model chip");+ assert.match(+ shared,+ /message-meta-chip model[\s\S]{0,400}?<TurnUsageCapsule/,+ );+ assert.doesNotMatch(shared, /<TurnUsageCapsule[\s\S]{0,200}?message-meta-chip model/);+});++test("the capsule renders only from turn usage and replaces the legacy chip", () => {+ assert.match(shared, /turnUsageBreakdown\(usage\)\.totalTokens > 0/);+ assert.match(shared, /usage && showTurnUsage/);+ assert.match(shared, /responseOutputEstimated/);+ assert.match(shared, /estimated=\{responseOutputEstimated\}/);+ assert.match(capsule, /estimated\s*\?/);+ assert.match(capsule, /chat\.usageThroughputEstimated/);+ assert.match(shared, /const showThroughput = !usage && throughput !== undefined/);+ assert.match(shared, /showThroughput \? \(/);+ assert.match(shared, /!modelId && !showThroughput && !showTurnUsage/);+});++test("the capsule wires hover, focus, grace close, Escape, and outside press", () => {+ assert.match(capsule, /const CLOSE_DELAY_MS = 120/);+ assert.match(capsule, /onPointerEnter/);+ assert.match(capsule, /onPointerLeave/);+ assert.match(capsule, /onFocus=\{openPopover\}/);+ assert.match(capsule, /onBlur=\{scheduleClose\}/);+ assert.match(capsule, /onClick=\{openPopover\}/);+ assert.match(capsule, /overTriggerRef\.current/);+ assert.match(capsule, /overPanelRef\.current/);+ assert.match(capsule, /document\.activeElement === triggerRef\.current/);+ assert.match(capsule, /event\.key !== "Escape"/);+ assert.match(capsule, /window\.setTimeout\(/);+ assert.match(+ capsule,+ /addEventListener\("pointerdown", handlePointerDown, true\)/,+ );+});++test("the popover portals to body and clamps to the conversation pane", () => {+ assert.match(capsule, /useId\(\)/);+ assert.match(capsule, /portalToBody\(popover\)/);+ assert.match(capsule, /placeContextInspector\(\{/);+ assert.match(capsule, /prefer: "below"/);+ assert.match(capsule, /closest\("\.main-pane"\)/);+ assert.match(capsule, /new ResizeObserver\(updatePosition\)/);+ assert.match(capsule, /addEventListener\("scroll", handleViewportChange, true\)/);+ assert.match(capsule, /addEventListener\("resize", handleViewportChange\)/);+ assert.match(capsule, /triggerRect\.bottom <= 0/);+ assert.match(capsule, /const popover = open \?/);+});++test("the capsule exposes dialog semantics and an accessible turn summary", () => {+ assert.match(capsule, /aria-haspopup="dialog"/);+ assert.match(capsule, /aria-expanded=\{open\}/);+ assert.match(capsule, /aria-controls=\{open \? panelId : undefined\}/);+ assert.match(capsule, /aria-label=\{t\("chat\.usageTurnAria"/);+ assert.match(capsule, /role="dialog"/);+ assert.match(capsule, /aria-label=\{t\("chat\.usageTurnTotal"\)\}/);+ assert.match(capsule, /aria-hidden="true"/);+ assert.match(capsule, /new Intl\.NumberFormat\(i18n\.language\)/);+ assert.match(capsule, /formatCompactTokenCount/);+});++test("the composition omits empty segments and keeps cache write conditional", () => {+ assert.match(capsule, /filter\(\(segment\) => segment\.tokens > 0\)/);+ assert.match(capsule, /className=\{`turn-usage-seg \$\{segment\.key\}`\}/);+ assert.match(capsule, /style=\{\{ flexGrow: segment\.tokens \}\}/);+ assert.match(capsule, /breakdown\.cacheWriteTokens > 0 \?/);+ assert.match(capsule, /className="turn-usage-bar"/);+});++test("the capsule styles use surface tokens and match the meta chip height", () => {+ const capsuleRule = css.match(/\.turn-usage-capsule \{[\s\S]*?\n\}/)?.[0] ?? "";+ assert.match(capsuleRule, /min-height: 20px/);+ assert.match(capsuleRule, /padding: 0 8px/);+ assert.match(capsuleRule, /gap: 6px/);+ assert.match(capsuleRule, /font-size: var\(--text-xs\)/);+ assert.match(capsuleRule, /line-height: var\(--leading-compact\)/);+ assert.match(capsuleRule, /font-variant-numeric: tabular-nums/);+ assert.match(capsuleRule, /white-space: nowrap/);+ assert.match(capsuleRule, /max-width: 100%/);+ assert.match(capsuleRule, /background: var\(--ds-tile\)/);++ const hoverRule =+ css.match(+ /\.turn-usage-capsule:hover,\n\.turn-usage-capsule\[data-open="true"\] \{[\s\S]*?\n\}/,+ )?.[0] ?? "";+ assert.match(hoverRule, /background: var\(--ds-tile-hover\)/);+ assert.match(hoverRule, /inset 0 0 0 1px var\(--ds-border-subtle\)/);++ const barRule = css.match(/\.turn-usage-bar \{[\s\S]*?\n\}/)?.[0] ?? "";+ assert.match(barRule, /width: 36px/);+ assert.match(barRule, /height: 4px/);++ const segmentRule = css.match(/\.turn-usage-seg \{[\s\S]*?\n\}/)?.[0] ?? "";+ assert.match(segmentRule, /flex-basis: 0/);+ for (const key of ["cache", "input", "output", "write"]) {+ assert.match(css, new RegExp(`\\.turn-usage-seg\\.${key} \\{`));+ }+ for (const key of ["cache", "input", "output", "write"]) {+ assert.match(+ css,+ new RegExp(+ `\\.turn-usage-seg\\.${key} \\{\\s*background: color-mix\\(in oklab, var\\(--ds-text-primary\\)`,+ ),+ );+ }++ const popoverRule =+ css.match(/\.turn-usage-popover \{[\s\S]*?\n\}/)?.[0] ?? "";+ assert.match(popoverRule, /position: fixed/);+ assert.match(popoverRule, /z-index: 60/);+ assert.match(popoverRule, /width: min\(268px, calc\(100vw - 32px\)\)/);+ assert.match(popoverRule, /background: var\(--ds-bg-elevated-opaque\)/);+ assert.match(popoverRule, /border: 1px solid var\(--ds-border-default\)/);+ assert.match(popoverRule, /border-radius: var\(--radius-md-plus\)/);+ assert.match(popoverRule, /padding: 12px/);+ assert.match(popoverRule, /box-shadow: var\(--ds-shadow-dialog\)/);+ assert.match(css, /\.turn-usage-popover\.is-open \{/);+ assert.match(+ css,+ /@media \(prefers-reduced-motion: reduce\) \{\s*\.turn-usage-capsule,\s*\.turn-usage-popover \{\s*transition: none;/,+ );++ const newBlock = css.slice(+ css.indexOf(".turn-usage-capsule {"),+ css.indexOf(".context-inspector {"),+ );+ assert.doesNotMatch(newBlock, /#[\da-f]{3,8}\b/i);+});++test("every locale adds the turn aria label and total label exactly once", () => {+ for (const [index, locale] of LOCALES.entries()) {+ const source = catalogs[index];+ assert.equal(+ (source.match(/"?usageTurnAria"?\s*:/g) ?? []).length,+ 1,+ `${locale} defines usageTurnAria once`,+ );+ assert.equal(+ (source.match(/"?usageTotal"?\s*:/g) ?? []).length,+ 1,+ `${locale} defines usageTotal once`,+ );+ assert.match(+ source,+ /"?usageTurnAria"?\s*:\s*"[^"]*\{\{speed\}\}[^"]*\{\{count\}\}[^"]*"/,+ `${locale} keeps speed and count placeholders`,+ );+ }+});++test("the component spec documents the capsule aggregate and its boundary", () => {+ assert.match(componentSpec, /turn usage capsule/i);+ assert.match(componentSpec, /summed\s+across the visual turn's assistant messages/);+ assert.match(componentSpec, /reasoning tokens/);+ assert.match(+ componentSpec,+ /last-request\s+occupancy stays deliberately distinct/,+ );+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex c0cabe228..21255536b 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1963,7 +1963,24 @@ Single message render — either user (plaintext) or assistant (markdown streamicopies all contentful fragments in order; Fork and Regenerate target the lastcontentful fragment so existing durable transcript semantics remain intact(D157).-- Assistant meta: optional model badge under the answer. The compact+- Assistant meta: optional model badge under the answer, followed immediately+ by the turn usage capsule whenever that completed visual turn has usage. The+ capsule always shows the turn's average generation speed and compact total+ tokens; hovering or keyboard-focusing it opens a fixed-position popover with+ the compact total, the cache-read/input/output composition bar, exact+ cache-read/input/output counts (cache write only when non-zero), and an+ exact total. The total is `input + output + cacheRead + cacheWrite` summed+ across the visual turn's assistant messages; `output` already carries the+ reasoning tokens, so `reasoningTokens` is never added again, and subagent+ spend is not included (D103). Speed is summed output tokens over summed+ response duration. No meta row, and therefore no capsule, renders while the+ turn is streaming. The capsule's+ accessible name states the speed and total and that activating it shows the+ breakdown. The popover portals to the document body, clamps to the+ conversation pane, repositions on scroll, resize, and pane geometry, closes+ on pointer leave after a short grace delay (unless the trigger still has+ keyboard focus), Escape, or an outside pointer press, and disables its+ transition under reduced motion. The compactCodex-style context inspector lives in the composer right toolbar,immediately left of the model × reasoning chip, and always mirrors thenewest assistant turn that reported usage (D347). Occupancy, remaining@@ -1972,8 +1989,9 @@ Single message render — either user (plaintext) or assistant (markdown streamiassistant message (the last model request), using`input + output + cacheRead + cacheWrite` (D355; `output` already carries thereasoning tokens, so `reasoningTokens` is never added again). They are not- the sum of every model call in the visual tool-loop. It is hidden until that- usage exists. The trigger keeps a small capacity ring beside the+ the sum of every model call in the visual tool-loop, and this last-request+ occupancy stays deliberately distinct from the capsule's turn aggregate. It+ is hidden until that usage exists. The trigger keeps a small capacity ring beside thepercentage and omits the redundant `Context` label; the leading figure(ring arc, percentage, token label, popover heading, tooltip, and`aria-label`) follows `settings.contextUsageDisplay` — `"remaining"`diff --git a/docs/spec/04-ux/10-workbuddy-benchmark-ux.md b/docs/spec/04-ux/10-workbuddy-benchmark-ux.mdindex 8d57eb50c..89bcf8aba 100644--- a/docs/spec/04-ux/10-workbuddy-benchmark-ux.md+++ b/docs/spec/04-ux/10-workbuddy-benchmark-ux.md@@ -99,9 +99,15 @@ input/output/cached breakdown). Data already exists in the runtime usageevents.**Adopted in D103 (tokens-only first cut), placement amended by D347**:-completed assistant turns show a model badge under the answer. The compact-Codex-style context inspector lives in the composer toolbar next to the model-picker and always mirrors the newest assistant turn that reported usage. The+completed assistant turns show a model badge under the answer, followed by the+turn usage capsule. The capsule keeps the visible turn's average generation+speed and compact total tokens beside the model badge, and hovering or+keyboard-focusing it opens the cache-read/input/output breakdown with exact+counts and one exact total. Its total sums every assistant message in the+visual turn, so it is a turn aggregate rather than a single request. The+compact Codex-style context inspector lives in the composer toolbar next to+the model picker and always mirrors the newest assistant turn that reported+usage, remaining the last-request occupancy authority. Thetrigger shows remaining context percentage in a small ring; clicking ittoggles a light summary panel with remaining/window counts and two unboxedturn/speed values. Provider input/output/cache/reasoning usage staysdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 433e758e5..70ffe6553 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -5236,12 +5236,18 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.#### E2E-060d: Assistant meta chips, compact context summary, and retry action-- **Preconditions**: A completed assistant message includes modelId and token- usage; another completed assistant message has content but no usage. The- selected model has a published 1m-class context window, while its provider- binding still contains the legacy 128k generic seed.+- **Preconditions**: A completed visual turn includes modelId and token usage+ across more than one assistant message; another completed assistant message+ has content but no usage. The selected model has a published 1m-class context+ window, while its provider binding still contains the legacy 128k generic+ seed.- **Steps**: 1) Open the session. 2) Confirm the completed turn shows a model- badge and no context inspector under the answer. 3) Hover the composer+ badge and no context inspector under the answer. Confirm the turn usage+ capsule follows the badge with its average speed and compact total, then+ hover or keyboard-focus it and inspect the cache-read/input/output exact+ counts, the turn total, and cache write only when non-zero. Move the pointer+ into the popover and confirm it stays open, then dismiss it with Escape and+ with an outside pointer press. 3) Hover the composertoolbar inspector trigger, confirm the panel stays closed, then click it.4) Inspect the remaining-token-plus-percentage heading, used/window counts,unboxed turn/speed values, total session duration, and three timing rows for@@ -5263,7 +5269,15 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.without usage still offers Retry on completed turns and omits the composerinspector.- **Expected**: Model badge appears under completed assistant answers when a- model id exists. The compact Context inspector appears in the composer+ model id exists, followed immediately by the turn usage capsule when that+ turn has usage. The capsule's speed is summed output tokens over summed+ response duration, and its total sums input/output/cache read/cache write+ across the visual turn, counting reasoning inside output and excluding+ subagent spend. Its popover stays open while the pointer is over it, closes+ on pointer leave after a grace delay unless the trigger retains keyboard+ focus, on Escape, or on an outside press; it portals to the body, clamps to+ the conversation pane, and is absent on streaming turns.+ The compact Context inspector appears in the composerright toolbar, left of the model picker, once any usage exists, and alwaysmirrors the newest usage-bearing assistant turn. The trigger shows the ringplus remaining-capacity percentage (no Context label) and low-space@@ -5282,7 +5296,8 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.explanatory estimate paragraph is rendered. Occupancy, turn total, andprovider cache/input/output/reasoning/hit-rate are the last usage-bearingassistant message, not the summed tool-loop, so cache read stays on the- same scale as the context window. The cache hit rate is omitted+ same scale as the context window; this last-request value remains distinct+ from the capsule's visual-turn aggregate. The cache hit rate is omittedwhen cache-read metadata is absent rather than inferred. A published 1m-classlimit (for example `gpt-5.6-luna` at 1,050,000 tokens) is shown instead of128k, the same effective window is used by the agent runtime, and a non-defaultdiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 1f66f179e..a402ef4d9 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1319,14 +1319,26 @@ row 而不是在转录本中添加树镶边。按顺序复制所有内容片段;分叉并重新生成目标最后一个内容丰富的片段,因此现有的持久转录语义保持不变(D157)。-- 助理元:答案下方只保留可选模型徽章。紧凑的 Codex 风格上下文检查器- 放在输入框右侧工具栏、模型 × 推理芯片左侧,始终对应当前最新一条已- 报告用量的助手回合(D347)。占用、剩余容量、已用/窗口计数、本轮合计- 以及模型 input/output/cache/reasoning/命中率取该回合最新一条已报告用量- 的助手消息(最后一次模型请求),占用为+- 助理元:答案下方可选模型徽章;这个已完成的视觉回合有用量时,紧跟其后+ 显示回合用量胶囊。胶囊始终显示该回合的平均生成速度和紧凑令牌总数;+ 悬停或用键盘聚焦会打开固定定位浮层,展示紧凑总数、缓存读取/输入/输出+ 构成条、精确的缓存读取/输入/输出数值(仅在有缓存写入时显示该项)以及+ 精确合计。合计为视觉回合内各助手消息的+ `input + output + cacheRead + cacheWrite` 之和;`output` 已包含推理令牌,+ 因此不再重复加上 `reasoningTokens`,也不包含子代理开销(D103)。速度为+ 总输出令牌除以总响应时长。流式回合不渲染元信息行,因此也不显示胶囊。胶囊的可访问名称+ 会说明速度、总量以及激活后可查看明细。浮层传送到 document body、限制在+ 会话面板内,并在滚动、窗口调整或面板几何变化时重新定位;指针离开后经过+ 短暂宽限关闭(触发器仍保持键盘焦点时除外),也可用 Escape 或外部指针按下+ 关闭;减少动态效果时禁用过渡。+ 紧凑的 Codex 风格上下文检查器放在输入框右侧工具栏、模型 × 推理芯片左侧,+ 始终对应当前最新一条已报告用量的助手回合(D347)。占用、剩余容量、已用/+ 窗口计数、本轮合计以及模型 input/output/cache/reasoning/命中率取该回合+ 最新一条已报告用量的助手消息(最后一次模型请求),占用为`input + output + cacheRead + cacheWrite`(D355;`output` 已包含推理令牌,- 因此不再重复加上 `reasoningTokens`);它们不是- 视觉工具循环里每一次请求的加总。没有用量时不显示。触发器保留容量+ 因此不再重复加上 `reasoningTokens`);它们不是视觉工具循环里每一次请求+ 的加总,最后一次请求的占用与胶囊的回合合计刻意保持不同。没有用量时不显示。+ 触发器保留容量圆环和百分比,去掉重复的 `Context` 文字;引导数值(圆弧、百分比、令牌标签、弹层标题、tooltip 与 `aria-label`)跟随`settings.contextUsageDisplay`——`"remaining"`(默认)或 `"used"`——diff --git a/docs/zh-CN/spec/04-ux/10-workbuddy-benchmark-ux.md b/docs/zh-CN/spec/04-ux/10-workbuddy-benchmark-ux.mdindex d5bbccf49..ea56e58f9 100644--- a/docs/zh-CN/spec/04-ux/10-workbuddy-benchmark-ux.md+++ b/docs/zh-CN/spec/04-ux/10-workbuddy-benchmark-ux.md@@ -101,8 +101,12 @@ WorkBuddy 将权限姿势放在发送按钮旁边。 PI-Desktopinput/output/cached 细分)。运行时使用中数据已存在事件。-**在 D103 中采用(仅限代币第一刀)**:完成的辅助回合显示-模型徽章和答案下的紧凑 Codex 风格上下文检查器。检查器显示小环中+**在 D103 中采用(仅限代币第一刀)**:完成的辅助回合在答案下方显示模型+徽章,紧跟回合用量胶囊。胶囊常驻显示该视觉回合的平均生成速度与紧凑总量;+悬停或用键盘聚焦会展开缓存读取/输入/输出构成、精确数值及一个精确合计。+合计为视觉回合内所有助手消息的加总,因此是回合聚合而非单次请求。紧凑的+Codex 风格上下文检查器位于输入框工具栏、模型选择器旁,始终对应最新一条+已报告用量的助手回合,仍是最后一次请求占用的权威。检查器显示小环中的剩余上下文百分比;点击触发器后打开轻量摘要面板,展示剩余/窗口计数以及无卡片的本轮/速度数值。提供商的 input/output/cache/reasoning用量压缩为一条精确摘要;工具用量压缩为一条聚合摘要,展示工具种类、diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex d6b118154..d4d92ddf2 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -2750,11 +2750,14 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编#### E2E-060d:助理元芯片、紧凑上下文摘要和重试操作-- **前提**:完整的辅助消息包含 modelId 和 token 用法;另一条已完成的- 助理消息有内容但没有用量。所选模型发布了 1m 级上下文窗口,但 provider- binding 仍含有历史 128k 通用种子。+- **前提**:一个已完成的视觉回合在多条助手消息中包含 modelId 和 token+ 用量;另一条已完成的助理消息有内容但没有用量。所选模型发布了 1m 级+ 上下文窗口,但 provider binding 仍含有历史 128k 通用种子。- **步骤**:1) 打开会话。2) 确认已完成回合答案下方只有模型徽章、没有- 上下文检查器。3) 将鼠标悬停在输入框工具栏的检查器触发器上,确认面板+ 上下文检查器。确认回合用量胶囊紧跟模型徽章,显示平均速度和紧凑总量;+ 悬停或用键盘聚焦胶囊,检查缓存读取/输入/输出精确数值、回合合计,以及+ 仅在非零时出现的缓存写入。将鼠标移入浮层确认其保持打开,然后用 Escape+ 和外部指针按下关闭。3) 将鼠标悬停在输入框工具栏的检查器触发器上,确认面板不会打开,然后点击它。4) 检查剩余令牌 + 百分比标题、已用/窗口计数、无卡片的本轮/速度数值、内联模型用量摘要和聚合工具摘要,确认标题下没有双线、弹层内部没有分隔线。5) 面板打开时滚动记录、调整窗口大小。@@ -2763,15 +2766,21 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编会话面板内:完全可见、不进入面板列,且在较窄面板上收窄而不是被裁剪。8) 空闲时点击该回合的重试。9) 确认没有用量的会话仍提供重试但不显示输入框检查器。-- **预期**:有模型 id 时答案下方显示模型徽章。有用量后,紧凑上下文- 检查器出现在输入框右侧工具栏、模型选择器左侧,并始终对应最新一条- 已报告用量的助手回合。触发器显示圆环和剩余容量百分比(无 Context+- **预期**:有模型 id 时答案下方显示模型徽章;该回合有用量时,回合用量+ 胶囊紧跟其后。胶囊速度等于总输出令牌除以总响应时长,合计为视觉回合内+ 输入/输出/缓存读取/缓存写入之和,推理令牌计入输出,子代理开销不计入。+ 浮层在指针停留其上时保持打开,并在指针离开的宽限后(触发器仍保持键盘焦点+ 时除外)、Escape 或外部按下时关闭;浮层传送到 body、限制在会话面板内,+ 流式回合不显示胶囊。有用量后,+ 紧凑上下文检查器出现在输入框右侧工具栏、模型选择器左侧,并始终对应最新+ 一条已报告用量的助手回合。触发器显示圆环和剩余容量百分比(无 Context文字)以及低容量 warning/error 状态,点击或键盘激活打开同一摘要,而单纯悬停不会打开或关闭。摘要保留精确的提供商数值,并用 `~` 标识估算的工具合计;默认不渲染逐工具列表、来源徽章、进度条、解释性估算段落或内部分隔线。占用、本轮合计和模型缓存/输入/输出/推理/命中率取最后一条已报告用量的助手消息,而不是工具循环加总,因此缓存读取与- 上下文窗口同量级。没有缓存读取元数据时省略缓存命中率而不是推算。+ 上下文窗口同量级;这个最后一次请求的值与胶囊的视觉回合合计刻意不同。+ 没有缓存读取元数据时省略缓存命中率而不是推算。发布的 1m 级窗口(例如 `gpt-5.6-luna` 的 1,050,000 tokens)显示为实际窗口而不是 128k,且与 agent runtime 使用同一个 effective window;非默认 Advanced 覆盖仍然生效。生成速度只代表已完成回合。重试重新diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 9345e590c..609349edc 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -470,6 +470,8 @@ export const de = {"usageContextAriaRemaining": "verbleibend","usageContextAriaUsed": "verwendet","usageTurnTotal": "Diese Runde",+ "usageTurnAria": "Dieser Turn: {{speed}}, {{count}} Tokens. Aufschlüsselung anzeigen.",+ "usageTotal": "Gesamt","usageThroughputLabel": "Generierungsgeschwindigkeit","usageThroughput": "{{count}} Tokens/s","usageThroughputEstimated": "≈ {{count}} Tokens/s",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 405e9ea7c..a830b8c11 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -485,6 +485,8 @@ export const en = {usageContextAriaRemaining: "remaining",usageContextAriaUsed: "used",usageTurnTotal: "This turn",+ usageTurnAria: "This turn: {{speed}}, {{count}} tokens. Show breakdown.",+ usageTotal: "Total",usageThroughputLabel: "Generation speed",usageThroughput: "{{count}} tokens/s",usageThroughputEstimated: "≈ {{count}} tokens/s",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex a035c89eb..9b0d82910 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -470,6 +470,8 @@ export const es = {"usageContextAriaRemaining": "restante","usageContextAriaUsed": "usado","usageTurnTotal": "Este turno",+ "usageTurnAria": "Este turno: {{speed}}, {{count}} tokens. Mostrar desglose.",+ "usageTotal": "Total","usageThroughputLabel": "Velocidad de generación","usageThroughput": "{{count}} tokens/s","usageThroughputEstimated": "≈ {{count}} tokens/s",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 8e868e16d..1d0d44dc3 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -470,6 +470,8 @@ export const fr = {"usageContextAriaRemaining": "restant","usageContextAriaUsed": "utilisé","usageTurnTotal": "Ce tour",+ "usageTurnAria": "Ce tour : {{speed}}, {{count}} tokens. Afficher le détail.",+ "usageTotal": "Total","usageThroughputLabel": "Vitesse de génération","usageThroughput": "{{count}} jetons/s","usageThroughputEstimated": "≈ {{count}} jetons/s",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 29135c06c..cc23bedb9 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -482,6 +482,8 @@ export const ko = {usageContextAriaRemaining: "남음",usageContextAriaUsed: "사용됨",usageTurnTotal: "이번 턴",+ usageTurnAria: "이번 턴: {{speed}}, {{count}} tokens. 세부 정보 보기.",+ usageTotal: "합계",usageThroughputLabel: "생성 속도",usageThroughput: "{{count}} tokens/s",usageThroughputEstimated: "≈ {{count}} tokens/s",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 9035d3609..bed1f138b 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -472,6 +472,8 @@ export const ptBR = {usageContextAriaRemaining: "restante",usageContextAriaUsed: "usado",usageTurnTotal: "Esta rodada",+ usageTurnAria: "Este turno: {{speed}}, {{count}} tokens. Mostrar detalhes.",+ usageTotal: "Total",usageThroughputLabel: "Velocidade de geração",usageThroughput: "{{count}} tokens/s",usageThroughputEstimated: "≈ {{count}} tokens/s",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex d64f99d0a..ac9169dc6 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -482,6 +482,8 @@ export const tr = {usageContextAriaRemaining: "kaldı",usageContextAriaUsed: "kullanıldı",usageTurnTotal: "Bu tur",+ usageTurnAria: "Bu tur: {{speed}}, {{count}} token. Ayrıntıları göster.",+ usageTotal: "Toplam",usageThroughputLabel: "Üretim hızı",usageThroughput: "{{count}} token/sn",usageThroughputEstimated: "≈ {{count}} token/sn",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex f2552173e..9f5a49a1d 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -475,6 +475,8 @@ export const zhCN = {usageContextAriaRemaining: "剩余",usageContextAriaUsed: "已用",usageTurnTotal: "本轮合计",+ usageTurnAria: "本轮:平均 {{speed}},共 {{count}} tokens,查看明细",+ usageTotal: "合计",usageThroughputLabel: "生成速度",usageThroughput: "{{count}} tokens/s",usageThroughputEstimated: "约 {{count}} tokens/s",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 6c5f1f13a..3b25369fb 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -475,6 +475,8 @@ export const zhTW = {usageContextAriaRemaining: "剩餘",usageContextAriaUsed: "已用",usageTurnTotal: "本輪合計",+ usageTurnAria: "本輪:平均 {{speed}},共 {{count}} tokens,查看明細",+ usageTotal: "合計",usageThroughputLabel: "生成速度",usageThroughput: "{{count}} tokens/s",usageThroughputEstimated: "約 {{count}} tokens/s",