Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(models): make the usage chart tooltip instant and follow the pointer (#2196)
Call White3cb466190e0c
diff --git a/ui/e2e/model-catalog/usage.spec.ts b/ui/e2e/model-catalog/usage.spec.tsindex 78b31cabf..4ea819786 100644--- a/ui/e2e/model-catalog/usage.spec.ts+++ b/ui/e2e/model-catalog/usage.spec.ts@@ -92,6 +92,94 @@ test.describe('hermetic UsageTab', () => {await expect(nextWindow).toBeFocused();});+ test('the detail follows a pointer that never stops and changes bucket at once', async ({ page }, testInfo) => {+ test.skip(testInfo.project.name === 'mobile', 'Pointer hover is a desktop contract');+ await openUsage(page);+ const svg = page.locator('.model-hub-usage-svg');+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });+ const heading = dialog.locator('.model-hub-usage-tooltip-range');+ const hitAreas = page.locator('.model-hub-usage-hit-area');+ const first = (await hitAreas.nth(2).boundingBox())!;+ const last = (await hitAreas.nth(20).boundingBox())!;+ await page.mouse.move(first.x + first.width / 2, first.y + first.height * 0.75);+ await expect(dialog).toBeVisible();+ // Sweep through the detail's own band, toward the side it sits on: the+ // pointer crosses the detail on every step and must not be caught by it.+ const detailBox = (await dialog.boundingBox())!;+ const midY = detailBox.y + detailBox.height / 2;+ await page.mouse.move(first.x + first.width / 2, midY);+ const seen = new Set([await heading.textContent()]);+ // Record every heading the detail shows while the pointer sweeps without+ // pausing: under a settle-delay the heading would hold still until the+ // pointer stops, so it would show at most the first and last bucket.+ await heading.evaluate((node) => {+ const log: string[] = [];+ (window as unknown as { usageHeadings: string[] }).usageHeadings = log;+ new MutationObserver(() => log.push(node.textContent ?? '')).observe(node, { subtree: true, characterData: true, childList: true });+ });+ const steps = 18;+ for (let step = 1; step <= steps; step += 1) {+ await page.mouse.move(first.x + first.width / 2 + ((last.x - first.x) * step) / steps, midY);+ }+ const headings = await page.evaluate(() => (window as unknown as { usageHeadings: string[] }).usageHeadings);+ for (const text of headings) seen.add(text);+ expect(seen.size).toBeGreaterThanOrEqual(10);+ await expect(svg).toBeVisible();++ // Along the detail's header band the pointer can still walk onto the pin+ // control: the header holds the bucket still once the pointer reaches it.+ await hitAreas.nth(4).hover();+ await expect.poll(async () => dialog.evaluate((node) => node.getAnimations().length)).toBe(0);+ const held = await heading.textContent();+ const head = (await dialog.locator('.model-hub-usage-tooltip-head').boundingBox())!;+ const bucketBox = (await hitAreas.nth(4).boundingBox())!;+ const startX = bucketBox.x + bucketBox.width / 2;+ const pin = (await dialog.getByRole('button', { name: 'Pin this bucket' }).boundingBox())!;+ await page.mouse.move(startX, head.y + head.height / 2);+ await page.mouse.move(head.x + 2, head.y + head.height / 2);+ await page.mouse.move(pin.x + pin.width / 2, pin.y + pin.height / 2, { steps: 12 });+ await page.mouse.down();+ await page.mouse.up();+ await expect(dialog).toHaveAttribute('data-pinned', 'true');+ await expect(heading).toHaveText(held ?? '');+ });++ test('the detail sits beside the crosshair, right of it by default and left of it at the right edge', async ({ page }, testInfo) => {+ test.skip(testInfo.project.name === 'mobile', 'The narrow chart docks the detail full-width');+ await openUsage(page);+ const hitAreas = page.locator('.model-hub-usage-hit-area');+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });+ const wrap = page.locator('.model-hub-usage-chart-wrap');+ const count = await hitAreas.count();+ const placement = async (index: number) => {+ await hitAreas.nth(index).hover();+ await expect(dialog).toBeVisible();+ // Wait out the short follow transition before measuring.+ await expect.poll(async () => dialog.evaluate((node) => node.getAnimations().length)).toBe(0);+ const box = (await dialog.boundingBox())!;+ const chart = (await wrap.boundingBox())!;+ const crosshair = (await page.locator('.model-hub-usage-crosshair').boundingBox())!;+ expect(box.x).toBeGreaterThanOrEqual(chart.x - 0.5);+ expect(box.x + box.width).toBeLessThanOrEqual(chart.x + chart.width + 0.5);+ return { box, crosshairX: crosshair.x + crosshair.width / 2 };+ };++ const leftmost = await placement(0);+ expect(leftmost.box.x).toBeGreaterThan(leftmost.crosshairX);+ await expect(dialog).toHaveAttribute('data-side', 'right');++ const rightmost = await placement(count - 1);+ expect(rightmost.box.x + rightmost.box.width).toBeLessThan(rightmost.crosshairX);+ await expect(dialog).toHaveAttribute('data-side', 'left');++ // A pinned detail stays where it was pinned while the pointer moves on.+ await dialog.getByRole('button', { name: 'Pin this bucket' }).click();+ const pinnedAt = (await dialog.boundingBox())!;+ await hitAreas.nth(3).hover();+ await expect(dialog).toHaveAttribute('data-pinned', 'true');+ expect((await dialog.boundingBox())!.x).toBeCloseTo(pinnedAt.x, 0);+ });+test('window switching renders coherent line and bar reports', async ({ page }) => {await openUsage(page);await expect(page.locator('.model-hub-usage-svg')).toBeVisible();@@ -126,6 +214,14 @@ test.describe('hermetic UsageTab', () => {const fitsViewport = await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth);expect(fitsViewport).toBe(true);expect(await page.locator('.model-hub-usage-svg').textContent()).not.toContain('2026');+ // Touch keeps the full-width detail docked across the top of the chart.+ await page.locator('.model-hub-usage-hit-area').nth(12).click();+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });+ await expect(dialog).toHaveAttribute('data-side', 'docked');+ const docked = (await dialog.boundingBox())!;+ const chart = (await page.locator('.model-hub-usage-chart-wrap').boundingBox())!;+ expect(docked.width).toBeGreaterThan(chart.width - 12);+ await page.mouse.click(4, 4);const scrollOwner = page.locator('main');const scrollMetrics = await scrollOwner.evaluate((node) => ({clientHeight: node.clientHeight,diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsxindex 3577426b8..9cb1f89d3 100644--- a/ui/src/components/settings/models/UsageTab.tsx+++ b/ui/src/components/settings/models/UsageTab.tsx@@ -30,6 +30,7 @@ import {filteredRows,formatBucketAxisLabel,formatBucketLabel,+ formatBucketHeading,formatBucketRange,identityDisplayLabel,modelLabel,@@ -235,6 +236,9 @@ function MultiFilter({);}+/** A legend item's border and padding before its swatch. */+const LEGEND_SWATCH_OFFSET = 7;+const ChartLegend: React.FC<{series: UsageSeries[];hidden: readonly string[];@@ -243,8 +247,10 @@ const ChartLegend: React.FC<{count: (value: number) => string;blank: string;ariaLabel: string;-}> = ({ series, hidden, onToggle, labels, count, blank, ariaLabel }) => (- <div className="model-hub-usage-legend" aria-label={ariaLabel}>+ /** The plot's left edge, which the first swatch lines up with. */+ inset: number;+}> = ({ series, hidden, onToggle, labels, count, blank, ariaLabel, inset }) => (+ <div className="model-hub-usage-legend" aria-label={ariaLabel} style={{ marginLeft: Math.max(0, inset - LEGEND_SWATCH_OFFSET) }}>{series.map((item) => {const values = item.values.filter((value): value is number => value !== null);const total = values.reduce((sum, value) => sum + value, 0);@@ -267,6 +273,32 @@ const ChartLegend: React.FC<{</div>);+const TOOLTIP_WIDTH = 264;+const TOOLTIP_INSET = 8;+const TOOLTIP_GAP = 6;+/** Below this chart width the detail docks full-width across the top, for touch. */+const TOOLTIP_DOCK_BELOW = 560;+const HOUR_TICK_STEPS = [1, 2, 3, 4, 6, 12];+const DAY_TICK_STEPS = [1, 2, 3, 5, 7, 10, 14, 15, 30];++/**+ * The buckets that carry an x-axis label: the finest step whose labels stay a+ * readable distance apart. Hours align to the clock (every 3h lands on 00, 03,+ * 06 …); days count back from the newest, so today always has its label.+ */+function axisTickIndexes(report: UsageReport, bucketSpan: number, narrow: boolean): number[] {+ const count = report.buckets.length;+ if (count === 0) return [];+ const minGap = narrow ? 52 : 68;+ const hourly = report.granularity === 'hour';+ const steps = hourly ? HOUR_TICK_STEPS : DAY_TICK_STEPS;+ const step = steps.find((candidate) => candidate * bucketSpan >= minGap) ?? steps[steps.length - 1];+ const hourOf = (index: number) => Number(report.buckets[index].start_at.slice(11, 13));+ return report.buckets.map((_, index) => index).filter((index) => (hourly+ ? Number.isFinite(hourOf(index)) && hourOf(index) % step === 0+ : (count - 1 - index) % step === 0));+}+function UsageChart({report,filter,@@ -294,6 +326,7 @@ function UsageChart({const [width, setWidth] = React.useState(920);const [keyboardActivation, setKeyboardActivation] = React.useState(0);const hostRef = React.useRef<HTMLDivElement>(null);+ const svgRef = React.useRef<SVGSVGElement>(null);const pinButtonRef = React.useRef<HTMLButtonElement>(null);const bucketButtonRefs = React.useRef(new Map<string, HTMLButtonElement>());const invokingBucketKeyRef = React.useRef<string | null>(null);@@ -301,7 +334,6 @@ function UsageChart({const focusPinAfterOpenRef = React.useRef(false);const previousUsageInputRef = React.useRef({ report, scopeKey, group, metric });const hoverClearTimer = React.useRef<number | null>(null);- const pendingHoverTimer = React.useRef<number | null>(null);const [escapeDismissed, setEscapeDismissed] = React.useState(false);const pinnedIndex = pinnedKey === null ? -1 : report.buckets.findIndex((bucket) => bucket.key === pinnedKey);const requestedIndex = dismissed || escapeDismissed@@ -331,7 +363,7 @@ function UsageChart({? metricLabel('cost', t): item.label,])), [metric, series, t]);- const visibleSeries = series.filter((item) => !hidden.includes(item.key));+ const visibleSeries = React.useMemo(() => series.filter((item) => !hidden.includes(item.key)), [hidden, series]);const narrow = width < 560;const height = narrow ? 236 : 292;const left = narrow ? 40 : 54;@@ -340,7 +372,10 @@ function UsageChart({const bottom = 38;const plotWidth = Math.max(1, width - left - right);const plotHeight = Math.max(1, height - top - bottom);- const lineHitWidth = Math.min(28, Math.max(8, plotWidth / Math.max(1, report.buckets.length - 1) * 0.82));+ const bucketCount = report.buckets.length;+ // One bucket's share of the plot: a bar's column, or the span a line point+ // owns between its neighbours' midpoints.+ const bucketSpan = bars ? plotWidth / Math.max(1, bucketCount) : plotWidth / Math.max(1, bucketCount - 1);const values = report.buckets.map((_, index) => bars? visibleSeries.reduce((sum, item) => sum + (item.values[index] ?? 0), 0): Math.max(0, ...visibleSeries.map((item) => item.values[index] ?? 0)));@@ -348,8 +383,8 @@ function UsageChart({const scale = 10 ** Math.floor(Math.log10(rawMax));const max = Math.ceil(rawMax / scale / 0.5) * scale * 0.5;const x = (index: number) => left + (bars- ? (index + 0.5) / report.buckets.length- : index / Math.max(1, report.buckets.length - 1)) * plotWidth;+ ? (index + 0.5) / bucketCount+ : index / Math.max(1, bucketCount - 1)) * plotWidth;const y = (value: number) => top + plotHeight * (1 - value / max);const bucket = activeIndex === null || activeIndex < 0 ? null : report.buckets[activeIndex];const bucketRows = bucket === null ? [] : filterBucketRows(bucket, filter);@@ -361,16 +396,149 @@ function UsageChart({&& report.window_key === '24h'&& activeIndex === report.buckets.length - 1&& Date.parse(bucket.end_at) - Date.parse(bucket.start_at) < 60 * 60 * 1000;- const tickIndexes = report.buckets.length <= 7- ? report.buckets.map((_, index) => index)- : [...new Set([0, Math.floor((report.buckets.length - 1) / 2), report.buckets.length - 1])];+ const tickIndexes = axisTickIndexes(report, bucketSpan, narrow);+ const heading = bucket === null ? null : formatBucketHeading(bucket, i18n.language);+ const gradientId = React.useId().replace(/[^a-zA-Z0-9_-]/g, '');- const cancelPendingHover = () => {- if (pendingHoverTimer.current !== null) {- window.clearTimeout(pendingHoverTimer.current);- pendingHoverTimer.current = null;+ // Everything that does not depend on the hovered bucket. A hover change+ // re-renders only the highlight, crosshair, active dots, and tooltip.+ const seriesLayer = React.useMemo(() => {+ const xAt = (index: number) => left + (bars+ ? (index + 0.5) / bucketCount+ : index / Math.max(1, bucketCount - 1)) * plotWidth;+ const yAt = (value: number) => top + plotHeight * (1 - value / max);+ const colorOf = (item: UsageSeries) => SERIES_COLORS[item.colorIndex % SERIES_COLORS.length];+ const columnWidth = plotWidth / Math.max(1, bucketCount);+ if (bars) {+ return report.buckets.map((currentBucket, index) => {+ let offset = 0;+ return (+ <g key={currentBucket.key}>+ {visibleSeries.map((item) => {+ const value = item.values[index];+ const start = offset;+ offset += value ?? 0;+ return (+ <rect+ key={item.key}+ x={xAt(index) - columnWidth * 0.32}+ y={yAt(offset)}+ width={columnWidth * 0.64}+ height={value === null ? 4 : Math.max(0, yAt(start) - yAt(offset))}+ fill={value === null ? 'url(#usage-unknown-pattern)' : colorOf(item)}+ opacity={0.88}+ rx="2"+ />+ );+ })}+ </g>+ );+ });}- };+ const baseline = yAt(0);+ return visibleSeries.map((item, seriesIndex) => {+ // Contiguous known runs; an unknown bucket breaks the line.+ const runs: number[][] = [];+ item.values.forEach((value, index) => {+ if (value === null) return;+ const previous = item.values[index - 1];+ if (previous === null || previous === undefined) runs.push([index]);+ else runs[runs.length - 1].push(index);+ });+ const line = runs.map((run) => run+ .map((index, position) => `${position === 0 ? 'M' : 'L'}${xAt(index)},${yAt(item.values[index] as number)}`)+ .join(' ')).join(' ');+ const area = runs.filter((run) => run.length > 1).map((run) => [+ ...run.map((index, position) => `${position === 0 ? 'M' : 'L'}${xAt(index)},${yAt(item.values[index] as number)}`),+ `L${xAt(run[run.length - 1])},${baseline}`,+ `L${xAt(run[0])},${baseline}`,+ 'Z',+ ].join(' ')).join(' ');+ const color = colorOf(item);+ return (+ <g key={item.key}>+ <defs>+ <linearGradient id={`${gradientId}-area-${seriesIndex}`} x1="0" x2="0" y1="0" y2="1">+ <stop offset="0%" style={{ stopColor: color, stopOpacity: 0.16 }} />+ <stop offset="100%" style={{ stopColor: color, stopOpacity: 0 }} />+ </linearGradient>+ </defs>+ {area && <path d={area} fill={`url(#${gradientId}-area-${seriesIndex})`} stroke="none" className="model-hub-usage-area" />}+ <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ {/* A point with no known neighbour draws no segment, so it needs a dot to be seen at all. */}+ {runs.filter((run) => run.length === 1).map(([index]) => (+ <circle key={`solo-${index}`} cx={xAt(index)} cy={yAt(item.values[index] as number)} r="2.5" fill={color} stroke="var(--background)" strokeWidth="1.5" />+ ))}+ {item.values.map((value, index) => (value === null+ ? <circle key={`unknown-${index}`} cx={xAt(index)} cy={baseline} r="3" className="model-hub-usage-unknown-point" />+ : null))}+ </g>+ );+ });+ }, [bars, bucketCount, gradientId, left, max, plotHeight, plotWidth, report.buckets, visibleSeries]);++ const gridLayer = React.useMemo(() => [0, 1, 2, 3, 4].map((step) => {+ const value = max * step / 4;+ const lineY = top + plotHeight * (1 - step / 4);+ return (+ <g key={step}>+ <line x1={left} x2={width - right} y1={lineY} y2={lineY} className="model-hub-usage-grid" />+ <text x={left - 10} y={lineY + 4} textAnchor="end" className="model-hub-usage-tick model-hub-usage-tick--y">{format(value)}</text>+ </g>+ );+ }), [format, left, max, plotHeight, width]);++ // The hovered bucket's own stack, redrawn over the dimmed columns at full strength.+ const activeColumn = bars && activeIndex !== null+ ? (() => {+ let offset = 0;+ const columnWidth = plotWidth / Math.max(1, bucketCount);+ return (+ <g className="model-hub-usage-active-column">+ {visibleSeries.map((item) => {+ const value = item.values[activeIndex];+ const start = offset;+ offset += value ?? 0;+ return (+ <rect+ key={item.key}+ x={x(activeIndex) - columnWidth * 0.32}+ y={y(offset)}+ width={columnWidth * 0.64}+ height={value === null ? 4 : Math.max(0, y(start) - y(offset))}+ fill={value === null ? 'url(#usage-unknown-pattern)' : SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]}+ opacity={0.88}+ rx="2"+ />+ );+ })}+ </g>+ );+ })()+ : null;++ // Beside the crosshair, right by default, flipped left where it would pass+ // the chart's right edge, and kept inside the chart either way. A narrow+ // chart docks it full-width across the top instead, for touch.+ const docked = width < TOOLTIP_DOCK_BELOW;+ const tooltipWidth = Math.min(TOOLTIP_WIDTH, width - 2 * TOOLTIP_INSET);+ // The detail starts past the active bucket's own edge: a pointer moving+ // across the plot enters the next bucket (and the detail moves on) before it+ // could land on the detail, while a deliberate jump onto it still holds it.+ const tooltipGap = bucketSpan / 2 + TOOLTIP_GAP;+ let tooltipLeft = 0;+ let tooltipSide: 'left' | 'right' = 'right';+ if (activeIndex !== null && !docked) {+ const anchor = x(activeIndex);+ const roomRight = width - TOOLTIP_INSET - (anchor + tooltipGap);+ const roomLeft = anchor - tooltipGap - TOOLTIP_INSET;+ // Flip only when the right side is short and the left side has more room;+ // the clamp below covers a chart too narrow for either.+ if (roomRight < tooltipWidth && roomLeft > roomRight) tooltipSide = 'left';+ tooltipLeft = tooltipSide === 'right' ? anchor + tooltipGap : anchor - tooltipGap - tooltipWidth;+ tooltipLeft = Math.max(TOOLTIP_INSET, Math.min(width - TOOLTIP_INSET - tooltipWidth, tooltipLeft));+ }+const cancelHoverClear = () => {if (hoverClearTimer.current !== null) {window.clearTimeout(hoverClearTimer.current);@@ -378,10 +546,6 @@ function UsageChart({}};const handleEscape = React.useCallback(() => {- if (pendingHoverTimer.current !== null) {- window.clearTimeout(pendingHoverTimer.current);- pendingHoverTimer.current = null;- }if (hoverClearTimer.current !== null) {window.clearTimeout(hoverClearTimer.current);hoverClearTimer.current = null;@@ -467,12 +631,10 @@ function UsageChart({React.useEffect(() => () => {if (hoverClearTimer.current !== null) window.clearTimeout(hoverClearTimer.current);- if (pendingHoverTimer.current !== null) window.clearTimeout(pendingHoverTimer.current);}, []);const scheduleHoverClear = () => {if (pinnedKey !== null || inspected !== null) return;- cancelPendingHover();cancelHoverClear();hoverClearTimer.current = window.setTimeout(() => {hoverClearTimer.current = null;@@ -480,22 +642,15 @@ function UsageChart({}, 100);};+ // Entering a bucket shows it at once; only leaving the plot waits (see+ // scheduleHoverClear), so the pointer can cross into the detail.const setHover = (index: number, reopenAfterEscape = false) => {if ((escapeDismissed && !reopenAfterEscape) || pinnedKey !== null || inspected !== null) return;- cancelPendingHover();cancelHoverClear();const next = Math.max(0, Math.min(report.buckets.length - 1, index));if (reopenAfterEscape) setEscapeDismissed(false);setDismissed(false);- if (hovered === null || hovered === next) {- setHovered(next);- return;- }- pendingHoverTimer.current = window.setTimeout(() => {- pendingHoverTimer.current = null;- if (escapeDismissed && !reopenAfterEscape) return;- setHovered(next);- }, 100);+ setHovered(next);};const openDetail = (index: number) => {if (pinnedKey !== null) return;@@ -530,13 +685,22 @@ function UsageChart({return [...current, key];});};- const svgIndexFromPointer = (event: React.PointerEvent<SVGSVGElement>) => {- const bounds = event.currentTarget.getBoundingClientRect();+ // One pointer path for the whole chart, the detail included: a sweep that+ // crosses the detail keeps moving the bucket. Only the detail's header,+ // which holds the pin control, holds the bucket still so it can be reached.+ const trackPointer = (event: React.PointerEvent<HTMLDivElement>) => {+ const svg = svgRef.current;+ if (event.pointerType === 'touch' || !svg) return;+ if ((event.target as Element).closest('.model-hub-usage-tooltip-head')) {+ cancelHoverClear();+ return;+ }+ const bounds = svg.getBoundingClientRect();const position = ((event.clientX - bounds.left) / bounds.width) * width;const index = bars? Math.floor((position - left) / plotWidth * report.buckets.length): Math.round((position - left) / plotWidth * (report.buckets.length - 1));- return Math.max(0, Math.min(report.buckets.length - 1, index));+ setHover(index, true);};const pinLabel = pinnedKey !== null? t('settings.models.usage.chart.unpin')@@ -552,96 +716,64 @@ function UsageChart({count={format}blank={t('settings.models.usage.blank') as string}ariaLabel={t('settings.models.usage.chart.legend') as string}+ inset={left}/>- <div className="model-hub-usage-chart-wrap" ref={hostRef}>+ <div+ className="model-hub-usage-chart-wrap"+ ref={hostRef}+ onPointerMove={trackPointer}+ onPointerLeave={scheduleHoverClear}+ ><svg+ ref={svgRef}className="model-hub-usage-svg"viewBox={`0 0 ${width} ${height}`}aria-hidden="true"- onPointerMove={(event) => {- if (event.pointerType !== 'touch') setHover(svgIndexFromPointer(event), true);- }}- onPointerLeave={scheduleHoverClear}><defs><pattern id="usage-unknown-pattern" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M-1,1 l2,-2 M0,6 L6,0 M5,7 l2,-2" stroke="var(--model-hub-usage-unknown)" strokeWidth="1" /></pattern></defs>- {[0, 1, 2, 3, 4].map((step) => (- <g key={step}>- <line x1={left} x2={width - right} y1={y(max * step / 4)} y2={y(max * step / 4)} className="model-hub-usage-grid" strokeDasharray={step === 0 ? undefined : '3 5'} />- <text x={left - 10} y={y(max * step / 4) + 4} textAnchor="end" className="model-hub-usage-tick">{format(max * step / 4)}</text>- </g>- ))}- {activeIndex !== null && activeIndex >= 0 && (+ {gridLayer}+ {activeIndex !== null && (<rect- x={x(activeIndex) - (bars ? plotWidth / report.buckets.length / 2 : 18)}+ x={x(activeIndex) - (bars ? bucketSpan / 2 : Math.min(18, bucketSpan / 2))}y={top}- width={bars ? plotWidth / report.buckets.length : 36}+ width={bars ? bucketSpan : Math.min(36, bucketSpan)}height={plotHeight}className="model-hub-usage-highlight"- rx="4"+ rx="3"/>)}- {bars- ? report.buckets.map((currentBucket, index) => {- let offset = 0;- return (- <g key={currentBucket.key}>- {visibleSeries.map((item) => {- const value = item.values[index];- const start = offset;- offset += value ?? 0;- return (- <rect- key={item.key}- x={x(index) - plotWidth / report.buckets.length * 0.32}- y={y(offset)}- width={plotWidth / report.buckets.length * 0.64}- height={value === null ? 4 : Math.max(0, y(start) - y(offset))}- fill={value === null ? 'url(#usage-unknown-pattern)' : SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]}- opacity={activeIndex !== null && activeIndex !== index ? 0.48 : 0.88}- rx="2"- />- );- })}- </g>- );- })- : visibleSeries.map((item) => {- const path = item.values.reduce<string[]>((segments, value, index) => {- if (value === null) return segments;- const previous = item.values[index - 1];- const command = previous === null || previous === undefined ? 'M' : 'L';- segments.push(`${command}${x(index)},${y(value)}`);- return segments;- }, []).join(' ');- return (- <g key={item.key}>- <path d={path} fill="none" stroke={SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />- {item.values.map((value, index) => value === null- ? <circle key={index} cx={x(index)} cy={y(0)} r="3" className="model-hub-usage-unknown-point" />- : <circle key={index} cx={x(index)} cy={y(value)} r={activeIndex === index ? 4.5 : 2.5} fill={SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]} stroke="var(--background)" strokeWidth="1.5" />)}- </g>- );- })}- {activeIndex !== null && activeIndex >= 0 && (+ <g className={cn('model-hub-usage-series', bars && activeIndex !== null && 'is-dimmed')}>{seriesLayer}</g>+ {activeColumn}+ {activeIndex !== null && (<line x1={x(activeIndex)} x2={x(activeIndex)} y1={top} y2={top + plotHeight} className="model-hub-usage-crosshair" />)}+ {!bars && activeIndex !== null && visibleSeries.map((item) => {+ const value = item.values[activeIndex];+ if (value === null || value === undefined) return null;+ return (+ <circle+ key={`active-${item.key}`}+ cx={x(activeIndex)}+ cy={y(value)}+ r="4"+ fill={SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]}+ stroke="var(--background)"+ strokeWidth="2"+ />+ );+ })}{report.buckets.map((currentBucket, index) => (<rectkey={`hit-${currentBucket.key}`}className="model-hub-usage-hit-area"- x={bars ? x(index) - plotWidth / report.buckets.length / 2 : x(index) - lineHitWidth / 2}+ x={x(index) - bucketSpan / 2}y={top}- width={bars ? plotWidth / report.buckets.length : lineHitWidth}+ width={bucketSpan}height={plotHeight}- onPointerEnter={() => {- // Removing a dismissed tooltip can expose a stationary pointer.- // Only a real move, focus, or activation should reopen it.- setHover(index);- }}onClick={() => openDetail(index)}/>))}@@ -650,7 +782,7 @@ function UsageChart({key={`tick-${report.buckets[index].key}`}x={x(index)}y={height - 12}- textAnchor={index === 0 ? 'start' : index === report.buckets.length - 1 ? 'end' : 'middle'}+ textAnchor={x(index) - left < 20 ? 'start' : width - right - x(index) < 20 ? 'end' : 'middle'}className="model-hub-usage-tick">{formatBucketAxisLabel(report.buckets[index], i18n.language)}@@ -685,15 +817,12 @@ function UsageChart({</div>{bucket && (<div- className={cn('model-hub-usage-tooltip', pinnedKey !== null && 'is-pinned')}+ className={cn('model-hub-usage-tooltip', pinnedKey !== null && 'is-pinned', docked && 'is-docked')}role="dialog"aria-label={t('settings.models.usage.chart.detail') as string}data-pinned={pinnedKey !== null ? 'true' : 'false'}- onPointerEnter={() => {- cancelPendingHover();- cancelHoverClear();- }}- onPointerLeave={scheduleHoverClear}+ data-side={docked ? 'docked' : tooltipSide}+ style={docked ? undefined : { width: tooltipWidth, transform: `translateX(${tooltipLeft}px)` }}onKeyDownCapture={(event) => {if (event.key !== 'Escape') return;event.stopPropagation();@@ -701,7 +830,11 @@ function UsageChart({}}><div className="model-hub-usage-tooltip-head">- <span>{formatBucketRange(bucket, i18n.language, true)}</span>+ <span className="model-hub-usage-tooltip-range">+ <span aria-hidden="true">{heading?.range}</span>+ {heading?.zone && <small aria-hidden="true">{heading.zone}</small>}+ <span className="sr-only">{formatBucketRange(bucket, i18n.language, true)}</span>+ </span><div className="model-hub-usage-tooltip-actions">{pinnedKey !== null && <span>{t('settings.models.usage.chart.pinned')}</span>}<buttondiff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex d1db14b22..645f53edd 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -2551,12 +2551,14 @@padding: 12px 16px 13px;}+/* UsageChart sets the left margin to the plot's axis gutter, so the first+ * swatch sits over the plot's left edge. */.model-hub-usage-legend {display: flex;min-width: 0;flex-wrap: wrap;- gap: 5px 8px;- margin-bottom: 6px;+ gap: 5px 6px;+ margin-bottom: 8px;}.model-hub-usage-legend-item {@@ -2565,18 +2567,35 @@align-items: center;gap: 5px;padding: 4px 6px;+ border: 1px solid transparent;border-radius: 6px;color: var(--model-hub-ink-73);font-size: 10.5px;+ transition: background-color .12s ease, border-color .12s ease, opacity .12s ease;}-.model-hub-usage-legend-item:hover,-.model-hub-usage-legend-item[aria-pressed="false"] {+.model-hub-usage-legend-item:hover {+ border-color: var(--border);background: var(--model-hub-wash-05);}+.model-hub-usage-legend-item:focus-visible {+ border-color: var(--model-hub-gold-4d);+ outline: none;+}+.model-hub-usage-legend-item.is-hidden {- opacity: .42;+ opacity: .5;+}++.model-hub-usage-legend-item.is-hidden > span:not(.model-hub-usage-legend-swatch),+.model-hub-usage-legend-item.is-hidden strong {+ text-decoration: line-through;+}++.model-hub-usage-legend-item.is-hidden .model-hub-usage-legend-swatch {+ background: transparent !important;+ box-shadow: inset 0 0 0 1.5px var(--model-hub-muted-b3);}.model-hub-usage-legend-swatch {@@ -2607,25 +2626,36 @@touch-action: pan-y;}+/* Every grid line, the baseline included, is the same quiet dash. */.model-hub-usage-grid {stroke: var(--border);- opacity: .8;+ stroke-dasharray: 2 5;+ opacity: .7;}.model-hub-usage-tick {fill: var(--model-hub-muted-b3);font-size: 10px;+ font-variant-numeric: tabular-nums;+}++.model-hub-usage-tick--y {+ opacity: .78;}.model-hub-usage-highlight {- fill: var(--model-hub-wash-08);+ fill: var(--model-hub-wash-05);+}++/* The non-active columns keep ~.6 of their ink (.88 × .68). */+.model-hub-usage-series.is-dimmed {+ opacity: .68;}.model-hub-usage-crosshair {stroke: var(--model-hub-gold);- stroke-dasharray: 3 4;stroke-width: 1;- opacity: .75;+ opacity: .6;}.model-hub-usage-hit-area {@@ -2646,14 +2676,18 @@stroke-width: 1.5;}+/* Placed beside the crosshair by UsageChart through left:0 + translateX, so a+ * bucket change moves it on the compositor. The transition is short enough to+ * read as following, never as lagging. */.model-hub-usage-tooltip {position: absolute;z-index: 10;- top: 10px;- right: 10px;- width: min(340px, calc(100% - 20px));+ top: 14px;+ left: 0;+ width: 264px;pointer-events: auto;- padding: 10px 11px;+ padding: 9px 10px;+ transition: transform 90ms ease-out;border: 1px solid var(--model-hub-gold-4d);border-radius: 9px;background: color-mix(in srgb, var(--surface) 96%, var(--gold) 4%);@@ -2661,6 +2695,18 @@color: var(--foreground);}+.model-hub-usage-tooltip.is-docked {+ top: 5px;+ right: 5px;+ left: auto;+ width: calc(100% - 10px);+ transition: none;+}++@media (prefers-reduced-motion: reduce) {+ .model-hub-usage-tooltip { transition: none; }+}+.model-hub-usage-tooltip.is-pinned {border-color: var(--model-hub-mint-4d);background: color-mix(in srgb, var(--surface) 96%, var(--mint) 4%);@@ -2670,10 +2716,22 @@justify-content: space-between;gap: 10px;color: var(--model-hub-ink-73);- font-size: 10.5px;+ font-size: 11px;line-height: 1.35;}+.model-hub-usage-tooltip-range {+ min-width: 0;+ color: var(--foreground);+ font-variant-numeric: tabular-nums;+}++.model-hub-usage-tooltip-range small {+ margin-left: 6px;+ color: var(--model-hub-muted-b3);+ font-size: 10px;+}+.model-hub-usage-tooltip-actions {flex: none;gap: 6px;@@ -2684,8 +2742,8 @@display: inline-flex;align-items: center;justify-content: center;- width: 25px;- height: 25px;+ width: 24px;+ height: 24px;border: 1px solid var(--border);border-radius: 6px;background: var(--model-hub-wash-08);@@ -3108,7 +3166,6 @@.model-hub-usage-group-control > div { width: 100%; }.model-hub-usage-group-control button { flex: 1; }.model-hub-usage-details-actions { width: 100%; justify-content: flex-start; }- .model-hub-usage-tooltip { top: 5px; right: 5px; width: calc(100% - 10px); }/* One account per line; the pace and reset lines stack so neither truncates. */.model-hub-quota-grid { grid-template-columns: minmax(0, 1fr); }.model-hub-quota-row-foot { flex-direction: column; gap: 4px; }diff --git a/ui/src/components/settings/models/usageProjection.test.ts b/ui/src/components/settings/models/usageProjection.test.tsindex 265bbd68e..f1715e463 100644--- a/ui/src/components/settings/models/usageProjection.test.ts+++ b/ui/src/components/settings/models/usageProjection.test.ts@@ -4,6 +4,7 @@ import type { UsageBucket, UsageBucketRow, UsageCounters, UsageReport } from './import {aggregateCounters,formatBucketAxisLabel,+ formatBucketHeading,formatBucketRange,identityLabel,pairKey,@@ -202,6 +203,23 @@ describe('usageProjection', () => {}, 'en-US', true)).toContain('UTC-05:00');});+ // The tooltip heading is compact; the full, zone-qualified range stays in+ // the accessible label (formatBucketRange above).+ it('shortens a bucket heading to one date and names the zone only where it matters', () => {+ const at = (start_at: string, end_at: string, key = start_at): UsageBucket => ({ ...bucket('00', []), key, start_at, end_at });+ const hostOffset = (value: string) => -new Date(value).getTimezoneOffset();+ const hour = at('2026-09-23T22:00:00+08:00', '2026-09-23T23:00:00+08:00');+ const expectedZone = hostOffset(hour.start_at) === 8 * 60 ? null : 'UTC+08:00';+ expect(formatBucketHeading(hour, 'zh')).toEqual({ range: '9月23日 22:00–23:00', zone: expectedZone });+ expect(formatBucketHeading(hour, 'en-US').range).toBe('Sep 23, 22:00–23:00');+ // The last hour of a day ends at the next midnight, still one date.+ expect(formatBucketHeading(at('2026-09-23T23:00:00+08:00', '2026-09-24T00:00:00+08:00'), 'zh').range).toBe('9月23日 23:00–24:00');+ // A whole day reads as its date.+ expect(formatBucketHeading(at('2026-09-23T00:00:00+08:00', '2026-09-24T00:00:00+08:00', '2026-09-23'), 'zh').range).toBe('9月23日');+ // Two ends in different offsets always name both.+ expect(formatBucketHeading(at('2026-11-01T01:00:00-04:00', '2026-11-01T01:00:00-05:00'), 'en-US').zone).toBe('UTC-04:00 – UTC-05:00');+ });+it('keeps axis labels compact while detail labels remain full', () => {const hourly = bucket('00', []);expect(formatBucketAxisLabel(hourly, 'en-US')).toBe('00:00');diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.tsindex f3d878a86..a85eda631 100644--- a/ui/src/components/settings/models/usageProjection.ts+++ b/ui/src/components/settings/models/usageProjection.ts@@ -163,6 +163,59 @@ export function formatBucketRange(bucket: UsageBucket, locale: string, includeOfreturn `${formatRfc3339(bucket.start_at, locale, includeOffsets)} – ${formatRfc3339(bucket.end_at, locale, includeOffsets)}`;}+type LocalStamp = { year: number; month: number; day: number; hour: string; minute: string };++const localStamp = (value: string): LocalStamp | null => {+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);+ if (!match) return null;+ const [, year, month, day, hour, minute] = match;+ return { year: Number(year), month: Number(month), day: Number(day), hour, minute };+};++const offsetMinutes = (value: string): number | null => {+ const match = value.match(/(Z|([+-])(\d{2}):(\d{2}))$/);+ if (!match) return null;+ if (match[1] === 'Z') return 0;+ return (match[2] === '-' ? -1 : 1) * (Number(match[3]) * 60 + Number(match[4]));+};++/**+ * A bucket's range as a tooltip heading: 「9月23日 22:00–23:00」, one date when the+ * range stays on one day, and only the date for a whole day. The zone is set+ * apart so the heading can mute it; it is named only when the two ends differ+ * (a DST change) or the report's offset is not the viewer's own.+ */+export function formatBucketHeading(bucket: UsageBucket, locale: string): { range: string; zone: string | null } {+ const start = localStamp(bucket.start_at);+ const end = localStamp(bucket.end_at);+ if (!start || !end) return { range: formatBucketRange(bucket, locale, true), zone: null };+ const date = ({ year, month, day }: LocalStamp) => (locale.startsWith('zh')+ ? `${month}月${day}日`+ : new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' })+ .format(new Date(Date.UTC(year, month - 1, day))));+ const separator = locale.startsWith('zh') ? ' ' : ', ';+ const time = (stamp: LocalStamp) => `${stamp.hour}:${stamp.minute}`;+ const dayOf = (stamp: LocalStamp) => Date.UTC(stamp.year, stamp.month - 1, stamp.day);+ const endsAtMidnight = end.hour === '00' && end.minute === '00';+ const nextDay = dayOf(end) - dayOf(start) === 24 * 60 * 60 * 1000;+ let range: string;+ if (dayOf(start) === dayOf(end)) {+ range = `${date(start)}${separator}${time(start)}–${time(end)}`;+ } else if (nextDay && endsAtMidnight) {+ range = time(start) === '00:00' ? date(start) : `${date(start)}${separator}${time(start)}–24:00`;+ } else {+ range = `${date(start)}${separator}${time(start)} – ${date(end)}${separator}${time(end)}`;+ }+ const startZone = formatOffset(bucket.start_at);+ const endZone = formatOffset(bucket.end_at);+ const reportOffset = offsetMinutes(bucket.start_at);+ const hostOffset = -new Date(bucket.start_at).getTimezoneOffset();+ const zone = startZone !== endZone+ ? `${startZone} – ${endZone}`+ : reportOffset !== null && reportOffset !== hostOffset ? startZone : null;+ return { range, zone };+}+export function sourceLabel(report: UsageReport, sourceId: string): string {const source = report.sources.find((candidate) => candidate.source_id === sourceId);return source?.label?.trim() || sourceId;