Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

refactor(runtimes): make period the usage section's only filter (MUL-8981) (#10319)

Jiayuan Zhang68b58096c537
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index d7020410ef..332ef4c8e7 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -477,7 +477,6 @@
},
"usage": {
"period_label": "Period",
- "dimension_label": "Dimension",
"kpi_cost_label": "Cost · {{days}}D",
"kpi_cost_delta": "{{sign}}{{pct}}% vs prev",
"kpi_cache_label": "Cache savings · {{days}}D",
@@ -485,8 +484,6 @@
"kpi_tokens_label": "Tokens · {{days}}D",
"kpi_tokens_hint": "in {{input}} · out {{output}}",
"when_title": "When this runtime spent",
- "when_tab_daily": "Daily",
- "when_tab_weekly": "Weekly",
"when_tab_heatmap": "Heatmap",
"daily_metric_cost": "Cost",
"daily_metric_tokens": "Tokens",
@@ -522,6 +519,7 @@
"cost_by_title_model": "Cost by model",
"cost_by_tab_agent": "By agent",
"cost_by_tab_model": "By model",
+ "cost_by_label": "Group by",
"cost_by_caption_agent_one": "{{count}} agent on this runtime",
"cost_by_caption_agent_other": "{{count}} agents on this runtime",
"cost_by_caption_model_one": "{{count}} model used",
diff --git a/packages/views/locales/es/runtimes.json b/packages/views/locales/es/runtimes.json
index 10ad276313..753adf3378 100644
--- a/packages/views/locales/es/runtimes.json
+++ b/packages/views/locales/es/runtimes.json
@@ -477,7 +477,6 @@
},
"usage": {
"period_label": "Periodo",
- "dimension_label": "Dimensión",
"kpi_cost_label": "Coste · {{days}}d",
"kpi_cost_delta": "{{sign}}{{pct}}% vs anterior",
"kpi_cache_label": "Ahorro por caché · {{days}}d",
@@ -485,8 +484,6 @@
"kpi_tokens_label": "Tokens · {{days}}d",
"kpi_tokens_hint": "entrada {{input}} · salida {{output}}",
"when_title": "Cuándo gastó este runtime",
- "when_tab_daily": "Diario",
- "when_tab_weekly": "Semanal",
"when_tab_heatmap": "Mapa de calor",
"daily_metric_cost": "Coste",
"daily_metric_tokens": "Tokens",
@@ -522,6 +519,7 @@
"cost_by_title_model": "Coste por modelo",
"cost_by_tab_agent": "Por agente",
"cost_by_tab_model": "Por modelo",
+ "cost_by_label": "Agrupar por",
"cost_by_caption_agent_one": "{{count}} agente en este runtime",
"cost_by_caption_agent_other": "{{count}} agentes en este runtime",
"cost_by_caption_model_one": "{{count}} modelo usado",
diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.json
index 4983a20922..4576be8647 100644
--- a/packages/views/locales/fr/runtimes.json
+++ b/packages/views/locales/fr/runtimes.json
@@ -477,7 +477,6 @@
},
"usage": {
"period_label": "Période",
- "dimension_label": "Dimension",
"kpi_cost_label": "Coût · {{days}} j",
"kpi_cost_delta": "{{sign}}{{pct}} % vs préc.",
"kpi_cache_label": "Économies de cache · {{days}} j",
@@ -485,8 +484,6 @@
"kpi_tokens_label": "Tokens · {{days}} j",
"kpi_tokens_hint": "entrée {{input}} · sortie {{output}}",
"when_title": "Quand ce runtime a dépensé",
- "when_tab_daily": "Quotidien",
- "when_tab_weekly": "Hebdomadaire",
"when_tab_heatmap": "Carte de chaleur",
"daily_metric_cost": "Coût",
"daily_metric_tokens": "Tokens",
@@ -522,6 +519,7 @@
"cost_by_title_model": "Coût par modèle",
"cost_by_tab_agent": "Par agent",
"cost_by_tab_model": "Par modèle",
+ "cost_by_label": "Regrouper par",
"cost_by_caption_agent_one": "{{count}} agent sur ce runtime",
"cost_by_caption_agent_other": "{{count}} agents sur ce runtime",
"cost_by_caption_model_one": "{{count}} modèle utilisé",
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index c03f208adf..f17b9572a8 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -465,7 +465,6 @@
},
"usage": {
"period_label": "期間",
- "dimension_label": "ディメンション",
"kpi_cost_label": "コスト · {{days}} 日",
"kpi_cost_delta": "前期比 {{sign}}{{pct}}%",
"kpi_cache_label": "キャッシュによる節約 · {{days}} 日",
@@ -473,8 +472,6 @@
"kpi_tokens_label": "トークン · {{days}} 日",
"kpi_tokens_hint": "入力 {{input}} · 出力 {{output}}",
"when_title": "このランタイムでコストが発生した時期",
- "when_tab_daily": "日別",
- "when_tab_weekly": "週別",
"when_tab_heatmap": "ヒートマップ",
"daily_metric_cost": "コスト",
"daily_metric_tokens": "トークン",
@@ -509,6 +506,7 @@
"cost_by_title_model": "モデル別コスト",
"cost_by_tab_agent": "エージェント別",
"cost_by_tab_model": "モデル別",
+ "cost_by_label": "グループ化",
"cost_by_caption_agent_other": "このランタイムのエージェント {{count}} 個",
"cost_by_caption_model_other": "使用されたモデル {{count}} 個",
"daily_breakdown_toggle": "日別内訳テーブル",
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index 4e8d412372..ac515d44fd 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -465,7 +465,6 @@
},
"usage": {
"period_label": "기간",
- "dimension_label": "단위",
"kpi_cost_label": "비용 · {{days}}일",
"kpi_cost_delta": "이전 대비 {{sign}}{{pct}}%",
"kpi_cache_label": "캐시 절감 · {{days}}일",
@@ -473,8 +472,6 @@
"kpi_tokens_label": "토큰 · {{days}}일",
"kpi_tokens_hint": "입력 {{input}} · 출력 {{output}}",
"when_title": "런타임 비용 발생 시점",
- "when_tab_daily": "일별",
- "when_tab_weekly": "주별",
"when_tab_heatmap": "히트맵",
"daily_metric_cost": "비용",
"daily_metric_tokens": "토큰",
@@ -509,6 +506,7 @@
"cost_by_title_model": "모델별 비용",
"cost_by_tab_agent": "에이전트별",
"cost_by_tab_model": "모델별",
+ "cost_by_label": "그룹 기준",
"cost_by_caption_agent_other": "이 런타임의 에이전트 {{count}}개",
"cost_by_caption_model_other": "사용된 모델 {{count}}개",
"daily_breakdown_toggle": "일별 상세 테이블",
diff --git a/packages/views/locales/ru/runtimes.json b/packages/views/locales/ru/runtimes.json
index 1224b02bd1..3448c34ae7 100644
--- a/packages/views/locales/ru/runtimes.json
+++ b/packages/views/locales/ru/runtimes.json
@@ -497,7 +497,6 @@
},
"usage": {
"period_label": "Период",
- "dimension_label": "Измерение",
"kpi_cost_label": "Стоимость · {{days}} дн.",
"kpi_cost_delta": "{{sign}}{{pct}}% к пред. периоду",
"kpi_cache_label": "Экономия на кэше · {{days}} дн.",
@@ -505,8 +504,6 @@
"kpi_tokens_label": "Токены · {{days}} дн.",
"kpi_tokens_hint": "вход {{input}} · выход {{output}}",
"when_title": "Когда эта среда выполнения тратила",
- "when_tab_daily": "По дням",
- "when_tab_weekly": "По неделям",
"when_tab_heatmap": "Тепловая карта",
"daily_metric_cost": "Стоимость",
"daily_metric_tokens": "Токены",
@@ -542,6 +539,7 @@
"cost_by_title_model": "Стоимость по моделям",
"cost_by_tab_agent": "По агентам",
"cost_by_tab_model": "По моделям",
+ "cost_by_label": "Группировка",
"cost_by_caption_agent_one": "{{count}} агент в этой среде выполнения",
"cost_by_caption_agent_other": "{{count}} агента в этой среде выполнения",
"cost_by_caption_model_one": "{{count}} модель использована",
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 7b75632eff..439e717b80 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -465,7 +465,6 @@
},
"usage": {
"period_label": "时间范围",
- "dimension_label": "维度",
"kpi_cost_label": "费用 · {{days}} 天",
"kpi_cost_delta": "{{sign}}{{pct}}% 对比上期",
"kpi_cache_label": "缓存节省 · {{days}} 天",
@@ -473,8 +472,6 @@
"kpi_tokens_label": "Token · {{days}} 天",
"kpi_tokens_hint": "输入 {{input}} · 输出 {{output}}",
"when_title": "这个运行时在何时消耗",
- "when_tab_daily": "按天",
- "when_tab_weekly": "按周",
"when_tab_heatmap": "热力图",
"daily_metric_cost": "费用",
"daily_metric_tokens": "Token",
@@ -509,6 +506,7 @@
"cost_by_title_model": "按模型分摊",
"cost_by_tab_agent": "按智能体",
"cost_by_tab_model": "按模型",
+ "cost_by_label": "分组方式",
"cost_by_caption_agent_other": "{{count}} 个智能体使用此运行时",
"cost_by_caption_model_other": "{{count}} 个模型已使用",
"daily_breakdown_toggle": "每日明细表",
diff --git a/packages/views/locales/zh-Hant/runtimes.json b/packages/views/locales/zh-Hant/runtimes.json
index 42ad488e24..a07dfb4914 100644
--- a/packages/views/locales/zh-Hant/runtimes.json
+++ b/packages/views/locales/zh-Hant/runtimes.json
@@ -465,7 +465,6 @@
},
"usage": {
"period_label": "時間範圍",
- "dimension_label": "維度",
"kpi_cost_label": "費用 · {{days}} 天",
"kpi_cost_delta": "{{sign}}{{pct}}% 對比上期",
"kpi_cache_label": "快取節省 · {{days}} 天",
@@ -473,8 +472,6 @@
"kpi_tokens_label": "Token · {{days}} 天",
"kpi_tokens_hint": "輸入 {{input}} · 輸出 {{output}}",
"when_title": "這個執行時在何時消耗",
- "when_tab_daily": "按天",
- "when_tab_weekly": "按周",
"when_tab_heatmap": "熱力圖",
"daily_metric_cost": "費用",
"daily_metric_tokens": "Token",
@@ -509,6 +506,7 @@
"cost_by_title_model": "按模型分攤",
"cost_by_tab_agent": "按 AI 代理",
"cost_by_tab_model": "按模型",
+ "cost_by_label": "分組方式",
"cost_by_caption_agent_other": "{{count}} 個 AI 代理使用此執行時",
"cost_by_caption_model_other": "{{count}} 個模型已使用",
"daily_breakdown_toggle": "每日明細表",
diff --git a/packages/views/runtimes/components/usage-section.test.tsx b/packages/views/runtimes/components/usage-section.test.tsx
index 7f903acfe8..dc19ee74da 100644
--- a/packages/views/runtimes/components/usage-section.test.tsx
+++ b/packages/views/runtimes/components/usage-section.test.tsx
@@ -2,13 +2,16 @@
import type { ReactNode } from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent } from "@testing-library/react";
+import { render, screen, fireEvent, within } from "@testing-library/react";
import type { AgentRuntime } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enRuntimes from "../../locales/en/runtimes.json";
+import enUsage from "../../locales/en/usage.json";
-const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };
+const TEST_RESOURCES = {
+ en: { common: enCommon, runtimes: enRuntimes, usage: enUsage },
+};
// The viewer's tz (Viewing layer) drives both the trend and the heatmap.
const VIEWER_TZ = "Asia/Tokyo";
@@ -196,6 +199,69 @@ describe("UsageSection — Viewing timezone wiring", () => {
});
});
+describe("UsageSection — period and grain", () => {
+ beforeEach(() => {
+ usageOverride.rows = null;
+ });
+
+ const periodGroup = () => screen.getByRole("group", { name: "Period" });
+ const dimGroup = () => screen.queryByRole("group", { name: "Dimension" });
+
+ it("offers every period up front, so 180d is one click", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ for (const label of ["7d", "30d", "90d", "180d"]) {
+ expect(
+ within(periodGroup()).getByRole("button", { name: label }),
+ ).toBeInTheDocument();
+ }
+
+ fireEvent.click(within(periodGroup()).getByRole("button", { name: "180d" }));
+
+ expect(screen.getByText("Cost · 180D")).toBeInTheDocument();
+ expect(screen.getByTestId("weekly-cost-chart")).toBeInTheDocument();
+ // 180d allows only the weekly grain — a one-option toggle is not shown.
+ expect(dimGroup()).toBeNull();
+ });
+
+ it("switching the grain never changes the period", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ fireEvent.click(within(dimGroup()!).getByRole("button", { name: "Weekly" }));
+
+ expect(screen.getByTestId("weekly-cost-chart")).toBeInTheDocument();
+ expect(screen.getByText("Cost · 30D")).toBeInTheDocument();
+ expect(
+ within(periodGroup()).getByRole("button", { name: "30d" }),
+ ).toHaveAttribute("aria-pressed", "true");
+ });
+
+ it("draws 7d daily without forgetting the reader's weekly choice", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ // Tokens, because the 7d fixture's cost rounds to $0 and would render
+ // the empty state instead of a chart.
+ fireEvent.click(screen.getByRole("button", { name: "Tokens" }));
+ fireEvent.click(within(dimGroup()!).getByRole("button", { name: "Weekly" }));
+ fireEvent.click(within(periodGroup()).getByRole("button", { name: "7d" }));
+
+ expect(screen.getByTestId("daily-tokens-chart")).toBeInTheDocument();
+ expect(dimGroup()).toBeNull();
+
+ fireEvent.click(within(periodGroup()).getByRole("button", { name: "30d" }));
+
+ expect(screen.getByTestId("weekly-tokens-chart")).toBeInTheDocument();
+ });
+
+ it("hides the grain toggle while the heatmap is on", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ fireEvent.click(screen.getByRole("button", { name: "Heatmap" }));
+
+ expect(dimGroup()).toBeNull();
+ });
+});
+
describe("UsageSection — cache hit rate", () => {
beforeEach(() => {
usageOverride.rows = null;
diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsx
index e451398c52..054d7ffff0 100644
--- a/packages/views/runtimes/components/usage-section.tsx
+++ b/packages/views/runtimes/components/usage-section.tsx
@@ -46,76 +46,24 @@ import {
import { CustomPricingDialog } from "./custom-pricing-dialog";
import { useT } from "../../i18n";
import { ObjectSectionEmpty } from "../../layout/object-page";
+import {
+ Segmented,
+ TIME_RANGES,
+ dimsForDays,
+ type Dim,
+ type TimeRange as DashboardTimeRange,
+} from "../../dashboard/components/dashboard-shared";
+import { DimSegmented } from "../../dashboard/components/dim-segmented";
// Single source of truth for the period selector. KPIs, the When-chart, the
// Cost-by tabs, and the CSV export all read from the same `days` value so
-// the labels ("· 30D") and the data slice never disagree.
-//
-// `dims` declares which dimensions each range is allowed in. 7 days at the
-// weekly grain is one bar, so 7d is daily-only; 180d is weekly-only because
-// 180 daily bars are visually unreadable.
-const TIME_RANGES = [
- { label: "7d", days: 7, dims: ["daily"] as const },
- { label: "30d", days: 30, dims: ["daily", "weekly"] as const },
- { label: "90d", days: 90, dims: ["daily", "weekly"] as const },
- { label: "180d", days: 180, dims: ["weekly"] as const },
-] as const;
-
-type TimeRange = (typeof TIME_RANGES)[number]["days"];
-type WhenTab = "daily" | "weekly" | "heatmap";
-
-// Default time range per dimension. Switching dimensions resets the period
-// to its default rather than keeping a now-invalid value.
-const DEFAULT_DAYS_BY_DIM: Record<Exclude<WhenTab, "heatmap">, TimeRange> = {
- daily: 30,
- weekly: 90,
-};
-
-function rangesForDim(dim: Exclude<WhenTab, "heatmap">) {
- return TIME_RANGES.filter((r) =>
- (r.dims as readonly string[]).includes(dim),
- );
-}
+// the labels ("· 30D") and the data slice never disagree. Same ranges as the
+// Analytics page except 1d.
+const PERIODS = TIME_RANGES.filter(
+ (r): r is Exclude<(typeof TIME_RANGES)[number], { days: 1 }> => r.days !== 1,
+);
-// Local segmented control. shadcn's Tabs is wired for full tab pages with
-// keyboard nav and ARIA semantics that a compact toolbar pill doesn't need.
-// Visual: light-grey track + white "raised" active pill.
-
-function Segmented<T extends string | number>({
- value,
- onChange,
- options,
- disabled,
-}: {
- value: T;
- onChange: (v: T) => void;
- options: readonly { label: string; value: T }[];
- disabled?: boolean;
-}) {
- return (
- <div
- className={`inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5 ${
- disabled ? "opacity-50" : ""
- }`}
- >
- {options.map((o) => (
- <button
- key={String(o.value)}
- type="button"
- disabled={disabled}
- onClick={() => onChange(o.value)}
- className={`rounded-sm px-2.5 py-1 text-caption font-medium transition-colors disabled:cursor-not-allowed ${
- o.value === value
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground"
- }`}
- >
- {o.label}
- </button>
- ))}
- </div>
- );
-}
+type TimeRange = Exclude<DashboardTimeRange, 1>;
// Top-level orchestrator. Owns the time window, fetches a 180-day usage
// cache once, slices it into "current" / "prior" windows for delta math,
@@ -136,7 +84,6 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
const { data: usage = [], isLoading: loading } = useQuery(
runtimeUsageOptions(runtimeId, 180, tz),
);
- const [dim, setDim] = useState<Exclude<WhenTab, "heatmap">>("daily");
const [days, setDays] = useState<TimeRange>(30);
// Subscribe so the KPI cards (which call estimateCost at render-time, not
// through a memo) re-evaluate when the user saves a custom rate. The
@@ -154,16 +101,6 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
// boundary the backend used when bucketing rows.
const { filtered, prevFiltered } = sliceWindow(usage, days, tz);
- const allowedRanges = rangesForDim(dim);
- const handleDimChange = (next: Exclude<WhenTab, "heatmap">) => {
- setDim(next);
- const stillAllowed = (rangesForDim(next) as readonly { days: number }[]).some(
- (r) => r.days === days,
- );
- if (!stillAllowed) {
- setDays(DEFAULT_DAYS_BY_DIM[next]);
- }
- };
const totals = computeTotals(filtered);
const prevTotals = computeTotals(prevFiltered);
@@ -180,40 +117,19 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
return (
<div className="space-y-5">
- {/* Page-wide period selector. Lives at the top because it controls
- basically everything below: the KPI numbers and labels, the
- daily / weekly chart window, and the cost-by aggregations. The
- Heatmap tab is the only sub-view that ignores it (always shows
- 26 weeks), and its tab disables this control to telegraph that. */}
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="flex items-center gap-3">
- <span className="text-caption uppercase tracking-wider text-muted-foreground">
- {t(($) => $.usage.dimension_label)}
- </span>
- <Segmented
- value={dim}
- onChange={handleDimChange}
- options={
- [
- { label: t(($) => $.usage.when_tab_daily), value: "daily" },
- { label: t(($) => $.usage.when_tab_weekly), value: "weekly" },
- ] as const
- }
- />
- </div>
- <div className="flex items-center gap-3">
- <span className="text-caption uppercase tracking-wider text-muted-foreground">
- {t(($) => $.usage.period_label)}
- </span>
- <Segmented
- value={days}
- onChange={setDays}
- options={allowedRanges.map((r) => ({
- label: r.label,
- value: r.days,
- }))}
- />
- </div>
+ {/* The section's only filter: the KPIs, the When chart's window and
+ the cost-by aggregations all follow it. The heatmap view ignores
+ it (always 26 weeks) and says so in its caption. */}
+ <div className="flex flex-wrap items-center justify-end gap-3">
+ <span className="text-caption uppercase tracking-wider text-muted-foreground">
+ {t(($) => $.usage.period_label)}
+ </span>
+ <Segmented
+ label={t(($) => $.usage.period_label)}
+ value={days}
+ onChange={setDays}
+ options={PERIODS.map((r) => ({ label: r.label, value: r.days }))}
+ />
</div>
{/* Pricing bar. Sits above the KPI grid so a *partial* unmapping
@@ -301,17 +217,8 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
/>
</div>
- {/* Layer 2 — WHEN chart. Dimension (Daily / Weekly) is owned by the
- parent so the period selector at the top can react to it. The
- Heatmap is an independent toggle inside this card — it ignores
- the period selector by design (it's a fixed 26-week long-view). */}
- <WhenChart
- usage={usage}
- filtered={filtered}
- days={days}
- dim={dim}
- tz={tz}
- />
+ {/* Layer 2 — WHEN chart. */}
+ <WhenChart usage={usage} filtered={filtered} days={days} tz={tz} />
{/* Layer 3 — WHO/WHAT burned the spend. */}
<CostByBlock runtimeId={runtimeId} days={days} usage={filtered} tz={tz} />
@@ -325,30 +232,30 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
}
// WhenChart — answers "WHEN was this runtime spending money?".
-// Dimension (Daily / Weekly) is owned by the parent so the page-level
-// period selector can react to it. Heatmap is an independent view toggled
-// inside this card; it ignores both the dimension and the period selector,
-// always showing the long 26-week view.
+// Daily / Weekly is card-scoped and offers only the grains the period allows,
+// so it never changes the period (MUL-5759). Heatmap is an independent view
+// toggled inside this card; it ignores both, always showing 26 weeks.
-type Dim = Exclude<WhenTab, "heatmap">;
type DailyMetric = "cost" | "tokens";
function WhenChart({
usage,
filtered,
days,
- dim,
tz,
}: {
usage: RuntimeUsage[];
filtered: RuntimeUsage[];
days: TimeRange;
- dim: Dim;
tz: string;
}) {
const { t } = useT("runtimes");
- // Heatmap is the "independent" sibling — toggled here, not part of the
- // page-level dimension segmented (per the RFC).
+ const { t: tUsage } = useT("usage");
+ const allowedDims = dimsForDays(days);
+ const [dim, setDim] = useState<Dim>("daily");
+ // Derived, never written back: 7d and 180d each draw the one grain they
+ // allow, and widening back to 30d / 90d restores the reader's choice.
+ const effectiveDim: Dim = allowedDims.includes(dim) ? dim : allowedDims[0]!;
const [showHeatmap, setShowHeatmap] = useState(false);
// Daily and Weekly share a Cost-vs-Tokens metric toggle.
const [chartMetric, setChartMetric] = useState<DailyMetric>("cost");
@@ -383,22 +290,29 @@ function WhenChart({
<div className="mb-3 flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-3">
<h4 className="text-body font-semibold">{t(($) => $.usage.when_title)}</h4>
- {/* Cost / Tokens metric toggle — only meaningful when the chart
- actually has two series-types to switch between. */}
+ {/* Metric and grain toggles — the heatmap has neither, so both
+ hide while it is on. */}
{metricToggleVisible && (
- <Segmented
- value={chartMetric}
- onChange={setChartMetric}
- options={
- [
- { label: t(($) => $.usage.daily_metric_cost), value: "cost" },
- { label: t(($) => $.usage.daily_metric_tokens), value: "tokens" },
- ] as const
- }
- />
+ <>
+ <Segmented
+ label={tUsage(($) => $.daily.metric_label)}
+ value={chartMetric}
+ onChange={setChartMetric}
+ options={
+ [
+ { label: t(($) => $.usage.daily_metric_cost), value: "cost" },
+ { label: t(($) => $.usage.daily_metric_tokens), value: "tokens" },
+ ] as const
+ }
+ />
+ <DimSegmented
+ allowedDims={allowedDims}
+ value={effectiveDim}
+ onChange={setDim}
+ />
+ </>
)}
- {/* Heatmap toggle — independent of the page-level dim segmented.
- "On" puts the card into a fixed 26-week long-view that ignores
+ {/* "On" puts the card into a fixed 26-week long-view that ignores
the period selector. */}
<button
type="button"
@@ -427,7 +341,7 @@ function WhenChart({
<div className="min-h-[260px]">
{showHeatmap ? (
<ActivityHeatmap usage={usage} tz={tz} />
- ) : dim === "daily" ? (
+ ) : effectiveDim === "daily" ? (
<DailyTab
metric={chartMetric}
costData={dailyCostStack}
@@ -697,6 +611,7 @@ function CostByBlock({
: t(($) => $.usage.cost_by_title_model)}
</h4>
<Segmented
+ label={t(($) => $.usage.cost_by_label)}
value={tab}
onChange={setTab}
options={