A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
feat(usage): add inline detail drawer and range selection to heatmap (#9994)
青衣_璃b00a3efb387f
diff --git a/src/components/usage/UsageDashboard.tsx b/src/components/usage/UsageDashboard.tsxindex 22e4bcb65..b22e52ef4 100644--- a/src/components/usage/UsageDashboard.tsx+++ b/src/components/usage/UsageDashboard.tsx@@ -921,6 +921,7 @@ export function UsageDashboard({providerName={providerName}model={model}refreshIntervalMs={0}+ onApplyRange={applyRange}/>) : (<UsageTrendChartdiff --git a/src/components/usage/UsageHeatmap.tsx b/src/components/usage/UsageHeatmap.tsxindex 4efe45a3f..a1bd4870f 100644--- a/src/components/usage/UsageHeatmap.tsx+++ b/src/components/usage/UsageHeatmap.tsx@@ -1,22 +1,39 @@-import { Fragment, useMemo, useRef, useState } from "react";+import {+ Fragment,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { useTranslation } from "react-i18next";-import { ChevronDown, Loader2 } from "lucide-react";+import { ChevronDown, Loader2, X } from "lucide-react";import { Button } from "@/components/ui/button";+import { Notice } from "@/components/ui/notice";import { useUsageFirstDate, useUsageTrends } from "@/lib/query/usage";import { cn } from "@/lib/utils";import type { UsageRangeSelection } from "@/types/usage";import {+ fmtInt,+ formatHitRatePercent,+ formatTokensCompact,formatTokensShort,getLocaleFromLanguage,parseFiniteNumber,} from "./format";-import { hitRateOf, type UsageTrendStatLike } from "./UsageTrendChart";+import {+ UsageTrendChart,+ hitRateOf,+ type UsageTrendStatLike,+} from "./UsageTrendChart";import { UsageTooltipCard } from "./UsageTooltipCard";import { useMoneyFormat } from "@/hooks/useMoneyFormat";import type { UsageMetric } from "./rememberedChoice";const WEEKS = 53;const DAY_MS = 24 * 60 * 60 * 1000;+/** 后端 `rollup_and_prune(30)` 会在 30 天后合并原始请求明细并仅保留每日汇总 */+export const HEATMAP_RAW_RETENTION_DAYS = 30;/** 0 档用底色,1–4 档是 --heat-1…4(与趋势图同一色相,色阶在 index.css 按深浅色分别定) */const LEVELS = [0, 1, 2, 3, 4];@@ -27,6 +44,8 @@ interface UsageHeatmapProps {providerName?: string;model?: string;refreshIntervalMs: number;+ /** 可选:把热力图当前选中的单日或连续区间同步应用到主仪表盘筛选器 */+ onApplyRange?: (selection: UsageRangeSelection) => void;}interface DayCell {@@ -124,6 +143,219 @@ function metricValue();}+/** 热力图选中的连续本地日期闭区间 `[start, end]`(均为本地零点) */+export interface HeatmapDayRange {+ start: Date;+ end: Date;+}++export interface HeatmapSelectionState {+ selectedRange: HeatmapDayRange | null;+ rangeAnchor: Date | null;+}++export interface HeatmapRangeSummary {+ days: number;+ activeDays: number;+ tokens: number;+ requests: number;+ cost: number;+ hitRate: number | null;+}++/** 把任意顺序的两个日期归一化为闭区间 `[较早, 较晚]`(本地日历零点) */+export function normalizeHeatmapRange(a: Date, b: Date): HeatmapDayRange {+ const start = startOfDay(a);+ const end = startOfDay(b);+ return start.getTime() <= end.getTime()+ ? { start, end }+ : { start: end, end: start };+}++/**+ * 解析热力图日期格点击后的选区与锚点状态:+ * - 普通点击:切换关闭当前单日,或选中新的单日并将其设为下一次 Shift+点击的锚点+ * - Shift+点击:以现有锚点(或已选区间起点)为基准归一化连续闭区间并保留锚点,+ * 便于继续 Shift+点击调整范围;若此前未选中任何日期,则将该日同时设为选区与锚点+ */+export function resolveHeatmapDayClick(+ current: HeatmapSelectionState,+ rawDate: Date,+ shiftKey: boolean,+): HeatmapSelectionState {+ const clicked = startOfDay(rawDate);++ if (shiftKey) {+ const anchor = current.rangeAnchor ?? current.selectedRange?.start ?? null;+ if (anchor) {+ return {+ selectedRange: normalizeHeatmapRange(anchor, clicked),+ rangeAnchor: anchor,+ };+ }+ return {+ selectedRange: { start: clicked, end: clicked },+ rangeAnchor: clicked,+ };+ }++ if (+ current.selectedRange &&+ daysBetween(current.selectedRange.start, current.selectedRange.end) === 0 &&+ dayKey(current.selectedRange.start) === dayKey(clicked)+ ) {+ return {+ selectedRange: null,+ rangeAnchor: null,+ };+ }++ return {+ selectedRange: { start: clicked, end: clicked },+ rangeAnchor: clicked,+ };+}++function isShiftKeyboardEvent(event: KeyboardEvent): boolean {+ return (+ event.key === "Shift" ||+ event.code === "ShiftLeft" ||+ event.code === "ShiftRight"+ );+}++export function isDayInHeatmapRange(+ date: Date,+ range: HeatmapDayRange | null,+): boolean {+ if (!range) return false;+ const target = startOfDay(date).getTime();+ return (+ target >= startOfDay(range.start).getTime() &&+ target <= startOfDay(range.end).getTime()+ );+}++export function isHeatmapRangeEndpoint(+ date: Date,+ range: HeatmapDayRange | null,+): boolean {+ if (!range) return false;+ const target = startOfDay(date).getTime();+ return (+ target === startOfDay(range.start).getTime() ||+ target === startOfDay(range.end).getTime()+ );+}++/**+ * 转为后端 `get_usage_trends` / 主筛选器识别的闭区间秒级时间戳:+ * 起点必须严格对齐本地 00:00:00、终点对齐 23:59:59,后端 `compute_rollup_date_bounds`+ * 才会将超过 30 天的每日汇总行(usage_daily_rollups)纳入统计。+ */+export function buildHeatmapUsageSelection(+ range: HeatmapDayRange,+): UsageRangeSelection {+ const { start, end } = normalizeHeatmapRange(range.start, range.end);+ const customStartDate = Math.floor(+ new Date(+ start.getFullYear(),+ start.getMonth(),+ start.getDate(),+ 0,+ 0,+ 0,+ ).getTime() / 1000,+ );+ const customEndDate = Math.floor(+ new Date(+ end.getFullYear(),+ end.getMonth(),+ end.getDate(),+ 23,+ 59,+ 59,+ ).getTime() / 1000,+ );+ return {+ preset: "custom",+ customStartDate,+ customEndDate,+ liveEndTime: false,+ };+}++/**+ * 判断选中的单日是否已跨过 30 天原始明细保留期。+ * 单日区间时长 <= 24h,后端走按小时分支且仅查 proxy_request_logs;30 天及更早的日期+ * 原始请求已被清理并归档至每日汇总,需要提示用户改看汇总或开启多日趋势。+ */+export function isSingleDayArchived(+ range: HeatmapDayRange,+ today: Date = startOfDay(new Date()),+): boolean {+ const normalized = normalizeHeatmapRange(range.start, range.end);+ if (daysBetween(normalized.start, normalized.end) !== 0) return false;+ return (+ daysBetween(normalized.start, startOfDay(today)) >=+ HEATMAP_RAW_RETENTION_DAYS+ );+}++/** 按热力图已加载的按天趋势汇总选中区间的核心指标,与卡片上方 KPI 和工具提示同口径 */+export function summarizeHeatmapRange(+ range: HeatmapDayRange,+ byDay: ReadonlyMap<string, UsageTrendStatLike>,+ today: Date = startOfDay(new Date()),+): HeatmapRangeSummary {+ const normalized = normalizeHeatmapRange(range.start, range.end);+ const normalizedToday = startOfDay(today);+ const limit =+ normalized.end.getTime() <= normalizedToday.getTime()+ ? normalized.end+ : normalizedToday;++ let days = 0;+ let activeDays = 0;+ let tokens = 0;+ let requests = 0;+ let cost = 0;+ let cacheRead = 0;+ let cacheable = 0;++ for (+ let cursor = normalized.start;+ cursor.getTime() <= limit.getTime();+ cursor = addDays(cursor, 1)+ ) {+ days += 1;+ const stat = byDay.get(dayKey(cursor));+ if (!stat) continue;+ const dayTokens = metricValue(stat, "tokens");+ const dayRequests = stat.requestCount ?? 0;+ tokens += dayTokens;+ requests += dayRequests;+ cost += metricValue(stat, "cost");+ cacheRead += stat.totalCacheReadTokens;+ cacheable +=+ stat.totalInputTokens ++ stat.totalCacheCreationTokens ++ stat.totalCacheReadTokens;+ if (dayRequests > 0 || dayTokens > 0) {+ activeDays += 1;+ }+ }++ return {+ days: Math.max(days, 1),+ activeDays,+ tokens,+ requests,+ cost,+ hitRate: cacheable > 0 ? cacheRead / cacheable : null,+ };+}+/** 格子分档用的值:用量类指标 0 就是没用;命中率 0% 是真实数据,只有没有输入时才是空 */function heatValue(stat: UsageTrendStatLike | undefined,@@ -264,6 +496,7 @@ export function UsageHeatmap({providerName,model,refreshIntervalMs,+ onApplyRange,}: UsageHeatmapProps) {const { t, i18n } = useTranslation();const { money } = useMoneyFormat();@@ -271,6 +504,64 @@ export function UsageHeatmap({const [hover, setHover] = useState<HoverState | null>(null);// 默认只画最近 53 周,点「显示更多」才把更早的段全部展开;不记住,每次进来都是收起const [showEarlier, setShowEarlier] = useState(false);+ // 行内详情与连续区间选择:点击单日展开,按住 Shift 点击可划定连续日期区间+ const [rangeAnchor, setRangeAnchor] = useState<Date | null>(null);+ const [selectedRange, setSelectedRange] = useState<HeatmapDayRange | null>(+ null,+ );+ // 收起抽屉时短暂保留上一次内容直到 CSS 高度动画(1fr -> 0fr)完成,避免文字/图表瞬间跳没+ const [closingRange, setClosingRange] = useState<HeatmapDayRange | null>(+ null,+ );+ const shiftPressedRef = useRef(false);+ const pointerDownShiftCellRef = useRef<string | null>(null);+ const [isShiftPressed, setIsShiftPressed] = useState(false);++ const syncShiftPressed = useCallback((pressed: boolean) => {+ shiftPressedRef.current = pressed;+ setIsShiftPressed((prev) => (prev === pressed ? prev : pressed));+ }, []);++ useEffect(() => {+ if (selectedRange != null || closingRange == null) return;+ const timer = window.setTimeout(() => setClosingRange(null), 240);+ return () => window.clearTimeout(timer);+ }, [selectedRange, closingRange]);++ useEffect(() => {+ const handleWindowKeyDown = (event: KeyboardEvent) => {+ if (isShiftKeyboardEvent(event) || event.shiftKey) {+ syncShiftPressed(true);+ }+ };+ const handleWindowKeyUp = (event: KeyboardEvent) => {+ // On Linux X11/WebKitGTK, keyup for Shift can still carry shiftKey=true+ // (pre-release modifier state), so always reset on Shift keyup.+ if (isShiftKeyboardEvent(event) || !event.shiftKey) {+ syncShiftPressed(false);+ }+ };+ const handleResetShift = () => {+ syncShiftPressed(false);+ pointerDownShiftCellRef.current = null;+ };+ const handleVisibilityChange = () => {+ if (document.hidden) {+ handleResetShift();+ }+ };++ window.addEventListener("keydown", handleWindowKeyDown);+ window.addEventListener("keyup", handleWindowKeyUp);+ window.addEventListener("blur", handleResetShift);+ document.addEventListener("visibilitychange", handleVisibilityChange);+ return () => {+ window.removeEventListener("keydown", handleWindowKeyDown);+ window.removeEventListener("keyup", handleWindowKeyUp);+ window.removeEventListener("blur", handleResetShift);+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ };+ }, [syncShiftPressed]);const showTooltip = (cell: DayCell, target: HTMLElement) => {const section = sectionRef.current;@@ -307,18 +598,32 @@ export function UsageHeatmap({.filter((cell) => !cell.future);const thresholds = buildThresholds(days.map((cell) => cell.value));- return { spans, thresholds };+ return { spans, thresholds, byDay, today };}, [trends, metric, spanCount]);- const earlierCount = heat.spans.length - 1;- const visibleSpans = showEarlier ? heat.spans : heat.spans.slice(0, 1);- const formatDay = (date: Date) =>- date.toLocaleDateString(locale, {- year: "numeric",- month: "short",- day: "numeric",- });-+ const shortDayFormatter = useMemo(+ () =>+ new Intl.DateTimeFormat(locale, {+ year: "numeric",+ month: "short",+ day: "numeric",+ }),+ [locale],+ );+ const fullDayFormatter = useMemo(+ () =>+ new Intl.DateTimeFormat(locale, {+ year: "numeric",+ month: "long",+ day: "numeric",+ weekday: "short",+ }),+ [locale],+ );+ const monthFormatter = useMemo(+ () => new Intl.DateTimeFormat(locale, { month: "short" }),+ [locale],+ );const weekdayLabels = useMemo(() => {// 2024-01-01 是周一return Array.from({ length: 7 }, (_, d) =>@@ -328,22 +633,92 @@ export function UsageHeatmap({);}, [locale]);+ const clearSelection = () => {+ if (selectedRange) {+ setClosingRange(selectedRange);+ }+ setSelectedRange(null);+ setRangeAnchor(null);+ };++ const handleDayClick = (rawDate: Date, shiftKey: boolean) => {+ const next = resolveHeatmapDayClick(+ { selectedRange, rangeAnchor },+ rawDate,+ shiftKey,+ );+ if (next.selectedRange == null) {+ clearSelection();+ return;+ }+ setClosingRange(null);+ setSelectedRange(next.selectedRange);+ setRangeAnchor(next.rangeAnchor);+ };++ const earlierCount = heat.spans.length - 1;+ const visibleSpans = showEarlier ? heat.spans : heat.spans.slice(0, 1);++ const isDrawerOpen = selectedRange != null;+ const displayedRange = selectedRange ?? closingRange;+ const previewRange =+ isShiftPressed && rangeAnchor && hover && !hover.cell.future+ ? normalizeHeatmapRange(rangeAnchor, hover.cell.date)+ : null;++ const drawerSelection = useMemo(+ () => (displayedRange ? buildHeatmapUsageSelection(displayedRange) : null),+ [displayedRange],+ );+ const drawerSummary = useMemo(+ () =>+ displayedRange+ ? summarizeHeatmapRange(displayedRange, heat.byDay, heat.today)+ : null,+ [displayedRange, heat.byDay, heat.today],+ );+ const drawerArchivedSingleDay = displayedRange+ ? isSingleDayArchived(displayedRange, heat.today)+ : false;+ const drawerHeading =+ displayedRange && drawerSummary+ ? drawerSummary.days === 1+ ? fullDayFormatter.format(displayedRange.start)+ : `${shortDayFormatter.format(displayedRange.start)} – ${shortDayFormatter.format(displayedRange.end)}`+ : "";+ const drawerCostDigits =+ drawerSummary && drawerSummary.cost > 0 && drawerSummary.cost < 0.01+ ? 4+ : 2;+return (<sectionref={sectionRef}aria-labelledby="usage-heatmap-title"+ onKeyDown={(event) => {+ if (event.key === "Escape" && selectedRange != null) {+ event.preventDefault();+ event.stopPropagation();+ clearSelection();+ }+ }}className="relative px-4 pb-3 pt-5">- <div>- <h2- id="usage-heatmap-title"- className="m-0 text-body font-semibold text-fg-1"- >- {t("usage.heatmap.title")}- </h2>- <p className="m-0 text-caption text-fg-3">- {t("usage.heatmap.subtitle")}- </p>+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div>+ <h2+ id="usage-heatmap-title"+ className="m-0 text-body font-semibold text-fg-1"+ >+ {t("usage.heatmap.title")}+ </h2>+ <p className="m-0 text-caption text-fg-3">+ {t("usage.heatmap.subtitle")}+ </p>+ </div>+ <span className="select-none text-caption text-fg-3">+ {t("usage.heatmap.rangeHint")}+ </span></div>{isLoading ? (@@ -351,74 +726,135 @@ export function UsageHeatmap({<Loader2 className="h-5 w-5 animate-spin text-fg-3" /></div>) : (- visibleSpans.map((span, index) => (- <div- key={dayKey(span.start)}- className={index === 0 ? "mt-3" : "mt-4"}- >- <div className="flex flex-wrap items-baseline gap-x-2">- <h3 className="m-0 text-body font-semibold tabular-nums text-fg-1">- {`${formatDay(span.start)} – ${formatDay(span.end)}`}- </h3>- <span className="text-caption tabular-nums text-fg-3">- {t("usage.heatmap.spanSummary", {- tokens: formatTokensShort(span.totals.tokens, language),- requests: formatTokensShort(span.totals.requests, language),- cost: money(span.totals.cost, 2),- })}- </span>- </div>- <div- className="mt-1.5 grid items-center gap-[3px]"- style={{- gridTemplateColumns: `max-content repeat(${WEEKS}, minmax(0, 1fr))`,- }}- >- <span />- {span.weeks.map((_, w) => (- <span- key={`m${w}`}- className="h-4 overflow-visible whitespace-nowrap text-badge leading-4 text-fg-3"- >- {span.monthLabels[w] != null- ? new Date(- 2024,- span.monthLabels[w]! - 1,- 1,- ).toLocaleDateString(locale, { month: "short" })- : ""}+ <div className="mt-3 space-y-4 select-none">+ {visibleSpans.map((span) => (+ <div key={dayKey(span.start)}>+ <div className="flex flex-wrap items-baseline gap-x-2">+ <h3 className="m-0 text-body font-semibold tabular-nums text-fg-1">+ {`${shortDayFormatter.format(span.start)} – ${shortDayFormatter.format(span.end)}`}+ </h3>+ <span className="text-caption tabular-nums text-fg-3">+ {t("usage.heatmap.spanSummary", {+ tokens: formatTokensShort(span.totals.tokens, language),+ requests: formatTokensShort(span.totals.requests, language),+ cost: money(span.totals.cost, 2),+ })}</span>- ))}- {weekdayLabels.map((label, d) => (- <Fragment key={`r${d}`}>- <span className="pe-1.5 text-badge leading-none text-fg-3">- {d % 2 === 0 ? label : ""}+ </div>+ <div+ className="mt-1.5 grid items-center gap-[3px]"+ style={{+ gridTemplateColumns: `max-content repeat(${WEEKS}, minmax(0, 1fr))`,+ }}+ >+ <span />+ {span.weeks.map((_, w) => (+ <span+ key={`m${w}`}+ className="h-4 overflow-visible whitespace-nowrap text-badge leading-4 text-fg-3"+ >+ {span.monthLabels[w] != null+ ? monthFormatter.format(+ new Date(2024, span.monthLabels[w]! - 1, 1),+ )+ : ""}</span>- {span.weeks.map((column) => {- const cell = column[d];- const level = levelOf(cell.value, heat.thresholds);- return (- <div- key={cell.key}- onMouseEnter={- cell.future- ? undefined- : (event) => showTooltip(cell, event.currentTarget)- }- onMouseLeave={() => setHover(null)}- className={cn(- "aspect-square w-full rounded-[3px]",- !cell.future && level === 0 && "bg-subtle",- )}- style={cell.future ? undefined : cellStyle(level)}- />- );- })}- </Fragment>- ))}+ ))}+ {weekdayLabels.map((label, d) => (+ <Fragment key={`r${d}`}>+ <span className="pe-1.5 text-badge leading-none text-fg-3">+ {d % 2 === 0 ? label : ""}+ </span>+ {span.weeks.map((column) => {+ const cell = column[d];+ if (cell.future) {+ return (+ <div+ key={cell.key}+ aria-hidden="true"+ className="aspect-square w-full rounded-[3px]"+ />+ );+ }+ const level = levelOf(cell.value, heat.thresholds);+ const isSelected = isDayInHeatmapRange(+ cell.date,+ selectedRange,+ );+ const isEndpoint = isHeatmapRangeEndpoint(+ cell.date,+ selectedRange,+ );+ const isPreview =+ previewRange != null &&+ isDayInHeatmapRange(cell.date, previewRange) &&+ !isSelected;+ const cellCostDigits =+ cell.cost > 0 && cell.cost < 0.01 ? 4 : 2;+ return (+ <button+ key={cell.key}+ type="button"+ data-day-key={cell.key}+ data-preview={isPreview ? "true" : undefined}+ aria-pressed={isSelected}+ aria-label={t("usage.heatmap.cellAriaSingle", {+ date: fullDayFormatter.format(cell.date),+ tokens: formatTokensShort(cell.tokens, language),+ requests: fmtInt(cell.requests, locale),+ cost: money(cell.cost, cellCostDigits),+ })}+ onMouseDown={(event) => {+ if (event.button !== 0) return;+ syncShiftPressed(event.shiftKey);+ pointerDownShiftCellRef.current = event.shiftKey+ ? cell.key+ : null;+ if (event.shiftKey) {+ // Prevent native text-range selection on Windows/macOS/Linux WebViews+ event.preventDefault();+ }+ }}+ onClick={(event) => {+ const fromPointerDown =+ pointerDownShiftCellRef.current === cell.key;+ pointerDownShiftCellRef.current = null;+ const shiftHeld =+ event.shiftKey ||+ fromPointerDown ||+ (event.detail === 0 && shiftPressedRef.current);+ handleDayClick(cell.date, shiftHeld);+ }}+ onMouseEnter={(event) => {+ syncShiftPressed(event.shiftKey);+ showTooltip(cell, event.currentTarget);+ }}+ onMouseLeave={() => setHover(null)}+ onFocus={(event) =>+ showTooltip(cell, event.currentTarget)+ }+ onBlur={() => setHover(null)}+ className={cn(+ "relative block aspect-square w-full cursor-pointer appearance-none rounded-[3px] border-0 p-0 transition-transform duration-100 hover:scale-110 focus-visible:z-10 motion-reduce:transition-none",+ level === 0 && "bg-subtle",+ isEndpoint &&+ "z-10 after:pointer-events-none after:absolute after:-inset-[1px] after:rounded-[4px] after:border-2 after:border-action",+ isSelected &&+ !isEndpoint &&+ "after:pointer-events-none after:absolute after:inset-0 after:rounded-[3px] after:border after:border-action",+ isPreview &&+ "after:pointer-events-none after:absolute after:inset-0 after:rounded-[3px] after:border after:border-dashed after:border-action",+ )}+ style={cellStyle(level)}+ />+ );+ })}+ </Fragment>+ ))}+ </div></div>- </div>- ))+ ))}+ </div>)}{hover && (@@ -439,12 +875,7 @@ export function UsageHeatmap({}}><UsageTooltipCard- heading={hover.cell.date.toLocaleDateString(locale, {- year: "numeric",- month: "long",- day: "numeric",- weekday: "short",- })}+ heading={fullDayFormatter.format(hover.cell.date)}tokens={hover.cell.tokens}requests={hover.cell.requests}cost={hover.cell.cost}@@ -488,6 +919,144 @@ export function UsageHeatmap({))}{t("usage.heatmap.more")}</div>++ {/* 行内折叠抽屉:复用 grid-template-rows (0fr ↔ 1fr) 动画在热力图原地展开单日或连续区间详情 */}+ <div+ data-testid="usage-heatmap-drawer"+ data-state={isDrawerOpen ? "open" : "closed"}+ aria-hidden={!isDrawerOpen}+ className={cn(+ "grid transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",+ isDrawerOpen ? "grid-rows-[1fr]" : "grid-rows-[0fr]",+ )}+ onTransitionEnd={(event) => {+ if (event.target === event.currentTarget && !isDrawerOpen) {+ setClosingRange(null);+ }+ }}+ {...(isDrawerOpen ? {} : { inert: "" })}+ >+ <div className="min-h-0 overflow-hidden">+ {displayedRange && drawerSelection && drawerSummary && (+ <div className="mt-3 border-t border-border pt-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <h3 className="m-0 text-body font-semibold tabular-nums text-fg-1">+ {drawerHeading}+ </h3>+ {drawerSummary.days > 1 && (+ <span className="rounded-control bg-subtle px-2 py-0.5 text-badge font-medium tabular-nums text-fg-2">+ {t("usage.heatmap.dayCount", {+ count: drawerSummary.days,+ })}+ </span>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ {onApplyRange && (+ <Button+ type="button"+ variant="neutral"+ size="compact"+ onClick={() => onApplyRange(drawerSelection)}+ >+ {t("usage.heatmap.applyRange")}+ </Button>+ )}+ <Button+ type="button"+ variant="quiet"+ size="icon-compact"+ aria-label={t("usage.heatmap.closeDetail")}+ onClick={clearSelection}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>++ <dl className="mt-2.5 grid grid-cols-2 gap-2 rounded-control bg-subtle px-3 py-2 sm:grid-cols-4">+ <div className="min-w-0">+ <dt className="text-badge text-fg-3">+ {t("usage.trend.tokens")}+ </dt>+ <dd+ className={cn(+ "m-0 truncate text-body font-semibold tabular-nums",+ metric === "tokens" ? "text-action-text" : "text-fg-1",+ )}+ >+ {formatTokensCompact(drawerSummary.tokens, locale)}+ </dd>+ </div>+ <div className="min-w-0">+ <dt className="text-badge text-fg-3">+ {t("usage.trend.requestsLegend")}+ </dt>+ <dd+ className={cn(+ "m-0 truncate text-body font-semibold tabular-nums",+ metric === "requests" ? "text-action-text" : "text-fg-1",+ )}+ >+ {fmtInt(drawerSummary.requests, locale)}+ </dd>+ </div>+ <div className="min-w-0">+ <dt className="text-badge text-fg-3">+ {t("usage.trend.cost")}+ </dt>+ <dd+ className={cn(+ "m-0 truncate text-body font-semibold tabular-nums",+ metric === "cost" ? "text-action-text" : "text-fg-1",+ )}+ >+ {money(drawerSummary.cost, drawerCostDigits)}+ </dd>+ </div>+ <div className="min-w-0">+ <dt className="text-badge text-fg-3">+ {t("usage.cacheHitRate")}+ </dt>+ <dd+ className={cn(+ "m-0 truncate text-body font-semibold tabular-nums",+ metric === "hitRate" ? "text-action-text" : "text-fg-1",+ )}+ >+ {drawerSummary.hitRate == null+ ? "—"+ : formatHitRatePercent(drawerSummary.hitRate)}+ </dd>+ </div>+ </dl>++ {drawerArchivedSingleDay ? (+ <Notice+ tone="neutral"+ title={t("usage.heatmap.archivedTitle")}+ className="mt-2.5"+ >+ {t("usage.heatmap.archivedBody", {+ days: HEATMAP_RAW_RETENTION_DAYS,+ })}+ </Notice>+ ) : (+ <UsageTrendChart+ embedded+ range={drawerSelection}+ metric={metric}+ appType={appType}+ providerName={providerName}+ model={model}+ refreshIntervalMs={refreshIntervalMs}+ />+ )}+ </div>+ )}+ </div>+ </div></section>);}diff --git a/src/components/usage/UsageTrendChart.tsx b/src/components/usage/UsageTrendChart.tsxindex bbc8eceff..d773ceed5 100644--- a/src/components/usage/UsageTrendChart.tsx+++ b/src/components/usage/UsageTrendChart.tsx@@ -34,6 +34,8 @@ interface UsageTrendChartProps {providerName?: string;model?: string;refreshIntervalMs: number;+ /** 嵌在热力图折叠抽屉里时收紧外边距,避免与外层卡片留白叠加 */+ embedded?: boolean;}export interface UsageTrendStatLike {@@ -286,6 +288,7 @@ export function UsageTrendChart({providerName,model,refreshIntervalMs,+ embedded = false,}: UsageTrendChartProps) {const { t, i18n } = useTranslation();const { money, moneyTick, rate } = useMoneyFormat();@@ -380,10 +383,15 @@ export function UsageTrendChart({);};+ const titleId = embedded ? "usage-heatmap-trend-title" : "usage-trend-title";+return (- <section aria-labelledby="usage-trend-title" className="px-4 pb-2.5 pt-5">+ <section+ aria-labelledby={titleId}+ className={embedded ? "pt-2" : "px-4 pb-2.5 pt-5"}+ ><h2- id="usage-trend-title"+ id={titleId}className="m-0 min-h-7 whitespace-nowrap text-caption font-semibold leading-7 text-fg-2">{t("usage.trend.titleMetric", {diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.jsonindex 9c804d680..ae1880f0c 100644--- a/src/i18n/locales/de.json+++ b/src/i18n/locales/de.json@@ -2758,7 +2758,14 @@"showMore": "Mehr anzeigen","showLess": "Weniger anzeigen","less": "Weniger",- "more": "Mehr"+ "more": "Mehr",+ "rangeHint": "Shift+Klick für Bereichsauswahl",+ "dayCount": "{{count}} Tage",+ "applyRange": "Auf Filter anwenden",+ "closeDetail": "Details schließen",+ "archivedTitle": "Nur Tageszusammenfassung",+ "archivedBody": "Rohdaten, die älter als {{days}} Tage sind, werden zu Tageswerten verdichtet, sodass kein Stundenverlauf verfügbar ist. Mit Shift+Klick auf einen anderen Tag lassen sich mehrtägige Verläufe anzeigen.",+ "cellAriaSingle": "{{date}}: {{tokens}} Token, {{requests}} Anfragen, {{cost}}"},"trend": {"title": "Nutzungstrend · {{range}}",diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.jsonindex 1819e9d37..17d77f19f 100644--- a/src/i18n/locales/en.json+++ b/src/i18n/locales/en.json@@ -2758,7 +2758,14 @@"showMore": "Show more","showLess": "Show less","less": "Less",- "more": "More"+ "more": "More",+ "rangeHint": "Shift+click to select a range",+ "dayCount": "{{count}} days",+ "applyRange": "Apply to filter",+ "closeDetail": "Close details",+ "archivedTitle": "Daily rollup only",+ "archivedBody": "Raw requests older than {{days}} days are rolled up into daily totals, so hourly trends are unavailable. Shift+click another day to inspect multi-day trends.",+ "cellAriaSingle": "{{date}}: {{tokens}} tokens, {{requests}} requests, {{cost}}"},"trend": {"title": "Usage trend · {{range}}",diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.jsonindex de501c1b4..694f63006 100644--- a/src/i18n/locales/ja.json+++ b/src/i18n/locales/ja.json@@ -2758,7 +2758,14 @@"showMore": "もっと見る","showLess": "折りたたむ","less": "少",- "more": "多"+ "more": "多",+ "rangeHint": "Shift+クリックで範囲選択",+ "dayCount": "{{count}} 日間",+ "applyRange": "フィルターに適用",+ "closeDetail": "詳細を閉じる",+ "archivedTitle": "日別集計のみ保持",+ "archivedBody": "{{days}} 日より前の生ログは日別集計にアーカイブされるため、時間別の推移は表示できません。別の日にちを Shift+クリックすると複数日の日別推移を確認できます。",+ "cellAriaSingle": "{{date}}: {{tokens}} トークン、{{requests}} リクエスト、{{cost}}"},"trend": {"title": "使用状況の推移 · {{range}}",diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.jsonindex 6ee72a328..e9cafe175 100644--- a/src/i18n/locales/ko.json+++ b/src/i18n/locales/ko.json@@ -2753,7 +2753,14 @@"showMore": "더 보기","showLess": "간략히 보기","less": "적음",- "more": "많음"+ "more": "많음",+ "rangeHint": "Shift+클릭으로 범위 선택",+ "dayCount": "{{count}}일",+ "applyRange": "필터에 적용",+ "closeDetail": "세부 정보 닫기",+ "archivedTitle": "일별 집계만 보관됨",+ "archivedBody": "{{days}}일이 지난 원본 요청은 일별 집계로 보관되어 시간별 추이를 볼 수 없습니다. 다른 날짜를 Shift+클릭하면 여러 날의 추이를 볼 수 있습니다.",+ "cellAriaSingle": "{{date}}: {{tokens}} 토큰, {{requests}} 요청, {{cost}}"},"trend": {"title": "사용량 추이 · {{range}}",diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.jsonindex 84f2dea02..2110ec7d9 100644--- a/src/i18n/locales/ru.json+++ b/src/i18n/locales/ru.json@@ -2757,7 +2757,14 @@"showMore": "Показать больше","showLess": "Показать меньше","less": "Меньше",- "more": "Больше"+ "more": "Больше",+ "rangeHint": "Shift+клик для выбора диапазона",+ "dayCount": "{{count}} дн.",+ "applyRange": "Применить к фильтру",+ "closeDetail": "Закрыть детали",+ "archivedTitle": "Только дневная сводка",+ "archivedBody": "Исходные запросы старше {{days}} дней свёрнуты в дневные итоги, поэтому почасовой график недоступен. Нажмите другой день с зажатым Shift, чтобы посмотреть динамику за несколько дней.",+ "cellAriaSingle": "{{date}}: {{tokens}} токенов, {{requests}} запросов, {{cost}}"},"trend": {"title": "Динамика использования · {{range}}",diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.jsonindex d848d8a8c..1690d61f3 100644--- a/src/i18n/locales/tr.json+++ b/src/i18n/locales/tr.json@@ -2687,7 +2687,14 @@"showMore": "Daha fazlasını göster","showLess": "Daha az göster","less": "Daha az",- "more": "Diğer"+ "more": "Diğer",+ "rangeHint": "Aralık seçmek için Shift+tıklayın",+ "dayCount": "{{count}} gün",+ "applyRange": "Filtreye uygula",+ "closeDetail": "Ayrıntıları kapat",+ "archivedTitle": "Yalnızca günlük özet",+ "archivedBody": "{{days}} günden eski ham istekler günlük özetlere sıkıştırıldığı için saatlik dağılım kullanılamaz. Çok günlük eğilimleri görmek için başka bir güne Shift+tıklayın.",+ "cellAriaSingle": "{{date}}: {{tokens}} token, {{requests}} istek, {{cost}}"},"trend": {"title": "Kullanım eğilimi · {{range}}",diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.jsonindex d458bcf7e..17afae5e3 100644--- a/src/i18n/locales/zh-TW.json+++ b/src/i18n/locales/zh-TW.json@@ -2758,7 +2758,14 @@"showMore": "顯示更多","showLess": "收起","less": "少",- "more": "多"+ "more": "多",+ "rangeHint": "按住 Shift 點擊可選擇連續日期",+ "dayCount": "{{count}} 天",+ "applyRange": "套用到主篩選",+ "closeDetail": "收起詳情",+ "archivedTitle": "僅保留每日彙總",+ "archivedBody": "超過 {{days}} 天的原始請求已歸檔為按日彙總,暫不支援按小時曲線;按住 Shift 點擊另一天可查看多日趨勢。",+ "cellAriaSingle": "{{date}}:{{tokens}} Token,{{requests}} 次請求,{{cost}}"},"trend": {"title": "使用趨勢 · {{range}}",diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.jsonindex 5570a76cf..b7da8e225 100644--- a/src/i18n/locales/zh.json+++ b/src/i18n/locales/zh.json@@ -2758,7 +2758,14 @@"showMore": "显示更多","showLess": "收起","less": "少",- "more": "多"+ "more": "多",+ "rangeHint": "按住 Shift 点击可选择连续日期",+ "dayCount": "{{count}} 天",+ "applyRange": "应用到主筛选",+ "closeDetail": "收起详情",+ "archivedTitle": "仅保留每日汇总",+ "archivedBody": "超过 {{days}} 天的原始请求已归档为按天汇总,暂不支持按小时曲线;按住 Shift 点击另一天可查看多日趋势。",+ "cellAriaSingle": "{{date}}:{{tokens}} Token,{{requests}} 次请求,{{cost}}"},"trend": {"title": "使用趋势 · {{range}}",diff --git a/tests/components/UsageHeatmap.selection.test.tsx b/tests/components/UsageHeatmap.selection.test.tsxnew file mode 100644index 000000000..e0d0934e6--- /dev/null+++ b/tests/components/UsageHeatmap.selection.test.tsx@@ -0,0 +1,500 @@+import { createEvent, fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ HEATMAP_RAW_RETENTION_DAYS,+ UsageHeatmap,+ buildHeatmapUsageSelection,+ isSingleDayArchived,+ normalizeHeatmapRange,+ resolveHeatmapDayClick,+ summarizeHeatmapRange,+} from "@/components/usage/UsageHeatmap";+import type { UsageTrendStatLike } from "@/components/usage/UsageTrendChart";++const hoisted = vi.hoisted(() => ({+ firstDate: "2026-09-01",+ trends: [] as UsageTrendStatLike[],+ lastTrendProps: null as null | {+ range: {+ preset: string;+ customStartDate?: number;+ customEndDate?: number;+ liveEndTime?: boolean;+ };+ metric: string;+ embedded?: boolean;+ },+}));++vi.mock("@/lib/query/usage", () => ({+ useUsageFirstDate: () => ({+ isSuccess: true,+ isPending: false,+ data: hoisted.firstDate,+ }),+ useUsageTrends: () => ({+ isLoading: false,+ data: hoisted.trends,+ }),+}));++vi.mock("@/hooks/useMoneyFormat", () => ({+ useMoneyFormat: () => ({+ money: (value: unknown, digits = 2) =>+ `$${Number(value ?? 0).toFixed(digits)}`,+ moneyTick: (value: unknown) => `$${Number(value ?? 0)}`,+ rate: 1,+ currency: "USD",+ }),+}));++vi.mock("@/components/usage/UsageTrendChart", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@/components/usage/UsageTrendChart")>();+ return {+ ...actual,+ UsageTrendChart: (props: {+ range: {+ preset: string;+ customStartDate?: number;+ customEndDate?: number;+ liveEndTime?: boolean;+ };+ metric: string;+ embedded?: boolean;+ }) => {+ hoisted.lastTrendProps = props;+ return (+ <div+ data-testid="mock-heatmap-trend-chart"+ data-start={String(props.range.customStartDate ?? "")}+ data-end={String(props.range.customEndDate ?? "")}+ data-live-end={String(Boolean(props.range.liveEndTime))}+ data-embedded={String(Boolean(props.embedded))}+ data-metric={props.metric}+ />+ );+ },+ };+});++function localDay(daysAgo: number): Date {+ const now = new Date();+ return new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo);+}++function dayButtonKey(date: Date): string {+ return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;+}++function localTimestampString(date: Date): string {+ const y = date.getFullYear();+ const m = String(date.getMonth() + 1).padStart(2, "0");+ const d = String(date.getDate()).padStart(2, "0");+ return `${y}-${m}-${d}T00:00:00`;+}++function makeStat(+ date: Date,+ overrides: Partial<UsageTrendStatLike> = {},+): UsageTrendStatLike {+ return {+ date: localTimestampString(date),+ requestCount: 10,+ totalInputTokens: 1_000,+ totalOutputTokens: 500,+ totalCacheCreationTokens: 200,+ totalCacheReadTokens: 8_800,+ totalCost: "1.25",+ ...overrides,+ };+}++function getDayCell(date: Date): HTMLElement {+ const key = dayButtonKey(date);+ const el = document.querySelector<HTMLElement>(`[data-day-key="${key}"]`);+ if (!el) {+ throw new Error(`Day cell not found for key: ${key}`);+ }+ return el;+}++describe("UsageHeatmap selection & range helpers", () => {+ it("normalizes arbitrary endpoint order to [start, end] at local midnight", () => {+ const earlier = new Date(2026, 9, 10, 15, 30);+ const later = new Date(2026, 9, 14, 9, 15);+ const normalized = normalizeHeatmapRange(later, earlier);+ expect(normalized.start).toEqual(new Date(2026, 9, 10, 0, 0, 0, 0));+ expect(normalized.end).toEqual(new Date(2026, 9, 14, 0, 0, 0, 0));+ });++ it("builds local 00:00:00–23:59:59 custom range with liveEndTime false", () => {+ const start = new Date(2026, 10, 20);+ const end = new Date(2026, 10, 22);+ const selection = buildHeatmapUsageSelection({ start, end });+ expect(selection).toEqual({+ preset: "custom",+ customStartDate: Math.floor(+ new Date(2026, 10, 20, 0, 0, 0).getTime() / 1000,+ ),+ customEndDate: Math.floor(+ new Date(2026, 10, 22, 23, 59, 59).getTime() / 1000,+ ),+ liveEndTime: false,+ });+ });++ it("flags single-day selections at or beyond retention days as archived, but allows multi-day", () => {+ const today = new Date(2026, 10, 26);+ const recent = new Date(2026, 10, 26 - (HEATMAP_RAW_RETENTION_DAYS - 1));+ const archived = new Date(2026, 10, 26 - HEATMAP_RAW_RETENTION_DAYS);++ expect(isSingleDayArchived({ start: recent, end: recent }, today)).toBe(+ false,+ );+ expect(isSingleDayArchived({ start: archived, end: archived }, today)).toBe(+ true,+ );+ expect(isSingleDayArchived({ start: archived, end: recent }, today)).toBe(+ false,+ );+ });++ it("summarizes weighted cache hit rate and totals across days", () => {+ const d1 = new Date(2026, 10, 20);+ const d3 = new Date(2026, 10, 22);+ const today = new Date(2026, 10, 26);++ const byDay = new Map<string, UsageTrendStatLike>([+ [+ dayButtonKey(d1),+ makeStat(d1, {+ requestCount: 4,+ totalInputTokens: 100,+ totalOutputTokens: 50,+ totalCacheCreationTokens: 0,+ totalCacheReadTokens: 900,+ totalCost: "1.5",+ }),+ ],+ // d2 故意留空,验证空日计入总天数但不算活跃天+ [+ dayButtonKey(d3),+ makeStat(d3, {+ requestCount: 6,+ totalInputTokens: 500,+ totalOutputTokens: 100,+ totalCacheCreationTokens: 0,+ totalCacheReadTokens: 500,+ totalCost: "2.5",+ }),+ ],+ ]);++ const summary = summarizeHeatmapRange({ start: d1, end: d3 }, byDay, today);+ expect(summary.days).toBe(3);+ expect(summary.activeDays).toBe(2);+ expect(summary.requests).toBe(10);+ // d1: 1050, d3: 1100+ expect(summary.tokens).toBe(2150);+ expect(summary.cost).toBeCloseTo(4.0);+ // 加权命中率 = (900 + 500) / ((100 + 900) + (500 + 500)) = 1400 / 2000 = 0.7+ expect(summary.hitRate).toBeCloseTo(0.7);+ });++ it("resolves plain clicks, Shift+click ranges, re-adjustment around anchor, and collapsing back to a single day", () => {+ const d1 = new Date(2026, 10, 20);+ const d2 = new Date(2026, 10, 22);+ const d3 = new Date(2026, 10, 25);++ // 1. Plain click from empty opens single day and sets anchor+ const s1 = resolveHeatmapDayClick(+ { selectedRange: null, rangeAnchor: null },+ d2,+ false,+ );+ expect(s1).toEqual({+ selectedRange: { start: d2, end: d2 },+ rangeAnchor: d2,+ });++ // 2. Second plain click on same day toggles closed+ expect(resolveHeatmapDayClick(s1, d2, false)).toEqual({+ selectedRange: null,+ rangeAnchor: null,+ });++ // 3. Plain click on different day switches single day and updates anchor+ const s2 = resolveHeatmapDayClick(s1, d3, false);+ expect(s2).toEqual({+ selectedRange: { start: d3, end: d3 },+ rangeAnchor: d3,+ });++ // 4. Shift+click in reverse order normalizes [d1, d3] while keeping anchor d3+ const s3 = resolveHeatmapDayClick(s2, d1, true);+ expect(s3).toEqual({+ selectedRange: { start: d1, end: d3 },+ rangeAnchor: d3,+ });++ // 5. Subsequent Shift+click re-adjusts range around preserved anchor d3+ const s4 = resolveHeatmapDayClick(s3, d2, true);+ expect(s4).toEqual({+ selectedRange: { start: d2, end: d3 },+ rangeAnchor: d3,+ });++ // 6. Plain click while multi-day range is active collapses to clicked single day+ const s5 = resolveHeatmapDayClick(s4, d1, false);+ expect(s5).toEqual({+ selectedRange: { start: d1, end: d1 },+ rangeAnchor: d1,+ });++ // 7. Shift+click from empty state sets anchor & single day so a second Shift+click completes range+ const fromEmpty = resolveHeatmapDayClick(+ { selectedRange: null, rangeAnchor: null },+ d1,+ true,+ );+ expect(fromEmpty).toEqual({+ selectedRange: { start: d1, end: d1 },+ rangeAnchor: d1,+ });+ expect(resolveHeatmapDayClick(fromEmpty, d3, true)).toEqual({+ selectedRange: { start: d1, end: d3 },+ rangeAnchor: d1,+ });+ });+});++describe("UsageHeatmap inline drawer & Shift+click range selection", () => {+ const recentA = localDay(5);+ const recentMid = localDay(4);+ const recentB = localDay(3);+ const archivedDay = localDay(40);++ beforeEach(() => {+ hoisted.lastTrendProps = null;+ hoisted.firstDate = "2026-01-01";+ hoisted.trends = [+ makeStat(recentA, { requestCount: 12, totalCost: "2.00" }),+ makeStat(recentMid, { requestCount: 8, totalCost: "1.50" }),+ makeStat(recentB, { requestCount: 20, totalCost: "4.00" }),+ makeStat(archivedDay, { requestCount: 30, totalCost: "6.00" }),+ ];+ });++ it("renders a Shift+click hint without any range-select switch", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ expect(screen.queryByRole("switch")).not.toBeInTheDocument();+ expect(screen.getByText("usage.heatmap.rangeHint")).toBeInTheDocument();+ });++ it("expands inline drawer on day click and toggles closed on second click", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ const drawer = screen.getByTestId("usage-heatmap-drawer");+ expect(drawer).toHaveAttribute("data-state", "closed");+ expect(drawer).toHaveAttribute("aria-hidden", "true");+ expect(+ screen.queryByTestId("mock-heatmap-trend-chart"),+ ).not.toBeInTheDocument();++ const cellA = getDayCell(recentA);+ fireEvent.click(cellA);++ expect(drawer).toHaveAttribute("data-state", "open");+ expect(drawer).toHaveAttribute("aria-hidden", "false");+ expect(cellA).toHaveAttribute("aria-pressed", "true");++ const chart = screen.getByTestId("mock-heatmap-trend-chart");+ expect(chart).toHaveAttribute("data-embedded", "true");+ expect(chart).toHaveAttribute("data-live-end", "false");+ expect(hoisted.lastTrendProps?.range).toEqual(+ buildHeatmapUsageSelection({ start: recentA, end: recentA }),+ );++ // 再次点击同一天:收起抽屉+ fireEvent.click(cellA);+ expect(drawer).toHaveAttribute("data-state", "closed");+ expect(cellA).toHaveAttribute("aria-pressed", "false");+ });++ it("supports Shift+click range selection in reverse order, re-adjustment, collapse, and onApplyRange", () => {+ const onApplyRange = vi.fn();+ render(+ <UsageHeatmap+ metric="cost"+ refreshIntervalMs={0}+ onApplyRange={onApplyRange}+ />,+ );++ // 先点较晚的 B,再按住 Shift 点击较早的 A(验证逆序自动归一化为 [A, B])+ fireEvent.click(getDayCell(recentB));+ fireEvent.click(getDayCell(recentA), { shiftKey: true });++ expect(screen.getByText("usage.heatmap.dayCount")).toBeInTheDocument();++ // 起止与中间格子均处于选中态+ expect(getDayCell(recentA)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentMid)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "true");++ const expectedRange = buildHeatmapUsageSelection({+ start: recentA,+ end: recentB,+ });+ expect(hoisted.lastTrendProps?.range).toEqual(expectedRange);++ // 再次 Shift+点击 Mid,保持原锚点 B 重新调整为 [Mid, B]+ fireEvent.click(getDayCell(recentMid), { shiftKey: true });+ expect(getDayCell(recentA)).toHaveAttribute("aria-pressed", "false");+ expect(getDayCell(recentMid)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "true");++ // 恢复 [A, B] 后验证应用到主筛选+ fireEvent.click(getDayCell(recentA), { shiftKey: true });+ fireEvent.click(+ screen.getByRole("button", { name: "usage.heatmap.applyRange" }),+ );+ expect(onApplyRange).toHaveBeenCalledTimes(1);+ expect(onApplyRange).toHaveBeenCalledWith(expectedRange);++ // 普通点击收拢回单日+ fireEvent.click(getDayCell(recentA));+ expect(getDayCell(recentA)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentMid)).toHaveAttribute("aria-pressed", "false");+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "false");+ expect(+ screen.queryByText("usage.heatmap.dayCount"),+ ).not.toBeInTheDocument();+ });++ it("allows starting a Shift+click range directly from an empty selection", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ fireEvent.click(getDayCell(recentB), { shiftKey: true });+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "true");+ expect(+ screen.queryByText("usage.heatmap.dayCount"),+ ).not.toBeInTheDocument();++ fireEvent.click(getDayCell(recentA), { shiftKey: true });+ expect(getDayCell(recentA)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentMid)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByText("usage.heatmap.dayCount")).toBeInTheDocument();+ });++ it("shows daily rollup notice for archived single day and extends into multi-day trend on Shift+click", () => {+ render(<UsageHeatmap metric="requests" refreshIntervalMs={0} />);++ fireEvent.click(getDayCell(archivedDay));+ expect(screen.getByText("usage.heatmap.archivedTitle")).toBeInTheDocument();+ expect(+ screen.queryByTestId("mock-heatmap-trend-chart"),+ ).not.toBeInTheDocument();++ // 按住 Shift 点击另一天:直接由归档单日扩展为多日趋势图+ fireEvent.click(getDayCell(recentB), { shiftKey: true });+ expect(+ screen.queryByText("usage.heatmap.archivedTitle"),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("mock-heatmap-trend-chart")).toBeInTheDocument();+ });++ it("prevents native text selection on Shift+mouseDown and handles Shift released before click across WebViews", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ fireEvent.click(getDayCell(recentB));++ const cellA = getDayCell(recentA);+ const downEvent = createEvent.mouseDown(cellA, {+ button: 0,+ shiftKey: true,+ });+ fireEvent(cellA, downEvent);+ expect(downEvent.defaultPrevented).toBe(true);++ // 即使在 mouseup/click 之前松开了 Shift 键,仍应基于 mousedown 时的修饰键完成区间选择+ fireEvent.click(cellA, { shiftKey: false });+ expect(getDayCell(recentA)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentMid)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "true");+ });++ it("shows preview while holding Shift and resets on Linux-style keyUp or window blur", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ fireEvent.click(getDayCell(recentB));+ fireEvent.keyDown(window, {+ key: "Shift",+ code: "ShiftLeft",+ shiftKey: true,+ });+ fireEvent.mouseEnter(getDayCell(recentA), { shiftKey: true });++ expect(getDayCell(recentA)).toHaveAttribute("data-preview", "true");+ expect(getDayCell(recentMid)).toHaveAttribute("data-preview", "true");++ // 模拟 Linux X11 / WebKitGTK 下 keyUp 仍携带 shiftKey=true 的场景+ fireEvent.keyUp(window, {+ key: "Shift",+ code: "ShiftLeft",+ shiftKey: true,+ });+ expect(getDayCell(recentA)).not.toHaveAttribute("data-preview");+ expect(getDayCell(recentMid)).not.toHaveAttribute("data-preview");++ // 再次按下 Shift 悬停预览后,窗口失焦也应重置预览状态+ fireEvent.keyDown(window, {+ key: "Shift",+ code: "ShiftRight",+ shiftKey: true,+ });+ fireEvent.mouseEnter(getDayCell(recentA), { shiftKey: true });+ expect(getDayCell(recentA)).toHaveAttribute("data-preview", "true");++ fireEvent.blur(window);+ expect(getDayCell(recentA)).not.toHaveAttribute("data-preview");+ });++ it("supports keyboard activation while holding Shift", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ fireEvent.click(getDayCell(recentB));+ fireEvent.keyDown(window, {+ key: "Shift",+ code: "ShiftLeft",+ shiftKey: true,+ });+ // 键盘 Enter/Space 触发按钮 click 时 detail === 0,且某些 WebView click 上不带 shiftKey+ fireEvent.click(getDayCell(recentA), { detail: 0, shiftKey: false });++ expect(getDayCell(recentA)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentMid)).toHaveAttribute("aria-pressed", "true");+ expect(getDayCell(recentB)).toHaveAttribute("aria-pressed", "true");+ });++ it("closes drawer via close button and Escape key", () => {+ render(<UsageHeatmap metric="tokens" refreshIntervalMs={0} />);++ fireEvent.click(getDayCell(recentA));+ const drawer = screen.getByTestId("usage-heatmap-drawer");+ expect(drawer).toHaveAttribute("data-state", "open");++ fireEvent.click(+ screen.getByRole("button", { name: "usage.heatmap.closeDetail" }),+ );+ expect(drawer).toHaveAttribute("data-state", "closed");++ fireEvent.click(getDayCell(recentB));+ expect(drawer).toHaveAttribute("data-state", "open");+ fireEvent.keyDown(getDayCell(recentB), { key: "Escape" });+ expect(drawer).toHaveAttribute("data-state", "closed");+ });+});